diff --git a/CMakeLists.txt b/CMakeLists.txt index 5826aec8bae..1285e2ac71d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -35,7 +35,9 @@ set(CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib") set(CMAKE_INSTALL_RPATH_USE_LINK_PATH 1) # set macro-directory -set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake/macros") +list(APPEND CMAKE_MODULE_PATH + "${CMAKE_SOURCE_DIR}/cmake/macros" + "${CMAKE_SOURCE_DIR}/dep/cotire/CMake") # build in Release-mode by default if not explicitly set if( NOT CMAKE_BUILD_TYPE ) @@ -55,6 +57,7 @@ if( NOPCH ) set(USE_SCRIPTPCH 0) endif() +include(ConfigureBaseTargets) include(CheckPlatform) include(GroupSources) diff --git a/cmake/compiler/clang/settings.cmake b/cmake/compiler/clang/settings.cmake index b826c1dba36..3d420d3830c 100644 --- a/cmake/compiler/clang/settings.cmake +++ b/cmake/compiler/clang/settings.cmake @@ -1,29 +1,52 @@ # Set build-directive (used in core to tell which buildtype we used) -add_definitions(-D_BUILD_DIRECTIVE='"${CMAKE_BUILD_TYPE}"') +target_compile_definitions(trinity-compile-option-interface + INTERFACE + -D_BUILD_DIRECTIVE="${CMAKE_BUILD_TYPE}") if(WITH_WARNINGS) - set(WARNING_FLAGS "-W -Wall -Wextra -Winit-self -Wfatal-errors -Wno-mismatched-tags") - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${WARNING_FLAGS}") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${WARNING_FLAGS} -Woverloaded-virtual") + target_compile_options(trinity-warning-interface + INTERFACE + -W + -Wall + -Wextra + -Winit-self + -Wfatal-errors + -Wno-mismatched-tags + -Woverloaded-virtual) + message(STATUS "Clang: All warnings enabled") endif() if(WITH_COREDEBUG) - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g3") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g3") + target_compile_options(trinity-compile-option-interface + INTERFACE + -g3) + message(STATUS "Clang: Debug-flags set (-g3)") endif() # -Wno-narrowing needed to suppress a warning in g3d # -Wno-deprecated-register is needed to suppress 185 gsoap warnings on Unix systems. -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -Wno-narrowing -Wno-deprecated-register") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG=1") +target_compile_options(trinity-compile-option-interface + INTERFACE + -Wno-narrowing + -Wno-deprecated-register) + +target_compile_definitions(trinity-compile-option-interface + INTERFACE + -DDEBUG=1) if (BUILD_SHARED_LIBS) # -fPIC is needed to allow static linking in shared libs. # -fvisibility=hidden sets the default visibility to hidden to prevent exporting of all symbols. - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIC -fvisibility=hidden") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -fvisibility=hidden") + target_compile_options(trinity-compile-option-interface + INTERFACE + -fPIC) + + target_compile_options(trinity-hidden-symbols-interface + INTERFACE + -fvisibility=hidden) # --no-undefined to throw errors when there are undefined symbols # (caused through missing TRINITY_*_API macros). diff --git a/cmake/compiler/gcc/settings.cmake b/cmake/compiler/gcc/settings.cmake index 52924ba0667..9139a028f18 100644 --- a/cmake/compiler/gcc/settings.cmake +++ b/cmake/compiler/gcc/settings.cmake @@ -1,5 +1,7 @@ # Set build-directive (used in core to tell which buildtype we used) -add_definitions(-D_BUILD_DIRECTIVE='"${CMAKE_BUILD_TYPE}"') +target_compile_definitions(trinity-compile-option-interface + INTERFACE + -D_BUILD_DIRECTIVE="${CMAKE_BUILD_TYPE}") set(GCC_EXPECTED_VERSION 6.3.0) @@ -7,37 +9,50 @@ if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS GCC_EXPECTED_VERSION) message(FATAL_ERROR "GCC: TrinityCore requires version ${GCC_EXPECTED_VERSION} to build but found ${CMAKE_CXX_COMPILER_VERSION}") endif() -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14") -message(STATUS "GCC: Enabled c++14 support") - -set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -std=gnu99") -message(STATUS "GCC: Enabled C99 support") - if(PLATFORM EQUAL 32) # Required on 32-bit systems to enable SSE2 (standard on x64) - set(SSE_FLAGS "-msse2 -mfpmath=sse") - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${SSE_FLAGS}") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${SSE_FLAGS}") + target_compile_options(trinity-compile-option-interface + INTERFACE + -msse2 + -mfpmath=sse) endif() -add_definitions(-DHAVE_SSE2 -D__SSE2__) +target_compile_definitions(trinity-compile-option-interface + INTERFACE + -DHAVE_SSE2 + -D__SSE2__) message(STATUS "GCC: SFMT enabled, SSE2 flags forced") if( WITH_WARNINGS ) - set(WARNING_FLAGS "-W -Wall -Wextra -Winit-self -Winvalid-pch -Wfatal-errors") - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${WARNING_FLAGS}") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${WARNING_FLAGS} -Woverloaded-virtual") + target_compile_options(trinity-warning-interface + INTERFACE + -W + -Wall + -Wextra + -Winit-self + -Winvalid-pch + -Wfatal-errors + -Woverloaded-virtual) + message(STATUS "GCC: All warnings enabled") endif() if( WITH_COREDEBUG ) - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g3") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g3") + target_compile_options(trinity-compile-option-interface + INTERFACE + -g3) + message(STATUS "GCC: Debug-flags set (-g3)") endif() if (BUILD_SHARED_LIBS) - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIC -fvisibility=hidden -Wno-attributes") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -fvisibility=hidden -Wno-attributes") + target_compile_options(trinity-compile-option-interface + INTERFACE + -fPIC + -Wno-attributes) + + target_compile_options(trinity-hidden-symbols-interface + INTERFACE + -fvisibility=hidden) # Should break the build when there are TRINITY_*_API macros missing # but it complains about missing references in precompiled headers. diff --git a/cmake/compiler/icc/settings.cmake b/cmake/compiler/icc/settings.cmake index 133bc15e59e..d14931f6455 100644 --- a/cmake/compiler/icc/settings.cmake +++ b/cmake/compiler/icc/settings.cmake @@ -1,18 +1,28 @@ # Set build-directive (used in core to tell which buildtype we used) -add_definitions(-D_BUILD_DIRECTIVE="'${CMAKE_BUILD_TYPE}'") +target_compile_definitions(trinity-compile-option-interface + INTERFACE + -D_BUILD_DIRECTIVE="${CMAKE_BUILD_TYPE}") if(PLATFORM EQUAL 32) - add_definitions(-axSSE2) + target_compile_options(trinity-compile-option-interface + INTERFACE + -axSSE2) else() - add_definitions(-xSSE2) + target_compile_options(trinity-compile-option-interface + INTERFACE + -xSSE2) endif() if( WITH_WARNINGS ) - add_definitions(-w1) + target_compile_options(trinity-warning-interface + INTERFACE + -w1) message(STATUS "ICC: All warnings enabled") endif() if( WITH_COREDEBUG ) - add_definitions(-g) + target_compile_options(trinity-compile-option-interface + INTERFACE + -g) message(STATUS "ICC: Debug-flag set (-g)") endif() diff --git a/cmake/compiler/mingw/settings.cmake b/cmake/compiler/mingw/settings.cmake index 68156bd0b6b..0850d8b5319 100644 --- a/cmake/compiler/mingw/settings.cmake +++ b/cmake/compiler/mingw/settings.cmake @@ -2,26 +2,39 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) # Set build-directive (used in core to tell which buildtype we used) -add_definitions(-D_BUILD_DIRECTIVE=\\"${CMAKE_BUILD_TYPE}\\") +target_compile_definitions(trinity-compile-option-interface + INTERFACE + -D_BUILD_DIRECTIVE="${CMAKE_BUILD_TYPE}") if(PLATFORM EQUAL 32) # Required on 32-bit systems to enable SSE2 (standard on x64) - set(SSE_FLAGS "-msse2 -mfpmath=sse") - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${SSE_FLAGS}") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${SSE_FLAGS}") + target_compile_options(trinity-compile-option-interface + INTERFACE + -msse2 + -mfpmath=sse) endif() -add_definitions(-DHAVE_SSE2 -D__SSE2__) +target_compile_definitions(trinity-compile-option-interface + INTERFACE + -DHAVE_SSE2 + -D__SSE2__) message(STATUS "GCC: SFMT enabled, SSE2 flags forced") if( WITH_WARNINGS ) - set(WARNING_FLAGS "-W -Wall -Wextra -Winit-self -Winvalid-pch -Wfatal-errors") - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${WARNING_FLAGS}") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${WARNING_FLAGS} -Woverloaded-virtual") + target_compile_options(trinity-warning-interface + INTERFACE + -W + -Wall + -Wextra + -Winit-self + -Winvalid-pch + -Wfatal-errors + -Woverloaded-virtual) message(STATUS "GCC: All warnings enabled") endif() if( WITH_COREDEBUG ) - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g3") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g3") + target_compile_options(trinity-compile-option-interface + INTERFACE + -g3) message(STATUS "GCC: Debug-flags set (-g3)") endif() diff --git a/cmake/compiler/msvc/settings.cmake b/cmake/compiler/msvc/settings.cmake index a30e73a817d..fb0ce54c499 100644 --- a/cmake/compiler/msvc/settings.cmake +++ b/cmake/compiler/msvc/settings.cmake @@ -1,12 +1,26 @@ # set up output paths for executable binaries (.exe-files, and .dll-files on DLL-capable platforms) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) -set(MSVC_EXPECTED_VERSION 19.00.23506) +set(MSVC_EXPECTED_VERSION 19.10) +set(MSVC_EXPECTED_VERSION_STRING "MSVC 2017") if(CMAKE_CXX_COMPILER_VERSION VERSION_LESS MSVC_EXPECTED_VERSION) - message(FATAL_ERROR "MSVC: TrinityCore requires version ${MSVC_EXPECTED_VERSION} (MSVC 2015 Update 1) to build but found ${CMAKE_CXX_COMPILER_VERSION}") + message(FATAL_ERROR "MSVC: TrinityCore requires version ${MSVC_EXPECTED_VERSION} (${MSVC_EXPECTED_VERSION_STRING}) to build but found ${CMAKE_CXX_COMPILER_VERSION}") endif() +# CMake sets warning flags by default, however we manage it manually +# for different core and dependency targets +string(REGEX REPLACE "/W[0-4] " "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") +# Search twice, once for space after /W argument, +# once for end of line as CMake regex has no \b +string(REGEX REPLACE "/W[0-4]$" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") +string(REGEX REPLACE "/W[0-4] " "" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}") +string(REGEX REPLACE "/W[0-4]$" "" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}") + +target_compile_options(trinity-warning-interface + INTERFACE + /W3) + # set up output paths ofr static libraries etc (commented out - shown here as an example only) #set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) #set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) @@ -15,7 +29,9 @@ if(PLATFORM EQUAL 64) # This definition is necessary to work around a bug with Intellisense described # here: http://tinyurl.com/2cb428. Syntax highlighting is important for proper # debugger functionality. - add_definitions("-D_WIN64") + target_compile_definitions(trinity-compile-option-interface + INTERFACE + -D_WIN64) message(STATUS "MSVC: 64-bit platform, enforced -D_WIN64 parameter") else() @@ -23,7 +39,9 @@ else() set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /LARGEADDRESSAWARE") message(STATUS "MSVC: Enabled large address awareness") - add_definitions(/arch:SSE2) + target_compile_options(trinity-compile-option-interface + INTERFACE + /arch:SSE2) message(STATUS "MSVC: Enabled SSE2 support") set(CMAKE_EXE_LINKER_FLAGS_DEBUG "${CMAKE_EXE_LINKER_FLAGS_DEBUG} /SAFESEH:NO") @@ -32,17 +50,25 @@ endif() # Set build-directive (used in core to tell which buildtype we used) if(CMAKE_MAKE_PROGRAM MATCHES "nmake") - add_definitions(-D_BUILD_DIRECTIVE=\\"${CMAKE_BUILD_TYPE}\\") + target_compile_definitions(trinity-compile-option-interface + INTERFACE + -D_BUILD_DIRECTIVE="${CMAKE_BUILD_TYPE}") else() - add_definitions(-D_BUILD_DIRECTIVE=\\"$(ConfigurationName)\\") + target_compile_definitions(trinity-compile-option-interface + INTERFACE + -D_BUILD_DIRECTIVE="$(ConfigurationName)") endif() # multithreaded compiling on VS -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP") +target_compile_options(trinity-compile-option-interface + INTERFACE + /MP) if((PLATFORM EQUAL 64) OR (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.0.23026.0) OR BUILD_SHARED_LIBS) # Enable extended object support - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj") + target_compile_options(trinity-compile-option-interface + INTERFACE + /bigobj) message(STATUS "MSVC: Enabled increased number of sections in object files") endif() @@ -53,48 +79,67 @@ endif() # http://blogs.msdn.com/b/vcblog/archive/2015/08/06/new-in-vs-2015-zc-throwingnew.aspx if(NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.0.23026.0)) # makes this flag a requirement to build TC at all - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /Zc:throwingNew") + target_compile_options(trinity-compile-option-interface + INTERFACE + /Zc:throwingNew) endif() # Define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES - eliminates the warning by changing the strcpy call to strcpy_s, which prevents buffer overruns -add_definitions(-D_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES) +target_compile_definitions(trinity-compile-option-interface + INTERFACE + -D_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES) message(STATUS "MSVC: Overloaded standard names") # Ignore warnings about older, less secure functions -add_definitions(-D_CRT_SECURE_NO_WARNINGS) +target_compile_definitions(trinity-compile-option-interface + INTERFACE + -D_CRT_SECURE_NO_WARNINGS) message(STATUS "MSVC: Disabled NON-SECURE warnings") #Ignore warnings about POSIX deprecation -add_definitions(-D_CRT_NONSTDC_NO_WARNINGS) +target_compile_definitions(trinity-compile-option-interface + INTERFACE + -D_CRT_NONSTDC_NO_WARNINGS) message(STATUS "MSVC: Disabled POSIX warnings") # Ignore specific warnings # C4351: new behavior: elements of array 'x' will be default initialized # C4091: 'typedef ': ignored on left of '' when no variable is declared -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4351 /wd4091") +target_compile_options(trinity-compile-option-interface + INTERFACE + /wd4351 + /wd4091) + if(NOT WITH_WARNINGS) - set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /wd4996 /wd4355 /wd4244 /wd4985 /wd4267 /wd4619 /wd4512") - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4996 /wd4355 /wd4244 /wd4985 /wd4267 /wd4619 /wd4512") + target_compile_options(trinity-compile-option-interface + INTERFACE + /wd4996 + /wd4355 + /wd4244 + /wd4985 + /wd4267 + /wd4619 + /wd4512) message(STATUS "MSVC: Disabled generic compiletime warnings") endif() if (BUILD_SHARED_LIBS) # C4251: needs to have dll-interface to be used by clients of class '...' # C4275: non dll-interface class ...' used as base for dll-interface class '...' - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4251 /wd4275") + target_compile_options(trinity-compile-option-interface + INTERFACE + /wd4251 + /wd4275) message(STATUS "MSVC: Enabled shared linking") endif() -# Specify the maximum PreCompiled Header memory allocation limit -# Fixes a compiler-problem when using PCH - the /Ym flag is adjusted by the compiler in MSVC2012, hence we need to set an upper limit with /Zm to avoid discrepancies) -# (And yes, this is a verified , unresolved bug with MSVC... *sigh*) -string(REGEX REPLACE "/Zm[0-9]+ *" "" CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS}) -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /Zm500") - # Enable and treat as errors the following warnings to easily detect virtual function signature failures: # 'function' : member function does not override any base class virtual member function # 'virtual_function' : no override available for virtual member function from base 'class'; function is hidden -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /we4263 /we4264") +target_compile_options(trinity-compile-option-interface + INTERFACE + /we4263 + /we4264) # Disable incremental linking in debug builds. # To prevent linking getting stuck (which might be fixed in a later VS version). diff --git a/cmake/macros/ConfigureBaseTargets.cmake b/cmake/macros/ConfigureBaseTargets.cmake new file mode 100644 index 00000000000..3c3c5430502 --- /dev/null +++ b/cmake/macros/ConfigureBaseTargets.cmake @@ -0,0 +1,79 @@ +# Copyright (C) 2008-2018 TrinityCore +# +# 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. + +# An interface library to make the target com available to other targets +add_library(trinity-compile-option-interface INTERFACE) + +# Use -std=c++11 instead of -std=gnu++11 +set(CXX_EXTENSIONS OFF) + +# An interface library to make the target features available to other targets +add_library(trinity-feature-interface INTERFACE) + +target_compile_features(trinity-feature-interface + INTERFACE + cxx_alias_templates + cxx_auto_type + cxx_constexpr + cxx_decltype + cxx_decltype_auto + cxx_final + cxx_lambdas + cxx_generic_lambdas + cxx_variadic_templates + cxx_defaulted_functions + cxx_nullptr + cxx_trailing_return_types + cxx_return_type_deduction) + +# An interface library to make the warnings level available to other targets +# This interface taget is set-up through the platform specific script +add_library(trinity-warning-interface INTERFACE) + +# An interface used for all other interfaces +add_library(trinity-default-interface INTERFACE) +target_link_libraries(trinity-default-interface + INTERFACE + trinity-compile-option-interface + trinity-feature-interface) + +# An interface used for silencing all warnings +add_library(trinity-no-warning-interface INTERFACE) + +if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") + target_compile_options(trinity-no-warning-interface + INTERFACE + /W0) +else() + target_compile_options(trinity-no-warning-interface + INTERFACE + -w) +endif() + +# An interface library to change the default behaviour +# to hide symbols automatically. +add_library(trinity-hidden-symbols-interface INTERFACE) + +# An interface amalgamation which provides the flags and definitions +# used by the dependency targets. +add_library(trinity-dependency-interface INTERFACE) +target_link_libraries(trinity-dependency-interface + INTERFACE + trinity-default-interface + trinity-no-warning-interface + trinity-hidden-symbols-interface) + +# An interface amalgamation which provides the flags and definitions +# used by the core targets. +add_library(trinity-core-interface INTERFACE) +target_link_libraries(trinity-core-interface + INTERFACE + trinity-default-interface + trinity-warning-interface) diff --git a/cmake/macros/FindPCHSupport.cmake b/cmake/macros/FindPCHSupport.cmake index 9c7a233ac53..9c77605616b 100644 --- a/cmake/macros/FindPCHSupport.cmake +++ b/cmake/macros/FindPCHSupport.cmake @@ -1,170 +1,27 @@ -FUNCTION(GET_COMMON_PCH_PARAMS TARGET_NAME_LIST PCH_HEADER PCH_FE INCLUDE_PREFIX) - GET_FILENAME_COMPONENT(PCH_HEADER_N ${PCH_HEADER} NAME) - GET_DIRECTORY_PROPERTY(TARGET_INCLUDES INCLUDE_DIRECTORIES) +if (MSVC) + # Specify the maximum PreCompiled Header memory allocation limit + # Fixes a compiler-problem when using PCH - the /Ym flag is adjusted by the compiler in MSVC2012, + # hence we need to set an upper limit with /Zm to avoid discrepancies) + # (And yes, this is a verified, unresolved bug with MSVC... *sigh*) + # + # Note: This workaround was verified to be required on MSVC 2017 as well + set(COTIRE_PCH_MEMORY_SCALING_FACTOR 500) +endif() - # Stores the inherited dependency definitions and include directories - # from the given target into the given variables - MACRO(CollectIncludes target inherited_includes inherited_definitions) - # Append the includes and definitions of the current target to the list - get_property(included TARGET ${target} PROPERTY INTERFACE_INCLUDE_DIRECTORIES) - LIST(APPEND "${inherited_includes}" ${included}) - get_property(definitions TARGET ${target} PROPERTY INTERFACE_COMPILE_DEFINITIONS) - FOREACH(def ${definitions}) - LIST(APPEND "${inherited_definitions}" "-D${def}") - ENDFOREACH() - # Add all inherited link targets which weren't included already - get_property(links TARGET ${target} PROPERTY INTERFACE_LINK_LIBRARIES) - # TODO Maybe catch circular dependencies? - FOREACH(target_link ${links}) - IF(TARGET ${target_link}) - CollectIncludes(${target_link} "${inherited_includes}" "${inherited_definitions}") - ENDIF() - ENDFOREACH() - ENDMACRO() +include(cotire) - FOREACH(TARGET_NAME ${TARGET_NAME_LIST}) - CollectIncludes(${TARGET_NAME} TARGET_INCLUDES TARGET_DEFINITIONS) - ENDFOREACH() +function(ADD_CXX_PCH TARGET_NAME_LIST PCH_HEADER) + # Use the header for every target + foreach(TARGET_NAME ${TARGET_NAME_LIST}) + # Disable unity builds + set_target_properties(${TARGET_NAME} PROPERTIES COTIRE_ADD_UNITY_BUILD OFF) - IF (PARENT_PACKAGE_INCLUDE_DIRS) - LIST(REMOVE_DUPLICATES TARGET_INCLUDES) - ENDIF() - IF (PARENT_PACKAGE_LIBRARY_DIRS) - LIST(REMOVE_DUPLICATES TARGET_DEFINITIONS) - ENDIF() - # NOTE: Above, in the rare case that none of the subpackages contain any - # libraries or any include directories, we need to not call - # LIST(REMOVE_DUPLICATES ...). + # Set the prefix header + set_target_properties(${TARGET_NAME} PROPERTIES COTIRE_CXX_PREFIX_HEADER_INIT ${PCH_HEADER}) - FOREACH(ITEM ${TARGET_INCLUDES}) - LIST(APPEND INCLUDE_FLAGS_LIST "${INCLUDE_PREFIX}\"${ITEM}\" ") - ENDFOREACH(ITEM) + # Workaround for cotire bug: https://github.com/sakra/cotire/issues/138 + set_property(TARGET ${TARGET_NAME} PROPERTY CXX_STANDARD 14) + endforeach() - SET(PCH_INCLUDES ${TARGET_INCLUDES} PARENT_SCOPE) - SET(PCH_DEFINITIONS ${TARGET_DEFINITIONS} PARENT_SCOPE) - SET(PCH_HEADER_NAME ${PCH_HEADER_N} PARENT_SCOPE) - SET(PCH_HEADER_OUT ${CMAKE_CURRENT_BINARY_DIR}/${PCH_HEADER_N}.${PCH_FE} PARENT_SCOPE) - SET(INCLUDE_FLAGS ${INCLUDE_FLAGS_LIST} PARENT_SCOPE) -ENDFUNCTION(GET_COMMON_PCH_PARAMS) - -FUNCTION(GENERATE_CXX_PCH_COMMAND TARGET_NAME_LIST INCLUDE_FLAGS IN PCH_SRC OUT) - include_directories(${PCH_INCLUDES}) - add_definitions(${PCH_DEFINITIONS}) - - IF (CMAKE_BUILD_TYPE) - STRING(TOUPPER _${CMAKE_BUILD_TYPE} CURRENT_BUILD_TYPE) - ENDIF () - - SET(COMPILE_FLAGS ${CMAKE_CXX_FLAGS${CURRENT_BUILD_TYPE}}) - LIST(APPEND COMPILE_FLAGS ${CMAKE_CXX_FLAGS}) - - IF ("${CMAKE_SYSTEM_NAME}" MATCHES "Darwin") - IF (NOT "${CMAKE_OSX_ARCHITECTURES}" STREQUAL "") - LIST(APPEND COMPILE_FLAGS "-arch ${CMAKE_OSX_ARCHITECTURES}") - ENDIF () - IF (NOT "${CMAKE_OSX_SYSROOT}" STREQUAL "") - LIST(APPEND COMPILE_FLAGS "-isysroot ${CMAKE_OSX_SYSROOT}") - ENDIF () - IF (NOT "${CMAKE_OSX_DEPLOYMENT_TARGET}" STREQUAL "") - LIST(APPEND COMPILE_FLAGS "-mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}") - ENDIF () - ENDIF () - - GET_DIRECTORY_PROPERTY(TARGET_DEFINITIONS COMPILE_DEFINITIONS) - FOREACH(ITEM ${TARGET_DEFINITIONS}) - LIST(APPEND DEFINITION_FLAGS "-D${ITEM} ") - ENDFOREACH(ITEM) - - SEPARATE_ARGUMENTS(COMPILE_FLAGS) - SEPARATE_ARGUMENTS(INCLUDE_FLAGS) - SEPARATE_ARGUMENTS(DEFINITION_FLAGS) - - GET_FILENAME_COMPONENT(PCH_SRC_N ${PCH_SRC} NAME) - ADD_LIBRARY(${PCH_SRC_N}_dephelp MODULE ${PCH_SRC}) - - ADD_CUSTOM_COMMAND( - OUTPUT ${OUT} - COMMAND ${CMAKE_CXX_COMPILER} - ARGS ${DEFINITION_FLAGS} ${COMPILE_FLAGS} ${INCLUDE_FLAGS} -x c++-header -c ${IN} -o ${OUT} - DEPENDS ${IN} ${PCH_SRC_N}_dephelp - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} - ) - - ADD_CUSTOM_TARGET(generate_${PCH_SRC_N} - DEPENDS ${OUT} - ) - - FOREACH(TARGET_NAME ${TARGET_NAME_LIST}) - ADD_DEPENDENCIES(${TARGET_NAME} generate_${PCH_SRC_N}) - ENDFOREACH() - -ENDFUNCTION(GENERATE_CXX_PCH_COMMAND) - -FUNCTION(ADD_CXX_PCH_GCC TARGET_NAME_LIST PCH_HEADER PCH_SOURCE) - GET_COMMON_PCH_PARAMS("${TARGET_NAME_LIST}" ${PCH_HEADER} "gch" "-I") - GENERATE_CXX_PCH_COMMAND("${TARGET_NAME_LIST}" "${INCLUDE_FLAGS}" ${PCH_HEADER} ${PCH_SOURCE} ${PCH_HEADER_OUT}) - - FOREACH(TARGET_NAME ${TARGET_NAME_LIST}) - SET_TARGET_PROPERTIES( - ${TARGET_NAME} PROPERTIES - COMPILE_FLAGS "-include ${CMAKE_CURRENT_BINARY_DIR}/${PCH_HEADER_NAME}" - ) - ENDFOREACH() -ENDFUNCTION(ADD_CXX_PCH_GCC) - -FUNCTION(ADD_CXX_PCH_CLANG TARGET_NAME_LIST PCH_HEADER PCH_SOURCE) - GET_COMMON_PCH_PARAMS("${TARGET_NAME_LIST}" ${PCH_HEADER} "pch" "-I") - GENERATE_CXX_PCH_COMMAND("${TARGET_NAME_LIST}" "${INCLUDE_FLAGS}" ${PCH_HEADER} ${PCH_SOURCE} ${PCH_HEADER_OUT}) - - FOREACH(TARGET_NAME ${TARGET_NAME_LIST}) - SET_TARGET_PROPERTIES( - ${TARGET_NAME} PROPERTIES - COMPILE_FLAGS "-include-pch ${PCH_HEADER_OUT}" - ) - ENDFOREACH() -ENDFUNCTION(ADD_CXX_PCH_CLANG) - -FUNCTION(ADD_CXX_PCH_MSVC TARGET_NAME_LIST PCH_HEADER PCH_SOURCE) - GET_COMMON_PCH_PARAMS("${TARGET_NAME_LIST}" ${PCH_HEADER} "pch" "/I") - - FOREACH(TARGET_NAME ${TARGET_NAME_LIST}) - SET(PCH_COMPILE_FLAGS "/FI${PCH_HEADER_NAME} /Yu${PCH_HEADER_NAME}") - IF (NOT ${CMAKE_MAKE_PROGRAM} MATCHES "MSBuild") - SET(PCH_COMPILE_FLAGS "${PCH_COMPILE_FLAGS} /Fp${PCH_HEADER_OUT}") - SET(TARGET_SOURCES_LIST "") - GET_PROPERTY(TARGET_SOURCES_LIST TARGET ${TARGET_NAME} PROPERTY SOURCES) - LIST(REMOVE_ITEM TARGET_SOURCES_LIST ${PCH_SOURCE}) - SET_SOURCE_FILES_PROPERTIES(${TARGET_SOURCES_LIST} PROPERTIES OBJECT_DEPENDS "${CMAKE_CURRENT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/${TARGET_NAME}.dir/${PCH_SOURCE}.obj") - ENDIF() - SET_TARGET_PROPERTIES( - ${TARGET_NAME} PROPERTIES - COMPILE_FLAGS "${PCH_COMPILE_FLAGS}" - ) - ENDFOREACH() - - SET_SOURCE_FILES_PROPERTIES( - ${PCH_SOURCE} PROPERTIES - COMPILE_FLAGS "/Yc${PCH_HEADER_NAME}" - ) -ENDFUNCTION(ADD_CXX_PCH_MSVC) - -FUNCTION(ADD_CXX_PCH_XCODE TARGET_NAME_LIST PCH_HEADER PCH_SOURCE) - FOREACH(TARGET_NAME ${TARGET_NAME_LIST}) - SET_TARGET_PROPERTIES("${TARGET_NAME}" PROPERTIES - XCODE_ATTRIBUTE_GCC_PRECOMPILE_PREFIX_HEADER YES - XCODE_ATTRIBUTE_GCC_PREFIX_HEADER "${CMAKE_CURRENT_SOURCE_DIR}/${PCH_HEADER}" - ) - ENDFOREACH() -ENDFUNCTION(ADD_CXX_PCH_XCODE) - -FUNCTION(ADD_CXX_PCH TARGET_NAME_LIST PCH_HEADER PCH_SOURCE) - IF (CMAKE_CXX_COMPILER_ID MATCHES "MSVC") - ADD_CXX_PCH_MSVC("${TARGET_NAME_LIST}" ${PCH_HEADER} ${PCH_SOURCE}) - ELSEIF ("${CMAKE_GENERATOR}" MATCHES "Xcode") - ADD_CXX_PCH_XCODE("${TARGET_NAME_LIST}" ${PCH_HEADER} ${PCH_SOURCE}) - ELSEIF ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang") - ADD_CXX_PCH_CLANG("${TARGET_NAME_LIST}" ${PCH_HEADER} ${PCH_SOURCE}) - ELSEIF ("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU") - ADD_CXX_PCH_GCC("${TARGET_NAME_LIST}" ${PCH_HEADER} ${PCH_SOURCE}) - ENDIF () -ENDFUNCTION(ADD_CXX_PCH) + cotire(${TARGET_NAME_LIST}) +endfunction(ADD_CXX_PCH) diff --git a/cmake/platform/unix/settings.cmake b/cmake/platform/unix/settings.cmake index 79b426d7e03..0d38c6886a5 100644 --- a/cmake/platform/unix/settings.cmake +++ b/cmake/platform/unix/settings.cmake @@ -32,5 +32,7 @@ elseif(CMAKE_C_COMPILER MATCHES "icc") elseif(CMAKE_C_COMPILER MATCHES "clang" OR CMAKE_C_COMPILER_ID MATCHES "Clang") include(${CMAKE_SOURCE_DIR}/cmake/compiler/clang/settings.cmake) else() - add_definitions(-D_BUILD_DIRECTIVE='"${CMAKE_BUILD_TYPE}"') + target_compile_definitions(trinity-compile-option-interface + INTERFACE + -D_BUILD_DIRECTIVE="${CMAKE_BUILD_TYPE}") endif() diff --git a/dep/CMakeLists.txt b/dep/CMakeLists.txt index 139e51664ff..da9527f9c98 100644 --- a/dep/CMakeLists.txt +++ b/dep/CMakeLists.txt @@ -8,17 +8,6 @@ # WITHOUT ANY WARRANTY, to the extent permitted by law; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") - # Search twice, once for space after /W argument, once for end of line as CMake regex has no \b - string(REGEX REPLACE "/W[0-4] " "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") - string(REGEX REPLACE "/W[0-4]$" "" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") - string(REGEX REPLACE "/W[0-4] " "" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}") - string(REGEX REPLACE "/W[0-4]$" "" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}") - add_definitions(/W0) -else() - add_definitions(-w) -endif() - add_subdirectory(threads) if(SERVERS OR TOOLS) diff --git a/dep/PackageList.txt b/dep/PackageList.txt index 786febfa18a..df8139ddd3e 100644 --- a/dep/PackageList.txt +++ b/dep/PackageList.txt @@ -12,13 +12,17 @@ bzip2 (a freely available, patent free, high-quality data compressor) http://www.bzip.org/ Version: 1.0.6 +cotire (CMake module to speed up builds) + https://github.com/sakra/cotire + Version: 1.7.10 516d78476f6dda336181fc5514f72774e1e0a8e2 + efws (Entropia File System Watcher - crossplatform file system watcher) https://bitbucket.org/SpartanJ/efsw Version: 1.0.0 9a7cbec70b8a88b2e876a382f57c59f3796da0d9 fmt (a small, safe and fast formatting library) https://github.com/fmtlib/fmt - Version: 4.0.0 5f39721c0a41be404a23c3893cdea89e598c9531 + Version: 4.0.0 f9c97de46b9914c86366ddcb3474a36e654cbd42 G3D (a commercial-grade C++ 3D engine available as Open Source (BSD License) http://g3d.sourceforge.net/ diff --git a/dep/StormLib/CMakeLists.txt b/dep/StormLib/CMakeLists.txt index 7096c8f8729..a5478ebcd33 100644 --- a/dep/StormLib/CMakeLists.txt +++ b/dep/StormLib/CMakeLists.txt @@ -211,56 +211,37 @@ set(TOMMATH_FILES src/libtommath/bn_s_mp_sub.c ) -set(ZLIB_BZIP2_FILES - src/bzip2/blocksort.c - src/bzip2/bzlib.c - src/bzip2/compress.c - src/bzip2/crctable.c - src/bzip2/decompress.c - src/bzip2/huffman.c - src/bzip2/randtable.c - src/zlib/adler32.c - src/zlib/compress2.c - src/zlib/crc32.c - src/zlib/deflate.c - src/zlib/inffast.c - src/zlib/inflate.c - src/zlib/inftrees.c - src/zlib/trees.c - src/zlib/zutil.c -) - set(TEST_SRC_FILES test/Test.cpp ) add_definitions(-D_7ZIP_ST -DBZ_STRICT_ANSI) +add_definitions(-D__SYS_ZLIB -D__SYS_BZLIB) if(WIN32) if(MSVC) add_definitions(-D_7ZIP_ST -DWIN32) endif() - set(SRC_ADDITIONAL_FILES ${ZLIB_BZIP2_FILES} ${TOMCRYPT_FILES} ${TOMMATH_FILES}) + set(SRC_ADDITIONAL_FILES ${TOMCRYPT_FILES} ${TOMMATH_FILES}) set(LINK_LIBS wininet) endif() if(APPLE) - set(LINK_LIBS z bz2) set(SRC_ADDITIONAL_FILES ${TOMCRYPT_FILES} ${TOMMATH_FILES}) endif() if (${CMAKE_SYSTEM_NAME} STREQUAL Linux) option(WITH_LIBTOMCRYPT "Use system LibTomCrypt library" OFF) if(WITH_LIBTOMCRYPT) - set(LINK_LIBS z bz2 tomcrypt) + set(LINK_LIBS tomcrypt) else() - set(LINK_LIBS z bz2) set(SRC_ADDITIONAL_FILES ${TOMCRYPT_FILES} ${TOMMATH_FILES}) endif() endif() add_library(storm STATIC ${SRC_FILES} ${SRC_ADDITIONAL_FILES}) -target_link_libraries(storm ${LINK_LIBS}) + +set_target_properties(storm PROPERTIES LINKER_LANGUAGE CXX) if(UNIX) set_target_properties(storm PROPERTIES SOVERSION 0) @@ -270,3 +251,22 @@ endif() if(WIN32) set_target_properties(storm PROPERTIES OUTPUT_NAME StormLib) endif() + +target_include_directories(storm + PUBLIC + ${CMAKE_CURRENT_SOURCE_DIR}/src + ${CMAKE_SOURCE_DIR}/dep/zlib + ${CMAKE_SOURCE_DIR}/dep/bzip2) + +target_link_libraries(storm + PRIVATE + trinity-dependency-interface + PUBLIC + zlib + bzip2 + ${LINK_LIBS}) + +set_target_properties(storm + PROPERTIES + FOLDER + "dep") diff --git a/dep/StormLib/src/bzip2/blocksort.c b/dep/StormLib/src/bzip2/blocksort.c deleted file mode 100644 index bd2dec157fa..00000000000 --- a/dep/StormLib/src/bzip2/blocksort.c +++ /dev/null @@ -1,1094 +0,0 @@ - -/*-------------------------------------------------------------*/ -/*--- Block sorting machinery ---*/ -/*--- blocksort.c ---*/ -/*-------------------------------------------------------------*/ - -/* ------------------------------------------------------------------ - This file is part of bzip2/libbzip2, a program and library for - lossless, block-sorting data compression. - - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward - - Please read the WARNING, DISCLAIMER and PATENTS sections in the - README file. - - This program is released under the terms of the license contained - in the file LICENSE. - ------------------------------------------------------------------ */ - - -#include "bzlib_private.h" - -/*---------------------------------------------*/ -/*--- Fallback O(N log(N)^2) sorting ---*/ -/*--- algorithm, for repetitive blocks ---*/ -/*---------------------------------------------*/ - -/*---------------------------------------------*/ -static -__inline__ -void fallbackSimpleSort ( UInt32* fmap, - UInt32* eclass, - Int32 lo, - Int32 hi ) -{ - Int32 i, j, tmp; - UInt32 ec_tmp; - - if (lo == hi) return; - - if (hi - lo > 3) { - for ( i = hi-4; i >= lo; i-- ) { - tmp = fmap[i]; - ec_tmp = eclass[tmp]; - for ( j = i+4; j <= hi && ec_tmp > eclass[fmap[j]]; j += 4 ) - fmap[j-4] = fmap[j]; - fmap[j-4] = tmp; - } - } - - for ( i = hi-1; i >= lo; i-- ) { - tmp = fmap[i]; - ec_tmp = eclass[tmp]; - for ( j = i+1; j <= hi && ec_tmp > eclass[fmap[j]]; j++ ) - fmap[j-1] = fmap[j]; - fmap[j-1] = tmp; - } -} - - -/*---------------------------------------------*/ -#define fswap(zz1, zz2) \ - { Int32 zztmp = zz1; zz1 = zz2; zz2 = zztmp; } - -#define fvswap(zzp1, zzp2, zzn) \ -{ \ - Int32 yyp1 = (zzp1); \ - Int32 yyp2 = (zzp2); \ - Int32 yyn = (zzn); \ - while (yyn > 0) { \ - fswap(fmap[yyp1], fmap[yyp2]); \ - yyp1++; yyp2++; yyn--; \ - } \ -} - - -#define fmin(a,b) ((a) < (b)) ? (a) : (b) - -#define fpush(lz,hz) { stackLo[sp] = lz; \ - stackHi[sp] = hz; \ - sp++; } - -#define fpop(lz,hz) { sp--; \ - lz = stackLo[sp]; \ - hz = stackHi[sp]; } - -#define FALLBACK_QSORT_SMALL_THRESH 10 -#define FALLBACK_QSORT_STACK_SIZE 100 - - -static -void fallbackQSort3 ( UInt32* fmap, - UInt32* eclass, - Int32 loSt, - Int32 hiSt ) -{ - Int32 unLo, unHi, ltLo, gtHi, n, m; - Int32 sp, lo, hi; - UInt32 med, r, r3; - Int32 stackLo[FALLBACK_QSORT_STACK_SIZE]; - Int32 stackHi[FALLBACK_QSORT_STACK_SIZE]; - - r = 0; - - sp = 0; - fpush ( loSt, hiSt ); - - while (sp > 0) { - - AssertH ( sp < FALLBACK_QSORT_STACK_SIZE - 1, 1004 ); - - fpop ( lo, hi ); - if (hi - lo < FALLBACK_QSORT_SMALL_THRESH) { - fallbackSimpleSort ( fmap, eclass, lo, hi ); - continue; - } - - /* Random partitioning. Median of 3 sometimes fails to - avoid bad cases. Median of 9 seems to help but - looks rather expensive. This too seems to work but - is cheaper. Guidance for the magic constants - 7621 and 32768 is taken from Sedgewick's algorithms - book, chapter 35. - */ - r = ((r * 7621) + 1) % 32768; - r3 = r % 3; - if (r3 == 0) med = eclass[fmap[lo]]; else - if (r3 == 1) med = eclass[fmap[(lo+hi)>>1]]; else - med = eclass[fmap[hi]]; - - unLo = ltLo = lo; - unHi = gtHi = hi; - - while (1) { - while (1) { - if (unLo > unHi) break; - n = (Int32)eclass[fmap[unLo]] - (Int32)med; - if (n == 0) { - fswap(fmap[unLo], fmap[ltLo]); - ltLo++; unLo++; - continue; - }; - if (n > 0) break; - unLo++; - } - while (1) { - if (unLo > unHi) break; - n = (Int32)eclass[fmap[unHi]] - (Int32)med; - if (n == 0) { - fswap(fmap[unHi], fmap[gtHi]); - gtHi--; unHi--; - continue; - }; - if (n < 0) break; - unHi--; - } - if (unLo > unHi) break; - fswap(fmap[unLo], fmap[unHi]); unLo++; unHi--; - } - - AssertD ( unHi == unLo-1, "fallbackQSort3(2)" ); - - if (gtHi < ltLo) continue; - - n = fmin(ltLo-lo, unLo-ltLo); fvswap(lo, unLo-n, n); - m = fmin(hi-gtHi, gtHi-unHi); fvswap(unLo, hi-m+1, m); - - n = lo + unLo - ltLo - 1; - m = hi - (gtHi - unHi) + 1; - - if (n - lo > hi - m) { - fpush ( lo, n ); - fpush ( m, hi ); - } else { - fpush ( m, hi ); - fpush ( lo, n ); - } - } -} - -#undef fmin -#undef fpush -#undef fpop -#undef fswap -#undef fvswap -#undef FALLBACK_QSORT_SMALL_THRESH -#undef FALLBACK_QSORT_STACK_SIZE - - -/*---------------------------------------------*/ -/* Pre: - nblock > 0 - eclass exists for [0 .. nblock-1] - ((UChar*)eclass) [0 .. nblock-1] holds block - ptr exists for [0 .. nblock-1] - - Post: - ((UChar*)eclass) [0 .. nblock-1] holds block - All other areas of eclass destroyed - fmap [0 .. nblock-1] holds sorted order - bhtab [ 0 .. 2+(nblock/32) ] destroyed -*/ - -#define SET_BH(zz) bhtab[(zz) >> 5] |= (1 << ((zz) & 31)) -#define CLEAR_BH(zz) bhtab[(zz) >> 5] &= ~(1 << ((zz) & 31)) -#define ISSET_BH(zz) (bhtab[(zz) >> 5] & (1 << ((zz) & 31))) -#define WORD_BH(zz) bhtab[(zz) >> 5] -#define UNALIGNED_BH(zz) ((zz) & 0x01f) - -static -void fallbackSort ( UInt32* fmap, - UInt32* eclass, - UInt32* bhtab, - Int32 nblock, - Int32 verb ) -{ - Int32 ftab[257]; - Int32 ftabCopy[256]; - Int32 H, i, j, k, l, r, cc, cc1; - Int32 nNotDone; - Int32 nBhtab; - UChar* eclass8 = (UChar*)eclass; - - /*-- - Initial 1-char radix sort to generate - initial fmap and initial BH bits. - --*/ - if (verb >= 4) - VPrintf0 ( " bucket sorting ...\n" ); - for (i = 0; i < 257; i++) ftab[i] = 0; - for (i = 0; i < nblock; i++) ftab[eclass8[i]]++; - for (i = 0; i < 256; i++) ftabCopy[i] = ftab[i]; - for (i = 1; i < 257; i++) ftab[i] += ftab[i-1]; - - for (i = 0; i < nblock; i++) { - j = eclass8[i]; - k = ftab[j] - 1; - ftab[j] = k; - fmap[k] = i; - } - - nBhtab = 2 + (nblock / 32); - for (i = 0; i < nBhtab; i++) bhtab[i] = 0; - for (i = 0; i < 256; i++) SET_BH(ftab[i]); - - /*-- - Inductively refine the buckets. Kind-of an - "exponential radix sort" (!), inspired by the - Manber-Myers suffix array construction algorithm. - --*/ - - /*-- set sentinel bits for block-end detection --*/ - for (i = 0; i < 32; i++) { - SET_BH(nblock + 2*i); - CLEAR_BH(nblock + 2*i + 1); - } - - /*-- the log(N) loop --*/ - H = 1; - while (1) { - - if (verb >= 4) - VPrintf1 ( " depth %6d has ", H ); - - j = 0; - for (i = 0; i < nblock; i++) { - if (ISSET_BH(i)) j = i; - k = fmap[i] - H; if (k < 0) k += nblock; - eclass[k] = j; - } - - nNotDone = 0; - r = -1; - while (1) { - - /*-- find the next non-singleton bucket --*/ - k = r + 1; - while (ISSET_BH(k) && UNALIGNED_BH(k)) k++; - if (ISSET_BH(k)) { - while (WORD_BH(k) == 0xffffffff) k += 32; - while (ISSET_BH(k)) k++; - } - l = k - 1; - if (l >= nblock) break; - while (!ISSET_BH(k) && UNALIGNED_BH(k)) k++; - if (!ISSET_BH(k)) { - while (WORD_BH(k) == 0x00000000) k += 32; - while (!ISSET_BH(k)) k++; - } - r = k - 1; - if (r >= nblock) break; - - /*-- now [l, r] bracket current bucket --*/ - if (r > l) { - nNotDone += (r - l + 1); - fallbackQSort3 ( fmap, eclass, l, r ); - - /*-- scan bucket and generate header bits-- */ - cc = -1; - for (i = l; i <= r; i++) { - cc1 = eclass[fmap[i]]; - if (cc != cc1) { SET_BH(i); cc = cc1; }; - } - } - } - - if (verb >= 4) - VPrintf1 ( "%6d unresolved strings\n", nNotDone ); - - H *= 2; - if (H > nblock || nNotDone == 0) break; - } - - /*-- - Reconstruct the original block in - eclass8 [0 .. nblock-1], since the - previous phase destroyed it. - --*/ - if (verb >= 4) - VPrintf0 ( " reconstructing block ...\n" ); - j = 0; - for (i = 0; i < nblock; i++) { - while (ftabCopy[j] == 0) j++; - ftabCopy[j]--; - eclass8[fmap[i]] = (UChar)j; - } - AssertH ( j < 256, 1005 ); -} - -#undef SET_BH -#undef CLEAR_BH -#undef ISSET_BH -#undef WORD_BH -#undef UNALIGNED_BH - - -/*---------------------------------------------*/ -/*--- The main, O(N^2 log(N)) sorting ---*/ -/*--- algorithm. Faster for "normal" ---*/ -/*--- non-repetitive blocks. ---*/ -/*---------------------------------------------*/ - -/*---------------------------------------------*/ -static -__inline__ -Bool mainGtU ( UInt32 i1, - UInt32 i2, - UChar* block, - UInt16* quadrant, - UInt32 nblock, - Int32* budget ) -{ - Int32 k; - UChar c1, c2; - UInt16 s1, s2; - - AssertD ( i1 != i2, "mainGtU" ); - /* 1 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 2 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 3 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 4 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 5 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 6 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 7 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 8 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 9 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 10 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 11 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - /* 12 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - i1++; i2++; - - k = nblock + 8; - - do { - /* 1 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - s1 = quadrant[i1]; s2 = quadrant[i2]; - if (s1 != s2) return (s1 > s2); - i1++; i2++; - /* 2 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - s1 = quadrant[i1]; s2 = quadrant[i2]; - if (s1 != s2) return (s1 > s2); - i1++; i2++; - /* 3 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - s1 = quadrant[i1]; s2 = quadrant[i2]; - if (s1 != s2) return (s1 > s2); - i1++; i2++; - /* 4 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - s1 = quadrant[i1]; s2 = quadrant[i2]; - if (s1 != s2) return (s1 > s2); - i1++; i2++; - /* 5 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - s1 = quadrant[i1]; s2 = quadrant[i2]; - if (s1 != s2) return (s1 > s2); - i1++; i2++; - /* 6 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - s1 = quadrant[i1]; s2 = quadrant[i2]; - if (s1 != s2) return (s1 > s2); - i1++; i2++; - /* 7 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - s1 = quadrant[i1]; s2 = quadrant[i2]; - if (s1 != s2) return (s1 > s2); - i1++; i2++; - /* 8 */ - c1 = block[i1]; c2 = block[i2]; - if (c1 != c2) return (c1 > c2); - s1 = quadrant[i1]; s2 = quadrant[i2]; - if (s1 != s2) return (s1 > s2); - i1++; i2++; - - if (i1 >= nblock) i1 -= nblock; - if (i2 >= nblock) i2 -= nblock; - - k -= 8; - (*budget)--; - } - while (k >= 0); - - return False; -} - - -/*---------------------------------------------*/ -/*-- - Knuth's increments seem to work better - than Incerpi-Sedgewick here. Possibly - because the number of elems to sort is - usually small, typically <= 20. ---*/ -static -Int32 incs[14] = { 1, 4, 13, 40, 121, 364, 1093, 3280, - 9841, 29524, 88573, 265720, - 797161, 2391484 }; - -static -void mainSimpleSort ( UInt32* ptr, - UChar* block, - UInt16* quadrant, - Int32 nblock, - Int32 lo, - Int32 hi, - Int32 d, - Int32* budget ) -{ - Int32 i, j, h, bigN, hp; - UInt32 v; - - bigN = hi - lo + 1; - if (bigN < 2) return; - - hp = 0; - while (incs[hp] < bigN) hp++; - hp--; - - for (; hp >= 0; hp--) { - h = incs[hp]; - - i = lo + h; - while (True) { - - /*-- copy 1 --*/ - if (i > hi) break; - v = ptr[i]; - j = i; - while ( mainGtU ( - ptr[j-h]+d, v+d, block, quadrant, nblock, budget - ) ) { - ptr[j] = ptr[j-h]; - j = j - h; - if (j <= (lo + h - 1)) break; - } - ptr[j] = v; - i++; - - /*-- copy 2 --*/ - if (i > hi) break; - v = ptr[i]; - j = i; - while ( mainGtU ( - ptr[j-h]+d, v+d, block, quadrant, nblock, budget - ) ) { - ptr[j] = ptr[j-h]; - j = j - h; - if (j <= (lo + h - 1)) break; - } - ptr[j] = v; - i++; - - /*-- copy 3 --*/ - if (i > hi) break; - v = ptr[i]; - j = i; - while ( mainGtU ( - ptr[j-h]+d, v+d, block, quadrant, nblock, budget - ) ) { - ptr[j] = ptr[j-h]; - j = j - h; - if (j <= (lo + h - 1)) break; - } - ptr[j] = v; - i++; - - if (*budget < 0) return; - } - } -} - - -/*---------------------------------------------*/ -/*-- - The following is an implementation of - an elegant 3-way quicksort for strings, - described in a paper "Fast Algorithms for - Sorting and Searching Strings", by Robert - Sedgewick and Jon L. Bentley. ---*/ - -#define mswap(zz1, zz2) \ - { Int32 zztmp = zz1; zz1 = zz2; zz2 = zztmp; } - -#define mvswap(zzp1, zzp2, zzn) \ -{ \ - Int32 yyp1 = (zzp1); \ - Int32 yyp2 = (zzp2); \ - Int32 yyn = (zzn); \ - while (yyn > 0) { \ - mswap(ptr[yyp1], ptr[yyp2]); \ - yyp1++; yyp2++; yyn--; \ - } \ -} - -static -__inline__ -UChar mmed3 ( UChar a, UChar b, UChar c ) -{ - UChar t; - if (a > b) { t = a; a = b; b = t; }; - if (b > c) { - b = c; - if (a > b) b = a; - } - return b; -} - -#define mmin(a,b) ((a) < (b)) ? (a) : (b) - -#define mpush(lz,hz,dz) { stackLo[sp] = lz; \ - stackHi[sp] = hz; \ - stackD [sp] = dz; \ - sp++; } - -#define mpop(lz,hz,dz) { sp--; \ - lz = stackLo[sp]; \ - hz = stackHi[sp]; \ - dz = stackD [sp]; } - - -#define mnextsize(az) (nextHi[az]-nextLo[az]) - -#define mnextswap(az,bz) \ - { Int32 tz; \ - tz = nextLo[az]; nextLo[az] = nextLo[bz]; nextLo[bz] = tz; \ - tz = nextHi[az]; nextHi[az] = nextHi[bz]; nextHi[bz] = tz; \ - tz = nextD [az]; nextD [az] = nextD [bz]; nextD [bz] = tz; } - - -#define MAIN_QSORT_SMALL_THRESH 20 -#define MAIN_QSORT_DEPTH_THRESH (BZ_N_RADIX + BZ_N_QSORT) -#define MAIN_QSORT_STACK_SIZE 100 - -static -void mainQSort3 ( UInt32* ptr, - UChar* block, - UInt16* quadrant, - Int32 nblock, - Int32 loSt, - Int32 hiSt, - Int32 dSt, - Int32* budget ) -{ - Int32 unLo, unHi, ltLo, gtHi, n, m, med; - Int32 sp, lo, hi, d; - - Int32 stackLo[MAIN_QSORT_STACK_SIZE]; - Int32 stackHi[MAIN_QSORT_STACK_SIZE]; - Int32 stackD [MAIN_QSORT_STACK_SIZE]; - - Int32 nextLo[3]; - Int32 nextHi[3]; - Int32 nextD [3]; - - sp = 0; - mpush ( loSt, hiSt, dSt ); - - while (sp > 0) { - - AssertH ( sp < MAIN_QSORT_STACK_SIZE - 2, 1001 ); - - mpop ( lo, hi, d ); - if (hi - lo < MAIN_QSORT_SMALL_THRESH || - d > MAIN_QSORT_DEPTH_THRESH) { - mainSimpleSort ( ptr, block, quadrant, nblock, lo, hi, d, budget ); - if (*budget < 0) return; - continue; - } - - med = (Int32) - mmed3 ( block[ptr[ lo ]+d], - block[ptr[ hi ]+d], - block[ptr[ (lo+hi)>>1 ]+d] ); - - unLo = ltLo = lo; - unHi = gtHi = hi; - - while (True) { - while (True) { - if (unLo > unHi) break; - n = ((Int32)block[ptr[unLo]+d]) - med; - if (n == 0) { - mswap(ptr[unLo], ptr[ltLo]); - ltLo++; unLo++; continue; - }; - if (n > 0) break; - unLo++; - } - while (True) { - if (unLo > unHi) break; - n = ((Int32)block[ptr[unHi]+d]) - med; - if (n == 0) { - mswap(ptr[unHi], ptr[gtHi]); - gtHi--; unHi--; continue; - }; - if (n < 0) break; - unHi--; - } - if (unLo > unHi) break; - mswap(ptr[unLo], ptr[unHi]); unLo++; unHi--; - } - - AssertD ( unHi == unLo-1, "mainQSort3(2)" ); - - if (gtHi < ltLo) { - mpush(lo, hi, d+1 ); - continue; - } - - n = mmin(ltLo-lo, unLo-ltLo); mvswap(lo, unLo-n, n); - m = mmin(hi-gtHi, gtHi-unHi); mvswap(unLo, hi-m+1, m); - - n = lo + unLo - ltLo - 1; - m = hi - (gtHi - unHi) + 1; - - nextLo[0] = lo; nextHi[0] = n; nextD[0] = d; - nextLo[1] = m; nextHi[1] = hi; nextD[1] = d; - nextLo[2] = n+1; nextHi[2] = m-1; nextD[2] = d+1; - - if (mnextsize(0) < mnextsize(1)) mnextswap(0,1); - if (mnextsize(1) < mnextsize(2)) mnextswap(1,2); - if (mnextsize(0) < mnextsize(1)) mnextswap(0,1); - - AssertD (mnextsize(0) >= mnextsize(1), "mainQSort3(8)" ); - AssertD (mnextsize(1) >= mnextsize(2), "mainQSort3(9)" ); - - mpush (nextLo[0], nextHi[0], nextD[0]); - mpush (nextLo[1], nextHi[1], nextD[1]); - mpush (nextLo[2], nextHi[2], nextD[2]); - } -} - -#undef mswap -#undef mvswap -#undef mpush -#undef mpop -#undef mmin -#undef mnextsize -#undef mnextswap -#undef MAIN_QSORT_SMALL_THRESH -#undef MAIN_QSORT_DEPTH_THRESH -#undef MAIN_QSORT_STACK_SIZE - - -/*---------------------------------------------*/ -/* Pre: - nblock > N_OVERSHOOT - block32 exists for [0 .. nblock-1 +N_OVERSHOOT] - ((UChar*)block32) [0 .. nblock-1] holds block - ptr exists for [0 .. nblock-1] - - Post: - ((UChar*)block32) [0 .. nblock-1] holds block - All other areas of block32 destroyed - ftab [0 .. 65536 ] destroyed - ptr [0 .. nblock-1] holds sorted order - if (*budget < 0), sorting was abandoned -*/ - -#define BIGFREQ(b) (ftab[((b)+1) << 8] - ftab[(b) << 8]) -#define SETMASK (1 << 21) -#define CLEARMASK (~(SETMASK)) - -static -void mainSort ( UInt32* ptr, - UChar* block, - UInt16* quadrant, - UInt32* ftab, - Int32 nblock, - Int32 verb, - Int32* budget ) -{ - Int32 i, j, k, ss, sb; - Int32 runningOrder[256]; - Bool bigDone[256]; - Int32 copyStart[256]; - Int32 copyEnd [256]; - UChar c1; - Int32 numQSorted; - UInt16 s; - if (verb >= 4) VPrintf0 ( " main sort initialise ...\n" ); - - /*-- set up the 2-byte frequency table --*/ - for (i = 65536; i >= 0; i--) ftab[i] = 0; - - j = block[0] << 8; - i = nblock-1; - for (; i >= 3; i -= 4) { - quadrant[i] = 0; - j = (j >> 8) | ( ((UInt16)block[i]) << 8); - ftab[j]++; - quadrant[i-1] = 0; - j = (j >> 8) | ( ((UInt16)block[i-1]) << 8); - ftab[j]++; - quadrant[i-2] = 0; - j = (j >> 8) | ( ((UInt16)block[i-2]) << 8); - ftab[j]++; - quadrant[i-3] = 0; - j = (j >> 8) | ( ((UInt16)block[i-3]) << 8); - ftab[j]++; - } - for (; i >= 0; i--) { - quadrant[i] = 0; - j = (j >> 8) | ( ((UInt16)block[i]) << 8); - ftab[j]++; - } - - /*-- (emphasises close relationship of block & quadrant) --*/ - for (i = 0; i < BZ_N_OVERSHOOT; i++) { - block [nblock+i] = block[i]; - quadrant[nblock+i] = 0; - } - - if (verb >= 4) VPrintf0 ( " bucket sorting ...\n" ); - - /*-- Complete the initial radix sort --*/ - for (i = 1; i <= 65536; i++) ftab[i] += ftab[i-1]; - - s = block[0] << 8; - i = nblock-1; - for (; i >= 3; i -= 4) { - s = (s >> 8) | (block[i] << 8); - j = ftab[s] -1; - ftab[s] = j; - ptr[j] = i; - s = (s >> 8) | (block[i-1] << 8); - j = ftab[s] -1; - ftab[s] = j; - ptr[j] = i-1; - s = (s >> 8) | (block[i-2] << 8); - j = ftab[s] -1; - ftab[s] = j; - ptr[j] = i-2; - s = (s >> 8) | (block[i-3] << 8); - j = ftab[s] -1; - ftab[s] = j; - ptr[j] = i-3; - } - for (; i >= 0; i--) { - s = (s >> 8) | (block[i] << 8); - j = ftab[s] -1; - ftab[s] = j; - ptr[j] = i; - } - - /*-- - Now ftab contains the first loc of every small bucket. - Calculate the running order, from smallest to largest - big bucket. - --*/ - for (i = 0; i <= 255; i++) { - bigDone [i] = False; - runningOrder[i] = i; - } - - { - Int32 vv; - Int32 h = 1; - do h = 3 * h + 1; while (h <= 256); - do { - h = h / 3; - for (i = h; i <= 255; i++) { - vv = runningOrder[i]; - j = i; - while ( BIGFREQ(runningOrder[j-h]) > BIGFREQ(vv) ) { - runningOrder[j] = runningOrder[j-h]; - j = j - h; - if (j <= (h - 1)) goto zero; - } - zero: - runningOrder[j] = vv; - } - } while (h != 1); - } - - /*-- - The main sorting loop. - --*/ - - numQSorted = 0; - - for (i = 0; i <= 255; i++) { - - /*-- - Process big buckets, starting with the least full. - Basically this is a 3-step process in which we call - mainQSort3 to sort the small buckets [ss, j], but - also make a big effort to avoid the calls if we can. - --*/ - ss = runningOrder[i]; - - /*-- - Step 1: - Complete the big bucket [ss] by quicksorting - any unsorted small buckets [ss, j], for j != ss. - Hopefully previous pointer-scanning phases have already - completed many of the small buckets [ss, j], so - we don't have to sort them at all. - --*/ - for (j = 0; j <= 255; j++) { - if (j != ss) { - sb = (ss << 8) + j; - if ( ! (ftab[sb] & SETMASK) ) { - Int32 lo = ftab[sb] & CLEARMASK; - Int32 hi = (ftab[sb+1] & CLEARMASK) - 1; - if (hi > lo) { - if (verb >= 4) - VPrintf4 ( " qsort [0x%x, 0x%x] " - "done %d this %d\n", - ss, j, numQSorted, hi - lo + 1 ); - mainQSort3 ( - ptr, block, quadrant, nblock, - lo, hi, BZ_N_RADIX, budget - ); - numQSorted += (hi - lo + 1); - if (*budget < 0) return; - } - } - ftab[sb] |= SETMASK; - } - } - - AssertH ( !bigDone[ss], 1006 ); - - /*-- - Step 2: - Now scan this big bucket [ss] so as to synthesise the - sorted order for small buckets [t, ss] for all t, - including, magically, the bucket [ss,ss] too. - This will avoid doing Real Work in subsequent Step 1's. - --*/ - { - for (j = 0; j <= 255; j++) { - copyStart[j] = ftab[(j << 8) + ss] & CLEARMASK; - copyEnd [j] = (ftab[(j << 8) + ss + 1] & CLEARMASK) - 1; - } - for (j = ftab[ss << 8] & CLEARMASK; j < copyStart[ss]; j++) { - k = ptr[j]-1; if (k < 0) k += nblock; - c1 = block[k]; - if (!bigDone[c1]) - ptr[ copyStart[c1]++ ] = k; - } - for (j = (ftab[(ss+1) << 8] & CLEARMASK) - 1; j > copyEnd[ss]; j--) { - k = ptr[j]-1; if (k < 0) k += nblock; - c1 = block[k]; - if (!bigDone[c1]) - ptr[ copyEnd[c1]-- ] = k; - } - } - - AssertH ( (copyStart[ss]-1 == copyEnd[ss]) - || - /* Extremely rare case missing in bzip2-1.0.0 and 1.0.1. - Necessity for this case is demonstrated by compressing - a sequence of approximately 48.5 million of character - 251; 1.0.0/1.0.1 will then die here. */ - (copyStart[ss] == 0 && copyEnd[ss] == nblock-1), - 1007 ) - - for (j = 0; j <= 255; j++) ftab[(j << 8) + ss] |= SETMASK; - - /*-- - Step 3: - The [ss] big bucket is now done. Record this fact, - and update the quadrant descriptors. Remember to - update quadrants in the overshoot area too, if - necessary. The "if (i < 255)" test merely skips - this updating for the last bucket processed, since - updating for the last bucket is pointless. - - The quadrant array provides a way to incrementally - cache sort orderings, as they appear, so as to - make subsequent comparisons in fullGtU() complete - faster. For repetitive blocks this makes a big - difference (but not big enough to be able to avoid - the fallback sorting mechanism, exponential radix sort). - - The precise meaning is: at all times: - - for 0 <= i < nblock and 0 <= j <= nblock - - if block[i] != block[j], - - then the relative values of quadrant[i] and - quadrant[j] are meaningless. - - else { - if quadrant[i] < quadrant[j] - then the string starting at i lexicographically - precedes the string starting at j - - else if quadrant[i] > quadrant[j] - then the string starting at j lexicographically - precedes the string starting at i - - else - the relative ordering of the strings starting - at i and j has not yet been determined. - } - --*/ - bigDone[ss] = True; - - if (i < 255) { - Int32 bbStart = ftab[ss << 8] & CLEARMASK; - Int32 bbSize = (ftab[(ss+1) << 8] & CLEARMASK) - bbStart; - Int32 shifts = 0; - - while ((bbSize >> shifts) > 65534) shifts++; - - for (j = bbSize-1; j >= 0; j--) { - Int32 a2update = ptr[bbStart + j]; - UInt16 qVal = (UInt16)(j >> shifts); - quadrant[a2update] = qVal; - if (a2update < BZ_N_OVERSHOOT) - quadrant[a2update + nblock] = qVal; - } - AssertH ( ((bbSize-1) >> shifts) <= 65535, 1002 ); - } - - } - - if (verb >= 4) - VPrintf3 ( " %d pointers, %d sorted, %d scanned\n", - nblock, numQSorted, nblock - numQSorted ); -} - -#undef BIGFREQ -#undef SETMASK -#undef CLEARMASK - - -/*---------------------------------------------*/ -/* Pre: - nblock > 0 - arr2 exists for [0 .. nblock-1 +N_OVERSHOOT] - ((UChar*)arr2) [0 .. nblock-1] holds block - arr1 exists for [0 .. nblock-1] - - Post: - ((UChar*)arr2) [0 .. nblock-1] holds block - All other areas of block destroyed - ftab [ 0 .. 65536 ] destroyed - arr1 [0 .. nblock-1] holds sorted order -*/ -void BZ2_blockSort ( EState* s ) -{ - UInt32* ptr = s->ptr; - UChar* block = s->block; - UInt32* ftab = s->ftab; - Int32 nblock = s->nblock; - Int32 verb = s->verbosity; - Int32 wfact = s->workFactor; - UInt16* quadrant; - Int32 budget; - Int32 budgetInit; - Int32 i; - - if (nblock < 10000) { - fallbackSort ( s->arr1, s->arr2, ftab, nblock, verb ); - } else { - /* Calculate the location for quadrant, remembering to get - the alignment right. Assumes that &(block[0]) is at least - 2-byte aligned -- this should be ok since block is really - the first section of arr2. - */ - i = nblock+BZ_N_OVERSHOOT; - if (i & 1) i++; - quadrant = (UInt16*)(&(block[i])); - - /* (wfact-1) / 3 puts the default-factor-30 - transition point at very roughly the same place as - with v0.1 and v0.9.0. - Not that it particularly matters any more, since the - resulting compressed stream is now the same regardless - of whether or not we use the main sort or fallback sort. - */ - if (wfact < 1 ) wfact = 1; - if (wfact > 100) wfact = 100; - budgetInit = nblock * ((wfact-1) / 3); - budget = budgetInit; - - mainSort ( ptr, block, quadrant, ftab, nblock, verb, &budget ); - if (verb >= 3) - VPrintf3 ( " %d work, %d block, ratio %5.2f\n", - budgetInit - budget, - nblock, - (float)(budgetInit - budget) / - (float)(nblock==0 ? 1 : nblock) ); - if (budget < 0) { - if (verb >= 2) - VPrintf0 ( " too repetitive; using fallback" - " sorting algorithm\n" ); - fallbackSort ( s->arr1, s->arr2, ftab, nblock, verb ); - } - } - - s->origPtr = -1; - for (i = 0; i < s->nblock; i++) - if (ptr[i] == 0) - { s->origPtr = i; break; }; - - AssertH( s->origPtr != -1, 1003 ); -} - - -/*-------------------------------------------------------------*/ -/*--- end blocksort.c ---*/ -/*-------------------------------------------------------------*/ diff --git a/dep/StormLib/src/bzip2/bzlib.c b/dep/StormLib/src/bzip2/bzlib.c deleted file mode 100644 index b98f3e586bc..00000000000 --- a/dep/StormLib/src/bzip2/bzlib.c +++ /dev/null @@ -1,1573 +0,0 @@ - -/*-------------------------------------------------------------*/ -/*--- Library top-level functions. ---*/ -/*--- bzlib.c ---*/ -/*-------------------------------------------------------------*/ - -/* ------------------------------------------------------------------ - This file is part of bzip2/libbzip2, a program and library for - lossless, block-sorting data compression. - - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward - - Please read the WARNING, DISCLAIMER and PATENTS sections in the - README file. - - This program is released under the terms of the license contained - in the file LICENSE. - ------------------------------------------------------------------ */ - -/* CHANGES - 0.9.0 -- original version. - 0.9.0a/b -- no changes in this file. - 0.9.0c -- made zero-length BZ_FLUSH work correctly in bzCompress(). - fixed bzWrite/bzRead to ignore zero-length requests. - fixed bzread to correctly handle read requests after EOF. - wrong parameter order in call to bzDecompressInit in - bzBuffToBuffDecompress. Fixed. -*/ - -#define _CRT_SECURE_NO_WARNINGS -#include "bzlib_private.h" - - -/*---------------------------------------------------*/ -/*--- Compression stuff ---*/ -/*---------------------------------------------------*/ - - -/*---------------------------------------------------*/ -#ifndef BZ_NO_STDIO -void BZ2_bz__AssertH__fail ( int errcode ) -{ - fprintf(stderr, - "\n\nbzip2/libbzip2: internal error number %d.\n" - "This is a bug in bzip2/libbzip2, %s.\n" - "Please report it to me at: jseward@bzip.org. If this happened\n" - "when you were using some program which uses libbzip2 as a\n" - "component, you should also report this bug to the author(s)\n" - "of that program. Please make an effort to report this bug;\n" - "timely and accurate bug reports eventually lead to higher\n" - "quality software. Thanks. Julian Seward, 10 December 2007.\n\n", - errcode, - BZ2_bzlibVersion() - ); - - if (errcode == 1007) { - fprintf(stderr, - "\n*** A special note about internal error number 1007 ***\n" - "\n" - "Experience suggests that a common cause of i.e. 1007\n" - "is unreliable memory or other hardware. The 1007 assertion\n" - "just happens to cross-check the results of huge numbers of\n" - "memory reads/writes, and so acts (unintendedly) as a stress\n" - "test of your memory system.\n" - "\n" - "I suggest the following: try compressing the file again,\n" - "possibly monitoring progress in detail with the -vv flag.\n" - "\n" - "* If the error cannot be reproduced, and/or happens at different\n" - " points in compression, you may have a flaky memory system.\n" - " Try a memory-test program. I have used Memtest86\n" - " (www.memtest86.com). At the time of writing it is free (GPLd).\n" - " Memtest86 tests memory much more thorougly than your BIOSs\n" - " power-on test, and may find failures that the BIOS doesn't.\n" - "\n" - "* If the error can be repeatably reproduced, this is a bug in\n" - " bzip2, and I would very much like to hear about it. Please\n" - " let me know, and, ideally, save a copy of the file causing the\n" - " problem -- without which I will be unable to investigate it.\n" - "\n" - ); - } - - exit(3); -} -#endif - - -/*---------------------------------------------------*/ -static -int bz_config_ok ( void ) -{ - if (sizeof(int) != 4) return 0; - if (sizeof(short) != 2) return 0; - if (sizeof(char) != 1) return 0; - return 1; -} - - -/*---------------------------------------------------*/ -static -void* default_bzalloc ( void* opaque, Int32 items, Int32 size ) -{ - void* v = malloc ( items * size ); - return v; -} - -static -void default_bzfree ( void* opaque, void* addr ) -{ - if (addr != NULL) free ( addr ); -} - - -/*---------------------------------------------------*/ -static -void prepare_new_block ( EState* s ) -{ - Int32 i; - s->nblock = 0; - s->numZ = 0; - s->state_out_pos = 0; - BZ_INITIALISE_CRC ( s->blockCRC ); - for (i = 0; i < 256; i++) s->inUse[i] = False; - s->blockNo++; -} - - -/*---------------------------------------------------*/ -static -void init_RL ( EState* s ) -{ - s->state_in_ch = 256; - s->state_in_len = 0; -} - - -static -Bool isempty_RL ( EState* s ) -{ - if (s->state_in_ch < 256 && s->state_in_len > 0) - return False; else - return True; -} - - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzCompressInit) - ( bz_stream* strm, - int blockSize100k, - int verbosity, - int workFactor ) -{ - Int32 n; - EState* s; - - if (!bz_config_ok()) return BZ_CONFIG_ERROR; - - if (strm == NULL || - blockSize100k < 1 || blockSize100k > 9 || - workFactor < 0 || workFactor > 250) - return BZ_PARAM_ERROR; - - if (workFactor == 0) workFactor = 30; - if (strm->bzalloc == NULL) strm->bzalloc = default_bzalloc; - if (strm->bzfree == NULL) strm->bzfree = default_bzfree; - - s = BZALLOC( sizeof(EState) ); - if (s == NULL) return BZ_MEM_ERROR; - s->strm = strm; - - s->arr1 = NULL; - s->arr2 = NULL; - s->ftab = NULL; - - n = 100000 * blockSize100k; - s->arr1 = BZALLOC( n * sizeof(UInt32) ); - s->arr2 = BZALLOC( (n+BZ_N_OVERSHOOT) * sizeof(UInt32) ); - s->ftab = BZALLOC( 65537 * sizeof(UInt32) ); - - if (s->arr1 == NULL || s->arr2 == NULL || s->ftab == NULL) { - if (s->arr1 != NULL) BZFREE(s->arr1); - if (s->arr2 != NULL) BZFREE(s->arr2); - if (s->ftab != NULL) BZFREE(s->ftab); - if (s != NULL) BZFREE(s); - return BZ_MEM_ERROR; - } - - s->blockNo = 0; - s->state = BZ_S_INPUT; - s->mode = BZ_M_RUNNING; - s->combinedCRC = 0; - s->blockSize100k = blockSize100k; - s->nblockMAX = 100000 * blockSize100k - 19; - s->verbosity = verbosity; - s->workFactor = workFactor; - - s->block = (UChar*)s->arr2; - s->mtfv = (UInt16*)s->arr1; - s->zbits = NULL; - s->ptr = (UInt32*)s->arr1; - - strm->state = s; - strm->total_in_lo32 = 0; - strm->total_in_hi32 = 0; - strm->total_out_lo32 = 0; - strm->total_out_hi32 = 0; - init_RL ( s ); - prepare_new_block ( s ); - return BZ_OK; -} - - -/*---------------------------------------------------*/ -static -void add_pair_to_block ( EState* s ) -{ - Int32 i; - UChar ch = (UChar)(s->state_in_ch); - for (i = 0; i < s->state_in_len; i++) { - BZ_UPDATE_CRC( s->blockCRC, ch ); - } - s->inUse[s->state_in_ch] = True; - switch (s->state_in_len) { - case 1: - s->block[s->nblock] = (UChar)ch; s->nblock++; - break; - case 2: - s->block[s->nblock] = (UChar)ch; s->nblock++; - s->block[s->nblock] = (UChar)ch; s->nblock++; - break; - case 3: - s->block[s->nblock] = (UChar)ch; s->nblock++; - s->block[s->nblock] = (UChar)ch; s->nblock++; - s->block[s->nblock] = (UChar)ch; s->nblock++; - break; - default: - s->inUse[s->state_in_len-4] = True; - s->block[s->nblock] = (UChar)ch; s->nblock++; - s->block[s->nblock] = (UChar)ch; s->nblock++; - s->block[s->nblock] = (UChar)ch; s->nblock++; - s->block[s->nblock] = (UChar)ch; s->nblock++; - s->block[s->nblock] = ((UChar)(s->state_in_len-4)); - s->nblock++; - break; - } -} - - -/*---------------------------------------------------*/ -static -void flush_RL ( EState* s ) -{ - if (s->state_in_ch < 256) add_pair_to_block ( s ); - init_RL ( s ); -} - - -/*---------------------------------------------------*/ -#define ADD_CHAR_TO_BLOCK(zs,zchh0) \ -{ \ - UInt32 zchh = (UInt32)(zchh0); \ - /*-- fast track the common case --*/ \ - if (zchh != zs->state_in_ch && \ - zs->state_in_len == 1) { \ - UChar ch = (UChar)(zs->state_in_ch); \ - BZ_UPDATE_CRC( zs->blockCRC, ch ); \ - zs->inUse[zs->state_in_ch] = True; \ - zs->block[zs->nblock] = (UChar)ch; \ - zs->nblock++; \ - zs->state_in_ch = zchh; \ - } \ - else \ - /*-- general, uncommon cases --*/ \ - if (zchh != zs->state_in_ch || \ - zs->state_in_len == 255) { \ - if (zs->state_in_ch < 256) \ - add_pair_to_block ( zs ); \ - zs->state_in_ch = zchh; \ - zs->state_in_len = 1; \ - } else { \ - zs->state_in_len++; \ - } \ -} - - -/*---------------------------------------------------*/ -static -Bool copy_input_until_stop ( EState* s ) -{ - Bool progress_in = False; - - if (s->mode == BZ_M_RUNNING) { - - /*-- fast track the common case --*/ - while (True) { - /*-- block full? --*/ - if (s->nblock >= s->nblockMAX) break; - /*-- no input? --*/ - if (s->strm->avail_in == 0) break; - progress_in = True; - ADD_CHAR_TO_BLOCK ( s, (UInt32)(*((UChar*)(s->strm->next_in))) ); - s->strm->next_in++; - s->strm->avail_in--; - s->strm->total_in_lo32++; - if (s->strm->total_in_lo32 == 0) s->strm->total_in_hi32++; - } - - } else { - - /*-- general, uncommon case --*/ - while (True) { - /*-- block full? --*/ - if (s->nblock >= s->nblockMAX) break; - /*-- no input? --*/ - if (s->strm->avail_in == 0) break; - /*-- flush/finish end? --*/ - if (s->avail_in_expect == 0) break; - progress_in = True; - ADD_CHAR_TO_BLOCK ( s, (UInt32)(*((UChar*)(s->strm->next_in))) ); - s->strm->next_in++; - s->strm->avail_in--; - s->strm->total_in_lo32++; - if (s->strm->total_in_lo32 == 0) s->strm->total_in_hi32++; - s->avail_in_expect--; - } - } - return progress_in; -} - - -/*---------------------------------------------------*/ -static -Bool copy_output_until_stop ( EState* s ) -{ - Bool progress_out = False; - - while (True) { - - /*-- no output space? --*/ - if (s->strm->avail_out == 0) break; - - /*-- block done? --*/ - if (s->state_out_pos >= s->numZ) break; - - progress_out = True; - *(s->strm->next_out) = s->zbits[s->state_out_pos]; - s->state_out_pos++; - s->strm->avail_out--; - s->strm->next_out++; - s->strm->total_out_lo32++; - if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; - } - - return progress_out; -} - - -/*---------------------------------------------------*/ -static -Bool handle_compress ( bz_stream* strm ) -{ - Bool progress_in = False; - Bool progress_out = False; - EState* s = strm->state; - - while (True) { - - if (s->state == BZ_S_OUTPUT) { - progress_out |= copy_output_until_stop ( s ); - if (s->state_out_pos < s->numZ) break; - if (s->mode == BZ_M_FINISHING && - s->avail_in_expect == 0 && - isempty_RL(s)) break; - prepare_new_block ( s ); - s->state = BZ_S_INPUT; - if (s->mode == BZ_M_FLUSHING && - s->avail_in_expect == 0 && - isempty_RL(s)) break; - } - - if (s->state == BZ_S_INPUT) { - progress_in |= copy_input_until_stop ( s ); - if (s->mode != BZ_M_RUNNING && s->avail_in_expect == 0) { - flush_RL ( s ); - BZ2_compressBlock ( s, (Bool)(s->mode == BZ_M_FINISHING) ); - s->state = BZ_S_OUTPUT; - } - else - if (s->nblock >= s->nblockMAX) { - BZ2_compressBlock ( s, False ); - s->state = BZ_S_OUTPUT; - } - else - if (s->strm->avail_in == 0) { - break; - } - } - - } - - return progress_in || progress_out; -} - - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzCompress) ( bz_stream *strm, int action ) -{ - Bool progress; - EState* s; - if (strm == NULL) return BZ_PARAM_ERROR; - s = strm->state; - if (s == NULL) return BZ_PARAM_ERROR; - if (s->strm != strm) return BZ_PARAM_ERROR; - - preswitch: - switch (s->mode) { - - case BZ_M_IDLE: - return BZ_SEQUENCE_ERROR; - - case BZ_M_RUNNING: - if (action == BZ_RUN) { - progress = handle_compress ( strm ); - return progress ? BZ_RUN_OK : BZ_PARAM_ERROR; - } - else - if (action == BZ_FLUSH) { - s->avail_in_expect = strm->avail_in; - s->mode = BZ_M_FLUSHING; - goto preswitch; - } - else - if (action == BZ_FINISH) { - s->avail_in_expect = strm->avail_in; - s->mode = BZ_M_FINISHING; - goto preswitch; - } - else - return BZ_PARAM_ERROR; - - case BZ_M_FLUSHING: - if (action != BZ_FLUSH) return BZ_SEQUENCE_ERROR; - if (s->avail_in_expect != s->strm->avail_in) - return BZ_SEQUENCE_ERROR; - progress = handle_compress ( strm ); - if (s->avail_in_expect > 0 || !isempty_RL(s) || - s->state_out_pos < s->numZ) return BZ_FLUSH_OK; - s->mode = BZ_M_RUNNING; - return BZ_RUN_OK; - - case BZ_M_FINISHING: - if (action != BZ_FINISH) return BZ_SEQUENCE_ERROR; - if (s->avail_in_expect != s->strm->avail_in) - return BZ_SEQUENCE_ERROR; - progress = handle_compress ( strm ); - if (!progress) return BZ_SEQUENCE_ERROR; - if (s->avail_in_expect > 0 || !isempty_RL(s) || - s->state_out_pos < s->numZ) return BZ_FINISH_OK; - s->mode = BZ_M_IDLE; - return BZ_STREAM_END; - } - return BZ_OK; /*--not reached--*/ -} - - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzCompressEnd) ( bz_stream *strm ) -{ - EState* s; - if (strm == NULL) return BZ_PARAM_ERROR; - s = strm->state; - if (s == NULL) return BZ_PARAM_ERROR; - if (s->strm != strm) return BZ_PARAM_ERROR; - - if (s->arr1 != NULL) BZFREE(s->arr1); - if (s->arr2 != NULL) BZFREE(s->arr2); - if (s->ftab != NULL) BZFREE(s->ftab); - BZFREE(strm->state); - - strm->state = NULL; - - return BZ_OK; -} - - -/*---------------------------------------------------*/ -/*--- Decompression stuff ---*/ -/*---------------------------------------------------*/ - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzDecompressInit) - ( bz_stream* strm, - int verbosity, - int small ) -{ - DState* s; - - if (!bz_config_ok()) return BZ_CONFIG_ERROR; - - if (strm == NULL) return BZ_PARAM_ERROR; - if (small != 0 && small != 1) return BZ_PARAM_ERROR; - if (verbosity < 0 || verbosity > 4) return BZ_PARAM_ERROR; - - if (strm->bzalloc == NULL) strm->bzalloc = default_bzalloc; - if (strm->bzfree == NULL) strm->bzfree = default_bzfree; - - s = BZALLOC( sizeof(DState) ); - if (s == NULL) return BZ_MEM_ERROR; - s->strm = strm; - strm->state = s; - s->state = BZ_X_MAGIC_1; - s->bsLive = 0; - s->bsBuff = 0; - s->calculatedCombinedCRC = 0; - strm->total_in_lo32 = 0; - strm->total_in_hi32 = 0; - strm->total_out_lo32 = 0; - strm->total_out_hi32 = 0; - s->smallDecompress = (Bool)small; - s->ll4 = NULL; - s->ll16 = NULL; - s->tt = NULL; - s->currBlockNo = 0; - s->verbosity = verbosity; - - return BZ_OK; -} - - -/*---------------------------------------------------*/ -/* Return True iff data corruption is discovered. - Returns False if there is no problem. -*/ -static -Bool unRLE_obuf_to_output_FAST ( DState* s ) -{ - UChar k1; - - if (s->blockRandomised) { - - while (True) { - /* try to finish existing run */ - while (True) { - if (s->strm->avail_out == 0) return False; - if (s->state_out_len == 0) break; - *( (UChar*)(s->strm->next_out) ) = s->state_out_ch; - BZ_UPDATE_CRC ( s->calculatedBlockCRC, s->state_out_ch ); - s->state_out_len--; - s->strm->next_out++; - s->strm->avail_out--; - s->strm->total_out_lo32++; - if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; - } - - /* can a new run be started? */ - if (s->nblock_used == s->save_nblock+1) return False; - - /* Only caused by corrupt data stream? */ - if (s->nblock_used > s->save_nblock+1) - return True; - - s->state_out_len = 1; - s->state_out_ch = s->k0; - BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; - k1 ^= BZ_RAND_MASK; s->nblock_used++; - if (s->nblock_used == s->save_nblock+1) continue; - if (k1 != s->k0) { s->k0 = k1; continue; }; - - s->state_out_len = 2; - BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; - k1 ^= BZ_RAND_MASK; s->nblock_used++; - if (s->nblock_used == s->save_nblock+1) continue; - if (k1 != s->k0) { s->k0 = k1; continue; }; - - s->state_out_len = 3; - BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; - k1 ^= BZ_RAND_MASK; s->nblock_used++; - if (s->nblock_used == s->save_nblock+1) continue; - if (k1 != s->k0) { s->k0 = k1; continue; }; - - BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; - k1 ^= BZ_RAND_MASK; s->nblock_used++; - s->state_out_len = ((Int32)k1) + 4; - BZ_GET_FAST(s->k0); BZ_RAND_UPD_MASK; - s->k0 ^= BZ_RAND_MASK; s->nblock_used++; - } - - } else { - - /* restore */ - UInt32 c_calculatedBlockCRC = s->calculatedBlockCRC; - UChar c_state_out_ch = s->state_out_ch; - Int32 c_state_out_len = s->state_out_len; - Int32 c_nblock_used = s->nblock_used; - Int32 c_k0 = s->k0; - UInt32* c_tt = s->tt; - UInt32 c_tPos = s->tPos; - char* cs_next_out = s->strm->next_out; - unsigned int cs_avail_out = s->strm->avail_out; - Int32 ro_blockSize100k = s->blockSize100k; - /* end restore */ - - UInt32 avail_out_INIT = cs_avail_out; - Int32 s_save_nblockPP = s->save_nblock+1; - unsigned int total_out_lo32_old; - - while (True) { - - /* try to finish existing run */ - if (c_state_out_len > 0) { - while (True) { - if (cs_avail_out == 0) goto return_notr; - if (c_state_out_len == 1) break; - *( (UChar*)(cs_next_out) ) = c_state_out_ch; - BZ_UPDATE_CRC ( c_calculatedBlockCRC, c_state_out_ch ); - c_state_out_len--; - cs_next_out++; - cs_avail_out--; - } - s_state_out_len_eq_one: - { - if (cs_avail_out == 0) { - c_state_out_len = 1; goto return_notr; - }; - *( (UChar*)(cs_next_out) ) = c_state_out_ch; - BZ_UPDATE_CRC ( c_calculatedBlockCRC, c_state_out_ch ); - cs_next_out++; - cs_avail_out--; - } - } - /* Only caused by corrupt data stream? */ - if (c_nblock_used > s_save_nblockPP) - return True; - - /* can a new run be started? */ - if (c_nblock_used == s_save_nblockPP) { - c_state_out_len = 0; goto return_notr; - }; - c_state_out_ch = c_k0; - BZ_GET_FAST_C(k1); c_nblock_used++; - if (k1 != c_k0) { - c_k0 = k1; goto s_state_out_len_eq_one; - }; - if (c_nblock_used == s_save_nblockPP) - goto s_state_out_len_eq_one; - - c_state_out_len = 2; - BZ_GET_FAST_C(k1); c_nblock_used++; - if (c_nblock_used == s_save_nblockPP) continue; - if (k1 != c_k0) { c_k0 = k1; continue; }; - - c_state_out_len = 3; - BZ_GET_FAST_C(k1); c_nblock_used++; - if (c_nblock_used == s_save_nblockPP) continue; - if (k1 != c_k0) { c_k0 = k1; continue; }; - - BZ_GET_FAST_C(k1); c_nblock_used++; - c_state_out_len = ((Int32)k1) + 4; - BZ_GET_FAST_C(c_k0); c_nblock_used++; - } - - return_notr: - total_out_lo32_old = s->strm->total_out_lo32; - s->strm->total_out_lo32 += (avail_out_INIT - cs_avail_out); - if (s->strm->total_out_lo32 < total_out_lo32_old) - s->strm->total_out_hi32++; - - /* save */ - s->calculatedBlockCRC = c_calculatedBlockCRC; - s->state_out_ch = c_state_out_ch; - s->state_out_len = c_state_out_len; - s->nblock_used = c_nblock_used; - s->k0 = c_k0; - s->tt = c_tt; - s->tPos = c_tPos; - s->strm->next_out = cs_next_out; - s->strm->avail_out = cs_avail_out; - /* end save */ - } - return False; -} - - - -/*---------------------------------------------------*/ -__inline__ Int32 BZ2_indexIntoF ( Int32 indx, Int32 *cftab ) -{ - Int32 nb, na, mid; - nb = 0; - na = 256; - do { - mid = (nb + na) >> 1; - if (indx >= cftab[mid]) nb = mid; else na = mid; - } - while (na - nb != 1); - return nb; -} - - -/*---------------------------------------------------*/ -/* Return True iff data corruption is discovered. - Returns False if there is no problem. -*/ -static -Bool unRLE_obuf_to_output_SMALL ( DState* s ) -{ - UChar k1; - - if (s->blockRandomised) { - - while (True) { - /* try to finish existing run */ - while (True) { - if (s->strm->avail_out == 0) return False; - if (s->state_out_len == 0) break; - *( (UChar*)(s->strm->next_out) ) = s->state_out_ch; - BZ_UPDATE_CRC ( s->calculatedBlockCRC, s->state_out_ch ); - s->state_out_len--; - s->strm->next_out++; - s->strm->avail_out--; - s->strm->total_out_lo32++; - if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; - } - - /* can a new run be started? */ - if (s->nblock_used == s->save_nblock+1) return False; - - /* Only caused by corrupt data stream? */ - if (s->nblock_used > s->save_nblock+1) - return True; - - s->state_out_len = 1; - s->state_out_ch = s->k0; - BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; - k1 ^= BZ_RAND_MASK; s->nblock_used++; - if (s->nblock_used == s->save_nblock+1) continue; - if (k1 != s->k0) { s->k0 = k1; continue; }; - - s->state_out_len = 2; - BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; - k1 ^= BZ_RAND_MASK; s->nblock_used++; - if (s->nblock_used == s->save_nblock+1) continue; - if (k1 != s->k0) { s->k0 = k1; continue; }; - - s->state_out_len = 3; - BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; - k1 ^= BZ_RAND_MASK; s->nblock_used++; - if (s->nblock_used == s->save_nblock+1) continue; - if (k1 != s->k0) { s->k0 = k1; continue; }; - - BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; - k1 ^= BZ_RAND_MASK; s->nblock_used++; - s->state_out_len = ((Int32)k1) + 4; - BZ_GET_SMALL(s->k0); BZ_RAND_UPD_MASK; - s->k0 ^= BZ_RAND_MASK; s->nblock_used++; - } - - } else { - - while (True) { - /* try to finish existing run */ - while (True) { - if (s->strm->avail_out == 0) return False; - if (s->state_out_len == 0) break; - *( (UChar*)(s->strm->next_out) ) = s->state_out_ch; - BZ_UPDATE_CRC ( s->calculatedBlockCRC, s->state_out_ch ); - s->state_out_len--; - s->strm->next_out++; - s->strm->avail_out--; - s->strm->total_out_lo32++; - if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; - } - - /* can a new run be started? */ - if (s->nblock_used == s->save_nblock+1) return False; - - /* Only caused by corrupt data stream? */ - if (s->nblock_used > s->save_nblock+1) - return True; - - s->state_out_len = 1; - s->state_out_ch = s->k0; - BZ_GET_SMALL(k1); s->nblock_used++; - if (s->nblock_used == s->save_nblock+1) continue; - if (k1 != s->k0) { s->k0 = k1; continue; }; - - s->state_out_len = 2; - BZ_GET_SMALL(k1); s->nblock_used++; - if (s->nblock_used == s->save_nblock+1) continue; - if (k1 != s->k0) { s->k0 = k1; continue; }; - - s->state_out_len = 3; - BZ_GET_SMALL(k1); s->nblock_used++; - if (s->nblock_used == s->save_nblock+1) continue; - if (k1 != s->k0) { s->k0 = k1; continue; }; - - BZ_GET_SMALL(k1); s->nblock_used++; - s->state_out_len = ((Int32)k1) + 4; - BZ_GET_SMALL(s->k0); s->nblock_used++; - } - - } -} - - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzDecompress) ( bz_stream *strm ) -{ - Bool corrupt; - DState* s; - if (strm == NULL) return BZ_PARAM_ERROR; - s = strm->state; - if (s == NULL) return BZ_PARAM_ERROR; - if (s->strm != strm) return BZ_PARAM_ERROR; - - while (True) { - if (s->state == BZ_X_IDLE) return BZ_SEQUENCE_ERROR; - if (s->state == BZ_X_OUTPUT) { - if (s->smallDecompress) - corrupt = unRLE_obuf_to_output_SMALL ( s ); else - corrupt = unRLE_obuf_to_output_FAST ( s ); - if (corrupt) return BZ_DATA_ERROR; - if (s->nblock_used == s->save_nblock+1 && s->state_out_len == 0) { - BZ_FINALISE_CRC ( s->calculatedBlockCRC ); - if (s->verbosity >= 3) - VPrintf2 ( " {0x%08x, 0x%08x}", s->storedBlockCRC, - s->calculatedBlockCRC ); - if (s->verbosity >= 2) VPrintf0 ( "]" ); - if (s->calculatedBlockCRC != s->storedBlockCRC) - return BZ_DATA_ERROR; - s->calculatedCombinedCRC - = (s->calculatedCombinedCRC << 1) | - (s->calculatedCombinedCRC >> 31); - s->calculatedCombinedCRC ^= s->calculatedBlockCRC; - s->state = BZ_X_BLKHDR_1; - } else { - return BZ_OK; - } - } - if (s->state >= BZ_X_MAGIC_1) { - Int32 r = BZ2_decompress ( s ); - if (r == BZ_STREAM_END) { - if (s->verbosity >= 3) - VPrintf2 ( "\n combined CRCs: stored = 0x%08x, computed = 0x%08x", - s->storedCombinedCRC, s->calculatedCombinedCRC ); - if (s->calculatedCombinedCRC != s->storedCombinedCRC) - return BZ_DATA_ERROR; - return r; - } - if (s->state != BZ_X_OUTPUT) return r; - } - } - - AssertH ( 0, 6001 ); - - return 0; /*NOTREACHED*/ -} - - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzDecompressEnd) ( bz_stream *strm ) -{ - DState* s; - if (strm == NULL) return BZ_PARAM_ERROR; - s = strm->state; - if (s == NULL) return BZ_PARAM_ERROR; - if (s->strm != strm) return BZ_PARAM_ERROR; - - if (s->tt != NULL) BZFREE(s->tt); - if (s->ll16 != NULL) BZFREE(s->ll16); - if (s->ll4 != NULL) BZFREE(s->ll4); - - BZFREE(strm->state); - strm->state = NULL; - - return BZ_OK; -} - - -#ifndef BZ_NO_STDIO -/*---------------------------------------------------*/ -/*--- File I/O stuff ---*/ -/*---------------------------------------------------*/ - -#define BZ_SETERR(eee) \ -{ \ - if (bzerror != NULL) *bzerror = eee; \ - if (bzf != NULL) bzf->lastErr = eee; \ -} - -typedef - struct { - FILE* handle; - Char buf[BZ_MAX_UNUSED]; - Int32 bufN; - Bool writing; - bz_stream strm; - Int32 lastErr; - Bool initialisedOk; - } - bzFile; - - -/*---------------------------------------------*/ -static Bool myfeof ( FILE* f ) -{ - Int32 c = fgetc ( f ); - if (c == EOF) return True; - ungetc ( c, f ); - return False; -} - - -/*---------------------------------------------------*/ -BZFILE* BZ_API(BZ2_bzWriteOpen) - ( int* bzerror, - FILE* f, - int blockSize100k, - int verbosity, - int workFactor ) -{ - Int32 ret; - bzFile* bzf = NULL; - - BZ_SETERR(BZ_OK); - - if (f == NULL || - (blockSize100k < 1 || blockSize100k > 9) || - (workFactor < 0 || workFactor > 250) || - (verbosity < 0 || verbosity > 4)) - { BZ_SETERR(BZ_PARAM_ERROR); return NULL; }; - - if (ferror(f)) - { BZ_SETERR(BZ_IO_ERROR); return NULL; }; - - bzf = malloc ( sizeof(bzFile) ); - if (bzf == NULL) - { BZ_SETERR(BZ_MEM_ERROR); return NULL; }; - - BZ_SETERR(BZ_OK); - bzf->initialisedOk = False; - bzf->bufN = 0; - bzf->handle = f; - bzf->writing = True; - bzf->strm.bzalloc = NULL; - bzf->strm.bzfree = NULL; - bzf->strm.opaque = NULL; - - if (workFactor == 0) workFactor = 30; - ret = BZ2_bzCompressInit ( &(bzf->strm), blockSize100k, - verbosity, workFactor ); - if (ret != BZ_OK) - { BZ_SETERR(ret); free(bzf); return NULL; }; - - bzf->strm.avail_in = 0; - bzf->initialisedOk = True; - return bzf; -} - - - -/*---------------------------------------------------*/ -void BZ_API(BZ2_bzWrite) - ( int* bzerror, - BZFILE* b, - void* buf, - int len ) -{ - Int32 n, n2, ret; - bzFile* bzf = (bzFile*)b; - - BZ_SETERR(BZ_OK); - if (bzf == NULL || buf == NULL || len < 0) - { BZ_SETERR(BZ_PARAM_ERROR); return; }; - if (!(bzf->writing)) - { BZ_SETERR(BZ_SEQUENCE_ERROR); return; }; - if (ferror(bzf->handle)) - { BZ_SETERR(BZ_IO_ERROR); return; }; - - if (len == 0) - { BZ_SETERR(BZ_OK); return; }; - - bzf->strm.avail_in = len; - bzf->strm.next_in = buf; - - while (True) { - bzf->strm.avail_out = BZ_MAX_UNUSED; - bzf->strm.next_out = bzf->buf; - ret = BZ2_bzCompress ( &(bzf->strm), BZ_RUN ); - if (ret != BZ_RUN_OK) - { BZ_SETERR(ret); return; }; - - if (bzf->strm.avail_out < BZ_MAX_UNUSED) { - n = BZ_MAX_UNUSED - bzf->strm.avail_out; - n2 = fwrite ( (void*)(bzf->buf), sizeof(UChar), - n, bzf->handle ); - if (n != n2 || ferror(bzf->handle)) - { BZ_SETERR(BZ_IO_ERROR); return; }; - } - - if (bzf->strm.avail_in == 0) - { BZ_SETERR(BZ_OK); return; }; - } -} - - -/*---------------------------------------------------*/ -void BZ_API(BZ2_bzWriteClose) - ( int* bzerror, - BZFILE* b, - int abandon, - unsigned int* nbytes_in, - unsigned int* nbytes_out ) -{ - BZ2_bzWriteClose64 ( bzerror, b, abandon, - nbytes_in, NULL, nbytes_out, NULL ); -} - - -void BZ_API(BZ2_bzWriteClose64) - ( int* bzerror, - BZFILE* b, - int abandon, - unsigned int* nbytes_in_lo32, - unsigned int* nbytes_in_hi32, - unsigned int* nbytes_out_lo32, - unsigned int* nbytes_out_hi32 ) -{ - Int32 n, n2, ret; - bzFile* bzf = (bzFile*)b; - - if (bzf == NULL) - { BZ_SETERR(BZ_OK); return; }; - if (!(bzf->writing)) - { BZ_SETERR(BZ_SEQUENCE_ERROR); return; }; - if (ferror(bzf->handle)) - { BZ_SETERR(BZ_IO_ERROR); return; }; - - if (nbytes_in_lo32 != NULL) *nbytes_in_lo32 = 0; - if (nbytes_in_hi32 != NULL) *nbytes_in_hi32 = 0; - if (nbytes_out_lo32 != NULL) *nbytes_out_lo32 = 0; - if (nbytes_out_hi32 != NULL) *nbytes_out_hi32 = 0; - - if ((!abandon) && bzf->lastErr == BZ_OK) { - while (True) { - bzf->strm.avail_out = BZ_MAX_UNUSED; - bzf->strm.next_out = bzf->buf; - ret = BZ2_bzCompress ( &(bzf->strm), BZ_FINISH ); - if (ret != BZ_FINISH_OK && ret != BZ_STREAM_END) - { BZ_SETERR(ret); return; }; - - if (bzf->strm.avail_out < BZ_MAX_UNUSED) { - n = BZ_MAX_UNUSED - bzf->strm.avail_out; - n2 = fwrite ( (void*)(bzf->buf), sizeof(UChar), - n, bzf->handle ); - if (n != n2 || ferror(bzf->handle)) - { BZ_SETERR(BZ_IO_ERROR); return; }; - } - - if (ret == BZ_STREAM_END) break; - } - } - - if ( !abandon && !ferror ( bzf->handle ) ) { - fflush ( bzf->handle ); - if (ferror(bzf->handle)) - { BZ_SETERR(BZ_IO_ERROR); return; }; - } - - if (nbytes_in_lo32 != NULL) - *nbytes_in_lo32 = bzf->strm.total_in_lo32; - if (nbytes_in_hi32 != NULL) - *nbytes_in_hi32 = bzf->strm.total_in_hi32; - if (nbytes_out_lo32 != NULL) - *nbytes_out_lo32 = bzf->strm.total_out_lo32; - if (nbytes_out_hi32 != NULL) - *nbytes_out_hi32 = bzf->strm.total_out_hi32; - - BZ_SETERR(BZ_OK); - BZ2_bzCompressEnd ( &(bzf->strm) ); - free ( bzf ); -} - - -/*---------------------------------------------------*/ -BZFILE* BZ_API(BZ2_bzReadOpen) - ( int* bzerror, - FILE* f, - int verbosity, - int small, - void* unused, - int nUnused ) -{ - bzFile* bzf = NULL; - int ret; - - BZ_SETERR(BZ_OK); - - if (f == NULL || - (small != 0 && small != 1) || - (verbosity < 0 || verbosity > 4) || - (unused == NULL && nUnused != 0) || - (unused != NULL && (nUnused < 0 || nUnused > BZ_MAX_UNUSED))) - { BZ_SETERR(BZ_PARAM_ERROR); return NULL; }; - - if (ferror(f)) - { BZ_SETERR(BZ_IO_ERROR); return NULL; }; - - bzf = malloc ( sizeof(bzFile) ); - if (bzf == NULL) - { BZ_SETERR(BZ_MEM_ERROR); return NULL; }; - - BZ_SETERR(BZ_OK); - - bzf->initialisedOk = False; - bzf->handle = f; - bzf->bufN = 0; - bzf->writing = False; - bzf->strm.bzalloc = NULL; - bzf->strm.bzfree = NULL; - bzf->strm.opaque = NULL; - - while (nUnused > 0) { - bzf->buf[bzf->bufN] = *((UChar*)(unused)); bzf->bufN++; - unused = ((void*)( 1 + ((UChar*)(unused)) )); - nUnused--; - } - - ret = BZ2_bzDecompressInit ( &(bzf->strm), verbosity, small ); - if (ret != BZ_OK) - { BZ_SETERR(ret); free(bzf); return NULL; }; - - bzf->strm.avail_in = bzf->bufN; - bzf->strm.next_in = bzf->buf; - - bzf->initialisedOk = True; - return bzf; -} - - -/*---------------------------------------------------*/ -void BZ_API(BZ2_bzReadClose) ( int *bzerror, BZFILE *b ) -{ - bzFile* bzf = (bzFile*)b; - - BZ_SETERR(BZ_OK); - if (bzf == NULL) - { BZ_SETERR(BZ_OK); return; }; - - if (bzf->writing) - { BZ_SETERR(BZ_SEQUENCE_ERROR); return; }; - - if (bzf->initialisedOk) - (void)BZ2_bzDecompressEnd ( &(bzf->strm) ); - free ( bzf ); -} - - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzRead) - ( int* bzerror, - BZFILE* b, - void* buf, - int len ) -{ - Int32 n, ret; - bzFile* bzf = (bzFile*)b; - - BZ_SETERR(BZ_OK); - - if (bzf == NULL || buf == NULL || len < 0) - { BZ_SETERR(BZ_PARAM_ERROR); return 0; }; - - if (bzf->writing) - { BZ_SETERR(BZ_SEQUENCE_ERROR); return 0; }; - - if (len == 0) - { BZ_SETERR(BZ_OK); return 0; }; - - bzf->strm.avail_out = len; - bzf->strm.next_out = buf; - - while (True) { - - if (ferror(bzf->handle)) - { BZ_SETERR(BZ_IO_ERROR); return 0; }; - - if (bzf->strm.avail_in == 0 && !myfeof(bzf->handle)) { - n = fread ( bzf->buf, sizeof(UChar), - BZ_MAX_UNUSED, bzf->handle ); - if (ferror(bzf->handle)) - { BZ_SETERR(BZ_IO_ERROR); return 0; }; - bzf->bufN = n; - bzf->strm.avail_in = bzf->bufN; - bzf->strm.next_in = bzf->buf; - } - - ret = BZ2_bzDecompress ( &(bzf->strm) ); - - if (ret != BZ_OK && ret != BZ_STREAM_END) - { BZ_SETERR(ret); return 0; }; - - if (ret == BZ_OK && myfeof(bzf->handle) && - bzf->strm.avail_in == 0 && bzf->strm.avail_out > 0) - { BZ_SETERR(BZ_UNEXPECTED_EOF); return 0; }; - - if (ret == BZ_STREAM_END) - { BZ_SETERR(BZ_STREAM_END); - return len - bzf->strm.avail_out; }; - if (bzf->strm.avail_out == 0) - { BZ_SETERR(BZ_OK); return len; }; - - } - - return 0; /*not reached*/ -} - - -/*---------------------------------------------------*/ -void BZ_API(BZ2_bzReadGetUnused) - ( int* bzerror, - BZFILE* b, - void** unused, - int* nUnused ) -{ - bzFile* bzf = (bzFile*)b; - if (bzf == NULL) - { BZ_SETERR(BZ_PARAM_ERROR); return; }; - if (bzf->lastErr != BZ_STREAM_END) - { BZ_SETERR(BZ_SEQUENCE_ERROR); return; }; - if (unused == NULL || nUnused == NULL) - { BZ_SETERR(BZ_PARAM_ERROR); return; }; - - BZ_SETERR(BZ_OK); - *nUnused = bzf->strm.avail_in; - *unused = bzf->strm.next_in; -} -#endif - - -/*---------------------------------------------------*/ -/*--- Misc convenience stuff ---*/ -/*---------------------------------------------------*/ - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzBuffToBuffCompress) - ( char* dest, - unsigned int* destLen, - char* source, - unsigned int sourceLen, - int blockSize100k, - int verbosity, - int workFactor ) -{ - bz_stream strm; - int ret; - - if (dest == NULL || destLen == NULL || - source == NULL || - blockSize100k < 1 || blockSize100k > 9 || - verbosity < 0 || verbosity > 4 || - workFactor < 0 || workFactor > 250) - return BZ_PARAM_ERROR; - - if (workFactor == 0) workFactor = 30; - strm.bzalloc = NULL; - strm.bzfree = NULL; - strm.opaque = NULL; - ret = BZ2_bzCompressInit ( &strm, blockSize100k, - verbosity, workFactor ); - if (ret != BZ_OK) return ret; - - strm.next_in = source; - strm.next_out = dest; - strm.avail_in = sourceLen; - strm.avail_out = *destLen; - - ret = BZ2_bzCompress ( &strm, BZ_FINISH ); - if (ret == BZ_FINISH_OK) goto output_overflow; - if (ret != BZ_STREAM_END) goto errhandler; - - /* normal termination */ - *destLen -= strm.avail_out; - BZ2_bzCompressEnd ( &strm ); - return BZ_OK; - - output_overflow: - BZ2_bzCompressEnd ( &strm ); - return BZ_OUTBUFF_FULL; - - errhandler: - BZ2_bzCompressEnd ( &strm ); - return ret; -} - - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzBuffToBuffDecompress) - ( char* dest, - unsigned int* destLen, - char* source, - unsigned int sourceLen, - int small, - int verbosity ) -{ - bz_stream strm; - int ret; - - if (dest == NULL || destLen == NULL || - source == NULL || - (small != 0 && small != 1) || - verbosity < 0 || verbosity > 4) - return BZ_PARAM_ERROR; - - strm.bzalloc = NULL; - strm.bzfree = NULL; - strm.opaque = NULL; - ret = BZ2_bzDecompressInit ( &strm, verbosity, small ); - if (ret != BZ_OK) return ret; - - strm.next_in = source; - strm.next_out = dest; - strm.avail_in = sourceLen; - strm.avail_out = *destLen; - - ret = BZ2_bzDecompress ( &strm ); - if (ret == BZ_OK) goto output_overflow_or_eof; - if (ret != BZ_STREAM_END) goto errhandler; - - /* normal termination */ - *destLen -= strm.avail_out; - BZ2_bzDecompressEnd ( &strm ); - return BZ_OK; - - output_overflow_or_eof: - if (strm.avail_out > 0) { - BZ2_bzDecompressEnd ( &strm ); - return BZ_UNEXPECTED_EOF; - } else { - BZ2_bzDecompressEnd ( &strm ); - return BZ_OUTBUFF_FULL; - }; - - errhandler: - BZ2_bzDecompressEnd ( &strm ); - return ret; -} - - -/*---------------------------------------------------*/ -/*-- - Code contributed by Yoshioka Tsuneo (tsuneo@rr.iij4u.or.jp) - to support better zlib compatibility. - This code is not _officially_ part of libbzip2 (yet); - I haven't tested it, documented it, or considered the - threading-safeness of it. - If this code breaks, please contact both Yoshioka and me. ---*/ -/*---------------------------------------------------*/ - -/*---------------------------------------------------*/ -/*-- - return version like "0.9.5d, 4-Sept-1999". ---*/ -const char * BZ_API(BZ2_bzlibVersion)(void) -{ - return BZ_VERSION; -} - - -#ifndef BZ_NO_STDIO -/*---------------------------------------------------*/ - -#if defined(_WIN32) || defined(OS2) || defined(MSDOS) -# include -# include -# define SET_BINARY_MODE(file) _setmode(_fileno(file),O_BINARY) -#else -# define SET_BINARY_MODE(file) -#endif -static -BZFILE * bzopen_or_bzdopen - ( const char *path, /* no use when bzdopen */ - int fd, /* no use when bzdopen */ - const char *mode, - int open_mode) /* bzopen: 0, bzdopen:1 */ -{ - int bzerr; - char unused[BZ_MAX_UNUSED]; - int blockSize100k = 9; - int writing = 0; - char mode2[10] = ""; - FILE *fp = NULL; - BZFILE *bzfp = NULL; - int verbosity = 0; - int workFactor = 30; - int smallMode = 0; - int nUnused = 0; - - if (mode == NULL) return NULL; - while (*mode) { - switch (*mode) { - case 'r': - writing = 0; break; - case 'w': - writing = 1; break; - case 's': - smallMode = 1; break; - default: - if (isdigit((int)(*mode))) { - blockSize100k = *mode-BZ_HDR_0; - } - } - mode++; - } - strcat(mode2, writing ? "w" : "r" ); - strcat(mode2,"b"); /* binary mode */ - - if (open_mode==0) { - if (path==NULL || strcmp(path,"")==0) { - fp = (writing ? stdout : stdin); - SET_BINARY_MODE(fp); - } else { - fp = fopen(path,mode2); - } - } else { -#ifdef BZ_STRICT_ANSI - fp = NULL; -#else - fp = _fdopen(fd,mode2); -#endif - } - if (fp == NULL) return NULL; - - if (writing) { - /* Guard against total chaos and anarchy -- JRS */ - if (blockSize100k < 1) blockSize100k = 1; - if (blockSize100k > 9) blockSize100k = 9; - bzfp = BZ2_bzWriteOpen(&bzerr,fp,blockSize100k, - verbosity,workFactor); - } else { - bzfp = BZ2_bzReadOpen(&bzerr,fp,verbosity,smallMode, - unused,nUnused); - } - if (bzfp == NULL) { - if (fp != stdin && fp != stdout) fclose(fp); - return NULL; - } - return bzfp; -} - - -/*---------------------------------------------------*/ -/*-- - open file for read or write. - ex) bzopen("file","w9") - case path="" or NULL => use stdin or stdout. ---*/ -BZFILE * BZ_API(BZ2_bzopen) - ( const char *path, - const char *mode ) -{ - return bzopen_or_bzdopen(path,-1,mode,/*bzopen*/0); -} - - -/*---------------------------------------------------*/ -BZFILE * BZ_API(BZ2_bzdopen) - ( int fd, - const char *mode ) -{ - return bzopen_or_bzdopen(NULL,fd,mode,/*bzdopen*/1); -} - - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzread) (BZFILE* b, void* buf, int len ) -{ - int bzerr, nread; - if (((bzFile*)b)->lastErr == BZ_STREAM_END) return 0; - nread = BZ2_bzRead(&bzerr,b,buf,len); - if (bzerr == BZ_OK || bzerr == BZ_STREAM_END) { - return nread; - } else { - return -1; - } -} - - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzwrite) (BZFILE* b, void* buf, int len ) -{ - int bzerr; - - BZ2_bzWrite(&bzerr,b,buf,len); - if(bzerr == BZ_OK){ - return len; - }else{ - return -1; - } -} - - -/*---------------------------------------------------*/ -int BZ_API(BZ2_bzflush) (BZFILE *b) -{ - /* do nothing now... */ - return 0; -} - - -/*---------------------------------------------------*/ -void BZ_API(BZ2_bzclose) (BZFILE* b) -{ - int bzerr; - FILE *fp; - - if (b==NULL) {return;} - fp = ((bzFile *)b)->handle; - if(((bzFile*)b)->writing){ - BZ2_bzWriteClose(&bzerr,b,0,NULL,NULL); - if(bzerr != BZ_OK){ - BZ2_bzWriteClose(NULL,b,1,NULL,NULL); - } - }else{ - BZ2_bzReadClose(&bzerr,b); - } - if(fp!=stdin && fp!=stdout){ - fclose(fp); - } -} - - -/*---------------------------------------------------*/ -/*-- - return last error code ---*/ -static const char *bzerrorstrings[] = { - "OK" - ,"SEQUENCE_ERROR" - ,"PARAM_ERROR" - ,"MEM_ERROR" - ,"DATA_ERROR" - ,"DATA_ERROR_MAGIC" - ,"IO_ERROR" - ,"UNEXPECTED_EOF" - ,"OUTBUFF_FULL" - ,"CONFIG_ERROR" - ,"???" /* for future */ - ,"???" /* for future */ - ,"???" /* for future */ - ,"???" /* for future */ - ,"???" /* for future */ - ,"???" /* for future */ -}; - - -const char * BZ_API(BZ2_bzerror) (BZFILE *b, int *errnum) -{ - int err = ((bzFile *)b)->lastErr; - - if(err>0) err = 0; - *errnum = err; - return bzerrorstrings[err*-1]; -} -#endif - - -/*-------------------------------------------------------------*/ -/*--- end bzlib.c ---*/ -/*-------------------------------------------------------------*/ diff --git a/dep/StormLib/src/bzip2/bzlib.h b/dep/StormLib/src/bzip2/bzlib.h deleted file mode 100644 index c5b75d6d8ff..00000000000 --- a/dep/StormLib/src/bzip2/bzlib.h +++ /dev/null @@ -1,282 +0,0 @@ - -/*-------------------------------------------------------------*/ -/*--- Public header file for the library. ---*/ -/*--- bzlib.h ---*/ -/*-------------------------------------------------------------*/ - -/* ------------------------------------------------------------------ - This file is part of bzip2/libbzip2, a program and library for - lossless, block-sorting data compression. - - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward - - Please read the WARNING, DISCLAIMER and PATENTS sections in the - README file. - - This program is released under the terms of the license contained - in the file LICENSE. - ------------------------------------------------------------------ */ - - -#ifndef _BZLIB_H -#define _BZLIB_H - -#ifdef __cplusplus -extern "C" { -#endif - -#define BZ_RUN 0 -#define BZ_FLUSH 1 -#define BZ_FINISH 2 - -#define BZ_OK 0 -#define BZ_RUN_OK 1 -#define BZ_FLUSH_OK 2 -#define BZ_FINISH_OK 3 -#define BZ_STREAM_END 4 -#define BZ_SEQUENCE_ERROR (-1) -#define BZ_PARAM_ERROR (-2) -#define BZ_MEM_ERROR (-3) -#define BZ_DATA_ERROR (-4) -#define BZ_DATA_ERROR_MAGIC (-5) -#define BZ_IO_ERROR (-6) -#define BZ_UNEXPECTED_EOF (-7) -#define BZ_OUTBUFF_FULL (-8) -#define BZ_CONFIG_ERROR (-9) - -typedef - struct { - char *next_in; - unsigned int avail_in; - unsigned int total_in_lo32; - unsigned int total_in_hi32; - - char *next_out; - unsigned int avail_out; - unsigned int total_out_lo32; - unsigned int total_out_hi32; - - void *state; - - void *(*bzalloc)(void *,int,int); - void (*bzfree)(void *,void *); - void *opaque; - } - bz_stream; - - -#ifndef BZ_IMPORT -#define BZ_EXPORT -#endif - -#ifndef BZ_NO_STDIO -/* Need a definitition for FILE */ -#include -#endif - -#ifdef _WIN32 -# include -# ifdef small - /* windows.h define small to char */ -# undef small -# endif -# ifdef BZ_EXPORT -# define BZ_API(func) WINAPI func -# define BZ_EXTERN extern -# else - /* import windows dll dynamically */ -# define BZ_API(func) (WINAPI * func) -# define BZ_EXTERN -# endif -#else -# define BZ_API(func) func -# define BZ_EXTERN extern -#endif - - -/*-- Core (low-level) library functions --*/ - -BZ_EXTERN int BZ_API(BZ2_bzCompressInit) ( - bz_stream* strm, - int blockSize100k, - int verbosity, - int workFactor - ); - -BZ_EXTERN int BZ_API(BZ2_bzCompress) ( - bz_stream* strm, - int action - ); - -BZ_EXTERN int BZ_API(BZ2_bzCompressEnd) ( - bz_stream* strm - ); - -BZ_EXTERN int BZ_API(BZ2_bzDecompressInit) ( - bz_stream *strm, - int verbosity, - int small - ); - -BZ_EXTERN int BZ_API(BZ2_bzDecompress) ( - bz_stream* strm - ); - -BZ_EXTERN int BZ_API(BZ2_bzDecompressEnd) ( - bz_stream *strm - ); - - - -/*-- High(er) level library functions --*/ - -#ifndef BZ_NO_STDIO -#define BZ_MAX_UNUSED 5000 - -typedef void BZFILE; - -BZ_EXTERN BZFILE* BZ_API(BZ2_bzReadOpen) ( - int* bzerror, - FILE* f, - int verbosity, - int small, - void* unused, - int nUnused - ); - -BZ_EXTERN void BZ_API(BZ2_bzReadClose) ( - int* bzerror, - BZFILE* b - ); - -BZ_EXTERN void BZ_API(BZ2_bzReadGetUnused) ( - int* bzerror, - BZFILE* b, - void** unused, - int* nUnused - ); - -BZ_EXTERN int BZ_API(BZ2_bzRead) ( - int* bzerror, - BZFILE* b, - void* buf, - int len - ); - -BZ_EXTERN BZFILE* BZ_API(BZ2_bzWriteOpen) ( - int* bzerror, - FILE* f, - int blockSize100k, - int verbosity, - int workFactor - ); - -BZ_EXTERN void BZ_API(BZ2_bzWrite) ( - int* bzerror, - BZFILE* b, - void* buf, - int len - ); - -BZ_EXTERN void BZ_API(BZ2_bzWriteClose) ( - int* bzerror, - BZFILE* b, - int abandon, - unsigned int* nbytes_in, - unsigned int* nbytes_out - ); - -BZ_EXTERN void BZ_API(BZ2_bzWriteClose64) ( - int* bzerror, - BZFILE* b, - int abandon, - unsigned int* nbytes_in_lo32, - unsigned int* nbytes_in_hi32, - unsigned int* nbytes_out_lo32, - unsigned int* nbytes_out_hi32 - ); -#endif - - -/*-- Utility functions --*/ - -BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffCompress) ( - char* dest, - unsigned int* destLen, - char* source, - unsigned int sourceLen, - int blockSize100k, - int verbosity, - int workFactor - ); - -BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffDecompress) ( - char* dest, - unsigned int* destLen, - char* source, - unsigned int sourceLen, - int small, - int verbosity - ); - - -/*-- - Code contributed by Yoshioka Tsuneo (tsuneo@rr.iij4u.or.jp) - to support better zlib compatibility. - This code is not _officially_ part of libbzip2 (yet); - I haven't tested it, documented it, or considered the - threading-safeness of it. - If this code breaks, please contact both Yoshioka and me. ---*/ - -BZ_EXTERN const char * BZ_API(BZ2_bzlibVersion) ( - void - ); - -#ifndef BZ_NO_STDIO -BZ_EXTERN BZFILE * BZ_API(BZ2_bzopen) ( - const char *path, - const char *mode - ); - -BZ_EXTERN BZFILE * BZ_API(BZ2_bzdopen) ( - int fd, - const char *mode - ); - -BZ_EXTERN int BZ_API(BZ2_bzread) ( - BZFILE* b, - void* buf, - int len - ); - -BZ_EXTERN int BZ_API(BZ2_bzwrite) ( - BZFILE* b, - void* buf, - int len - ); - -BZ_EXTERN int BZ_API(BZ2_bzflush) ( - BZFILE* b - ); - -BZ_EXTERN void BZ_API(BZ2_bzclose) ( - BZFILE* b - ); - -BZ_EXTERN const char * BZ_API(BZ2_bzerror) ( - BZFILE *b, - int *errnum - ); -#endif - -#ifdef __cplusplus -} -#endif - -#endif - -/*-------------------------------------------------------------*/ -/*--- end bzlib.h ---*/ -/*-------------------------------------------------------------*/ diff --git a/dep/StormLib/src/bzip2/bzlib_private.h b/dep/StormLib/src/bzip2/bzlib_private.h deleted file mode 100644 index 23427879b18..00000000000 --- a/dep/StormLib/src/bzip2/bzlib_private.h +++ /dev/null @@ -1,509 +0,0 @@ - -/*-------------------------------------------------------------*/ -/*--- Private header file for the library. ---*/ -/*--- bzlib_private.h ---*/ -/*-------------------------------------------------------------*/ - -/* ------------------------------------------------------------------ - This file is part of bzip2/libbzip2, a program and library for - lossless, block-sorting data compression. - - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward - - Please read the WARNING, DISCLAIMER and PATENTS sections in the - README file. - - This program is released under the terms of the license contained - in the file LICENSE. - ------------------------------------------------------------------ */ - - -#ifndef _BZLIB_PRIVATE_H -#define _BZLIB_PRIVATE_H - -#include - -#ifndef BZ_NO_STDIO -#include -#include -#include -#endif - -#include "bzlib.h" - - - -/*-- General stuff. --*/ - -#define BZ_VERSION "1.0.5, 10-Dec-2007" - -typedef char Char; -typedef unsigned char Bool; -typedef unsigned char UChar; -typedef int Int32; -typedef unsigned int UInt32; -typedef short Int16; -typedef unsigned short UInt16; - -#define True ((Bool)1) -#define False ((Bool)0) - -#ifndef __GNUC__ -#define __inline__ /* */ -#endif - -#ifndef BZ_NO_STDIO - -extern void BZ2_bz__AssertH__fail ( int errcode ); -#define AssertH(cond,errcode) \ - { if (!(cond)) BZ2_bz__AssertH__fail ( errcode ); } - -#if BZ_DEBUG -#define AssertD(cond,msg) \ - { if (!(cond)) { \ - fprintf ( stderr, \ - "\n\nlibbzip2(debug build): internal error\n\t%s\n", msg );\ - exit(1); \ - }} -#else -#define AssertD(cond,msg) /* */ -#endif - -#define VPrintf0(zf) \ - fprintf(stderr,zf) -#define VPrintf1(zf,za1) \ - fprintf(stderr,zf,za1) -#define VPrintf2(zf,za1,za2) \ - fprintf(stderr,zf,za1,za2) -#define VPrintf3(zf,za1,za2,za3) \ - fprintf(stderr,zf,za1,za2,za3) -#define VPrintf4(zf,za1,za2,za3,za4) \ - fprintf(stderr,zf,za1,za2,za3,za4) -#define VPrintf5(zf,za1,za2,za3,za4,za5) \ - fprintf(stderr,zf,za1,za2,za3,za4,za5) - -#else - -extern void bz_internal_error ( int errcode ); -#define AssertH(cond,errcode) \ - { if (!(cond)) bz_internal_error ( errcode ); } -#define AssertD(cond,msg) do { } while (0) -#define VPrintf0(zf) do { } while (0) -#define VPrintf1(zf,za1) do { } while (0) -#define VPrintf2(zf,za1,za2) do { } while (0) -#define VPrintf3(zf,za1,za2,za3) do { } while (0) -#define VPrintf4(zf,za1,za2,za3,za4) do { } while (0) -#define VPrintf5(zf,za1,za2,za3,za4,za5) do { } while (0) - -#endif - - -#define BZALLOC(nnn) (strm->bzalloc)(strm->opaque,(nnn),1) -#define BZFREE(ppp) (strm->bzfree)(strm->opaque,(ppp)) - - -/*-- Header bytes. --*/ - -#define BZ_HDR_B 0x42 /* 'B' */ -#define BZ_HDR_Z 0x5a /* 'Z' */ -#define BZ_HDR_h 0x68 /* 'h' */ -#define BZ_HDR_0 0x30 /* '0' */ - -/*-- Constants for the back end. --*/ - -#define BZ_MAX_ALPHA_SIZE 258 -#define BZ_MAX_CODE_LEN 23 - -#define BZ_RUNA 0 -#define BZ_RUNB 1 - -#define BZ_N_GROUPS 6 -#define BZ_G_SIZE 50 -#define BZ_N_ITERS 4 - -#define BZ_MAX_SELECTORS (2 + (900000 / BZ_G_SIZE)) - - - -/*-- Stuff for randomising repetitive blocks. --*/ - -extern Int32 BZ2_rNums[512]; - -#define BZ_RAND_DECLS \ - Int32 rNToGo; \ - Int32 rTPos \ - -#define BZ_RAND_INIT_MASK \ - s->rNToGo = 0; \ - s->rTPos = 0 \ - -#define BZ_RAND_MASK ((s->rNToGo == 1) ? 1 : 0) - -#define BZ_RAND_UPD_MASK \ - if (s->rNToGo == 0) { \ - s->rNToGo = BZ2_rNums[s->rTPos]; \ - s->rTPos++; \ - if (s->rTPos == 512) s->rTPos = 0; \ - } \ - s->rNToGo--; - - - -/*-- Stuff for doing CRCs. --*/ - -extern UInt32 BZ2_crc32Table[256]; - -#define BZ_INITIALISE_CRC(crcVar) \ -{ \ - crcVar = 0xffffffffL; \ -} - -#define BZ_FINALISE_CRC(crcVar) \ -{ \ - crcVar = ~(crcVar); \ -} - -#define BZ_UPDATE_CRC(crcVar,cha) \ -{ \ - crcVar = (crcVar << 8) ^ \ - BZ2_crc32Table[(crcVar >> 24) ^ \ - ((UChar)cha)]; \ -} - - - -/*-- States and modes for compression. --*/ - -#define BZ_M_IDLE 1 -#define BZ_M_RUNNING 2 -#define BZ_M_FLUSHING 3 -#define BZ_M_FINISHING 4 - -#define BZ_S_OUTPUT 1 -#define BZ_S_INPUT 2 - -#define BZ_N_RADIX 2 -#define BZ_N_QSORT 12 -#define BZ_N_SHELL 18 -#define BZ_N_OVERSHOOT (BZ_N_RADIX + BZ_N_QSORT + BZ_N_SHELL + 2) - - - - -/*-- Structure holding all the compression-side stuff. --*/ - -typedef - struct { - /* pointer back to the struct bz_stream */ - bz_stream* strm; - - /* mode this stream is in, and whether inputting */ - /* or outputting data */ - Int32 mode; - Int32 state; - - /* remembers avail_in when flush/finish requested */ - UInt32 avail_in_expect; - - /* for doing the block sorting */ - UInt32* arr1; - UInt32* arr2; - UInt32* ftab; - Int32 origPtr; - - /* aliases for arr1 and arr2 */ - UInt32* ptr; - UChar* block; - UInt16* mtfv; - UChar* zbits; - - /* for deciding when to use the fallback sorting algorithm */ - Int32 workFactor; - - /* run-length-encoding of the input */ - UInt32 state_in_ch; - Int32 state_in_len; - BZ_RAND_DECLS; - - /* input and output limits and current posns */ - Int32 nblock; - Int32 nblockMAX; - Int32 numZ; - Int32 state_out_pos; - - /* map of bytes used in block */ - Int32 nInUse; - Bool inUse[256]; - UChar unseqToSeq[256]; - - /* the buffer for bit stream creation */ - UInt32 bsBuff; - Int32 bsLive; - - /* block and combined CRCs */ - UInt32 blockCRC; - UInt32 combinedCRC; - - /* misc administratium */ - Int32 verbosity; - Int32 blockNo; - Int32 blockSize100k; - - /* stuff for coding the MTF values */ - Int32 nMTF; - Int32 mtfFreq [BZ_MAX_ALPHA_SIZE]; - UChar selector [BZ_MAX_SELECTORS]; - UChar selectorMtf[BZ_MAX_SELECTORS]; - - UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; - Int32 code [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; - Int32 rfreq [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; - /* second dimension: only 3 needed; 4 makes index calculations faster */ - UInt32 len_pack[BZ_MAX_ALPHA_SIZE][4]; - - } - EState; - - - -/*-- externs for compression. --*/ - -extern void -BZ2_blockSort ( EState* ); - -extern void -BZ2_compressBlock ( EState*, Bool ); - -extern void -BZ2_bsInitWrite ( EState* ); - -extern void -BZ2_hbAssignCodes ( Int32*, UChar*, Int32, Int32, Int32 ); - -extern void -BZ2_hbMakeCodeLengths ( UChar*, Int32*, Int32, Int32 ); - - - -/*-- states for decompression. --*/ - -#define BZ_X_IDLE 1 -#define BZ_X_OUTPUT 2 - -#define BZ_X_MAGIC_1 10 -#define BZ_X_MAGIC_2 11 -#define BZ_X_MAGIC_3 12 -#define BZ_X_MAGIC_4 13 -#define BZ_X_BLKHDR_1 14 -#define BZ_X_BLKHDR_2 15 -#define BZ_X_BLKHDR_3 16 -#define BZ_X_BLKHDR_4 17 -#define BZ_X_BLKHDR_5 18 -#define BZ_X_BLKHDR_6 19 -#define BZ_X_BCRC_1 20 -#define BZ_X_BCRC_2 21 -#define BZ_X_BCRC_3 22 -#define BZ_X_BCRC_4 23 -#define BZ_X_RANDBIT 24 -#define BZ_X_ORIGPTR_1 25 -#define BZ_X_ORIGPTR_2 26 -#define BZ_X_ORIGPTR_3 27 -#define BZ_X_MAPPING_1 28 -#define BZ_X_MAPPING_2 29 -#define BZ_X_SELECTOR_1 30 -#define BZ_X_SELECTOR_2 31 -#define BZ_X_SELECTOR_3 32 -#define BZ_X_CODING_1 33 -#define BZ_X_CODING_2 34 -#define BZ_X_CODING_3 35 -#define BZ_X_MTF_1 36 -#define BZ_X_MTF_2 37 -#define BZ_X_MTF_3 38 -#define BZ_X_MTF_4 39 -#define BZ_X_MTF_5 40 -#define BZ_X_MTF_6 41 -#define BZ_X_ENDHDR_2 42 -#define BZ_X_ENDHDR_3 43 -#define BZ_X_ENDHDR_4 44 -#define BZ_X_ENDHDR_5 45 -#define BZ_X_ENDHDR_6 46 -#define BZ_X_CCRC_1 47 -#define BZ_X_CCRC_2 48 -#define BZ_X_CCRC_3 49 -#define BZ_X_CCRC_4 50 - - - -/*-- Constants for the fast MTF decoder. --*/ - -#define MTFA_SIZE 4096 -#define MTFL_SIZE 16 - - - -/*-- Structure holding all the decompression-side stuff. --*/ - -typedef - struct { - /* pointer back to the struct bz_stream */ - bz_stream* strm; - - /* state indicator for this stream */ - Int32 state; - - /* for doing the final run-length decoding */ - UChar state_out_ch; - Int32 state_out_len; - Bool blockRandomised; - BZ_RAND_DECLS; - - /* the buffer for bit stream reading */ - UInt32 bsBuff; - Int32 bsLive; - - /* misc administratium */ - Int32 blockSize100k; - Bool smallDecompress; - Int32 currBlockNo; - Int32 verbosity; - - /* for undoing the Burrows-Wheeler transform */ - Int32 origPtr; - UInt32 tPos; - Int32 k0; - Int32 unzftab[256]; - Int32 nblock_used; - Int32 cftab[257]; - Int32 cftabCopy[257]; - - /* for undoing the Burrows-Wheeler transform (FAST) */ - UInt32 *tt; - - /* for undoing the Burrows-Wheeler transform (SMALL) */ - UInt16 *ll16; - UChar *ll4; - - /* stored and calculated CRCs */ - UInt32 storedBlockCRC; - UInt32 storedCombinedCRC; - UInt32 calculatedBlockCRC; - UInt32 calculatedCombinedCRC; - - /* map of bytes used in block */ - Int32 nInUse; - Bool inUse[256]; - Bool inUse16[16]; - UChar seqToUnseq[256]; - - /* for decoding the MTF values */ - UChar mtfa [MTFA_SIZE]; - Int32 mtfbase[256 / MTFL_SIZE]; - UChar selector [BZ_MAX_SELECTORS]; - UChar selectorMtf[BZ_MAX_SELECTORS]; - UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; - - Int32 limit [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; - Int32 base [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; - Int32 perm [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; - Int32 minLens[BZ_N_GROUPS]; - - /* save area for scalars in the main decompress code */ - Int32 save_i; - Int32 save_j; - Int32 save_t; - Int32 save_alphaSize; - Int32 save_nGroups; - Int32 save_nSelectors; - Int32 save_EOB; - Int32 save_groupNo; - Int32 save_groupPos; - Int32 save_nextSym; - Int32 save_nblockMAX; - Int32 save_nblock; - Int32 save_es; - Int32 save_N; - Int32 save_curr; - Int32 save_zt; - Int32 save_zn; - Int32 save_zvec; - Int32 save_zj; - Int32 save_gSel; - Int32 save_gMinlen; - Int32* save_gLimit; - Int32* save_gBase; - Int32* save_gPerm; - - } - DState; - - - -/*-- Macros for decompression. --*/ - -#define BZ_GET_FAST(cccc) \ - /* c_tPos is unsigned, hence test < 0 is pointless. */ \ - if (s->tPos >= (UInt32)100000 * (UInt32)s->blockSize100k) return True; \ - s->tPos = s->tt[s->tPos]; \ - cccc = (UChar)(s->tPos & 0xff); \ - s->tPos >>= 8; - -#define BZ_GET_FAST_C(cccc) \ - /* c_tPos is unsigned, hence test < 0 is pointless. */ \ - if (c_tPos >= (UInt32)100000 * (UInt32)ro_blockSize100k) return True; \ - c_tPos = c_tt[c_tPos]; \ - cccc = (UChar)(c_tPos & 0xff); \ - c_tPos >>= 8; - -#define SET_LL4(i,n) \ - { if (((i) & 0x1) == 0) \ - s->ll4[(i) >> 1] = (s->ll4[(i) >> 1] & 0xf0) | (n); else \ - s->ll4[(i) >> 1] = (s->ll4[(i) >> 1] & 0x0f) | ((n) << 4); \ - } - -#define GET_LL4(i) \ - ((((UInt32)(s->ll4[(i) >> 1])) >> (((i) << 2) & 0x4)) & 0xF) - -#define SET_LL(i,n) \ - { s->ll16[i] = (UInt16)(n & 0x0000ffff); \ - SET_LL4(i, n >> 16); \ - } - -#define GET_LL(i) \ - (((UInt32)s->ll16[i]) | (GET_LL4(i) << 16)) - -#define BZ_GET_SMALL(cccc) \ - /* c_tPos is unsigned, hence test < 0 is pointless. */ \ - if (s->tPos >= (UInt32)100000 * (UInt32)s->blockSize100k) return True; \ - cccc = BZ2_indexIntoF ( s->tPos, s->cftab ); \ - s->tPos = GET_LL(s->tPos); - - -/*-- externs for decompression. --*/ - -extern Int32 -BZ2_indexIntoF ( Int32, Int32* ); - -extern Int32 -BZ2_decompress ( DState* ); - -extern void -BZ2_hbCreateDecodeTables ( Int32*, Int32*, Int32*, UChar*, - Int32, Int32, Int32 ); - - -#endif - - -/*-- BZ_NO_STDIO seems to make NULL disappear on some platforms. --*/ - -#ifdef BZ_NO_STDIO -#ifndef NULL -#define NULL 0 -#endif -#endif - - -/*-------------------------------------------------------------*/ -/*--- end bzlib_private.h ---*/ -/*-------------------------------------------------------------*/ diff --git a/dep/StormLib/src/bzip2/compress.c b/dep/StormLib/src/bzip2/compress.c deleted file mode 100644 index 8c80a079700..00000000000 --- a/dep/StormLib/src/bzip2/compress.c +++ /dev/null @@ -1,672 +0,0 @@ - -/*-------------------------------------------------------------*/ -/*--- Compression machinery (not incl block sorting) ---*/ -/*--- compress.c ---*/ -/*-------------------------------------------------------------*/ - -/* ------------------------------------------------------------------ - This file is part of bzip2/libbzip2, a program and library for - lossless, block-sorting data compression. - - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward - - Please read the WARNING, DISCLAIMER and PATENTS sections in the - README file. - - This program is released under the terms of the license contained - in the file LICENSE. - ------------------------------------------------------------------ */ - - -/* CHANGES - 0.9.0 -- original version. - 0.9.0a/b -- no changes in this file. - 0.9.0c -- changed setting of nGroups in sendMTFValues() - so as to do a bit better on small files -*/ - -#include "bzlib_private.h" - - -/*---------------------------------------------------*/ -/*--- Bit stream I/O ---*/ -/*---------------------------------------------------*/ - -/*---------------------------------------------------*/ -void BZ2_bsInitWrite ( EState* s ) -{ - s->bsLive = 0; - s->bsBuff = 0; -} - - -/*---------------------------------------------------*/ -static -void bsFinishWrite ( EState* s ) -{ - while (s->bsLive > 0) { - s->zbits[s->numZ] = (UChar)(s->bsBuff >> 24); - s->numZ++; - s->bsBuff <<= 8; - s->bsLive -= 8; - } -} - - -/*---------------------------------------------------*/ -#define bsNEEDW(nz) \ -{ \ - while (s->bsLive >= 8) { \ - s->zbits[s->numZ] \ - = (UChar)(s->bsBuff >> 24); \ - s->numZ++; \ - s->bsBuff <<= 8; \ - s->bsLive -= 8; \ - } \ -} - - -/*---------------------------------------------------*/ -static -__inline__ -void bsW ( EState* s, Int32 n, UInt32 v ) -{ - bsNEEDW ( n ); - s->bsBuff |= (v << (32 - s->bsLive - n)); - s->bsLive += n; -} - - -/*---------------------------------------------------*/ -static -void bsPutUInt32 ( EState* s, UInt32 u ) -{ - bsW ( s, 8, (u >> 24) & 0xffL ); - bsW ( s, 8, (u >> 16) & 0xffL ); - bsW ( s, 8, (u >> 8) & 0xffL ); - bsW ( s, 8, u & 0xffL ); -} - - -/*---------------------------------------------------*/ -static -void bsPutUChar ( EState* s, UChar c ) -{ - bsW( s, 8, (UInt32)c ); -} - - -/*---------------------------------------------------*/ -/*--- The back end proper ---*/ -/*---------------------------------------------------*/ - -/*---------------------------------------------------*/ -static -void makeMaps_e ( EState* s ) -{ - Int32 i; - s->nInUse = 0; - for (i = 0; i < 256; i++) - if (s->inUse[i]) { - s->unseqToSeq[i] = s->nInUse; - s->nInUse++; - } -} - - -/*---------------------------------------------------*/ -static -void generateMTFValues ( EState* s ) -{ - UChar yy[256]; - Int32 i, j; - Int32 zPend; - Int32 wr; - Int32 EOB; - - /* - After sorting (eg, here), - s->arr1 [ 0 .. s->nblock-1 ] holds sorted order, - and - ((UChar*)s->arr2) [ 0 .. s->nblock-1 ] - holds the original block data. - - The first thing to do is generate the MTF values, - and put them in - ((UInt16*)s->arr1) [ 0 .. s->nblock-1 ]. - Because there are strictly fewer or equal MTF values - than block values, ptr values in this area are overwritten - with MTF values only when they are no longer needed. - - The final compressed bitstream is generated into the - area starting at - (UChar*) (&((UChar*)s->arr2)[s->nblock]) - - These storage aliases are set up in bzCompressInit(), - except for the last one, which is arranged in - compressBlock(). - */ - UInt32* ptr = s->ptr; - UChar* block = s->block; - UInt16* mtfv = s->mtfv; - - makeMaps_e ( s ); - EOB = s->nInUse+1; - - for (i = 0; i <= EOB; i++) s->mtfFreq[i] = 0; - - wr = 0; - zPend = 0; - for (i = 0; i < s->nInUse; i++) yy[i] = (UChar) i; - - for (i = 0; i < s->nblock; i++) { - UChar ll_i; - AssertD ( wr <= i, "generateMTFValues(1)" ); - j = ptr[i]-1; if (j < 0) j += s->nblock; - ll_i = s->unseqToSeq[block[j]]; - AssertD ( ll_i < s->nInUse, "generateMTFValues(2a)" ); - - if (yy[0] == ll_i) { - zPend++; - } else { - - if (zPend > 0) { - zPend--; - while (True) { - if (zPend & 1) { - mtfv[wr] = BZ_RUNB; wr++; - s->mtfFreq[BZ_RUNB]++; - } else { - mtfv[wr] = BZ_RUNA; wr++; - s->mtfFreq[BZ_RUNA]++; - } - if (zPend < 2) break; - zPend = (zPend - 2) / 2; - }; - zPend = 0; - } - { - register UChar rtmp; - register UChar* ryy_j; - register UChar rll_i; - rtmp = yy[1]; - yy[1] = yy[0]; - ryy_j = &(yy[1]); - rll_i = ll_i; - while ( rll_i != rtmp ) { - register UChar rtmp2; - ryy_j++; - rtmp2 = rtmp; - rtmp = *ryy_j; - *ryy_j = rtmp2; - }; - yy[0] = rtmp; - j = ryy_j - &(yy[0]); - mtfv[wr] = j+1; wr++; s->mtfFreq[j+1]++; - } - - } - } - - if (zPend > 0) { - zPend--; - while (True) { - if (zPend & 1) { - mtfv[wr] = BZ_RUNB; wr++; - s->mtfFreq[BZ_RUNB]++; - } else { - mtfv[wr] = BZ_RUNA; wr++; - s->mtfFreq[BZ_RUNA]++; - } - if (zPend < 2) break; - zPend = (zPend - 2) / 2; - }; - zPend = 0; - } - - mtfv[wr] = EOB; wr++; s->mtfFreq[EOB]++; - - s->nMTF = wr; -} - - -/*---------------------------------------------------*/ -#define BZ_LESSER_ICOST 0 -#define BZ_GREATER_ICOST 15 - -static -void sendMTFValues ( EState* s ) -{ - Int32 v, t, i, j, gs, ge, totc, bt, bc, iter; - Int32 nSelectors, alphaSize, minLen, maxLen, selCtr; - Int32 nGroups, nBytes; - - /*-- - UChar len [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; - is a global since the decoder also needs it. - - Int32 code[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; - Int32 rfreq[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE]; - are also globals only used in this proc. - Made global to keep stack frame size small. - --*/ - - - UInt16 cost[BZ_N_GROUPS]; - Int32 fave[BZ_N_GROUPS]; - - UInt16* mtfv = s->mtfv; - - if (s->verbosity >= 3) - VPrintf3( " %d in block, %d after MTF & 1-2 coding, " - "%d+2 syms in use\n", - s->nblock, s->nMTF, s->nInUse ); - - alphaSize = s->nInUse+2; - for (t = 0; t < BZ_N_GROUPS; t++) - for (v = 0; v < alphaSize; v++) - s->len[t][v] = BZ_GREATER_ICOST; - - /*--- Decide how many coding tables to use ---*/ - AssertH ( s->nMTF > 0, 3001 ); - if (s->nMTF < 200) nGroups = 2; else - if (s->nMTF < 600) nGroups = 3; else - if (s->nMTF < 1200) nGroups = 4; else - if (s->nMTF < 2400) nGroups = 5; else - nGroups = 6; - - /*--- Generate an initial set of coding tables ---*/ - { - Int32 nPart, remF, tFreq, aFreq; - - nPart = nGroups; - remF = s->nMTF; - gs = 0; - while (nPart > 0) { - tFreq = remF / nPart; - ge = gs-1; - aFreq = 0; - while (aFreq < tFreq && ge < alphaSize-1) { - ge++; - aFreq += s->mtfFreq[ge]; - } - - if (ge > gs - && nPart != nGroups && nPart != 1 - && ((nGroups-nPart) % 2 == 1)) { - aFreq -= s->mtfFreq[ge]; - ge--; - } - - if (s->verbosity >= 3) - VPrintf5( " initial group %d, [%d .. %d], " - "has %d syms (%4.1f%%)\n", - nPart, gs, ge, aFreq, - (100.0 * (float)aFreq) / (float)(s->nMTF) ); - - for (v = 0; v < alphaSize; v++) - if (v >= gs && v <= ge) - s->len[nPart-1][v] = BZ_LESSER_ICOST; else - s->len[nPart-1][v] = BZ_GREATER_ICOST; - - nPart--; - gs = ge+1; - remF -= aFreq; - } - } - - /*--- - Iterate up to BZ_N_ITERS times to improve the tables. - ---*/ - for (iter = 0; iter < BZ_N_ITERS; iter++) { - - for (t = 0; t < nGroups; t++) fave[t] = 0; - - for (t = 0; t < nGroups; t++) - for (v = 0; v < alphaSize; v++) - s->rfreq[t][v] = 0; - - /*--- - Set up an auxiliary length table which is used to fast-track - the common case (nGroups == 6). - ---*/ - if (nGroups == 6) { - for (v = 0; v < alphaSize; v++) { - s->len_pack[v][0] = (s->len[1][v] << 16) | s->len[0][v]; - s->len_pack[v][1] = (s->len[3][v] << 16) | s->len[2][v]; - s->len_pack[v][2] = (s->len[5][v] << 16) | s->len[4][v]; - } - } - - nSelectors = 0; - totc = 0; - gs = 0; - while (True) { - - /*--- Set group start & end marks. --*/ - if (gs >= s->nMTF) break; - ge = gs + BZ_G_SIZE - 1; - if (ge >= s->nMTF) ge = s->nMTF-1; - - /*-- - Calculate the cost of this group as coded - by each of the coding tables. - --*/ - for (t = 0; t < nGroups; t++) cost[t] = 0; - - if (nGroups == 6 && 50 == ge-gs+1) { - /*--- fast track the common case ---*/ - register UInt32 cost01, cost23, cost45; - register UInt16 icv; - cost01 = cost23 = cost45 = 0; - -# define BZ_ITER(nn) \ - icv = mtfv[gs+(nn)]; \ - cost01 += s->len_pack[icv][0]; \ - cost23 += s->len_pack[icv][1]; \ - cost45 += s->len_pack[icv][2]; \ - - BZ_ITER(0); BZ_ITER(1); BZ_ITER(2); BZ_ITER(3); BZ_ITER(4); - BZ_ITER(5); BZ_ITER(6); BZ_ITER(7); BZ_ITER(8); BZ_ITER(9); - BZ_ITER(10); BZ_ITER(11); BZ_ITER(12); BZ_ITER(13); BZ_ITER(14); - BZ_ITER(15); BZ_ITER(16); BZ_ITER(17); BZ_ITER(18); BZ_ITER(19); - BZ_ITER(20); BZ_ITER(21); BZ_ITER(22); BZ_ITER(23); BZ_ITER(24); - BZ_ITER(25); BZ_ITER(26); BZ_ITER(27); BZ_ITER(28); BZ_ITER(29); - BZ_ITER(30); BZ_ITER(31); BZ_ITER(32); BZ_ITER(33); BZ_ITER(34); - BZ_ITER(35); BZ_ITER(36); BZ_ITER(37); BZ_ITER(38); BZ_ITER(39); - BZ_ITER(40); BZ_ITER(41); BZ_ITER(42); BZ_ITER(43); BZ_ITER(44); - BZ_ITER(45); BZ_ITER(46); BZ_ITER(47); BZ_ITER(48); BZ_ITER(49); - -# undef BZ_ITER - - cost[0] = cost01 & 0xffff; cost[1] = cost01 >> 16; - cost[2] = cost23 & 0xffff; cost[3] = cost23 >> 16; - cost[4] = cost45 & 0xffff; cost[5] = cost45 >> 16; - - } else { - /*--- slow version which correctly handles all situations ---*/ - for (i = gs; i <= ge; i++) { - UInt16 icv = mtfv[i]; - for (t = 0; t < nGroups; t++) cost[t] += s->len[t][icv]; - } - } - - /*-- - Find the coding table which is best for this group, - and record its identity in the selector table. - --*/ - bc = 999999999; bt = -1; - for (t = 0; t < nGroups; t++) - if (cost[t] < bc) { bc = cost[t]; bt = t; }; - totc += bc; - fave[bt]++; - s->selector[nSelectors] = bt; - nSelectors++; - - /*-- - Increment the symbol frequencies for the selected table. - --*/ - if (nGroups == 6 && 50 == ge-gs+1) { - /*--- fast track the common case ---*/ - -# define BZ_ITUR(nn) s->rfreq[bt][ mtfv[gs+(nn)] ]++ - - BZ_ITUR(0); BZ_ITUR(1); BZ_ITUR(2); BZ_ITUR(3); BZ_ITUR(4); - BZ_ITUR(5); BZ_ITUR(6); BZ_ITUR(7); BZ_ITUR(8); BZ_ITUR(9); - BZ_ITUR(10); BZ_ITUR(11); BZ_ITUR(12); BZ_ITUR(13); BZ_ITUR(14); - BZ_ITUR(15); BZ_ITUR(16); BZ_ITUR(17); BZ_ITUR(18); BZ_ITUR(19); - BZ_ITUR(20); BZ_ITUR(21); BZ_ITUR(22); BZ_ITUR(23); BZ_ITUR(24); - BZ_ITUR(25); BZ_ITUR(26); BZ_ITUR(27); BZ_ITUR(28); BZ_ITUR(29); - BZ_ITUR(30); BZ_ITUR(31); BZ_ITUR(32); BZ_ITUR(33); BZ_ITUR(34); - BZ_ITUR(35); BZ_ITUR(36); BZ_ITUR(37); BZ_ITUR(38); BZ_ITUR(39); - BZ_ITUR(40); BZ_ITUR(41); BZ_ITUR(42); BZ_ITUR(43); BZ_ITUR(44); - BZ_ITUR(45); BZ_ITUR(46); BZ_ITUR(47); BZ_ITUR(48); BZ_ITUR(49); - -# undef BZ_ITUR - - } else { - /*--- slow version which correctly handles all situations ---*/ - for (i = gs; i <= ge; i++) - s->rfreq[bt][ mtfv[i] ]++; - } - - gs = ge+1; - } - if (s->verbosity >= 3) { - VPrintf2 ( " pass %d: size is %d, grp uses are ", - iter+1, totc/8 ); - for (t = 0; t < nGroups; t++) - VPrintf1 ( "%d ", fave[t] ); - VPrintf0 ( "\n" ); - } - - /*-- - Recompute the tables based on the accumulated frequencies. - --*/ - /* maxLen was changed from 20 to 17 in bzip2-1.0.3. See - comment in huffman.c for details. */ - for (t = 0; t < nGroups; t++) - BZ2_hbMakeCodeLengths ( &(s->len[t][0]), &(s->rfreq[t][0]), - alphaSize, 17 /*20*/ ); - } - - - AssertH( nGroups < 8, 3002 ); - AssertH( nSelectors < 32768 && - nSelectors <= (2 + (900000 / BZ_G_SIZE)), - 3003 ); - - - /*--- Compute MTF values for the selectors. ---*/ - { - UChar pos[BZ_N_GROUPS], ll_i, tmp2, tmp; - for (i = 0; i < nGroups; i++) pos[i] = i; - for (i = 0; i < nSelectors; i++) { - ll_i = s->selector[i]; - j = 0; - tmp = pos[j]; - while ( ll_i != tmp ) { - j++; - tmp2 = tmp; - tmp = pos[j]; - pos[j] = tmp2; - }; - pos[0] = tmp; - s->selectorMtf[i] = j; - } - }; - - /*--- Assign actual codes for the tables. --*/ - for (t = 0; t < nGroups; t++) { - minLen = 32; - maxLen = 0; - for (i = 0; i < alphaSize; i++) { - if (s->len[t][i] > maxLen) maxLen = s->len[t][i]; - if (s->len[t][i] < minLen) minLen = s->len[t][i]; - } - AssertH ( !(maxLen > 17 /*20*/ ), 3004 ); - AssertH ( !(minLen < 1), 3005 ); - BZ2_hbAssignCodes ( &(s->code[t][0]), &(s->len[t][0]), - minLen, maxLen, alphaSize ); - } - - /*--- Transmit the mapping table. ---*/ - { - Bool inUse16[16]; - for (i = 0; i < 16; i++) { - inUse16[i] = False; - for (j = 0; j < 16; j++) - if (s->inUse[i * 16 + j]) inUse16[i] = True; - } - - nBytes = s->numZ; - for (i = 0; i < 16; i++) - if (inUse16[i]) bsW(s,1,1); else bsW(s,1,0); - - for (i = 0; i < 16; i++) - if (inUse16[i]) - for (j = 0; j < 16; j++) { - if (s->inUse[i * 16 + j]) bsW(s,1,1); else bsW(s,1,0); - } - - if (s->verbosity >= 3) - VPrintf1( " bytes: mapping %d, ", s->numZ-nBytes ); - } - - /*--- Now the selectors. ---*/ - nBytes = s->numZ; - bsW ( s, 3, nGroups ); - bsW ( s, 15, nSelectors ); - for (i = 0; i < nSelectors; i++) { - for (j = 0; j < s->selectorMtf[i]; j++) bsW(s,1,1); - bsW(s,1,0); - } - if (s->verbosity >= 3) - VPrintf1( "selectors %d, ", s->numZ-nBytes ); - - /*--- Now the coding tables. ---*/ - nBytes = s->numZ; - - for (t = 0; t < nGroups; t++) { - Int32 curr = s->len[t][0]; - bsW ( s, 5, curr ); - for (i = 0; i < alphaSize; i++) { - while (curr < s->len[t][i]) { bsW(s,2,2); curr++; /* 10 */ }; - while (curr > s->len[t][i]) { bsW(s,2,3); curr--; /* 11 */ }; - bsW ( s, 1, 0 ); - } - } - - if (s->verbosity >= 3) - VPrintf1 ( "code lengths %d, ", s->numZ-nBytes ); - - /*--- And finally, the block data proper ---*/ - nBytes = s->numZ; - selCtr = 0; - gs = 0; - while (True) { - if (gs >= s->nMTF) break; - ge = gs + BZ_G_SIZE - 1; - if (ge >= s->nMTF) ge = s->nMTF-1; - AssertH ( s->selector[selCtr] < nGroups, 3006 ); - - if (nGroups == 6 && 50 == ge-gs+1) { - /*--- fast track the common case ---*/ - UInt16 mtfv_i; - UChar* s_len_sel_selCtr - = &(s->len[s->selector[selCtr]][0]); - Int32* s_code_sel_selCtr - = &(s->code[s->selector[selCtr]][0]); - -# define BZ_ITAH(nn) \ - mtfv_i = mtfv[gs+(nn)]; \ - bsW ( s, \ - s_len_sel_selCtr[mtfv_i], \ - s_code_sel_selCtr[mtfv_i] ) - - BZ_ITAH(0); BZ_ITAH(1); BZ_ITAH(2); BZ_ITAH(3); BZ_ITAH(4); - BZ_ITAH(5); BZ_ITAH(6); BZ_ITAH(7); BZ_ITAH(8); BZ_ITAH(9); - BZ_ITAH(10); BZ_ITAH(11); BZ_ITAH(12); BZ_ITAH(13); BZ_ITAH(14); - BZ_ITAH(15); BZ_ITAH(16); BZ_ITAH(17); BZ_ITAH(18); BZ_ITAH(19); - BZ_ITAH(20); BZ_ITAH(21); BZ_ITAH(22); BZ_ITAH(23); BZ_ITAH(24); - BZ_ITAH(25); BZ_ITAH(26); BZ_ITAH(27); BZ_ITAH(28); BZ_ITAH(29); - BZ_ITAH(30); BZ_ITAH(31); BZ_ITAH(32); BZ_ITAH(33); BZ_ITAH(34); - BZ_ITAH(35); BZ_ITAH(36); BZ_ITAH(37); BZ_ITAH(38); BZ_ITAH(39); - BZ_ITAH(40); BZ_ITAH(41); BZ_ITAH(42); BZ_ITAH(43); BZ_ITAH(44); - BZ_ITAH(45); BZ_ITAH(46); BZ_ITAH(47); BZ_ITAH(48); BZ_ITAH(49); - -# undef BZ_ITAH - - } else { - /*--- slow version which correctly handles all situations ---*/ - for (i = gs; i <= ge; i++) { - bsW ( s, - s->len [s->selector[selCtr]] [mtfv[i]], - s->code [s->selector[selCtr]] [mtfv[i]] ); - } - } - - - gs = ge+1; - selCtr++; - } - AssertH( selCtr == nSelectors, 3007 ); - - if (s->verbosity >= 3) - VPrintf1( "codes %d\n", s->numZ-nBytes ); -} - - -/*---------------------------------------------------*/ -void BZ2_compressBlock ( EState* s, Bool is_last_block ) -{ - if (s->nblock > 0) { - - BZ_FINALISE_CRC ( s->blockCRC ); - s->combinedCRC = (s->combinedCRC << 1) | (s->combinedCRC >> 31); - s->combinedCRC ^= s->blockCRC; - if (s->blockNo > 1) s->numZ = 0; - - if (s->verbosity >= 2) - VPrintf4( " block %d: crc = 0x%08x, " - "combined CRC = 0x%08x, size = %d\n", - s->blockNo, s->blockCRC, s->combinedCRC, s->nblock ); - - BZ2_blockSort ( s ); - } - - s->zbits = (UChar*) (&((UChar*)s->arr2)[s->nblock]); - - /*-- If this is the first block, create the stream header. --*/ - if (s->blockNo == 1) { - BZ2_bsInitWrite ( s ); - bsPutUChar ( s, BZ_HDR_B ); - bsPutUChar ( s, BZ_HDR_Z ); - bsPutUChar ( s, BZ_HDR_h ); - bsPutUChar ( s, (UChar)(BZ_HDR_0 + s->blockSize100k) ); - } - - if (s->nblock > 0) { - - bsPutUChar ( s, 0x31 ); bsPutUChar ( s, 0x41 ); - bsPutUChar ( s, 0x59 ); bsPutUChar ( s, 0x26 ); - bsPutUChar ( s, 0x53 ); bsPutUChar ( s, 0x59 ); - - /*-- Now the block's CRC, so it is in a known place. --*/ - bsPutUInt32 ( s, s->blockCRC ); - - /*-- - Now a single bit indicating (non-)randomisation. - As of version 0.9.5, we use a better sorting algorithm - which makes randomisation unnecessary. So always set - the randomised bit to 'no'. Of course, the decoder - still needs to be able to handle randomised blocks - so as to maintain backwards compatibility with - older versions of bzip2. - --*/ - bsW(s,1,0); - - bsW ( s, 24, s->origPtr ); - generateMTFValues ( s ); - sendMTFValues ( s ); - } - - - /*-- If this is the last block, add the stream trailer. --*/ - if (is_last_block) { - - bsPutUChar ( s, 0x17 ); bsPutUChar ( s, 0x72 ); - bsPutUChar ( s, 0x45 ); bsPutUChar ( s, 0x38 ); - bsPutUChar ( s, 0x50 ); bsPutUChar ( s, 0x90 ); - bsPutUInt32 ( s, s->combinedCRC ); - if (s->verbosity >= 2) - VPrintf1( " final combined CRC = 0x%08x\n ", s->combinedCRC ); - bsFinishWrite ( s ); - } -} - - -/*-------------------------------------------------------------*/ -/*--- end compress.c ---*/ -/*-------------------------------------------------------------*/ diff --git a/dep/StormLib/src/bzip2/crctable.c b/dep/StormLib/src/bzip2/crctable.c deleted file mode 100644 index 215687b2c05..00000000000 --- a/dep/StormLib/src/bzip2/crctable.c +++ /dev/null @@ -1,104 +0,0 @@ - -/*-------------------------------------------------------------*/ -/*--- Table for doing CRCs ---*/ -/*--- crctable.c ---*/ -/*-------------------------------------------------------------*/ - -/* ------------------------------------------------------------------ - This file is part of bzip2/libbzip2, a program and library for - lossless, block-sorting data compression. - - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward - - Please read the WARNING, DISCLAIMER and PATENTS sections in the - README file. - - This program is released under the terms of the license contained - in the file LICENSE. - ------------------------------------------------------------------ */ - - -#include "bzlib_private.h" - -/*-- - I think this is an implementation of the AUTODIN-II, - Ethernet & FDDI 32-bit CRC standard. Vaguely derived - from code by Rob Warnock, in Section 51 of the - comp.compression FAQ. ---*/ - -UInt32 BZ2_crc32Table[256] = { - - /*-- Ugly, innit? --*/ - - 0x00000000L, 0x04c11db7L, 0x09823b6eL, 0x0d4326d9L, - 0x130476dcL, 0x17c56b6bL, 0x1a864db2L, 0x1e475005L, - 0x2608edb8L, 0x22c9f00fL, 0x2f8ad6d6L, 0x2b4bcb61L, - 0x350c9b64L, 0x31cd86d3L, 0x3c8ea00aL, 0x384fbdbdL, - 0x4c11db70L, 0x48d0c6c7L, 0x4593e01eL, 0x4152fda9L, - 0x5f15adacL, 0x5bd4b01bL, 0x569796c2L, 0x52568b75L, - 0x6a1936c8L, 0x6ed82b7fL, 0x639b0da6L, 0x675a1011L, - 0x791d4014L, 0x7ddc5da3L, 0x709f7b7aL, 0x745e66cdL, - 0x9823b6e0L, 0x9ce2ab57L, 0x91a18d8eL, 0x95609039L, - 0x8b27c03cL, 0x8fe6dd8bL, 0x82a5fb52L, 0x8664e6e5L, - 0xbe2b5b58L, 0xbaea46efL, 0xb7a96036L, 0xb3687d81L, - 0xad2f2d84L, 0xa9ee3033L, 0xa4ad16eaL, 0xa06c0b5dL, - 0xd4326d90L, 0xd0f37027L, 0xddb056feL, 0xd9714b49L, - 0xc7361b4cL, 0xc3f706fbL, 0xceb42022L, 0xca753d95L, - 0xf23a8028L, 0xf6fb9d9fL, 0xfbb8bb46L, 0xff79a6f1L, - 0xe13ef6f4L, 0xe5ffeb43L, 0xe8bccd9aL, 0xec7dd02dL, - 0x34867077L, 0x30476dc0L, 0x3d044b19L, 0x39c556aeL, - 0x278206abL, 0x23431b1cL, 0x2e003dc5L, 0x2ac12072L, - 0x128e9dcfL, 0x164f8078L, 0x1b0ca6a1L, 0x1fcdbb16L, - 0x018aeb13L, 0x054bf6a4L, 0x0808d07dL, 0x0cc9cdcaL, - 0x7897ab07L, 0x7c56b6b0L, 0x71159069L, 0x75d48ddeL, - 0x6b93dddbL, 0x6f52c06cL, 0x6211e6b5L, 0x66d0fb02L, - 0x5e9f46bfL, 0x5a5e5b08L, 0x571d7dd1L, 0x53dc6066L, - 0x4d9b3063L, 0x495a2dd4L, 0x44190b0dL, 0x40d816baL, - 0xaca5c697L, 0xa864db20L, 0xa527fdf9L, 0xa1e6e04eL, - 0xbfa1b04bL, 0xbb60adfcL, 0xb6238b25L, 0xb2e29692L, - 0x8aad2b2fL, 0x8e6c3698L, 0x832f1041L, 0x87ee0df6L, - 0x99a95df3L, 0x9d684044L, 0x902b669dL, 0x94ea7b2aL, - 0xe0b41de7L, 0xe4750050L, 0xe9362689L, 0xedf73b3eL, - 0xf3b06b3bL, 0xf771768cL, 0xfa325055L, 0xfef34de2L, - 0xc6bcf05fL, 0xc27dede8L, 0xcf3ecb31L, 0xcbffd686L, - 0xd5b88683L, 0xd1799b34L, 0xdc3abdedL, 0xd8fba05aL, - 0x690ce0eeL, 0x6dcdfd59L, 0x608edb80L, 0x644fc637L, - 0x7a089632L, 0x7ec98b85L, 0x738aad5cL, 0x774bb0ebL, - 0x4f040d56L, 0x4bc510e1L, 0x46863638L, 0x42472b8fL, - 0x5c007b8aL, 0x58c1663dL, 0x558240e4L, 0x51435d53L, - 0x251d3b9eL, 0x21dc2629L, 0x2c9f00f0L, 0x285e1d47L, - 0x36194d42L, 0x32d850f5L, 0x3f9b762cL, 0x3b5a6b9bL, - 0x0315d626L, 0x07d4cb91L, 0x0a97ed48L, 0x0e56f0ffL, - 0x1011a0faL, 0x14d0bd4dL, 0x19939b94L, 0x1d528623L, - 0xf12f560eL, 0xf5ee4bb9L, 0xf8ad6d60L, 0xfc6c70d7L, - 0xe22b20d2L, 0xe6ea3d65L, 0xeba91bbcL, 0xef68060bL, - 0xd727bbb6L, 0xd3e6a601L, 0xdea580d8L, 0xda649d6fL, - 0xc423cd6aL, 0xc0e2d0ddL, 0xcda1f604L, 0xc960ebb3L, - 0xbd3e8d7eL, 0xb9ff90c9L, 0xb4bcb610L, 0xb07daba7L, - 0xae3afba2L, 0xaafbe615L, 0xa7b8c0ccL, 0xa379dd7bL, - 0x9b3660c6L, 0x9ff77d71L, 0x92b45ba8L, 0x9675461fL, - 0x8832161aL, 0x8cf30badL, 0x81b02d74L, 0x857130c3L, - 0x5d8a9099L, 0x594b8d2eL, 0x5408abf7L, 0x50c9b640L, - 0x4e8ee645L, 0x4a4ffbf2L, 0x470cdd2bL, 0x43cdc09cL, - 0x7b827d21L, 0x7f436096L, 0x7200464fL, 0x76c15bf8L, - 0x68860bfdL, 0x6c47164aL, 0x61043093L, 0x65c52d24L, - 0x119b4be9L, 0x155a565eL, 0x18197087L, 0x1cd86d30L, - 0x029f3d35L, 0x065e2082L, 0x0b1d065bL, 0x0fdc1becL, - 0x3793a651L, 0x3352bbe6L, 0x3e119d3fL, 0x3ad08088L, - 0x2497d08dL, 0x2056cd3aL, 0x2d15ebe3L, 0x29d4f654L, - 0xc5a92679L, 0xc1683bceL, 0xcc2b1d17L, 0xc8ea00a0L, - 0xd6ad50a5L, 0xd26c4d12L, 0xdf2f6bcbL, 0xdbee767cL, - 0xe3a1cbc1L, 0xe760d676L, 0xea23f0afL, 0xeee2ed18L, - 0xf0a5bd1dL, 0xf464a0aaL, 0xf9278673L, 0xfde69bc4L, - 0x89b8fd09L, 0x8d79e0beL, 0x803ac667L, 0x84fbdbd0L, - 0x9abc8bd5L, 0x9e7d9662L, 0x933eb0bbL, 0x97ffad0cL, - 0xafb010b1L, 0xab710d06L, 0xa6322bdfL, 0xa2f33668L, - 0xbcb4666dL, 0xb8757bdaL, 0xb5365d03L, 0xb1f740b4L -}; - - -/*-------------------------------------------------------------*/ -/*--- end crctable.c ---*/ -/*-------------------------------------------------------------*/ diff --git a/dep/StormLib/src/bzip2/decompress.c b/dep/StormLib/src/bzip2/decompress.c deleted file mode 100644 index bba5e0fa36d..00000000000 --- a/dep/StormLib/src/bzip2/decompress.c +++ /dev/null @@ -1,626 +0,0 @@ - -/*-------------------------------------------------------------*/ -/*--- Decompression machinery ---*/ -/*--- decompress.c ---*/ -/*-------------------------------------------------------------*/ - -/* ------------------------------------------------------------------ - This file is part of bzip2/libbzip2, a program and library for - lossless, block-sorting data compression. - - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward - - Please read the WARNING, DISCLAIMER and PATENTS sections in the - README file. - - This program is released under the terms of the license contained - in the file LICENSE. - ------------------------------------------------------------------ */ - - -#include "bzlib_private.h" - - -/*---------------------------------------------------*/ -static -void makeMaps_d ( DState* s ) -{ - Int32 i; - s->nInUse = 0; - for (i = 0; i < 256; i++) - if (s->inUse[i]) { - s->seqToUnseq[s->nInUse] = i; - s->nInUse++; - } -} - - -/*---------------------------------------------------*/ -#define RETURN(rrr) \ - { retVal = rrr; goto save_state_and_return; }; - -#define GET_BITS(lll,vvv,nnn) \ - case lll: s->state = lll; \ - while (True) { \ - if (s->bsLive >= nnn) { \ - UInt32 v; \ - v = (s->bsBuff >> \ - (s->bsLive-nnn)) & ((1 << nnn)-1); \ - s->bsLive -= nnn; \ - vvv = v; \ - break; \ - } \ - if (s->strm->avail_in == 0) RETURN(BZ_OK); \ - s->bsBuff \ - = (s->bsBuff << 8) | \ - ((UInt32) \ - (*((UChar*)(s->strm->next_in)))); \ - s->bsLive += 8; \ - s->strm->next_in++; \ - s->strm->avail_in--; \ - s->strm->total_in_lo32++; \ - if (s->strm->total_in_lo32 == 0) \ - s->strm->total_in_hi32++; \ - } - -#define GET_UCHAR(lll,uuu) \ - GET_BITS(lll,uuu,8) - -#define GET_BIT(lll,uuu) \ - GET_BITS(lll,uuu,1) - -/*---------------------------------------------------*/ -#define GET_MTF_VAL(label1,label2,lval) \ -{ \ - if (groupPos == 0) { \ - groupNo++; \ - if (groupNo >= nSelectors) \ - RETURN(BZ_DATA_ERROR); \ - groupPos = BZ_G_SIZE; \ - gSel = s->selector[groupNo]; \ - gMinlen = s->minLens[gSel]; \ - gLimit = &(s->limit[gSel][0]); \ - gPerm = &(s->perm[gSel][0]); \ - gBase = &(s->base[gSel][0]); \ - } \ - groupPos--; \ - zn = gMinlen; \ - GET_BITS(label1, zvec, zn); \ - while (1) { \ - if (zn > 20 /* the longest code */) \ - RETURN(BZ_DATA_ERROR); \ - if (zvec <= gLimit[zn]) break; \ - zn++; \ - GET_BIT(label2, zj); \ - zvec = (zvec << 1) | zj; \ - }; \ - if (zvec - gBase[zn] < 0 \ - || zvec - gBase[zn] >= BZ_MAX_ALPHA_SIZE) \ - RETURN(BZ_DATA_ERROR); \ - lval = gPerm[zvec - gBase[zn]]; \ -} - - -/*---------------------------------------------------*/ -Int32 BZ2_decompress ( DState* s ) -{ - UChar uc; - Int32 retVal; - Int32 minLen, maxLen; - bz_stream* strm = s->strm; - - /* stuff that needs to be saved/restored */ - Int32 i; - Int32 j; - Int32 t; - Int32 alphaSize; - Int32 nGroups; - Int32 nSelectors; - Int32 EOB; - Int32 groupNo; - Int32 groupPos; - Int32 nextSym; - Int32 nblockMAX; - Int32 nblock; - Int32 es; - Int32 N; - Int32 curr; - Int32 zt; - Int32 zn; - Int32 zvec; - Int32 zj; - Int32 gSel; - Int32 gMinlen; - Int32* gLimit; - Int32* gBase; - Int32* gPerm; - - if (s->state == BZ_X_MAGIC_1) { - /*initialise the save area*/ - s->save_i = 0; - s->save_j = 0; - s->save_t = 0; - s->save_alphaSize = 0; - s->save_nGroups = 0; - s->save_nSelectors = 0; - s->save_EOB = 0; - s->save_groupNo = 0; - s->save_groupPos = 0; - s->save_nextSym = 0; - s->save_nblockMAX = 0; - s->save_nblock = 0; - s->save_es = 0; - s->save_N = 0; - s->save_curr = 0; - s->save_zt = 0; - s->save_zn = 0; - s->save_zvec = 0; - s->save_zj = 0; - s->save_gSel = 0; - s->save_gMinlen = 0; - s->save_gLimit = NULL; - s->save_gBase = NULL; - s->save_gPerm = NULL; - } - - /*restore from the save area*/ - i = s->save_i; - j = s->save_j; - t = s->save_t; - alphaSize = s->save_alphaSize; - nGroups = s->save_nGroups; - nSelectors = s->save_nSelectors; - EOB = s->save_EOB; - groupNo = s->save_groupNo; - groupPos = s->save_groupPos; - nextSym = s->save_nextSym; - nblockMAX = s->save_nblockMAX; - nblock = s->save_nblock; - es = s->save_es; - N = s->save_N; - curr = s->save_curr; - zt = s->save_zt; - zn = s->save_zn; - zvec = s->save_zvec; - zj = s->save_zj; - gSel = s->save_gSel; - gMinlen = s->save_gMinlen; - gLimit = s->save_gLimit; - gBase = s->save_gBase; - gPerm = s->save_gPerm; - - retVal = BZ_OK; - - switch (s->state) { - - GET_UCHAR(BZ_X_MAGIC_1, uc); - if (uc != BZ_HDR_B) RETURN(BZ_DATA_ERROR_MAGIC); - - GET_UCHAR(BZ_X_MAGIC_2, uc); - if (uc != BZ_HDR_Z) RETURN(BZ_DATA_ERROR_MAGIC); - - GET_UCHAR(BZ_X_MAGIC_3, uc) - if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC); - - GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8) - if (s->blockSize100k < (BZ_HDR_0 + 1) || - s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC); - s->blockSize100k -= BZ_HDR_0; - - if (s->smallDecompress) { - s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) ); - s->ll4 = BZALLOC( - ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar) - ); - if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR); - } else { - s->tt = BZALLOC( s->blockSize100k * 100000 * sizeof(Int32) ); - if (s->tt == NULL) RETURN(BZ_MEM_ERROR); - } - - GET_UCHAR(BZ_X_BLKHDR_1, uc); - - if (uc == 0x17) goto endhdr_2; - if (uc != 0x31) RETURN(BZ_DATA_ERROR); - GET_UCHAR(BZ_X_BLKHDR_2, uc); - if (uc != 0x41) RETURN(BZ_DATA_ERROR); - GET_UCHAR(BZ_X_BLKHDR_3, uc); - if (uc != 0x59) RETURN(BZ_DATA_ERROR); - GET_UCHAR(BZ_X_BLKHDR_4, uc); - if (uc != 0x26) RETURN(BZ_DATA_ERROR); - GET_UCHAR(BZ_X_BLKHDR_5, uc); - if (uc != 0x53) RETURN(BZ_DATA_ERROR); - GET_UCHAR(BZ_X_BLKHDR_6, uc); - if (uc != 0x59) RETURN(BZ_DATA_ERROR); - - s->currBlockNo++; - if (s->verbosity >= 2) - VPrintf1 ( "\n [%d: huff+mtf ", s->currBlockNo ); - - s->storedBlockCRC = 0; - GET_UCHAR(BZ_X_BCRC_1, uc); - s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); - GET_UCHAR(BZ_X_BCRC_2, uc); - s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); - GET_UCHAR(BZ_X_BCRC_3, uc); - s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); - GET_UCHAR(BZ_X_BCRC_4, uc); - s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); - - GET_BITS(BZ_X_RANDBIT, s->blockRandomised, 1); - - s->origPtr = 0; - GET_UCHAR(BZ_X_ORIGPTR_1, uc); - s->origPtr = (s->origPtr << 8) | ((Int32)uc); - GET_UCHAR(BZ_X_ORIGPTR_2, uc); - s->origPtr = (s->origPtr << 8) | ((Int32)uc); - GET_UCHAR(BZ_X_ORIGPTR_3, uc); - s->origPtr = (s->origPtr << 8) | ((Int32)uc); - - if (s->origPtr < 0) - RETURN(BZ_DATA_ERROR); - if (s->origPtr > 10 + 100000*s->blockSize100k) - RETURN(BZ_DATA_ERROR); - - /*--- Receive the mapping table ---*/ - for (i = 0; i < 16; i++) { - GET_BIT(BZ_X_MAPPING_1, uc); - if (uc == 1) - s->inUse16[i] = True; else - s->inUse16[i] = False; - } - - for (i = 0; i < 256; i++) s->inUse[i] = False; - - for (i = 0; i < 16; i++) - if (s->inUse16[i]) - for (j = 0; j < 16; j++) { - GET_BIT(BZ_X_MAPPING_2, uc); - if (uc == 1) s->inUse[i * 16 + j] = True; - } - makeMaps_d ( s ); - if (s->nInUse == 0) RETURN(BZ_DATA_ERROR); - alphaSize = s->nInUse+2; - - /*--- Now the selectors ---*/ - GET_BITS(BZ_X_SELECTOR_1, nGroups, 3); - if (nGroups < 2 || nGroups > 6) RETURN(BZ_DATA_ERROR); - GET_BITS(BZ_X_SELECTOR_2, nSelectors, 15); - if (nSelectors < 1) RETURN(BZ_DATA_ERROR); - for (i = 0; i < nSelectors; i++) { - j = 0; - while (True) { - GET_BIT(BZ_X_SELECTOR_3, uc); - if (uc == 0) break; - j++; - if (j >= nGroups) RETURN(BZ_DATA_ERROR); - } - s->selectorMtf[i] = j; - } - - /*--- Undo the MTF values for the selectors. ---*/ - { - UChar pos[BZ_N_GROUPS], tmp, v; - for (v = 0; v < nGroups; v++) pos[v] = v; - - for (i = 0; i < nSelectors; i++) { - v = s->selectorMtf[i]; - tmp = pos[v]; - while (v > 0) { pos[v] = pos[v-1]; v--; } - pos[0] = tmp; - s->selector[i] = tmp; - } - } - - /*--- Now the coding tables ---*/ - for (t = 0; t < nGroups; t++) { - GET_BITS(BZ_X_CODING_1, curr, 5); - for (i = 0; i < alphaSize; i++) { - while (True) { - if (curr < 1 || curr > 20) RETURN(BZ_DATA_ERROR); - GET_BIT(BZ_X_CODING_2, uc); - if (uc == 0) break; - GET_BIT(BZ_X_CODING_3, uc); - if (uc == 0) curr++; else curr--; - } - s->len[t][i] = curr; - } - } - - /*--- Create the Huffman decoding tables ---*/ - for (t = 0; t < nGroups; t++) { - minLen = 32; - maxLen = 0; - for (i = 0; i < alphaSize; i++) { - if (s->len[t][i] > maxLen) maxLen = s->len[t][i]; - if (s->len[t][i] < minLen) minLen = s->len[t][i]; - } - BZ2_hbCreateDecodeTables ( - &(s->limit[t][0]), - &(s->base[t][0]), - &(s->perm[t][0]), - &(s->len[t][0]), - minLen, maxLen, alphaSize - ); - s->minLens[t] = minLen; - } - - /*--- Now the MTF values ---*/ - - EOB = s->nInUse+1; - nblockMAX = 100000 * s->blockSize100k; - groupNo = -1; - groupPos = 0; - - for (i = 0; i <= 255; i++) s->unzftab[i] = 0; - - /*-- MTF init --*/ - { - Int32 ii, jj, kk; - kk = MTFA_SIZE-1; - for (ii = 256 / MTFL_SIZE - 1; ii >= 0; ii--) { - for (jj = MTFL_SIZE-1; jj >= 0; jj--) { - s->mtfa[kk] = (UChar)(ii * MTFL_SIZE + jj); - kk--; - } - s->mtfbase[ii] = kk + 1; - } - } - /*-- end MTF init --*/ - - nblock = 0; - GET_MTF_VAL(BZ_X_MTF_1, BZ_X_MTF_2, nextSym); - - while (True) { - - if (nextSym == EOB) break; - - if (nextSym == BZ_RUNA || nextSym == BZ_RUNB) { - - es = -1; - N = 1; - do { - if (nextSym == BZ_RUNA) es = es + (0+1) * N; else - if (nextSym == BZ_RUNB) es = es + (1+1) * N; - N = N * 2; - GET_MTF_VAL(BZ_X_MTF_3, BZ_X_MTF_4, nextSym); - } - while (nextSym == BZ_RUNA || nextSym == BZ_RUNB); - - es++; - uc = s->seqToUnseq[ s->mtfa[s->mtfbase[0]] ]; - s->unzftab[uc] += es; - - if (s->smallDecompress) - while (es > 0) { - if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); - s->ll16[nblock] = (UInt16)uc; - nblock++; - es--; - } - else - while (es > 0) { - if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); - s->tt[nblock] = (UInt32)uc; - nblock++; - es--; - }; - - continue; - - } else { - - if (nblock >= nblockMAX) RETURN(BZ_DATA_ERROR); - - /*-- uc = MTF ( nextSym-1 ) --*/ - { - Int32 ii, jj, kk, pp, lno, off; - UInt32 nn; - nn = (UInt32)(nextSym - 1); - - if (nn < MTFL_SIZE) { - /* avoid general-case expense */ - pp = s->mtfbase[0]; - uc = s->mtfa[pp+nn]; - while (nn > 3) { - Int32 z = pp+nn; - s->mtfa[(z) ] = s->mtfa[(z)-1]; - s->mtfa[(z)-1] = s->mtfa[(z)-2]; - s->mtfa[(z)-2] = s->mtfa[(z)-3]; - s->mtfa[(z)-3] = s->mtfa[(z)-4]; - nn -= 4; - } - while (nn > 0) { - s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--; - }; - s->mtfa[pp] = uc; - } else { - /* general case */ - lno = nn / MTFL_SIZE; - off = nn % MTFL_SIZE; - pp = s->mtfbase[lno] + off; - uc = s->mtfa[pp]; - while (pp > s->mtfbase[lno]) { - s->mtfa[pp] = s->mtfa[pp-1]; pp--; - }; - s->mtfbase[lno]++; - while (lno > 0) { - s->mtfbase[lno]--; - s->mtfa[s->mtfbase[lno]] - = s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1]; - lno--; - } - s->mtfbase[0]--; - s->mtfa[s->mtfbase[0]] = uc; - if (s->mtfbase[0] == 0) { - kk = MTFA_SIZE-1; - for (ii = 256 / MTFL_SIZE-1; ii >= 0; ii--) { - for (jj = MTFL_SIZE-1; jj >= 0; jj--) { - s->mtfa[kk] = s->mtfa[s->mtfbase[ii] + jj]; - kk--; - } - s->mtfbase[ii] = kk + 1; - } - } - } - } - /*-- end uc = MTF ( nextSym-1 ) --*/ - - s->unzftab[s->seqToUnseq[uc]]++; - if (s->smallDecompress) - s->ll16[nblock] = (UInt16)(s->seqToUnseq[uc]); else - s->tt[nblock] = (UInt32)(s->seqToUnseq[uc]); - nblock++; - - GET_MTF_VAL(BZ_X_MTF_5, BZ_X_MTF_6, nextSym); - continue; - } - } - - /* Now we know what nblock is, we can do a better sanity - check on s->origPtr. - */ - if (s->origPtr < 0 || s->origPtr >= nblock) - RETURN(BZ_DATA_ERROR); - - /*-- Set up cftab to facilitate generation of T^(-1) --*/ - s->cftab[0] = 0; - for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1]; - for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1]; - for (i = 0; i <= 256; i++) { - if (s->cftab[i] < 0 || s->cftab[i] > nblock) { - /* s->cftab[i] can legitimately be == nblock */ - RETURN(BZ_DATA_ERROR); - } - } - - s->state_out_len = 0; - s->state_out_ch = 0; - BZ_INITIALISE_CRC ( s->calculatedBlockCRC ); - s->state = BZ_X_OUTPUT; - if (s->verbosity >= 2) VPrintf0 ( "rt+rld" ); - - if (s->smallDecompress) { - - /*-- Make a copy of cftab, used in generation of T --*/ - for (i = 0; i <= 256; i++) s->cftabCopy[i] = s->cftab[i]; - - /*-- compute the T vector --*/ - for (i = 0; i < nblock; i++) { - uc = (UChar)(s->ll16[i]); - SET_LL(i, s->cftabCopy[uc]); - s->cftabCopy[uc]++; - } - - /*-- Compute T^(-1) by pointer reversal on T --*/ - i = s->origPtr; - j = GET_LL(i); - do { - Int32 tmp = GET_LL(j); - SET_LL(j, i); - i = j; - j = tmp; - } - while (i != s->origPtr); - - s->tPos = s->origPtr; - s->nblock_used = 0; - if (s->blockRandomised) { - BZ_RAND_INIT_MASK; - BZ_GET_SMALL(s->k0); s->nblock_used++; - BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; - } else { - BZ_GET_SMALL(s->k0); s->nblock_used++; - } - - } else { - - /*-- compute the T^(-1) vector --*/ - for (i = 0; i < nblock; i++) { - uc = (UChar)(s->tt[i] & 0xff); - s->tt[s->cftab[uc]] |= (i << 8); - s->cftab[uc]++; - } - - s->tPos = s->tt[s->origPtr] >> 8; - s->nblock_used = 0; - if (s->blockRandomised) { - BZ_RAND_INIT_MASK; - BZ_GET_FAST(s->k0); s->nblock_used++; - BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; - } else { - BZ_GET_FAST(s->k0); s->nblock_used++; - } - - } - - RETURN(BZ_OK); - - - - endhdr_2: - - GET_UCHAR(BZ_X_ENDHDR_2, uc); - if (uc != 0x72) RETURN(BZ_DATA_ERROR); - GET_UCHAR(BZ_X_ENDHDR_3, uc); - if (uc != 0x45) RETURN(BZ_DATA_ERROR); - GET_UCHAR(BZ_X_ENDHDR_4, uc); - if (uc != 0x38) RETURN(BZ_DATA_ERROR); - GET_UCHAR(BZ_X_ENDHDR_5, uc); - if (uc != 0x50) RETURN(BZ_DATA_ERROR); - GET_UCHAR(BZ_X_ENDHDR_6, uc); - if (uc != 0x90) RETURN(BZ_DATA_ERROR); - - s->storedCombinedCRC = 0; - GET_UCHAR(BZ_X_CCRC_1, uc); - s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); - GET_UCHAR(BZ_X_CCRC_2, uc); - s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); - GET_UCHAR(BZ_X_CCRC_3, uc); - s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); - GET_UCHAR(BZ_X_CCRC_4, uc); - s->storedCombinedCRC = (s->storedCombinedCRC << 8) | ((UInt32)uc); - - s->state = BZ_X_IDLE; - RETURN(BZ_STREAM_END); - - default: AssertH ( False, 4001 ); - } - - AssertH ( False, 4002 ); - - save_state_and_return: - - s->save_i = i; - s->save_j = j; - s->save_t = t; - s->save_alphaSize = alphaSize; - s->save_nGroups = nGroups; - s->save_nSelectors = nSelectors; - s->save_EOB = EOB; - s->save_groupNo = groupNo; - s->save_groupPos = groupPos; - s->save_nextSym = nextSym; - s->save_nblockMAX = nblockMAX; - s->save_nblock = nblock; - s->save_es = es; - s->save_N = N; - s->save_curr = curr; - s->save_zt = zt; - s->save_zn = zn; - s->save_zvec = zvec; - s->save_zj = zj; - s->save_gSel = gSel; - s->save_gMinlen = gMinlen; - s->save_gLimit = gLimit; - s->save_gBase = gBase; - s->save_gPerm = gPerm; - - return retVal; -} - - -/*-------------------------------------------------------------*/ -/*--- end decompress.c ---*/ -/*-------------------------------------------------------------*/ diff --git a/dep/StormLib/src/bzip2/huffman.c b/dep/StormLib/src/bzip2/huffman.c deleted file mode 100644 index 87e79e38af0..00000000000 --- a/dep/StormLib/src/bzip2/huffman.c +++ /dev/null @@ -1,205 +0,0 @@ - -/*-------------------------------------------------------------*/ -/*--- Huffman coding low-level stuff ---*/ -/*--- huffman.c ---*/ -/*-------------------------------------------------------------*/ - -/* ------------------------------------------------------------------ - This file is part of bzip2/libbzip2, a program and library for - lossless, block-sorting data compression. - - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward - - Please read the WARNING, DISCLAIMER and PATENTS sections in the - README file. - - This program is released under the terms of the license contained - in the file LICENSE. - ------------------------------------------------------------------ */ - - -#include "bzlib_private.h" - -/*---------------------------------------------------*/ -#define WEIGHTOF(zz0) ((zz0) & 0xffffff00) -#define DEPTHOF(zz1) ((zz1) & 0x000000ff) -#define MYMAX(zz2,zz3) ((zz2) > (zz3) ? (zz2) : (zz3)) - -#define ADDWEIGHTS(zw1,zw2) \ - (WEIGHTOF(zw1)+WEIGHTOF(zw2)) | \ - (1 + MYMAX(DEPTHOF(zw1),DEPTHOF(zw2))) - -#define UPHEAP(z) \ -{ \ - Int32 zz, tmp; \ - zz = z; tmp = heap[zz]; \ - while (weight[tmp] < weight[heap[zz >> 1]]) { \ - heap[zz] = heap[zz >> 1]; \ - zz >>= 1; \ - } \ - heap[zz] = tmp; \ -} - -#define DOWNHEAP(z) \ -{ \ - Int32 zz, yy, tmp; \ - zz = z; tmp = heap[zz]; \ - while (True) { \ - yy = zz << 1; \ - if (yy > nHeap) break; \ - if (yy < nHeap && \ - weight[heap[yy+1]] < weight[heap[yy]]) \ - yy++; \ - if (weight[tmp] < weight[heap[yy]]) break; \ - heap[zz] = heap[yy]; \ - zz = yy; \ - } \ - heap[zz] = tmp; \ -} - - -/*---------------------------------------------------*/ -void BZ2_hbMakeCodeLengths ( UChar *len, - Int32 *freq, - Int32 alphaSize, - Int32 maxLen ) -{ - /*-- - Nodes and heap entries run from 1. Entry 0 - for both the heap and nodes is a sentinel. - --*/ - Int32 nNodes, nHeap, n1, n2, i, j, k; - Bool tooLong; - - Int32 heap [ BZ_MAX_ALPHA_SIZE + 2 ]; - Int32 weight [ BZ_MAX_ALPHA_SIZE * 2 ]; - Int32 parent [ BZ_MAX_ALPHA_SIZE * 2 ]; - - for (i = 0; i < alphaSize; i++) - weight[i+1] = (freq[i] == 0 ? 1 : freq[i]) << 8; - - while (True) { - - nNodes = alphaSize; - nHeap = 0; - - heap[0] = 0; - weight[0] = 0; - parent[0] = -2; - - for (i = 1; i <= alphaSize; i++) { - parent[i] = -1; - nHeap++; - heap[nHeap] = i; - UPHEAP(nHeap); - } - - AssertH( nHeap < (BZ_MAX_ALPHA_SIZE+2), 2001 ); - - while (nHeap > 1) { - n1 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1); - n2 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1); - nNodes++; - parent[n1] = parent[n2] = nNodes; - weight[nNodes] = ADDWEIGHTS(weight[n1], weight[n2]); - parent[nNodes] = -1; - nHeap++; - heap[nHeap] = nNodes; - UPHEAP(nHeap); - } - - AssertH( nNodes < (BZ_MAX_ALPHA_SIZE * 2), 2002 ); - - tooLong = False; - for (i = 1; i <= alphaSize; i++) { - j = 0; - k = i; - while (parent[k] >= 0) { k = parent[k]; j++; } - len[i-1] = j; - if (j > maxLen) tooLong = True; - } - - if (! tooLong) break; - - /* 17 Oct 04: keep-going condition for the following loop used - to be 'i < alphaSize', which missed the last element, - theoretically leading to the possibility of the compressor - looping. However, this count-scaling step is only needed if - one of the generated Huffman code words is longer than - maxLen, which up to and including version 1.0.2 was 20 bits, - which is extremely unlikely. In version 1.0.3 maxLen was - changed to 17 bits, which has minimal effect on compression - ratio, but does mean this scaling step is used from time to - time, enough to verify that it works. - - This means that bzip2-1.0.3 and later will only produce - Huffman codes with a maximum length of 17 bits. However, in - order to preserve backwards compatibility with bitstreams - produced by versions pre-1.0.3, the decompressor must still - handle lengths of up to 20. */ - - for (i = 1; i <= alphaSize; i++) { - j = weight[i] >> 8; - j = 1 + (j / 2); - weight[i] = j << 8; - } - } -} - - -/*---------------------------------------------------*/ -void BZ2_hbAssignCodes ( Int32 *code, - UChar *length, - Int32 minLen, - Int32 maxLen, - Int32 alphaSize ) -{ - Int32 n, vec, i; - - vec = 0; - for (n = minLen; n <= maxLen; n++) { - for (i = 0; i < alphaSize; i++) - if (length[i] == n) { code[i] = vec; vec++; }; - vec <<= 1; - } -} - - -/*---------------------------------------------------*/ -void BZ2_hbCreateDecodeTables ( Int32 *limit, - Int32 *base, - Int32 *perm, - UChar *length, - Int32 minLen, - Int32 maxLen, - Int32 alphaSize ) -{ - Int32 pp, i, j, vec; - - pp = 0; - for (i = minLen; i <= maxLen; i++) - for (j = 0; j < alphaSize; j++) - if (length[j] == i) { perm[pp] = j; pp++; }; - - for (i = 0; i < BZ_MAX_CODE_LEN; i++) base[i] = 0; - for (i = 0; i < alphaSize; i++) base[length[i]+1]++; - - for (i = 1; i < BZ_MAX_CODE_LEN; i++) base[i] += base[i-1]; - - for (i = 0; i < BZ_MAX_CODE_LEN; i++) limit[i] = 0; - vec = 0; - - for (i = minLen; i <= maxLen; i++) { - vec += (base[i+1] - base[i]); - limit[i] = vec-1; - vec <<= 1; - } - for (i = minLen + 1; i <= maxLen; i++) - base[i] = ((limit[i-1] + 1) << 1) - base[i]; -} - - -/*-------------------------------------------------------------*/ -/*--- end huffman.c ---*/ -/*-------------------------------------------------------------*/ diff --git a/dep/StormLib/src/bzip2/randtable.c b/dep/StormLib/src/bzip2/randtable.c deleted file mode 100644 index 068b76367bc..00000000000 --- a/dep/StormLib/src/bzip2/randtable.c +++ /dev/null @@ -1,84 +0,0 @@ - -/*-------------------------------------------------------------*/ -/*--- Table for randomising repetitive blocks ---*/ -/*--- randtable.c ---*/ -/*-------------------------------------------------------------*/ - -/* ------------------------------------------------------------------ - This file is part of bzip2/libbzip2, a program and library for - lossless, block-sorting data compression. - - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward - - Please read the WARNING, DISCLAIMER and PATENTS sections in the - README file. - - This program is released under the terms of the license contained - in the file LICENSE. - ------------------------------------------------------------------ */ - - -#include "bzlib_private.h" - - -/*---------------------------------------------*/ -Int32 BZ2_rNums[512] = { - 619, 720, 127, 481, 931, 816, 813, 233, 566, 247, - 985, 724, 205, 454, 863, 491, 741, 242, 949, 214, - 733, 859, 335, 708, 621, 574, 73, 654, 730, 472, - 419, 436, 278, 496, 867, 210, 399, 680, 480, 51, - 878, 465, 811, 169, 869, 675, 611, 697, 867, 561, - 862, 687, 507, 283, 482, 129, 807, 591, 733, 623, - 150, 238, 59, 379, 684, 877, 625, 169, 643, 105, - 170, 607, 520, 932, 727, 476, 693, 425, 174, 647, - 73, 122, 335, 530, 442, 853, 695, 249, 445, 515, - 909, 545, 703, 919, 874, 474, 882, 500, 594, 612, - 641, 801, 220, 162, 819, 984, 589, 513, 495, 799, - 161, 604, 958, 533, 221, 400, 386, 867, 600, 782, - 382, 596, 414, 171, 516, 375, 682, 485, 911, 276, - 98, 553, 163, 354, 666, 933, 424, 341, 533, 870, - 227, 730, 475, 186, 263, 647, 537, 686, 600, 224, - 469, 68, 770, 919, 190, 373, 294, 822, 808, 206, - 184, 943, 795, 384, 383, 461, 404, 758, 839, 887, - 715, 67, 618, 276, 204, 918, 873, 777, 604, 560, - 951, 160, 578, 722, 79, 804, 96, 409, 713, 940, - 652, 934, 970, 447, 318, 353, 859, 672, 112, 785, - 645, 863, 803, 350, 139, 93, 354, 99, 820, 908, - 609, 772, 154, 274, 580, 184, 79, 626, 630, 742, - 653, 282, 762, 623, 680, 81, 927, 626, 789, 125, - 411, 521, 938, 300, 821, 78, 343, 175, 128, 250, - 170, 774, 972, 275, 999, 639, 495, 78, 352, 126, - 857, 956, 358, 619, 580, 124, 737, 594, 701, 612, - 669, 112, 134, 694, 363, 992, 809, 743, 168, 974, - 944, 375, 748, 52, 600, 747, 642, 182, 862, 81, - 344, 805, 988, 739, 511, 655, 814, 334, 249, 515, - 897, 955, 664, 981, 649, 113, 974, 459, 893, 228, - 433, 837, 553, 268, 926, 240, 102, 654, 459, 51, - 686, 754, 806, 760, 493, 403, 415, 394, 687, 700, - 946, 670, 656, 610, 738, 392, 760, 799, 887, 653, - 978, 321, 576, 617, 626, 502, 894, 679, 243, 440, - 680, 879, 194, 572, 640, 724, 926, 56, 204, 700, - 707, 151, 457, 449, 797, 195, 791, 558, 945, 679, - 297, 59, 87, 824, 713, 663, 412, 693, 342, 606, - 134, 108, 571, 364, 631, 212, 174, 643, 304, 329, - 343, 97, 430, 751, 497, 314, 983, 374, 822, 928, - 140, 206, 73, 263, 980, 736, 876, 478, 430, 305, - 170, 514, 364, 692, 829, 82, 855, 953, 676, 246, - 369, 970, 294, 750, 807, 827, 150, 790, 288, 923, - 804, 378, 215, 828, 592, 281, 565, 555, 710, 82, - 896, 831, 547, 261, 524, 462, 293, 465, 502, 56, - 661, 821, 976, 991, 658, 869, 905, 758, 745, 193, - 768, 550, 608, 933, 378, 286, 215, 979, 792, 961, - 61, 688, 793, 644, 986, 403, 106, 366, 905, 644, - 372, 567, 466, 434, 645, 210, 389, 550, 919, 135, - 780, 773, 635, 389, 707, 100, 626, 958, 165, 504, - 920, 176, 193, 713, 857, 265, 203, 50, 668, 108, - 645, 990, 626, 197, 510, 357, 358, 850, 858, 364, - 936, 638 -}; - - -/*-------------------------------------------------------------*/ -/*--- end randtable.c ---*/ -/*-------------------------------------------------------------*/ diff --git a/dep/StormLib/src/zlib/adler32.c b/dep/StormLib/src/zlib/adler32.c deleted file mode 100644 index 007ba26277c..00000000000 --- a/dep/StormLib/src/zlib/adler32.c +++ /dev/null @@ -1,149 +0,0 @@ -/* adler32.c -- compute the Adler-32 checksum of a data stream - * Copyright (C) 1995-2004 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#define ZLIB_INTERNAL -#include "zlib.h" - -#define BASE 65521UL /* largest prime smaller than 65536 */ -#define NMAX 5552 -/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ - -#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} -#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); -#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); -#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); -#define DO16(buf) DO8(buf,0); DO8(buf,8); - -/* use NO_DIVIDE if your processor does not do division in hardware */ -#ifdef NO_DIVIDE -# define MOD(a) \ - do { \ - if (a >= (BASE << 16)) a -= (BASE << 16); \ - if (a >= (BASE << 15)) a -= (BASE << 15); \ - if (a >= (BASE << 14)) a -= (BASE << 14); \ - if (a >= (BASE << 13)) a -= (BASE << 13); \ - if (a >= (BASE << 12)) a -= (BASE << 12); \ - if (a >= (BASE << 11)) a -= (BASE << 11); \ - if (a >= (BASE << 10)) a -= (BASE << 10); \ - if (a >= (BASE << 9)) a -= (BASE << 9); \ - if (a >= (BASE << 8)) a -= (BASE << 8); \ - if (a >= (BASE << 7)) a -= (BASE << 7); \ - if (a >= (BASE << 6)) a -= (BASE << 6); \ - if (a >= (BASE << 5)) a -= (BASE << 5); \ - if (a >= (BASE << 4)) a -= (BASE << 4); \ - if (a >= (BASE << 3)) a -= (BASE << 3); \ - if (a >= (BASE << 2)) a -= (BASE << 2); \ - if (a >= (BASE << 1)) a -= (BASE << 1); \ - if (a >= BASE) a -= BASE; \ - } while (0) -# define MOD4(a) \ - do { \ - if (a >= (BASE << 4)) a -= (BASE << 4); \ - if (a >= (BASE << 3)) a -= (BASE << 3); \ - if (a >= (BASE << 2)) a -= (BASE << 2); \ - if (a >= (BASE << 1)) a -= (BASE << 1); \ - if (a >= BASE) a -= BASE; \ - } while (0) -#else -# define MOD(a) a %= BASE -# define MOD4(a) a %= BASE -#endif - -/* ========================================================================= */ -uLong ZEXPORT adler32(adler, buf, len) - uLong adler; - const Bytef *buf; - uInt len; -{ - unsigned long sum2; - unsigned n; - - /* split Adler-32 into component sums */ - sum2 = (adler >> 16) & 0xffff; - adler &= 0xffff; - - /* in case user likes doing a byte at a time, keep it fast */ - if (len == 1) { - adler += buf[0]; - if (adler >= BASE) - adler -= BASE; - sum2 += adler; - if (sum2 >= BASE) - sum2 -= BASE; - return adler | (sum2 << 16); - } - - /* initial Adler-32 value (deferred check for len == 1 speed) */ - if (buf == Z_NULL) - return 1L; - - /* in case short lengths are provided, keep it somewhat fast */ - if (len < 16) { - while (len--) { - adler += *buf++; - sum2 += adler; - } - if (adler >= BASE) - adler -= BASE; - MOD4(sum2); /* only added so many BASE's */ - return adler | (sum2 << 16); - } - - /* do length NMAX blocks -- requires just one modulo operation */ - while (len >= NMAX) { - len -= NMAX; - n = NMAX / 16; /* NMAX is divisible by 16 */ - do { - DO16(buf); /* 16 sums unrolled */ - buf += 16; - } while (--n); - MOD(adler); - MOD(sum2); - } - - /* do remaining bytes (less than NMAX, still just one modulo) */ - if (len) { /* avoid modulos if none remaining */ - while (len >= 16) { - len -= 16; - DO16(buf); - buf += 16; - } - while (len--) { - adler += *buf++; - sum2 += adler; - } - MOD(adler); - MOD(sum2); - } - - /* return recombined sums */ - return adler | (sum2 << 16); -} - -/* ========================================================================= */ -uLong ZEXPORT adler32_combine(adler1, adler2, len2) - uLong adler1; - uLong adler2; - z_off_t len2; -{ - unsigned long sum1; - unsigned long sum2; - unsigned rem; - - /* the derivation of this formula is left as an exercise for the reader */ - rem = (unsigned)(len2 % BASE); - sum1 = adler1 & 0xffff; - sum2 = rem * sum1; - MOD(sum2); - sum1 += (adler2 & 0xffff) + BASE - 1; - sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; - if (sum1 > BASE) sum1 -= BASE; - if (sum1 > BASE) sum1 -= BASE; - if (sum2 > (BASE << 1)) sum2 -= (BASE << 1); - if (sum2 > BASE) sum2 -= BASE; - return sum1 | (sum2 << 16); -} diff --git a/dep/StormLib/src/zlib/compress2.c b/dep/StormLib/src/zlib/compress2.c deleted file mode 100644 index df04f0148e6..00000000000 --- a/dep/StormLib/src/zlib/compress2.c +++ /dev/null @@ -1,79 +0,0 @@ -/* compress.c -- compress a memory buffer - * Copyright (C) 1995-2003 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#define ZLIB_INTERNAL -#include "zlib.h" - -/* =========================================================================== - Compresses the source buffer into the destination buffer. The level - parameter has the same meaning as in deflateInit. sourceLen is the byte - length of the source buffer. Upon entry, destLen is the total size of the - destination buffer, which must be at least 0.1% larger than sourceLen plus - 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. - - compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_BUF_ERROR if there was not enough room in the output buffer, - Z_STREAM_ERROR if the level parameter is invalid. -*/ -int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) - Bytef *dest; - uLongf *destLen; - const Bytef *source; - uLong sourceLen; - int level; -{ - z_stream stream; - int err; - - stream.next_in = (Bytef*)source; - stream.avail_in = (uInt)sourceLen; -#ifdef MAXSEG_64K - /* Check for source > 64K on 16-bit machine: */ - if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; -#endif - stream.next_out = dest; - stream.avail_out = (uInt)*destLen; - if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; - - stream.zalloc = (alloc_func)0; - stream.zfree = (free_func)0; - stream.opaque = (voidpf)0; - - err = deflateInit(&stream, level); - if (err != Z_OK) return err; - - err = deflate(&stream, Z_FINISH); - if (err != Z_STREAM_END) { - deflateEnd(&stream); - return err == Z_OK ? Z_BUF_ERROR : err; - } - *destLen = stream.total_out; - - err = deflateEnd(&stream); - return err; -} - -/* =========================================================================== - */ -int ZEXPORT compress (dest, destLen, source, sourceLen) - Bytef *dest; - uLongf *destLen; - const Bytef *source; - uLong sourceLen; -{ - return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); -} - -/* =========================================================================== - If the default memLevel or windowBits for deflateInit() is changed, then - this function needs to be updated. - */ -uLong ZEXPORT compressBound (sourceLen) - uLong sourceLen; -{ - return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11; -} diff --git a/dep/StormLib/src/zlib/crc32.c b/dep/StormLib/src/zlib/crc32.c deleted file mode 100644 index f658a9ef55e..00000000000 --- a/dep/StormLib/src/zlib/crc32.c +++ /dev/null @@ -1,423 +0,0 @@ -/* crc32.c -- compute the CRC-32 of a data stream - * Copyright (C) 1995-2005 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - * - * Thanks to Rodney Brown for his contribution of faster - * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing - * tables for updating the shift register in one step with three exclusive-ors - * instead of four steps with four exclusive-ors. This results in about a - * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. - */ - -/* @(#) $Id$ */ - -/* - Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore - protection on the static variables used to control the first-use generation - of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should - first call get_crc_table() to initialize the tables before allowing more than - one thread to use crc32(). - */ - -#ifdef MAKECRCH -# include -# ifndef DYNAMIC_CRC_TABLE -# define DYNAMIC_CRC_TABLE -# endif /* !DYNAMIC_CRC_TABLE */ -#endif /* MAKECRCH */ - -#include "zutil.h" /* for STDC and FAR definitions */ - -#define local static - -/* Find a four-byte integer type for crc32_little() and crc32_big(). */ -#ifndef NOBYFOUR -# ifdef STDC /* need ANSI C limits.h to determine sizes */ -# include -# define BYFOUR -# if (UINT_MAX == 0xffffffffUL) - typedef unsigned int u4; -# else -# if (ULONG_MAX == 0xffffffffUL) - typedef unsigned long u4; -# else -# if (USHRT_MAX == 0xffffffffUL) - typedef unsigned short u4; -# else -# undef BYFOUR /* can't find a four-byte integer type! */ -# endif -# endif -# endif -# endif /* STDC */ -#endif /* !NOBYFOUR */ - -/* Definitions for doing the crc four data bytes at a time. */ -#ifdef BYFOUR -# define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \ - (((w)&0xff00)<<8)+(((w)&0xff)<<24)) - local unsigned long crc32_little OF((unsigned long, - const unsigned char FAR *, unsigned)); - local unsigned long crc32_big OF((unsigned long, - const unsigned char FAR *, unsigned)); -# define TBLS 8 -#else -# define TBLS 1 -#endif /* BYFOUR */ - -/* Local functions for crc concatenation */ -local unsigned long gf2_matrix_times OF((unsigned long *mat, - unsigned long vec)); -local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); - -#ifdef DYNAMIC_CRC_TABLE - -local volatile int crc_table_empty = 1; -local unsigned long FAR crc_table[TBLS][256]; -local void make_crc_table OF((void)); -#ifdef MAKECRCH - local void write_table OF((FILE *, const unsigned long FAR *)); -#endif /* MAKECRCH */ -/* - Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: - x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. - - Polynomials over GF(2) are represented in binary, one bit per coefficient, - with the lowest powers in the most significant bit. Then adding polynomials - is just exclusive-or, and multiplying a polynomial by x is a right shift by - one. If we call the above polynomial p, and represent a byte as the - polynomial q, also with the lowest power in the most significant bit (so the - byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, - where a mod b means the remainder after dividing a by b. - - This calculation is done using the shift-register method of multiplying and - taking the remainder. The register is initialized to zero, and for each - incoming bit, x^32 is added mod p to the register if the bit is a one (where - x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by - x (which is shifting right by one and adding x^32 mod p if the bit shifted - out is a one). We start with the highest power (least significant bit) of - q and repeat for all eight bits of q. - - The first table is simply the CRC of all possible eight bit values. This is - all the information needed to generate CRCs on data a byte at a time for all - combinations of CRC register values and incoming bytes. The remaining tables - allow for word-at-a-time CRC calculation for both big-endian and little- - endian machines, where a word is four bytes. -*/ -local void make_crc_table() -{ - unsigned long c; - int n, k; - unsigned long poly; /* polynomial exclusive-or pattern */ - /* terms of polynomial defining this crc (except x^32): */ - static volatile int first = 1; /* flag to limit concurrent making */ - static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; - - /* See if another task is already doing this (not thread-safe, but better - than nothing -- significantly reduces duration of vulnerability in - case the advice about DYNAMIC_CRC_TABLE is ignored) */ - if (first) { - first = 0; - - /* make exclusive-or pattern from polynomial (0xedb88320UL) */ - poly = 0UL; - for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++) - poly |= 1UL << (31 - p[n]); - - /* generate a crc for every 8-bit value */ - for (n = 0; n < 256; n++) { - c = (unsigned long)n; - for (k = 0; k < 8; k++) - c = c & 1 ? poly ^ (c >> 1) : c >> 1; - crc_table[0][n] = c; - } - -#ifdef BYFOUR - /* generate crc for each value followed by one, two, and three zeros, - and then the byte reversal of those as well as the first table */ - for (n = 0; n < 256; n++) { - c = crc_table[0][n]; - crc_table[4][n] = REV(c); - for (k = 1; k < 4; k++) { - c = crc_table[0][c & 0xff] ^ (c >> 8); - crc_table[k][n] = c; - crc_table[k + 4][n] = REV(c); - } - } -#endif /* BYFOUR */ - - crc_table_empty = 0; - } - else { /* not first */ - /* wait for the other guy to finish (not efficient, but rare) */ - while (crc_table_empty) - ; - } - -#ifdef MAKECRCH - /* write out CRC tables to crc32.h */ - { - FILE *out; - - out = fopen("crc32.h", "w"); - if (out == NULL) return; - fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n"); - fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); - fprintf(out, "local const unsigned long FAR "); - fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); - write_table(out, crc_table[0]); -# ifdef BYFOUR - fprintf(out, "#ifdef BYFOUR\n"); - for (k = 1; k < 8; k++) { - fprintf(out, " },\n {\n"); - write_table(out, crc_table[k]); - } - fprintf(out, "#endif\n"); -# endif /* BYFOUR */ - fprintf(out, " }\n};\n"); - fclose(out); - } -#endif /* MAKECRCH */ -} - -#ifdef MAKECRCH -local void write_table(out, table) - FILE *out; - const unsigned long FAR *table; -{ - int n; - - for (n = 0; n < 256; n++) - fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n], - n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); -} -#endif /* MAKECRCH */ - -#else /* !DYNAMIC_CRC_TABLE */ -/* ======================================================================== - * Tables of CRC-32s of all single-byte values, made by make_crc_table(). - */ -#include "crc32.h" -#endif /* DYNAMIC_CRC_TABLE */ - -/* ========================================================================= - * This function can be used by asm versions of crc32() - */ -const unsigned long FAR * ZEXPORT get_crc_table() -{ -#ifdef DYNAMIC_CRC_TABLE - if (crc_table_empty) - make_crc_table(); -#endif /* DYNAMIC_CRC_TABLE */ - return (const unsigned long FAR *)crc_table; -} - -/* ========================================================================= */ -#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) -#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 - -/* ========================================================================= */ -unsigned long ZEXPORT crc32(crc, buf, len) - unsigned long crc; - const unsigned char FAR *buf; - unsigned len; -{ - if (buf == Z_NULL) return 0UL; - -#ifdef DYNAMIC_CRC_TABLE - if (crc_table_empty) - make_crc_table(); -#endif /* DYNAMIC_CRC_TABLE */ - -#ifdef BYFOUR - if (sizeof(void *) == sizeof(ptrdiff_t)) { - u4 endian; - - endian = 1; - if (*((unsigned char *)(&endian))) - return crc32_little(crc, buf, len); - else - return crc32_big(crc, buf, len); - } -#endif /* BYFOUR */ - crc = crc ^ 0xffffffffUL; - while (len >= 8) { - DO8; - len -= 8; - } - if (len) do { - DO1; - } while (--len); - return crc ^ 0xffffffffUL; -} - -#ifdef BYFOUR - -/* ========================================================================= */ -#define DOLIT4 c ^= *buf4++; \ - c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ - crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] -#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 - -/* ========================================================================= */ -local unsigned long crc32_little(crc, buf, len) - unsigned long crc; - const unsigned char FAR *buf; - unsigned len; -{ - register u4 c; - register const u4 FAR *buf4; - - c = (u4)crc; - c = ~c; - while (len && ((ptrdiff_t)buf & 3)) { - c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); - len--; - } - - buf4 = (const u4 FAR *)(const void FAR *)buf; - while (len >= 32) { - DOLIT32; - len -= 32; - } - while (len >= 4) { - DOLIT4; - len -= 4; - } - buf = (const unsigned char FAR *)buf4; - - if (len) do { - c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); - } while (--len); - c = ~c; - return (unsigned long)c; -} - -/* ========================================================================= */ -#define DOBIG4 c ^= *++buf4; \ - c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ - crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] -#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 - -/* ========================================================================= */ -local unsigned long crc32_big(crc, buf, len) - unsigned long crc; - const unsigned char FAR *buf; - unsigned len; -{ - register u4 c; - register const u4 FAR *buf4; - - c = REV((u4)crc); - c = ~c; - while (len && ((ptrdiff_t)buf & 3)) { - c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); - len--; - } - - buf4 = (const u4 FAR *)(const void FAR *)buf; - buf4--; - while (len >= 32) { - DOBIG32; - len -= 32; - } - while (len >= 4) { - DOBIG4; - len -= 4; - } - buf4++; - buf = (const unsigned char FAR *)buf4; - - if (len) do { - c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); - } while (--len); - c = ~c; - return (unsigned long)(REV(c)); -} - -#endif /* BYFOUR */ - -#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */ - -/* ========================================================================= */ -local unsigned long gf2_matrix_times(mat, vec) - unsigned long *mat; - unsigned long vec; -{ - unsigned long sum; - - sum = 0; - while (vec) { - if (vec & 1) - sum ^= *mat; - vec >>= 1; - mat++; - } - return sum; -} - -/* ========================================================================= */ -local void gf2_matrix_square(square, mat) - unsigned long *square; - unsigned long *mat; -{ - int n; - - for (n = 0; n < GF2_DIM; n++) - square[n] = gf2_matrix_times(mat, mat[n]); -} - -/* ========================================================================= */ -uLong ZEXPORT crc32_combine(crc1, crc2, len2) - uLong crc1; - uLong crc2; - z_off_t len2; -{ - int n; - unsigned long row; - unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ - unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ - - /* degenerate case */ - if (len2 == 0) - return crc1; - - /* put operator for one zero bit in odd */ - odd[0] = 0xedb88320L; /* CRC-32 polynomial */ - row = 1; - for (n = 1; n < GF2_DIM; n++) { - odd[n] = row; - row <<= 1; - } - - /* put operator for two zero bits in even */ - gf2_matrix_square(even, odd); - - /* put operator for four zero bits in odd */ - gf2_matrix_square(odd, even); - - /* apply len2 zeros to crc1 (first square will put the operator for one - zero byte, eight zero bits, in even) */ - do { - /* apply zeros operator for this bit of len2 */ - gf2_matrix_square(even, odd); - if (len2 & 1) - crc1 = gf2_matrix_times(even, crc1); - len2 >>= 1; - - /* if no more bits set, then done */ - if (len2 == 0) - break; - - /* another iteration of the loop with odd and even swapped */ - gf2_matrix_square(odd, even); - if (len2 & 1) - crc1 = gf2_matrix_times(odd, crc1); - len2 >>= 1; - - /* if no more bits set, then done */ - } while (len2 != 0); - - /* return combined crc */ - crc1 ^= crc2; - return crc1; -} diff --git a/dep/StormLib/src/zlib/crc32.h b/dep/StormLib/src/zlib/crc32.h deleted file mode 100644 index 8053b6117c0..00000000000 --- a/dep/StormLib/src/zlib/crc32.h +++ /dev/null @@ -1,441 +0,0 @@ -/* crc32.h -- tables for rapid CRC calculation - * Generated automatically by crc32.c - */ - -local const unsigned long FAR crc_table[TBLS][256] = -{ - { - 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, - 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, - 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, - 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, - 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, - 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, - 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, - 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, - 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, - 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, - 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, - 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, - 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, - 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, - 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, - 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, - 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, - 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, - 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, - 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, - 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, - 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, - 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, - 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, - 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, - 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, - 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, - 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, - 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, - 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, - 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, - 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, - 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, - 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, - 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, - 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, - 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, - 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, - 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, - 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, - 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, - 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, - 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, - 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, - 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, - 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, - 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, - 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, - 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, - 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, - 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, - 0x2d02ef8dUL -#ifdef BYFOUR - }, - { - 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL, - 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL, - 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL, - 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL, - 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL, - 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL, - 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL, - 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL, - 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL, - 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL, - 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL, - 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL, - 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL, - 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL, - 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL, - 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL, - 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL, - 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL, - 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL, - 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL, - 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL, - 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL, - 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL, - 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL, - 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL, - 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL, - 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL, - 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL, - 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL, - 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL, - 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL, - 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL, - 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL, - 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL, - 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL, - 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL, - 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL, - 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL, - 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL, - 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL, - 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL, - 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL, - 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL, - 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL, - 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL, - 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL, - 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL, - 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL, - 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL, - 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL, - 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL, - 0x9324fd72UL - }, - { - 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL, - 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL, - 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL, - 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL, - 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL, - 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL, - 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL, - 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL, - 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL, - 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL, - 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL, - 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL, - 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL, - 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL, - 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL, - 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL, - 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL, - 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL, - 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL, - 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL, - 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL, - 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL, - 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL, - 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL, - 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL, - 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL, - 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL, - 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL, - 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL, - 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL, - 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL, - 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL, - 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL, - 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL, - 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL, - 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL, - 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL, - 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL, - 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL, - 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL, - 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL, - 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL, - 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL, - 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL, - 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL, - 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL, - 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL, - 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL, - 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL, - 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL, - 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL, - 0xbe9834edUL - }, - { - 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL, - 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL, - 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL, - 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL, - 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL, - 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL, - 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL, - 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL, - 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL, - 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL, - 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL, - 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL, - 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL, - 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL, - 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL, - 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL, - 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL, - 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL, - 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL, - 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL, - 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL, - 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL, - 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL, - 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL, - 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL, - 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL, - 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL, - 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL, - 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL, - 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL, - 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL, - 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL, - 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL, - 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL, - 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL, - 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL, - 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL, - 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL, - 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL, - 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL, - 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL, - 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL, - 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL, - 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL, - 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL, - 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL, - 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL, - 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL, - 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL, - 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL, - 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL, - 0xde0506f1UL - }, - { - 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL, - 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL, - 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL, - 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL, - 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL, - 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL, - 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL, - 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL, - 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL, - 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL, - 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL, - 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL, - 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL, - 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL, - 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL, - 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL, - 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL, - 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL, - 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL, - 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL, - 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL, - 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL, - 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL, - 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL, - 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL, - 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL, - 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL, - 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL, - 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL, - 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL, - 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL, - 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL, - 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL, - 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL, - 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL, - 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL, - 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL, - 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL, - 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL, - 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL, - 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL, - 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL, - 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL, - 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL, - 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL, - 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL, - 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL, - 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL, - 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL, - 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL, - 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL, - 0x8def022dUL - }, - { - 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL, - 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL, - 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL, - 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL, - 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL, - 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL, - 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL, - 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL, - 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL, - 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL, - 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL, - 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL, - 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL, - 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL, - 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL, - 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL, - 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL, - 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL, - 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL, - 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL, - 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL, - 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL, - 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL, - 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL, - 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL, - 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL, - 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL, - 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL, - 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL, - 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL, - 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL, - 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL, - 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL, - 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL, - 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL, - 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL, - 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL, - 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL, - 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL, - 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL, - 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL, - 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL, - 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL, - 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL, - 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL, - 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL, - 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL, - 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL, - 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL, - 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL, - 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL, - 0x72fd2493UL - }, - { - 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL, - 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL, - 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL, - 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL, - 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL, - 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL, - 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL, - 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL, - 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL, - 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL, - 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL, - 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL, - 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL, - 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL, - 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL, - 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL, - 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL, - 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL, - 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL, - 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL, - 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL, - 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL, - 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL, - 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL, - 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL, - 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL, - 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL, - 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL, - 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL, - 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL, - 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL, - 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL, - 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL, - 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL, - 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL, - 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL, - 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL, - 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL, - 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL, - 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL, - 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL, - 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL, - 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL, - 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL, - 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL, - 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL, - 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL, - 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL, - 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL, - 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL, - 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL, - 0xed3498beUL - }, - { - 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL, - 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL, - 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL, - 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL, - 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL, - 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL, - 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL, - 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL, - 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL, - 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL, - 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL, - 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL, - 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL, - 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL, - 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL, - 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL, - 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL, - 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL, - 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL, - 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL, - 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL, - 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL, - 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL, - 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL, - 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL, - 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL, - 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL, - 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL, - 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL, - 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL, - 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL, - 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL, - 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL, - 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL, - 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL, - 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL, - 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL, - 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL, - 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL, - 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL, - 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL, - 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL, - 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL, - 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL, - 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL, - 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL, - 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL, - 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL, - 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL, - 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL, - 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL, - 0xf10605deUL -#endif - } -}; diff --git a/dep/StormLib/src/zlib/deflate.c b/dep/StormLib/src/zlib/deflate.c deleted file mode 100644 index 29ce1f64a57..00000000000 --- a/dep/StormLib/src/zlib/deflate.c +++ /dev/null @@ -1,1736 +0,0 @@ -/* deflate.c -- compress data using the deflation algorithm - * Copyright (C) 1995-2005 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - * ALGORITHM - * - * The "deflation" process depends on being able to identify portions - * of the input text which are identical to earlier input (within a - * sliding window trailing behind the input currently being processed). - * - * The most straightforward technique turns out to be the fastest for - * most input files: try all possible matches and select the longest. - * The key feature of this algorithm is that insertions into the string - * dictionary are very simple and thus fast, and deletions are avoided - * completely. Insertions are performed at each input character, whereas - * string matches are performed only when the previous match ends. So it - * is preferable to spend more time in matches to allow very fast string - * insertions and avoid deletions. The matching algorithm for small - * strings is inspired from that of Rabin & Karp. A brute force approach - * is used to find longer strings when a small match has been found. - * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze - * (by Leonid Broukhis). - * A previous version of this file used a more sophisticated algorithm - * (by Fiala and Greene) which is guaranteed to run in linear amortized - * time, but has a larger average cost, uses more memory and is patented. - * However the F&G algorithm may be faster for some highly redundant - * files if the parameter max_chain_length (described below) is too large. - * - * ACKNOWLEDGEMENTS - * - * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and - * I found it in 'freeze' written by Leonid Broukhis. - * Thanks to many people for bug reports and testing. - * - * REFERENCES - * - * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". - * Available in http://www.ietf.org/rfc/rfc1951.txt - * - * A description of the Rabin and Karp algorithm is given in the book - * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. - * - * Fiala,E.R., and Greene,D.H. - * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 - * - */ - -/* @(#) $Id$ */ - -#include "deflate.h" - -const char deflate_copyright[] = - " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly "; -/* - If you use the zlib library in a product, an acknowledgment is welcome - in the documentation of your product. If for some reason you cannot - include such an acknowledgment, I would appreciate that you keep this - copyright string in the executable of your product. - */ - -/* =========================================================================== - * Function prototypes. - */ -typedef enum { - need_more, /* block not completed, need more input or more output */ - block_done, /* block flush performed */ - finish_started, /* finish started, need only more output at next deflate */ - finish_done /* finish done, accept no more input or output */ -} block_state; - -typedef block_state (*compress_func) OF((deflate_state *s, int flush)); -/* Compression function. Returns the block state after the call. */ - -local void fill_window OF((deflate_state *s)); -local block_state deflate_stored OF((deflate_state *s, int flush)); -local block_state deflate_fast OF((deflate_state *s, int flush)); -#ifndef FASTEST -local block_state deflate_slow OF((deflate_state *s, int flush)); -#endif -local void lm_init OF((deflate_state *s)); -local void putShortMSB OF((deflate_state *s, uInt b)); -local void flush_pending OF((z_streamp strm)); -local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); -#ifndef FASTEST -#ifdef ASMV - void match_init OF((void)); /* asm code initialization */ - uInt longest_match OF((deflate_state *s, IPos cur_match)); -#else -local uInt longest_match OF((deflate_state *s, IPos cur_match)); -#endif -#endif -local uInt longest_match_fast OF((deflate_state *s, IPos cur_match)); - -#ifdef DEBUG -local void check_match OF((deflate_state *s, IPos start, IPos match, - int length)); -#endif - -/* =========================================================================== - * Local data - */ - -#define NIL 0 -/* Tail of hash chains */ - -#ifndef TOO_FAR -# define TOO_FAR 4096 -#endif -/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ - -#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) -/* Minimum amount of lookahead, except at the end of the input file. - * See deflate.c for comments about the MIN_MATCH+1. - */ - -/* Values for max_lazy_match, good_match and max_chain_length, depending on - * the desired pack level (0..9). The values given below have been tuned to - * exclude worst case performance for pathological files. Better values may be - * found for specific files. - */ -typedef struct config_s { - ush good_length; /* reduce lazy search above this match length */ - ush max_lazy; /* do not perform lazy search above this match length */ - ush nice_length; /* quit search above this match length */ - ush max_chain; - compress_func func; -} config; - -#ifdef FASTEST -local const config configuration_table[2] = { -/* good lazy nice chain */ -/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ -/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ -#else -local const config configuration_table[10] = { -/* good lazy nice chain */ -/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ -/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ -/* 2 */ {4, 5, 16, 8, deflate_fast}, -/* 3 */ {4, 6, 32, 32, deflate_fast}, - -/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ -/* 5 */ {8, 16, 32, 32, deflate_slow}, -/* 6 */ {8, 16, 128, 128, deflate_slow}, -/* 7 */ {8, 32, 128, 256, deflate_slow}, -/* 8 */ {32, 128, 258, 1024, deflate_slow}, -/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ -#endif - -/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 - * For deflate_fast() (levels <= 3) good is ignored and lazy has a different - * meaning. - */ - -#define EQUAL 0 -/* result of memcmp for equal strings */ - -#ifndef NO_DUMMY_DECL -struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ -#endif - -/* =========================================================================== - * Update a hash value with the given input byte - * IN assertion: all calls to to UPDATE_HASH are made with consecutive - * input characters, so that a running hash key can be computed from the - * previous key instead of complete recalculation each time. - */ -#define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) - - -/* =========================================================================== - * Insert string str in the dictionary and set match_head to the previous head - * of the hash chain (the most recent string with same hash key). Return - * the previous length of the hash chain. - * If this file is compiled with -DFASTEST, the compression level is forced - * to 1, and no hash chains are maintained. - * IN assertion: all calls to to INSERT_STRING are made with consecutive - * input characters and the first MIN_MATCH bytes of str are valid - * (except for the last MIN_MATCH-1 bytes of the input file). - */ -#ifdef FASTEST -#define INSERT_STRING(s, str, match_head) \ - (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ - match_head = s->head[s->ins_h], \ - s->head[s->ins_h] = (Pos)(str)) -#else -#define INSERT_STRING(s, str, match_head) \ - (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ - match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ - s->head[s->ins_h] = (Pos)(str)) -#endif - -/* =========================================================================== - * Initialize the hash table (avoiding 64K overflow for 16 bit systems). - * prev[] will be initialized on the fly. - */ -#define CLEAR_HASH(s) \ - s->head[s->hash_size-1] = NIL; \ - zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); - -/* ========================================================================= */ -int ZEXPORT deflateInit_(strm, level, version, stream_size) - z_streamp strm; - int level; - const char *version; - int stream_size; -{ - return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, - Z_DEFAULT_STRATEGY, version, stream_size); - /* To do: ignore strm->next_in if we use it as window */ -} - -/* ========================================================================= */ -int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, - version, stream_size) - z_streamp strm; - int level; - int method; - int windowBits; - int memLevel; - int strategy; - const char *version; - int stream_size; -{ - deflate_state *s; - int wrap = 1; - static const char my_version[] = ZLIB_VERSION; - - ushf *overlay; - /* We overlay pending_buf and d_buf+l_buf. This works since the average - * output size for (length,distance) codes is <= 24 bits. - */ - - if (version == Z_NULL || version[0] != my_version[0] || - stream_size != sizeof(z_stream)) { - return Z_VERSION_ERROR; - } - if (strm == Z_NULL) return Z_STREAM_ERROR; - - strm->msg = Z_NULL; - if (strm->zalloc == (alloc_func)0) { - strm->zalloc = zcalloc; - strm->opaque = (voidpf)0; - } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; - -#ifdef FASTEST - if (level != 0) level = 1; -#else - if (level == Z_DEFAULT_COMPRESSION) level = 6; -#endif - - if (windowBits < 0) { /* suppress zlib wrapper */ - wrap = 0; - windowBits = -windowBits; - } -#ifdef GZIP - else if (windowBits > 15) { - wrap = 2; /* write gzip wrapper instead */ - windowBits -= 16; - } -#endif - if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || - windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || - strategy < 0 || strategy > Z_FIXED) { - return Z_STREAM_ERROR; - } - if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ - s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); - if (s == Z_NULL) return Z_MEM_ERROR; - strm->state = (struct internal_state FAR *)s; - s->strm = strm; - - s->wrap = wrap; - s->gzhead = Z_NULL; - s->w_bits = windowBits; - s->w_size = 1 << s->w_bits; - s->w_mask = s->w_size - 1; - - s->hash_bits = memLevel + 7; - s->hash_size = 1 << s->hash_bits; - s->hash_mask = s->hash_size - 1; - s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); - - s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); - s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); - s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); - - s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ - - overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); - s->pending_buf = (uchf *) overlay; - s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); - - if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || - s->pending_buf == Z_NULL) { - s->status = FINISH_STATE; - strm->msg = (char*)ERR_MSG(Z_MEM_ERROR); - deflateEnd (strm); - return Z_MEM_ERROR; - } - s->d_buf = overlay + s->lit_bufsize/sizeof(ush); - s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; - - s->level = level; - s->strategy = strategy; - s->method = (Byte)method; - - return deflateReset(strm); -} - -/* ========================================================================= */ -int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) - z_streamp strm; - const Bytef *dictionary; - uInt dictLength; -{ - deflate_state *s; - uInt length = dictLength; - uInt n; - IPos hash_head = 0; - - if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL || - strm->state->wrap == 2 || - (strm->state->wrap == 1 && strm->state->status != INIT_STATE)) - return Z_STREAM_ERROR; - - s = strm->state; - if (s->wrap) - strm->adler = adler32(strm->adler, dictionary, dictLength); - - if (length < MIN_MATCH) return Z_OK; - if (length > MAX_DIST(s)) { - length = MAX_DIST(s); - dictionary += dictLength - length; /* use the tail of the dictionary */ - } - zmemcpy(s->window, dictionary, length); - s->strstart = length; - s->block_start = (long)length; - - /* Insert all strings in the hash table (except for the last two bytes). - * s->lookahead stays null, so s->ins_h will be recomputed at the next - * call of fill_window. - */ - s->ins_h = s->window[0]; - UPDATE_HASH(s, s->ins_h, s->window[1]); - for (n = 0; n <= length - MIN_MATCH; n++) { - INSERT_STRING(s, n, hash_head); - } - if (hash_head) hash_head = 0; /* to make compiler happy */ - return Z_OK; -} - -/* ========================================================================= */ -int ZEXPORT deflateReset (strm) - z_streamp strm; -{ - deflate_state *s; - - if (strm == Z_NULL || strm->state == Z_NULL || - strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) { - return Z_STREAM_ERROR; - } - - strm->total_in = strm->total_out = 0; - strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ - strm->data_type = Z_UNKNOWN; - - s = (deflate_state *)strm->state; - s->pending = 0; - s->pending_out = s->pending_buf; - - if (s->wrap < 0) { - s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ - } - s->status = s->wrap ? INIT_STATE : BUSY_STATE; - strm->adler = -#ifdef GZIP - s->wrap == 2 ? crc32(0L, Z_NULL, 0) : -#endif - adler32(0L, Z_NULL, 0); - s->last_flush = Z_NO_FLUSH; - - _tr_init(s); - lm_init(s); - - return Z_OK; -} - -/* ========================================================================= */ -int ZEXPORT deflateSetHeader (strm, head) - z_streamp strm; - gz_headerp head; -{ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - if (strm->state->wrap != 2) return Z_STREAM_ERROR; - strm->state->gzhead = head; - return Z_OK; -} - -/* ========================================================================= */ -int ZEXPORT deflatePrime (strm, bits, value) - z_streamp strm; - int bits; - int value; -{ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - strm->state->bi_valid = bits; - strm->state->bi_buf = (ush)(value & ((1 << bits) - 1)); - return Z_OK; -} - -/* ========================================================================= */ -int ZEXPORT deflateParams(strm, level, strategy) - z_streamp strm; - int level; - int strategy; -{ - deflate_state *s; - compress_func func; - int err = Z_OK; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - s = strm->state; - -#ifdef FASTEST - if (level != 0) level = 1; -#else - if (level == Z_DEFAULT_COMPRESSION) level = 6; -#endif - if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { - return Z_STREAM_ERROR; - } - func = configuration_table[s->level].func; - - if (func != configuration_table[level].func && strm->total_in != 0) { - /* Flush the last buffer: */ - err = deflate(strm, Z_PARTIAL_FLUSH); - } - if (s->level != level) { - s->level = level; - s->max_lazy_match = configuration_table[level].max_lazy; - s->good_match = configuration_table[level].good_length; - s->nice_match = configuration_table[level].nice_length; - s->max_chain_length = configuration_table[level].max_chain; - } - s->strategy = strategy; - return err; -} - -/* ========================================================================= */ -int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) - z_streamp strm; - int good_length; - int max_lazy; - int nice_length; - int max_chain; -{ - deflate_state *s; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - s = strm->state; - s->good_match = good_length; - s->max_lazy_match = max_lazy; - s->nice_match = nice_length; - s->max_chain_length = max_chain; - return Z_OK; -} - -/* ========================================================================= - * For the default windowBits of 15 and memLevel of 8, this function returns - * a close to exact, as well as small, upper bound on the compressed size. - * They are coded as constants here for a reason--if the #define's are - * changed, then this function needs to be changed as well. The return - * value for 15 and 8 only works for those exact settings. - * - * For any setting other than those defaults for windowBits and memLevel, - * the value returned is a conservative worst case for the maximum expansion - * resulting from using fixed blocks instead of stored blocks, which deflate - * can emit on compressed data for some combinations of the parameters. - * - * This function could be more sophisticated to provide closer upper bounds - * for every combination of windowBits and memLevel, as well as wrap. - * But even the conservative upper bound of about 14% expansion does not - * seem onerous for output buffer allocation. - */ -uLong ZEXPORT deflateBound(strm, sourceLen) - z_streamp strm; - uLong sourceLen; -{ - deflate_state *s; - uLong destLen; - - /* conservative upper bound */ - destLen = sourceLen + - ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11; - - /* if can't get parameters, return conservative bound */ - if (strm == Z_NULL || strm->state == Z_NULL) - return destLen; - - /* if not default parameters, return conservative bound */ - s = strm->state; - if (s->w_bits != 15 || s->hash_bits != 8 + 7) - return destLen; - - /* default settings: return tight bound for that case */ - return compressBound(sourceLen); -} - -/* ========================================================================= - * Put a short in the pending buffer. The 16-bit value is put in MSB order. - * IN assertion: the stream state is correct and there is enough room in - * pending_buf. - */ -local void putShortMSB (s, b) - deflate_state *s; - uInt b; -{ - put_byte(s, (Byte)(b >> 8)); - put_byte(s, (Byte)(b & 0xff)); -} - -/* ========================================================================= - * Flush as much pending output as possible. All deflate() output goes - * through this function so some applications may wish to modify it - * to avoid allocating a large strm->next_out buffer and copying into it. - * (See also read_buf()). - */ -local void flush_pending(strm) - z_streamp strm; -{ - unsigned len = strm->state->pending; - - if (len > strm->avail_out) len = strm->avail_out; - if (len == 0) return; - - zmemcpy(strm->next_out, strm->state->pending_out, len); - strm->next_out += len; - strm->state->pending_out += len; - strm->total_out += len; - strm->avail_out -= len; - strm->state->pending -= len; - if (strm->state->pending == 0) { - strm->state->pending_out = strm->state->pending_buf; - } -} - -/* ========================================================================= */ -int ZEXPORT deflate (strm, flush) - z_streamp strm; - int flush; -{ - int old_flush; /* value of flush param for previous deflate call */ - deflate_state *s; - - if (strm == Z_NULL || strm->state == Z_NULL || - flush > Z_FINISH || flush < 0) { - return Z_STREAM_ERROR; - } - s = strm->state; - - if (strm->next_out == Z_NULL || - (strm->next_in == Z_NULL && strm->avail_in != 0) || - (s->status == FINISH_STATE && flush != Z_FINISH)) { - ERR_RETURN(strm, Z_STREAM_ERROR); - } - if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); - - s->strm = strm; /* just in case */ - old_flush = s->last_flush; - s->last_flush = flush; - - /* Write the header */ - if (s->status == INIT_STATE) { -#ifdef GZIP - if (s->wrap == 2) { - strm->adler = crc32(0L, Z_NULL, 0); - put_byte(s, 31); - put_byte(s, 139); - put_byte(s, 8); - if (s->gzhead == NULL) { - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, 0); - put_byte(s, s->level == 9 ? 2 : - (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? - 4 : 0)); - put_byte(s, OS_CODE); - s->status = BUSY_STATE; - } - else { - put_byte(s, (s->gzhead->text ? 1 : 0) + - (s->gzhead->hcrc ? 2 : 0) + - (s->gzhead->extra == Z_NULL ? 0 : 4) + - (s->gzhead->name == Z_NULL ? 0 : 8) + - (s->gzhead->comment == Z_NULL ? 0 : 16) - ); - put_byte(s, (Byte)(s->gzhead->time & 0xff)); - put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); - put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); - put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); - put_byte(s, s->level == 9 ? 2 : - (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? - 4 : 0)); - put_byte(s, s->gzhead->os & 0xff); - if (s->gzhead->extra != NULL) { - put_byte(s, s->gzhead->extra_len & 0xff); - put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); - } - if (s->gzhead->hcrc) - strm->adler = crc32(strm->adler, s->pending_buf, - s->pending); - s->gzindex = 0; - s->status = EXTRA_STATE; - } - } - else -#endif - { - uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; - uInt level_flags; - - if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) - level_flags = 0; - else if (s->level < 6) - level_flags = 1; - else if (s->level == 6) - level_flags = 2; - else - level_flags = 3; - header |= (level_flags << 6); - if (s->strstart != 0) header |= PRESET_DICT; - header += 31 - (header % 31); - - s->status = BUSY_STATE; - putShortMSB(s, header); - - /* Save the adler32 of the preset dictionary: */ - if (s->strstart != 0) { - putShortMSB(s, (uInt)(strm->adler >> 16)); - putShortMSB(s, (uInt)(strm->adler & 0xffff)); - } - strm->adler = adler32(0L, Z_NULL, 0); - } - } -#ifdef GZIP - if (s->status == EXTRA_STATE) { - if (s->gzhead->extra != NULL) { - uInt beg = s->pending; /* start of bytes to update crc */ - - while (s->gzindex < (s->gzhead->extra_len & 0xffff)) { - if (s->pending == s->pending_buf_size) { - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - flush_pending(strm); - beg = s->pending; - if (s->pending == s->pending_buf_size) - break; - } - put_byte(s, s->gzhead->extra[s->gzindex]); - s->gzindex++; - } - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - if (s->gzindex == s->gzhead->extra_len) { - s->gzindex = 0; - s->status = NAME_STATE; - } - } - else - s->status = NAME_STATE; - } - if (s->status == NAME_STATE) { - if (s->gzhead->name != NULL) { - uInt beg = s->pending; /* start of bytes to update crc */ - int val; - - do { - if (s->pending == s->pending_buf_size) { - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - flush_pending(strm); - beg = s->pending; - if (s->pending == s->pending_buf_size) { - val = 1; - break; - } - } - val = s->gzhead->name[s->gzindex++]; - put_byte(s, val); - } while (val != 0); - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - if (val == 0) { - s->gzindex = 0; - s->status = COMMENT_STATE; - } - } - else - s->status = COMMENT_STATE; - } - if (s->status == COMMENT_STATE) { - if (s->gzhead->comment != NULL) { - uInt beg = s->pending; /* start of bytes to update crc */ - int val; - - do { - if (s->pending == s->pending_buf_size) { - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - flush_pending(strm); - beg = s->pending; - if (s->pending == s->pending_buf_size) { - val = 1; - break; - } - } - val = s->gzhead->comment[s->gzindex++]; - put_byte(s, val); - } while (val != 0); - if (s->gzhead->hcrc && s->pending > beg) - strm->adler = crc32(strm->adler, s->pending_buf + beg, - s->pending - beg); - if (val == 0) - s->status = HCRC_STATE; - } - else - s->status = HCRC_STATE; - } - if (s->status == HCRC_STATE) { - if (s->gzhead->hcrc) { - if (s->pending + 2 > s->pending_buf_size) - flush_pending(strm); - if (s->pending + 2 <= s->pending_buf_size) { - put_byte(s, (Byte)(strm->adler & 0xff)); - put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); - strm->adler = crc32(0L, Z_NULL, 0); - s->status = BUSY_STATE; - } - } - else - s->status = BUSY_STATE; - } -#endif - - /* Flush as much pending output as possible */ - if (s->pending != 0) { - flush_pending(strm); - if (strm->avail_out == 0) { - /* Since avail_out is 0, deflate will be called again with - * more output space, but possibly with both pending and - * avail_in equal to zero. There won't be anything to do, - * but this is not an error situation so make sure we - * return OK instead of BUF_ERROR at next call of deflate: - */ - s->last_flush = -1; - return Z_OK; - } - - /* Make sure there is something to do and avoid duplicate consecutive - * flushes. For repeated and useless calls with Z_FINISH, we keep - * returning Z_STREAM_END instead of Z_BUF_ERROR. - */ - } else if (strm->avail_in == 0 && flush <= old_flush && - flush != Z_FINISH) { - ERR_RETURN(strm, Z_BUF_ERROR); - } - - /* User must not provide more input after the first FINISH: */ - if (s->status == FINISH_STATE && strm->avail_in != 0) { - ERR_RETURN(strm, Z_BUF_ERROR); - } - - /* Start a new block or continue the current one. - */ - if (strm->avail_in != 0 || s->lookahead != 0 || - (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { - block_state bstate; - - bstate = (*(configuration_table[s->level].func))(s, flush); - - if (bstate == finish_started || bstate == finish_done) { - s->status = FINISH_STATE; - } - if (bstate == need_more || bstate == finish_started) { - if (strm->avail_out == 0) { - s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ - } - return Z_OK; - /* If flush != Z_NO_FLUSH && avail_out == 0, the next call - * of deflate should use the same flush parameter to make sure - * that the flush is complete. So we don't have to output an - * empty block here, this will be done at next call. This also - * ensures that for a very small output buffer, we emit at most - * one empty block. - */ - } - if (bstate == block_done) { - if (flush == Z_PARTIAL_FLUSH) { - _tr_align(s); - } else { /* FULL_FLUSH or SYNC_FLUSH */ - _tr_stored_block(s, (char*)0, 0L, 0); - /* For a full flush, this empty block will be recognized - * as a special marker by inflate_sync(). - */ - if (flush == Z_FULL_FLUSH) { - CLEAR_HASH(s); /* forget history */ - } - } - flush_pending(strm); - if (strm->avail_out == 0) { - s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ - return Z_OK; - } - } - } - Assert(strm->avail_out > 0, "bug2"); - - if (flush != Z_FINISH) return Z_OK; - if (s->wrap <= 0) return Z_STREAM_END; - - /* Write the trailer */ -#ifdef GZIP - if (s->wrap == 2) { - put_byte(s, (Byte)(strm->adler & 0xff)); - put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); - put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); - put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); - put_byte(s, (Byte)(strm->total_in & 0xff)); - put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); - put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); - put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); - } - else -#endif - { - putShortMSB(s, (uInt)(strm->adler >> 16)); - putShortMSB(s, (uInt)(strm->adler & 0xffff)); - } - flush_pending(strm); - /* If avail_out is zero, the application will call deflate again - * to flush the rest. - */ - if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ - return s->pending != 0 ? Z_OK : Z_STREAM_END; -} - -/* ========================================================================= */ -int ZEXPORT deflateEnd (strm) - z_streamp strm; -{ - int status; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - - status = strm->state->status; - if (status != INIT_STATE && - status != EXTRA_STATE && - status != NAME_STATE && - status != COMMENT_STATE && - status != HCRC_STATE && - status != BUSY_STATE && - status != FINISH_STATE) { - return Z_STREAM_ERROR; - } - - /* Deallocate in reverse order of allocations: */ - TRY_FREE(strm, strm->state->pending_buf); - TRY_FREE(strm, strm->state->head); - TRY_FREE(strm, strm->state->prev); - TRY_FREE(strm, strm->state->window); - - ZFREE(strm, strm->state); - strm->state = Z_NULL; - - return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; -} - -/* ========================================================================= - * Copy the source state to the destination state. - * To simplify the source, this is not supported for 16-bit MSDOS (which - * doesn't have enough memory anyway to duplicate compression states). - */ -int ZEXPORT deflateCopy (dest, source) - z_streamp dest; - z_streamp source; -{ -#ifdef MAXSEG_64K - return Z_STREAM_ERROR; -#else - deflate_state *ds; - deflate_state *ss; - ushf *overlay; - - - if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) { - return Z_STREAM_ERROR; - } - - ss = source->state; - - zmemcpy(dest, source, sizeof(z_stream)); - - ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); - if (ds == Z_NULL) return Z_MEM_ERROR; - dest->state = (struct internal_state FAR *) ds; - zmemcpy(ds, ss, sizeof(deflate_state)); - ds->strm = dest; - - ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); - ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); - ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); - overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); - ds->pending_buf = (uchf *) overlay; - - if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || - ds->pending_buf == Z_NULL) { - deflateEnd (dest); - return Z_MEM_ERROR; - } - /* following zmemcpy do not work for 16-bit MSDOS */ - zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); - zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos)); - zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos)); - zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); - - ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); - ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); - ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; - - ds->l_desc.dyn_tree = ds->dyn_ltree; - ds->d_desc.dyn_tree = ds->dyn_dtree; - ds->bl_desc.dyn_tree = ds->bl_tree; - - return Z_OK; -#endif /* MAXSEG_64K */ -} - -/* =========================================================================== - * Read a new buffer from the current input stream, update the adler32 - * and total number of bytes read. All deflate() input goes through - * this function so some applications may wish to modify it to avoid - * allocating a large strm->next_in buffer and copying from it. - * (See also flush_pending()). - */ -local int read_buf(strm, buf, size) - z_streamp strm; - Bytef *buf; - unsigned size; -{ - unsigned len = strm->avail_in; - - if (len > size) len = size; - if (len == 0) return 0; - - strm->avail_in -= len; - - if (strm->state->wrap == 1) { - strm->adler = adler32(strm->adler, strm->next_in, len); - } -#ifdef GZIP - else if (strm->state->wrap == 2) { - strm->adler = crc32(strm->adler, strm->next_in, len); - } -#endif - zmemcpy(buf, strm->next_in, len); - strm->next_in += len; - strm->total_in += len; - - return (int)len; -} - -/* =========================================================================== - * Initialize the "longest match" routines for a new zlib stream - */ -local void lm_init (s) - deflate_state *s; -{ - s->window_size = (ulg)2L*s->w_size; - - CLEAR_HASH(s); - - /* Set the default configuration parameters: - */ - s->max_lazy_match = configuration_table[s->level].max_lazy; - s->good_match = configuration_table[s->level].good_length; - s->nice_match = configuration_table[s->level].nice_length; - s->max_chain_length = configuration_table[s->level].max_chain; - - s->strstart = 0; - s->block_start = 0L; - s->lookahead = 0; - s->match_length = s->prev_length = MIN_MATCH-1; - s->match_available = 0; - s->ins_h = 0; -#ifndef FASTEST -#ifdef ASMV - match_init(); /* initialize the asm code */ -#endif -#endif -} - -#ifndef FASTEST -/* =========================================================================== - * Set match_start to the longest match starting at the given string and - * return its length. Matches shorter or equal to prev_length are discarded, - * in which case the result is equal to prev_length and match_start is - * garbage. - * IN assertions: cur_match is the head of the hash chain for the current - * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 - * OUT assertion: the match length is not greater than s->lookahead. - */ -#ifndef ASMV -/* For 80x86 and 680x0, an optimized version will be provided in match.asm or - * match.S. The code will be functionally equivalent. - */ -local uInt longest_match(s, cur_match) - deflate_state *s; - IPos cur_match; /* current match */ -{ - unsigned chain_length = s->max_chain_length;/* max hash chain length */ - register Bytef *scan = s->window + s->strstart; /* current string */ - register Bytef *match; /* matched string */ - register int len; /* length of current match */ - int best_len = s->prev_length; /* best match length so far */ - int nice_match = s->nice_match; /* stop if match long enough */ - IPos limit = s->strstart > (IPos)MAX_DIST(s) ? - s->strstart - (IPos)MAX_DIST(s) : NIL; - /* Stop when cur_match becomes <= limit. To simplify the code, - * we prevent matches with the string of window index 0. - */ - Posf *prev = s->prev; - uInt wmask = s->w_mask; - -#ifdef UNALIGNED_OK - /* Compare two bytes at a time. Note: this is not always beneficial. - * Try with and without -DUNALIGNED_OK to check. - */ - register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; - register ush scan_start = *(ushf*)scan; - register ush scan_end = *(ushf*)(scan+best_len-1); -#else - register Bytef *strend = s->window + s->strstart + MAX_MATCH; - register Byte scan_end1 = scan[best_len-1]; - register Byte scan_end = scan[best_len]; -#endif - - /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. - * It is easy to get rid of this optimization if necessary. - */ - Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); - - /* Do not waste too much time if we already have a good match: */ - if (s->prev_length >= s->good_match) { - chain_length >>= 2; - } - /* Do not look for matches beyond the end of the input. This is necessary - * to make deflate deterministic. - */ - if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; - - Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); - - do { - Assert(cur_match < s->strstart, "no future"); - match = s->window + cur_match; - - /* Skip to next match if the match length cannot increase - * or if the match length is less than 2. Note that the checks below - * for insufficient lookahead only occur occasionally for performance - * reasons. Therefore uninitialized memory will be accessed, and - * conditional jumps will be made that depend on those values. - * However the length of the match is limited to the lookahead, so - * the output of deflate is not affected by the uninitialized values. - */ -#if (defined(UNALIGNED_OK) && MAX_MATCH == 258) - /* This code assumes sizeof(unsigned short) == 2. Do not use - * UNALIGNED_OK if your compiler uses a different size. - */ - if (*(ushf*)(match+best_len-1) != scan_end || - *(ushf*)match != scan_start) continue; - - /* It is not necessary to compare scan[2] and match[2] since they are - * always equal when the other bytes match, given that the hash keys - * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at - * strstart+3, +5, ... up to strstart+257. We check for insufficient - * lookahead only every 4th comparison; the 128th check will be made - * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is - * necessary to put more guard bytes at the end of the window, or - * to check more often for insufficient lookahead. - */ - Assert(scan[2] == match[2], "scan[2]?"); - scan++, match++; - do { - } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && - *(ushf*)(scan+=2) == *(ushf*)(match+=2) && - *(ushf*)(scan+=2) == *(ushf*)(match+=2) && - *(ushf*)(scan+=2) == *(ushf*)(match+=2) && - scan < strend); - /* The funny "do {}" generates better code on most compilers */ - - /* Here, scan <= window+strstart+257 */ - Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - if (*scan == *match) scan++; - - len = (MAX_MATCH - 1) - (int)(strend-scan); - scan = strend - (MAX_MATCH-1); - -#else /* UNALIGNED_OK */ - - if (match[best_len] != scan_end || - match[best_len-1] != scan_end1 || - *match != *scan || - *++match != scan[1]) continue; - - /* The check at best_len-1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that - * the hash keys are equal and that HASH_BITS >= 8. - */ - scan += 2, match++; - Assert(*scan == *match, "match[2]?"); - - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart+258. - */ - do { - } while (*++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - scan < strend); - - Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - - len = MAX_MATCH - (int)(strend - scan); - scan = strend - MAX_MATCH; - -#endif /* UNALIGNED_OK */ - - if (len > best_len) { - s->match_start = cur_match; - best_len = len; - if (len >= nice_match) break; -#ifdef UNALIGNED_OK - scan_end = *(ushf*)(scan+best_len-1); -#else - scan_end1 = scan[best_len-1]; - scan_end = scan[best_len]; -#endif - } - } while ((cur_match = prev[cur_match & wmask]) > limit - && --chain_length != 0); - - if ((uInt)best_len <= s->lookahead) return (uInt)best_len; - return s->lookahead; -} -#endif /* ASMV */ -#endif /* FASTEST */ - -/* --------------------------------------------------------------------------- - * Optimized version for level == 1 or strategy == Z_RLE only - */ -local uInt longest_match_fast(s, cur_match) - deflate_state *s; - IPos cur_match; /* current match */ -{ - register Bytef *scan = s->window + s->strstart; /* current string */ - register Bytef *match; /* matched string */ - register int len; /* length of current match */ - register Bytef *strend = s->window + s->strstart + MAX_MATCH; - - /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. - * It is easy to get rid of this optimization if necessary. - */ - Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); - - Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); - - Assert(cur_match < s->strstart, "no future"); - - match = s->window + cur_match; - - /* Return failure if the match length is less than 2: - */ - if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; - - /* The check at best_len-1 can be removed because it will be made - * again later. (This heuristic is not always a win.) - * It is not necessary to compare scan[2] and match[2] since they - * are always equal when the other bytes match, given that - * the hash keys are equal and that HASH_BITS >= 8. - */ - scan += 2, match += 2; - Assert(*scan == *match, "match[2]?"); - - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart+258. - */ - do { - } while (*++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - *++scan == *++match && *++scan == *++match && - scan < strend); - - Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); - - len = MAX_MATCH - (int)(strend - scan); - - if (len < MIN_MATCH) return MIN_MATCH - 1; - - s->match_start = cur_match; - return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; -} - -#ifdef DEBUG -/* =========================================================================== - * Check that the match at match_start is indeed a match. - */ -local void check_match(s, start, match, length) - deflate_state *s; - IPos start, match; - int length; -{ - /* check that the match is indeed a match */ - if (zmemcmp(s->window + match, - s->window + start, length) != EQUAL) { - fprintf(stderr, " start %u, match %u, length %d\n", - start, match, length); - do { - fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); - } while (--length != 0); - z_error("invalid match"); - } - if (z_verbose > 1) { - fprintf(stderr,"\\[%d,%d]", start-match, length); - do { putc(s->window[start++], stderr); } while (--length != 0); - } -} -#else -# define check_match(s, start, match, length) -#endif /* DEBUG */ - -/* =========================================================================== - * Fill the window when the lookahead becomes insufficient. - * Updates strstart and lookahead. - * - * IN assertion: lookahead < MIN_LOOKAHEAD - * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD - * At least one byte has been read, or avail_in == 0; reads are - * performed for at least two bytes (required for the zip translate_eol - * option -- not supported here). - */ -local void fill_window(s) - deflate_state *s; -{ - register unsigned n, m; - register Posf *p; - unsigned more; /* Amount of free space at the end of the window. */ - uInt wsize = s->w_size; - - do { - more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); - - /* Deal with !@#$% 64K limit: */ - if (sizeof(int) <= 2) { - if (more == 0 && s->strstart == 0 && s->lookahead == 0) { - more = wsize; - - } else if (more == (unsigned)(-1)) { - /* Very unlikely, but possible on 16 bit machine if - * strstart == 0 && lookahead == 1 (input done a byte at time) - */ - more--; - } - } - - /* If the window is almost full and there is insufficient lookahead, - * move the upper half to the lower one to make room in the upper half. - */ - if (s->strstart >= wsize+MAX_DIST(s)) { - - zmemcpy(s->window, s->window+wsize, (unsigned)wsize); - s->match_start -= wsize; - s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ - s->block_start -= (long) wsize; - - /* Slide the hash table (could be avoided with 32 bit values - at the expense of memory usage). We slide even when level == 0 - to keep the hash table consistent if we switch back to level > 0 - later. (Using level 0 permanently is not an optimal usage of - zlib, so we don't care about this pathological case.) - */ - /* %%% avoid this when Z_RLE */ - n = s->hash_size; - p = &s->head[n]; - do { - m = *--p; - *p = (Pos)(m >= wsize ? m-wsize : NIL); - } while (--n); - - n = wsize; -#ifndef FASTEST - p = &s->prev[n]; - do { - m = *--p; - *p = (Pos)(m >= wsize ? m-wsize : NIL); - /* If n is not on any hash chain, prev[n] is garbage but - * its value will never be used. - */ - } while (--n); -#endif - more += wsize; - } - if (s->strm->avail_in == 0) return; - - /* If there was no sliding: - * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && - * more == window_size - lookahead - strstart - * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) - * => more >= window_size - 2*WSIZE + 2 - * In the BIG_MEM or MMAP case (not yet supported), - * window_size == input_size + MIN_LOOKAHEAD && - * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. - * Otherwise, window_size == 2*WSIZE so more >= 2. - * If there was sliding, more >= WSIZE. So in all cases, more >= 2. - */ - Assert(more >= 2, "more < 2"); - - n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); - s->lookahead += n; - - /* Initialize the hash value now that we have some input: */ - if (s->lookahead >= MIN_MATCH) { - s->ins_h = s->window[s->strstart]; - UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); -#if MIN_MATCH != 3 - Call UPDATE_HASH() MIN_MATCH-3 more times -#endif - } - /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, - * but this is not important since only literal bytes will be emitted. - */ - - } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); -} - -/* =========================================================================== - * Flush the current block, with given end-of-file flag. - * IN assertion: strstart is set to the end of the current match. - */ -#define FLUSH_BLOCK_ONLY(s, eof) { \ - _tr_flush_block(s, (s->block_start >= 0L ? \ - (charf *)&s->window[(unsigned)s->block_start] : \ - (charf *)Z_NULL), \ - (ulg)((long)s->strstart - s->block_start), \ - (eof)); \ - s->block_start = s->strstart; \ - flush_pending(s->strm); \ - Tracev((stderr,"[FLUSH]")); \ -} - -/* Same but force premature exit if necessary. */ -#define FLUSH_BLOCK(s, eof) { \ - FLUSH_BLOCK_ONLY(s, eof); \ - if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \ -} - -/* =========================================================================== - * Copy without compression as much as possible from the input stream, return - * the current block state. - * This function does not insert new strings in the dictionary since - * uncompressible data is probably not useful. This function is used - * only for the level=0 compression option. - * NOTE: this function should be optimized to avoid extra copying from - * window to pending_buf. - */ -local block_state deflate_stored(s, flush) - deflate_state *s; - int flush; -{ - /* Stored blocks are limited to 0xffff bytes, pending_buf is limited - * to pending_buf_size, and each stored block has a 5 byte header: - */ - ulg max_block_size = 0xffff; - ulg max_start; - - if (max_block_size > s->pending_buf_size - 5) { - max_block_size = s->pending_buf_size - 5; - } - - /* Copy as much as possible from input to output: */ - for (;;) { - /* Fill the window as much as possible: */ - if (s->lookahead <= 1) { - - Assert(s->strstart < s->w_size+MAX_DIST(s) || - s->block_start >= (long)s->w_size, "slide too late"); - - fill_window(s); - if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; - - if (s->lookahead == 0) break; /* flush the current block */ - } - Assert(s->block_start >= 0L, "block gone"); - - s->strstart += s->lookahead; - s->lookahead = 0; - - /* Emit a stored block if pending_buf will be full: */ - max_start = s->block_start + max_block_size; - if (s->strstart == 0 || (ulg)s->strstart >= max_start) { - /* strstart == 0 is possible when wraparound on 16-bit machine */ - s->lookahead = (uInt)(s->strstart - max_start); - s->strstart = (uInt)max_start; - FLUSH_BLOCK(s, 0); - } - /* Flush if we may have to slide, otherwise block_start may become - * negative and the data will be gone: - */ - if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { - FLUSH_BLOCK(s, 0); - } - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; -} - -/* =========================================================================== - * Compress as much as possible from the input stream, return the current - * block state. - * This function does not perform lazy evaluation of matches and inserts - * new strings in the dictionary only for unmatched strings or for short - * matches. It is used only for the fast compression options. - */ -local block_state deflate_fast(s, flush) - deflate_state *s; - int flush; -{ - IPos hash_head = NIL; /* head of the hash chain */ - int bflush; /* set if current block must be flushed */ - - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s->lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { - return need_more; - } - if (s->lookahead == 0) break; /* flush the current block */ - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - if (s->lookahead >= MIN_MATCH) { - INSERT_STRING(s, s->strstart, hash_head); - } - - /* Find the longest match, discarding those <= prev_length. - * At this point we have always match_length < MIN_MATCH - */ - if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ -#ifdef FASTEST - if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) || - (s->strategy == Z_RLE && s->strstart - hash_head == 1)) { - s->match_length = longest_match_fast (s, hash_head); - } -#else - if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) { - s->match_length = longest_match (s, hash_head); - } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { - s->match_length = longest_match_fast (s, hash_head); - } -#endif - /* longest_match() or longest_match_fast() sets match_start */ - } - if (s->match_length >= MIN_MATCH) { - check_match(s, s->strstart, s->match_start, s->match_length); - - _tr_tally_dist(s, s->strstart - s->match_start, - s->match_length - MIN_MATCH, bflush); - - s->lookahead -= s->match_length; - - /* Insert new strings in the hash table only if the match length - * is not too large. This saves time but degrades compression. - */ -#ifndef FASTEST - if (s->match_length <= s->max_insert_length && - s->lookahead >= MIN_MATCH) { - s->match_length--; /* string at strstart already in table */ - do { - s->strstart++; - INSERT_STRING(s, s->strstart, hash_head); - /* strstart never exceeds WSIZE-MAX_MATCH, so there are - * always MIN_MATCH bytes ahead. - */ - } while (--s->match_length != 0); - s->strstart++; - } else -#endif - { - s->strstart += s->match_length; - s->match_length = 0; - s->ins_h = s->window[s->strstart]; - UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); -#if MIN_MATCH != 3 - Call UPDATE_HASH() MIN_MATCH-3 more times -#endif - /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not - * matter since it will be recomputed at next deflate call. - */ - } - } else { - /* No match, output a literal byte */ - Tracevv((stderr,"%c", s->window[s->strstart])); - _tr_tally_lit (s, s->window[s->strstart], bflush); - s->lookahead--; - s->strstart++; - } - if (bflush) FLUSH_BLOCK(s, 0); - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; -} - -#ifndef FASTEST -/* =========================================================================== - * Same as above, but achieves better compression. We use a lazy - * evaluation for matches: a match is finally adopted only if there is - * no better match at the next window position. - */ -local block_state deflate_slow(s, flush) - deflate_state *s; - int flush; -{ - IPos hash_head = NIL; /* head of hash chain */ - int bflush; /* set if current block must be flushed */ - - /* Process the input block. */ - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the next match, plus MIN_MATCH bytes to insert the - * string following the next match. - */ - if (s->lookahead < MIN_LOOKAHEAD) { - fill_window(s); - if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { - return need_more; - } - if (s->lookahead == 0) break; /* flush the current block */ - } - - /* Insert the string window[strstart .. strstart+2] in the - * dictionary, and set hash_head to the head of the hash chain: - */ - if (s->lookahead >= MIN_MATCH) { - INSERT_STRING(s, s->strstart, hash_head); - } - - /* Find the longest match, discarding those <= prev_length. - */ - s->prev_length = s->match_length, s->prev_match = s->match_start; - s->match_length = MIN_MATCH-1; - - if (hash_head != NIL && s->prev_length < s->max_lazy_match && - s->strstart - hash_head <= MAX_DIST(s)) { - /* To simplify the code, we prevent matches with the string - * of window index 0 (in particular we have to avoid a match - * of the string with itself at the start of the input file). - */ - if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) { - s->match_length = longest_match (s, hash_head); - } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) { - s->match_length = longest_match_fast (s, hash_head); - } - /* longest_match() or longest_match_fast() sets match_start */ - - if (s->match_length <= 5 && (s->strategy == Z_FILTERED -#if TOO_FAR <= 32767 - || (s->match_length == MIN_MATCH && - s->strstart - s->match_start > TOO_FAR) -#endif - )) { - - /* If prev_match is also MIN_MATCH, match_start is garbage - * but we will ignore the current match anyway. - */ - s->match_length = MIN_MATCH-1; - } - } - /* If there was a match at the previous step and the current - * match is not better, output the previous match: - */ - if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { - uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; - /* Do not insert strings in hash table beyond this. */ - - check_match(s, s->strstart-1, s->prev_match, s->prev_length); - - _tr_tally_dist(s, s->strstart -1 - s->prev_match, - s->prev_length - MIN_MATCH, bflush); - - /* Insert in hash table all strings up to the end of the match. - * strstart-1 and strstart are already inserted. If there is not - * enough lookahead, the last two strings are not inserted in - * the hash table. - */ - s->lookahead -= s->prev_length-1; - s->prev_length -= 2; - do { - if (++s->strstart <= max_insert) { - INSERT_STRING(s, s->strstart, hash_head); - } - } while (--s->prev_length != 0); - s->match_available = 0; - s->match_length = MIN_MATCH-1; - s->strstart++; - - if (bflush) FLUSH_BLOCK(s, 0); - - } else if (s->match_available) { - /* If there was no match at the previous position, output a - * single literal. If there was a match but the current match - * is longer, truncate the previous match to a single literal. - */ - Tracevv((stderr,"%c", s->window[s->strstart-1])); - _tr_tally_lit(s, s->window[s->strstart-1], bflush); - if (bflush) { - FLUSH_BLOCK_ONLY(s, 0); - } - s->strstart++; - s->lookahead--; - if (s->strm->avail_out == 0) return need_more; - } else { - /* There is no previous match to compare with, wait for - * the next step to decide. - */ - s->match_available = 1; - s->strstart++; - s->lookahead--; - } - } - Assert (flush != Z_NO_FLUSH, "no flush?"); - if (s->match_available) { - Tracevv((stderr,"%c", s->window[s->strstart-1])); - _tr_tally_lit(s, s->window[s->strstart-1], bflush); - s->match_available = 0; - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; -} -#endif /* FASTEST */ - -#if 0 -/* =========================================================================== - * For Z_RLE, simply look for runs of bytes, generate matches only of distance - * one. Do not maintain a hash table. (It will be regenerated if this run of - * deflate switches away from Z_RLE.) - */ -local block_state deflate_rle(s, flush) - deflate_state *s; - int flush; -{ - int bflush; /* set if current block must be flushed */ - uInt run; /* length of run */ - uInt max; /* maximum length of run */ - uInt prev; /* byte at distance one to match */ - Bytef *scan; /* scan for end of run */ - - for (;;) { - /* Make sure that we always have enough lookahead, except - * at the end of the input file. We need MAX_MATCH bytes - * for the longest encodable run. - */ - if (s->lookahead < MAX_MATCH) { - fill_window(s); - if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) { - return need_more; - } - if (s->lookahead == 0) break; /* flush the current block */ - } - - /* See how many times the previous byte repeats */ - run = 0; - if (s->strstart > 0) { /* if there is a previous byte, that is */ - max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH; - scan = s->window + s->strstart - 1; - prev = *scan++; - do { - if (*scan++ != prev) - break; - } while (++run < max); - } - - /* Emit match if have run of MIN_MATCH or longer, else emit literal */ - if (run >= MIN_MATCH) { - check_match(s, s->strstart, s->strstart - 1, run); - _tr_tally_dist(s, 1, run - MIN_MATCH, bflush); - s->lookahead -= run; - s->strstart += run; - } else { - /* No match, output a literal byte */ - Tracevv((stderr,"%c", s->window[s->strstart])); - _tr_tally_lit (s, s->window[s->strstart], bflush); - s->lookahead--; - s->strstart++; - } - if (bflush) FLUSH_BLOCK(s, 0); - } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; -} -#endif diff --git a/dep/StormLib/src/zlib/deflate.h b/dep/StormLib/src/zlib/deflate.h deleted file mode 100644 index 05a5ab3a2c1..00000000000 --- a/dep/StormLib/src/zlib/deflate.h +++ /dev/null @@ -1,331 +0,0 @@ -/* deflate.h -- internal compression state - * Copyright (C) 1995-2004 Jean-loup Gailly - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* @(#) $Id$ */ - -#ifndef DEFLATE_H -#define DEFLATE_H - -#include "zutil.h" - -/* define NO_GZIP when compiling if you want to disable gzip header and - trailer creation by deflate(). NO_GZIP would be used to avoid linking in - the crc code when it is not needed. For shared libraries, gzip encoding - should be left enabled. */ -#ifndef NO_GZIP -# define GZIP -#endif - -/* =========================================================================== - * Internal compression state. - */ - -#define LENGTH_CODES 29 -/* number of length codes, not counting the special END_BLOCK code */ - -#define LITERALS 256 -/* number of literal bytes 0..255 */ - -#define L_CODES (LITERALS+1+LENGTH_CODES) -/* number of Literal or Length codes, including the END_BLOCK code */ - -#define D_CODES 30 -/* number of distance codes */ - -#define BL_CODES 19 -/* number of codes used to transfer the bit lengths */ - -#define HEAP_SIZE (2*L_CODES+1) -/* maximum heap size */ - -#define MAX_BITS 15 -/* All codes must not exceed MAX_BITS bits */ - -#define INIT_STATE 42 -#define EXTRA_STATE 69 -#define NAME_STATE 73 -#define COMMENT_STATE 91 -#define HCRC_STATE 103 -#define BUSY_STATE 113 -#define FINISH_STATE 666 -/* Stream status */ - - -/* Data structure describing a single value and its code string. */ -typedef struct ct_data_s { - union { - ush freq; /* frequency count */ - ush code; /* bit string */ - } fc; - union { - ush dad; /* father node in Huffman tree */ - ush len; /* length of bit string */ - } dl; -} FAR ct_data; - -#define Freq fc.freq -#define Code fc.code -#define Dad dl.dad -#define Len dl.len - -typedef struct static_tree_desc_s static_tree_desc; - -typedef struct tree_desc_s { - ct_data *dyn_tree; /* the dynamic tree */ - int max_code; /* largest code with non zero frequency */ - static_tree_desc *stat_desc; /* the corresponding static tree */ -} FAR tree_desc; - -typedef ush Pos; -typedef Pos FAR Posf; -typedef unsigned IPos; - -/* A Pos is an index in the character window. We use short instead of int to - * save space in the various tables. IPos is used only for parameter passing. - */ - -typedef struct internal_state { - z_streamp strm; /* pointer back to this zlib stream */ - int status; /* as the name implies */ - Bytef *pending_buf; /* output still pending */ - ulg pending_buf_size; /* size of pending_buf */ - Bytef *pending_out; /* next pending byte to output to the stream */ - uInt pending; /* nb of bytes in the pending buffer */ - int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ - gz_headerp gzhead; /* gzip header information to write */ - uInt gzindex; /* where in extra, name, or comment */ - Byte method; /* STORED (for zip only) or DEFLATED */ - int last_flush; /* value of flush param for previous deflate call */ - - /* used by deflate.c: */ - - uInt w_size; /* LZ77 window size (32K by default) */ - uInt w_bits; /* log2(w_size) (8..16) */ - uInt w_mask; /* w_size - 1 */ - - Bytef *window; - /* Sliding window. Input bytes are read into the second half of the window, - * and move to the first half later to keep a dictionary of at least wSize - * bytes. With this organization, matches are limited to a distance of - * wSize-MAX_MATCH bytes, but this ensures that IO is always - * performed with a length multiple of the block size. Also, it limits - * the window size to 64K, which is quite useful on MSDOS. - * To do: use the user input buffer as sliding window. - */ - - ulg window_size; - /* Actual size of window: 2*wSize, except when the user input buffer - * is directly used as sliding window. - */ - - Posf *prev; - /* Link to older string with same hash index. To limit the size of this - * array to 64K, this link is maintained only for the last 32K strings. - * An index in this array is thus a window index modulo 32K. - */ - - Posf *head; /* Heads of the hash chains or NIL. */ - - uInt ins_h; /* hash index of string to be inserted */ - uInt hash_size; /* number of elements in hash table */ - uInt hash_bits; /* log2(hash_size) */ - uInt hash_mask; /* hash_size-1 */ - - uInt hash_shift; - /* Number of bits by which ins_h must be shifted at each input - * step. It must be such that after MIN_MATCH steps, the oldest - * byte no longer takes part in the hash key, that is: - * hash_shift * MIN_MATCH >= hash_bits - */ - - long block_start; - /* Window position at the beginning of the current output block. Gets - * negative when the window is moved backwards. - */ - - uInt match_length; /* length of best match */ - IPos prev_match; /* previous match */ - int match_available; /* set if previous match exists */ - uInt strstart; /* start of string to insert */ - uInt match_start; /* start of matching string */ - uInt lookahead; /* number of valid bytes ahead in window */ - - uInt prev_length; - /* Length of the best match at previous step. Matches not greater than this - * are discarded. This is used in the lazy match evaluation. - */ - - uInt max_chain_length; - /* To speed up deflation, hash chains are never searched beyond this - * length. A higher limit improves compression ratio but degrades the - * speed. - */ - - uInt max_lazy_match; - /* Attempt to find a better match only when the current match is strictly - * smaller than this value. This mechanism is used only for compression - * levels >= 4. - */ -# define max_insert_length max_lazy_match - /* Insert new strings in the hash table only if the match length is not - * greater than this length. This saves time but degrades compression. - * max_insert_length is used only for compression levels <= 3. - */ - - int level; /* compression level (1..9) */ - int strategy; /* favor or force Huffman coding*/ - - uInt good_match; - /* Use a faster search when the previous match is longer than this */ - - int nice_match; /* Stop searching when current match exceeds this */ - - /* used by trees.c: */ - /* Didn't use ct_data typedef below to supress compiler warning */ - struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ - struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ - struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ - - struct tree_desc_s l_desc; /* desc. for literal tree */ - struct tree_desc_s d_desc; /* desc. for distance tree */ - struct tree_desc_s bl_desc; /* desc. for bit length tree */ - - ush bl_count[MAX_BITS+1]; - /* number of codes at each bit length for an optimal tree */ - - int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ - int heap_len; /* number of elements in the heap */ - int heap_max; /* element of largest frequency */ - /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. - * The same heap array is used to build all trees. - */ - - uch depth[2*L_CODES+1]; - /* Depth of each subtree used as tie breaker for trees of equal frequency - */ - - uchf *l_buf; /* buffer for literals or lengths */ - - uInt lit_bufsize; - /* Size of match buffer for literals/lengths. There are 4 reasons for - * limiting lit_bufsize to 64K: - * - frequencies can be kept in 16 bit counters - * - if compression is not successful for the first block, all input - * data is still in the window so we can still emit a stored block even - * when input comes from standard input. (This can also be done for - * all blocks if lit_bufsize is not greater than 32K.) - * - if compression is not successful for a file smaller than 64K, we can - * even emit a stored file instead of a stored block (saving 5 bytes). - * This is applicable only for zip (not gzip or zlib). - * - creating new Huffman trees less frequently may not provide fast - * adaptation to changes in the input data statistics. (Take for - * example a binary file with poorly compressible code followed by - * a highly compressible string table.) Smaller buffer sizes give - * fast adaptation but have of course the overhead of transmitting - * trees more frequently. - * - I can't count above 4 - */ - - uInt last_lit; /* running index in l_buf */ - - ushf *d_buf; - /* Buffer for distances. To simplify the code, d_buf and l_buf have - * the same number of elements. To use different lengths, an extra flag - * array would be necessary. - */ - - ulg opt_len; /* bit length of current block with optimal trees */ - ulg static_len; /* bit length of current block with static trees */ - uInt matches; /* number of string matches in current block */ - int last_eob_len; /* bit length of EOB code for last block */ - -#ifdef DEBUG - ulg compressed_len; /* total bit length of compressed file mod 2^32 */ - ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ -#endif - - ush bi_buf; - /* Output buffer. bits are inserted starting at the bottom (least - * significant bits). - */ - int bi_valid; - /* Number of valid bits in bi_buf. All bits above the last valid bit - * are always zero. - */ - -} FAR deflate_state; - -/* Output a byte on the stream. - * IN assertion: there is enough room in pending_buf. - */ -#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);} - - -#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) -/* Minimum amount of lookahead, except at the end of the input file. - * See deflate.c for comments about the MIN_MATCH+1. - */ - -#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) -/* In order to simplify the code, particularly on 16 bit machines, match - * distances are limited to MAX_DIST instead of WSIZE. - */ - - /* in trees.c */ -void _tr_init OF((deflate_state *s)); -int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); -void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len, - int eof)); -void _tr_align OF((deflate_state *s)); -void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len, - int eof)); - -#define d_code(dist) \ - ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) -/* Mapping from a distance to a distance code. dist is the distance - 1 and - * must not have side effects. _dist_code[256] and _dist_code[257] are never - * used. - */ - -#ifndef DEBUG -/* Inline versions of _tr_tally for speed: */ - -#if defined(GEN_TREES_H) || !defined(STDC) - extern uch _length_code[]; - extern uch _dist_code[]; -#else - extern const uch _length_code[]; - extern const uch _dist_code[]; -#endif - -# define _tr_tally_lit(s, c, flush) \ - { uch cc = (c); \ - s->d_buf[s->last_lit] = 0; \ - s->l_buf[s->last_lit++] = cc; \ - s->dyn_ltree[cc].Freq++; \ - flush = (s->last_lit == s->lit_bufsize-1); \ - } -# define _tr_tally_dist(s, distance, length, flush) \ - { uch len = (length); \ - ush dist = (distance); \ - s->d_buf[s->last_lit] = dist; \ - s->l_buf[s->last_lit++] = len; \ - dist--; \ - s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ - s->dyn_dtree[d_code(dist)].Freq++; \ - flush = (s->last_lit == s->lit_bufsize-1); \ - } -#else -# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) -# define _tr_tally_dist(s, distance, length, flush) \ - flush = _tr_tally(s, distance, length) -#endif - -#endif /* DEFLATE_H */ diff --git a/dep/StormLib/src/zlib/inffast.c b/dep/StormLib/src/zlib/inffast.c deleted file mode 100644 index bbee92ed1e6..00000000000 --- a/dep/StormLib/src/zlib/inffast.c +++ /dev/null @@ -1,318 +0,0 @@ -/* inffast.c -- fast decoding - * Copyright (C) 1995-2004 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -#include "zutil.h" -#include "inftrees.h" -#include "inflate.h" -#include "inffast.h" - -#ifndef ASMINF - -/* Allow machine dependent optimization for post-increment or pre-increment. - Based on testing to date, - Pre-increment preferred for: - - PowerPC G3 (Adler) - - MIPS R5000 (Randers-Pehrson) - Post-increment preferred for: - - none - No measurable difference: - - Pentium III (Anderson) - - M68060 (Nikl) - */ -#ifdef POSTINC -# define OFF 0 -# define PUP(a) *(a)++ -#else -# define OFF 1 -# define PUP(a) *++(a) -#endif - -/* - Decode literal, length, and distance codes and write out the resulting - literal and match bytes until either not enough input or output is - available, an end-of-block is encountered, or a data error is encountered. - When large enough input and output buffers are supplied to inflate(), for - example, a 16K input buffer and a 64K output buffer, more than 95% of the - inflate execution time is spent in this routine. - - Entry assumptions: - - state->mode == LEN - strm->avail_in >= 6 - strm->avail_out >= 258 - start >= strm->avail_out - state->bits < 8 - - On return, state->mode is one of: - - LEN -- ran out of enough output space or enough available input - TYPE -- reached end of block code, inflate() to interpret next block - BAD -- error in block data - - Notes: - - - The maximum input bits used by a length/distance pair is 15 bits for the - length code, 5 bits for the length extra, 15 bits for the distance code, - and 13 bits for the distance extra. This totals 48 bits, or six bytes. - Therefore if strm->avail_in >= 6, then there is enough input to avoid - checking for available input while decoding. - - - The maximum bytes that a single length/distance pair can output is 258 - bytes, which is the maximum length that can be coded. inflate_fast() - requires strm->avail_out >= 258 for each loop to avoid checking for - output space. - */ -void inflate_fast(strm, start) -z_streamp strm; -unsigned start; /* inflate()'s starting value for strm->avail_out */ -{ - struct inflate_state FAR *state; - unsigned char FAR *in; /* local strm->next_in */ - unsigned char FAR *last; /* while in < last, enough input available */ - unsigned char FAR *out; /* local strm->next_out */ - unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ - unsigned char FAR *end; /* while out < end, enough space available */ -#ifdef INFLATE_STRICT - unsigned dmax; /* maximum distance from zlib header */ -#endif - unsigned wsize; /* window size or zero if not using window */ - unsigned whave; /* valid bytes in the window */ - unsigned write; /* window write index */ - unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ - unsigned long hold; /* local strm->hold */ - unsigned bits; /* local strm->bits */ - code const FAR *lcode; /* local strm->lencode */ - code const FAR *dcode; /* local strm->distcode */ - unsigned lmask; /* mask for first level of length codes */ - unsigned dmask; /* mask for first level of distance codes */ - code this; /* retrieved table entry */ - unsigned op; /* code bits, operation, extra bits, or */ - /* window position, window bytes to copy */ - unsigned len; /* match length, unused bytes */ - unsigned dist; /* match distance */ - unsigned char FAR *from; /* where to copy match from */ - - /* copy state to local variables */ - state = (struct inflate_state FAR *)strm->state; - in = strm->next_in - OFF; - last = in + (strm->avail_in - 5); - out = strm->next_out - OFF; - beg = out - (start - strm->avail_out); - end = out + (strm->avail_out - 257); -#ifdef INFLATE_STRICT - dmax = state->dmax; -#endif - wsize = state->wsize; - whave = state->whave; - write = state->write; - window = state->window; - hold = state->hold; - bits = state->bits; - lcode = state->lencode; - dcode = state->distcode; - lmask = (1U << state->lenbits) - 1; - dmask = (1U << state->distbits) - 1; - - /* decode literals and length/distances until end-of-block or not enough - input data or output space */ - do { - if (bits < 15) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - } - this = lcode[hold & lmask]; - dolen: - op = (unsigned)(this.bits); - hold >>= op; - bits -= op; - op = (unsigned)(this.op); - if (op == 0) { /* literal */ - Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? - "inflate: literal '%c'\n" : - "inflate: literal 0x%02x\n", this.val)); - PUP(out) = (unsigned char)(this.val); - } - else if (op & 16) { /* length base */ - len = (unsigned)(this.val); - op &= 15; /* number of extra bits */ - if (op) { - if (bits < op) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - } - len += (unsigned)hold & ((1U << op) - 1); - hold >>= op; - bits -= op; - } - Tracevv((stderr, "inflate: length %u\n", len)); - if (bits < 15) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - } - this = dcode[hold & dmask]; - dodist: - op = (unsigned)(this.bits); - hold >>= op; - bits -= op; - op = (unsigned)(this.op); - if (op & 16) { /* distance base */ - dist = (unsigned)(this.val); - op &= 15; /* number of extra bits */ - if (bits < op) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - if (bits < op) { - hold += (unsigned long)(PUP(in)) << bits; - bits += 8; - } - } - dist += (unsigned)hold & ((1U << op) - 1); -#ifdef INFLATE_STRICT - if (dist > dmax) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } -#endif - hold >>= op; - bits -= op; - Tracevv((stderr, "inflate: distance %u\n", dist)); - op = (unsigned)(out - beg); /* max distance in output */ - if (dist > op) { /* see if copy from window */ - op = dist - op; /* distance back in window */ - if (op > whave) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } - from = window - OFF; - if (write == 0) { /* very common case */ - from += wsize - op; - if (op < len) { /* some from window */ - len -= op; - do { - PUP(out) = PUP(from); - } while (--op); - from = out - dist; /* rest from output */ - } - } - else if (write < op) { /* wrap around window */ - from += wsize + write - op; - op -= write; - if (op < len) { /* some from end of window */ - len -= op; - do { - PUP(out) = PUP(from); - } while (--op); - from = window - OFF; - if (write < len) { /* some from start of window */ - op = write; - len -= op; - do { - PUP(out) = PUP(from); - } while (--op); - from = out - dist; /* rest from output */ - } - } - } - else { /* contiguous in window */ - from += write - op; - if (op < len) { /* some from window */ - len -= op; - do { - PUP(out) = PUP(from); - } while (--op); - from = out - dist; /* rest from output */ - } - } - while (len > 2) { - PUP(out) = PUP(from); - PUP(out) = PUP(from); - PUP(out) = PUP(from); - len -= 3; - } - if (len) { - PUP(out) = PUP(from); - if (len > 1) - PUP(out) = PUP(from); - } - } - else { - from = out - dist; /* copy direct from output */ - do { /* minimum length is three */ - PUP(out) = PUP(from); - PUP(out) = PUP(from); - PUP(out) = PUP(from); - len -= 3; - } while (len > 2); - if (len) { - PUP(out) = PUP(from); - if (len > 1) - PUP(out) = PUP(from); - } - } - } - else if ((op & 64) == 0) { /* 2nd level distance code */ - this = dcode[this.val + (hold & ((1U << op) - 1))]; - goto dodist; - } - else { - strm->msg = (char *)"invalid distance code"; - state->mode = BAD; - break; - } - } - else if ((op & 64) == 0) { /* 2nd level length code */ - this = lcode[this.val + (hold & ((1U << op) - 1))]; - goto dolen; - } - else if (op & 32) { /* end-of-block */ - Tracevv((stderr, "inflate: end of block\n")); - state->mode = TYPE; - break; - } - else { - strm->msg = (char *)"invalid literal/length code"; - state->mode = BAD; - break; - } - } while (in < last && out < end); - - /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ - len = bits >> 3; - in -= len; - bits -= len << 3; - hold &= (1U << bits) - 1; - - /* update state and return */ - strm->next_in = in + OFF; - strm->next_out = out + OFF; - strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); - strm->avail_out = (unsigned)(out < end ? - 257 + (end - out) : 257 - (out - end)); - state->hold = hold; - state->bits = bits; - return; -} - -/* - inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): - - Using bit fields for code structure - - Different op definition to avoid & for extra bits (do & for table bits) - - Three separate decoding do-loops for direct, window, and write == 0 - - Special case for distance > 1 copies to do overlapped load and store copy - - Explicit branch predictions (based on measured branch probabilities) - - Deferring match copy and interspersed it with decoding subsequent codes - - Swapping literal/length else - - Swapping window/direct else - - Larger unrolled copy loops (three is about right) - - Moving len -= 3 statement into middle of loop - */ - -#endif /* !ASMINF */ diff --git a/dep/StormLib/src/zlib/inffast.h b/dep/StormLib/src/zlib/inffast.h deleted file mode 100644 index 1e88d2d97b5..00000000000 --- a/dep/StormLib/src/zlib/inffast.h +++ /dev/null @@ -1,11 +0,0 @@ -/* inffast.h -- header to use inffast.c - * Copyright (C) 1995-2003 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -void inflate_fast OF((z_streamp strm, unsigned start)); diff --git a/dep/StormLib/src/zlib/inffixed.h b/dep/StormLib/src/zlib/inffixed.h deleted file mode 100644 index 75ed4b5978d..00000000000 --- a/dep/StormLib/src/zlib/inffixed.h +++ /dev/null @@ -1,94 +0,0 @@ - /* inffixed.h -- table for decoding fixed codes - * Generated automatically by makefixed(). - */ - - /* WARNING: this file should *not* be used by applications. It - is part of the implementation of the compression library and - is subject to change. Applications should only use zlib.h. - */ - - static const code lenfix[512] = { - {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48}, - {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128}, - {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59}, - {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176}, - {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20}, - {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100}, - {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8}, - {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216}, - {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76}, - {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114}, - {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2}, - {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148}, - {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42}, - {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86}, - {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15}, - {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236}, - {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62}, - {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, - {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31}, - {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162}, - {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25}, - {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105}, - {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4}, - {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202}, - {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69}, - {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125}, - {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13}, - {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195}, - {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35}, - {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91}, - {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19}, - {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246}, - {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55}, - {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135}, - {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99}, - {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190}, - {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16}, - {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96}, - {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6}, - {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209}, - {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72}, - {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116}, - {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4}, - {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153}, - {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44}, - {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82}, - {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11}, - {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, - {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58}, - {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138}, - {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51}, - {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173}, - {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30}, - {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110}, - {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0}, - {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195}, - {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65}, - {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121}, - {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9}, - {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258}, - {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37}, - {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93}, - {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23}, - {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251}, - {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51}, - {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, - {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67}, - {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183}, - {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23}, - {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103}, - {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9}, - {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223}, - {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79}, - {0,9,255} - }; - - static const code distfix[32] = { - {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025}, - {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193}, - {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385}, - {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577}, - {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073}, - {22,5,193},{64,5,0} - }; diff --git a/dep/StormLib/src/zlib/inflate.c b/dep/StormLib/src/zlib/inflate.c deleted file mode 100644 index 792fdee8e9c..00000000000 --- a/dep/StormLib/src/zlib/inflate.c +++ /dev/null @@ -1,1368 +0,0 @@ -/* inflate.c -- zlib decompression - * Copyright (C) 1995-2005 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - * Change history: - * - * 1.2.beta0 24 Nov 2002 - * - First version -- complete rewrite of inflate to simplify code, avoid - * creation of window when not needed, minimize use of window when it is - * needed, make inffast.c even faster, implement gzip decoding, and to - * improve code readability and style over the previous zlib inflate code - * - * 1.2.beta1 25 Nov 2002 - * - Use pointers for available input and output checking in inffast.c - * - Remove input and output counters in inffast.c - * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 - * - Remove unnecessary second byte pull from length extra in inffast.c - * - Unroll direct copy to three copies per loop in inffast.c - * - * 1.2.beta2 4 Dec 2002 - * - Change external routine names to reduce potential conflicts - * - Correct filename to inffixed.h for fixed tables in inflate.c - * - Make hbuf[] unsigned char to match parameter type in inflate.c - * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) - * to avoid negation problem on Alphas (64 bit) in inflate.c - * - * 1.2.beta3 22 Dec 2002 - * - Add comments on state->bits assertion in inffast.c - * - Add comments on op field in inftrees.h - * - Fix bug in reuse of allocated window after inflateReset() - * - Remove bit fields--back to byte structure for speed - * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths - * - Change post-increments to pre-increments in inflate_fast(), PPC biased? - * - Add compile time option, POSTINC, to use post-increments instead (Intel?) - * - Make MATCH copy in inflate() much faster for when inflate_fast() not used - * - Use local copies of stream next and avail values, as well as local bit - * buffer and bit count in inflate()--for speed when inflate_fast() not used - * - * 1.2.beta4 1 Jan 2003 - * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings - * - Move a comment on output buffer sizes from inffast.c to inflate.c - * - Add comments in inffast.c to introduce the inflate_fast() routine - * - Rearrange window copies in inflate_fast() for speed and simplification - * - Unroll last copy for window match in inflate_fast() - * - Use local copies of window variables in inflate_fast() for speed - * - Pull out common write == 0 case for speed in inflate_fast() - * - Make op and len in inflate_fast() unsigned for consistency - * - Add FAR to lcode and dcode declarations in inflate_fast() - * - Simplified bad distance check in inflate_fast() - * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new - * source file infback.c to provide a call-back interface to inflate for - * programs like gzip and unzip -- uses window as output buffer to avoid - * window copying - * - * 1.2.beta5 1 Jan 2003 - * - Improved inflateBack() interface to allow the caller to provide initial - * input in strm. - * - Fixed stored blocks bug in inflateBack() - * - * 1.2.beta6 4 Jan 2003 - * - Added comments in inffast.c on effectiveness of POSTINC - * - Typecasting all around to reduce compiler warnings - * - Changed loops from while (1) or do {} while (1) to for (;;), again to - * make compilers happy - * - Changed type of window in inflateBackInit() to unsigned char * - * - * 1.2.beta7 27 Jan 2003 - * - Changed many types to unsigned or unsigned short to avoid warnings - * - Added inflateCopy() function - * - * 1.2.0 9 Mar 2003 - * - Changed inflateBack() interface to provide separate opaque descriptors - * for the in() and out() functions - * - Changed inflateBack() argument and in_func typedef to swap the length - * and buffer address return values for the input function - * - Check next_in and next_out for Z_NULL on entry to inflate() - * - * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. - */ - -#include "zutil.h" -#include "inftrees.h" -#include "inflate.h" -#include "inffast.h" - -#ifdef MAKEFIXED -# ifndef BUILDFIXED -# define BUILDFIXED -# endif -#endif - -/* function prototypes */ -local void fixedtables OF((struct inflate_state FAR *state)); -local int updatewindow OF((z_streamp strm, unsigned out)); -#ifdef BUILDFIXED - void makefixed OF((void)); -#endif -local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf, - unsigned len)); - -int ZEXPORT inflateReset(strm) -z_streamp strm; -{ - struct inflate_state FAR *state; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - strm->total_in = strm->total_out = state->total = 0; - strm->msg = Z_NULL; - strm->adler = 1; /* to support ill-conceived Java test suite */ - state->mode = HEAD; - state->last = 0; - state->havedict = 0; - state->dmax = 32768U; - state->head = Z_NULL; - state->wsize = 0; - state->whave = 0; - state->write = 0; - state->hold = 0; - state->bits = 0; - state->lencode = state->distcode = state->next = state->codes; - Tracev((stderr, "inflate: reset\n")); - return Z_OK; -} - -int ZEXPORT inflatePrime(strm, bits, value) -z_streamp strm; -int bits; -int value; -{ - struct inflate_state FAR *state; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR; - value &= (1L << bits) - 1; - state->hold += value << state->bits; - state->bits += bits; - return Z_OK; -} - -int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) -z_streamp strm; -int windowBits; -const char *version; -int stream_size; -{ - struct inflate_state FAR *state; - - if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || - stream_size != (int)(sizeof(z_stream))) - return Z_VERSION_ERROR; - if (strm == Z_NULL) return Z_STREAM_ERROR; - strm->msg = Z_NULL; /* in case we return an error */ - if (strm->zalloc == (alloc_func)0) { - strm->zalloc = zcalloc; - strm->opaque = (voidpf)0; - } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; - state = (struct inflate_state FAR *) - ZALLOC(strm, 1, sizeof(struct inflate_state)); - if (state == Z_NULL) return Z_MEM_ERROR; - Tracev((stderr, "inflate: allocated\n")); - strm->state = (struct internal_state FAR *)state; - if (windowBits < 0) { - state->wrap = 0; - windowBits = -windowBits; - } - else { - state->wrap = (windowBits >> 4) + 1; -#ifdef GUNZIP - if (windowBits < 48) windowBits &= 15; -#endif - } - if (windowBits < 8 || windowBits > 15) { - ZFREE(strm, state); - strm->state = Z_NULL; - return Z_STREAM_ERROR; - } - state->wbits = (unsigned)windowBits; - state->window = Z_NULL; - return inflateReset(strm); -} - -int ZEXPORT inflateInit_(strm, version, stream_size) -z_streamp strm; -const char *version; -int stream_size; -{ - return inflateInit2_(strm, DEF_WBITS, version, stream_size); -} - -/* - Return state with length and distance decoding tables and index sizes set to - fixed code decoding. Normally this returns fixed tables from inffixed.h. - If BUILDFIXED is defined, then instead this routine builds the tables the - first time it's called, and returns those tables the first time and - thereafter. This reduces the size of the code by about 2K bytes, in - exchange for a little execution time. However, BUILDFIXED should not be - used for threaded applications, since the rewriting of the tables and virgin - may not be thread-safe. - */ -local void fixedtables(state) -struct inflate_state FAR *state; -{ -#ifdef BUILDFIXED - static int virgin = 1; - static code *lenfix, *distfix; - static code fixed[544]; - - /* build fixed huffman tables if first call (may not be thread safe) */ - if (virgin) { - unsigned sym, bits; - static code *next; - - /* literal/length table */ - sym = 0; - while (sym < 144) state->lens[sym++] = 8; - while (sym < 256) state->lens[sym++] = 9; - while (sym < 280) state->lens[sym++] = 7; - while (sym < 288) state->lens[sym++] = 8; - next = fixed; - lenfix = next; - bits = 9; - inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); - - /* distance table */ - sym = 0; - while (sym < 32) state->lens[sym++] = 5; - distfix = next; - bits = 5; - inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); - - /* do this just once */ - virgin = 0; - } -#else /* !BUILDFIXED */ -# include "inffixed.h" -#endif /* BUILDFIXED */ - state->lencode = lenfix; - state->lenbits = 9; - state->distcode = distfix; - state->distbits = 5; -} - -#ifdef MAKEFIXED -#include - -/* - Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also - defines BUILDFIXED, so the tables are built on the fly. makefixed() writes - those tables to stdout, which would be piped to inffixed.h. A small program - can simply call makefixed to do this: - - void makefixed(void); - - int main(void) - { - makefixed(); - return 0; - } - - Then that can be linked with zlib built with MAKEFIXED defined and run: - - a.out > inffixed.h - */ -void makefixed() -{ - unsigned low, size; - struct inflate_state state; - - fixedtables(&state); - puts(" /* inffixed.h -- table for decoding fixed codes"); - puts(" * Generated automatically by makefixed()."); - puts(" */"); - puts(""); - puts(" /* WARNING: this file should *not* be used by applications."); - puts(" It is part of the implementation of this library and is"); - puts(" subject to change. Applications should only use zlib.h."); - puts(" */"); - puts(""); - size = 1U << 9; - printf(" static const code lenfix[%u] = {", size); - low = 0; - for (;;) { - if ((low % 7) == 0) printf("\n "); - printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits, - state.lencode[low].val); - if (++low == size) break; - putchar(','); - } - puts("\n };"); - size = 1U << 5; - printf("\n static const code distfix[%u] = {", size); - low = 0; - for (;;) { - if ((low % 6) == 0) printf("\n "); - printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, - state.distcode[low].val); - if (++low == size) break; - putchar(','); - } - puts("\n };"); -} -#endif /* MAKEFIXED */ - -/* - Update the window with the last wsize (normally 32K) bytes written before - returning. If window does not exist yet, create it. This is only called - when a window is already in use, or when output has been written during this - inflate call, but the end of the deflate stream has not been reached yet. - It is also called to create a window for dictionary data when a dictionary - is loaded. - - Providing output buffers larger than 32K to inflate() should provide a speed - advantage, since only the last 32K of output is copied to the sliding window - upon return from inflate(), and since all distances after the first 32K of - output will fall in the output data, making match copies simpler and faster. - The advantage may be dependent on the size of the processor's data caches. - */ -local int updatewindow(strm, out) -z_streamp strm; -unsigned out; -{ - struct inflate_state FAR *state; - unsigned copy, dist; - - state = (struct inflate_state FAR *)strm->state; - - /* if it hasn't been done already, allocate space for the window */ - if (state->window == Z_NULL) { - state->window = (unsigned char FAR *) - ZALLOC(strm, 1U << state->wbits, - sizeof(unsigned char)); - if (state->window == Z_NULL) return 1; - } - - /* if window not in use yet, initialize */ - if (state->wsize == 0) { - state->wsize = 1U << state->wbits; - state->write = 0; - state->whave = 0; - } - - /* copy state->wsize or less output bytes into the circular window */ - copy = out - strm->avail_out; - if (copy >= state->wsize) { - zmemcpy(state->window, strm->next_out - state->wsize, state->wsize); - state->write = 0; - state->whave = state->wsize; - } - else { - dist = state->wsize - state->write; - if (dist > copy) dist = copy; - zmemcpy(state->window + state->write, strm->next_out - copy, dist); - copy -= dist; - if (copy) { - zmemcpy(state->window, strm->next_out - copy, copy); - state->write = copy; - state->whave = state->wsize; - } - else { - state->write += dist; - if (state->write == state->wsize) state->write = 0; - if (state->whave < state->wsize) state->whave += dist; - } - } - return 0; -} - -/* Macros for inflate(): */ - -/* check function to use adler32() for zlib or crc32() for gzip */ -#ifdef GUNZIP -# define UPDATE(check, buf, len) \ - (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) -#else -# define UPDATE(check, buf, len) adler32(check, buf, len) -#endif - -/* check macros for header crc */ -#ifdef GUNZIP -# define CRC2(check, word) \ - do { \ - hbuf[0] = (unsigned char)(word); \ - hbuf[1] = (unsigned char)((word) >> 8); \ - check = crc32(check, hbuf, 2); \ - } while (0) - -# define CRC4(check, word) \ - do { \ - hbuf[0] = (unsigned char)(word); \ - hbuf[1] = (unsigned char)((word) >> 8); \ - hbuf[2] = (unsigned char)((word) >> 16); \ - hbuf[3] = (unsigned char)((word) >> 24); \ - check = crc32(check, hbuf, 4); \ - } while (0) -#endif - -/* Load registers with state in inflate() for speed */ -#define LOAD() \ - do { \ - put = strm->next_out; \ - left = strm->avail_out; \ - next = strm->next_in; \ - have = strm->avail_in; \ - hold = state->hold; \ - bits = state->bits; \ - } while (0) - -/* Restore state from registers in inflate() */ -#define RESTORE() \ - do { \ - strm->next_out = put; \ - strm->avail_out = left; \ - strm->next_in = next; \ - strm->avail_in = have; \ - state->hold = hold; \ - state->bits = bits; \ - } while (0) - -/* Clear the input bit accumulator */ -#define INITBITS() \ - do { \ - hold = 0; \ - bits = 0; \ - } while (0) - -/* Get a byte of input into the bit accumulator, or return from inflate() - if there is no input available. */ -#define PULLBYTE() \ - do { \ - if (have == 0) goto inf_leave; \ - have--; \ - hold += (unsigned long)(*next++) << bits; \ - bits += 8; \ - } while (0) - -/* Assure that there are at least n bits in the bit accumulator. If there is - not enough available input to do that, then return from inflate(). */ -#define NEEDBITS(n) \ - do { \ - while (bits < (unsigned)(n)) \ - PULLBYTE(); \ - } while (0) - -/* Return the low n bits of the bit accumulator (n < 16) */ -#define BITS(n) \ - ((unsigned)hold & ((1U << (n)) - 1)) - -/* Remove n bits from the bit accumulator */ -#define DROPBITS(n) \ - do { \ - hold >>= (n); \ - bits -= (unsigned)(n); \ - } while (0) - -/* Remove zero to seven bits as needed to go to a byte boundary */ -#define BYTEBITS() \ - do { \ - hold >>= bits & 7; \ - bits -= bits & 7; \ - } while (0) - -/* Reverse the bytes in a 32-bit value */ -#define REVERSE(q) \ - ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ - (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) - -/* - inflate() uses a state machine to process as much input data and generate as - much output data as possible before returning. The state machine is - structured roughly as follows: - - for (;;) switch (state) { - ... - case STATEn: - if (not enough input data or output space to make progress) - return; - ... make progress ... - state = STATEm; - break; - ... - } - - so when inflate() is called again, the same case is attempted again, and - if the appropriate resources are provided, the machine proceeds to the - next state. The NEEDBITS() macro is usually the way the state evaluates - whether it can proceed or should return. NEEDBITS() does the return if - the requested bits are not available. The typical use of the BITS macros - is: - - NEEDBITS(n); - ... do something with BITS(n) ... - DROPBITS(n); - - where NEEDBITS(n) either returns from inflate() if there isn't enough - input left to load n bits into the accumulator, or it continues. BITS(n) - gives the low n bits in the accumulator. When done, DROPBITS(n) drops - the low n bits off the accumulator. INITBITS() clears the accumulator - and sets the number of available bits to zero. BYTEBITS() discards just - enough bits to put the accumulator on a byte boundary. After BYTEBITS() - and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. - - NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return - if there is no input available. The decoding of variable length codes uses - PULLBYTE() directly in order to pull just enough bytes to decode the next - code, and no more. - - Some states loop until they get enough input, making sure that enough - state information is maintained to continue the loop where it left off - if NEEDBITS() returns in the loop. For example, want, need, and keep - would all have to actually be part of the saved state in case NEEDBITS() - returns: - - case STATEw: - while (want < need) { - NEEDBITS(n); - keep[want++] = BITS(n); - DROPBITS(n); - } - state = STATEx; - case STATEx: - - As shown above, if the next state is also the next case, then the break - is omitted. - - A state may also return if there is not enough output space available to - complete that state. Those states are copying stored data, writing a - literal byte, and copying a matching string. - - When returning, a "goto inf_leave" is used to update the total counters, - update the check value, and determine whether any progress has been made - during that inflate() call in order to return the proper return code. - Progress is defined as a change in either strm->avail_in or strm->avail_out. - When there is a window, goto inf_leave will update the window with the last - output written. If a goto inf_leave occurs in the middle of decompression - and there is no window currently, goto inf_leave will create one and copy - output to the window for the next call of inflate(). - - In this implementation, the flush parameter of inflate() only affects the - return code (per zlib.h). inflate() always writes as much as possible to - strm->next_out, given the space available and the provided input--the effect - documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers - the allocation of and copying into a sliding window until necessary, which - provides the effect documented in zlib.h for Z_FINISH when the entire input - stream available. So the only thing the flush parameter actually does is: - when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it - will return Z_BUF_ERROR if it has not reached the end of the stream. - */ - -int ZEXPORT inflate(strm, flush) -z_streamp strm; -int flush; -{ - struct inflate_state FAR *state; - unsigned char FAR *next; /* next input */ - unsigned char FAR *put; /* next output */ - unsigned have, left; /* available input and output */ - unsigned long hold; /* bit buffer */ - unsigned bits; /* bits in bit buffer */ - unsigned in, out; /* save starting available input and output */ - unsigned copy; /* number of stored or match bytes to copy */ - unsigned char FAR *from; /* where to copy match bytes from */ - code this; /* current decoding table entry */ - code last; /* parent table entry */ - unsigned len; /* length to copy for repeats, bits to drop */ - int ret; /* return code */ -#ifdef GUNZIP - unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ -#endif - static const unsigned short order[19] = /* permutation of code lengths */ - {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; - - if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL || - (strm->next_in == Z_NULL && strm->avail_in != 0)) - return Z_STREAM_ERROR; - - state = (struct inflate_state FAR *)strm->state; - if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ - LOAD(); - in = have; - out = left; - ret = Z_OK; - for (;;) - switch (state->mode) { - case HEAD: - if (state->wrap == 0) { - state->mode = TYPEDO; - break; - } - NEEDBITS(16); -#ifdef GUNZIP - if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ - state->check = crc32(0L, Z_NULL, 0); - CRC2(state->check, hold); - INITBITS(); - state->mode = FLAGS; - break; - } - state->flags = 0; /* expect zlib header */ - if (state->head != Z_NULL) - state->head->done = -1; - if (!(state->wrap & 1) || /* check if zlib header allowed */ -#else - if ( -#endif - ((BITS(8) << 8) + (hold >> 8)) % 31) { - strm->msg = (char *)"incorrect header check"; - state->mode = BAD; - break; - } - if (BITS(4) != Z_DEFLATED) { - strm->msg = (char *)"unknown compression method"; - state->mode = BAD; - break; - } - DROPBITS(4); - len = BITS(4) + 8; - if (len > state->wbits) { - strm->msg = (char *)"invalid window size"; - state->mode = BAD; - break; - } - state->dmax = 1U << len; - Tracev((stderr, "inflate: zlib header ok\n")); - strm->adler = state->check = adler32(0L, Z_NULL, 0); - state->mode = hold & 0x200 ? DICTID : TYPE; - INITBITS(); - break; -#ifdef GUNZIP - case FLAGS: - NEEDBITS(16); - state->flags = (int)(hold); - if ((state->flags & 0xff) != Z_DEFLATED) { - strm->msg = (char *)"unknown compression method"; - state->mode = BAD; - break; - } - if (state->flags & 0xe000) { - strm->msg = (char *)"unknown header flags set"; - state->mode = BAD; - break; - } - if (state->head != Z_NULL) - state->head->text = (int)((hold >> 8) & 1); - if (state->flags & 0x0200) CRC2(state->check, hold); - INITBITS(); - state->mode = TIME; - case TIME: - NEEDBITS(32); - if (state->head != Z_NULL) - state->head->time = hold; - if (state->flags & 0x0200) CRC4(state->check, hold); - INITBITS(); - state->mode = OS; - case OS: - NEEDBITS(16); - if (state->head != Z_NULL) { - state->head->xflags = (int)(hold & 0xff); - state->head->os = (int)(hold >> 8); - } - if (state->flags & 0x0200) CRC2(state->check, hold); - INITBITS(); - state->mode = EXLEN; - case EXLEN: - if (state->flags & 0x0400) { - NEEDBITS(16); - state->length = (unsigned)(hold); - if (state->head != Z_NULL) - state->head->extra_len = (unsigned)hold; - if (state->flags & 0x0200) CRC2(state->check, hold); - INITBITS(); - } - else if (state->head != Z_NULL) - state->head->extra = Z_NULL; - state->mode = EXTRA; - case EXTRA: - if (state->flags & 0x0400) { - copy = state->length; - if (copy > have) copy = have; - if (copy) { - if (state->head != Z_NULL && - state->head->extra != Z_NULL) { - len = state->head->extra_len - state->length; - zmemcpy(state->head->extra + len, next, - len + copy > state->head->extra_max ? - state->head->extra_max - len : copy); - } - if (state->flags & 0x0200) - state->check = crc32(state->check, next, copy); - have -= copy; - next += copy; - state->length -= copy; - } - if (state->length) goto inf_leave; - } - state->length = 0; - state->mode = NAME; - case NAME: - if (state->flags & 0x0800) { - if (have == 0) goto inf_leave; - copy = 0; - do { - len = (unsigned)(next[copy++]); - if (state->head != Z_NULL && - state->head->name != Z_NULL && - state->length < state->head->name_max) - state->head->name[state->length++] = len; - } while (len && copy < have); - if (state->flags & 0x0200) - state->check = crc32(state->check, next, copy); - have -= copy; - next += copy; - if (len) goto inf_leave; - } - else if (state->head != Z_NULL) - state->head->name = Z_NULL; - state->length = 0; - state->mode = COMMENT; - case COMMENT: - if (state->flags & 0x1000) { - if (have == 0) goto inf_leave; - copy = 0; - do { - len = (unsigned)(next[copy++]); - if (state->head != Z_NULL && - state->head->comment != Z_NULL && - state->length < state->head->comm_max) - state->head->comment[state->length++] = len; - } while (len && copy < have); - if (state->flags & 0x0200) - state->check = crc32(state->check, next, copy); - have -= copy; - next += copy; - if (len) goto inf_leave; - } - else if (state->head != Z_NULL) - state->head->comment = Z_NULL; - state->mode = HCRC; - case HCRC: - if (state->flags & 0x0200) { - NEEDBITS(16); - if (hold != (state->check & 0xffff)) { - strm->msg = (char *)"header crc mismatch"; - state->mode = BAD; - break; - } - INITBITS(); - } - if (state->head != Z_NULL) { - state->head->hcrc = (int)((state->flags >> 9) & 1); - state->head->done = 1; - } - strm->adler = state->check = crc32(0L, Z_NULL, 0); - state->mode = TYPE; - break; -#endif - case DICTID: - NEEDBITS(32); - strm->adler = state->check = REVERSE(hold); - INITBITS(); - state->mode = DICT; - case DICT: - if (state->havedict == 0) { - RESTORE(); - return Z_NEED_DICT; - } - strm->adler = state->check = adler32(0L, Z_NULL, 0); - state->mode = TYPE; - case TYPE: - if (flush == Z_BLOCK) goto inf_leave; - case TYPEDO: - if (state->last) { - BYTEBITS(); - state->mode = CHECK; - break; - } - NEEDBITS(3); - state->last = BITS(1); - DROPBITS(1); - switch (BITS(2)) { - case 0: /* stored block */ - Tracev((stderr, "inflate: stored block%s\n", - state->last ? " (last)" : "")); - state->mode = STORED; - break; - case 1: /* fixed block */ - fixedtables(state); - Tracev((stderr, "inflate: fixed codes block%s\n", - state->last ? " (last)" : "")); - state->mode = LEN; /* decode codes */ - break; - case 2: /* dynamic block */ - Tracev((stderr, "inflate: dynamic codes block%s\n", - state->last ? " (last)" : "")); - state->mode = TABLE; - break; - case 3: - strm->msg = (char *)"invalid block type"; - state->mode = BAD; - } - DROPBITS(2); - break; - case STORED: - BYTEBITS(); /* go to byte boundary */ - NEEDBITS(32); - if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { - strm->msg = (char *)"invalid stored block lengths"; - state->mode = BAD; - break; - } - state->length = (unsigned)hold & 0xffff; - Tracev((stderr, "inflate: stored length %u\n", - state->length)); - INITBITS(); - state->mode = COPY; - case COPY: - copy = state->length; - if (copy) { - if (copy > have) copy = have; - if (copy > left) copy = left; - if (copy == 0) goto inf_leave; - zmemcpy(put, next, copy); - have -= copy; - next += copy; - left -= copy; - put += copy; - state->length -= copy; - break; - } - Tracev((stderr, "inflate: stored end\n")); - state->mode = TYPE; - break; - case TABLE: - NEEDBITS(14); - state->nlen = BITS(5) + 257; - DROPBITS(5); - state->ndist = BITS(5) + 1; - DROPBITS(5); - state->ncode = BITS(4) + 4; - DROPBITS(4); -#ifndef PKZIP_BUG_WORKAROUND - if (state->nlen > 286 || state->ndist > 30) { - strm->msg = (char *)"too many length or distance symbols"; - state->mode = BAD; - break; - } -#endif - Tracev((stderr, "inflate: table sizes ok\n")); - state->have = 0; - state->mode = LENLENS; - case LENLENS: - while (state->have < state->ncode) { - NEEDBITS(3); - state->lens[order[state->have++]] = (unsigned short)BITS(3); - DROPBITS(3); - } - while (state->have < 19) - state->lens[order[state->have++]] = 0; - state->next = state->codes; - state->lencode = (code const FAR *)(state->next); - state->lenbits = 7; - ret = inflate_table(CODES, state->lens, 19, &(state->next), - &(state->lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid code lengths set"; - state->mode = BAD; - break; - } - Tracev((stderr, "inflate: code lengths ok\n")); - state->have = 0; - state->mode = CODELENS; - case CODELENS: - while (state->have < state->nlen + state->ndist) { - for (;;) { - this = state->lencode[BITS(state->lenbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if (this.val < 16) { - NEEDBITS(this.bits); - DROPBITS(this.bits); - state->lens[state->have++] = this.val; - } - else { - if (this.val == 16) { - NEEDBITS(this.bits + 2); - DROPBITS(this.bits); - if (state->have == 0) { - strm->msg = (char *)"invalid bit length repeat"; - state->mode = BAD; - break; - } - len = state->lens[state->have - 1]; - copy = 3 + BITS(2); - DROPBITS(2); - } - else if (this.val == 17) { - NEEDBITS(this.bits + 3); - DROPBITS(this.bits); - len = 0; - copy = 3 + BITS(3); - DROPBITS(3); - } - else { - NEEDBITS(this.bits + 7); - DROPBITS(this.bits); - len = 0; - copy = 11 + BITS(7); - DROPBITS(7); - } - if (state->have + copy > state->nlen + state->ndist) { - strm->msg = (char *)"invalid bit length repeat"; - state->mode = BAD; - break; - } - while (copy--) - state->lens[state->have++] = (unsigned short)len; - } - } - - /* handle error breaks in while */ - if (state->mode == BAD) break; - - /* build code tables */ - state->next = state->codes; - state->lencode = (code const FAR *)(state->next); - state->lenbits = 9; - ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), - &(state->lenbits), state->work); - if (ret) { - strm->msg = (char *)"invalid literal/lengths set"; - state->mode = BAD; - break; - } - state->distcode = (code const FAR *)(state->next); - state->distbits = 6; - ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, - &(state->next), &(state->distbits), state->work); - if (ret) { - strm->msg = (char *)"invalid distances set"; - state->mode = BAD; - break; - } - Tracev((stderr, "inflate: codes ok\n")); - state->mode = LEN; - case LEN: - if (have >= 6 && left >= 258) { - RESTORE(); - inflate_fast(strm, out); - LOAD(); - break; - } - for (;;) { - this = state->lencode[BITS(state->lenbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if (this.op && (this.op & 0xf0) == 0) { - last = this; - for (;;) { - this = state->lencode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + this.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - } - DROPBITS(this.bits); - state->length = (unsigned)this.val; - if ((int)(this.op) == 0) { - Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ? - "inflate: literal '%c'\n" : - "inflate: literal 0x%02x\n", this.val)); - state->mode = LIT; - break; - } - if (this.op & 32) { - Tracevv((stderr, "inflate: end of block\n")); - state->mode = TYPE; - break; - } - if (this.op & 64) { - strm->msg = (char *)"invalid literal/length code"; - state->mode = BAD; - break; - } - state->extra = (unsigned)(this.op) & 15; - state->mode = LENEXT; - case LENEXT: - if (state->extra) { - NEEDBITS(state->extra); - state->length += BITS(state->extra); - DROPBITS(state->extra); - } - Tracevv((stderr, "inflate: length %u\n", state->length)); - state->mode = DIST; - case DIST: - for (;;) { - this = state->distcode[BITS(state->distbits)]; - if ((unsigned)(this.bits) <= bits) break; - PULLBYTE(); - } - if ((this.op & 0xf0) == 0) { - last = this; - for (;;) { - this = state->distcode[last.val + - (BITS(last.bits + last.op) >> last.bits)]; - if ((unsigned)(last.bits + this.bits) <= bits) break; - PULLBYTE(); - } - DROPBITS(last.bits); - } - DROPBITS(this.bits); - if (this.op & 64) { - strm->msg = (char *)"invalid distance code"; - state->mode = BAD; - break; - } - state->offset = (unsigned)this.val; - state->extra = (unsigned)(this.op) & 15; - state->mode = DISTEXT; - case DISTEXT: - if (state->extra) { - NEEDBITS(state->extra); - state->offset += BITS(state->extra); - DROPBITS(state->extra); - } -#ifdef INFLATE_STRICT - if (state->offset > state->dmax) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } -#endif - if (state->offset > state->whave + out - left) { - strm->msg = (char *)"invalid distance too far back"; - state->mode = BAD; - break; - } - Tracevv((stderr, "inflate: distance %u\n", state->offset)); - state->mode = MATCH; - case MATCH: - if (left == 0) goto inf_leave; - copy = out - left; - if (state->offset > copy) { /* copy from window */ - copy = state->offset - copy; - if (copy > state->write) { - copy -= state->write; - from = state->window + (state->wsize - copy); - } - else - from = state->window + (state->write - copy); - if (copy > state->length) copy = state->length; - } - else { /* copy from output */ - from = put - state->offset; - copy = state->length; - } - if (copy > left) copy = left; - left -= copy; - state->length -= copy; - do { - *put++ = *from++; - } while (--copy); - if (state->length == 0) state->mode = LEN; - break; - case LIT: - if (left == 0) goto inf_leave; - *put++ = (unsigned char)(state->length); - left--; - state->mode = LEN; - break; - case CHECK: - if (state->wrap) { - NEEDBITS(32); - out -= left; - strm->total_out += out; - state->total += out; - if (out) - strm->adler = state->check = - UPDATE(state->check, put - out, out); - out = left; - if (( -#ifdef GUNZIP - state->flags ? hold : -#endif - REVERSE(hold)) != state->check) { - strm->msg = (char *)"incorrect data check"; - state->mode = BAD; - break; - } - INITBITS(); - Tracev((stderr, "inflate: check matches trailer\n")); - } -#ifdef GUNZIP - state->mode = LENGTH; - case LENGTH: - if (state->wrap && state->flags) { - NEEDBITS(32); - if (hold != (state->total & 0xffffffffUL)) { - strm->msg = (char *)"incorrect length check"; - state->mode = BAD; - break; - } - INITBITS(); - Tracev((stderr, "inflate: length matches trailer\n")); - } -#endif - state->mode = DONE; - case DONE: - ret = Z_STREAM_END; - goto inf_leave; - case BAD: - ret = Z_DATA_ERROR; - goto inf_leave; - case MEM: - return Z_MEM_ERROR; - case SYNC: - default: - return Z_STREAM_ERROR; - } - - /* - Return from inflate(), updating the total counts and the check value. - If there was no progress during the inflate() call, return a buffer - error. Call updatewindow() to create and/or update the window state. - Note: a memory error from inflate() is non-recoverable. - */ - inf_leave: - RESTORE(); - if (state->wsize || (state->mode < CHECK && out != strm->avail_out)) - if (updatewindow(strm, out)) { - state->mode = MEM; - return Z_MEM_ERROR; - } - in -= strm->avail_in; - out -= strm->avail_out; - strm->total_in += in; - strm->total_out += out; - state->total += out; - if (state->wrap && out) - strm->adler = state->check = - UPDATE(state->check, strm->next_out - out, out); - strm->data_type = state->bits + (state->last ? 64 : 0) + - (state->mode == TYPE ? 128 : 0); - if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) - ret = Z_BUF_ERROR; - return ret; -} - -int ZEXPORT inflateEnd(strm) -z_streamp strm; -{ - struct inflate_state FAR *state; - if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) - return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if (state->window != Z_NULL) ZFREE(strm, state->window); - ZFREE(strm, strm->state); - strm->state = Z_NULL; - Tracev((stderr, "inflate: end\n")); - return Z_OK; -} - -int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) -z_streamp strm; -const Bytef *dictionary; -uInt dictLength; -{ - struct inflate_state FAR *state; - unsigned long id; - - /* check state */ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if (state->wrap != 0 && state->mode != DICT) - return Z_STREAM_ERROR; - - /* check for correct dictionary id */ - if (state->mode == DICT) { - id = adler32(0L, Z_NULL, 0); - id = adler32(id, dictionary, dictLength); - if (id != state->check) - return Z_DATA_ERROR; - } - - /* copy dictionary to window */ - if (updatewindow(strm, strm->avail_out)) { - state->mode = MEM; - return Z_MEM_ERROR; - } - if (dictLength > state->wsize) { - zmemcpy(state->window, dictionary + dictLength - state->wsize, - state->wsize); - state->whave = state->wsize; - } - else { - zmemcpy(state->window + state->wsize - dictLength, dictionary, - dictLength); - state->whave = dictLength; - } - state->havedict = 1; - Tracev((stderr, "inflate: dictionary set\n")); - return Z_OK; -} - -int ZEXPORT inflateGetHeader(strm, head) -z_streamp strm; -gz_headerp head; -{ - struct inflate_state FAR *state; - - /* check state */ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; - - /* save header structure */ - state->head = head; - head->done = 0; - return Z_OK; -} - -/* - Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found - or when out of input. When called, *have is the number of pattern bytes - found in order so far, in 0..3. On return *have is updated to the new - state. If on return *have equals four, then the pattern was found and the - return value is how many bytes were read including the last byte of the - pattern. If *have is less than four, then the pattern has not been found - yet and the return value is len. In the latter case, syncsearch() can be - called again with more data and the *have state. *have is initialized to - zero for the first call. - */ -local unsigned syncsearch(have, buf, len) -unsigned FAR *have; -unsigned char FAR *buf; -unsigned len; -{ - unsigned got; - unsigned next; - - got = *have; - next = 0; - while (next < len && got < 4) { - if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) - got++; - else if (buf[next]) - got = 0; - else - got = 4 - got; - next++; - } - *have = got; - return next; -} - -int ZEXPORT inflateSync(strm) -z_streamp strm; -{ - unsigned len; /* number of bytes to look at or looked at */ - unsigned long in, out; /* temporary to save total_in and total_out */ - unsigned char buf[4]; /* to restore bit buffer to byte string */ - struct inflate_state FAR *state; - - /* check parameters */ - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; - - /* if first time, start search in bit buffer */ - if (state->mode != SYNC) { - state->mode = SYNC; - state->hold <<= state->bits & 7; - state->bits -= state->bits & 7; - len = 0; - while (state->bits >= 8) { - buf[len++] = (unsigned char)(state->hold); - state->hold >>= 8; - state->bits -= 8; - } - state->have = 0; - syncsearch(&(state->have), buf, len); - } - - /* search available input */ - len = syncsearch(&(state->have), strm->next_in, strm->avail_in); - strm->avail_in -= len; - strm->next_in += len; - strm->total_in += len; - - /* return no joy or set up to restart inflate() on a new block */ - if (state->have != 4) return Z_DATA_ERROR; - in = strm->total_in; out = strm->total_out; - inflateReset(strm); - strm->total_in = in; strm->total_out = out; - state->mode = TYPE; - return Z_OK; -} - -/* - Returns true if inflate is currently at the end of a block generated by - Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP - implementation to provide an additional safety check. PPP uses - Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored - block. When decompressing, PPP checks that at the end of input packet, - inflate is waiting for these length bytes. - */ -int ZEXPORT inflateSyncPoint(strm) -z_streamp strm; -{ - struct inflate_state FAR *state; - - if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)strm->state; - return state->mode == STORED && state->bits == 0; -} - -int ZEXPORT inflateCopy(dest, source) -z_streamp dest; -z_streamp source; -{ - struct inflate_state FAR *state; - struct inflate_state FAR *copy; - unsigned char FAR *window; - unsigned wsize; - - /* check input */ - if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL || - source->zalloc == (alloc_func)0 || source->zfree == (free_func)0) - return Z_STREAM_ERROR; - state = (struct inflate_state FAR *)source->state; - - /* allocate space */ - copy = (struct inflate_state FAR *) - ZALLOC(source, 1, sizeof(struct inflate_state)); - if (copy == Z_NULL) return Z_MEM_ERROR; - window = Z_NULL; - if (state->window != Z_NULL) { - window = (unsigned char FAR *) - ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); - if (window == Z_NULL) { - ZFREE(source, copy); - return Z_MEM_ERROR; - } - } - - /* copy state */ - zmemcpy(dest, source, sizeof(z_stream)); - zmemcpy(copy, state, sizeof(struct inflate_state)); - if (state->lencode >= state->codes && - state->lencode <= state->codes + ENOUGH - 1) { - copy->lencode = copy->codes + (state->lencode - state->codes); - copy->distcode = copy->codes + (state->distcode - state->codes); - } - copy->next = copy->codes + (state->next - state->codes); - if (window != Z_NULL) { - wsize = 1U << state->wbits; - zmemcpy(window, state->window, wsize); - } - copy->window = window; - dest->state = (struct internal_state FAR *)copy; - return Z_OK; -} diff --git a/dep/StormLib/src/zlib/inflate.h b/dep/StormLib/src/zlib/inflate.h deleted file mode 100644 index 07bd3e78a7c..00000000000 --- a/dep/StormLib/src/zlib/inflate.h +++ /dev/null @@ -1,115 +0,0 @@ -/* inflate.h -- internal inflate state definition - * Copyright (C) 1995-2004 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* define NO_GZIP when compiling if you want to disable gzip header and - trailer decoding by inflate(). NO_GZIP would be used to avoid linking in - the crc code when it is not needed. For shared libraries, gzip decoding - should be left enabled. */ -#ifndef NO_GZIP -# define GUNZIP -#endif - -/* Possible inflate modes between inflate() calls */ -typedef enum { - HEAD, /* i: waiting for magic header */ - FLAGS, /* i: waiting for method and flags (gzip) */ - TIME, /* i: waiting for modification time (gzip) */ - OS, /* i: waiting for extra flags and operating system (gzip) */ - EXLEN, /* i: waiting for extra length (gzip) */ - EXTRA, /* i: waiting for extra bytes (gzip) */ - NAME, /* i: waiting for end of file name (gzip) */ - COMMENT, /* i: waiting for end of comment (gzip) */ - HCRC, /* i: waiting for header crc (gzip) */ - DICTID, /* i: waiting for dictionary check value */ - DICT, /* waiting for inflateSetDictionary() call */ - TYPE, /* i: waiting for type bits, including last-flag bit */ - TYPEDO, /* i: same, but skip check to exit inflate on new block */ - STORED, /* i: waiting for stored size (length and complement) */ - COPY, /* i/o: waiting for input or output to copy stored block */ - TABLE, /* i: waiting for dynamic block table lengths */ - LENLENS, /* i: waiting for code length code lengths */ - CODELENS, /* i: waiting for length/lit and distance code lengths */ - LEN, /* i: waiting for length/lit code */ - LENEXT, /* i: waiting for length extra bits */ - DIST, /* i: waiting for distance code */ - DISTEXT, /* i: waiting for distance extra bits */ - MATCH, /* o: waiting for output space to copy string */ - LIT, /* o: waiting for output space to write literal */ - CHECK, /* i: waiting for 32-bit check value */ - LENGTH, /* i: waiting for 32-bit length (gzip) */ - DONE, /* finished check, done -- remain here until reset */ - BAD, /* got a data error -- remain here until reset */ - MEM, /* got an inflate() memory error -- remain here until reset */ - SYNC /* looking for synchronization bytes to restart inflate() */ -} inflate_mode; - -/* - State transitions between above modes - - - (most modes can go to the BAD or MEM mode -- not shown for clarity) - - Process header: - HEAD -> (gzip) or (zlib) - (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME - NAME -> COMMENT -> HCRC -> TYPE - (zlib) -> DICTID or TYPE - DICTID -> DICT -> TYPE - Read deflate blocks: - TYPE -> STORED or TABLE or LEN or CHECK - STORED -> COPY -> TYPE - TABLE -> LENLENS -> CODELENS -> LEN - Read deflate codes: - LEN -> LENEXT or LIT or TYPE - LENEXT -> DIST -> DISTEXT -> MATCH -> LEN - LIT -> LEN - Process trailer: - CHECK -> LENGTH -> DONE - */ - -/* state maintained between inflate() calls. Approximately 7K bytes. */ -struct inflate_state { - inflate_mode mode; /* current inflate mode */ - int last; /* true if processing last block */ - int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ - int havedict; /* true if dictionary provided */ - int flags; /* gzip header method and flags (0 if zlib) */ - unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */ - unsigned long check; /* protected copy of check value */ - unsigned long total; /* protected copy of output count */ - gz_headerp head; /* where to save gzip header information */ - /* sliding window */ - unsigned wbits; /* log base 2 of requested window size */ - unsigned wsize; /* window size or zero if not using window */ - unsigned whave; /* valid bytes in the window */ - unsigned write; /* window write index */ - unsigned char FAR *window; /* allocated sliding window, if needed */ - /* bit accumulator */ - unsigned long hold; /* input bit accumulator */ - unsigned bits; /* number of bits in "in" */ - /* for string and stored block copying */ - unsigned length; /* literal or length of data to copy */ - unsigned offset; /* distance back to copy string from */ - /* for table and code decoding */ - unsigned extra; /* extra bits needed */ - /* fixed and dynamic code tables */ - code const FAR *lencode; /* starting table for length/literal codes */ - code const FAR *distcode; /* starting table for distance codes */ - unsigned lenbits; /* index bits for lencode */ - unsigned distbits; /* index bits for distcode */ - /* dynamic table building */ - unsigned ncode; /* number of code length code lengths */ - unsigned nlen; /* number of length code lengths */ - unsigned ndist; /* number of distance code lengths */ - unsigned have; /* number of code lengths in lens[] */ - code FAR *next; /* next available space in codes[] */ - unsigned short lens[320]; /* temporary storage for code lengths */ - unsigned short work[288]; /* work area for code table building */ - code codes[ENOUGH]; /* space for code tables */ -}; diff --git a/dep/StormLib/src/zlib/inftrees.c b/dep/StormLib/src/zlib/inftrees.c deleted file mode 100644 index 8a9c13ff03d..00000000000 --- a/dep/StormLib/src/zlib/inftrees.c +++ /dev/null @@ -1,329 +0,0 @@ -/* inftrees.c -- generate Huffman trees for efficient decoding - * Copyright (C) 1995-2005 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -#include "zutil.h" -#include "inftrees.h" - -#define MAXBITS 15 - -const char inflate_copyright[] = - " inflate 1.2.3 Copyright 1995-2005 Mark Adler "; -/* - If you use the zlib library in a product, an acknowledgment is welcome - in the documentation of your product. If for some reason you cannot - include such an acknowledgment, I would appreciate that you keep this - copyright string in the executable of your product. - */ - -/* - Build a set of tables to decode the provided canonical Huffman code. - The code lengths are lens[0..codes-1]. The result starts at *table, - whose indices are 0..2^bits-1. work is a writable array of at least - lens shorts, which is used as a work area. type is the type of code - to be generated, CODES, LENS, or DISTS. On return, zero is success, - -1 is an invalid code, and +1 means that ENOUGH isn't enough. table - on return points to the next available entry's address. bits is the - requested root table index bits, and on return it is the actual root - table index bits. It will differ if the request is greater than the - longest code or if it is less than the shortest code. - */ -int inflate_table(type, lens, codes, table, bits, work) -codetype type; -unsigned short FAR *lens; -unsigned codes; -code FAR * FAR *table; -unsigned FAR *bits; -unsigned short FAR *work; -{ - unsigned len; /* a code's length in bits */ - unsigned sym; /* index of code symbols */ - unsigned min, max; /* minimum and maximum code lengths */ - unsigned root; /* number of index bits for root table */ - unsigned curr; /* number of index bits for current table */ - unsigned drop; /* code bits to drop for sub-table */ - int left; /* number of prefix codes available */ - unsigned used; /* code entries in table used */ - unsigned huff; /* Huffman code */ - unsigned incr; /* for incrementing code, index */ - unsigned fill; /* index for replicating entries */ - unsigned low; /* low bits for current root entry */ - unsigned mask; /* mask for low root bits */ - code this; /* table entry for duplication */ - code FAR *next; /* next available space in table */ - const unsigned short FAR *base; /* base value table to use */ - const unsigned short FAR *extra; /* extra bits table to use */ - int end; /* use base and extra for symbol > end */ - unsigned short count[MAXBITS+1]; /* number of codes of each length */ - unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ - static const unsigned short lbase[31] = { /* Length codes 257..285 base */ - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; - static const unsigned short lext[31] = { /* Length codes 257..285 extra */ - 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, - 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196}; - static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577, 0, 0}; - static const unsigned short dext[32] = { /* Distance codes 0..29 extra */ - 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, - 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, - 28, 28, 29, 29, 64, 64}; - - /* - Process a set of code lengths to create a canonical Huffman code. The - code lengths are lens[0..codes-1]. Each length corresponds to the - symbols 0..codes-1. The Huffman code is generated by first sorting the - symbols by length from short to long, and retaining the symbol order - for codes with equal lengths. Then the code starts with all zero bits - for the first code of the shortest length, and the codes are integer - increments for the same length, and zeros are appended as the length - increases. For the deflate format, these bits are stored backwards - from their more natural integer increment ordering, and so when the - decoding tables are built in the large loop below, the integer codes - are incremented backwards. - - This routine assumes, but does not check, that all of the entries in - lens[] are in the range 0..MAXBITS. The caller must assure this. - 1..MAXBITS is interpreted as that code length. zero means that that - symbol does not occur in this code. - - The codes are sorted by computing a count of codes for each length, - creating from that a table of starting indices for each length in the - sorted table, and then entering the symbols in order in the sorted - table. The sorted table is work[], with that space being provided by - the caller. - - The length counts are used for other purposes as well, i.e. finding - the minimum and maximum length codes, determining if there are any - codes at all, checking for a valid set of lengths, and looking ahead - at length counts to determine sub-table sizes when building the - decoding tables. - */ - - /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ - for (len = 0; len <= MAXBITS; len++) - count[len] = 0; - for (sym = 0; sym < codes; sym++) - count[lens[sym]]++; - - /* bound code lengths, force root to be within code lengths */ - root = *bits; - for (max = MAXBITS; max >= 1; max--) - if (count[max] != 0) break; - if (root > max) root = max; - if (max == 0) { /* no symbols to code at all */ - this.op = (unsigned char)64; /* invalid code marker */ - this.bits = (unsigned char)1; - this.val = (unsigned short)0; - *(*table)++ = this; /* make a table to force an error */ - *(*table)++ = this; - *bits = 1; - return 0; /* no symbols, but wait for decoding to report error */ - } - for (min = 1; min <= MAXBITS; min++) - if (count[min] != 0) break; - if (root < min) root = min; - - /* check for an over-subscribed or incomplete set of lengths */ - left = 1; - for (len = 1; len <= MAXBITS; len++) { - left <<= 1; - left -= count[len]; - if (left < 0) return -1; /* over-subscribed */ - } - if (left > 0 && (type == CODES || max != 1)) - return -1; /* incomplete set */ - - /* generate offsets into symbol table for each length for sorting */ - offs[1] = 0; - for (len = 1; len < MAXBITS; len++) - offs[len + 1] = offs[len] + count[len]; - - /* sort symbols by length, by symbol order within each length */ - for (sym = 0; sym < codes; sym++) - if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; - - /* - Create and fill in decoding tables. In this loop, the table being - filled is at next and has curr index bits. The code being used is huff - with length len. That code is converted to an index by dropping drop - bits off of the bottom. For codes where len is less than drop + curr, - those top drop + curr - len bits are incremented through all values to - fill the table with replicated entries. - - root is the number of index bits for the root table. When len exceeds - root, sub-tables are created pointed to by the root entry with an index - of the low root bits of huff. This is saved in low to check for when a - new sub-table should be started. drop is zero when the root table is - being filled, and drop is root when sub-tables are being filled. - - When a new sub-table is needed, it is necessary to look ahead in the - code lengths to determine what size sub-table is needed. The length - counts are used for this, and so count[] is decremented as codes are - entered in the tables. - - used keeps track of how many table entries have been allocated from the - provided *table space. It is checked when a LENS table is being made - against the space in *table, ENOUGH, minus the maximum space needed by - the worst case distance code, MAXD. This should never happen, but the - sufficiency of ENOUGH has not been proven exhaustively, hence the check. - This assumes that when type == LENS, bits == 9. - - sym increments through all symbols, and the loop terminates when - all codes of length max, i.e. all codes, have been processed. This - routine permits incomplete codes, so another loop after this one fills - in the rest of the decoding tables with invalid code markers. - */ - - /* set up for code type */ - switch (type) { - case CODES: - base = extra = work; /* dummy value--not used */ - end = 19; - break; - case LENS: - base = lbase; - base -= 257; - extra = lext; - extra -= 257; - end = 256; - break; - default: /* DISTS */ - base = dbase; - extra = dext; - end = -1; - } - - /* initialize state for loop */ - huff = 0; /* starting code */ - sym = 0; /* starting code symbol */ - len = min; /* starting code length */ - next = *table; /* current table to fill in */ - curr = root; /* current table index bits */ - drop = 0; /* current bits to drop from code for index */ - low = (unsigned)(-1); /* trigger new sub-table when len > root */ - used = 1U << root; /* use root table entries */ - mask = used - 1; /* mask for comparing low */ - - /* check available table space */ - if (type == LENS && used >= ENOUGH - MAXD) - return 1; - - /* process all codes and make table entries */ - for (;;) { - /* create table entry */ - this.bits = (unsigned char)(len - drop); - if ((int)(work[sym]) < end) { - this.op = (unsigned char)0; - this.val = work[sym]; - } - else if ((int)(work[sym]) > end) { - this.op = (unsigned char)(extra[work[sym]]); - this.val = base[work[sym]]; - } - else { - this.op = (unsigned char)(32 + 64); /* end of block */ - this.val = 0; - } - - /* replicate for those indices with low len bits equal to huff */ - incr = 1U << (len - drop); - fill = 1U << curr; - min = fill; /* save offset to next table */ - do { - fill -= incr; - next[(huff >> drop) + fill] = this; - } while (fill != 0); - - /* backwards increment the len-bit code huff */ - incr = 1U << (len - 1); - while (huff & incr) - incr >>= 1; - if (incr != 0) { - huff &= incr - 1; - huff += incr; - } - else - huff = 0; - - /* go to next symbol, update count, len */ - sym++; - if (--(count[len]) == 0) { - if (len == max) break; - len = lens[work[sym]]; - } - - /* create new sub-table if needed */ - if (len > root && (huff & mask) != low) { - /* if first time, transition to sub-tables */ - if (drop == 0) - drop = root; - - /* increment past last table */ - next += min; /* here min is 1 << curr */ - - /* determine length of next table */ - curr = len - drop; - left = (int)(1 << curr); - while (curr + drop < max) { - left -= count[curr + drop]; - if (left <= 0) break; - curr++; - left <<= 1; - } - - /* check for enough space */ - used += 1U << curr; - if (type == LENS && used >= ENOUGH - MAXD) - return 1; - - /* point entry in root table to sub-table */ - low = huff & mask; - (*table)[low].op = (unsigned char)curr; - (*table)[low].bits = (unsigned char)root; - (*table)[low].val = (unsigned short)(next - *table); - } - } - - /* - Fill in rest of table for incomplete codes. This loop is similar to the - loop above in incrementing huff for table indices. It is assumed that - len is equal to curr + drop, so there is no loop needed to increment - through high index bits. When the current sub-table is filled, the loop - drops back to the root table to fill in any remaining entries there. - */ - this.op = (unsigned char)64; /* invalid code marker */ - this.bits = (unsigned char)(len - drop); - this.val = (unsigned short)0; - while (huff != 0) { - /* when done with sub-table, drop back to root table */ - if (drop != 0 && (huff & mask) != low) { - drop = 0; - len = root; - next = *table; - this.bits = (unsigned char)len; - } - - /* put invalid code marker in table */ - next[huff >> drop] = this; - - /* backwards increment the len-bit code huff */ - incr = 1U << (len - 1); - while (huff & incr) - incr >>= 1; - if (incr != 0) { - huff &= incr - 1; - huff += incr; - } - else - huff = 0; - } - - /* set return parameters */ - *table += used; - *bits = root; - return 0; -} diff --git a/dep/StormLib/src/zlib/inftrees.h b/dep/StormLib/src/zlib/inftrees.h deleted file mode 100644 index b1104c87e76..00000000000 --- a/dep/StormLib/src/zlib/inftrees.h +++ /dev/null @@ -1,55 +0,0 @@ -/* inftrees.h -- header to use inftrees.c - * Copyright (C) 1995-2005 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* Structure for decoding tables. Each entry provides either the - information needed to do the operation requested by the code that - indexed that table entry, or it provides a pointer to another - table that indexes more bits of the code. op indicates whether - the entry is a pointer to another table, a literal, a length or - distance, an end-of-block, or an invalid code. For a table - pointer, the low four bits of op is the number of index bits of - that table. For a length or distance, the low four bits of op - is the number of extra bits to get after the code. bits is - the number of bits in this code or part of the code to drop off - of the bit buffer. val is the actual byte to output in the case - of a literal, the base length or distance, or the offset from - the current table to the next table. Each entry is four bytes. */ -typedef struct { - unsigned char op; /* operation, extra bits, table bits */ - unsigned char bits; /* bits in this part of the code */ - unsigned short val; /* offset in table or code value */ -} code; - -/* op values as set by inflate_table(): - 00000000 - literal - 0000tttt - table link, tttt != 0 is the number of table index bits - 0001eeee - length or distance, eeee is the number of extra bits - 01100000 - end of block - 01000000 - invalid code - */ - -/* Maximum size of dynamic tree. The maximum found in a long but non- - exhaustive search was 1444 code structures (852 for length/literals - and 592 for distances, the latter actually the result of an - exhaustive search). The true maximum is not known, but the value - below is more than safe. */ -#define ENOUGH 2048 -#define MAXD 592 - -/* Type of code to build for inftable() */ -typedef enum { - CODES, - LENS, - DISTS -} codetype; - -extern int inflate_table OF((codetype type, unsigned short FAR *lens, - unsigned codes, code FAR * FAR *table, - unsigned FAR *bits, unsigned short FAR *work)); diff --git a/dep/StormLib/src/zlib/trees.c b/dep/StormLib/src/zlib/trees.c deleted file mode 100644 index 395e4e16814..00000000000 --- a/dep/StormLib/src/zlib/trees.c +++ /dev/null @@ -1,1219 +0,0 @@ -/* trees.c -- output deflated data using Huffman coding - * Copyright (C) 1995-2005 Jean-loup Gailly - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* - * ALGORITHM - * - * The "deflation" process uses several Huffman trees. The more - * common source values are represented by shorter bit sequences. - * - * Each code tree is stored in a compressed form which is itself - * a Huffman encoding of the lengths of all the code strings (in - * ascending order by source values). The actual code strings are - * reconstructed from the lengths in the inflate process, as described - * in the deflate specification. - * - * REFERENCES - * - * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". - * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc - * - * Storer, James A. - * Data Compression: Methods and Theory, pp. 49-50. - * Computer Science Press, 1988. ISBN 0-7167-8156-5. - * - * Sedgewick, R. - * Algorithms, p290. - * Addison-Wesley, 1983. ISBN 0-201-06672-6. - */ - -/* @(#) $Id$ */ - -/* #define GEN_TREES_H */ - -#include "deflate.h" - -#ifdef DEBUG -# include -#endif - -/* =========================================================================== - * Constants - */ - -#define MAX_BL_BITS 7 -/* Bit length codes must not exceed MAX_BL_BITS bits */ - -#define END_BLOCK 256 -/* end of block literal code */ - -#define REP_3_6 16 -/* repeat previous bit length 3-6 times (2 bits of repeat count) */ - -#define REPZ_3_10 17 -/* repeat a zero length 3-10 times (3 bits of repeat count) */ - -#define REPZ_11_138 18 -/* repeat a zero length 11-138 times (7 bits of repeat count) */ - -local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ - = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; - -local const int extra_dbits[D_CODES] /* extra bits for each distance code */ - = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; - -local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ - = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; - -local const uch bl_order[BL_CODES] - = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; -/* The lengths of the bit length codes are sent in order of decreasing - * probability, to avoid transmitting the lengths for unused bit length codes. - */ - -#define Buf_size (8 * 2*sizeof(char)) -/* Number of bits used within bi_buf. (bi_buf might be implemented on - * more than 16 bits on some systems.) - */ - -/* =========================================================================== - * Local data. These are initialized only once. - */ - -#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ - -#if defined(GEN_TREES_H) || !defined(STDC) -/* non ANSI compilers may not accept trees.h */ - -local ct_data static_ltree[L_CODES+2]; -/* The static literal tree. Since the bit lengths are imposed, there is no - * need for the L_CODES extra codes used during heap construction. However - * The codes 286 and 287 are needed to build a canonical tree (see _tr_init - * below). - */ - -local ct_data static_dtree[D_CODES]; -/* The static distance tree. (Actually a trivial tree since all codes use - * 5 bits.) - */ - -uch _dist_code[DIST_CODE_LEN]; -/* Distance codes. The first 256 values correspond to the distances - * 3 .. 258, the last 256 values correspond to the top 8 bits of - * the 15 bit distances. - */ - -uch _length_code[MAX_MATCH-MIN_MATCH+1]; -/* length code for each normalized match length (0 == MIN_MATCH) */ - -local int base_length[LENGTH_CODES]; -/* First normalized length for each code (0 = MIN_MATCH) */ - -local int base_dist[D_CODES]; -/* First normalized distance for each code (0 = distance of 1) */ - -#else -# include "trees.h" -#endif /* GEN_TREES_H */ - -struct static_tree_desc_s { - const ct_data *static_tree; /* static tree or NULL */ - const intf *extra_bits; /* extra bits for each code or NULL */ - int extra_base; /* base index for extra_bits */ - int elems; /* max number of elements in the tree */ - int max_length; /* max bit length for the codes */ -}; - -local static_tree_desc static_l_desc = -{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; - -local static_tree_desc static_d_desc = -{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; - -local static_tree_desc static_bl_desc = -{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; - -/* =========================================================================== - * Local (static) routines in this file. - */ - -local void tr_static_init OF((void)); -local void init_block OF((deflate_state *s)); -local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); -local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); -local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); -local void build_tree OF((deflate_state *s, tree_desc *desc)); -local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); -local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); -local int build_bl_tree OF((deflate_state *s)); -local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, - int blcodes)); -local void compress_block OF((deflate_state *s, ct_data *ltree, - ct_data *dtree)); -local void set_data_type OF((deflate_state *s)); -local unsigned bi_reverse OF((unsigned value, int length)); -local void bi_windup OF((deflate_state *s)); -local void bi_flush OF((deflate_state *s)); -local void copy_block OF((deflate_state *s, charf *buf, unsigned len, - int header)); - -#ifdef GEN_TREES_H -local void gen_trees_header OF((void)); -#endif - -#ifndef DEBUG -# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) - /* Send a code of the given tree. c and tree must not have side effects */ - -#else /* DEBUG */ -# define send_code(s, c, tree) \ - { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ - send_bits(s, tree[c].Code, tree[c].Len); } -#endif - -/* =========================================================================== - * Output a short LSB first on the stream. - * IN assertion: there is enough room in pendingBuf. - */ -#define put_short(s, w) { \ - put_byte(s, (uch)((w) & 0xff)); \ - put_byte(s, (uch)((ush)(w) >> 8)); \ -} - -/* =========================================================================== - * Send a value on a given number of bits. - * IN assertion: length <= 16 and value fits in length bits. - */ -#ifdef DEBUG -local void send_bits OF((deflate_state *s, int value, int length)); - -local void send_bits(s, value, length) - deflate_state *s; - int value; /* value to send */ - int length; /* number of bits */ -{ - Tracevv((stderr," l %2d v %4x ", length, value)); - Assert(length > 0 && length <= 15, "invalid length"); - s->bits_sent += (ulg)length; - - /* If not enough room in bi_buf, use (valid) bits from bi_buf and - * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) - * unused bits in value. - */ - if (s->bi_valid > (int)Buf_size - length) { - s->bi_buf |= (value << s->bi_valid); - put_short(s, s->bi_buf); - s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); - s->bi_valid += length - Buf_size; - } else { - s->bi_buf |= value << s->bi_valid; - s->bi_valid += length; - } -} -#else /* !DEBUG */ - -#define send_bits(s, value, length) \ -{ int len = length;\ - if (s->bi_valid > (int)Buf_size - len) {\ - int val = value;\ - s->bi_buf |= (val << s->bi_valid);\ - put_short(s, s->bi_buf);\ - s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ - s->bi_valid += len - Buf_size;\ - } else {\ - s->bi_buf |= (value) << s->bi_valid;\ - s->bi_valid += len;\ - }\ -} -#endif /* DEBUG */ - - -/* the arguments must not have side effects */ - -/* =========================================================================== - * Initialize the various 'constant' tables. - */ -local void tr_static_init() -{ -#if defined(GEN_TREES_H) || !defined(STDC) - static int static_init_done = 0; - int n; /* iterates over tree elements */ - int bits; /* bit counter */ - int length; /* length value */ - int code; /* code value */ - int dist; /* distance index */ - ush bl_count[MAX_BITS+1]; - /* number of codes at each bit length for an optimal tree */ - - if (static_init_done) return; - - /* For some embedded targets, global variables are not initialized: */ - static_l_desc.static_tree = static_ltree; - static_l_desc.extra_bits = extra_lbits; - static_d_desc.static_tree = static_dtree; - static_d_desc.extra_bits = extra_dbits; - static_bl_desc.extra_bits = extra_blbits; - - /* Initialize the mapping length (0..255) -> length code (0..28) */ - length = 0; - for (code = 0; code < LENGTH_CODES-1; code++) { - base_length[code] = length; - for (n = 0; n < (1< dist code (0..29) */ - dist = 0; - for (code = 0 ; code < 16; code++) { - base_dist[code] = dist; - for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ - for ( ; code < D_CODES; code++) { - base_dist[code] = dist << 7; - for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { - _dist_code[256 + dist++] = (uch)code; - } - } - Assert (dist == 256, "tr_static_init: 256+dist != 512"); - - /* Construct the codes of the static literal tree */ - for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; - n = 0; - while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; - while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; - while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; - while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; - /* Codes 286 and 287 do not exist, but we must include them in the - * tree construction to get a canonical Huffman tree (longest code - * all ones) - */ - gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); - - /* The static distance tree is trivial: */ - for (n = 0; n < D_CODES; n++) { - static_dtree[n].Len = 5; - static_dtree[n].Code = bi_reverse((unsigned)n, 5); - } - static_init_done = 1; - -# ifdef GEN_TREES_H - gen_trees_header(); -# endif -#endif /* defined(GEN_TREES_H) || !defined(STDC) */ -} - -/* =========================================================================== - * Genererate the file trees.h describing the static trees. - */ -#ifdef GEN_TREES_H -# ifndef DEBUG -# include -# endif - -# define SEPARATOR(i, last, width) \ - ((i) == (last)? "\n};\n\n" : \ - ((i) % (width) == (width)-1 ? ",\n" : ", ")) - -void gen_trees_header() -{ - FILE *header = fopen("trees.h", "w"); - int i; - - Assert (header != NULL, "Can't open trees.h"); - fprintf(header, - "/* header created automatically with -DGEN_TREES_H */\n\n"); - - fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); - for (i = 0; i < L_CODES+2; i++) { - fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, - static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); - } - - fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); - for (i = 0; i < D_CODES; i++) { - fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, - static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); - } - - fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n"); - for (i = 0; i < DIST_CODE_LEN; i++) { - fprintf(header, "%2u%s", _dist_code[i], - SEPARATOR(i, DIST_CODE_LEN-1, 20)); - } - - fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); - for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { - fprintf(header, "%2u%s", _length_code[i], - SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); - } - - fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); - for (i = 0; i < LENGTH_CODES; i++) { - fprintf(header, "%1u%s", base_length[i], - SEPARATOR(i, LENGTH_CODES-1, 20)); - } - - fprintf(header, "local const int base_dist[D_CODES] = {\n"); - for (i = 0; i < D_CODES; i++) { - fprintf(header, "%5u%s", base_dist[i], - SEPARATOR(i, D_CODES-1, 10)); - } - - fclose(header); -} -#endif /* GEN_TREES_H */ - -/* =========================================================================== - * Initialize the tree data structures for a new zlib stream. - */ -void _tr_init(s) - deflate_state *s; -{ - tr_static_init(); - - s->l_desc.dyn_tree = s->dyn_ltree; - s->l_desc.stat_desc = &static_l_desc; - - s->d_desc.dyn_tree = s->dyn_dtree; - s->d_desc.stat_desc = &static_d_desc; - - s->bl_desc.dyn_tree = s->bl_tree; - s->bl_desc.stat_desc = &static_bl_desc; - - s->bi_buf = 0; - s->bi_valid = 0; - s->last_eob_len = 8; /* enough lookahead for inflate */ -#ifdef DEBUG - s->compressed_len = 0L; - s->bits_sent = 0L; -#endif - - /* Initialize the first block of the first file: */ - init_block(s); -} - -/* =========================================================================== - * Initialize a new block. - */ -local void init_block(s) - deflate_state *s; -{ - int n; /* iterates over tree elements */ - - /* Initialize the trees. */ - for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; - for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; - for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; - - s->dyn_ltree[END_BLOCK].Freq = 1; - s->opt_len = s->static_len = 0L; - s->last_lit = s->matches = 0; -} - -#define SMALLEST 1 -/* Index within the heap array of least frequent node in the Huffman tree */ - - -/* =========================================================================== - * Remove the smallest element from the heap and recreate the heap with - * one less element. Updates heap and heap_len. - */ -#define pqremove(s, tree, top) \ -{\ - top = s->heap[SMALLEST]; \ - s->heap[SMALLEST] = s->heap[s->heap_len--]; \ - pqdownheap(s, tree, SMALLEST); \ -} - -/* =========================================================================== - * Compares to subtrees, using the tree depth as tie breaker when - * the subtrees have equal frequency. This minimizes the worst case length. - */ -#define smaller(tree, n, m, depth) \ - (tree[n].Freq < tree[m].Freq || \ - (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) - -/* =========================================================================== - * Restore the heap property by moving down the tree starting at node k, - * exchanging a node with the smallest of its two sons if necessary, stopping - * when the heap property is re-established (each father smaller than its - * two sons). - */ -local void pqdownheap(s, tree, k) - deflate_state *s; - ct_data *tree; /* the tree to restore */ - int k; /* node to move down */ -{ - int v = s->heap[k]; - int j = k << 1; /* left son of k */ - while (j <= s->heap_len) { - /* Set j to the smallest of the two sons: */ - if (j < s->heap_len && - smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { - j++; - } - /* Exit if v is smaller than both sons */ - if (smaller(tree, v, s->heap[j], s->depth)) break; - - /* Exchange v with the smallest son */ - s->heap[k] = s->heap[j]; k = j; - - /* And continue down the tree, setting j to the left son of k */ - j <<= 1; - } - s->heap[k] = v; -} - -/* =========================================================================== - * Compute the optimal bit lengths for a tree and update the total bit length - * for the current block. - * IN assertion: the fields freq and dad are set, heap[heap_max] and - * above are the tree nodes sorted by increasing frequency. - * OUT assertions: the field len is set to the optimal bit length, the - * array bl_count contains the frequencies for each bit length. - * The length opt_len is updated; static_len is also updated if stree is - * not null. - */ -local void gen_bitlen(s, desc) - deflate_state *s; - tree_desc *desc; /* the tree descriptor */ -{ - ct_data *tree = desc->dyn_tree; - int max_code = desc->max_code; - const ct_data *stree = desc->stat_desc->static_tree; - const intf *extra = desc->stat_desc->extra_bits; - int base = desc->stat_desc->extra_base; - int max_length = desc->stat_desc->max_length; - int h; /* heap index */ - int n, m; /* iterate over the tree elements */ - int bits; /* bit length */ - int xbits; /* extra bits */ - ush f; /* frequency */ - int overflow = 0; /* number of elements with bit length too large */ - - for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; - - /* In a first pass, compute the optimal bit lengths (which may - * overflow in the case of the bit length tree). - */ - tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ - - for (h = s->heap_max+1; h < HEAP_SIZE; h++) { - n = s->heap[h]; - bits = tree[tree[n].Dad].Len + 1; - if (bits > max_length) bits = max_length, overflow++; - tree[n].Len = (ush)bits; - /* We overwrite tree[n].Dad which is no longer needed */ - - if (n > max_code) continue; /* not a leaf node */ - - s->bl_count[bits]++; - xbits = 0; - if (n >= base) xbits = extra[n-base]; - f = tree[n].Freq; - s->opt_len += (ulg)f * (bits + xbits); - if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits); - } - if (overflow == 0) return; - - Trace((stderr,"\nbit length overflow\n")); - /* This happens for example on obj2 and pic of the Calgary corpus */ - - /* Find the first bit length which could increase: */ - do { - bits = max_length-1; - while (s->bl_count[bits] == 0) bits--; - s->bl_count[bits]--; /* move one leaf down the tree */ - s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ - s->bl_count[max_length]--; - /* The brother of the overflow item also moves one step up, - * but this does not affect bl_count[max_length] - */ - overflow -= 2; - } while (overflow > 0); - - /* Now recompute all bit lengths, scanning in increasing frequency. - * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all - * lengths instead of fixing only the wrong ones. This idea is taken - * from 'ar' written by Haruhiko Okumura.) - */ - for (bits = max_length; bits != 0; bits--) { - n = s->bl_count[bits]; - while (n != 0) { - m = s->heap[--h]; - if (m > max_code) continue; - if ((unsigned) tree[m].Len != (unsigned) bits) { - Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); - s->opt_len += ((long)bits - (long)tree[m].Len) - *(long)tree[m].Freq; - tree[m].Len = (ush)bits; - } - n--; - } - } -} - -/* =========================================================================== - * Generate the codes for a given tree and bit counts (which need not be - * optimal). - * IN assertion: the array bl_count contains the bit length statistics for - * the given tree and the field len is set for all tree elements. - * OUT assertion: the field code is set for all tree elements of non - * zero code length. - */ -local void gen_codes (tree, max_code, bl_count) - ct_data *tree; /* the tree to decorate */ - int max_code; /* largest code with non zero frequency */ - ushf *bl_count; /* number of codes at each bit length */ -{ - ush next_code[MAX_BITS+1]; /* next code value for each bit length */ - ush code = 0; /* running code value */ - int bits; /* bit index */ - int n; /* code index */ - - /* The distribution counts are first used to generate the code values - * without bit reversal. - */ - for (bits = 1; bits <= MAX_BITS; bits++) { - next_code[bits] = code = (code + bl_count[bits-1]) << 1; - } - /* Check that the bit counts in bl_count are consistent. The last code - * must be all ones. - */ - Assert (code + bl_count[MAX_BITS]-1 == (1<dyn_tree; - const ct_data *stree = desc->stat_desc->static_tree; - int elems = desc->stat_desc->elems; - int n, m; /* iterate over heap elements */ - int max_code = -1; /* largest code with non zero frequency */ - int node; /* new node being created */ - - /* Construct the initial heap, with least frequent element in - * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. - * heap[0] is not used. - */ - s->heap_len = 0, s->heap_max = HEAP_SIZE; - - for (n = 0; n < elems; n++) { - if (tree[n].Freq != 0) { - s->heap[++(s->heap_len)] = max_code = n; - s->depth[n] = 0; - } else { - tree[n].Len = 0; - } - } - - /* The pkzip format requires that at least one distance code exists, - * and that at least one bit should be sent even if there is only one - * possible code. So to avoid special checks later on we force at least - * two codes of non zero frequency. - */ - while (s->heap_len < 2) { - node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); - tree[node].Freq = 1; - s->depth[node] = 0; - s->opt_len--; if (stree) s->static_len -= stree[node].Len; - /* node is 0 or 1 so it does not have extra bits */ - } - desc->max_code = max_code; - - /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, - * establish sub-heaps of increasing lengths: - */ - for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); - - /* Construct the Huffman tree by repeatedly combining the least two - * frequent nodes. - */ - node = elems; /* next internal node of the tree */ - do { - pqremove(s, tree, n); /* n = node of least frequency */ - m = s->heap[SMALLEST]; /* m = node of next least frequency */ - - s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ - s->heap[--(s->heap_max)] = m; - - /* Create a new node father of n and m */ - tree[node].Freq = tree[n].Freq + tree[m].Freq; - s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? - s->depth[n] : s->depth[m]) + 1); - tree[n].Dad = tree[m].Dad = (ush)node; -#ifdef DUMP_BL_TREE - if (tree == s->bl_tree) { - fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", - node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); - } -#endif - /* and insert the new node in the heap */ - s->heap[SMALLEST] = node++; - pqdownheap(s, tree, SMALLEST); - - } while (s->heap_len >= 2); - - s->heap[--(s->heap_max)] = s->heap[SMALLEST]; - - /* At this point, the fields freq and dad are set. We can now - * generate the bit lengths. - */ - gen_bitlen(s, (tree_desc *)desc); - - /* The field len is now set, we can generate the bit codes */ - gen_codes ((ct_data *)tree, max_code, s->bl_count); -} - -/* =========================================================================== - * Scan a literal or distance tree to determine the frequencies of the codes - * in the bit length tree. - */ -local void scan_tree (s, tree, max_code) - deflate_state *s; - ct_data *tree; /* the tree to be scanned */ - int max_code; /* and its largest code of non zero frequency */ -{ - int n; /* iterates over all tree elements */ - int prevlen = -1; /* last emitted length */ - int curlen; /* length of current code */ - int nextlen = tree[0].Len; /* length of next code */ - int count = 0; /* repeat count of the current code */ - int max_count = 7; /* max repeat count */ - int min_count = 4; /* min repeat count */ - - if (nextlen == 0) max_count = 138, min_count = 3; - tree[max_code+1].Len = (ush)0xffff; /* guard */ - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; nextlen = tree[n+1].Len; - if (++count < max_count && curlen == nextlen) { - continue; - } else if (count < min_count) { - s->bl_tree[curlen].Freq += count; - } else if (curlen != 0) { - if (curlen != prevlen) s->bl_tree[curlen].Freq++; - s->bl_tree[REP_3_6].Freq++; - } else if (count <= 10) { - s->bl_tree[REPZ_3_10].Freq++; - } else { - s->bl_tree[REPZ_11_138].Freq++; - } - count = 0; prevlen = curlen; - if (nextlen == 0) { - max_count = 138, min_count = 3; - } else if (curlen == nextlen) { - max_count = 6, min_count = 3; - } else { - max_count = 7, min_count = 4; - } - } -} - -/* =========================================================================== - * Send a literal or distance tree in compressed form, using the codes in - * bl_tree. - */ -local void send_tree (s, tree, max_code) - deflate_state *s; - ct_data *tree; /* the tree to be scanned */ - int max_code; /* and its largest code of non zero frequency */ -{ - int n; /* iterates over all tree elements */ - int prevlen = -1; /* last emitted length */ - int curlen; /* length of current code */ - int nextlen = tree[0].Len; /* length of next code */ - int count = 0; /* repeat count of the current code */ - int max_count = 7; /* max repeat count */ - int min_count = 4; /* min repeat count */ - - /* tree[max_code+1].Len = -1; */ /* guard already set */ - if (nextlen == 0) max_count = 138, min_count = 3; - - for (n = 0; n <= max_code; n++) { - curlen = nextlen; nextlen = tree[n+1].Len; - if (++count < max_count && curlen == nextlen) { - continue; - } else if (count < min_count) { - do { send_code(s, curlen, s->bl_tree); } while (--count != 0); - - } else if (curlen != 0) { - if (curlen != prevlen) { - send_code(s, curlen, s->bl_tree); count--; - } - Assert(count >= 3 && count <= 6, " 3_6?"); - send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); - - } else if (count <= 10) { - send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); - - } else { - send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); - } - count = 0; prevlen = curlen; - if (nextlen == 0) { - max_count = 138, min_count = 3; - } else if (curlen == nextlen) { - max_count = 6, min_count = 3; - } else { - max_count = 7, min_count = 4; - } - } -} - -/* =========================================================================== - * Construct the Huffman tree for the bit lengths and return the index in - * bl_order of the last bit length code to send. - */ -local int build_bl_tree(s) - deflate_state *s; -{ - int max_blindex; /* index of last bit length code of non zero freq */ - - /* Determine the bit length frequencies for literal and distance trees */ - scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); - scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); - - /* Build the bit length tree: */ - build_tree(s, (tree_desc *)(&(s->bl_desc))); - /* opt_len now includes the length of the tree representations, except - * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. - */ - - /* Determine the number of bit length codes to send. The pkzip format - * requires that at least 4 bit length codes be sent. (appnote.txt says - * 3 but the actual value used is 4.) - */ - for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { - if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; - } - /* Update opt_len to include the bit length tree and counts */ - s->opt_len += 3*(max_blindex+1) + 5+5+4; - Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", - s->opt_len, s->static_len)); - - return max_blindex; -} - -/* =========================================================================== - * Send the header for a block using dynamic Huffman trees: the counts, the - * lengths of the bit length codes, the literal tree and the distance tree. - * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. - */ -local void send_all_trees(s, lcodes, dcodes, blcodes) - deflate_state *s; - int lcodes, dcodes, blcodes; /* number of codes for each tree */ -{ - int rank; /* index in bl_order */ - - Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); - Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, - "too many codes"); - Tracev((stderr, "\nbl counts: ")); - send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ - send_bits(s, dcodes-1, 5); - send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ - for (rank = 0; rank < blcodes; rank++) { - Tracev((stderr, "\nbl code %2d ", bl_order[rank])); - send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); - } - Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); - - send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ - Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); - - send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ - Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); -} - -/* =========================================================================== - * Send a stored block - */ -void _tr_stored_block(s, buf, stored_len, eof) - deflate_state *s; - charf *buf; /* input block */ - ulg stored_len; /* length of input block */ - int eof; /* true if this is the last block for a file */ -{ - send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */ -#ifdef DEBUG - s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; - s->compressed_len += (stored_len + 4) << 3; -#endif - copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ -} - -/* =========================================================================== - * Send one empty static block to give enough lookahead for inflate. - * This takes 10 bits, of which 7 may remain in the bit buffer. - * The current inflate code requires 9 bits of lookahead. If the - * last two codes for the previous block (real code plus EOB) were coded - * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode - * the last real code. In this case we send two empty static blocks instead - * of one. (There are no problems if the previous block is stored or fixed.) - * To simplify the code, we assume the worst case of last real code encoded - * on one bit only. - */ -void _tr_align(s) - deflate_state *s; -{ - send_bits(s, STATIC_TREES<<1, 3); - send_code(s, END_BLOCK, static_ltree); -#ifdef DEBUG - s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ -#endif - bi_flush(s); - /* Of the 10 bits for the empty block, we have already sent - * (10 - bi_valid) bits. The lookahead for the last real code (before - * the EOB of the previous block) was thus at least one plus the length - * of the EOB plus what we have just sent of the empty static block. - */ - if (1 + s->last_eob_len + 10 - s->bi_valid < 9) { - send_bits(s, STATIC_TREES<<1, 3); - send_code(s, END_BLOCK, static_ltree); -#ifdef DEBUG - s->compressed_len += 10L; -#endif - bi_flush(s); - } - s->last_eob_len = 7; -} - -/* =========================================================================== - * Determine the best encoding for the current block: dynamic trees, static - * trees or store, and output the encoded block to the zip file. - */ -void _tr_flush_block(s, buf, stored_len, eof) - deflate_state *s; - charf *buf; /* input block, or NULL if too old */ - ulg stored_len; /* length of input block */ - int eof; /* true if this is the last block for a file */ -{ - ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ - int max_blindex = 0; /* index of last bit length code of non zero freq */ - - /* Build the Huffman trees unless a stored block is forced */ - if (s->level > 0) { - - /* Check if the file is binary or text */ - if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN) - set_data_type(s); - - /* Construct the literal and distance trees */ - build_tree(s, (tree_desc *)(&(s->l_desc))); - Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, - s->static_len)); - - build_tree(s, (tree_desc *)(&(s->d_desc))); - Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, - s->static_len)); - /* At this point, opt_len and static_len are the total bit lengths of - * the compressed block data, excluding the tree representations. - */ - - /* Build the bit length tree for the above two trees, and get the index - * in bl_order of the last bit length code to send. - */ - max_blindex = build_bl_tree(s); - - /* Determine the best encoding. Compute the block lengths in bytes. */ - opt_lenb = (s->opt_len+3+7)>>3; - static_lenb = (s->static_len+3+7)>>3; - - Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", - opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, - s->last_lit)); - - if (static_lenb <= opt_lenb) opt_lenb = static_lenb; - - } else { - Assert(buf != (char*)0, "lost buf"); - opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ - } - -#ifdef FORCE_STORED - if (buf != (char*)0) { /* force stored block */ -#else - if (stored_len+4 <= opt_lenb && buf != (char*)0) { - /* 4: two words for the lengths */ -#endif - /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. - * Otherwise we can't have processed more than WSIZE input bytes since - * the last block flush, because compression would have been - * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to - * transform a block into a stored block. - */ - _tr_stored_block(s, buf, stored_len, eof); - -#ifdef FORCE_STATIC - } else if (static_lenb >= 0) { /* force static trees */ -#else - } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { -#endif - send_bits(s, (STATIC_TREES<<1)+eof, 3); - compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree); -#ifdef DEBUG - s->compressed_len += 3 + s->static_len; -#endif - } else { - send_bits(s, (DYN_TREES<<1)+eof, 3); - send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, - max_blindex+1); - compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree); -#ifdef DEBUG - s->compressed_len += 3 + s->opt_len; -#endif - } - Assert (s->compressed_len == s->bits_sent, "bad compressed size"); - /* The above check is made mod 2^32, for files larger than 512 MB - * and uLong implemented on 32 bits. - */ - init_block(s); - - if (eof) { - bi_windup(s); -#ifdef DEBUG - s->compressed_len += 7; /* align on byte boundary */ -#endif - } - Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, - s->compressed_len-7*eof)); -} - -/* =========================================================================== - * Save the match info and tally the frequency counts. Return true if - * the current block must be flushed. - */ -int _tr_tally (s, dist, lc) - deflate_state *s; - unsigned dist; /* distance of matched string */ - unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ -{ - s->d_buf[s->last_lit] = (ush)dist; - s->l_buf[s->last_lit++] = (uch)lc; - if (dist == 0) { - /* lc is the unmatched char */ - s->dyn_ltree[lc].Freq++; - } else { - s->matches++; - /* Here, lc is the match length - MIN_MATCH */ - dist--; /* dist = match distance - 1 */ - Assert((ush)dist < (ush)MAX_DIST(s) && - (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && - (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); - - s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; - s->dyn_dtree[d_code(dist)].Freq++; - } - -#ifdef TRUNCATE_BLOCK - /* Try to guess if it is profitable to stop the current block here */ - if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { - /* Compute an upper bound for the compressed length */ - ulg out_length = (ulg)s->last_lit*8L; - ulg in_length = (ulg)((long)s->strstart - s->block_start); - int dcode; - for (dcode = 0; dcode < D_CODES; dcode++) { - out_length += (ulg)s->dyn_dtree[dcode].Freq * - (5L+extra_dbits[dcode]); - } - out_length >>= 3; - Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", - s->last_lit, in_length, out_length, - 100L - out_length*100L/in_length)); - if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; - } -#endif - return (s->last_lit == s->lit_bufsize-1); - /* We avoid equality with lit_bufsize because of wraparound at 64K - * on 16 bit machines and because stored blocks are restricted to - * 64K-1 bytes. - */ -} - -/* =========================================================================== - * Send the block data compressed using the given Huffman trees - */ -local void compress_block(s, ltree, dtree) - deflate_state *s; - ct_data *ltree; /* literal tree */ - ct_data *dtree; /* distance tree */ -{ - unsigned dist; /* distance of matched string */ - int lc; /* match length or unmatched char (if dist == 0) */ - unsigned lx = 0; /* running index in l_buf */ - unsigned code; /* the code to send */ - int extra; /* number of extra bits to send */ - - if (s->last_lit != 0) do { - dist = s->d_buf[lx]; - lc = s->l_buf[lx++]; - if (dist == 0) { - send_code(s, lc, ltree); /* send a literal byte */ - Tracecv(isgraph(lc), (stderr," '%c' ", lc)); - } else { - /* Here, lc is the match length - MIN_MATCH */ - code = _length_code[lc]; - send_code(s, code+LITERALS+1, ltree); /* send the length code */ - extra = extra_lbits[code]; - if (extra != 0) { - lc -= base_length[code]; - send_bits(s, lc, extra); /* send the extra length bits */ - } - dist--; /* dist is now the match distance - 1 */ - code = d_code(dist); - Assert (code < D_CODES, "bad d_code"); - - send_code(s, code, dtree); /* send the distance code */ - extra = extra_dbits[code]; - if (extra != 0) { - dist -= base_dist[code]; - send_bits(s, dist, extra); /* send the extra distance bits */ - } - } /* literal or match pair ? */ - - /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ - Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, - "pendingBuf overflow"); - - } while (lx < s->last_lit); - - send_code(s, END_BLOCK, ltree); - s->last_eob_len = ltree[END_BLOCK].Len; -} - -/* =========================================================================== - * Set the data type to BINARY or TEXT, using a crude approximation: - * set it to Z_TEXT if all symbols are either printable characters (33 to 255) - * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise. - * IN assertion: the fields Freq of dyn_ltree are set. - */ -local void set_data_type(s) - deflate_state *s; -{ - int n; - - for (n = 0; n < 9; n++) - if (s->dyn_ltree[n].Freq != 0) - break; - if (n == 9) - for (n = 14; n < 32; n++) - if (s->dyn_ltree[n].Freq != 0) - break; - s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY; -} - -/* =========================================================================== - * Reverse the first len bits of a code, using straightforward code (a faster - * method would use a table) - * IN assertion: 1 <= len <= 15 - */ -local unsigned bi_reverse(code, len) - unsigned code; /* the value to invert */ - int len; /* its bit length */ -{ - register unsigned res = 0; - do { - res |= code & 1; - code >>= 1, res <<= 1; - } while (--len > 0); - return res >> 1; -} - -/* =========================================================================== - * Flush the bit buffer, keeping at most 7 bits in it. - */ -local void bi_flush(s) - deflate_state *s; -{ - if (s->bi_valid == 16) { - put_short(s, s->bi_buf); - s->bi_buf = 0; - s->bi_valid = 0; - } else if (s->bi_valid >= 8) { - put_byte(s, (Byte)s->bi_buf); - s->bi_buf >>= 8; - s->bi_valid -= 8; - } -} - -/* =========================================================================== - * Flush the bit buffer and align the output on a byte boundary - */ -local void bi_windup(s) - deflate_state *s; -{ - if (s->bi_valid > 8) { - put_short(s, s->bi_buf); - } else if (s->bi_valid > 0) { - put_byte(s, (Byte)s->bi_buf); - } - s->bi_buf = 0; - s->bi_valid = 0; -#ifdef DEBUG - s->bits_sent = (s->bits_sent+7) & ~7; -#endif -} - -/* =========================================================================== - * Copy a stored block, storing first the length and its - * one's complement if requested. - */ -local void copy_block(s, buf, len, header) - deflate_state *s; - charf *buf; /* the input data */ - unsigned len; /* its length */ - int header; /* true if block header must be written */ -{ - bi_windup(s); /* align on byte boundary */ - s->last_eob_len = 8; /* enough lookahead for inflate */ - - if (header) { - put_short(s, (ush)len); - put_short(s, (ush)~len); -#ifdef DEBUG - s->bits_sent += 2*16; -#endif - } -#ifdef DEBUG - s->bits_sent += (ulg)len<<3; -#endif - while (len--) { - put_byte(s, *buf++); - } -} diff --git a/dep/StormLib/src/zlib/trees.h b/dep/StormLib/src/zlib/trees.h deleted file mode 100644 index 72facf900f7..00000000000 --- a/dep/StormLib/src/zlib/trees.h +++ /dev/null @@ -1,128 +0,0 @@ -/* header created automatically with -DGEN_TREES_H */ - -local const ct_data static_ltree[L_CODES+2] = { -{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, -{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, -{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, -{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, -{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, -{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, -{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, -{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, -{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, -{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, -{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, -{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, -{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, -{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, -{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, -{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, -{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, -{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, -{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, -{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, -{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, -{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, -{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, -{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, -{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, -{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, -{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, -{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, -{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, -{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, -{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, -{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, -{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, -{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, -{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, -{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, -{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, -{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, -{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, -{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, -{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, -{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, -{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, -{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, -{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, -{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, -{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, -{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, -{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, -{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, -{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, -{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, -{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, -{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, -{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, -{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, -{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, -{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} -}; - -local const ct_data static_dtree[D_CODES] = { -{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, -{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, -{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, -{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, -{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, -{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} -}; - -const uch _dist_code[DIST_CODE_LEN] = { - 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, - 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, -10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, -11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, -12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, -13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, -13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, -14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, -14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, -14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, -15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, -15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, -15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, -18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, -23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, -24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, -26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, -26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, -27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, -27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, -28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, -28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, -28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, -29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, -29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, -29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 -}; - -const uch _length_code[MAX_MATCH-MIN_MATCH+1]= { - 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, -13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, -17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, -19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, -21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, -22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, -23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, -24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, -25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, -25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, -26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, -26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, -27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 -}; - -local const int base_length[LENGTH_CODES] = { -0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, -64, 80, 96, 112, 128, 160, 192, 224, 0 -}; - -local const int base_dist[D_CODES] = { - 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, - 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, - 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 -}; - diff --git a/dep/StormLib/src/zlib/zconf.h b/dep/StormLib/src/zlib/zconf.h deleted file mode 100644 index 03a9431c8be..00000000000 --- a/dep/StormLib/src/zlib/zconf.h +++ /dev/null @@ -1,332 +0,0 @@ -/* zconf.h -- configuration of the zlib compression library - * Copyright (C) 1995-2005 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#ifndef ZCONF_H -#define ZCONF_H - -/* - * If you *really* need a unique prefix for all types and library functions, - * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. - */ -#ifdef Z_PREFIX -# define deflateInit_ z_deflateInit_ -# define deflate z_deflate -# define deflateEnd z_deflateEnd -# define inflateInit_ z_inflateInit_ -# define inflate z_inflate -# define inflateEnd z_inflateEnd -# define deflateInit2_ z_deflateInit2_ -# define deflateSetDictionary z_deflateSetDictionary -# define deflateCopy z_deflateCopy -# define deflateReset z_deflateReset -# define deflateParams z_deflateParams -# define deflateBound z_deflateBound -# define deflatePrime z_deflatePrime -# define inflateInit2_ z_inflateInit2_ -# define inflateSetDictionary z_inflateSetDictionary -# define inflateSync z_inflateSync -# define inflateSyncPoint z_inflateSyncPoint -# define inflateCopy z_inflateCopy -# define inflateReset z_inflateReset -# define inflateBack z_inflateBack -# define inflateBackEnd z_inflateBackEnd -# define compress z_compress -# define compress2 z_compress2 -# define compressBound z_compressBound -# define uncompress z_uncompress -# define adler32 z_adler32 -# define crc32 z_crc32 -# define get_crc_table z_get_crc_table -# define zError z_zError - -# define alloc_func z_alloc_func -# define free_func z_free_func -# define in_func z_in_func -# define out_func z_out_func -# define Byte z_Byte -# define uInt z_uInt -# define uLong z_uLong -# define Bytef z_Bytef -# define charf z_charf -# define intf z_intf -# define uIntf z_uIntf -# define uLongf z_uLongf -# define voidpf z_voidpf -# define voidp z_voidp -#endif - -#if defined(__MSDOS__) && !defined(MSDOS) -# define MSDOS -#endif -#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) -# define OS2 -#endif -#if defined(_WINDOWS) && !defined(WINDOWS) -# define WINDOWS -#endif -#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) -# ifndef WIN32 -# define WIN32 -# endif -#endif -#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) -# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) -# ifndef SYS16BIT -# define SYS16BIT -# endif -# endif -#endif - -/* - * Compile with -DMAXSEG_64K if the alloc function cannot allocate more - * than 64k bytes at a time (needed on systems with 16-bit int). - */ -#ifdef SYS16BIT -# define MAXSEG_64K -#endif -#ifdef MSDOS -# define UNALIGNED_OK -#endif - -#ifdef __STDC_VERSION__ -# ifndef STDC -# define STDC -# endif -# if __STDC_VERSION__ >= 199901L -# ifndef STDC99 -# define STDC99 -# endif -# endif -#endif -#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) -# define STDC -#endif -#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) -# define STDC -#endif -#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) -# define STDC -#endif -#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) -# define STDC -#endif - -#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ -# define STDC -#endif - -#ifndef STDC -# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ -# define const /* note: need a more gentle solution here */ -# endif -#endif - -/* Some Mac compilers merge all .h files incorrectly: */ -#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) -# define NO_DUMMY_DECL -#endif - -/* Maximum value for memLevel in deflateInit2 */ -#ifndef MAX_MEM_LEVEL -# ifdef MAXSEG_64K -# define MAX_MEM_LEVEL 8 -# else -# define MAX_MEM_LEVEL 9 -# endif -#endif - -/* Maximum value for windowBits in deflateInit2 and inflateInit2. - * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files - * created by gzip. (Files created by minigzip can still be extracted by - * gzip.) - */ -#ifndef MAX_WBITS -# define MAX_WBITS 15 /* 32K LZ77 window */ -#endif - -/* The memory requirements for deflate are (in bytes): - (1 << (windowBits+2)) + (1 << (memLevel+9)) - that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) - plus a few kilobytes for small objects. For example, if you want to reduce - the default memory requirements from 256K to 128K, compile with - make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" - Of course this will generally degrade compression (there's no free lunch). - - The memory requirements for inflate are (in bytes) 1 << windowBits - that is, 32K for windowBits=15 (default value) plus a few kilobytes - for small objects. -*/ - - /* Type declarations */ - -#ifndef OF /* function prototypes */ -# ifdef STDC -# define OF(args) args -# else -# define OF(args) () -# endif -#endif - -/* The following definitions for FAR are needed only for MSDOS mixed - * model programming (small or medium model with some far allocations). - * This was tested only with MSC; for other MSDOS compilers you may have - * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, - * just define FAR to be empty. - */ -#ifdef SYS16BIT -# if defined(M_I86SM) || defined(M_I86MM) - /* MSC small or medium model */ -# define SMALL_MEDIUM -# ifdef _MSC_VER -# define FAR _far -# else -# define FAR far -# endif -# endif -# if (defined(__SMALL__) || defined(__MEDIUM__)) - /* Turbo C small or medium model */ -# define SMALL_MEDIUM -# ifdef __BORLANDC__ -# define FAR _far -# else -# define FAR far -# endif -# endif -#endif - -#if defined(WINDOWS) || defined(WIN32) - /* If building or using zlib as a DLL, define ZLIB_DLL. - * This is not mandatory, but it offers a little performance increase. - */ -# ifdef ZLIB_DLL -# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) -# ifdef ZLIB_INTERNAL -# define ZEXTERN extern __declspec(dllexport) -# else -# define ZEXTERN extern __declspec(dllimport) -# endif -# endif -# endif /* ZLIB_DLL */ - /* If building or using zlib with the WINAPI/WINAPIV calling convention, - * define ZLIB_WINAPI. - * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. - */ -# ifdef ZLIB_WINAPI -# ifdef FAR -# undef FAR -# endif -# include - /* No need for _export, use ZLIB.DEF instead. */ - /* For complete Windows compatibility, use WINAPI, not __stdcall. */ -# define ZEXPORT WINAPI -# ifdef WIN32 -# define ZEXPORTVA WINAPIV -# else -# define ZEXPORTVA FAR CDECL -# endif -# endif -#endif - -#if defined (__BEOS__) -# ifdef ZLIB_DLL -# ifdef ZLIB_INTERNAL -# define ZEXPORT __declspec(dllexport) -# define ZEXPORTVA __declspec(dllexport) -# else -# define ZEXPORT __declspec(dllimport) -# define ZEXPORTVA __declspec(dllimport) -# endif -# endif -#endif - -#ifndef ZEXTERN -# define ZEXTERN extern -#endif -#ifndef ZEXPORT -# define ZEXPORT -#endif -#ifndef ZEXPORTVA -# define ZEXPORTVA -#endif - -#ifndef FAR -# define FAR -#endif - -#if !defined(__MACTYPES__) -typedef unsigned char Byte; /* 8 bits */ -#endif -typedef unsigned int uInt; /* 16 bits or more */ -typedef unsigned long uLong; /* 32 bits or more */ - -#ifdef SMALL_MEDIUM - /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ -# define Bytef Byte FAR -#else - typedef Byte FAR Bytef; -#endif -typedef char FAR charf; -typedef int FAR intf; -typedef uInt FAR uIntf; -typedef uLong FAR uLongf; - -#ifdef STDC - typedef void const *voidpc; - typedef void FAR *voidpf; - typedef void *voidp; -#else - typedef Byte const *voidpc; - typedef Byte FAR *voidpf; - typedef Byte *voidp; -#endif - -#if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */ -# include /* for off_t */ -# include /* for SEEK_* and off_t */ -# ifdef VMS -# include /* for off_t */ -# endif -# define z_off_t off_t -#endif -#ifndef SEEK_SET -# define SEEK_SET 0 /* Seek from beginning of file. */ -# define SEEK_CUR 1 /* Seek from current position. */ -# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ -#endif -#ifndef z_off_t -# define z_off_t long -#endif - -#if defined(__OS400__) -# define NO_vsnprintf -#endif - -#if defined(__MVS__) -# define NO_vsnprintf -# ifdef FAR -# undef FAR -# endif -#endif - -/* MVS linker does not support external names larger than 8 bytes */ -#if defined(__MVS__) -# pragma map(deflateInit_,"DEIN") -# pragma map(deflateInit2_,"DEIN2") -# pragma map(deflateEnd,"DEEND") -# pragma map(deflateBound,"DEBND") -# pragma map(inflateInit_,"ININ") -# pragma map(inflateInit2_,"ININ2") -# pragma map(inflateEnd,"INEND") -# pragma map(inflateSync,"INSY") -# pragma map(inflateSetDictionary,"INSEDI") -# pragma map(compressBound,"CMBND") -# pragma map(inflate_table,"INTABL") -# pragma map(inflate_fast,"INFA") -# pragma map(inflate_copyright,"INCOPY") -#endif - -#endif /* ZCONF_H */ diff --git a/dep/StormLib/src/zlib/zlib.h b/dep/StormLib/src/zlib/zlib.h deleted file mode 100644 index 022817927ce..00000000000 --- a/dep/StormLib/src/zlib/zlib.h +++ /dev/null @@ -1,1357 +0,0 @@ -/* zlib.h -- interface of the 'zlib' general purpose compression library - version 1.2.3, July 18th, 2005 - - Copyright (C) 1995-2005 Jean-loup Gailly and Mark Adler - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - Jean-loup Gailly Mark Adler - jloup@gzip.org madler@alumni.caltech.edu - - - The data format used by the zlib library is described by RFCs (Request for - Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt - (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). -*/ - -#ifndef ZLIB_H -#define ZLIB_H - -#include "zconf.h" - -#ifdef __cplusplus -extern "C" { -#endif - -#define ZLIB_VERSION "1.2.3" -#define ZLIB_VERNUM 0x1230 - -/* - The 'zlib' compression library provides in-memory compression and - decompression functions, including integrity checks of the uncompressed - data. This version of the library supports only one compression method - (deflation) but other algorithms will be added later and will have the same - stream interface. - - Compression can be done in a single step if the buffers are large - enough (for example if an input file is mmap'ed), or can be done by - repeated calls of the compression function. In the latter case, the - application must provide more input and/or consume the output - (providing more output space) before each call. - - The compressed data format used by default by the in-memory functions is - the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped - around a deflate stream, which is itself documented in RFC 1951. - - The library also supports reading and writing files in gzip (.gz) format - with an interface similar to that of stdio using the functions that start - with "gz". The gzip format is different from the zlib format. gzip is a - gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. - - This library can optionally read and write gzip streams in memory as well. - - The zlib format was designed to be compact and fast for use in memory - and on communications channels. The gzip format was designed for single- - file compression on file systems, has a larger header than zlib to maintain - directory information, and uses a different, slower check method than zlib. - - The library does not install any signal handler. The decoder checks - the consistency of the compressed data, so the library should never - crash even in case of corrupted input. -*/ - -typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); -typedef void (*free_func) OF((voidpf opaque, voidpf address)); - -struct internal_state; - -typedef struct z_stream_s { - Bytef *next_in; /* next input byte */ - uInt avail_in; /* number of bytes available at next_in */ - uLong total_in; /* total nb of input bytes read so far */ - - Bytef *next_out; /* next output byte should be put there */ - uInt avail_out; /* remaining free space at next_out */ - uLong total_out; /* total nb of bytes output so far */ - - char *msg; /* last error message, NULL if no error */ - struct internal_state FAR *state; /* not visible by applications */ - - alloc_func zalloc; /* used to allocate the internal state */ - free_func zfree; /* used to free the internal state */ - voidpf opaque; /* private data object passed to zalloc and zfree */ - - int data_type; /* best guess about the data type: binary or text */ - uLong adler; /* adler32 value of the uncompressed data */ - uLong reserved; /* reserved for future use */ -} z_stream; - -typedef z_stream FAR *z_streamp; - -/* - gzip header information passed to and from zlib routines. See RFC 1952 - for more details on the meanings of these fields. -*/ -typedef struct gz_header_s { - int text; /* true if compressed data believed to be text */ - uLong time; /* modification time */ - int xflags; /* extra flags (not used when writing a gzip file) */ - int os; /* operating system */ - Bytef *extra; /* pointer to extra field or Z_NULL if none */ - uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ - uInt extra_max; /* space at extra (only when reading header) */ - Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ - uInt name_max; /* space at name (only when reading header) */ - Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ - uInt comm_max; /* space at comment (only when reading header) */ - int hcrc; /* true if there was or will be a header crc */ - int done; /* true when done reading gzip header (not used - when writing a gzip file) */ -} gz_header; - -typedef gz_header FAR *gz_headerp; - -/* - The application must update next_in and avail_in when avail_in has - dropped to zero. It must update next_out and avail_out when avail_out - has dropped to zero. The application must initialize zalloc, zfree and - opaque before calling the init function. All other fields are set by the - compression library and must not be updated by the application. - - The opaque value provided by the application will be passed as the first - parameter for calls of zalloc and zfree. This can be useful for custom - memory management. The compression library attaches no meaning to the - opaque value. - - zalloc must return Z_NULL if there is not enough memory for the object. - If zlib is used in a multi-threaded application, zalloc and zfree must be - thread safe. - - On 16-bit systems, the functions zalloc and zfree must be able to allocate - exactly 65536 bytes, but will not be required to allocate more than this - if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, - pointers returned by zalloc for objects of exactly 65536 bytes *must* - have their offset normalized to zero. The default allocation function - provided by this library ensures this (see zutil.c). To reduce memory - requirements and avoid any allocation of 64K objects, at the expense of - compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h). - - The fields total_in and total_out can be used for statistics or - progress reports. After compression, total_in holds the total size of - the uncompressed data and may be saved for use in the decompressor - (particularly if the decompressor wants to decompress everything in - a single step). -*/ - - /* constants */ - -#define Z_NO_FLUSH 0 -#define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */ -#define Z_SYNC_FLUSH 2 -#define Z_FULL_FLUSH 3 -#define Z_FINISH 4 -#define Z_BLOCK 5 -/* Allowed flush values; see deflate() and inflate() below for details */ - -#define Z_OK 0 -#define Z_STREAM_END 1 -#define Z_NEED_DICT 2 -#define Z_ERRNO (-1) -#define Z_STREAM_ERROR (-2) -#define Z_DATA_ERROR (-3) -#define Z_MEM_ERROR (-4) -#define Z_BUF_ERROR (-5) -#define Z_VERSION_ERROR (-6) -/* Return codes for the compression/decompression functions. Negative - * values are errors, positive values are used for special but normal events. - */ - -#define Z_NO_COMPRESSION 0 -#define Z_BEST_SPEED 1 -#define Z_BEST_COMPRESSION 9 -#define Z_DEFAULT_COMPRESSION (-1) -/* compression levels */ - -#define Z_FILTERED 1 -#define Z_HUFFMAN_ONLY 2 -#define Z_RLE 3 -#define Z_FIXED 4 -#define Z_DEFAULT_STRATEGY 0 -/* compression strategy; see deflateInit2() below for details */ - -#define Z_BINARY 0 -#define Z_TEXT 1 -#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ -#define Z_UNKNOWN 2 -/* Possible values of the data_type field (though see inflate()) */ - -#define Z_DEFLATED 8 -/* The deflate compression method (the only one supported in this version) */ - -#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ - -#define zlib_version zlibVersion() -/* for compatibility with versions < 1.0.2 */ - - /* basic functions */ - -ZEXTERN const char * ZEXPORT zlibVersion OF((void)); -/* The application can compare zlibVersion and ZLIB_VERSION for consistency. - If the first character differs, the library code actually used is - not compatible with the zlib.h header file used by the application. - This check is automatically made by deflateInit and inflateInit. - */ - -/* -ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); - - Initializes the internal stream state for compression. The fields - zalloc, zfree and opaque must be initialized before by the caller. - If zalloc and zfree are set to Z_NULL, deflateInit updates them to - use default allocation functions. - - The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: - 1 gives best speed, 9 gives best compression, 0 gives no compression at - all (the input data is simply copied a block at a time). - Z_DEFAULT_COMPRESSION requests a default compromise between speed and - compression (currently equivalent to level 6). - - deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if level is not a valid compression level, - Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible - with the version assumed by the caller (ZLIB_VERSION). - msg is set to null if there is no error message. deflateInit does not - perform any compression: this will be done by deflate(). -*/ - - -ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); -/* - deflate compresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce some - output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. deflate performs one or both of the - following actions: - - - Compress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in and avail_in are updated and - processing will resume at this point for the next call of deflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. This action is forced if the parameter flush is non zero. - Forcing flush frequently degrades the compression ratio, so this parameter - should be set only when necessary (in interactive applications). - Some output may be provided even if flush is not set. - - Before the call of deflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming - more output, and updating avail_in or avail_out accordingly; avail_out - should never be zero before the call. The application can consume the - compressed output when it wants, for example when the output buffer is full - (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK - and with zero avail_out, it must be called again after making room in the - output buffer because there might be more output pending. - - Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to - decide how much data to accumualte before producing output, in order to - maximize compression. - - If the parameter flush is set to Z_SYNC_FLUSH, all pending output is - flushed to the output buffer and the output is aligned on a byte boundary, so - that the decompressor can get all input data available so far. (In particular - avail_in is zero after the call if enough output space has been provided - before the call.) Flushing may degrade compression for some compression - algorithms and so it should be used only when necessary. - - If flush is set to Z_FULL_FLUSH, all output is flushed as with - Z_SYNC_FLUSH, and the compression state is reset so that decompression can - restart from this point if previous compressed data has been damaged or if - random access is desired. Using Z_FULL_FLUSH too often can seriously degrade - compression. - - If deflate returns with avail_out == 0, this function must be called again - with the same value of the flush parameter and more output space (updated - avail_out), until the flush is complete (deflate returns with non-zero - avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that - avail_out is greater than six to avoid repeated flush markers due to - avail_out == 0 on return. - - If the parameter flush is set to Z_FINISH, pending input is processed, - pending output is flushed and deflate returns with Z_STREAM_END if there - was enough output space; if deflate returns with Z_OK, this function must be - called again with Z_FINISH and more output space (updated avail_out) but no - more input data, until it returns with Z_STREAM_END or an error. After - deflate has returned Z_STREAM_END, the only possible operations on the - stream are deflateReset or deflateEnd. - - Z_FINISH can be used immediately after deflateInit if all the compression - is to be done in a single step. In this case, avail_out must be at least - the value returned by deflateBound (see below). If deflate does not return - Z_STREAM_END, then it must be called again as described above. - - deflate() sets strm->adler to the adler32 checksum of all input read - so far (that is, total_in bytes). - - deflate() may update strm->data_type if it can make a good guess about - the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered - binary. This field is only for information purposes and does not affect - the compression algorithm in any manner. - - deflate() returns Z_OK if some progress has been made (more input - processed or more output produced), Z_STREAM_END if all input has been - consumed and all output has been produced (only when flush is set to - Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example - if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible - (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not - fatal, and deflate() can be called again with more input and more output - space to continue compressing. -*/ - - -ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any - pending output. - - deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the - stream state was inconsistent, Z_DATA_ERROR if the stream was freed - prematurely (some input or output was discarded). In the error case, - msg may be set but then points to a static string (which must not be - deallocated). -*/ - - -/* -ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); - - Initializes the internal stream state for decompression. The fields - next_in, avail_in, zalloc, zfree and opaque must be initialized before by - the caller. If next_in is not Z_NULL and avail_in is large enough (the exact - value depends on the compression method), inflateInit determines the - compression method from the zlib header and allocates all data structures - accordingly; otherwise the allocation will be deferred to the first call of - inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to - use default allocation functions. - - inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_VERSION_ERROR if the zlib library version is incompatible with the - version assumed by the caller. msg is set to null if there is no error - message. inflateInit does not perform any decompression apart from reading - the zlib header if present: this will be done by inflate(). (So next_in and - avail_in may be modified, but next_out and avail_out are unchanged.) -*/ - - -ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); -/* - inflate decompresses as much data as possible, and stops when the input - buffer becomes empty or the output buffer becomes full. It may introduce - some output latency (reading input without producing any output) except when - forced to flush. - - The detailed semantics are as follows. inflate performs one or both of the - following actions: - - - Decompress more input starting at next_in and update next_in and avail_in - accordingly. If not all input can be processed (because there is not - enough room in the output buffer), next_in is updated and processing - will resume at this point for the next call of inflate(). - - - Provide more output starting at next_out and update next_out and avail_out - accordingly. inflate() provides as much output as possible, until there - is no more input data or no more space in the output buffer (see below - about the flush parameter). - - Before the call of inflate(), the application should ensure that at least - one of the actions is possible, by providing more input and/or consuming - more output, and updating the next_* and avail_* values accordingly. - The application can consume the uncompressed output when it wants, for - example when the output buffer is full (avail_out == 0), or after each - call of inflate(). If inflate returns Z_OK and with zero avail_out, it - must be called again after making room in the output buffer because there - might be more output pending. - - The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, - Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much - output as possible to the output buffer. Z_BLOCK requests that inflate() stop - if and when it gets to the next deflate block boundary. When decoding the - zlib or gzip format, this will cause inflate() to return immediately after - the header and before the first block. When doing a raw inflate, inflate() - will go ahead and process the first block, and will return when it gets to - the end of that block, or when it runs out of data. - - The Z_BLOCK option assists in appending to or combining deflate streams. - Also to assist in this, on return inflate() will set strm->data_type to the - number of unused bits in the last byte taken from strm->next_in, plus 64 - if inflate() is currently decoding the last block in the deflate stream, - plus 128 if inflate() returned immediately after decoding an end-of-block - code or decoding the complete header up to just before the first byte of the - deflate stream. The end-of-block will not be indicated until all of the - uncompressed data from that block has been written to strm->next_out. The - number of unused bits may in general be greater than seven, except when - bit 7 of data_type is set, in which case the number of unused bits will be - less than eight. - - inflate() should normally be called until it returns Z_STREAM_END or an - error. However if all decompression is to be performed in a single step - (a single call of inflate), the parameter flush should be set to - Z_FINISH. In this case all pending input is processed and all pending - output is flushed; avail_out must be large enough to hold all the - uncompressed data. (The size of the uncompressed data may have been saved - by the compressor for this purpose.) The next operation on this stream must - be inflateEnd to deallocate the decompression state. The use of Z_FINISH - is never required, but can be used to inform inflate that a faster approach - may be used for the single inflate() call. - - In this implementation, inflate() always flushes as much output as - possible to the output buffer, and always uses the faster approach on the - first call. So the only effect of the flush parameter in this implementation - is on the return value of inflate(), as noted below, or when it returns early - because Z_BLOCK is used. - - If a preset dictionary is needed after this call (see inflateSetDictionary - below), inflate sets strm->adler to the adler32 checksum of the dictionary - chosen by the compressor and returns Z_NEED_DICT; otherwise it sets - strm->adler to the adler32 checksum of all output produced so far (that is, - total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described - below. At the end of the stream, inflate() checks that its computed adler32 - checksum is equal to that saved by the compressor and returns Z_STREAM_END - only if the checksum is correct. - - inflate() will decompress and check either zlib-wrapped or gzip-wrapped - deflate data. The header type is detected automatically. Any information - contained in the gzip header is not retained, so applications that need that - information should instead use raw inflate, see inflateInit2() below, or - inflateBack() and perform their own processing of the gzip header and - trailer. - - inflate() returns Z_OK if some progress has been made (more input processed - or more output produced), Z_STREAM_END if the end of the compressed data has - been reached and all uncompressed output has been produced, Z_NEED_DICT if a - preset dictionary is needed at this point, Z_DATA_ERROR if the input data was - corrupted (input stream not conforming to the zlib format or incorrect check - value), Z_STREAM_ERROR if the stream structure was inconsistent (for example - if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory, - Z_BUF_ERROR if no progress is possible or if there was not enough room in the - output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and - inflate() can be called again with more input and more output space to - continue decompressing. If Z_DATA_ERROR is returned, the application may then - call inflateSync() to look for a good compression block if a partial recovery - of the data is desired. -*/ - - -ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); -/* - All dynamically allocated data structures for this stream are freed. - This function discards any unprocessed input and does not flush any - pending output. - - inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state - was inconsistent. In the error case, msg may be set but then points to a - static string (which must not be deallocated). -*/ - - /* Advanced functions */ - -/* - The following functions are needed only in some special applications. -*/ - -/* -ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, - int level, - int method, - int windowBits, - int memLevel, - int strategy)); - - This is another version of deflateInit with more compression options. The - fields next_in, zalloc, zfree and opaque must be initialized before by - the caller. - - The method parameter is the compression method. It must be Z_DEFLATED in - this version of the library. - - The windowBits parameter is the base two logarithm of the window size - (the size of the history buffer). It should be in the range 8..15 for this - version of the library. Larger values of this parameter result in better - compression at the expense of memory usage. The default value is 15 if - deflateInit is used instead. - - windowBits can also be -8..-15 for raw deflate. In this case, -windowBits - determines the window size. deflate() will then generate raw deflate data - with no zlib header or trailer, and will not compute an adler32 check value. - - windowBits can also be greater than 15 for optional gzip encoding. Add - 16 to windowBits to write a simple gzip header and trailer around the - compressed data instead of a zlib wrapper. The gzip header will have no - file name, no extra data, no comment, no modification time (set to zero), - no header crc, and the operating system will be set to 255 (unknown). If a - gzip stream is being written, strm->adler is a crc32 instead of an adler32. - - The memLevel parameter specifies how much memory should be allocated - for the internal compression state. memLevel=1 uses minimum memory but - is slow and reduces compression ratio; memLevel=9 uses maximum memory - for optimal speed. The default value is 8. See zconf.h for total memory - usage as a function of windowBits and memLevel. - - The strategy parameter is used to tune the compression algorithm. Use the - value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a - filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no - string match), or Z_RLE to limit match distances to one (run-length - encoding). Filtered data consists mostly of small values with a somewhat - random distribution. In this case, the compression algorithm is tuned to - compress them better. The effect of Z_FILTERED is to force more Huffman - coding and less string matching; it is somewhat intermediate between - Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as - Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy - parameter only affects the compression ratio but not the correctness of the - compressed output even if it is not set appropriately. Z_FIXED prevents the - use of dynamic Huffman codes, allowing for a simpler decoder for special - applications. - - deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid - method). msg is set to null if there is no error message. deflateInit2 does - not perform any compression: this will be done by deflate(). -*/ - -ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the compression dictionary from the given byte sequence - without producing any compressed output. This function must be called - immediately after deflateInit, deflateInit2 or deflateReset, before any - call of deflate. The compressor and decompressor must use exactly the same - dictionary (see inflateSetDictionary). - - The dictionary should consist of strings (byte sequences) that are likely - to be encountered later in the data to be compressed, with the most commonly - used strings preferably put towards the end of the dictionary. Using a - dictionary is most useful when the data to be compressed is short and can be - predicted with good accuracy; the data can then be compressed better than - with the default empty dictionary. - - Depending on the size of the compression data structures selected by - deflateInit or deflateInit2, a part of the dictionary may in effect be - discarded, for example if the dictionary is larger than the window size in - deflate or deflate2. Thus the strings most likely to be useful should be - put at the end of the dictionary, not at the front. In addition, the - current implementation of deflate will use at most the window size minus - 262 bytes of the provided dictionary. - - Upon return of this function, strm->adler is set to the adler32 value - of the dictionary; the decompressor may later use this value to determine - which dictionary has been used by the compressor. (The adler32 value - applies to the whole dictionary even if only a subset of the dictionary is - actually used by the compressor.) If a raw deflate was requested, then the - adler32 value is not computed and strm->adler is not set. - - deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a - parameter is invalid (such as NULL dictionary) or the stream state is - inconsistent (for example if deflate has already been called for this stream - or if the compression method is bsort). deflateSetDictionary does not - perform any compression: this will be done by deflate(). -*/ - -ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, - z_streamp source)); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when several compression strategies will be - tried, for example when there are several ways of pre-processing the input - data with a filter. The streams that will be discarded should then be freed - by calling deflateEnd. Note that deflateCopy duplicates the internal - compression state which can be quite large, so this strategy is slow and - can consume lots of memory. - - deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being NULL). msg is left unchanged in both source and - destination. -*/ - -ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); -/* - This function is equivalent to deflateEnd followed by deflateInit, - but does not free and reallocate all the internal compression state. - The stream will keep the same compression level and any other attributes - that may have been set by deflateInit2. - - deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being NULL). -*/ - -ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, - int level, - int strategy)); -/* - Dynamically update the compression level and compression strategy. The - interpretation of level and strategy is as in deflateInit2. This can be - used to switch between compression and straight copy of the input data, or - to switch to a different kind of input data requiring a different - strategy. If the compression level is changed, the input available so far - is compressed with the old level (and may be flushed); the new level will - take effect only at the next call of deflate(). - - Before the call of deflateParams, the stream state must be set as for - a call of deflate(), since the currently available input may have to - be compressed and flushed. In particular, strm->avail_out must be non-zero. - - deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source - stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR - if strm->avail_out was zero. -*/ - -ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, - int good_length, - int max_lazy, - int nice_length, - int max_chain)); -/* - Fine tune deflate's internal compression parameters. This should only be - used by someone who understands the algorithm used by zlib's deflate for - searching for the best matching string, and even then only by the most - fanatic optimizer trying to squeeze out the last compressed bit for their - specific input data. Read the deflate.c source code for the meaning of the - max_lazy, good_length, nice_length, and max_chain parameters. - - deflateTune() can be called after deflateInit() or deflateInit2(), and - returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. - */ - -ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, - uLong sourceLen)); -/* - deflateBound() returns an upper bound on the compressed size after - deflation of sourceLen bytes. It must be called after deflateInit() - or deflateInit2(). This would be used to allocate an output buffer - for deflation in a single pass, and so would be called before deflate(). -*/ - -ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, - int bits, - int value)); -/* - deflatePrime() inserts bits in the deflate output stream. The intent - is that this function is used to start off the deflate output with the - bits leftover from a previous deflate stream when appending to it. As such, - this function can only be used for raw deflate, and must be used before the - first deflate() call after a deflateInit2() or deflateReset(). bits must be - less than or equal to 16, and that many of the least significant bits of - value will be inserted in the output. - - deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, - gz_headerp head)); -/* - deflateSetHeader() provides gzip header information for when a gzip - stream is requested by deflateInit2(). deflateSetHeader() may be called - after deflateInit2() or deflateReset() and before the first call of - deflate(). The text, time, os, extra field, name, and comment information - in the provided gz_header structure are written to the gzip header (xflag is - ignored -- the extra flags are set according to the compression level). The - caller must assure that, if not Z_NULL, name and comment are terminated with - a zero byte, and that if extra is not Z_NULL, that extra_len bytes are - available there. If hcrc is true, a gzip header crc is included. Note that - the current versions of the command-line version of gzip (up through version - 1.3.x) do not support header crc's, and will report that it is a "multi-part - gzip file" and give up. - - If deflateSetHeader is not used, the default gzip header has text false, - the time set to zero, and os set to 255, with no extra, name, or comment - fields. The gzip header is returned to the default state by deflateReset(). - - deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, - int windowBits)); - - This is another version of inflateInit with an extra parameter. The - fields next_in, avail_in, zalloc, zfree and opaque must be initialized - before by the caller. - - The windowBits parameter is the base two logarithm of the maximum window - size (the size of the history buffer). It should be in the range 8..15 for - this version of the library. The default value is 15 if inflateInit is used - instead. windowBits must be greater than or equal to the windowBits value - provided to deflateInit2() while compressing, or it must be equal to 15 if - deflateInit2() was not used. If a compressed stream with a larger window - size is given as input, inflate() will return with the error code - Z_DATA_ERROR instead of trying to allocate a larger window. - - windowBits can also be -8..-15 for raw inflate. In this case, -windowBits - determines the window size. inflate() will then process raw deflate data, - not looking for a zlib or gzip header, not generating a check value, and not - looking for any check values for comparison at the end of the stream. This - is for use with other formats that use the deflate compressed data format - such as zip. Those formats provide their own check values. If a custom - format is developed using the raw deflate format for compressed data, it is - recommended that a check value such as an adler32 or a crc32 be applied to - the uncompressed data as is done in the zlib, gzip, and zip formats. For - most applications, the zlib format should be used as is. Note that comments - above on the use in deflateInit2() applies to the magnitude of windowBits. - - windowBits can also be greater than 15 for optional gzip decoding. Add - 32 to windowBits to enable zlib and gzip decoding with automatic header - detection, or add 16 to decode only the gzip format (the zlib format will - return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is - a crc32 instead of an adler32. - - inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg - is set to null if there is no error message. inflateInit2 does not perform - any decompression apart from reading the zlib header if present: this will - be done by inflate(). (So next_in and avail_in may be modified, but next_out - and avail_out are unchanged.) -*/ - -ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, - const Bytef *dictionary, - uInt dictLength)); -/* - Initializes the decompression dictionary from the given uncompressed byte - sequence. This function must be called immediately after a call of inflate, - if that call returned Z_NEED_DICT. The dictionary chosen by the compressor - can be determined from the adler32 value returned by that call of inflate. - The compressor and decompressor must use exactly the same dictionary (see - deflateSetDictionary). For raw inflate, this function can be called - immediately after inflateInit2() or inflateReset() and before any call of - inflate() to set the dictionary. The application must insure that the - dictionary that was used for compression is provided. - - inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a - parameter is invalid (such as NULL dictionary) or the stream state is - inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the - expected one (incorrect adler32 value). inflateSetDictionary does not - perform any decompression: this will be done by subsequent calls of - inflate(). -*/ - -ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); -/* - Skips invalid compressed data until a full flush point (see above the - description of deflate with Z_FULL_FLUSH) can be found, or until all - available input is skipped. No output is provided. - - inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR - if no more input was provided, Z_DATA_ERROR if no flush point has been found, - or Z_STREAM_ERROR if the stream structure was inconsistent. In the success - case, the application may save the current current value of total_in which - indicates where valid compressed data was found. In the error case, the - application may repeatedly call inflateSync, providing more input each time, - until success or end of the input data. -*/ - -ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, - z_streamp source)); -/* - Sets the destination stream as a complete copy of the source stream. - - This function can be useful when randomly accessing a large stream. The - first pass through the stream can periodically record the inflate state, - allowing restarting inflate at those points when randomly accessing the - stream. - - inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_STREAM_ERROR if the source stream state was inconsistent - (such as zalloc being NULL). msg is left unchanged in both source and - destination. -*/ - -ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); -/* - This function is equivalent to inflateEnd followed by inflateInit, - but does not free and reallocate all the internal decompression state. - The stream will keep attributes that may have been set by inflateInit2. - - inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent (such as zalloc or state being NULL). -*/ - -ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, - int bits, - int value)); -/* - This function inserts bits in the inflate input stream. The intent is - that this function is used to start inflating at a bit position in the - middle of a byte. The provided bits will be used before any bytes are used - from next_in. This function should only be used with raw inflate, and - should be used before the first inflate() call after inflateInit2() or - inflateReset(). bits must be less than or equal to 16, and that many of the - least significant bits of value will be inserted in the input. - - inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, - gz_headerp head)); -/* - inflateGetHeader() requests that gzip header information be stored in the - provided gz_header structure. inflateGetHeader() may be called after - inflateInit2() or inflateReset(), and before the first call of inflate(). - As inflate() processes the gzip stream, head->done is zero until the header - is completed, at which time head->done is set to one. If a zlib stream is - being decoded, then head->done is set to -1 to indicate that there will be - no gzip header information forthcoming. Note that Z_BLOCK can be used to - force inflate() to return immediately after header processing is complete - and before any actual data is decompressed. - - The text, time, xflags, and os fields are filled in with the gzip header - contents. hcrc is set to true if there is a header CRC. (The header CRC - was valid if done is set to one.) If extra is not Z_NULL, then extra_max - contains the maximum number of bytes to write to extra. Once done is true, - extra_len contains the actual extra field length, and extra contains the - extra field, or that field truncated if extra_max is less than extra_len. - If name is not Z_NULL, then up to name_max characters are written there, - terminated with a zero unless the length is greater than name_max. If - comment is not Z_NULL, then up to comm_max characters are written there, - terminated with a zero unless the length is greater than comm_max. When - any of extra, name, or comment are not Z_NULL and the respective field is - not present in the header, then that field is set to Z_NULL to signal its - absence. This allows the use of deflateSetHeader() with the returned - structure to duplicate the header. However if those fields are set to - allocated memory, then the application will need to save those pointers - elsewhere so that they can be eventually freed. - - If inflateGetHeader is not used, then the header information is simply - discarded. The header is always checked for validity, including the header - CRC if present. inflateReset() will reset the process to discard the header - information. The application would need to call inflateGetHeader() again to - retrieve the header from the next gzip stream. - - inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. -*/ - -/* -ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, - unsigned char FAR *window)); - - Initialize the internal stream state for decompression using inflateBack() - calls. The fields zalloc, zfree and opaque in strm must be initialized - before the call. If zalloc and zfree are Z_NULL, then the default library- - derived memory allocation routines are used. windowBits is the base two - logarithm of the window size, in the range 8..15. window is a caller - supplied buffer of that size. Except for special applications where it is - assured that deflate was used with small window sizes, windowBits must be 15 - and a 32K byte window must be supplied to be able to decompress general - deflate streams. - - See inflateBack() for the usage of these routines. - - inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of - the paramaters are invalid, Z_MEM_ERROR if the internal state could not - be allocated, or Z_VERSION_ERROR if the version of the library does not - match the version of the header file. -*/ - -typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *)); -typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); - -ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, - in_func in, void FAR *in_desc, - out_func out, void FAR *out_desc)); -/* - inflateBack() does a raw inflate with a single call using a call-back - interface for input and output. This is more efficient than inflate() for - file i/o applications in that it avoids copying between the output and the - sliding window by simply making the window itself the output buffer. This - function trusts the application to not change the output buffer passed by - the output function, at least until inflateBack() returns. - - inflateBackInit() must be called first to allocate the internal state - and to initialize the state with the user-provided window buffer. - inflateBack() may then be used multiple times to inflate a complete, raw - deflate stream with each call. inflateBackEnd() is then called to free - the allocated state. - - A raw deflate stream is one with no zlib or gzip header or trailer. - This routine would normally be used in a utility that reads zip or gzip - files and writes out uncompressed files. The utility would decode the - header and process the trailer on its own, hence this routine expects - only the raw deflate stream to decompress. This is different from the - normal behavior of inflate(), which expects either a zlib or gzip header and - trailer around the deflate stream. - - inflateBack() uses two subroutines supplied by the caller that are then - called by inflateBack() for input and output. inflateBack() calls those - routines until it reads a complete deflate stream and writes out all of the - uncompressed data, or until it encounters an error. The function's - parameters and return types are defined above in the in_func and out_func - typedefs. inflateBack() will call in(in_desc, &buf) which should return the - number of bytes of provided input, and a pointer to that input in buf. If - there is no input available, in() must return zero--buf is ignored in that - case--and inflateBack() will return a buffer error. inflateBack() will call - out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() - should return zero on success, or non-zero on failure. If out() returns - non-zero, inflateBack() will return with an error. Neither in() nor out() - are permitted to change the contents of the window provided to - inflateBackInit(), which is also the buffer that out() uses to write from. - The length written by out() will be at most the window size. Any non-zero - amount of input may be provided by in(). - - For convenience, inflateBack() can be provided input on the first call by - setting strm->next_in and strm->avail_in. If that input is exhausted, then - in() will be called. Therefore strm->next_in must be initialized before - calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called - immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in - must also be initialized, and then if strm->avail_in is not zero, input will - initially be taken from strm->next_in[0 .. strm->avail_in - 1]. - - The in_desc and out_desc parameters of inflateBack() is passed as the - first parameter of in() and out() respectively when they are called. These - descriptors can be optionally used to pass any information that the caller- - supplied in() and out() functions need to do their job. - - On return, inflateBack() will set strm->next_in and strm->avail_in to - pass back any unused input that was provided by the last in() call. The - return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR - if in() or out() returned an error, Z_DATA_ERROR if there was a format - error in the deflate stream (in which case strm->msg is set to indicate the - nature of the error), or Z_STREAM_ERROR if the stream was not properly - initialized. In the case of Z_BUF_ERROR, an input or output error can be - distinguished using strm->next_in which will be Z_NULL only if in() returned - an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to - out() returning non-zero. (in() will always be called before out(), so - strm->next_in is assured to be defined if out() returns non-zero.) Note - that inflateBack() cannot return Z_OK. -*/ - -ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); -/* - All memory allocated by inflateBackInit() is freed. - - inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream - state was inconsistent. -*/ - -ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); -/* Return flags indicating compile-time options. - - Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: - 1.0: size of uInt - 3.2: size of uLong - 5.4: size of voidpf (pointer) - 7.6: size of z_off_t - - Compiler, assembler, and debug options: - 8: DEBUG - 9: ASMV or ASMINF -- use ASM code - 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention - 11: 0 (reserved) - - One-time table building (smaller code, but not thread-safe if true): - 12: BUILDFIXED -- build static block decoding tables when needed - 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed - 14,15: 0 (reserved) - - Library content (indicates missing functionality): - 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking - deflate code when not needed) - 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect - and decode gzip streams (to avoid linking crc code) - 18-19: 0 (reserved) - - Operation variations (changes in library functionality): - 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate - 21: FASTEST -- deflate algorithm with only one, lowest compression level - 22,23: 0 (reserved) - - The sprintf variant used by gzprintf (zero is best): - 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format - 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! - 26: 0 = returns value, 1 = void -- 1 means inferred string length returned - - Remainder: - 27-31: 0 (reserved) - */ - - - /* utility functions */ - -/* - The following utility functions are implemented on top of the - basic stream-oriented functions. To simplify the interface, some - default options are assumed (compression level and memory usage, - standard memory allocation functions). The source code of these - utility functions can easily be modified if you need special options. -*/ - -ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); -/* - Compresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total - size of the destination buffer, which must be at least the value returned - by compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - This function can be used to compress a whole file at once if the - input file is mmap'ed. - compress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer. -*/ - -ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen, - int level)); -/* - Compresses the source buffer into the destination buffer. The level - parameter has the same meaning as in deflateInit. sourceLen is the byte - length of the source buffer. Upon entry, destLen is the total size of the - destination buffer, which must be at least the value returned by - compressBound(sourceLen). Upon exit, destLen is the actual size of the - compressed buffer. - - compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough - memory, Z_BUF_ERROR if there was not enough room in the output buffer, - Z_STREAM_ERROR if the level parameter is invalid. -*/ - -ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); -/* - compressBound() returns an upper bound on the compressed size after - compress() or compress2() on sourceLen bytes. It would be used before - a compress() or compress2() call to allocate the destination buffer. -*/ - -ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, - const Bytef *source, uLong sourceLen)); -/* - Decompresses the source buffer into the destination buffer. sourceLen is - the byte length of the source buffer. Upon entry, destLen is the total - size of the destination buffer, which must be large enough to hold the - entire uncompressed data. (The size of the uncompressed data must have - been saved previously by the compressor and transmitted to the decompressor - by some mechanism outside the scope of this compression library.) - Upon exit, destLen is the actual size of the compressed buffer. - This function can be used to decompress a whole file at once if the - input file is mmap'ed. - - uncompress returns Z_OK if success, Z_MEM_ERROR if there was not - enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. -*/ - - -typedef voidp gzFile; - -ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); -/* - Opens a gzip (.gz) file for reading or writing. The mode parameter - is as in fopen ("rb" or "wb") but can also include a compression level - ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for - Huffman only compression as in "wb1h", or 'R' for run-length encoding - as in "wb1R". (See the description of deflateInit2 for more information - about the strategy parameter.) - - gzopen can be used to read a file which is not in gzip format; in this - case gzread will directly read from the file without decompression. - - gzopen returns NULL if the file could not be opened or if there was - insufficient memory to allocate the (de)compression state; errno - can be checked to distinguish the two cases (if errno is zero, the - zlib error is Z_MEM_ERROR). */ - -ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); -/* - gzdopen() associates a gzFile with the file descriptor fd. File - descriptors are obtained from calls like open, dup, creat, pipe or - fileno (in the file has been previously opened with fopen). - The mode parameter is as in gzopen. - The next call of gzclose on the returned gzFile will also close the - file descriptor fd, just like fclose(fdopen(fd), mode) closes the file - descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode). - gzdopen returns NULL if there was insufficient memory to allocate - the (de)compression state. -*/ - -ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); -/* - Dynamically update the compression level or strategy. See the description - of deflateInit2 for the meaning of these parameters. - gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not - opened for writing. -*/ - -ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); -/* - Reads the given number of uncompressed bytes from the compressed file. - If the input file was not in gzip format, gzread copies the given number - of bytes into the buffer. - gzread returns the number of uncompressed bytes actually read (0 for - end of file, -1 for error). */ - -ZEXTERN int ZEXPORT gzwrite OF((gzFile file, - voidpc buf, unsigned len)); -/* - Writes the given number of uncompressed bytes into the compressed file. - gzwrite returns the number of uncompressed bytes actually written - (0 in case of error). -*/ - -ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); -/* - Converts, formats, and writes the args to the compressed file under - control of the format string, as in fprintf. gzprintf returns the number of - uncompressed bytes actually written (0 in case of error). The number of - uncompressed bytes written is limited to 4095. The caller should assure that - this limit is not exceeded. If it is exceeded, then gzprintf() will return - return an error (0) with nothing written. In this case, there may also be a - buffer overflow with unpredictable consequences, which is possible only if - zlib was compiled with the insecure functions sprintf() or vsprintf() - because the secure snprintf() or vsnprintf() functions were not available. -*/ - -ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); -/* - Writes the given null-terminated string to the compressed file, excluding - the terminating null character. - gzputs returns the number of characters written, or -1 in case of error. -*/ - -ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); -/* - Reads bytes from the compressed file until len-1 characters are read, or - a newline character is read and transferred to buf, or an end-of-file - condition is encountered. The string is then terminated with a null - character. - gzgets returns buf, or Z_NULL in case of error. -*/ - -ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); -/* - Writes c, converted to an unsigned char, into the compressed file. - gzputc returns the value that was written, or -1 in case of error. -*/ - -ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); -/* - Reads one byte from the compressed file. gzgetc returns this byte - or -1 in case of end of file or error. -*/ - -ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); -/* - Push one character back onto the stream to be read again later. - Only one character of push-back is allowed. gzungetc() returns the - character pushed, or -1 on failure. gzungetc() will fail if a - character has been pushed but not read yet, or if c is -1. The pushed - character will be discarded if the stream is repositioned with gzseek() - or gzrewind(). -*/ - -ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); -/* - Flushes all pending output into the compressed file. The parameter - flush is as in the deflate() function. The return value is the zlib - error number (see function gzerror below). gzflush returns Z_OK if - the flush parameter is Z_FINISH and all output could be flushed. - gzflush should be called only when strictly necessary because it can - degrade compression. -*/ - -ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, - z_off_t offset, int whence)); -/* - Sets the starting position for the next gzread or gzwrite on the - given compressed file. The offset represents a number of bytes in the - uncompressed data stream. The whence parameter is defined as in lseek(2); - the value SEEK_END is not supported. - If the file is opened for reading, this function is emulated but can be - extremely slow. If the file is opened for writing, only forward seeks are - supported; gzseek then compresses a sequence of zeroes up to the new - starting position. - - gzseek returns the resulting offset location as measured in bytes from - the beginning of the uncompressed stream, or -1 in case of error, in - particular if the file is opened for writing and the new starting position - would be before the current position. -*/ - -ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); -/* - Rewinds the given file. This function is supported only for reading. - - gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) -*/ - -ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); -/* - Returns the starting position for the next gzread or gzwrite on the - given compressed file. This position represents a number of bytes in the - uncompressed data stream. - - gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) -*/ - -ZEXTERN int ZEXPORT gzeof OF((gzFile file)); -/* - Returns 1 when EOF has previously been detected reading the given - input stream, otherwise zero. -*/ - -ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); -/* - Returns 1 if file is being read directly without decompression, otherwise - zero. -*/ - -ZEXTERN int ZEXPORT gzclose OF((gzFile file)); -/* - Flushes all pending output if necessary, closes the compressed file - and deallocates all the (de)compression state. The return value is the zlib - error number (see function gzerror below). -*/ - -ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); -/* - Returns the error message for the last error which occurred on the - given compressed file. errnum is set to zlib error number. If an - error occurred in the file system and not in the compression library, - errnum is set to Z_ERRNO and the application may consult errno - to get the exact error code. -*/ - -ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); -/* - Clears the error and end-of-file flags for file. This is analogous to the - clearerr() function in stdio. This is useful for continuing to read a gzip - file that is being written concurrently. -*/ - - /* checksum functions */ - -/* - These functions are not related to compression but are exported - anyway because they might be useful in applications using the - compression library. -*/ - -ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); -/* - Update a running Adler-32 checksum with the bytes buf[0..len-1] and - return the updated checksum. If buf is NULL, this function returns - the required initial value for the checksum. - An Adler-32 checksum is almost as reliable as a CRC32 but can be computed - much faster. Usage example: - - uLong adler = adler32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - adler = adler32(adler, buffer, length); - } - if (adler != original_adler) error(); -*/ - -ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, - z_off_t len2)); -/* - Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 - and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for - each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of - seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. -*/ - -ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); -/* - Update a running CRC-32 with the bytes buf[0..len-1] and return the - updated CRC-32. If buf is NULL, this function returns the required initial - value for the for the crc. Pre- and post-conditioning (one's complement) is - performed within this function so it shouldn't be done by the application. - Usage example: - - uLong crc = crc32(0L, Z_NULL, 0); - - while (read_buffer(buffer, length) != EOF) { - crc = crc32(crc, buffer, length); - } - if (crc != original_crc) error(); -*/ - -ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); - -/* - Combine two CRC-32 check values into one. For two sequences of bytes, - seq1 and seq2 with lengths len1 and len2, CRC-32 check values were - calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 - check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and - len2. -*/ - - - /* various hacks, don't look :) */ - -/* deflateInit and inflateInit are macros to allow checking the zlib version - * and the compiler's view of z_stream: - */ -ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, - int windowBits, int memLevel, - int strategy, const char *version, - int stream_size)); -ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, - const char *version, int stream_size)); -ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, - unsigned char FAR *window, - const char *version, - int stream_size)); -#define deflateInit(strm, level) \ - deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit(strm) \ - inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) -#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ - deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ - (strategy), ZLIB_VERSION, sizeof(z_stream)) -#define inflateInit2(strm, windowBits) \ - inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) -#define inflateBackInit(strm, windowBits, window) \ - inflateBackInit_((strm), (windowBits), (window), \ - ZLIB_VERSION, sizeof(z_stream)) - - -#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) - struct internal_state {int dummy;}; /* hack for buggy compilers */ -#endif - -ZEXTERN const char * ZEXPORT zError OF((int)); -ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z)); -ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); - -#ifdef __cplusplus -} -#endif - -#endif /* ZLIB_H */ diff --git a/dep/StormLib/src/zlib/zutil.c b/dep/StormLib/src/zlib/zutil.c deleted file mode 100644 index d55f5948a37..00000000000 --- a/dep/StormLib/src/zlib/zutil.c +++ /dev/null @@ -1,318 +0,0 @@ -/* zutil.c -- target dependent utility functions for the compression library - * Copyright (C) 1995-2005 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* @(#) $Id$ */ - -#include "zutil.h" - -#ifndef NO_DUMMY_DECL -struct internal_state {int dummy;}; /* for buggy compilers */ -#endif - -const char * const z_errmsg[10] = { -"need dictionary", /* Z_NEED_DICT 2 */ -"stream end", /* Z_STREAM_END 1 */ -"", /* Z_OK 0 */ -"file error", /* Z_ERRNO (-1) */ -"stream error", /* Z_STREAM_ERROR (-2) */ -"data error", /* Z_DATA_ERROR (-3) */ -"insufficient memory", /* Z_MEM_ERROR (-4) */ -"buffer error", /* Z_BUF_ERROR (-5) */ -"incompatible version",/* Z_VERSION_ERROR (-6) */ -""}; - - -const char * ZEXPORT zlibVersion() -{ - return ZLIB_VERSION; -} - -uLong ZEXPORT zlibCompileFlags() -{ - uLong flags; - - flags = 0; - switch (sizeof(uInt)) { - case 2: break; - case 4: flags += 1; break; - case 8: flags += 2; break; - default: flags += 3; - } - switch (sizeof(uLong)) { - case 2: break; - case 4: flags += 1 << 2; break; - case 8: flags += 2 << 2; break; - default: flags += 3 << 2; - } - switch (sizeof(voidpf)) { - case 2: break; - case 4: flags += 1 << 4; break; - case 8: flags += 2 << 4; break; - default: flags += 3 << 4; - } - switch (sizeof(z_off_t)) { - case 2: break; - case 4: flags += 1 << 6; break; - case 8: flags += 2 << 6; break; - default: flags += 3 << 6; - } -#ifdef DEBUG - flags += 1 << 8; -#endif -#if defined(ASMV) || defined(ASMINF) - flags += 1 << 9; -#endif -#ifdef ZLIB_WINAPI - flags += 1 << 10; -#endif -#ifdef BUILDFIXED - flags += 1 << 12; -#endif -#ifdef DYNAMIC_CRC_TABLE - flags += 1 << 13; -#endif -#ifdef NO_GZCOMPRESS - flags += 1L << 16; -#endif -#ifdef NO_GZIP - flags += 1L << 17; -#endif -#ifdef PKZIP_BUG_WORKAROUND - flags += 1L << 20; -#endif -#ifdef FASTEST - flags += 1L << 21; -#endif -#ifdef STDC -# ifdef NO_vsnprintf - flags += 1L << 25; -# ifdef HAS_vsprintf_void - flags += 1L << 26; -# endif -# else -# ifdef HAS_vsnprintf_void - flags += 1L << 26; -# endif -# endif -#else - flags += 1L << 24; -# ifdef NO_snprintf - flags += 1L << 25; -# ifdef HAS_sprintf_void - flags += 1L << 26; -# endif -# else -# ifdef HAS_snprintf_void - flags += 1L << 26; -# endif -# endif -#endif - return flags; -} - -#ifdef DEBUG - -# ifndef verbose -# define verbose 0 -# endif -int z_verbose = verbose; - -void z_error (m) - char *m; -{ - fprintf(stderr, "%s\n", m); - exit(1); -} -#endif - -/* exported to allow conversion of error code to string for compress() and - * uncompress() - */ -const char * ZEXPORT zError(err) - int err; -{ - return ERR_MSG(err); -} - -#if defined(_WIN32_WCE) - /* The Microsoft C Run-Time Library for Windows CE doesn't have - * errno. We define it as a global variable to simplify porting. - * Its value is always 0 and should not be used. - */ - int errno = 0; -#endif - -#ifndef HAVE_MEMCPY - -void zmemcpy(dest, source, len) - Bytef* dest; - const Bytef* source; - uInt len; -{ - if (len == 0) return; - do { - *dest++ = *source++; /* ??? to be unrolled */ - } while (--len != 0); -} - -int zmemcmp(s1, s2, len) - const Bytef* s1; - const Bytef* s2; - uInt len; -{ - uInt j; - - for (j = 0; j < len; j++) { - if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; - } - return 0; -} - -void zmemzero(dest, len) - Bytef* dest; - uInt len; -{ - if (len == 0) return; - do { - *dest++ = 0; /* ??? to be unrolled */ - } while (--len != 0); -} -#endif - - -#ifdef SYS16BIT - -#ifdef __TURBOC__ -/* Turbo C in 16-bit mode */ - -# define MY_ZCALLOC - -/* Turbo C malloc() does not allow dynamic allocation of 64K bytes - * and farmalloc(64K) returns a pointer with an offset of 8, so we - * must fix the pointer. Warning: the pointer must be put back to its - * original form in order to free it, use zcfree(). - */ - -#define MAX_PTR 10 -/* 10*64K = 640K */ - -local int next_ptr = 0; - -typedef struct ptr_table_s { - voidpf org_ptr; - voidpf new_ptr; -} ptr_table; - -local ptr_table table[MAX_PTR]; -/* This table is used to remember the original form of pointers - * to large buffers (64K). Such pointers are normalized with a zero offset. - * Since MSDOS is not a preemptive multitasking OS, this table is not - * protected from concurrent access. This hack doesn't work anyway on - * a protected system like OS/2. Use Microsoft C instead. - */ - -voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) -{ - voidpf buf = opaque; /* just to make some compilers happy */ - ulg bsize = (ulg)items*size; - - /* If we allocate less than 65520 bytes, we assume that farmalloc - * will return a usable pointer which doesn't have to be normalized. - */ - if (bsize < 65520L) { - buf = farmalloc(bsize); - if (*(ush*)&buf != 0) return buf; - } else { - buf = farmalloc(bsize + 16L); - } - if (buf == NULL || next_ptr >= MAX_PTR) return NULL; - table[next_ptr].org_ptr = buf; - - /* Normalize the pointer to seg:0 */ - *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; - *(ush*)&buf = 0; - table[next_ptr++].new_ptr = buf; - return buf; -} - -void zcfree (voidpf opaque, voidpf ptr) -{ - int n; - if (*(ush*)&ptr != 0) { /* object < 64K */ - farfree(ptr); - return; - } - /* Find the original pointer */ - for (n = 0; n < next_ptr; n++) { - if (ptr != table[n].new_ptr) continue; - - farfree(table[n].org_ptr); - while (++n < next_ptr) { - table[n-1] = table[n]; - } - next_ptr--; - return; - } - ptr = opaque; /* just to make some compilers happy */ - Assert(0, "zcfree: ptr not found"); -} - -#endif /* __TURBOC__ */ - - -#ifdef M_I86 -/* Microsoft C in 16-bit mode */ - -# define MY_ZCALLOC - -#if (!defined(_MSC_VER) || (_MSC_VER <= 600)) -# define _halloc halloc -# define _hfree hfree -#endif - -voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) -{ - if (opaque) opaque = 0; /* to make compiler happy */ - return _halloc((long)items, size); -} - -void zcfree (voidpf opaque, voidpf ptr) -{ - if (opaque) opaque = 0; /* to make compiler happy */ - _hfree(ptr); -} - -#endif /* M_I86 */ - -#endif /* SYS16BIT */ - - -#ifndef MY_ZCALLOC /* Any system without a special alloc function */ - -#ifndef STDC -extern voidp malloc OF((uInt size)); -extern voidp calloc OF((uInt items, uInt size)); -extern void free OF((voidpf ptr)); -#endif - -voidpf zcalloc (opaque, items, size) - voidpf opaque; - unsigned items; - unsigned size; -{ - if (opaque) items += size - size; /* make compiler happy */ - return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : - (voidpf)calloc(items, size); -} - -void zcfree (opaque, ptr) - voidpf opaque; - voidpf ptr; -{ - free(ptr); - if (opaque) return; /* make compiler happy */ -} - -#endif /* MY_ZCALLOC */ diff --git a/dep/StormLib/src/zlib/zutil.h b/dep/StormLib/src/zlib/zutil.h deleted file mode 100644 index b7d5eff81b6..00000000000 --- a/dep/StormLib/src/zlib/zutil.h +++ /dev/null @@ -1,269 +0,0 @@ -/* zutil.h -- internal interface and configuration of the compression library - * Copyright (C) 1995-2005 Jean-loup Gailly. - * For conditions of distribution and use, see copyright notice in zlib.h - */ - -/* WARNING: this file should *not* be used by applications. It is - part of the implementation of the compression library and is - subject to change. Applications should only use zlib.h. - */ - -/* @(#) $Id$ */ - -#ifndef ZUTIL_H -#define ZUTIL_H - -#define ZLIB_INTERNAL -#include "zlib.h" - -#ifdef STDC -# ifndef _WIN32_WCE -# include -# endif -# include -# include -#endif -#ifdef NO_ERRNO_H -# ifdef _WIN32_WCE - /* The Microsoft C Run-Time Library for Windows CE doesn't have - * errno. We define it as a global variable to simplify porting. - * Its value is always 0 and should not be used. We rename it to - * avoid conflict with other libraries that use the same workaround. - */ -# define errno z_errno -# endif - extern int errno; -#else -# ifndef _WIN32_WCE -# include -# endif -#endif - -#ifndef local -# define local static -#endif -/* compile with -Dlocal if your debugger can't find static symbols */ - -typedef unsigned char uch; -typedef uch FAR uchf; -typedef unsigned short ush; -typedef ush FAR ushf; -typedef unsigned long ulg; - -extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ -/* (size given to avoid silly warnings with Visual C++) */ - -#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] - -#define ERR_RETURN(strm,err) \ - return (strm->msg = (char*)ERR_MSG(err), (err)) -/* To be used only when the state is known to be valid */ - - /* common constants */ - -#ifndef DEF_WBITS -# define DEF_WBITS MAX_WBITS -#endif -/* default windowBits for decompression. MAX_WBITS is for compression only */ - -#if MAX_MEM_LEVEL >= 8 -# define DEF_MEM_LEVEL 8 -#else -# define DEF_MEM_LEVEL MAX_MEM_LEVEL -#endif -/* default memLevel */ - -#define STORED_BLOCK 0 -#define STATIC_TREES 1 -#define DYN_TREES 2 -/* The three kinds of block type */ - -#define MIN_MATCH 3 -#define MAX_MATCH 258 -/* The minimum and maximum match lengths */ - -#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ - - /* target dependencies */ - -#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) -# define OS_CODE 0x00 -# if defined(__TURBOC__) || defined(__BORLANDC__) -# if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) - /* Allow compilation with ANSI keywords only enabled */ - void _Cdecl farfree( void *block ); - void *_Cdecl farmalloc( unsigned long nbytes ); -# else -# include -# endif -# else /* MSC or DJGPP */ -# include -# endif -#endif - -#ifdef AMIGA -# define OS_CODE 0x01 -#endif - -#if defined(VAXC) || defined(VMS) -# define OS_CODE 0x02 -# define F_OPEN(name, mode) \ - fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") -#endif - -#if defined(ATARI) || defined(atarist) -# define OS_CODE 0x05 -#endif - -#ifdef OS2 -# define OS_CODE 0x06 -# ifdef M_I86 - #include -# endif -#endif - -#if defined(MACOS) || defined(TARGET_OS_MAC) -# define OS_CODE 0x07 -# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os -# include /* for fdopen */ -# else -# ifndef fdopen -# define fdopen(fd,mode) NULL /* No fdopen() */ -# endif -# endif -#endif - -#ifdef TOPS20 -# define OS_CODE 0x0a -#endif - -#ifdef WIN32 -# ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */ -# define OS_CODE 0x0b -# endif -#endif - -#ifdef __50SERIES /* Prime/PRIMOS */ -# define OS_CODE 0x0f -#endif - -#if defined(_BEOS_) || defined(RISCOS) -# define fdopen(fd,mode) NULL /* No fdopen() */ -#endif - -#if (defined(_MSC_VER) && (_MSC_VER > 600)) -# if defined(_WIN32_WCE) -# define fdopen(fd,mode) NULL /* No fdopen() */ -# ifndef _PTRDIFF_T_DEFINED - typedef int ptrdiff_t; -# define _PTRDIFF_T_DEFINED -# endif -# else -# define fdopen(fd,type) _fdopen(fd,type) -# endif -#endif - - /* common defaults */ - -#ifndef OS_CODE -# define OS_CODE 0x03 /* assume Unix */ -#endif - -#ifndef F_OPEN -# define F_OPEN(name, mode) fopen((name), (mode)) -#endif - - /* functions */ - -#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) -# ifndef HAVE_VSNPRINTF -# define HAVE_VSNPRINTF -# endif -#endif -#if defined(__CYGWIN__) -# ifndef HAVE_VSNPRINTF -# define HAVE_VSNPRINTF -# endif -#endif -#ifndef HAVE_VSNPRINTF -# ifdef MSDOS - /* vsnprintf may exist on some MS-DOS compilers (DJGPP?), - but for now we just assume it doesn't. */ -# define NO_vsnprintf -# endif -# ifdef __TURBOC__ -# define NO_vsnprintf -# endif -# ifdef WIN32 - /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ -# if !defined(vsnprintf) && !defined(NO_vsnprintf) -# define vsnprintf _vsnprintf -# endif -# endif -# ifdef __SASC -# define NO_vsnprintf -# endif -#endif -#ifdef VMS -# define NO_vsnprintf -#endif - -#if defined(pyr) -# define NO_MEMCPY -#endif -#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) - /* Use our own functions for small and medium model with MSC <= 5.0. - * You may have to use the same strategy for Borland C (untested). - * The __SC__ check is for Symantec. - */ -# define NO_MEMCPY -#endif -#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) -# define HAVE_MEMCPY -#endif -#ifdef HAVE_MEMCPY -# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ -# define zmemcpy _fmemcpy -# define zmemcmp _fmemcmp -# define zmemzero(dest, len) _fmemset(dest, 0, len) -# else -# define zmemcpy memcpy -# define zmemcmp memcmp -# define zmemzero(dest, len) memset(dest, 0, len) -# endif -#else - extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); - extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); - extern void zmemzero OF((Bytef* dest, uInt len)); -#endif - -/* Diagnostic functions */ -#ifdef DEBUG -# include - extern int z_verbose; - extern void z_error OF((char *m)); -# define Assert(cond,msg) {if(!(cond)) z_error(msg);} -# define Trace(x) {if (z_verbose>=0) fprintf x ;} -# define Tracev(x) {if (z_verbose>0) fprintf x ;} -# define Tracevv(x) {if (z_verbose>1) fprintf x ;} -# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} -# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} -#else -# define Assert(cond,msg) -# define Trace(x) -# define Tracev(x) -# define Tracevv(x) -# define Tracec(c,x) -# define Tracecv(c,x) -#endif - - -voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size)); -void zcfree OF((voidpf opaque, voidpf ptr)); - -#define ZALLOC(strm, items, size) \ - (*((strm)->zalloc))((strm)->opaque, (items), (size)) -#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) -#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} - -#endif /* ZUTIL_H */ diff --git a/dep/boost/CMakeLists.txt b/dep/boost/CMakeLists.txt index b556caaaf8b..ec52cc55132 100644 --- a/dep/boost/CMakeLists.txt +++ b/dep/boost/CMakeLists.txt @@ -74,7 +74,10 @@ target_compile_definitions(boost -DBOOST_CHRONO_NO_LIB # Due to MSVC linking error boost::none" already defined in scripts_... # May be removed when the requirement is raised to boost 1.61 on windows. - -DBOOST_OPTIONAL_USE_OLD_DEFINITION_OF_NONE) + -DBOOST_OPTIONAL_USE_OLD_DEFINITION_OF_NONE + -DBOOST_CHRONO_NO_LIB + -DBOOST_CONFIG_SUPPRESS_OUTDATED_MESSAGE + -DBOOST_ASIO_NO_DEPRECATED) if (NOT boost_filesystem_copy_links_without_NO_SCOPED_ENUM) target_compile_definitions(boost diff --git a/dep/bzip2/CMakeLists.txt b/dep/bzip2/CMakeLists.txt index 35d70287f88..84869f4b153 100644 --- a/dep/bzip2/CMakeLists.txt +++ b/dep/bzip2/CMakeLists.txt @@ -30,6 +30,10 @@ else() PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) + target_link_libraries(bzip2 + PRIVATE + trinity-dependency-interface) + set_target_properties(bzip2 PROPERTIES FOLDER diff --git a/dep/cotire/CMake/cotire.cmake b/dep/cotire/CMake/cotire.cmake new file mode 100644 index 00000000000..62cd23db987 --- /dev/null +++ b/dep/cotire/CMake/cotire.cmake @@ -0,0 +1,4054 @@ +# - cotire (compile time reducer) +# +# See the cotire manual for usage hints. +# +#============================================================================= +# Copyright 2012-2017 Sascha Kratky +# +# Permission is hereby granted, free of charge, to any person +# obtaining a copy of this software and associated documentation +# files (the "Software"), to deal in the Software without +# restriction, including without limitation the rights to use, +# copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the +# Software is furnished to do so, subject to the following +# conditions: +# +# The above copyright notice and this permission notice shall be +# included in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +# OTHER DEALINGS IN THE SOFTWARE. +#============================================================================= + +if(__COTIRE_INCLUDED) + return() +endif() +set(__COTIRE_INCLUDED TRUE) + +# call cmake_minimum_required, but prevent modification of the CMake policy stack in include mode +# cmake_minimum_required also sets the policy version as a side effect, which we have to avoid +if (NOT CMAKE_SCRIPT_MODE_FILE) + cmake_policy(PUSH) +endif() +cmake_minimum_required(VERSION 2.8.12) +if (NOT CMAKE_SCRIPT_MODE_FILE) + cmake_policy(POP) +endif() + +set (COTIRE_CMAKE_MODULE_FILE "${CMAKE_CURRENT_LIST_FILE}") +set (COTIRE_CMAKE_MODULE_VERSION "1.7.10") + +# activate select policies +if (POLICY CMP0025) + # Compiler id for Apple Clang is now AppleClang + cmake_policy(SET CMP0025 NEW) +endif() + +if (POLICY CMP0026) + # disallow use of the LOCATION target property + cmake_policy(SET CMP0026 NEW) +endif() + +if (POLICY CMP0038) + # targets may not link directly to themselves + cmake_policy(SET CMP0038 NEW) +endif() + +if (POLICY CMP0039) + # utility targets may not have link dependencies + cmake_policy(SET CMP0039 NEW) +endif() + +if (POLICY CMP0040) + # target in the TARGET signature of add_custom_command() must exist + cmake_policy(SET CMP0040 NEW) +endif() + +if (POLICY CMP0045) + # error on non-existent target in get_target_property + cmake_policy(SET CMP0045 NEW) +endif() + +if (POLICY CMP0046) + # error on non-existent dependency in add_dependencies + cmake_policy(SET CMP0046 NEW) +endif() + +if (POLICY CMP0049) + # do not expand variables in target source entries + cmake_policy(SET CMP0049 NEW) +endif() + +if (POLICY CMP0050) + # disallow add_custom_command SOURCE signatures + cmake_policy(SET CMP0050 NEW) +endif() + +if (POLICY CMP0051) + # include TARGET_OBJECTS expressions in a target's SOURCES property + cmake_policy(SET CMP0051 NEW) +endif() + +if (POLICY CMP0053) + # simplify variable reference and escape sequence evaluation + cmake_policy(SET CMP0053 NEW) +endif() + +if (POLICY CMP0054) + # only interpret if() arguments as variables or keywords when unquoted + cmake_policy(SET CMP0054 NEW) +endif() + +if (POLICY CMP0055) + # strict checking for break() command + cmake_policy(SET CMP0055 NEW) +endif() + +include(CMakeParseArguments) +include(ProcessorCount) + +function (cotire_get_configuration_types _configsVar) + set (_configs "") + if (CMAKE_CONFIGURATION_TYPES) + list (APPEND _configs ${CMAKE_CONFIGURATION_TYPES}) + endif() + if (CMAKE_BUILD_TYPE) + list (APPEND _configs "${CMAKE_BUILD_TYPE}") + endif() + if (_configs) + list (REMOVE_DUPLICATES _configs) + set (${_configsVar} ${_configs} PARENT_SCOPE) + else() + set (${_configsVar} "None" PARENT_SCOPE) + endif() +endfunction() + +function (cotire_get_source_file_extension _sourceFile _extVar) + # get_filename_component returns extension from first occurrence of . in file name + # this function computes the extension from last occurrence of . in file name + string (FIND "${_sourceFile}" "." _index REVERSE) + if (_index GREATER -1) + math (EXPR _index "${_index} + 1") + string (SUBSTRING "${_sourceFile}" ${_index} -1 _sourceExt) + else() + set (_sourceExt "") + endif() + set (${_extVar} "${_sourceExt}" PARENT_SCOPE) +endfunction() + +macro (cotire_check_is_path_relative_to _path _isRelativeVar) + set (${_isRelativeVar} FALSE) + if (IS_ABSOLUTE "${_path}") + foreach (_dir ${ARGN}) + file (RELATIVE_PATH _relPath "${_dir}" "${_path}") + if (NOT _relPath OR (NOT IS_ABSOLUTE "${_relPath}" AND NOT "${_relPath}" MATCHES "^\\.\\.")) + set (${_isRelativeVar} TRUE) + break() + endif() + endforeach() + endif() +endmacro() + +function (cotire_filter_language_source_files _language _target _sourceFilesVar _excludedSourceFilesVar _cotiredSourceFilesVar) + if (CMAKE_${_language}_SOURCE_FILE_EXTENSIONS) + set (_languageExtensions "${CMAKE_${_language}_SOURCE_FILE_EXTENSIONS}") + else() + set (_languageExtensions "") + endif() + if (CMAKE_${_language}_IGNORE_EXTENSIONS) + set (_ignoreExtensions "${CMAKE_${_language}_IGNORE_EXTENSIONS}") + else() + set (_ignoreExtensions "") + endif() + if (COTIRE_UNITY_SOURCE_EXCLUDE_EXTENSIONS) + set (_excludeExtensions "${COTIRE_UNITY_SOURCE_EXCLUDE_EXTENSIONS}") + else() + set (_excludeExtensions "") + endif() + if (COTIRE_DEBUG AND _languageExtensions) + message (STATUS "${_language} source file extensions: ${_languageExtensions}") + endif() + if (COTIRE_DEBUG AND _ignoreExtensions) + message (STATUS "${_language} ignore extensions: ${_ignoreExtensions}") + endif() + if (COTIRE_DEBUG AND _excludeExtensions) + message (STATUS "${_language} exclude extensions: ${_excludeExtensions}") + endif() + if (CMAKE_VERSION VERSION_LESS "3.1.0") + set (_allSourceFiles ${ARGN}) + else() + # as of CMake 3.1 target sources may contain generator expressions + # since we cannot obtain required property information about source files added + # through generator expressions at configure time, we filter them out + string (GENEX_STRIP "${ARGN}" _allSourceFiles) + endif() + set (_filteredSourceFiles "") + set (_excludedSourceFiles "") + foreach (_sourceFile ${_allSourceFiles}) + get_source_file_property(_sourceIsHeaderOnly "${_sourceFile}" HEADER_FILE_ONLY) + get_source_file_property(_sourceIsExternal "${_sourceFile}" EXTERNAL_OBJECT) + get_source_file_property(_sourceIsSymbolic "${_sourceFile}" SYMBOLIC) + if (NOT _sourceIsHeaderOnly AND NOT _sourceIsExternal AND NOT _sourceIsSymbolic) + cotire_get_source_file_extension("${_sourceFile}" _sourceExt) + if (_sourceExt) + list (FIND _ignoreExtensions "${_sourceExt}" _ignoreIndex) + if (_ignoreIndex LESS 0) + list (FIND _excludeExtensions "${_sourceExt}" _excludeIndex) + if (_excludeIndex GREATER -1) + list (APPEND _excludedSourceFiles "${_sourceFile}") + else() + list (FIND _languageExtensions "${_sourceExt}" _sourceIndex) + if (_sourceIndex GREATER -1) + # consider source file unless it is excluded explicitly + get_source_file_property(_sourceIsExcluded "${_sourceFile}" COTIRE_EXCLUDED) + if (_sourceIsExcluded) + list (APPEND _excludedSourceFiles "${_sourceFile}") + else() + list (APPEND _filteredSourceFiles "${_sourceFile}") + endif() + else() + get_source_file_property(_sourceLanguage "${_sourceFile}" LANGUAGE) + if ("${_sourceLanguage}" STREQUAL "${_language}") + # add to excluded sources, if file is not ignored and has correct language without having the correct extension + list (APPEND _excludedSourceFiles "${_sourceFile}") + endif() + endif() + endif() + endif() + endif() + endif() + endforeach() + # separate filtered source files from already cotired ones + # the COTIRE_TARGET property of a source file may be set while a target is being processed by cotire + set (_sourceFiles "") + set (_cotiredSourceFiles "") + foreach (_sourceFile ${_filteredSourceFiles}) + get_source_file_property(_sourceIsCotired "${_sourceFile}" COTIRE_TARGET) + if (_sourceIsCotired) + list (APPEND _cotiredSourceFiles "${_sourceFile}") + else() + get_source_file_property(_sourceCompileFlags "${_sourceFile}" COMPILE_FLAGS) + if (_sourceCompileFlags) + # add to excluded sources, if file has custom compile flags + list (APPEND _excludedSourceFiles "${_sourceFile}") + else() + list (APPEND _sourceFiles "${_sourceFile}") + endif() + endif() + endforeach() + if (COTIRE_DEBUG) + if (_sourceFiles) + message (STATUS "Filtered ${_target} ${_language} sources: ${_sourceFiles}") + endif() + if (_excludedSourceFiles) + message (STATUS "Excluded ${_target} ${_language} sources: ${_excludedSourceFiles}") + endif() + if (_cotiredSourceFiles) + message (STATUS "Cotired ${_target} ${_language} sources: ${_cotiredSourceFiles}") + endif() + endif() + set (${_sourceFilesVar} ${_sourceFiles} PARENT_SCOPE) + set (${_excludedSourceFilesVar} ${_excludedSourceFiles} PARENT_SCOPE) + set (${_cotiredSourceFilesVar} ${_cotiredSourceFiles} PARENT_SCOPE) +endfunction() + +function (cotire_get_objects_with_property_on _filteredObjectsVar _property _type) + set (_filteredObjects "") + foreach (_object ${ARGN}) + get_property(_isSet ${_type} "${_object}" PROPERTY ${_property} SET) + if (_isSet) + get_property(_propertyValue ${_type} "${_object}" PROPERTY ${_property}) + if (_propertyValue) + list (APPEND _filteredObjects "${_object}") + endif() + endif() + endforeach() + set (${_filteredObjectsVar} ${_filteredObjects} PARENT_SCOPE) +endfunction() + +function (cotire_get_objects_with_property_off _filteredObjectsVar _property _type) + set (_filteredObjects "") + foreach (_object ${ARGN}) + get_property(_isSet ${_type} "${_object}" PROPERTY ${_property} SET) + if (_isSet) + get_property(_propertyValue ${_type} "${_object}" PROPERTY ${_property}) + if (NOT _propertyValue) + list (APPEND _filteredObjects "${_object}") + endif() + endif() + endforeach() + set (${_filteredObjectsVar} ${_filteredObjects} PARENT_SCOPE) +endfunction() + +function (cotire_get_source_file_property_values _valuesVar _property) + set (_values "") + foreach (_sourceFile ${ARGN}) + get_source_file_property(_propertyValue "${_sourceFile}" ${_property}) + if (_propertyValue) + list (APPEND _values "${_propertyValue}") + endif() + endforeach() + set (${_valuesVar} ${_values} PARENT_SCOPE) +endfunction() + +function (cotire_resolve_config_properties _configurations _propertiesVar) + set (_properties "") + foreach (_property ${ARGN}) + if ("${_property}" MATCHES "") + foreach (_config ${_configurations}) + string (TOUPPER "${_config}" _upperConfig) + string (REPLACE "" "${_upperConfig}" _configProperty "${_property}") + list (APPEND _properties ${_configProperty}) + endforeach() + else() + list (APPEND _properties ${_property}) + endif() + endforeach() + set (${_propertiesVar} ${_properties} PARENT_SCOPE) +endfunction() + +function (cotire_copy_set_properties _configurations _type _source _target) + cotire_resolve_config_properties("${_configurations}" _properties ${ARGN}) + foreach (_property ${_properties}) + get_property(_isSet ${_type} ${_source} PROPERTY ${_property} SET) + if (_isSet) + get_property(_propertyValue ${_type} ${_source} PROPERTY ${_property}) + set_property(${_type} ${_target} PROPERTY ${_property} "${_propertyValue}") + endif() + endforeach() +endfunction() + +function (cotire_get_target_usage_requirements _target _config _targetRequirementsVar) + set (_targetRequirements "") + get_target_property(_librariesToProcess ${_target} LINK_LIBRARIES) + while (_librariesToProcess) + # remove from head + list (GET _librariesToProcess 0 _library) + list (REMOVE_AT _librariesToProcess 0) + if (_library MATCHES "^\\$<\\$:([A-Za-z0-9_:-]+)>$") + set (_library "${CMAKE_MATCH_1}") + elseif (_config STREQUAL "None" AND _library MATCHES "^\\$<\\$:([A-Za-z0-9_:-]+)>$") + set (_library "${CMAKE_MATCH_1}") + endif() + if (TARGET ${_library}) + list (FIND _targetRequirements ${_library} _index) + if (_index LESS 0) + list (APPEND _targetRequirements ${_library}) + # BFS traversal of transitive libraries + get_target_property(_libraries ${_library} INTERFACE_LINK_LIBRARIES) + if (_libraries) + list (APPEND _librariesToProcess ${_libraries}) + list (REMOVE_DUPLICATES _librariesToProcess) + endif() + endif() + endif() + endwhile() + set (${_targetRequirementsVar} ${_targetRequirements} PARENT_SCOPE) +endfunction() + +function (cotire_filter_compile_flags _language _flagFilter _matchedOptionsVar _unmatchedOptionsVar) + if (WIN32 AND CMAKE_${_language}_COMPILER_ID MATCHES "MSVC|Intel") + set (_flagPrefix "[/-]") + else() + set (_flagPrefix "--?") + endif() + set (_optionFlag "") + set (_matchedOptions "") + set (_unmatchedOptions "") + foreach (_compileFlag ${ARGN}) + if (_compileFlag) + if (_optionFlag AND NOT "${_compileFlag}" MATCHES "^${_flagPrefix}") + # option with separate argument + list (APPEND _matchedOptions "${_compileFlag}") + set (_optionFlag "") + elseif ("${_compileFlag}" MATCHES "^(${_flagPrefix})(${_flagFilter})$") + # remember option + set (_optionFlag "${CMAKE_MATCH_2}") + elseif ("${_compileFlag}" MATCHES "^(${_flagPrefix})(${_flagFilter})(.+)$") + # option with joined argument + list (APPEND _matchedOptions "${CMAKE_MATCH_3}") + set (_optionFlag "") + else() + # flush remembered option + if (_optionFlag) + list (APPEND _matchedOptions "${_optionFlag}") + set (_optionFlag "") + endif() + # add to unfiltered options + list (APPEND _unmatchedOptions "${_compileFlag}") + endif() + endif() + endforeach() + if (_optionFlag) + list (APPEND _matchedOptions "${_optionFlag}") + endif() + if (COTIRE_DEBUG AND _matchedOptions) + message (STATUS "Filter ${_flagFilter} matched: ${_matchedOptions}") + endif() + if (COTIRE_DEBUG AND _unmatchedOptions) + message (STATUS "Filter ${_flagFilter} unmatched: ${_unmatchedOptions}") + endif() + set (${_matchedOptionsVar} ${_matchedOptions} PARENT_SCOPE) + set (${_unmatchedOptionsVar} ${_unmatchedOptions} PARENT_SCOPE) +endfunction() + +function (cotire_is_target_supported _target _isSupportedVar) + if (NOT TARGET "${_target}") + set (${_isSupportedVar} FALSE PARENT_SCOPE) + return() + endif() + get_target_property(_imported ${_target} IMPORTED) + if (_imported) + set (${_isSupportedVar} FALSE PARENT_SCOPE) + return() + endif() + get_target_property(_targetType ${_target} TYPE) + if (NOT _targetType MATCHES "EXECUTABLE|(STATIC|SHARED|MODULE|OBJECT)_LIBRARY") + set (${_isSupportedVar} FALSE PARENT_SCOPE) + return() + endif() + set (${_isSupportedVar} TRUE PARENT_SCOPE) +endfunction() + +function (cotire_get_target_compile_flags _config _language _target _flagsVar) + string (TOUPPER "${_config}" _upperConfig) + # collect options from CMake language variables + set (_compileFlags "") + if (CMAKE_${_language}_FLAGS) + set (_compileFlags "${_compileFlags} ${CMAKE_${_language}_FLAGS}") + endif() + if (CMAKE_${_language}_FLAGS_${_upperConfig}) + set (_compileFlags "${_compileFlags} ${CMAKE_${_language}_FLAGS_${_upperConfig}}") + endif() + if (_target) + # add target compile flags + get_target_property(_targetflags ${_target} COMPILE_FLAGS) + if (_targetflags) + set (_compileFlags "${_compileFlags} ${_targetflags}") + endif() + endif() + if (UNIX) + separate_arguments(_compileFlags UNIX_COMMAND "${_compileFlags}") + elseif(WIN32) + separate_arguments(_compileFlags WINDOWS_COMMAND "${_compileFlags}") + else() + separate_arguments(_compileFlags) + endif() + # target compile options + if (_target) + get_target_property(_targetOptions ${_target} COMPILE_OPTIONS) + if (_targetOptions) + list (APPEND _compileFlags ${_targetOptions}) + endif() + endif() + # interface compile options from linked library targets + if (_target) + set (_linkedTargets "") + cotire_get_target_usage_requirements(${_target} ${_config} _linkedTargets) + foreach (_linkedTarget ${_linkedTargets}) + get_target_property(_targetOptions ${_linkedTarget} INTERFACE_COMPILE_OPTIONS) + if (_targetOptions) + list (APPEND _compileFlags ${_targetOptions}) + endif() + endforeach() + endif() + # handle language standard properties + if (CMAKE_${_language}_STANDARD_DEFAULT) + # used compiler supports language standard levels + if (_target) + get_target_property(_targetLanguageStandard ${_target} ${_language}_STANDARD) + if (_targetLanguageStandard) + set (_type "EXTENSION") + get_property(_isSet TARGET ${_target} PROPERTY ${_language}_EXTENSIONS SET) + if (_isSet) + get_target_property(_targetUseLanguageExtensions ${_target} ${_language}_EXTENSIONS) + if (NOT _targetUseLanguageExtensions) + set (_type "STANDARD") + endif() + endif() + if (CMAKE_${_language}${_targetLanguageStandard}_${_type}_COMPILE_OPTION) + list (APPEND _compileFlags "${CMAKE_${_language}${_targetLanguageStandard}_${_type}_COMPILE_OPTION}") + endif() + endif() + endif() + endif() + # handle the POSITION_INDEPENDENT_CODE target property + if (_target) + get_target_property(_targetPIC ${_target} POSITION_INDEPENDENT_CODE) + if (_targetPIC) + get_target_property(_targetType ${_target} TYPE) + if (_targetType STREQUAL "EXECUTABLE" AND CMAKE_${_language}_COMPILE_OPTIONS_PIE) + list (APPEND _compileFlags "${CMAKE_${_language}_COMPILE_OPTIONS_PIE}") + elseif (CMAKE_${_language}_COMPILE_OPTIONS_PIC) + list (APPEND _compileFlags "${CMAKE_${_language}_COMPILE_OPTIONS_PIC}") + endif() + endif() + endif() + # handle visibility target properties + if (_target) + get_target_property(_targetVisibility ${_target} ${_language}_VISIBILITY_PRESET) + if (_targetVisibility AND CMAKE_${_language}_COMPILE_OPTIONS_VISIBILITY) + list (APPEND _compileFlags "${CMAKE_${_language}_COMPILE_OPTIONS_VISIBILITY}${_targetVisibility}") + endif() + get_target_property(_targetVisibilityInlines ${_target} VISIBILITY_INLINES_HIDDEN) + if (_targetVisibilityInlines AND CMAKE_${_language}_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN) + list (APPEND _compileFlags "${CMAKE_${_language}_COMPILE_OPTIONS_VISIBILITY_INLINES_HIDDEN}") + endif() + endif() + # platform specific flags + if (APPLE) + get_target_property(_architectures ${_target} OSX_ARCHITECTURES_${_upperConfig}) + if (NOT _architectures) + get_target_property(_architectures ${_target} OSX_ARCHITECTURES) + endif() + if (_architectures) + foreach (_arch ${_architectures}) + list (APPEND _compileFlags "-arch" "${_arch}") + endforeach() + endif() + if (CMAKE_OSX_SYSROOT) + if (CMAKE_${_language}_SYSROOT_FLAG) + list (APPEND _compileFlags "${CMAKE_${_language}_SYSROOT_FLAG}" "${CMAKE_OSX_SYSROOT}") + else() + list (APPEND _compileFlags "-isysroot" "${CMAKE_OSX_SYSROOT}") + endif() + endif() + if (CMAKE_OSX_DEPLOYMENT_TARGET) + if (CMAKE_${_language}_OSX_DEPLOYMENT_TARGET_FLAG) + list (APPEND _compileFlags "${CMAKE_${_language}_OSX_DEPLOYMENT_TARGET_FLAG}${CMAKE_OSX_DEPLOYMENT_TARGET}") + else() + list (APPEND _compileFlags "-mmacosx-version-min=${CMAKE_OSX_DEPLOYMENT_TARGET}") + endif() + endif() + endif() + if (COTIRE_DEBUG AND _compileFlags) + message (STATUS "Target ${_target} compile flags: ${_compileFlags}") + endif() + set (${_flagsVar} ${_compileFlags} PARENT_SCOPE) +endfunction() + +function (cotire_get_target_include_directories _config _language _target _includeDirsVar _systemIncludeDirsVar) + set (_includeDirs "") + set (_systemIncludeDirs "") + # default include dirs + if (CMAKE_INCLUDE_CURRENT_DIR) + list (APPEND _includeDirs "${CMAKE_CURRENT_BINARY_DIR}") + list (APPEND _includeDirs "${CMAKE_CURRENT_SOURCE_DIR}") + endif() + set (_targetFlags "") + cotire_get_target_compile_flags("${_config}" "${_language}" "${_target}" _targetFlags) + # parse additional include directories from target compile flags + if (CMAKE_INCLUDE_FLAG_${_language}) + string (STRIP "${CMAKE_INCLUDE_FLAG_${_language}}" _includeFlag) + string (REGEX REPLACE "^[-/]+" "" _includeFlag "${_includeFlag}") + if (_includeFlag) + set (_dirs "") + cotire_filter_compile_flags("${_language}" "${_includeFlag}" _dirs _ignore ${_targetFlags}) + if (_dirs) + list (APPEND _includeDirs ${_dirs}) + endif() + endif() + endif() + # parse additional system include directories from target compile flags + if (CMAKE_INCLUDE_SYSTEM_FLAG_${_language}) + string (STRIP "${CMAKE_INCLUDE_SYSTEM_FLAG_${_language}}" _includeFlag) + string (REGEX REPLACE "^[-/]+" "" _includeFlag "${_includeFlag}") + if (_includeFlag) + set (_dirs "") + cotire_filter_compile_flags("${_language}" "${_includeFlag}" _dirs _ignore ${_targetFlags}) + if (_dirs) + list (APPEND _systemIncludeDirs ${_dirs}) + endif() + endif() + endif() + # target include directories + get_directory_property(_dirs DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" INCLUDE_DIRECTORIES) + if (_target) + get_target_property(_targetDirs ${_target} INCLUDE_DIRECTORIES) + if (_targetDirs) + list (APPEND _dirs ${_targetDirs}) + endif() + get_target_property(_targetDirs ${_target} INTERFACE_SYSTEM_INCLUDE_DIRECTORIES) + if (_targetDirs) + list (APPEND _systemIncludeDirs ${_targetDirs}) + endif() + endif() + # interface include directories from linked library targets + if (_target) + set (_linkedTargets "") + cotire_get_target_usage_requirements(${_target} ${_config} _linkedTargets) + foreach (_linkedTarget ${_linkedTargets}) + get_target_property(_linkedTargetType ${_linkedTarget} TYPE) + if (CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE AND NOT CMAKE_VERSION VERSION_LESS "3.4.0" AND + _linkedTargetType MATCHES "(STATIC|SHARED|MODULE|OBJECT)_LIBRARY") + # CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE refers to CMAKE_CURRENT_BINARY_DIR and CMAKE_CURRENT_SOURCE_DIR + # at the time, when the target was created. These correspond to the target properties BINARY_DIR and SOURCE_DIR + # which are only available with CMake 3.4 or later. + get_target_property(_targetDirs ${_linkedTarget} BINARY_DIR) + if (_targetDirs) + list (APPEND _dirs ${_targetDirs}) + endif() + get_target_property(_targetDirs ${_linkedTarget} SOURCE_DIR) + if (_targetDirs) + list (APPEND _dirs ${_targetDirs}) + endif() + endif() + get_target_property(_targetDirs ${_linkedTarget} INTERFACE_INCLUDE_DIRECTORIES) + if (_targetDirs) + list (APPEND _dirs ${_targetDirs}) + endif() + get_target_property(_targetDirs ${_linkedTarget} INTERFACE_SYSTEM_INCLUDE_DIRECTORIES) + if (_targetDirs) + list (APPEND _systemIncludeDirs ${_targetDirs}) + endif() + endforeach() + endif() + if (dirs) + list (REMOVE_DUPLICATES _dirs) + endif() + list (LENGTH _includeDirs _projectInsertIndex) + foreach (_dir ${_dirs}) + if (CMAKE_INCLUDE_DIRECTORIES_PROJECT_BEFORE) + cotire_check_is_path_relative_to("${_dir}" _isRelative "${CMAKE_SOURCE_DIR}" "${CMAKE_BINARY_DIR}") + if (_isRelative) + list (LENGTH _includeDirs _len) + if (_len EQUAL _projectInsertIndex) + list (APPEND _includeDirs "${_dir}") + else() + list (INSERT _includeDirs _projectInsertIndex "${_dir}") + endif() + math (EXPR _projectInsertIndex "${_projectInsertIndex} + 1") + else() + list (APPEND _includeDirs "${_dir}") + endif() + else() + list (APPEND _includeDirs "${_dir}") + endif() + endforeach() + list (REMOVE_DUPLICATES _includeDirs) + list (REMOVE_DUPLICATES _systemIncludeDirs) + if (CMAKE_${_language}_IMPLICIT_INCLUDE_DIRECTORIES) + list (REMOVE_ITEM _includeDirs ${CMAKE_${_language}_IMPLICIT_INCLUDE_DIRECTORIES}) + endif() + if (WIN32 AND NOT MINGW) + # convert Windows paths in include directories to CMake paths + if (_includeDirs) + set (_paths "") + foreach (_dir ${_includeDirs}) + file (TO_CMAKE_PATH "${_dir}" _path) + list (APPEND _paths "${_path}") + endforeach() + set (_includeDirs ${_paths}) + endif() + if (_systemIncludeDirs) + set (_paths "") + foreach (_dir ${_systemIncludeDirs}) + file (TO_CMAKE_PATH "${_dir}" _path) + list (APPEND _paths "${_path}") + endforeach() + set (_systemIncludeDirs ${_paths}) + endif() + endif() + if (COTIRE_DEBUG AND _includeDirs) + message (STATUS "Target ${_target} include dirs: ${_includeDirs}") + endif() + set (${_includeDirsVar} ${_includeDirs} PARENT_SCOPE) + if (COTIRE_DEBUG AND _systemIncludeDirs) + message (STATUS "Target ${_target} system include dirs: ${_systemIncludeDirs}") + endif() + set (${_systemIncludeDirsVar} ${_systemIncludeDirs} PARENT_SCOPE) +endfunction() + +function (cotire_get_target_export_symbol _target _exportSymbolVar) + set (_exportSymbol "") + get_target_property(_targetType ${_target} TYPE) + get_target_property(_enableExports ${_target} ENABLE_EXPORTS) + if (_targetType MATCHES "(SHARED|MODULE)_LIBRARY" OR + (_targetType STREQUAL "EXECUTABLE" AND _enableExports)) + get_target_property(_exportSymbol ${_target} DEFINE_SYMBOL) + if (NOT _exportSymbol) + set (_exportSymbol "${_target}_EXPORTS") + endif() + string (MAKE_C_IDENTIFIER "${_exportSymbol}" _exportSymbol) + endif() + set (${_exportSymbolVar} ${_exportSymbol} PARENT_SCOPE) +endfunction() + +function (cotire_get_target_compile_definitions _config _language _target _definitionsVar) + string (TOUPPER "${_config}" _upperConfig) + set (_configDefinitions "") + # CMAKE_INTDIR for multi-configuration build systems + if (NOT "${CMAKE_CFG_INTDIR}" STREQUAL ".") + list (APPEND _configDefinitions "CMAKE_INTDIR=\"${_config}\"") + endif() + # target export define symbol + cotire_get_target_export_symbol("${_target}" _defineSymbol) + if (_defineSymbol) + list (APPEND _configDefinitions "${_defineSymbol}") + endif() + # directory compile definitions + get_directory_property(_definitions DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" COMPILE_DEFINITIONS) + if (_definitions) + list (APPEND _configDefinitions ${_definitions}) + endif() + get_directory_property(_definitions DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" COMPILE_DEFINITIONS_${_upperConfig}) + if (_definitions) + list (APPEND _configDefinitions ${_definitions}) + endif() + # target compile definitions + get_target_property(_definitions ${_target} COMPILE_DEFINITIONS) + if (_definitions) + list (APPEND _configDefinitions ${_definitions}) + endif() + get_target_property(_definitions ${_target} COMPILE_DEFINITIONS_${_upperConfig}) + if (_definitions) + list (APPEND _configDefinitions ${_definitions}) + endif() + # interface compile definitions from linked library targets + set (_linkedTargets "") + cotire_get_target_usage_requirements(${_target} ${_config} _linkedTargets) + foreach (_linkedTarget ${_linkedTargets}) + get_target_property(_definitions ${_linkedTarget} INTERFACE_COMPILE_DEFINITIONS) + if (_definitions) + list (APPEND _configDefinitions ${_definitions}) + endif() + endforeach() + # parse additional compile definitions from target compile flags + # and don't look at directory compile definitions, which we already handled + set (_targetFlags "") + cotire_get_target_compile_flags("${_config}" "${_language}" "${_target}" _targetFlags) + cotire_filter_compile_flags("${_language}" "D" _definitions _ignore ${_targetFlags}) + if (_definitions) + list (APPEND _configDefinitions ${_definitions}) + endif() + list (REMOVE_DUPLICATES _configDefinitions) + if (COTIRE_DEBUG AND _configDefinitions) + message (STATUS "Target ${_target} compile definitions: ${_configDefinitions}") + endif() + set (${_definitionsVar} ${_configDefinitions} PARENT_SCOPE) +endfunction() + +function (cotire_get_target_compiler_flags _config _language _target _compilerFlagsVar) + # parse target compile flags omitting compile definitions and include directives + set (_targetFlags "") + cotire_get_target_compile_flags("${_config}" "${_language}" "${_target}" _targetFlags) + set (_flagFilter "D") + if (CMAKE_INCLUDE_FLAG_${_language}) + string (STRIP "${CMAKE_INCLUDE_FLAG_${_language}}" _includeFlag) + string (REGEX REPLACE "^[-/]+" "" _includeFlag "${_includeFlag}") + if (_includeFlag) + set (_flagFilter "${_flagFilter}|${_includeFlag}") + endif() + endif() + if (CMAKE_INCLUDE_SYSTEM_FLAG_${_language}) + string (STRIP "${CMAKE_INCLUDE_SYSTEM_FLAG_${_language}}" _includeFlag) + string (REGEX REPLACE "^[-/]+" "" _includeFlag "${_includeFlag}") + if (_includeFlag) + set (_flagFilter "${_flagFilter}|${_includeFlag}") + endif() + endif() + set (_compilerFlags "") + cotire_filter_compile_flags("${_language}" "${_flagFilter}" _ignore _compilerFlags ${_targetFlags}) + if (COTIRE_DEBUG AND _compilerFlags) + message (STATUS "Target ${_target} compiler flags: ${_compilerFlags}") + endif() + set (${_compilerFlagsVar} ${_compilerFlags} PARENT_SCOPE) +endfunction() + +function (cotire_add_sys_root_paths _pathsVar) + if (APPLE) + if (CMAKE_OSX_SYSROOT AND CMAKE_${_language}_HAS_ISYSROOT) + foreach (_path IN LISTS ${_pathsVar}) + if (IS_ABSOLUTE "${_path}") + get_filename_component(_path "${CMAKE_OSX_SYSROOT}/${_path}" ABSOLUTE) + if (EXISTS "${_path}") + list (APPEND ${_pathsVar} "${_path}") + endif() + endif() + endforeach() + endif() + endif() + set (${_pathsVar} ${${_pathsVar}} PARENT_SCOPE) +endfunction() + +function (cotire_get_source_extra_properties _sourceFile _pattern _resultVar) + set (_extraProperties ${ARGN}) + set (_result "") + if (_extraProperties) + list (FIND _extraProperties "${_sourceFile}" _index) + if (_index GREATER -1) + math (EXPR _index "${_index} + 1") + list (LENGTH _extraProperties _len) + math (EXPR _len "${_len} - 1") + foreach (_index RANGE ${_index} ${_len}) + list (GET _extraProperties ${_index} _value) + if (_value MATCHES "${_pattern}") + list (APPEND _result "${_value}") + else() + break() + endif() + endforeach() + endif() + endif() + set (${_resultVar} ${_result} PARENT_SCOPE) +endfunction() + +function (cotire_get_source_compile_definitions _config _language _sourceFile _definitionsVar) + set (_compileDefinitions "") + if (NOT CMAKE_SCRIPT_MODE_FILE) + string (TOUPPER "${_config}" _upperConfig) + get_source_file_property(_definitions "${_sourceFile}" COMPILE_DEFINITIONS) + if (_definitions) + list (APPEND _compileDefinitions ${_definitions}) + endif() + get_source_file_property(_definitions "${_sourceFile}" COMPILE_DEFINITIONS_${_upperConfig}) + if (_definitions) + list (APPEND _compileDefinitions ${_definitions}) + endif() + endif() + cotire_get_source_extra_properties("${_sourceFile}" "^[a-zA-Z0-9_]+(=.*)?$" _definitions ${ARGN}) + if (_definitions) + list (APPEND _compileDefinitions ${_definitions}) + endif() + if (COTIRE_DEBUG AND _compileDefinitions) + message (STATUS "Source ${_sourceFile} compile definitions: ${_compileDefinitions}") + endif() + set (${_definitionsVar} ${_compileDefinitions} PARENT_SCOPE) +endfunction() + +function (cotire_get_source_files_compile_definitions _config _language _definitionsVar) + set (_configDefinitions "") + foreach (_sourceFile ${ARGN}) + cotire_get_source_compile_definitions("${_config}" "${_language}" "${_sourceFile}" _sourceDefinitions) + if (_sourceDefinitions) + list (APPEND _configDefinitions "${_sourceFile}" ${_sourceDefinitions} "-") + endif() + endforeach() + set (${_definitionsVar} ${_configDefinitions} PARENT_SCOPE) +endfunction() + +function (cotire_get_source_undefs _sourceFile _property _sourceUndefsVar) + set (_sourceUndefs "") + if (NOT CMAKE_SCRIPT_MODE_FILE) + get_source_file_property(_undefs "${_sourceFile}" ${_property}) + if (_undefs) + list (APPEND _sourceUndefs ${_undefs}) + endif() + endif() + cotire_get_source_extra_properties("${_sourceFile}" "^[a-zA-Z0-9_]+$" _undefs ${ARGN}) + if (_undefs) + list (APPEND _sourceUndefs ${_undefs}) + endif() + if (COTIRE_DEBUG AND _sourceUndefs) + message (STATUS "Source ${_sourceFile} ${_property} undefs: ${_sourceUndefs}") + endif() + set (${_sourceUndefsVar} ${_sourceUndefs} PARENT_SCOPE) +endfunction() + +function (cotire_get_source_files_undefs _property _sourceUndefsVar) + set (_sourceUndefs "") + foreach (_sourceFile ${ARGN}) + cotire_get_source_undefs("${_sourceFile}" ${_property} _undefs) + if (_undefs) + list (APPEND _sourceUndefs "${_sourceFile}" ${_undefs} "-") + endif() + endforeach() + set (${_sourceUndefsVar} ${_sourceUndefs} PARENT_SCOPE) +endfunction() + +macro (cotire_set_cmd_to_prologue _cmdVar) + set (${_cmdVar} "${CMAKE_COMMAND}") + if (COTIRE_DEBUG) + list (APPEND ${_cmdVar} "--warn-uninitialized") + endif() + list (APPEND ${_cmdVar} "-DCOTIRE_BUILD_TYPE:STRING=$") + if (XCODE) + list (APPEND ${_cmdVar} "-DXCODE:BOOL=TRUE") + endif() + if (COTIRE_VERBOSE) + list (APPEND ${_cmdVar} "-DCOTIRE_VERBOSE:BOOL=ON") + elseif("${CMAKE_GENERATOR}" MATCHES "Makefiles") + list (APPEND ${_cmdVar} "-DCOTIRE_VERBOSE:BOOL=$(VERBOSE)") + endif() +endmacro() + +function (cotire_init_compile_cmd _cmdVar _language _compilerLauncher _compilerExe _compilerArg1) + if (NOT _compilerLauncher) + set (_compilerLauncher ${CMAKE_${_language}_COMPILER_LAUNCHER}) + endif() + if (NOT _compilerExe) + set (_compilerExe "${CMAKE_${_language}_COMPILER}") + endif() + if (NOT _compilerArg1) + set (_compilerArg1 ${CMAKE_${_language}_COMPILER_ARG1}) + endif() + string (STRIP "${_compilerArg1}" _compilerArg1) + if ("${CMAKE_GENERATOR}" MATCHES "Make|Ninja") + # compiler launcher is only supported for Makefile and Ninja + set (${_cmdVar} ${_compilerLauncher} "${_compilerExe}" ${_compilerArg1} PARENT_SCOPE) + else() + set (${_cmdVar} "${_compilerExe}" ${_compilerArg1} PARENT_SCOPE) + endif() +endfunction() + +macro (cotire_add_definitions_to_cmd _cmdVar _language) + foreach (_definition ${ARGN}) + if (WIN32 AND CMAKE_${_language}_COMPILER_ID MATCHES "MSVC|Intel") + list (APPEND ${_cmdVar} "/D${_definition}") + else() + list (APPEND ${_cmdVar} "-D${_definition}") + endif() + endforeach() +endmacro() + +function (cotire_add_includes_to_cmd _cmdVar _language _includesVar _systemIncludesVar) + set (_includeDirs ${${_includesVar}} ${${_systemIncludesVar}}) + if (_includeDirs) + list (REMOVE_DUPLICATES _includeDirs) + foreach (_include ${_includeDirs}) + if (WIN32 AND CMAKE_${_language}_COMPILER_ID MATCHES "MSVC|Intel") + file (TO_NATIVE_PATH "${_include}" _include) + list (APPEND ${_cmdVar} "${CMAKE_INCLUDE_FLAG_${_language}}${CMAKE_INCLUDE_FLAG_SEP_${_language}}${_include}") + else() + set (_index -1) + if ("${CMAKE_INCLUDE_SYSTEM_FLAG_${_language}}" MATCHES ".+") + list (FIND ${_systemIncludesVar} "${_include}" _index) + endif() + if (_index GREATER -1) + list (APPEND ${_cmdVar} "${CMAKE_INCLUDE_SYSTEM_FLAG_${_language}}${CMAKE_INCLUDE_FLAG_SEP_${_language}}${_include}") + else() + list (APPEND ${_cmdVar} "${CMAKE_INCLUDE_FLAG_${_language}}${CMAKE_INCLUDE_FLAG_SEP_${_language}}${_include}") + endif() + endif() + endforeach() + endif() + set (${_cmdVar} ${${_cmdVar}} PARENT_SCOPE) +endfunction() + +function (cotire_add_frameworks_to_cmd _cmdVar _language _includesVar _systemIncludesVar) + if (APPLE) + set (_frameworkDirs "") + foreach (_include ${${_includesVar}}) + if (IS_ABSOLUTE "${_include}" AND _include MATCHES "\\.framework$") + get_filename_component(_frameworkDir "${_include}" DIRECTORY) + list (APPEND _frameworkDirs "${_frameworkDir}") + endif() + endforeach() + set (_systemFrameworkDirs "") + foreach (_include ${${_systemIncludesVar}}) + if (IS_ABSOLUTE "${_include}" AND _include MATCHES "\\.framework$") + get_filename_component(_frameworkDir "${_include}" DIRECTORY) + list (APPEND _systemFrameworkDirs "${_frameworkDir}") + endif() + endforeach() + if (_systemFrameworkDirs) + list (APPEND _frameworkDirs ${_systemFrameworkDirs}) + endif() + if (_frameworkDirs) + list (REMOVE_DUPLICATES _frameworkDirs) + foreach (_frameworkDir ${_frameworkDirs}) + set (_index -1) + if ("${CMAKE_${_language}_SYSTEM_FRAMEWORK_SEARCH_FLAG}" MATCHES ".+") + list (FIND _systemFrameworkDirs "${_frameworkDir}" _index) + endif() + if (_index GREATER -1) + list (APPEND ${_cmdVar} "${CMAKE_${_language}_SYSTEM_FRAMEWORK_SEARCH_FLAG}${_frameworkDir}") + else() + list (APPEND ${_cmdVar} "${CMAKE_${_language}_FRAMEWORK_SEARCH_FLAG}${_frameworkDir}") + endif() + endforeach() + endif() + endif() + set (${_cmdVar} ${${_cmdVar}} PARENT_SCOPE) +endfunction() + +macro (cotire_add_compile_flags_to_cmd _cmdVar) + foreach (_flag ${ARGN}) + list (APPEND ${_cmdVar} "${_flag}") + endforeach() +endmacro() + +function (cotire_check_file_up_to_date _fileIsUpToDateVar _file) + if (EXISTS "${_file}") + set (_triggerFile "") + foreach (_dependencyFile ${ARGN}) + if (EXISTS "${_dependencyFile}") + # IS_NEWER_THAN returns TRUE if both files have the same timestamp + # thus we do the comparison in both directions to exclude ties + if ("${_dependencyFile}" IS_NEWER_THAN "${_file}" AND + NOT "${_file}" IS_NEWER_THAN "${_dependencyFile}") + set (_triggerFile "${_dependencyFile}") + break() + endif() + endif() + endforeach() + if (_triggerFile) + if (COTIRE_VERBOSE) + get_filename_component(_fileName "${_file}" NAME) + message (STATUS "${_fileName} update triggered by ${_triggerFile} change.") + endif() + set (${_fileIsUpToDateVar} FALSE PARENT_SCOPE) + else() + if (COTIRE_VERBOSE) + get_filename_component(_fileName "${_file}" NAME) + message (STATUS "${_fileName} is up-to-date.") + endif() + set (${_fileIsUpToDateVar} TRUE PARENT_SCOPE) + endif() + else() + if (COTIRE_VERBOSE) + get_filename_component(_fileName "${_file}" NAME) + message (STATUS "${_fileName} does not exist yet.") + endif() + set (${_fileIsUpToDateVar} FALSE PARENT_SCOPE) + endif() +endfunction() + +macro (cotire_find_closest_relative_path _headerFile _includeDirs _relPathVar) + set (${_relPathVar} "") + foreach (_includeDir ${_includeDirs}) + if (IS_DIRECTORY "${_includeDir}") + file (RELATIVE_PATH _relPath "${_includeDir}" "${_headerFile}") + if (NOT IS_ABSOLUTE "${_relPath}" AND NOT "${_relPath}" MATCHES "^\\.\\.") + string (LENGTH "${${_relPathVar}}" _closestLen) + string (LENGTH "${_relPath}" _relLen) + if (_closestLen EQUAL 0 OR _relLen LESS _closestLen) + set (${_relPathVar} "${_relPath}") + endif() + endif() + elseif ("${_includeDir}" STREQUAL "${_headerFile}") + # if path matches exactly, return short non-empty string + set (${_relPathVar} "1") + break() + endif() + endforeach() +endmacro() + +macro (cotire_check_header_file_location _headerFile _insideIncludeDirs _outsideIncludeDirs _headerIsInside) + # check header path against ignored and honored include directories + cotire_find_closest_relative_path("${_headerFile}" "${_insideIncludeDirs}" _insideRelPath) + if (_insideRelPath) + # header is inside, but could be become outside if there is a shorter outside match + cotire_find_closest_relative_path("${_headerFile}" "${_outsideIncludeDirs}" _outsideRelPath) + if (_outsideRelPath) + string (LENGTH "${_insideRelPath}" _insideRelPathLen) + string (LENGTH "${_outsideRelPath}" _outsideRelPathLen) + if (_outsideRelPathLen LESS _insideRelPathLen) + set (${_headerIsInside} FALSE) + else() + set (${_headerIsInside} TRUE) + endif() + else() + set (${_headerIsInside} TRUE) + endif() + else() + # header is outside + set (${_headerIsInside} FALSE) + endif() +endmacro() + +macro (cotire_check_ignore_header_file_path _headerFile _headerIsIgnoredVar) + if (NOT EXISTS "${_headerFile}") + set (${_headerIsIgnoredVar} TRUE) + elseif (IS_DIRECTORY "${_headerFile}") + set (${_headerIsIgnoredVar} TRUE) + elseif ("${_headerFile}" MATCHES "\\.\\.|[_-]fixed" AND "${_headerFile}" MATCHES "\\.h$") + # heuristic: ignore C headers with embedded parent directory references or "-fixed" or "_fixed" in path + # these often stem from using GCC #include_next tricks, which may break the precompiled header compilation + # with the error message "error: no include path in which to search for header.h" + set (${_headerIsIgnoredVar} TRUE) + else() + set (${_headerIsIgnoredVar} FALSE) + endif() +endmacro() + +macro (cotire_check_ignore_header_file_ext _headerFile _ignoreExtensionsVar _headerIsIgnoredVar) + # check header file extension + cotire_get_source_file_extension("${_headerFile}" _headerFileExt) + set (${_headerIsIgnoredVar} FALSE) + if (_headerFileExt) + list (FIND ${_ignoreExtensionsVar} "${_headerFileExt}" _index) + if (_index GREATER -1) + set (${_headerIsIgnoredVar} TRUE) + endif() + endif() +endmacro() + +macro (cotire_parse_line _line _headerFileVar _headerDepthVar) + if (MSVC) + # cl.exe /showIncludes output looks different depending on the language pack used, e.g.: + # English: "Note: including file: C:\directory\file" + # German: "Hinweis: Einlesen der Datei: C:\directory\file" + # We use a very general regular expression, relying on the presence of the : characters + if (_line MATCHES "( +)([a-zA-Z]:[^:]+)$") + # Visual Studio compiler output + string (LENGTH "${CMAKE_MATCH_1}" ${_headerDepthVar}) + get_filename_component(${_headerFileVar} "${CMAKE_MATCH_2}" ABSOLUTE) + else() + set (${_headerFileVar} "") + set (${_headerDepthVar} 0) + endif() + else() + if (_line MATCHES "^(\\.+) (.*)$") + # GCC like output + string (LENGTH "${CMAKE_MATCH_1}" ${_headerDepthVar}) + if (IS_ABSOLUTE "${CMAKE_MATCH_2}") + set (${_headerFileVar} "${CMAKE_MATCH_2}") + else() + get_filename_component(${_headerFileVar} "${CMAKE_MATCH_2}" REALPATH) + endif() + else() + set (${_headerFileVar} "") + set (${_headerDepthVar} 0) + endif() + endif() +endmacro() + +function (cotire_parse_includes _language _scanOutput _ignoredIncludeDirs _honoredIncludeDirs _ignoredExtensions _selectedIncludesVar _unparsedLinesVar) + if (WIN32) + # prevent CMake macro invocation errors due to backslash characters in Windows paths + string (REPLACE "\\" "/" _scanOutput "${_scanOutput}") + endif() + # canonize slashes + string (REPLACE "//" "/" _scanOutput "${_scanOutput}") + # prevent semicolon from being interpreted as a line separator + string (REPLACE ";" "\\;" _scanOutput "${_scanOutput}") + # then separate lines + string (REGEX REPLACE "\n" ";" _scanOutput "${_scanOutput}") + list (LENGTH _scanOutput _len) + # remove duplicate lines to speed up parsing + list (REMOVE_DUPLICATES _scanOutput) + list (LENGTH _scanOutput _uniqueLen) + if (COTIRE_VERBOSE OR COTIRE_DEBUG) + message (STATUS "Scanning ${_uniqueLen} unique lines of ${_len} for includes") + if (_ignoredExtensions) + message (STATUS "Ignored extensions: ${_ignoredExtensions}") + endif() + if (_ignoredIncludeDirs) + message (STATUS "Ignored paths: ${_ignoredIncludeDirs}") + endif() + if (_honoredIncludeDirs) + message (STATUS "Included paths: ${_honoredIncludeDirs}") + endif() + endif() + set (_sourceFiles ${ARGN}) + set (_selectedIncludes "") + set (_unparsedLines "") + # stack keeps track of inside/outside project status of processed header files + set (_headerIsInsideStack "") + foreach (_line IN LISTS _scanOutput) + if (_line) + cotire_parse_line("${_line}" _headerFile _headerDepth) + if (_headerFile) + cotire_check_header_file_location("${_headerFile}" "${_ignoredIncludeDirs}" "${_honoredIncludeDirs}" _headerIsInside) + if (COTIRE_DEBUG) + message (STATUS "${_headerDepth}: ${_headerFile} ${_headerIsInside}") + endif() + # update stack + list (LENGTH _headerIsInsideStack _stackLen) + if (_headerDepth GREATER _stackLen) + math (EXPR _stackLen "${_stackLen} + 1") + foreach (_index RANGE ${_stackLen} ${_headerDepth}) + list (APPEND _headerIsInsideStack ${_headerIsInside}) + endforeach() + else() + foreach (_index RANGE ${_headerDepth} ${_stackLen}) + list (REMOVE_AT _headerIsInsideStack -1) + endforeach() + list (APPEND _headerIsInsideStack ${_headerIsInside}) + endif() + if (COTIRE_DEBUG) + message (STATUS "${_headerIsInsideStack}") + endif() + # header is a candidate if it is outside project + if (NOT _headerIsInside) + # get parent header file's inside/outside status + if (_headerDepth GREATER 1) + math (EXPR _index "${_headerDepth} - 2") + list (GET _headerIsInsideStack ${_index} _parentHeaderIsInside) + else() + set (_parentHeaderIsInside TRUE) + endif() + # select header file if parent header file is inside project + # (e.g., a project header file that includes a standard header file) + if (_parentHeaderIsInside) + cotire_check_ignore_header_file_path("${_headerFile}" _headerIsIgnored) + if (NOT _headerIsIgnored) + cotire_check_ignore_header_file_ext("${_headerFile}" _ignoredExtensions _headerIsIgnored) + if (NOT _headerIsIgnored) + list (APPEND _selectedIncludes "${_headerFile}") + else() + # fix header's inside status on stack, it is ignored by extension now + list (REMOVE_AT _headerIsInsideStack -1) + list (APPEND _headerIsInsideStack TRUE) + endif() + endif() + if (COTIRE_DEBUG) + message (STATUS "${_headerFile} ${_ignoredExtensions} ${_headerIsIgnored}") + endif() + endif() + endif() + else() + if (MSVC) + # for cl.exe do not keep unparsed lines which solely consist of a source file name + string (FIND "${_sourceFiles}" "${_line}" _index) + if (_index LESS 0) + list (APPEND _unparsedLines "${_line}") + endif() + else() + list (APPEND _unparsedLines "${_line}") + endif() + endif() + endif() + endforeach() + list (REMOVE_DUPLICATES _selectedIncludes) + set (${_selectedIncludesVar} ${_selectedIncludes} PARENT_SCOPE) + set (${_unparsedLinesVar} ${_unparsedLines} PARENT_SCOPE) +endfunction() + +function (cotire_scan_includes _includesVar) + set(_options "") + set(_oneValueArgs COMPILER_ID COMPILER_EXECUTABLE COMPILER_ARG1 COMPILER_VERSION LANGUAGE UNPARSED_LINES SCAN_RESULT) + set(_multiValueArgs COMPILE_DEFINITIONS COMPILE_FLAGS INCLUDE_DIRECTORIES SYSTEM_INCLUDE_DIRECTORIES + IGNORE_PATH INCLUDE_PATH IGNORE_EXTENSIONS INCLUDE_PRIORITY_PATH COMPILER_LAUNCHER) + cmake_parse_arguments(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN}) + set (_sourceFiles ${_option_UNPARSED_ARGUMENTS}) + if (NOT _option_LANGUAGE) + set (_option_LANGUAGE "CXX") + endif() + if (NOT _option_COMPILER_ID) + set (_option_COMPILER_ID "${CMAKE_${_option_LANGUAGE}_ID}") + endif() + if (NOT _option_COMPILER_VERSION) + set (_option_COMPILER_VERSION "${CMAKE_${_option_LANGUAGE}_COMPILER_VERSION}") + endif() + cotire_init_compile_cmd(_cmd "${_option_LANGUAGE}" "${_option_COMPILER_LAUNCHER}" "${_option_COMPILER_EXECUTABLE}" "${_option_COMPILER_ARG1}") + cotire_add_definitions_to_cmd(_cmd "${_option_LANGUAGE}" ${_option_COMPILE_DEFINITIONS}) + cotire_add_compile_flags_to_cmd(_cmd ${_option_COMPILE_FLAGS}) + cotire_add_includes_to_cmd(_cmd "${_option_LANGUAGE}" _option_INCLUDE_DIRECTORIES _option_SYSTEM_INCLUDE_DIRECTORIES) + cotire_add_frameworks_to_cmd(_cmd "${_option_LANGUAGE}" _option_INCLUDE_DIRECTORIES _option_SYSTEM_INCLUDE_DIRECTORIES) + cotire_add_makedep_flags("${_option_LANGUAGE}" "${_option_COMPILER_ID}" "${_option_COMPILER_VERSION}" _cmd) + # only consider existing source files for scanning + set (_existingSourceFiles "") + foreach (_sourceFile ${_sourceFiles}) + if (EXISTS "${_sourceFile}") + list (APPEND _existingSourceFiles "${_sourceFile}") + endif() + endforeach() + if (NOT _existingSourceFiles) + set (${_includesVar} "" PARENT_SCOPE) + return() + endif() + list (APPEND _cmd ${_existingSourceFiles}) + if (COTIRE_VERBOSE) + message (STATUS "execute_process: ${_cmd}") + endif() + if (_option_COMPILER_ID MATCHES "MSVC") + # cl.exe messes with the output streams unless the environment variable VS_UNICODE_OUTPUT is cleared + unset (ENV{VS_UNICODE_OUTPUT}) + endif() + execute_process( + COMMAND ${_cmd} + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + RESULT_VARIABLE _result + OUTPUT_QUIET + ERROR_VARIABLE _output) + if (_result) + message (STATUS "Result ${_result} scanning includes of ${_existingSourceFiles}.") + endif() + cotire_parse_includes( + "${_option_LANGUAGE}" "${_output}" + "${_option_IGNORE_PATH}" "${_option_INCLUDE_PATH}" + "${_option_IGNORE_EXTENSIONS}" + _includes _unparsedLines + ${_sourceFiles}) + if (_option_INCLUDE_PRIORITY_PATH) + set (_sortedIncludes "") + foreach (_priorityPath ${_option_INCLUDE_PRIORITY_PATH}) + foreach (_include ${_includes}) + string (FIND ${_include} ${_priorityPath} _position) + if (_position GREATER -1) + list (APPEND _sortedIncludes ${_include}) + endif() + endforeach() + endforeach() + if (_sortedIncludes) + list (INSERT _includes 0 ${_sortedIncludes}) + list (REMOVE_DUPLICATES _includes) + endif() + endif() + set (${_includesVar} ${_includes} PARENT_SCOPE) + if (_option_UNPARSED_LINES) + set (${_option_UNPARSED_LINES} ${_unparsedLines} PARENT_SCOPE) + endif() + if (_option_SCAN_RESULT) + set (${_option_SCAN_RESULT} ${_result} PARENT_SCOPE) + endif() +endfunction() + +macro (cotire_append_undefs _contentsVar) + set (_undefs ${ARGN}) + if (_undefs) + list (REMOVE_DUPLICATES _undefs) + foreach (_definition ${_undefs}) + list (APPEND ${_contentsVar} "#undef ${_definition}") + endforeach() + endif() +endmacro() + +macro (cotire_comment_str _language _commentText _commentVar) + if ("${_language}" STREQUAL "CMAKE") + set (${_commentVar} "# ${_commentText}") + else() + set (${_commentVar} "/* ${_commentText} */") + endif() +endmacro() + +function (cotire_write_file _language _file _contents _force) + get_filename_component(_moduleName "${COTIRE_CMAKE_MODULE_FILE}" NAME) + cotire_comment_str("${_language}" "${_moduleName} ${COTIRE_CMAKE_MODULE_VERSION} generated file" _header1) + cotire_comment_str("${_language}" "${_file}" _header2) + set (_contents "${_header1}\n${_header2}\n${_contents}") + if (COTIRE_DEBUG) + message (STATUS "${_contents}") + endif() + if (_force OR NOT EXISTS "${_file}") + file (WRITE "${_file}" "${_contents}") + else() + file (READ "${_file}" _oldContents) + if (NOT "${_oldContents}" STREQUAL "${_contents}") + file (WRITE "${_file}" "${_contents}") + else() + if (COTIRE_DEBUG) + message (STATUS "${_file} unchanged") + endif() + endif() + endif() +endfunction() + +function (cotire_generate_unity_source _unityFile) + set(_options "") + set(_oneValueArgs LANGUAGE) + set(_multiValueArgs + DEPENDS SOURCES_COMPILE_DEFINITIONS + PRE_UNDEFS SOURCES_PRE_UNDEFS POST_UNDEFS SOURCES_POST_UNDEFS PROLOGUE EPILOGUE) + cmake_parse_arguments(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN}) + if (_option_DEPENDS) + cotire_check_file_up_to_date(_unityFileIsUpToDate "${_unityFile}" ${_option_DEPENDS}) + if (_unityFileIsUpToDate) + return() + endif() + endif() + set (_sourceFiles ${_option_UNPARSED_ARGUMENTS}) + if (NOT _option_PRE_UNDEFS) + set (_option_PRE_UNDEFS "") + endif() + if (NOT _option_SOURCES_PRE_UNDEFS) + set (_option_SOURCES_PRE_UNDEFS "") + endif() + if (NOT _option_POST_UNDEFS) + set (_option_POST_UNDEFS "") + endif() + if (NOT _option_SOURCES_POST_UNDEFS) + set (_option_SOURCES_POST_UNDEFS "") + endif() + set (_contents "") + if (_option_PROLOGUE) + list (APPEND _contents ${_option_PROLOGUE}) + endif() + if (_option_LANGUAGE AND _sourceFiles) + if ("${_option_LANGUAGE}" STREQUAL "CXX") + list (APPEND _contents "#ifdef __cplusplus") + elseif ("${_option_LANGUAGE}" STREQUAL "C") + list (APPEND _contents "#ifndef __cplusplus") + endif() + endif() + set (_compileUndefinitions "") + foreach (_sourceFile ${_sourceFiles}) + cotire_get_source_compile_definitions( + "${_option_CONFIGURATION}" "${_option_LANGUAGE}" "${_sourceFile}" _compileDefinitions + ${_option_SOURCES_COMPILE_DEFINITIONS}) + cotire_get_source_undefs("${_sourceFile}" COTIRE_UNITY_SOURCE_PRE_UNDEFS _sourcePreUndefs ${_option_SOURCES_PRE_UNDEFS}) + cotire_get_source_undefs("${_sourceFile}" COTIRE_UNITY_SOURCE_POST_UNDEFS _sourcePostUndefs ${_option_SOURCES_POST_UNDEFS}) + if (_option_PRE_UNDEFS) + list (APPEND _compileUndefinitions ${_option_PRE_UNDEFS}) + endif() + if (_sourcePreUndefs) + list (APPEND _compileUndefinitions ${_sourcePreUndefs}) + endif() + if (_compileUndefinitions) + cotire_append_undefs(_contents ${_compileUndefinitions}) + set (_compileUndefinitions "") + endif() + if (_sourcePostUndefs) + list (APPEND _compileUndefinitions ${_sourcePostUndefs}) + endif() + if (_option_POST_UNDEFS) + list (APPEND _compileUndefinitions ${_option_POST_UNDEFS}) + endif() + foreach (_definition ${_compileDefinitions}) + if (_definition MATCHES "^([a-zA-Z0-9_]+)=(.+)$") + list (APPEND _contents "#define ${CMAKE_MATCH_1} ${CMAKE_MATCH_2}") + list (INSERT _compileUndefinitions 0 "${CMAKE_MATCH_1}") + else() + list (APPEND _contents "#define ${_definition}") + list (INSERT _compileUndefinitions 0 "${_definition}") + endif() + endforeach() + # use absolute path as source file location + get_filename_component(_sourceFileLocation "${_sourceFile}" ABSOLUTE) + if (WIN32) + file (TO_NATIVE_PATH "${_sourceFileLocation}" _sourceFileLocation) + endif() + list (APPEND _contents "#include \"${_sourceFileLocation}\"") + endforeach() + if (_compileUndefinitions) + cotire_append_undefs(_contents ${_compileUndefinitions}) + set (_compileUndefinitions "") + endif() + if (_option_LANGUAGE AND _sourceFiles) + list (APPEND _contents "#endif") + endif() + if (_option_EPILOGUE) + list (APPEND _contents ${_option_EPILOGUE}) + endif() + list (APPEND _contents "") + string (REPLACE ";" "\n" _contents "${_contents}") + if (COTIRE_VERBOSE) + message ("${_contents}") + endif() + cotire_write_file("${_option_LANGUAGE}" "${_unityFile}" "${_contents}" TRUE) +endfunction() + +function (cotire_generate_prefix_header _prefixFile) + set(_options "") + set(_oneValueArgs LANGUAGE COMPILER_EXECUTABLE COMPILER_ARG1 COMPILER_ID COMPILER_VERSION) + set(_multiValueArgs DEPENDS COMPILE_DEFINITIONS COMPILE_FLAGS + INCLUDE_DIRECTORIES SYSTEM_INCLUDE_DIRECTORIES IGNORE_PATH INCLUDE_PATH + IGNORE_EXTENSIONS INCLUDE_PRIORITY_PATH COMPILER_LAUNCHER) + cmake_parse_arguments(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN}) + if (NOT _option_COMPILER_ID) + set (_option_COMPILER_ID "${CMAKE_${_option_LANGUAGE}_ID}") + endif() + if (NOT _option_COMPILER_VERSION) + set (_option_COMPILER_VERSION "${CMAKE_${_option_LANGUAGE}_COMPILER_VERSION}") + endif() + if (_option_DEPENDS) + cotire_check_file_up_to_date(_prefixFileIsUpToDate "${_prefixFile}" ${_option_DEPENDS}) + if (_prefixFileIsUpToDate) + # create empty log file + set (_unparsedLinesFile "${_prefixFile}.log") + file (WRITE "${_unparsedLinesFile}" "") + return() + endif() + endif() + set (_prologue "") + set (_epilogue "") + if (_option_COMPILER_ID MATCHES "Clang") + set (_prologue "#pragma clang system_header") + elseif (_option_COMPILER_ID MATCHES "GNU") + set (_prologue "#pragma GCC system_header") + elseif (_option_COMPILER_ID MATCHES "MSVC") + set (_prologue "#pragma warning(push, 0)") + set (_epilogue "#pragma warning(pop)") + elseif (_option_COMPILER_ID MATCHES "Intel") + # Intel compiler requires hdrstop pragma to stop generating PCH file + set (_epilogue "#pragma hdrstop") + endif() + set (_sourceFiles ${_option_UNPARSED_ARGUMENTS}) + cotire_scan_includes(_selectedHeaders ${_sourceFiles} + LANGUAGE "${_option_LANGUAGE}" + COMPILER_LAUNCHER "${_option_COMPILER_LAUNCHER}" + COMPILER_EXECUTABLE "${_option_COMPILER_EXECUTABLE}" + COMPILER_ARG1 "${_option_COMPILER_ARG1}" + COMPILER_ID "${_option_COMPILER_ID}" + COMPILER_VERSION "${_option_COMPILER_VERSION}" + COMPILE_DEFINITIONS ${_option_COMPILE_DEFINITIONS} + COMPILE_FLAGS ${_option_COMPILE_FLAGS} + INCLUDE_DIRECTORIES ${_option_INCLUDE_DIRECTORIES} + SYSTEM_INCLUDE_DIRECTORIES ${_option_SYSTEM_INCLUDE_DIRECTORIES} + IGNORE_PATH ${_option_IGNORE_PATH} + INCLUDE_PATH ${_option_INCLUDE_PATH} + IGNORE_EXTENSIONS ${_option_IGNORE_EXTENSIONS} + INCLUDE_PRIORITY_PATH ${_option_INCLUDE_PRIORITY_PATH} + UNPARSED_LINES _unparsedLines + SCAN_RESULT _scanResult) + cotire_generate_unity_source("${_prefixFile}" + PROLOGUE ${_prologue} EPILOGUE ${_epilogue} LANGUAGE "${_option_LANGUAGE}" ${_selectedHeaders}) + set (_unparsedLinesFile "${_prefixFile}.log") + if (_unparsedLines) + if (COTIRE_VERBOSE OR _scanResult OR NOT _selectedHeaders) + list (LENGTH _unparsedLines _skippedLineCount) + message (STATUS "${_skippedLineCount} line(s) skipped, see ${_unparsedLinesFile}") + endif() + string (REPLACE ";" "\n" _unparsedLines "${_unparsedLines}") + endif() + file (WRITE "${_unparsedLinesFile}" "${_unparsedLines}") +endfunction() + +function (cotire_add_makedep_flags _language _compilerID _compilerVersion _flagsVar) + set (_flags ${${_flagsVar}}) + if (_compilerID MATCHES "MSVC") + # cl.exe options used + # /nologo suppresses display of sign-on banner + # /TC treat all files named on the command line as C source files + # /TP treat all files named on the command line as C++ source files + # /EP preprocess to stdout without #line directives + # /showIncludes list include files + set (_sourceFileTypeC "/TC") + set (_sourceFileTypeCXX "/TP") + if (_flags) + # append to list + list (APPEND _flags /nologo "${_sourceFileType${_language}}" /EP /showIncludes) + else() + # return as a flag string + set (_flags "${_sourceFileType${_language}} /EP /showIncludes") + endif() + elseif (_compilerID MATCHES "GNU") + # GCC options used + # -H print the name of each header file used + # -E invoke preprocessor + # -fdirectives-only do not expand macros, requires GCC >= 4.3 + if (_flags) + # append to list + list (APPEND _flags -H -E) + if (NOT "${_compilerVersion}" VERSION_LESS "4.3.0") + list (APPEND _flags "-fdirectives-only") + endif() + else() + # return as a flag string + set (_flags "-H -E") + if (NOT "${_compilerVersion}" VERSION_LESS "4.3.0") + set (_flags "${_flags} -fdirectives-only") + endif() + endif() + elseif (_compilerID MATCHES "Clang") + # Clang options used + # -H print the name of each header file used + # -E invoke preprocessor + # -fno-color-diagnostics don't prints diagnostics in color + if (_flags) + # append to list + list (APPEND _flags -H -E -fno-color-diagnostics) + else() + # return as a flag string + set (_flags "-H -E -fno-color-diagnostics") + endif() + elseif (_compilerID MATCHES "Intel") + if (WIN32) + # Windows Intel options used + # /nologo do not display compiler version information + # /QH display the include file order + # /EP preprocess to stdout, omitting #line directives + # /TC process all source or unrecognized file types as C source files + # /TP process all source or unrecognized file types as C++ source files + set (_sourceFileTypeC "/TC") + set (_sourceFileTypeCXX "/TP") + if (_flags) + # append to list + list (APPEND _flags /nologo "${_sourceFileType${_language}}" /EP /QH) + else() + # return as a flag string + set (_flags "${_sourceFileType${_language}} /EP /QH") + endif() + else() + # Linux / Mac OS X Intel options used + # -H print the name of each header file used + # -EP preprocess to stdout, omitting #line directives + # -Kc++ process all source or unrecognized file types as C++ source files + if (_flags) + # append to list + if ("${_language}" STREQUAL "CXX") + list (APPEND _flags -Kc++) + endif() + list (APPEND _flags -H -EP) + else() + # return as a flag string + if ("${_language}" STREQUAL "CXX") + set (_flags "-Kc++ ") + endif() + set (_flags "${_flags}-H -EP") + endif() + endif() + else() + message (FATAL_ERROR "cotire: unsupported ${_language} compiler ${_compilerID} version ${_compilerVersion}.") + endif() + set (${_flagsVar} ${_flags} PARENT_SCOPE) +endfunction() + +function (cotire_add_pch_compilation_flags _language _compilerID _compilerVersion _prefixFile _pchFile _hostFile _flagsVar) + set (_flags ${${_flagsVar}}) + if (_compilerID MATCHES "MSVC") + file (TO_NATIVE_PATH "${_prefixFile}" _prefixFileNative) + file (TO_NATIVE_PATH "${_pchFile}" _pchFileNative) + file (TO_NATIVE_PATH "${_hostFile}" _hostFileNative) + # cl.exe options used + # /Yc creates a precompiled header file + # /Fp specifies precompiled header binary file name + # /FI forces inclusion of file + # /TC treat all files named on the command line as C source files + # /TP treat all files named on the command line as C++ source files + # /Zs syntax check only + # /Zm precompiled header memory allocation scaling factor + set (_sourceFileTypeC "/TC") + set (_sourceFileTypeCXX "/TP") + if (_flags) + # append to list + list (APPEND _flags /nologo "${_sourceFileType${_language}}" + "/Yc${_prefixFileNative}" "/Fp${_pchFileNative}" "/FI${_prefixFileNative}" /Zs "${_hostFileNative}") + if (COTIRE_PCH_MEMORY_SCALING_FACTOR) + list (APPEND _flags "/Zm${COTIRE_PCH_MEMORY_SCALING_FACTOR}") + endif() + else() + # return as a flag string + set (_flags "/Yc\"${_prefixFileNative}\" /Fp\"${_pchFileNative}\" /FI\"${_prefixFileNative}\"") + if (COTIRE_PCH_MEMORY_SCALING_FACTOR) + set (_flags "${_flags} /Zm${COTIRE_PCH_MEMORY_SCALING_FACTOR}") + endif() + endif() + elseif (_compilerID MATCHES "GNU|Clang") + # GCC / Clang options used + # -x specify the source language + # -c compile but do not link + # -o place output in file + # note that we cannot use -w to suppress all warnings upon pre-compiling, because turning off a warning may + # alter compile flags as a side effect (e.g., -Wwrite-string implies -fconst-strings) + set (_xLanguage_C "c-header") + set (_xLanguage_CXX "c++-header") + if (_flags) + # append to list + list (APPEND _flags "-x" "${_xLanguage_${_language}}" "-c" "${_prefixFile}" -o "${_pchFile}") + else() + # return as a flag string + set (_flags "-x ${_xLanguage_${_language}} -c \"${_prefixFile}\" -o \"${_pchFile}\"") + endif() + elseif (_compilerID MATCHES "Intel") + if (WIN32) + file (TO_NATIVE_PATH "${_prefixFile}" _prefixFileNative) + file (TO_NATIVE_PATH "${_pchFile}" _pchFileNative) + file (TO_NATIVE_PATH "${_hostFile}" _hostFileNative) + # Windows Intel options used + # /nologo do not display compiler version information + # /Yc create a precompiled header (PCH) file + # /Fp specify a path or file name for precompiled header files + # /FI tells the preprocessor to include a specified file name as the header file + # /TC process all source or unrecognized file types as C source files + # /TP process all source or unrecognized file types as C++ source files + # /Zs syntax check only + # /Wpch-messages enable diagnostics related to pre-compiled headers (requires Intel XE 2013 Update 2) + set (_sourceFileTypeC "/TC") + set (_sourceFileTypeCXX "/TP") + if (_flags) + # append to list + list (APPEND _flags /nologo "${_sourceFileType${_language}}" + "/Yc" "/Fp${_pchFileNative}" "/FI${_prefixFileNative}" /Zs "${_hostFileNative}") + if (NOT "${_compilerVersion}" VERSION_LESS "13.1.0") + list (APPEND _flags "/Wpch-messages") + endif() + else() + # return as a flag string + set (_flags "/Yc /Fp\"${_pchFileNative}\" /FI\"${_prefixFileNative}\"") + if (NOT "${_compilerVersion}" VERSION_LESS "13.1.0") + set (_flags "${_flags} /Wpch-messages") + endif() + endif() + else() + # Linux / Mac OS X Intel options used + # -pch-dir location for precompiled header files + # -pch-create name of the precompiled header (PCH) to create + # -Kc++ process all source or unrecognized file types as C++ source files + # -fsyntax-only check only for correct syntax + # -Wpch-messages enable diagnostics related to pre-compiled headers (requires Intel XE 2013 Update 2) + get_filename_component(_pchDir "${_pchFile}" DIRECTORY) + get_filename_component(_pchName "${_pchFile}" NAME) + set (_xLanguage_C "c-header") + set (_xLanguage_CXX "c++-header") + set (_pchSuppressMessages FALSE) + if ("${CMAKE_${_language}_FLAGS}" MATCHES ".*-Wno-pch-messages.*") + set(_pchSuppressMessages TRUE) + endif() + if (_flags) + # append to list + if ("${_language}" STREQUAL "CXX") + list (APPEND _flags -Kc++) + endif() + list (APPEND _flags "-include" "${_prefixFile}" "-pch-dir" "${_pchDir}" "-pch-create" "${_pchName}" "-fsyntax-only" "${_hostFile}") + if (NOT "${_compilerVersion}" VERSION_LESS "13.1.0") + if (NOT _pchSuppressMessages) + list (APPEND _flags "-Wpch-messages") + endif() + endif() + else() + # return as a flag string + set (_flags "-include \"${_prefixFile}\" -pch-dir \"${_pchDir}\" -pch-create \"${_pchName}\"") + if (NOT "${_compilerVersion}" VERSION_LESS "13.1.0") + if (NOT _pchSuppressMessages) + set (_flags "${_flags} -Wpch-messages") + endif() + endif() + endif() + endif() + else() + message (FATAL_ERROR "cotire: unsupported ${_language} compiler ${_compilerID} version ${_compilerVersion}.") + endif() + set (${_flagsVar} ${_flags} PARENT_SCOPE) +endfunction() + +function (cotire_add_prefix_pch_inclusion_flags _language _compilerID _compilerVersion _prefixFile _pchFile _flagsVar) + set (_flags ${${_flagsVar}}) + if (_compilerID MATCHES "MSVC") + file (TO_NATIVE_PATH "${_prefixFile}" _prefixFileNative) + # cl.exe options used + # /Yu uses a precompiled header file during build + # /Fp specifies precompiled header binary file name + # /FI forces inclusion of file + # /Zm precompiled header memory allocation scaling factor + if (_pchFile) + file (TO_NATIVE_PATH "${_pchFile}" _pchFileNative) + if (_flags) + # append to list + list (APPEND _flags "/Yu${_prefixFileNative}" "/Fp${_pchFileNative}" "/FI${_prefixFileNative}") + if (COTIRE_PCH_MEMORY_SCALING_FACTOR) + list (APPEND _flags "/Zm${COTIRE_PCH_MEMORY_SCALING_FACTOR}") + endif() + else() + # return as a flag string + set (_flags "/Yu\"${_prefixFileNative}\" /Fp\"${_pchFileNative}\" /FI\"${_prefixFileNative}\"") + if (COTIRE_PCH_MEMORY_SCALING_FACTOR) + set (_flags "${_flags} /Zm${COTIRE_PCH_MEMORY_SCALING_FACTOR}") + endif() + endif() + else() + # no precompiled header, force inclusion of prefix header + if (_flags) + # append to list + list (APPEND _flags "/FI${_prefixFileNative}") + else() + # return as a flag string + set (_flags "/FI\"${_prefixFileNative}\"") + endif() + endif() + elseif (_compilerID MATCHES "GNU") + # GCC options used + # -include process include file as the first line of the primary source file + # -Winvalid-pch warns if precompiled header is found but cannot be used + # note: ccache requires the -include flag to be used in order to process precompiled header correctly + if (_flags) + # append to list + list (APPEND _flags "-Winvalid-pch" "-include" "${_prefixFile}") + else() + # return as a flag string + set (_flags "-Winvalid-pch -include \"${_prefixFile}\"") + endif() + elseif (_compilerID MATCHES "Clang") + # Clang options used + # -include process include file as the first line of the primary source file + # -include-pch include precompiled header file + # -Qunused-arguments don't emit warning for unused driver arguments + # note: ccache requires the -include flag to be used in order to process precompiled header correctly + if (_flags) + # append to list + list (APPEND _flags "-Qunused-arguments" "-include" "${_prefixFile}") + else() + # return as a flag string + set (_flags "-Qunused-arguments -include \"${_prefixFile}\"") + endif() + elseif (_compilerID MATCHES "Intel") + if (WIN32) + file (TO_NATIVE_PATH "${_prefixFile}" _prefixFileNative) + # Windows Intel options used + # /Yu use a precompiled header (PCH) file + # /Fp specify a path or file name for precompiled header files + # /FI tells the preprocessor to include a specified file name as the header file + # /Wpch-messages enable diagnostics related to pre-compiled headers (requires Intel XE 2013 Update 2) + if (_pchFile) + file (TO_NATIVE_PATH "${_pchFile}" _pchFileNative) + if (_flags) + # append to list + list (APPEND _flags "/Yu" "/Fp${_pchFileNative}" "/FI${_prefixFileNative}") + if (NOT "${_compilerVersion}" VERSION_LESS "13.1.0") + list (APPEND _flags "/Wpch-messages") + endif() + else() + # return as a flag string + set (_flags "/Yu /Fp\"${_pchFileNative}\" /FI\"${_prefixFileNative}\"") + if (NOT "${_compilerVersion}" VERSION_LESS "13.1.0") + set (_flags "${_flags} /Wpch-messages") + endif() + endif() + else() + # no precompiled header, force inclusion of prefix header + if (_flags) + # append to list + list (APPEND _flags "/FI${_prefixFileNative}") + else() + # return as a flag string + set (_flags "/FI\"${_prefixFileNative}\"") + endif() + endif() + else() + # Linux / Mac OS X Intel options used + # -pch-dir location for precompiled header files + # -pch-use name of the precompiled header (PCH) to use + # -include process include file as the first line of the primary source file + # -Wpch-messages enable diagnostics related to pre-compiled headers (requires Intel XE 2013 Update 2) + if (_pchFile) + get_filename_component(_pchDir "${_pchFile}" DIRECTORY) + get_filename_component(_pchName "${_pchFile}" NAME) + set (_pchSuppressMessages FALSE) + if ("${CMAKE_${_language}_FLAGS}" MATCHES ".*-Wno-pch-messages.*") + set(_pchSuppressMessages TRUE) + endif() + if (_flags) + # append to list + list (APPEND _flags "-include" "${_prefixFile}" "-pch-dir" "${_pchDir}" "-pch-use" "${_pchName}") + if (NOT "${_compilerVersion}" VERSION_LESS "13.1.0") + if (NOT _pchSuppressMessages) + list (APPEND _flags "-Wpch-messages") + endif() + endif() + else() + # return as a flag string + set (_flags "-include \"${_prefixFile}\" -pch-dir \"${_pchDir}\" -pch-use \"${_pchName}\"") + if (NOT "${_compilerVersion}" VERSION_LESS "13.1.0") + if (NOT _pchSuppressMessages) + set (_flags "${_flags} -Wpch-messages") + endif() + endif() + endif() + else() + # no precompiled header, force inclusion of prefix header + if (_flags) + # append to list + list (APPEND _flags "-include" "${_prefixFile}") + else() + # return as a flag string + set (_flags "-include \"${_prefixFile}\"") + endif() + endif() + endif() + else() + message (FATAL_ERROR "cotire: unsupported ${_language} compiler ${_compilerID} version ${_compilerVersion}.") + endif() + set (${_flagsVar} ${_flags} PARENT_SCOPE) +endfunction() + +function (cotire_precompile_prefix_header _prefixFile _pchFile _hostFile) + set(_options "") + set(_oneValueArgs COMPILER_EXECUTABLE COMPILER_ARG1 COMPILER_ID COMPILER_VERSION LANGUAGE) + set(_multiValueArgs COMPILE_DEFINITIONS COMPILE_FLAGS INCLUDE_DIRECTORIES SYSTEM_INCLUDE_DIRECTORIES SYS COMPILER_LAUNCHER) + cmake_parse_arguments(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN}) + if (NOT _option_LANGUAGE) + set (_option_LANGUAGE "CXX") + endif() + if (NOT _option_COMPILER_ID) + set (_option_COMPILER_ID "${CMAKE_${_option_LANGUAGE}_ID}") + endif() + if (NOT _option_COMPILER_VERSION) + set (_option_COMPILER_VERSION "${CMAKE_${_option_LANGUAGE}_COMPILER_VERSION}") + endif() + cotire_init_compile_cmd(_cmd "${_option_LANGUAGE}" "${_option_COMPILER_LAUNCHER}" "${_option_COMPILER_EXECUTABLE}" "${_option_COMPILER_ARG1}") + cotire_add_definitions_to_cmd(_cmd "${_option_LANGUAGE}" ${_option_COMPILE_DEFINITIONS}) + cotire_add_compile_flags_to_cmd(_cmd ${_option_COMPILE_FLAGS}) + cotire_add_includes_to_cmd(_cmd "${_option_LANGUAGE}" _option_INCLUDE_DIRECTORIES _option_SYSTEM_INCLUDE_DIRECTORIES) + cotire_add_frameworks_to_cmd(_cmd "${_option_LANGUAGE}" _option_INCLUDE_DIRECTORIES _option_SYSTEM_INCLUDE_DIRECTORIES) + cotire_add_pch_compilation_flags( + "${_option_LANGUAGE}" "${_option_COMPILER_ID}" "${_option_COMPILER_VERSION}" + "${_prefixFile}" "${_pchFile}" "${_hostFile}" _cmd) + if (COTIRE_VERBOSE) + message (STATUS "execute_process: ${_cmd}") + endif() + if (_option_COMPILER_ID MATCHES "MSVC") + # cl.exe messes with the output streams unless the environment variable VS_UNICODE_OUTPUT is cleared + unset (ENV{VS_UNICODE_OUTPUT}) + elseif (_option_COMPILER_ID MATCHES "GNU|Clang") + if (_option_COMPILER_LAUNCHER MATCHES "ccache" OR + _option_COMPILER_EXECUTABLE MATCHES "ccache") + # Newer versions of Clang and GCC seem to embed a compilation timestamp into the precompiled header binary, + # which results in "file has been modified since the precompiled header was built" errors if ccache is used. + # We work around the problem by disabling ccache upon pre-compiling the prefix header. + set (ENV{CCACHE_DISABLE} "true") + endif() + endif() + execute_process( + COMMAND ${_cmd} + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + RESULT_VARIABLE _result) + if (_result) + message (FATAL_ERROR "cotire: error ${_result} precompiling ${_prefixFile}.") + endif() +endfunction() + +function (cotire_check_precompiled_header_support _language _target _msgVar) + set (_unsupportedCompiler + "Precompiled headers not supported for ${_language} compiler ${CMAKE_${_language}_COMPILER_ID}") + if (CMAKE_${_language}_COMPILER_ID MATCHES "MSVC") + # supported since Visual Studio C++ 6.0 + # and CMake does not support an earlier version + set (${_msgVar} "" PARENT_SCOPE) + elseif (CMAKE_${_language}_COMPILER_ID MATCHES "GNU") + # GCC PCH support requires version >= 3.4 + if ("${CMAKE_${_language}_COMPILER_VERSION}" VERSION_LESS "3.4.0") + set (${_msgVar} "${_unsupportedCompiler} version ${CMAKE_${_language}_COMPILER_VERSION}." PARENT_SCOPE) + else() + set (${_msgVar} "" PARENT_SCOPE) + endif() + elseif (CMAKE_${_language}_COMPILER_ID MATCHES "Clang") + # all Clang versions have PCH support + set (${_msgVar} "" PARENT_SCOPE) + elseif (CMAKE_${_language}_COMPILER_ID MATCHES "Intel") + # Intel PCH support requires version >= 8.0.0 + if ("${CMAKE_${_language}_COMPILER_VERSION}" VERSION_LESS "8.0.0") + set (${_msgVar} "${_unsupportedCompiler} version ${CMAKE_${_language}_COMPILER_VERSION}." PARENT_SCOPE) + else() + set (${_msgVar} "" PARENT_SCOPE) + endif() + else() + set (${_msgVar} "${_unsupportedCompiler}." PARENT_SCOPE) + endif() + get_target_property(_launcher ${_target} ${_language}_COMPILER_LAUNCHER) + if (CMAKE_${_language}_COMPILER MATCHES "ccache" OR _launcher MATCHES "ccache") + if (DEFINED ENV{CCACHE_SLOPPINESS}) + if (NOT "$ENV{CCACHE_SLOPPINESS}" MATCHES "pch_defines" OR NOT "$ENV{CCACHE_SLOPPINESS}" MATCHES "time_macros") + set (${_msgVar} + "ccache requires the environment variable CCACHE_SLOPPINESS to be set to \"pch_defines,time_macros\"." + PARENT_SCOPE) + endif() + else() + if (_launcher MATCHES "ccache") + get_filename_component(_ccacheExe "${_launcher}" REALPATH) + else() + get_filename_component(_ccacheExe "${CMAKE_${_language}_COMPILER}" REALPATH) + endif() + execute_process( + COMMAND "${_ccacheExe}" "--print-config" + WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}" + RESULT_VARIABLE _result + OUTPUT_VARIABLE _ccacheConfig OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_QUIET) + if (_result OR NOT + _ccacheConfig MATCHES "sloppiness.*=.*time_macros" OR NOT + _ccacheConfig MATCHES "sloppiness.*=.*pch_defines") + set (${_msgVar} + "ccache requires configuration setting \"sloppiness\" to be set to \"pch_defines,time_macros\"." + PARENT_SCOPE) + endif() + endif() + endif() + if (APPLE) + # PCH compilation not supported by GCC / Clang for multi-architecture builds (e.g., i386, x86_64) + cotire_get_configuration_types(_configs) + foreach (_config ${_configs}) + set (_targetFlags "") + cotire_get_target_compile_flags("${_config}" "${_language}" "${_target}" _targetFlags) + cotire_filter_compile_flags("${_language}" "arch" _architectures _ignore ${_targetFlags}) + list (LENGTH _architectures _numberOfArchitectures) + if (_numberOfArchitectures GREATER 1) + string (REPLACE ";" ", " _architectureStr "${_architectures}") + set (${_msgVar} + "Precompiled headers not supported on Darwin for multi-architecture builds (${_architectureStr})." + PARENT_SCOPE) + break() + endif() + endforeach() + endif() +endfunction() + +macro (cotire_get_intermediate_dir _cotireDir) + # ${CMAKE_CFG_INTDIR} may reference a build-time variable when using a generator which supports configuration types + get_filename_component(${_cotireDir} "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}/${COTIRE_INTDIR}" ABSOLUTE) +endmacro() + +macro (cotire_setup_file_extension_variables) + set (_unityFileExt_C ".c") + set (_unityFileExt_CXX ".cxx") + set (_prefixFileExt_C ".h") + set (_prefixFileExt_CXX ".hxx") + set (_prefixSourceFileExt_C ".c") + set (_prefixSourceFileExt_CXX ".cxx") +endmacro() + +function (cotire_make_single_unity_source_file_path _language _target _unityFileVar) + cotire_setup_file_extension_variables() + if (NOT DEFINED _unityFileExt_${_language}) + set (${_unityFileVar} "" PARENT_SCOPE) + return() + endif() + set (_unityFileBaseName "${_target}_${_language}${COTIRE_UNITY_SOURCE_FILENAME_SUFFIX}") + set (_unityFileName "${_unityFileBaseName}${_unityFileExt_${_language}}") + cotire_get_intermediate_dir(_baseDir) + set (_unityFile "${_baseDir}/${_unityFileName}") + set (${_unityFileVar} "${_unityFile}" PARENT_SCOPE) +endfunction() + +function (cotire_make_unity_source_file_paths _language _target _maxIncludes _unityFilesVar) + cotire_setup_file_extension_variables() + if (NOT DEFINED _unityFileExt_${_language}) + set (${_unityFileVar} "" PARENT_SCOPE) + return() + endif() + set (_unityFileBaseName "${_target}_${_language}${COTIRE_UNITY_SOURCE_FILENAME_SUFFIX}") + cotire_get_intermediate_dir(_baseDir) + set (_startIndex 0) + set (_index 0) + set (_unityFiles "") + set (_sourceFiles ${ARGN}) + foreach (_sourceFile ${_sourceFiles}) + get_source_file_property(_startNew "${_sourceFile}" COTIRE_START_NEW_UNITY_SOURCE) + math (EXPR _unityFileCount "${_index} - ${_startIndex}") + if (_startNew OR (_maxIncludes GREATER 0 AND NOT _unityFileCount LESS _maxIncludes)) + if (_index GREATER 0) + # start new unity file segment + math (EXPR _endIndex "${_index} - 1") + set (_unityFileName "${_unityFileBaseName}_${_startIndex}_${_endIndex}${_unityFileExt_${_language}}") + list (APPEND _unityFiles "${_baseDir}/${_unityFileName}") + endif() + set (_startIndex ${_index}) + endif() + math (EXPR _index "${_index} + 1") + endforeach() + list (LENGTH _sourceFiles _numberOfSources) + if (_startIndex EQUAL 0) + # there is only a single unity file + cotire_make_single_unity_source_file_path(${_language} ${_target} _unityFiles) + elseif (_startIndex LESS _numberOfSources) + # end with final unity file segment + math (EXPR _endIndex "${_index} - 1") + set (_unityFileName "${_unityFileBaseName}_${_startIndex}_${_endIndex}${_unityFileExt_${_language}}") + list (APPEND _unityFiles "${_baseDir}/${_unityFileName}") + endif() + set (${_unityFilesVar} ${_unityFiles} PARENT_SCOPE) + if (COTIRE_DEBUG AND _unityFiles) + message (STATUS "unity files: ${_unityFiles}") + endif() +endfunction() + +function (cotire_unity_to_prefix_file_path _language _target _unityFile _prefixFileVar) + cotire_setup_file_extension_variables() + if (NOT DEFINED _unityFileExt_${_language}) + set (${_prefixFileVar} "" PARENT_SCOPE) + return() + endif() + set (_unityFileBaseName "${_target}_${_language}${COTIRE_UNITY_SOURCE_FILENAME_SUFFIX}") + set (_prefixFileBaseName "${_target}_${_language}${COTIRE_PREFIX_HEADER_FILENAME_SUFFIX}") + string (REPLACE "${_unityFileBaseName}" "${_prefixFileBaseName}" _prefixFile "${_unityFile}") + string (REGEX REPLACE "${_unityFileExt_${_language}}$" "${_prefixFileExt_${_language}}" _prefixFile "${_prefixFile}") + set (${_prefixFileVar} "${_prefixFile}" PARENT_SCOPE) +endfunction() + +function (cotire_prefix_header_to_source_file_path _language _prefixHeaderFile _prefixSourceFileVar) + cotire_setup_file_extension_variables() + if (NOT DEFINED _prefixSourceFileExt_${_language}) + set (${_prefixSourceFileVar} "" PARENT_SCOPE) + return() + endif() + string (REGEX REPLACE "${_prefixFileExt_${_language}}$" "${_prefixSourceFileExt_${_language}}" _prefixSourceFile "${_prefixHeaderFile}") + set (${_prefixSourceFileVar} "${_prefixSourceFile}" PARENT_SCOPE) +endfunction() + +function (cotire_make_prefix_file_name _language _target _prefixFileBaseNameVar _prefixFileNameVar) + cotire_setup_file_extension_variables() + if (NOT _language) + set (_prefixFileBaseName "${_target}${COTIRE_PREFIX_HEADER_FILENAME_SUFFIX}") + set (_prefixFileName "${_prefixFileBaseName}${_prefixFileExt_C}") + elseif (DEFINED _prefixFileExt_${_language}) + set (_prefixFileBaseName "${_target}_${_language}${COTIRE_PREFIX_HEADER_FILENAME_SUFFIX}") + set (_prefixFileName "${_prefixFileBaseName}${_prefixFileExt_${_language}}") + else() + set (_prefixFileBaseName "") + set (_prefixFileName "") + endif() + set (${_prefixFileBaseNameVar} "${_prefixFileBaseName}" PARENT_SCOPE) + set (${_prefixFileNameVar} "${_prefixFileName}" PARENT_SCOPE) +endfunction() + +function (cotire_make_prefix_file_path _language _target _prefixFileVar) + cotire_make_prefix_file_name("${_language}" "${_target}" _prefixFileBaseName _prefixFileName) + set (${_prefixFileVar} "" PARENT_SCOPE) + if (_prefixFileName) + if (NOT _language) + set (_language "C") + endif() + if (CMAKE_${_language}_COMPILER_ID MATCHES "GNU|Clang|Intel|MSVC") + cotire_get_intermediate_dir(_baseDir) + set (${_prefixFileVar} "${_baseDir}/${_prefixFileName}" PARENT_SCOPE) + endif() + endif() +endfunction() + +function (cotire_make_pch_file_path _language _target _pchFileVar) + cotire_make_prefix_file_name("${_language}" "${_target}" _prefixFileBaseName _prefixFileName) + set (${_pchFileVar} "" PARENT_SCOPE) + if (_prefixFileBaseName AND _prefixFileName) + cotire_check_precompiled_header_support("${_language}" "${_target}" _msg) + if (NOT _msg) + if (XCODE) + # For Xcode, we completely hand off the compilation of the prefix header to the IDE + return() + endif() + cotire_get_intermediate_dir(_baseDir) + if (CMAKE_${_language}_COMPILER_ID MATCHES "MSVC") + # MSVC uses the extension .pch added to the prefix header base name + set (${_pchFileVar} "${_baseDir}/${_prefixFileBaseName}.pch" PARENT_SCOPE) + elseif (CMAKE_${_language}_COMPILER_ID MATCHES "Clang") + # Clang looks for a precompiled header corresponding to the prefix header with the extension .pch appended + set (${_pchFileVar} "${_baseDir}/${_prefixFileName}.pch" PARENT_SCOPE) + elseif (CMAKE_${_language}_COMPILER_ID MATCHES "GNU") + # GCC looks for a precompiled header corresponding to the prefix header with the extension .gch appended + set (${_pchFileVar} "${_baseDir}/${_prefixFileName}.gch" PARENT_SCOPE) + elseif (CMAKE_${_language}_COMPILER_ID MATCHES "Intel") + # Intel uses the extension .pchi added to the prefix header base name + set (${_pchFileVar} "${_baseDir}/${_prefixFileBaseName}.pchi" PARENT_SCOPE) + endif() + endif() + endif() +endfunction() + +function (cotire_select_unity_source_files _unityFile _sourcesVar) + set (_sourceFiles ${ARGN}) + if (_sourceFiles AND "${_unityFile}" MATCHES "${COTIRE_UNITY_SOURCE_FILENAME_SUFFIX}_([0-9]+)_([0-9]+)") + set (_startIndex ${CMAKE_MATCH_1}) + set (_endIndex ${CMAKE_MATCH_2}) + list (LENGTH _sourceFiles _numberOfSources) + if (NOT _startIndex LESS _numberOfSources) + math (EXPR _startIndex "${_numberOfSources} - 1") + endif() + if (NOT _endIndex LESS _numberOfSources) + math (EXPR _endIndex "${_numberOfSources} - 1") + endif() + set (_files "") + foreach (_index RANGE ${_startIndex} ${_endIndex}) + list (GET _sourceFiles ${_index} _file) + list (APPEND _files "${_file}") + endforeach() + else() + set (_files ${_sourceFiles}) + endif() + set (${_sourcesVar} ${_files} PARENT_SCOPE) +endfunction() + +function (cotire_get_unity_source_dependencies _language _target _dependencySourcesVar) + set (_dependencySources "") + # depend on target's generated source files + get_target_property(_targetSourceFiles ${_target} SOURCES) + cotire_get_objects_with_property_on(_generatedSources GENERATED SOURCE ${_targetSourceFiles}) + if (_generatedSources) + # but omit all generated source files that have the COTIRE_EXCLUDED property set to true + cotire_get_objects_with_property_on(_excludedGeneratedSources COTIRE_EXCLUDED SOURCE ${_generatedSources}) + if (_excludedGeneratedSources) + list (REMOVE_ITEM _generatedSources ${_excludedGeneratedSources}) + endif() + # and omit all generated source files that have the COTIRE_DEPENDENCY property set to false explicitly + cotire_get_objects_with_property_off(_excludedNonDependencySources COTIRE_DEPENDENCY SOURCE ${_generatedSources}) + if (_excludedNonDependencySources) + list (REMOVE_ITEM _generatedSources ${_excludedNonDependencySources}) + endif() + if (_generatedSources) + list (APPEND _dependencySources ${_generatedSources}) + endif() + endif() + if (COTIRE_DEBUG AND _dependencySources) + message (STATUS "${_language} ${_target} unity source dependencies: ${_dependencySources}") + endif() + set (${_dependencySourcesVar} ${_dependencySources} PARENT_SCOPE) +endfunction() + +function (cotire_get_prefix_header_dependencies _language _target _dependencySourcesVar) + set (_dependencySources "") + # depend on target source files marked with custom COTIRE_DEPENDENCY property + get_target_property(_targetSourceFiles ${_target} SOURCES) + cotire_get_objects_with_property_on(_dependencySources COTIRE_DEPENDENCY SOURCE ${_targetSourceFiles}) + if (COTIRE_DEBUG AND _dependencySources) + message (STATUS "${_language} ${_target} prefix header dependencies: ${_dependencySources}") + endif() + set (${_dependencySourcesVar} ${_dependencySources} PARENT_SCOPE) +endfunction() + +function (cotire_generate_target_script _language _configurations _target _targetScriptVar _targetConfigScriptVar) + set (_targetSources ${ARGN}) + cotire_get_prefix_header_dependencies(${_language} ${_target} COTIRE_TARGET_PREFIX_DEPENDS ${_targetSources}) + cotire_get_unity_source_dependencies(${_language} ${_target} COTIRE_TARGET_UNITY_DEPENDS ${_targetSources}) + # set up variables to be configured + set (COTIRE_TARGET_LANGUAGE "${_language}") + get_target_property(COTIRE_TARGET_IGNORE_PATH ${_target} COTIRE_PREFIX_HEADER_IGNORE_PATH) + cotire_add_sys_root_paths(COTIRE_TARGET_IGNORE_PATH) + get_target_property(COTIRE_TARGET_INCLUDE_PATH ${_target} COTIRE_PREFIX_HEADER_INCLUDE_PATH) + cotire_add_sys_root_paths(COTIRE_TARGET_INCLUDE_PATH) + get_target_property(COTIRE_TARGET_PRE_UNDEFS ${_target} COTIRE_UNITY_SOURCE_PRE_UNDEFS) + get_target_property(COTIRE_TARGET_POST_UNDEFS ${_target} COTIRE_UNITY_SOURCE_POST_UNDEFS) + get_target_property(COTIRE_TARGET_MAXIMUM_NUMBER_OF_INCLUDES ${_target} COTIRE_UNITY_SOURCE_MAXIMUM_NUMBER_OF_INCLUDES) + get_target_property(COTIRE_TARGET_INCLUDE_PRIORITY_PATH ${_target} COTIRE_PREFIX_HEADER_INCLUDE_PRIORITY_PATH) + cotire_get_source_files_undefs(COTIRE_UNITY_SOURCE_PRE_UNDEFS COTIRE_TARGET_SOURCES_PRE_UNDEFS ${_targetSources}) + cotire_get_source_files_undefs(COTIRE_UNITY_SOURCE_POST_UNDEFS COTIRE_TARGET_SOURCES_POST_UNDEFS ${_targetSources}) + set (COTIRE_TARGET_CONFIGURATION_TYPES "${_configurations}") + foreach (_config ${_configurations}) + string (TOUPPER "${_config}" _upperConfig) + cotire_get_target_include_directories( + "${_config}" "${_language}" "${_target}" COTIRE_TARGET_INCLUDE_DIRECTORIES_${_upperConfig} COTIRE_TARGET_SYSTEM_INCLUDE_DIRECTORIES_${_upperConfig}) + cotire_get_target_compile_definitions( + "${_config}" "${_language}" "${_target}" COTIRE_TARGET_COMPILE_DEFINITIONS_${_upperConfig}) + cotire_get_target_compiler_flags( + "${_config}" "${_language}" "${_target}" COTIRE_TARGET_COMPILE_FLAGS_${_upperConfig}) + cotire_get_source_files_compile_definitions( + "${_config}" "${_language}" COTIRE_TARGET_SOURCES_COMPILE_DEFINITIONS_${_upperConfig} ${_targetSources}) + endforeach() + get_target_property(COTIRE_TARGET_${_language}_COMPILER_LAUNCHER ${_target} ${_language}_COMPILER_LAUNCHER) + # set up COTIRE_TARGET_SOURCES + set (COTIRE_TARGET_SOURCES "") + foreach (_sourceFile ${_targetSources}) + get_source_file_property(_generated "${_sourceFile}" GENERATED) + if (_generated) + # use absolute paths for generated files only, retrieving the LOCATION property is an expensive operation + get_source_file_property(_sourceLocation "${_sourceFile}" LOCATION) + list (APPEND COTIRE_TARGET_SOURCES "${_sourceLocation}") + else() + list (APPEND COTIRE_TARGET_SOURCES "${_sourceFile}") + endif() + endforeach() + # copy variable definitions to cotire target script + get_cmake_property(_vars VARIABLES) + string (REGEX MATCHALL "COTIRE_[A-Za-z0-9_]+" _matchVars "${_vars}") + # omit COTIRE_*_INIT variables + string (REGEX MATCHALL "COTIRE_[A-Za-z0-9_]+_INIT" _initVars "${_matchVars}") + if (_initVars) + list (REMOVE_ITEM _matchVars ${_initVars}) + endif() + # omit COTIRE_VERBOSE which is passed as a CMake define on command line + list (REMOVE_ITEM _matchVars COTIRE_VERBOSE) + set (_contents "") + set (_contentsHasGeneratorExpressions FALSE) + foreach (_var IN LISTS _matchVars ITEMS + XCODE MSVC CMAKE_GENERATOR CMAKE_BUILD_TYPE CMAKE_CONFIGURATION_TYPES + CMAKE_${_language}_COMPILER_ID CMAKE_${_language}_COMPILER_VERSION + CMAKE_${_language}_COMPILER_LAUNCHER CMAKE_${_language}_COMPILER CMAKE_${_language}_COMPILER_ARG1 + CMAKE_INCLUDE_FLAG_${_language} CMAKE_INCLUDE_FLAG_SEP_${_language} + CMAKE_INCLUDE_SYSTEM_FLAG_${_language} + CMAKE_${_language}_FRAMEWORK_SEARCH_FLAG + CMAKE_${_language}_SYSTEM_FRAMEWORK_SEARCH_FLAG + CMAKE_${_language}_SOURCE_FILE_EXTENSIONS) + if (DEFINED ${_var}) + string (REPLACE "\"" "\\\"" _value "${${_var}}") + set (_contents "${_contents}set (${_var} \"${_value}\")\n") + if (NOT _contentsHasGeneratorExpressions) + if ("${_value}" MATCHES "\\$<.*>") + set (_contentsHasGeneratorExpressions TRUE) + endif() + endif() + endif() + endforeach() + # generate target script file + get_filename_component(_moduleName "${COTIRE_CMAKE_MODULE_FILE}" NAME) + set (_targetCotireScript "${CMAKE_CURRENT_BINARY_DIR}/${_target}_${_language}_${_moduleName}") + cotire_write_file("CMAKE" "${_targetCotireScript}" "${_contents}" FALSE) + if (_contentsHasGeneratorExpressions) + # use file(GENERATE ...) to expand generator expressions in the target script at CMake generate-time + set (_configNameOrNoneGeneratorExpression "$<$:None>$<$>:$>") + set (_targetCotireConfigScript "${CMAKE_CURRENT_BINARY_DIR}/${_target}_${_language}_${_configNameOrNoneGeneratorExpression}_${_moduleName}") + file (GENERATE OUTPUT "${_targetCotireConfigScript}" INPUT "${_targetCotireScript}") + else() + set (_targetCotireConfigScript "${_targetCotireScript}") + endif() + set (${_targetScriptVar} "${_targetCotireScript}" PARENT_SCOPE) + set (${_targetConfigScriptVar} "${_targetCotireConfigScript}" PARENT_SCOPE) +endfunction() + +function (cotire_setup_pch_file_compilation _language _target _targetScript _prefixFile _pchFile _hostFile) + set (_sourceFiles ${ARGN}) + if (CMAKE_${_language}_COMPILER_ID MATCHES "MSVC|Intel") + # for Visual Studio and Intel, we attach the precompiled header compilation to the host file + # the remaining files include the precompiled header, see cotire_setup_pch_file_inclusion + if (_sourceFiles) + set (_flags "") + cotire_add_pch_compilation_flags( + "${_language}" "${CMAKE_${_language}_COMPILER_ID}" "${CMAKE_${_language}_COMPILER_VERSION}" + "${_prefixFile}" "${_pchFile}" "${_hostFile}" _flags) + set_property (SOURCE ${_hostFile} APPEND_STRING PROPERTY COMPILE_FLAGS " ${_flags} ") + set_property (SOURCE ${_hostFile} APPEND PROPERTY OBJECT_OUTPUTS "${_pchFile}") + # make object file generated from host file depend on prefix header + set_property (SOURCE ${_hostFile} APPEND PROPERTY OBJECT_DEPENDS "${_prefixFile}") + # mark host file as cotired to prevent it from being used in another cotired target + set_property (SOURCE ${_hostFile} PROPERTY COTIRE_TARGET "${_target}") + endif() + elseif ("${CMAKE_GENERATOR}" MATCHES "Make|Ninja") + # for makefile based generator, we add a custom command to precompile the prefix header + if (_targetScript) + cotire_set_cmd_to_prologue(_cmds) + list (APPEND _cmds -P "${COTIRE_CMAKE_MODULE_FILE}" "precompile" "${_targetScript}" "${_prefixFile}" "${_pchFile}" "${_hostFile}") + if (MSVC_IDE) + file (TO_NATIVE_PATH "${_pchFile}" _pchFileLogPath) + else() + file (RELATIVE_PATH _pchFileLogPath "${CMAKE_BINARY_DIR}" "${_pchFile}") + endif() + # make precompiled header compilation depend on the actual compiler executable used to force + # re-compilation when the compiler executable is updated. This prevents "created by a different GCC executable" + # warnings when the precompiled header is included. + get_filename_component(_realCompilerExe "${CMAKE_${_language}_COMPILER}" ABSOLUTE) + if (COTIRE_DEBUG) + message (STATUS "add_custom_command: OUTPUT ${_pchFile} ${_cmds} DEPENDS ${_prefixFile} ${_realCompilerExe} IMPLICIT_DEPENDS ${_language} ${_prefixFile}") + endif() + set_property (SOURCE "${_pchFile}" PROPERTY GENERATED TRUE) + add_custom_command( + OUTPUT "${_pchFile}" + COMMAND ${_cmds} + DEPENDS "${_prefixFile}" "${_realCompilerExe}" + IMPLICIT_DEPENDS ${_language} "${_prefixFile}" + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + COMMENT "Building ${_language} precompiled header ${_pchFileLogPath}" + VERBATIM) + endif() + endif() +endfunction() + +function (cotire_setup_pch_file_inclusion _language _target _wholeTarget _prefixFile _pchFile _hostFile) + if (CMAKE_${_language}_COMPILER_ID MATCHES "MSVC|Intel") + # for Visual Studio and Intel, we include the precompiled header in all but the host file + # the host file does the precompiled header compilation, see cotire_setup_pch_file_compilation + set (_sourceFiles ${ARGN}) + list (LENGTH _sourceFiles _numberOfSourceFiles) + if (_numberOfSourceFiles GREATER 0) + # mark sources as cotired to prevent them from being used in another cotired target + set_source_files_properties(${_sourceFiles} PROPERTIES COTIRE_TARGET "${_target}") + set (_flags "") + cotire_add_prefix_pch_inclusion_flags( + "${_language}" "${CMAKE_${_language}_COMPILER_ID}" "${CMAKE_${_language}_COMPILER_VERSION}" + "${_prefixFile}" "${_pchFile}" _flags) + set_property (SOURCE ${_sourceFiles} APPEND_STRING PROPERTY COMPILE_FLAGS " ${_flags} ") + # make object files generated from source files depend on precompiled header + set_property (SOURCE ${_sourceFiles} APPEND PROPERTY OBJECT_DEPENDS "${_pchFile}") + endif() + elseif ("${CMAKE_GENERATOR}" MATCHES "Make|Ninja") + set (_sourceFiles ${_hostFile} ${ARGN}) + if (NOT _wholeTarget) + # for makefile based generator, we force the inclusion of the prefix header for a subset + # of the source files, if this is a multi-language target or has excluded files + set (_flags "") + cotire_add_prefix_pch_inclusion_flags( + "${_language}" "${CMAKE_${_language}_COMPILER_ID}" "${CMAKE_${_language}_COMPILER_VERSION}" + "${_prefixFile}" "${_pchFile}" _flags) + set_property (SOURCE ${_sourceFiles} APPEND_STRING PROPERTY COMPILE_FLAGS " ${_flags} ") + # mark sources as cotired to prevent them from being used in another cotired target + set_source_files_properties(${_sourceFiles} PROPERTIES COTIRE_TARGET "${_target}") + endif() + # make object files generated from source files depend on precompiled header + set_property (SOURCE ${_sourceFiles} APPEND PROPERTY OBJECT_DEPENDS "${_pchFile}") + endif() +endfunction() + +function (cotire_setup_prefix_file_inclusion _language _target _prefixFile) + set (_sourceFiles ${ARGN}) + # force the inclusion of the prefix header for the given source files + set (_flags "") + set (_pchFile "") + cotire_add_prefix_pch_inclusion_flags( + "${_language}" "${CMAKE_${_language}_COMPILER_ID}" "${CMAKE_${_language}_COMPILER_VERSION}" + "${_prefixFile}" "${_pchFile}" _flags) + set_property (SOURCE ${_sourceFiles} APPEND_STRING PROPERTY COMPILE_FLAGS " ${_flags} ") + # mark sources as cotired to prevent them from being used in another cotired target + set_source_files_properties(${_sourceFiles} PROPERTIES COTIRE_TARGET "${_target}") + # make object files generated from source files depend on prefix header + set_property (SOURCE ${_sourceFiles} APPEND PROPERTY OBJECT_DEPENDS "${_prefixFile}") +endfunction() + +function (cotire_get_first_set_property_value _propertyValueVar _type _object) + set (_properties ${ARGN}) + foreach (_property ${_properties}) + get_property(_propertyValue ${_type} "${_object}" PROPERTY ${_property}) + if (_propertyValue) + set (${_propertyValueVar} ${_propertyValue} PARENT_SCOPE) + return() + endif() + endforeach() + set (${_propertyValueVar} "" PARENT_SCOPE) +endfunction() + +function (cotire_setup_combine_command _language _targetScript _joinedFile _cmdsVar) + set (_files ${ARGN}) + set (_filesPaths "") + foreach (_file ${_files}) + get_filename_component(_filePath "${_file}" ABSOLUTE) + list (APPEND _filesPaths "${_filePath}") + endforeach() + cotire_set_cmd_to_prologue(_prefixCmd) + list (APPEND _prefixCmd -P "${COTIRE_CMAKE_MODULE_FILE}" "combine") + if (_targetScript) + list (APPEND _prefixCmd "${_targetScript}") + endif() + list (APPEND _prefixCmd "${_joinedFile}" ${_filesPaths}) + if (COTIRE_DEBUG) + message (STATUS "add_custom_command: OUTPUT ${_joinedFile} COMMAND ${_prefixCmd} DEPENDS ${_files}") + endif() + set_property (SOURCE "${_joinedFile}" PROPERTY GENERATED TRUE) + if (MSVC_IDE) + file (TO_NATIVE_PATH "${_joinedFile}" _joinedFileLogPath) + else() + file (RELATIVE_PATH _joinedFileLogPath "${CMAKE_BINARY_DIR}" "${_joinedFile}") + endif() + get_filename_component(_joinedFileBaseName "${_joinedFile}" NAME_WE) + get_filename_component(_joinedFileExt "${_joinedFile}" EXT) + if (_language AND _joinedFileBaseName MATCHES "${COTIRE_UNITY_SOURCE_FILENAME_SUFFIX}$") + set (_comment "Generating ${_language} unity source ${_joinedFileLogPath}") + elseif (_language AND _joinedFileBaseName MATCHES "${COTIRE_PREFIX_HEADER_FILENAME_SUFFIX}$") + if (_joinedFileExt MATCHES "^\\.c") + set (_comment "Generating ${_language} prefix source ${_joinedFileLogPath}") + else() + set (_comment "Generating ${_language} prefix header ${_joinedFileLogPath}") + endif() + else() + set (_comment "Generating ${_joinedFileLogPath}") + endif() + add_custom_command( + OUTPUT "${_joinedFile}" + COMMAND ${_prefixCmd} + DEPENDS ${_files} + COMMENT "${_comment}" + WORKING_DIRECTORY "${CMAKE_BINARY_DIR}" + VERBATIM) + list (APPEND ${_cmdsVar} COMMAND ${_prefixCmd}) + set (${_cmdsVar} ${${_cmdsVar}} PARENT_SCOPE) +endfunction() + +function (cotire_setup_target_pch_usage _languages _target _wholeTarget) + if (XCODE) + # for Xcode, we attach a pre-build action to generate the unity sources and prefix headers + set (_prefixFiles "") + foreach (_language ${_languages}) + get_property(_prefixFile TARGET ${_target} PROPERTY COTIRE_${_language}_PREFIX_HEADER) + if (_prefixFile) + list (APPEND _prefixFiles "${_prefixFile}") + endif() + endforeach() + set (_cmds ${ARGN}) + list (LENGTH _prefixFiles _numberOfPrefixFiles) + if (_numberOfPrefixFiles GREATER 1) + # we also generate a generic, single prefix header which includes all language specific prefix headers + set (_language "") + set (_targetScript "") + cotire_make_prefix_file_path("${_language}" ${_target} _prefixHeader) + cotire_setup_combine_command("${_language}" "${_targetScript}" "${_prefixHeader}" _cmds ${_prefixFiles}) + else() + set (_prefixHeader "${_prefixFiles}") + endif() + if (COTIRE_DEBUG) + message (STATUS "add_custom_command: TARGET ${_target} PRE_BUILD ${_cmds}") + endif() + # because CMake PRE_BUILD command does not support dependencies, + # we check dependencies explicity in cotire script mode when the pre-build action is run + add_custom_command( + TARGET "${_target}" + PRE_BUILD ${_cmds} + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + COMMENT "Updating target ${_target} prefix headers" + VERBATIM) + # make Xcode precompile the generated prefix header with ProcessPCH and ProcessPCH++ + set_target_properties(${_target} PROPERTIES XCODE_ATTRIBUTE_GCC_PRECOMPILE_PREFIX_HEADER "YES") + set_target_properties(${_target} PROPERTIES XCODE_ATTRIBUTE_GCC_PREFIX_HEADER "${_prefixHeader}") + elseif ("${CMAKE_GENERATOR}" MATCHES "Make|Ninja") + # for makefile based generator, we force inclusion of the prefix header for all target source files + # if this is a single-language target without any excluded files + if (_wholeTarget) + set (_language "${_languages}") + # for Visual Studio and Intel, precompiled header inclusion is always done on the source file level + # see cotire_setup_pch_file_inclusion + if (NOT CMAKE_${_language}_COMPILER_ID MATCHES "MSVC|Intel") + get_property(_prefixFile TARGET ${_target} PROPERTY COTIRE_${_language}_PREFIX_HEADER) + if (_prefixFile) + get_property(_pchFile TARGET ${_target} PROPERTY COTIRE_${_language}_PRECOMPILED_HEADER) + set (_options COMPILE_OPTIONS) + cotire_add_prefix_pch_inclusion_flags( + "${_language}" "${CMAKE_${_language}_COMPILER_ID}" "${CMAKE_${_language}_COMPILER_VERSION}" + "${_prefixFile}" "${_pchFile}" _options) + set_property(TARGET ${_target} APPEND PROPERTY ${_options}) + endif() + endif() + endif() + endif() +endfunction() + +function (cotire_setup_unity_generation_commands _language _target _targetScript _targetConfigScript _unityFiles _cmdsVar) + set (_dependencySources "") + cotire_get_unity_source_dependencies(${_language} ${_target} _dependencySources ${ARGN}) + foreach (_unityFile ${_unityFiles}) + set_property (SOURCE "${_unityFile}" PROPERTY GENERATED TRUE) + # set up compiled unity source dependencies via OBJECT_DEPENDS + # this ensures that missing source files are generated before the unity file is compiled + if (COTIRE_DEBUG AND _dependencySources) + message (STATUS "${_unityFile} OBJECT_DEPENDS ${_dependencySources}") + endif() + if (_dependencySources) + # the OBJECT_DEPENDS property requires a list of full paths + set (_objectDependsPaths "") + foreach (_sourceFile ${_dependencySources}) + get_source_file_property(_sourceLocation "${_sourceFile}" LOCATION) + list (APPEND _objectDependsPaths "${_sourceLocation}") + endforeach() + set_property (SOURCE "${_unityFile}" PROPERTY OBJECT_DEPENDS ${_objectDependsPaths}) + endif() + if (WIN32 AND CMAKE_${_language}_COMPILER_ID MATCHES "MSVC|Intel") + # unity file compilation results in potentially huge object file, thus use /bigobj by default unter MSVC and Windows Intel + set_property (SOURCE "${_unityFile}" APPEND_STRING PROPERTY COMPILE_FLAGS "/bigobj") + endif() + cotire_set_cmd_to_prologue(_unityCmd) + list (APPEND _unityCmd -P "${COTIRE_CMAKE_MODULE_FILE}" "unity" "${_targetConfigScript}" "${_unityFile}") + if (CMAKE_VERSION VERSION_LESS "3.1.0") + set (_unityCmdDepends "${_targetScript}") + else() + # CMake 3.1.0 supports generator expressions in arguments to DEPENDS + set (_unityCmdDepends "${_targetConfigScript}") + endif() + if (MSVC_IDE) + file (TO_NATIVE_PATH "${_unityFile}" _unityFileLogPath) + else() + file (RELATIVE_PATH _unityFileLogPath "${CMAKE_BINARY_DIR}" "${_unityFile}") + endif() + if (COTIRE_DEBUG) + message (STATUS "add_custom_command: OUTPUT ${_unityFile} COMMAND ${_unityCmd} DEPENDS ${_unityCmdDepends}") + endif() + add_custom_command( + OUTPUT "${_unityFile}" + COMMAND ${_unityCmd} + DEPENDS ${_unityCmdDepends} + COMMENT "Generating ${_language} unity source ${_unityFileLogPath}" + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + VERBATIM) + list (APPEND ${_cmdsVar} COMMAND ${_unityCmd}) + endforeach() + set (${_cmdsVar} ${${_cmdsVar}} PARENT_SCOPE) +endfunction() + +function (cotire_setup_prefix_generation_command _language _target _targetScript _prefixFile _unityFiles _cmdsVar) + set (_sourceFiles ${ARGN}) + set (_dependencySources "") + cotire_get_prefix_header_dependencies(${_language} ${_target} _dependencySources ${_sourceFiles}) + cotire_set_cmd_to_prologue(_prefixCmd) + list (APPEND _prefixCmd -P "${COTIRE_CMAKE_MODULE_FILE}" "prefix" "${_targetScript}" "${_prefixFile}" ${_unityFiles}) + set_property (SOURCE "${_prefixFile}" PROPERTY GENERATED TRUE) + # make prefix header generation depend on the actual compiler executable used to force + # re-generation when the compiler executable is updated. This prevents "file not found" + # errors for compiler version specific system header files. + get_filename_component(_realCompilerExe "${CMAKE_${_language}_COMPILER}" ABSOLUTE) + if (COTIRE_DEBUG) + message (STATUS "add_custom_command: OUTPUT ${_prefixFile} COMMAND ${_prefixCmd} DEPENDS ${_unityFile} ${_dependencySources} ${_realCompilerExe}") + endif() + if (MSVC_IDE) + file (TO_NATIVE_PATH "${_prefixFile}" _prefixFileLogPath) + else() + file (RELATIVE_PATH _prefixFileLogPath "${CMAKE_BINARY_DIR}" "${_prefixFile}") + endif() + get_filename_component(_prefixFileExt "${_prefixFile}" EXT) + if (_prefixFileExt MATCHES "^\\.c") + set (_comment "Generating ${_language} prefix source ${_prefixFileLogPath}") + else() + set (_comment "Generating ${_language} prefix header ${_prefixFileLogPath}") + endif() + # prevent pre-processing errors upon generating the prefix header when a target's generated include file does not yet exist + # we do not add a file-level dependency for the target's generated files though, because we only want to depend on their existence + # thus we make the prefix header generation depend on a custom helper target which triggers the generation of the files + set (_preTargetName "${_target}${COTIRE_PCH_TARGET_SUFFIX}_pre") + if (TARGET ${_preTargetName}) + # custom helper target has already been generated while processing a different language + list (APPEND _dependencySources ${_preTargetName}) + else() + get_target_property(_targetSourceFiles ${_target} SOURCES) + cotire_get_objects_with_property_on(_generatedSources GENERATED SOURCE ${_targetSourceFiles}) + if (_generatedSources) + add_custom_target("${_preTargetName}" DEPENDS ${_generatedSources}) + cotire_init_target("${_preTargetName}") + list (APPEND _dependencySources ${_preTargetName}) + endif() + endif() + add_custom_command( + OUTPUT "${_prefixFile}" "${_prefixFile}.log" + COMMAND ${_prefixCmd} + DEPENDS ${_unityFiles} ${_dependencySources} "${_realCompilerExe}" + COMMENT "${_comment}" + WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" + VERBATIM) + list (APPEND ${_cmdsVar} COMMAND ${_prefixCmd}) + set (${_cmdsVar} ${${_cmdsVar}} PARENT_SCOPE) +endfunction() + +function (cotire_setup_prefix_generation_from_unity_command _language _target _targetScript _prefixFile _unityFiles _cmdsVar) + set (_sourceFiles ${ARGN}) + if (CMAKE_${_language}_COMPILER_ID MATCHES "GNU|Clang") + # GNU and Clang require indirect compilation of the prefix header to make them honor the system_header pragma + cotire_prefix_header_to_source_file_path(${_language} "${_prefixFile}" _prefixSourceFile) + else() + set (_prefixSourceFile "${_prefixFile}") + endif() + cotire_setup_prefix_generation_command( + ${_language} ${_target} "${_targetScript}" + "${_prefixSourceFile}" "${_unityFiles}" ${_cmdsVar} ${_sourceFiles}) + if (CMAKE_${_language}_COMPILER_ID MATCHES "GNU|Clang") + # set up generation of a prefix source file which includes the prefix header + cotire_setup_combine_command(${_language} "${_targetScript}" "${_prefixFile}" _cmds ${_prefixSourceFile}) + endif() + set (${_cmdsVar} ${${_cmdsVar}} PARENT_SCOPE) +endfunction() + +function (cotire_setup_prefix_generation_from_provided_command _language _target _targetScript _prefixFile _cmdsVar) + set (_prefixHeaderFiles ${ARGN}) + if (CMAKE_${_language}_COMPILER_ID MATCHES "GNU|Clang") + # GNU and Clang require indirect compilation of the prefix header to make them honor the system_header pragma + cotire_prefix_header_to_source_file_path(${_language} "${_prefixFile}" _prefixSourceFile) + else() + set (_prefixSourceFile "${_prefixFile}") + endif() + cotire_setup_combine_command(${_language} "${_targetScript}" "${_prefixSourceFile}" _cmds ${_prefixHeaderFiles}) + if (CMAKE_${_language}_COMPILER_ID MATCHES "GNU|Clang") + # set up generation of a prefix source file which includes the prefix header + cotire_setup_combine_command(${_language} "${_targetScript}" "${_prefixFile}" _cmds ${_prefixSourceFile}) + endif() + set (${_cmdsVar} ${${_cmdsVar}} PARENT_SCOPE) +endfunction() + +function (cotire_init_cotire_target_properties _target) + get_property(_isSet TARGET ${_target} PROPERTY COTIRE_ENABLE_PRECOMPILED_HEADER SET) + if (NOT _isSet) + set_property(TARGET ${_target} PROPERTY COTIRE_ENABLE_PRECOMPILED_HEADER TRUE) + endif() + get_property(_isSet TARGET ${_target} PROPERTY COTIRE_ADD_UNITY_BUILD SET) + if (NOT _isSet) + set_property(TARGET ${_target} PROPERTY COTIRE_ADD_UNITY_BUILD TRUE) + endif() + get_property(_isSet TARGET ${_target} PROPERTY COTIRE_ADD_CLEAN SET) + if (NOT _isSet) + set_property(TARGET ${_target} PROPERTY COTIRE_ADD_CLEAN FALSE) + endif() + get_property(_isSet TARGET ${_target} PROPERTY COTIRE_PREFIX_HEADER_IGNORE_PATH SET) + if (NOT _isSet) + set_property(TARGET ${_target} PROPERTY COTIRE_PREFIX_HEADER_IGNORE_PATH "${CMAKE_SOURCE_DIR}") + cotire_check_is_path_relative_to("${CMAKE_BINARY_DIR}" _isRelative "${CMAKE_SOURCE_DIR}") + if (NOT _isRelative) + set_property(TARGET ${_target} APPEND PROPERTY COTIRE_PREFIX_HEADER_IGNORE_PATH "${CMAKE_BINARY_DIR}") + endif() + endif() + get_property(_isSet TARGET ${_target} PROPERTY COTIRE_PREFIX_HEADER_INCLUDE_PATH SET) + if (NOT _isSet) + set_property(TARGET ${_target} PROPERTY COTIRE_PREFIX_HEADER_INCLUDE_PATH "") + endif() + get_property(_isSet TARGET ${_target} PROPERTY COTIRE_PREFIX_HEADER_INCLUDE_PRIORITY_PATH SET) + if (NOT _isSet) + set_property(TARGET ${_target} PROPERTY COTIRE_PREFIX_HEADER_INCLUDE_PRIORITY_PATH "") + endif() + get_property(_isSet TARGET ${_target} PROPERTY COTIRE_UNITY_SOURCE_PRE_UNDEFS SET) + if (NOT _isSet) + set_property(TARGET ${_target} PROPERTY COTIRE_UNITY_SOURCE_PRE_UNDEFS "") + endif() + get_property(_isSet TARGET ${_target} PROPERTY COTIRE_UNITY_SOURCE_POST_UNDEFS SET) + if (NOT _isSet) + set_property(TARGET ${_target} PROPERTY COTIRE_UNITY_SOURCE_POST_UNDEFS "") + endif() + get_property(_isSet TARGET ${_target} PROPERTY COTIRE_UNITY_LINK_LIBRARIES_INIT SET) + if (NOT _isSet) + set_property(TARGET ${_target} PROPERTY COTIRE_UNITY_LINK_LIBRARIES_INIT "COPY_UNITY") + endif() + get_property(_isSet TARGET ${_target} PROPERTY COTIRE_UNITY_SOURCE_MAXIMUM_NUMBER_OF_INCLUDES SET) + if (NOT _isSet) + if (COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES) + set_property(TARGET ${_target} PROPERTY COTIRE_UNITY_SOURCE_MAXIMUM_NUMBER_OF_INCLUDES "${COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES}") + else() + set_property(TARGET ${_target} PROPERTY COTIRE_UNITY_SOURCE_MAXIMUM_NUMBER_OF_INCLUDES "") + endif() + endif() +endfunction() + +function (cotire_make_target_message _target _languages _disableMsg _targetMsgVar) + get_target_property(_targetUsePCH ${_target} COTIRE_ENABLE_PRECOMPILED_HEADER) + get_target_property(_targetAddSCU ${_target} COTIRE_ADD_UNITY_BUILD) + string (REPLACE ";" " " _languagesStr "${_languages}") + math (EXPR _numberOfExcludedFiles "${ARGC} - 4") + if (_numberOfExcludedFiles EQUAL 0) + set (_excludedStr "") + elseif (COTIRE_VERBOSE OR _numberOfExcludedFiles LESS 4) + string (REPLACE ";" ", " _excludedStr "excluding ${ARGN}") + else() + set (_excludedStr "excluding ${_numberOfExcludedFiles} files") + endif() + set (_targetMsg "") + if (NOT _languages) + set (_targetMsg "Target ${_target} cannot be cotired.") + if (_disableMsg) + set (_targetMsg "${_targetMsg} ${_disableMsg}") + endif() + elseif (NOT _targetUsePCH AND NOT _targetAddSCU) + set (_targetMsg "${_languagesStr} target ${_target} cotired without unity build and precompiled header.") + if (_disableMsg) + set (_targetMsg "${_targetMsg} ${_disableMsg}") + endif() + elseif (NOT _targetUsePCH) + if (_excludedStr) + set (_targetMsg "${_languagesStr} target ${_target} cotired without precompiled header ${_excludedStr}.") + else() + set (_targetMsg "${_languagesStr} target ${_target} cotired without precompiled header.") + endif() + if (_disableMsg) + set (_targetMsg "${_targetMsg} ${_disableMsg}") + endif() + elseif (NOT _targetAddSCU) + if (_excludedStr) + set (_targetMsg "${_languagesStr} target ${_target} cotired without unity build ${_excludedStr}.") + else() + set (_targetMsg "${_languagesStr} target ${_target} cotired without unity build.") + endif() + else() + if (_excludedStr) + set (_targetMsg "${_languagesStr} target ${_target} cotired ${_excludedStr}.") + else() + set (_targetMsg "${_languagesStr} target ${_target} cotired.") + endif() + endif() + set (${_targetMsgVar} "${_targetMsg}" PARENT_SCOPE) +endfunction() + +function (cotire_choose_target_languages _target _targetLanguagesVar _wholeTargetVar) + set (_languages ${ARGN}) + set (_allSourceFiles "") + set (_allExcludedSourceFiles "") + set (_allCotiredSourceFiles "") + set (_targetLanguages "") + set (_pchEligibleTargetLanguages "") + get_target_property(_targetType ${_target} TYPE) + get_target_property(_targetSourceFiles ${_target} SOURCES) + get_target_property(_targetUsePCH ${_target} COTIRE_ENABLE_PRECOMPILED_HEADER) + get_target_property(_targetAddSCU ${_target} COTIRE_ADD_UNITY_BUILD) + set (_disableMsg "") + foreach (_language ${_languages}) + get_target_property(_prefixHeader ${_target} COTIRE_${_language}_PREFIX_HEADER) + get_target_property(_unityBuildFile ${_target} COTIRE_${_language}_UNITY_SOURCE) + if (_prefixHeader OR _unityBuildFile) + message (STATUS "cotire: target ${_target} has already been cotired.") + set (${_targetLanguagesVar} "" PARENT_SCOPE) + return() + endif() + if (_targetUsePCH AND "${_language}" MATCHES "^C|CXX$" AND DEFINED CMAKE_${_language}_COMPILER_ID) + if (CMAKE_${_language}_COMPILER_ID) + cotire_check_precompiled_header_support("${_language}" "${_target}" _disableMsg) + if (_disableMsg) + set (_targetUsePCH FALSE) + endif() + endif() + endif() + set (_sourceFiles "") + set (_excludedSources "") + set (_cotiredSources "") + cotire_filter_language_source_files(${_language} ${_target} _sourceFiles _excludedSources _cotiredSources ${_targetSourceFiles}) + if (_sourceFiles OR _excludedSources OR _cotiredSources) + list (APPEND _targetLanguages ${_language}) + endif() + if (_sourceFiles) + list (APPEND _allSourceFiles ${_sourceFiles}) + endif() + list (LENGTH _sourceFiles _numberOfSources) + if (NOT _numberOfSources LESS ${COTIRE_MINIMUM_NUMBER_OF_TARGET_SOURCES}) + list (APPEND _pchEligibleTargetLanguages ${_language}) + endif() + if (_excludedSources) + list (APPEND _allExcludedSourceFiles ${_excludedSources}) + endif() + if (_cotiredSources) + list (APPEND _allCotiredSourceFiles ${_cotiredSources}) + endif() + endforeach() + set (_targetMsgLevel STATUS) + if (NOT _targetLanguages) + string (REPLACE ";" " or " _languagesStr "${_languages}") + set (_disableMsg "No ${_languagesStr} source files.") + set (_targetUsePCH FALSE) + set (_targetAddSCU FALSE) + endif() + if (_targetUsePCH) + if (_allCotiredSourceFiles) + cotire_get_source_file_property_values(_cotireTargets COTIRE_TARGET ${_allCotiredSourceFiles}) + list (REMOVE_DUPLICATES _cotireTargets) + string (REPLACE ";" ", " _cotireTargetsStr "${_cotireTargets}") + set (_disableMsg "Target sources already include a precompiled header for target(s) ${_cotireTargets}.") + set (_disableMsg "${_disableMsg} Set target property COTIRE_ENABLE_PRECOMPILED_HEADER to FALSE for targets ${_target},") + set (_disableMsg "${_disableMsg} ${_cotireTargetsStr} to get a workable build system.") + set (_targetMsgLevel SEND_ERROR) + set (_targetUsePCH FALSE) + elseif (NOT _pchEligibleTargetLanguages) + set (_disableMsg "Too few applicable sources.") + set (_targetUsePCH FALSE) + elseif (XCODE AND _allExcludedSourceFiles) + # for Xcode, we cannot apply the precompiled header to individual sources, only to the whole target + set (_disableMsg "Exclusion of source files not supported for generator Xcode.") + set (_targetUsePCH FALSE) + elseif (XCODE AND "${_targetType}" STREQUAL "OBJECT_LIBRARY") + # for Xcode, we cannot apply the required PRE_BUILD action to generate the prefix header to an OBJECT_LIBRARY target + set (_disableMsg "Required PRE_BUILD action not supported for OBJECT_LIBRARY targets for generator Xcode.") + set (_targetUsePCH FALSE) + endif() + endif() + set_property(TARGET ${_target} PROPERTY COTIRE_ENABLE_PRECOMPILED_HEADER ${_targetUsePCH}) + set_property(TARGET ${_target} PROPERTY COTIRE_ADD_UNITY_BUILD ${_targetAddSCU}) + cotire_make_target_message(${_target} "${_targetLanguages}" "${_disableMsg}" _targetMsg ${_allExcludedSourceFiles}) + if (_targetMsg) + if (NOT DEFINED COTIREMSG_${_target}) + set (COTIREMSG_${_target} "") + endif() + if (COTIRE_VERBOSE OR NOT "${_targetMsgLevel}" STREQUAL "STATUS" OR + NOT "${COTIREMSG_${_target}}" STREQUAL "${_targetMsg}") + # cache message to avoid redundant messages on re-configure + set (COTIREMSG_${_target} "${_targetMsg}" CACHE INTERNAL "${_target} cotire message.") + message (${_targetMsgLevel} "${_targetMsg}") + endif() + endif() + list (LENGTH _targetLanguages _numberOfLanguages) + if (_numberOfLanguages GREATER 1 OR _allExcludedSourceFiles) + set (${_wholeTargetVar} FALSE PARENT_SCOPE) + else() + set (${_wholeTargetVar} TRUE PARENT_SCOPE) + endif() + set (${_targetLanguagesVar} ${_targetLanguages} PARENT_SCOPE) +endfunction() + +function (cotire_compute_unity_max_number_of_includes _target _maxIncludesVar) + set (_sourceFiles ${ARGN}) + get_target_property(_maxIncludes ${_target} COTIRE_UNITY_SOURCE_MAXIMUM_NUMBER_OF_INCLUDES) + if (_maxIncludes MATCHES "(-j|--parallel|--jobs) ?([0-9]*)") + set (_numberOfThreads "${CMAKE_MATCH_2}") + if (NOT _numberOfThreads) + # use all available cores + ProcessorCount(_numberOfThreads) + endif() + list (LENGTH _sourceFiles _numberOfSources) + math (EXPR _maxIncludes "(${_numberOfSources} + ${_numberOfThreads} - 1) / ${_numberOfThreads}") + elseif (NOT _maxIncludes MATCHES "[0-9]+") + set (_maxIncludes 0) + endif() + if (COTIRE_DEBUG) + message (STATUS "${_target} unity source max includes: ${_maxIncludes}") + endif() + set (${_maxIncludesVar} ${_maxIncludes} PARENT_SCOPE) +endfunction() + +function (cotire_process_target_language _language _configurations _target _wholeTarget _cmdsVar) + set (${_cmdsVar} "" PARENT_SCOPE) + get_target_property(_targetSourceFiles ${_target} SOURCES) + set (_sourceFiles "") + set (_excludedSources "") + set (_cotiredSources "") + cotire_filter_language_source_files(${_language} ${_target} _sourceFiles _excludedSources _cotiredSources ${_targetSourceFiles}) + if (NOT _sourceFiles AND NOT _cotiredSources) + return() + endif() + set (_cmds "") + # check for user provided unity source file list + get_property(_unitySourceFiles TARGET ${_target} PROPERTY COTIRE_${_language}_UNITY_SOURCE_INIT) + if (NOT _unitySourceFiles) + set (_unitySourceFiles ${_sourceFiles} ${_cotiredSources}) + endif() + cotire_generate_target_script( + ${_language} "${_configurations}" ${_target} _targetScript _targetConfigScript ${_unitySourceFiles}) + # set up unity files for parallel compilation + cotire_compute_unity_max_number_of_includes(${_target} _maxIncludes ${_unitySourceFiles}) + cotire_make_unity_source_file_paths(${_language} ${_target} ${_maxIncludes} _unityFiles ${_unitySourceFiles}) + list (LENGTH _unityFiles _numberOfUnityFiles) + if (_numberOfUnityFiles EQUAL 0) + return() + elseif (_numberOfUnityFiles GREATER 1) + cotire_setup_unity_generation_commands( + ${_language} ${_target} "${_targetScript}" "${_targetConfigScript}" "${_unityFiles}" _cmds ${_unitySourceFiles}) + endif() + # set up single unity file for prefix header generation + cotire_make_single_unity_source_file_path(${_language} ${_target} _unityFile) + cotire_setup_unity_generation_commands( + ${_language} ${_target} "${_targetScript}" "${_targetConfigScript}" "${_unityFile}" _cmds ${_unitySourceFiles}) + cotire_make_prefix_file_path(${_language} ${_target} _prefixFile) + # set up prefix header + if (_prefixFile) + # check for user provided prefix header files + get_property(_prefixHeaderFiles TARGET ${_target} PROPERTY COTIRE_${_language}_PREFIX_HEADER_INIT) + if (_prefixHeaderFiles) + cotire_setup_prefix_generation_from_provided_command( + ${_language} ${_target} "${_targetConfigScript}" "${_prefixFile}" _cmds ${_prefixHeaderFiles}) + else() + cotire_setup_prefix_generation_from_unity_command( + ${_language} ${_target} "${_targetConfigScript}" "${_prefixFile}" "${_unityFile}" _cmds ${_unitySourceFiles}) + endif() + # check if selected language has enough sources at all + list (LENGTH _sourceFiles _numberOfSources) + if (_numberOfSources LESS ${COTIRE_MINIMUM_NUMBER_OF_TARGET_SOURCES}) + set (_targetUsePCH FALSE) + else() + get_target_property(_targetUsePCH ${_target} COTIRE_ENABLE_PRECOMPILED_HEADER) + endif() + if (_targetUsePCH) + cotire_make_pch_file_path(${_language} ${_target} _pchFile) + if (_pchFile) + # first file in _sourceFiles is passed as the host file + cotire_setup_pch_file_compilation( + ${_language} ${_target} "${_targetConfigScript}" "${_prefixFile}" "${_pchFile}" ${_sourceFiles}) + cotire_setup_pch_file_inclusion( + ${_language} ${_target} ${_wholeTarget} "${_prefixFile}" "${_pchFile}" ${_sourceFiles}) + endif() + elseif (_prefixHeaderFiles) + # user provided prefix header must be included unconditionally + cotire_setup_prefix_file_inclusion(${_language} ${_target} "${_prefixFile}" ${_sourceFiles}) + endif() + endif() + # mark target as cotired for language + set_property(TARGET ${_target} PROPERTY COTIRE_${_language}_UNITY_SOURCE "${_unityFiles}") + if (_prefixFile) + set_property(TARGET ${_target} PROPERTY COTIRE_${_language}_PREFIX_HEADER "${_prefixFile}") + if (_targetUsePCH AND _pchFile) + set_property(TARGET ${_target} PROPERTY COTIRE_${_language}_PRECOMPILED_HEADER "${_pchFile}") + endif() + endif() + set (${_cmdsVar} ${_cmds} PARENT_SCOPE) +endfunction() + +function (cotire_setup_clean_target _target) + set (_cleanTargetName "${_target}${COTIRE_CLEAN_TARGET_SUFFIX}") + if (NOT TARGET "${_cleanTargetName}") + cotire_set_cmd_to_prologue(_cmds) + get_filename_component(_outputDir "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_CFG_INTDIR}" ABSOLUTE) + list (APPEND _cmds -P "${COTIRE_CMAKE_MODULE_FILE}" "cleanup" "${_outputDir}" "${COTIRE_INTDIR}" "${_target}") + add_custom_target(${_cleanTargetName} + COMMAND ${_cmds} + WORKING_DIRECTORY "${CMAKE_BINARY_DIR}" + COMMENT "Cleaning up target ${_target} cotire generated files" + VERBATIM) + cotire_init_target("${_cleanTargetName}") + endif() +endfunction() + +function (cotire_setup_pch_target _languages _configurations _target) + if ("${CMAKE_GENERATOR}" MATCHES "Make|Ninja") + # for makefile based generators, we add a custom target to trigger the generation of the cotire related files + set (_dependsFiles "") + foreach (_language ${_languages}) + set (_props COTIRE_${_language}_PREFIX_HEADER COTIRE_${_language}_UNITY_SOURCE) + if (NOT CMAKE_${_language}_COMPILER_ID MATCHES "MSVC|Intel") + # Visual Studio and Intel only create precompiled header as a side effect + list (INSERT _props 0 COTIRE_${_language}_PRECOMPILED_HEADER) + endif() + cotire_get_first_set_property_value(_dependsFile TARGET ${_target} ${_props}) + if (_dependsFile) + list (APPEND _dependsFiles "${_dependsFile}") + endif() + endforeach() + if (_dependsFiles) + set (_pchTargetName "${_target}${COTIRE_PCH_TARGET_SUFFIX}") + add_custom_target("${_pchTargetName}" DEPENDS ${_dependsFiles}) + cotire_init_target("${_pchTargetName}") + cotire_add_to_pch_all_target(${_pchTargetName}) + endif() + else() + # for other generators, we add the "clean all" target to clean up the precompiled header + cotire_setup_clean_all_target() + endif() +endfunction() + +function (cotire_filter_object_libraries _target _objectLibrariesVar) + set (_objectLibraries "") + foreach (_source ${ARGN}) + if (_source MATCHES "^\\$$") + list (APPEND _objectLibraries "${_source}") + endif() + endforeach() + set (${_objectLibrariesVar} ${_objectLibraries} PARENT_SCOPE) +endfunction() + +function (cotire_collect_unity_target_sources _target _languages _unityTargetSourcesVar) + get_target_property(_targetSourceFiles ${_target} SOURCES) + set (_unityTargetSources ${_targetSourceFiles}) + foreach (_language ${_languages}) + get_property(_unityFiles TARGET ${_target} PROPERTY COTIRE_${_language}_UNITY_SOURCE) + if (_unityFiles) + # remove source files that are included in the unity source + set (_sourceFiles "") + set (_excludedSources "") + set (_cotiredSources "") + cotire_filter_language_source_files(${_language} ${_target} _sourceFiles _excludedSources _cotiredSources ${_targetSourceFiles}) + if (_sourceFiles OR _cotiredSources) + list (REMOVE_ITEM _unityTargetSources ${_sourceFiles} ${_cotiredSources}) + endif() + # add unity source files instead + list (APPEND _unityTargetSources ${_unityFiles}) + endif() + endforeach() + get_target_property(_linkLibrariesStrategy ${_target} COTIRE_UNITY_LINK_LIBRARIES_INIT) + if ("${_linkLibrariesStrategy}" MATCHES "^COPY_UNITY$") + cotire_filter_object_libraries(${_target} _objectLibraries ${_targetSourceFiles}) + if (_objectLibraries) + cotire_map_libraries("${_linkLibrariesStrategy}" _unityObjectLibraries ${_objectLibraries}) + list (REMOVE_ITEM _unityTargetSources ${_objectLibraries}) + list (APPEND _unityTargetSources ${_unityObjectLibraries}) + endif() + endif() + set (${_unityTargetSourcesVar} ${_unityTargetSources} PARENT_SCOPE) +endfunction() + +function (cotire_setup_unity_target_pch_usage _languages _target) + foreach (_language ${_languages}) + get_property(_unityFiles TARGET ${_target} PROPERTY COTIRE_${_language}_UNITY_SOURCE) + if (_unityFiles) + get_property(_userPrefixFile TARGET ${_target} PROPERTY COTIRE_${_language}_PREFIX_HEADER_INIT) + get_property(_prefixFile TARGET ${_target} PROPERTY COTIRE_${_language}_PREFIX_HEADER) + if (_userPrefixFile AND _prefixFile) + # user provided prefix header must be included unconditionally by unity sources + cotire_setup_prefix_file_inclusion(${_language} ${_target} "${_prefixFile}" ${_unityFiles}) + endif() + endif() + endforeach() +endfunction() + +function (cotire_setup_unity_build_target _languages _configurations _target) + get_target_property(_unityTargetName ${_target} COTIRE_UNITY_TARGET_NAME) + if (NOT _unityTargetName) + set (_unityTargetName "${_target}${COTIRE_UNITY_BUILD_TARGET_SUFFIX}") + endif() + # determine unity target sub type + get_target_property(_targetType ${_target} TYPE) + if ("${_targetType}" STREQUAL "EXECUTABLE") + set (_unityTargetSubType "") + elseif (_targetType MATCHES "(STATIC|SHARED|MODULE|OBJECT)_LIBRARY") + set (_unityTargetSubType "${CMAKE_MATCH_1}") + else() + message (WARNING "cotire: target ${_target} has unknown target type ${_targetType}.") + return() + endif() + # determine unity target sources + set (_unityTargetSources "") + cotire_collect_unity_target_sources(${_target} "${_languages}" _unityTargetSources) + # handle automatic Qt processing + get_target_property(_targetAutoMoc ${_target} AUTOMOC) + get_target_property(_targetAutoUic ${_target} AUTOUIC) + get_target_property(_targetAutoRcc ${_target} AUTORCC) + if (_targetAutoMoc OR _targetAutoUic OR _targetAutoRcc) + # if the original target sources are subject to CMake's automatic Qt processing, + # also include implicitly generated _automoc.cpp file + if (CMAKE_VERSION VERSION_LESS "3.8.0") + list (APPEND _unityTargetSources "${_target}_automoc.cpp") + set_property (SOURCE "${_target}_automoc.cpp" PROPERTY GENERATED TRUE) + else() + list (APPEND _unityTargetSources "${_target}_autogen/moc_compilation.cpp") + set_property (SOURCE "${_target}_autogen/moc_compilation.cpp" PROPERTY GENERATED TRUE) + endif() + endif() + # prevent AUTOMOC, AUTOUIC and AUTORCC properties from being set when the unity target is created + set (CMAKE_AUTOMOC OFF) + set (CMAKE_AUTOUIC OFF) + set (CMAKE_AUTORCC OFF) + if (COTIRE_DEBUG) + message (STATUS "add target ${_targetType} ${_unityTargetName} ${_unityTargetSubType} EXCLUDE_FROM_ALL ${_unityTargetSources}") + endif() + # generate unity target + if ("${_targetType}" STREQUAL "EXECUTABLE") + add_executable(${_unityTargetName} ${_unityTargetSubType} EXCLUDE_FROM_ALL ${_unityTargetSources}) + else() + add_library(${_unityTargetName} ${_unityTargetSubType} EXCLUDE_FROM_ALL ${_unityTargetSources}) + endif() + if ("${CMAKE_GENERATOR}" MATCHES "Visual Studio") + # depend on original target's automoc target, if it exists + if (TARGET ${_target}_automoc) + add_dependencies(${_unityTargetName} ${_target}_automoc) + endif() + else() + if (_targetAutoMoc OR _targetAutoUic OR _targetAutoRcc) + # depend on the original target's implicity generated _automoc target + if (CMAKE_VERSION VERSION_LESS "3.8.0") + add_dependencies(${_unityTargetName} ${_target}_automoc) + else() + add_dependencies(${_unityTargetName} ${_target}_autogen) + endif() + endif() + endif() + # copy output location properties + set (_outputDirProperties + ARCHIVE_OUTPUT_DIRECTORY ARCHIVE_OUTPUT_DIRECTORY_ + LIBRARY_OUTPUT_DIRECTORY LIBRARY_OUTPUT_DIRECTORY_ + RUNTIME_OUTPUT_DIRECTORY RUNTIME_OUTPUT_DIRECTORY_) + if (COTIRE_UNITY_OUTPUT_DIRECTORY) + set (_setDefaultOutputDir TRUE) + if (IS_ABSOLUTE "${COTIRE_UNITY_OUTPUT_DIRECTORY}") + set (_outputDir "${COTIRE_UNITY_OUTPUT_DIRECTORY}") + else() + # append relative COTIRE_UNITY_OUTPUT_DIRECTORY to target's actual output directory + cotire_copy_set_properties("${_configurations}" TARGET ${_target} ${_unityTargetName} ${_outputDirProperties}) + cotire_resolve_config_properties("${_configurations}" _properties ${_outputDirProperties}) + foreach (_property ${_properties}) + get_property(_outputDir TARGET ${_target} PROPERTY ${_property}) + if (_outputDir) + get_filename_component(_outputDir "${_outputDir}/${COTIRE_UNITY_OUTPUT_DIRECTORY}" ABSOLUTE) + set_property(TARGET ${_unityTargetName} PROPERTY ${_property} "${_outputDir}") + set (_setDefaultOutputDir FALSE) + endif() + endforeach() + if (_setDefaultOutputDir) + get_filename_component(_outputDir "${CMAKE_CURRENT_BINARY_DIR}/${COTIRE_UNITY_OUTPUT_DIRECTORY}" ABSOLUTE) + endif() + endif() + if (_setDefaultOutputDir) + set_target_properties(${_unityTargetName} PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${_outputDir}" + LIBRARY_OUTPUT_DIRECTORY "${_outputDir}" + RUNTIME_OUTPUT_DIRECTORY "${_outputDir}") + endif() + else() + cotire_copy_set_properties("${_configurations}" TARGET ${_target} ${_unityTargetName} + ${_outputDirProperties}) + endif() + # copy output name + cotire_copy_set_properties("${_configurations}" TARGET ${_target} ${_unityTargetName} + ARCHIVE_OUTPUT_NAME ARCHIVE_OUTPUT_NAME_ + LIBRARY_OUTPUT_NAME LIBRARY_OUTPUT_NAME_ + OUTPUT_NAME OUTPUT_NAME_ + RUNTIME_OUTPUT_NAME RUNTIME_OUTPUT_NAME_ + PREFIX _POSTFIX SUFFIX + IMPORT_PREFIX IMPORT_SUFFIX) + # copy compile stuff + cotire_copy_set_properties("${_configurations}" TARGET ${_target} ${_unityTargetName} + COMPILE_DEFINITIONS COMPILE_DEFINITIONS_ + COMPILE_FLAGS COMPILE_OPTIONS + Fortran_FORMAT Fortran_MODULE_DIRECTORY + INCLUDE_DIRECTORIES + INTERPROCEDURAL_OPTIMIZATION INTERPROCEDURAL_OPTIMIZATION_ + POSITION_INDEPENDENT_CODE + C_COMPILER_LAUNCHER CXX_COMPILER_LAUNCHER + C_INCLUDE_WHAT_YOU_USE CXX_INCLUDE_WHAT_YOU_USE + C_VISIBILITY_PRESET CXX_VISIBILITY_PRESET VISIBILITY_INLINES_HIDDEN + C_CLANG_TIDY CXX_CLANG_TIDY) + # copy compile features + cotire_copy_set_properties("${_configurations}" TARGET ${_target} ${_unityTargetName} + C_EXTENSIONS C_STANDARD C_STANDARD_REQUIRED + CXX_EXTENSIONS CXX_STANDARD CXX_STANDARD_REQUIRED + COMPILE_FEATURES) + # copy interface stuff + cotire_copy_set_properties("${_configurations}" TARGET ${_target} ${_unityTargetName} + COMPATIBLE_INTERFACE_BOOL COMPATIBLE_INTERFACE_NUMBER_MAX COMPATIBLE_INTERFACE_NUMBER_MIN + COMPATIBLE_INTERFACE_STRING + INTERFACE_COMPILE_DEFINITIONS INTERFACE_COMPILE_FEATURES INTERFACE_COMPILE_OPTIONS + INTERFACE_INCLUDE_DIRECTORIES INTERFACE_SOURCES + INTERFACE_POSITION_INDEPENDENT_CODE INTERFACE_SYSTEM_INCLUDE_DIRECTORIES + INTERFACE_AUTOUIC_OPTIONS NO_SYSTEM_FROM_IMPORTED) + # copy link stuff + cotire_copy_set_properties("${_configurations}" TARGET ${_target} ${_unityTargetName} + BUILD_WITH_INSTALL_RPATH INSTALL_RPATH INSTALL_RPATH_USE_LINK_PATH SKIP_BUILD_RPATH + LINKER_LANGUAGE LINK_DEPENDS LINK_DEPENDS_NO_SHARED + LINK_FLAGS LINK_FLAGS_ + LINK_INTERFACE_LIBRARIES LINK_INTERFACE_LIBRARIES_ + LINK_INTERFACE_MULTIPLICITY LINK_INTERFACE_MULTIPLICITY_ + LINK_SEARCH_START_STATIC LINK_SEARCH_END_STATIC + STATIC_LIBRARY_FLAGS STATIC_LIBRARY_FLAGS_ + NO_SONAME SOVERSION VERSION + LINK_WHAT_YOU_USE BUILD_RPATH) + # copy cmake stuff + cotire_copy_set_properties("${_configurations}" TARGET ${_target} ${_unityTargetName} + IMPLICIT_DEPENDS_INCLUDE_TRANSFORM RULE_LAUNCH_COMPILE RULE_LAUNCH_CUSTOM RULE_LAUNCH_LINK) + # copy Apple platform specific stuff + cotire_copy_set_properties("${_configurations}" TARGET ${_target} ${_unityTargetName} + BUNDLE BUNDLE_EXTENSION FRAMEWORK FRAMEWORK_VERSION INSTALL_NAME_DIR + MACOSX_BUNDLE MACOSX_BUNDLE_INFO_PLIST MACOSX_FRAMEWORK_INFO_PLIST MACOSX_RPATH + OSX_ARCHITECTURES OSX_ARCHITECTURES_ PRIVATE_HEADER PUBLIC_HEADER RESOURCE XCTEST + IOS_INSTALL_COMBINED XCODE_EXPLICIT_FILE_TYPE XCODE_PRODUCT_TYPE) + # copy Windows platform specific stuff + cotire_copy_set_properties("${_configurations}" TARGET ${_target} ${_unityTargetName} + GNUtoMS + COMPILE_PDB_NAME COMPILE_PDB_NAME_ + COMPILE_PDB_OUTPUT_DIRECTORY COMPILE_PDB_OUTPUT_DIRECTORY_ + PDB_NAME PDB_NAME_ PDB_OUTPUT_DIRECTORY PDB_OUTPUT_DIRECTORY_ + VS_DESKTOP_EXTENSIONS_VERSION VS_DOTNET_REFERENCES VS_DOTNET_TARGET_FRAMEWORK_VERSION + VS_GLOBAL_KEYWORD VS_GLOBAL_PROJECT_TYPES VS_GLOBAL_ROOTNAMESPACE + VS_IOT_EXTENSIONS_VERSION VS_IOT_STARTUP_TASK + VS_KEYWORD VS_MOBILE_EXTENSIONS_VERSION + VS_SCC_AUXPATH VS_SCC_LOCALPATH VS_SCC_PROJECTNAME VS_SCC_PROVIDER + VS_WINDOWS_TARGET_PLATFORM_MIN_VERSION + VS_WINRT_COMPONENT VS_WINRT_EXTENSIONS VS_WINRT_REFERENCES + WIN32_EXECUTABLE WINDOWS_EXPORT_ALL_SYMBOLS + DEPLOYMENT_REMOTE_DIRECTORY VS_CONFIGURATION_TYPE + VS_SDK_REFERENCES VS_USER_PROPS VS_DEBUGGER_WORKING_DIRECTORY) + # copy Android platform specific stuff + cotire_copy_set_properties("${_configurations}" TARGET ${_target} ${_unityTargetName} + ANDROID_API ANDROID_API_MIN ANDROID_GUI + ANDROID_ANT_ADDITIONAL_OPTIONS ANDROID_ARCH ANDROID_ASSETS_DIRECTORIES + ANDROID_JAR_DEPENDENCIES ANDROID_JAR_DIRECTORIES ANDROID_JAVA_SOURCE_DIR + ANDROID_NATIVE_LIB_DEPENDENCIES ANDROID_NATIVE_LIB_DIRECTORIES + ANDROID_PROCESS_MAX ANDROID_PROGUARD ANDROID_PROGUARD_CONFIG_PATH + ANDROID_SECURE_PROPS_PATH ANDROID_SKIP_ANT_STEP ANDROID_STL_TYPE) + # use output name from original target + get_target_property(_targetOutputName ${_unityTargetName} OUTPUT_NAME) + if (NOT _targetOutputName) + set_property(TARGET ${_unityTargetName} PROPERTY OUTPUT_NAME "${_target}") + endif() + # use export symbol from original target + cotire_get_target_export_symbol("${_target}" _defineSymbol) + if (_defineSymbol) + set_property(TARGET ${_unityTargetName} PROPERTY DEFINE_SYMBOL "${_defineSymbol}") + if ("${_targetType}" STREQUAL "EXECUTABLE") + set_property(TARGET ${_unityTargetName} PROPERTY ENABLE_EXPORTS TRUE) + endif() + endif() + cotire_init_target(${_unityTargetName}) + cotire_add_to_unity_all_target(${_unityTargetName}) + set_property(TARGET ${_target} PROPERTY COTIRE_UNITY_TARGET_NAME "${_unityTargetName}") +endfunction(cotire_setup_unity_build_target) + +function (cotire_target _target) + set(_options "") + set(_oneValueArgs "") + set(_multiValueArgs LANGUAGES CONFIGURATIONS) + cmake_parse_arguments(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN}) + if (NOT _option_LANGUAGES) + get_property (_option_LANGUAGES GLOBAL PROPERTY ENABLED_LANGUAGES) + endif() + if (NOT _option_CONFIGURATIONS) + cotire_get_configuration_types(_option_CONFIGURATIONS) + endif() + # check if cotire can be applied to target at all + cotire_is_target_supported(${_target} _isSupported) + if (NOT _isSupported) + get_target_property(_imported ${_target} IMPORTED) + get_target_property(_targetType ${_target} TYPE) + if (_imported) + message (WARNING "cotire: imported ${_targetType} target ${_target} cannot be cotired.") + else() + message (STATUS "cotire: ${_targetType} target ${_target} cannot be cotired.") + endif() + return() + endif() + # resolve alias + get_target_property(_aliasName ${_target} ALIASED_TARGET) + if (_aliasName) + if (COTIRE_DEBUG) + message (STATUS "${_target} is an alias. Applying cotire to aliased target ${_aliasName} instead.") + endif() + set (_target ${_aliasName}) + endif() + # check if target needs to be cotired for build type + # when using configuration types, the test is performed at build time + cotire_init_cotire_target_properties(${_target}) + if (NOT CMAKE_CONFIGURATION_TYPES) + if (CMAKE_BUILD_TYPE) + list (FIND _option_CONFIGURATIONS "${CMAKE_BUILD_TYPE}" _index) + else() + list (FIND _option_CONFIGURATIONS "None" _index) + endif() + if (_index EQUAL -1) + if (COTIRE_DEBUG) + message (STATUS "CMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE} not cotired (${_option_CONFIGURATIONS})") + endif() + return() + endif() + endif() + # when not using configuration types, immediately create cotire intermediate dir + if (NOT CMAKE_CONFIGURATION_TYPES) + cotire_get_intermediate_dir(_baseDir) + file (MAKE_DIRECTORY "${_baseDir}") + endif() + # choose languages that apply to the target + cotire_choose_target_languages("${_target}" _targetLanguages _wholeTarget ${_option_LANGUAGES}) + if (NOT _targetLanguages) + return() + endif() + set (_cmds "") + foreach (_language ${_targetLanguages}) + cotire_process_target_language("${_language}" "${_option_CONFIGURATIONS}" ${_target} ${_wholeTarget} _cmd) + if (_cmd) + list (APPEND _cmds ${_cmd}) + endif() + endforeach() + get_target_property(_targetAddSCU ${_target} COTIRE_ADD_UNITY_BUILD) + if (_targetAddSCU) + cotire_setup_unity_build_target("${_targetLanguages}" "${_option_CONFIGURATIONS}" ${_target}) + endif() + get_target_property(_targetUsePCH ${_target} COTIRE_ENABLE_PRECOMPILED_HEADER) + if (_targetUsePCH) + cotire_setup_target_pch_usage("${_targetLanguages}" ${_target} ${_wholeTarget} ${_cmds}) + cotire_setup_pch_target("${_targetLanguages}" "${_option_CONFIGURATIONS}" ${_target}) + if (_targetAddSCU) + cotire_setup_unity_target_pch_usage("${_targetLanguages}" ${_target}) + endif() + endif() + get_target_property(_targetAddCleanTarget ${_target} COTIRE_ADD_CLEAN) + if (_targetAddCleanTarget) + cotire_setup_clean_target(${_target}) + endif() +endfunction(cotire_target) + +function (cotire_map_libraries _strategy _mappedLibrariesVar) + set (_mappedLibraries "") + foreach (_library ${ARGN}) + if (_library MATCHES "^\\$$") + set (_libraryName "${CMAKE_MATCH_1}") + set (_linkOnly TRUE) + set (_objectLibrary FALSE) + elseif (_library MATCHES "^\\$$") + set (_libraryName "${CMAKE_MATCH_1}") + set (_linkOnly FALSE) + set (_objectLibrary TRUE) + else() + set (_libraryName "${_library}") + set (_linkOnly FALSE) + set (_objectLibrary FALSE) + endif() + if ("${_strategy}" MATCHES "COPY_UNITY") + cotire_is_target_supported(${_libraryName} _isSupported) + if (_isSupported) + # use target's corresponding unity target, if available + get_target_property(_libraryUnityTargetName ${_libraryName} COTIRE_UNITY_TARGET_NAME) + if (TARGET "${_libraryUnityTargetName}") + if (_linkOnly) + list (APPEND _mappedLibraries "$") + elseif (_objectLibrary) + list (APPEND _mappedLibraries "$") + else() + list (APPEND _mappedLibraries "${_libraryUnityTargetName}") + endif() + else() + list (APPEND _mappedLibraries "${_library}") + endif() + else() + list (APPEND _mappedLibraries "${_library}") + endif() + else() + list (APPEND _mappedLibraries "${_library}") + endif() + endforeach() + list (REMOVE_DUPLICATES _mappedLibraries) + set (${_mappedLibrariesVar} ${_mappedLibraries} PARENT_SCOPE) +endfunction() + +function (cotire_target_link_libraries _target) + cotire_is_target_supported(${_target} _isSupported) + if (NOT _isSupported) + return() + endif() + get_target_property(_unityTargetName ${_target} COTIRE_UNITY_TARGET_NAME) + if (TARGET "${_unityTargetName}") + get_target_property(_linkLibrariesStrategy ${_target} COTIRE_UNITY_LINK_LIBRARIES_INIT) + if (COTIRE_DEBUG) + message (STATUS "unity target ${_unityTargetName} link strategy: ${_linkLibrariesStrategy}") + endif() + if ("${_linkLibrariesStrategy}" MATCHES "^(COPY|COPY_UNITY)$") + get_target_property(_linkLibraries ${_target} LINK_LIBRARIES) + if (_linkLibraries) + cotire_map_libraries("${_linkLibrariesStrategy}" _unityLinkLibraries ${_linkLibraries}) + set_target_properties(${_unityTargetName} PROPERTIES LINK_LIBRARIES "${_unityLinkLibraries}") + if (COTIRE_DEBUG) + message (STATUS "unity target ${_unityTargetName} link libraries: ${_unityLinkLibraries}") + endif() + endif() + get_target_property(_interfaceLinkLibraries ${_target} INTERFACE_LINK_LIBRARIES) + if (_interfaceLinkLibraries) + cotire_map_libraries("${_linkLibrariesStrategy}" _unityLinkInterfaceLibraries ${_interfaceLinkLibraries}) + set_target_properties(${_unityTargetName} PROPERTIES INTERFACE_LINK_LIBRARIES "${_unityLinkInterfaceLibraries}") + if (COTIRE_DEBUG) + message (STATUS "unity target ${_unityTargetName} interface link libraries: ${_unityLinkInterfaceLibraries}") + endif() + endif() + endif() + endif() +endfunction(cotire_target_link_libraries) + +function (cotire_cleanup _binaryDir _cotireIntermediateDirName _targetName) + if (_targetName) + file (GLOB_RECURSE _cotireFiles "${_binaryDir}/${_targetName}*.*") + else() + file (GLOB_RECURSE _cotireFiles "${_binaryDir}/*.*") + endif() + # filter files in intermediate directory + set (_filesToRemove "") + foreach (_file ${_cotireFiles}) + get_filename_component(_dir "${_file}" DIRECTORY) + get_filename_component(_dirName "${_dir}" NAME) + if ("${_dirName}" STREQUAL "${_cotireIntermediateDirName}") + list (APPEND _filesToRemove "${_file}") + endif() + endforeach() + if (_filesToRemove) + if (COTIRE_VERBOSE) + message (STATUS "cleaning up ${_filesToRemove}") + endif() + file (REMOVE ${_filesToRemove}) + endif() +endfunction() + +function (cotire_init_target _targetName) + if (COTIRE_TARGETS_FOLDER) + set_target_properties(${_targetName} PROPERTIES FOLDER "${COTIRE_TARGETS_FOLDER}") + endif() + set_target_properties(${_targetName} PROPERTIES EXCLUDE_FROM_ALL TRUE) + if (MSVC_IDE) + set_target_properties(${_targetName} PROPERTIES EXCLUDE_FROM_DEFAULT_BUILD TRUE) + endif() +endfunction() + +function (cotire_add_to_pch_all_target _pchTargetName) + set (_targetName "${COTIRE_PCH_ALL_TARGET_NAME}") + if (NOT TARGET "${_targetName}") + add_custom_target("${_targetName}" + WORKING_DIRECTORY "${CMAKE_BINARY_DIR}" + VERBATIM) + cotire_init_target("${_targetName}") + endif() + cotire_setup_clean_all_target() + add_dependencies(${_targetName} ${_pchTargetName}) +endfunction() + +function (cotire_add_to_unity_all_target _unityTargetName) + set (_targetName "${COTIRE_UNITY_BUILD_ALL_TARGET_NAME}") + if (NOT TARGET "${_targetName}") + add_custom_target("${_targetName}" + WORKING_DIRECTORY "${CMAKE_BINARY_DIR}" + VERBATIM) + cotire_init_target("${_targetName}") + endif() + cotire_setup_clean_all_target() + add_dependencies(${_targetName} ${_unityTargetName}) +endfunction() + +function (cotire_setup_clean_all_target) + set (_targetName "${COTIRE_CLEAN_ALL_TARGET_NAME}") + if (NOT TARGET "${_targetName}") + cotire_set_cmd_to_prologue(_cmds) + list (APPEND _cmds -P "${COTIRE_CMAKE_MODULE_FILE}" "cleanup" "${CMAKE_BINARY_DIR}" "${COTIRE_INTDIR}") + add_custom_target(${_targetName} + COMMAND ${_cmds} + WORKING_DIRECTORY "${CMAKE_BINARY_DIR}" + COMMENT "Cleaning up all cotire generated files" + VERBATIM) + cotire_init_target("${_targetName}") + endif() +endfunction() + +function (cotire) + set(_options "") + set(_oneValueArgs "") + set(_multiValueArgs LANGUAGES CONFIGURATIONS) + cmake_parse_arguments(_option "${_options}" "${_oneValueArgs}" "${_multiValueArgs}" ${ARGN}) + set (_targets ${_option_UNPARSED_ARGUMENTS}) + foreach (_target ${_targets}) + if (TARGET ${_target}) + cotire_target(${_target} LANGUAGES ${_option_LANGUAGES} CONFIGURATIONS ${_option_CONFIGURATIONS}) + else() + message (WARNING "cotire: ${_target} is not a target.") + endif() + endforeach() + foreach (_target ${_targets}) + if (TARGET ${_target}) + cotire_target_link_libraries(${_target}) + endif() + endforeach() +endfunction() + +if (CMAKE_SCRIPT_MODE_FILE) + + # cotire is being run in script mode + # locate -P on command args + set (COTIRE_ARGC -1) + foreach (_index RANGE ${CMAKE_ARGC}) + if (COTIRE_ARGC GREATER -1) + set (COTIRE_ARGV${COTIRE_ARGC} "${CMAKE_ARGV${_index}}") + math (EXPR COTIRE_ARGC "${COTIRE_ARGC} + 1") + elseif ("${CMAKE_ARGV${_index}}" STREQUAL "-P") + set (COTIRE_ARGC 0) + endif() + endforeach() + + # include target script if available + if ("${COTIRE_ARGV2}" MATCHES "\\.cmake$") + # the included target scripts sets up additional variables relating to the target (e.g., COTIRE_TARGET_SOURCES) + include("${COTIRE_ARGV2}") + endif() + + if (COTIRE_DEBUG) + message (STATUS "${COTIRE_ARGV0} ${COTIRE_ARGV1} ${COTIRE_ARGV2} ${COTIRE_ARGV3} ${COTIRE_ARGV4} ${COTIRE_ARGV5}") + endif() + + if (NOT COTIRE_BUILD_TYPE) + set (COTIRE_BUILD_TYPE "None") + endif() + string (TOUPPER "${COTIRE_BUILD_TYPE}" _upperConfig) + set (_includeDirs ${COTIRE_TARGET_INCLUDE_DIRECTORIES_${_upperConfig}}) + set (_systemIncludeDirs ${COTIRE_TARGET_SYSTEM_INCLUDE_DIRECTORIES_${_upperConfig}}) + set (_compileDefinitions ${COTIRE_TARGET_COMPILE_DEFINITIONS_${_upperConfig}}) + set (_compileFlags ${COTIRE_TARGET_COMPILE_FLAGS_${_upperConfig}}) + # check if target has been cotired for actual build type COTIRE_BUILD_TYPE + list (FIND COTIRE_TARGET_CONFIGURATION_TYPES "${COTIRE_BUILD_TYPE}" _index) + if (_index GREATER -1) + set (_sources ${COTIRE_TARGET_SOURCES}) + set (_sourcesDefinitions ${COTIRE_TARGET_SOURCES_COMPILE_DEFINITIONS_${_upperConfig}}) + else() + if (COTIRE_DEBUG) + message (STATUS "COTIRE_BUILD_TYPE=${COTIRE_BUILD_TYPE} not cotired (${COTIRE_TARGET_CONFIGURATION_TYPES})") + endif() + set (_sources "") + set (_sourcesDefinitions "") + endif() + set (_targetPreUndefs ${COTIRE_TARGET_PRE_UNDEFS}) + set (_targetPostUndefs ${COTIRE_TARGET_POST_UNDEFS}) + set (_sourcesPreUndefs ${COTIRE_TARGET_SOURCES_PRE_UNDEFS}) + set (_sourcesPostUndefs ${COTIRE_TARGET_SOURCES_POST_UNDEFS}) + + if ("${COTIRE_ARGV1}" STREQUAL "unity") + + if (XCODE) + # executing pre-build action under Xcode, check dependency on target script + set (_dependsOption DEPENDS "${COTIRE_ARGV2}") + else() + # executing custom command, no need to re-check for dependencies + set (_dependsOption "") + endif() + + cotire_select_unity_source_files("${COTIRE_ARGV3}" _sources ${_sources}) + + cotire_generate_unity_source( + "${COTIRE_ARGV3}" ${_sources} + LANGUAGE "${COTIRE_TARGET_LANGUAGE}" + SOURCES_COMPILE_DEFINITIONS ${_sourcesDefinitions} + PRE_UNDEFS ${_targetPreUndefs} + POST_UNDEFS ${_targetPostUndefs} + SOURCES_PRE_UNDEFS ${_sourcesPreUndefs} + SOURCES_POST_UNDEFS ${_sourcesPostUndefs} + ${_dependsOption}) + + elseif ("${COTIRE_ARGV1}" STREQUAL "prefix") + + if (XCODE) + # executing pre-build action under Xcode, check dependency on unity file and prefix dependencies + set (_dependsOption DEPENDS "${COTIRE_ARGV4}" ${COTIRE_TARGET_PREFIX_DEPENDS}) + else() + # executing custom command, no need to re-check for dependencies + set (_dependsOption "") + endif() + + set (_files "") + foreach (_index RANGE 4 ${COTIRE_ARGC}) + if (COTIRE_ARGV${_index}) + list (APPEND _files "${COTIRE_ARGV${_index}}") + endif() + endforeach() + + cotire_generate_prefix_header( + "${COTIRE_ARGV3}" ${_files} + COMPILER_LAUNCHER "${COTIRE_TARGET_${COTIRE_TARGET_LANGUAGE}_COMPILER_LAUNCHER}" + COMPILER_EXECUTABLE "${CMAKE_${COTIRE_TARGET_LANGUAGE}_COMPILER}" + COMPILER_ARG1 ${CMAKE_${COTIRE_TARGET_LANGUAGE}_COMPILER_ARG1} + COMPILER_ID "${CMAKE_${COTIRE_TARGET_LANGUAGE}_COMPILER_ID}" + COMPILER_VERSION "${CMAKE_${COTIRE_TARGET_LANGUAGE}_COMPILER_VERSION}" + LANGUAGE "${COTIRE_TARGET_LANGUAGE}" + IGNORE_PATH "${COTIRE_TARGET_IGNORE_PATH};${COTIRE_ADDITIONAL_PREFIX_HEADER_IGNORE_PATH}" + INCLUDE_PATH ${COTIRE_TARGET_INCLUDE_PATH} + IGNORE_EXTENSIONS "${CMAKE_${COTIRE_TARGET_LANGUAGE}_SOURCE_FILE_EXTENSIONS};${COTIRE_ADDITIONAL_PREFIX_HEADER_IGNORE_EXTENSIONS}" + INCLUDE_PRIORITY_PATH ${COTIRE_TARGET_INCLUDE_PRIORITY_PATH} + INCLUDE_DIRECTORIES ${_includeDirs} + SYSTEM_INCLUDE_DIRECTORIES ${_systemIncludeDirs} + COMPILE_DEFINITIONS ${_compileDefinitions} + COMPILE_FLAGS ${_compileFlags} + ${_dependsOption}) + + elseif ("${COTIRE_ARGV1}" STREQUAL "precompile") + + set (_files "") + foreach (_index RANGE 5 ${COTIRE_ARGC}) + if (COTIRE_ARGV${_index}) + list (APPEND _files "${COTIRE_ARGV${_index}}") + endif() + endforeach() + + cotire_precompile_prefix_header( + "${COTIRE_ARGV3}" "${COTIRE_ARGV4}" "${COTIRE_ARGV5}" + COMPILER_LAUNCHER "${COTIRE_TARGET_${COTIRE_TARGET_LANGUAGE}_COMPILER_LAUNCHER}" + COMPILER_EXECUTABLE "${CMAKE_${COTIRE_TARGET_LANGUAGE}_COMPILER}" + COMPILER_ARG1 ${CMAKE_${COTIRE_TARGET_LANGUAGE}_COMPILER_ARG1} + COMPILER_ID "${CMAKE_${COTIRE_TARGET_LANGUAGE}_COMPILER_ID}" + COMPILER_VERSION "${CMAKE_${COTIRE_TARGET_LANGUAGE}_COMPILER_VERSION}" + LANGUAGE "${COTIRE_TARGET_LANGUAGE}" + INCLUDE_DIRECTORIES ${_includeDirs} + SYSTEM_INCLUDE_DIRECTORIES ${_systemIncludeDirs} + COMPILE_DEFINITIONS ${_compileDefinitions} + COMPILE_FLAGS ${_compileFlags}) + + elseif ("${COTIRE_ARGV1}" STREQUAL "combine") + + if (COTIRE_TARGET_LANGUAGE) + set (_combinedFile "${COTIRE_ARGV3}") + set (_startIndex 4) + else() + set (_combinedFile "${COTIRE_ARGV2}") + set (_startIndex 3) + endif() + set (_files "") + foreach (_index RANGE ${_startIndex} ${COTIRE_ARGC}) + if (COTIRE_ARGV${_index}) + list (APPEND _files "${COTIRE_ARGV${_index}}") + endif() + endforeach() + + if (XCODE) + # executing pre-build action under Xcode, check dependency on files to be combined + set (_dependsOption DEPENDS ${_files}) + else() + # executing custom command, no need to re-check for dependencies + set (_dependsOption "") + endif() + + if (COTIRE_TARGET_LANGUAGE) + cotire_generate_unity_source( + "${_combinedFile}" ${_files} + LANGUAGE "${COTIRE_TARGET_LANGUAGE}" + ${_dependsOption}) + else() + cotire_generate_unity_source("${_combinedFile}" ${_files} ${_dependsOption}) + endif() + + elseif ("${COTIRE_ARGV1}" STREQUAL "cleanup") + + cotire_cleanup("${COTIRE_ARGV2}" "${COTIRE_ARGV3}" "${COTIRE_ARGV4}") + + else() + message (FATAL_ERROR "cotire: unknown command \"${COTIRE_ARGV1}\".") + endif() + +else() + + # cotire is being run in include mode + # set up all variable and property definitions + + if (NOT DEFINED COTIRE_DEBUG_INIT) + if (DEFINED COTIRE_DEBUG) + set (COTIRE_DEBUG_INIT ${COTIRE_DEBUG}) + else() + set (COTIRE_DEBUG_INIT FALSE) + endif() + endif() + option (COTIRE_DEBUG "Enable cotire debugging output?" ${COTIRE_DEBUG_INIT}) + + if (NOT DEFINED COTIRE_VERBOSE_INIT) + if (DEFINED COTIRE_VERBOSE) + set (COTIRE_VERBOSE_INIT ${COTIRE_VERBOSE}) + else() + set (COTIRE_VERBOSE_INIT FALSE) + endif() + endif() + option (COTIRE_VERBOSE "Enable cotire verbose output?" ${COTIRE_VERBOSE_INIT}) + + set (COTIRE_ADDITIONAL_PREFIX_HEADER_IGNORE_EXTENSIONS "inc;inl;ipp" CACHE STRING + "Ignore headers with the listed file extensions from the generated prefix header.") + + set (COTIRE_ADDITIONAL_PREFIX_HEADER_IGNORE_PATH "" CACHE STRING + "Ignore headers from these directories when generating the prefix header.") + + set (COTIRE_UNITY_SOURCE_EXCLUDE_EXTENSIONS "m;mm" CACHE STRING + "Ignore sources with the listed file extensions from the generated unity source.") + + set (COTIRE_MINIMUM_NUMBER_OF_TARGET_SOURCES "3" CACHE STRING + "Minimum number of sources in target required to enable use of precompiled header.") + + if (NOT DEFINED COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES_INIT) + if (DEFINED COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES) + set (COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES_INIT ${COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES}) + elseif ("${CMAKE_GENERATOR}" MATCHES "JOM|Ninja|Visual Studio") + # enable parallelization for generators that run multiple jobs by default + set (COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES_INIT "-j") + else() + set (COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES_INIT "0") + endif() + endif() + set (COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES "${COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES_INIT}" CACHE STRING + "Maximum number of source files to include in a single unity source file.") + + if (NOT COTIRE_PREFIX_HEADER_FILENAME_SUFFIX) + set (COTIRE_PREFIX_HEADER_FILENAME_SUFFIX "_prefix") + endif() + if (NOT COTIRE_UNITY_SOURCE_FILENAME_SUFFIX) + set (COTIRE_UNITY_SOURCE_FILENAME_SUFFIX "_unity") + endif() + if (NOT COTIRE_INTDIR) + set (COTIRE_INTDIR "cotire") + endif() + if (NOT COTIRE_PCH_ALL_TARGET_NAME) + set (COTIRE_PCH_ALL_TARGET_NAME "all_pch") + endif() + if (NOT COTIRE_UNITY_BUILD_ALL_TARGET_NAME) + set (COTIRE_UNITY_BUILD_ALL_TARGET_NAME "all_unity") + endif() + if (NOT COTIRE_CLEAN_ALL_TARGET_NAME) + set (COTIRE_CLEAN_ALL_TARGET_NAME "clean_cotire") + endif() + if (NOT COTIRE_CLEAN_TARGET_SUFFIX) + set (COTIRE_CLEAN_TARGET_SUFFIX "_clean_cotire") + endif() + if (NOT COTIRE_PCH_TARGET_SUFFIX) + set (COTIRE_PCH_TARGET_SUFFIX "_pch") + endif() + if (MSVC) + # MSVC default PCH memory scaling factor of 100 percent (75 MB) is too small for template heavy C++ code + # use a bigger default factor of 170 percent (128 MB) + if (NOT DEFINED COTIRE_PCH_MEMORY_SCALING_FACTOR) + set (COTIRE_PCH_MEMORY_SCALING_FACTOR "170") + endif() + endif() + if (NOT COTIRE_UNITY_BUILD_TARGET_SUFFIX) + set (COTIRE_UNITY_BUILD_TARGET_SUFFIX "_unity") + endif() + if (NOT DEFINED COTIRE_TARGETS_FOLDER) + set (COTIRE_TARGETS_FOLDER "cotire") + endif() + if (NOT DEFINED COTIRE_UNITY_OUTPUT_DIRECTORY) + if ("${CMAKE_GENERATOR}" MATCHES "Ninja") + # generated Ninja build files do not work if the unity target produces the same output file as the cotired target + set (COTIRE_UNITY_OUTPUT_DIRECTORY "unity") + else() + set (COTIRE_UNITY_OUTPUT_DIRECTORY "") + endif() + endif() + + # define cotire cache variables + + define_property( + CACHED_VARIABLE PROPERTY "COTIRE_ADDITIONAL_PREFIX_HEADER_IGNORE_PATH" + BRIEF_DOCS "Ignore headers from these directories when generating the prefix header." + FULL_DOCS + "The variable can be set to a semicolon separated list of include directories." + "If a header file is found in one of these directories or sub-directories, it will be excluded from the generated prefix header." + "If not defined, defaults to empty list." + ) + + define_property( + CACHED_VARIABLE PROPERTY "COTIRE_ADDITIONAL_PREFIX_HEADER_IGNORE_EXTENSIONS" + BRIEF_DOCS "Ignore includes with the listed file extensions from the generated prefix header." + FULL_DOCS + "The variable can be set to a semicolon separated list of file extensions." + "If a header file extension matches one in the list, it will be excluded from the generated prefix header." + "Includes with an extension in CMAKE__SOURCE_FILE_EXTENSIONS are always ignored." + "If not defined, defaults to inc;inl;ipp." + ) + + define_property( + CACHED_VARIABLE PROPERTY "COTIRE_UNITY_SOURCE_EXCLUDE_EXTENSIONS" + BRIEF_DOCS "Exclude sources with the listed file extensions from the generated unity source." + FULL_DOCS + "The variable can be set to a semicolon separated list of file extensions." + "If a source file extension matches one in the list, it will be excluded from the generated unity source file." + "Source files with an extension in CMAKE__IGNORE_EXTENSIONS are always excluded." + "If not defined, defaults to m;mm." + ) + + define_property( + CACHED_VARIABLE PROPERTY "COTIRE_MINIMUM_NUMBER_OF_TARGET_SOURCES" + BRIEF_DOCS "Minimum number of sources in target required to enable use of precompiled header." + FULL_DOCS + "The variable can be set to an integer > 0." + "If a target contains less than that number of source files, cotire will not enable the use of the precompiled header for the target." + "If not defined, defaults to 3." + ) + + define_property( + CACHED_VARIABLE PROPERTY "COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES" + BRIEF_DOCS "Maximum number of source files to include in a single unity source file." + FULL_DOCS + "This may be set to an integer >= 0." + "If 0, cotire will only create a single unity source file." + "If a target contains more than that number of source files, cotire will create multiple unity source files for it." + "Can be set to \"-j\" to optimize the count of unity source files for the number of available processor cores." + "Can be set to \"-j jobs\" to optimize the number of unity source files for the given number of simultaneous jobs." + "Is used to initialize the target property COTIRE_UNITY_SOURCE_MAXIMUM_NUMBER_OF_INCLUDES." + "Defaults to \"-j\" for the generators Visual Studio, JOM or Ninja. Defaults to 0 otherwise." + ) + + # define cotire directory properties + + define_property( + DIRECTORY PROPERTY "COTIRE_ENABLE_PRECOMPILED_HEADER" + BRIEF_DOCS "Modify build command of cotired targets added in this directory to make use of the generated precompiled header." + FULL_DOCS + "See target property COTIRE_ENABLE_PRECOMPILED_HEADER." + ) + + define_property( + DIRECTORY PROPERTY "COTIRE_ADD_UNITY_BUILD" + BRIEF_DOCS "Add a new target that performs a unity build for cotired targets added in this directory." + FULL_DOCS + "See target property COTIRE_ADD_UNITY_BUILD." + ) + + define_property( + DIRECTORY PROPERTY "COTIRE_ADD_CLEAN" + BRIEF_DOCS "Add a new target that cleans all cotire generated files for cotired targets added in this directory." + FULL_DOCS + "See target property COTIRE_ADD_CLEAN." + ) + + define_property( + DIRECTORY PROPERTY "COTIRE_PREFIX_HEADER_IGNORE_PATH" + BRIEF_DOCS "Ignore headers from these directories when generating the prefix header." + FULL_DOCS + "See target property COTIRE_PREFIX_HEADER_IGNORE_PATH." + ) + + define_property( + DIRECTORY PROPERTY "COTIRE_PREFIX_HEADER_INCLUDE_PATH" + BRIEF_DOCS "Honor headers from these directories when generating the prefix header." + FULL_DOCS + "See target property COTIRE_PREFIX_HEADER_INCLUDE_PATH." + ) + + define_property( + DIRECTORY PROPERTY "COTIRE_PREFIX_HEADER_INCLUDE_PRIORITY_PATH" + BRIEF_DOCS "Header paths matching one of these directories are put at the top of the prefix header." + FULL_DOCS + "See target property COTIRE_PREFIX_HEADER_INCLUDE_PRIORITY_PATH." + ) + + define_property( + DIRECTORY PROPERTY "COTIRE_UNITY_SOURCE_PRE_UNDEFS" + BRIEF_DOCS "Preprocessor undefs to place in the generated unity source file before the inclusion of each source file." + FULL_DOCS + "See target property COTIRE_UNITY_SOURCE_PRE_UNDEFS." + ) + + define_property( + DIRECTORY PROPERTY "COTIRE_UNITY_SOURCE_POST_UNDEFS" + BRIEF_DOCS "Preprocessor undefs to place in the generated unity source file after the inclusion of each source file." + FULL_DOCS + "See target property COTIRE_UNITY_SOURCE_POST_UNDEFS." + ) + + define_property( + DIRECTORY PROPERTY "COTIRE_UNITY_SOURCE_MAXIMUM_NUMBER_OF_INCLUDES" + BRIEF_DOCS "Maximum number of source files to include in a single unity source file." + FULL_DOCS + "See target property COTIRE_UNITY_SOURCE_MAXIMUM_NUMBER_OF_INCLUDES." + ) + + define_property( + DIRECTORY PROPERTY "COTIRE_UNITY_LINK_LIBRARIES_INIT" + BRIEF_DOCS "Define strategy for setting up the unity target's link libraries." + FULL_DOCS + "See target property COTIRE_UNITY_LINK_LIBRARIES_INIT." + ) + + # define cotire target properties + + define_property( + TARGET PROPERTY "COTIRE_ENABLE_PRECOMPILED_HEADER" INHERITED + BRIEF_DOCS "Modify this target's build command to make use of the generated precompiled header." + FULL_DOCS + "If this property is set to TRUE, cotire will modify the build command to make use of the generated precompiled header." + "Irrespective of the value of this property, cotire will setup custom commands to generate the unity source and prefix header for the target." + "For makefile based generators cotire will also set up a custom target to manually invoke the generation of the precompiled header." + "The target name will be set to this target's name with the suffix _pch appended." + "Inherited from directory." + "Defaults to TRUE." + ) + + define_property( + TARGET PROPERTY "COTIRE_ADD_UNITY_BUILD" INHERITED + BRIEF_DOCS "Add a new target that performs a unity build for this target." + FULL_DOCS + "If this property is set to TRUE, cotire creates a new target of the same type that uses the generated unity source file instead of the target sources." + "Most of the relevant target properties will be copied from this target to the new unity build target." + "Target dependencies and linked libraries have to be manually set up for the new unity build target." + "The unity target name will be set to this target's name with the suffix _unity appended." + "Inherited from directory." + "Defaults to TRUE." + ) + + define_property( + TARGET PROPERTY "COTIRE_ADD_CLEAN" INHERITED + BRIEF_DOCS "Add a new target that cleans all cotire generated files for this target." + FULL_DOCS + "If this property is set to TRUE, cotire creates a new target that clean all files (unity source, prefix header, precompiled header)." + "The clean target name will be set to this target's name with the suffix _clean_cotire appended." + "Inherited from directory." + "Defaults to FALSE." + ) + + define_property( + TARGET PROPERTY "COTIRE_PREFIX_HEADER_IGNORE_PATH" INHERITED + BRIEF_DOCS "Ignore headers from these directories when generating the prefix header." + FULL_DOCS + "The property can be set to a list of directories." + "If a header file is found in one of these directories or sub-directories, it will be excluded from the generated prefix header." + "Inherited from directory." + "If not set, this property is initialized to \${CMAKE_SOURCE_DIR};\${CMAKE_BINARY_DIR}." + ) + + define_property( + TARGET PROPERTY "COTIRE_PREFIX_HEADER_INCLUDE_PATH" INHERITED + BRIEF_DOCS "Honor headers from these directories when generating the prefix header." + FULL_DOCS + "The property can be set to a list of directories." + "If a header file is found in one of these directories or sub-directories, it will be included in the generated prefix header." + "If a header file is both selected by COTIRE_PREFIX_HEADER_IGNORE_PATH and COTIRE_PREFIX_HEADER_INCLUDE_PATH," + "the option which yields the closer relative path match wins." + "Inherited from directory." + "If not set, this property is initialized to the empty list." + ) + + define_property( + TARGET PROPERTY "COTIRE_PREFIX_HEADER_INCLUDE_PRIORITY_PATH" INHERITED + BRIEF_DOCS "Header paths matching one of these directories are put at the top of prefix header." + FULL_DOCS + "The property can be set to a list of directories." + "Header file paths matching one of these directories will be inserted at the beginning of the generated prefix header." + "Header files are sorted according to the order of the directories in the property." + "If not set, this property is initialized to the empty list." + ) + + define_property( + TARGET PROPERTY "COTIRE_UNITY_SOURCE_PRE_UNDEFS" INHERITED + BRIEF_DOCS "Preprocessor undefs to place in the generated unity source file before the inclusion of each target source file." + FULL_DOCS + "This may be set to a semicolon-separated list of preprocessor symbols." + "cotire will add corresponding #undef directives to the generated unit source file before each target source file." + "Inherited from directory." + "Defaults to empty string." + ) + + define_property( + TARGET PROPERTY "COTIRE_UNITY_SOURCE_POST_UNDEFS" INHERITED + BRIEF_DOCS "Preprocessor undefs to place in the generated unity source file after the inclusion of each target source file." + FULL_DOCS + "This may be set to a semicolon-separated list of preprocessor symbols." + "cotire will add corresponding #undef directives to the generated unit source file after each target source file." + "Inherited from directory." + "Defaults to empty string." + ) + + define_property( + TARGET PROPERTY "COTIRE_UNITY_SOURCE_MAXIMUM_NUMBER_OF_INCLUDES" INHERITED + BRIEF_DOCS "Maximum number of source files to include in a single unity source file." + FULL_DOCS + "This may be set to an integer > 0." + "If a target contains more than that number of source files, cotire will create multiple unity build files for it." + "If not set, cotire will only create a single unity source file." + "Inherited from directory." + "Defaults to empty." + ) + + define_property( + TARGET PROPERTY "COTIRE__UNITY_SOURCE_INIT" + BRIEF_DOCS "User provided unity source file to be used instead of the automatically generated one." + FULL_DOCS + "If set, cotire will only add the given file(s) to the generated unity source file." + "If not set, cotire will add all the target source files to the generated unity source file." + "The property can be set to a user provided unity source file." + "Defaults to empty." + ) + + define_property( + TARGET PROPERTY "COTIRE__PREFIX_HEADER_INIT" + BRIEF_DOCS "User provided prefix header file to be used instead of the automatically generated one." + FULL_DOCS + "If set, cotire will add the given header file(s) to the generated prefix header file." + "If not set, cotire will generate a prefix header by tracking the header files included by the unity source file." + "The property can be set to a user provided prefix header file (e.g., stdafx.h)." + "Defaults to empty." + ) + + define_property( + TARGET PROPERTY "COTIRE_UNITY_LINK_LIBRARIES_INIT" INHERITED + BRIEF_DOCS "Define strategy for setting up unity target's link libraries." + FULL_DOCS + "If this property is empty or set to NONE, the generated unity target's link libraries have to be set up manually." + "If this property is set to COPY, the unity target's link libraries will be copied from this target." + "If this property is set to COPY_UNITY, the unity target's link libraries will be copied from this target with considering existing unity targets." + "Inherited from directory." + "Defaults to empty." + ) + + define_property( + TARGET PROPERTY "COTIRE__UNITY_SOURCE" + BRIEF_DOCS "Read-only property. The generated unity source file(s)." + FULL_DOCS + "cotire sets this property to the path of the generated single computation unit source file for the target." + "Defaults to empty string." + ) + + define_property( + TARGET PROPERTY "COTIRE__PREFIX_HEADER" + BRIEF_DOCS "Read-only property. The generated prefix header file." + FULL_DOCS + "cotire sets this property to the full path of the generated language prefix header for the target." + "Defaults to empty string." + ) + + define_property( + TARGET PROPERTY "COTIRE__PRECOMPILED_HEADER" + BRIEF_DOCS "Read-only property. The generated precompiled header file." + FULL_DOCS + "cotire sets this property to the full path of the generated language precompiled header binary for the target." + "Defaults to empty string." + ) + + define_property( + TARGET PROPERTY "COTIRE_UNITY_TARGET_NAME" + BRIEF_DOCS "The name of the generated unity build target corresponding to this target." + FULL_DOCS + "This property can be set to the desired name of the unity target that will be created by cotire." + "If not set, the unity target name will be set to this target's name with the suffix _unity appended." + "After this target has been processed by cotire, the property is set to the actual name of the generated unity target." + "Defaults to empty string." + ) + + # define cotire source properties + + define_property( + SOURCE PROPERTY "COTIRE_EXCLUDED" + BRIEF_DOCS "Do not modify source file's build command." + FULL_DOCS + "If this property is set to TRUE, the source file's build command will not be modified to make use of the precompiled header." + "The source file will also be excluded from the generated unity source file." + "Source files that have their COMPILE_FLAGS property set will be excluded by default." + "Defaults to FALSE." + ) + + define_property( + SOURCE PROPERTY "COTIRE_DEPENDENCY" + BRIEF_DOCS "Add this source file to dependencies of the automatically generated prefix header file." + FULL_DOCS + "If this property is set to TRUE, the source file is added to dependencies of the generated prefix header file." + "If the file is modified, cotire will re-generate the prefix header source upon build." + "Defaults to FALSE." + ) + + define_property( + SOURCE PROPERTY "COTIRE_UNITY_SOURCE_PRE_UNDEFS" + BRIEF_DOCS "Preprocessor undefs to place in the generated unity source file before the inclusion of this source file." + FULL_DOCS + "This may be set to a semicolon-separated list of preprocessor symbols." + "cotire will add corresponding #undef directives to the generated unit source file before this file is included." + "Defaults to empty string." + ) + + define_property( + SOURCE PROPERTY "COTIRE_UNITY_SOURCE_POST_UNDEFS" + BRIEF_DOCS "Preprocessor undefs to place in the generated unity source file after the inclusion of this source file." + FULL_DOCS + "This may be set to a semicolon-separated list of preprocessor symbols." + "cotire will add corresponding #undef directives to the generated unit source file after this file is included." + "Defaults to empty string." + ) + + define_property( + SOURCE PROPERTY "COTIRE_START_NEW_UNITY_SOURCE" + BRIEF_DOCS "Start a new unity source file which includes this source file as the first one." + FULL_DOCS + "If this property is set to TRUE, cotire will complete the current unity file and start a new one." + "The new unity source file will include this source file as the first one." + "This property essentially works as a separator for unity source files." + "Defaults to FALSE." + ) + + define_property( + SOURCE PROPERTY "COTIRE_TARGET" + BRIEF_DOCS "Read-only property. Mark this source file as cotired for the given target." + FULL_DOCS + "cotire sets this property to the name of target, that the source file's build command has been altered for." + "Defaults to empty string." + ) + + message (STATUS "cotire ${COTIRE_CMAKE_MODULE_VERSION} loaded.") + +endif() diff --git a/dep/cotire/HISTORY.md b/dep/cotire/HISTORY.md new file mode 100644 index 00000000000..c92e0b1bffb --- /dev/null +++ b/dep/cotire/HISTORY.md @@ -0,0 +1,341 @@ +## 1.7.10 (2017-06-16) + +* CMake 3.8 compatibility. +* CMake 3.8.0 Qt automoc support (thanks bilke). +* fix Xcode recompiling every time builds happen (thanks gcamp). +* disable PCH messages when `-Wno-pch-messages` flag exists (thanks kbinani). +* work around ccache incompatibility with newer versions of GCC and Clang. +* fix MinGW incompatibility with `BUILD_INTERFACE` generator expression. +* fix handling of `CMAKE_INCLUDE_FLAG_SEP_` variables. + +## 1.7.9 (2016-12-08) + +* CMake 3.6 and 3.7 compatibility. +* fix ccache 3.2 compatibility issues. +* fix bugs with handling language standard related properties (e.g., `CXX_STANDARD`, `CXX_EXTENSIONS`). +* make prefix header generation and precompiled header compilation depend on the compiler executable. +* fix Qt automoc handling for Windows (thanks jcelerier). +* convert Windows paths in include directories to CMake paths (thanks wdx04). +* replace object library with corresponding unity object library when using `COPY_UNITY` linking strategy. +* better error reporting from prefix header generation. + +## 1.7.8 (2016-03-27) + +* fix `COPY_UNITY` linking strategy for private link dependencies. +* honor `CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE` upon handling of target usage requirements. +* reworked setting up of `LINK_LIBRARIES` and `INTERFACE_LINK_LIBRARIES` properties for unity targets. + +## 1.7.7 (2016-03-20) + +* CMake 3.5 compatibility. +* fix bugs related to handling of interface libraries. +* output shorter log messages when using Visual Studio IDE. +* don't disable PCH if CMAKE__COMPILER_ID is not set (thanks jcelerier). +* add support for compiler launchers introduced in CMake 3.4 (thanks misery). + +## 1.7.6 (2015-12-06) + +* fix CMake 3.4 compatibility issues. +* prevent redundant re-generation of prefix header when a target has generated source files. + +## 1.7.5 (2015-10-27) + +* handle visibility target properties (`CXX_VISIBILITY_PRESET` and `VISIBILITY_INLINES_HIDDEN`). +* better handling of include directories and system include directories. +* parse additional system include directories from target compile flags. +* activate select CMake policies. + +## 1.7.4 (2015-10-10) + +* set up single unity source file for prefix header generation. +* increase MSVC default PCH memory to 128M. +* remove obsolete code. + +## 1.7.3 (2015-07-25) + +* handle language standard target properties (e.g., `CXX_STANDARD`). +* apply user provided prefix header to unity build target. +* remove effect of `COTIRE_MINIMUM_NUMBER_OF_TARGET_SOURCES` on generated unity target. +* manual updates. + +## 1.7.2 (2015-04-22) + +* reduce configure time overhead. +* fix bug with dependency checking when using Xcode. +* remove obsolete code required for CMake versions older than 2.8.12. +* streamline debugging output. + +## 1.7.1 (2015-04-06) + +* fix problem with CMake's automatic Qt processing for generated unity targets. +* added a section on common pitfalls when using cotire to the manual. +* remove obsolete code required for CMake versions older than 2.8.12. +* streamline debugging output. +* activate select CMake policies. + +## 1.7.0 (2015-03-29) + +* fix CMake 3.2 compatibility issues. +* cotire now requires CMake 2.8.12 or newer. +* copy `IMPORT_PREFIX` and `IMPORT_SUFFIX` target properties for unity targets (thanks peterhuene). +* new property `COTIRE_PREFIX_HEADER_INCLUDE_PRIORITY_PATH` allows for organizing includes + added to the prefix header by priority (thanks ArnaudD-FR). +* for Visual Studio C++, increase static precompiled header memory allocation. +* the default strategy for setting up a unity target's linked libraries is now `COPY_UNITY`. +* for Qt projects, fix problem with handling of `AUTOMOC` in generated unity target. +* fix problem with generating the cotire intermediate directory. +* documentation updates. + +## 1.6.9 (2015-01-18) + +* fix bug with parsing of localized MSVC `/showIncludes` output. + +## 1.6.8 (2014-12-28) + +* fix bug with generation of unity source file segments for parallel builds. + +## 1.6.7 (2014-12-21) + +* fix CMake 3.1 compatibility issues. +* fix ccache 3.2 compatibility issues. +* handle `COTIRE_MINIMUM_NUMBER_OF_TARGET_SOURCES` correctly for mixed-language targets. +* correctly compute absolute paths of generated source files added to the unity source file. +* fix bug with checking unity source and prefix header dependencies under Xcode. +* fix bug with handling of unity source file dependencies. +* move code to determine build configurations to function of its own. +* documentation updates. + +## 1.6.6 (2014-09-21) + +* fix GCC issue with prefix header generation when source files are missing. +* fix bug where some target properties were not properly propagated to the generated unity target. +* use `target_link_libraries` to set up the unity target link libraries. +* add Qt4 and Qt5 examples to the `Patches` directory. +* documentation updates. + +## 1.6.5 (2014-08-26) + +* correctly handle generator expressions used in compile definitions, compile flags and include + directories (requires CMake 2.8.12 or newer). +* fix `-isystem` includes being incorrectly passed to `execute_process` (thanks nickhutchinson). +* make some error messages more verbose. + +## 1.6.4 (2014-07-14) + +* fix CMake 3.0 compatibility issues. +* preserve system flag for includes when generating PCH (thanks gjasny). +* fix bug with setting up `EXPORTS` symbol for shared libraries. + +## 1.6.3 (2014-06-11) + +* correctly handle usage requirements for transitive link targets. +* use indirect inclusion for prefix header when using generator Xcode. + +## 1.6.2 (2014-06-09) + +* don't use `-w` flag for pre-compiling the prefix header, because it has unwanted side effects. +* correctly handle linked targets' `INTERFACE_COMPILE_OPTIONS`, `INTERFACE_INCLUDE_DIRECTORIES` + and `INTERFACE_COMPILE_DEFINITIONS` properties upon pre-compiling and prefix header generation. +* For Clang and GCC, pre-compile prefix header through indirect inclusion via a prefix source file, + to make both compilers honor the `system_header` pragma in the prefix header correctly. +* fix ccache incompatibility. + +## 1.6.1 (2014-04-20) + +* fixed bug where precompiled headers did not work with Clang (thanks to nh2 for reporting). +* when using ccache, require that environment variable `CCACHE_SLOPPINESS` is set to `time_macros`. + +## 1.6.0 (2014-03-16) + +* suppress compiler warnings from precompiled headers. +* fix Clang compatibility issue with prefix header generation. +* use file extension `.pch` for precompiled headers generated with Clang. +* manual updates. + +## 1.5.2 (2014-01-17) + +* honor framework includes under OS X correctly. +* fix handling of OS X specific variables `CMAKE_OSX_SYSROOT` and `CMAKE_OSX_DEPLOYMENT_TARGET`. +* add new examples to the `Patches` directory. + +## 1.5.1 (2013-11-12) + +* fixed string quoting bugs. + +## 1.5.0 (2013-10-13) + +* CMake 2.8.12 compatibility fixes. +* Upon generation of a unity target, cotire can now be configured to automatically copy all the + linked libraries and targets from the original target. See the section on the new target property + `COTIRE_UNITY_LINK_LIBRARIES_INIT` in the cotire manual. +* fixed bug with copying target properties to generated unity target. +* cotire manual updates. +* add new examples to the `Patches` directory. +* fix typos. + +## 1.4.3 (2013-09-28) + +* fixed bug with generation of unity source file when `COTIRE_MINIMUM_NUMBER_OF_TARGET_SOURCES` is + set to 0. + +## 1.4.2 (2013-08-24) + +* CMake 2.8.11 compatibility fixes. +* always force the inclusion of a user provided prefix header, even if the target + contains too few sources to enable the use of a precompiled header. + +## 1.4.1 (2013-06-08) + +* fixed bug with determination of compiler version. +* fixed bug with generation of unity source when target source files are used for multiple targets. +* fixed bug with multi-core optimized prefix header generation. + +## 1.4.0 (2013-03-11) + +* one year anniversary release. +* add support for multi-core optimized unity builds for some CMake generators. +* add support for multi-core optimized prefix header generation. +* add more examples to cotire manual. + +## 1.3.6 (2013-03-06) + +* fix bug with prefix header initialization for generator Xcode. +* print cotire version upon inclusion. + +## 1.3.5 (2013-03-01) + +* fix typos in function names and property descriptions. + +## 1.3.4 (2013-02-07) + +* fixed bug with computing to output directory of the generated unity target (thanks shaunew). +* fixed wrong variable reference in debugging output (thanks shaunew). + +## 1.3.3 (2013-02-03) + +* fixed bug with handling of policy CMP0018 relating to target property `POSITION_INDEPENDENT_CODE`. +* fixed warnings relating to uninitialized variables. +* Intel XE 2013 Update 2 compatibility fixes. + +## 1.3.2 (2013-02-02) + +* fixed missing curly brace (thanks shaunew). + +## 1.3.1 (2013-01-29) + +* fix bug with filtering of compile options. + +## 1.3.0 (2013-01-09) + +* add support for Intel C and C++ compilers. +* CMake 2.8.10 compatibility fixes. +* properly clean up generated cotire log files upon invoking `clean` target. +* documentation updates. + +## 1.2.0 (2012-11-01) + +* add support for manually maintained prefix header and unity source files. +* the target property `COTIRE__PREFIX_HEADER_INIT` can be set to a user provided prefix + header file to be used instead of the automatically generated one (e.g., `stdafx.h`). +* the new target property `COTIRE__UNITY_SOURCE_INIT` can be set to a user provided unity + source file to be used instead of the automatically generated one. +* the target property `COTIRE_UNITY_TARGET_NAME` is no longer read-only. It can be set to the + desired name of the unity target that will be added by cotire. +* add parameters `SOURCE_DIR` and `BINARY_DIR` to function `cotire` to allow for explicitly + specifying a target's source and binary directory, if target to be cotired has been added in a + different directory. + +## 1.1.8 (2012-10-27) + +* when using MSVC, apply option `/bigobj` to compilation of generated unity files. + +## 1.1.7 (2012-10-26) + +* cope with double slash characters in scanned include paths. + +## 1.1.6 (2012-09-22) + +* check result code upon scanning includes. +* always add a `clean_cotire` target to easily clean up cotire generated files. +* add section on `extern "C"` linkage issues to manual. + +## 1.1.5 (2012-08-17) + +* new cache variable `COTIRE_UNITY_SOURCE_EXCLUDE_EXTENSIONS` can be set to globally exclude + sources with the listed file extensions from the generated unity source. +* fix check for multi-architecture builds under OS X. + +## 1.1.4 (2012-08-15) + +* prevent redundant re-generation of the unity source, prefix header and precompiled header files + (this makes cotire more applicable to C++ projects that use Qt). + +## 1.1.3 (2012-08-12) + +* fix out of range index operation upon building list of target include directories. +* honor target properties `POSITION_INDEPENDENT_CODE` and `NO_SONAME` introduced with CMake 2.8.9. +* make selection of target source files for requested target language more careful. +* prevent modification of the CMake policy stack upon CMake version check. + +## 1.1.2 (2012-05-06) + +* make handling of include directories more robust against invalid paths. + +## 1.1.1 (2012-04-20) + +* fixed bug with generation of unity targets for `WIN32_EXECUTABLE` targets. +* fixed bug with parsing of localized MSVC `/showIncludes` output. + +## 1.1.0 (2012-04-19) + +* tested with CMake 2.8.8. +* added example to manual that shows how to apply cotire to CMake object library targets. +* fixed multiple bugs with handling of CMake single build type and multiple configuration builds. +* added more robust parsing of localized MSVC `/showIncludes` output. + +## 1.0.9 (2012-04-09) + +* add support for compiler wrappers like ccache. +* under OS X, apply `CMAKE_OSX_SYSROOT` to prefix header include and ignore paths. + +## 1.0.8 (2012-04-05) + +* require CMake 2.8.6 since we are using `set_property` option `APPEND_STRING`. + +## 1.0.7 (2012-04-02) + +* add support for Ninja generator introduced in CMake 2.8.8. +* fix bug with initialization of variable `COTIRE_VERBOSE`. + +## 1.0.6 (2012-04-01) + +* correctly handle builds where both `CMAKE_BUILD_TYPE` and `CMAKE_CONFIGURATION_TYPES` are set. + +## 1.0.5 (2012-03-26) + +* fix Visual Studio C++ 2010 compilation of example project. +* enhance heuristic for #include_next directive detection. +* fix llvm-3.0.src.patch for GCC 4.6 compilation. + +## 1.0.4 (2012-03-24) + +* honor target property INCLUDE_DIRECTORIES introduced in CMake 2.8.8. + +## 1.0.3 (2012-03-23) + +* handle OBJECT_LIBRARY targets introduced in CMake 2.8.8. +* use predefined compiler version variable, if available. + +## 1.0.2 (2012-03-16) + +* fix Xcode 4.3 compatibility. +* Cotire manual corrections. + +## 1.0.1 (2012-03-15) + +* Cotire manual corrections. +* Add prefix header to the generated unity build target. + +## 1.0.0 (2012-03-11) + +* First release. diff --git a/dep/cotire/MANUAL.md b/dep/cotire/MANUAL.md new file mode 100644 index 00000000000..af1f1fed03a --- /dev/null +++ b/dep/cotire/MANUAL.md @@ -0,0 +1,795 @@ +cotire manual +============= + +Cotire (compile time reducer) is a CMake module that speeds up the build process of CMake based +build systems by fully automating techniques as [precompiled header][pch] usage and +[single compilation unit][scu] builds for C and C++. + +motivation +---------- + +Cotire was born out of a dissatisfaction with the existing CMake solutions for adding +[precompiled header][1260] support and unity build support to CMake based build systems. +The design of cotire tries to adhere to the following principles: + +#### as automatic as possible + +[Precompiled header][pch] and [unity builds][scu] are good ideas in principle, but in reality +they do not work if the burden of maintaining the required additional source files (a +[prefix header][pfh] and a unity source file) is put on the developer. A modern build system +like CMake provides enough context information to have the build system generate and update +these files automatically. + +#### non-intrusive + +The configuration of precompiled headers usage and single computation unit builds belongs to the +build system and not in the source code. Nobody wants to litter one's source files with `hdrstop` +pragmas or be forced to add an include directive to every file. Source code should build properly +when a precompiled header isn't used and should build faster when a precompiled header is used. + +#### minimal interface + +Maintaining a build system over time is enough work and the CMake language may often get in your +way. Thus the solution should only add few public CMake functions. It should be easy to integrate +it into an existing CMake based build system and it should be just as easy to remove it again. + +#### lazy file creation + +The additional source files needed for precompiled header support and unity build support should +only be created when they are required for the compilation of a target. Thus the solution should +not create these files upon configuring the project, but should set up custom build commands for +the creation of these files that only kick in when the files are required to exist by the build +process. + +#### cross-platform + +C/C++ Compilers and IDEs on different platforms vary widely in how the implement precompiled +header support. The solution should hide these implementation details and present a uniform +interface to the developer on all supported platforms. + +cotire basic usage +------------------ + +Cotire consists of a single CMake module file, which can be easily added to an existing CMake +project. + +The file `CMake/cotire.cmake` needs to be copied to the module directory of a CMake project. In the +top-level `CMakeList.txt` file, the module directory needs to be added to the CMake module search +path: + + set (CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/CMake") + +To use cotire in a CMake project, one adds the following include directive to the beginning of the +top-level `CMakeList.txt`: + + include(cotire) + +To speed the build process of a CMake library or executable target, the `cotire` function is +applied to a CMake target. From the example project that ships with cotire: + + add_executable(example main.cpp example.cpp log.cpp log.h example.h) + ... + cotire(example) + +Cotire looks at the properties of the target provided by CMake (e.g., target type, source files, +compile flags, preprocessor defines, include directories, ...) and modifies the target's build +process in the following way: + +1. cotire adds a custom build rule to produce a unity source file from the target's sources. +2. cotire adds a custom build rule to produce a prefix header file by tracking the header files + included by the target's sources. +3. cotire adds a custom build rule to produce a precompiled header from the prefix header. +4. cotire modifies the target's compile flags to make use of the generated precompiled header. +5. cotire adds a couple of new targets. + +For makefile based build systems, running `make help` in the terminal reveals the new targets: + + $ make help + ... + ... all_pch + ... all_unity + ... clean_cotire + ... example + ... example_pch + ... example_unity + +The `example_pch` target triggers the compilation of the precompiled header and as a side effect +the generation of the unity source and the prefix header. The target `clean_cotire` cleans up all +files generated by cotire. The `example_unity` target produces the same output as the original +`example` target, but does so by performing a unity build. The `all_pch` and `all_unity` serve as +pool targets for all cotired project targets. + +By default, the `example_unity` target inherits all build settings from the original target +`example` including linked libraries and target dependencies. + +cotire generated files +---------------------- + +For a target that has been cotired, three files will be generated as part of the build process: + +### the unity source + +The unity source file is generated from the target by querying the target's `SOURCES` property. +It consists of preprocessor include directives for each of the target source files. The files +are included in the same order that is used in the CMake `add_executable` or `add_library` call. +Header files are omitted. + +This is a unity source generated for the example project under OS X: + + #ifdef __cplusplus + #include "/Users/sakra/Documents/cotire/src/main.cpp" + #include "/Users/sakra/Documents/cotire/src/example.cpp" + #include "/Users/sakra/Documents/cotire/src/log.cpp" + #endif + +The unity source file uses absolute paths to include the target's source file. The file is not +intended to be portable across different build folders or machines. It is an intermediate file +tied to the build folder that is automatically recreated by the build system if it is missing. + +For multi-core machines cotire can be configured to generate multiple unity file segments that +can be built in parallel by the chosen CMake generator (see below). + +### the prefix header + +The prefix header is produced from the unity source file by running the unity file through the +preprocessor and keeping track of each header file used (this is done by using option `-H` with +GCC / Clang and `/showIncludes` with Visual Studio C++). The path of each used header file is +compared against an exclude directory list and an include directory list to decide if the header +file should be added to the prefix header. + +By default the include directory list is empty and the exclude directory list is initialized to +`"${CMAKE_SOURCE_DIR};${CMAKE_BINARY_DIR}"`. This default setting guarantees that project headers +which are likely to be changed frequently are not added to the prefix header. + +Upon generation of the prefix header cotire makes sure that target compile options, include path +settings and preprocessor defines (e.g., `NDEBUG`) that affect the outcome of the preprocessor +are correctly set up. + +Generating the prefix header from the unity source is much faster than running each individual +target source file through the preprocessor, because the coalesced unity source will make the +preprocessor process most header files only once. + +This is a prefix header produced for the example project with Visual Studio 2013 under Windows 7: + + #pragma warning(push, 0) + #ifdef __cplusplus + #include "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\string" + #include "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\algorithm" + #include "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\iostream" + #endif + #pragma warning(pop) + +Generating the prefix file under Ubuntu 12.04 with GCC 4.6 yields the following result: + + #pragma GCC system_header + #ifdef __cplusplus + #include "/usr/include/c++/4.6/string" + #include "/usr/include/c++/4.6/algorithm" + #include "/usr/include/c++/4.6/iterator" + #include "/usr/include/c++/4.6/iostream" + #endif + +Using Xcode 5.1 under OS X 10.9, this is the resulting prefix header: + + #pragma clang system_header + #ifdef __cplusplus + #include "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/c++/v1/string" + #include "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/c++/v1/iostream" + #endif + +Besides include directives, cotire also adds compiler specific pragmas to the generated prefix +header to suppress compiler warnings upon inclusion. + +Cotire attempts to produce a minimal list of header files by omitting header files indirectly +included by a header that is already part of the prefix header. Header files with nonstandard +file extensions like `.inl`, `.inc` of `.ipp` are omitted by default. + +The generated prefix file includes the selected header files by their absolute paths. This speeds +up the precompiling of the prefix header because the compiler does not have to search for header +files in include directories again. + +The prefix header is tailored to the CMake target that it is generated for. It is tied to the +compiler environment of the local machine and is not portable across different compilers or +machines. It is automatically recreated by the build system if it goes missing. + +The generated prefix header can be applied to a different target added in the same source directory +(see below). + +Optionally, cotire will also create a prefix source file that consists of a single include directive +for the prefix header. This file is needed for pre-compiling the prefix header with Clang or GCC +to make both compilers handle the `system_header` pragma correctly. + +### the precompiled header + +The precompiled header is produced from the generated prefix header by using the proprietary +precompiling mechanism depending on the compiler used. For GCC and Clang cotire sets up a custom +build rule and generates the precompiled header as described in the documentation for +[GCC][gcc_pch] and [Clang][clang_pch]. Cotire then modifies the `COMPILE_FLAGS` property of the +target to force the inclusion of the prefix header. + +Visual Studio C++ and Intel C++ use a [different approach][msvc_pch] to pre-compiling. Both +compilers require a host source file to generate the precompiled header as a side effect of +producing an object file. Cotire modifies the `COMPILE_FLAGS` of the first target source file to +[generate][msvc_pch_create] the precompiled header and then modifies the `COMPILE_FLAGS` of the +remaining target source files to [include][msvc_pch_use] the generated precompiled header. + +For Xcode projects generated with CMake, cotire completely hands off the pre-compilation of +the prefix header and the inclusion of the precompiled header to the IDE. Cotire attaches a +pre-build action to the target which generates the unity source file and the prefix header. +Cotire then modifies Xcode attributes of the generated Xcode project to have Xcode precompile the +the generated prefix header with the Xcode build steps `ProcessPCH` for C sources and +`ProcessPCH++` for C++ sources. + +For precompiled headers creation flags must match use flags exactly. Cotire uses the same flags, +include directories and preprocessor defines that are used for the compilation of source files +for the generation of the precompiled header. Thus the resulting precompiled header binary is only +usable for the target and cannot be re-used for a different CMake target. + +cotire advanced usage +--------------------- + +### applying cotire to multiple targets at the same time + +The `cotire` function can be applied to multiple targets added in the same source directory in one +call: + + add_library(libA STATIC ...) + add_library(libB SHARED ...) + add_executable(example ...) + ... + cotire(example libA libB) + +### mixed-language targets + +Cotire is able to speed up the build process of mixed language targets, consisting of both C and +C++ sources. It generates a separate set of unity source files, prefix headers and precompiled +headers for both languages and modifies the `COMPILE_FLAGS` of each target source file to include +the correct precompiled header depending on the compilation language of the source file. + +### obtaining the names of the generated files and targets + +For a cotired target the target properties `COTIRE__UNITY_SOURCE`, +`COTIRE__PREFIX_HEADER`, `COTIRE__PRECOMPILED_HEADER` will be set to the paths of the +generated files (`` can be set to `CXX` or `C`). The target property +`COTIRE_UNITY_TARGET_NAME` will be set to the name of the generated unity target: + + cotire(example) + ... + get_target_property(_unitySource example COTIRE_CXX_UNITY_SOURCE) + get_target_property(_prefixHeader example COTIRE_CXX_PREFIX_HEADER) + get_target_property(_precompiledHeader example COTIRE_CXX_PRECOMPILED_HEADER) + get_target_property(_unityTargetName example COTIRE_UNITY_TARGET_NAME) + +If a source file's `COMPILE_FLAGS` are modified by cotire, it sets the source file property +`COTIRE_TARGET` to the name of the target, that the source file's build command has been +altered for: + + cotire(example) + ... + get_source_file_property(_cotireTargetName "example.cpp" COTIRE_TARGET) + if (_cotireTargetName) + message(STATUS "example.cpp has been cotired for target ${_cotireTargetName}") + endif() + +### changing the name of the generated unity build target + +By default cotire uses the name of the the original target with the suffix `_unity` appended +for the name of the generated unity build target. To create the unity build target under a +different name, set the `COTIRE_UNITY_TARGET_NAME` property: + + add_executable(example_template main.cpp example.cpp log.cpp log.h example.h) + set_target_properties(example_template PROPERTIES COTIRE_UNITY_TARGET_NAME "example") + ... + cotire(example_template) + +Invoking the `example` target will then run the unity build. + +### restricting cotire to certain build configurations + +To restrict the cotire related modifications to the build process to certain build configurations, +the `CONFIGURATIONS` parameter can be added to the `cotire` call. + + cotire(example CONFIGURATIONS Release MinSizeRel) + +For single build type builds the selected configuration will be checked at configure time, for +multi-configuration builds the check will be done at build time. + +It is recommended to have at least one build configuration that does not make use of cotire to +ensure that the project builds properly without cotire. + +### disabling precompiled headers and unity builds + +If the target's build process should not be modified to make use of the generated precompiled +header, the target property `COTIRE_ENABLE_PRECOMPILED_HEADER` can be set to `FALSE`: + + set_target_properties(example PROPERTIES COTIRE_ENABLE_PRECOMPILED_HEADER FALSE) + cotire(example) + +If a unity build target should not be added by cotire, the target property +`COTIRE_ADD_UNITY_BUILD` can be set to `FALSE`: + + set_target_properties(example PROPERTIES COTIRE_ADD_UNITY_BUILD FALSE) + cotire(example) + +The property `COTIRE_ADD_UNITY_BUILD` only affects the addition of the unity build target. Custom +build rules for the generation of the unity source file will always be set up, because the +unity source file is needed for the generation of the prefix header. + +Both properties default to `TRUE`. If both are set to `FALSE`, cotire will only set up custom build +rules for the generation of the unity source and the prefix header. + +The properties `COTIRE_ENABLE_PRECOMPILED_HEADER` and `COTIRE_ADD_UNITY_BUILD` can also be set on +directories. A target inherits the property value from its enclosing directory. + +### disabling precompiled headers for small targets + +The cache variable `COTIRE_MINIMUM_NUMBER_OF_TARGET_SOURCES` can be set to the minimum number of +source files required to enable the use of a precompiled header. It defaults to 3. To override the +default, run `cmake` with the following options: + + $ cmake -D COTIRE_MINIMUM_NUMBER_OF_TARGET_SOURCES=5 + +### using a manually maintained prefix header instead of the automatically generated one + +cotire can be configured to use an existing manually maintained prefix header (e.g., Visual Studio +projects often use a prefix header named `stdafx.h`) instead of the automatically generated one. +Set the target property `COTIRE_CXX_PREFIX_HEADER_INIT` to the path of the existing prefix header +file. The path is interpreted relative to the target source directory: + + set_target_properties(example PROPERTIES COTIRE_CXX_PREFIX_HEADER_INIT "stdafx.h") + cotire(example) + +If the prefix header `stdafx.h` needs an accompanying source file (e.g., `stdafx.cpp`) in order +to be precompiled properly, that source file needs to be the first one on the list of source +files in the target's `add_executable` or `add_library` call. + +The property `COTIRE_CXX_PREFIX_HEADER_INIT` can also be set to a list of header files which will +then make up the contents of the generated prefix header. + +A manually maintained prefix header will always be applied to the corresponding target, +even if the target contains too few sources to enable the use of a precompiled header. + +### using a generated prefix header for multiple targets + +A prefix header that is generated for a cotired target can be applied to a different target +added in the same source directory: + + cotire(example) + get_target_property(_prefixHeader example COTIRE_CXX_PREFIX_HEADER) + ... + set_target_properties(other_target PROPERTIES COTIRE_CXX_PREFIX_HEADER_INIT "${_prefixHeader}") + cotire(other_target) + +The compilation of either target will trigger the generation of the prefix header. + +### configuring the generation of the prefix header + +There are multiple target properties which affect the generation of the prefix header: + +* `COTIRE_PREFIX_HEADER_IGNORE_PATH` can be set to a semicolon separated list of directories. If a +header file is found in one of these directories or sub-directories, it will be excluded from the +generated prefix header. + +* `COTIRE_PREFIX_HEADER_INCLUDE_PATH` can be set to a semicolon separated list of directories. If +a header file is included from one of these directories or sub-directories, it will be included +in the generated prefix header. + +If a header file is matched by both `COTIRE_PREFIX_HEADER_IGNORE_PATH` and +`COTIRE_PREFIX_HEADER_INCLUDE_PATH`, the option which yields the closer relative path match wins. +For example, if third-party libraries are part of the source tree in a directory called `Libs`, +the following setting will make cotire select header files from the third-party directory, but +ignore other project related headers in `CMAKE_SOURCE_DIR`: + + set_target_properties(example PROPERTIES + COTIRE_PREFIX_HEADER_IGNORE_PATH "${CMAKE_SOURCE_DIR}" + COTIRE_PREFIX_HEADER_INCLUDE_PATH "${CMAKE_SOURCE_DIR}/Libs") + +The properties `COTIRE_PREFIX_HEADER_IGNORE_PATH` and `COTIRE_PREFIX_HEADER_INCLUDE_PATH` can +also be set on directories. + +The following cache variables also affect the selection of prefix headers: + +* Directory paths in `COTIRE_ADDITIONAL_PREFIX_HEADER_IGNORE_PATH` will be added to the list of +ignored directories when the prefix header file is created. + +* `COTIRE_ADDITIONAL_PREFIX_HEADER_IGNORE_EXTENSIONS` can be used to ignore header files by file +extension. It defaults to the CMake list `inc;inl;ipp`. + +During development, changes to the project source files may affect the list of header files that +should be selected for inclusion in the prefix header (e.g., a standard include may be added or +removed from a target source file). Cotire does not automatically recreate the prefix header, +when a target source file is changed, because this would always trigger a re-compilation of the +precompiled header and would result in a rebuild of the whole target. To make the prefix header +creation dependent on changes to certain target source files, the source file property +`COTIRE_DEPENDENCY` can be set to `TRUE` for those files: + + set_property (SOURCE "example.cpp" PROPERTY COTIRE_DEPENDENCY "TRUE") + +### fixing linkage issues + +When a C++ program uses `extern "C"` on a system header file, cotire will not be able to detect +that the include file needs C linkage and will include the file with C++ linkage in the generated +prefix header instead. For example, the C interface to BLAS `cblas.h` usually has to be included +as `extern "C"` in a C++ program: + + extern "C" { + #include + } + +The presence of `extern "C"` includes will prevent cotired targets from being linked successfully +because of unresolved function references using the wrong linkage. To work around the problem, +the property `COTIRE_PREFIX_HEADER_IGNORE_PATH` can also include the full path of header files +besides directories. Here is an example: + + set_property(DIRECTORY + PROPERTY COTIRE_PREFIX_HEADER_IGNORE_PATH + "${ATLAS_INCLUDE_DIR}/cblas.h" + "${CMAKE_SOURCE_DIR}" "${CMAKE_BINARY_DIR}") + +That way `cblas.h` will not be included in the generated prefix header and will not cause problems +upon linking. + +### using a manually maintained unity source instead of the automatically generated one + +Cotire can be configured to use an existing manually maintained unity source file instead of the +automatically generated one. Set the target property `COTIRE_CXX_UNITY_SOURCE_INIT` to the path +of the existing unity source file. Its path is interpreted relative to the target source directory: + + set_target_properties(example PROPERTIES COTIRE_CXX_UNITY_SOURCE_INIT "example-all.cpp") + cotire(example) + +The property can also be set to a list of source files which will then make up the contents of +the generated unity source file. + +### configuring the generation of the unity source + +By default cotire adds all target source files to the generated unity source. In most cases a +unity build will not work out of the box, because unity builds [break][EoUB] the use of some C +and C++ language features. Unity build problems can be tackled in the following way: + +* Change the order of the source files in the `add_executable` or `add_library` calls. +Problematic source files should be moved towards the end. + +* Set the source file property `COTIRE_EXCLUDED` on problematic source files. The source file +will not be included in the unity source file and will be compiled separately when the unity build +is performed. + +* `COTIRE_UNITY_SOURCE_EXCLUDE_EXTENSIONS` can be used to exclude source files by file extension +from inclusion in the generated unity source. It defaults to the CMake list `m;mm`. + +* If the unity source file is too large and the compilation process runs into a compiler limit, +the target property `COTIRE_UNITY_SOURCE_MAXIMUM_NUMBER_OF_INCLUDES` can be set. If the target +contains more than that number of source files, cotire will create multiple unity source files +for it. Each unity source file is compiled separately when the unity build is performed. +The property is initialized by value of the cache variable +`COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES`. + +* Another way to break up a large unity source file is to set the source file property +`COTIRE_START_NEW_UNITY_SOURCE` to `TRUE` on selected target source files. If cotire encounters +this property, it will complete the current unity file and start a new one. The new unity source +file will include the source file as the first one. This property essentially works as a separator +for unity source files. + +### optimizing the build process for multiple processor cores + +To make use of all the machine's CPU cores for the unity compilation of a target, the target +property `COTIRE_UNITY_SOURCE_MAXIMUM_NUMBER_OF_INCLUDES` can be set to the string `-j`. Cotire +will then create as many unity file segments as there are CPU cores on the machine. Because +the unity file segments do not depend on each other, a multi-core aware build process can compile +the file segments in parallel. + +To explicitly specify the number of cores, append the number after `-j`, e.g. `-j 4` or `-j4`. + +For CMake generators that are multi-core aware by default (i.e., Visual Studio, JOM, Ninja), cotire +will automatically initialize the property to `-j`. For makefile based generators, this has to be +done explicitly by setting the cache variable `COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES`, i.e.: + + $ cmake -D COTIRE_MAXIMUM_NUMBER_OF_UNITY_INCLUDES=-j4 + $ make -j 4 + +### fixing macro definition clashes + +Many unity build problems stem from macro definitions leaking into other target source files, +where they may conflict with other definitions of the same name. Cotire adds the properties +`COTIRE_UNITY_SOURCE_PRE_UNDEFS` and `COTIRE_UNITY_SOURCE_POST_UNDEFS` to fix macro definition +clashes. + +As an example, if these properties are set on a source file of the example project: + + set_source_files_properties (example.cpp PROPERTIES + COTIRE_UNITY_SOURCE_PRE_UNDEFS "max;min" + COTIRE_UNITY_SOURCE_POST_UNDEFS "DEBUG_TYPE") + +This will make cotire add undefs to the generated unity source file. + + #ifdef __cplusplus + #include "/Users/sakra/Documents/cotire/src/main.cpp" + #undef min + #undef max + #include "/Users/sakra/Documents/cotire/src/example.cpp" + #undef DEBUG_TYPE + #include "/Users/sakra/Documents/cotire/src/log.cpp" + #endif + +The properties `COTIRE_UNITY_SOURCE_PRE_UNDEFS` and `COTIRE_UNITY_SOURCE_POST_UNDEFS` can also be +set on targets. Cotire will add `#undef` directives for each source file in the unity source then. + +### enabling verbose builds + +The cache variable `COTIRE_VERBOSE` can be set to `TRUE` to see all compile commands used when +generating the cotire related files. Cotire will also print the contents of the generated unity +source and the prefix header for verbose builds. `COTIRE_VERBOSE` defaults to `FALSE`. +When using a Makefile generator `COTIRE_VERBOSE` defaults to the value of the makefile variable +`VERBOSE` (i.e., `make VERBOSE=1`). + +### conditionally loading cotire + +To make a `CMakeLists.txt` robust against a missing `cotire.cmake` module, the following strategy +can be applied to using cotire: + + include(cotire OPTIONAL) + ... + add_executable(example main.cpp example.cpp log.cpp log.h example.h) + ... + if (COMMAND cotire) + cotire(example) + endif() + +The `include(cotire OPTIONAL)` will prevent CMake from raising an error if cotire cannot be +found. The actual calls to cotire need to be guarded by `if (COMMAND cotire)` blocks. + +### using cotire with compiler wrappers + +Cotire is compatible with CMake compiler wrappers. For example, the use of [ccache][ccch] may be +enabled in the following way upon configuring the project: + + $ export CC="/usr/local/bin/ccache /usr/bin/gcc" + $ export CXX="/usr/local/bin/ccache /usr/bin/g++" + $ export CCACHE_SLOPPINESS=pch_defines,time_macros + $ cmake .. + +Alternatively, for CMake 3.4 or later compiler wrappers can be enabled by pointing the CMake +variable `CMAKE_CXX_COMPILER_LAUNCHER` to the compiler wrapper executable upon configuring: + + $ cmake -D CMAKE_CXX_COMPILER_LAUNCHER=/usr/local/bin/ccache + +Note that with ccache in order for precompiled headers to work properly, it is necessary to set +the environment variable `CCACHE_SLOPPINESS` to `pch_defines,time_macros`. Otherwise the build +process may abort with the following error message: + + fatal error: file 'example_CXX_prefix.hxx' has been modified since the precompiled header + 'example_CXX_prefix.hxx.gch' was built + +Also see the [ccache manual][ccch_pch]. + +### applying cotire to object library targets + +CMake 2.8.8 introduced a new type of library target called [object library][objlib]. An object +library is a convenience target that compiles multiple source files but does not create a linked +target library for them, e.g.: + + add_library(myLib OBJECT lib1.cpp lib2.cpp lib3.cpp) + add_executable(exeA $ mainA.cpp) + add_executable(exeB $ mainB.cpp) + +The `cotire` function can be applied to an object library target in a familiar fashion: + + add_library(myLib OBJECT lib1.cpp lib2.cpp lib3.cpp) + cotire(myLib) + # use unity object library for executables + add_executable(exeA $ mainA.cpp) + add_executable(exeB $ mainB.cpp) + +Because object library targets do not support `PRE_BUILD` actions, precompiled header usage cannot +be enabled for them for Xcode projects generated with CMake. Unity builds work as expected, though. + +### automatically setting up linked libraries in the unity target + +The setting of the target property `COTIRE_UNITY_LINK_LIBRARIES_INIT` controls the linking +strategy for the generated unit target. + +If this property is empty or set to `NONE`, the generated unity target's link libraries have to be +set up manually with subsequent `target_link_libraries` calls: + + set_target_properties(example PROPERTIES COTIRE_UNITY_LINK_LIBRARIES_INIT "NONE") + ... + cotire(example) + target_link_libraries(MyExecutable_unity ${MyExecutableLibraries}) + +If this property is set to `COPY`, the unity target's link libraries will be copied from the +original target. + +If this property is set to `COPY_UNITY`, the unity target's link libraries will be copied from the +original target but instead of copying a linked target verbatim, the target's corresponding unity +target will be preferred, provided one exists. This also applies to object libraries, which have +been added to the original target with a `TARGET_OBJECTS` generator expression. + +As of cotire 1.7.0, the default linking strategy for unit targets is `COPY_UNITY`. + +The property `COTIRE_UNITY_LINK_LIBRARIES_INIT` can also be set on directories. A target inherits +the property value from its enclosing directory. To make all targets in the project use the +`COPY` strategy, the directory property can be set in the outermost `CMakeList.txt` file: + + include(cotire) + ... + set_property(DIRECTORY PROPERTY COTIRE_UNITY_LINK_LIBRARIES_INIT "COPY") + +### using cotire with Qt + +Cotire is compatible with both Qt4 and Qt5 projects that use CMake as build system. + +If a CMake target's `AUTOMOC` or `AUTOUIC` properties are set, the generated unity target will +automatically add a dependency to the implicitly generated `_automoc` target to ensure +that `moc` and `uic` are run on the individual source files. + +The unity target will also include the implicitly generated `_automoc.cpp` source file. + +The `Patches` directory contains examples for the [Qt4][fsedit_qt4] and [Qt5][fsedit_qt5] based +variants of the *FSEditor* sample Qt application. + +### installing files generated by unity targets + +Cotire cannot set up a `install_unity` target that mimics the `install` target automatically, +because CMake does not provide the necessary information about the existing install rules +programmatically. + +When using a Makefile generator, you can use the following workaround (thanks to peterhuene): + + $ make all_unity + $ make install/fast + +The `install/fast` does not trigger a build, but will use the binaries built by the `all_unity` +target. + +For other generators, set up an `install_unity` target manually. First set up install rules for +all unity targets, that mimic the install rules for the original targets: + + install(TARGETS example_unity RUNTIME DESTINATION "bin" OPTIONAL COMPONENT "unity") + +This installs the `example` executable built by the unity target to the `bin` folder. The install +rules for unity targets must use a custom install component. Then add a global `install_unity` +target that performs the installation of all unity targets: + + add_custom_target(install_unity + COMMAND ${CMAKE_COMMAND} -DCOMPONENT=unity -P cmake_install.cmake + COMMENT "Install the unity-built project..." + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}) + add_dependencies(unity_install example_unity) + +The global `install_unity` target must depend on all unity targets that should be installed. + +### customized inclusion of system headers + +If a system header ends up in a precompiled header, it is not possible to customize the inclusion +of that header in a source file through preprocessor defines. + +For example, under Windows one may want to include `Windows.h` with `NOMINMAX` defined to prevent +the definition of the `min` and `max` macros: + + #define NOMINMAX + #include + +The dependency of `Windows.h` on the preprocessor define `NOMINMAX` will not be picked up by cotire +automatically upon adding `Windows.h` to the prefix header. To work around the problem, make the +dependency explicit by using `add_definitions` in the corresponding `CMakeLists.txt`: + + if (WIN32) + # prevent definition of min and max macros through inclusion of Windows.h + add_definitions("-DNOMINMAX") + endif() + +That way, the preprocessor define `NOMINMAX` will be picked up by cotire and applied to the +pre-compilation of the prefix header. + +### organize includes added to the prefix header + +Sometimes the order of the includes in the automatically generated prefix header may result in +compilation errors due to subtile header dependencies. + +To work around the problem, the target property `COTIRE_PREFIX_HEADER_INCLUDE_PRIORITY_PATH` +can be set to a list of directories. Header files whose path matches one of these directories will +be inserted at the beginning of generated prefix header. Header files are sorted according to +the order of the directories in the property. Headers not matching one of these directories are +left untouched. + +The property `COTIRE_PREFIX_HEADER_INCLUDE_PRIORITY_PATH` can also be set on directories. A target +inherits the property value from its enclosing directory. + +common pitfalls +--------------- + +### include the `cotire.cmake` module correctly + +If CMake issues the message `Unknown CMake command "cotire"`, double check that the cotire module +has been included correctly in your project. See the manual section "cotire basic usage". + +### do not modify a target's build related properties after applying cotire + +Cotire only considers build related settings of a target at the time of the `cotire` function call. +If target properties that control the build are changed after the call to the `cotire` function, +the build rules set up by cotire for the precompiled header and unity build may not work correctly. + +Don't do this: + + add_executable(example main.cpp example.cpp log.cpp log.h example.h) + cotire(example) + ... + set_target_properties(example PROPERTIES POSITION_INDEPENDENT_CODE ON) # affects build + + +### always apply cotire in the same source directory where a target has been added + +CMake targets are globally visible. Nevertheless, it is important that the `cotire` function is +called for a target in the exact same directory that creates the target with `add_library` or +`add_executable`. + +Don't do this: + + add_subdirectory(src) + ... + cotire(mytarget) # mytarget added in src directory + +Cotire may fail to inspect the target's source files correctly, if the target has been added in a +different directory and you may get odd messages about missing source files. + +known issues +------------ + +### Ninja compatibility + +Under Ninja indirect prefix header dependencies are ignored by the generated build system. Cotire +uses the `IMPLICIT_DEPENDS` option of `add_custom_command` to make the precompiled header depend +on header files indirectly included by the prefix header. The `IMPLICIT_DEPENDS` option is not +supported by CMake's Ninja generator. See [CMake issue][ninja_issue]. + +### using source files for multiple targets + +When the same set of source files is used for different targets (e.g., for producing a static +and a shared library variant from the same sources), using a precompiled header may not work. +Under certain circumstances, cotire cannot enable the precompiled header usage by changing the +`COMPILE_FLAGS` property of the whole target, but must set the `COMPILE_FLAGS` properties of +individual target source files instead. This will break the usage of the source file for multiple +targets. + +### multi-architecture builds under Mac OS X + +Neither GCC nor Clang support the use of precompiled headers when performing a Mac OS X +multi-architecture build (e.g., using option `-DCMAKE_OSX_ARCHITECTURES=i386;x86_64`). + +### Objective-C + +CMake targets that contain Objective-C or Objective-C++ source files cannot be cotired. Source +files ending with .m and .mm are excluded by default through the initial default setting of +`COTIRE_UNITY_SOURCE_EXCLUDE_EXTENSIONS`. + +### Intel C++ + +Intel C++ support has only been tested with [Intel C++ Composer XE 2013 for Linux][icc_linux] and +may not work with other platforms or versions. + +The Intel compiler may issue incorrect warnings #672 (the command line options do not match those +used when precompiled header was created) or #673 (the initial sequence of preprocessing directives +is not compatible with those of precompiled header file) upon compilation of cotired targets. + +### IncrediBuild + +Cotire is not compatible with [Xoreax IncrediBuild][XGE]. + +[1260]:http://www.cmake.org/Bug/view.php?id=1260 +[ccch]:https://ccache.samba.org/ +[ccch_pch]:https://ccache.samba.org/manual.html#_precompiled_headers +[clang_pch]:http://clang.llvm.org/docs/UsersManual.html#precompiled-headers +[fsedit_qt4]:http://www.vikingsoft.eu/fseditor.html +[fsedit_qt5]:https://github.com/joonhwan/fsedit-qt5 +[gcc_pch]:https://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html +[msvc_pch]:https://msdn.microsoft.com/en-us/library/szfdksca(v=vs.90).aspx +[msvc_pch_create]:https://msdn.microsoft.com/en-us/library/7zc28563(v=vs.90).aspx +[msvc_pch_use]:https://msdn.microsoft.com/en-us/library/z0atkd6c(v=vs.90).aspx +[ninja_issue]:https://cmake.org/Bug/view.php?id=13234 +[EoUB]:https://engineering-game-dev.com/2009/12/15/the-evils-of-unity-builds/ +[pch]:https://en.wikipedia.org/wiki/Precompiled_header +[scu]:https://en.wikipedia.org/wiki/Single_Compilation_Unit +[objlib]:https://cmake.org/cmake/help/v2.8.12/cmake.html#command:add_library +[pfh]:https://en.wikipedia.org/wiki/Prefix_header +[icc_linux]:https://software.intel.com/en-us/c-compilers/ipsxe-support +[XGE]:https://www.incredibuild.com/ diff --git a/dep/cotire/README.md b/dep/cotire/README.md new file mode 100644 index 00000000000..0a048b204c4 --- /dev/null +++ b/dep/cotire/README.md @@ -0,0 +1,137 @@ +cotire +====== + +Cotire (compile time reducer) is a CMake module that speeds up the build process of CMake based +build systems by fully automating techniques as [precompiled header][pch] usage and +[single compilation unit][scu] builds for C and C++. + +features +-------- + +* Non-intrusive. Requires no source code modification and only minimal changes to CMake list files. +* Automatically generates a [single compilation unit][scu] (aka unity source file) for a CMake target. +* Automatically generates a [prefix header][pfh] by tracking includes used by a CMake target. +* Automatically precompiles prefix header and applies resulting [precompiled header][pch] to a CMake target. +* Alternatively, allows for using manually maintained unity source and prefix header files. +* Supports C/C++ compilers Clang, GCC, Intel and Visual Studio C++. +* Supports mixed language CMake targets. +* Supports console (Makefile generator) and IDE (Visual Studio and Xcode) based builds. +* Compatible with CMake single build type and CMake multi-configuration builds. +* Compatible with most CMake generators (including [Ninja][ninja]). +* Supports multi-core unity builds for some generators (make -j, [jom][jom], Visual Studio, Ninja). +* Leverages native precompiled header generation features of IDEs (Visual Studio and Xcode). +* Compatible with CMake's [cross-compiling][ccrc] support. +* Compatible with compiler wrappers like [ccache][ccch]. +* Applicable to CMake based Qt projects. +* Tested with Windows, Linux and OS X. +* MIT licensed. + +requirements +------------ + +* [CMake 2.8.12][cmk] or newer. The executable `cmake` should be on the system path. +* [Visual Studio C++][vslstd], [MinGW][mingw] or [Cygwin][cgwn] under Windows. +* [GCC][gcc] or [Clang][clang] under Linux or OS X. +* [Intel C++ compiler][intel] under Windows, Linux or OS X. +* [Xcode][xcdt] application or Xcode Command Line Tools under OS X. + +installation +------------ + +Copy the file `CMake/cotire.cmake` to the module directory of your CMake project. In the +top-level `CMakeList.txt` file, add the module directory to the CMake module search path: + + set (CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/CMake") + +usage +----- + +To use cotire in your CMake project, add the following include directive to the beginning of the +top-level `CMakeList.txt`: + + include(cotire) + +To speed the build process of a CMake library or executable target, just apply the `cotire` +function to the target: + + add_executable(MyExecutable ${MyExecutableSources}) + target_link_libraries(MyExecutable ${MyExecutableLibraries}) + cotire(MyExecutable) + +Cotire looks at the properties of the target provided by CMake (e.g., target type, source files, +compile flags, preprocessor defines, include directories, ...) and sets up custom commands that +will generate a unity source file, a prefix header and a precompiled header at build time +specially tailored to the target. + +For the generation of the prefix header, cotire will automatically choose headers used by the +target that are outside of the project directory and thus are likely to change infrequently. +The precompiled prefix header is then applied to the target to speed up the compilation process. + +To use an existing manually maintained prefix header instead of the automatically generated one, +set the `COTIRE_CXX_PREFIX_HEADER_INIT` property before invoking cotire: + + set_target_properties(MyExecutable PROPERTIES COTIRE_CXX_PREFIX_HEADER_INIT "stdafx.h") + cotire(MyExecutable) + +As a side effect, cotire generates a new target named `MyExecutable_unity`, which lets you perform +a unity build for the original target. The unity target inherits all build settings from the +original target, including linked library dependencies. + +For Makefile based generators you can then invoke a unity build that produces the same output as +the original target, but does so much faster by entering: + + $ make MyExecutable_unity + +See the advanced usage section of the [cotire manual][manual] for information on how to +configure the cotire process (e.g., how to make the unity build use all available processor +cores). + +The directory `Patches` contains patch files to enable cotire for some popular open sources +packages that use CMake as a build system. + +speedup +------- + +Depending on factors like hardware, compiler, the number of files in the target and the complexity +of the C/C++ code, the build process of targets that use a cotire generated precompiled header +will be sped up from 10 to 40 percent. Using precompiled headers however is not without +[issues][PCHH] and may not work for some programs. + +A unity build may be up to 90 percent faster than the one file at a time build of the original +target. Single compilation unit builds however are very unlikely to work without source code +modifications, because they [break][EoUB] the use of some C and C++ language features. + +Generally, modern C++ code which makes heavy use of header-only libraries will profit the most from +cotiring. + +This [blog post][shrp] discusses speedup results obtained for real-world projects. + +known issues +------------ + +* CMake configure time will increase for cotired targets. +* The size of the CMake build folder will increase, because precompiled headers are large binaries. +* It is not possible to share precompiled headers generated by cotire between CMake targets. + Multiple targets can share a generated prefix header, though (see the [cotire manual][manual]). +* Cotire is not compatible with [Xoreax IncrediBuild][XGE]. + +[ccch]:https://ccache.samba.org/ +[ccrc]:https://cmake.org/Wiki/CMake_Cross_Compiling +[cgwn]:http://www.cygwin.com/ +[clang]:http://clang.llvm.org/ +[cmk]:https://cmake.org/download/ +[gcc]:https://gcc.gnu.org/ +[manual]:https://github.com/sakra/cotire/blob/master/MANUAL.md +[mingw]:http://www.mingw.org/ +[ninja]:https://ninja-build.org/ +[pch]:https://en.wikipedia.org/wiki/Precompiled_header +[pfh]:https://en.wikipedia.org/wiki/Prefix_header +[scu]:https://en.wikipedia.org/wiki/Single_Compilation_Unit +[vslstd]:https://www.visualstudio.com/ +[xcdt]:https://developer.apple.com/xcode/ +[PCHH]:https://gcc.gnu.org/wiki/PCHHaters +[EoUB]:https://engineering-game-dev.com/2009/12/15/the-evils-of-unity-builds/ +[jom]:http://wiki.qt.io/Jom +[intel]:https://software.intel.com/en-us/c-compilers +[XGE]:https://www.incredibuild.com/ +[shrp]:http://unriskinsight.blogspot.co.at/2014/09/sharpen-your-tools.html diff --git a/dep/cotire/license b/dep/cotire/license new file mode 100644 index 00000000000..33a6ea7ce93 --- /dev/null +++ b/dep/cotire/license @@ -0,0 +1,22 @@ +Copyright (c) 2012-2017 Sascha Kratky + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/dep/efsw/CMakeLists.txt b/dep/efsw/CMakeLists.txt index f268558a527..b37e5021e0a 100644 --- a/dep/efsw/CMakeLists.txt +++ b/dep/efsw/CMakeLists.txt @@ -73,6 +73,8 @@ if (BUILD_SHARED_LIBS) ${CMAKE_CURRENT_SOURCE_DIR}/src) target_link_libraries(efsw + PRIVATE + trinity-dependency-interface PUBLIC threads ${OPTIONAL_MAC_LINK_LIBRARIES}) diff --git a/dep/fmt/CMakeLists.txt b/dep/fmt/CMakeLists.txt index b6f8c3e409f..595bf001fb1 100644 --- a/dep/fmt/CMakeLists.txt +++ b/dep/fmt/CMakeLists.txt @@ -35,6 +35,7 @@ endif() add_library(fmt STATIC ${FMT_SOURCES}) target_include_directories(fmt + PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) @@ -46,6 +47,10 @@ target_compile_definitions(fmt -DFMT_USE_DELETED_FUNCTIONS -DFMT_USE_EXTERN_TEMPLATES) +target_link_libraries(fmt + PRIVATE + trinity-dependency-interface) + set_target_properties(fmt PROPERTIES FOLDER diff --git a/dep/fmt/fmt/format.h b/dep/fmt/fmt/format.h index dd8d2836005..bd99746a58c 100644 --- a/dep/fmt/fmt/format.h +++ b/dep/fmt/fmt/format.h @@ -157,7 +157,7 @@ typedef __int64 intmax_t; # define FMT_HAS_CXX17_ATTRIBUTE_MAYBE_UNUSED // VC++ 1910 support /std: option and that will set _MSVC_LANG macro // Clang with Microsoft CodeGen doesn't define _MSVC_LANG macro -#elif defined(_MSVC_LANG) && _MSVC_LANG > 201402 +#elif defined(_MSVC_LANG) && _MSVC_LANG > 201402 && _MSC_VER >= 1910 # define FMT_HAS_CXX17_ATTRIBUTE_MAYBE_UNUSED #endif @@ -200,6 +200,12 @@ typedef __int64 intmax_t; # endif #endif +#if __cplusplus >= 201103L || FMT_MSC_VER >= 1700 +# define FMT_USE_ALLOCATOR_TRAITS 1 +#else +# define FMT_USE_ALLOCATOR_TRAITS 0 +#endif + // Check if exceptions are disabled. #if defined(__GNUC__) && !defined(__EXCEPTIONS) # define FMT_EXCEPTIONS 0 @@ -869,7 +875,12 @@ void MemoryBuffer::grow(std::size_t size) { std::size_t new_capacity = this->capacity_ + this->capacity_ / 2; if (size > new_capacity) new_capacity = size; +#if FMT_USE_ALLOCATOR_TRAITS + T *new_ptr = + std::allocator_traits::allocate(*this, new_capacity, FMT_NULL); +#else T *new_ptr = this->allocate(new_capacity, FMT_NULL); +#endif // The following code doesn't throw, so the raw pointer above doesn't leak. std::uninitialized_copy(this->ptr_, this->ptr_ + this->size_, make_ptr(new_ptr, new_capacity)); @@ -3623,10 +3634,10 @@ void arg(WStringRef, const internal::NamedArg&) FMT_DELETED_OR_UNDEFINED; #define FMT_GET_ARG_NAME(type, index) arg##index #if FMT_USE_VARIADIC_TEMPLATES -# define FMT_VARIADIC_(Char, ReturnType, func, call, ...) \ +# define FMT_VARIADIC_(Const, Char, ReturnType, func, call, ...) \ template \ ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \ - const Args & ... args) { \ + const Args & ... args) Const { \ typedef fmt::internal::ArgArray ArgArray; \ typename ArgArray::Type array{ \ ArgArray::template make >(args)...}; \ @@ -3636,35 +3647,35 @@ void arg(WStringRef, const internal::NamedArg&) FMT_DELETED_OR_UNDEFINED; #else // Defines a wrapper for a function taking __VA_ARGS__ arguments // and n additional arguments of arbitrary types. -# define FMT_WRAP(Char, ReturnType, func, call, n, ...) \ +# define FMT_WRAP(Const, Char, ReturnType, func, call, n, ...) \ template \ inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__), \ - FMT_GEN(n, FMT_MAKE_ARG)) { \ + FMT_GEN(n, FMT_MAKE_ARG)) Const { \ fmt::internal::ArgArray::Type arr; \ FMT_GEN(n, FMT_ASSIGN_##Char); \ call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList( \ fmt::internal::make_type(FMT_GEN(n, FMT_MAKE_REF2)), arr)); \ } -# define FMT_VARIADIC_(Char, ReturnType, func, call, ...) \ - inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__)) { \ +# define FMT_VARIADIC_(Const, Char, ReturnType, func, call, ...) \ + inline ReturnType func(FMT_FOR_EACH(FMT_ADD_ARG_NAME, __VA_ARGS__)) Const { \ call(FMT_FOR_EACH(FMT_GET_ARG_NAME, __VA_ARGS__), fmt::ArgList()); \ } \ - FMT_WRAP(Char, ReturnType, func, call, 1, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 2, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 3, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 4, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 5, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 6, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 7, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 8, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 9, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 10, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 11, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 12, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 13, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 14, __VA_ARGS__) \ - FMT_WRAP(Char, ReturnType, func, call, 15, __VA_ARGS__) + FMT_WRAP(Const, Char, ReturnType, func, call, 1, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 2, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 3, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 4, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 5, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 6, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 7, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 8, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 9, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 10, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 11, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 12, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 13, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 14, __VA_ARGS__) \ + FMT_WRAP(Const, Char, ReturnType, func, call, 15, __VA_ARGS__) #endif // FMT_USE_VARIADIC_TEMPLATES /** @@ -3695,10 +3706,16 @@ void arg(WStringRef, const internal::NamedArg&) FMT_DELETED_OR_UNDEFINED; \endrst */ #define FMT_VARIADIC(ReturnType, func, ...) \ - FMT_VARIADIC_(char, ReturnType, func, return func, __VA_ARGS__) + FMT_VARIADIC_(, char, ReturnType, func, return func, __VA_ARGS__) + +#define FMT_VARIADIC_CONST(ReturnType, func, ...) \ + FMT_VARIADIC_(const, char, ReturnType, func, return func, __VA_ARGS__) #define FMT_VARIADIC_W(ReturnType, func, ...) \ - FMT_VARIADIC_(wchar_t, ReturnType, func, return func, __VA_ARGS__) + FMT_VARIADIC_(, wchar_t, ReturnType, func, return func, __VA_ARGS__) + +#define FMT_VARIADIC_CONST_W(ReturnType, func, ...) \ + FMT_VARIADIC_(const, wchar_t, ReturnType, func, return func, __VA_ARGS__) #define FMT_CAPTURE_ARG_(id, index) ::fmt::arg(#id, id) @@ -3741,17 +3758,19 @@ template unsigned parse_nonnegative_int(const Char *&s) { assert('0' <= *s && *s <= '9'); unsigned value = 0; - do { - unsigned new_value = value * 10 + (*s++ - '0'); - // Check if value wrapped around. - if (new_value < value) { - value = (std::numeric_limits::max)(); - break; - } - value = new_value; - } while ('0' <= *s && *s <= '9'); // Convert to unsigned to prevent a warning. unsigned max_int = (std::numeric_limits::max)(); + unsigned big = max_int / 10; + do { + // Check for overflow. + if (value > big) { + value = max_int + 1; + break; + } + value = value * 10 + (*s - '0'); + ++s; + } while ('0' <= *s && *s <= '9'); + // Convert to unsigned to prevent a warning. if (value > max_int) FMT_THROW(FormatError("number is too big")); return value; @@ -3923,7 +3942,8 @@ const Char *BasicFormatter::format( default: FMT_THROW(FormatError("width is not integer")); } - if (value > (std::numeric_limits::max)()) + unsigned max_int = (std::numeric_limits::max)(); + if (value > max_int) FMT_THROW(FormatError("number is too big")); spec.width_ = static_cast(value); } @@ -3961,7 +3981,8 @@ const Char *BasicFormatter::format( default: FMT_THROW(FormatError("precision is not integer")); } - if (value > (std::numeric_limits::max)()) + unsigned max_int = (std::numeric_limits::max)(); + if (value > max_int) FMT_THROW(FormatError("number is too big")); spec.precision_ = static_cast(value); } else { diff --git a/dep/fmt/fmt/printf.h b/dep/fmt/fmt/printf.h index db91022c598..46205a78eee 100644 --- a/dep/fmt/fmt/printf.h +++ b/dep/fmt/fmt/printf.h @@ -125,7 +125,7 @@ class ArgConverter : public ArgVisitor, void> { using internal::Arg; typedef typename internal::Conditional< is_same::value, U, T>::type TargetType; - if (sizeof(TargetType) <= sizeof(int)) { + if (const_check(sizeof(TargetType) <= sizeof(int))) { // Extra casts are used to silence warnings. if (is_signed) { arg_.type = Arg::INT; diff --git a/dep/g3dlite/CMakeLists.txt b/dep/g3dlite/CMakeLists.txt index a952370c31a..99dd866cb45 100644 --- a/dep/g3dlite/CMakeLists.txt +++ b/dep/g3dlite/CMakeLists.txt @@ -62,6 +62,8 @@ target_include_directories(g3dlib ${CMAKE_CURRENT_SOURCE_DIR}/include) target_link_libraries(g3dlib + PRIVATE + trinity-dependency-interface PUBLIC zlib threads) diff --git a/dep/gsoap/CMakeLists.txt b/dep/gsoap/CMakeLists.txt index 1c7168d7753..9345dcc8556 100644 --- a/dep/gsoap/CMakeLists.txt +++ b/dep/gsoap/CMakeLists.txt @@ -18,6 +18,16 @@ target_include_directories(gsoap PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) +target_compile_definitions(gsoap + PUBLIC + -DWITH_OPENSSL) + +target_link_libraries(gsoap + PRIVATE + trinity-dependency-interface + PUBLIC + openssl) + set_target_properties(gsoap PROPERTIES FOLDER diff --git a/dep/jemalloc/CMakeLists.txt b/dep/jemalloc/CMakeLists.txt index 46f513e3f2c..39a48004a8e 100644 --- a/dep/jemalloc/CMakeLists.txt +++ b/dep/jemalloc/CMakeLists.txt @@ -83,6 +83,8 @@ if(CMAKE_SYSTEM_NAME MATCHES "Linux" AND NOT NOJEM) -D_REENTRAN) target_link_libraries(jemalloc + PRIVATE + trinity-dependency-interface PUBLIC threads valgrind diff --git a/dep/libzmq/CMakeLists.txt b/dep/libzmq/CMakeLists.txt index a569fffdcce..b35c35c6f6a 100644 --- a/dep/libzmq/CMakeLists.txt +++ b/dep/libzmq/CMakeLists.txt @@ -77,15 +77,12 @@ set (libzmq_STAT_SRCS src/zap_client.cpp ) -add_definitions(-DZMQ_USE_SELECT) -add_definitions(-DZMQ_STATIC) - if (WIN32) - add_definitions(-DZMQ_HAVE_WINDOWS) + set(ZMQ_PLATFORM -DZMQ_HAVE_WINDOWS) elseif (APPLE) - add_definitions(-DZMQ_HAVE_OSX) + set(ZMQ_PLATFORM -DZMQ_HAVE_OSX) elseif (UNIX) - add_definitions(-DZMQ_HAVE_LINUX) + set(ZMQ_PLATFORM -DZMQ_HAVE_LINUX) endif() add_library(libzmq STATIC ${libzmq_STAT_SRCS}) @@ -95,8 +92,21 @@ target_include_directories(libzmq ${CMAKE_CURRENT_SOURCE_DIR}/include PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) + +target_link_libraries(libzmq + PRIVATE + trinity-dependency-interface + PUBLIC + bzip2 + zlib) set_target_properties(libzmq PROPERTIES FOLDER "dep") + +target_compile_definitions(libzmq + PUBLIC + -DZMQ_USE_SELECT + -DZMQ_STATIC + ${ZMQ_PLATFORM}) diff --git a/dep/libzmq/src/platform.hpp b/dep/libzmq/src/platform.hpp index 964ee900551..a38b7776aaa 100644 --- a/dep/libzmq/src/platform.hpp +++ b/dep/libzmq/src/platform.hpp @@ -1,7 +1,7 @@ #ifndef __PLATFORM_HPP_INCLUDED__ #define __PLATFORM_HPP_INCLUDED__ -#define ZMQ_HAVE_WINDOWS +// #define ZMQ_HAVE_WINDOWS // MSVC build configuration is controlled via options exposed in the Visual // Studio user interface. The option to use libsodium is not exposed in the diff --git a/dep/recastnavigation/Detour/CMakeLists.txt b/dep/recastnavigation/Detour/CMakeLists.txt index 64860ab2039..433337cd00d 100644 --- a/dep/recastnavigation/Detour/CMakeLists.txt +++ b/dep/recastnavigation/Detour/CMakeLists.txt @@ -25,6 +25,8 @@ target_include_directories(Detour ${CMAKE_CURRENT_SOURCE_DIR}/Include) target_link_libraries(Detour + PRIVATE + trinity-dependency-interface PUBLIC zlib) diff --git a/dep/recastnavigation/Recast/CMakeLists.txt b/dep/recastnavigation/Recast/CMakeLists.txt index e7d87c8458c..60164bb6997 100644 --- a/dep/recastnavigation/Recast/CMakeLists.txt +++ b/dep/recastnavigation/Recast/CMakeLists.txt @@ -29,6 +29,8 @@ target_include_directories(Recast ${CMAKE_CURRENT_SOURCE_DIR}/Include) target_link_libraries(Recast + PRIVATE + trinity-dependency-interface PUBLIC zlib) diff --git a/dep/zlib/CMakeLists.txt b/dep/zlib/CMakeLists.txt index 1d16f7b5a51..2500395ae45 100644 --- a/dep/zlib/CMakeLists.txt +++ b/dep/zlib/CMakeLists.txt @@ -43,6 +43,10 @@ else() PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) + target_link_libraries(zlib + PRIVATE + trinity-dependency-interface) + set_target_properties(zlib PROPERTIES FOLDER diff --git a/dep/zmqpp/CMakeLists.txt b/dep/zmqpp/CMakeLists.txt index 9248d34c758..bb1e4a3774f 100644 --- a/dep/zmqpp/CMakeLists.txt +++ b/dep/zmqpp/CMakeLists.txt @@ -10,20 +10,18 @@ file(GLOB_RECURSE sources_zmqpp zmqpp/*.cpp zmqpp/*.hpp zmqpp/*.h) -include_directories(libzmq) - -add_library(zmqpp STATIC - ${sources_zmqpp} -) - -target_link_libraries(zmqpp - PUBLIC - libzmq) +add_library(zmqpp STATIC ${sources_zmqpp}) target_include_directories(zmqpp PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) +target_link_libraries(zmqpp + PRIVATE + trinity-dependency-interface + PUBLIC + libzmq) + set_target_properties(zmqpp PROPERTIES FOLDER diff --git a/sql/base/characters_database.sql b/sql/base/characters_database.sql index 7d65d6fd8aa..97e9ceac9d2 100644 --- a/sql/base/characters_database.sql +++ b/sql/base/characters_database.sql @@ -2439,7 +2439,8 @@ DROP TABLE IF EXISTS `item_loot_money`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `item_loot_money` ( `container_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'guid of container (item_instance.guid)', - `money` int(10) NOT NULL DEFAULT '0' COMMENT 'money loot (in copper)' + `money` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'money loot (in copper)', + PRIMARY KEY (`container_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; @@ -2952,7 +2953,8 @@ INSERT INTO `updates` VALUES ('2017_12_17_00_characters.sql','937E8F51DC74AC41FF8F213CE36C69DDEB878D6A','ARCHIVED','2017-12-17 00:00:00',0), ('2018_01_15_00_characters.sql','43C8E4549E1AA9610B377BC7139C88C63D0DC193','ARCHIVED','2018-01-15 00:00:00',0), ('2018_02_16_00_characters.sql','F1254689CE8A0B0AF149E557830287FF583B8D91','ARCHIVED','2018-02-16 00:00:00',0), -('2018_03_16_00_characters.sql','722EAFB7F508882F584DCAE61F97F1A11EDE126E','ARCHIVED','2018-03-16 00:00:00',0); +('2018_03_16_00_characters.sql','722EAFB7F508882F584DCAE61F97F1A11EDE126E','RELEASED','2018-03-16 00:00:00',0), +('2018_03_25_00_characters.sql','4FE3C6866A6DCD4926D451F6009464D290C2EF1F','RELEASED','2018-03-25 00:00:00',0); /*!40000 ALTER TABLE `updates` ENABLE KEYS */; UNLOCK TABLES; diff --git a/sql/updates/characters/4.3.4/2018_03_25_00_characters.sql b/sql/updates/characters/4.3.4/2018_03_25_00_characters.sql new file mode 100644 index 00000000000..117e3baa78d --- /dev/null +++ b/sql/updates/characters/4.3.4/2018_03_25_00_characters.sql @@ -0,0 +1,3 @@ +ALTER TABLE `item_loot_money` +CHANGE `money` `money` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'money loot (in copper)', +ADD PRIMARY KEY (`container_id`); diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 27a5495b3d8..83c3c6fec3c 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -8,6 +8,13 @@ # WITHOUT ANY WARRANTY, to the extent permitted by law; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +if(WIN32) + set(sources_windows + ${CMAKE_SOURCE_DIR}/src/common/Debugging/WheatyExceptionReport.cpp + ${CMAKE_SOURCE_DIR}/src/common/Debugging/WheatyExceptionReport.h + ) +endif(WIN32) + add_subdirectory(genrev) add_subdirectory(common) diff --git a/src/common/Asio/AsioHacksFwd.h b/src/common/Asio/AsioHacksFwd.h new file mode 100644 index 00000000000..457f53f39b1 --- /dev/null +++ b/src/common/Asio/AsioHacksFwd.h @@ -0,0 +1,94 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef AsioHacksFwd_h__ +#define AsioHacksFwd_h__ + +#include + +/** + Collection of forward declarations to improve compile time + */ +namespace boost +{ + namespace posix_time + { + class ptime; + } + + namespace asio + { + template + struct time_traits; + + namespace ip + { + class address; + + class tcp; + + template + class basic_endpoint; + + typedef basic_endpoint tcp_endpoint; + } + +#if BOOST_VERSION >= 106600 + template + class basic_deadline_timer; + + typedef basic_deadline_timer> deadline_timer; + + namespace ip + { + template + class basic_resolver; + + typedef basic_resolver tcp_resolver; + } +#else + template + class deadline_timer_service; + + template + class basic_deadline_timer; + + typedef basic_deadline_timer, deadline_timer_service>> deadline_timer; + + namespace ip + { + template + class resolver_service; + + template + class basic_resolver; + + typedef basic_resolver> tcp_resolver; + } +#endif + } +} + +namespace Trinity +{ + namespace Asio + { + class Strand; + } +} + +#endif // AsioHacksFwd_h__ diff --git a/src/common/Asio/IoContext.h b/src/common/Asio/IoContext.h new file mode 100644 index 00000000000..50411b76957 --- /dev/null +++ b/src/common/Asio/IoContext.h @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef IoContext_h__ +#define IoContext_h__ + +#include + +#if BOOST_VERSION >= 106600 +#include +#include +#define IoContextBaseNamespace boost::asio +#define IoContextBase io_context +#else +#include +#define IoContextBaseNamespace boost::asio +#define IoContextBase io_service +#endif + +namespace Trinity +{ + namespace Asio + { + class IoContext : public IoContextBaseNamespace::IoContextBase + { + using IoContextBaseNamespace::IoContextBase::IoContextBase; + }; + + template + inline decltype(auto) post(IoContextBaseNamespace::IoContextBase& ioContext, T&& t) + { +#if BOOST_VERSION >= 106600 + return boost::asio::post(ioContext, std::forward(t)); +#else + return ioContext.post(std::forward(t)); +#endif + } + + template + inline decltype(auto) get_io_context(T&& ioObject) + { +#if BOOST_VERSION >= 106600 + return ioObject.get_executor().context(); +#else + return ioObject.get_io_service(); +#endif + } + } +} + +#endif // IoContext_h__ diff --git a/src/common/Asio/IpAddress.h b/src/common/Asio/IpAddress.h new file mode 100644 index 00000000000..a4994012036 --- /dev/null +++ b/src/common/Asio/IpAddress.h @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef IpAddress_h__ +#define IpAddress_h__ + +#include "Define.h" +#include + +namespace Trinity +{ + namespace Net + { +#if BOOST_VERSION >= 106600 + using boost::asio::ip::make_address; + using boost::asio::ip::make_address_v4; + inline uint32 address_to_uint(boost::asio::ip::address_v4 const& address) { return address.to_uint(); } +#else + inline boost::asio::ip::address make_address(char const* str) { return boost::asio::ip::address::from_string(str); } + inline boost::asio::ip::address make_address(char const* str, boost::system::error_code& ec) { return boost::asio::ip::address::from_string(str, ec); } + inline boost::asio::ip::address make_address(std::string const& str) { return boost::asio::ip::address::from_string(str); } + inline boost::asio::ip::address make_address(std::string const& str, boost::system::error_code& ec) { return boost::asio::ip::address::from_string(str, ec); } + inline boost::asio::ip::address_v4 make_address_v4(char const* str) { return boost::asio::ip::address_v4::from_string(str); } + inline boost::asio::ip::address_v4 make_address_v4(char const* str, boost::system::error_code& ec) { return boost::asio::ip::address_v4::from_string(str, ec); } + inline boost::asio::ip::address_v4 make_address_v4(std::string const& str) { return boost::asio::ip::address_v4::from_string(str); } + inline boost::asio::ip::address_v4 make_address_v4(std::string const& str, boost::system::error_code& ec) { return boost::asio::ip::address_v4::from_string(str, ec); } + inline uint32 address_to_uint(boost::asio::ip::address_v4 const& address) { return address.to_ulong(); } +#endif + } +} + +#endif // IpAddress_h__ diff --git a/src/common/Asio/IpNetwork.h b/src/common/Asio/IpNetwork.h new file mode 100644 index 00000000000..bdd3c1dc683 --- /dev/null +++ b/src/common/Asio/IpNetwork.h @@ -0,0 +1,71 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef IpNetwork_h__ +#define IpNetwork_h__ + +#include "Define.h" +#include "IpAddress.h" +#include +#if BOOST_VERSION >= 106600 +#include +#include +#endif + +namespace Trinity +{ + namespace Net + { + inline bool IsInNetwork(boost::asio::ip::address_v4 const& networkAddress, boost::asio::ip::address_v4 const& mask, boost::asio::ip::address_v4 const& clientAddress) + { +#if BOOST_VERSION >= 106600 + boost::asio::ip::network_v4 network = boost::asio::ip::make_network_v4(networkAddress, mask); + boost::asio::ip::address_v4_range hosts = network.hosts(); + return hosts.find(clientAddress) != hosts.end(); +#else + return (clientAddress.to_ulong() & mask.to_ulong()) == (networkAddress.to_ulong() & mask.to_ulong()); +#endif + } + + inline boost::asio::ip::address_v4 GetDefaultNetmaskV4(boost::asio::ip::address_v4 const& networkAddress) + { + if ((address_to_uint(networkAddress) & 0x80000000) == 0) + return boost::asio::ip::address_v4(0xFF000000); + if ((address_to_uint(networkAddress) & 0xC0000000) == 0x80000000) + return boost::asio::ip::address_v4(0xFFFF0000); + if ((address_to_uint(networkAddress) & 0xE0000000) == 0xC0000000) + return boost::asio::ip::address_v4(0xFFFFFF00); + return boost::asio::ip::address_v4(0xFFFFFFFF); + } + + inline bool IsInNetwork(boost::asio::ip::address_v6 const& networkAddress, uint16 prefixLength, boost::asio::ip::address_v6 const& clientAddress) + { +#if BOOST_VERSION >= 106600 + boost::asio::ip::network_v6 network = boost::asio::ip::make_network_v6(networkAddress, prefixLength); + boost::asio::ip::address_v6_range hosts = network.hosts(); + return hosts.find(clientAddress) != hosts.end(); +#else + (void)networkAddress; + (void)prefixLength; + (void)clientAddress; + return false; +#endif + } + } +} + +#endif // IpNetwork_h__ diff --git a/src/common/Asio/Resolver.h b/src/common/Asio/Resolver.h new file mode 100644 index 00000000000..5106421ee5e --- /dev/null +++ b/src/common/Asio/Resolver.h @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef Resolver_h__ +#define Resolver_h__ + +#include "Optional.h" +#include +#include + +namespace Trinity +{ + namespace Net + { + inline Optional Resolve(boost::asio::ip::tcp::resolver& resolver, boost::asio::ip::tcp const& protocol, + std::string const& host, std::string const& service) + { + boost::system::error_code ec; +#if BOOST_VERSION >= 106600 + boost::asio::ip::tcp::resolver::results_type results = resolver.resolve(protocol, host, service, ec); + if (results.empty() || ec) + return {}; + + return results.begin()->endpoint(); +#else + boost::asio::ip::tcp::resolver::query query(std::move(protocol), std::move(host), std::move(service)); + boost::asio::ip::tcp::resolver::iterator itr = resolver.resolve(query, ec); + boost::asio::ip::tcp::resolver::iterator end; + if (itr == end || ec) + return {}; + + return itr->endpoint(); +#endif + } + } +} + +#endif // Resolver_h__ diff --git a/src/common/Asio/Strand.h b/src/common/Asio/Strand.h new file mode 100644 index 00000000000..2b69c02f7bd --- /dev/null +++ b/src/common/Asio/Strand.h @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef Strand_h__ +#define Strand_h__ + +#include "IoContext.h" +#include + +#if BOOST_VERSION >= 106600 +#include +#endif + +namespace Trinity +{ + namespace Asio + { + /** + Hack to make it possible to forward declare strand (which is a inner class) + */ + class Strand : public IoContextBaseNamespace::IoContextBase::strand + { + public: + Strand(IoContext& ioContext) : IoContextBaseNamespace::IoContextBase::strand(ioContext) { } + }; + +#if BOOST_VERSION >= 106600 + using boost::asio::bind_executor; +#else + template + inline decltype(auto) bind_executor(Strand& strand, T&& t) + { + return strand.wrap(std::forward(t)); + } +#endif + } +} + +#endif // Strand_h__ diff --git a/src/common/Banner.cpp b/src/common/Banner.cpp new file mode 100644 index 00000000000..a18e58e67a4 --- /dev/null +++ b/src/common/Banner.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#include "Banner.h" +#include "GitRevision.h" +#include "StringFormat.h" + +void Trinity::Banner::Show(char const* applicationName, void(*log)(char const* text), void(*logExtraInfo)()) +{ + log(Trinity::StringFormat("%s (%s)", GitRevision::GetFullVersion(), applicationName).c_str()); + log(" to stop.\n"); + log(" ______ __"); + log("/\\__ _\\ __ __/\\ \\__"); + log("\\/_/\\ \\/ _ __ /\\_\\ ___ /\\_\\ \\, _\\ __ __"); + log(" \\ \\ \\/\\`'__\\/\\ \\ /' _ `\\/\\ \\ \\ \\/ /\\ \\/\\ \\"); + log(" \\ \\ \\ \\ \\/ \\ \\ \\/\\ \\/\\ \\ \\ \\ \\ \\_\\ \\ \\_\\ \\"); + log(" \\ \\_\\ \\_\\ \\ \\_\\ \\_\\ \\_\\ \\_\\ \\__\\\\/`____ \\"); + log(" \\/_/\\/_/ \\/_/\\/_/\\/_/\\/_/\\/__/ `/___/> \\"); + log(" C O R E /\\___/"); + log("http://TrinityCore.org \\/__/\n"); + + if (logExtraInfo) + logExtraInfo(); +} diff --git a/src/common/Banner.h b/src/common/Banner.h new file mode 100644 index 00000000000..23a3e2d5e22 --- /dev/null +++ b/src/common/Banner.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef TrinityCore_Banner_h__ +#define TrinityCore_Banner_h__ + +#include "Define.h" + +namespace Trinity +{ + namespace Banner + { + TC_COMMON_API void Show(char const* applicationName, void(*log)(char const* text), void(*logExtraInfo)()); + } +} + +#endif // TrinityCore_Banner_h__ diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt index 65cd3c5bdb8..ece3db728ee 100644 --- a/src/common/CMakeLists.txt +++ b/src/common/CMakeLists.txt @@ -25,10 +25,6 @@ list(APPEND PRIVATE_SOURCES if (USE_COREPCH) set(PRIVATE_PCH_HEADER PrecompiledHeaders/commonPCH.h) - set(PRIVATE_PCH_SOURCE PrecompiledHeaders/commonPCH.cpp) - if (MSVC) - list(INSERT PRIVATE_SOURCES 0 PrecompiledHeaders/commonPCH.cpp) - endif (MSVC) endif (USE_COREPCH) GroupSources(${CMAKE_CURRENT_SOURCE_DIR}) @@ -65,6 +61,7 @@ target_include_directories(common target_link_libraries(common PRIVATE process + trinity-core-interface PUBLIC boost fmt @@ -98,5 +95,5 @@ endif() # Generate precompiled header if (USE_COREPCH) - add_cxx_pch(common ${PRIVATE_PCH_HEADER} ${PRIVATE_PCH_SOURCE}) + add_cxx_pch(common ${PRIVATE_PCH_HEADER}) endif () diff --git a/src/common/Collision/BoundingIntervalHierarchyWrapper.h b/src/common/Collision/BoundingIntervalHierarchyWrapper.h index adbc6754fa4..616f82546af 100644 --- a/src/common/Collision/BoundingIntervalHierarchyWrapper.h +++ b/src/common/Collision/BoundingIntervalHierarchyWrapper.h @@ -80,7 +80,7 @@ public: uint32 Idx = 0; const T * temp; if (m_obj2Idx.getRemove(&obj, temp, Idx)) - m_objects[Idx] = NULL; + m_objects[Idx] = nullptr; else m_objects_to_push.remove(&obj); } diff --git a/src/common/Collision/Management/IVMapManager.h b/src/common/Collision/Management/IVMapManager.h index 31ea635a091..e9aae51a025 100644 --- a/src/common/Collision/Management/IVMapManager.h +++ b/src/common/Collision/Management/IVMapManager.h @@ -19,10 +19,10 @@ #ifndef _IVMAPMANAGER_H #define _IVMAPMANAGER_H -#include #include "Define.h" #include "ModelIgnoreFlags.h" -#include "Common.h" +#include "Optional.h" +#include //=========================================================== @@ -83,9 +83,9 @@ namespace VMAP virtual ~IVMapManager(void) { } - virtual int loadMap(const char* pBasePath, unsigned int pMapId, int x, int y) = 0; + virtual int loadMap(char const* pBasePath, unsigned int pMapId, int x, int y) = 0; - virtual LoadResult existsMap(const char* pBasePath, unsigned int pMapId, int x, int y) = 0; + virtual LoadResult existsMap(char const* pBasePath, unsigned int pMapId, int x, int y) = 0; virtual void unloadMap(unsigned int pMapId, int x, int y) = 0; virtual void unloadMap(unsigned int pMapId) = 0; diff --git a/src/common/Collision/Management/MMapManager.cpp b/src/common/Collision/Management/MMapManager.cpp index c1f05becdd5..c36d2e06e6d 100644 --- a/src/common/Collision/Management/MMapManager.cpp +++ b/src/common/Collision/Management/MMapManager.cpp @@ -17,6 +17,7 @@ */ #include "MMapManager.h" +#include "Errors.h" #include "Log.h" #include "MMapFactory.h" #include "MapDefines.h" diff --git a/src/common/Collision/Management/VMapFactory.cpp b/src/common/Collision/Management/VMapFactory.cpp index b195955c4a9..c1a895e9c4d 100644 --- a/src/common/Collision/Management/VMapFactory.cpp +++ b/src/common/Collision/Management/VMapFactory.cpp @@ -21,7 +21,7 @@ namespace VMAP { - IVMapManager* gVMapManager = NULL; + IVMapManager* gVMapManager = nullptr; //=============================================== // just return the instance @@ -37,6 +37,6 @@ namespace VMAP void VMapFactory::clear() { delete gVMapManager; - gVMapManager = NULL; + gVMapManager = nullptr; } } diff --git a/src/common/Collision/Management/VMapManager2.cpp b/src/common/Collision/Management/VMapManager2.cpp index 1239a27d66c..f302d6e0f45 100644 --- a/src/common/Collision/Management/VMapManager2.cpp +++ b/src/common/Collision/Management/VMapManager2.cpp @@ -94,7 +94,7 @@ namespace VMAP return fname.str(); } - int VMapManager2::loadMap(const char* basePath, unsigned int mapId, int x, int y) + int VMapManager2::loadMap(char const* basePath, unsigned int mapId, int x, int y) { int result = VMAP_LOAD_RESULT_IGNORED; if (isMapLoadingEnabled()) @@ -352,7 +352,7 @@ namespace VMAP { VMAP_ERROR_LOG("misc", "VMapManager2: could not load '%s%s.vmo'", basepath.c_str(), filename.c_str()); delete worldmodel; - return NULL; + return nullptr; } VMAP_DEBUG_LOG("maps", "VMapManager2: loading file '%s%s'", basepath.c_str(), filename.c_str()); @@ -384,7 +384,7 @@ namespace VMAP } } - LoadResult VMapManager2::existsMap(const char* basePath, unsigned int mapId, int x, int y) + LoadResult VMapManager2::existsMap(char const* basePath, unsigned int mapId, int x, int y) { return StaticMapTree::CanLoadMap(std::string(basePath), mapId, x, y, this); } diff --git a/src/common/Collision/Management/VMapManager2.h b/src/common/Collision/Management/VMapManager2.h index 3782e76001e..f07a8f73b28 100644 --- a/src/common/Collision/Management/VMapManager2.h +++ b/src/common/Collision/Management/VMapManager2.h @@ -102,7 +102,7 @@ namespace VMAP void InitializeThreadUnsafe(std::unordered_map> const& mapData); - int loadMap(const char* pBasePath, unsigned int mapId, int x, int y) override; + int loadMap(char const* pBasePath, unsigned int mapId, int x, int y) override; bool loadSingleMap(uint32 mapId, const std::string& basePath, uint32 tileX, uint32 tileY); void unloadMap(unsigned int mapId, int x, int y) override; @@ -132,7 +132,7 @@ namespace VMAP { return getMapFileName(mapId); } - virtual LoadResult existsMap(const char* basePath, unsigned int mapId, int x, int y) override; + virtual LoadResult existsMap(char const* basePath, unsigned int mapId, int x, int y) override; void getInstanceMapTree(InstanceTreeMap &instanceMapTree); diff --git a/src/common/Collision/Maps/MapTree.cpp b/src/common/Collision/Maps/MapTree.cpp index 42489dda581..3c1c82282de 100644 --- a/src/common/Collision/Maps/MapTree.cpp +++ b/src/common/Collision/Maps/MapTree.cpp @@ -121,7 +121,7 @@ namespace VMAP } StaticMapTree::StaticMapTree(uint32 mapID, const std::string &basePath) : - iMapID(mapID), iIsTiled(false), iTreeValues(NULL), + iMapID(mapID), iIsTiled(false), iTreeValues(nullptr), iNTreeValues(0), iBasePath(basePath) { if (iBasePath.length() > 0 && iBasePath[iBasePath.length()-1] != '/' && iBasePath[iBasePath.length()-1] != '\\') diff --git a/src/common/Collision/Maps/TileAssembler.cpp b/src/common/Collision/Maps/TileAssembler.cpp index 00ac2b263f1..2714c8907aa 100644 --- a/src/common/Collision/Maps/TileAssembler.cpp +++ b/src/common/Collision/Maps/TileAssembler.cpp @@ -54,7 +54,7 @@ namespace VMAP //================================================================= TileAssembler::TileAssembler(const std::string& pSrcDirName, const std::string& pDestDirName) - : iDestDir(pDestDirName), iSrcDir(pSrcDirName), iFilterMethod(NULL), iCurrentUniqueNameId(0) + : iDestDir(pDestDirName), iSrcDir(pSrcDirName), iFilterMethod(nullptr), iCurrentUniqueNameId(0) { boost::filesystem::create_directory(iDestDir); //init(); diff --git a/src/common/Collision/Maps/TileAssembler.h b/src/common/Collision/Maps/TileAssembler.h index 8c3b3f5b88d..a79784c9451 100644 --- a/src/common/Collision/Maps/TileAssembler.h +++ b/src/common/Collision/Maps/TileAssembler.h @@ -82,7 +82,7 @@ namespace VMAP class WmoLiquid* liquid; GroupModel_Raw() : mogpflags(0), GroupWMOID(0), liquidflags(0), - liquid(NULL) { } + liquid(nullptr) { } ~GroupModel_Raw(); bool Read(FILE* f); diff --git a/src/common/Collision/Models/GameObjectModel.cpp b/src/common/Collision/Models/GameObjectModel.cpp index 219026c12e5..1c5f7ada0b6 100644 --- a/src/common/Collision/Models/GameObjectModel.cpp +++ b/src/common/Collision/Models/GameObjectModel.cpp @@ -146,7 +146,7 @@ GameObjectModel* GameObjectModel::Create(std::unique_ptrinitialize(std::move(modelOwner), dataPath)) { delete mdl; - return NULL; + return nullptr; } return mdl; diff --git a/src/common/Collision/Models/WorldModel.cpp b/src/common/Collision/Models/WorldModel.cpp index 4bbf0d9a051..e111bd8948e 100644 --- a/src/common/Collision/Models/WorldModel.cpp +++ b/src/common/Collision/Models/WorldModel.cpp @@ -331,7 +331,7 @@ namespace VMAP triangles.clear(); vertices.clear(); delete iLiquid; - iLiquid = NULL; + iLiquid = nullptr; if (result && fread(&iBound, sizeof(G3D::AABox), 1, rf) != 1) result = false; if (result && fread(&iMogpFlags, sizeof(uint32), 1, rf) != 1) result = false; diff --git a/src/common/Collision/Models/WorldModel.h b/src/common/Collision/Models/WorldModel.h index 5ff3300b840..617514eee83 100644 --- a/src/common/Collision/Models/WorldModel.h +++ b/src/common/Collision/Models/WorldModel.h @@ -61,7 +61,7 @@ namespace VMAP static bool readFromFile(FILE* rf, WmoLiquid* &liquid); void getPosInfo(uint32 &tilesX, uint32 &tilesY, G3D::Vector3 &corner) const; private: - WmoLiquid() : iTilesX(0), iTilesY(0), iCorner(), iType(0), iHeight(NULL), iFlags(NULL) { } + WmoLiquid() : iTilesX(0), iTilesY(0), iCorner(), iType(0), iHeight(nullptr), iFlags(nullptr) { } uint32 iTilesX; //!< number of tiles in x direction, each uint32 iTilesY; G3D::Vector3 iCorner; //!< the lower corner @@ -74,15 +74,15 @@ namespace VMAP class TC_COMMON_API GroupModel { public: - GroupModel() : iBound(), iMogpFlags(0), iGroupWMOID(0), iLiquid(NULL) { } + GroupModel() : iBound(), iMogpFlags(0), iGroupWMOID(0), iLiquid(nullptr) { } GroupModel(const GroupModel &other); GroupModel(uint32 mogpFlags, uint32 groupWMOID, const G3D::AABox &bound): - iBound(bound), iMogpFlags(mogpFlags), iGroupWMOID(groupWMOID), iLiquid(NULL) { } + iBound(bound), iMogpFlags(mogpFlags), iGroupWMOID(groupWMOID), iLiquid(nullptr) { } ~GroupModel() { delete iLiquid; } //! pass mesh data to object and create BIH. Passed vectors get get swapped with old geometry! void setMeshData(std::vector &vert, std::vector &tri); - void setLiquidData(WmoLiquid*& liquid) { iLiquid = liquid; liquid = NULL; } + void setLiquidData(WmoLiquid*& liquid) { iLiquid = liquid; liquid = nullptr; } bool IntersectRay(const G3D::Ray &ray, float &distance, bool stopAtFirstHit) const; bool IsInsideObject(const G3D::Vector3 &pos, const G3D::Vector3 &down, float &z_dist) const; bool GetLiquidLevel(const G3D::Vector3 &pos, float &liqHeight) const; diff --git a/src/common/Collision/RegularGrid.h b/src/common/Collision/RegularGrid.h index 5de9d80c893..c5a9b8c4c54 100644 --- a/src/common/Collision/RegularGrid.h +++ b/src/common/Collision/RegularGrid.h @@ -1,3 +1,20 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + #ifndef _REGULAR_GRID_H #define _REGULAR_GRID_H diff --git a/src/common/Common.h b/src/common/Common.h index 3fdece63d18..aa5748fdae5 100644 --- a/src/common/Common.h +++ b/src/common/Common.h @@ -20,38 +20,9 @@ #define TRINITYCORE_COMMON_H #include "Define.h" - -#include -#include -#include -#include -#include #include -#include -#include -#include #include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "Debugging/Errors.h" - -#include "Threading/LockedQueue.h" +#include #if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS # include @@ -69,12 +40,11 @@ # include # include # include +# include #endif #if TRINITY_COMPILER == TRINITY_COMPILER_MICROSOFT -#include - #define snprintf _snprintf #define atoll _atoi64 #define vsnprintf _vsnprintf @@ -87,8 +57,6 @@ #endif -inline float finiteAlways(float f) { return std::isfinite(f) ? f : 0.0f; } - inline unsigned long atoul(char const* str) { return strtoul(str, nullptr, 10); } inline unsigned long long atoull(char const* str) { return strtoull(str, nullptr, 10); } @@ -114,7 +82,7 @@ enum AccountTypes SEC_CONSOLE = 4 // must be always last in list, accounts must have less security level always also }; -enum LocaleConstant +enum LocaleConstant : uint8 { LOCALE_enUS = 0, LOCALE_koKR = 1, @@ -131,7 +99,7 @@ enum LocaleConstant TOTAL_LOCALES }; -const uint8 OLD_TOTAL_LOCALES = 9; /// @todo convert in simple system +uint8 const OLD_TOTAL_LOCALES = 9; /// @todo convert in simple system #define DEFAULT_LOCALE LOCALE_enUS #define MAX_LOCALES 10 @@ -139,28 +107,14 @@ const uint8 OLD_TOTAL_LOCALES = 9; /// @todo convert in simple system TC_COMMON_API extern char const* localeNames[TOTAL_LOCALES]; -TC_COMMON_API LocaleConstant GetLocaleByName(const std::string& name); - -typedef std::vector StringVector; - -#if defined(__GNUC__) -#pragma pack(1) -#else -#pragma pack(push, 1) -#endif +TC_COMMON_API LocaleConstant GetLocaleByName(std::string const& name); struct LocalizedString { char const* Str[TOTAL_LOCALES]; }; -#if defined(__GNUC__) -#pragma pack() -#else -#pragma pack(pop) -#endif - -// we always use stdlibc++ std::max/std::min, undefine some not C++ standard defines (Win API and some other platforms) +// we always use stdlib std::max/std::min, undefine some not C++ standard defines (Win API and some other platforms) #ifdef max #undef max #endif @@ -175,33 +129,9 @@ struct LocalizedString #define MAX_QUERY_LEN 32*1024 -//! Optional helper class to wrap optional values within. -template -using Optional = boost::optional; - namespace Trinity { - //! std::make_unique implementation (TODO: remove this once C++14 is supported) - template - std::unique_ptr make_unique(Args&& ...args) - { - return std::unique_ptr(new T(std::forward(args)...)); - } -} - -//! Hash implementation for std::pair to allow using pairs in unordered_set or as key for unordered_map -//! Individual types used in pair must be hashable by boost::hash -namespace std -{ - template - struct hash> - { - public: - size_t operator()(std::pair const& key) const - { - return boost::hash_value(key); - } - }; + using std::make_unique; } #endif diff --git a/src/common/Configuration/Config.cpp b/src/common/Configuration/Config.cpp index 4eb663ae3c6..df4e5fd151d 100644 --- a/src/common/Configuration/Config.cpp +++ b/src/common/Configuration/Config.cpp @@ -16,14 +16,23 @@ * with this program. If not, see . */ -#include -#include -#include -#include #include "Config.h" #include "Log.h" +#include "Util.h" +#include +#include +#include +#include -using namespace boost::property_tree; +namespace bpt = boost::property_tree; + +namespace +{ + std::string _filename; + std::vector _args; + bpt::ptree _config; + std::mutex _configLock; +} bool ConfigMgr::LoadInitial(std::string const& file, std::vector args, std::string& error) @@ -35,8 +44,8 @@ bool ConfigMgr::LoadInitial(std::string const& file, std::vector ar try { - ptree fullTree; - ini_parser::read_ini(file, fullTree); + bpt::ptree fullTree; + bpt::ini_parser::read_ini(file, fullTree); if (fullTree.empty()) { @@ -47,7 +56,7 @@ bool ConfigMgr::LoadInitial(std::string const& file, std::vector ar // Since we're using only one section per config file, we skip the section and have direct property access _config = fullTree.begin()->second; } - catch (ini_parser::ini_parser_error const& e) + catch (bpt::ini_parser::ini_parser_error const& e) { if (e.line() == 0) error = e.message() + " (" + e.filename() + ")"; @@ -75,14 +84,14 @@ T ConfigMgr::GetValueDefault(std::string const& name, T def) const { try { - return _config.get(ptree::path_type(name, '/')); + return _config.get(bpt::ptree::path_type(name, '/')); } - catch (boost::property_tree::ptree_bad_path) + catch (bpt::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) + catch (bpt::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()); @@ -96,14 +105,14 @@ std::string ConfigMgr::GetValueDefault(std::string const& name, std { try { - return _config.get(ptree::path_type(name, '/')); + return _config.get(bpt::ptree::path_type(name, '/')); } - catch (boost::property_tree::ptree_bad_path) + catch (bpt::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 (boost::property_tree::ptree_bad_data) + catch (bpt::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(), def.c_str()); @@ -123,7 +132,7 @@ 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"); + return StringToBool(val); } int ConfigMgr::GetIntDefault(std::string const& name, int def) const @@ -142,13 +151,18 @@ std::string const& ConfigMgr::GetFilename() return _filename; } -std::list ConfigMgr::GetKeysByString(std::string const& name) +std::vector const& ConfigMgr::GetArguments() const +{ + return _args; +} + +std::vector ConfigMgr::GetKeysByString(std::string const& name) { std::lock_guard lock(_configLock); - std::list keys; + std::vector keys; - for (const ptree::value_type& child : _config) + for (bpt::ptree::value_type const& child : _config) if (child.first.compare(0, name.length(), name) == 0) keys.push_back(child.first); diff --git a/src/common/Configuration/Config.h b/src/common/Configuration/Config.h index c2600b40587..8f5422e3d92 100644 --- a/src/common/Configuration/Config.h +++ b/src/common/Configuration/Config.h @@ -20,12 +20,8 @@ #define CONFIG_H #include "Define.h" - #include -#include #include -#include -#include class TC_COMMON_API ConfigMgr { @@ -36,8 +32,7 @@ class TC_COMMON_API ConfigMgr public: /// Method used only for loading main configuration files (authserver.conf and worldserver.conf) - bool LoadInitial(std::string const& file, std::vector args, - std::string& error); + bool LoadInitial(std::string const& file, std::vector args, std::string& error); static ConfigMgr* instance(); @@ -49,15 +44,10 @@ public: float GetFloatDefault(std::string const& name, float def) const; std::string const& GetFilename(); - std::vector const& GetArguments() const { return _args; } - std::list GetKeysByString(std::string const& name); + std::vector const& GetArguments() const; + std::vector GetKeysByString(std::string const& name); private: - std::string _filename; - std::vector _args; - boost::property_tree::ptree _config; - std::mutex _configLock; - template T GetValueDefault(std::string const& name, T def) const; }; diff --git a/src/common/Cryptography/BigNumber.cpp b/src/common/Cryptography/BigNumber.cpp index 69588709852..6062289a44a 100644 --- a/src/common/Cryptography/BigNumber.cpp +++ b/src/common/Cryptography/BigNumber.cpp @@ -112,7 +112,7 @@ BigNumber BigNumber::operator/=(BigNumber const& bn) BN_CTX *bnctx; bnctx = BN_CTX_new(); - BN_div(_bn, NULL, _bn, bn._bn, bnctx); + BN_div(_bn, nullptr, _bn, bn._bn, bnctx); BN_CTX_free(bnctx); return *this; diff --git a/src/common/Cryptography/HmacHash.cpp b/src/common/Cryptography/HmacHash.cpp index a0ad8356ef9..d5945517da0 100644 --- a/src/common/Cryptography/HmacHash.cpp +++ b/src/common/Cryptography/HmacHash.cpp @@ -18,7 +18,8 @@ #include "HmacHash.h" #include "BigNumber.h" -#include "Common.h" +#include "Errors.h" +#include #if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER < 0x10100000L HMAC_CTX* HMAC_CTX_new() diff --git a/src/common/Cryptography/OpenSSLCrypto.cpp b/src/common/Cryptography/OpenSSLCrypto.cpp index cb1cf17c1c6..75b22a71ce7 100644 --- a/src/common/Cryptography/OpenSSLCrypto.cpp +++ b/src/common/Cryptography/OpenSSLCrypto.cpp @@ -23,7 +23,7 @@ std::vector cryptoLocks; -static void lockingCallback(int mode, int type, const char* /*file*/, int /*line*/) +static void lockingCallback(int mode, int type, char const* /*file*/, int /*line*/) { if (mode & CRYPTO_LOCK) cryptoLocks[type]->lock(); @@ -49,8 +49,8 @@ void OpenSSLCrypto::threadsSetup() void OpenSSLCrypto::threadsCleanup() { - CRYPTO_set_locking_callback(NULL); - CRYPTO_THREADID_set_callback(NULL); + CRYPTO_set_locking_callback(nullptr); + CRYPTO_THREADID_set_callback(nullptr); for(int i = 0 ; i < CRYPTO_num_locks(); ++i) { delete cryptoLocks[i]; diff --git a/src/common/DataStores/DBCFileLoader.cpp b/src/common/DataStores/DBCFileLoader.cpp index 1a3d33677a1..91bfc366f85 100644 --- a/src/common/DataStores/DBCFileLoader.cpp +++ b/src/common/DataStores/DBCFileLoader.cpp @@ -23,15 +23,15 @@ #include "DBCFileLoader.h" #include "Errors.h" -DBCFileLoader::DBCFileLoader() : recordSize(0), recordCount(0), fieldCount(0), stringSize(0), fieldsOffset(NULL), data(NULL), stringTable(NULL) { } +DBCFileLoader::DBCFileLoader() : recordSize(0), recordCount(0), fieldCount(0), stringSize(0), fieldsOffset(nullptr), data(nullptr), stringTable(nullptr) { } -bool DBCFileLoader::Load(const char* filename, const char* fmt) +bool DBCFileLoader::Load(char const* filename, char const* fmt) { uint32 header; if (data) { delete [] data; - data = NULL; + data = nullptr; } FILE* f = fopen(filename, "rb"); @@ -125,7 +125,7 @@ DBCFileLoader::Record DBCFileLoader::getRecord(size_t id) return Record(*this, data + id * recordSize); } -uint32 DBCFileLoader::GetFormatRecordSize(const char* format, int32* index_pos) +uint32 DBCFileLoader::GetFormatRecordSize(char const* format, int32* index_pos) { uint32 recordsize = 0; int32 i = -1; @@ -170,7 +170,7 @@ uint32 DBCFileLoader::GetFormatRecordSize(const char* format, int32* index_pos) return recordsize; } -char* DBCFileLoader::AutoProduceData(const char* format, uint32& records, char**& indexTable, uint32 sqlRecordCount, uint32 sqlHighestIndex, char*& sqlDataTable) +char* DBCFileLoader::AutoProduceData(char const* format, uint32& records, char**& indexTable) { /* format STRING, NA, FLOAT, NA, INT <=> @@ -185,7 +185,7 @@ char* DBCFileLoader::AutoProduceData(const char* format, uint32& records, char** typedef char* ptr; if (strlen(format) != fieldCount) - return NULL; + return nullptr; //get struct size and index pos int32 i; @@ -202,10 +202,6 @@ char* DBCFileLoader::AutoProduceData(const char* format, uint32& records, char** maxi = ind; } - // If higher index avalible from sql - use it instead of dbcs - if (sqlHighestIndex > maxi) - maxi = sqlHighestIndex; - ++maxi; records = maxi; indexTable = new ptr[maxi]; @@ -213,11 +209,11 @@ char* DBCFileLoader::AutoProduceData(const char* format, uint32& records, char** } else { - records = recordCount + sqlRecordCount; - indexTable = new ptr[recordCount + sqlRecordCount]; + records = recordCount; + indexTable = new ptr[recordCount]; } - char* dataTable = new char[(recordCount + sqlRecordCount) * recordsize]; + char* dataTable = new char[recordCount * recordsize]; uint32 offset = 0; @@ -250,7 +246,7 @@ char* DBCFileLoader::AutoProduceData(const char* format, uint32& records, char** offset += sizeof(uint64); break; case FT_STRING: - *((char**)(&dataTable[offset])) = NULL; // will replace non-empty or "" strings in AutoProduceStrings + *((char**)(&dataTable[offset])) = nullptr; // will replace non-empty or "" strings in AutoProduceStrings offset += sizeof(char*); break; case FT_NA: @@ -264,15 +260,13 @@ char* DBCFileLoader::AutoProduceData(const char* format, uint32& records, char** } } - sqlDataTable = dataTable + offset; - return dataTable; } -char* DBCFileLoader::AutoProduceStrings(const char* format, char* dataTable) +char* DBCFileLoader::AutoProduceStrings(char const* format, char* dataTable) { if (strlen(format) != fieldCount) - return NULL; + return nullptr; char* stringPool = new char[stringSize]; memcpy(stringPool, stringTable, stringSize); @@ -305,7 +299,7 @@ char* DBCFileLoader::AutoProduceStrings(const char* format, char* dataTable) if (!*slot || !**slot) { const char * st = getRecord(y).getString(x); - *slot=stringPool+(st-(const char*)stringTable); + *slot = stringPool + (st - (char const*)stringTable); } offset += sizeof(char*); break; diff --git a/src/common/DataStores/DBCFileLoader.h b/src/common/DataStores/DBCFileLoader.h index 1b675452aae..57f4487340c 100644 --- a/src/common/DataStores/DBCFileLoader.h +++ b/src/common/DataStores/DBCFileLoader.h @@ -18,6 +18,7 @@ #ifndef DBC_FILE_LOADER_H #define DBC_FILE_LOADER_H + #include "Define.h" #include "Utilities/ByteConverter.h" #include @@ -89,13 +90,13 @@ class TC_COMMON_API DBCFileLoader uint32 GetNumRows() const { return recordCount; } uint32 GetRowSize() const { return recordSize; } uint32 GetCols() const { return fieldCount; } - uint32 GetOffset(size_t id) const { return (fieldsOffset != NULL && id < fieldCount) ? fieldsOffset[id] : 0; } - bool IsLoaded() const { return data != NULL; } - char* AutoProduceData(const char* fmt, uint32& count, char**& indexTable, uint32 sqlRecordCount, uint32 sqlHighestIndex, char *& sqlDataTable); - char* AutoProduceStrings(const char* fmt, char* dataTable); - static uint32 GetFormatRecordSize(const char * format, int32 * index_pos = NULL); - private: + uint32 GetOffset(size_t id) const { return (fieldsOffset != nullptr && id < fieldCount) ? fieldsOffset[id] : 0; } + bool IsLoaded() const { return data != nullptr; } + char* AutoProduceData(char const* fmt, uint32& count, char**& indexTable); + char* AutoProduceStrings(char const* fmt, char* dataTable); + static uint32 GetFormatRecordSize(char const* format, int32* index_pos = nullptr); + private: uint32 recordSize; uint32 recordCount; uint32 fieldCount; diff --git a/src/common/Debugging/Errors.cpp b/src/common/Debugging/Errors.cpp index 731a779344e..fa4e67237a6 100644 --- a/src/common/Debugging/Errors.cpp +++ b/src/common/Debugging/Errors.cpp @@ -28,7 +28,7 @@ @brief This file contains definitions of functions used for reporting critical application errors - It is very important that (std::)abort is NEVER called in place of *((volatile int*)NULL) = 0; + It is very important that (std::)abort is NEVER called in place of *((volatile int*)nullptr) = 0; Calling abort() on Windows does not invoke unhandled exception filters - a mechanism used by WheatyExceptionReport to log crashes. exit(1) calls here are for static analysis tools to indicate that calling functions defined in this file terminates the application. @@ -40,7 +40,7 @@ void Assert(char const* file, int line, char const* function, char const* messag { fprintf(stderr, "\n%s:%i in %s ASSERTION FAILED:\n %s\n", file, line, function, message); - *((volatile int*)NULL) = 0; + *((volatile int*)nullptr) = 0; exit(1); } @@ -55,7 +55,7 @@ void Assert(char const* file, int line, char const* function, char const* messag fflush(stderr); va_end(args); - *((volatile int*)NULL) = 0; + *((volatile int*)nullptr) = 0; exit(1); } @@ -70,7 +70,7 @@ void Fatal(char const* file, int line, char const* function, char const* message fflush(stderr); std::this_thread::sleep_for(std::chrono::seconds(10)); - *((volatile int*)NULL) = 0; + *((volatile int*)nullptr) = 0; exit(1); } @@ -78,7 +78,7 @@ void Error(char const* file, int line, char const* function, char const* message { fprintf(stderr, "\n%s:%i in %s ERROR:\n %s\n", file, line, function, message); - *((volatile int*)NULL) = 0; + *((volatile int*)nullptr) = 0; exit(1); } @@ -92,14 +92,14 @@ void Abort(char const* file, int line, char const* function) { fprintf(stderr, "\n%s:%i in %s ABORTED.\n", file, line, function); - *((volatile int*)NULL) = 0; + *((volatile int*)nullptr) = 0; exit(1); } void AbortHandler(int /*sigval*/) { // nothing useful to log here, no way to pass args - *((volatile int*)NULL) = 0; + *((volatile int*)nullptr) = 0; exit(1); } diff --git a/src/common/Debugging/WheatyExceptionReport.cpp b/src/common/Debugging/WheatyExceptionReport.cpp index b2f3c692dcd..f1adbb8505c 100644 --- a/src/common/Debugging/WheatyExceptionReport.cpp +++ b/src/common/Debugging/WheatyExceptionReport.cpp @@ -6,7 +6,9 @@ #include "CompilerDefs.h" #if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS && !defined(__MINGW32__) +#ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN +#endif #pragma warning(disable:4996) #pragma warning(disable:4312) #pragma warning(disable:4311) @@ -21,6 +23,7 @@ #include "Common.h" #include "GitRevision.h" +#include #define CrashFolder _T("Crashes") #pragma comment(linker, "/DEFAULTLIB:dbghelp.lib") @@ -924,7 +927,7 @@ DWORD64 modBase, DWORD dwTypeIndex, DWORD_PTR offset, bool & bHandled, -const char* Name, +char const* Name, char* /*suffix*/, bool newSymbol, bool logChildren) diff --git a/src/common/Debugging/WheatyExceptionReport.h b/src/common/Debugging/WheatyExceptionReport.h index 42d4d3e0a2a..a6f871bfb13 100644 --- a/src/common/Debugging/WheatyExceptionReport.h +++ b/src/common/Debugging/WheatyExceptionReport.h @@ -56,7 +56,7 @@ enum DataKind // Stolen from CVCONS DataIsConstant }; -const char* const rgBaseType[] = +char const* const rgBaseType[] = { "", // btNoType = 0, "void", // btVoid = 1, @@ -100,7 +100,7 @@ struct SymbolPair _offset = offset; } - bool operator<(const SymbolPair& other) const + bool operator<(SymbolPair const& other) const { return _offset < other._offset || (_offset == other._offset && _type < other._type); @@ -176,7 +176,7 @@ class WheatyExceptionReport static bool FormatSymbolValue(PSYMBOL_INFO, STACKFRAME64 *); - static void DumpTypeIndex(DWORD64, DWORD, DWORD_PTR, bool &, const char*, char*, bool, bool); + static void DumpTypeIndex(DWORD64, DWORD, DWORD_PTR, bool &, char const*, 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 eac3d9d186d..8b179983745 100644 --- a/src/common/Define.h +++ b/src/common/Define.h @@ -56,7 +56,7 @@ #endif #if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS -# define TRINITY_PATH_MAX MAX_PATH +# define TRINITY_PATH_MAX 260 # define _USE_MATH_DEFINES # ifndef DECLSPEC_NORETURN # define DECLSPEC_NORETURN __declspec(noreturn) diff --git a/src/common/GitRevision.cpp b/src/common/GitRevision.cpp index 4ed5b69997d..519e6f4b17f 100644 --- a/src/common/GitRevision.cpp +++ b/src/common/GitRevision.cpp @@ -1,3 +1,20 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + #include "GitRevision.h" #include "revision_data.h" diff --git a/src/common/GitRevision.h b/src/common/GitRevision.h index 131078ce860..c6d3fc52896 100644 --- a/src/common/GitRevision.h +++ b/src/common/GitRevision.h @@ -18,7 +18,6 @@ #ifndef __GITREVISION_H__ #define __GITREVISION_H__ -#include #include "Define.h" namespace GitRevision diff --git a/src/common/Logging/Appender.cpp b/src/common/Logging/Appender.cpp index 311308bf7d8..43da1d8a019 100644 --- a/src/common/Logging/Appender.cpp +++ b/src/common/Logging/Appender.cpp @@ -16,27 +16,10 @@ */ #include "Appender.h" -#include "Common.h" -#include "Util.h" +#include "LogMessage.h" #include "StringFormat.h" - -#include #include -std::string LogMessage::getTimeStr(time_t time) -{ - tm aTm; - localtime_r(&time, &aTm); - char buf[20]; - snprintf(buf, 20, "%04d-%02d-%02d_%02d:%02d:%02d", aTm.tm_year+1900, aTm.tm_mon+1, aTm.tm_mday, aTm.tm_hour, aTm.tm_min, aTm.tm_sec); - return std::string(buf); -} - -std::string LogMessage::getTimeStr() -{ - return getTimeStr(mtime); -} - Appender::Appender(uint8 _id, std::string const& _name, LogLevel _level /* = LOG_LEVEL_DISABLED */, AppenderFlags _flags /* = APPENDER_FLAGS_NONE */): id(_id), name(_name), level(_level), flags(_flags) { } @@ -87,7 +70,7 @@ void Appender::write(LogMessage* message) _write(message); } -const char* Appender::getLogLevelString(LogLevel level) +char const* Appender::getLogLevelString(LogLevel level) { switch (level) { diff --git a/src/common/Logging/Appender.h b/src/common/Logging/Appender.h index b8c3c119ec3..44ffeb8f0df 100644 --- a/src/common/Logging/Appender.h +++ b/src/common/Logging/Appender.h @@ -18,72 +18,13 @@ #ifndef APPENDER_H #define APPENDER_H -#include +#include "Define.h" +#include "LogCommon.h" #include #include -#include -#include #include -#include -#include "Define.h" -// Values assigned have their equivalent in enum ACE_Log_Priority -enum LogLevel -{ - LOG_LEVEL_DISABLED = 0, - LOG_LEVEL_TRACE = 1, - LOG_LEVEL_DEBUG = 2, - LOG_LEVEL_INFO = 3, - LOG_LEVEL_WARN = 4, - LOG_LEVEL_ERROR = 5, - LOG_LEVEL_FATAL = 6 -}; - -const uint8 MaxLogLevels = 6; - -enum AppenderType : uint8 -{ - APPENDER_NONE, - APPENDER_CONSOLE, - APPENDER_FILE, - APPENDER_DB -}; - -enum AppenderFlags -{ - APPENDER_FLAGS_NONE = 0x00, - APPENDER_FLAGS_PREFIX_TIMESTAMP = 0x01, - APPENDER_FLAGS_PREFIX_LOGLEVEL = 0x02, - APPENDER_FLAGS_PREFIX_LOGFILTERTYPE = 0x04, - APPENDER_FLAGS_USE_TIMESTAMP = 0x08, // only used by FileAppender - APPENDER_FLAGS_MAKE_FILE_BACKUP = 0x10 // only used by FileAppender -}; - -struct TC_COMMON_API LogMessage -{ - LogMessage(LogLevel _level, std::string const& _type, std::string&& _text) - : level(_level), type(_type), text(std::forward(_text)), mtime(time(NULL)) - { } - - LogMessage(LogMessage const& /*other*/) = delete; - LogMessage& operator=(LogMessage const& /*other*/) = delete; - - static std::string getTimeStr(time_t time); - std::string getTimeStr(); - - LogLevel const level; - std::string const type; - std::string const text; - std::string prefix; - std::string param1; - time_t mtime; - - ///@ Returns size of the log message content in bytes - uint32 Size() const - { - return static_cast(prefix.size() + text.size()); - } -}; +struct LogMessage; class TC_COMMON_API Appender { @@ -99,7 +40,7 @@ class TC_COMMON_API Appender void setLogLevel(LogLevel); void write(LogMessage* message); - static const char* getLogLevelString(LogLevel level); + static char const* getLogLevelString(LogLevel level); virtual void setRealmId(uint32 /*realmId*/) { } private: @@ -111,18 +52,6 @@ class TC_COMMON_API Appender AppenderFlags flags; }; -typedef std::unordered_map AppenderMap; - -typedef std::vector ExtraAppenderArgs; -typedef Appender*(*AppenderCreatorFn)(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, ExtraAppenderArgs extraArgs); -typedef std::unordered_map AppenderCreatorMap; - -template -Appender* CreateAppender(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, ExtraAppenderArgs extraArgs) -{ - return new AppenderImpl(id, name, level, flags, std::forward(extraArgs)); -} - class TC_COMMON_API InvalidAppenderArgsException : public std::length_error { public: diff --git a/src/common/Logging/AppenderConsole.cpp b/src/common/Logging/AppenderConsole.cpp index 76658eea8f3..3d30343cfdd 100644 --- a/src/common/Logging/AppenderConsole.cpp +++ b/src/common/Logging/AppenderConsole.cpp @@ -15,20 +15,19 @@ * with this program. If not, see . */ -#include - #include "AppenderConsole.h" -#include "Config.h" +#include "LogMessage.h" #include "Util.h" +#include #if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS #include #endif -AppenderConsole::AppenderConsole(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, ExtraAppenderArgs extraArgs) +AppenderConsole::AppenderConsole(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, std::vector extraArgs) : Appender(id, name, level, flags), _colored(false) { - for (uint8 i = 0; i < MaxLogLevels; ++i) + for (uint8 i = 0; i < NUM_ENABLED_LOG_LEVELS; ++i) _colors[i] = ColorTypes(MaxColors); if (!extraArgs.empty()) @@ -43,11 +42,11 @@ void AppenderConsole::InitColors(std::string const& str) return; } - int color[MaxLogLevels]; + int color[NUM_ENABLED_LOG_LEVELS]; std::istringstream ss(str); - for (uint8 i = 0; i < MaxLogLevels; ++i) + for (uint8 i = 0; i < NUM_ENABLED_LOG_LEVELS; ++i) { ss >> color[i]; @@ -58,7 +57,7 @@ void AppenderConsole::InitColors(std::string const& str) return; } - for (uint8 i = 0; i < MaxLogLevels; ++i) + for (uint8 i = 0; i < NUM_ENABLED_LOG_LEVELS; ++i) _colors[i] = ColorTypes(color[i]); _colored = true; diff --git a/src/common/Logging/AppenderConsole.h b/src/common/Logging/AppenderConsole.h index c175aa3ebea..8928c9b26d9 100644 --- a/src/common/Logging/AppenderConsole.h +++ b/src/common/Logging/AppenderConsole.h @@ -18,7 +18,6 @@ #ifndef APPENDERCONSOLE_H #define APPENDERCONSOLE_H -#include #include "Appender.h" enum ColorTypes @@ -47,7 +46,7 @@ class TC_COMMON_API AppenderConsole : public Appender public: typedef std::integral_constant::type TypeIndex; - AppenderConsole(uint8 _id, std::string const& name, LogLevel level, AppenderFlags flags, ExtraAppenderArgs extraArgs); + AppenderConsole(uint8 _id, std::string const& name, LogLevel level, AppenderFlags flags, std::vector extraArgs); void InitColors(const std::string& init_str); AppenderType getType() const override { return TypeIndex::value; } @@ -56,7 +55,7 @@ class TC_COMMON_API AppenderConsole : public Appender void ResetColor(bool stdout_stream); void _write(LogMessage const* message) override; bool _colored; - ColorTypes _colors[MaxLogLevels]; + ColorTypes _colors[NUM_ENABLED_LOG_LEVELS]; }; #endif diff --git a/src/common/Logging/AppenderFile.cpp b/src/common/Logging/AppenderFile.cpp index df8b44b3c8f..7c06e6bc6f8 100644 --- a/src/common/Logging/AppenderFile.cpp +++ b/src/common/Logging/AppenderFile.cpp @@ -16,17 +16,13 @@ */ #include "AppenderFile.h" -#include "Common.h" -#include "StringFormat.h" #include "Log.h" +#include "LogMessage.h" +#include -#if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS -# include -#endif - -AppenderFile::AppenderFile(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, ExtraAppenderArgs extraArgs) : +AppenderFile::AppenderFile(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, std::vector extraArgs) : Appender(id, name, level, flags), - logfile(NULL), + logfile(nullptr), _logDir(sLog->GetLogsDir()), _maxFileSize(0), _fileSize(0) @@ -101,7 +97,7 @@ FILE* AppenderFile::OpenFile(std::string const& filename, std::string const& mod CloseFile(); std::string newName(fullName); newName.push_back('.'); - newName.append(LogMessage::getTimeStr(time(NULL))); + newName.append(LogMessage::getTimeStr(time(nullptr))); std::replace(newName.begin(), newName.end(), ':', '-'); rename(fullName.c_str(), newName.c_str()); // no error handling... if we couldn't make a backup, just ignore } @@ -112,7 +108,7 @@ FILE* AppenderFile::OpenFile(std::string const& filename, std::string const& mod return ret; } - return NULL; + return nullptr; } void AppenderFile::CloseFile() @@ -120,6 +116,6 @@ void AppenderFile::CloseFile() if (logfile) { fclose(logfile); - logfile = NULL; + logfile = nullptr; } } diff --git a/src/common/Logging/AppenderFile.h b/src/common/Logging/AppenderFile.h index 295ff850f48..2710e03a09d 100644 --- a/src/common/Logging/AppenderFile.h +++ b/src/common/Logging/AppenderFile.h @@ -18,15 +18,15 @@ #ifndef APPENDERFILE_H #define APPENDERFILE_H -#include #include "Appender.h" +#include class TC_COMMON_API AppenderFile : public Appender { public: typedef std::integral_constant::type TypeIndex; - AppenderFile(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, ExtraAppenderArgs extraArgs); + AppenderFile(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, std::vector extraArgs); ~AppenderFile(); FILE* OpenFile(std::string const& name, std::string const& mode, bool backup); AppenderType getType() const override { return TypeIndex::value; } diff --git a/src/common/Logging/Log.cpp b/src/common/Logging/Log.cpp index 0750c5e9342..c506f0c3a46 100644 --- a/src/common/Logging/Log.cpp +++ b/src/common/Logging/Log.cpp @@ -17,17 +17,20 @@ */ #include "Log.h" -#include "Common.h" -#include "Config.h" -#include "Util.h" #include "AppenderConsole.h" #include "AppenderFile.h" +#include "Common.h" +#include "Config.h" +#include "Errors.h" +#include "Logger.h" +#include "LogMessage.h" #include "LogOperation.h" - -#include +#include "Strand.h" +#include "Util.h" +#include #include -Log::Log() : AppenderId(0), lowestLogLevel(LOG_LEVEL_FATAL), _ioService(nullptr), _strand(nullptr) +Log::Log() : AppenderId(0), lowestLogLevel(LOG_LEVEL_FATAL), _ioContext(nullptr), _strand(nullptr) { m_logsTimestamp = "_" + GetTimestampStr(); RegisterAppender(); @@ -45,25 +48,13 @@ uint8 Log::NextAppenderId() return AppenderId++; } -int32 GetConfigIntDefault(std::string base, const char* name, int32 value) -{ - base.append(name); - return sConfigMgr->GetIntDefault(base.c_str(), value); -} - -std::string GetConfigStringDefault(std::string base, const char* name, const char* value) -{ - base.append(name); - return sConfigMgr->GetStringDefault(base.c_str(), value); -} - Appender* Log::GetAppenderByName(std::string const& name) { - AppenderMap::iterator it = appenders.begin(); + auto it = appenders.begin(); while (it != appenders.end() && it->second && it->second->getName() != name) ++it; - return it == appenders.end() ? NULL : it->second; + return it == appenders.end() ? nullptr : it->second.get(); } void Log::CreateAppenderFromConfig(std::string const& appenderName) @@ -71,13 +62,13 @@ void Log::CreateAppenderFromConfig(std::string const& appenderName) if (appenderName.empty()) return; - // Format=type, level, flags, optional1, optional2 + // Format = type, level, flags, optional1, optional2 // if type = File. optional1 = file and option2 = mode // if type = Console. optional1 = Color std::string options = sConfigMgr->GetStringDefault(appenderName, ""); Tokenizer tokens(options, ','); - Tokenizer::const_iterator iter = tokens.begin(); + auto iter = tokens.begin(); size_t size = tokens.size(); std::string name = appenderName.substr(9); @@ -110,8 +101,8 @@ void Log::CreateAppenderFromConfig(std::string const& appenderName) try { - Appender* appender = factoryFunction->second(NextAppenderId(), name, level, flags, ExtraAppenderArgs(iter, tokens.end())); - appenders[appender->getId()] = appender; + Appender* appender = factoryFunction->second(NextAppenderId(), name, level, flags, std::vector(iter, tokens.end())); + appenders[appender->getId()].reset(appender); } catch (InvalidAppenderArgsException const& iaae) { @@ -145,8 +136,8 @@ void Log::CreateLoggerFromConfig(std::string const& appenderName) return; } - Logger& logger = loggers[name]; - if (!logger.getName().empty()) + std::unique_ptr& logger = loggers[name]; + if (logger) { fprintf(stderr, "Error while configuring Logger %s. Already defined\n", name.c_str()); return; @@ -162,7 +153,7 @@ void Log::CreateLoggerFromConfig(std::string const& appenderName) if (level < lowestLogLevel) lowestLogLevel = level; - logger.Create(name, level); + logger = Trinity::make_unique(name, level); //fprintf(stdout, "Log::CreateLoggerFromConfig: Created Logger %s, Level %u\n", name.c_str(), level); std::istringstream ss(*iter); @@ -173,7 +164,7 @@ void Log::CreateLoggerFromConfig(std::string const& appenderName) { if (Appender* appender = GetAppenderByName(str)) { - logger.addAppender(appender->getId(), appender); + logger->addAppender(appender->getId(), appender); //fprintf(stdout, "Log::CreateLoggerFromConfig: Added Appender %s to Logger %s\n", appender->getName().c_str(), name.c_str()); } else @@ -184,24 +175,16 @@ void Log::CreateLoggerFromConfig(std::string const& appenderName) void Log::ReadAppendersFromConfig() { - std::list keys = sConfigMgr->GetKeysByString("Appender."); - - while (!keys.empty()) - { - CreateAppenderFromConfig(keys.front()); - keys.pop_front(); - } + std::vector keys = sConfigMgr->GetKeysByString("Appender."); + for (std::string const& appenderName : keys) + CreateAppenderFromConfig(appenderName); } void Log::ReadLoggersFromConfig() { - std::list keys = sConfigMgr->GetKeysByString("Logger."); - - while (!keys.empty()) - { - CreateLoggerFromConfig(keys.front()); - keys.pop_front(); - } + std::vector keys = sConfigMgr->GetKeysByString("Logger."); + for (std::string const& loggerName : keys) + CreateLoggerFromConfig(loggerName); // Bad config configuration, creating default config if (loggers.find(LOGGER_ROOT) == loggers.end()) @@ -211,33 +194,66 @@ void Log::ReadLoggersFromConfig() Close(); // Clean any Logger or Appender created - AppenderConsole* appender = new AppenderConsole(NextAppenderId(), "Console", LOG_LEVEL_DEBUG, APPENDER_FLAGS_NONE, ExtraAppenderArgs()); - appenders[appender->getId()] = appender; + AppenderConsole* appender = new AppenderConsole(NextAppenderId(), "Console", LOG_LEVEL_DEBUG, APPENDER_FLAGS_NONE, std::vector()); + appenders[appender->getId()].reset(appender); - Logger& rootLogger = loggers[LOGGER_ROOT]; - rootLogger.Create(LOGGER_ROOT, LOG_LEVEL_ERROR); - rootLogger.addAppender(appender->getId(), appender); + Logger* rootLogger = new Logger(LOGGER_ROOT, LOG_LEVEL_ERROR); + rootLogger->addAppender(appender->getId(), appender); + loggers[LOGGER_ROOT].reset(rootLogger); - Logger& serverLogger = loggers["server"]; - serverLogger.Create("server", LOG_LEVEL_INFO); - serverLogger.addAppender(appender->getId(), appender); + Logger* serverLogger = new Logger("server", LOG_LEVEL_INFO); + serverLogger->addAppender(appender->getId(), appender); + loggers["server"].reset(serverLogger); } } +void Log::RegisterAppender(uint8 index, AppenderCreatorFn appenderCreateFn) +{ + auto itr = appenderFactory.find(index); + ASSERT(itr == appenderFactory.end()); + appenderFactory[index] = appenderCreateFn; +} + +void Log::outMessage(std::string const& filter, LogLevel level, std::string&& message) +{ + write(Trinity::make_unique(level, filter, std::move(message))); +} + +void Log::outCommand(std::string&& message, std::string&& param1) +{ + write(Trinity::make_unique(LOG_LEVEL_INFO, "commands.gm", std::move(message), std::move(param1))); +} + void Log::write(std::unique_ptr&& msg) const { Logger const* logger = GetLoggerByType(msg->type); - if (_ioService) + if (_ioContext) { - auto logOperation = std::shared_ptr(new LogOperation(logger, std::move(msg))); - - _ioService->post(_strand->wrap([logOperation](){ logOperation->call(); })); + std::shared_ptr logOperation = std::make_shared(logger, std::move(msg)); + Trinity::Asio::post(*_ioContext, Trinity::Asio::bind_executor(*_strand, [logOperation]() { logOperation->call(); })); } else logger->write(msg.get()); } +Logger const* Log::GetLoggerByType(std::string const& type) const +{ + auto it = loggers.find(type); + if (it != loggers.end()) + return it->second.get(); + + if (type == LOGGER_ROOT) + return nullptr; + + std::string parentLogger = LOGGER_ROOT; + size_t found = type.find_last_of('.'); + if (found != std::string::npos) + parentLogger = type.substr(0, found); + + return GetLoggerByType(parentLogger); +} + std::string Log::GetTimestampStr() { time_t tt = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); @@ -255,7 +271,7 @@ std::string Log::GetTimestampStr() aTm.tm_year + 1900, aTm.tm_mon + 1, aTm.tm_mday, aTm.tm_hour, aTm.tm_min, aTm.tm_sec); } -bool Log::SetLogLevel(std::string const& name, const char* newLevelc, bool isLogger /* = true */) +bool Log::SetLogLevel(std::string const& name, char const* newLevelc, bool isLogger /* = true */) { LogLevel newLevel = LogLevel(atoi(newLevelc)); if (static_cast(newLevel) < 0) @@ -263,14 +279,14 @@ bool Log::SetLogLevel(std::string const& name, const char* newLevelc, bool isLog if (isLogger) { - LoggerMap::iterator it = loggers.begin(); - while (it != loggers.end() && it->second.getName() != name) + auto it = loggers.begin(); + while (it != loggers.end() && it->second->getName() != name) ++it; if (it == loggers.end()) return false; - it->second.setLogLevel(newLevel); + it->second->setLogLevel(newLevel); if (newLevel != LOG_LEVEL_DISABLED && newLevel < lowestLogLevel) lowestLogLevel = newLevel; @@ -307,31 +323,46 @@ void Log::outCharDump(char const* str, uint32 accountId, uint64 guid, char const void Log::SetRealmId(uint32 id) { - for (AppenderMap::iterator it = appenders.begin(); it != appenders.end(); ++it) + for (auto it = appenders.begin(); it != appenders.end(); ++it) it->second->setRealmId(id); } void Log::Close() { loggers.clear(); - for (AppenderMap::iterator it = appenders.begin(); it != appenders.end(); ++it) - delete it->second; - appenders.clear(); } +bool Log::ShouldLog(std::string const& type, LogLevel level) const +{ + // TODO: Use cache to store "Type.sub1.sub2": "Type" equivalence, should + // Speed up in cases where requesting "Type.sub1.sub2" but only configured + // Logger "Type" + + // Don't even look for a logger if the LogLevel is lower than lowest log levels across all loggers + if (level < lowestLogLevel) + return false; + + Logger const* logger = GetLoggerByType(type); + if (!logger) + return false; + + LogLevel logLevel = logger->getLogLevel(); + return logLevel != LOG_LEVEL_DISABLED && logLevel <= level; +} + Log* Log::instance() { static Log instance; return &instance; } -void Log::Initialize(boost::asio::io_service* ioService) +void Log::Initialize(Trinity::Asio::IoContext* ioContext) { - if (ioService) + if (ioContext) { - _ioService = ioService; - _strand = new boost::asio::strand(*ioService); + _ioContext = ioContext; + _strand = new Trinity::Asio::Strand(*ioContext); } LoadFromConfig(); @@ -341,7 +372,7 @@ void Log::SetSynchronous() { delete _strand; _strand = nullptr; - _ioService = nullptr; + _ioContext = nullptr; } void Log::LoadFromConfig() diff --git a/src/common/Logging/Log.h b/src/common/Logging/Log.h index fe84a4cc6bc..118fcdba6fc 100644 --- a/src/common/Logging/Log.h +++ b/src/common/Logging/Log.h @@ -20,20 +20,35 @@ #define TRINITYCORE_LOG_H #include "Define.h" -#include "Appender.h" -#include "Logger.h" +#include "AsioHacksFwd.h" +#include "LogCommon.h" #include "StringFormat.h" -#include "Common.h" -#include -#include - -#include -#include -#include #include +#include +#include + +class Appender; +class Logger; +struct LogMessage; + +namespace Trinity +{ + namespace Asio + { + class IoContext; + } +} #define LOGGER_ROOT "root" +typedef Appender*(*AppenderCreatorFn)(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, std::vector&& extraArgs); + +template +Appender* CreateAppender(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, std::vector&& extraArgs) +{ + return new AppenderImpl(id, name, level, flags, std::forward>(extraArgs)); +} + class TC_COMMON_API Log { typedef std::unordered_map LoggerMap; @@ -41,12 +56,15 @@ class TC_COMMON_API Log private: Log(); ~Log(); + Log(Log const&) = delete; + Log(Log&&) = delete; + Log& operator=(Log const&) = delete; + Log& operator=(Log&&) = delete; public: - static Log* instance(); - void Initialize(boost::asio::io_service* ioService); + void Initialize(Trinity::Asio::IoContext* ioContext); void SetSynchronous(); // Not threadsafe - should only be called from main() after all threads are joined void LoadFromConfig(); void Close(); @@ -56,8 +74,7 @@ class TC_COMMON_API Log template inline void outMessage(std::string const& filter, LogLevel const level, Format&& fmt, Args&&... args) { - write(Trinity::make_unique(level, filter, - Trinity::StringFormat(std::forward(fmt), std::forward(args)...))); + outMessage(filter, level, Trinity::StringFormat(std::forward(fmt), std::forward(args)...)); } template @@ -66,26 +83,18 @@ class TC_COMMON_API Log if (!ShouldLog("commands.gm", LOG_LEVEL_INFO)) return; - std::unique_ptr msg = - Trinity::make_unique(LOG_LEVEL_INFO, "commands.gm", - Trinity::StringFormat(std::forward(fmt), std::forward(args)...)); - - msg->param1 = std::to_string(account); - - write(std::move(msg)); + outCommand(Trinity::StringFormat(std::forward(fmt), std::forward(args)...), std::to_string(account)); } void outCharDump(char const* str, uint32 account_id, uint64 guid, char const* name); void SetRealmId(uint32 id); - template + template void RegisterAppender() { using Index = typename AppenderImpl::TypeIndex; - auto itr = appenderFactory.find(Index::value); - ASSERT(itr == appenderFactory.end()); - appenderFactory[Index::value] = &CreateAppender; + RegisterAppender(Index::value, &CreateAppender); } std::string const& GetLogsDir() const { return m_logsDir; } @@ -102,55 +111,23 @@ class TC_COMMON_API Log void CreateLoggerFromConfig(std::string const& name); void ReadAppendersFromConfig(); void ReadLoggersFromConfig(); + void RegisterAppender(uint8 index, AppenderCreatorFn appenderCreateFn); + void outMessage(std::string const& filter, LogLevel const level, std::string&& message); + void outCommand(std::string&& message, std::string&& param1); - AppenderCreatorMap appenderFactory; - AppenderMap appenders; - LoggerMap loggers; + std::unordered_map appenderFactory; + std::unordered_map> appenders; + std::unordered_map> loggers; uint8 AppenderId; LogLevel lowestLogLevel; std::string m_logsDir; std::string m_logsTimestamp; - boost::asio::io_service* _ioService; - boost::asio::strand* _strand; + Trinity::Asio::IoContext* _ioContext; + Trinity::Asio::Strand* _strand; }; -inline Logger const* Log::GetLoggerByType(std::string const& type) const -{ - LoggerMap::const_iterator it = loggers.find(type); - if (it != loggers.end()) - return &(it->second); - - if (type == LOGGER_ROOT) - return NULL; - - std::string parentLogger = LOGGER_ROOT; - size_t found = type.find_last_of('.'); - if (found != std::string::npos) - parentLogger = type.substr(0,found); - - return GetLoggerByType(parentLogger); -} - -inline bool Log::ShouldLog(std::string const& type, LogLevel level) const -{ - // TODO: Use cache to store "Type.sub1.sub2": "Type" equivalence, should - // Speed up in cases where requesting "Type.sub1.sub2" but only configured - // Logger "Type" - - // Don't even look for a logger if the LogLevel is lower than lowest log levels across all loggers - if (level < lowestLogLevel) - return false; - - Logger const* logger = GetLoggerByType(type); - if (!logger) - return false; - - LogLevel logLevel = logger->getLogLevel(); - return logLevel != LOG_LEVEL_DISABLED && logLevel <= level; -} - #define sLog Log::instance() #define LOG_EXCEPTION_FREE(filterType__, level__, ...) \ diff --git a/src/common/Logging/LogCommon.h b/src/common/Logging/LogCommon.h new file mode 100644 index 00000000000..0c10421e22f --- /dev/null +++ b/src/common/Logging/LogCommon.h @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef LogCommon_h__ +#define LogCommon_h__ + +enum LogLevel +{ + LOG_LEVEL_DISABLED = 0, + LOG_LEVEL_TRACE = 1, + LOG_LEVEL_DEBUG = 2, + LOG_LEVEL_INFO = 3, + LOG_LEVEL_WARN = 4, + LOG_LEVEL_ERROR = 5, + LOG_LEVEL_FATAL = 6, + + NUM_ENABLED_LOG_LEVELS = 6 +}; + +enum AppenderType : uint8 +{ + APPENDER_NONE, + APPENDER_CONSOLE, + APPENDER_FILE, + APPENDER_DB +}; + +enum AppenderFlags +{ + APPENDER_FLAGS_NONE = 0x00, + APPENDER_FLAGS_PREFIX_TIMESTAMP = 0x01, + APPENDER_FLAGS_PREFIX_LOGLEVEL = 0x02, + APPENDER_FLAGS_PREFIX_LOGFILTERTYPE = 0x04, + APPENDER_FLAGS_USE_TIMESTAMP = 0x08, + APPENDER_FLAGS_MAKE_FILE_BACKUP = 0x10 +}; + +#endif // LogCommon_h__ diff --git a/src/common/Logging/LogMessage.cpp b/src/common/Logging/LogMessage.cpp new file mode 100644 index 00000000000..51d75ed6d50 --- /dev/null +++ b/src/common/Logging/LogMessage.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#include "LogMessage.h" +#include "Util.h" + +LogMessage::LogMessage(LogLevel _level, std::string const& _type, std::string&& _text) + : level(_level), type(_type), text(std::forward(_text)), mtime(time(nullptr)) +{ +} + +LogMessage::LogMessage(LogLevel _level, std::string const& _type, std::string&& _text, std::string&& _param1) + : level(_level), type(_type), text(std::forward(_text)), param1(std::forward(_param1)), mtime(time(nullptr)) +{ +} + +std::string LogMessage::getTimeStr(time_t time) +{ + tm aTm; + localtime_r(&time, &aTm); + char buf[20]; + snprintf(buf, 20, "%04d-%02d-%02d_%02d:%02d:%02d", aTm.tm_year + 1900, aTm.tm_mon + 1, aTm.tm_mday, aTm.tm_hour, aTm.tm_min, aTm.tm_sec); + return std::string(buf); +} + +std::string LogMessage::getTimeStr() const +{ + return getTimeStr(mtime); +} diff --git a/src/common/Logging/LogMessage.h b/src/common/Logging/LogMessage.h new file mode 100644 index 00000000000..424677203ac --- /dev/null +++ b/src/common/Logging/LogMessage.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef LogMessage_h__ +#define LogMessage_h__ + +#include "Define.h" +#include "LogCommon.h" +#include +#include + +struct TC_COMMON_API LogMessage +{ + LogMessage(LogLevel _level, std::string const& _type, std::string&& _text); + LogMessage(LogLevel _level, std::string const& _type, std::string&& _text, std::string&& _param1); + + LogMessage(LogMessage const& /*other*/) = delete; + LogMessage& operator=(LogMessage const& /*other*/) = delete; + + static std::string getTimeStr(time_t time); + std::string getTimeStr() const; + + LogLevel const level; + std::string const type; + std::string const text; + std::string prefix; + std::string param1; + time_t mtime; + + ///@ Returns size of the log message content in bytes + uint32 Size() const + { + return static_cast(prefix.size() + text.size()); + } +}; + +#endif // LogMessage_h__ diff --git a/src/common/Logging/LogOperation.cpp b/src/common/Logging/LogOperation.cpp index 99740d97af6..2ceb2edccf4 100644 --- a/src/common/Logging/LogOperation.cpp +++ b/src/common/Logging/LogOperation.cpp @@ -17,9 +17,18 @@ #include "LogOperation.h" #include "Logger.h" +#include "LogMessage.h" + +LogOperation::LogOperation(Logger const* logger, std::unique_ptr&& msg) : _logger(logger), _msg(std::forward>(_msg)) +{ +} + +LogOperation::~LogOperation() +{ +} int LogOperation::call() { - logger->write(msg.get()); + _logger->write(_msg.get()); return 0; } diff --git a/src/common/Logging/LogOperation.h b/src/common/Logging/LogOperation.h index 641eca92683..42f0597ca5a 100644 --- a/src/common/Logging/LogOperation.h +++ b/src/common/Logging/LogOperation.h @@ -18,6 +18,7 @@ #ifndef LOGOPERATION_H #define LOGOPERATION_H +#include "Define.h" #include class Logger; @@ -26,17 +27,14 @@ struct LogMessage; class TC_COMMON_API LogOperation { public: - LogOperation(Logger const* _logger, std::unique_ptr&& _msg) - : logger(_logger), msg(std::forward>(_msg)) - { } - - ~LogOperation() { } + LogOperation(Logger const* logger, std::unique_ptr&& msg); + ~LogOperation(); int call(); protected: - Logger const* logger; - std::unique_ptr msg; + Logger const* _logger; + std::unique_ptr _msg; }; #endif diff --git a/src/common/Logging/Logger.cpp b/src/common/Logging/Logger.cpp index 5ca4e597cdc..3e609b29165 100644 --- a/src/common/Logging/Logger.cpp +++ b/src/common/Logging/Logger.cpp @@ -16,49 +16,45 @@ */ #include "Logger.h" +#include "Appender.h" +#include "LogMessage.h" -Logger::Logger(): name(""), level(LOG_LEVEL_DISABLED) { } - -void Logger::Create(std::string const& _name, LogLevel _level) -{ - name = _name; - level = _level; -} +Logger::Logger(std::string const& name, LogLevel level): _name(name), _level(level) { } std::string const& Logger::getName() const { - return name; + return _name; } LogLevel Logger::getLogLevel() const { - return level; + return _level; } void Logger::addAppender(uint8 id, Appender* appender) { - appenders[id] = appender; + _appenders[id] = appender; } void Logger::delAppender(uint8 id) { - appenders.erase(id); + _appenders.erase(id); } -void Logger::setLogLevel(LogLevel _level) +void Logger::setLogLevel(LogLevel level) { - level = _level; + _level = level; } void Logger::write(LogMessage* message) const { - if (!level || level > message->level || message->text.empty()) + if (!_level || _level > message->level || message->text.empty()) { //fprintf(stderr, "Logger::write: Logger %s, Level %u. Msg %s Level %u WRONG LEVEL MASK OR EMPTY MSG\n", getName().c_str(), getLogLevel(), message.text.c_str(), message.level); return; } - for (AppenderMap::const_iterator it = appenders.begin(); it != appenders.end(); ++it) + for (auto it = _appenders.begin(); it != _appenders.end(); ++it) if (it->second) it->second->write(message); } diff --git a/src/common/Logging/Logger.h b/src/common/Logging/Logger.h index 63d2cb4dfcc..fa11bd9c2fc 100644 --- a/src/common/Logging/Logger.h +++ b/src/common/Logging/Logger.h @@ -18,15 +18,20 @@ #ifndef LOGGER_H #define LOGGER_H -#include "Appender.h" +#include "Define.h" +#include "LogCommon.h" +#include +#include + +class Appender; +struct LogMessage; class TC_COMMON_API Logger { public: - Logger(); + Logger(std::string const& name, LogLevel level); - void Create(std::string const& name, LogLevel level); - void addAppender(uint8 type, Appender *); + void addAppender(uint8 type, Appender* appender); void delAppender(uint8 type); std::string const& getName() const; @@ -35,9 +40,9 @@ class TC_COMMON_API Logger void write(LogMessage* message) const; private: - std::string name; - LogLevel level; - AppenderMap appenders; + std::string _name; + LogLevel _level; + std::unordered_map _appenders; }; #endif diff --git a/src/common/Metric/Metric.cpp b/src/common/Metric/Metric.cpp index 058c3a9311e..20b01362a72 100644 --- a/src/common/Metric/Metric.cpp +++ b/src/common/Metric/Metric.cpp @@ -16,23 +16,30 @@ */ #include "Metric.h" -#include "Log.h" +#include "Common.h" #include "Config.h" +#include "Log.h" +#include "Strand.h" #include "Util.h" +#include +#include +#include -void Metric::Initialize(std::string const& realmName, boost::asio::io_service& ioService, std::function overallStatusLogger) +void Metric::Initialize(std::string const& realmName, Trinity::Asio::IoContext& ioContext, std::function overallStatusLogger) { + _dataStream = Trinity::make_unique(); _realmName = FormatInfluxDBTagValue(realmName); - _batchTimer = Trinity::make_unique(ioService); - _overallStatusTimer = Trinity::make_unique(ioService); + _batchTimer = Trinity::make_unique(ioContext); + _overallStatusTimer = Trinity::make_unique(ioContext); _overallStatusLogger = overallStatusLogger; LoadFromConfigs(); } bool Metric::Connect() { - _dataStream.connect(_hostname, _port); - auto error = _dataStream.error(); + auto& stream = static_cast(GetDataStream()); + stream.connect(_hostname, _port); + auto error = stream.error(); if (error) { TC_LOG_ERROR("metric", "Error connecting to '%s:%s', disabling Metric. Error message : %s", @@ -40,7 +47,7 @@ bool Metric::Connect() _enabled = false; return false; } - _dataStream.clear(); + stream.clear(); return true; } @@ -156,22 +163,22 @@ void Metric::SendBatch() return; } - if (!_dataStream.good() && !Connect()) + if (!GetDataStream().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"; + GetDataStream() << "POST " << "/write?db=" << _databaseName << " HTTP/1.1\r\n"; + GetDataStream() << "Host: " << _hostname << ":" << _port << "\r\n"; + GetDataStream() << "Accept: */*\r\n"; + GetDataStream() << "Content-Type: application/octet-stream\r\n"; + GetDataStream() << "Content-Transfer-Encoding: binary\r\n"; - _dataStream << "Content-Length: " << std::to_string(batchedData.tellp()) << "\r\n\r\n"; - _dataStream << batchedData.rdbuf(); + GetDataStream() << "Content-Length: " << std::to_string(batchedData.tellp()) << "\r\n\r\n"; + GetDataStream() << batchedData.rdbuf(); std::string http_version; - _dataStream >> http_version; + GetDataStream() >> http_version; unsigned int status_code = 0; - _dataStream >> status_code; + GetDataStream() >> status_code; if (status_code != 204) { TC_LOG_ERROR("metric", "Error sending data, returned HTTP code: %u", status_code); @@ -179,14 +186,12 @@ void Metric::SendBatch() // Read and ignore the status description std::string status_description; - std::getline(_dataStream, status_description); + std::getline(GetDataStream(), status_description); // Read headers std::string header; - while (std::getline(_dataStream, header) && header != "\r") - { + while (std::getline(GetDataStream(), header) && header != "\r") if (header == "Connection: close\r") - _dataStream.close(); - } + static_cast(GetDataStream()).close(); ScheduleSend(); } @@ -200,7 +205,7 @@ void Metric::ScheduleSend() } else { - _dataStream.close(); + static_cast(GetDataStream()).close(); MetricData* data; // Clear the queue while (_queuedData.Dequeue(data)) @@ -210,8 +215,8 @@ void Metric::ScheduleSend() void Metric::Unload() { - // Send what's queued only if io_service is stopped (so only on shutdown) - if (_enabled && _batchTimer->get_io_service().stopped()) + // Send what's queued only if IoContext is stopped (so only on shutdown) + if (_enabled && Trinity::Asio::get_io_context(*_batchTimer).stopped()) { _enabled = false; SendBatch(); @@ -234,8 +239,62 @@ void Metric::ScheduleOverallStatusLog() } } +std::string Metric::FormatInfluxDBValue(bool value) +{ + return value ? "t" : "f"; +} + +template +std::string Metric::FormatInfluxDBValue(T value) +{ + return std::to_string(value) + 'i'; +} + +std::string Metric::FormatInfluxDBValue(std::string const& value) +{ + return '"' + boost::replace_all_copy(value, "\"", "\\\"") + '"'; +} + +std::string Metric::FormatInfluxDBValue(char const* value) +{ + return FormatInfluxDBValue(std::string(value)); +} + +std::string Metric::FormatInfluxDBValue(double value) +{ + return std::to_string(value); +} + +std::string Metric::FormatInfluxDBValue(float value) +{ + return FormatInfluxDBValue(double(value)); +} + +std::string Metric::FormatInfluxDBTagValue(std::string const& value) +{ + // ToDo: should handle '=' and ',' characters too + return boost::replace_all_copy(value, " ", "\\ "); +} + +Metric::Metric() +{ +} + +Metric::~Metric() +{ +} + Metric* Metric::instance() { static Metric instance; return &instance; } + +template TC_COMMON_API std::string Metric::FormatInfluxDBValue(int8); +template TC_COMMON_API std::string Metric::FormatInfluxDBValue(uint8); +template TC_COMMON_API std::string Metric::FormatInfluxDBValue(int16); +template TC_COMMON_API std::string Metric::FormatInfluxDBValue(uint16); +template TC_COMMON_API std::string Metric::FormatInfluxDBValue(int32); +template TC_COMMON_API std::string Metric::FormatInfluxDBValue(uint32); +template TC_COMMON_API std::string Metric::FormatInfluxDBValue(int64); +template TC_COMMON_API std::string Metric::FormatInfluxDBValue(uint64); diff --git a/src/common/Metric/Metric.h b/src/common/Metric/Metric.h index ec95f20eec6..97a2a6b2e6f 100644 --- a/src/common/Metric/Metric.h +++ b/src/common/Metric/Metric.h @@ -18,11 +18,22 @@ #ifndef METRIC_H__ #define METRIC_H__ -#include "Common.h" -#include "Threading/MPSCQueue.h" -#include -#include -#include +#include "Define.h" +#include "AsioHacksFwd.h" +#include "MPSCQueue.h" +#include +#include +#include +#include +#include + +namespace Trinity +{ + namespace Asio + { + class IoContext; + } +} enum MetricDataType { @@ -33,7 +44,7 @@ enum MetricDataType struct MetricData { std::string Category; - std::chrono::time_point Timestamp; + std::chrono::system_clock::time_point Timestamp; MetricDataType Type; // LogValue-specific fields @@ -47,7 +58,8 @@ struct MetricData class TC_COMMON_API Metric { private: - boost::asio::ip::tcp::iostream _dataStream; + std::iostream& GetDataStream() { return *_dataStream; } + std::unique_ptr _dataStream; MPSCQueue _queuedData; std::unique_ptr _batchTimer; std::unique_ptr _overallStatusTimer; @@ -66,31 +78,24 @@ private: void ScheduleSend(); void ScheduleOverallStatusLog(); - template::value>::type* = nullptr> - static std::string FormatInfluxDBValue(T value) { return std::to_string(value) + 'i'; } + static std::string FormatInfluxDBValue(bool value); + template + static std::string FormatInfluxDBValue(T value); + static std::string FormatInfluxDBValue(std::string const& value); + static std::string FormatInfluxDBValue(char const* value); + static std::string FormatInfluxDBValue(double value); + static std::string FormatInfluxDBValue(float value); - 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)); } - - static std::string FormatInfluxDBTagValue(std::string const& value) - { - // ToDo: should handle '=' and ',' characters too - return boost::replace_all_copy(value, " ", "\\ "); - } + static std::string FormatInfluxDBTagValue(std::string const& value); // ToDo: should format TagKey and FieldKey too in the same way as TagValue public: + Metric(); + ~Metric(); static Metric* instance(); - void Initialize(std::string const& realmName, boost::asio::io_service& ioService, std::function overallStatusLogger = [](){}); + void Initialize(std::string const& realmName, Trinity::Asio::IoContext& ioContext, std::function overallStatusLogger); void LoadFromConfigs(); void Update(); diff --git a/src/common/PrecompiledHeaders/commonPCH.cpp b/src/common/PrecompiledHeaders/commonPCH.cpp deleted file mode 100644 index 52c623ca64a..00000000000 --- a/src/common/PrecompiledHeaders/commonPCH.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "PrecompiledHeaders/commonPCH.h" diff --git a/src/common/PrecompiledHeaders/commonPCH.h b/src/common/PrecompiledHeaders/commonPCH.h index 2d4f1ff4694..214ad549ea0 100644 --- a/src/common/PrecompiledHeaders/commonPCH.h +++ b/src/common/PrecompiledHeaders/commonPCH.h @@ -1,13 +1,41 @@ -#include "Define.h" -#include "Common.h" +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + #include "BoundingIntervalHierarchy.h" -#include "BoundingIntervalHierarchyWrapper.h" -#include "RegularGrid.h" -#include "Collision/VMapDefinitions.h" -#include "Collision/Maps/MapTree.h" -#include "Collision/Models/WorldModel.h" -#include "Collision/Models/ModelInstance.h" -#include "Collision/Models/GameObjectModel.h" -#include "Threading/ProducerConsumerQueue.h" -#include "Utilities/TaskScheduler.h" -#include "Utilities/EventMap.h" +#include "Common.h" +#include "Config.h" +#include "Define.h" +#include "Errors.h" +#include "GitRevision.h" +#include "Log.h" +#include "LogMessage.h" +#include "MapTree.h" +#include "ModelInstance.h" +#include "Util.h" +#include "VMapDefinitions.h" +#include "WorldModel.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include diff --git a/src/common/Threading/ProcessPriority.cpp b/src/common/Threading/ProcessPriority.cpp new file mode 100644 index 00000000000..7673ea40952 --- /dev/null +++ b/src/common/Threading/ProcessPriority.cpp @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#include "ProcessPriority.h" +#include "Log.h" + +#ifdef _WIN32 // Windows +#include +#elif defined(__linux__) +#include +#include +#define PROCESS_HIGH_PRIORITY -15 // [-20, 19], default is 0 +#endif + +void SetProcessPriority(std::string const& logChannel, uint32 affinity, bool highPriority) +{ + ///- Handle affinity for multiple processors and process priority +#ifdef _WIN32 // Windows + + HANDLE hProcess = GetCurrentProcess(); + if (affinity > 0) + { + ULONG_PTR appAff; + ULONG_PTR sysAff; + + if (GetProcessAffinityMask(hProcess, &appAff, &sysAff)) + { + // remove non accessible processors + ULONG_PTR currentAffinity = affinity & appAff; + + if (!currentAffinity) + TC_LOG_ERROR(logChannel, "Processors marked in UseProcessors bitmask (hex) %x are not accessible. Accessible processors bitmask (hex): %x", affinity, appAff); + else if (SetProcessAffinityMask(hProcess, currentAffinity)) + TC_LOG_INFO(logChannel, "Using processors (bitmask, hex): %x", currentAffinity); + else + TC_LOG_ERROR(logChannel, "Can't set used processors (hex): %x", currentAffinity); + } + } + + if (highPriority) + { + if (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS)) + TC_LOG_INFO(logChannel, "Process priority class set to HIGH"); + else + TC_LOG_ERROR(logChannel, "Can't set process priority class."); + } + +#elif defined(__linux__) // Linux + + if (affinity > 0) + { + cpu_set_t mask; + CPU_ZERO(&mask); + + for (unsigned int i = 0; i < sizeof(affinity) * 8; ++i) + if (affinity & (1 << i)) + CPU_SET(i, &mask); + + if (sched_setaffinity(0, sizeof(mask), &mask)) + TC_LOG_ERROR(logChannel, "Can't set used processors (hex): %x, error: %s", affinity, strerror(errno)); + else + { + CPU_ZERO(&mask); + sched_getaffinity(0, sizeof(mask), &mask); + TC_LOG_INFO(logChannel, "Using processors (bitmask, hex): %lx", *(__cpu_mask*)(&mask)); + } + } + + if (highPriority) + { + if (setpriority(PRIO_PROCESS, 0, PROCESS_HIGH_PRIORITY)) + TC_LOG_ERROR(logChannel, "Can't set process priority class, error: %s", strerror(errno)); + else + TC_LOG_INFO(logChannel, "Process priority class set to %i", getpriority(PRIO_PROCESS, 0)); + } + +#else + // Suppresses unused argument warning for all other platforms + (void)logChannel; + (void)affinity; + (void)highPriority; +#endif +} diff --git a/src/common/Threading/ProcessPriority.h b/src/common/Threading/ProcessPriority.h index cd17d4c0125..8b7797e3035 100644 --- a/src/common/Threading/ProcessPriority.h +++ b/src/common/Threading/ProcessPriority.h @@ -18,86 +18,12 @@ #ifndef _PROCESSPRIO_H #define _PROCESSPRIO_H -#include "Configuration/Config.h" +#include "Define.h" +#include -#ifdef __linux__ -#include -#include -#define PROCESS_HIGH_PRIORITY -15 // [-20, 19], default is 0 -#endif +#define CONFIG_PROCESSOR_AFFINITY "UseProcessors" +#define CONFIG_HIGH_PRIORITY "ProcessPriority" -void SetProcessPriority(const std::string& logChannel) -{ -#if defined(_WIN32) || defined(__linux__) - - ///- Handle affinity for multiple processors and process priority - uint32 affinity = sConfigMgr->GetIntDefault("UseProcessors", 0); - bool highPriority = sConfigMgr->GetBoolDefault("ProcessPriority", false); - -#ifdef _WIN32 // Windows - - HANDLE hProcess = GetCurrentProcess(); - if (affinity > 0) - { - ULONG_PTR appAff; - ULONG_PTR sysAff; - - if (GetProcessAffinityMask(hProcess, &appAff, &sysAff)) - { - // remove non accessible processors - ULONG_PTR currentAffinity = affinity & appAff; - - if (!currentAffinity) - TC_LOG_ERROR(logChannel, "Processors marked in UseProcessors bitmask (hex) %x are not accessible. Accessible processors bitmask (hex): %x", affinity, appAff); - else if (SetProcessAffinityMask(hProcess, currentAffinity)) - TC_LOG_INFO(logChannel, "Using processors (bitmask, hex): %x", currentAffinity); - else - TC_LOG_ERROR(logChannel, "Can't set used processors (hex): %x", currentAffinity); - } - } - - if (highPriority) - { - if (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS)) - TC_LOG_INFO(logChannel, "Process priority class set to HIGH"); - else - TC_LOG_ERROR(logChannel, "Can't set process priority class."); - } - -#else // Linux - - if (affinity > 0) - { - cpu_set_t mask; - CPU_ZERO(&mask); - - for (unsigned int i = 0; i < sizeof(affinity) * 8; ++i) - if (affinity & (1 << i)) - CPU_SET(i, &mask); - - if (sched_setaffinity(0, sizeof(mask), &mask)) - TC_LOG_ERROR(logChannel, "Can't set used processors (hex): %x, error: %s", affinity, strerror(errno)); - else - { - CPU_ZERO(&mask); - sched_getaffinity(0, sizeof(mask), &mask); - TC_LOG_INFO(logChannel, "Using processors (bitmask, hex): %lx", *(__cpu_mask*)(&mask)); - } - } - - if (highPriority) - { - if (setpriority(PRIO_PROCESS, 0, PROCESS_HIGH_PRIORITY)) - TC_LOG_ERROR(logChannel, "Can't set process priority class, error: %s", strerror(errno)); - else - TC_LOG_INFO(logChannel, "Process priority class set to %i", getpriority(PRIO_PROCESS, 0)); - } - -#endif -#else - // Suppresses unused argument warning for all other platforms - (void)logChannel; -#endif -} +void TC_COMMON_API SetProcessPriority(std::string const& logChannel, uint32 affinity, bool highPriority); #endif diff --git a/src/common/Utilities/Duration.h b/src/common/Utilities/Duration.h index 91372618f66..8d1fc9afb49 100644 --- a/src/common/Utilities/Duration.h +++ b/src/common/Utilities/Duration.h @@ -33,7 +33,6 @@ typedef std::chrono::minutes Minutes; typedef std::chrono::hours Hours; /// Makes std::chrono_literals globally available. -// ToDo: Enable this when TC supports C++14. -// using namespace std::chrono_literals; +using namespace std::chrono_literals; #endif // _DURATION_H_ diff --git a/src/common/Utilities/EventMap.cpp b/src/common/Utilities/EventMap.cpp index d7976513423..b82507b5281 100644 --- a/src/common/Utilities/EventMap.cpp +++ b/src/common/Utilities/EventMap.cpp @@ -16,6 +16,7 @@ */ #include "EventMap.h" +#include "Random.h" void EventMap::Reset() { @@ -32,6 +33,11 @@ void EventMap::SetPhase(uint8 phase) _phase = uint8(1 << (phase - 1)); } +void EventMap::ScheduleEvent(uint32 eventId, Milliseconds const& minTime, Milliseconds const& maxTime, uint32 group /*= 0*/, uint32 phase /*= 0*/) +{ + ScheduleEvent(eventId, urand(uint32(minTime.count()), uint32(maxTime.count())), group, phase); +} + void EventMap::ScheduleEvent(uint32 eventId, uint32 time, uint32 group /*= 0*/, uint8 phase /*= 0*/) { if (group && group <= 8) @@ -43,6 +49,16 @@ void EventMap::ScheduleEvent(uint32 eventId, uint32 time, uint32 group /*= 0*/, _eventMap.insert(EventStore::value_type(_time + time, eventId)); } +void EventMap::RescheduleEvent(uint32 eventId, Milliseconds const& minTime, Milliseconds const& maxTime, uint32 group /*= 0*/, uint32 phase /*= 0*/) +{ + RescheduleEvent(eventId, urand(uint32(minTime.count()), uint32(maxTime.count())), group, phase); +} + +void EventMap::Repeat(uint32 minTime, uint32 maxTime) +{ + Repeat(urand(minTime, maxTime)); +} + uint32 EventMap::ExecuteEvent() { while (!Empty()) diff --git a/src/common/Utilities/EventMap.h b/src/common/Utilities/EventMap.h index 65f8bd02da4..e8f062c54fe 100644 --- a/src/common/Utilities/EventMap.h +++ b/src/common/Utilities/EventMap.h @@ -18,9 +18,9 @@ #ifndef _EVENT_MAP_H_ #define _EVENT_MAP_H_ -#include "Common.h" +#include "Define.h" #include "Duration.h" -#include "Util.h" +#include class TC_COMMON_API EventMap { @@ -134,10 +134,7 @@ public: * @param group The group which the event is associated to. Has to be between 1 and 8. 0 means it has no group. * @param phase The phase in which the event can occur. Has to be between 1 and 8. 0 means it can occur in all phases. */ - void ScheduleEvent(uint32 eventId, Milliseconds const& minTime, Milliseconds const& maxTime, uint32 group = 0, uint32 phase = 0) - { - ScheduleEvent(eventId, urand(uint32(minTime.count()), uint32(maxTime.count())), group, phase); - } + void ScheduleEvent(uint32 eventId, Milliseconds const& minTime, Milliseconds const& maxTime, uint32 group = 0, uint32 phase = 0); /** * @name ScheduleEvent @@ -171,10 +168,7 @@ public: * @param group The group which the event is associated to. Has to be between 1 and 8. 0 means it has no group. * @param phase The phase in which the event can occur. Has to be between 1 and 8. 0 means it can occur in all phases. */ - void RescheduleEvent(uint32 eventId, Milliseconds const& minTime, Milliseconds const& maxTime, uint32 group = 0, uint32 phase = 0) - { - RescheduleEvent(eventId, urand(uint32(minTime.count()), uint32(maxTime.count())), group, phase); - } + void RescheduleEvent(uint32 eventId, Milliseconds const& minTime, Milliseconds const& maxTime, uint32 group = 0, uint32 phase = 0); /** * @name RescheduleEvent @@ -227,10 +221,7 @@ public: * @param minTime Minimum time until the event occurs. * @param maxTime Maximum time until the event occurs. */ - void Repeat(uint32 minTime, uint32 maxTime) - { - Repeat(urand(minTime, maxTime)); - } + void Repeat(uint32 minTime, uint32 maxTime); /** * @name ExecuteEvent diff --git a/src/common/Utilities/Hash.h b/src/common/Utilities/Hash.h new file mode 100644 index 00000000000..514cb2c72d2 --- /dev/null +++ b/src/common/Utilities/Hash.h @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef TrinityCore_Hash_h__ +#define TrinityCore_Hash_h__ + +#include +#include + +namespace Trinity +{ + template + inline void hash_combine(std::size_t& seed, T const& val) + { + seed ^= std::hash()(val) + 0x9E3779B9 + (seed << 6) + (seed >> 2); + } +} + + //! Hash implementation for std::pair to allow using pairs in unordered_set or as key for unordered_map + //! Individual types used in pair must be hashable by std::hash +namespace std +{ + template + struct hash> + { + public: + size_t operator()(std::pair const& p) const + { + size_t hashVal = 0; + Trinity::hash_combine(hashVal, p.first); + Trinity::hash_combine(hashVal, p.second); + return hashVal; + } + }; +} + +#endif // TrinityCore_Hash_h__ diff --git a/src/server/database/PrecompiledHeaders/databasePCH.cpp b/src/common/Utilities/Optional.h similarity index 78% rename from src/server/database/PrecompiledHeaders/databasePCH.cpp rename to src/common/Utilities/Optional.h index 2a83f984e92..07f11d648e4 100644 --- a/src/server/database/PrecompiledHeaders/databasePCH.cpp +++ b/src/common/Utilities/Optional.h @@ -15,4 +15,11 @@ * with this program. If not, see . */ -#include "databasePCH.h" +#ifndef TrinityCore_Optional_h__ +#define TrinityCore_Optional_h__ + +#include "OptionalFwd.h" +#include +#include + +#endif // TrinityCore_Optional_h__ diff --git a/src/server/scripts/ScriptPCH.cpp b/src/common/Utilities/OptionalFwd.h similarity index 74% rename from src/server/scripts/ScriptPCH.cpp rename to src/common/Utilities/OptionalFwd.h index 68a806c3771..56716d96a4f 100644 --- a/src/server/scripts/ScriptPCH.cpp +++ b/src/common/Utilities/OptionalFwd.h @@ -1,6 +1,5 @@ /* * Copyright (C) 2008-2018 TrinityCore - * Copyright (C) 2006 - 2009 ScriptDev2 * * 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,4 +15,17 @@ * with this program. If not, see . */ -#include "ScriptPCH.h" +#ifndef OptionalFwd_h__ +#define OptionalFwd_h__ + +namespace boost +{ + template + class optional; +} + +//! Optional helper class to wrap optional values within. +template +using Optional = boost::optional; + +#endif // OptionalFwd_h__ diff --git a/src/common/Utilities/StartProcess.cpp b/src/common/Utilities/StartProcess.cpp index 8a88364136f..ce252087d85 100644 --- a/src/common/Utilities/StartProcess.cpp +++ b/src/common/Utilities/StartProcess.cpp @@ -16,27 +16,20 @@ */ #include "StartProcess.h" - -#include -#include -#include +#include "Errors.h" +#include "Log.h" +#include "Optional.h" #include -#include #include -#include -#include #include -#include - -#include "Common.h" -#include "Log.h" using namespace boost::process; using namespace boost::process::initializers; using namespace boost::iostreams; -namespace Trinity { +namespace Trinity +{ template class TCLogSink @@ -51,7 +44,7 @@ public: TCLogSink(T callback) : callback_(std::move(callback)) { } - std::streamsize write(const char* str, std::streamsize size) + std::streamsize write(char const* str, std::streamsize size) { callback_(std::string(str, size)); return size; @@ -250,19 +243,15 @@ std::shared_ptr return handle; } -Optional SearchExecutableInPath(std::string const& filename) +std::string SearchExecutableInPath(std::string const& filename) { try { - auto result = search_path(filename); - if (result.empty()) - return boost::none; - else - return result; + return search_path(filename); } catch (...) { - return boost::none; + return ""; } } diff --git a/src/common/Utilities/StartProcess.h b/src/common/Utilities/StartProcess.h index 6e912422225..ff5ff9d5295 100644 --- a/src/common/Utilities/StartProcess.h +++ b/src/common/Utilities/StartProcess.h @@ -18,11 +18,14 @@ #ifndef Process_h__ #define Process_h__ +#include "Define.h" #include #include -#include "Common.h" +#include +#include -namespace Trinity { +namespace Trinity +{ /// Starts a process with the given arguments and parameters and will block /// until the process is finished. @@ -59,8 +62,8 @@ TC_COMMON_API std::shared_ptr 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 SearchExecutableInPath(std::string const& filename); +/// and returns a non-empty string when it was found. +TC_COMMON_API std::string SearchExecutableInPath(std::string const& filename); } // namespace Trinity diff --git a/src/common/Utilities/StringFormat.h b/src/common/Utilities/StringFormat.h index 494597f5e76..43830e7f99d 100644 --- a/src/common/Utilities/StringFormat.h +++ b/src/common/Utilities/StringFormat.h @@ -31,7 +31,7 @@ namespace Trinity } /// Returns true if the given char pointer is null. - inline bool IsFormatEmptyOrNull(const char* fmt) + inline bool IsFormatEmptyOrNull(char const* fmt) { return fmt == nullptr; } diff --git a/src/common/Utilities/TaskScheduler.cpp b/src/common/Utilities/TaskScheduler.cpp index 50e7198fe96..93482a8530a 100644 --- a/src/common/Utilities/TaskScheduler.cpp +++ b/src/common/Utilities/TaskScheduler.cpp @@ -16,6 +16,7 @@ */ #include "TaskScheduler.h" +#include "Errors.h" TaskScheduler& TaskScheduler::ClearValidator() { diff --git a/src/common/Utilities/TaskScheduler.h b/src/common/Utilities/TaskScheduler.h index 2783299285f..0f100532445 100644 --- a/src/common/Utilities/TaskScheduler.h +++ b/src/common/Utilities/TaskScheduler.h @@ -18,6 +18,9 @@ #ifndef _TASK_SCHEDULER_H_ #define _TASK_SCHEDULER_H_ +#include "Duration.h" +#include "Optional.h" +#include "Random.h" #include #include #include @@ -26,11 +29,6 @@ #include #include -#include - -#include "Util.h" -#include "Duration.h" - class TaskContext; /// The TaskScheduler class provides the ability to schedule std::function's in the near future. @@ -73,13 +71,13 @@ class TC_COMMON_API TaskScheduler timepoint_t _end; duration_t _duration; - boost::optional _group; + Optional _group; repeated_t _repeated; task_handler_t _task; public: // All Argument construct - Task(timepoint_t const& end, duration_t const& duration, boost::optional const& group, + Task(timepoint_t const& end, duration_t const& duration, Optional const& group, repeated_t const repeated, task_handler_t const& task) : _end(end), _duration(duration), _group(group), _repeated(repeated), _task(task) { } diff --git a/src/common/Utilities/Timer.h b/src/common/Utilities/Timer.h index 29f49fa594b..0c99e7afe0d 100644 --- a/src/common/Utilities/Timer.h +++ b/src/common/Utilities/Timer.h @@ -19,6 +19,7 @@ #ifndef TRINITY_TIMER_H #define TRINITY_TIMER_H +#include "Define.h" #include inline uint32 getMSTime() diff --git a/src/common/Utilities/Util.cpp b/src/common/Utilities/Util.cpp index 4eed82fde5c..889ab9176dd 100644 --- a/src/common/Utilities/Util.cpp +++ b/src/common/Utilities/Util.cpp @@ -18,11 +18,12 @@ #include "Util.h" #include "Common.h" -#include "CompilerDefs.h" -#include "utf8.h" -#include "Errors.h" // for ASSERT -#include -#include +#include "IpAddress.h" +#include +#include +#include +#include +#include #if TRINITY_COMPILER == TRINITY_COMPILER_GNU #include @@ -100,7 +101,7 @@ void stripLineInvisibleChars(std::string &str) } #if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__)) -struct tm* localtime_r(const time_t* time, struct tm *result) +struct tm* localtime_r(time_t const* time, struct tm *result) { localtime_s(result, time); return result; @@ -130,7 +131,7 @@ std::string secsToTimeString(uint64 timeInSecs, bool shortText, bool hoursOnly) return ss.str(); } -int64 MoneyStringToMoney(const std::string& moneyString) +int64 MoneyStringToMoney(std::string const& moneyString) { int64 money = 0; @@ -149,7 +150,7 @@ int64 MoneyStringToMoney(const std::string& moneyString) if (gCount + sCount + cCount != 1) return 0; - uint64 amount = atol(*itr); + uint64 amount = strtoull(*itr, nullptr, 10); if (gCount == 1) money += amount * 100 * 100; else if (sCount == 1) @@ -161,7 +162,7 @@ int64 MoneyStringToMoney(const std::string& moneyString) return money; } -uint32 TimeStringToSecs(const std::string& timestring) +uint32 TimeStringToSecs(std::string const& timestring) { uint32 secs = 0; uint32 buffer = 0; @@ -171,8 +172,8 @@ uint32 TimeStringToSecs(const std::string& timestring) { if (isdigit(*itr)) { - buffer*=10; - buffer+= (*itr)-'0'; + buffer *= 10; + buffer += (*itr) - '0'; } else { @@ -184,9 +185,9 @@ uint32 TimeStringToSecs(const std::string& timestring) case 's': multiplier = 1; break; default : return 0; //bad format } - buffer*=multiplier; - secs+=buffer; - buffer=0; + buffer *= multiplier; + secs += buffer; + buffer = 0; } } @@ -214,16 +215,16 @@ bool IsIPAddress(char const* ipaddress) if (!ipaddress) return false; - // Let the big boys do it. - // Drawback: all valid ip address formats are recognized e.g.: 12.23, 121234, 0xABCD) - return inet_addr(ipaddress) != INADDR_NONE; + boost::system::error_code error; + Trinity::Net::make_address(ipaddress, error); + return !error; } /// create PID file uint32 CreatePIDFile(std::string const& filename) { FILE* pid_file = fopen(filename.c_str(), "w"); - if (pid_file == NULL) + if (pid_file == nullptr) return 0; uint32 pid = GetPID(); @@ -374,6 +375,16 @@ bool WStrToUtf8(std::wstring const& wstr, std::string& utf8str) typedef wchar_t const* const* wstrlist; +void wstrToUpper(std::wstring& str) +{ + std::transform(str.begin(), str.end(), str.begin(), wcharToUpper); +} + +void wstrToLower(std::wstring& str) +{ + std::transform(str.begin(), str.end(), str.begin(), wcharToLower); +} + std::wstring GetMainPartOfName(std::wstring const& wname, uint32 declension) { // supported only Cyrillic cases @@ -400,20 +411,20 @@ std::wstring GetMainPartOfName(std::wstring const& wname, uint32 declension) static wchar_t const j_End[] = { wchar_t(1), wchar_t(0x0439), wchar_t(0x0000)}; static wchar_t const* const dropEnds[6][8] = { - { &a_End[1], &o_End[1], &ya_End[1], &ie_End[1], &soft_End[1], &j_End[1], NULL, NULL }, - { &a_End[1], &ya_End[1], &yeru_End[1], &i_End[1], NULL, NULL, NULL, NULL }, - { &ie_End[1], &u_End[1], &yu_End[1], &i_End[1], NULL, NULL, NULL, NULL }, - { &u_End[1], &yu_End[1], &o_End[1], &ie_End[1], &soft_End[1], &ya_End[1], &a_End[1], NULL }, - { &oj_End[1], &io_j_End[1], &ie_j_End[1], &o_m_End[1], &io_m_End[1], &ie_m_End[1], &yu_End[1], NULL }, - { &ie_End[1], &i_End[1], NULL, NULL, NULL, NULL, NULL, NULL } + { &a_End[1], &o_End[1], &ya_End[1], &ie_End[1], &soft_End[1], &j_End[1], nullptr, nullptr }, + { &a_End[1], &ya_End[1], &yeru_End[1], &i_End[1], nullptr, nullptr, nullptr, nullptr }, + { &ie_End[1], &u_End[1], &yu_End[1], &i_End[1], nullptr, nullptr, nullptr, nullptr }, + { &u_End[1], &yu_End[1], &o_End[1], &ie_End[1], &soft_End[1], &ya_End[1], &a_End[1], nullptr }, + { &oj_End[1], &io_j_End[1], &ie_j_End[1], &o_m_End[1], &io_m_End[1], &ie_m_End[1], &yu_End[1], nullptr }, + { &ie_End[1], &i_End[1], nullptr, nullptr, nullptr, nullptr, nullptr, nullptr } }; for (wchar_t const* const* itr = &dropEnds[declension][0]; *itr; ++itr) { size_t len = size_t((*itr)[-1]); // get length from string size field - if (wname.substr(wname.size()-len, len)==*itr) - return wname.substr(0, wname.size()-len); + if (wname.substr(wname.size() - len, len) == *itr) + return wname.substr(0, wname.size() - len); } return wname; @@ -552,13 +563,14 @@ void HexStrToByteArray(std::string const& str, uint8* out, bool reverse /*= fals for (int32 i = init; i != end; i += 2 * op) { char buffer[3] = { str[i], str[i + 1], '\0' }; - out[j++] = strtoul(buffer, NULL, 16); + out[j++] = strtoul(buffer, nullptr, 16); } } bool StringToBool(std::string const& str) { - std::string lowerStr = boost::algorithm::to_lower_copy(str); + std::string lowerStr = str; + std::transform(str.begin(), str.end(), lowerStr.begin(), ::tolower); return lowerStr == "1" || lowerStr == "true" || lowerStr == "yes"; } diff --git a/src/common/Utilities/Util.h b/src/common/Utilities/Util.h index 654e3b40181..9a2bd548172 100644 --- a/src/common/Utilities/Util.h +++ b/src/common/Utilities/Util.h @@ -21,25 +21,10 @@ #include "Define.h" #include "Errors.h" -#include "Random.h" -#include #include #include #include -#include -#include -#include - -// Searcher for map of structs -template struct Finder -{ - T val_; - T S::* idMember_; - - Finder(T val, T S::* idMember) : val_(val), idMember_(idMember) {} - bool operator()(const std::pair &obj) { return obj.second.*idMember_ == val_; } -}; class TC_COMMON_API Tokenizer { @@ -71,12 +56,12 @@ private: TC_COMMON_API void stripLineInvisibleChars(std::string &src); -TC_COMMON_API int64 MoneyStringToMoney(const std::string& moneyString); +TC_COMMON_API int64 MoneyStringToMoney(std::string const& moneyString); -TC_COMMON_API struct tm* localtime_r(const time_t* time, struct tm *result); +TC_COMMON_API struct tm* localtime_r(time_t const* time, struct tm *result); 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 uint32 TimeStringToSecs(std::string const& timestring); TC_COMMON_API std::string TimeToTimestampStr(time_t t); inline void ApplyPercentModFloatVar(float& var, float val, bool apply) @@ -296,15 +281,8 @@ inline wchar_t wcharToLower(wchar_t wchar) return wchar; } -inline void wstrToUpper(std::wstring& str) -{ - std::transform( str.begin(), str.end(), str.begin(), wcharToUpper ); -} - -inline void wstrToLower(std::wstring& str) -{ - std::transform( str.begin(), str.end(), str.begin(), wcharToLower ); -} +TC_COMMON_API void wstrToUpper(std::wstring& str); +TC_COMMON_API void wstrToLower(std::wstring& str); TC_COMMON_API std::wstring GetMainPartOfName(std::wstring const& wname, uint32 declension); @@ -406,7 +384,7 @@ public: part[2] = p3; } - inline bool operator <(const flag96 &right) const + inline bool operator<(flag96 const& right) const { for (uint8 i = 3; i > 0; --i) { @@ -418,7 +396,7 @@ public: return false; } - inline bool operator ==(const flag96 &right) const + inline bool operator==(flag96 const& right) const { return ( @@ -428,12 +406,12 @@ public: ); } - inline bool operator !=(const flag96 &right) const + inline bool operator!=(flag96 const& right) const { return !this->operator ==(right); } - inline flag96 & operator =(const flag96 &right) + inline flag96& operator=(flag96 const& right) { part[0] = right.part[0]; part[1] = right.part[1]; @@ -441,13 +419,13 @@ public: return *this; } - inline flag96 operator &(const flag96 &right) const + inline flag96 operator&(flag96 const& right) const { return flag96(part[0] & right.part[0], part[1] & right.part[1], part[2] & right.part[2]); } - inline flag96 & operator &=(const flag96 &right) + inline flag96& operator&=(flag96 const& right) { part[0] &= right.part[0]; part[1] &= right.part[1]; @@ -455,13 +433,13 @@ public: return *this; } - inline flag96 operator |(const flag96 &right) const + inline flag96 operator|(flag96 const& right) const { return flag96(part[0] | right.part[0], part[1] | right.part[1], part[2] | right.part[2]); } - inline flag96 & operator |=(const flag96 &right) + inline flag96& operator|=(flag96 const& right) { part[0] |= right.part[0]; part[1] |= right.part[1]; @@ -469,18 +447,18 @@ public: return *this; } - inline flag96 operator ~() const + inline flag96 operator~() const { return flag96(~part[0], ~part[1], ~part[2]); } - inline flag96 operator ^(const flag96 &right) const + inline flag96 operator^(flag96 const& right) const { return flag96(part[0] ^ right.part[0], part[1] ^ right.part[1], part[2] ^ right.part[2]); } - inline flag96 & operator ^=(const flag96 &right) + inline flag96 & operator^=(flag96 const& right) { part[0] ^= right.part[0]; part[1] ^= right.part[1]; @@ -493,17 +471,17 @@ public: return (part[0] != 0 || part[1] != 0 || part[2] != 0); } - inline bool operator !() const + inline bool operator!() const { - return !this->operator bool(); + return !(bool(*this)); } - inline uint32 & operator [](uint8 el) + inline uint32& operator[](uint8 el) { return part[el]; } - inline const uint32 & operator [](uint8 el) const + inline uint32 const& operator[](uint8 el) const { return part[el]; } diff --git a/src/server/CMakeLists.txt b/src/server/CMakeLists.txt index ed4be76a1a9..62ddaaa89b8 100644 --- a/src/server/CMakeLists.txt +++ b/src/server/CMakeLists.txt @@ -21,9 +21,7 @@ if(CMAKE_COMPILER_IS_GNUCXX AND NOT MINGW) endif() if(WIN32) - set(sources_windows - ${CMAKE_SOURCE_DIR}/src/common/Debugging/WheatyExceptionReport.cpp - ${CMAKE_SOURCE_DIR}/src/common/Debugging/WheatyExceptionReport.h + list(APPEND sources_windows ${CMAKE_SOURCE_DIR}/src/common/Platform/ServiceWin32.cpp ${CMAKE_SOURCE_DIR}/src/common/Platform/ServiceWin32.h ) diff --git a/src/server/authserver/Authentication/AuthCodes.cpp b/src/server/authserver/Authentication/AuthCodes.cpp index ea017bd0cb5..98d61ce2c4c 100644 --- a/src/server/authserver/Authentication/AuthCodes.cpp +++ b/src/server/authserver/Authentication/AuthCodes.cpp @@ -77,7 +77,7 @@ namespace AuthHelper if (PreBcAcceptedClientBuilds[i].Build == build) return &PreBcAcceptedClientBuilds[i]; - return NULL; + return nullptr; } bool IsBuildSupportingBattlenet(int build) diff --git a/src/server/authserver/Authentication/TOTP.cpp b/src/server/authserver/Authentication/TOTP.cpp index 2d7e39d35ac..76df2f653ec 100644 --- a/src/server/authserver/Authentication/TOTP.cpp +++ b/src/server/authserver/Authentication/TOTP.cpp @@ -18,7 +18,7 @@ #include "TOTP.h" #include -int base32_decode(const char* encoded, char* result, int bufSize) +int base32_decode(char const* encoded, char* result, int bufSize) { // Base32 implementation // Copyright 2010 Google Inc. @@ -68,7 +68,7 @@ int base32_decode(const char* encoded, char* result, int bufSize) namespace TOTP { - unsigned int GenerateToken(const char* b32key) + unsigned int GenerateToken(char const* b32key) { size_t keySize = strlen(b32key); int bufsize = (keySize + 7)/8*5; @@ -76,7 +76,7 @@ namespace TOTP memset(encoded, 0, bufsize); unsigned int hmacResSize = HMAC_RES_SIZE; unsigned char hmacRes[HMAC_RES_SIZE]; - unsigned long timestamp = time(NULL)/30; + unsigned long timestamp = time(nullptr)/30; unsigned char challenge[8]; for (int i = 8; i--;timestamp >>= 8) diff --git a/src/server/authserver/Authentication/TOTP.h b/src/server/authserver/Authentication/TOTP.h index d490fb44f51..2c274a222b1 100644 --- a/src/server/authserver/Authentication/TOTP.h +++ b/src/server/authserver/Authentication/TOTP.h @@ -23,7 +23,7 @@ namespace TOTP { - unsigned int GenerateToken(const char* b32key); + unsigned int GenerateToken(char const* b32key); } #endif diff --git a/src/server/authserver/CMakeLists.txt b/src/server/authserver/CMakeLists.txt index 9f16b6853ec..b56866ec0ee 100644 --- a/src/server/authserver/CMakeLists.txt +++ b/src/server/authserver/CMakeLists.txt @@ -25,10 +25,6 @@ endif() if (USE_COREPCH) set(PRIVATE_PCH_HEADER PrecompiledHeaders/authPCH.h) - set(PRIVATE_PCH_SOURCE PrecompiledHeaders/authPCH.cpp) - if (MSVC) - list(INSERT PRIVATE_SOURCES 0 PrecompiledHeaders/authPCH.cpp) - endif (MSVC) endif() GroupSources(${CMAKE_CURRENT_SOURCE_DIR}) @@ -44,6 +40,8 @@ if( NOT WIN32 ) endif() target_link_libraries(authserver + PRIVATE + trinity-core-interface PUBLIC shared) @@ -88,5 +86,5 @@ endif() # Generate precompiled header if (USE_COREPCH) - add_cxx_pch(authserver ${PRIVATE_PCH_HEADER} ${PRIVATE_PCH_SOURCE}) + add_cxx_pch(authserver ${PRIVATE_PCH_HEADER}) endif() diff --git a/src/server/authserver/Main.cpp b/src/server/authserver/Main.cpp index 2b0987e82fb..3417f522481 100644 --- a/src/server/authserver/Main.cpp +++ b/src/server/authserver/Main.cpp @@ -24,22 +24,25 @@ * authentication server */ +#include "AppenderDB.h" #include "AuthSocketMgr.h" -#include "Common.h" +#include "Banner.h" #include "Config.h" #include "DatabaseEnv.h" #include "DatabaseLoader.h" -#include "Log.h" -#include "AppenderDB.h" -#include "ProcessPriority.h" -#include "RealmList.h" #include "GitRevision.h" +#include "GruntRealmList.h" +#include "IoContext.h" +#include "MySQLThreading.h" +#include "ProcessPriority.h" #include "Util.h" -#include -#include +#include #include -#include +#include #include +#include +#include +#include using boost::asio::ip::tcp; using namespace boost::program_options; @@ -62,12 +65,12 @@ char serviceDescription[] = "TrinityCore World of Warcraft emulator auth service */ int m_ServiceStatus = -1; -void ServiceStatusWatcher(std::weak_ptr serviceStatusWatchTimerRef, std::weak_ptr ioServiceRef, boost::system::error_code const& error); +void ServiceStatusWatcher(std::weak_ptr serviceStatusWatchTimerRef, std::weak_ptr ioContextRef, boost::system::error_code const& error); #endif bool StartDB(); void StopDB(); -void SignalHandler(std::weak_ptr ioServiceRef, boost::system::error_code const& error, int signalNumber); +void SignalHandler(std::weak_ptr ioContextRef, boost::system::error_code const& error, int signalNumber); void KeepDatabaseAliveHandler(std::weak_ptr dbPingTimerRef, int32 dbPingInterval, boost::system::error_code const& error); void BanExpiryHandler(std::weak_ptr banExpiryCheckTimerRef, int32 banExpiryCheckInterval, boost::system::error_code const& error); variables_map GetConsoleArguments(int argc, char** argv, fs::path& configFile, std::string& configService); @@ -104,11 +107,18 @@ int main(int argc, char** argv) sLog->RegisterAppender(); sLog->Initialize(nullptr); - TC_LOG_INFO("server.authserver", "%s (authserver)", GitRevision::GetFullVersion()); - TC_LOG_INFO("server.authserver", " to stop.\n"); - 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); + Trinity::Banner::Show("authserver", + [](char const* text) + { + TC_LOG_INFO("server.authserver", "%s", text); + }, + []() + { + 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); + } + ); // authserver PID file creation std::string pidFile = sConfigMgr->GetStringDefault("PidFile", ""); @@ -129,14 +139,14 @@ int main(int argc, char** argv) std::shared_ptr dbHandle(nullptr, [](void*) { StopDB(); }); - std::shared_ptr ioService = std::make_shared(); + std::shared_ptr ioContext = std::make_shared(); // Get the list of realms for the server - sRealmList->Initialize(*ioService, sConfigMgr->GetIntDefault("RealmsStateUpdateDelay", 20)); + sGruntRealmList->Initialize(*ioContext, sConfigMgr->GetIntDefault("RealmsStateUpdateDelay", 20)); - std::shared_ptr sRealmListHandle(nullptr, [](void*) { sRealmList->Close(); }); + std::shared_ptr sRealmListHandle(nullptr, [](void*) { sGruntRealmList->Close(); }); - if (sRealmList->GetRealms().empty()) + if (sGruntRealmList->GetRealms().empty()) { TC_LOG_ERROR("server.authserver", "No valid realms specified."); return 1; @@ -152,7 +162,7 @@ int main(int argc, char** argv) std::string bindIp = sConfigMgr->GetStringDefault("BindIP", "0.0.0.0"); - if (!sAuthSocketMgr.StartNetwork(*ioService, bindIp, port)) + if (!sAuthSocketMgr.StartNetwork(*ioContext, bindIp, port)) { TC_LOG_ERROR("server.authserver", "Failed to initialize network"); return 1; @@ -161,23 +171,23 @@ int main(int argc, char** argv) std::shared_ptr sAuthSocketMgrHandle(nullptr, [](void*) { sAuthSocketMgr.StopNetwork(); }); // Set signal handlers - boost::asio::signal_set signals(*ioService, SIGINT, SIGTERM); + boost::asio::signal_set signals(*ioContext, SIGINT, SIGTERM); #if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS signals.add(SIGBREAK); #endif - signals.async_wait(std::bind(&SignalHandler, std::weak_ptr(ioService), std::placeholders::_1, std::placeholders::_2)); + signals.async_wait(std::bind(&SignalHandler, std::weak_ptr(ioContext), std::placeholders::_1, std::placeholders::_2)); // Set process priority according to configuration settings - SetProcessPriority("server.authserver"); + SetProcessPriority("server.authserver", sConfigMgr->GetIntDefault(CONFIG_PROCESSOR_AFFINITY, 0), sConfigMgr->GetBoolDefault(CONFIG_HIGH_PRIORITY, false)); // Enabled a timed callback for handling the database keep alive ping int32 dbPingInterval = sConfigMgr->GetIntDefault("MaxPingTime", 30); - std::shared_ptr dbPingTimer = std::make_shared(*ioService); + std::shared_ptr dbPingTimer = std::make_shared(*ioContext); dbPingTimer->expires_from_now(boost::posix_time::minutes(dbPingInterval)); dbPingTimer->async_wait(std::bind(&KeepDatabaseAliveHandler, std::weak_ptr(dbPingTimer), dbPingInterval, std::placeholders::_1)); int32 banExpiryCheckInterval = sConfigMgr->GetIntDefault("BanExpiryCheckInterval", 60); - std::shared_ptr banExpiryCheckTimer = std::make_shared(*ioService); + std::shared_ptr banExpiryCheckTimer = std::make_shared(*ioContext); banExpiryCheckTimer->expires_from_now(boost::posix_time::seconds(banExpiryCheckInterval)); banExpiryCheckTimer->async_wait(std::bind(&BanExpiryHandler, std::weak_ptr(banExpiryCheckTimer), banExpiryCheckInterval, std::placeholders::_1)); @@ -185,17 +195,17 @@ int main(int argc, char** argv) std::shared_ptr serviceStatusWatchTimer; if (m_ServiceStatus != -1) { - serviceStatusWatchTimer = std::make_shared(*ioService); + serviceStatusWatchTimer = std::make_shared(*ioContext); serviceStatusWatchTimer->expires_from_now(boost::posix_time::seconds(1)); serviceStatusWatchTimer->async_wait(std::bind(&ServiceStatusWatcher, std::weak_ptr(serviceStatusWatchTimer), - std::weak_ptr(ioService), + std::weak_ptr(ioContext), std::placeholders::_1)); } #endif // Start the io service worker loop - ioService->run(); + ioContext->run(); banExpiryCheckTimer->cancel(); dbPingTimer->cancel(); @@ -234,11 +244,11 @@ void StopDB() MySQL::Library_End(); } -void SignalHandler(std::weak_ptr ioServiceRef, boost::system::error_code const& error, int /*signalNumber*/) +void SignalHandler(std::weak_ptr ioContextRef, boost::system::error_code const& error, int /*signalNumber*/) { if (!error) - if (std::shared_ptr ioService = ioServiceRef.lock()) - ioService->stop(); + if (std::shared_ptr ioContext = ioContextRef.lock()) + ioContext->stop(); } void KeepDatabaseAliveHandler(std::weak_ptr dbPingTimerRef, int32 dbPingInterval, boost::system::error_code const& error) @@ -272,18 +282,18 @@ void BanExpiryHandler(std::weak_ptr banExpiryCheckT } #if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS -void ServiceStatusWatcher(std::weak_ptr serviceStatusWatchTimerRef, std::weak_ptr ioServiceRef, boost::system::error_code const& error) +void ServiceStatusWatcher(std::weak_ptr serviceStatusWatchTimerRef, std::weak_ptr ioContextRef, boost::system::error_code const& error) { if (!error) { - if (std::shared_ptr ioService = ioServiceRef.lock()) + if (std::shared_ptr ioContext = ioContextRef.lock()) { if (m_ServiceStatus == 0) - ioService->stop(); + ioContext->stop(); else if (std::shared_ptr serviceStatusWatchTimer = serviceStatusWatchTimerRef.lock()) { serviceStatusWatchTimer->expires_from_now(boost::posix_time::seconds(1)); - serviceStatusWatchTimer->async_wait(std::bind(&ServiceStatusWatcher, serviceStatusWatchTimerRef, ioServiceRef, std::placeholders::_1)); + serviceStatusWatchTimer->async_wait(std::bind(&ServiceStatusWatcher, serviceStatusWatchTimerRef, ioContextRef, std::placeholders::_1)); } } } diff --git a/src/server/authserver/PrecompiledHeaders/authPCH.cpp b/src/server/authserver/PrecompiledHeaders/authPCH.cpp deleted file mode 100644 index eed50cb2c0b..00000000000 --- a/src/server/authserver/PrecompiledHeaders/authPCH.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "authPCH.h" diff --git a/src/server/authserver/PrecompiledHeaders/authPCH.h b/src/server/authserver/PrecompiledHeaders/authPCH.h index 90424161344..b2be78a8a37 100644 --- a/src/server/authserver/PrecompiledHeaders/authPCH.h +++ b/src/server/authserver/PrecompiledHeaders/authPCH.h @@ -1,7 +1,23 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + #include "Common.h" #include "Configuration/Config.h" #include "Database/DatabaseEnv.h" #include "Log.h" -#include "RealmList.h" -#include "ByteBuffer.h" +#include "GruntRealmList.h" #include "AuthSession.h" diff --git a/src/server/shared/Realm/RealmList.cpp b/src/server/authserver/Realms/GruntRealmList.cpp similarity index 54% rename from src/server/shared/Realm/RealmList.cpp rename to src/server/authserver/Realms/GruntRealmList.cpp index 1f8f021b19f..0dff0a93f3e 100644 --- a/src/server/shared/Realm/RealmList.cpp +++ b/src/server/authserver/Realms/GruntRealmList.cpp @@ -16,48 +16,56 @@ * with this program. If not, see . */ -#include "RealmList.h" -#include "Database/DatabaseEnv.h" +#include "GruntRealmList.h" +#include "DatabaseEnv.h" +#include "IoContext.h" +#include "Log.h" +#include "Resolver.h" #include "Util.h" +#include +#include -RealmList::RealmList() : _updateInterval(0), _updateTimer(nullptr), _resolver(nullptr) +GruntRealmList::GruntRealmList() : _updateInterval(0) { } -RealmList::~RealmList() +GruntRealmList::~GruntRealmList() { - delete _updateTimer; } -RealmList* RealmList::Instance() +GruntRealmList* GruntRealmList::Instance() { - static RealmList instance; + static GruntRealmList instance; return &instance; } // Load the realm list from the database -void RealmList::Initialize(boost::asio::io_service& ioService, uint32 updateInterval) +void GruntRealmList::Initialize(Trinity::Asio::IoContext& ioContext, uint32 updateInterval) { _updateInterval = updateInterval; - _updateTimer = new boost::asio::deadline_timer(ioService); - _resolver = new boost::asio::ip::tcp::resolver(ioService); + _updateTimer = Trinity::make_unique(ioContext); + _resolver = Trinity::make_unique(ioContext); // Get the content of the realmlist table in the database UpdateRealms(boost::system::error_code()); } -void RealmList::Close() +void GruntRealmList::Close() { _updateTimer->cancel(); } -void RealmList::UpdateRealm(Battlenet::RealmHandle const& id, uint32 build, const std::string& name, boost::asio::ip::address const& address, boost::asio::ip::address const& localAddr, - boost::asio::ip::address const& localSubmask, uint16 port, uint8 icon, RealmFlags flag, uint8 timezone, AccountTypes allowedSecurityLevel, - float population) +void GruntRealmList::UpdateRealm(Battlenet::RealmHandle const& id, uint32 build, std::string const& name, + boost::asio::ip::address&& address, boost::asio::ip::address&& localAddr, boost::asio::ip::address&& 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]; + // grunt server doesn't use these values, but keep them initialized + realm.Updated = false; + realm.Keep = true; + realm.Id = id; realm.Build = build; realm.Name = name; @@ -66,13 +74,16 @@ void RealmList::UpdateRealm(Battlenet::RealmHandle const& id, uint32 build, cons realm.Timezone = timezone; realm.AllowedSecurityLevel = allowedSecurityLevel; realm.PopulationLevel = population; - realm.ExternalAddress = address; - realm.LocalAddress = localAddr; - realm.LocalSubnetMask = localSubmask; + if (!realm.ExternalAddress || *realm.ExternalAddress != address) + realm.ExternalAddress = Trinity::make_unique(std::move(address)); + if (!realm.LocalAddress || *realm.LocalAddress != localAddr) + realm.LocalAddress = Trinity::make_unique(std::move(localAddr)); + if (!realm.LocalSubnetMask || *realm.LocalSubnetMask != localSubmask) + realm.LocalSubnetMask = Trinity::make_unique(std::move(localSubmask)); realm.Port = port; } -void RealmList::UpdateRealms(boost::system::error_code const& error) +void GruntRealmList::UpdateRealms(boost::system::error_code const& error) { if (error) return; @@ -95,43 +106,34 @@ void RealmList::UpdateRealms(boost::system::error_code const& error) { try { - boost::asio::ip::tcp::resolver::iterator end; - Field* fields = result->Fetch(); uint32 realmId = fields[0].GetUInt32(); std::string name = fields[1].GetString(); - boost::asio::ip::tcp::resolver::query externalAddressQuery(boost::asio::ip::tcp::v4(), fields[2].GetString(), ""); + std::string externalAddressString = fields[2].GetString(); + std::string localAddressString = fields[3].GetString(); + std::string localSubmaskString = fields[4].GetString(); - boost::system::error_code ec; - boost::asio::ip::tcp::resolver::iterator endPoint = _resolver->resolve(externalAddressQuery, ec); - if (endPoint == end || ec) + Optional externalAddress = Trinity::Net::Resolve(*_resolver, boost::asio::ip::tcp::v4(), externalAddressString, ""); + if (!externalAddress) { - TC_LOG_ERROR("server.authserver", "Could not resolve address %s for realm \"%s\" id %u", fields[2].GetString().c_str(), name.c_str(), realmId); + TC_LOG_ERROR("realmlist", "Could not resolve address %s", externalAddressString.c_str()); continue; } - boost::asio::ip::address externalAddress = (*endPoint).endpoint().address(); - - boost::asio::ip::tcp::resolver::query localAddressQuery(boost::asio::ip::tcp::v4(), fields[3].GetString(), ""); - endPoint = _resolver->resolve(localAddressQuery, ec); - if (endPoint == end || ec) + Optional localAddress = Trinity::Net::Resolve(*_resolver, boost::asio::ip::tcp::v4(), localAddressString, ""); + if (!localAddress) { - TC_LOG_ERROR("server.authserver", "Could not resolve localAddress %s for realm \"%s\" id %u", fields[3].GetString().c_str(), name.c_str(), realmId); + TC_LOG_ERROR("realmlist", "Could not resolve address %s", localAddressString.c_str()); continue; } - boost::asio::ip::address localAddress = (*endPoint).endpoint().address(); - - boost::asio::ip::tcp::resolver::query localSubmaskQuery(boost::asio::ip::tcp::v4(), fields[4].GetString(), ""); - endPoint = _resolver->resolve(localSubmaskQuery, ec); - if (endPoint == end || ec) + Optional localSubmask = Trinity::Net::Resolve(*_resolver, boost::asio::ip::tcp::v4(), localSubmaskString, ""); + if (!localSubmask) { - TC_LOG_ERROR("server.authserver", "Could not resolve localSubnetMask %s for realm \"%s\" id %u", fields[4].GetString().c_str(), name.c_str(), realmId); + TC_LOG_ERROR("realmlist", "Could not resolve address %s", localSubmaskString.c_str()); continue; } - boost::asio::ip::address localSubmask = (*endPoint).endpoint().address(); - uint16 port = fields[5].GetUInt16(); uint8 icon = fields[6].GetUInt8(); if (icon == REALM_TYPE_FFA_PVP) @@ -148,19 +150,19 @@ void RealmList::UpdateRealms(boost::system::error_code const& error) Battlenet::RealmHandle id{ region, battlegroup, realmId }; - UpdateRealm(id, build, name, externalAddress, localAddress, localSubmask, port, icon, flag, + UpdateRealm(id, build, name, externalAddress->address(), localAddress->address(), localSubmask->address(), 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); + TC_LOG_INFO("server.authserver", "Added realm \"%s\" at %s:%u.", name.c_str(), externalAddressString.c_str(), port); else - TC_LOG_DEBUG("server.authserver", "Updating realm \"%s\" at %s:%u.", name.c_str(), externalAddress.to_string().c_str(), port); + TC_LOG_DEBUG("server.authserver", "Updating realm \"%s\" at %s:%u.", name.c_str(), externalAddressString.c_str(), port); existingRealms.erase(id); } catch (std::exception& ex) { - TC_LOG_ERROR("server.authserver", "Realmlist::UpdateRealms has thrown an exception: %s", ex.what()); + TC_LOG_ERROR("server.authserver", "GruntRealmList::UpdateRealms has thrown an exception: %s", ex.what()); ABORT(); } } @@ -173,15 +175,15 @@ void RealmList::UpdateRealms(boost::system::error_code const& error) if (_updateInterval) { _updateTimer->expires_from_now(boost::posix_time::seconds(_updateInterval)); - _updateTimer->async_wait(std::bind(&RealmList::UpdateRealms, this, std::placeholders::_1)); + _updateTimer->async_wait(std::bind(&GruntRealmList::UpdateRealms, this, std::placeholders::_1)); } } -Realm const* RealmList::GetRealm(Battlenet::RealmHandle const& id) const +Realm const* GruntRealmList::GetRealm(Battlenet::RealmHandle const& id) const { auto itr = _realms.find(id); if (itr != _realms.end()) return &itr->second; - return NULL; + return nullptr; } diff --git a/src/server/authserver/Realms/GruntRealmList.h b/src/server/authserver/Realms/GruntRealmList.h new file mode 100644 index 00000000000..06211235129 --- /dev/null +++ b/src/server/authserver/Realms/GruntRealmList.h @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * Copyright (C) 2005-2009 MaNGOS + * + * 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 . + */ + +#ifndef GruntRealmList_h__ +#define GruntRealmList_h__ + +#include "Define.h" +#include "Realm.h" +#include +#include +#include + +namespace boost +{ + namespace system + { + class error_code; + } +} + +namespace Trinity +{ + namespace Asio + { + class IoContext; + } +} + +/// Storage object for the list of realms on the server +class GruntRealmList +{ + public: + typedef std::map RealmMap; + + static GruntRealmList* Instance(); + + ~GruntRealmList(); + + void Initialize(Trinity::Asio::IoContext& ioContext, uint32 updateInterval); + void Close(); + + RealmMap const& GetRealms() const { return _realms; } + Realm const* GetRealm(Battlenet::RealmHandle const& id) const; + + private: + GruntRealmList(); + + void UpdateRealms(boost::system::error_code const& error); + void UpdateRealm(Battlenet::RealmHandle const& id, uint32 build, std::string const& name, + boost::asio::ip::address&& address, boost::asio::ip::address&& localAddr, boost::asio::ip::address&& localSubmask, + uint16 port, uint8 icon, RealmFlags flag, uint8 timezone, AccountTypes allowedSecurityLevel, float population); + + RealmMap _realms; + uint32 _updateInterval; + std::unique_ptr _updateTimer; + std::unique_ptr _resolver; +}; + +#define sGruntRealmList GruntRealmList::Instance() + +#endif // GruntRealmList_h__ diff --git a/src/server/authserver/Server/AuthSession.cpp b/src/server/authserver/Server/AuthSession.cpp index d308bd432d4..1ebfaa50372 100644 --- a/src/server/authserver/Server/AuthSession.cpp +++ b/src/server/authserver/Server/AuthSession.cpp @@ -17,16 +17,19 @@ */ #include "AuthSession.h" -#include "Log.h" #include "AuthCodes.h" -#include "Database/DatabaseEnv.h" -#include "QueryCallback.h" +#include "ByteBuffer.h" +#include "Config.h" +#include "DatabaseEnv.h" +#include "Errors.h" +#include "GruntRealmList.h" +#include "Log.h" +#include "Realm.h" #include "SHA1.h" #include "TOTP.h" -#include "openssl/crypto.h" -#include "Configuration/Config.h" -#include "RealmList.h" +#include "Util.h" #include +#include using boost::asio::ip::tcp; @@ -285,7 +288,7 @@ bool AuthSession::HandleLogonChallenge() if (challenge->size - (sizeof(sAuthLogonChallenge_C) - AUTH_LOGON_CHALLENGE_INITIAL_SIZE - 1) != challenge->I_len) return false; - std::string login((const char*)challenge->I, challenge->I_len); + std::string login((char const*)challenge->I, challenge->I_len); TC_LOG_DEBUG("server.authserver", "[AuthChallenge] '%s'", login.c_str()); _build = challenge->build; @@ -483,7 +486,7 @@ bool AuthSession::HandleLogonProof() return false; SHA1Hash sha; - sha.UpdateBigNumbers(&A, &B, NULL); + sha.UpdateBigNumbers(&A, &B, nullptr); sha.Finalize(); BigNumber u; u.SetBinary(sha.GetDigest(), 20); @@ -519,11 +522,11 @@ bool AuthSession::HandleLogonProof() uint8 hash[20]; sha.Initialize(); - sha.UpdateBigNumbers(&N, NULL); + sha.UpdateBigNumbers(&N, nullptr); sha.Finalize(); memcpy(hash, sha.GetDigest(), 20); sha.Initialize(); - sha.UpdateBigNumbers(&g, NULL); + sha.UpdateBigNumbers(&g, nullptr); sha.Finalize(); for (int i = 0; i < 20; ++i) @@ -539,9 +542,9 @@ bool AuthSession::HandleLogonProof() memcpy(t4, sha.GetDigest(), SHA_DIGEST_LENGTH); sha.Initialize(); - sha.UpdateBigNumbers(&t3, NULL); + sha.UpdateBigNumbers(&t3, nullptr); sha.UpdateData(t4, SHA_DIGEST_LENGTH); - sha.UpdateBigNumbers(&s, &A, &B, &K, NULL); + sha.UpdateBigNumbers(&s, &A, &B, &K, nullptr); sha.Finalize(); BigNumber M; M.SetBinary(sha.GetDigest(), sha.GetLength()); @@ -585,7 +588,7 @@ bool AuthSession::HandleLogonProof() // Finish SRP6 and send the final result to the client sha.Initialize(); - sha.UpdateBigNumbers(&A, &M, &K, NULL); + sha.UpdateBigNumbers(&A, &M, &K, nullptr); sha.Finalize(); ByteBuffer packet; @@ -689,7 +692,7 @@ bool AuthSession::HandleReconnectChallenge() if (challenge->size - (sizeof(sAuthLogonChallenge_C) - AUTH_LOGON_CHALLENGE_INITIAL_SIZE - 1) != challenge->I_len) return false; - std::string login((const char*)challenge->I, challenge->I_len); + std::string login((char const*)challenge->I, challenge->I_len); TC_LOG_DEBUG("server.authserver", "[ReconnectChallenge] '%s'", login.c_str()); _build = challenge->build; @@ -756,7 +759,7 @@ bool AuthSession::HandleReconnectProof() SHA1Hash sha; sha.Initialize(); sha.UpdateData(_accountInfo.Login); - sha.UpdateBigNumbers(&t1, &_reconnectProof, &K, NULL); + sha.UpdateBigNumbers(&t1, &_reconnectProof, &K, nullptr); sha.Finalize(); if (!memcmp(sha.GetDigest(), reconnectProof->R2, SHA_DIGEST_LENGTH)) @@ -806,9 +809,9 @@ void AuthSession::RealmListCallback(PreparedQueryResult result) ByteBuffer pkt; size_t RealmListSize = 0; - for (RealmList::RealmMap::value_type const& i : sRealmList->GetRealms()) + for (auto const& i : sGruntRealmList->GetRealms()) { - const Realm &realm = i.second; + Realm const& realm = i.second; // don't work with realms which not compatible with the client bool okBuild = ((_expversion & POST_BC_EXP_FLAG) && realm.Build == _build) || ((_expversion & PRE_BC_EXP_FLAG) && !AuthHelper::IsPreBCAcceptedClientBuild(realm.Build)); diff --git a/src/server/authserver/Server/AuthSession.h b/src/server/authserver/Server/AuthSession.h index d3c199cac0b..12ce0ea9fcb 100644 --- a/src/server/authserver/Server/AuthSession.h +++ b/src/server/authserver/Server/AuthSession.h @@ -20,16 +20,16 @@ #define __AUTHSESSION_H__ #include "Common.h" -#include "ByteBuffer.h" -#include "Socket.h" #include "BigNumber.h" -#include "QueryResult.h" +#include "DatabaseEnvFwd.h" #include "QueryCallbackProcessor.h" -#include +#include "Socket.h" #include +#include using boost::asio::ip::tcp; +class ByteBuffer; class Field; struct AuthHandler; diff --git a/src/server/authserver/Server/AuthSocketMgr.h b/src/server/authserver/Server/AuthSocketMgr.h index 781fb09e5c8..04d65d396b0 100644 --- a/src/server/authserver/Server/AuthSocketMgr.h +++ b/src/server/authserver/Server/AuthSocketMgr.h @@ -32,9 +32,9 @@ public: return instance; } - bool StartNetwork(boost::asio::io_service& service, std::string const& bindIp, uint16 port, int threadCount = 1) override + bool StartNetwork(Trinity::Asio::IoContext& ioContext, std::string const& bindIp, uint16 port, int threadCount = 1) override { - if (!BaseSocketMgr::StartNetwork(service, bindIp, port, threadCount)) + if (!BaseSocketMgr::StartNetwork(ioContext, bindIp, port, threadCount)) return false; _acceptor->AsyncAcceptWithCallback<&AuthSocketMgr::OnSocketAccept>(); diff --git a/src/server/bnetserver/CMakeLists.txt b/src/server/bnetserver/CMakeLists.txt index 8317f5e084d..89f18077261 100644 --- a/src/server/bnetserver/CMakeLists.txt +++ b/src/server/bnetserver/CMakeLists.txt @@ -10,106 +10,66 @@ ########### bnetserver ############### -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_RECURSE sources_packets Packets/*.cpp Packets/*.h) -file(GLOB sources_localdir *.cpp *.h) +CollectSourceFiles( + ${CMAKE_CURRENT_SOURCE_DIR} + PRIVATE_SOURCES + # Exclude + ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders) + +if (WIN32) + list(APPEND PRIVATE_SOURCES ${sources_windows}) + if (MSVC) + list(APPEND PRIVATE_SOURCES bnetserver.rc) + endif() +endif() if (USE_COREPCH) - set(bnetserver_PCH_HDR PrecompiledHeaders/bnetPCH.h) - set(bnetserver_PCH_SRC PrecompiledHeaders/bnetPCH.cpp) + set(PRIVATE_PCH_HEADER PrecompiledHeaders/bnetPCH.h) endif() -set(bnetserver_SRCS - ${bnetserver_SRCS} - ${sources_authentication} - ${sources_realms} - ${sources_server} - ${sources_packets} - ${sources_localdir} -) - -if( WIN32 ) - set(bnetserver_SRCS - ${bnetserver_SRCS} - ${sources_windows} - ) - if ( MSVC ) - set(bnetserver_SRCS - ${bnetserver_SRCS} - bnetserver.rc - ) - endif () -endif() - -include_directories( - ${CMAKE_BINARY_DIR} - ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_SOURCE_DIR}/Authentication - ${CMAKE_CURRENT_SOURCE_DIR}/Packets - ${CMAKE_CURRENT_SOURCE_DIR}/Realms - ${CMAKE_CURRENT_SOURCE_DIR}/Server - ${CMAKE_SOURCE_DIR}/dep/fmt - ${CMAKE_SOURCE_DIR}/dep/libzmq - ${CMAKE_SOURCE_DIR}/dep/zmqpp - ${CMAKE_SOURCE_DIR}/src/common - ${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/common/Platform - ${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/database/Updater - ${CMAKE_SOURCE_DIR}/src/server/ipc - ${CMAKE_SOURCE_DIR}/src/server/shared - ${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} -) - GroupSources(${CMAKE_CURRENT_SOURCE_DIR}) add_executable(bnetserver - ${bnetserver_SRCS} - ${bnetserver_PCH_SRC} + ${PRIVATE_SOURCES} ) -if( NOT WIN32 ) +if (NOT WIN32) set_target_properties(bnetserver PROPERTIES COMPILE_DEFINITIONS _TRINITY_BNET_CONFIG="${CONF_DIR}/bnetserver.conf" ) endif() target_link_libraries(bnetserver - shared - database - ipc - common - zmqpp - fmt - libzmq - ${MYSQL_LIBRARY} - ${OPENSSL_LIBRARIES} - ${CMAKE_THREAD_LIBS_INIT} - ${Boost_LIBRARIES} -) + PRIVATE + trinity-core-interface + PUBLIC + shared + ipc) -if( WIN32 ) - if ( MSVC ) +CollectIncludeDirectories( + ${CMAKE_CURRENT_SOURCE_DIR} + PUBLIC_INCLUDES + # Exclude + ${CMAKE_CURRENT_SOURCE_DIR}/PrecompiledHeaders) + +target_include_directories(bnetserver + PUBLIC + ${PUBLIC_INCLUDES} + PRIVATE + ${CMAKE_CURRENT_BINARY_DIR}) + +set_target_properties(bnetserver + PROPERTIES + FOLDER + "server") + +if (WIN32) + if ("${CMAKE_MAKE_PROGRAM}" MATCHES "MSBuild") add_custom_command(TARGET bnetserver POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/bnetserver.conf.dist ${CMAKE_BINARY_DIR}/bin/$(ConfigurationName)/ ) - elseif ( MINGW ) + elseif (MINGW) add_custom_command(TARGET bnetserver POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/bnetserver.conf.dist ${CMAKE_BINARY_DIR}/bin/ @@ -117,15 +77,15 @@ if( WIN32 ) endif() endif() -if( UNIX ) +if (UNIX) install(TARGETS bnetserver DESTINATION bin) - install(FILES bnetserver.conf.dist DESTINATION ${CONF_DIR}) -elseif( WIN32 ) + install(FILES bnetserver.conf.dist DESTINATION ${CONF_DIR}) +elseif (WIN32) install(TARGETS bnetserver DESTINATION "${CMAKE_INSTALL_PREFIX}") install(FILES bnetserver.conf.dist DESTINATION "${CMAKE_INSTALL_PREFIX}") endif() # Generate precompiled header if (USE_COREPCH) - add_cxx_pch(bnetserver ${bnetserver_PCH_HDR} ${bnetserver_PCH_SRC}) + add_cxx_pch(bnetserver ${PRIVATE_PCH_HEADER}) endif() diff --git a/src/server/bnetserver/Main.cpp b/src/server/bnetserver/Main.cpp index b9e029438b3..339f0b907c1 100644 --- a/src/server/bnetserver/Main.cpp +++ b/src/server/bnetserver/Main.cpp @@ -24,26 +24,29 @@ * authentication server */ +#include "AppenderDB.h" +#include "Banner.h" +#include "BNetRealmList.h" #include "ComponentManager.h" -#include "ModuleManager.h" -#include "SessionManager.h" -#include "Common.h" #include "Config.h" #include "DatabaseEnv.h" -#include "Log.h" +#include "DatabaseLoader.h" +#include "IoContext.h" +#include "MySQLThreading.h" +#include "ModuleManager.h" #include "ProcessPriority.h" -#include "RealmList.h" -#include "GitRevision.h" +#include "SessionManager.h" #include "Util.h" #include "ZmqContext.h" -#include "DatabaseLoader.h" -#include -#include -#include -#include +#include #include -#include -#include +#include +#include +#include + +#ifdef _WIN32 // ugly as hell +#pragma comment(lib, "iphlpapi.lib") +#endif using boost::asio::ip::tcp; using namespace boost::program_options; @@ -66,28 +69,35 @@ char serviceDescription[] = "TrinityCore Battle.net emulator authentication serv */ int m_ServiceStatus = -1; -static boost::asio::deadline_timer* _serviceStatusWatchTimer; -void ServiceStatusWatcher(boost::system::error_code const& error); +void ServiceStatusWatcher(std::weak_ptr serviceStatusWatchTimerRef, std::weak_ptr ioContextRef, boost::system::error_code const& error); #endif 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, fs::path& configFile); - -boost::asio::io_service _ioService; -boost::asio::deadline_timer _dbPingTimer(_ioService); -uint32 _dbPingInterval; +void SignalHandler(std::weak_ptr ioContextRef, boost::system::error_code const& error, int signalNumber); +void KeepDatabaseAliveHandler(std::weak_ptr dbPingTimerRef, int32 dbPingInterval, boost::system::error_code const& error); +variables_map GetConsoleArguments(int argc, char** argv, fs::path& configFile, std::string& configService); int main(int argc, char** argv) { + signal(SIGABRT, &Trinity::AbortHandler); + auto configFile = fs::absolute(_TRINITY_BNET_CONFIG); - auto vm = GetConsoleArguments(argc, argv, configFile); + std::string configService; + auto vm = GetConsoleArguments(argc, argv, configFile, configService); // exit if help is enabled if (vm.count("help")) return 0; +#if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS + if (configService.compare("install") == 0) + return WinServiceInstall() ? 0 : 1; + else if (configService.compare("uninstall") == 0) + return WinServiceUninstall() ? 0 : 1; + else if (configService.compare("run") == 0) + return WinServiceRun() ? 0 : 1; +#endif + std::string configError; if (!sConfigMgr->LoadInitial(configFile.generic_string(), std::vector(argv, argv + argc), @@ -97,11 +107,26 @@ int main(int argc, char** argv) return 1; } - TC_LOG_INFO("server.bnetserver", "%s (bnetserver)", GitRevision::GetFullVersion()); - TC_LOG_INFO("server.bnetserver", " to stop.\n"); - TC_LOG_INFO("server.bnetserver", "Using configuration file %s.", sConfigMgr->GetFilename().c_str()); - TC_LOG_INFO("server.bnetserver", "Using SSL version: %s (library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION)); - TC_LOG_INFO("server.bnetserver", "Using Boost version: %i.%i.%i", BOOST_VERSION / 100000, BOOST_VERSION / 100 % 1000, BOOST_VERSION % 100); + sLog->RegisterAppender(); + sLog->Initialize(nullptr); + + Trinity::Banner::Show("bnetserver", + [](char const* text) + { + TC_LOG_INFO("server.bnetserver", "%s", text); + }, + []() + { + TC_LOG_INFO("server.bnetserver", "Using configuration file %s.", sConfigMgr->GetFilename().c_str()); + TC_LOG_INFO("server.bnetserver", "Using SSL version: %s (library: %s)", OPENSSL_VERSION_TEXT, SSLeay_version(SSLEAY_VERSION)); + TC_LOG_INFO("server.bnetserver", "Using Boost version: %i.%i.%i", BOOST_VERSION / 100000, BOOST_VERSION / 100 % 1000, BOOST_VERSION % 100); + } + ); + + // Seed the OpenSSL's PRNG here. + // That way it won't auto-seed when calling BigNumber::SetRand and slow down the first world login + BigNumber seed; + seed.SetRand(16 * 8); // bnetserver PID file creation std::string pidFile = sConfigMgr->GetStringDefault("PidFile", ""); @@ -127,53 +152,77 @@ int main(int argc, char** argv) if (!StartDB()) return 1; - sIpcContext->Initialize(); + std::shared_ptr dbHandle(nullptr, [](void*) { StopDB(); }); - // Get the list of realms for the server - sRealmList->Initialize(_ioService, sConfigMgr->GetIntDefault("RealmsStateUpdateDelay", 10), worldListenPort); + sIpcContext->Initialize(); + std::shared_ptr ipcHandle(nullptr, [](void*) { sIpcContext->Close(); }); + + std::shared_ptr ioContext = std::make_unique(); // Start the listening port (acceptor) for auth connections int32 bnport = sConfigMgr->GetIntDefault("BattlenetPort", 1119); if (bnport < 0 || bnport > 0xFFFF) { TC_LOG_ERROR("server.bnetserver", "Specified battle.net port (%d) out of allowed range (1-65535)", bnport); - StopDB(); return 1; } + // Get the list of realms for the server + sBNetRealmList->Initialize(*ioContext, sConfigMgr->GetIntDefault("RealmsStateUpdateDelay", 10), worldListenPort); + + std::shared_ptr sBNetRealmListHandle(nullptr, [](void*) { sBNetRealmList->Close(); }); + std::string bindIp = sConfigMgr->GetStringDefault("BindIP", "0.0.0.0"); - sSessionMgr.StartNetwork(_ioService, bindIp, bnport); + if (!sSessionMgr.StartNetwork(*ioContext, bindIp, bnport)) + { + TC_LOG_ERROR("server.bnetserver", "Failed to initialize network"); + return 1; + } + + std::shared_ptr sSessionMgrHandle(nullptr, [](void*) { sSessionMgr.StopNetwork(); }); // Set signal handlers - boost::asio::signal_set signals(_ioService, SIGINT, SIGTERM); + boost::asio::signal_set signals(*ioContext, SIGINT, SIGTERM); #if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS signals.add(SIGBREAK); #endif - signals.async_wait(SignalHandler); + signals.async_wait(std::bind(&SignalHandler, std::weak_ptr(ioContext), std::placeholders::_1, std::placeholders::_2)); // Set process priority according to configuration settings - SetProcessPriority("server.bnetserver"); + SetProcessPriority("server.bnetserver", sConfigMgr->GetIntDefault(CONFIG_PROCESSOR_AFFINITY, 0), sConfigMgr->GetBoolDefault(CONFIG_HIGH_PRIORITY, false)); // Enabled a timed callback for handling the database keep alive ping - _dbPingInterval = sConfigMgr->GetIntDefault("MaxPingTime", 30); - _dbPingTimer.expires_from_now(boost::posix_time::minutes(_dbPingInterval)); - _dbPingTimer.async_wait(KeepDatabaseAliveHandler); + int32 dbPingInterval = sConfigMgr->GetIntDefault("MaxPingTime", 30); + std::shared_ptr dbPingTimer = std::make_shared(*ioContext); + dbPingTimer->expires_from_now(boost::posix_time::minutes(dbPingInterval)); + dbPingTimer->async_wait(std::bind(&KeepDatabaseAliveHandler, std::weak_ptr(dbPingTimer), dbPingInterval, std::placeholders::_1)); + +#if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS + std::shared_ptr serviceStatusWatchTimer; + if (m_ServiceStatus != -1) + { + serviceStatusWatchTimer = std::make_shared(*ioContext); + serviceStatusWatchTimer->expires_from_now(boost::posix_time::seconds(1)); + serviceStatusWatchTimer->async_wait(std::bind(&ServiceStatusWatcher, + std::weak_ptr(serviceStatusWatchTimer), + std::weak_ptr(ioContext), + std::placeholders::_1)); + } +#endif sComponentMgr->Load(); sModuleMgr->Load(); // Start the io service worker loop - _ioService.run(); + ioContext->run(); - sIpcContext->Close(); - - sRealmList->Close(); - - // Close the Database Pool and library - StopDB(); + dbPingTimer->cancel(); TC_LOG_INFO("server.bnetserver", "Halting process..."); + + signals.cancel(); + return 0; } @@ -203,32 +252,67 @@ void StopDB() MySQL::Library_End(); } -void SignalHandler(const boost::system::error_code& error, int /*signalNumber*/) +void SignalHandler(std::weak_ptr ioContextRef, boost::system::error_code const& error, int /*signalNumber*/) { if (!error) - _ioService.stop(); + if (std::shared_ptr ioContext = ioContextRef.lock()) + ioContext->stop(); } -void KeepDatabaseAliveHandler(const boost::system::error_code& error) +void KeepDatabaseAliveHandler(std::weak_ptr dbPingTimerRef, int32 dbPingInterval, boost::system::error_code const& error) { if (!error) { - TC_LOG_INFO("server.bnetserver", "Ping MySQL to keep connection alive"); - LoginDatabase.KeepAlive(); + if (std::shared_ptr dbPingTimer = dbPingTimerRef.lock()) + { + TC_LOG_INFO("server.bnetserver", "Ping MySQL to keep connection alive"); + LoginDatabase.KeepAlive(); - _dbPingTimer.expires_from_now(boost::posix_time::minutes(_dbPingInterval)); - _dbPingTimer.async_wait(KeepDatabaseAliveHandler); + dbPingTimer->expires_from_now(boost::posix_time::minutes(dbPingInterval)); + dbPingTimer->async_wait(std::bind(&KeepDatabaseAliveHandler, dbPingTimerRef, dbPingInterval, std::placeholders::_1)); + } } } -variables_map GetConsoleArguments(int argc, char** argv, fs::path& configFile) +#if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS +void ServiceStatusWatcher(std::weak_ptr serviceStatusWatchTimerRef, std::weak_ptr ioContextRef, boost::system::error_code const& error) { + if (!error) + { + if (std::shared_ptr ioContext = ioContextRef.lock()) + { + if (m_ServiceStatus == 0) + { + ioContext->stop(); + } + else if (std::shared_ptr serviceStatusWatchTimer = serviceStatusWatchTimerRef.lock()) + { + serviceStatusWatchTimer->expires_from_now(boost::posix_time::seconds(1)); + serviceStatusWatchTimer->async_wait(std::bind(&ServiceStatusWatcher, serviceStatusWatchTimerRef, ioContext, std::placeholders::_1)); + } + } + } +} +#endif + +variables_map GetConsoleArguments(int argc, char** argv, fs::path& configFile, std::string& configService) +{ + (void)configService; + options_description all("Allowed options"); all.add_options() ("help,h", "print usage message") ("config,c", value(&configFile)->default_value(fs::absolute(_TRINITY_BNET_CONFIG)), "use as configuration file") ; +#if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS + options_description win("Windows platform specific options"); + win.add_options() + ("service,s", value(&configService)->default_value(""), "Windows service options: [install | uninstall]") + ; + + all.add(win); +#endif variables_map variablesMap; try { diff --git a/src/server/bnetserver/Packets/AuthenticationPackets.cpp b/src/server/bnetserver/Packets/AuthenticationPackets.cpp index 777bd4afbcc..a298686792d 100644 --- a/src/server/bnetserver/Packets/AuthenticationPackets.cpp +++ b/src/server/bnetserver/Packets/AuthenticationPackets.cpp @@ -182,7 +182,7 @@ void Battlenet::Authentication::LogonResponse::Write() } _stream.Write(PingTimeout + std::numeric_limits::min(), 32); - _stream.Write(1, 1); // RegulatorRules != NULL (not a pointer for us, always write) + _stream.Write(1, 1); // RegulatorRules != nullptr (not a pointer for us, always write) // if written == 1 { _stream.Write(RegulatorRules.Type == Regulator::LEAKY_BUCKET, 1); @@ -269,7 +269,7 @@ void Battlenet::Authentication::ResumeResponse::Write() } _stream.Write(PingTimeout + std::numeric_limits::min(), 32); - _stream.Write(1, 1); // RegulatorRules != NULL (not a pointer for us, always write) + _stream.Write(1, 1); // RegulatorRules != nullptr (not a pointer for us, always write) // if written == 1 { _stream.Write(RegulatorRules.Type == Regulator::LEAKY_BUCKET, 1); diff --git a/src/server/bnetserver/Packets/WoWRealmPackets.h b/src/server/bnetserver/Packets/WoWRealmPackets.h index 4802004025b..d722193fa52 100644 --- a/src/server/bnetserver/Packets/WoWRealmPackets.h +++ b/src/server/bnetserver/Packets/WoWRealmPackets.h @@ -19,7 +19,7 @@ #define WoWRealmPackets_h__ #include "PacketsBase.h" -#include "RealmList.h" +#include "Realm.h" namespace Battlenet { diff --git a/src/server/bnetserver/PrecompiledHeaders/bnetPCH.cpp b/src/server/bnetserver/PrecompiledHeaders/bnetPCH.cpp deleted file mode 100644 index 60b1d41a1a8..00000000000 --- a/src/server/bnetserver/PrecompiledHeaders/bnetPCH.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "bnetPCH.h" diff --git a/src/server/bnetserver/PrecompiledHeaders/bnetPCH.h b/src/server/bnetserver/PrecompiledHeaders/bnetPCH.h index 82cd5393489..023c6b6e83f 100644 --- a/src/server/bnetserver/PrecompiledHeaders/bnetPCH.h +++ b/src/server/bnetserver/PrecompiledHeaders/bnetPCH.h @@ -1,10 +1,24 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#include "BNetRealmList.h" #include "Common.h" -#include "Configuration/Config.h" -#include "Database/DatabaseEnv.h" -#include "Log.h" #include "ComponentManager.h" +#include "Configuration/Config.h" +#include "Log.h" #include "ModuleManager.h" -#include "RealmList.h" -#include "ByteBuffer.h" -#include "Packets.h" -#include "Session.h" +#include "SessionManager.h" diff --git a/src/server/bnetserver/Realms/RealmList.cpp b/src/server/bnetserver/Realms/BNetRealmList.cpp similarity index 58% rename from src/server/bnetserver/Realms/RealmList.cpp rename to src/server/bnetserver/Realms/BNetRealmList.cpp index 93c9ff6b805..c4d8a97d8a3 100644 --- a/src/server/bnetserver/Realms/RealmList.cpp +++ b/src/server/bnetserver/Realms/BNetRealmList.cpp @@ -16,46 +16,52 @@ * with this program. If not, see . */ -#include "Common.h" -#include "Database/DatabaseEnv.h" +#include "BNetRealmList.h" +#include "DatabaseEnv.h" +#include "IoContext.h" +#include "Log.h" +#include "Resolver.h" #include "SessionManager.h" #include "Util.h" -#include "Commands.h" -#include "RealmList.h" +#include "WorldListener.h" +#include #include -RealmList::RealmList() : _updateInterval(0), _updateTimer(nullptr), _resolver(nullptr), _worldListener(nullptr) +BNetRealmList::BNetRealmList() : _updateInterval(0) { } -RealmList::~RealmList() +BNetRealmList::~BNetRealmList() { - delete _updateTimer; - delete _resolver; - delete _worldListener; +} + +BNetRealmList* BNetRealmList::Instance() +{ + static BNetRealmList instance; + return &instance; } // Load the realm list from the database -void RealmList::Initialize(boost::asio::io_service& ioService, uint32 updateInterval, uint16 worldListenPort) +void BNetRealmList::Initialize(Trinity::Asio::IoContext& ioContext, uint32 updateInterval, uint16 worldListenPort) { _updateInterval = updateInterval; - _updateTimer = new boost::asio::deadline_timer(ioService); - _resolver = new boost::asio::ip::tcp::resolver(ioService); + _updateTimer = Trinity::make_unique(ioContext); + _resolver = Trinity::make_unique(ioContext); // Get the content of the realmlist table in the database UpdateRealms(boost::system::error_code()); - _worldListener = new WorldListener(worldListenPort); + _worldListener = Trinity::make_unique(worldListenPort); _worldListener->Start(); } -void RealmList::Close() +void BNetRealmList::Close() { _worldListener->End(); _updateTimer->cancel(); } -template +template inline void UpdateField(FieldType& out, FieldType const& in, bool& changed) { if (out != in) @@ -65,14 +71,23 @@ inline void UpdateField(FieldType& out, FieldType const& in, bool& changed) } } -void RealmList::UpdateRealm(Battlenet::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) +inline void UpdateAddress(std::unique_ptr& out, boost::asio::ip::address&& in, bool& changed) +{ + if (!out || *out != in) + { + out = Trinity::make_unique(std::move(in)); + changed = true; + } +} + +void BNetRealmList::UpdateRealm(Battlenet::RealmHandle const& id, uint32 build, std::string const& name, + boost::asio::ip::address&& address, boost::asio::ip::address&& localAddr, boost::asio::ip::address&& 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.Keep = true; + realm.Updated = false; realm.Id = id; UpdateField(realm.Build, build, realm.Updated); @@ -82,18 +97,20 @@ void RealmList::UpdateRealm(Battlenet::RealmHandle const& id, uint32 build, cons UpdateField(realm.Timezone, timezone, realm.Updated); UpdateField(realm.AllowedSecurityLevel, allowedSecurityLevel, realm.Updated); UpdateField(realm.PopulationLevel, population, realm.Updated); - UpdateField(realm.ExternalAddress, address, realm.Updated); - UpdateField(realm.LocalAddress, localAddr, realm.Updated); - UpdateField(realm.LocalSubnetMask, localSubmask, realm.Updated); + + UpdateAddress(realm.ExternalAddress, std::forward(address), realm.Updated); + UpdateAddress(realm.LocalAddress, std::forward(localAddr), realm.Updated); + UpdateAddress(realm.LocalSubnetMask, std::forward(localSubmask), realm.Updated); + UpdateField(realm.Port, port, realm.Updated); } -void RealmList::UpdateRealms(boost::system::error_code const& error) +void BNetRealmList::UpdateRealms(boost::system::error_code const& error) { if (error) return; - TC_LOG_DEBUG("realmlist", "Updating Realm List..."); + TC_LOG_DEBUG("server.authserver", "Updating Realm List..."); PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_REALMLIST); PreparedQueryResult result = LoginDatabase.Query(stmt); @@ -105,42 +122,34 @@ void RealmList::UpdateRealms(boost::system::error_code const& error) { try { - boost::asio::ip::tcp::resolver::iterator end; - Field* fields = result->Fetch(); + uint32 realmId = fields[0].GetUInt32(); std::string name = fields[1].GetString(); - boost::asio::ip::tcp::resolver::query externalAddressQuery(ip::tcp::v4(), fields[2].GetString(), ""); + std::string externalAddressString = fields[2].GetString(); + std::string localAddressString = fields[3].GetString(); + std::string localSubmaskString = fields[4].GetString(); - boost::system::error_code ec; - boost::asio::ip::tcp::resolver::iterator endPoint = _resolver->resolve(externalAddressQuery, ec); - if (endPoint == end || ec) + Optional externalAddress = Trinity::Net::Resolve(*_resolver, boost::asio::ip::tcp::v4(), externalAddressString, ""); + if (!externalAddress) { - TC_LOG_ERROR("realmlist", "Could not resolve address %s", fields[2].GetString().c_str()); + TC_LOG_ERROR("realmlist", "Could not resolve address %s", externalAddressString.c_str()); continue; } - ip::address 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) + Optional localAddress = Trinity::Net::Resolve(*_resolver, boost::asio::ip::tcp::v4(), localAddressString, ""); + if (!localAddress) { - TC_LOG_ERROR("realmlist", "Could not resolve address %s", fields[3].GetString().c_str()); + TC_LOG_ERROR("realmlist", "Could not resolve address %s", localAddressString.c_str()); continue; } - ip::address 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) + Optional localSubmask = Trinity::Net::Resolve(*_resolver, boost::asio::ip::tcp::v4(), localSubmaskString, ""); + if (!localSubmask) { - TC_LOG_ERROR("realmlist", "Could not resolve address %s", fields[4].GetString().c_str()); + TC_LOG_ERROR("realmlist", "Could not resolve address %s", localSubmaskString.c_str()); continue; } - ip::address localSubmask = (*endPoint).endpoint().address(); - uint16 port = fields[5].GetUInt16(); uint8 icon = fields[6].GetUInt8(); if (icon == REALM_TYPE_FFA_PVP) @@ -151,21 +160,20 @@ void RealmList::UpdateRealms(boost::system::error_code const& error) uint8 timezone = fields[8].GetUInt8(); uint8 allowedSecurityLevel = fields[9].GetUInt8(); float pop = fields[10].GetFloat(); - uint32 realmId = fields[0].GetUInt32(); uint32 build = fields[11].GetUInt32(); uint8 region = fields[12].GetUInt8(); uint8 battlegroup = fields[13].GetUInt8(); Battlenet::RealmHandle id{ region, battlegroup, realmId }; - UpdateRealm(id, build, name, externalAddress, localAddress, localSubmask, port, icon, flag, + UpdateRealm(id, build, name, externalAddress->address(), localAddress->address(), localSubmask->address(), port, icon, flag, timezone, (allowedSecurityLevel <= SEC_ADMINISTRATOR ? AccountTypes(allowedSecurityLevel) : SEC_ADMINISTRATOR), pop); - TC_LOG_TRACE("realmlist", "Realm \"%s\" at %s:%u.", name.c_str(), externalAddress.to_string().c_str(), port); + TC_LOG_TRACE("server.bnetserver", "Realm \"%s\" at %s:%u.", name.c_str(), externalAddressString.c_str(), port); } catch (std::exception& ex) { - TC_LOG_ERROR("realmlist", "Realmlist::UpdateRealms has thrown an exception: %s", ex.what()); + TC_LOG_ERROR("server.bnetserver", "BNetRealmList::UpdateRealms has thrown an exception: %s", ex.what()); ABORT(); } } @@ -201,15 +209,15 @@ void RealmList::UpdateRealms(boost::system::error_code const& error) if (_updateInterval) { _updateTimer->expires_from_now(boost::posix_time::seconds(_updateInterval)); - _updateTimer->async_wait(std::bind(&RealmList::UpdateRealms, this, std::placeholders::_1)); + _updateTimer->async_wait(std::bind(&BNetRealmList::UpdateRealms, this, std::placeholders::_1)); } } -Realm const* RealmList::GetRealm(Battlenet::RealmHandle const& id) const +Realm const* BNetRealmList::GetRealm(Battlenet::RealmHandle const& id) const { auto itr = _realms.find(id); if (itr != _realms.end()) return &itr->second; - return NULL; + return nullptr; } diff --git a/src/server/bnetserver/Realms/BNetRealmList.h b/src/server/bnetserver/Realms/BNetRealmList.h new file mode 100644 index 00000000000..b4bdf59649f --- /dev/null +++ b/src/server/bnetserver/Realms/BNetRealmList.h @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * Copyright (C) 2005-2009 MaNGOS + * + * 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 . + */ + +#ifndef BNetRealmList_h__ +#define BNetRealmList_h__ + +#include "Define.h" +#include "Realm.h" +#include +#include +#include + +class WorldListener; + +namespace boost +{ + namespace system + { + class error_code; + } +} + +namespace Trinity +{ + namespace Asio + { + class IoContext; + } +} + +/// Storage object for the list of realms on the server +class BNetRealmList +{ + public: + typedef std::map RealmMap; + + static BNetRealmList* Instance(); + + ~BNetRealmList(); + + void Initialize(Trinity::Asio::IoContext& ioContext, uint32 updateInterval, uint16 worldListenPort); + void Close(); + + RealmMap const& GetRealms() const { return _realms; } + Realm const* GetRealm(Battlenet::RealmHandle const& id) const; + + private: + BNetRealmList(); + + void UpdateRealms(boost::system::error_code const& error); + void UpdateRealm(Battlenet::RealmHandle const& id, uint32 build, std::string const& name, + boost::asio::ip::address&& address, boost::asio::ip::address&& localAddr, boost::asio::ip::address&& localSubmask, + uint16 port, uint8 icon, RealmFlags flag, uint8 timezone, AccountTypes allowedSecurityLevel, float population); + + RealmMap _realms; + uint32 _updateInterval; + std::unique_ptr _updateTimer; + std::unique_ptr _resolver; + std::unique_ptr _worldListener; +}; + +#define sBNetRealmList BNetRealmList::Instance() + +#endif // BNetRealmList_h__ diff --git a/src/server/bnetserver/Realms/RealmList.h b/src/server/bnetserver/Realms/RealmList.h deleted file mode 100644 index c865116c1db..00000000000 --- a/src/server/bnetserver/Realms/RealmList.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2008-2018 TrinityCore - * Copyright (C) 2005-2009 MaNGOS - * - * 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 . - */ - -#ifndef _REALMLIST_H -#define _REALMLIST_H - -#include "Common.h" -#include "Realm/Realm.h" -#include "WorldListener.h" -#include -#include -#include -#include - -using namespace boost::asio; - -/// Storage object for the list of realms on the server -class RealmList -{ -public: - typedef std::map RealmMap; - - static RealmList* instance() - { - static RealmList instance; - return &instance; - } - - ~RealmList(); - - void Initialize(boost::asio::io_service& ioService, uint32 updateInterval, uint16 worldListenPort); - void Close(); - - RealmMap const& GetRealms() const { return _realms; } - Realm const* GetRealm(Battlenet::RealmHandle const& id) const; - -private: - RealmList(); - - void UpdateRealms(boost::system::error_code const& error); - void UpdateRealm(Battlenet::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; - WorldListener* _worldListener; -}; - -#define sRealmList RealmList::instance() -#endif diff --git a/src/server/bnetserver/Server/ModuleManager.cpp b/src/server/bnetserver/Server/ModuleManager.cpp index b21dabbc40c..65ff7ce00a1 100644 --- a/src/server/bnetserver/Server/ModuleManager.cpp +++ b/src/server/bnetserver/Server/ModuleManager.cpp @@ -17,6 +17,7 @@ #include "ModuleManager.h" #include "DatabaseEnv.h" +#include "Util.h" Battlenet::ModuleManager::~ModuleManager() { diff --git a/src/server/bnetserver/Server/Session.cpp b/src/server/bnetserver/Server/Session.cpp index 0766a378159..6f16d5a5e59 100644 --- a/src/server/bnetserver/Server/Session.cpp +++ b/src/server/bnetserver/Server/Session.cpp @@ -15,17 +15,20 @@ * with this program. If not, see . */ +#include "Session.h" #include "AuthCodes.h" #include "BitStream.h" -#include "PacketManager.h" -#include "SessionManager.h" +#include "BNetRealmList.h" #include "Database/DatabaseEnv.h" -#include "QueryCallback.h" #include "HmacHash.h" #include "Log.h" -#include "RealmList.h" +#include "PacketManager.h" +#include "QueryCallback.h" +#include "Random.h" +#include "Realm.h" +#include "SessionManager.h" #include "SHA256.h" -#include +#include "Util.h" Battlenet::Session::ModuleHandler const Battlenet::Session::ModuleHandlers[MODULE_COUNT] = { @@ -86,7 +89,7 @@ Battlenet::Session::Session(tcp::socket&& socket) : Socket(std::move(socket)), _ g.SetDword(2); SHA256Hash sha; - sha.UpdateBigNumbers(&N, &g, NULL); + sha.UpdateBigNumbers(&N, &g, nullptr); sha.Finalize(); k.SetBinary(sha.GetDigest(), sha.GetLength()); } @@ -107,7 +110,7 @@ void Battlenet::Session::_SetVSFields(std::string const& pstr) p.SetHexStr(pstr.c_str()); SHA256Hash sha; - sha.UpdateBigNumbers(&s, &p, NULL); + sha.UpdateBigNumbers(&s, &p, nullptr); sha.Finalize(); BigNumber x; x.SetBinary(sha.GetDigest(), sha.GetLength()); @@ -452,7 +455,7 @@ void Battlenet::Session::HandleListSubscribeRequestCallback(PreparedQueryResult AsyncWrite(listSubscribeResponse); - for (RealmList::RealmMap::value_type const& i : sRealmList->GetRealms()) + for (auto const& i : sBNetRealmList->GetRealms()) AsyncWrite(BuildListUpdate(&i.second)); AsyncWrite(new WoWRealm::ListComplete()); @@ -468,7 +471,7 @@ void Battlenet::Session::HandleListUnsubscribe(WoWRealm::ListUnsubscribe const& void Battlenet::Session::HandleJoinRequestV2(WoWRealm::JoinRequestV2 const& joinRequest) { WoWRealm::JoinResponseV2* joinResponse = new WoWRealm::JoinResponseV2(); - Realm const* realm = sRealmList->GetRealm(joinRequest.Realm); + Realm const* realm = sBNetRealmList->GetRealm(joinRequest.Realm); if (!realm || realm->Flags & (REALM_FLAG_VERSION_MISMATCH | REALM_FLAG_OFFLINE)) { joinResponse->Response = WoWRealm::JoinResponseV2::FAILURE; @@ -498,9 +501,9 @@ void Battlenet::Session::HandleJoinRequestV2(WoWRealm::JoinRequestV2 const& join LoginDatabase.DirectPExecute("UPDATE account SET sessionkey = '%s', last_ip = '%s', last_login = NOW(), locale = %u, failed_logins = 0, os = '%s' WHERE id = %u", ByteArrayToHexStr(sessionKey, 40, true).c_str(), GetRemoteIpAddress().to_string().c_str(), GetLocaleByName(_locale), _os.c_str(), _gameAccountInfo->Id); - joinResponse->IPv4.emplace_back(realm->ExternalAddress, realm->Port); - if (realm->ExternalAddress != realm->LocalAddress) - joinResponse->IPv4.emplace_back(realm->LocalAddress, realm->Port); + joinResponse->IPv4.emplace_back(*realm->ExternalAddress, realm->Port); + if (*realm->ExternalAddress != *realm->LocalAddress) + joinResponse->IPv4.emplace_back(*realm->LocalAddress, realm->Port); AsyncWrite(joinResponse); } @@ -729,7 +732,7 @@ bool Battlenet::Session::HandlePasswordModule(BitStream* dataStream, ServerPacke } SHA256Hash sha; - sha.UpdateBigNumbers(&A, &B, NULL); + sha.UpdateBigNumbers(&A, &B, nullptr); sha.Finalize(); BigNumber u; @@ -768,12 +771,12 @@ bool Battlenet::Session::HandlePasswordModule(BitStream* dataStream, ServerPacke uint8 hash[SHA256_DIGEST_LENGTH]; sha.Initialize(); - sha.UpdateBigNumbers(&N, NULL); + sha.UpdateBigNumbers(&N, nullptr); sha.Finalize(); memcpy(hash, sha.GetDigest(), sha.GetLength()); sha.Initialize(); - sha.UpdateBigNumbers(&g, NULL); + sha.UpdateBigNumbers(&g, nullptr); sha.Finalize(); for (int i = 0; i < sha.GetLength(); ++i) @@ -787,7 +790,7 @@ bool Battlenet::Session::HandlePasswordModule(BitStream* dataStream, ServerPacke sha.Initialize(); sha.UpdateData(hash, SHA256_DIGEST_LENGTH); sha.UpdateData(shaI.GetDigest(), shaI.GetLength()); - sha.UpdateBigNumbers(&s, &A, &B, &K, NULL); + sha.UpdateBigNumbers(&s, &A, &B, &K, nullptr); sha.Finalize(); M1.SetBinary(sha.GetDigest(), sha.GetLength()); @@ -816,7 +819,7 @@ bool Battlenet::Session::HandlePasswordModule(BitStream* dataStream, ServerPacke BigNumber M; sha.Initialize(); - sha.UpdateBigNumbers(&A, &M1, &K, NULL); + sha.UpdateBigNumbers(&A, &M1, &K, nullptr); sha.Finalize(); M.SetBinary(sha.GetDigest(), sha.GetLength()); diff --git a/src/server/bnetserver/Server/SessionManager.cpp b/src/server/bnetserver/Server/SessionManager.cpp index e16d013ac82..36c7a35af48 100644 --- a/src/server/bnetserver/Server/SessionManager.cpp +++ b/src/server/bnetserver/Server/SessionManager.cpp @@ -16,10 +16,35 @@ */ #include "SessionManager.h" +#include "Containers.h" +#include "Hash.h" +#include +#include -bool Battlenet::SessionManager::StartNetwork(boost::asio::io_service& service, std::string const& bindIp, uint16 port, int threadCount) +namespace { - if (!BaseSocketMgr::StartNetwork(service, bindIp, port, threadCount)) + std::unordered_map, Battlenet::Session*> _sessions; + std::unordered_map> _sessionsByAccountId; + boost::shared_mutex _sessionMutex; +} + +Battlenet::SessionManager::SessionManager() : SocketMgr() +{ +} + +Battlenet::SessionManager::~SessionManager() +{ +} + +Battlenet::SessionManager& Battlenet::SessionManager::Instance() +{ + static SessionManager instance; + return instance; +} + +bool Battlenet::SessionManager::StartNetwork(Trinity::Asio::IoContext& ioContext, std::string const& bindIp, uint16 port, int threadCount /*= 1*/) +{ + if (!BaseSocketMgr::StartNetwork(ioContext, bindIp, port, threadCount)) return false; _acceptor->SetSocketFactory(std::bind(&BaseSocketMgr::GetSocketForAccept, this)); @@ -58,20 +83,18 @@ void Battlenet::SessionManager::RemoveSession(Session* session) Battlenet::Session* Battlenet::SessionManager::GetSession(uint32 accountId, uint32 gameAccountId) const { boost::shared_lock lock(_sessionMutex); - auto itr = _sessions.find({ accountId, gameAccountId }); - if (itr != _sessions.end()) - return itr->second; - - return nullptr; + return Trinity::Containers::MapGetValuePtr(_sessions, { accountId, gameAccountId }); } -std::list Battlenet::SessionManager::GetSessions(uint32 accountId) const +std::list* Battlenet::SessionManager::GetSessions(uint32 accountId) const { boost::shared_lock lock(_sessionMutex); - std::list sessions; - auto itr = _sessionsByAccountId.find(accountId); - if (itr != _sessionsByAccountId.end()) - sessions = itr->second; - - return sessions; + return Trinity::Containers::MapGetValuePtr(_sessionsByAccountId, accountId); +} + +void Battlenet::SessionManager::LockedForEach(std::function&& iterator) const +{ + boost::shared_lock lock(_sessionMutex); + for (auto const& pair : _sessions) + iterator(pair.second); } diff --git a/src/server/bnetserver/Server/SessionManager.h b/src/server/bnetserver/Server/SessionManager.h index 919021a0bc2..325db4773f7 100644 --- a/src/server/bnetserver/Server/SessionManager.h +++ b/src/server/bnetserver/Server/SessionManager.h @@ -18,68 +18,37 @@ #ifndef SessionManager_h__ #define SessionManager_h__ -#include "Session.h" #include "SocketMgr.h" -#include -#include +#include "Session.h" +#include namespace Battlenet { -#pragma pack(push, 1) - - struct SessionInfo - { - uint32 AccountId; - uint32 GameAccountId; - - bool operator<(SessionInfo const& right) const - { - return memcmp(this, &right, sizeof(SessionInfo)) < 0; - } - }; - -#pragma pack(pop) - class SessionManager : public SocketMgr { typedef SocketMgr BaseSocketMgr; - typedef std::map SessionMap; - typedef std::map> SessionByAccountMap; - public: - static SessionManager& Instance() - { - static SessionManager instance; - return instance; - } + public: + static SessionManager& Instance(); - bool StartNetwork(boost::asio::io_service& service, std::string const& bindIp, uint16 port, int threadCount = 1) override; + bool StartNetwork(Trinity::Asio::IoContext& ioContext, std::string const& bindIp, uint16 port, int threadCount = 1) override; - // noop for now, will be needed later to broadcast realmlist updates for example - void AddSession(Session* /*session*/); + void AddSession(Session* session); + void RemoveSession(Session* session); - void RemoveSession(Session* /*session*/); + Session* GetSession(uint32 accountId, uint32 gameAccountId) const; + std::list* GetSessions(uint32 accountId) const; - Session* GetSession(uint32 accountId, uint32 gameAccountId) const; - std::list GetSessions(uint32 accountId) const; + void LockedForEach(std::function&& iterator) const; - template - void LockedForEach(Iterator iterator) const - { - boost::shared_lock lock(_sessionMutex); - for (SessionMap::value_type const& pair : _sessions) - iterator(pair.second); - } + protected: + NetworkThread* CreateThreads() const override; - protected: - NetworkThread* CreateThreads() const override; + private: + static void OnSocketAccept(tcp::socket&& sock, uint32 threadIndex); - private: - static void OnSocketAccept(tcp::socket&& sock, uint32 threadIndex); - - SessionMap _sessions; - SessionByAccountMap _sessionsByAccountId; - mutable boost::shared_mutex _sessionMutex; + SessionManager(); + ~SessionManager(); }; } diff --git a/src/server/database/CMakeLists.txt b/src/server/database/CMakeLists.txt index 739ee15411c..3605b498b50 100644 --- a/src/server/database/CMakeLists.txt +++ b/src/server/database/CMakeLists.txt @@ -16,10 +16,6 @@ CollectSourceFiles( if (USE_COREPCH) set(PRIVATE_PCH_HEADER PrecompiledHeaders/databasePCH.h) - set(PRIVATE_PCH_SOURCE PrecompiledHeaders/databasePCH.cpp) - if (MSVC) - list(INSERT PRIVATE_SOURCES 0 PrecompiledHeaders/databasePCH.cpp) - endif (MSVC) endif() GroupSources(${CMAKE_CURRENT_SOURCE_DIR}) @@ -52,6 +48,8 @@ target_include_directories(database add_definitions(-DTRINITY_API_EXPORT_DATABASE) target_link_libraries(database + PRIVATE + trinity-core-interface PUBLIC common mysql) @@ -75,5 +73,5 @@ endif() # Generate precompiled header if (USE_COREPCH) - add_cxx_pch(database ${PRIVATE_PCH_HEADER} ${PRIVATE_PCH_SOURCE}) + add_cxx_pch(database ${PRIVATE_PCH_HEADER}) endif () diff --git a/src/server/database/Database/AdhocStatement.cpp b/src/server/database/Database/AdhocStatement.cpp index dfa4da4ead4..f50266b1189 100644 --- a/src/server/database/Database/AdhocStatement.cpp +++ b/src/server/database/Database/AdhocStatement.cpp @@ -16,10 +16,14 @@ */ #include "AdhocStatement.h" +#include "Errors.h" #include "MySQLConnection.h" +#include "QueryResult.h" +#include +#include /*! Basic, ad-hoc queries. */ -BasicStatementTask::BasicStatementTask(const char* sql, bool async) : +BasicStatementTask::BasicStatementTask(char const* sql, bool async) : m_result(nullptr) { m_sql = strdup(sql); @@ -43,7 +47,7 @@ bool BasicStatementTask::Execute() if (!result || !result->GetRowCount() || !result->NextRow()) { delete result; - m_result->set_value(QueryResult(NULL)); + m_result->set_value(QueryResult(nullptr)); return false; } diff --git a/src/server/database/Database/AdhocStatement.h b/src/server/database/Database/AdhocStatement.h index 1ddaea3ddf8..a2f9fe241b2 100644 --- a/src/server/database/Database/AdhocStatement.h +++ b/src/server/database/Database/AdhocStatement.h @@ -18,24 +18,22 @@ #ifndef _ADHOCSTATEMENT_H #define _ADHOCSTATEMENT_H -#include +#include "Define.h" +#include "DatabaseEnvFwd.h" #include "SQLOperation.h" -typedef std::future QueryResultFuture; -typedef std::promise QueryResultPromise; - /*! Raw, ad-hoc query. */ class TC_DATABASE_API BasicStatementTask : public SQLOperation { public: - BasicStatementTask(const char* sql, bool async = false); + BasicStatementTask(char const* sql, bool async = false); ~BasicStatementTask(); bool Execute() override; QueryResultFuture GetFuture() const { return m_result->get_future(); } private: - const char* m_sql; //- Raw query to be executed + char const* m_sql; //- Raw query to be executed bool m_has_result; QueryResultPromise* m_result; }; diff --git a/src/server/database/Database/DatabaseEnv.cpp b/src/server/database/Database/DatabaseEnv.cpp index 4ab9054c1c0..f5e692ded13 100644 --- a/src/server/database/Database/DatabaseEnv.cpp +++ b/src/server/database/Database/DatabaseEnv.cpp @@ -17,6 +17,6 @@ #include "DatabaseEnv.h" -WorldDatabaseWorkerPool WorldDatabase; -CharacterDatabaseWorkerPool CharacterDatabase; -LoginDatabaseWorkerPool LoginDatabase; +DatabaseWorkerPool WorldDatabase; +DatabaseWorkerPool CharacterDatabase; +DatabaseWorkerPool LoginDatabase; diff --git a/src/server/database/Database/DatabaseEnv.h b/src/server/database/Database/DatabaseEnv.h index bb63c2e913f..27904828fe9 100644 --- a/src/server/database/Database/DatabaseEnv.h +++ b/src/server/database/Database/DatabaseEnv.h @@ -19,30 +19,24 @@ #ifndef DATABASEENV_H #define DATABASEENV_H -#include "Common.h" -#include "Errors.h" -#include "Log.h" - -#include "Field.h" -#include "QueryResult.h" - -#include "MySQLThreading.h" -#include "Transaction.h" - -#define _LIKE_ "LIKE" -#define _TABLE_SIM_ '`' -#define _CONCAT3_(A, B, C) "CONCAT( " A ", " B ", " C " )" -#define _OFFSET_ "LIMIT %d, 1" +#include "Define.h" +#include "DatabaseWorkerPool.h" #include "Implementation/LoginDatabase.h" #include "Implementation/CharacterDatabase.h" #include "Implementation/WorldDatabase.h" +#include "Field.h" +#include "PreparedStatement.h" +#include "QueryCallback.h" +#include "QueryResult.h" +#include "Transaction.h" + /// Accessor to the world database -TC_DATABASE_API extern WorldDatabaseWorkerPool WorldDatabase; +TC_DATABASE_API extern DatabaseWorkerPool WorldDatabase; /// Accessor to the character database -TC_DATABASE_API extern CharacterDatabaseWorkerPool CharacterDatabase; +TC_DATABASE_API extern DatabaseWorkerPool CharacterDatabase; /// Accessor to the realm/login database -TC_DATABASE_API extern LoginDatabaseWorkerPool LoginDatabase; +TC_DATABASE_API extern DatabaseWorkerPool LoginDatabase; #endif diff --git a/src/server/database/Database/DatabaseEnvFwd.h b/src/server/database/Database/DatabaseEnvFwd.h new file mode 100644 index 00000000000..0e3482b638f --- /dev/null +++ b/src/server/database/Database/DatabaseEnvFwd.h @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef DatabaseEnvFwd_h__ +#define DatabaseEnvFwd_h__ + +#include +#include + +class Field; + +class ResultSet; +typedef std::shared_ptr QueryResult; +typedef std::future QueryResultFuture; +typedef std::promise QueryResultPromise; + +class PreparedStatement; + +class PreparedResultSet; +typedef std::shared_ptr PreparedQueryResult; +typedef std::future PreparedQueryResultFuture; +typedef std::promise PreparedQueryResultPromise; + +class QueryCallback; + +class Transaction; +typedef std::shared_ptr SQLTransaction; + +class SQLQueryHolder; +typedef std::future QueryResultHolderFuture; +typedef std::promise QueryResultHolderPromise; + +// mysql +typedef struct st_mysql MYSQL; +typedef struct st_mysql_res MYSQL_RES; +typedef struct st_mysql_field MYSQL_FIELD; +typedef struct st_mysql_bind MYSQL_BIND; +typedef struct st_mysql_stmt MYSQL_STMT; + +#endif // DatabaseEnvFwd_h__ diff --git a/src/server/database/Database/DatabaseLoader.cpp b/src/server/database/Database/DatabaseLoader.cpp index c40b50f40f7..1bb4925209d 100644 --- a/src/server/database/Database/DatabaseLoader.cpp +++ b/src/server/database/Database/DatabaseLoader.cpp @@ -16,9 +16,10 @@ */ #include "DatabaseLoader.h" -#include "DBUpdater.h" #include "Config.h" - +#include "DatabaseEnv.h" +#include "DBUpdater.h" +#include "Log.h" #include DatabaseLoader::DatabaseLoader(std::string const& logger, uint32 const defaultUpdateMask) @@ -178,8 +179,8 @@ bool DatabaseLoader::Process(std::queue& queue) } template TC_DATABASE_API -DatabaseLoader& DatabaseLoader::AddDatabase(LoginDatabaseWorkerPool&, std::string const&); +DatabaseLoader& DatabaseLoader::AddDatabase(DatabaseWorkerPool&, std::string const&); template TC_DATABASE_API -DatabaseLoader& DatabaseLoader::AddDatabase(CharacterDatabaseWorkerPool&, std::string const&); +DatabaseLoader& DatabaseLoader::AddDatabase(DatabaseWorkerPool&, std::string const&); template TC_DATABASE_API -DatabaseLoader& DatabaseLoader::AddDatabase(WorldDatabaseWorkerPool&, std::string const&); +DatabaseLoader& DatabaseLoader::AddDatabase(DatabaseWorkerPool&, std::string const&); diff --git a/src/server/database/Database/DatabaseLoader.h b/src/server/database/Database/DatabaseLoader.h index ed0caab26b5..9e7221f235f 100644 --- a/src/server/database/Database/DatabaseLoader.h +++ b/src/server/database/Database/DatabaseLoader.h @@ -18,12 +18,14 @@ #ifndef DatabaseLoader_h__ #define DatabaseLoader_h__ -#include "DatabaseWorkerPool.h" -#include "DBUpdater.h" - +#include "Define.h" #include -#include #include +#include +#include + +template +class DatabaseWorkerPool; // A helper class to initiate all database worker pools, // handles updating, delays preparing of statements and cleans up on failure. diff --git a/src/server/database/Database/DatabaseWorker.cpp b/src/server/database/Database/DatabaseWorker.cpp index 605b11a1634..781bd6450c6 100644 --- a/src/server/database/Database/DatabaseWorker.cpp +++ b/src/server/database/Database/DatabaseWorker.cpp @@ -15,7 +15,6 @@ * with this program. If not, see . */ -#include "DatabaseEnv.h" #include "DatabaseWorker.h" #include "SQLOperation.h" #include "ProducerConsumerQueue.h" diff --git a/src/server/database/Database/DatabaseWorker.h b/src/server/database/Database/DatabaseWorker.h index 823287fe225..4cfdd9630db 100644 --- a/src/server/database/Database/DatabaseWorker.h +++ b/src/server/database/Database/DatabaseWorker.h @@ -18,8 +18,12 @@ #ifndef _WORKERTHREAD_H #define _WORKERTHREAD_H +#include "Define.h" +#include #include -#include "ProducerConsumerQueue.h" + +template +class ProducerConsumerQueue; class MySQLConnection; class SQLOperation; @@ -37,7 +41,7 @@ class TC_DATABASE_API DatabaseWorker void WorkerThread(); std::thread _workerThread; - std::atomic_bool _cancelationToken; + std::atomic _cancelationToken; DatabaseWorker(DatabaseWorker const& right) = delete; DatabaseWorker& operator=(DatabaseWorker const& right) = delete; diff --git a/src/server/database/Database/DatabaseWorkerPool.cpp b/src/server/database/Database/DatabaseWorkerPool.cpp index 4661cd52442..932f6af91a7 100644 --- a/src/server/database/Database/DatabaseWorkerPool.cpp +++ b/src/server/database/Database/DatabaseWorkerPool.cpp @@ -16,12 +16,39 @@ */ #include "DatabaseWorkerPool.h" -#include "DatabaseEnv.h" +#include "AdhocStatement.h" +#include "Common.h" +#include "Errors.h" +#include "Implementation/LoginDatabase.h" +#include "Implementation/WorldDatabase.h" +#include "Implementation/CharacterDatabase.h" +#include "Log.h" +#include "PreparedStatement.h" +#include "ProducerConsumerQueue.h" #include "QueryCallback.h" +#include "QueryHolder.h" +#include "QueryResult.h" +#include "SQLOperation.h" +#include "Transaction.h" +#ifdef _WIN32 // hack for broken mysql.h not including the correct winsock header for SOCKET definition, fixed in 5.7 +#include +#endif +#include +#include #define MIN_MYSQL_SERVER_VERSION 50100u #define MIN_MYSQL_CLIENT_VERSION 50100u +class PingOperation : public SQLOperation +{ + //! Operation for idle delaythreads + bool Execute() override + { + m_conn->Ping(); + return true; + } +}; + template DatabaseWorkerPool::DatabaseWorkerPool() : _queue(new ProducerConsumerQueue()), @@ -33,6 +60,12 @@ DatabaseWorkerPool::DatabaseWorkerPool() mysql_get_client_info(), MYSQL_SERVER_VERSION); } +template +DatabaseWorkerPool::~DatabaseWorkerPool() +{ + _queue->Cancel(); +} + template void DatabaseWorkerPool::SetConnectionInfo(std::string const& infoString, uint8 const asyncThreads, uint8 const synchThreads) @@ -135,7 +168,7 @@ bool DatabaseWorkerPool::PrepareStatements() } template -QueryResult DatabaseWorkerPool::Query(const char* sql, T* connection /*= nullptr*/) +QueryResult DatabaseWorkerPool::Query(char const* sql, T* connection /*= nullptr*/) { if (!connection) connection = GetFreeConnection(); @@ -145,7 +178,7 @@ QueryResult DatabaseWorkerPool::Query(const char* sql, T* connection /*= null if (!result || !result->GetRowCount() || !result->NextRow()) { delete result; - return QueryResult(NULL); + return QueryResult(nullptr); } return QueryResult(result); @@ -164,14 +197,14 @@ PreparedQueryResult DatabaseWorkerPool::Query(PreparedStatement* stmt) if (!ret || !ret->GetRowCount()) { delete ret; - return PreparedQueryResult(NULL); + return PreparedQueryResult(nullptr); } return PreparedQueryResult(ret); } template -QueryCallback DatabaseWorkerPool::AsyncQuery(const char* sql) +QueryCallback DatabaseWorkerPool::AsyncQuery(char const* sql) { BasicStatementTask* task = new BasicStatementTask(sql, true); // Store future result before enqueueing - task might get already processed and deleted before returning from this method @@ -200,6 +233,12 @@ QueryResultHolderFuture DatabaseWorkerPool::DelayQueryHolder(SQLQueryHolder* return result; } +template +SQLTransaction DatabaseWorkerPool::BeginTransaction() +{ + return std::make_shared(); +} + template void DatabaseWorkerPool::CommitTransaction(SQLTransaction transaction) { @@ -253,6 +292,12 @@ void DatabaseWorkerPool::DirectCommitTransaction(SQLTransaction& transaction) connection->Unlock(); } +template +PreparedStatement* DatabaseWorkerPool::GetPreparedStatement(PreparedStatementIndex index) +{ + return new PreparedStatement(index, _preparedStatementSize[index]); +} + template void DatabaseWorkerPool::EscapeString(std::string& str) { @@ -325,6 +370,22 @@ uint32 DatabaseWorkerPool::OpenConnections(InternalIndex type, uint8 numConne return 0; } +template +unsigned long DatabaseWorkerPool::EscapeString(char* to, char const* from, unsigned long length) +{ + if (!to || !from || !length) + return 0; + + return mysql_real_escape_string( + _connections[IDX_SYNCH].front()->GetHandle(), to, from, length); +} + +template +void DatabaseWorkerPool::Enqueue(SQLOperation* op) +{ + _queue->Push(op); +} + template T* DatabaseWorkerPool::GetFreeConnection() { @@ -343,6 +404,69 @@ T* DatabaseWorkerPool::GetFreeConnection() return connection; } +template +char const* DatabaseWorkerPool::GetDatabaseName() const +{ + return _connectionInfo->database.c_str(); +} + +template +void DatabaseWorkerPool::Execute(char const* sql) +{ + if (Trinity::IsFormatEmptyOrNull(sql)) + return; + + BasicStatementTask* task = new BasicStatementTask(sql); + Enqueue(task); +} + +template +void DatabaseWorkerPool::Execute(PreparedStatement* stmt) +{ + PreparedStatementTask* task = new PreparedStatementTask(stmt); + Enqueue(task); +} + +template +void DatabaseWorkerPool::DirectExecute(char const* sql) +{ + if (Trinity::IsFormatEmptyOrNull(sql)) + return; + + T* connection = GetFreeConnection(); + connection->Execute(sql); + connection->Unlock(); +} + +template +void DatabaseWorkerPool::DirectExecute(PreparedStatement* stmt) +{ + T* connection = GetFreeConnection(); + connection->Execute(stmt); + connection->Unlock(); + + //! Delete proxy-class. Not needed anymore + delete stmt; +} + +template +void DatabaseWorkerPool::ExecuteOrAppend(SQLTransaction& trans, char const* sql) +{ + if (!trans) + Execute(sql); + else + trans->Append(sql); +} + +template +void DatabaseWorkerPool::ExecuteOrAppend(SQLTransaction& trans, PreparedStatement* stmt) +{ + if (!trans) + Execute(stmt); + else + trans->Append(stmt); +} + template class TC_DATABASE_API DatabaseWorkerPool; template class TC_DATABASE_API DatabaseWorkerPool; template class TC_DATABASE_API DatabaseWorkerPool; diff --git a/src/server/database/Database/DatabaseWorkerPool.h b/src/server/database/Database/DatabaseWorkerPool.h index e746e9e01fb..d4fbb132fb8 100644 --- a/src/server/database/Database/DatabaseWorkerPool.h +++ b/src/server/database/Database/DatabaseWorkerPool.h @@ -18,32 +18,18 @@ #ifndef _DATABASEWORKERPOOL_H #define _DATABASEWORKERPOOL_H -#include "Common.h" -#include "MySQLConnection.h" -#include "Transaction.h" -#include "DatabaseWorker.h" -#include "PreparedStatement.h" -#include "Log.h" -#include "QueryResult.h" -#include "QueryHolder.h" -#include "AdhocStatement.h" +#include "Define.h" +#include "DatabaseEnvFwd.h" #include "StringFormat.h" - -#include -#include #include +#include +#include -class QueryCallback; +template +class ProducerConsumerQueue; -class PingOperation : public SQLOperation -{ - //! Operation for idle delaythreads - bool Execute() override - { - m_conn->Ping(); - return true; - } -}; +class SQLOperation; +struct MySQLConnectionInfo; template class DatabaseWorkerPool @@ -60,10 +46,7 @@ class DatabaseWorkerPool /* Activity state */ DatabaseWorkerPool(); - ~DatabaseWorkerPool() - { - _queue->Cancel(); - } + ~DatabaseWorkerPool(); void SetConnectionInfo(std::string const& infoString, uint8 const asyncThreads, uint8 const synchThreads); @@ -85,14 +68,7 @@ class DatabaseWorkerPool //! Enqueues a one-way SQL operation in string format that will be executed asynchronously. //! This method should only be used for queries that are only executed once, e.g during startup. - void Execute(const char* sql) - { - if (Trinity::IsFormatEmptyOrNull(sql)) - return; - - BasicStatementTask* task = new BasicStatementTask(sql); - Enqueue(task); - } + void Execute(char const* sql); //! Enqueues a one-way SQL operation in string format -with variable args- that will be executed asynchronously. //! This method should only be used for queries that are only executed once, e.g during startup. @@ -107,11 +83,7 @@ class DatabaseWorkerPool //! Enqueues a one-way SQL operation in prepared statement format that will be executed asynchronously. //! Statement must be prepared with CONNECTION_ASYNC flag. - void Execute(PreparedStatement* stmt) - { - PreparedStatementTask* task = new PreparedStatementTask(stmt); - Enqueue(task); - } + void Execute(PreparedStatement* stmt); /** Direct synchronous one-way statement methods. @@ -119,15 +91,7 @@ class DatabaseWorkerPool //! Directly executes a one-way SQL operation in string format, that will block the calling thread until finished. //! This method should only be used for queries that are only executed once, e.g during startup. - void DirectExecute(const char* sql) - { - if (Trinity::IsFormatEmptyOrNull(sql)) - return; - - T* connection = GetFreeConnection(); - connection->Execute(sql); - connection->Unlock(); - } + void DirectExecute(char const* sql); //! Directly executes a one-way SQL operation in string format -with variable args-, that will block the calling thread until finished. //! This method should only be used for queries that are only executed once, e.g during startup. @@ -142,15 +106,7 @@ class DatabaseWorkerPool //! Directly executes a one-way SQL operation in prepared statement format, that will block the calling thread until finished. //! Statement must be prepared with the CONNECTION_SYNCH flag. - void DirectExecute(PreparedStatement* stmt) - { - T* connection = GetFreeConnection(); - connection->Execute(stmt); - connection->Unlock(); - - //! Delete proxy-class. Not needed anymore - delete stmt; - } + void DirectExecute(PreparedStatement* stmt); /** Synchronous query (with resultset) methods. @@ -158,7 +114,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* connection = nullptr); + QueryResult Query(char const* 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. @@ -193,7 +149,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. - QueryCallback AsyncQuery(const char* sql); + QueryCallback AsyncQuery(char const* sql); //! 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. @@ -211,10 +167,7 @@ class DatabaseWorkerPool */ //! Begins an automanaged transaction pointer that will automatically rollback if not commited. (Autocommit=0) - SQLTransaction BeginTransaction() - { - return SQLTransaction(new Transaction); - } + SQLTransaction BeginTransaction(); //! 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. @@ -224,25 +177,13 @@ class DatabaseWorkerPool //! were appended to the transaction will be respected during execution. 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. - void ExecuteOrAppend(SQLTransaction& trans, PreparedStatement* stmt) - { - if (!trans) - Execute(stmt); - else - trans->Append(stmt); - } - //! Method used to execute ad-hoc statements in a diverse context. //! Will be wrapped in a transaction if valid object is present, otherwise executed standalone. - void ExecuteOrAppend(SQLTransaction& trans, const char* sql) - { - if (!trans) - Execute(sql); - else - trans->Append(sql); - } + void ExecuteOrAppend(SQLTransaction& trans, char const* sql); + + //! Method used to execute prepared statements in a diverse context. + //! Will be wrapped in a transaction if valid object is present, otherwise executed standalone. + void ExecuteOrAppend(SQLTransaction& trans, PreparedStatement* stmt); /** Other @@ -253,10 +194,7 @@ class DatabaseWorkerPool //! Automanaged (internally) pointer to a prepared statement object for usage in upper level code. //! Pointer is deleted in this->DirectExecute(PreparedStatement*), this->Query(PreparedStatement*) or PreparedStatementTask::~PreparedStatementTask. //! This object is not tied to the prepared statement on the MySQL context yet until execution. - PreparedStatement* GetPreparedStatement(PreparedStatementIndex index) - { - return new PreparedStatement(index, _preparedStatementSize[index]); - } + PreparedStatement* GetPreparedStatement(PreparedStatementIndex index); //! Apply escape string'ing for current collation. (utf8) void EscapeString(std::string& str); @@ -267,28 +205,15 @@ class DatabaseWorkerPool private: uint32 OpenConnections(InternalIndex type, uint8 numConnections); - unsigned long EscapeString(char *to, const char *from, unsigned long length) - { - if (!to || !from || !length) - return 0; + unsigned long EscapeString(char* to, char const* from, unsigned long length); - return mysql_real_escape_string( - _connections[IDX_SYNCH].front()->GetHandle(), to, from, length); - } - - void Enqueue(SQLOperation* op) - { - _queue->Push(op); - } + void Enqueue(SQLOperation* op); //! Gets a free connection in the synchronous connection pool. //! Caller MUST call t->Unlock() after touching the MySQL context to prevent deadlocks. T* GetFreeConnection(); - char const* GetDatabaseName() const - { - return _connectionInfo->database.c_str(); - } + char const* GetDatabaseName() const; //! Queue shared by async worker threads. std::unique_ptr> _queue; diff --git a/src/server/database/Database/Field.cpp b/src/server/database/Database/Field.cpp index 5ab505058b6..0f806265b03 100644 --- a/src/server/database/Database/Field.cpp +++ b/src/server/database/Database/Field.cpp @@ -16,11 +16,12 @@ */ #include "Field.h" +#include "Log.h" Field::Field() { - data.value = NULL; - data.type = MYSQL_TYPE_NULL; + data.value = nullptr; + data.type = DatabaseFieldTypes::Null; data.length = 0; data.raw = false; } @@ -30,7 +31,236 @@ Field::~Field() CleanUp(); } -void Field::SetByteValue(void* newValue, enum_field_types newType, uint32 length) +uint8 Field::GetUInt8() const +{ + if (!data.value) + return 0; + +#ifdef TRINITY_DEBUG + if (!IsType(DatabaseFieldTypes::Int8)) + { + TC_LOG_WARN("sql.sql", "Warning: GetUInt8() on non-tinyint field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return 0; + } +#endif + + if (data.raw) + return *reinterpret_cast(data.value); + return static_cast(strtoul((char*)data.value, nullptr, 10)); +} + +int8 Field::GetInt8() const +{ + if (!data.value) + return 0; + +#ifdef TRINITY_DEBUG + if (!IsType(DatabaseFieldTypes::Int8)) + { + TC_LOG_WARN("sql.sql", "Warning: GetInt8() on non-tinyint field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return 0; + } +#endif + + if (data.raw) + return *reinterpret_cast(data.value); + return static_cast(strtol((char*)data.value, nullptr, 10)); +} + +uint16 Field::GetUInt16() const +{ + if (!data.value) + return 0; + +#ifdef TRINITY_DEBUG + if (!IsType(DatabaseFieldTypes::Int16)) + { + TC_LOG_WARN("sql.sql", "Warning: GetUInt16() on non-smallint field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return 0; + } +#endif + + if (data.raw) + return *reinterpret_cast(data.value); + return static_cast(strtoul((char*)data.value, nullptr, 10)); +} + +int16 Field::GetInt16() const +{ + if (!data.value) + return 0; + +#ifdef TRINITY_DEBUG + if (!IsType(DatabaseFieldTypes::Int16)) + { + TC_LOG_WARN("sql.sql", "Warning: GetInt16() on non-smallint field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return 0; + } +#endif + + if (data.raw) + return *reinterpret_cast(data.value); + return static_cast(strtol((char*)data.value, nullptr, 10)); +} + +uint32 Field::GetUInt32() const +{ + if (!data.value) + return 0; + +#ifdef TRINITY_DEBUG + if (!IsType(DatabaseFieldTypes::Int32)) + { + TC_LOG_WARN("sql.sql", "Warning: GetUInt32() on non-(medium)int field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return 0; + } +#endif + + if (data.raw) + return *reinterpret_cast(data.value); + return static_cast(strtoul((char*)data.value, nullptr, 10)); +} + +int32 Field::GetInt32() const +{ + if (!data.value) + return 0; + +#ifdef TRINITY_DEBUG + if (!IsType(DatabaseFieldTypes::Int32)) + { + TC_LOG_WARN("sql.sql", "Warning: GetInt32() on non-(medium)int field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return 0; + } +#endif + + if (data.raw) + return *reinterpret_cast(data.value); + return static_cast(strtol((char*)data.value, nullptr, 10)); +} + +uint64 Field::GetUInt64() const +{ + if (!data.value) + return 0; + +#ifdef TRINITY_DEBUG + if (!IsType(DatabaseFieldTypes::Int64)) + { + TC_LOG_WARN("sql.sql", "Warning: GetUInt64() on non-bigint field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return 0; + } +#endif + + if (data.raw) + return *reinterpret_cast(data.value); + return static_cast(strtoull((char*)data.value, nullptr, 10)); +} + +int64 Field::GetInt64() const +{ + if (!data.value) + return 0; + +#ifdef TRINITY_DEBUG + if (!IsType(DatabaseFieldTypes::Int64)) + { + TC_LOG_WARN("sql.sql", "Warning: GetInt64() on non-bigint field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return 0; + } +#endif + + if (data.raw) + return *reinterpret_cast(data.value); + return static_cast(strtoll((char*)data.value, nullptr, 10)); +} + +float Field::GetFloat() const +{ + if (!data.value) + return 0.0f; + +#ifdef TRINITY_DEBUG + if (!IsType(DatabaseFieldTypes::Float)) + { + TC_LOG_WARN("sql.sql", "Warning: GetFloat() on non-float field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return 0.0f; + } +#endif + + if (data.raw) + return *reinterpret_cast(data.value); + return static_cast(atof((char*)data.value)); +} + +double Field::GetDouble() const +{ + if (!data.value) + return 0.0f; + +#ifdef TRINITY_DEBUG + if (!IsType(DatabaseFieldTypes::Double) && !IsType(DatabaseFieldTypes::Decimal)) + { + TC_LOG_WARN("sql.sql", "Warning: GetDouble() on non-double/non-decimal field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return 0.0f; + } +#endif + + if (data.raw && !IsType(DatabaseFieldTypes::Decimal)) + return *reinterpret_cast(data.value); + return static_cast(atof((char*)data.value)); +} + +char const* Field::GetCString() const +{ + if (!data.value) + return nullptr; + +#ifdef TRINITY_DEBUG + if (IsNumeric() && data.raw) + { + TC_LOG_WARN("sql.sql", "Error: GetCString() on numeric field %s.%s (%s.%s) at index %u. Using type: %s.", + meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); + return nullptr; + } +#endif + return static_cast(data.value); +} + +std::string Field::GetString() const +{ + if (!data.value) + return ""; + + char const* string = GetCString(); + if (!string) + return ""; + + return std::string(string, data.length); +} + +std::vector Field::GetBinary() const +{ + std::vector result; + if (!data.value || !data.length) + return result; + + result.resize(data.length); + memcpy(result.data(), data.value, data.length); + return result; +} + +void Field::SetByteValue(void* newValue, DatabaseFieldTypes newType, uint32 length) { // This value stores raw bytes that have to be explicitly cast later data.value = newValue; @@ -39,7 +269,7 @@ void Field::SetByteValue(void* newValue, enum_field_types newType, uint32 length data.raw = true; } -void Field::SetStructuredValue(char* newValue, enum_field_types newType, uint32 length) +void Field::SetStructuredValue(char* newValue, DatabaseFieldTypes newType, uint32 length) { if (data.value) CleanUp(); @@ -56,3 +286,70 @@ void Field::SetStructuredValue(char* newValue, enum_field_types newType, uint32 data.type = newType; data.raw = false; } + +bool Field::IsType(DatabaseFieldTypes type) const +{ + return data.type == type; +} + +bool Field::IsNumeric() const +{ + return (data.type == DatabaseFieldTypes::Int8 || + data.type == DatabaseFieldTypes::Int16 || + data.type == DatabaseFieldTypes::Int32 || + data.type == DatabaseFieldTypes::Int64 || + data.type == DatabaseFieldTypes::Float || + data.type == DatabaseFieldTypes::Double); +} + +#ifdef TRINITY_DEBUG + +#ifdef _WIN32 // hack for broken mysql.h not including the correct winsock header for SOCKET definition, fixed in 5.7 +#include +#endif +#include + +static char const* FieldTypeToString(enum_field_types type) +{ + switch (type) + { + case MYSQL_TYPE_BIT: return "BIT"; + case MYSQL_TYPE_BLOB: return "BLOB"; + case MYSQL_TYPE_DATE: return "DATE"; + case MYSQL_TYPE_DATETIME: return "DATETIME"; + case MYSQL_TYPE_NEWDECIMAL: return "NEWDECIMAL"; + case MYSQL_TYPE_DECIMAL: return "DECIMAL"; + case MYSQL_TYPE_DOUBLE: return "DOUBLE"; + case MYSQL_TYPE_ENUM: return "ENUM"; + case MYSQL_TYPE_FLOAT: return "FLOAT"; + case MYSQL_TYPE_GEOMETRY: return "GEOMETRY"; + case MYSQL_TYPE_INT24: return "INT24"; + case MYSQL_TYPE_LONG: return "LONG"; + case MYSQL_TYPE_LONGLONG: return "LONGLONG"; + case MYSQL_TYPE_LONG_BLOB: return "LONG_BLOB"; + case MYSQL_TYPE_MEDIUM_BLOB: return "MEDIUM_BLOB"; + case MYSQL_TYPE_NEWDATE: return "NEWDATE"; + case MYSQL_TYPE_NULL: return "NULL"; + case MYSQL_TYPE_SET: return "SET"; + case MYSQL_TYPE_SHORT: return "SHORT"; + case MYSQL_TYPE_STRING: return "STRING"; + case MYSQL_TYPE_TIME: return "TIME"; + case MYSQL_TYPE_TIMESTAMP: return "TIMESTAMP"; + case MYSQL_TYPE_TINY: return "TINY"; + case MYSQL_TYPE_TINY_BLOB: return "TINY_BLOB"; + case MYSQL_TYPE_VAR_STRING: return "VAR_STRING"; + case MYSQL_TYPE_YEAR: return "YEAR"; + default: return "-Unknown-"; + } +} + +void Field::SetMetadata(MYSQL_FIELD* field, uint32 fieldIndex) +{ + meta.TableName = field->org_table; + meta.TableAlias = field->table; + meta.Name = field->org_name; + meta.Alias = field->name; + meta.Type = FieldTypeToString(field->type); + meta.Index = fieldIndex; +} +#endif diff --git a/src/server/database/Database/Field.h b/src/server/database/Database/Field.h index e6ae8821b11..4c206540127 100644 --- a/src/server/database/Database/Field.h +++ b/src/server/database/Database/Field.h @@ -18,10 +18,23 @@ #ifndef _FIELD_H #define _FIELD_H -#include "Common.h" -#include "Log.h" +#include "Define.h" +#include "DatabaseEnvFwd.h" +#include -#include +enum class DatabaseFieldTypes : uint8 +{ + Null, + Int8, + Int16, + Int32, + Int64, + Float, + Double, + Decimal, + Date, + Binary +}; /** @class Field @@ -67,240 +80,26 @@ class TC_DATABASE_API Field return GetUInt8() == 1 ? true : false; } - uint8 GetUInt8() const - { - if (!data.value) - return 0; - - #ifdef TRINITY_DEBUG - if (!IsType(MYSQL_TYPE_TINY)) - { - TC_LOG_WARN("sql.sql", "Warning: GetUInt8() on non-tinyint field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return 0; - } - #endif - - if (data.raw) - return *reinterpret_cast(data.value); - return static_cast(strtoul((char*)data.value, nullptr, 10)); - } - - int8 GetInt8() const - { - if (!data.value) - return 0; - - #ifdef TRINITY_DEBUG - if (!IsType(MYSQL_TYPE_TINY)) - { - TC_LOG_WARN("sql.sql", "Warning: GetInt8() on non-tinyint field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return 0; - } - #endif - - if (data.raw) - return *reinterpret_cast(data.value); - return static_cast(strtol((char*)data.value, NULL, 10)); - } - - uint16 GetUInt16() const - { - if (!data.value) - return 0; - - #ifdef TRINITY_DEBUG - if (!IsType(MYSQL_TYPE_SHORT) && !IsType(MYSQL_TYPE_YEAR)) - { - TC_LOG_WARN("sql.sql", "Warning: GetUInt16() on non-smallint field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return 0; - } - #endif - - if (data.raw) - return *reinterpret_cast(data.value); - return static_cast(strtoul((char*)data.value, nullptr, 10)); - } - - int16 GetInt16() const - { - if (!data.value) - return 0; - - #ifdef TRINITY_DEBUG - if (!IsType(MYSQL_TYPE_SHORT) && !IsType(MYSQL_TYPE_YEAR)) - { - TC_LOG_WARN("sql.sql", "Warning: GetInt16() on non-smallint field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return 0; - } - #endif - - if (data.raw) - return *reinterpret_cast(data.value); - return static_cast(strtol((char*)data.value, NULL, 10)); - } - - uint32 GetUInt32() const - { - if (!data.value) - return 0; - - #ifdef TRINITY_DEBUG - if (!IsType(MYSQL_TYPE_INT24) && !IsType(MYSQL_TYPE_LONG)) - { - TC_LOG_WARN("sql.sql", "Warning: GetUInt32() on non-(medium)int field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return 0; - } - #endif - - if (data.raw) - return *reinterpret_cast(data.value); - return static_cast(strtoul((char*)data.value, nullptr, 10)); - } - - int32 GetInt32() const - { - if (!data.value) - return 0; - - #ifdef TRINITY_DEBUG - if (!IsType(MYSQL_TYPE_INT24) && !IsType(MYSQL_TYPE_LONG)) - { - TC_LOG_WARN("sql.sql", "Warning: GetInt32() on non-(medium)int field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return 0; - } - #endif - - if (data.raw) - return *reinterpret_cast(data.value); - return static_cast(strtol((char*)data.value, NULL, 10)); - } - - uint64 GetUInt64() const - { - if (!data.value) - return 0; - - #ifdef TRINITY_DEBUG - if (!IsType(MYSQL_TYPE_LONGLONG) && !IsType(MYSQL_TYPE_BIT)) - { - TC_LOG_WARN("sql.sql", "Warning: GetUInt64() on non-bigint field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return 0; - } - #endif - - if (data.raw) - return *reinterpret_cast(data.value); - return static_cast(strtoull((char*)data.value, nullptr, 10)); - } - - int64 GetInt64() const - { - if (!data.value) - return 0; - - #ifdef TRINITY_DEBUG - if (!IsType(MYSQL_TYPE_LONGLONG) && !IsType(MYSQL_TYPE_BIT)) - { - TC_LOG_WARN("sql.sql", "Warning: GetInt64() on non-bigint field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return 0; - } - #endif - - if (data.raw) - return *reinterpret_cast(data.value); - return static_cast(strtoll((char*)data.value, NULL, 10)); - } - - float GetFloat() const - { - if (!data.value) - return 0.0f; - - #ifdef TRINITY_DEBUG - if (!IsType(MYSQL_TYPE_FLOAT)) - { - TC_LOG_WARN("sql.sql", "Warning: GetFloat() on non-float field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return 0.0f; - } - #endif - - if (data.raw) - return *reinterpret_cast(data.value); - return static_cast(atof((char*)data.value)); - } - - double GetDouble() const - { - if (!data.value) - return 0.0f; - - #ifdef TRINITY_DEBUG - if (!IsType(MYSQL_TYPE_DOUBLE) && !IsType(MYSQL_TYPE_NEWDECIMAL)) - { - TC_LOG_WARN("sql.sql", "Warning: GetDouble() on non-double/non-decimal field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return 0.0f; - } - #endif - - if (data.raw && !IsType(MYSQL_TYPE_NEWDECIMAL)) - return *reinterpret_cast(data.value); - return static_cast(atof((char*)data.value)); - } - - char const* GetCString() const - { - if (!data.value) - return NULL; - - #ifdef TRINITY_DEBUG - if (IsNumeric()) - { - TC_LOG_WARN("sql.sql", "Error: GetCString() on numeric field %s.%s (%s.%s) at index %u. Using type: %s.", - meta.TableAlias, meta.Alias, meta.TableName, meta.Name, meta.Index, meta.Type); - return NULL; - } - #endif - return static_cast(data.value); - } - - std::string GetString() const - { - if (!data.value) - return ""; - - char const* string = GetCString(); - if (!string) - return ""; - - return std::string(string, data.length); - } - - std::vector GetBinary() const - { - std::vector result; - if (!data.value || !data.length) - return result; - - result.resize(data.length); - memcpy(result.data(), data.value, data.length); - return result; - } + uint8 GetUInt8() const; + int8 GetInt8() const; + uint16 GetUInt16() const; + int16 GetInt16() const; + uint32 GetUInt32() const; + int32 GetInt32() const; + uint64 GetUInt64() const; + int64 GetInt64() const; + float GetFloat() const; + double GetDouble() const; + char const* GetCString() const; + std::string GetString() const; + std::vector GetBinary() const; bool IsNull() const { - return data.value == NULL; + return data.value == nullptr; } + #ifdef TRINITY_DEBUG struct Metadata { char const* TableName; @@ -310,143 +109,38 @@ class TC_DATABASE_API Field char const* Type; uint32 Index; }; + #endif protected: #pragma pack(push, 1) struct { - uint32 length; // Length (prepared strings only) - void* value; // Actual data in memory - enum_field_types type; // Field type - bool raw; // Raw bytes? (Prepared statement or ad hoc) + uint32 length; // Length (prepared strings only) + void* value; // Actual data in memory + DatabaseFieldTypes type; // Field type + bool raw; // Raw bytes? (Prepared statement or ad hoc) } data; #pragma pack(pop) - void SetByteValue(void* newValue, enum_field_types newType, uint32 length); - void SetStructuredValue(char* newValue, enum_field_types newType, uint32 length); + void SetByteValue(void* newValue, DatabaseFieldTypes newType, uint32 length); + void SetStructuredValue(char* newValue, DatabaseFieldTypes newType, uint32 length); void CleanUp() { // Field does not own the data if fetched with prepared statement if (!data.raw) delete[] ((char*)data.value); - data.value = NULL; + data.value = nullptr; } - static uint32 SizeForType(MYSQL_FIELD* field) - { - switch (field->type) - { - case MYSQL_TYPE_NULL: - return 0; - case MYSQL_TYPE_TINY: - return 1; - case MYSQL_TYPE_YEAR: - case MYSQL_TYPE_SHORT: - return 2; - case MYSQL_TYPE_INT24: - case MYSQL_TYPE_LONG: - case MYSQL_TYPE_FLOAT: - return 4; - case MYSQL_TYPE_DOUBLE: - case MYSQL_TYPE_LONGLONG: - case MYSQL_TYPE_BIT: - return 8; + bool IsType(DatabaseFieldTypes type) const; - case MYSQL_TYPE_TIMESTAMP: - case MYSQL_TYPE_DATE: - case MYSQL_TYPE_TIME: - case MYSQL_TYPE_DATETIME: - return sizeof(MYSQL_TIME); - - case MYSQL_TYPE_TINY_BLOB: - case MYSQL_TYPE_MEDIUM_BLOB: - case MYSQL_TYPE_LONG_BLOB: - case MYSQL_TYPE_BLOB: - case MYSQL_TYPE_STRING: - case MYSQL_TYPE_VAR_STRING: - return field->max_length + 1; - - case MYSQL_TYPE_DECIMAL: - case MYSQL_TYPE_NEWDECIMAL: - return 64; - - case MYSQL_TYPE_GEOMETRY: - /* - Following types are not sent over the wire: - MYSQL_TYPE_ENUM: - MYSQL_TYPE_SET: - */ - default: - TC_LOG_WARN("sql.sql", "SQL::SizeForType(): invalid field type %u", uint32(field->type)); - return 0; - } - } - - bool IsType(enum_field_types type) const - { - return data.type == type; - } - - bool IsNumeric() const - { - return (data.type == MYSQL_TYPE_TINY || - data.type == MYSQL_TYPE_SHORT || - data.type == MYSQL_TYPE_INT24 || - data.type == MYSQL_TYPE_LONG || - data.type == MYSQL_TYPE_FLOAT || - data.type == MYSQL_TYPE_DOUBLE || - data.type == MYSQL_TYPE_LONGLONG ); - } + bool IsNumeric() const; private: #ifdef TRINITY_DEBUG - static char const* FieldTypeToString(enum_field_types type) - { - switch (type) - { - case MYSQL_TYPE_BIT: return "BIT"; - case MYSQL_TYPE_BLOB: return "BLOB"; - case MYSQL_TYPE_DATE: return "DATE"; - case MYSQL_TYPE_DATETIME: return "DATETIME"; - case MYSQL_TYPE_NEWDECIMAL: return "NEWDECIMAL"; - case MYSQL_TYPE_DECIMAL: return "DECIMAL"; - case MYSQL_TYPE_DOUBLE: return "DOUBLE"; - case MYSQL_TYPE_ENUM: return "ENUM"; - case MYSQL_TYPE_FLOAT: return "FLOAT"; - case MYSQL_TYPE_GEOMETRY: return "GEOMETRY"; - case MYSQL_TYPE_INT24: return "INT24"; - case MYSQL_TYPE_LONG: return "LONG"; - case MYSQL_TYPE_LONGLONG: return "LONGLONG"; - case MYSQL_TYPE_LONG_BLOB: return "LONG_BLOB"; - case MYSQL_TYPE_MEDIUM_BLOB: return "MEDIUM_BLOB"; - case MYSQL_TYPE_NEWDATE: return "NEWDATE"; - case MYSQL_TYPE_NULL: return "NULL"; - case MYSQL_TYPE_SET: return "SET"; - case MYSQL_TYPE_SHORT: return "SHORT"; - case MYSQL_TYPE_STRING: return "STRING"; - case MYSQL_TYPE_TIME: return "TIME"; - case MYSQL_TYPE_TIMESTAMP: return "TIMESTAMP"; - case MYSQL_TYPE_TINY: return "TINY"; - case MYSQL_TYPE_TINY_BLOB: return "TINY_BLOB"; - case MYSQL_TYPE_VAR_STRING: return "VAR_STRING"; - case MYSQL_TYPE_YEAR: return "YEAR"; - default: return "-Unknown-"; - } - } - - void SetMetadata(MYSQL_FIELD* field, uint32 fieldIndex) - { - meta.TableName = field->org_table; - meta.TableAlias = field->table; - meta.Name = field->org_name; - meta.Alias = field->name; - meta.Type = FieldTypeToString(field->type); - meta.Index = fieldIndex; - } - + void SetMetadata(MYSQL_FIELD* field, uint32 fieldIndex); Metadata meta; - #endif }; diff --git a/src/server/database/Database/Implementation/CharacterDatabase.cpp b/src/server/database/Database/Implementation/CharacterDatabase.cpp index 15e160f9f8b..195582690a9 100644 --- a/src/server/database/Database/Implementation/CharacterDatabase.cpp +++ b/src/server/database/Database/Implementation/CharacterDatabase.cpp @@ -16,6 +16,7 @@ */ #include "CharacterDatabase.h" +#include "PreparedStatement.h" void CharacterDatabaseConnection::DoPrepareStatements() { @@ -582,11 +583,11 @@ void CharacterDatabaseConnection::DoPrepareStatements() PrepareStatement(CHAR_DEL_GUILD_FINDER_GUILD_SETTINGS, "DELETE FROM guild_finder_guild_settings WHERE guildId = ?", CONNECTION_ASYNC); // Items that hold loot or money - PrepareStatement(CHAR_SEL_ITEMCONTAINER_ITEMS, "SELECT item_id, item_count, follow_rules, ffa, blocked, counted, under_threshold, needs_quest, rnd_prop, rnd_suffix FROM item_loot_items WHERE container_id = ?", CONNECTION_SYNCH); + PrepareStatement(CHAR_SEL_ITEMCONTAINER_ITEMS, "SELECT container_id, item_id, item_count, follow_rules, ffa, blocked, counted, under_threshold, needs_quest, rnd_prop, rnd_suffix FROM item_loot_items", CONNECTION_SYNCH); PrepareStatement(CHAR_DEL_ITEMCONTAINER_ITEMS, "DELETE FROM item_loot_items WHERE container_id = ?", CONNECTION_ASYNC); - PrepareStatement(CHAR_DEL_ITEMCONTAINER_ITEM, "DELETE FROM item_loot_items WHERE container_id = ? AND item_id = ?", CONNECTION_ASYNC); + PrepareStatement(CHAR_DEL_ITEMCONTAINER_ITEM, "DELETE FROM item_loot_items WHERE container_id = ? AND item_id = ? AND item_count = ?", CONNECTION_ASYNC); PrepareStatement(CHAR_INS_ITEMCONTAINER_ITEMS, "INSERT INTO item_loot_items (container_id, item_id, item_count, follow_rules, ffa, blocked, counted, under_threshold, needs_quest, rnd_prop, rnd_suffix) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); - PrepareStatement(CHAR_SEL_ITEMCONTAINER_MONEY, "SELECT money FROM item_loot_money WHERE container_id = ?", CONNECTION_SYNCH); + PrepareStatement(CHAR_SEL_ITEMCONTAINER_MONEY, "SELECT container_id, money FROM item_loot_money", CONNECTION_SYNCH); PrepareStatement(CHAR_DEL_ITEMCONTAINER_MONEY, "DELETE FROM item_loot_money WHERE container_id = ?", CONNECTION_ASYNC); PrepareStatement(CHAR_INS_ITEMCONTAINER_MONEY, "INSERT INTO item_loot_money (container_id, money) VALUES (?, ?)", CONNECTION_ASYNC); @@ -646,3 +647,15 @@ void CharacterDatabaseConnection::DoPrepareStatements() // DeserterTracker PrepareStatement(CHAR_INS_DESERTER_TRACK, "INSERT INTO battleground_deserters (guid, type, datetime) VALUES (?, ?, NOW())", CONNECTION_ASYNC); } + +CharacterDatabaseConnection::CharacterDatabaseConnection(MySQLConnectionInfo& connInfo) : MySQLConnection(connInfo) +{ +} + +CharacterDatabaseConnection::CharacterDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo) : MySQLConnection(q, connInfo) +{ +} + +CharacterDatabaseConnection::~CharacterDatabaseConnection() +{ +} diff --git a/src/server/database/Database/Implementation/CharacterDatabase.h b/src/server/database/Database/Implementation/CharacterDatabase.h index 2a414c08e87..c13d02ec456 100644 --- a/src/server/database/Database/Implementation/CharacterDatabase.h +++ b/src/server/database/Database/Implementation/CharacterDatabase.h @@ -18,10 +18,9 @@ #ifndef _CHARACTERDATABASE_H #define _CHARACTERDATABASE_H -#include "DatabaseWorkerPool.h" #include "MySQLConnection.h" -enum CharacterDatabaseStatements +enum CharacterDatabaseStatements : uint32 { /* Naming standard for defines: {DB}_{SEL/INS/UPD/DEL/REP}_{Summary of data changed} @@ -569,13 +568,12 @@ public: typedef CharacterDatabaseStatements Statements; //- Constructors for sync and async connections - CharacterDatabaseConnection(MySQLConnectionInfo& connInfo) : MySQLConnection(connInfo) { } - CharacterDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo) : MySQLConnection(q, connInfo) { } + CharacterDatabaseConnection(MySQLConnectionInfo& connInfo); + CharacterDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo); + ~CharacterDatabaseConnection(); //- Loads database type specific prepared statements void DoPrepareStatements() override; }; -typedef DatabaseWorkerPool CharacterDatabaseWorkerPool; - #endif diff --git a/src/server/database/Database/Implementation/LoginDatabase.cpp b/src/server/database/Database/Implementation/LoginDatabase.cpp index 0aed48ac91b..00baae69568 100644 --- a/src/server/database/Database/Implementation/LoginDatabase.cpp +++ b/src/server/database/Database/Implementation/LoginDatabase.cpp @@ -16,6 +16,7 @@ */ #include "LoginDatabase.h" +#include "PreparedStatement.h" void LoginDatabaseConnection::DoPrepareStatements() { @@ -66,7 +67,7 @@ void LoginDatabaseConnection::DoPrepareStatements() PrepareStatement(LOGIN_INS_REALM_CHARACTERS, "INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (?, ?, ?)", CONNECTION_ASYNC); PrepareStatement(LOGIN_SEL_SUM_REALM_CHARACTERS, "SELECT SUM(numchars) FROM realmcharacters WHERE acctid = ?", CONNECTION_ASYNC); PrepareStatement(LOGIN_INS_ACCOUNT, "INSERT INTO account(username, sha_pass_hash, reg_mail, email, joindate) VALUES(?, ?, ?, ?, NOW())", CONNECTION_SYNCH); - PrepareStatement(LOGIN_INS_REALM_CHARACTERS_INIT, "INSERT INTO realmcharacters (realmid, acctid, numchars) SELECT realmlist.id, account.id, 0 FROM realmlist, account LEFT JOIN realmcharacters ON acctid=account.id WHERE acctid IS NULL", CONNECTION_ASYNC); + PrepareStatement(LOGIN_INS_REALM_CHARACTERS_INIT, "INSERT INTO realmcharacters (realmid, acctid, numchars) SELECT realmlist.id, account.id, 0 FROM realmlist, account LEFT JOIN realmcharacters ON acctid = account.id WHERE acctid IS NULL", CONNECTION_ASYNC); PrepareStatement(LOGIN_UPD_EXPANSION, "UPDATE account SET expansion = ? WHERE id = ?", CONNECTION_ASYNC); PrepareStatement(LOGIN_UPD_ACCOUNT_LOCK, "UPDATE account SET locked = ? WHERE id = ?", CONNECTION_ASYNC); PrepareStatement(LOGIN_UPD_ACCOUNT_LOCK_CONTRY, "UPDATE account SET lock_country = ? WHERE id = ?", CONNECTION_ASYNC); @@ -93,7 +94,7 @@ void LoginDatabaseConnection::DoPrepareStatements() PrepareStatement(LOGIN_SEL_CHECK_PASSWORD_BY_NAME, "SELECT 1 FROM account WHERE username = ? AND sha_pass_hash = ?", CONNECTION_SYNCH); PrepareStatement(LOGIN_SEL_PINFO, "SELECT a.username, aa.gmlevel, a.email, a.reg_mail, a.last_ip, DATE_FORMAT(a.last_login, '%Y-%m-%d %T'), a.mutetime, a.mutereason, a.muteby, a.failed_logins, a.locked, a.OS FROM account a LEFT JOIN account_access aa ON (a.id = aa.id AND (aa.RealmID = ? OR aa.RealmID = -1)) WHERE a.id = ?", CONNECTION_SYNCH); PrepareStatement(LOGIN_SEL_PINFO_BANS, "SELECT unbandate, bandate = unbandate, bannedby, banreason FROM account_banned WHERE id = ? AND active ORDER BY bandate ASC LIMIT 1", CONNECTION_SYNCH); - PrepareStatement(LOGIN_SEL_GM_ACCOUNTS, "SELECT a.username, aa.gmlevel FROM account a, account_access aa WHERE a.id=aa.id AND aa.gmlevel >= ? AND (aa.realmid = -1 OR aa.realmid = ?)", CONNECTION_SYNCH); + PrepareStatement(LOGIN_SEL_GM_ACCOUNTS, "SELECT a.username, aa.gmlevel FROM account a, account_access aa WHERE a.id = aa.id AND aa.gmlevel >= ? AND (aa.realmid = -1 OR aa.realmid = ?)", CONNECTION_SYNCH); PrepareStatement(LOGIN_SEL_ACCOUNT_INFO, "SELECT a.username, a.last_ip, aa.gmlevel, a.expansion FROM account a LEFT JOIN account_access aa ON (a.id = aa.id) WHERE a.id = ?", CONNECTION_SYNCH); PrepareStatement(LOGIN_SEL_ACCOUNT_ACCESS_GMLEVEL_TEST, "SELECT 1 FROM account_access WHERE id = ? AND gmlevel > ?", CONNECTION_SYNCH); PrepareStatement(LOGIN_SEL_ACCOUNT_ACCESS, "SELECT a.id, aa.gmlevel, aa.RealmID FROM account a LEFT JOIN account_access aa ON (a.id = aa.id) WHERE a.username = ?", CONNECTION_SYNCH); @@ -149,3 +150,15 @@ void LoginDatabaseConnection::DoPrepareStatements() PrepareStatement(LOGIN_UPD_BNET_ACCOUNT_LOCK_CONTRY, "UPDATE battlenet_accounts SET lock_country = ? WHERE id = ?", CONNECTION_ASYNC); PrepareStatement(LOGIN_SEL_BNET_ACCOUNT_ID_BY_GAME_ACCOUNT, "SELECT battlenet_account FROM account WHERE id = ?", CONNECTION_SYNCH); } + +LoginDatabaseConnection::LoginDatabaseConnection(MySQLConnectionInfo& connInfo) : MySQLConnection(connInfo) +{ +} + +LoginDatabaseConnection::LoginDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo) : MySQLConnection(q, connInfo) +{ +} + +LoginDatabaseConnection::~LoginDatabaseConnection() +{ +} diff --git a/src/server/database/Database/Implementation/LoginDatabase.h b/src/server/database/Database/Implementation/LoginDatabase.h index bf9721b8c76..f5503684d74 100644 --- a/src/server/database/Database/Implementation/LoginDatabase.h +++ b/src/server/database/Database/Implementation/LoginDatabase.h @@ -18,10 +18,9 @@ #ifndef _LOGINDATABASE_H #define _LOGINDATABASE_H -#include "DatabaseWorkerPool.h" #include "MySQLConnection.h" -enum LoginDatabaseStatements +enum LoginDatabaseStatements : uint32 { /* Naming standard for defines: {DB}_{SEL/INS/UPD/DEL/REP}_{Summary of data changed} @@ -140,13 +139,12 @@ public: typedef LoginDatabaseStatements Statements; //- Constructors for sync and async connections - LoginDatabaseConnection(MySQLConnectionInfo& connInfo) : MySQLConnection(connInfo) { } - LoginDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo) : MySQLConnection(q, connInfo) { } + LoginDatabaseConnection(MySQLConnectionInfo& connInfo); + LoginDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo); + ~LoginDatabaseConnection(); //- Loads database type specific prepared statements void DoPrepareStatements() override; }; -typedef DatabaseWorkerPool LoginDatabaseWorkerPool; - #endif diff --git a/src/server/database/Database/Implementation/WorldDatabase.cpp b/src/server/database/Database/Implementation/WorldDatabase.cpp index c971297325c..2d41ffd0151 100644 --- a/src/server/database/Database/Implementation/WorldDatabase.cpp +++ b/src/server/database/Database/Implementation/WorldDatabase.cpp @@ -16,6 +16,7 @@ */ #include "WorldDatabase.h" +#include "PreparedStatement.h" void WorldDatabaseConnection::DoPrepareStatements() { @@ -92,3 +93,15 @@ void WorldDatabaseConnection::DoPrepareStatements() PrepareStatement(WORLD_UPD_CREATURE_ZONE_AREA_DATA, "UPDATE creature SET zoneId = ?, areaId = ? WHERE guid = ?", CONNECTION_ASYNC); PrepareStatement(WORLD_UPD_GAMEOBJECT_ZONE_AREA_DATA, "UPDATE gameobject SET zoneId = ?, areaId = ? WHERE guid = ?", CONNECTION_ASYNC); } + +WorldDatabaseConnection::WorldDatabaseConnection(MySQLConnectionInfo& connInfo) : MySQLConnection(connInfo) +{ +} + +WorldDatabaseConnection::WorldDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo) : MySQLConnection(q, connInfo) +{ +} + +WorldDatabaseConnection::~WorldDatabaseConnection() +{ +} diff --git a/src/server/database/Database/Implementation/WorldDatabase.h b/src/server/database/Database/Implementation/WorldDatabase.h index 3a0a488e0fa..84ff1f3e8c8 100644 --- a/src/server/database/Database/Implementation/WorldDatabase.h +++ b/src/server/database/Database/Implementation/WorldDatabase.h @@ -18,10 +18,9 @@ #ifndef _WORLDDATABASE_H #define _WORLDDATABASE_H -#include "DatabaseWorkerPool.h" #include "MySQLConnection.h" -enum WorldDatabaseStatements +enum WorldDatabaseStatements : uint32 { /* Naming standard for defines: {DB}_{SEL/INS/UPD/DEL/REP}_{Summary of data changed} @@ -109,13 +108,12 @@ public: typedef WorldDatabaseStatements Statements; //- Constructors for sync and async connections - WorldDatabaseConnection(MySQLConnectionInfo& connInfo) : MySQLConnection(connInfo) { } - WorldDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo) : MySQLConnection(q, connInfo) { } + WorldDatabaseConnection(MySQLConnectionInfo& connInfo); + WorldDatabaseConnection(ProducerConsumerQueue* q, MySQLConnectionInfo& connInfo); + ~WorldDatabaseConnection(); //- Loads database type specific prepared statements void DoPrepareStatements() override; }; -typedef DatabaseWorkerPool WorldDatabaseWorkerPool; - #endif diff --git a/src/server/database/Database/MySQLConnection.cpp b/src/server/database/Database/MySQLConnection.cpp index 8451ca23815..b4cdd4a91b9 100644 --- a/src/server/database/Database/MySQLConnection.cpp +++ b/src/server/database/Database/MySQLConnection.cpp @@ -16,28 +16,41 @@ */ +#include "MySQLConnection.h" #include "Common.h" - -#ifdef _WIN32 - #include +#include "DatabaseWorker.h" +#include "Log.h" +#include "PreparedStatement.h" +#include "QueryResult.h" +#include "Timer.h" +#include "Transaction.h" +#include "Util.h" +#include +#ifdef _WIN32 // hack for broken mysql.h not including the correct winsock header for SOCKET definition, fixed in 5.7 +#include #endif #include -#include +#include -#include "MySQLConnection.h" -#include "QueryResult.h" -#include "SQLOperation.h" -#include "PreparedStatement.h" -#include "DatabaseWorker.h" -#include "Timer.h" -#include "Log.h" -#include "ProducerConsumerQueue.h" +MySQLConnectionInfo::MySQLConnectionInfo(std::string const& infoString) +{ + Tokenizer tokens(infoString, ';'); + if (tokens.size() != 5) + return; + + uint8 i = 0; + host.assign(tokens[i++]); + port_or_socket.assign(tokens[i++]); + user.assign(tokens[i++]); + password.assign(tokens[i++]); + database.assign(tokens[i++]); +} MySQLConnection::MySQLConnection(MySQLConnectionInfo& connInfo) : m_reconnecting(false), m_prepareError(false), -m_queue(NULL), -m_Mysql(NULL), +m_queue(nullptr), +m_Mysql(nullptr), m_connectionInfo(connInfo), m_connectionFlags(CONNECTION_SYNCH) { } @@ -45,7 +58,7 @@ MySQLConnection::MySQLConnection(ProducerConsumerQueue* queue, My m_reconnecting(false), m_prepareError(false), m_queue(queue), -m_Mysql(NULL), +m_Mysql(nullptr), m_connectionInfo(connInfo), m_connectionFlags(CONNECTION_ASYNC) { @@ -74,7 +87,7 @@ void MySQLConnection::Close() uint32 MySQLConnection::Open() { MYSQL *mysqlInit; - mysqlInit = mysql_init(NULL); + mysqlInit = mysql_init(nullptr); if (!mysqlInit) { TC_LOG_ERROR("sql.sql", "Could not initialize Mysql connection to database `%s`", m_connectionInfo.database.c_str()); @@ -152,7 +165,7 @@ bool MySQLConnection::PrepareStatements() return !m_prepareError; } -bool MySQLConnection::Execute(const char* sql) +bool MySQLConnection::Execute(char const* sql) { if (!m_Mysql) return false; @@ -281,18 +294,18 @@ bool MySQLConnection::_Query(PreparedStatement* stmt, MYSQL_RES **pResult, uint6 return true; } -ResultSet* MySQLConnection::Query(const char* sql) +ResultSet* MySQLConnection::Query(char const* sql) { if (!sql) - return NULL; + return nullptr; - MYSQL_RES *result = NULL; - MYSQL_FIELD *fields = NULL; + MYSQL_RES *result = nullptr; + MYSQL_FIELD *fields = nullptr; uint64 rowCount = 0; uint32 fieldCount = 0; if (!_Query(sql, &result, &fields, &rowCount, &fieldCount)) - return NULL; + return nullptr; return new ResultSet(result, fields, rowCount, fieldCount); } @@ -355,14 +368,13 @@ void MySQLConnection::CommitTransaction() int MySQLConnection::ExecuteTransaction(SQLTransaction& transaction) { - std::list const& queries = transaction->m_queries; + std::vector const& queries = transaction->m_queries; if (queries.empty()) return -1; BeginTransaction(); - std::list::const_iterator itr; - for (itr = queries.begin(); itr != queries.end(); ++itr) + for (auto itr = queries.begin(); itr != queries.end(); ++itr) { SQLElementData const& data = *itr; switch (itr->type) @@ -378,11 +390,11 @@ int MySQLConnection::ExecuteTransaction(SQLTransaction& transaction) RollbackTransaction(); return errorCode; } + break; } - break; case SQL_ELEMENT_RAW: { - const char* sql = data.element.query; + char const* sql = data.element.query; ASSERT(sql); if (!Execute(sql)) { @@ -391,8 +403,8 @@ int MySQLConnection::ExecuteTransaction(SQLTransaction& transaction) RollbackTransaction(); return errorCode; } + break; } - break; } } @@ -405,6 +417,26 @@ int MySQLConnection::ExecuteTransaction(SQLTransaction& transaction) return 0; } +void MySQLConnection::Ping() +{ + mysql_ping(m_Mysql); +} + +uint32 MySQLConnection::GetLastError() +{ + return mysql_errno(m_Mysql); +} + +bool MySQLConnection::LockIfReady() +{ + return m_Mutex.try_lock(); +} + +void MySQLConnection::Unlock() +{ + m_Mutex.unlock(); +} + MySQLPreparedStatement* MySQLConnection::GetPreparedStatement(uint32 index) { ASSERT(index < m_stmts.size()); @@ -450,12 +482,12 @@ void MySQLConnection::PrepareStatement(uint32 index, std::string const& sql, Con PreparedResultSet* MySQLConnection::Query(PreparedStatement* stmt) { - MYSQL_RES *result = NULL; + MYSQL_RES *result = nullptr; uint64 rowCount = 0; uint32 fieldCount = 0; if (!_Query(stmt, &result, &rowCount, &fieldCount)) - return NULL; + return nullptr; if (mysql_more_results(m_Mysql)) { diff --git a/src/server/database/Database/MySQLConnection.h b/src/server/database/Database/MySQLConnection.h index ff9b29dcd03..d5a6f8babbd 100644 --- a/src/server/database/Database/MySQLConnection.h +++ b/src/server/database/Database/MySQLConnection.h @@ -15,18 +15,23 @@ * with this program. If not, see . */ -#include "DatabaseWorkerPool.h" -#include "Transaction.h" -#include "Util.h" -#include "ProducerConsumerQueue.h" - #ifndef _MYSQLCONNECTION_H #define _MYSQLCONNECTION_H +#include "Define.h" +#include "DatabaseEnvFwd.h" +#include +#include +#include +#include +#include + +template +class ProducerConsumerQueue; + class DatabaseWorker; -class PreparedStatement; class MySQLPreparedStatement; -class PingOperation; +class SQLOperation; enum ConnectionFlags { @@ -37,21 +42,7 @@ enum ConnectionFlags struct TC_DATABASE_API MySQLConnectionInfo { - explicit MySQLConnectionInfo(std::string const& infoString) - { - Tokenizer tokens(infoString, ';'); - - if (tokens.size() != 5) - return; - - uint8 i = 0; - - host.assign(tokens[i++]); - port_or_socket.assign(tokens[i++]); - user.assign(tokens[i++]); - password.assign(tokens[i++]); - database.assign(tokens[i++]); - } + explicit MySQLConnectionInfo(std::string const& infoString); std::string user; std::string password; @@ -76,36 +67,29 @@ class TC_DATABASE_API MySQLConnection bool PrepareStatements(); public: - bool Execute(const char* sql); + bool Execute(char const* sql); bool Execute(PreparedStatement* stmt); - ResultSet* Query(const char* sql); + ResultSet* Query(char const* sql); PreparedResultSet* Query(PreparedStatement* stmt); - bool _Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount); - bool _Query(PreparedStatement* stmt, MYSQL_RES **pResult, uint64* pRowCount, uint32* pFieldCount); + bool _Query(char const* sql, MYSQL_RES** pResult, MYSQL_FIELD** pFields, uint64* pRowCount, uint32* pFieldCount); + bool _Query(PreparedStatement* stmt, MYSQL_RES** pResult, uint64* pRowCount, uint32* pFieldCount); void BeginTransaction(); void RollbackTransaction(); void CommitTransaction(); int ExecuteTransaction(SQLTransaction& transaction); - operator bool () const { return m_Mysql != NULL; } - void Ping() { mysql_ping(m_Mysql); } + void Ping(); - uint32 GetLastError() { return mysql_errno(m_Mysql); } + uint32 GetLastError(); protected: - bool LockIfReady() - { - /// Tries to acquire lock. If lock is acquired by another thread - /// the calling parent will just try another connection - return m_Mutex.try_lock(); - } + /// Tries to acquire lock. If lock is acquired by another thread + /// the calling parent will just try another connection + bool LockIfReady(); - void Unlock() - { - /// Called by parent databasepool. Will let other threads access this connection - m_Mutex.unlock(); - } + /// Called by parent databasepool. Will let other threads access this connection + void Unlock(); MYSQL* GetHandle() { return m_Mysql; } MySQLPreparedStatement* GetPreparedStatement(uint32 index); diff --git a/src/server/database/Database/MySQLThreading.cpp b/src/server/database/Database/MySQLThreading.cpp new file mode 100644 index 00000000000..85183c4a0f9 --- /dev/null +++ b/src/server/database/Database/MySQLThreading.cpp @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#include "MySQLThreading.h" +#ifdef _WIN32 // hack for broken mysql.h not including the correct winsock header for SOCKET definition, fixed in 5.7 +#include +#endif +#include + +void MySQL::Library_Init() +{ + mysql_library_init(-1, nullptr, nullptr); +} + +void MySQL::Library_End() +{ + mysql_library_end(); +} diff --git a/src/server/database/Database/MySQLThreading.h b/src/server/database/Database/MySQLThreading.h index 1e46c7ffd5f..170153eb9c3 100644 --- a/src/server/database/Database/MySQLThreading.h +++ b/src/server/database/Database/MySQLThreading.h @@ -18,20 +18,12 @@ #ifndef _MYSQLTHREADING_H #define _MYSQLTHREADING_H -#include "Log.h" +#include "Define.h" -class TC_DATABASE_API MySQL +namespace MySQL { - public: - static void Library_Init() - { - mysql_library_init(-1, NULL, NULL); - } - - static void Library_End() - { - mysql_library_end(); - } -}; + void TC_DATABASE_API Library_Init(); + void TC_DATABASE_API Library_End(); +} #endif diff --git a/src/server/database/Database/PreparedStatement.cpp b/src/server/database/Database/PreparedStatement.cpp index f1bfa10130d..644f9d0f65c 100644 --- a/src/server/database/Database/PreparedStatement.cpp +++ b/src/server/database/Database/PreparedStatement.cpp @@ -16,8 +16,15 @@ */ #include "PreparedStatement.h" +#include "Errors.h" #include "MySQLConnection.h" +#include "QueryResult.h" #include "Log.h" +#ifdef _WIN32 // hack for broken mysql.h not including the correct winsock header for SOCKET definition, fixed in 5.7 +#include +#endif +#include +#include PreparedStatement::PreparedStatement(uint32 index, uint8 capacity) : m_stmt(nullptr), m_index(index), statement_data(capacity) { } @@ -214,9 +221,9 @@ void MySQLPreparedStatement::ClearParameters() for (uint32 i=0; i < m_paramCount; ++i) { delete m_bind[i].length; - m_bind[i].length = NULL; + m_bind[i].length = nullptr; delete[] (char*) m_bind[i].buffer; - m_bind[i].buffer = NULL; + m_bind[i].buffer = nullptr; m_paramsSet[i] = false; } } @@ -227,6 +234,19 @@ static bool ParamenterIndexAssertFail(uint32 stmtIndex, uint8 index, uint32 para return false; } +static void SetParameterValue(MYSQL_BIND* param, enum_field_types type, void const* value, uint32 len, bool isUnsigned) +{ + param->buffer_type = type; + delete[] static_cast(param->buffer); + param->buffer = new char[len]; + param->buffer_length = 0; + param->is_null_value = 0; + param->length = nullptr; // Only != NULL for strings + param->is_unsigned = isUnsigned; + + memcpy(param->buffer, value, len); +} + //- Bind on mysql level void MySQLPreparedStatement::AssertValidIndex(uint8 index) { @@ -236,99 +256,113 @@ void MySQLPreparedStatement::AssertValidIndex(uint8 index) TC_LOG_ERROR("sql.sql", "[ERROR] Prepared Statement (id: %u) trying to bind value on already bound index (%u).", m_stmt->m_index, index); } -void MySQLPreparedStatement::setBool(const uint8 index, const bool value) +void MySQLPreparedStatement::setNull(uint8 index) +{ + AssertValidIndex(index); + m_paramsSet[index] = true; + MYSQL_BIND* param = &m_bind[index]; + param->buffer_type = MYSQL_TYPE_NULL; + delete[] static_cast(param->buffer); + param->buffer = nullptr; + param->buffer_length = 0; + param->is_null_value = 1; + delete param->length; + param->length = nullptr; +} + +void MySQLPreparedStatement::setBool(uint8 index, bool value) { setUInt8(index, value ? 1 : 0); } -void MySQLPreparedStatement::setUInt8(const uint8 index, const uint8 value) +void MySQLPreparedStatement::setUInt8(uint8 index, uint8 value) { AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - setValue(param, MYSQL_TYPE_TINY, &value, sizeof(uint8), true); + SetParameterValue(param, MYSQL_TYPE_TINY, &value, sizeof(uint8), true); } -void MySQLPreparedStatement::setUInt16(const uint8 index, const uint16 value) +void MySQLPreparedStatement::setUInt16(uint8 index, uint16 value) { AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - setValue(param, MYSQL_TYPE_SHORT, &value, sizeof(uint16), true); + SetParameterValue(param, MYSQL_TYPE_SHORT, &value, sizeof(uint16), true); } -void MySQLPreparedStatement::setUInt32(const uint8 index, const uint32 value) +void MySQLPreparedStatement::setUInt32(uint8 index, uint32 value) { AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - setValue(param, MYSQL_TYPE_LONG, &value, sizeof(uint32), true); + SetParameterValue(param, MYSQL_TYPE_LONG, &value, sizeof(uint32), true); } -void MySQLPreparedStatement::setUInt64(const uint8 index, const uint64 value) +void MySQLPreparedStatement::setUInt64(uint8 index, uint64 value) { AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - setValue(param, MYSQL_TYPE_LONGLONG, &value, sizeof(uint64), true); + SetParameterValue(param, MYSQL_TYPE_LONGLONG, &value, sizeof(uint64), true); } -void MySQLPreparedStatement::setInt8(const uint8 index, const int8 value) +void MySQLPreparedStatement::setInt8(uint8 index, int8 value) { AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - setValue(param, MYSQL_TYPE_TINY, &value, sizeof(int8), false); + SetParameterValue(param, MYSQL_TYPE_TINY, &value, sizeof(int8), false); } -void MySQLPreparedStatement::setInt16(const uint8 index, const int16 value) +void MySQLPreparedStatement::setInt16(uint8 index, int16 value) { AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - setValue(param, MYSQL_TYPE_SHORT, &value, sizeof(int16), false); + SetParameterValue(param, MYSQL_TYPE_SHORT, &value, sizeof(int16), false); } -void MySQLPreparedStatement::setInt32(const uint8 index, const int32 value) +void MySQLPreparedStatement::setInt32(uint8 index, int32 value) { AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - setValue(param, MYSQL_TYPE_LONG, &value, sizeof(int32), false); + SetParameterValue(param, MYSQL_TYPE_LONG, &value, sizeof(int32), false); } -void MySQLPreparedStatement::setInt64(const uint8 index, const int64 value) +void MySQLPreparedStatement::setInt64(uint8 index, int64 value) { AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - setValue(param, MYSQL_TYPE_LONGLONG, &value, sizeof(int64), false); + SetParameterValue(param, MYSQL_TYPE_LONGLONG, &value, sizeof(int64), false); } -void MySQLPreparedStatement::setFloat(const uint8 index, const float value) +void MySQLPreparedStatement::setFloat(uint8 index, float value) { AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - setValue(param, MYSQL_TYPE_FLOAT, &value, sizeof(float), (value > 0.0f)); + SetParameterValue(param, MYSQL_TYPE_FLOAT, &value, sizeof(float), (value > 0.0f)); } -void MySQLPreparedStatement::setDouble(const uint8 index, const double value) +void MySQLPreparedStatement::setDouble(uint8 index, double value) { AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; - setValue(param, MYSQL_TYPE_DOUBLE, &value, sizeof(double), (value > 0.0f)); + SetParameterValue(param, MYSQL_TYPE_DOUBLE, &value, sizeof(double), (value > 0.0f)); } -void MySQLPreparedStatement::setBinary(const uint8 index, const std::vector& value, bool isString) +void MySQLPreparedStatement::setBinary(uint8 index, std::vector const& value, bool isString) { AssertValidIndex(index); m_paramsSet[index] = true; MYSQL_BIND* param = &m_bind[index]; uint32 len = uint32(value.size()); param->buffer_type = MYSQL_TYPE_BLOB; - delete [] static_cast(param->buffer); + delete [] static_cast(param->buffer); param->buffer = new char[len]; param->buffer_length = len; param->is_null_value = 0; @@ -343,33 +377,6 @@ void MySQLPreparedStatement::setBinary(const uint8 index, const std::vectorbuffer, value.data(), len); } -void MySQLPreparedStatement::setNull(const uint8 index) -{ - AssertValidIndex(index); - m_paramsSet[index] = true; - MYSQL_BIND* param = &m_bind[index]; - param->buffer_type = MYSQL_TYPE_NULL; - delete [] static_cast(param->buffer); - param->buffer = NULL; - param->buffer_length = 0; - param->is_null_value = 1; - delete param->length; - param->length = NULL; -} - -void MySQLPreparedStatement::setValue(MYSQL_BIND* param, enum_field_types type, const void* value, uint32 len, bool isUnsigned) -{ - param->buffer_type = type; - delete [] static_cast(param->buffer); - param->buffer = new char[len]; - param->buffer_length = 0; - param->is_null_value = 0; - param->length = NULL; // Only != NULL for strings - param->is_unsigned = isUnsigned; - - memcpy(param->buffer, value, len); -} - std::string MySQLPreparedStatement::getQueryString() const { std::string queryString(m_queryString); @@ -422,7 +429,7 @@ std::string MySQLPreparedStatement::getQueryString() const ss << "BINARY"; break; case TYPE_NULL: - ss << "NULL"; + ss << "nullptr"; break; } @@ -458,7 +465,7 @@ bool PreparedStatementTask::Execute() if (!result || !result->GetRowCount()) { delete result; - m_result->set_value(PreparedQueryResult(NULL)); + m_result->set_value(PreparedQueryResult(nullptr)); return false; } m_result->set_value(PreparedQueryResult(result)); diff --git a/src/server/database/Database/PreparedStatement.h b/src/server/database/Database/PreparedStatement.h index 5f740daa4d9..ff3f917de72 100644 --- a/src/server/database/Database/PreparedStatement.h +++ b/src/server/database/Database/PreparedStatement.h @@ -18,8 +18,10 @@ #ifndef _PREPAREDSTATEMENT_H #define _PREPAREDSTATEMENT_H -#include +#include "Define.h" #include "SQLOperation.h" +#include +#include #ifdef __APPLE__ #undef TYPE_BOOL @@ -81,20 +83,20 @@ class TC_DATABASE_API PreparedStatement PreparedStatement(uint32 index, uint8 capacity); ~PreparedStatement(); - void setBool(const uint8 index, const bool value); - void setUInt8(const uint8 index, const uint8 value); - void setUInt16(const uint8 index, const uint16 value); - void setUInt32(const uint8 index, const uint32 value); - void setUInt64(const uint8 index, const uint64 value); - void setInt8(const uint8 index, const int8 value); - void setInt16(const uint8 index, const int16 value); - void setInt32(const uint8 index, const int32 value); - void setInt64(const uint8 index, const int64 value); - void setFloat(const uint8 index, const float value); - void setDouble(const uint8 index, const double value); - void setString(const uint8 index, const std::string& value); - void setBinary(const uint8 index, const std::vector& value); - void setNull(const uint8 index); + void setNull(uint8 index); + void setBool(uint8 index, bool value); + void setUInt8(uint8 index, uint8 value); + void setUInt16(uint8 index, uint16 value); + void setUInt32(uint8 index, uint32 value); + void setUInt64(uint8 index, uint64 value); + void setInt8(uint8 index, int8 value); + void setInt16(uint8 index, int16 value); + void setInt32(uint8 index, int32 value); + void setInt64(uint8 index, int64 value); + void setFloat(uint8 index, float value); + void setDouble(uint8 index, double value); + void setString(uint8 index, std::string const& value); + void setBinary(uint8 index, std::vector const& value); protected: void BindParameters(MySQLPreparedStatement* stmt); @@ -122,19 +124,19 @@ class TC_DATABASE_API MySQLPreparedStatement MySQLPreparedStatement(MYSQL_STMT* stmt, std::string queryString); ~MySQLPreparedStatement(); - void setBool(const uint8 index, const bool value); - void setUInt8(const uint8 index, const uint8 value); - void setUInt16(const uint8 index, const uint16 value); - void setUInt32(const uint8 index, const uint32 value); - void setUInt64(const uint8 index, const uint64 value); - void setInt8(const uint8 index, const int8 value); - void setInt16(const uint8 index, const int16 value); - void setInt32(const uint8 index, const int32 value); - void setInt64(const uint8 index, const int64 value); - void setFloat(const uint8 index, const float value); - void setDouble(const uint8 index, const double value); - void setBinary(const uint8 index, const std::vector& value, bool isString); - void setNull(const uint8 index); + void setNull(uint8 index); + void setBool(uint8 index, bool value); + void setUInt8(uint8 index, uint8 value); + void setUInt16(uint8 index, uint16 value); + void setUInt32(uint8 index, uint32 value); + void setUInt64(uint8 index, uint64 value); + void setInt8(uint8 index, int8 value); + void setInt16(uint8 index, int16 value); + void setInt32(uint8 index, int32 value); + void setInt64(uint8 index, int64 value); + void setFloat(uint8 index, float value); + void setDouble(uint8 index, double value); + void setBinary(uint8 index, std::vector const& value, bool isString); uint32 GetParameterCount() const { return m_paramCount; } @@ -146,9 +148,6 @@ class TC_DATABASE_API MySQLPreparedStatement void AssertValidIndex(uint8 index); std::string getQueryString() const; - private: - void setValue(MYSQL_BIND* param, enum_field_types type, const void* value, uint32 len, bool isUnsigned); - private: MYSQL_STMT* m_Mstmt; uint32 m_paramCount; @@ -160,9 +159,6 @@ class TC_DATABASE_API MySQLPreparedStatement MySQLPreparedStatement& operator=(MySQLPreparedStatement const& right) = delete; }; -typedef std::future PreparedQueryResultFuture; -typedef std::promise PreparedQueryResultPromise; - //- Lower-level class, enqueuable operation class TC_DATABASE_API PreparedStatementTask : public SQLOperation { diff --git a/src/server/database/Database/QueryCallback.cpp b/src/server/database/Database/QueryCallback.cpp index d7b3332e95b..fecae0efb57 100644 --- a/src/server/database/Database/QueryCallback.cpp +++ b/src/server/database/Database/QueryCallback.cpp @@ -16,6 +16,7 @@ */ #include "QueryCallback.h" +#include "Errors.h" template inline void Construct(T& t, Args&&... args) @@ -30,7 +31,7 @@ inline void Destroy(T& t) } template -void ConstructActiveMember(T* obj) +inline void ConstructActiveMember(T* obj) { if (!obj->_isPrepared) Construct(obj->_string); @@ -39,7 +40,7 @@ void ConstructActiveMember(T* obj) } template -void DestroyActiveMember(T* obj) +inline void DestroyActiveMember(T* obj) { if (!obj->_isPrepared) Destroy(obj->_string); @@ -48,7 +49,7 @@ void DestroyActiveMember(T* obj) } template -void MoveFrom(T* to, T&& from) +inline void MoveFrom(T* to, T&& from) { ASSERT(to->_isPrepared == from._isPrepared); @@ -199,7 +200,7 @@ QueryCallback::Status QueryCallback::InvokeIfReady() { if (_string.valid() && _string.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { - std::future f(std::move(_string)); + QueryResultFuture f(std::move(_string)); std::function cb(std::move(callback._string)); cb(*this, f.get()); return checkStateAndReturnCompletion(); @@ -209,7 +210,7 @@ QueryCallback::Status QueryCallback::InvokeIfReady() { if (_prepared.valid() && _prepared.wait_for(std::chrono::seconds(0)) == std::future_status::ready) { - std::future f(std::move(_prepared)); + PreparedQueryResultFuture f(std::move(_prepared)); std::function cb(std::move(callback._prepared)); cb(*this, f.get()); return checkStateAndReturnCompletion(); diff --git a/src/server/database/Database/QueryCallback.h b/src/server/database/Database/QueryCallback.h index bf167a2ce23..9d04e3ca9ab 100644 --- a/src/server/database/Database/QueryCallback.h +++ b/src/server/database/Database/QueryCallback.h @@ -18,14 +18,19 @@ #ifndef _QUERY_CALLBACK_H #define _QUERY_CALLBACK_H -#include "QueryResult.h" +#include "Define.h" +#include "DatabaseEnvFwd.h" +#include #include +#include +#include +#include class TC_DATABASE_API QueryCallback { public: - explicit QueryCallback(std::future&& result); - explicit QueryCallback(std::future&& result); + explicit QueryCallback(QueryResultFuture&& result); + explicit QueryCallback(PreparedQueryResultFuture&& result); QueryCallback(QueryCallback&& right); QueryCallback& operator=(QueryCallback&& right); ~QueryCallback(); @@ -58,8 +63,8 @@ private: union { - std::future _string; - std::future _prepared; + QueryResultFuture _string; + PreparedQueryResultFuture _prepared; }; bool _isPrepared; diff --git a/src/server/database/Database/QueryHolder.cpp b/src/server/database/Database/QueryHolder.cpp index 0498c67a89f..1869d6f9ce6 100644 --- a/src/server/database/Database/QueryHolder.cpp +++ b/src/server/database/Database/QueryHolder.cpp @@ -19,26 +19,7 @@ #include "QueryHolder.h" #include "PreparedStatement.h" #include "Log.h" - -bool SQLQueryHolder::SetQuery(size_t index, const char *sql) -{ - if (m_queries.size() <= index) - { - TC_LOG_ERROR("sql.sql", "Query index (%u) out of range (size: %u) for query: %s", uint32(index), (uint32)m_queries.size(), sql); - return false; - } - - /// not executed yet, just stored (it's not called a holder for nothing) - SQLElementData element; - element.type = SQL_ELEMENT_RAW; - element.element.query = strdup(sql); - - SQLResultSetUnion result; - result.qresult = NULL; - - m_queries[index] = SQLResultPair(element, result); - return true; -} +#include "QueryResult.h" bool SQLQueryHolder::SetPreparedQuery(size_t index, PreparedStatement* stmt) { @@ -48,59 +29,17 @@ bool SQLQueryHolder::SetPreparedQuery(size_t index, PreparedStatement* stmt) return false; } - /// not executed yet, just stored (it's not called a holder for nothing) - SQLElementData element; - element.type = SQL_ELEMENT_PREPARED; - element.element.stmt = stmt; - - SQLResultSetUnion result; - result.presult = NULL; - - m_queries[index] = SQLResultPair(element, result); + m_queries[index].first = stmt; return true; } -QueryResult SQLQueryHolder::GetResult(size_t index) -{ - // Don't call to this function if the index is of an ad-hoc statement - if (index < m_queries.size()) - { - ResultSet* result = m_queries[index].second.qresult; - if (!result || !result->GetRowCount() || !result->NextRow()) - return QueryResult(NULL); - - return QueryResult(result); - } - else - return QueryResult(NULL); -} - PreparedQueryResult SQLQueryHolder::GetPreparedResult(size_t index) { // Don't call to this function if the index is of a prepared statement if (index < m_queries.size()) - { - PreparedResultSet* result = m_queries[index].second.presult; - if (!result || !result->GetRowCount()) - return PreparedQueryResult(NULL); - - return PreparedQueryResult(result); - } + return m_queries[index].second; else - return PreparedQueryResult(NULL); -} - -void SQLQueryHolder::SetResult(size_t index, ResultSet* result) -{ - if (result && !result->GetRowCount()) - { - delete result; - result = NULL; - } - - /// store the result in the holder - if (index < m_queries.size()) - m_queries[index].second.qresult = result; + return PreparedQueryResult(nullptr); } void SQLQueryHolder::SetPreparedResult(size_t index, PreparedResultSet* result) @@ -108,12 +47,12 @@ void SQLQueryHolder::SetPreparedResult(size_t index, PreparedResultSet* result) if (result && !result->GetRowCount()) { delete result; - result = NULL; + result = nullptr; } /// store the result in the holder if (index < m_queries.size()) - m_queries[index].second.presult = result; + m_queries[index].second = PreparedQueryResult(result); } SQLQueryHolder::~SQLQueryHolder() @@ -122,18 +61,7 @@ SQLQueryHolder::~SQLQueryHolder() { /// if the result was never used, free the resources /// results used already (getresult called) are expected to be deleted - if (SQLElementData* data = &m_queries[i].first) - { - switch (data->type) - { - case SQL_ELEMENT_RAW: - free((void*)(const_cast(data->element.query))); - break; - case SQL_ELEMENT_PREPARED: - delete data->element.stmt; - break; - } - } + delete m_queries[i].first; } } @@ -156,33 +84,10 @@ bool SQLQueryHolderTask::Execute() if (!m_holder) return false; - /// we can do this, we are friends - std::vector &queries = m_holder->m_queries; - - for (size_t i = 0; i < queries.size(); i++) - { - /// execute all queries in the holder and pass the results - if (SQLElementData* data = &queries[i].first) - { - switch (data->type) - { - case SQL_ELEMENT_RAW: - { - char const* sql = data->element.query; - if (sql) - m_holder->SetResult(i, m_conn->Query(sql)); - break; - } - case SQL_ELEMENT_PREPARED: - { - PreparedStatement* stmt = data->element.stmt; - if (stmt) - m_holder->SetPreparedResult(i, m_conn->Query(stmt)); - break; - } - } - } - } + /// execute all queries in the holder and pass the results + for (size_t i = 0; i < m_holder->m_queries.size(); ++i) + if (PreparedStatement* stmt = m_holder->m_queries[i].first) + m_holder->SetPreparedResult(i, m_conn->Query(stmt)); m_result.set_value(m_holder); return true; diff --git a/src/server/database/Database/QueryHolder.h b/src/server/database/Database/QueryHolder.h index ffd7cc2bef4..6f65db5a0f1 100644 --- a/src/server/database/Database/QueryHolder.h +++ b/src/server/database/Database/QueryHolder.h @@ -18,34 +18,23 @@ #ifndef _QUERYHOLDER_H #define _QUERYHOLDER_H -#include +#include "SQLOperation.h" class TC_DATABASE_API SQLQueryHolder { friend class SQLQueryHolderTask; private: - typedef std::pair SQLResultPair; - std::vector m_queries; + std::vector> m_queries; + public: SQLQueryHolder() { } virtual ~SQLQueryHolder(); - bool SetQuery(size_t index, const char* sql); - template - bool SetPQuery(size_t index, Format&& sql, Args&&... args) - { - return SetQuery(index, Trinity::StringFormat(std::forward(sql), std::forward(args)...).c_str()); - } bool SetPreparedQuery(size_t index, PreparedStatement* stmt); void SetSize(size_t size); - QueryResult GetResult(size_t index); PreparedQueryResult GetPreparedResult(size_t index); - void SetResult(size_t index, ResultSet* result); void SetPreparedResult(size_t index, PreparedResultSet* result); }; -typedef std::future QueryResultHolderFuture; -typedef std::promise QueryResultHolderPromise; - class TC_DATABASE_API SQLQueryHolderTask : public SQLOperation { private: diff --git a/src/server/database/Database/QueryResult.cpp b/src/server/database/Database/QueryResult.cpp index c1aaf869e9b..d222f687dcd 100644 --- a/src/server/database/Database/QueryResult.cpp +++ b/src/server/database/Database/QueryResult.cpp @@ -16,8 +16,108 @@ * with this program. If not, see . */ -#include "DatabaseEnv.h" +#include "QueryResult.h" +#include "Errors.h" +#include "Field.h" #include "Log.h" +#ifdef _WIN32 // hack for broken mysql.h not including the correct winsock header for SOCKET definition, fixed in 5.7 +#include +#endif +#include + +static uint32 SizeForType(MYSQL_FIELD* field) +{ + switch (field->type) + { + case MYSQL_TYPE_NULL: + return 0; + case MYSQL_TYPE_TINY: + return 1; + case MYSQL_TYPE_YEAR: + case MYSQL_TYPE_SHORT: + return 2; + case MYSQL_TYPE_INT24: + case MYSQL_TYPE_LONG: + case MYSQL_TYPE_FLOAT: + return 4; + case MYSQL_TYPE_DOUBLE: + case MYSQL_TYPE_LONGLONG: + case MYSQL_TYPE_BIT: + return 8; + + case MYSQL_TYPE_TIMESTAMP: + case MYSQL_TYPE_DATE: + case MYSQL_TYPE_TIME: + case MYSQL_TYPE_DATETIME: + return sizeof(MYSQL_TIME); + + case MYSQL_TYPE_TINY_BLOB: + case MYSQL_TYPE_MEDIUM_BLOB: + case MYSQL_TYPE_LONG_BLOB: + case MYSQL_TYPE_BLOB: + case MYSQL_TYPE_STRING: + case MYSQL_TYPE_VAR_STRING: + return field->max_length + 1; + + case MYSQL_TYPE_DECIMAL: + case MYSQL_TYPE_NEWDECIMAL: + return 64; + + case MYSQL_TYPE_GEOMETRY: + /* + Following types are not sent over the wire: + MYSQL_TYPE_ENUM: + MYSQL_TYPE_SET: + */ + default: + TC_LOG_WARN("sql.sql", "SQL::SizeForType(): invalid field type %u", uint32(field->type)); + return 0; + } +} + +DatabaseFieldTypes MysqlTypeToFieldType(enum_field_types type) +{ + switch (type) + { + case MYSQL_TYPE_NULL: + return DatabaseFieldTypes::Null; + case MYSQL_TYPE_TINY: + return DatabaseFieldTypes::Int8; + case MYSQL_TYPE_YEAR: + case MYSQL_TYPE_SHORT: + return DatabaseFieldTypes::Int16; + case MYSQL_TYPE_INT24: + case MYSQL_TYPE_LONG: + return DatabaseFieldTypes::Int32; + case MYSQL_TYPE_LONGLONG: + case MYSQL_TYPE_BIT: + return DatabaseFieldTypes::Int64; + case MYSQL_TYPE_FLOAT: + return DatabaseFieldTypes::Float; + case MYSQL_TYPE_DOUBLE: + return DatabaseFieldTypes::Double; + case MYSQL_TYPE_DECIMAL: + case MYSQL_TYPE_NEWDECIMAL: + return DatabaseFieldTypes::Decimal; + case MYSQL_TYPE_TIMESTAMP: + case MYSQL_TYPE_DATE: + case MYSQL_TYPE_TIME: + case MYSQL_TYPE_DATETIME: + return DatabaseFieldTypes::Date; + case MYSQL_TYPE_TINY_BLOB: + case MYSQL_TYPE_MEDIUM_BLOB: + case MYSQL_TYPE_LONG_BLOB: + case MYSQL_TYPE_BLOB: + case MYSQL_TYPE_STRING: + case MYSQL_TYPE_VAR_STRING: + return DatabaseFieldTypes::Binary; + default: + TC_LOG_WARN("sql.sql", "MysqlTypeToFieldType(): invalid field type %u", uint32(type)); + break; + } + + return DatabaseFieldTypes::Null; +} ResultSet::ResultSet(MYSQL_RES *result, MYSQL_FIELD *fields, uint64 rowCount, uint32 fieldCount) : _rowCount(rowCount), @@ -36,11 +136,9 @@ PreparedResultSet::PreparedResultSet(MYSQL_STMT* stmt, MYSQL_RES *result, uint64 m_rowCount(rowCount), m_rowPosition(0), m_fieldCount(fieldCount), -m_rBind(NULL), +m_rBind(nullptr), m_stmt(stmt), -m_metadataResult(result), -m_isNull(NULL), -m_length(NULL) +m_metadataResult(result) { if (!m_metadataResult) return; @@ -52,8 +150,12 @@ m_length(NULL) } m_rBind = new MYSQL_BIND[m_fieldCount]; - m_isNull = new my_bool[m_fieldCount]; - m_length = new unsigned long[m_fieldCount]; + + //- for future readers wondering where the fuck this is freed - mysql_stmt_bind_result moves pointers to these + // from m_rBind to m_stmt->bind and it is later freed by the `if (m_stmt->bind_result_done)` block just above here + // MYSQL_STMT lifetime is equal to connection lifetime + my_bool* m_isNull = new my_bool[m_fieldCount]; + unsigned long* m_length = new unsigned long[m_fieldCount]; memset(m_isNull, 0, sizeof(my_bool) * m_fieldCount); memset(m_rBind, 0, sizeof(MYSQL_BIND) * m_fieldCount); @@ -76,14 +178,14 @@ m_length(NULL) std::size_t rowSize = 0; for (uint32 i = 0; i < m_fieldCount; ++i) { - uint32 size = Field::SizeForType(&field[i]); + uint32 size = SizeForType(&field[i]); rowSize += size; m_rBind[i].buffer_type = field[i].type; m_rBind[i].buffer_length = size; m_rBind[i].length = &m_length[i]; m_rBind[i].is_null = &m_isNull[i]; - m_rBind[i].error = NULL; + m_rBind[i].error = nullptr; m_rBind[i].is_unsigned = field[i].flags & UNSIGNED_FLAG; } @@ -137,7 +239,7 @@ m_length(NULL) m_rows[uint32(m_rowPosition) * m_fieldCount + fIndex].SetByteValue( buffer, - m_rBind[fIndex].buffer_type, + MysqlTypeToFieldType(m_rBind[fIndex].buffer_type), fetched_length); // move buffer pointer to next part @@ -147,7 +249,7 @@ m_length(NULL) { m_rows[uint32(m_rowPosition) * m_fieldCount + fIndex].SetByteValue( nullptr, - m_rBind[fIndex].buffer_type, + MysqlTypeToFieldType(m_rBind[fIndex].buffer_type), *m_rBind[fIndex].length); } @@ -196,7 +298,7 @@ bool ResultSet::NextRow() } for (uint32 i = 0; i < _fieldCount; i++) - _currentRow[i].SetStructuredValue(row[i], _fields[i].type, lengths[i]); + _currentRow[i].SetStructuredValue(row[i], MysqlTypeToFieldType( _fields[i].type), lengths[i]); return true; } @@ -227,16 +329,35 @@ void ResultSet::CleanUp() if (_currentRow) { delete [] _currentRow; - _currentRow = NULL; + _currentRow = nullptr; } if (_result) { mysql_free_result(_result); - _result = NULL; + _result = nullptr; } } +Field const& ResultSet::operator[](std::size_t index) const +{ + ASSERT(index < _fieldCount); + return _currentRow[index]; +} + +Field* PreparedResultSet::Fetch() const +{ + ASSERT(m_rowPosition < m_rowCount); + return const_cast(&m_rows[uint32(m_rowPosition) * m_fieldCount]); +} + +Field const& PreparedResultSet::operator[](std::size_t index) const +{ + ASSERT(m_rowPosition < m_rowCount); + ASSERT(index < m_fieldCount); + return m_rows[uint32(m_rowPosition) * m_fieldCount + index]; +} + void PreparedResultSet::CleanUp() { if (m_metadataResult) diff --git a/src/server/database/Database/QueryResult.h b/src/server/database/Database/QueryResult.h index 59363813baf..649149e4e4e 100644 --- a/src/server/database/Database/QueryResult.h +++ b/src/server/database/Database/QueryResult.h @@ -19,13 +19,9 @@ #ifndef QUERYRESULT_H #define QUERYRESULT_H -#include -#include "Field.h" - -#ifdef _WIN32 - #include -#endif -#include +#include "Define.h" +#include "DatabaseEnvFwd.h" +#include class TC_DATABASE_API ResultSet { @@ -38,11 +34,7 @@ class TC_DATABASE_API ResultSet uint32 GetFieldCount() const { return _fieldCount; } Field* Fetch() const { return _currentRow; } - const Field & operator [] (uint32 index) const - { - ASSERT(index < _fieldCount); - return _currentRow[index]; - } + Field const& operator[](std::size_t index) const; protected: uint64 _rowCount; @@ -58,8 +50,6 @@ class TC_DATABASE_API ResultSet ResultSet& operator=(ResultSet const& right) = delete; }; -typedef std::shared_ptr QueryResult; - class TC_DATABASE_API PreparedResultSet { public: @@ -70,18 +60,8 @@ class TC_DATABASE_API PreparedResultSet uint64 GetRowCount() const { return m_rowCount; } uint32 GetFieldCount() const { return m_fieldCount; } - Field* Fetch() const - { - ASSERT(m_rowPosition < m_rowCount); - return const_cast(&m_rows[uint32(m_rowPosition) * m_fieldCount]); - } - - Field const& operator[](uint32 index) const - { - ASSERT(m_rowPosition < m_rowCount); - ASSERT(index < m_fieldCount); - return m_rows[uint32(m_rowPosition) * m_fieldCount + index]; - } + Field* Fetch() const; + Field const& operator[](std::size_t index) const; protected: std::vector m_rows; @@ -94,9 +74,6 @@ class TC_DATABASE_API PreparedResultSet MYSQL_STMT* m_stmt; MYSQL_RES* m_metadataResult; ///< Field metadata, returned by mysql_stmt_result_metadata - my_bool* m_isNull; - unsigned long* m_length; - void CleanUp(); bool _NextRow(); @@ -104,6 +81,4 @@ class TC_DATABASE_API PreparedResultSet PreparedResultSet& operator=(PreparedResultSet const& right) = delete; }; -typedef std::shared_ptr PreparedQueryResult; - #endif diff --git a/src/server/database/Database/SQLOperation.h b/src/server/database/Database/SQLOperation.h index 0bedccaa68a..aea866bd7a5 100644 --- a/src/server/database/Database/SQLOperation.h +++ b/src/server/database/Database/SQLOperation.h @@ -18,16 +18,14 @@ #ifndef _SQLOPERATION_H #define _SQLOPERATION_H -#include "QueryResult.h" - -//- Forward declare (don't include header to prevent circular includes) -class PreparedStatement; +#include "Define.h" +#include "DatabaseEnvFwd.h" //- Union that holds element data union SQLElementUnion { PreparedStatement* stmt; - const char* query; + char const* query; }; //- Type specifier of our element data @@ -56,7 +54,7 @@ class MySQLConnection; class TC_DATABASE_API SQLOperation { public: - SQLOperation(): m_conn(NULL) { } + SQLOperation(): m_conn(nullptr) { } virtual ~SQLOperation() { } virtual int call() diff --git a/src/server/database/Database/Transaction.cpp b/src/server/database/Database/Transaction.cpp index 929653d2109..9b551fb4625 100644 --- a/src/server/database/Database/Transaction.cpp +++ b/src/server/database/Database/Transaction.cpp @@ -15,21 +15,20 @@ * with this program. If not, see . */ -#include "Log.h" #include "Transaction.h" +#include "Log.h" #include "MySQLConnection.h" #include "PreparedStatement.h" #include "Timer.h" #include #include -#include std::mutex TransactionTask::_deadlockLock; #define DEADLOCK_MAX_RETRY_TIME_MS 60000 //- Append a raw ad-hoc query to the transaction -void Transaction::Append(const char* sql) +void Transaction::Append(char const* sql) { SQLElementData data; data.type = SQL_ELEMENT_RAW; @@ -52,9 +51,8 @@ void Transaction::Cleanup() if (_cleanedUp) return; - while (!m_queries.empty()) + for (SQLElementData const& data : m_queries) { - SQLElementData const &data = m_queries.front(); switch (data.type) { case SQL_ELEMENT_PREPARED: @@ -64,10 +62,9 @@ void Transaction::Cleanup() free((void*)(data.element.query)); break; } - - m_queries.pop_front(); } + m_queries.clear(); _cleanedUp = true; } diff --git a/src/server/database/Database/Transaction.h b/src/server/database/Database/Transaction.h index 646b01274d2..1471fa85e7a 100644 --- a/src/server/database/Database/Transaction.h +++ b/src/server/database/Database/Transaction.h @@ -18,11 +18,12 @@ #ifndef _TRANSACTION_H #define _TRANSACTION_H +#include "Define.h" +#include "DatabaseEnvFwd.h" #include "SQLOperation.h" #include "StringFormat.h" - -//- Forward declare (don't include header to prevent circular includes) -class PreparedStatement; +#include +#include /*! Transactions, high level class. */ class TC_DATABASE_API Transaction @@ -38,24 +39,23 @@ class TC_DATABASE_API Transaction ~Transaction() { Cleanup(); } void Append(PreparedStatement* statement); - void Append(const char* sql); + void Append(char const* sql); template void PAppend(Format&& sql, Args&&... args) { Append(Trinity::StringFormat(std::forward(sql), std::forward(args)...).c_str()); } - size_t GetSize() const { return m_queries.size(); } + std::size_t GetSize() const { return m_queries.size(); } protected: void Cleanup(); - std::list m_queries; + std::vector m_queries; private: bool _cleanedUp; }; -typedef std::shared_ptr SQLTransaction; /*! Low level class*/ class TC_DATABASE_API TransactionTask : public SQLOperation diff --git a/src/server/database/Logging/AppenderDB.cpp b/src/server/database/Logging/AppenderDB.cpp index 5fc739b285b..5460b38aa0b 100644 --- a/src/server/database/Logging/AppenderDB.cpp +++ b/src/server/database/Logging/AppenderDB.cpp @@ -16,9 +16,11 @@ */ #include "AppenderDB.h" -#include "Database/DatabaseEnv.h" +#include "DatabaseEnv.h" +#include "LogMessage.h" +#include "PreparedStatement.h" -AppenderDB::AppenderDB(uint8 id, std::string const& name, LogLevel level, AppenderFlags /*flags*/, ExtraAppenderArgs /*extraArgs*/) +AppenderDB::AppenderDB(uint8 id, std::string const& name, LogLevel level, AppenderFlags /*flags*/, std::vector /*extraArgs*/) : Appender(id, name, level), realmId(0), enabled(false) { } AppenderDB::~AppenderDB() { } diff --git a/src/server/database/Logging/AppenderDB.h b/src/server/database/Logging/AppenderDB.h index ef703a21cf5..f2866426523 100644 --- a/src/server/database/Logging/AppenderDB.h +++ b/src/server/database/Logging/AppenderDB.h @@ -25,7 +25,7 @@ class TC_DATABASE_API AppenderDB: public Appender public: typedef std::integral_constant::type TypeIndex; - AppenderDB(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, ExtraAppenderArgs extraArgs); + AppenderDB(uint8 id, std::string const& name, LogLevel level, AppenderFlags flags, std::vector extraArgs); ~AppenderDB(); void setRealmId(uint32 realmId) override; diff --git a/src/server/database/PrecompiledHeaders/databasePCH.h b/src/server/database/PrecompiledHeaders/databasePCH.h index d524d52ade0..f51bbbb0861 100644 --- a/src/server/database/PrecompiledHeaders/databasePCH.h +++ b/src/server/database/PrecompiledHeaders/databasePCH.h @@ -1,23 +1,32 @@ -#include "Config.h" -#include "Database/AdhocStatement.h" -#include "Database/DatabaseEnv.h" -#include "Database/DatabaseLoader.h" -#include "Database/DatabaseWorker.h" -#include "Database/DatabaseWorkerPool.h" -#include "Database/Field.h" -#include "Database/MySQLConnection.h" -#include "Database/MySQLThreading.h" -#include "Database/PreparedStatement.h" -#include "Database/QueryHolder.h" -#include "Database/QueryResult.h" -#include "Database/SQLOperation.h" -#include "Database/Transaction.h" -#include "Logging/Appender.h" -#include "Logging/AppenderConsole.h" -#include "Logging/AppenderDB.h" -#include "Logging/AppenderFile.h" -#include "Logging/Log.h" -#include "Logging/LogOperation.h" -#include "Logging/Logger.h" -#include "Updater/DBUpdater.h" -#include "Updater/UpdateFetcher.h" +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#include "Define.h" +#include "Errors.h" +#include "Field.h" +#include "Log.h" +#include "MySQLConnection.h" +#include "PreparedStatement.h" +#include "QueryResult.h" +#include "SQLOperation.h" +#include "Transaction.h" +#ifdef _WIN32 // hack for broken mysql.h not including the correct winsock header for SOCKET definition, fixed in 5.7 +#include +#endif +#include +#include +#include diff --git a/src/server/database/Updater/DBUpdater.cpp b/src/server/database/Updater/DBUpdater.cpp index 75abd9bcd0f..2c48aeed2df 100644 --- a/src/server/database/Updater/DBUpdater.cpp +++ b/src/server/database/Updater/DBUpdater.cpp @@ -16,17 +16,18 @@ */ #include "DBUpdater.h" -#include "Log.h" -#include "GitRevision.h" -#include "UpdateFetcher.h" -#include "DatabaseLoader.h" -#include "Config.h" #include "BuiltInConfig.h" +#include "Config.h" +#include "DatabaseEnv.h" +#include "DatabaseLoader.h" +#include "GitRevision.h" +#include "Log.h" +#include "QueryResult.h" #include "StartProcess.h" - +#include "UpdateFetcher.h" +#include #include #include -#include std::string DBUpdaterUtil::GetCorrectedMySQLExecutable() { @@ -41,18 +42,12 @@ bool DBUpdaterUtil::CheckExecutable() boost::filesystem::path exe(GetCorrectedMySQLExecutable()); if (!exists(exe)) { - exe.clear(); - - if (auto path = Trinity::SearchExecutableInPath("mysql")) + exe = Trinity::SearchExecutableInPath("mysql"); + if (!exe.empty() && exists(exe)) { - exe = std::move(*path); - - if (!exe.empty() && exists(exe)) - { - // Correct the path to the cli - corrected_path() = absolute(exe).generic_string(); - return true; - } + // Correct the path to the cli + corrected_path() = absolute(exe).generic_string(); + return true; } TC_LOG_FATAL("sql.updates", "Didn't find any executable MySQL binary at \'%s\' or in path, correct the path in the *.conf (\"MySQLExecutable\").", @@ -316,7 +311,7 @@ bool DBUpdater::Populate(DatabaseWorkerPool& pool) template QueryResult DBUpdater::Retrieve(DatabaseWorkerPool& pool, std::string const& query) { - return pool.PQuery(query.c_str()); + return pool.Query(query.c_str()); } template diff --git a/src/server/database/Updater/DBUpdater.h b/src/server/database/Updater/DBUpdater.h index b80d0f83686..dc011fbf8bd 100644 --- a/src/server/database/Updater/DBUpdater.h +++ b/src/server/database/Updater/DBUpdater.h @@ -18,10 +18,20 @@ #ifndef DBUpdater_h__ #define DBUpdater_h__ -#include "DatabaseEnv.h" - +#include "Define.h" +#include "DatabaseEnvFwd.h" #include -#include + +template +class DatabaseWorkerPool; + +namespace boost +{ + namespace filesystem + { + class path; + } +} class TC_DATABASE_API UpdateException : public std::exception { @@ -41,19 +51,6 @@ enum BaseLocation LOCATION_DOWNLOAD }; -struct TC_DATABASE_API UpdateResult -{ - UpdateResult() - : updated(0), recent(0), archived(0) { } - - UpdateResult(size_t const updated_, size_t const recent_, size_t const archived_) - : updated(updated_), recent(recent_), archived(archived_) { } - - size_t updated; - size_t recent; - size_t archived; -}; - class DBUpdaterUtil { public: diff --git a/src/server/database/Updater/UpdateFetcher.cpp b/src/server/database/Updater/UpdateFetcher.cpp index a6656c46af8..632c5f3779d 100644 --- a/src/server/database/Updater/UpdateFetcher.cpp +++ b/src/server/database/Updater/UpdateFetcher.cpp @@ -16,28 +16,40 @@ */ #include "UpdateFetcher.h" +#include "Common.h" +#include "DBUpdater.h" +#include "Field.h" #include "Log.h" +#include "QueryResult.h" #include "Util.h" #include "SHA1.h" - +#include #include -#include -#include #include -#include -#include using namespace boost::filesystem; +struct UpdateFetcher::DirectoryEntry +{ + DirectoryEntry(Path const& path_, State state_) : path(path_), state(state_) { } + + Path const path; + State const state; +}; + UpdateFetcher::UpdateFetcher(Path const& sourceDirectory, std::function const& apply, std::function const& applyFile, std::function const& retrieve) : - _sourceDirectory(sourceDirectory), _apply(apply), _applyFile(applyFile), + _sourceDirectory(Trinity::make_unique(sourceDirectory)), _apply(apply), _applyFile(applyFile), _retrieve(retrieve) { } +UpdateFetcher::~UpdateFetcher() +{ +} + UpdateFetcher::LocaleFileStorage UpdateFetcher::GetFileList() const { LocaleFileStorage files; @@ -95,7 +107,7 @@ UpdateFetcher::DirectoryStorage UpdateFetcher::ReceiveIncludedDirectories() cons std::string path = fields[0].GetString(); if (path.substr(0, 1) == "$") - path = _sourceDirectory.generic_string() + path.substr(1); + path = _sourceDirectory->generic_string() + path.substr(1); Path const p(path); @@ -405,3 +417,8 @@ void UpdateFetcher::UpdateState(std::string const& name, State const state) cons // Update database _apply(update); } + +bool UpdateFetcher::PathCompare::operator()(LocaleFileEntry const& left, LocaleFileEntry const& right) const +{ + return left.first.filename().string() < right.first.filename().string(); +} diff --git a/src/server/database/Updater/UpdateFetcher.h b/src/server/database/Updater/UpdateFetcher.h index 07249e07995..79afd686df6 100644 --- a/src/server/database/Updater/UpdateFetcher.h +++ b/src/server/database/Updater/UpdateFetcher.h @@ -18,13 +18,34 @@ #ifndef UpdateFetcher_h__ #define UpdateFetcher_h__ -#include - -#include +#include "Define.h" +#include "DatabaseEnvFwd.h" +#include #include -#include +#include #include +namespace boost +{ + namespace filesystem + { + class path; + } +} + +struct TC_DATABASE_API UpdateResult +{ + UpdateResult() + : updated(0), recent(0), archived(0) { } + + UpdateResult(size_t updated_, size_t recent_, size_t archived_) + : updated(updated_), recent(recent_), archived(archived_) { } + + size_t updated; + size_t recent; + size_t archived; +}; + class TC_DATABASE_API UpdateFetcher { typedef boost::filesystem::path Path; @@ -34,6 +55,7 @@ public: std::function const& apply, std::function const& applyFile, std::function const& retrieve); + ~UpdateFetcher(); UpdateResult Update(bool const redundancyChecks, bool const allowRehash, bool const archivedRedundancy, int32 const cleanDeadReferencesMaxCount) const; @@ -80,23 +102,13 @@ private: } }; - struct DirectoryEntry - { - DirectoryEntry(Path const& path_, State state_) : path(path_), state(state_) { } - - Path const path; - - State const state; - }; + struct DirectoryEntry; typedef std::pair LocaleFileEntry; struct PathCompare { - inline bool operator() (LocaleFileEntry const& left, LocaleFileEntry const& right) const - { - return left.first.filename().string() < right.first.filename().string(); - } + bool operator()(LocaleFileEntry const& left, LocaleFileEntry const& right) const; }; typedef std::set LocaleFileStorage; @@ -121,7 +133,7 @@ private: void UpdateState(std::string const& name, State const state) const; - Path const _sourceDirectory; + std::unique_ptr const _sourceDirectory; std::function const _apply; std::function const _applyFile; diff --git a/src/server/game/AI/CoreAI/CombatAI.cpp b/src/server/game/AI/CoreAI/CombatAI.cpp index c6cdf4aea4e..680b5ebb7c3 100644 --- a/src/server/game/AI/CoreAI/CombatAI.cpp +++ b/src/server/game/AI/CoreAI/CombatAI.cpp @@ -17,11 +17,16 @@ */ #include "CombatAI.h" -#include "SpellMgr.h" -#include "SpellInfo.h" -#include "Vehicle.h" +#include "ConditionMgr.h" +#include "Creature.h" +#include "CreatureAIImpl.h" +#include "Log.h" +#include "MotionMaster.h" #include "ObjectAccessor.h" #include "Player.h" +#include "SpellInfo.h" +#include "SpellMgr.h" +#include "Vehicle.h" ///////////////// // AggressorAI diff --git a/src/server/game/AI/CoreAI/CombatAI.h b/src/server/game/AI/CoreAI/CombatAI.h index 905e1f3e8f0..a27c8fc64ef 100644 --- a/src/server/game/AI/CoreAI/CombatAI.h +++ b/src/server/game/AI/CoreAI/CombatAI.h @@ -20,8 +20,6 @@ #define TRINITY_COMBATAI_H #include "CreatureAI.h" -#include "CreatureAIImpl.h" -#include "ConditionMgr.h" class Creature; diff --git a/src/server/game/AI/CoreAI/GameObjectAI.cpp b/src/server/game/AI/CoreAI/GameObjectAI.cpp index 2e927e35383..12a1dcb9cb8 100644 --- a/src/server/game/AI/CoreAI/GameObjectAI.cpp +++ b/src/server/game/AI/CoreAI/GameObjectAI.cpp @@ -17,5 +17,18 @@ */ #include "GameObjectAI.h" +#include "CreatureAI.h" -NullGameObjectAI::NullGameObjectAI(GameObject* g) : GameObjectAI(g) { } +int32 GameObjectAI::Permissible(GameObject const* /*go*/) +{ + return PERMIT_BASE_NO; +} + +NullGameObjectAI::NullGameObjectAI(GameObject* g) : GameObjectAI(g) +{ +} + +int32 NullGameObjectAI::Permissible(GameObject const* /*go*/) +{ + return PERMIT_BASE_IDLE; +} diff --git a/src/server/game/AI/CoreAI/GameObjectAI.h b/src/server/game/AI/CoreAI/GameObjectAI.h index 02e0b03625f..81f77f3ab47 100644 --- a/src/server/game/AI/CoreAI/GameObjectAI.h +++ b/src/server/game/AI/CoreAI/GameObjectAI.h @@ -20,12 +20,12 @@ #define TRINITY_GAMEOBJECTAI_H #include "Define.h" -#include -#include "Object.h" -#include "QuestDef.h" -#include "GameObject.h" -#include "CreatureAI.h" #include "ObjectGuid.h" +#include "QuestDef.h" + +class GameObject; +class Unit; +class SpellInfo; class TC_GAME_API GameObjectAI { @@ -46,7 +46,7 @@ class TC_GAME_API GameObjectAI virtual void SetGUID(ObjectGuid const& /*guid*/, int32 /*id = 0 */) { } virtual ObjectGuid GetGUID(int32 /*id = 0 */) const { return ObjectGuid::Empty; } - static int32 Permissible(GameObject const* /*go*/) { return PERMIT_BASE_NO; } + static int32 Permissible(GameObject const* go); // Called when a player opens a gossip dialog with the gameobject. virtual bool GossipHello(Player* /*player*/) { return false; } @@ -82,7 +82,7 @@ class TC_GAME_API GameObjectAI virtual void OnLootStateChanged(uint32 /*state*/, Unit* /*unit*/) { } virtual void OnStateChanged(uint32 /*state*/) { } virtual void EventInform(uint32 /*eventId*/) { } - virtual void SpellHit(Unit* /*unit*/, const SpellInfo* /*spellInfo*/) { } + virtual void SpellHit(Unit* /*unit*/, SpellInfo const* /*spellInfo*/) { } }; class TC_GAME_API NullGameObjectAI : public GameObjectAI @@ -92,6 +92,6 @@ class TC_GAME_API NullGameObjectAI : public GameObjectAI void UpdateAI(uint32 /*diff*/) override { } - static int32 Permissible(GameObject const* /*go*/) { return PERMIT_BASE_IDLE; } + static int32 Permissible(GameObject const* go); }; #endif diff --git a/src/server/game/AI/CoreAI/GuardAI.cpp b/src/server/game/AI/CoreAI/GuardAI.cpp index 0b3be44b1e8..939a7a84161 100644 --- a/src/server/game/AI/CoreAI/GuardAI.cpp +++ b/src/server/game/AI/CoreAI/GuardAI.cpp @@ -17,9 +17,16 @@ */ #include "GuardAI.h" +#include "Creature.h" #include "Errors.h" +#include "Log.h" +#include "MotionMaster.h" #include "Player.h" +GuardAI::GuardAI(Creature* creature) : ScriptedAI(creature) +{ +} + int32 GuardAI::Permissible(Creature const* creature) { if (creature->IsGuard()) @@ -28,7 +35,13 @@ int32 GuardAI::Permissible(Creature const* creature) return PERMIT_BASE_NO; } -GuardAI::GuardAI(Creature* creature) : ScriptedAI(creature) { } +void GuardAI::UpdateAI(uint32 /*diff*/) +{ + if (!UpdateVictim()) + return; + + DoMeleeAttackIfReady(); +} bool GuardAI::CanSeeAlways(WorldObject const* obj) { diff --git a/src/server/game/AI/CoreAI/GuardAI.h b/src/server/game/AI/CoreAI/GuardAI.h index 4ab4cc44693..5ed18cdc2b0 100644 --- a/src/server/game/AI/CoreAI/GuardAI.h +++ b/src/server/game/AI/CoreAI/GuardAI.h @@ -29,6 +29,7 @@ class TC_GAME_API GuardAI : public ScriptedAI explicit GuardAI(Creature* creature); static int32 Permissible(Creature const* creature); + void UpdateAI(uint32 diff) override; bool CanSeeAlways(WorldObject const* obj) override; void EnterEvadeMode(EvadeReason /*why*/) override; diff --git a/src/server/game/AI/CoreAI/PetAI.cpp b/src/server/game/AI/CoreAI/PetAI.cpp index 1068f2334fd..de15d9830f5 100644 --- a/src/server/game/AI/CoreAI/PetAI.cpp +++ b/src/server/game/AI/CoreAI/PetAI.cpp @@ -269,7 +269,7 @@ void PetAI::UpdateAllies() if (!owner) return; - Group* group = NULL; + Group* group = nullptr; if (Player* player = owner->ToPlayer()) group = player->GetGroup(); @@ -285,7 +285,7 @@ void PetAI::UpdateAllies() m_AllySet.insert(me->GetGUID()); if (group) //add group { - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* Target = itr->GetSource(); if (!Target || !Target->IsInMap(owner) || !group->SameSubGroup(owner->ToPlayer(), Target)) @@ -369,7 +369,7 @@ void PetAI::OwnerAttacked(Unit* target) // Called when owner attacks something. Allows defensive pets to know // that they need to assist - // Target might be NULL if called from spell with invalid cast targets + // Target might be nullptr if called from spell with invalid cast targets if (!target || !me->IsAlive()) return; @@ -394,7 +394,7 @@ Unit* PetAI::SelectNextTarget(bool allowAutoSelect) const // Passive pets don't do next target selection if (me->HasReactState(REACT_PASSIVE)) - return NULL; + return nullptr; // Check pet attackers first so we don't drag a bunch of targets to the owner if (Unit* myAttacker = me->getAttackerForHelper()) @@ -403,7 +403,7 @@ Unit* PetAI::SelectNextTarget(bool allowAutoSelect) const // Not sure why we wouldn't have an owner but just in case... if (!me->GetCharmerOrOwner()) - return NULL; + return nullptr; // Check owner attackers if (Unit* ownerAttacker = me->GetCharmerOrOwner()->getAttackerForHelper()) @@ -426,7 +426,7 @@ Unit* PetAI::SelectNextTarget(bool allowAutoSelect) const } // Default - no valid targets - return NULL; + return nullptr; } void PetAI::HandleReturnMovement() @@ -575,7 +575,7 @@ bool PetAI::CanAttack(Unit* target) if (me->GetVictim() && me->GetVictim() != target) { // Check if our owner selected this target and clicked "attack" - Unit* ownerTarget = NULL; + Unit* ownerTarget = nullptr; if (Player* owner = me->GetCharmerOrOwner()->ToPlayer()) ownerTarget = owner->GetSelectedUnit(); else diff --git a/src/server/game/AI/CoreAI/ReactorAI.cpp b/src/server/game/AI/CoreAI/ReactorAI.cpp index e0f0c2ab8a6..048d3e7f138 100644 --- a/src/server/game/AI/CoreAI/ReactorAI.cpp +++ b/src/server/game/AI/CoreAI/ReactorAI.cpp @@ -16,8 +16,8 @@ * with this program. If not, see . */ -#include "ByteBuffer.h" #include "ReactorAI.h" +#include "Creature.h" int32 ReactorAI::Permissible(Creature const* creature) { diff --git a/src/server/game/AI/CoreAI/ReactorAI.h b/src/server/game/AI/CoreAI/ReactorAI.h index 6020d052145..69f3758e7a6 100644 --- a/src/server/game/AI/CoreAI/ReactorAI.h +++ b/src/server/game/AI/CoreAI/ReactorAI.h @@ -21,8 +21,6 @@ #include "CreatureAI.h" -class Unit; - class TC_GAME_API ReactorAI : public CreatureAI { public: diff --git a/src/server/game/AI/CoreAI/UnitAI.cpp b/src/server/game/AI/CoreAI/UnitAI.cpp index 6bd4cfac3b2..d2450c69d70 100644 --- a/src/server/game/AI/CoreAI/UnitAI.cpp +++ b/src/server/game/AI/CoreAI/UnitAI.cpp @@ -17,14 +17,15 @@ */ #include "UnitAI.h" -#include "Player.h" #include "Creature.h" -#include "SpellAuras.h" -#include "SpellAuraEffects.h" -#include "SpellMgr.h" -#include "SpellInfo.h" -#include "Spell.h" #include "CreatureAIImpl.h" +#include "MotionMaster.h" +#include "Player.h" +#include "Spell.h" +#include "SpellAuraEffects.h" +#include "SpellAuras.h" +#include "SpellInfo.h" +#include "SpellMgr.h" void UnitAI::AttackStart(Unit* victim) { @@ -40,6 +41,12 @@ void UnitAI::AttackStart(Unit* victim) } } +void UnitAI::InitializeAI() +{ + if (!me->isDead()) + Reset(); +} + void UnitAI::AttackStartCaster(Unit* victim, float dist) { if (victim && me->Attack(victim, false)) @@ -112,37 +119,9 @@ float UnitAI::DoGetSpellMaxRange(uint32 spellId, bool positive) return spellInfo ? spellInfo->GetMaxRange(positive) : 0; } -void UnitAI::DoAddAuraToAllHostilePlayers(uint32 spellid) -{ - if (me->IsInCombat()) - { - ThreatContainer::StorageType threatlist = me->getThreatManager().getThreatList(); - for (ThreatContainer::StorageType::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) - { - if (Unit* unit = ObjectAccessor::GetUnit(*me, (*itr)->getUnitGuid())) - if (unit->GetTypeId() == TYPEID_PLAYER) - me->AddAura(spellid, unit); - } - } -} - -void UnitAI::DoCastToAllHostilePlayers(uint32 spellid, bool triggered) -{ - if (me->IsInCombat()) - { - ThreatContainer::StorageType threatlist = me->getThreatManager().getThreatList(); - for (ThreatContainer::StorageType::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) - { - if (Unit* unit = ObjectAccessor::GetUnit(*me, (*itr)->getUnitGuid())) - if (unit->GetTypeId() == TYPEID_PLAYER) - me->CastSpell(unit, spellid, triggered); - } - } -} - void UnitAI::DoCast(uint32 spellId) { - Unit* target = NULL; + Unit* target = nullptr; switch (AISpellInfo[spellId].target) { @@ -211,7 +190,12 @@ void UnitAI::DoCastAOE(uint32 spellId, bool triggered) if (!triggered && me->HasUnitState(UNIT_STATE_CASTING)) return; - me->CastSpell((Unit*)NULL, spellId, triggered); + me->CastSpell((Unit*)nullptr, spellId, triggered); +} + +uint32 UnitAI::GetDialogStatus(Player* /*player*/) +{ + return DIALOG_STATUS_SCRIPTED_NO_STATUS; } #define UPDATE_TARGET(a) {if (AIInfo->targettarget=a;} @@ -221,11 +205,9 @@ void UnitAI::FillAISpellInfo() AISpellInfo = new AISpellInfoType[sSpellMgr->GetSpellInfoStoreSize()]; AISpellInfoType* AIInfo = AISpellInfo; - const SpellInfo* spellInfo; - for (uint32 i = 0; i < sSpellMgr->GetSpellInfoStoreSize(); ++i, ++AIInfo) { - spellInfo = sSpellMgr->GetSpellInfo(i); + SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(i); if (!spellInfo) continue; @@ -267,6 +249,45 @@ void UnitAI::FillAISpellInfo() } } +ThreatManager& UnitAI::GetThreatManager() +{ + return me->getThreatManager(); +} + +bool DefaultTargetSelector::operator()(Unit const* target) const +{ + if (!me) + return false; + + if (!target) + return false; + + if (m_playerOnly && (target->GetTypeId() != TYPEID_PLAYER)) + return false; + + if (m_dist > 0.0f && !me->IsWithinCombatRange(target, m_dist)) + return false; + + if (m_dist < 0.0f && me->IsWithinCombatRange(target, -m_dist)) + return false; + + if (m_aura) + { + if (m_aura > 0) + { + if (!target->HasAura(m_aura)) + return false; + } + else + { + if (target->HasAura(-m_aura)) + return false; + } + } + + return true; +} + SpellTargetSelector::SpellTargetSelector(Unit* caster, uint32 spellId) : _caster(caster), _spellInfo(sSpellMgr->GetSpellForDifficultyFromSpell(sSpellMgr->GetSpellInfo(spellId), caster)) { @@ -384,3 +405,8 @@ bool FarthestTargetSelector::operator()(Unit const* target) const return true; } + +void SortByDistanceTo(Unit* reference, std::list& targets) +{ + targets.sort(Trinity::ObjectDistanceOrderPred(reference)); +} diff --git a/src/server/game/AI/CoreAI/UnitAI.h b/src/server/game/AI/CoreAI/UnitAI.h index f55edff471f..3936cd686b0 100644 --- a/src/server/game/AI/CoreAI/UnitAI.h +++ b/src/server/game/AI/CoreAI/UnitAI.h @@ -19,15 +19,29 @@ #ifndef TRINITY_UNITAI_H #define TRINITY_UNITAI_H -#include "Define.h" -#include "Unit.h" #include "Containers.h" #include "EventMap.h" -#include +#include "ObjectGuid.h" +#include "ThreatManager.h" + +#define CAST_AI(a, b) (dynamic_cast(b)) +#define ENSURE_AI(a,b) (EnsureAI(b)) + +template +inline T* EnsureAI(U* ai) +{ + T* cast_ai = dynamic_cast(ai); + ASSERT(cast_ai); + return cast_ai; +}; class Player; class Quest; +class SpellInfo; +class Unit; struct AISpellInfoType; +enum DamageEffectType : uint8; +enum SpellEffIndex : uint8; //Selection method used by SelectTarget enum SelectAggroTarget @@ -40,9 +54,9 @@ enum SelectAggroTarget }; // default predicate function to select target based on distance, player and/or aura criteria -struct TC_GAME_API DefaultTargetSelector : public std::unary_function +struct TC_GAME_API DefaultTargetSelector { - const Unit* me; + Unit const* me; float m_dist; bool m_playerOnly; int32 m_aura; @@ -53,44 +67,12 @@ struct TC_GAME_API DefaultTargetSelector : public std::unary_function 0: the target shall have the aura, if < 0, the target shall NOT have the aura DefaultTargetSelector(Unit const* unit, float dist, bool playerOnly, int32 aura) : me(unit), m_dist(dist), m_playerOnly(playerOnly), m_aura(aura) { } - bool operator()(Unit const* target) const - { - if (!me) - return false; - - if (!target) - return false; - - if (m_playerOnly && (target->GetTypeId() != TYPEID_PLAYER)) - return false; - - if (m_dist > 0.0f && !me->IsWithinCombatRange(target, m_dist)) - return false; - - if (m_dist < 0.0f && me->IsWithinCombatRange(target, -m_dist)) - return false; - - if (m_aura) - { - if (m_aura > 0) - { - if (!target->HasAura(m_aura)) - return false; - } - else - { - if (target->HasAura(-m_aura)) - return false; - } - } - - return true; - } + bool operator()(Unit const* target) const; }; // Target selector for spell casts checking range, auras and attributes /// @todo Add more checks from Spell::CheckCast -struct TC_GAME_API SpellTargetSelector : public std::unary_function +struct TC_GAME_API SpellTargetSelector { public: SpellTargetSelector(Unit* caster, uint32 spellId); @@ -104,7 +86,7 @@ struct TC_GAME_API SpellTargetSelector : public std::unary_function // 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 TC_GAME_API NonTankTargetSelector : public std::unary_function +struct TC_GAME_API NonTankTargetSelector { public: NonTankTargetSelector(Unit* source, bool playerOnly = true) : _source(source), _playerOnly(playerOnly) { } @@ -136,12 +118,14 @@ struct TC_GAME_API FarthestTargetSelector bool operator()(Unit const* target) const; private: - const Unit* _me; + Unit const* _me; float _dist; bool _playerOnly; bool _inLos; }; +TC_GAME_API void SortByDistanceTo(Unit* reference, std::list& targets); + class TC_GAME_API UnitAI { protected: @@ -154,7 +138,7 @@ class TC_GAME_API UnitAI virtual void AttackStart(Unit* /*target*/); virtual void UpdateAI(uint32 diff) = 0; - virtual void InitializeAI() { if (!me->isDead()) Reset(); } + virtual void InitializeAI(); virtual void Reset() { } @@ -171,15 +155,16 @@ class TC_GAME_API UnitAI Unit* SelectTarget(SelectAggroTarget targetType, uint32 position = 0, float dist = 0.0f, bool playerOnly = false, int32 aura = 0); // Select the targets satisfying the predicate. // predicate shall extend std::unary_function - template Unit* SelectTarget(SelectAggroTarget targetType, uint32 position, PREDICATE const& predicate) + template + Unit* SelectTarget(SelectAggroTarget targetType, uint32 position, PREDICATE const& predicate) { - ThreatContainer::StorageType const& threatlist = me->getThreatManager().getThreatList(); + ThreatContainer::StorageType const& threatlist = GetThreatManager().getThreatList(); if (position >= threatlist.size()) return nullptr; std::list targetList; Unit* currentVictim = nullptr; - if (auto currentVictimReference = me->getThreatManager().getCurrentVictim()) + if (auto currentVictimReference = GetThreatManager().getCurrentVictim()) { currentVictim = currentVictimReference->getTarget(); @@ -188,42 +173,38 @@ class TC_GAME_API UnitAI targetList.push_back(currentVictim); } - for (ThreatContainer::StorageType::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) + for (HostileReference* hostileRef : threatlist) { - 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 (currentVictim != nullptr && hostileRef->getTarget() != currentVictim && predicate(hostileRef->getTarget())) + targetList.push_back(hostileRef->getTarget()); + else if (currentVictim == nullptr && predicate(hostileRef->getTarget())) + targetList.push_back(hostileRef->getTarget()); } if (position >= targetList.size()) return nullptr; if (targetType == SELECT_TARGET_NEAREST || targetType == SELECT_TARGET_FARTHEST) - targetList.sort(Trinity::ObjectDistanceOrderPred(me)); + SortByDistanceTo(me, targetList); switch (targetType) { case SELECT_TARGET_NEAREST: case SELECT_TARGET_TOPAGGRO: { - std::list::iterator itr = targetList.begin(); + auto itr = targetList.begin(); std::advance(itr, position); return *itr; } case SELECT_TARGET_FARTHEST: case SELECT_TARGET_BOTTOMAGGRO: { - std::list::reverse_iterator ritr = targetList.rbegin(); + auto ritr = targetList.rbegin(); std::advance(ritr, position); return *ritr; } case SELECT_TARGET_RANDOM: - { - std::list::iterator itr = targetList.begin(); - std::advance(itr, urand(position, targetList.size() - 1)); - return *itr; - } + return Trinity::Containers::SelectRandomContainerElement(targetList); default: break; } @@ -235,21 +216,22 @@ class TC_GAME_API UnitAI // Select the targets satifying the predicate. // predicate shall extend std::unary_function - template void SelectTargetList(std::list& targetList, PREDICATE const& predicate, uint32 maxTargets, SelectAggroTarget targetType) + template + void SelectTargetList(std::list& targetList, PREDICATE const& predicate, uint32 maxTargets, SelectAggroTarget targetType) { - ThreatContainer::StorageType const& threatlist = me->getThreatManager().getThreatList(); + ThreatContainer::StorageType const& threatlist = GetThreatManager().getThreatList(); if (threatlist.empty()) return; - for (ThreatContainer::StorageType::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) - if (predicate((*itr)->getTarget())) - targetList.push_back((*itr)->getTarget()); + for (HostileReference* hostileRef : threatlist) + if (predicate(hostileRef->getTarget())) + targetList.push_back(hostileRef->getTarget()); if (targetList.size() < maxTargets) return; if (targetType == SELECT_TARGET_NEAREST || targetType == SELECT_TARGET_FARTHEST) - targetList.sort(Trinity::ObjectDistanceOrderPred(me)); + SortByDistanceTo(me, targetList); if (targetType == SELECT_TARGET_FARTHEST || targetType == SELECT_TARGET_BOTTOMAGGRO) targetList.reverse(); @@ -286,11 +268,9 @@ class TC_GAME_API UnitAI void AttackStartCaster(Unit* victim, float dist); - 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); @@ -323,11 +303,13 @@ class TC_GAME_API UnitAI virtual void OnGameEvent(bool /*start*/, uint16 /*eventId*/) { } // Called when the dialog status between a player and the creature is requested. - virtual uint32 GetDialogStatus(Player* /*player*/) { return DIALOG_STATUS_SCRIPTED_NO_STATUS; } + virtual uint32 GetDialogStatus(Player* /*player*/); private: UnitAI(UnitAI const& right) = delete; UnitAI& operator=(UnitAI const& right) = delete; + + ThreatManager& GetThreatManager(); }; #endif diff --git a/src/server/game/AI/CreatureAI.cpp b/src/server/game/AI/CreatureAI.cpp index 74b761f9101..fec727fce62 100644 --- a/src/server/game/AI/CreatureAI.cpp +++ b/src/server/game/AI/CreatureAI.cpp @@ -17,16 +17,20 @@ */ #include "CreatureAI.h" -#include "CreatureAIImpl.h" +#include "AreaBoundary.h" #include "Creature.h" -#include "World.h" -#include "SpellMgr.h" -#include "Vehicle.h" -#include "Log.h" -#include "MapReference.h" -#include "Player.h" +#include "CreatureAIImpl.h" #include "CreatureTextMgr.h" #include "Language.h" +#include "Log.h" +#include "Map.h" +#include "MapReference.h" +#include "MotionMaster.h" +#include "Player.h" +#include "SpellMgr.h" +#include "TemporarySummon.h" +#include "Vehicle.h" +#include "World.h" //Disable CreatureAI when charmed void CreatureAI::OnCharmed(bool apply) @@ -39,7 +43,15 @@ void CreatureAI::OnCharmed(bool apply) } AISpellInfoType* UnitAI::AISpellInfo; -AISpellInfoType* GetAISpellInfo(uint32 i) { return &CreatureAI::AISpellInfo[i]; } +AISpellInfoType* GetAISpellInfo(uint32 i) { return &UnitAI::AISpellInfo[i]; } + +CreatureAI::CreatureAI(Creature* creature) : UnitAI(creature), me(creature), _boundary(nullptr), _negateBoundary(false), m_MoveInLineOfSight_locked(false) +{ +} + +CreatureAI::~CreatureAI() +{ +} void CreatureAI::Talk(uint8 id, WorldObject const* whisperTarget /*= nullptr*/) { @@ -390,7 +402,7 @@ void CreatureAI::SetBoundary(CreatureBoundary const* boundary, bool negateBounda me->DoImmediateBoundaryCheck(); } -Creature* CreatureAI::DoSummon(uint32 entry, const Position& pos, uint32 despawnTime, TempSummonType summonType) +Creature* CreatureAI::DoSummon(uint32 entry, Position const& pos, uint32 despawnTime, TempSummonType summonType) { return me->SummonCreature(entry, pos, summonType, despawnTime); } diff --git a/src/server/game/AI/CreatureAI.h b/src/server/game/AI/CreatureAI.h index dc9483f762c..0572b1465a3 100644 --- a/src/server/game/AI/CreatureAI.h +++ b/src/server/game/AI/CreatureAI.h @@ -19,17 +19,19 @@ #ifndef TRINITY_CREATUREAI_H #define TRINITY_CREATUREAI_H -#include "Creature.h" #include "UnitAI.h" -#include "AreaBoundary.h" #include "Common.h" +#include "ObjectDefines.h" -class WorldObject; -class Unit; +class AreaBoundary; class Creature; -class Player; +class DynamicObject; +class GameObject; class PlayerAI; -class SpellInfo; +class WorldObject; +struct Position; + +typedef std::vector CreatureBoundary; #define TIME_INTERVAL_LOOK 5000 #define VISIBILITY_RANGE 10000 @@ -65,7 +67,6 @@ enum SCEquip EQUIP_UNEQUIP = 0 }; -typedef std::vector CreatureBoundary; class TC_GAME_API CreatureAI : public UnitAI { protected: @@ -92,12 +93,12 @@ class TC_GAME_API CreatureAI : public UnitAI EVADE_REASON_OTHER }; + explicit CreatureAI(Creature* creature); + + ~CreatureAI(); + void Talk(uint8 id, WorldObject const* whisperTarget = nullptr); - explicit CreatureAI(Creature* creature) : UnitAI(creature), me(creature), _boundary(nullptr), _negateBoundary(false), m_MoveInLineOfSight_locked(false) { } - - virtual ~CreatureAI() { } - /// == Reactions At ================================= // Called if IsVisible(Unit* who) is true at each who move, reaction at visibility zone enter diff --git a/src/server/game/AI/CreatureAIImpl.h b/src/server/game/AI/CreatureAIImpl.h index bdd9c624f05..cad71e001ed 100644 --- a/src/server/game/AI/CreatureAIImpl.h +++ b/src/server/game/AI/CreatureAIImpl.h @@ -17,17 +17,13 @@ #ifndef CREATUREAIIMPL_H #define CREATUREAIIMPL_H -#include "Common.h" -#include "Define.h" -#include "TemporarySummon.h" -#include "CreatureAI.h" -#include "SpellMgr.h" - -#include +#include "Random.h" #include +class WorldObject; + template -static inline First const& RAND(First const& first, Second const& second, Rest const&... rest) +inline First const& RAND(First const& first, Second const& second, Rest const&... rest) { std::reference_wrapper::type> const pack[] = { first, second, rest... }; return pack[urand(0, sizeof...(rest) + 1)].get(); @@ -65,4 +61,15 @@ struct AISpellInfoType AISpellInfoType* GetAISpellInfo(uint32 i); +TC_GAME_API bool InstanceHasScript(WorldObject const* obj, char const* scriptName); + +template +inline AI* GetInstanceAI(T* obj, char const* scriptName) +{ + if (InstanceHasScript(obj, scriptName)) + return new AI(obj); + + return nullptr; +} + #endif diff --git a/src/server/game/AI/CreatureAIRegistry.cpp b/src/server/game/AI/CreatureAIRegistry.cpp index ef7ecce041f..8ee69b87c51 100644 --- a/src/server/game/AI/CreatureAIRegistry.cpp +++ b/src/server/game/AI/CreatureAIRegistry.cpp @@ -16,19 +16,20 @@ * with this program. If not, see . */ -#include "PassiveAI.h" -#include "ReactorAI.h" -#include "CombatAI.h" -#include "GuardAI.h" -#include "PetAI.h" -#include "TotemAI.h" -#include "RandomMovementGenerator.h" -#include "MovementGenerator.h" -#include "CreatureAIRegistry.h" -#include "WaypointMovementGenerator.h" #include "CreatureAIFactory.h" #include "GameObjectAIFactory.h" + +#include "CombatAI.h" +#include "GuardAI.h" +#include "PassiveAI.h" +#include "PetAI.h" +#include "ReactorAI.h" #include "SmartAI.h" +#include "TotemAI.h" + +#include "MovementGenerator.h" +#include "RandomMovementGenerator.h" +#include "WaypointMovementGenerator.h" namespace AIRegistry { diff --git a/src/server/game/AI/CreatureAIRegistry.h b/src/server/game/AI/CreatureAIRegistry.h index c8f7c536785..a54236758ac 100644 --- a/src/server/game/AI/CreatureAIRegistry.h +++ b/src/server/game/AI/CreatureAIRegistry.h @@ -21,6 +21,6 @@ namespace AIRegistry { - void Initialize(void); + void Initialize(); } #endif diff --git a/src/server/game/AI/GameObjectAIFactory.h b/src/server/game/AI/GameObjectAIFactory.h index b7d88529e29..bf2d7843352 100644 --- a/src/server/game/AI/GameObjectAIFactory.h +++ b/src/server/game/AI/GameObjectAIFactory.h @@ -21,6 +21,9 @@ #include "ObjectRegistry.h" #include "SelectableAI.h" +class GameObject; +class GameObjectAI; + template struct GameObjectAIFactory : public SelectableAI { diff --git a/src/server/game/AI/PlayerAI/PlayerAI.cpp b/src/server/game/AI/PlayerAI/PlayerAI.cpp index ab7a0f0a78a..f28b76fbf02 100644 --- a/src/server/game/AI/PlayerAI/PlayerAI.cpp +++ b/src/server/game/AI/PlayerAI/PlayerAI.cpp @@ -16,8 +16,17 @@ */ #include "PlayerAI.h" +#include "Creature.h" +#include "DBCStores.h" +#include "Item.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "Spell.h" #include "SpellAuras.h" #include "SpellAuraEffects.h" +#include "SpellHistory.h" +#include "SpellMgr.h" enum Specs { @@ -425,6 +434,21 @@ enum Spells SPELL_LIFEBLOOM = 48451 }; +PlayerAI::PlayerAI(Player* player) : UnitAI(player), me(player), + _selfSpec(PlayerAI::GetPlayerSpec(player)), + _isSelfHealer(PlayerAI::IsPlayerHealer(player)), + _isSelfRangedAttacker(PlayerAI::IsPlayerRangedAttacker(player)) +{ +} + +Creature* PlayerAI::GetCharmer() const +{ + if (ObjectGuid charmerGUID = me->GetCharmerGUID()) + if (charmerGUID.IsCreature()) + return ObjectAccessor::GetCreature(*me, charmerGUID); + return nullptr; +} + uint8 PlayerAI::GetPlayerSpec(Player const* who) { if (!who) @@ -592,6 +616,13 @@ PlayerAI::TargetedSpell PlayerAI::SelectSpellCast(PossibleSpellVector& spells) return selected; } +void PlayerAI::DoCastAtTarget(TargetedSpell spell) +{ + SpellCastTargets targets; + targets.SetUnitTarget(spell.second); + spell.first->prepare(&targets); +} + void PlayerAI::DoRangedAttackIfReady() { if (me->HasUnitState(UNIT_STATE_CASTING)) @@ -663,13 +694,19 @@ void PlayerAI::CancelAllShapeshifts() me->RemoveOwnedAura(aura, AURA_REMOVE_BY_CANCEL); } -struct UncontrolledTargetSelectPredicate : public std::unary_function +Unit* PlayerAI::SelectAttackTarget() const +{ + return me->GetCharmer() ? me->GetCharmer()->GetVictim() : nullptr; +} + +struct UncontrolledTargetSelectPredicate { bool operator()(Unit const* target) const { return !target->HasBreakableByDamageCrowdControlAura(); } }; + Unit* SimpleCharmedPlayerAI::SelectAttackTarget() const { if (Unit* charmer = me->GetCharmer()) diff --git a/src/server/game/AI/PlayerAI/PlayerAI.h b/src/server/game/AI/PlayerAI/PlayerAI.h index 166bf37d8ea..5588abeba8e 100644 --- a/src/server/game/AI/PlayerAI/PlayerAI.h +++ b/src/server/game/AI/PlayerAI/PlayerAI.h @@ -19,25 +19,18 @@ #define TRINITY_PLAYERAI_H #include "UnitAI.h" -#include "Player.h" -#include "Spell.h" -#include "Creature.h" + +class Spell; class TC_GAME_API PlayerAI : public UnitAI { public: - explicit PlayerAI(Player* player) : UnitAI(static_cast(player)), me(player), _selfSpec(PlayerAI::GetPlayerSpec(player)), _isSelfHealer(PlayerAI::IsPlayerHealer(player)), _isSelfRangedAttacker(PlayerAI::IsPlayerRangedAttacker(player)) { } + explicit PlayerAI(Player* player); void OnCharmed(bool /*apply*/) override { } // charm AI application for players is handled by Unit::SetCharmedBy / Unit::RemoveCharmedBy + Creature* GetCharmer() const; - Creature* GetCharmer() const - { - if (ObjectGuid charmerGUID = me->GetCharmerGUID()) - if (charmerGUID.IsCreature()) - return ObjectAccessor::GetCreature(*me, charmerGUID); - return nullptr; - } // 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); @@ -85,14 +78,9 @@ class TC_GAME_API PlayerAI : public UnitAI 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); - } + void DoCastAtTarget(TargetedSpell spell); - virtual Unit* SelectAttackTarget() const { return me->GetCharmer() ? me->GetCharmer()->GetVictim() : nullptr; } + virtual Unit* SelectAttackTarget() const; void DoRangedAttackIfReady(); void DoAutoAttackIfReady(); diff --git a/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp b/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp index e1a02996c87..d1665ff6b25 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp +++ b/src/server/game/AI/ScriptedAI/ScriptedCreature.cpp @@ -17,13 +17,19 @@ */ #include "ScriptedCreature.h" -#include "Spell.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" +#include "AreaBoundary.h" #include "Cell.h" #include "CellImpl.h" -#include "ObjectMgr.h" -#include "AreaBoundary.h" +#include "DBCStores.h" +#include "GridNotifiers.h" +#include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Spell.h" +#include "SpellMgr.h" +#include "TemporarySummon.h" // Spell summary for ScriptedAI::SelectSpell struct TSpellSummary @@ -32,6 +38,16 @@ struct TSpellSummary uint8 Effects; // set of enum SelectEffect } extern* SpellSummary; +void SummonList::Summon(Creature const* summon) +{ + storage_.push_back(summon->GetGUID()); +} + +void SummonList::Despawn(Creature const* summon) +{ + storage_.remove(summon->GetGUID()); +} + void SummonList::DoZoneInCombat(uint32 entry, float maxRangeToNearestTarget) { for (StorageType::iterator i = storage_.begin(); i != storage_.end();) @@ -97,6 +113,16 @@ bool SummonList::HasEntry(uint32 entry) const return false; } +void SummonList::DoActionImpl(int32 action, StorageType const& summons) +{ + for (auto const& guid : summons) + { + Creature* summon = ObjectAccessor::GetCreature(*me, guid); + if (summon && summon->IsAIEnabled) + summon->AI()->DoAction(action); + } +} + ScriptedAI::ScriptedAI(Creature* creature) : CreatureAI(creature), IsFleeing(false), _isCombatMovementAllowed(true) @@ -179,6 +205,16 @@ Creature* ScriptedAI::DoSpawnCreature(uint32 entry, float offsetX, float offsetY return me->SummonCreature(entry, me->GetPositionX() + offsetX, me->GetPositionY() + offsetY, me->GetPositionZ() + offsetZ, angle, TempSummonType(type), despawntime); } +bool ScriptedAI::HealthBelowPct(uint32 pct) const +{ + return me->HealthBelowPct(pct); +} + +bool ScriptedAI::HealthAbovePct(uint32 pct) const +{ + return me->HealthAbovePct(pct); +} + SpellInfo const* ScriptedAI::SelectSpell(Unit* target, uint32 school, uint32 mechanic, SelectTargetType targets, uint32 powerCostMin, uint32 powerCostMax, float rangeMin, float rangeMax, SelectEffect effects) { //No target so we can't cast @@ -444,6 +480,11 @@ void BossAI::_JustDied() instance->SetBossState(_bossId, DONE); } +void BossAI::_JustReachedHome() +{ + me->setActive(false); +} + void BossAI::_JustEngagedWith() { if (instance) @@ -507,6 +548,11 @@ void BossAI::UpdateAI(uint32 diff) DoMeleeAttackIfReady(); } +bool BossAI::CanAIAttack(Unit const* target) const +{ + return CheckBoundary(target); +} + void BossAI::_DespawnAtEvade(uint32 delayToRespawn, Creature* who) { if (delayToRespawn < 2) diff --git a/src/server/game/AI/ScriptedAI/ScriptedCreature.h b/src/server/game/AI/ScriptedAI/ScriptedCreature.h index 530fe72576c..578cf644bea 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedCreature.h +++ b/src/server/game/AI/ScriptedAI/ScriptedCreature.h @@ -19,23 +19,11 @@ #ifndef SCRIPTEDCREATURE_H_ #define SCRIPTEDCREATURE_H_ -#include "Creature.h" #include "CreatureAI.h" -#include "CreatureAIImpl.h" -#include "InstanceScript.h" +#include "Creature.h" // convenience include for scripts, all uses of ScriptedCreature also need Creature (except ScriptedCreature itself doesn't need Creature) +#include "DBCEnums.h" #include "TaskScheduler.h" -#define CAST_AI(a, b) (dynamic_cast(b)) -#define ENSURE_AI(a,b) (EnsureAI(b)) - -template -T* EnsureAI(U* ai) -{ - T* cast_ai = dynamic_cast(ai); - ASSERT(cast_ai); - return cast_ai; -}; - class InstanceScript; class TC_GAME_API SummonList @@ -95,13 +83,13 @@ public: storage_.clear(); } - void Summon(Creature const* summon) { storage_.push_back(summon->GetGUID()); } - void Despawn(Creature const* summon) { storage_.remove(summon->GetGUID()); } + void Summon(Creature const* summon); + void Despawn(Creature const* summon); void DespawnEntry(uint32 entry); void DespawnAll(); template - void DespawnIf(T const &predicate) + void DespawnIf(T const& predicate) { storage_.remove_if(predicate); } @@ -112,12 +100,7 @@ public: // We need to use a copy of SummonList here, otherwise original SummonList would be modified StorageType listCopy = storage_; Trinity::Containers::RandomResize(listCopy, std::forward(predicate), max); - for (StorageType::iterator i = listCopy.begin(); i != listCopy.end(); ) - { - Creature* summon = ObjectAccessor::GetCreature(*me, *i++); - if (summon && summon->IsAIEnabled) - summon->AI()->DoAction(info); - } + DoActionImpl(info, listCopy); } void DoZoneInCombat(uint32 entry = 0, float maxRangeToNearestTarget = 250.0f); @@ -125,6 +108,8 @@ public: bool HasEntry(uint32 entry) const; private: + void DoActionImpl(int32 action, StorageType const& summons); + Creature* me; StorageType storage_; }; @@ -256,8 +241,8 @@ struct TC_GAME_API ScriptedAI : public CreatureAI //Spawns a creature relative to me Creature* DoSpawnCreature(uint32 entry, float offsetX, float offsetY, float offsetZ, float angle, uint32 type, uint32 despawntime); - bool HealthBelowPct(uint32 pct) const { return me->HealthBelowPct(pct); } - bool HealthAbovePct(uint32 pct) const { return me->HealthAbovePct(pct); } + bool HealthBelowPct(uint32 pct) const; + bool HealthAbovePct(uint32 pct) const; //Returns spells that meet the specified criteria from the creatures spell list SpellInfo const* SelectSpell(Unit* target, uint32 school, uint32 mechanic, SelectTargetType targets, uint32 powerCostMin, uint32 powerCostMax, float rangeMin, float rangeMax, SelectEffect effect); @@ -369,13 +354,13 @@ class TC_GAME_API BossAI : public ScriptedAI void JustDied(Unit* /*killer*/) override { _JustDied(); } void JustReachedHome() override { _JustReachedHome(); } - bool CanAIAttack(Unit const* target) const override { return CheckBoundary(target); } + bool CanAIAttack(Unit const* target) const override; protected: void _Reset(); void _JustEngagedWith(); void _JustDied(); - void _JustReachedHome() { me->setActive(false); } + void _JustReachedHome(); void _DespawnAtEvade(uint32 delayToRespawn = 30, Creature* who = nullptr); void _DespawnAtEvade(Seconds const& time, Creature* who = nullptr) { _DespawnAtEvade(uint32(time.count()), who); } diff --git a/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp b/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp index 0105c034395..0829ada44eb 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp +++ b/src/server/game/AI/ScriptedAI/ScriptedEscortAI.cpp @@ -23,10 +23,14 @@ SDComment: SDCategory: Npc EndScriptData */ -#include "Player.h" -#include "ScriptedCreature.h" #include "ScriptedEscortAI.h" +#include "Creature.h" #include "Group.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" enum Points { @@ -39,7 +43,7 @@ npc_escortAI::npc_escortAI(Creature* creature) : ScriptedAI(creature), m_uiPlayerCheckTimer(1000), m_uiEscortState(STATE_ESCORT_NONE), MaxPlayerDistance(DEFAULT_MAX_PLAYER_DISTANCE), - m_pQuestForEscort(NULL), + m_pQuestForEscort(nullptr), m_bIsActiveAttacker(true), m_bIsRunning(false), m_bCanInstantRespawn(false), @@ -65,6 +69,11 @@ void npc_escortAI::AttackStart(Unit* who) } } +Player* npc_escortAI::GetPlayerForEscort() +{ + return ObjectAccessor::GetPlayer(*me, m_uiPlayerGUID); +} + //see followerAI bool npc_escortAI::AssistPlayerInCombatAgainst(Unit* who) { @@ -148,7 +157,7 @@ void npc_escortAI::JustDied(Unit* /*killer*/) { if (Group* group = player->GetGroup()) { - for (GroupReference* groupRef = group->GetFirstMember(); groupRef != NULL; groupRef = groupRef->next()) + for (GroupReference* groupRef = group->GetFirstMember(); groupRef != nullptr; groupRef = groupRef->next()) if (Player* member = groupRef->GetSource()) if (member->IsInMap(player)) member->FailQuest(m_pQuestForEscort->GetQuestId()); @@ -186,7 +195,7 @@ void npc_escortAI::EnterEvadeMode(EvadeReason /*why*/) me->RemoveAllAuras(); me->DeleteThreatList(); me->CombatStop(true); - me->SetLootRecipient(NULL); + me->SetLootRecipient(nullptr); if (HasEscortState(STATE_ESCORT_ESCORTING)) { @@ -209,7 +218,7 @@ bool npc_escortAI::IsPlayerOrGroupInRange() { if (Group* group = player->GetGroup()) { - for (GroupReference* groupRef = group->GetFirstMember(); groupRef != NULL; groupRef = groupRef->next()) + for (GroupReference* groupRef = group->GetFirstMember(); groupRef != nullptr; groupRef = groupRef->next()) if (Player* member = groupRef->GetSource()) if (me->IsWithinDistInMap(member, GetMaxPlayerDistance())) return true; @@ -432,7 +441,7 @@ void npc_escortAI::SetRun(bool on) } /// @todo get rid of this many variables passed in function. -void npc_escortAI::Start(bool isActiveAttacker /* = true*/, bool run /* = false */, ObjectGuid playerGUID /* = 0 */, Quest const* quest /* = NULL */, bool instantRespawn /* = false */, bool canLoopPath /* = false */, bool resetWaypoints /* = true */) +void npc_escortAI::Start(bool isActiveAttacker /* = true*/, bool run /* = false */, ObjectGuid playerGUID /* = 0 */, Quest const* quest /* = nullptr */, bool instantRespawn /* = false */, bool canLoopPath /* = false */, bool resetWaypoints /* = true */) { if (me->GetVictim()) { diff --git a/src/server/game/AI/ScriptedAI/ScriptedEscortAI.h b/src/server/game/AI/ScriptedAI/ScriptedEscortAI.h index 687e352c7e6..926327f1d52 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedEscortAI.h +++ b/src/server/game/AI/ScriptedAI/ScriptedEscortAI.h @@ -19,8 +19,11 @@ #ifndef SC_ESCORTAI_H #define SC_ESCORTAI_H +#include "ScriptedCreature.h" #include "ScriptSystem.h" +class Quest; + #define DEFAULT_MAX_PLAYER_DISTANCE 50 struct Escort_Waypoint @@ -88,7 +91,7 @@ struct TC_GAME_API npc_escortAI : public ScriptedAI virtual void WaypointReached(uint32 pointId) = 0; virtual void WaypointStart(uint32 /*pointId*/) { } - void Start(bool isActiveAttacker = true, bool run = false, ObjectGuid playerGUID = ObjectGuid::Empty, Quest const* quest = NULL, bool instantRespawn = false, bool canLoopPath = false, bool resetWaypoints = true); + void Start(bool isActiveAttacker = true, bool run = false, ObjectGuid playerGUID = ObjectGuid::Empty, Quest const* quest = nullptr, bool instantRespawn = false, bool canLoopPath = false, bool resetWaypoints = true); void SetRun(bool on = true); void SetEscortPaused(bool on); @@ -106,7 +109,7 @@ struct TC_GAME_API npc_escortAI : public ScriptedAI ObjectGuid GetEventStarterGUID() const { return m_uiPlayerGUID; } protected: - Player* GetPlayerForEscort() { return ObjectAccessor::GetPlayer(*me, m_uiPlayerGUID); } + Player* GetPlayerForEscort(); private: bool AssistPlayerInCombatAgainst(Unit* who); diff --git a/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.cpp b/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.cpp index 91786534cd2..cb06347a43a 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.cpp +++ b/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.cpp @@ -23,12 +23,16 @@ SDComment: This AI is under development SDCategory: Npc EndScriptData */ -#include "Player.h" -#include "ScriptedCreature.h" #include "ScriptedFollowerAI.h" +#include "Creature.h" #include "Group.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" -const float MAX_PLAYER_DISTANCE = 100.0f; +float const MAX_PLAYER_DISTANCE = 100.0f; enum Points { @@ -38,7 +42,7 @@ enum Points FollowerAI::FollowerAI(Creature* creature) : ScriptedAI(creature), m_uiUpdateFollowTimer(2500), m_uiFollowState(STATE_FOLLOW_NONE), - m_pQuestForFollow(NULL) + m_pQuestForFollow(nullptr) { } void FollowerAI::AttackStart(Unit* who) @@ -146,7 +150,7 @@ void FollowerAI::JustDied(Unit* /*killer*/) { if (Group* group = player->GetGroup()) { - for (GroupReference* groupRef = group->GetFirstMember(); groupRef != NULL; groupRef = groupRef->next()) + for (GroupReference* groupRef = group->GetFirstMember(); groupRef != nullptr; groupRef = groupRef->next()) if (Player* member = groupRef->GetSource()) if (member->IsInMap(player)) member->FailQuest(m_pQuestForFollow->GetQuestId()); @@ -174,7 +178,7 @@ void FollowerAI::EnterEvadeMode(EvadeReason /*why*/) me->RemoveAllAuras(); me->DeleteThreatList(); me->CombatStop(true); - me->SetLootRecipient(NULL); + me->SetLootRecipient(nullptr); if (HasFollowState(STATE_FOLLOW_INPROGRESS)) { @@ -224,7 +228,7 @@ void FollowerAI::UpdateAI(uint32 uiDiff) if (Group* group = player->GetGroup()) { - for (GroupReference* groupRef = group->GetFirstMember(); groupRef != NULL; groupRef = groupRef->next()) + for (GroupReference* groupRef = group->GetFirstMember(); groupRef != nullptr; groupRef = groupRef->next()) { Player* member = groupRef->GetSource(); if (member && me->IsWithinDistInMap(member, MAX_PLAYER_DISTANCE)) @@ -330,7 +334,7 @@ Player* FollowerAI::GetLeaderForFollower() { if (Group* group = player->GetGroup()) { - for (GroupReference* groupRef = group->GetFirstMember(); groupRef != NULL; groupRef = groupRef->next()) + for (GroupReference* groupRef = group->GetFirstMember(); groupRef != nullptr; groupRef = groupRef->next()) { Player* member = groupRef->GetSource(); if (member && me->IsWithinDistInMap(member, MAX_PLAYER_DISTANCE) && member->IsAlive()) @@ -345,7 +349,7 @@ Player* FollowerAI::GetLeaderForFollower() } TC_LOG_DEBUG("scripts", "FollowerAI GetLeader can not find suitable leader."); - return NULL; + return nullptr; } void FollowerAI::SetFollowComplete(bool bWithEndEvent) diff --git a/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.h b/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.h index abf49355e1e..a3f1ae5db66 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.h +++ b/src/server/game/AI/ScriptedAI/ScriptedFollowerAI.h @@ -19,8 +19,11 @@ #ifndef SC_FOLLOWERAI_H #define SC_FOLLOWERAI_H +#include "ScriptedCreature.h" #include "ScriptSystem.h" +class Quest; + enum eFollowState { STATE_FOLLOW_NONE = 0x000, @@ -55,7 +58,7 @@ class TC_GAME_API FollowerAI : public ScriptedAI void UpdateAI(uint32) override; //the "internal" update, calls UpdateFollowerAI() virtual void UpdateFollowerAI(uint32); //used when it's needed to add code in update (abilities, scripted events, etc) - void StartFollow(Player* player, uint32 factionForFollower = 0, const Quest* quest = NULL); + void StartFollow(Player* player, uint32 factionForFollower = 0, Quest const* quest = nullptr); void SetFollowPaused(bool bPaused); //if special event require follow mode to hold/resume during the follow void SetFollowComplete(bool bWithEndEvent = false); @@ -75,7 +78,7 @@ class TC_GAME_API FollowerAI : public ScriptedAI uint32 m_uiUpdateFollowTimer; uint32 m_uiFollowState; - const Quest* m_pQuestForFollow; //normally we have a quest + Quest const* m_pQuestForFollow; //normally we have a quest }; #endif diff --git a/src/server/game/AI/SelectableAI.h b/src/server/game/AI/SelectableAI.h index 9998bc22494..527f22a5d8f 100644 --- a/src/server/game/AI/SelectableAI.h +++ b/src/server/game/AI/SelectableAI.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2008-2018 TrinityCore * * 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 diff --git a/src/server/game/AI/SmartScripts/SmartAI.cpp b/src/server/game/AI/SmartScripts/SmartAI.cpp index 530cfe043e1..fc8fb5f9870 100644 --- a/src/server/game/AI/SmartScripts/SmartAI.cpp +++ b/src/server/game/AI/SmartScripts/SmartAI.cpp @@ -15,15 +15,16 @@ * with this program. If not, see . */ -#include "DatabaseEnv.h" -#include "ObjectMgr.h" -#include "ObjectDefines.h" -#include "GridDefines.h" -#include "GridNotifiers.h" -#include "SpellMgr.h" -#include "Cell.h" -#include "Group.h" #include "SmartAI.h" +#include "Creature.h" +#include "DBCStructure.h" +#include "GameObject.h" +#include "Group.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "PetDefines.h" +#include "Player.h" #include "ScriptMgr.h" #include "Vehicle.h" @@ -231,7 +232,7 @@ void SmartAI::EndPath(bool fail) else GetScript()->SetPathId(0); - ObjectList* targets = GetScript()->GetTargetList(SMART_ESCORT_TARGETS); + ObjectVector const* targets = GetScript()->GetStoredTargetVector(SMART_ESCORT_TARGETS, *me); if (targets && mEscortQuestID) { if (targets->size() == 1 && GetScript()->IsPlayer((*targets->begin()))) @@ -260,11 +261,11 @@ void SmartAI::EndPath(bool fail) } else { - for (ObjectList::iterator iter = targets->begin(); iter != targets->end(); ++iter) + for (WorldObject* target : *targets) { - if (GetScript()->IsPlayer((*iter))) + if (GetScript()->IsPlayer(target)) { - Player* player = (*iter)->ToPlayer(); + Player* player = target->ToPlayer(); if (!fail && player->IsAtGroupRewardDistance(me) && !player->HasCorpse()) player->AreaExploredOrEventHappens(mEscortQuestID); else if (fail) @@ -294,7 +295,7 @@ void SmartAI::ReturnToLastOOCPos() me->GetMotionMaster()->MovePoint(SMART_ESCORT_LAST_OOC_POINT, mLastOOCPos); } -void SmartAI::UpdatePath(const uint32 diff) +void SmartAI::UpdatePath(uint32 diff) { if (mEscortInvokerCheckTimer < diff) { @@ -404,8 +405,7 @@ void SmartAI::UpdateAI(uint32 diff) bool SmartAI::IsEscortInvokerInRange() { - ObjectList* targets = GetScript()->GetTargetList(SMART_ESCORT_TARGETS); - if (targets) + if (ObjectVector const* targets = GetScript()->GetStoredTargetVector(SMART_ESCORT_TARGETS, *me)) { float checkDist = me->GetInstanceScript() ? SMART_ESCORT_MAX_PLAYER_DIST * 2 : SMART_ESCORT_MAX_PLAYER_DIST; if (targets->size() == 1 && GetScript()->IsPlayer((*targets->begin()))) @@ -426,11 +426,11 @@ bool SmartAI::IsEscortInvokerInRange() } else { - for (ObjectList::iterator iter = targets->begin(); iter != targets->end(); ++iter) + for (WorldObject* target : *targets) { - if (GetScript()->IsPlayer((*iter))) + if (GetScript()->IsPlayer(target)) { - if (me->GetDistance((*iter)->ToPlayer()) <= checkDist) + if (me->GetDistance(target->ToPlayer()) <= checkDist) return true; } } @@ -525,7 +525,7 @@ void SmartAI::MoveInLineOfSight(Unit* who) CreatureAI::MoveInLineOfSight(who); } -bool SmartAI::CanAIAttack(const Unit* /*who*/) const +bool SmartAI::CanAIAttack(Unit const* /*who*/) const { return !(me->HasReactState(REACT_PASSIVE)); } @@ -658,12 +658,12 @@ void SmartAI::AttackStart(Unit* who) } } -void SmartAI::SpellHit(Unit* unit, const SpellInfo* spellInfo) +void SmartAI::SpellHit(Unit* unit, SpellInfo const* spellInfo) { GetScript()->ProcessEventsFor(SMART_EVENT_SPELLHIT, unit, 0, 0, false, spellInfo); } -void SmartAI::SpellHitTarget(Unit* target, const SpellInfo* spellInfo) +void SmartAI::SpellHitTarget(Unit* target, SpellInfo const* spellInfo) { GetScript()->ProcessEventsFor(SMART_EVENT_SPELLHIT_TARGET, target, 0, 0, false, spellInfo); } @@ -811,7 +811,7 @@ bool SmartAI::GossipSelect(Player* player, uint32 menuId, uint32 gossipListId) return _gossipReturn; } -bool SmartAI::GossipSelectCode(Player* /*player*/, uint32 /*menuId*/, uint32 /*gossipListId*/, const char* /*code*/) +bool SmartAI::GossipSelectCode(Player* /*player*/, uint32 /*menuId*/, uint32 /*gossipListId*/, char const* /*code*/) { return false; } @@ -1001,7 +1001,7 @@ bool SmartGameObjectAI::GossipSelect(Player* player, uint32 menuId, uint32 gossi } // Called when a player selects a gossip with a code in the gameobject's gossip menu. -bool SmartGameObjectAI::GossipSelectCode(Player* /*player*/, uint32 /*menuId*/, uint32 /*gossipListId*/, const char* /*code*/) +bool SmartGameObjectAI::GossipSelectCode(Player* /*player*/, uint32 /*menuId*/, uint32 /*gossipListId*/, char const* /*code*/) { return false; } @@ -1051,7 +1051,7 @@ void SmartGameObjectAI::EventInform(uint32 eventId) GetScript()->ProcessEventsFor(SMART_EVENT_GO_EVENT_INFORM, nullptr, eventId); } -void SmartGameObjectAI::SpellHit(Unit* unit, const SpellInfo* spellInfo) +void SmartGameObjectAI::SpellHit(Unit* unit, SpellInfo const* spellInfo) { GetScript()->ProcessEventsFor(SMART_EVENT_SPELLHIT, unit, 0, 0, false, spellInfo); } diff --git a/src/server/game/AI/SmartScripts/SmartAI.h b/src/server/game/AI/SmartScripts/SmartAI.h index eafba2df55c..eebe3d9821e 100644 --- a/src/server/game/AI/SmartScripts/SmartAI.h +++ b/src/server/game/AI/SmartScripts/SmartAI.h @@ -18,15 +18,13 @@ #ifndef TRINITY_SMARTAI_H #define TRINITY_SMARTAI_H -#include "Common.h" -#include "Creature.h" +#include "Define.h" #include "CreatureAI.h" -#include "Unit.h" -#include "Spell.h" - -#include "SmartScript.h" -#include "SmartScriptMgr.h" #include "GameObjectAI.h" +#include "Position.h" +#include "SmartScript.h" + +struct WayPoint; enum SmartEscortState { @@ -100,10 +98,10 @@ class TC_GAME_API SmartAI : public CreatureAI void MoveInLineOfSight(Unit* who) override; // Called when hit by a spell - void SpellHit(Unit* unit, const SpellInfo* spellInfo) override; + void SpellHit(Unit* unit, SpellInfo const* spellInfo) override; // Called when spell hits a target - void SpellHitTarget(Unit* target, const SpellInfo* spellInfo) override; + void SpellHitTarget(Unit* target, SpellInfo const* spellInfo) override; // Called at any Damage from any attacker (before damage apply) void DamageTaken(Unit* doneBy, uint32& damage) override; @@ -142,7 +140,7 @@ class TC_GAME_API SmartAI : public CreatureAI void OnCharmed(bool apply) override; // Called when victim is in line of sight - bool CanAIAttack(const Unit* who) const override; + bool CanAIAttack(Unit const* who) const override; // Used in scripts to share variables void DoAction(int32 param = 0) override; @@ -180,7 +178,7 @@ class TC_GAME_API SmartAI : public CreatureAI bool GossipHello(Player* player) override; bool GossipSelect(Player* player, uint32 menuId, uint32 gossipListId) override; - bool GossipSelectCode(Player* player, uint32 menuId, uint32 gossipListId, const char* code) override; + bool GossipSelectCode(Player* player, uint32 menuId, uint32 gossipListId, char const* code) override; void QuestAccept(Player* player, Quest const* quest) override; void QuestReward(Player* player, Quest const* quest, uint32 opt) override; void OnGameEvent(bool start, uint16 eventId) override; @@ -262,7 +260,7 @@ class TC_GAME_API SmartGameObjectAI : public GameObjectAI bool GossipHello(Player* player) override; bool OnReportUse(Player* player) override; bool GossipSelect(Player* player, uint32 menuId, uint32 gossipListId) override; - bool GossipSelectCode(Player* player, uint32 menuId, uint32 gossipListId, const char* code) override; + bool GossipSelectCode(Player* player, uint32 menuId, uint32 gossipListId, char const* code) override; void QuestAccept(Player* player, Quest const* quest) override; void QuestReward(Player* player, Quest const* quest, uint32 opt) override; void Destroyed(Player* player, uint32 eventId) override; @@ -271,7 +269,7 @@ class TC_GAME_API SmartGameObjectAI : public GameObjectAI void OnGameEvent(bool start, uint16 eventId) override; void OnLootStateChanged(uint32 state, Unit* unit) override; void EventInform(uint32 eventId) override; - void SpellHit(Unit* unit, const SpellInfo* spellInfo) override; + void SpellHit(Unit* unit, SpellInfo const* spellInfo) override; void SetGossipReturn(bool val) { _gossipReturn = val; } diff --git a/src/server/game/AI/SmartScripts/SmartScript.cpp b/src/server/game/AI/SmartScripts/SmartScript.cpp index d071fed08bd..0eb43f94f97 100644 --- a/src/server/game/AI/SmartScripts/SmartScript.cpp +++ b/src/server/game/AI/SmartScripts/SmartScript.cpp @@ -15,28 +15,32 @@ * with this program. If not, see . */ -#include "Cell.h" +#include "SmartScript.h" #include "CellImpl.h" #include "ChatTextBuilder.h" +#include "Creature.h" #include "CreatureTextMgr.h" -#include "DatabaseEnv.h" +#include "CreatureTextMgrImpl.h" +#include "GameEventMgr.h" +#include "GameObject.h" #include "GossipDef.h" -#include "GridDefines.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "Group.h" #include "InstanceScript.h" #include "Language.h" -#include "ObjectDefines.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "PhasingHandler.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" +#include "Random.h" #include "SmartAI.h" -#include "SmartScript.h" +#include "SpellAuras.h" #include "SpellMgr.h" +#include "TemporarySummon.h" #include "Vehicle.h" -#include "GameEventMgr.h" +#include SmartScript::SmartScript() { @@ -45,7 +49,6 @@ SmartScript::SmartScript() trigger = nullptr; mEventPhase = 0; mPathId = 0; - mTargetStorage = new ObjectListMap(); mTextTimer = 0; mLastTextID = 0; mUseTextTimer = false; @@ -57,11 +60,97 @@ SmartScript::SmartScript() SmartScript::~SmartScript() { - for (ObjectListMap::iterator itr = mTargetStorage->begin(); itr != mTargetStorage->end(); ++itr) - delete itr->second; +} - delete mTargetStorage; - mCounterList.clear(); +bool SmartScript::IsSmart(Creature* c /*= nullptr*/) +{ + bool smart = true; + if (c && c->GetAIName() != "SmartAI") + smart = false; + + if (!me || me->GetAIName() != "SmartAI") + smart = false; + + if (!smart) + TC_LOG_ERROR("sql.sql", "SmartScript: Action target Creature (GUID: %u Entry: %u) is not using SmartAI, action called by Creature (GUID: %u Entry: %u) skipped to prevent crash.", c ? c->GetSpawnId() : 0, c ? c->GetEntry() : 0, me ? me->GetSpawnId() : 0, me ? me->GetEntry() : 0); + + return smart; +} + +bool SmartScript::IsSmartGO(GameObject* g /*= nullptr*/) +{ + bool smart = true; + if (g && g->GetAIName() != "SmartGameObjectAI") + smart = false; + + if (!go || go->GetAIName() != "SmartGameObjectAI") + smart = false; + if (!smart) + TC_LOG_ERROR("sql.sql", "SmartScript: Action target GameObject (GUID: %u Entry: %u) is not using SmartGameObjectAI, action called by GameObject (GUID: %u Entry: %u) skipped to prevent crash.", g ? g->GetSpawnId() : 0, g ? g->GetEntry() : 0, go ? go->GetSpawnId() : 0, go ? go->GetEntry() : 0); + + return smart; +} + +void SmartScript::StoreTargetList(ObjectVector const& targets, uint32 id) +{ + // insert or replace + _storedTargets.erase(id); + _storedTargets.emplace(id, ObjectGuidVector(targets)); +} + +ObjectVector const* SmartScript::GetStoredTargetVector(uint32 id, WorldObject const& ref) const +{ + auto itr = _storedTargets.find(id); + if (itr != _storedTargets.end()) + return itr->second.GetObjectVector(ref); + return nullptr; +} + +void SmartScript::StoreCounter(uint32 id, uint32 value, uint32 reset) +{ + CounterMap::iterator itr = mCounterList.find(id); + if (itr != mCounterList.end()) + { + if (reset == 0) + itr->second += value; + else + itr->second = value; + } + else + mCounterList.insert(std::make_pair(id, value)); + + ProcessEventsFor(SMART_EVENT_COUNTER_SET, nullptr, id); +} + +uint32 SmartScript::GetCounterValue(uint32 id) const +{ + CounterMap::const_iterator itr = mCounterList.find(id); + if (itr != mCounterList.end()) + return itr->second; + return 0; +} + +GameObject* SmartScript::FindGameObjectNear(WorldObject* searchObject, ObjectGuid::LowType guid) const +{ + auto bounds = searchObject->GetMap()->GetGameObjectBySpawnIdStore().equal_range(guid); + if (bounds.first == bounds.second) + return nullptr; + + return bounds.first->second; +} + +Creature* SmartScript::FindCreatureNear(WorldObject* searchObject, ObjectGuid::LowType guid) const +{ + auto bounds = searchObject->GetMap()->GetCreatureBySpawnIdStore().equal_range(guid); + if (bounds.first == bounds.second) + return nullptr; + + auto creatureItr = std::find_if(bounds.first, bounds.second, [](Map::CreatureBySpawnIdContainer::value_type const& pair) + { + return pair.second->IsAlive(); + }); + + return creatureItr != bounds.second ? creatureItr->second : bounds.first->second; } void SmartScript::OnReset() @@ -80,7 +169,37 @@ void SmartScript::OnReset() mCounterList.clear(); } -void SmartScript::ProcessEventsFor(SMART_EVENT e, Unit* unit, uint32 var0, uint32 var1, bool bvar, const SpellInfo* spell, GameObject* gob) +void SmartScript::ResetBaseObject() +{ + WorldObject* lookupRoot = me; + if (!lookupRoot) + lookupRoot = go; + + if (lookupRoot) + { + if (!meOrigGUID.IsEmpty()) + { + if (Creature* m = ObjectAccessor::GetCreature(*lookupRoot, meOrigGUID)) + { + me = m; + go = nullptr; + } + } + + if (!goOrigGUID.IsEmpty()) + { + if (GameObject* o = ObjectAccessor::GetGameObject(*lookupRoot, goOrigGUID)) + { + me = nullptr; + go = o; + } + } + } + goOrigGUID.Clear(); + meOrigGUID.Clear(); +} + +void SmartScript::ProcessEventsFor(SMART_EVENT e, Unit* unit, uint32 var0, uint32 var1, bool bvar, SpellInfo const* spell, GameObject* gob) { for (SmartAIEventList::iterator i = mEvents.begin(); i != mEvents.end(); ++i) { @@ -94,7 +213,7 @@ void SmartScript::ProcessEventsFor(SMART_EVENT e, Unit* unit, uint32 var0, uint3 } } -void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, uint32 var1, bool bvar, const SpellInfo* spell, GameObject* gob) +void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, uint32 var1, bool bvar, SpellInfo const* spell, GameObject* gob) { //calc random if (e.GetEventType() != SMART_EVENT_LINK && e.event.event_chance < 100 && e.event.event_chance) @@ -110,38 +229,35 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (Unit* tempInvoker = GetLastInvoker()) TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction: Invoker: %s (guidlow: %u)", tempInvoker->GetName().c_str(), tempInvoker->GetGUID().GetCounter()); + ObjectVector targets; + GetTargets(targets, e, unit); + switch (e.GetActionType()) { case SMART_ACTION_TALK: { - ObjectList* targets = GetTargets(e, unit); Creature* talker = e.target.type == 0 ? me : nullptr; Unit* talkTarget = nullptr; - if (targets) + for (WorldObject* target : targets) { - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsCreature(target) && !target->ToCreature()->IsPet()) // Prevented sending text to pets. { - if (IsCreature(*itr) && !(*itr)->ToCreature()->IsPet()) // Prevented sending text to pets. - { - if (e.action.talk.useTalkTarget) - { - talker = me; - talkTarget = (*itr)->ToCreature(); - } - else - talker = (*itr)->ToCreature(); - break; - } - else if (IsPlayer(*itr)) + if (e.action.talk.useTalkTarget) { talker = me; - talkTarget = (*itr)->ToPlayer(); - break; + talkTarget = target->ToCreature(); } + else + talker = target->ToCreature(); + break; + } + else if (IsPlayer(target)) + { + talker = me; + talkTarget = target->ToPlayer(); + break; } - - delete targets; } if (!talkTarget) @@ -161,111 +277,83 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u } case SMART_ACTION_SIMPLE_TALK: { - ObjectList* targets = GetTargets(e, unit); - if (targets) + for (WorldObject* target : targets) { - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsCreature(target)) + sCreatureTextMgr->SendChat(target->ToCreature(), uint8(e.action.talk.textGroupID), IsPlayer(GetLastInvoker()) ? GetLastInvoker() : 0); + else if (IsPlayer(target) && me) { - if (IsCreature(*itr)) - sCreatureTextMgr->SendChat((*itr)->ToCreature(), uint8(e.action.talk.textGroupID), IsPlayer(GetLastInvoker()) ? GetLastInvoker() : 0); - else if (IsPlayer(*itr) && me) - { - Unit* templastInvoker = GetLastInvoker(); - sCreatureTextMgr->SendChat(me, uint8(e.action.talk.textGroupID), IsPlayer(templastInvoker) ? templastInvoker : 0, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, (*itr)->ToPlayer()); - } - TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_SIMPLE_TALK: talker: %s (GuidLow: %u), textGroupId: %u", - (*itr)->GetName().c_str(), (*itr)->GetGUID().GetCounter(), uint8(e.action.talk.textGroupID)); + Unit* templastInvoker = GetLastInvoker(); + sCreatureTextMgr->SendChat(me, uint8(e.action.talk.textGroupID), IsPlayer(templastInvoker) ? templastInvoker : 0, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, target->ToPlayer()); } - - delete targets; + TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_SIMPLE_TALK: talker: %s (GuidLow: %u), textGroupId: %u", + target->GetName().c_str(), target->GetGUID().GetCounter(), uint8(e.action.talk.textGroupID)); } break; } case SMART_ACTION_PLAY_EMOTE: { - ObjectList* targets = GetTargets(e, unit); - if (targets) + for (WorldObject* target : targets) { - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(target)) { - if (IsUnit(*itr)) - { - (*itr)->ToUnit()->HandleEmoteCommand(e.action.emote.emote); - TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_PLAY_EMOTE: target: %s (GuidLow: %u), emote: %u", - (*itr)->GetName().c_str(), (*itr)->GetGUID().GetCounter(), e.action.emote.emote); - } + target->ToUnit()->HandleEmoteCommand(e.action.emote.emote); + TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_PLAY_EMOTE: target: %s (GuidLow: %u), emote: %u", + target->GetName().c_str(), target->GetGUID().GetCounter(), e.action.emote.emote); } - - delete targets; } break; } case SMART_ACTION_SOUND: { - ObjectList* targets = GetTargets(e, unit); - if (targets) + for (WorldObject* target : targets) { - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsUnit(target)) { - if (IsUnit(*itr)) - { - if (e.action.sound.distance == 1) - (*itr)->PlayDistanceSound(e.action.sound.sound, e.action.sound.onlySelf ? (*itr)->ToPlayer() : nullptr); - else - (*itr)->PlayDirectSound(e.action.sound.sound, e.action.sound.onlySelf ? (*itr)->ToPlayer() : nullptr); + if (e.action.sound.distance == 1) + target->PlayDistanceSound(e.action.sound.sound, e.action.sound.onlySelf ? target->ToPlayer() : nullptr); + else + target->PlayDirectSound(e.action.sound.sound, e.action.sound.onlySelf ? target->ToPlayer() : nullptr); - TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_SOUND: target: %s (GuidLow: %u), sound: %u, onlyself: %u", - (*itr)->GetName().c_str(), (*itr)->GetGUID().GetCounter(), e.action.sound.sound, e.action.sound.onlySelf); - } + TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_SOUND: target: %s (GuidLow: %u), sound: %u, onlyself: %u", + target->GetName().c_str(), target->GetGUID().GetCounter(), e.action.sound.sound, e.action.sound.onlySelf); } - - delete targets; } break; } case SMART_ACTION_SET_FACTION: { - ObjectList* targets = GetTargets(e, unit); - if (targets) + for (WorldObject* target : targets) { - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsCreature(target)) { - if (IsCreature(*itr)) + if (e.action.faction.factionID) { - if (e.action.faction.factionID) + target->ToCreature()->SetFaction(e.action.faction.factionID); + TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_SET_FACTION: Creature entry %u, GuidLow %u set faction to %u", + target->GetEntry(), target->GetGUID().GetCounter(), e.action.faction.factionID); + } + else + { + if (CreatureTemplate const* ci = sObjectMgr->GetCreatureTemplate(target->ToCreature()->GetEntry())) { - (*itr)->ToCreature()->SetFaction(e.action.faction.factionID); - TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_SET_FACTION: Creature entry %u, GuidLow %u set faction to %u", - (*itr)->GetEntry(), (*itr)->GetGUID().GetCounter(), e.action.faction.factionID); - } - else - { - if (CreatureTemplate const* ci = sObjectMgr->GetCreatureTemplate((*itr)->ToCreature()->GetEntry())) + if (target->ToCreature()->GetFaction() != ci->faction) { - if ((*itr)->ToCreature()->GetFaction() != ci->faction) - { - (*itr)->ToCreature()->SetFaction(ci->faction); - TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_SET_FACTION: Creature entry %u, GuidLow %u set faction to %u", - (*itr)->GetEntry(), (*itr)->GetGUID().GetCounter(), ci->faction); - } + target->ToCreature()->SetFaction(ci->faction); + TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_SET_FACTION: Creature entry %u, GuidLow %u set faction to %u", + target->GetEntry(), target->GetGUID().GetCounter(), ci->faction); } } } } - - delete targets; } break; } case SMART_ACTION_MORPH_TO_ENTRY_OR_MODEL: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (!IsCreature(*itr)) + if (!IsCreature(target)) continue; if (e.action.morphOrMount.creature || e.action.morphOrMount.model) @@ -276,58 +364,46 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (CreatureTemplate const* ci = sObjectMgr->GetCreatureTemplate(e.action.morphOrMount.creature)) { uint32 displayId = ObjectMgr::ChooseDisplayId(ci); - (*itr)->ToCreature()->SetDisplayId(displayId); + target->ToCreature()->SetDisplayId(displayId); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_MORPH_TO_ENTRY_OR_MODEL: Creature entry %u, GuidLow %u set displayid to %u", - (*itr)->GetEntry(), (*itr)->GetGUID().GetCounter(), displayId); + target->GetEntry(), target->GetGUID().GetCounter(), displayId); } } //if no param1, then use value from param2 (modelId) else { - (*itr)->ToCreature()->SetDisplayId(e.action.morphOrMount.model); + target->ToCreature()->SetDisplayId(e.action.morphOrMount.model); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_MORPH_TO_ENTRY_OR_MODEL: Creature entry %u, GuidLow %u set displayid to %u", - (*itr)->GetEntry(), (*itr)->GetGUID().GetCounter(), e.action.morphOrMount.model); + target->GetEntry(), target->GetGUID().GetCounter(), e.action.morphOrMount.model); } } else { - (*itr)->ToCreature()->DeMorph(); + target->ToCreature()->DeMorph(); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_MORPH_TO_ENTRY_OR_MODEL: Creature entry %u, GuidLow %u demorphs.", - (*itr)->GetEntry(), (*itr)->GetGUID().GetCounter()); + target->GetEntry(), target->GetGUID().GetCounter()); } } - - delete targets; break; } case SMART_ACTION_FAIL_QUEST: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsPlayer(*itr)) + if (IsPlayer(target)) { - (*itr)->ToPlayer()->FailQuest(e.action.quest.quest); + target->ToPlayer()->FailQuest(e.action.quest.quest); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_FAIL_QUEST: Player guidLow %u fails quest %u", - (*itr)->GetGUID().GetCounter(), e.action.quest.quest); + target->GetGUID().GetCounter(), e.action.quest.quest); } } - - delete targets; break; } case SMART_ACTION_OFFER_QUEST: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (Player* pTarget = (*itr)->ToPlayer()) + if (Player* pTarget = target->ToPlayer()) { if (Quest const* q = sObjectMgr->GetQuestTemplate(e.action.questOffer.questID)) { @@ -351,33 +427,21 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u } } } - - delete targets; break; } case SMART_ACTION_SET_REACT_STATE: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (!IsCreature(*itr)) + if (!IsCreature(target)) continue; - (*itr)->ToCreature()->SetReactState(ReactStates(e.action.react.state)); + target->ToCreature()->SetReactState(ReactStates(e.action.react.state)); } - - delete targets; break; } case SMART_ACTION_RANDOM_EMOTE: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - uint32 emotes[SMART_ACTION_PARAM_COUNT]; emotes[0] = e.action.randomEmote.emote1; emotes[1] = e.action.randomEmote.emote2; @@ -397,23 +461,18 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u } if (count == 0) - { - delete targets; break; - } - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsUnit(*itr)) + if (IsUnit(target)) { uint32 emote = temp[urand(0, count - 1)]; - (*itr)->ToUnit()->HandleEmoteCommand(emote); + target->ToUnit()->HandleEmoteCommand(emote); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_RANDOM_EMOTE: Creature guidLow %u handle random emote %u", - (*itr)->GetGUID().GetCounter(), emote); + target->GetGUID().GetCounter(), emote); } } - - delete targets; break; } case SMART_ACTION_THREAT_ALL_PCT: @@ -438,71 +497,56 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (!me) break; - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsUnit(*itr)) + if (IsUnit(target)) { - me->getThreatManager().modifyThreatPercent((*itr)->ToUnit(), e.action.threatPCT.threatINC ? (int32)e.action.threatPCT.threatINC : -(int32)e.action.threatPCT.threatDEC); + me->getThreatManager().modifyThreatPercent(target->ToUnit(), e.action.threatPCT.threatINC ? (int32)e.action.threatPCT.threatINC : -(int32)e.action.threatPCT.threatDEC); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_THREAT_SINGLE_PCT: Creature guidLow %u modify threat for unit %u, value %i", - me->GetGUID().GetCounter(), (*itr)->GetGUID().GetCounter(), e.action.threatPCT.threatINC ? (int32)e.action.threatPCT.threatINC : -(int32)e.action.threatPCT.threatDEC); + me->GetGUID().GetCounter(), target->GetGUID().GetCounter(), e.action.threatPCT.threatINC ? (int32)e.action.threatPCT.threatINC : -(int32)e.action.threatPCT.threatDEC); } } - - delete targets; break; } case SMART_ACTION_CALL_AREAEXPLOREDOREVENTHAPPENS: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { // Special handling for vehicles - if (IsUnit(*itr)) - if (Vehicle* vehicle = (*itr)->ToUnit()->GetVehicleKit()) + if (IsUnit(target)) + if (Vehicle* vehicle = target->ToUnit()->GetVehicleKit()) for (SeatMap::iterator it = vehicle->Seats.begin(); it != vehicle->Seats.end(); ++it) - if (Player* player = ObjectAccessor::GetPlayer(*(*itr), it->second.Passenger.Guid)) + if (Player* player = ObjectAccessor::GetPlayer(*target, it->second.Passenger.Guid)) player->AreaExploredOrEventHappens(e.action.quest.quest); - if (IsPlayer(*itr)) + if (IsPlayer(target)) { - (*itr)->ToPlayer()->AreaExploredOrEventHappens(e.action.quest.quest); + target->ToPlayer()->AreaExploredOrEventHappens(e.action.quest.quest); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_CALL_AREAEXPLOREDOREVENTHAPPENS: Player guidLow %u credited quest %u", - (*itr)->GetGUID().GetCounter(), e.action.quest.quest); + target->GetGUID().GetCounter(), e.action.quest.quest); } } - - delete targets; break; } case SMART_ACTION_CAST: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) + if (targets.empty()) break; - if (e.action.cast.targetsLimit > 0 && targets->size() > e.action.cast.targetsLimit) - Trinity::Containers::RandomResize(*targets, e.action.cast.targetsLimit); + if (e.action.cast.targetsLimit > 0 && targets.size() > e.action.cast.targetsLimit) + Trinity::Containers::RandomResize(targets, e.action.cast.targetsLimit); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { + // may be nullptr if (go) - { - // may be nullptr - go->CastSpell((*itr)->ToUnit(), e.action.cast.spell); - } + go->CastSpell(target->ToUnit(), e.action.cast.spell); - if (!IsUnit(*itr)) + if (!IsUnit(target)) continue; - if (!(e.action.cast.castFlags & SMARTCAST_AURA_NOT_PRESENT) || !(*itr)->ToUnit()->HasAura(e.action.cast.spell)) + if (!(e.action.cast.castFlags & SMARTCAST_AURA_NOT_PRESENT) || !target->ToUnit()->HasAura(e.action.cast.spell)) { TriggerCastFlags triggerFlag = TRIGGERED_NONE; if (e.action.cast.castFlags & SMARTCAST_TRIGGERED) @@ -527,28 +571,26 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(e.action.cast.spell); int32 mana = me->GetPower(POWER_MANA); - if (me->GetDistance(*itr) > spellInfo->GetMaxRange(true) || - me->GetDistance(*itr) < spellInfo->GetMinRange(true) || - !me->IsWithinLOSInMap(*itr) || + if (me->GetDistance(target) > spellInfo->GetMaxRange(true) || + me->GetDistance(target) < spellInfo->GetMinRange(true) || + !me->IsWithinLOSInMap(target) || mana < spellInfo->CalcPowerCost(me, spellInfo->GetSchoolMask())) _allowMove = true; ENSURE_AI(SmartAI, me->AI())->SetCombatMove(_allowMove); } - me->CastSpell((*itr)->ToUnit(), e.action.cast.spell, triggerFlag); + me->CastSpell(target->ToUnit(), e.action.cast.spell, triggerFlag); } else if (go) - go->CastSpell((*itr)->ToUnit(), e.action.cast.spell, triggerFlag); + go->CastSpell(target->ToUnit(), e.action.cast.spell, triggerFlag); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_CAST:: %s: %u casts spell %u on target %u with castflags %u", - (me ? me->GetGUID() : go->GetGUID()).GetTypeName(), me ? me->GetGUID().GetCounter() : go->GetGUID().GetCounter(), e.action.cast.spell, (*itr)->GetGUID().GetCounter(), e.action.cast.castFlags); + (me ? me->GetGUID() : go->GetGUID()).GetTypeName(), me ? me->GetGUID().GetCounter() : go->GetGUID().GetCounter(), e.action.cast.spell, target->GetGUID().GetCounter(), e.action.cast.castFlags); } else - TC_LOG_DEBUG("scripts.ai", "Spell %u not cast because it has flag SMARTCAST_AURA_NOT_PRESENT and the target (%s) already has the aura", e.action.cast.spell, (*itr)->GetGUID().ToString().c_str()); + TC_LOG_DEBUG("scripts.ai", "Spell %u not cast because it has flag SMARTCAST_AURA_NOT_PRESENT and the target (%s) already has the aura", e.action.cast.spell, target->GetGUID().ToString().c_str()); } - - delete targets; break; } case SMART_ACTION_INVOKER_CAST: @@ -557,19 +599,18 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (!tempLastInvoker) break; - ObjectList* targets = GetTargets(e, unit); - if (!targets) + if (targets.empty()) break; - if (e.action.cast.targetsLimit > 0 && targets->size() > e.action.cast.targetsLimit) - Trinity::Containers::RandomResize(*targets, e.action.cast.targetsLimit); + if (e.action.cast.targetsLimit > 0 && targets.size() > e.action.cast.targetsLimit) + Trinity::Containers::RandomResize(targets, e.action.cast.targetsLimit); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (!IsUnit(*itr)) + if (!IsUnit(target)) continue; - if (!(e.action.cast.castFlags & SMARTCAST_AURA_NOT_PRESENT) || !(*itr)->ToUnit()->HasAura(e.action.cast.spell)) + if (!(e.action.cast.castFlags & SMARTCAST_AURA_NOT_PRESENT) || !target->ToUnit()->HasAura(e.action.cast.spell)) { if (e.action.cast.castFlags & SMARTCAST_INTERRUPT_PREVIOUS) tempLastInvoker->InterruptNonMeleeSpells(false); @@ -583,149 +624,111 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u triggerFlag = TRIGGERED_FULL_MASK; } - tempLastInvoker->CastSpell((*itr)->ToUnit(), e.action.cast.spell, triggerFlag); + tempLastInvoker->CastSpell(target->ToUnit(), e.action.cast.spell, triggerFlag); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_INVOKER_CAST: Invoker %u casts spell %u on target %u with castflags %u", - tempLastInvoker->GetGUID().GetCounter(), e.action.cast.spell, (*itr)->GetGUID().GetCounter(), e.action.cast.castFlags); + tempLastInvoker->GetGUID().GetCounter(), e.action.cast.spell, target->GetGUID().GetCounter(), e.action.cast.castFlags); } else - TC_LOG_DEBUG("scripts.ai", "Spell %u not cast because it has flag SMARTCAST_AURA_NOT_PRESENT and the target (%s) already has the aura", e.action.cast.spell, (*itr)->GetGUID().ToString().c_str()); + TC_LOG_DEBUG("scripts.ai", "Spell %u not cast because it has flag SMARTCAST_AURA_NOT_PRESENT and the target (%s) already has the aura", e.action.cast.spell, target->GetGUID().ToString().c_str()); } - - delete targets; break; } case SMART_ACTION_ADD_AURA: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsUnit(*itr)) + if (IsUnit(target)) { - (*itr)->ToUnit()->AddAura(e.action.cast.spell, (*itr)->ToUnit()); + target->ToUnit()->AddAura(e.action.cast.spell, target->ToUnit()); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_ADD_AURA: Adding aura %u to unit %u", - e.action.cast.spell, (*itr)->GetGUID().GetCounter()); + e.action.cast.spell, target->GetGUID().GetCounter()); } } - - delete targets; break; } case SMART_ACTION_ACTIVATE_GOBJECT: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsGameObject(*itr)) + if (IsGameObject(target)) { // Activate - (*itr)->ToGameObject()->SetLootState(GO_READY); - (*itr)->ToGameObject()->UseDoorOrButton(0, false, unit); + target->ToGameObject()->SetLootState(GO_READY); + target->ToGameObject()->UseDoorOrButton(0, false, unit); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_ACTIVATE_GOBJECT. Gameobject %u (entry: %u) activated", - (*itr)->GetGUID().GetCounter(), (*itr)->GetEntry()); + target->GetGUID().GetCounter(), target->GetEntry()); } } - - delete targets; break; } case SMART_ACTION_RESET_GOBJECT: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsGameObject(*itr)) + if (IsGameObject(target)) { - (*itr)->ToGameObject()->ResetDoorOrButton(); + target->ToGameObject()->ResetDoorOrButton(); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_RESET_GOBJECT. Gameobject %u (entry: %u) reset", - (*itr)->GetGUID().GetCounter(), (*itr)->GetEntry()); + target->GetGUID().GetCounter(), target->GetEntry()); } } - - delete targets; break; } case SMART_ACTION_SET_EMOTE_STATE: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsUnit(*itr)) + if (IsUnit(target)) { - (*itr)->ToUnit()->SetUInt32Value(UNIT_NPC_EMOTESTATE, e.action.emote.emote); + target->ToUnit()->SetUInt32Value(UNIT_NPC_EMOTESTATE, e.action.emote.emote); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_SET_EMOTE_STATE. Unit %u set emotestate to %u", - (*itr)->GetGUID().GetCounter(), e.action.emote.emote); + target->GetGUID().GetCounter(), e.action.emote.emote); } } - - delete targets; break; } case SMART_ACTION_SET_UNIT_FLAG: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsUnit(*itr)) + if (IsUnit(target)) { if (!e.action.unitFlag.type) { - (*itr)->ToUnit()->SetFlag(UNIT_FIELD_FLAGS, e.action.unitFlag.flag); + target->ToUnit()->SetFlag(UNIT_FIELD_FLAGS, e.action.unitFlag.flag); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_SET_UNIT_FLAG. Unit %u added flag %u to UNIT_FIELD_FLAGS", - (*itr)->GetGUID().GetCounter(), e.action.unitFlag.flag); + target->GetGUID().GetCounter(), e.action.unitFlag.flag); } else { - (*itr)->ToUnit()->SetFlag(UNIT_FIELD_FLAGS_2, e.action.unitFlag.flag); + target->ToUnit()->SetFlag(UNIT_FIELD_FLAGS_2, e.action.unitFlag.flag); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_SET_UNIT_FLAG. Unit %u added flag %u to UNIT_FIELD_FLAGS_2", - (*itr)->GetGUID().GetCounter(), e.action.unitFlag.flag); + target->GetGUID().GetCounter(), e.action.unitFlag.flag); } } } - - delete targets; break; } case SMART_ACTION_REMOVE_UNIT_FLAG: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsUnit(*itr)) + if (IsUnit(target)) { if (!e.action.unitFlag.type) { - (*itr)->ToUnit()->RemoveFlag(UNIT_FIELD_FLAGS, e.action.unitFlag.flag); + target->ToUnit()->RemoveFlag(UNIT_FIELD_FLAGS, e.action.unitFlag.flag); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_REMOVE_UNIT_FLAG. Unit %u removed flag %u to UNIT_FIELD_FLAGS", - (*itr)->GetGUID().GetCounter(), e.action.unitFlag.flag); + target->GetGUID().GetCounter(), e.action.unitFlag.flag); } else { - (*itr)->ToUnit()->RemoveFlag(UNIT_FIELD_FLAGS_2, e.action.unitFlag.flag); + target->ToUnit()->RemoveFlag(UNIT_FIELD_FLAGS_2, e.action.unitFlag.flag); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_REMOVE_UNIT_FLAG. Unit %u removed flag %u to UNIT_FIELD_FLAGS_2", - (*itr)->GetGUID().GetCounter(), e.action.unitFlag.flag); + target->GetGUID().GetCounter(), e.action.unitFlag.flag); } } } - - delete targets; break; } case SMART_ACTION_AUTO_ATTACK: @@ -826,33 +829,27 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u } case SMART_ACTION_REMOVEAURASFROMSPELL: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (!IsUnit(*itr)) + if (!IsUnit(target)) continue; if (e.action.removeAura.spell) { if (e.action.removeAura.charges) { - if (Aura* aur = (*itr)->ToUnit()->GetAura(e.action.removeAura.spell)) + if (Aura* aur = target->ToUnit()->GetAura(e.action.removeAura.spell)) aur->ModCharges(-static_cast(e.action.removeAura.charges), AURA_REMOVE_BY_EXPIRE); } else - (*itr)->ToUnit()->RemoveAurasDueToSpell(e.action.removeAura.spell); + target->ToUnit()->RemoveAurasDueToSpell(e.action.removeAura.spell); } else - (*itr)->ToUnit()->RemoveAllAuras(); + target->ToUnit()->RemoveAllAuras(); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction: SMART_ACTION_REMOVEAURASFROMSPELL: Unit %u, spell %u", - (*itr)->GetGUID().GetCounter(), e.action.removeAura.spell); + target->GetGUID().GetCounter(), e.action.removeAura.spell); } - - delete targets; break; } case SMART_ACTION_FOLLOW: @@ -860,26 +857,23 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (!IsSmart()) break; - ObjectList* targets = GetTargets(e, unit); - if (!targets) + if (targets.empty()) { ENSURE_AI(SmartAI, me->AI())->StopFollow(false); break; } - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsUnit(*itr)) + if (IsUnit(target)) { float angle = e.action.follow.angle > 6 ? (e.action.follow.angle * M_PI / 180.0f) : e.action.follow.angle; - ENSURE_AI(SmartAI, me->AI())->SetFollow((*itr)->ToUnit(), float(e.action.follow.dist) + 0.1f, angle, e.action.follow.credit, e.action.follow.entry, e.action.follow.creditType); + ENSURE_AI(SmartAI, me->AI())->SetFollow(target->ToUnit(), float(e.action.follow.dist) + 0.1f, angle, e.action.follow.credit, e.action.follow.entry, e.action.follow.creditType); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction: SMART_ACTION_FOLLOW: Creature %u following target %u", - me->GetGUID().GetCounter(), (*itr)->GetGUID().GetCounter()); + me->GetGUID().GetCounter(), target->GetGUID().GetCounter()); break; } } - - delete targets; break; } case SMART_ACTION_RANDOM_PHASE: @@ -887,28 +881,11 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (!GetBaseObject()) break; - uint32 phases[SMART_ACTION_PARAM_COUNT]; - phases[0] = e.action.randomPhase.phase1; - phases[1] = e.action.randomPhase.phase2; - phases[2] = e.action.randomPhase.phase3; - phases[3] = e.action.randomPhase.phase4; - phases[4] = e.action.randomPhase.phase5; - phases[5] = e.action.randomPhase.phase6; - uint32 temp[SMART_ACTION_PARAM_COUNT]; - uint32 count = 0; - for (uint8 i = 0; i < SMART_ACTION_PARAM_COUNT; i++) - { - if (phases[i] > 0) - { - temp[count] = phases[i]; - ++count; - } - } + std::vector phases; + std::copy_if(std::begin(e.action.randomPhase.phases), std::end(e.action.randomPhase.phases), + std::back_inserter(phases), [](uint32 phase) { return phase != 0; }); - if (count == 0) - break; - - uint32 phase = temp[urand(0, count - 1)]; + uint32 phase = Trinity::Containers::SelectRandomContainerElement(phases); SetPhase(phase); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction: SMART_ACTION_RANDOM_PHASE: Creature %u sets event phase to %u", GetBaseObject()->GetGUID().GetCounter(), phase); @@ -941,26 +918,20 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u } else // Specific target type { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsPlayer(*itr)) + if (IsPlayer(target)) { - (*itr)->ToPlayer()->KilledMonsterCredit(e.action.killedMonster.creature); + target->ToPlayer()->KilledMonsterCredit(e.action.killedMonster.creature); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction: SMART_ACTION_CALL_KILLEDMONSTER: Player %u, Killcredit: %u", - (*itr)->GetGUID().GetCounter(), e.action.killedMonster.creature); + target->GetGUID().GetCounter(), e.action.killedMonster.creature); } - else if (IsUnit(*itr)) // Special handling for vehicles - if (Vehicle* vehicle = (*itr)->ToUnit()->GetVehicleKit()) + else if (IsUnit(target)) // Special handling for vehicles + if (Vehicle* vehicle = target->ToUnit()->GetVehicleKit()) for (SeatMap::iterator seatItr = vehicle->Seats.begin(); seatItr != vehicle->Seats.end(); ++seatItr) - if (Player* player = ObjectAccessor::GetPlayer(*(*itr), seatItr->second.Passenger.Guid)) + if (Player* player = ObjectAccessor::GetPlayer(*target, seatItr->second.Passenger.Guid)) player->KilledMonsterCredit(e.action.killedMonster.creature); } - - delete targets; } break; } @@ -1013,29 +984,20 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u break; } - ObjectList* targets = GetTargets(e, unit); - if (!targets) + if (targets.empty()) break; - instance->SetGuidData(e.action.setInstanceData64.field, targets->front()->GetGUID()); + instance->SetGuidData(e.action.setInstanceData64.field, targets.front()->GetGUID()); TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction: SMART_ACTION_SET_INST_DATA64: Field: %u, data: %s", - e.action.setInstanceData64.field, targets->front()->GetGUID().ToString().c_str()); - - delete targets; + e.action.setInstanceData64.field, targets.front()->GetGUID().ToString().c_str()); break; } case SMART_ACTION_UPDATE_TEMPLATE: { - ObjectList* targets = GetTargets(e, unit); - - if (!targets) - break; - - for (WorldObject* target : *targets) + for (WorldObject* target : targets) if (IsCreature(target)) target->ToCreature()->UpdateEntry(e.action.updateTemplate.creature, target->ToCreature()->GetCreatureData(), e.action.updateTemplate.updateLevel != 0); - delete targets; break; } case SMART_ACTION_DIE: @@ -1049,39 +1011,31 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u } case SMART_ACTION_SET_IN_COMBAT_WITH_ZONE: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) + for (WorldObject* target : targets) + { + if (IsCreature(target)) { - (*itr)->ToCreature()->SetInCombatWithZone(); - TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction: SMART_ACTION_SET_IN_COMBAT_WITH_ZONE: Creature %u, target: %u", me->GetGUID().GetCounter(), (*itr)->GetGUID().GetCounter()); + target->ToCreature()->SetInCombatWithZone(); + TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction: SMART_ACTION_SET_IN_COMBAT_WITH_ZONE: Creature %u, target: %u", me->GetGUID().GetCounter(), target->GetGUID().GetCounter()); } - - delete targets; + } break; } case SMART_ACTION_CALL_FOR_HELP: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) + for (WorldObject* target : targets) + { + if (IsCreature(target)) { - (*itr)->ToCreature()->CallForHelp((float)e.action.callHelp.range); + target->ToCreature()->CallForHelp((float)e.action.callHelp.range); if (e.action.callHelp.withEmote) { Trinity::BroadcastTextBuilder builder(me, CHAT_MSG_MONSTER_EMOTE, BROADCAST_TEXT_CALL_FOR_HELP, me->getGender()); sCreatureTextMgr->SendChatPacket(me, builder, CHAT_MSG_MONSTER_EMOTE); } - TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction: SMART_ACTION_CALL_FOR_HELP: Creature %u, target: %u", me->GetGUID().GetCounter(), (*itr)->GetGUID().GetCounter()); + TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction: SMART_ACTION_CALL_FOR_HELP: Creature %u, target: %u", me->GetGUID().GetCounter(), target->GetGUID().GetCounter()); } - - delete targets; + } break; } case SMART_ACTION_SET_SHEATH: @@ -1096,15 +1050,10 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u } case SMART_ACTION_FORCE_DESPAWN: { - ObjectList* targets = GetTargets(e, unit); - - if (!targets) - break; - // there should be at least a world update tick before despawn, to avoid breaking linked actions int32 const respawnDelay = std::max(e.action.forceDespawn.delay, 1); - for (WorldObject* target : *targets) + for (WorldObject* target : targets) { if (Creature* creatureTarget = target->ToCreature()) { @@ -1119,55 +1068,35 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u else if (GameObject* goTarget = target->ToGameObject()) goTarget->SetRespawnTime(respawnDelay); } - - delete targets; break; } case SMART_ACTION_SET_INGAME_PHASE_ID: { - ObjectList* targets = GetTargets(e, unit); - - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { if (e.action.ingamePhaseId.apply == 1) - PhasingHandler::AddPhase(*itr, e.action.ingamePhaseId.id, true); + PhasingHandler::AddPhase(target, e.action.ingamePhaseId.id, true); else - PhasingHandler::RemovePhase(*itr, e.action.ingamePhaseId.id, true); + PhasingHandler::RemovePhase(target, e.action.ingamePhaseId.id, true); } - - delete targets; break; } case SMART_ACTION_SET_INGAME_PHASE_GROUP: { - ObjectList* targets = GetTargets(e, unit); - - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { if (e.action.ingamePhaseGroup.apply == 1) - PhasingHandler::AddPhaseGroup(*itr, e.action.ingamePhaseGroup.groupId, true); + PhasingHandler::AddPhaseGroup(target, e.action.ingamePhaseGroup.groupId, true); else - PhasingHandler::RemovePhaseGroup(*itr, e.action.ingamePhaseGroup.groupId, true); + PhasingHandler::RemovePhaseGroup(target, e.action.ingamePhaseGroup.groupId, true); } - - delete targets; break; } case SMART_ACTION_MOUNT_TO_ENTRY_OR_MODEL: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (!IsUnit(*itr)) + if (!IsUnit(target)) continue; if (e.action.morphOrMount.creature || e.action.morphOrMount.model) @@ -1175,110 +1104,80 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (e.action.morphOrMount.creature > 0) { if (CreatureTemplate const* cInfo = sObjectMgr->GetCreatureTemplate(e.action.morphOrMount.creature)) - (*itr)->ToUnit()->Mount(ObjectMgr::ChooseDisplayId(cInfo)); + target->ToUnit()->Mount(ObjectMgr::ChooseDisplayId(cInfo)); } else - (*itr)->ToUnit()->Mount(e.action.morphOrMount.model); + target->ToUnit()->Mount(e.action.morphOrMount.model); } else - (*itr)->ToUnit()->Dismount(); + target->ToUnit()->Dismount(); } - - delete targets; break; } case SMART_ACTION_SET_INVINCIBILITY_HP_LEVEL: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsCreature(*itr)) + if (IsCreature(target)) { - SmartAI* ai = CAST_AI(SmartAI, (*itr)->ToCreature()->AI()); + SmartAI* ai = CAST_AI(SmartAI, target->ToCreature()->AI()); if (!ai) continue; if (e.action.invincHP.percent) - ai->SetInvincibilityHpLevel((*itr)->ToCreature()->CountPctFromMaxHealth(e.action.invincHP.percent)); + ai->SetInvincibilityHpLevel(target->ToCreature()->CountPctFromMaxHealth(e.action.invincHP.percent)); else ai->SetInvincibilityHpLevel(e.action.invincHP.minHP); } } - - delete targets; break; } case SMART_ACTION_SET_DATA: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsCreature(*itr)) - (*itr)->ToCreature()->AI()->SetData(e.action.setData.field, e.action.setData.data); - else if (IsGameObject(*itr)) - (*itr)->ToGameObject()->AI()->SetData(e.action.setData.field, e.action.setData.data); + if (IsCreature(target)) + target->ToCreature()->AI()->SetData(e.action.setData.field, e.action.setData.data); + else if (IsGameObject(target)) + target->ToGameObject()->AI()->SetData(e.action.setData.field, e.action.setData.data); } - - delete targets; break; } case SMART_ACTION_MOVE_OFFSET: { - if (ObjectList* targets = GetTargets(e, unit)) + for (WorldObject* target : targets) { - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (!IsCreature(*itr)) - continue; + if (!IsCreature(target)) + continue; - if (!(e.event.event_flags & SMART_EVENT_FLAG_WHILE_CHARMED) && IsCharmedCreature(*itr)) - continue; + if (!(e.event.event_flags & SMART_EVENT_FLAG_WHILE_CHARMED) && IsCharmedCreature(target)) + continue; - Position pos = (*itr)->GetPosition(); + Position pos = target->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; + // 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; + target->ToCreature()->GetMotionMaster()->MovePoint(SMART_RANDOM_POINT, x, y, z); } - break; } case SMART_ACTION_SET_VISIBILITY: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsUnit(target)) + target->ToUnit()->SetVisible(e.action.visibility.state ? true : false); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->SetVisible(e.action.visibility.state ? true : false); - - delete targets; break; } case SMART_ACTION_SET_ACTIVE: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + target->setActive(e.action.active.state ? true : false); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - (*itr)->setActive(e.action.active.state ? true : false); - - delete targets; break; } case SMART_ACTION_ATTACK_START: @@ -1286,36 +1185,28 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (!me) break; - ObjectList* targets = GetTargets(e, unit); - if (!targets) + if (targets.empty()) break; // attack random target - if (Unit* target = Trinity::Containers::SelectRandomContainerElement(*targets)->ToUnit()) + if (Unit* target = Trinity::Containers::SelectRandomContainerElement(targets)->ToUnit()) me->AI()->AttackStart(target); - - delete targets; break; } case SMART_ACTION_SUMMON_CREATURE: { - ObjectList* targets = GetTargets(e, unit); - if (targets) - { - float x, y, z, o; - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - (*itr)->GetPosition(x, y, z, o); - x += e.target.x; - y += e.target.y; - z += e.target.z; - o += e.target.o; - if (Creature* summon = GetBaseObject()->SummonCreature(e.action.summonCreature.creature, x, y, z, o, (TempSummonType)e.action.summonCreature.type, e.action.summonCreature.duration)) - if (e.action.summonCreature.attackInvoker) - summon->AI()->AttackStart((*itr)->ToUnit()); - } - delete targets; + float x, y, z, o; + for (WorldObject* target : targets) + { + target->GetPosition(x, y, z, o); + x += e.target.x; + y += e.target.y; + z += e.target.z; + o += e.target.o; + if (Creature* summon = GetBaseObject()->SummonCreature(e.action.summonCreature.creature, x, y, z, o, (TempSummonType)e.action.summonCreature.type, e.action.summonCreature.duration)) + if (e.action.summonCreature.attackInvoker) + summon->AI()->AttackStart(target->ToUnit()); } if (e.GetTargetType() != SMART_TARGET_POSITION) @@ -1331,43 +1222,29 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (!GetBaseObject()) break; - ObjectList* targets = GetTargets(e, unit); - if (targets) + for (WorldObject* target : targets) { - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - // allow gameobjects to summon gameobjects - //if (!IsUnit(*itr)) - // continue; - - 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, GOSummonType(e.action.summonGO.summonType)); - } - - delete targets; + Position pos = target->GetPositionWithOffset(Position(e.target.x, e.target.y, e.target.z, e.target.o)); + QuaternionData rot = QuaternionData::fromEulerAnglesZYX(pos.GetOrientation(), 0.f, 0.f); + GetBaseObject()->SummonGameObject(e.action.summonGO.entry, pos, rot, e.action.summonGO.despawnTime, GOSummonType(e.action.summonGO.summonType)); } if (e.GetTargetType() != SMART_TARGET_POSITION) break; - 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, GOSummonType(e.action.summonGO.summonType)); + QuaternionData rot = QuaternionData::fromEulerAnglesZYX(e.target.o, 0.f, 0.f); + GetBaseObject()->SummonGameObject(e.action.summonGO.entry, Position(e.target.x, e.target.y, e.target.z, e.target.o), rot, e.action.summonGO.despawnTime, GOSummonType(e.action.summonGO.summonType)); break; } case SMART_ACTION_KILL_UNIT: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (!IsUnit(*itr)) + if (!IsUnit(target)) continue; - (*itr)->ToUnit()->KillSelf(); + target->ToUnit()->KillSelf(); } - - delete targets; break; } case SMART_ACTION_INSTALL_AI_TEMPLATE: @@ -1377,59 +1254,40 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u } case SMART_ACTION_ADD_ITEM: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (!IsPlayer(*itr)) + if (!IsPlayer(target)) continue; - (*itr)->ToPlayer()->AddItem(e.action.item.entry, e.action.item.count); + target->ToPlayer()->AddItem(e.action.item.entry, e.action.item.count); } - - delete targets; break; } case SMART_ACTION_REMOVE_ITEM: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (!IsPlayer(*itr)) + if (!IsPlayer(target)) continue; - (*itr)->ToPlayer()->DestroyItemCount(e.action.item.entry, e.action.item.count, true); + target->ToPlayer()->DestroyItemCount(e.action.item.entry, e.action.item.count, true); } - - delete targets; break; } case SMART_ACTION_STORE_TARGET_LIST: { - ObjectList* targets = GetTargets(e, unit); StoreTargetList(targets, e.action.storeTargets.id); break; } case SMART_ACTION_TELEPORT: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsPlayer(*itr)) - (*itr)->ToPlayer()->TeleportTo(e.action.teleport.mapID, e.target.x, e.target.y, e.target.z, e.target.o); - else if (IsCreature(*itr)) - (*itr)->ToCreature()->NearTeleportTo(e.target.x, e.target.y, e.target.z, e.target.o); + if (IsPlayer(target)) + target->ToPlayer()->TeleportTo(e.action.teleport.mapID, e.target.x, e.target.y, e.target.z, e.target.o); + else if (IsCreature(target)) + target->ToCreature()->NearTeleportTo(e.target.x, e.target.y, e.target.z, e.target.o); } - - delete targets; break; } case SMART_ACTION_SET_DISABLE_GRAVITY: @@ -1466,31 +1324,28 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u } case SMART_ACTION_SET_COUNTER: { - if (ObjectList* targets = GetTargets(e, unit)) + if (!targets.empty()) { - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsCreature(*itr)) + if (IsCreature(target)) { - if (SmartAI* ai = CAST_AI(SmartAI, (*itr)->ToCreature()->AI())) + if (SmartAI* ai = CAST_AI(SmartAI, target->ToCreature()->AI())) ai->GetScript()->StoreCounter(e.action.setCounter.counterId, e.action.setCounter.value, e.action.setCounter.reset); else TC_LOG_ERROR("sql.sql", "SmartScript: Action target for SMART_ACTION_SET_COUNTER is not using SmartAI, skipping"); } - else if (IsGameObject(*itr)) + else if (IsGameObject(target)) { - if (SmartGameObjectAI* ai = CAST_AI(SmartGameObjectAI, (*itr)->ToGameObject()->AI())) + if (SmartGameObjectAI* ai = CAST_AI(SmartGameObjectAI, target->ToGameObject()->AI())) ai->GetScript()->StoreCounter(e.action.setCounter.counterId, e.action.setCounter.value, e.action.setCounter.reset); else TC_LOG_ERROR("sql.sql", "SmartScript: Action target for SMART_ACTION_SET_COUNTER is not using SmartGameObjectAI, skipping"); } } - - delete targets; } else StoreCounter(e.action.setCounter.counterId, e.action.setCounter.value, e.action.setCounter.reset); - break; } case SMART_ACTION_WP_START: @@ -1504,20 +1359,14 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u // ensure that SMART_ESCORT_TARGETS contains at least one player reference bool stored = false; - ObjectList* targets = GetTargets(e, unit); - if (targets) + for (WorldObject* target : targets) { - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (IsPlayer(target)) { - if (IsPlayer(*itr)) - { - stored = true; - StoreTargetList(targets, SMART_ESCORT_TARGETS); - break; - } + stored = true; + StoreTargetList(targets, SMART_ESCORT_TARGETS); + break; } - if (!stored) - delete targets; } me->SetReactState((ReactStates)e.action.wpStart.reactState); @@ -1566,31 +1415,19 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u me->SetFacingTo((me->GetTransport() ? me->GetTransportHomePosition() : me->GetHomePosition()).GetOrientation()); else if (e.GetTargetType() == SMART_TARGET_POSITION) me->SetFacingTo(e.target.o); - else if (ObjectList* targets = GetTargets(e, unit)) - { - if (!targets->empty()) - me->SetFacingToObject(*targets->begin()); - - delete targets; - } - + else if (!targets.empty()) + me->SetFacingToObject(targets.front()); break; } case SMART_ACTION_PLAYMOVIE: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (!IsPlayer(*itr)) + if (!IsPlayer(target)) continue; - (*itr)->ToPlayer()->SendMovieStart(e.action.movie.entry); + target->ToPlayer()->SendMovieStart(e.action.movie.entry); } - - delete targets; break; } case SMART_ACTION_MOVE_TO_POS: @@ -1608,12 +1445,8 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u e.GetTargetType() == SMART_TARGET_CLOSEST_ENEMY || e.GetTargetType() == SMART_TARGET_CLOSEST_FRIENDLY || e.GetTargetType() == SMART_TARGET_SELF || e.GetTargetType() == SMART_TARGET_STORED)*/ { - if (ObjectList* targets = GetTargets(e, unit)) - { - // we want to move to random element - target = Trinity::Containers::SelectRandomContainerElement(*targets); - delete targets; - } + // we want to move to random element + target = Trinity::Containers::SelectRandomContainerElement(targets); } if (!target) @@ -1637,49 +1470,34 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u } case SMART_ACTION_RESPAWN_TARGET: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsCreature(*itr)) - (*itr)->ToCreature()->Respawn(); - else if (IsGameObject(*itr)) + if (IsCreature(target)) + target->ToCreature()->Respawn(); + else if (IsGameObject(target)) { // do not modify respawndelay of already spawned gameobjects - if ((*itr)->ToGameObject()->isSpawnedByDefault()) - (*itr)->ToGameObject()->Respawn(); + if (target->ToGameObject()->isSpawnedByDefault()) + target->ToGameObject()->Respawn(); else - (*itr)->ToGameObject()->SetRespawnTime(e.action.RespawnTarget.goRespawnTime); + target->ToGameObject()->SetRespawnTime(e.action.RespawnTarget.goRespawnTime); } } - - delete targets; break; } case SMART_ACTION_CLOSE_GOSSIP: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsPlayer(target)) + target->ToPlayer()->PlayerTalkClass->SendCloseGossip(); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsPlayer(*itr)) - (*itr)->ToPlayer()->PlayerTalkClass->SendCloseGossip(); - - delete targets; break; } case SMART_ACTION_EQUIP: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (Creature* npc = (*itr)->ToCreature()) + if (Creature* npc = target->ToCreature()) { uint32 slot[3]; int8 equipId = (int8)e.action.equip.entry; @@ -1711,8 +1529,6 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u npc->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 2, slot[2]); } } - - delete targets; break; } case SMART_ACTION_CREATE_TIMED_EVENT: @@ -1756,35 +1572,29 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u break; case SMART_ACTION_OVERRIDE_SCRIPT_BASE_OBJECT: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsCreature(*itr)) + if (IsCreature(target)) { if (!meOrigGUID && me) meOrigGUID = me->GetGUID(); if (!goOrigGUID && go) goOrigGUID = go->GetGUID(); go = nullptr; - me = (*itr)->ToCreature(); + me = target->ToCreature(); break; } - else if (IsGameObject(*itr)) + else if (IsGameObject(target)) { if (!meOrigGUID && me) meOrigGUID = me->GetGUID(); if (!goOrigGUID && go) goOrigGUID = go->GetGUID(); - go = (*itr)->ToGameObject(); + go = target->ToGameObject(); me = nullptr; break; } } - - delete targets; break; } case SMART_ACTION_RESET_SCRIPT_BASE_OBJECT: @@ -1802,17 +1612,12 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u float attackDistance = float(e.action.setRangedMovement.distance); float attackAngle = float(e.action.setRangedMovement.angle) / 180.0f * float(M_PI); - ObjectList* targets = GetTargets(e, unit); - if (targets) - { - for (ObjectList::iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (Creature* target = (*itr)->ToCreature()) - if (IsSmart(target) && target->GetVictim()) - if (ENSURE_AI(SmartAI, target->AI())->CanCombatMove()) - target->GetMotionMaster()->MoveChase(target->GetVictim(), attackDistance, attackAngle); + for (WorldObject* target : targets) + if (Creature* creature = target->ToCreature()) + if (IsSmart(creature) && creature->GetVictim()) + if (ENSURE_AI(SmartAI, creature->AI())->CanCombatMove()) + creature->GetMotionMaster()->MoveChase(creature->GetVictim(), attackDistance, attackAngle); - delete targets; - } break; } case SMART_ACTION_CALL_TIMED_ACTIONLIST: @@ -1823,223 +1628,157 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u break; } - if (ObjectList* targets = GetTargets(e, unit)) + for (WorldObject* target : targets) { - for (ObjectList::iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (Creature* creature = target->ToCreature()) { - if (Creature* target = (*itr)->ToCreature()) - { - if (IsSmart(target)) - ENSURE_AI(SmartAI, target->AI())->SetScript9(e, e.action.timedActionList.id, GetLastInvoker()); - } - else if (GameObject* goTarget = (*itr)->ToGameObject()) - { - if (IsSmartGO(goTarget)) - ENSURE_AI(SmartGameObjectAI, goTarget->AI())->SetScript9(e, e.action.timedActionList.id, GetLastInvoker()); - } + if (IsSmart(creature)) + ENSURE_AI(SmartAI, creature->AI())->SetScript9(e, e.action.timedActionList.id, GetLastInvoker()); + } + else if (GameObject* goTarget = target->ToGameObject()) + { + if (IsSmartGO(goTarget)) + ENSURE_AI(SmartGameObjectAI, goTarget->AI())->SetScript9(e, e.action.timedActionList.id, GetLastInvoker()); } - - delete targets; } break; } case SMART_ACTION_SET_NPC_FLAG: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsCreature(target)) + target->ToUnit()->SetUInt32Value(UNIT_NPC_FLAGS, e.action.unitFlag.flag); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToUnit()->SetUInt32Value(UNIT_NPC_FLAGS, e.action.unitFlag.flag); - - delete targets; break; } case SMART_ACTION_ADD_NPC_FLAG: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsCreature(target)) + target->ToUnit()->SetFlag(UNIT_NPC_FLAGS, e.action.unitFlag.flag); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToUnit()->SetFlag(UNIT_NPC_FLAGS, e.action.unitFlag.flag); - - delete targets; break; } case SMART_ACTION_REMOVE_NPC_FLAG: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsCreature(target)) + target->ToUnit()->RemoveFlag(UNIT_NPC_FLAGS, e.action.unitFlag.flag); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToUnit()->RemoveFlag(UNIT_NPC_FLAGS, e.action.unitFlag.flag); - - delete targets; break; } case SMART_ACTION_CROSS_CAST: { - ObjectList* casters = GetTargets(CreateEvent(SMART_EVENT_UPDATE_IC, 0, 0, 0, 0, 0, 0, SMART_ACTION_NONE, 0, 0, 0, 0, 0, 0, (SMARTAI_TARGETS)e.action.crossCast.targetType, e.action.crossCast.targetParam1, e.action.crossCast.targetParam2, e.action.crossCast.targetParam3, 0), unit); - if (!casters) + if (targets.empty()) break; - ObjectList* targets = GetTargets(e, unit); - if (!targets) - { - delete casters; // casters already validated, delete now - break; - } + ObjectVector casters; + GetTargets(casters, CreateSmartEvent(SMART_EVENT_UPDATE_IC, 0, 0, 0, 0, 0, 0, SMART_ACTION_NONE, 0, 0, 0, 0, 0, 0, (SMARTAI_TARGETS)e.action.crossCast.targetType, e.action.crossCast.targetParam1, e.action.crossCast.targetParam2, e.action.crossCast.targetParam3, 0), unit); - for (ObjectList::const_iterator itr = casters->begin(); itr != casters->end(); ++itr) + for (WorldObject* caster : casters) { - if (!IsUnit(*itr)) + if (!IsUnit(caster)) continue; - Unit* targetUnit = (*itr)->ToUnit(); + Unit* casterUnit = caster->ToUnit(); bool interruptedSpell = false; - for (ObjectList::const_iterator it = targets->begin(); it != targets->end(); ++it) + for (WorldObject* target : targets) { - if (!IsUnit(*it)) + if (!IsUnit(target)) continue; - if (!(e.action.crossCast.castFlags & SMARTCAST_AURA_NOT_PRESENT) || !(*it)->ToUnit()->HasAura(e.action.crossCast.spell)) + if (!(e.action.crossCast.castFlags & SMARTCAST_AURA_NOT_PRESENT) || !target->ToUnit()->HasAura(e.action.crossCast.spell)) { if (!interruptedSpell && e.action.crossCast.castFlags & SMARTCAST_INTERRUPT_PREVIOUS) { - targetUnit->InterruptNonMeleeSpells(false); + casterUnit->InterruptNonMeleeSpells(false); interruptedSpell = true; } - targetUnit->CastSpell((*it)->ToUnit(), e.action.crossCast.spell, (e.action.crossCast.castFlags & SMARTCAST_TRIGGERED) != 0); + casterUnit->CastSpell(target->ToUnit(), e.action.crossCast.spell, (e.action.crossCast.castFlags & SMARTCAST_TRIGGERED) != 0); } else - TC_LOG_DEBUG("scripts.ai", "Spell %u not cast because it has flag SMARTCAST_AURA_NOT_PRESENT and the target (%s) already has the aura", e.action.crossCast.spell, (*it)->GetGUID().ToString().c_str()); + TC_LOG_DEBUG("scripts.ai", "Spell %u not cast because it has flag SMARTCAST_AURA_NOT_PRESENT and the target (%s) already has the aura", e.action.crossCast.spell, target->GetGUID().ToString().c_str()); } } - - delete targets; - delete casters; break; } case SMART_ACTION_CALL_RANDOM_TIMED_ACTIONLIST: { - uint32 actions[SMART_ACTION_PARAM_COUNT]; - actions[0] = e.action.randTimedActionList.entry1; - actions[1] = e.action.randTimedActionList.entry2; - actions[2] = e.action.randTimedActionList.entry3; - actions[3] = e.action.randTimedActionList.entry4; - actions[4] = e.action.randTimedActionList.entry5; - actions[5] = e.action.randTimedActionList.entry6; - uint32 temp[SMART_ACTION_PARAM_COUNT]; - uint32 count = 0; - for (uint8 i = 0; i < SMART_ACTION_PARAM_COUNT; i++) - { - if (actions[i] > 0) - { - temp[count] = actions[i]; - ++count; - } - } + std::vector actionLists; + std::copy_if(std::begin(e.action.randTimedActionList.actionLists), std::end(e.action.randTimedActionList.actionLists), + std::back_inserter(actionLists), [](uint32 actionList) { return actionList != 0; }); - if (count == 0) - break; - - uint32 id = temp[urand(0, count - 1)]; + uint32 id = Trinity::Containers::SelectRandomContainerElement(actionLists); if (e.GetTargetType() == SMART_TARGET_NONE) { TC_LOG_ERROR("sql.sql", "SmartScript: Entry %d SourceType %u Event %u Action %u is using TARGET_NONE(0) for Script9 target. Please correct target_type in database.", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetActionType()); break; } - ObjectList* targets = GetTargets(e, unit); - if (targets) + for (WorldObject* target : targets) { - for (ObjectList::iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (Creature* creature = target->ToCreature()) { - if (Creature* target = (*itr)->ToCreature()) - { - if (IsSmart(target)) - ENSURE_AI(SmartAI, target->AI())->SetScript9(e, id, GetLastInvoker()); - } - else if (GameObject* goTarget = (*itr)->ToGameObject()) - { - if (IsSmartGO(goTarget)) - ENSURE_AI(SmartGameObjectAI, goTarget->AI())->SetScript9(e, id, GetLastInvoker()); - } + if (IsSmart(creature)) + ENSURE_AI(SmartAI, creature->AI())->SetScript9(e, id, GetLastInvoker()); + } + else if (GameObject* goTarget = target->ToGameObject()) + { + if (IsSmartGO(goTarget)) + ENSURE_AI(SmartGameObjectAI, goTarget->AI())->SetScript9(e, id, GetLastInvoker()); } - - delete targets; } break; } case SMART_ACTION_CALL_RANDOM_RANGE_TIMED_ACTIONLIST: { - uint32 id = urand(e.action.randTimedActionList.entry1, e.action.randTimedActionList.entry2); + uint32 id = urand(e.action.randTimedActionList.actionLists[0], e.action.randTimedActionList.actionLists[1]); if (e.GetTargetType() == SMART_TARGET_NONE) { TC_LOG_ERROR("sql.sql", "SmartScript: Entry %d SourceType %u Event %u Action %u is using TARGET_NONE(0) for Script9 target. Please correct target_type in database.", e.entryOrGuid, e.GetScriptType(), e.GetEventType(), e.GetActionType()); break; } - ObjectList* targets = GetTargets(e, unit); - if (targets) + for (WorldObject* target : targets) { - for (ObjectList::iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (Creature* target = target->ToCreature()) { - if (Creature* target = (*itr)->ToCreature()) - { - if (IsSmart(target)) - ENSURE_AI(SmartAI, target->AI())->SetScript9(e, id, GetLastInvoker()); - } - else if (GameObject* goTarget = (*itr)->ToGameObject()) - { - if (IsSmartGO(goTarget)) - ENSURE_AI(SmartGameObjectAI, goTarget->AI())->SetScript9(e, id, GetLastInvoker()); - } + if (IsSmart(target)) + ENSURE_AI(SmartAI, target->AI())->SetScript9(e, id, GetLastInvoker()); + } + else if (GameObject* goTarget = target->ToGameObject()) + { + if (IsSmartGO(goTarget)) + ENSURE_AI(SmartGameObjectAI, goTarget->AI())->SetScript9(e, id, GetLastInvoker()); } - - delete targets; } break; } case SMART_ACTION_ACTIVATE_TAXI: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsPlayer(target)) + target->ToPlayer()->ActivateTaxiPathTo(e.action.taxi.id); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsPlayer(*itr)) - (*itr)->ToPlayer()->ActivateTaxiPathTo(e.action.taxi.id); - - delete targets; break; } case SMART_ACTION_RANDOM_MOVE: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - bool foundTarget = false; - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsCreature((*itr))) + if (IsCreature(target)) { foundTarget = true; if (e.action.moveRandom.distance) - (*itr)->ToCreature()->GetMotionMaster()->MoveRandom((float)e.action.moveRandom.distance); + target->ToCreature()->GetMotionMaster()->MoveRandom((float)e.action.moveRandom.distance); else - (*itr)->ToCreature()->GetMotionMaster()->MoveIdle(); + target->ToCreature()->GetMotionMaster()->MoveIdle(); } } @@ -2050,175 +1789,120 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u else me->GetMotionMaster()->MoveIdle(); } - - delete targets; break; } case SMART_ACTION_SET_UNIT_FIELD_BYTES_1: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->SetByteFlag(UNIT_FIELD_BYTES_1, e.action.setunitByte.type, e.action.setunitByte.byte1); + for (WorldObject* target : targets) + if (IsUnit(target)) + target->ToUnit()->SetByteFlag(UNIT_FIELD_BYTES_1, e.action.setunitByte.type, e.action.setunitByte.byte1); - delete targets; break; } case SMART_ACTION_REMOVE_UNIT_FIELD_BYTES_1: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsUnit(target)) + target->ToUnit()->RemoveByteFlag(UNIT_FIELD_BYTES_1, e.action.delunitByte.type, e.action.delunitByte.byte1); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->RemoveByteFlag(UNIT_FIELD_BYTES_1, e.action.delunitByte.type, e.action.delunitByte.byte1); - - delete targets; break; } case SMART_ACTION_INTERRUPT_SPELL: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsUnit(target)) + target->ToUnit()->InterruptNonMeleeSpells(e.action.interruptSpellCasting.withDelayed != 0, e.action.interruptSpellCasting.spell_id, e.action.interruptSpellCasting.withInstant != 0); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->InterruptNonMeleeSpells(e.action.interruptSpellCasting.withDelayed != 0, e.action.interruptSpellCasting.spell_id, e.action.interruptSpellCasting.withInstant != 0); - - delete targets; break; } case SMART_ACTION_SEND_GO_CUSTOM_ANIM: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsGameObject(target)) + target->ToGameObject()->SendCustomAnim(e.action.sendGoCustomAnim.anim); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsGameObject(*itr)) - (*itr)->ToGameObject()->SendCustomAnim(e.action.sendGoCustomAnim.anim); - - delete targets; break; } case SMART_ACTION_SET_DYNAMIC_FLAG: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsUnit(target)) + target->ToUnit()->SetUInt32Value(UNIT_DYNAMIC_FLAGS, e.action.unitFlag.flag); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->SetUInt32Value(UNIT_DYNAMIC_FLAGS, e.action.unitFlag.flag); - - delete targets; break; } case SMART_ACTION_ADD_DYNAMIC_FLAG: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsUnit(target)) + target->ToUnit()->SetFlag(UNIT_DYNAMIC_FLAGS, e.action.unitFlag.flag); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->SetFlag(UNIT_DYNAMIC_FLAGS, e.action.unitFlag.flag); - - delete targets; break; } case SMART_ACTION_REMOVE_DYNAMIC_FLAG: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsUnit(target)) + target->ToUnit()->RemoveFlag(UNIT_DYNAMIC_FLAGS, e.action.unitFlag.flag); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->RemoveFlag(UNIT_DYNAMIC_FLAGS, e.action.unitFlag.flag); - - delete targets; break; } case SMART_ACTION_JUMP_TO_POS: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (Creature* creature = (*itr)->ToCreature()) + if (Creature* creature = target->ToCreature()) creature->GetMotionMaster()->MoveJump(e.target.x, e.target.y, e.target.z, 0.0f, (float)e.action.jump.speedxy, (float)e.action.jump.speedz); // @todo add optional jump orientation support? } - delete targets; break; } case SMART_ACTION_GO_SET_LOOT_STATE: { - ObjectList* targets = GetTargets(e, unit); + for (WorldObject* target : targets) + if (IsGameObject(target)) + target->ToGameObject()->SetLootState((LootState)e.action.setGoLootState.state); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsGameObject(*itr)) - (*itr)->ToGameObject()->SetLootState((LootState)e.action.setGoLootState.state); - - delete targets; break; } case SMART_ACTION_GO_SET_GO_STATE: { - ObjectList* targets = GetTargets(e, unit); + for (WorldObject* target : targets) + if (IsGameObject(target)) + target->ToGameObject()->SetGoState((GOState)e.action.goState.state); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsGameObject(*itr)) - (*itr)->ToGameObject()->SetGoState((GOState)e.action.goState.state); - - delete targets; break; } case SMART_ACTION_SEND_TARGET_TO_TARGET: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) + WorldObject* ref = GetBaseObject(); + if (!ref) + ref = unit; + + if (!ref) break; - ObjectList* storedTargets = GetTargetList(e.action.sendTargetToTarget.id); + ObjectVector const* storedTargets = GetStoredTargetVector(e.action.sendTargetToTarget.id, *ref); if (!storedTargets) - { - delete targets; break; - } - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsCreature(*itr)) + if (IsCreature(target)) { - if (SmartAI* ai = CAST_AI(SmartAI, (*itr)->ToCreature()->AI())) - ai->GetScript()->StoreTargetList(new ObjectList(*storedTargets), e.action.sendTargetToTarget.id); // store a copy of target list + if (SmartAI* ai = CAST_AI(SmartAI, target->ToCreature()->AI())) + ai->GetScript()->StoreTargetList(ObjectVector(*storedTargets), e.action.sendTargetToTarget.id); // store a copy of target list else TC_LOG_ERROR("sql.sql", "SmartScript: Action target for SMART_ACTION_SEND_TARGET_TO_TARGET is not using SmartAI, skipping"); } - else if (IsGameObject(*itr)) + else if (IsGameObject(target)) { - if (SmartGameObjectAI* ai = CAST_AI(SmartGameObjectAI, (*itr)->ToGameObject()->AI())) - ai->GetScript()->StoreTargetList(new ObjectList(*storedTargets), e.action.sendTargetToTarget.id); // store a copy of target list + if (SmartGameObjectAI* ai = CAST_AI(SmartGameObjectAI, target->ToGameObject()->AI())) + ai->GetScript()->StoreTargetList(ObjectVector(*storedTargets), e.action.sendTargetToTarget.id); // store a copy of target list else TC_LOG_ERROR("sql.sql", "SmartScript: Action target for SMART_ACTION_SEND_TARGET_TO_TARGET is not using SmartGameObjectAI, skipping"); } } - - delete targets; break; } case SMART_ACTION_SEND_GOSSIP_MENU: @@ -2229,46 +1913,36 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_SEND_GOSSIP_MENU: gossipMenuId %d, gossipNpcTextId %d", e.action.sendGossipMenu.gossipMenuId, e.action.sendGossipMenu.gossipNpcTextId); - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - // override default gossip if (me) ENSURE_AI(SmartAI, me->AI())->SetGossipReturn(true); else if (go) ENSURE_AI(SmartGameObjectAI, go->AI())->SetGossipReturn(true); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (Player* player = (*itr)->ToPlayer()) + if (Player* player = target->ToPlayer()) { if (e.action.sendGossipMenu.gossipMenuId) player->PrepareGossipMenu(GetBaseObject(), e.action.sendGossipMenu.gossipMenuId, true); else - ClearGossipMenuFor(player); + player->PlayerTalkClass->ClearMenus(); - SendGossipMenuFor(player, e.action.sendGossipMenu.gossipNpcTextId, GetBaseObject()->GetGUID()); + player->PlayerTalkClass->SendGossipMenu(e.action.sendGossipMenu.gossipNpcTextId, GetBaseObject()->GetGUID()); } } - - delete targets; break; } case SMART_ACTION_SET_HOME_POS: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsCreature(*itr)) + if (IsCreature(target)) { if (e.GetTargetType() == SMART_TARGET_SELF) - (*itr)->ToCreature()->SetHomePosition(me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), me->GetOrientation()); + target->ToCreature()->SetHomePosition(me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), me->GetOrientation()); else if (e.GetTargetType() == SMART_TARGET_POSITION) - (*itr)->ToCreature()->SetHomePosition(e.target.x, e.target.y, e.target.z, e.target.o); + target->ToCreature()->SetHomePosition(e.target.x, e.target.y, e.target.z, e.target.o); else if (e.GetTargetType() == SMART_TARGET_CREATURE_RANGE || e.GetTargetType() == SMART_TARGET_CREATURE_GUID || e.GetTargetType() == SMART_TARGET_CREATURE_DISTANCE || e.GetTargetType() == SMART_TARGET_GAMEOBJECT_RANGE || e.GetTargetType() == SMART_TARGET_GAMEOBJECT_GUID || e.GetTargetType() == SMART_TARGET_GAMEOBJECT_DISTANCE || @@ -2276,79 +1950,53 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u e.GetTargetType() == SMART_TARGET_OWNER_OR_SUMMONER || e.GetTargetType() == SMART_TARGET_ACTION_INVOKER || e.GetTargetType() == SMART_TARGET_CLOSEST_ENEMY || e.GetTargetType() == SMART_TARGET_CLOSEST_FRIENDLY) { - (*itr)->ToCreature()->SetHomePosition((*itr)->GetPositionX(), (*itr)->GetPositionY(), (*itr)->GetPositionZ(), (*itr)->GetOrientation()); + target->ToCreature()->SetHomePosition(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), target->GetOrientation()); } else TC_LOG_ERROR("sql.sql", "SmartScript: Action target for SMART_ACTION_SET_HOME_POS is invalid, skipping"); } } - delete targets; break; } case SMART_ACTION_SET_HEALTH_REGEN: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsCreature(target)) + target->ToCreature()->setRegeneratingHealth(e.action.setHealthRegen.regenHealth != 0); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToCreature()->setRegeneratingHealth(e.action.setHealthRegen.regenHealth != 0); - - delete targets; break; } case SMART_ACTION_SET_ROOT: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsCreature(target)) + target->ToCreature()->SetControlled(e.action.setRoot.root != 0, UNIT_STATE_ROOT); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToCreature()->SetControlled(e.action.setRoot.root != 0, UNIT_STATE_ROOT); - - delete targets; break; } case SMART_ACTION_SET_GO_FLAG: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsGameObject(target)) + target->ToGameObject()->SetUInt32Value(GAMEOBJECT_FLAGS, e.action.goFlag.flag); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsGameObject(*itr)) - (*itr)->ToGameObject()->SetUInt32Value(GAMEOBJECT_FLAGS, e.action.goFlag.flag); - - delete targets; break; } case SMART_ACTION_ADD_GO_FLAG: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsGameObject(target)) + target->ToGameObject()->SetFlag(GAMEOBJECT_FLAGS, e.action.goFlag.flag); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsGameObject(*itr)) - (*itr)->ToGameObject()->SetFlag(GAMEOBJECT_FLAGS, e.action.goFlag.flag); - - delete targets; break; } case SMART_ACTION_REMOVE_GO_FLAG: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsGameObject(target)) + target->ToGameObject()->RemoveFlag(GAMEOBJECT_FLAGS, e.action.goFlag.flag); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsGameObject(*itr)) - (*itr)->ToGameObject()->RemoveFlag(GAMEOBJECT_FLAGS, e.action.goFlag.flag); - - delete targets; break; } case SMART_ACTION_SUMMON_CREATURE_GROUP: @@ -2356,46 +2004,34 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u std::list summonList; GetBaseObject()->SummonCreatureGroup(e.action.creatureGroup.group, &summonList); - for (std::list::const_iterator itr = summonList.begin(); itr != summonList.end(); ++itr) + for (TempSummon* summon : summonList) if (unit && e.action.creatureGroup.attackInvoker) - (*itr)->AI()->AttackStart(unit); + summon->AI()->AttackStart(unit); break; } case SMART_ACTION_SET_POWER: { - ObjectList* targets = GetTargets(e, unit); + for (WorldObject* target : targets) + if (IsUnit(target)) + target->ToUnit()->SetPower(Powers(e.action.power.powerType), e.action.power.newPower); - if (targets) - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->SetPower(Powers(e.action.power.powerType), e.action.power.newPower); - - delete targets; break; } case SMART_ACTION_ADD_POWER: { - ObjectList* targets = GetTargets(e, unit); + for (WorldObject* target : targets) + if (IsUnit(target)) + target->ToUnit()->SetPower(Powers(e.action.power.powerType), target->ToUnit()->GetPower(Powers(e.action.power.powerType)) + e.action.power.newPower); - if (targets) - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->SetPower(Powers(e.action.power.powerType), (*itr)->ToUnit()->GetPower(Powers(e.action.power.powerType)) + e.action.power.newPower); - - delete targets; break; } case SMART_ACTION_REMOVE_POWER: { - ObjectList* targets = GetTargets(e, unit); + for (WorldObject* target : targets) + if (IsUnit(target)) + target->ToUnit()->SetPower(Powers(e.action.power.powerType), target->ToUnit()->GetPower(Powers(e.action.power.powerType)) - e.action.power.newPower); - if (targets) - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->SetPower(Powers(e.action.power.powerType), (*itr)->ToUnit()->GetPower(Powers(e.action.power.powerType)) - e.action.power.newPower); - - delete targets; break; } case SMART_ACTION_GAME_EVENT_STOP: @@ -2422,106 +2058,77 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u } case SMART_ACTION_START_CLOSEST_WAYPOINT: { - uint32 waypoints[SMART_ACTION_PARAM_COUNT]; - waypoints[0] = e.action.closestWaypointFromList.wp1; - waypoints[1] = e.action.closestWaypointFromList.wp2; - waypoints[2] = e.action.closestWaypointFromList.wp3; - waypoints[3] = e.action.closestWaypointFromList.wp4; - waypoints[4] = e.action.closestWaypointFromList.wp5; - waypoints[5] = e.action.closestWaypointFromList.wp6; + std::vector waypoints; + std::copy_if(std::begin(e.action.closestWaypointFromList.wps), std::end(e.action.closestWaypointFromList.wps), + std::back_inserter(waypoints), [](uint32 wp) { return wp != 0; }); + float distanceToClosest = std::numeric_limits::max(); WayPoint* closestWp = nullptr; - ObjectList* targets = GetTargets(e, unit); - if (targets) + for (WorldObject* target : targets) { - for (ObjectList::iterator itr = targets->begin(); itr != targets->end(); ++itr) + if (Creature* target = target->ToCreature()) { - if (Creature* target = (*itr)->ToCreature()) + if (IsSmart(target)) { - if (IsSmart(target)) + for (uint32 wp : waypoints) { - for (uint8 i = 0; i < SMART_ACTION_PARAM_COUNT; i++) + WPPath* path = sSmartWaypointMgr->GetPath(wp); + if (!path || path->empty()) + continue; + + auto itrWp = path->find(0); + if (itrWp != path->end()) { - if (!waypoints[i]) - continue; - - WPPath* path = sSmartWaypointMgr->GetPath(waypoints[i]); - - if (!path || path->empty()) - continue; - - WPPath::const_iterator itrWp = path->find(0); - - if (itrWp != path->end()) + if (WayPoint* wp = itrWp->second) { - if (WayPoint* wp = itrWp->second) + float distToThisPath = target->GetDistance(wp->x, wp->y, wp->z); + if (distToThisPath < distanceToClosest) { - float distToThisPath = target->GetDistance(wp->x, wp->y, wp->z); - - if (distToThisPath < distanceToClosest) - { - distanceToClosest = distToThisPath; - closestWp = wp; - } + distanceToClosest = distToThisPath; + closestWp = wp; } } } - - if (closestWp) - CAST_AI(SmartAI, target->AI())->StartPath(false, closestWp->id, true); } + + if (closestWp) + CAST_AI(SmartAI, target->AI())->StartPath(false, closestWp->id, true); } } - - delete targets; } break; } case SMART_ACTION_RANDOM_SOUND: { std::vector sounds; - std::copy_if(e.action.randomSound.sounds.begin(), e.action.randomSound.sounds.end(), + std::copy_if(std::begin(e.action.randomSound.sounds), std::end(e.action.randomSound.sounds), std::back_inserter(sounds), [](uint32 sound) { return sound != 0; }); bool onlySelf = e.action.randomSound.onlySelf != 0; - if (ObjectList* targets = GetTargets(e, unit)) + for (WorldObject* target : targets) { - for (WorldObject* const obj : *targets) + if (IsUnit(target)) { - if (IsUnit(obj)) - { - uint32 sound = Trinity::Containers::SelectRandomContainerElement(sounds); + uint32 sound = Trinity::Containers::SelectRandomContainerElement(sounds); + if (e.action.randomSound.distance == 1) + target->PlayDistanceSound(sound, onlySelf ? target->ToPlayer() : nullptr); + else + target->PlayDirectSound(sound, onlySelf ? target->ToPlayer() : nullptr); - if (e.action.randomSound.distance == 1) - obj->PlayDistanceSound(sound, onlySelf ? obj->ToPlayer() : nullptr); - else - obj->PlayDirectSound(sound, onlySelf ? obj->ToPlayer() : nullptr); - - - TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_RANDOM_SOUND: target: %s (%s), sound: %u, onlyself: %s", - obj->GetName().c_str(), obj->GetGUID().ToString().c_str(), sound, onlySelf ? "true" : "false"); - } + TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_RANDOM_SOUND: target: %s (%s), sound: %u, onlyself: %s", + target->GetName().c_str(), target->GetGUID().ToString().c_str(), sound, onlySelf ? "true" : "false"); } - - delete targets; break; } } case SMART_ACTION_SET_CORPSE_DELAY: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsCreature(target)) + target->ToCreature()->SetCorpseDelay(e.action.corpseDelay.timer); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - { - if (IsCreature(*itr)) - (*itr)->ToCreature()->SetCorpseDelay(e.action.corpseDelay.timer); - } - - delete targets; break; } case SMART_ACTION_DISABLE_EVADE: @@ -2534,22 +2141,18 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u } case SMART_ACTION_PLAY_ANIMKIT: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) + for (WorldObject* target : targets) { - if (IsCreature(*itr)) + if (IsCreature(target)) { if (e.action.animKit.type == 0) - (*itr)->ToCreature()->PlayOneShotAnimKitId(e.action.animKit.animKit); + target->ToCreature()->PlayOneShotAnimKitId(e.action.animKit.animKit); else if (e.action.animKit.type == 1) - (*itr)->ToCreature()->SetAIAnimKitId(e.action.animKit.animKit); + target->ToCreature()->SetAIAnimKitId(e.action.animKit.animKit); else if (e.action.animKit.type == 2) - (*itr)->ToCreature()->SetMeleeAnimKitId(e.action.animKit.animKit); + target->ToCreature()->SetMeleeAnimKitId(e.action.animKit.animKit); else if (e.action.animKit.type == 3) - (*itr)->ToCreature()->SetMovementAnimKitId(e.action.animKit.animKit); + target->ToCreature()->SetMovementAnimKitId(e.action.animKit.animKit); else { TC_LOG_ERROR("sql.sql", "SmartScript: Invalid type for SMART_ACTION_PLAY_ANIMKIT, skipping"); @@ -2557,114 +2160,77 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u } TC_LOG_DEBUG("scripts.ai", "SmartScript::ProcessAction:: SMART_ACTION_PLAY_ANIMKIT: target: %s (%s), AnimKit: %u, Type: %u", - (*itr)->GetName().c_str(), (*itr)->GetGUID().ToString().c_str(), e.action.animKit.animKit, e.action.animKit.type); + target->GetName().c_str(), target->GetGUID().ToString().c_str(), e.action.animKit.animKit, e.action.animKit.type); } } - - delete targets; break; } case SMART_ACTION_REMOVE_AURAS_BY_TYPE: // can be used to exit vehicle for example { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsUnit(target)) + target->ToUnit()->RemoveAurasByType((AuraType)e.action.auraType.type); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->RemoveAurasByType((AuraType)e.action.auraType.type); - - delete targets; break; } case SMART_ACTION_SET_SIGHT_DIST: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToCreature()->m_SightDistance = e.action.sightDistance.dist; - - delete targets; + for (WorldObject* target : targets) + if (IsCreature(target)) + target->ToCreature()->m_SightDistance = e.action.sightDistance.dist; break; } case SMART_ACTION_FLEE: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsCreature(target)) + target->ToCreature()->GetMotionMaster()->MoveFleeing(me, e.action.flee.fleeTime); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToCreature()->GetMotionMaster()->MoveFleeing(me, e.action.flee.fleeTime); - - delete targets; break; } case SMART_ACTION_ADD_THREAT: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsUnit(target)) + me->AddThreat(target->ToUnit(), (float)e.action.threatPCT.threatINC - (float)e.action.threatPCT.threatDEC); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - me->AddThreat((*itr)->ToUnit(), (float)e.action.threatPCT.threatINC - (float)e.action.threatPCT.threatDEC); - - delete targets; break; } case SMART_ACTION_LOAD_EQUIPMENT: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsCreature(target)) + target->ToCreature()->LoadEquipment(e.action.loadEquipment.id, e.action.loadEquipment.force != 0); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsCreature(*itr)) - (*itr)->ToCreature()->LoadEquipment(e.action.loadEquipment.id, e.action.loadEquipment.force != 0); - - delete targets; break; } case SMART_ACTION_TRIGGER_RANDOM_TIMED_EVENT: { uint32 eventId = urand(e.action.randomTimedEvent.minId, e.action.randomTimedEvent.maxId); - ProcessEventsFor((SMART_EVENT)SMART_EVENT_TIMED_EVENT_TRIGGERED, NULL, eventId); + ProcessEventsFor((SMART_EVENT)SMART_EVENT_TIMED_EVENT_TRIGGERED, nullptr, eventId); break; } case SMART_ACTION_REMOVE_ALL_GAMEOBJECTS: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; + for (WorldObject* target : targets) + if (IsUnit(target)) + target->ToUnit()->RemoveAllGameObjects(); - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) - (*itr)->ToUnit()->RemoveAllGameObjects(); - - delete targets; break; } case SMART_ACTION_STOP_MOTION: { - ObjectList* targets = GetTargets(e, unit); - if (!targets) - break; - - for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) - if (IsUnit(*itr)) + for (WorldObject* target : targets) + { + if (IsUnit(target)) { if (e.action.stopMotion.stopMovement) - (*itr)->ToUnit()->StopMoving(); + target->ToUnit()->StopMoving(); if (e.action.stopMotion.movementExpired) - (*itr)->ToUnit()->GetMotionMaster()->MovementExpired(); + target->ToUnit()->GetMotionMaster()->MovementExpired(); } - - delete targets; + } break; } default: @@ -2682,7 +2248,7 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u } } -void SmartScript::ProcessTimedAction(SmartScriptHolder& e, uint32 const& min, uint32 const& max, Unit* unit, uint32 var0, uint32 var1, bool bvar, const SpellInfo* spell, GameObject* gob) +void SmartScript::ProcessTimedAction(SmartScriptHolder& e, uint32 const& min, uint32 const& max, Unit* unit, uint32 var0, uint32 var1, bool bvar, SpellInfo const* spell, GameObject* gob) { // We may want to execute action rarely and because of this if condition is not fulfilled the action will be rechecked in a long time if (sConditionMgr->IsObjectMeetingSmartEventConditions(e.entryOrGuid, e.event_id, e.source_type, unit, GetBaseObject())) @@ -2770,10 +2336,10 @@ void SmartScript::InstallTemplate(SmartScriptHolder const& e) void SmartScript::AddEvent(SMART_EVENT e, uint32 event_flags, uint32 event_param1, uint32 event_param2, uint32 event_param3, uint32 event_param4, uint32 event_param5, SMART_ACTION action, uint32 action_param1, uint32 action_param2, uint32 action_param3, uint32 action_param4, uint32 action_param5, uint32 action_param6, SMARTAI_TARGETS t, uint32 target_param1, uint32 target_param2, uint32 target_param3, uint32 phaseMask) { - mInstallEvents.push_back(CreateEvent(e, event_flags, event_param1, event_param2, event_param3, event_param4, event_param5, action, action_param1, action_param2, action_param3, action_param4, action_param5, action_param6, t, target_param1, target_param2, target_param3, phaseMask)); + mInstallEvents.push_back(CreateSmartEvent(e, event_flags, event_param1, event_param2, event_param3, event_param4, event_param5, action, action_param1, action_param2, action_param3, action_param4, action_param5, action_param6, t, target_param1, target_param2, target_param3, phaseMask)); } -SmartScriptHolder SmartScript::CreateEvent(SMART_EVENT e, uint32 event_flags, uint32 event_param1, uint32 event_param2, uint32 event_param3, uint32 event_param4, uint32 event_param5, SMART_ACTION action, uint32 action_param1, uint32 action_param2, uint32 action_param3, uint32 action_param4, uint32 action_param5, uint32 action_param6, SMARTAI_TARGETS t, uint32 target_param1, uint32 target_param2, uint32 target_param3, uint32 phaseMask) +SmartScriptHolder SmartScript::CreateSmartEvent(SMART_EVENT e, uint32 event_flags, uint32 event_param1, uint32 event_param2, uint32 event_param3, uint32 event_param4, uint32 event_param5, SMART_ACTION action, uint32 action_param1, uint32 action_param2, uint32 action_param3, uint32 action_param4, uint32 action_param5, uint32 action_param6, SMARTAI_TARGETS t, uint32 target_param1, uint32 target_param2, uint32 target_param3, uint32 phaseMask) { SmartScriptHolder script; script.event.type = e; @@ -2804,7 +2370,7 @@ SmartScriptHolder SmartScript::CreateEvent(SMART_EVENT e, uint32 event_flags, ui return script; } -ObjectList* SmartScript::GetTargets(SmartScriptHolder const& e, Unit* invoker /*= nullptr*/) +void SmartScript::GetTargets(ObjectVector& targets, SmartScriptHolder const& e, Unit* invoker /*= nullptr*/) { Unit* scriptTrigger = nullptr; if (invoker) @@ -2813,18 +2379,16 @@ ObjectList* SmartScript::GetTargets(SmartScriptHolder const& e, Unit* invoker /* scriptTrigger = tempLastInvoker; WorldObject* baseObject = GetBaseObject(); - - ObjectList* l = new ObjectList(); switch (e.GetTargetType()) { case SMART_TARGET_SELF: if (baseObject) - l->push_back(baseObject); + targets.push_back(baseObject); break; case SMART_TARGET_VICTIM: if (me) if (Unit* victim = me->GetVictim()) - l->push_back(victim); + targets.push_back(victim); break; case SMART_TARGET_HOSTILE_SECOND_AGGRO: if (me) @@ -2832,10 +2396,10 @@ ObjectList* SmartScript::GetTargets(SmartScriptHolder const& e, Unit* invoker /* if (e.target.hostilRandom.powerType) { if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_TOPAGGRO, 1, PowerUsersSelector(me, Powers(e.target.hostilRandom.powerType - 1), (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly != 0))) - l->push_back(u); + targets.push_back(u); } else if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_TOPAGGRO, 1, (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly != 0)) - l->push_back(u); + targets.push_back(u); } break; case SMART_TARGET_HOSTILE_LAST_AGGRO: @@ -2844,10 +2408,10 @@ ObjectList* SmartScript::GetTargets(SmartScriptHolder const& e, Unit* invoker /* if (e.target.hostilRandom.powerType) { if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_BOTTOMAGGRO, 0, PowerUsersSelector(me, Powers(e.target.hostilRandom.powerType - 1), (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly != 0))) - l->push_back(u); + targets.push_back(u); } else if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_BOTTOMAGGRO, 0, (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly != 0)) - l->push_back(u); + targets.push_back(u); } break; case SMART_TARGET_HOSTILE_RANDOM: @@ -2856,10 +2420,10 @@ ObjectList* SmartScript::GetTargets(SmartScriptHolder const& e, Unit* invoker /* if (e.target.hostilRandom.powerType) { if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_RANDOM, 0, PowerUsersSelector(me, Powers(e.target.hostilRandom.powerType - 1), (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly != 0))) - l->push_back(u); + targets.push_back(u); } else if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_RANDOM, 0, (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly != 0)) - l->push_back(u); + targets.push_back(u); } break; case SMART_TARGET_HOSTILE_RANDOM_NOT_TOP: @@ -2868,28 +2432,29 @@ ObjectList* SmartScript::GetTargets(SmartScriptHolder const& e, Unit* invoker /* if (e.target.hostilRandom.powerType) { if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_RANDOM, 1, PowerUsersSelector(me, Powers(e.target.hostilRandom.powerType - 1), (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly != 0))) - l->push_back(u); + targets.push_back(u); } else if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_RANDOM, 1, (float)e.target.hostilRandom.maxDist, e.target.hostilRandom.playerOnly != 0)) - l->push_back(u); + targets.push_back(u); } break; case SMART_TARGET_FARTHEST: if (me) { if (Unit* u = me->AI()->SelectTarget(SELECT_TARGET_FARTHEST, 0, FarthestTargetSelector(me, (float)e.target.farthest.maxDist, e.target.farthest.playerOnly != 0, e.target.farthest.isInLos != 0))) - l->push_back(u); + targets.push_back(u); } break; case SMART_TARGET_ACTION_INVOKER: if (scriptTrigger) - l->push_back(scriptTrigger); + targets.push_back(scriptTrigger); break; case SMART_TARGET_ACTION_INVOKER_VEHICLE: if (scriptTrigger && scriptTrigger->GetVehicle() && scriptTrigger->GetVehicle()->GetBase()) - l->push_back(scriptTrigger->GetVehicle()->GetBase()); + targets.push_back(scriptTrigger->GetVehicle()->GetBase()); break; case SMART_TARGET_INVOKER_PARTY: + { if (scriptTrigger) { if (Player* player = scriptTrigger->ToPlayer()) @@ -2899,90 +2464,87 @@ ObjectList* SmartScript::GetTargets(SmartScriptHolder const& e, Unit* invoker /* for (GroupReference* groupRef = group->GetFirstMember(); groupRef != nullptr; groupRef = groupRef->next()) if (Player* member = groupRef->GetSource()) if (member->IsInMap(player)) - l->push_back(member); + targets.push_back(member); } // We still add the player to the list if there is no group. If we do // this even if there is a group (thus the else-check), it will add the // same player to the list twice. We don't want that to happen. else - l->push_back(scriptTrigger); + targets.push_back(scriptTrigger); } } break; + } case SMART_TARGET_CREATURE_RANGE: { - // will always return a valid pointer, even if empty list - ObjectList* units = GetWorldObjectsInDist((float)e.target.unitRange.maxDist); - for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) + ObjectVector units; + GetWorldObjectsInDist(units, static_cast(e.target.unitRange.maxDist)); + + for (WorldObject* unit : units) { - if (!IsCreature(*itr)) + if (!IsCreature(unit)) continue; - if (me && me->GetGUID() == (*itr)->GetGUID()) + if (me && me->GetGUID() == unit->GetGUID()) continue; - if ((!e.target.unitRange.creature || (*itr)->ToCreature()->GetEntry() == e.target.unitRange.creature) && baseObject->IsInRange(*itr, float(e.target.unitRange.minDist), float(e.target.unitRange.maxDist))) - l->push_back(*itr); + if ((!e.target.unitRange.creature || unit->ToCreature()->GetEntry() == e.target.unitRange.creature) && baseObject->IsInRange(unit, float(e.target.unitRange.minDist), float(e.target.unitRange.maxDist))) + targets.push_back(unit); } - - delete units; break; } case SMART_TARGET_CREATURE_DISTANCE: { - // will always return a valid pointer, even if empty list - ObjectList* units = GetWorldObjectsInDist((float)e.target.unitDistance.dist); - for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) + ObjectVector units; + GetWorldObjectsInDist(units, static_cast(e.target.unitDistance.dist)); + + for (WorldObject* unit : units) { - if (!IsCreature(*itr)) + if (!IsCreature(unit)) continue; - if (me && me->GetGUID() == (*itr)->GetGUID()) + if (me && me->GetGUID() == unit->GetGUID()) continue; - if (!e.target.unitDistance.creature || (*itr)->ToCreature()->GetEntry() == e.target.unitDistance.creature) - l->push_back(*itr); + if (!e.target.unitDistance.creature || unit->ToCreature()->GetEntry() == e.target.unitDistance.creature) + targets.push_back(unit); } - - delete units; break; } case SMART_TARGET_GAMEOBJECT_DISTANCE: { - // will always return a valid pointer, even if empty list - ObjectList* units = GetWorldObjectsInDist((float)e.target.goDistance.dist); - for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) + ObjectVector units; + GetWorldObjectsInDist(units, static_cast(e.target.goDistance.dist)); + + for (WorldObject* unit : units) { - if (!IsGameObject(*itr)) + if (!IsGameObject(unit)) continue; - if (go && go->GetGUID() == (*itr)->GetGUID()) + if (go && go->GetGUID() == unit->GetGUID()) continue; - if (!e.target.goDistance.entry || (*itr)->ToGameObject()->GetEntry() == e.target.goDistance.entry) - l->push_back(*itr); + if (!e.target.goDistance.entry || unit->ToGameObject()->GetEntry() == e.target.goDistance.entry) + targets.push_back(unit); } - - delete units; break; } case SMART_TARGET_GAMEOBJECT_RANGE: { - // will always return a valid pointer, even if empty list - ObjectList* units = GetWorldObjectsInDist((float)e.target.goRange.maxDist); - for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) + ObjectVector units; + GetWorldObjectsInDist(units, static_cast(e.target.goRange.maxDist)); + + for (WorldObject* unit : units) { - if (!IsGameObject(*itr)) + if (!IsGameObject(unit)) continue; - if (go && go->GetGUID() == (*itr)->GetGUID()) + if (go && go->GetGUID() == unit->GetGUID()) continue; - if ((!e.target.goRange.entry && (*itr)->ToGameObject()->GetEntry() == e.target.goRange.entry) && baseObject->IsInRange(*itr, float(e.target.goRange.minDist), float(e.target.goRange.maxDist))) - l->push_back(*itr); + if ((!e.target.goRange.entry && unit->ToGameObject()->GetEntry() == e.target.goRange.entry) && baseObject->IsInRange(unit, float(e.target.goRange.minDist), float(e.target.goRange.maxDist))) + targets.push_back(unit); } - - delete units; break; } case SMART_TARGET_CREATURE_GUID: @@ -2995,7 +2557,7 @@ ObjectList* SmartScript::GetTargets(SmartScriptHolder const& e, Unit* invoker /* if (Creature* target = FindCreatureNear(scriptTrigger ? scriptTrigger : baseObject, e.target.unitGUID.dbGuid)) if (!e.target.unitGUID.entry || target->GetEntry() == e.target.unitGUID.entry) - l->push_back(target); + targets.push_back(target); break; } case SMART_TARGET_GAMEOBJECT_GUID: @@ -3008,60 +2570,58 @@ ObjectList* SmartScript::GetTargets(SmartScriptHolder const& e, Unit* invoker /* if (GameObject* target = FindGameObjectNear(scriptTrigger ? scriptTrigger : baseObject, e.target.goGUID.dbGuid)) if (!e.target.goGUID.entry || target->GetEntry() == e.target.goGUID.entry) - l->push_back(target); + targets.push_back(target); break; } case SMART_TARGET_PLAYER_RANGE: { - // will always return a valid pointer, even if empty list - ObjectList* units = GetWorldObjectsInDist((float)e.target.playerRange.maxDist); - if (!units->empty() && baseObject) - for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) - if (IsPlayer(*itr) && baseObject->IsInRange(*itr, (float)e.target.playerRange.minDist, (float)e.target.playerRange.maxDist)) - l->push_back(*itr); + ObjectVector units; + GetWorldObjectsInDist(units, static_cast(e.target.playerRange.maxDist)); - delete units; + if (!units.empty() && baseObject) + for (WorldObject* unit : units) + if (IsPlayer(unit) && baseObject->IsInRange(unit, float(e.target.playerRange.minDist), float(e.target.playerRange.maxDist))) + targets.push_back(unit); break; } case SMART_TARGET_PLAYER_DISTANCE: { - // will always return a valid pointer, even if empty list - ObjectList* units = GetWorldObjectsInDist((float)e.target.playerDistance.dist); - for (ObjectList::const_iterator itr = units->begin(); itr != units->end(); ++itr) - if (IsPlayer(*itr)) - l->push_back(*itr); + ObjectVector units; + GetWorldObjectsInDist(units, static_cast(e.target.playerDistance.dist)); - delete units; + for (WorldObject* unit : units) + if (IsPlayer(unit)) + targets.push_back(unit); break; } case SMART_TARGET_STORED: { - ObjectListMap::iterator itr = mTargetStorage->find(e.target.stored.id); - if (itr != mTargetStorage->end()) - { - ObjectList* objectList = itr->second->GetObjectList(); - l->assign(objectList->begin(), objectList->end()); - } + WorldObject* ref = GetBaseObject(); + if (!ref) + ref = scriptTrigger; + if (ref) + if (ObjectVector const* stored = GetStoredTargetVector(e.target.stored.id, *ref)) + targets.assign(stored->begin(), stored->end()); break; } case SMART_TARGET_CLOSEST_CREATURE: { - if (Creature* target = GetClosestCreatureWithEntry(baseObject, e.target.closest.entry, float(e.target.closest.dist ? e.target.closest.dist : 100), !e.target.closest.dead)) - l->push_back(target); + if (Creature* target = baseObject->FindNearestCreature(e.target.closest.entry, float(e.target.closest.dist ? e.target.closest.dist : 100), !e.target.closest.dead)) + targets.push_back(target); break; } case SMART_TARGET_CLOSEST_GAMEOBJECT: { - if (GameObject* target = GetClosestGameObjectWithEntry(baseObject, e.target.closest.entry, float(e.target.closest.dist ? e.target.closest.dist : 100))) - l->push_back(target); + if (GameObject* target = baseObject->FindNearestGameObject(e.target.closest.entry, float(e.target.closest.dist ? e.target.closest.dist : 100))) + targets.push_back(target); break; } case SMART_TARGET_CLOSEST_PLAYER: { if (WorldObject* obj = GetBaseObject()) if (Player* target = obj->SelectNearestPlayer(float(e.target.playerDistance.dist))) - l->push_back(target); + targets.push_back(target); break; } case SMART_TARGET_OWNER_OR_SUMMONER: @@ -3069,7 +2629,6 @@ ObjectList* SmartScript::GetTargets(SmartScriptHolder const& e, Unit* invoker /* if (me) { ObjectGuid charmerOrOwnerGuid = me->GetCharmerOrOwnerGUID(); - if (!charmerOrOwnerGuid) if (TempSummon* tempSummon = me->ToTempSummon()) if (Unit* summoner = tempSummon->GetSummoner()) @@ -3079,22 +2638,22 @@ ObjectList* SmartScript::GetTargets(SmartScriptHolder const& e, Unit* invoker /* charmerOrOwnerGuid = me->GetCreatorGUID(); if (Unit* owner = ObjectAccessor::GetUnit(*me, charmerOrOwnerGuid)) - l->push_back(owner); + targets.push_back(owner); } else if (go) { if (Unit* owner = ObjectAccessor::GetUnit(*go, go->GetOwnerGUID())) - l->push_back(owner); + targets.push_back(owner); } // Get owner of owner - if (e.target.owner.useCharmerOrOwner && !l->empty()) + if (e.target.owner.useCharmerOrOwner && !targets.empty()) { - Unit* owner = l->front()->ToUnit(); - l->clear(); + Unit* owner = targets.front()->ToUnit(); + targets.clear(); if (Unit* base = ObjectAccessor::GetUnit(*owner, owner->GetCharmerOrOwnerGUID())) - l->push_back(base); + targets.push_back(base); } break; } @@ -3106,7 +2665,7 @@ ObjectList* SmartScript::GetTargets(SmartScriptHolder const& e, Unit* invoker /* for (ThreatContainer::StorageType::const_iterator i = threatList.begin(); i != threatList.end(); ++i) if (Unit* temp = ObjectAccessor::GetUnit(*me, (*i)->getUnitGuid())) if (e.target.hostilRandom.maxDist == 0 || me->IsWithinCombatRange(temp, (float)e.target.hostilRandom.maxDist)) - l->push_back(temp); + targets.push_back(temp); } break; } @@ -3114,14 +2673,14 @@ ObjectList* SmartScript::GetTargets(SmartScriptHolder const& e, Unit* invoker /* { if (me) if (Unit* target = me->SelectNearestTarget(e.target.closestAttackable.maxDist, e.target.closestAttackable.playerOnly != 0)) - l->push_back(target); + targets.push_back(target); break; } case SMART_TARGET_CLOSEST_FRIENDLY: { if (me) if (Unit* target = DoFindClosestFriendlyInRange(e.target.closestFriendly.maxDist, e.target.closestFriendly.playerOnly != 0)) - l->push_back(target); + targets.push_back(target); break; } case SMART_TARGET_LOOT_RECIPIENTS: @@ -3133,12 +2692,12 @@ ObjectList* SmartScript::GetTargets(SmartScriptHolder const& e, Unit* invoker /* for (GroupReference* it = lootGroup->GetFirstMember(); it != nullptr; it = it->next()) if (Player* recipient = it->GetSource()) if (recipient->IsInMap(me)) - l->push_back(recipient); + targets.push_back(recipient); } else { if (Player* recipient = me->GetLootRecipient()) - l->push_back(recipient); + targets.push_back(recipient); } } break; @@ -3149,7 +2708,7 @@ ObjectList* SmartScript::GetTargets(SmartScriptHolder const& e, Unit* invoker /* for (auto seatItr = me->GetVehicleKit()->Seats.begin(); seatItr != me->GetVehicleKit()->Seats.end(); ++seatItr) if (!e.target.vehicle.seatMask || (e.target.vehicle.seatMask & (1 << seatItr->first))) if (Unit* u = ObjectAccessor::GetUnit(*me, seatItr->second.Passenger.Guid)) - l->push_back(u); + targets.push_back(u); break; } case SMART_TARGET_POSITION: @@ -3157,30 +2716,20 @@ ObjectList* SmartScript::GetTargets(SmartScriptHolder const& e, Unit* invoker /* default: break; } - - if (l->empty()) - { - delete l; - l = nullptr; - } - - return l; } -ObjectList* SmartScript::GetWorldObjectsInDist(float dist) +void SmartScript::GetWorldObjectsInDist(ObjectVector& targets, float dist) { - ObjectList* targets = new ObjectList(); WorldObject* obj = GetBaseObject(); - if (obj) - { - Trinity::AllWorldObjectsInRange u_check(obj, dist); - Trinity::WorldObjectListSearcher searcher(obj, *targets, u_check); - Cell::VisitAllObjects(obj, searcher, dist); - } - return targets; + if (!obj) + return; + + Trinity::AllWorldObjectsInRange u_check(obj, dist); + Trinity::WorldObjectListSearcher searcher(obj, targets, u_check); + Cell::VisitAllObjects(obj, searcher, dist); } -void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, uint32 var1, bool bvar, const SpellInfo* spell, GameObject* gob) +void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, uint32 var1, bool bvar, SpellInfo const* spell, GameObject* gob) { if (!e.active && e.GetEventType() != SMART_EVENT_LINK) return; @@ -3637,8 +3186,7 @@ void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, ui if (!me || !me->IsInCombat()) return; - ObjectList* _targets = nullptr; - + ObjectVector targets; switch (e.GetTargetType()) { case SMART_TARGET_CREATURE_RANGE: @@ -3648,37 +3196,30 @@ void SmartScript::ProcessEvent(SmartScriptHolder& e, Unit* unit, uint32 var0, ui case SMART_TARGET_CLOSEST_PLAYER: case SMART_TARGET_PLAYER_RANGE: case SMART_TARGET_PLAYER_DISTANCE: - _targets = GetTargets(e); + GetTargets(targets, e); break; default: return; } - if (!_targets) - return; - - Unit* target = nullptr; - - for (ObjectList::const_iterator itr = _targets->begin(); itr != _targets->end(); ++itr) + Unit* unitTarget = nullptr; + for (WorldObject* target : targets) { - if (IsUnit(*itr) && me->IsFriendlyTo((*itr)->ToUnit()) && (*itr)->ToUnit()->IsAlive() && (*itr)->ToUnit()->IsInCombat()) + if (IsUnit(target) && me->IsFriendlyTo(target->ToUnit()) && target->ToUnit()->IsAlive() && target->ToUnit()->IsInCombat()) { - uint32 healthPct = uint32((*itr)->ToUnit()->GetHealthPct()); - + uint32 healthPct = uint32(target->ToUnit()->GetHealthPct()); if (healthPct > e.event.friendlyHealthPct.maxHpPct || healthPct < e.event.friendlyHealthPct.minHpPct) continue; - target = (*itr)->ToUnit(); + unitTarget = target->ToUnit(); break; } } - delete _targets; - - if (!target) + if (!unitTarget) return; - ProcessTimedAction(e, e.event.friendlyHealthPct.repeatMin, e.event.friendlyHealthPct.repeatMax, target); + ProcessTimedAction(e, e.event.friendlyHealthPct.repeatMin, e.event.friendlyHealthPct.repeatMax, unitTarget); break; } case SMART_EVENT_DISTANCE_CREATURE: @@ -3878,6 +3419,62 @@ void SmartScript::InstallEvents() } } +void SmartScript::RemoveStoredEvent(uint32 id) +{ + if (!mStoredEvents.empty()) + { + for (auto i = mStoredEvents.begin(); i != mStoredEvents.end(); ++i) + { + if (i->event_id == id) + { + mStoredEvents.erase(i); + return; + } + } + } +} + +WorldObject* SmartScript::GetBaseObject() const +{ + WorldObject* obj = nullptr; + if (me) + obj = me; + else if (go) + obj = go; + return obj; +} + +bool SmartScript::IsUnit(WorldObject* obj) +{ + return obj && (obj->GetTypeId() == TYPEID_UNIT || obj->GetTypeId() == TYPEID_PLAYER); +} + +bool SmartScript::IsPlayer(WorldObject* obj) +{ + return obj && obj->GetTypeId() == TYPEID_PLAYER; +} + +bool SmartScript::IsCreature(WorldObject* obj) +{ + return obj && obj->GetTypeId() == TYPEID_UNIT; +} + +bool SmartScript::IsCharmedCreature(WorldObject* obj) +{ + if (!obj) + return false; + + if (Creature* creatureObj = obj->ToCreature()) + return creatureObj->IsCharmed(); + + return false; +} + +bool SmartScript::IsGameObject(WorldObject* obj) +{ + return obj && obj->GetTypeId() == TYPEID_GAMEOBJECT; +} + void SmartScript::OnUpdate(uint32 const diff) { if ((mScriptType == SMART_SCRIPT_TYPE_CREATURE || mScriptType == SMART_SCRIPT_TYPE_GAMEOBJECT) && !GetBaseObject()) diff --git a/src/server/game/AI/SmartScripts/SmartScript.h b/src/server/game/AI/SmartScripts/SmartScript.h index 7bd6c23cb9b..ff0e4ced602 100644 --- a/src/server/game/AI/SmartScripts/SmartScript.h +++ b/src/server/game/AI/SmartScripts/SmartScript.h @@ -18,15 +18,16 @@ #ifndef TRINITY_SMARTSCRIPT_H #define TRINITY_SMARTSCRIPT_H -#include "Common.h" -#include "Creature.h" -#include "CreatureAI.h" -#include "Unit.h" -#include "Spell.h" -#include "GridNotifiers.h" - +#include "Define.h" #include "SmartScriptMgr.h" -//#include "SmartAI.h" + +class Creature; +class GameObject; +class Player; +class SpellInfo; +class Unit; +class WorldObject; +struct AreaTriggerEntry; class TC_GAME_API SmartScript { @@ -38,61 +39,27 @@ class TC_GAME_API SmartScript void GetScript(); void FillScript(SmartAIEventList e, WorldObject* obj, AreaTriggerEntry const* at); - void ProcessEventsFor(SMART_EVENT e, Unit* unit = nullptr, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, const SpellInfo* spell = nullptr, GameObject* gob = nullptr); - void ProcessEvent(SmartScriptHolder& e, Unit* unit = nullptr, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, const SpellInfo* spell = nullptr, GameObject* gob = nullptr); + void ProcessEventsFor(SMART_EVENT e, Unit* unit = nullptr, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, SpellInfo const* spell = nullptr, GameObject* gob = nullptr); + void ProcessEvent(SmartScriptHolder& e, Unit* unit = nullptr, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, SpellInfo const* spell = nullptr, GameObject* gob = nullptr); bool CheckTimer(SmartScriptHolder const& e) const; void RecalcTimer(SmartScriptHolder& e, uint32 min, uint32 max); void UpdateTimer(SmartScriptHolder& e, uint32 const diff); void InitTimer(SmartScriptHolder& e); - void ProcessAction(SmartScriptHolder& e, Unit* unit = nullptr, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, const SpellInfo* spell = nullptr, GameObject* gob = nullptr); - void ProcessTimedAction(SmartScriptHolder& e, uint32 const& min, uint32 const& max, Unit* unit = nullptr, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, const SpellInfo* spell = nullptr, GameObject* gob = nullptr); - ObjectList* GetTargets(SmartScriptHolder const& e, Unit* invoker = nullptr); - ObjectList* GetWorldObjectsInDist(float dist); + void ProcessAction(SmartScriptHolder& e, Unit* unit = nullptr, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, SpellInfo const* spell = nullptr, GameObject* gob = nullptr); + void ProcessTimedAction(SmartScriptHolder& e, uint32 const& min, uint32 const& max, Unit* unit = nullptr, uint32 var0 = 0, uint32 var1 = 0, bool bvar = false, SpellInfo const* spell = nullptr, GameObject* gob = nullptr); + void GetTargets(ObjectVector& targets, SmartScriptHolder const& e, Unit* invoker = nullptr); + void GetWorldObjectsInDist(ObjectVector& targets, float dist); void InstallTemplate(SmartScriptHolder const& e); - SmartScriptHolder CreateEvent(SMART_EVENT e, uint32 event_flags, uint32 event_param1, uint32 event_param2, uint32 event_param3, uint32 event_param4, uint32 event_param5, SMART_ACTION action, uint32 action_param1, uint32 action_param2, uint32 action_param3, uint32 action_param4, uint32 action_param5, uint32 action_param6, SMARTAI_TARGETS t, uint32 target_param1, uint32 target_param2, uint32 target_param3, uint32 phaseMask = 0); + SmartScriptHolder CreateSmartEvent(SMART_EVENT e, uint32 event_flags, uint32 event_param1, uint32 event_param2, uint32 event_param3, uint32 event_param4, uint32 event_param5, SMART_ACTION action, uint32 action_param1, uint32 action_param2, uint32 action_param3, uint32 action_param4, uint32 action_param5, uint32 action_param6, SMARTAI_TARGETS t, uint32 target_param1, uint32 target_param2, uint32 target_param3, uint32 phaseMask = 0); void AddEvent(SMART_EVENT e, uint32 event_flags, uint32 event_param1, uint32 event_param2, uint32 event_param3, uint32 event_param4, uint32 event_param5, SMART_ACTION action, uint32 action_param1, uint32 action_param2, uint32 action_param3, uint32 action_param4, uint32 action_param5, uint32 action_param6, SMARTAI_TARGETS t, uint32 target_param1, uint32 target_param2, uint32 target_param3, uint32 phaseMask = 0); void SetPathId(uint32 id) { mPathId = id; } uint32 GetPathId() const { return mPathId; } - WorldObject* GetBaseObject() - { - WorldObject* obj = nullptr; - if (me) - obj = me; - else if (go) - obj = go; - return obj; - } - - static bool IsUnit(WorldObject* obj) - { - return obj && (obj->GetTypeId() == TYPEID_UNIT || obj->GetTypeId() == TYPEID_PLAYER); - } - - static bool IsPlayer(WorldObject* obj) - { - return obj && obj->GetTypeId() == TYPEID_PLAYER; - } - - static bool IsCreature(WorldObject* obj) - { - return obj && obj->GetTypeId() == TYPEID_UNIT; - } - - static bool IsCharmedCreature(WorldObject* obj) - { - if (!obj) - return false; - - if (Creature* creatureObj = obj->ToCreature()) - return creatureObj->IsCharmed(); - - return false; - } - - static bool IsGameObject(WorldObject* obj) - { - return obj && obj->GetTypeId() == TYPEID_GAMEOBJECT; - } + WorldObject* GetBaseObject() const; + static bool IsUnit(WorldObject* obj); + static bool IsPlayer(WorldObject* obj); + static bool IsCreature(WorldObject* obj); + static bool IsCharmedCreature(WorldObject* obj); + static bool IsGameObject(WorldObject* obj); void OnUpdate(const uint32 diff); void OnMoveInLineOfSight(Unit* who); @@ -102,136 +69,20 @@ class TC_GAME_API SmartScript void DoFindFriendlyMissingBuff(std::list& list, float range, uint32 spellid); Unit* DoFindClosestFriendlyInRange(float range, bool playerOnly); - void StoreTargetList(ObjectList* targets, uint32 id) - { - if (!targets) - return; + bool IsSmart(Creature* c = nullptr); + bool IsSmartGO(GameObject* g = nullptr); - if (mTargetStorage->find(id) != mTargetStorage->end()) - { - // check if already stored - if ((*mTargetStorage)[id]->Equals(targets)) - return; + void StoreTargetList(ObjectVector const& targets, uint32 id); + ObjectVector const* GetStoredTargetVector(uint32 id, WorldObject const& ref) const; - delete (*mTargetStorage)[id]; - } + void StoreCounter(uint32 id, uint32 value, uint32 reset); + uint32 GetCounterValue(uint32 id) const; - (*mTargetStorage)[id] = new ObjectGuidList(targets, GetBaseObject()); - } - - bool IsSmart(Creature* c = nullptr) - { - bool smart = true; - if (c && c->GetAIName() != "SmartAI") - smart = false; - - if (!me || me->GetAIName() != "SmartAI") - smart = false; - - if (!smart) - TC_LOG_ERROR("sql.sql", "SmartScript: Action target Creature (GUID: %u Entry: %u) is not using SmartAI, action called by Creature (GUID: %u Entry: %u) skipped to prevent crash.", c ? c->GetSpawnId() : 0, c ? c->GetEntry() : 0, me ? me->GetSpawnId() : 0, me ? me->GetEntry() : 0); - - return smart; - } - - bool IsSmartGO(GameObject* g = nullptr) - { - bool smart = true; - if (g && g->GetAIName() != "SmartGameObjectAI") - smart = false; - - if (!go || go->GetAIName() != "SmartGameObjectAI") - smart = false; - if (!smart) - TC_LOG_ERROR("sql.sql", "SmartScript: Action target GameObject (GUID: %u Entry: %u) is not using SmartGameObjectAI, action called by GameObject (GUID: %u Entry: %u) skipped to prevent crash.", g ? g->GetSpawnId() : 0, g ? g->GetEntry() : 0, go ? go->GetSpawnId() : 0, go ? go->GetEntry() : 0); - - return smart; - } - - ObjectList* GetTargetList(uint32 id) - { - ObjectListMap::iterator itr = mTargetStorage->find(id); - if (itr != mTargetStorage->end()) - return (*itr).second->GetObjectList(); - return nullptr; - } - - void StoreCounter(uint32 id, uint32 value, uint32 reset) - { - CounterMap::iterator itr = mCounterList.find(id); - if (itr != mCounterList.end()) - { - if (reset == 0) - itr->second += value; - else - itr->second = value; - } - else - mCounterList.insert(std::make_pair(id, value)); - - ProcessEventsFor(SMART_EVENT_COUNTER_SET, nullptr, id); - } - - uint32 GetCounterValue(uint32 id) const - { - CounterMap::const_iterator itr = mCounterList.find(id); - if (itr != mCounterList.end()) - return itr->second; - return 0; - } - - GameObject* FindGameObjectNear(WorldObject* searchObject, ObjectGuid::LowType guid) const - { - auto bounds = searchObject->GetMap()->GetGameObjectBySpawnIdStore().equal_range(guid); - if (bounds.first != bounds.second) - return bounds.first->second; - - return nullptr; - } - - Creature* FindCreatureNear(WorldObject* searchObject, ObjectGuid::LowType guid) const - { - auto bounds = searchObject->GetMap()->GetCreatureBySpawnIdStore().equal_range(guid); - if (bounds.first == bounds.second) - return nullptr; - - - auto creatureItr = std::find_if(bounds.first, bounds.second, [](Map::CreatureBySpawnIdContainer::value_type const& pair) -> bool { return pair.second->IsAlive(); }); - return creatureItr != bounds.second ? creatureItr->second : bounds.first->second; - } - - ObjectListMap* mTargetStorage; + GameObject* FindGameObjectNear(WorldObject* searchObject, ObjectGuid::LowType guid) const; + Creature* FindCreatureNear(WorldObject* searchObject, ObjectGuid::LowType guid) const; void OnReset(); - void ResetBaseObject() - { - WorldObject* lookupRoot = me; - if (!lookupRoot) - lookupRoot = go; - - if (lookupRoot) - { - if (!meOrigGUID.IsEmpty()) - { - if (Creature* m = ObjectAccessor::GetCreature(*lookupRoot, meOrigGUID)) - { - me = m; - go = nullptr; - } - } - - if (!goOrigGUID.IsEmpty()) - { - if (GameObject* o = ObjectAccessor::GetGameObject(*lookupRoot, goOrigGUID)) - { - me = nullptr; - go = o; - } - } - } - goOrigGUID.Clear(); - meOrigGUID.Clear(); - } + void ResetBaseObject(); //TIMED_ACTIONLIST (script type 9 aka script9) void SetScript9(SmartScriptHolder& e, uint32 entry); @@ -241,7 +92,6 @@ class TC_GAME_API SmartScript CounterMap mCounterList; private: - void IncPhase(uint32 p); void DecPhase(uint32 p); @@ -269,23 +119,12 @@ class TC_GAME_API SmartScript uint32 mTalkerEntry; bool mUseTextTimer; + ObjectVectorMap _storedTargets; + SMARTAI_TEMPLATE mTemplate; void InstallEvents(); - void RemoveStoredEvent(uint32 id) - { - if (!mStoredEvents.empty()) - { - for (auto i = mStoredEvents.begin(); i != mStoredEvents.end(); ++i) - { - if (i->event_id == id) - { - mStoredEvents.erase(i); - return; - } - } - } - } + void RemoveStoredEvent(uint32 id); }; #endif diff --git a/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp b/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp index 833cc9a3145..881a96ad82a 100644 --- a/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp +++ b/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp @@ -15,18 +15,21 @@ * with this program. If not, see . */ -#include "DatabaseEnv.h" -#include "ObjectMgr.h" -#include "GridDefines.h" -#include "GridNotifiers.h" -#include "InstanceScript.h" -#include "SpellMgr.h" -#include "Cell.h" -#include "GameEventMgr.h" -#include "CreatureTextMgr.h" -#include "SpellInfo.h" - #include "SmartScriptMgr.h" +#include "CreatureTextMgr.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "DB2Stores.h" +#include "GameEventMgr.h" +#include "InstanceScript.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "SpellInfo.h" +#include "SpellMgr.h" +#include "Timer.h" +#include "UnitDefines.h" SmartWaypointMgr* SmartWaypointMgr::instance() { @@ -380,6 +383,43 @@ void SmartAIMgr::LoadSmartAIFromDB() UnLoadHelperStores(); } +SmartAIEventList SmartAIMgr::GetScript(int32 entry, SmartScriptType type) +{ + SmartAIEventList temp; + if (mEventMap[uint32(type)].find(entry) != mEventMap[uint32(type)].end()) + return mEventMap[uint32(type)][entry]; + else + { + if (entry > 0)//first search is for guid (negative), do not drop error if not found + TC_LOG_DEBUG("scripts.ai", "SmartAIMgr::GetScript: Could not load Script for Entry %d ScriptType %u.", entry, uint32(type)); + return temp; + } +} + +SmartScriptHolder& SmartAIMgr::FindLinkedSourceEvent(SmartAIEventList& list, uint32 eventId) +{ + SmartAIEventList::iterator itr = std::find_if(list.begin(), list.end(), + [eventId](SmartScriptHolder& source) { return source.link == eventId; }); + + if (itr != list.end()) + return *itr; + + static SmartScriptHolder SmartScriptHolderDummy; + return SmartScriptHolderDummy; +} + +SmartScriptHolder& SmartAIMgr::FindLinkedEvent(SmartAIEventList& list, uint32 link) +{ + SmartAIEventList::iterator itr = std::find_if(list.begin(), list.end(), + [link](SmartScriptHolder& linked) { return linked.event_id == link && linked.GetEventType() == SMART_EVENT_LINK; }); + + if (itr != list.end()) + return *itr; + + static SmartScriptHolder SmartScriptHolderDummy; + return SmartScriptHolderDummy; +} + /*static*/ bool SmartAIMgr::EventHasInvoker(SMART_EVENT event) { switch (event) @@ -518,6 +558,126 @@ bool SmartAIMgr::IsTargetValid(SmartScriptHolder const& e) return true; } +bool SmartAIMgr::IsMinMaxValid(SmartScriptHolder const& e, uint32 min, uint32 max) +{ + if (max < min) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses min/max params wrong (%u/%u), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), min, max); + return false; + } + return true; +} + +bool SmartAIMgr::NotNULL(SmartScriptHolder const& e, uint32 data) +{ + if (!data) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u Parameter can not be nullptr, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); + return false; + } + return true; +} + +bool SmartAIMgr::IsCreatureValid(SmartScriptHolder const& e, uint32 entry) +{ + if (!sObjectMgr->GetCreatureTemplate(entry)) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Creature entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; +} + +bool SmartAIMgr::IsQuestValid(SmartScriptHolder const& e, uint32 entry) +{ + if (!sObjectMgr->GetQuestTemplate(entry)) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Quest entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; +} + +bool SmartAIMgr::IsGameObjectValid(SmartScriptHolder const& e, uint32 entry) +{ + if (!sObjectMgr->GetGameObjectTemplate(entry)) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent GameObject entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; +} + +bool SmartAIMgr::IsSpellValid(SmartScriptHolder const& e, uint32 entry) +{ + if (!sSpellMgr->GetSpellInfo(entry)) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Spell entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; +} + +bool SmartAIMgr::IsItemValid(SmartScriptHolder const& e, uint32 entry) +{ + if (!sItemStore.LookupEntry(entry)) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Item entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; +} + +bool SmartAIMgr::IsTextEmoteValid(SmartScriptHolder const& e, uint32 entry) +{ + if (!sEmotesTextStore.LookupEntry(entry)) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Text Emote entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; +} + +bool SmartAIMgr::IsEmoteValid(SmartScriptHolder const& e, uint32 entry) +{ + if (!sEmotesStore.LookupEntry(entry)) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Emote entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; +} + +bool SmartAIMgr::IsAreaTriggerValid(SmartScriptHolder const& e, uint32 entry) +{ + if (!sAreaTriggerStore.LookupEntry(entry)) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent AreaTrigger entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; +} + +bool SmartAIMgr::IsSoundValid(SmartScriptHolder const& e, uint32 entry) +{ + if (!sSoundEntriesStore.LookupEntry(entry)) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Sound entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; +} + +bool SmartAIMgr::IsAnimKitValid(SmartScriptHolder const& e, uint32 entry) +{ + if (!sAnimKitStore.LookupEntry(entry)) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %u SourceType %u Event %u Action %u uses non-existent AnimKit entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); + return false; + } + return true; +} + bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) { if (e.event.type >= SMART_EVENT_END) @@ -1000,7 +1160,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) break; case SMART_ACTION_RANDOM_SOUND: { - if (std::all_of(e.action.randomSound.sounds.begin(), e.action.randomSound.sounds.end(), [](uint32 sound) { return sound == 0; })) + if (std::all_of(std::begin(e.action.randomSound.sounds), std::end(e.action.randomSound.sounds), [](uint32 sound) { return sound == 0; })) { TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u does not have any non-zero sound", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); @@ -1081,19 +1241,21 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) return false; break; case SMART_ACTION_RANDOM_PHASE: + { + if (std::all_of(std::begin(e.action.randomPhase.phases), std::end(e.action.randomPhase.phases), [](uint32 phase) { return phase == 0; })) { - if (e.action.randomPhase.phase1 >= SMART_EVENT_PHASE_MAX || - e.action.randomPhase.phase2 >= SMART_EVENT_PHASE_MAX || - e.action.randomPhase.phase3 >= SMART_EVENT_PHASE_MAX || - e.action.randomPhase.phase4 >= SMART_EVENT_PHASE_MAX || - e.action.randomPhase.phase5 >= SMART_EVENT_PHASE_MAX || - e.action.randomPhase.phase6 >= SMART_EVENT_PHASE_MAX) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u attempts to set invalid phase, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); - return false; - } + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u does not have any non-zero phase", + e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); + return false; + } + + if (std::any_of(std::begin(e.action.randomPhase.phases), std::end(e.action.randomPhase.phases), [](uint32 phase) { return phase >= SMART_EVENT_PHASE_MAX; })) + { + TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u attempts to set invalid phase, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); + return false; } break; + } case SMART_ACTION_RANDOM_PHASE_RANGE: //PhaseMin, PhaseMax { if (e.action.randomPhaseRange.phaseMin >= SMART_EVENT_PHASE_MAX || @@ -1238,7 +1400,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) } case SMART_ACTION_CALL_RANDOM_RANGE_TIMED_ACTIONLIST: { - if (!IsMinMaxValid(e, e.action.randTimedActionList.entry1, e.action.randTimedActionList.entry2)) + if (!IsMinMaxValid(e, e.action.randTimedActionList.actionLists[0], e.action.randTimedActionList.actionLists[1])) return false; break; } @@ -1507,7 +1669,7 @@ void SmartAIMgr::LoadHelperStores() { uint32 oldMSTime = getMSTime(); - SpellInfo const* spellInfo = NULL; + SpellInfo const* spellInfo = nullptr; for (uint32 i = 0; i < sSpellMgr->GetSpellInfoStoreSize(); ++i) { spellInfo = sSpellMgr->GetSpellInfo(i); @@ -1560,3 +1722,19 @@ CacheSpellContainerBounds SmartAIMgr::GetCreateItemSpellContainerBounds(uint32 i { return CreateItemSpellStore.equal_range(itemId); } + +ObjectGuidVector::ObjectGuidVector(ObjectVector const& objectVector) : _objectVector(objectVector) +{ + _guidVector.reserve(_objectVector.size()); + for (WorldObject* obj : _objectVector) + _guidVector.push_back(obj->GetGUID()); +} + +void ObjectGuidVector::UpdateObjects(WorldObject const& ref) const +{ + _objectVector.clear(); + + for (ObjectGuid const& guid : _guidVector) + if (WorldObject* obj = ObjectAccessor::GetWorldObject(ref, guid)) + _objectVector.push_back(obj); +} diff --git a/src/server/game/AI/SmartScripts/SmartScriptMgr.h b/src/server/game/AI/SmartScripts/SmartScriptMgr.h index bd06e946341..a77e2374751 100644 --- a/src/server/game/AI/SmartScripts/SmartScriptMgr.h +++ b/src/server/game/AI/SmartScripts/SmartScriptMgr.h @@ -18,15 +18,14 @@ #ifndef TRINITY_SMARTSCRIPTMGR_H #define TRINITY_SMARTSCRIPTMGR_H -#include "Common.h" -#include "Creature.h" -#include "CreatureAI.h" -#include "Unit.h" -#include "Spell.h" -#include "DB2Stores.h" +#include "Define.h" +#include "ObjectGuid.h" +#include +#include +#include -//#include "SmartScript.h" -//#include "SmartAI.h" +class WorldObject; +enum SpellEffIndex : uint8; struct WayPoint { @@ -748,12 +747,7 @@ struct SmartAction struct { - uint32 phase1; - uint32 phase2; - uint32 phase3; - uint32 phase4; - uint32 phase5; - uint32 phase6; + uint32 phases[SMART_ACTION_PARAM_COUNT]; } randomPhase; struct @@ -988,12 +982,7 @@ struct SmartAction struct { - uint32 entry1; - uint32 entry2; - uint32 entry3; - uint32 entry4; - uint32 entry5; - uint32 entry6; + uint32 actionLists[SMART_ACTION_PARAM_COUNT]; } randTimedActionList; struct @@ -1103,17 +1092,12 @@ struct SmartAction struct { - uint32 wp1; - uint32 wp2; - uint32 wp3; - uint32 wp4; - uint32 wp5; - uint32 wp6; + uint32 wps[SMART_ACTION_PARAM_COUNT]; } closestWaypointFromList; struct { - std::array sounds; + uint32 sounds[SMART_ACTION_PARAM_COUNT - 2]; uint32 onlySelf; uint32 distance; } randomSound; @@ -1536,59 +1520,29 @@ struct SmartScriptHolder typedef std::unordered_map WPPath; -typedef std::list ObjectList; +typedef std::vector ObjectVector; -class ObjectGuidList +class ObjectGuidVector { - ObjectList* m_objectList; - GuidList* m_guidList; - WorldObject* m_baseObject; + public: + explicit ObjectGuidVector(ObjectVector const& objectVector); -public: - ObjectGuidList(ObjectList* objectList, WorldObject* baseObject) - { - ASSERT(objectList != NULL); - m_objectList = objectList; - m_baseObject = baseObject; - m_guidList = new GuidList(); - - for (ObjectList::iterator itr = objectList->begin(); itr != objectList->end(); ++itr) + ObjectVector const* GetObjectVector(WorldObject const& ref) const { - m_guidList->push_back((*itr)->GetGUID()); - } - } - - ObjectList* GetObjectList() - { - if (m_baseObject) - { - //sanitize list using m_guidList - m_objectList->clear(); - - for (GuidList::iterator itr = m_guidList->begin(); itr != m_guidList->end(); ++itr) - { - if (WorldObject* obj = ObjectAccessor::GetWorldObject(*m_baseObject, *itr)) - m_objectList->push_back(obj); - else - TC_LOG_DEBUG("scripts.ai", "SmartScript::mTargetStorage stores a guid to an invalid object: %s", itr->ToString().c_str()); - } + UpdateObjects(ref); + return &_objectVector; } - return m_objectList; - } + ~ObjectGuidVector() { } - bool Equals(ObjectList* objectList) - { - return m_objectList == objectList; - } + private: + GuidVector _guidVector; + mutable ObjectVector _objectVector; - ~ObjectGuidList() - { - delete m_objectList; - delete m_guidList; - } + //sanitize vector using _guidVector + void UpdateObjects(WorldObject const& ref) const; }; -typedef std::unordered_map ObjectListMap; +typedef std::unordered_map ObjectVectorMap; class TC_GAME_API SmartWaypointMgr { @@ -1634,42 +1588,11 @@ class TC_GAME_API SmartAIMgr void LoadSmartAIFromDB(); - SmartAIEventList GetScript(int32 entry, SmartScriptType type) - { - SmartAIEventList temp; - if (mEventMap[uint32(type)].find(entry) != mEventMap[uint32(type)].end()) - return mEventMap[uint32(type)][entry]; - else - { - if (entry > 0)//first search is for guid (negative), do not drop error if not found - TC_LOG_DEBUG("scripts.ai", "SmartAIMgr::GetScript: Could not load Script for Entry %d ScriptType %u.", entry, uint32(type)); - return temp; - } - } + SmartAIEventList GetScript(int32 entry, SmartScriptType type); - static SmartScriptHolder& FindLinkedSourceEvent(SmartAIEventList& list, uint32 eventId) - { - SmartAIEventList::iterator itr = std::find_if(list.begin(), list.end(), - [eventId](SmartScriptHolder& source) { return source.link == eventId; }); + static SmartScriptHolder& FindLinkedSourceEvent(SmartAIEventList& list, uint32 eventId); - if (itr != list.end()) - return *itr; - - static SmartScriptHolder SmartScriptHolderDummy; - return SmartScriptHolderDummy; - } - - static SmartScriptHolder& FindLinkedEvent(SmartAIEventList& list, uint32 link) - { - SmartAIEventList::iterator itr = std::find_if(list.begin(), list.end(), - [link](SmartScriptHolder& linked) { return linked.event_id == link && linked.GetEventType() == SMART_EVENT_LINK; }); - - if (itr != list.end()) - return *itr; - - static SmartScriptHolder SmartScriptHolderDummy; - return SmartScriptHolderDummy; - } + static SmartScriptHolder& FindLinkedEvent(SmartAIEventList& list, uint32 link); private: //event stores @@ -1680,137 +1603,20 @@ class TC_GAME_API SmartAIMgr bool IsEventValid(SmartScriptHolder& e); bool IsTargetValid(SmartScriptHolder const& e); - bool IsMinMaxValid(SmartScriptHolder const& e, uint32 min, uint32 max) - { - if (max < min) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses min/max params wrong (%u/%u), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), min, max); - return false; - } - return true; - } + static bool IsMinMaxValid(SmartScriptHolder const& e, uint32 min, uint32 max); - /*inline bool IsPercentValid(SmartScriptHolder e, int32 pct) - { - if (pct < -100 || pct > 100) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u has invalid Percent set (%d), skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), pct); - return false; - } - return true; - }*/ - - bool NotNULL(SmartScriptHolder const& e, uint32 data) - { - if (!data) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u Parameter can not be NULL, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType()); - return false; - } - return true; - } - - bool IsCreatureValid(SmartScriptHolder const& e, uint32 entry) - { - if (!sObjectMgr->GetCreatureTemplate(entry)) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Creature entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; - } - - bool IsQuestValid(SmartScriptHolder const& e, uint32 entry) - { - if (!sObjectMgr->GetQuestTemplate(entry)) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Quest entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; - } - - bool IsGameObjectValid(SmartScriptHolder const& e, uint32 entry) - { - if (!sObjectMgr->GetGameObjectTemplate(entry)) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent GameObject entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; - } - - bool IsSpellValid(SmartScriptHolder const& e, uint32 entry) - { - if (!sSpellMgr->GetSpellInfo(entry)) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Spell entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; - } - - bool IsItemValid(SmartScriptHolder const& e, uint32 entry) - { - if (!sItemStore.LookupEntry(entry)) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Item entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; - } - - bool IsTextEmoteValid(SmartScriptHolder const& e, uint32 entry) - { - if (!sEmotesTextStore.LookupEntry(entry)) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Text Emote entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; - } - - bool IsEmoteValid(SmartScriptHolder const& e, uint32 entry) - { - if (!sEmotesStore.LookupEntry(entry)) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Emote entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; - } - - bool IsAreaTriggerValid(SmartScriptHolder const& e, uint32 entry) - { - if (!sAreaTriggerStore.LookupEntry(entry)) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent AreaTrigger entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; - } - - bool IsSoundValid(SmartScriptHolder const& e, uint32 entry) - { - if (!sSoundEntriesStore.LookupEntry(entry)) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %d SourceType %u Event %u Action %u uses non-existent Sound entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; - } - - bool IsAnimKitValid(SmartScriptHolder const& e, uint32 entry) - { - if (!sAnimKitStore.LookupEntry(entry)) - { - TC_LOG_ERROR("sql.sql", "SmartAIMgr: Entry %u SourceType %u Event %u Action %u uses non-existent AnimKit entry %u, skipped.", e.entryOrGuid, e.GetScriptType(), e.event_id, e.GetActionType(), entry); - return false; - } - return true; - } - - bool IsTextValid(SmartScriptHolder const& e, uint32 id); + static bool NotNULL(SmartScriptHolder const& e, uint32 data); + static bool IsCreatureValid(SmartScriptHolder const& e, uint32 entry); + static bool IsQuestValid(SmartScriptHolder const& e, uint32 entry); + static bool IsGameObjectValid(SmartScriptHolder const& e, uint32 entry); + static bool IsSpellValid(SmartScriptHolder const& e, uint32 entry); + static bool IsItemValid(SmartScriptHolder const& e, uint32 entry); + static bool IsTextEmoteValid(SmartScriptHolder const& e, uint32 entry); + static bool IsEmoteValid(SmartScriptHolder const& e, uint32 entry); + static bool IsAreaTriggerValid(SmartScriptHolder const& e, uint32 entry); + static bool IsSoundValid(SmartScriptHolder const& e, uint32 entry); + static bool IsAnimKitValid(SmartScriptHolder const& e, uint32 entry); + static bool IsTextValid(SmartScriptHolder const& e, uint32 id); // Helpers void LoadHelperStores(); diff --git a/src/server/game/Accounts/AccountMgr.cpp b/src/server/game/Accounts/AccountMgr.cpp index edc29652ff2..b2dc5810709 100644 --- a/src/server/game/Accounts/AccountMgr.cpp +++ b/src/server/game/Accounts/AccountMgr.cpp @@ -19,11 +19,14 @@ #include "AccountMgr.h" #include "Config.h" #include "DatabaseEnv.h" +#include "Log.h" #include "ObjectAccessor.h" #include "Player.h" +#include "Realm.h" #include "ScriptMgr.h" -#include "Util.h" #include "SHA1.h" +#include "Util.h" +#include "World.h" #include "WorldSession.h" AccountMgr::AccountMgr() { } @@ -447,7 +450,7 @@ void AccountMgr::LoadRBAC() } uint32 permissionId = 0; - rbac::RBACPermission* permission = NULL; + rbac::RBACPermission* permission = nullptr; do { @@ -479,12 +482,12 @@ void AccountMgr::LoadRBAC() } uint8 secId = 255; - rbac::RBACPermissionContainer* permissions = NULL; + rbac::RBACPermissionContainer* permissions = nullptr; do { Field* field = result->Fetch(); uint32 newId = field[0].GetUInt32(); - if (secId != newId || permissions == NULL) + if (secId != newId || permissions == nullptr) { secId = newId; permissions = &_defaultPermissions[secId]; @@ -539,7 +542,7 @@ rbac::RBACPermission const* AccountMgr::GetRBACPermission(uint32 permissionId) c if (it != _permissions.end()) return it->second; - return NULL; + return nullptr; } bool AccountMgr::HasPermission(uint32 accountId, uint32 permissionId, uint32 realmId) diff --git a/src/server/game/Accounts/RBAC.cpp b/src/server/game/Accounts/RBAC.cpp index 8c9f01acfee..7e5557ce27c 100644 --- a/src/server/game/Accounts/RBAC.cpp +++ b/src/server/game/Accounts/RBAC.cpp @@ -17,8 +17,9 @@ #include "RBAC.h" #include "AccountMgr.h" +#include "DatabaseEnv.h" #include "Log.h" -#include "QueryCallback.h" +#include namespace rbac { diff --git a/src/server/game/Accounts/RBAC.h b/src/server/game/Accounts/RBAC.h index 6fccd412164..fbf05f1bc18 100644 --- a/src/server/game/Accounts/RBAC.h +++ b/src/server/game/Accounts/RBAC.h @@ -40,7 +40,8 @@ #ifndef _RBAC_H #define _RBAC_H -#include "DatabaseEnv.h" +#include "Define.h" +#include "DatabaseEnvFwd.h" #include #include #include diff --git a/src/server/game/Achievements/AchievementMgr.cpp b/src/server/game/Achievements/AchievementMgr.cpp index 2f14432b574..db451f8a27a 100644 --- a/src/server/game/Achievements/AchievementMgr.cpp +++ b/src/server/game/Achievements/AchievementMgr.cpp @@ -17,12 +17,9 @@ */ #include "AchievementMgr.h" -#include "ArenaTeam.h" #include "ArenaTeamMgr.h" #include "Battleground.h" -#include "CellImpl.h" #include "ChatTextBuilder.h" -#include "Common.h" #include "DatabaseEnv.h" #include "DBCEnums.h" #include "DisableMgr.h" @@ -32,7 +29,10 @@ #include "Guild.h" #include "GuildMgr.h" #include "InstanceScript.h" +#include "Item.h" #include "Language.h" +#include "Log.h" +#include "Mail.h" #include "Map.h" #include "MapManager.h" #include "ObjectMgr.h" @@ -41,7 +41,7 @@ #include "ScriptMgr.h" #include "SpellMgr.h" #include "World.h" -#include "WorldPacket.h" +#include "WorldSession.h" bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) { @@ -418,7 +418,7 @@ void AchievementMgr::SendPacket(WorldPacket* data) const template<> void AchievementMgr::SendPacket(WorldPacket* data) const { - GetOwner()->GetSession()->SendPacket(data); + GetOwner()->SendDirectMessage(data); } template @@ -694,7 +694,7 @@ void AchievementMgr::LoadFromDB(PreparedQueryResult achievementResult, P if (criteriaResult) { - time_t now = time(NULL); + time_t now = time(nullptr); do { Field* fields = criteriaResult->Fetch(); @@ -757,7 +757,7 @@ void AchievementMgr::LoadFromDB(PreparedQueryResult achievementResult, Pr if (criteriaResult) { - time_t now = time(NULL); + time_t now = time(nullptr); do { Field* fields = criteriaResult->Fetch(); @@ -896,7 +896,7 @@ void AchievementMgr::SendAchievementEarned(AchievementEntry const* achievemen WorldPacket data(SMSG_ACHIEVEMENT_EARNED, 8+4+8); data << GetOwner()->GetPackGUID(); data << uint32(achievement->ID); - data.AppendPackedTime(time(NULL)); + data.AppendPackedTime(time(nullptr)); data << uint32(0); // does not notify player ingame GetOwner()->SendMessageToSetInRange(&data, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY), true); } @@ -917,7 +917,7 @@ void AchievementMgr::SendAchievementEarned(AchievementEntry const* achiev data.WriteBit(guid[5]); data.WriteByteSeq(guid[2]); - data.AppendPackedTime(time(NULL)); + data.AppendPackedTime(time(nullptr)); data.WriteByteSeq(guid[0]); data.WriteByteSeq(guid[4]); data.WriteByteSeq(guid[1]); @@ -1094,7 +1094,7 @@ void AchievementMgr::SendAllTrackedCriterias(Player* receiver, std::setGetSession()->SendPacket(&data); + receiver->SendDirectMessage(&data); } /** @@ -1105,7 +1105,7 @@ void AchievementMgr::CheckAllAchievementCriteria(Player* referencePlayer) { // suppress sending packets for (uint32 i = 0; i < ACHIEVEMENT_CRITERIA_TYPE_TOTAL; ++i) - UpdateAchievementCriteria(AchievementCriteriaTypes(i), 0, 0, 0, NULL, referencePlayer); + UpdateAchievementCriteria(AchievementCriteriaTypes(i), 0, 0, 0, nullptr, referencePlayer); } static const uint32 achievIdByArenaSlot[MAX_ARENA_SLOT] = {1057, 1107, 1108}; @@ -1128,7 +1128,7 @@ template<> bool IsGuild() { return true; } * this function will be called whenever the user might have done a criteria relevant action */ template -void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, uint64 miscValue1 /*= 0*/, uint64 miscValue2 /*= 0*/, uint64 miscValue3 /*= 0*/, Unit const* unit /*= NULL*/, Player* referencePlayer /*= NULL*/) +void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, uint64 miscValue1 /*= 0*/, uint64 miscValue2 /*= 0*/, uint64 miscValue3 /*= 0*/, Unit const* unit /*= nullptr*/, Player* referencePlayer /*= nullptr*/) { if (type >= ACHIEVEMENT_CRITERIA_TYPE_TOTAL) { @@ -1138,7 +1138,7 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, if (!referencePlayer) { - TC_LOG_DEBUG("achievement", "UpdateAchievementCriteria: Player is NULL! Cant update criteria"); + TC_LOG_DEBUG("achievement", "UpdateAchievementCriteria: Player is nullptr! Cant update criteria"); return; } @@ -1318,7 +1318,7 @@ void AchievementMgr::UpdateAchievementCriteria(AchievementCriteriaTypes type, { uint32 counter = 0; - const RewardedQuestSet &rewQuests = referencePlayer->getRewardedQuests(); + RewardedQuestSet const& rewQuests = referencePlayer->getRewardedQuests(); for (RewardedQuestSet::const_iterator itr = rewQuests.begin(); itr != rewQuests.end(); ++itr) { Quest const* quest = sObjectMgr->GetQuestTemplate(*itr); @@ -1770,7 +1770,7 @@ CriteriaProgress* AchievementMgr::GetCriteriaProgress(AchievementCriteriaEntr CriteriaProgressMap::iterator iter = m_criteriaProgress.find(entry->ID); if (iter == m_criteriaProgress.end()) - return NULL; + return nullptr; return &(iter->second); } @@ -1825,7 +1825,7 @@ void AchievementMgr::SetCriteriaProgress(AchievementCriteriaEntry const* entr } progress->changed = true; - progress->date = time(NULL); // set the date to the latest update. + progress->date = time(nullptr); // set the date to the latest update. AchievementEntry const* achievement = sAchievementMgr->GetAchievement(entry->achievement); uint32 timeElapsed = 0; @@ -1942,15 +1942,15 @@ void AchievementMgr::CompletedAchievement(AchievementEntry const* achiev achievement->ID, GetOwner()->GetName().c_str(), GetOwner()->GetGUID().GetCounter()); CompletedAchievementData& ca = m_completedAchievements[achievement->ID]; - ca.date = time(NULL); + ca.date = time(nullptr); ca.changed = true; sAchievementMgr->SetRealmCompleted(achievement, GetOwner()->GetInstanceId()); _achievementPoints += achievement->points; - UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT, 0, 0, 0, NULL, referencePlayer); - UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS, achievement->points, 0, 0, NULL, referencePlayer); + UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT, 0, 0, 0, nullptr, referencePlayer); + UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS, achievement->points, 0, 0, nullptr, referencePlayer); // reward items and titles if any AchievementReward const* reward = sAchievementMgr->GetAchievementReward(achievement); @@ -1980,7 +1980,7 @@ void AchievementMgr::CompletedAchievement(AchievementEntry const* achiev std::string text = reward->Text; LocaleConstant localeConstant = GetOwner()->GetSession()->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) { if (AchievementRewardLocale const* loc = sAchievementMgr->GetAchievementRewardLocale(achievement)) { @@ -1994,7 +1994,7 @@ void AchievementMgr::CompletedAchievement(AchievementEntry const* achiev SQLTransaction trans = CharacterDatabase.BeginTransaction(); - Item* item = reward->ItemID ? Item::CreateItem(reward->ItemID, 1, GetOwner()) : NULL; + Item* item = reward->ItemID ? Item::CreateItem(reward->ItemID, 1, GetOwner()) : nullptr; if (item) { // save new item before send @@ -2023,7 +2023,7 @@ void AchievementMgr::CompletedAchievement(AchievementEntry const* achieve SendAchievementEarned(achievement); CompletedAchievementData& ca = m_completedAchievements[achievement->ID]; - ca.date = time(NULL); + ca.date = time(nullptr); ca.changed = true; if (achievement->flags & ACHIEVEMENT_FLAG_SHOW_GUILD_MEMBERS) @@ -2032,7 +2032,7 @@ void AchievementMgr::CompletedAchievement(AchievementEntry const* achieve ca.guids.insert(referencePlayer->GetGUID()); if (Group const* group = referencePlayer->GetGroup()) - for (GroupReference const* ref = group->GetFirstMember(); ref != NULL; ref = ref->next()) + for (GroupReference const* ref = group->GetFirstMember(); ref != nullptr; ref = ref->next()) if (Player const* groupMember = ref->GetSource()) if (groupMember->GetGuildId() == GetOwner()->GetId()) ca.guids.insert(groupMember->GetGUID()); @@ -2042,8 +2042,8 @@ void AchievementMgr::CompletedAchievement(AchievementEntry const* achieve _achievementPoints += achievement->points; - UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT, 0, 0, 0, NULL, referencePlayer); - UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS, achievement->points, 0, 0, NULL, referencePlayer); + UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT, 0, 0, 0, nullptr, referencePlayer); + UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS, achievement->points, 0, 0, nullptr, referencePlayer); } struct VisibleAchievementPred @@ -2147,7 +2147,7 @@ void AchievementMgr::SendAllAchievementData(Player* receiver) const data << uint32(itr->first); } - receiver->GetSession()->SendPacket(&data); + receiver->SendDirectMessage(&data); } template<> @@ -2237,7 +2237,7 @@ void AchievementMgr::SendAchievementInfo(Player* receiver, uint32 /*achi data.WriteByteSeq(guid[4]); data.WriteByteSeq(guid[5]); - receiver->GetSession()->SendPacket(&data); + receiver->SendDirectMessage(&data); } template<> @@ -2251,7 +2251,7 @@ void AchievementMgr::SendAchievementInfo(Player* receiver, uint32 achieve WorldPacket data(SMSG_GUILD_CRITERIA_DATA, 3); data.WriteBits(0, 21); data.FlushBits(); - receiver->GetSession()->SendPacket(&data); + receiver->SendDirectMessage(&data); return; } @@ -2327,7 +2327,7 @@ void AchievementMgr::SendAchievementInfo(Player* receiver, uint32 achieve if (numCriteria) data.append(criteriaData); - receiver->GetSession()->SendPacket(&data); + receiver->SendDirectMessage(&data); } template @@ -2346,7 +2346,7 @@ CompletedAchievementData* AchievementMgr::GetCompletedDataForAchievement(uint } else { - return NULL; + return nullptr; } } @@ -3334,7 +3334,7 @@ void AchievementGlobalMgr::LoadCompletedAchievements() Field* fields = result->Fetch(); uint16 achievementId = fields[0].GetUInt16(); - const AchievementEntry* achievement = sAchievementMgr->GetAchievement(achievementId); + AchievementEntry const* achievement = sAchievementMgr->GetAchievement(achievementId); if (!achievement) { // Remove non-existing achievements from all characters diff --git a/src/server/game/Achievements/AchievementMgr.h b/src/server/game/Achievements/AchievementMgr.h index 29965c6676f..3e8afef476d 100644 --- a/src/server/game/Achievements/AchievementMgr.h +++ b/src/server/game/Achievements/AchievementMgr.h @@ -19,14 +19,13 @@ #ifndef __TRINITY_ACHIEVEMENTMGR_H #define __TRINITY_ACHIEVEMENTMGR_H -#include -#include - -#include "Common.h" -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "DBCEnums.h" #include "DBCStores.h" #include "ObjectGuid.h" +#include +#include +#include class Unit; class Player; @@ -266,7 +265,7 @@ class TC_GAME_API AchievementMgr void LoadFromDB(PreparedQueryResult achievementResult, PreparedQueryResult criteriaResult); void SaveToDB(SQLTransaction& trans); void ResetAchievementCriteria(AchievementCriteriaTypes type, uint64 miscValue1 = 0, uint64 miscValue2 = 0, bool evenIfCriteriaComplete = false); - void UpdateAchievementCriteria(AchievementCriteriaTypes type, uint64 miscValue1 = 0, uint64 miscValue2 = 0, uint64 miscValue3 = 0, Unit const* unit = NULL, Player* referencePlayer = NULL); + void UpdateAchievementCriteria(AchievementCriteriaTypes type, uint64 miscValue1 = 0, uint64 miscValue2 = 0, uint64 miscValue3 = 0, Unit const* unit = nullptr, Player* referencePlayer = nullptr); void CompletedAchievement(AchievementEntry const* entry, Player* referencePlayer); void CheckAllAchievementCriteria(Player* referencePlayer); void SendAllAchievementData(Player* receiver) const; @@ -329,31 +328,31 @@ class TC_GAME_API AchievementGlobalMgr AchievementCriteriaEntryList const* GetAchievementCriteriaByAchievement(uint32 id) const { AchievementCriteriaListByAchievement::const_iterator itr = m_AchievementCriteriaListByAchievement.find(id); - return itr != m_AchievementCriteriaListByAchievement.end() ? &itr->second : NULL; + return itr != m_AchievementCriteriaListByAchievement.end() ? &itr->second : nullptr; } AchievementEntryList const* GetAchievementByReferencedId(uint32 id) const { AchievementListByReferencedId::const_iterator itr = m_AchievementListByReferencedId.find(id); - return itr != m_AchievementListByReferencedId.end() ? &itr->second : NULL; + return itr != m_AchievementListByReferencedId.end() ? &itr->second : nullptr; } AchievementReward const* GetAchievementReward(AchievementEntry const* achievement) const { AchievementRewards::const_iterator iter = m_achievementRewards.find(achievement->ID); - return iter != m_achievementRewards.end() ? &iter->second : NULL; + return iter != m_achievementRewards.end() ? &iter->second : nullptr; } AchievementRewardLocale const* GetAchievementRewardLocale(AchievementEntry const* achievement) const { AchievementRewardLocales::const_iterator iter = m_achievementRewardLocales.find(achievement->ID); - return iter != m_achievementRewardLocales.end() ? &iter->second : NULL; + return iter != m_achievementRewardLocales.end() ? &iter->second : nullptr; } AchievementCriteriaDataSet const* GetCriteriaDataSet(AchievementCriteriaEntry const* achievementCriteria) const { AchievementCriteriaDataMap::const_iterator iter = m_criteriaDataMap.find(achievementCriteria->ID); - return iter != m_criteriaDataMap.end() ? &iter->second : NULL; + return iter != m_criteriaDataMap.end() ? &iter->second : nullptr; } bool IsRealmCompleted(AchievementEntry const* achievement, uint32 instanceId) const diff --git a/src/server/game/Addons/AddonMgr.cpp b/src/server/game/Addons/AddonMgr.cpp index 3d199cef2c8..90eb4fa67df 100644 --- a/src/server/game/Addons/AddonMgr.cpp +++ b/src/server/game/Addons/AddonMgr.cpp @@ -119,7 +119,7 @@ SavedAddon const* GetAddonInfo(const std::string& name) return &addon; } - return NULL; + return nullptr; } BannedAddonList const* GetBannedAddons() diff --git a/src/server/game/AuctionHouse/AuctionHouseMgr.cpp b/src/server/game/AuctionHouse/AuctionHouseMgr.cpp index 29f2bd64231..55464583817 100644 --- a/src/server/game/AuctionHouse/AuctionHouseMgr.cpp +++ b/src/server/game/AuctionHouse/AuctionHouseMgr.cpp @@ -16,23 +16,27 @@ * with this program. If not, see . */ +#include "AuctionHouseMgr.h" +#include "AccountMgr.h" +#include "AuctionHouseBot.h" +#include "Bag.h" +#include "CharacterCache.h" #include "Common.h" -#include "ObjectMgr.h" -#include "Player.h" -#include "World.h" -#include "WorldPacket.h" -#include "WorldSession.h" #include "DatabaseEnv.h" #include "DBCStores.h" -#include "ScriptMgr.h" -#include "AccountMgr.h" -#include "AuctionHouseMgr.h" -#include "AuctionHouseBot.h" +#include "GameTime.h" #include "Item.h" #include "Language.h" #include "Log.h" -#include "GameTime.h" -#include "CharacterCache.h" +#include "Mail.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "Realm.h" +#include "ScriptMgr.h" +#include "World.h" +#include "WorldPacket.h" +#include "WorldSession.h" enum eAuctionHouse { @@ -459,7 +463,7 @@ bool AuctionHouseMgr::PendingAuctionAdd(Player* player, AuctionEntry* aEntry, It return true; } -uint32 AuctionHouseMgr::PendingAuctionCount(const Player* player) const +uint32 AuctionHouseMgr::PendingAuctionCount(Player const* player) const { auto const itr = pendingAuctionMap.find(player->GetGUID()); if (itr != pendingAuctionMap.end()) @@ -545,7 +549,7 @@ void AuctionHouseMgr::UpdatePendingAuctions() { AuctionEntry* AH = (*AHitr); ++AHitr; - AH->expire_time = time(NULL); + AH->expire_time = time(nullptr); AH->DeleteFromDB(trans); AH->SaveToDB(trans); } @@ -615,7 +619,7 @@ void AuctionHouseObject::Update() time_t curTime = GameTime::GetGameTime(); ///- Handle expired auctions - // If storage is empty, no need to update. next == NULL in this case. + // If storage is empty, no need to update. next == nullptr in this case. if (AuctionsMap.empty()) return; @@ -776,7 +780,7 @@ void AuctionHouseObject::BuildListAuctionItems(WorldPacket& data, Player* player continue; // local name - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) if (ItemLocale const* il = sObjectMgr->GetItemLocale(proto->ItemId)) ObjectMgr::GetLocaleString(il->Name, localeConstant, name); @@ -795,13 +799,13 @@ void AuctionHouseObject::BuildListAuctionItems(WorldPacket& data, Player* player if (propRefID < 0) { - const ItemRandomSuffixEntry* itemRandSuffix = sItemRandomSuffixStore.LookupEntry(-propRefID); + ItemRandomSuffixEntry const* itemRandSuffix = sItemRandomSuffixStore.LookupEntry(-propRefID); if (itemRandSuffix) suffix = itemRandSuffix->nameSuffix; } else { - const ItemRandomPropertiesEntry* itemRandProp = sItemRandomPropertiesStore.LookupEntry(propRefID); + ItemRandomPropertiesEntry const* itemRandProp = sItemRandomPropertiesStore.LookupEntry(propRefID); if (itemRandProp) suffix = itemRandProp->nameSuffix; } @@ -860,7 +864,7 @@ bool AuctionEntry::BuildAuctionInfo(WorldPacket& data, Item* sourceItem) const data << uint64(bid ? GetAuctionOutBid() : 0); // Minimal outbid data << uint64(buyout); // Auction->buyout - data << uint32((expire_time - time(NULL)) * IN_MILLISECONDS); // time left + data << uint32((expire_time - time(nullptr)) * IN_MILLISECONDS); // time left data << uint64(bidder); // auction->bidder current data << uint64(bid); // current bid return true; diff --git a/src/server/game/AuctionHouse/AuctionHouseMgr.h b/src/server/game/AuctionHouse/AuctionHouseMgr.h index abee3772327..245f2dc10ee 100644 --- a/src/server/game/AuctionHouse/AuctionHouseMgr.h +++ b/src/server/game/AuctionHouse/AuctionHouseMgr.h @@ -19,14 +19,17 @@ #ifndef _AUCTION_HOUSE_MGR_H #define _AUCTION_HOUSE_MGR_H -#include "Common.h" -#include "DatabaseEnv.h" -#include "DBCStructure.h" +#include "Define.h" +#include "DatabaseEnvFwd.h" +#include "ObjectGuid.h" +#include #include +#include class Item; class Player; class WorldPacket; +struct AuctionHouseEntry; #define MIN_AUCTION_TIME (12*HOUR) #define MAX_AUCTION_ITEMS 160 @@ -122,7 +125,7 @@ class TC_GAME_API AuctionHouseObject AuctionEntry* GetAuction(uint32 id) const { AuctionEntryMap::const_iterator itr = AuctionsMap.find(id); - return itr != AuctionsMap.end() ? itr->second : NULL; + return itr != AuctionsMap.end() ? itr->second : nullptr; } void AddAuction(AuctionEntry* auction); @@ -169,7 +172,7 @@ class TC_GAME_API AuctionHouseMgr if (itr != mAitems.end()) return itr->second; - return NULL; + return nullptr; } //auction messages @@ -192,7 +195,7 @@ class TC_GAME_API AuctionHouseMgr void AddAItem(Item* it); bool RemoveAItem(ObjectGuid::LowType id, bool deleteItem = false, SQLTransaction* trans = nullptr); bool PendingAuctionAdd(Player* player, AuctionEntry* aEntry, Item* item); - uint32 PendingAuctionCount(const Player* player) const; + uint32 PendingAuctionCount(Player const* player) const; void PendingAuctionProcess(Player* player); void UpdatePendingAuctions(); void Update(); diff --git a/src/server/game/AuctionHouseBot/AuctionHouseBot.cpp b/src/server/game/AuctionHouseBot/AuctionHouseBot.cpp index 65c976550e2..a88c97d1cdf 100644 --- a/src/server/game/AuctionHouseBot/AuctionHouseBot.cpp +++ b/src/server/game/AuctionHouseBot/AuctionHouseBot.cpp @@ -15,17 +15,18 @@ * with this program. If not, see . */ -#include "Containers.h" -#include "Log.h" -#include "Item.h" -#include "World.h" -#include "Config.h" -#include "AccountMgr.h" -#include "AuctionHouseMgr.h" #include "AuctionHouseBot.h" +#include "AccountMgr.h" #include "AuctionHouseBotBuyer.h" #include "AuctionHouseBotSeller.h" +#include "AuctionHouseMgr.h" +#include "Config.h" +#include "Containers.h" +#include "DatabaseEnv.h" #include "GameTime.h" +#include "Item.h" +#include "Log.h" +#include "World.h" AuctionBotConfig* AuctionBotConfig::instance() { diff --git a/src/server/game/AuctionHouseBot/AuctionHouseBot.h b/src/server/game/AuctionHouseBot/AuctionHouseBot.h index 53165663a43..685d27f0b18 100644 --- a/src/server/game/AuctionHouseBot/AuctionHouseBot.h +++ b/src/server/game/AuctionHouseBot/AuctionHouseBot.h @@ -19,6 +19,9 @@ #define AUCTION_HOUSE_BOT_H #include "Define.h" +#include "SharedDefines.h" +#include +#include class AuctionBotSeller; class AuctionBotBuyer; @@ -204,15 +207,15 @@ class TC_GAME_API AuctionBotConfig private: AuctionBotConfig(): _itemsPerCycleBoost(1000), _itemsPerCycleNormal(20) {} ~AuctionBotConfig() {} - AuctionBotConfig(const AuctionBotConfig&); - AuctionBotConfig& operator=(const AuctionBotConfig&); + AuctionBotConfig(AuctionBotConfig const&) = delete; + AuctionBotConfig& operator=(AuctionBotConfig const&) = delete; public: static AuctionBotConfig* instance(); bool Initialize(); - const std::string& GetAHBotIncludes() const { return _AHBotIncludes; } - const std::string& GetAHBotExcludes() const { return _AHBotExcludes; } + std::string const& GetAHBotIncludes() const { return _AHBotIncludes; } + std::string const& GetAHBotExcludes() const { return _AHBotExcludes; } uint32 GetConfig(AuctionBotConfigUInt32Values index) const { return _configUint32Values[index]; } bool GetConfig(AuctionBotConfigBoolValues index) const { return _configBoolValues[index]; } diff --git a/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.cpp b/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.cpp index 1abf495a467..57763311f9a 100644 --- a/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.cpp +++ b/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.cpp @@ -15,10 +15,12 @@ * with this program. If not, see . */ -#include "Log.h" +#include "AuctionHouseBotBuyer.h" +#include "DatabaseEnv.h" #include "Item.h" #include "ItemTemplate.h" -#include "AuctionHouseBotBuyer.h" +#include "Log.h" +#include "Random.h" AuctionBotBuyer::AuctionBotBuyer() : _checkInterval(20 * MINUTE) { @@ -155,8 +157,8 @@ uint32 AuctionBotBuyer::GetItemInformation(BuyerConfiguration& config) return count; } -// ahInfo can be NULL -bool AuctionBotBuyer::RollBuyChance(const BuyerItemInfo* ahInfo, const Item* item, const AuctionEntry* auction, uint32 /*bidPrice*/) +// ahInfo can be nullptr +bool AuctionBotBuyer::RollBuyChance(BuyerItemInfo const* ahInfo, Item const* item, AuctionEntry const* auction, uint32 /*bidPrice*/) { if (!auction->buyout) return false; @@ -194,8 +196,8 @@ bool AuctionBotBuyer::RollBuyChance(const BuyerItemInfo* ahInfo, const Item* ite return win; } -// ahInfo can be NULL -bool AuctionBotBuyer::RollBidChance(const BuyerItemInfo* ahInfo, const Item* item, const AuctionEntry* auction, uint32 bidPrice) +// ahInfo can be nullptr +bool AuctionBotBuyer::RollBidChance(BuyerItemInfo const* ahInfo, Item const* item, AuctionEntry const* auction, uint32 bidPrice) { float itemBidPrice = float(bidPrice / item->GetCount()); float itemPrice = float(item->GetTemplate()->SellPrice ? item->GetTemplate()->SellPrice : GetVendorPrice(item->GetTemplate()->Quality)); @@ -306,7 +308,7 @@ void AuctionBotBuyer::BuyAndBidItems(BuyerConfiguration& config) bidPrice = auction->startbid; } - const BuyerItemInfo* ahInfo = nullptr; + BuyerItemInfo const* ahInfo = nullptr; BuyerItemInfoMap::const_iterator sameItemItr = config.SameItemInfo.find(item->GetEntry()); if (sameItemItr != config.SameItemInfo.end()) ahInfo = &sameItemItr->second; @@ -392,7 +394,7 @@ void AuctionBotBuyer::BuyEntry(AuctionEntry* auction, AuctionHouseObject* auctio // Send mail to previous bidder if any if (auction->bidder && !sAuctionBotConfig->IsBotChar(auction->bidder)) - sAuctionMgr->SendAuctionOutbiddedMail(auction, auction->buyout, NULL, trans); + sAuctionMgr->SendAuctionOutbiddedMail(auction, auction->buyout, nullptr, trans); // Set bot as bidder and set new bid amount auction->bidder = sAuctionBotConfig->GetRandCharExclude(auction->owner); @@ -423,7 +425,7 @@ void AuctionBotBuyer::PlaceBidToEntry(AuctionEntry* auction, uint32 bidPrice) // Send mail to previous bidder if any if (auction->bidder && !sAuctionBotConfig->IsBotChar(auction->bidder)) - sAuctionMgr->SendAuctionOutbiddedMail(auction, bidPrice, NULL, trans); + sAuctionMgr->SendAuctionOutbiddedMail(auction, bidPrice, nullptr, trans); // Set bot as bidder and set new bid amount auction->bidder = sAuctionBotConfig->GetRandCharExclude(auction->owner); diff --git a/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.h b/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.h index c6616dcb096..630be136298 100644 --- a/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.h +++ b/src/server/game/AuctionHouseBot/AuctionHouseBotBuyer.h @@ -85,9 +85,9 @@ private: void LoadBuyerValues(BuyerConfiguration& config); - // ahInfo can be NULL - bool RollBuyChance(const BuyerItemInfo* ahInfo, const Item* item, const AuctionEntry* auction, uint32 bidPrice); - bool RollBidChance(const BuyerItemInfo* ahInfo, const Item* item, const AuctionEntry* auction, uint32 bidPrice); + // ahInfo can be nullptr + bool RollBuyChance(BuyerItemInfo const* ahInfo, Item const* item, AuctionEntry const* auction, uint32 bidPrice); + bool RollBidChance(BuyerItemInfo const* ahInfo, Item const* item, AuctionEntry const* auction, uint32 bidPrice); void PlaceBidToEntry(AuctionEntry* auction, uint32 bidPrice); void BuyEntry(AuctionEntry* auction, AuctionHouseObject* auctionHouse); void PrepareListOfEntry(BuyerConfiguration& config); diff --git a/src/server/game/AuctionHouseBot/AuctionHouseBotSeller.cpp b/src/server/game/AuctionHouseBot/AuctionHouseBotSeller.cpp index 149a3e77377..4aa5bf8f176 100644 --- a/src/server/game/AuctionHouseBot/AuctionHouseBotSeller.cpp +++ b/src/server/game/AuctionHouseBot/AuctionHouseBotSeller.cpp @@ -15,11 +15,17 @@ * with this program. If not, see . */ -#include "Log.h" -#include "DBCStores.h" -#include "ObjectMgr.h" -#include "AuctionHouseMgr.h" #include "AuctionHouseBotSeller.h" +#include "AuctionHouseMgr.h" +#include "Containers.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "DB2Stores.h" +#include "Item.h" +#include "Log.h" +#include "ObjectMgr.h" +#include "Random.h" +#include AuctionBotSeller::AuctionBotSeller() { @@ -59,16 +65,13 @@ bool AuctionBotSeller::Initialize() TC_LOG_DEBUG("ahbot", "Forced Exclusion %u items", (uint32)excludeItems.size()); TC_LOG_DEBUG("ahbot", "Loading npc vendor items for filter.."); - const CreatureTemplateContainer* creatures = sObjectMgr->GetCreatureTemplates(); + CreatureTemplateContainer const* creatures = sObjectMgr->GetCreatureTemplates(); std::set tempItems; for (CreatureTemplateContainer::const_iterator it = creatures->begin(); it != creatures->end(); ++it) - { - if (const VendorItemData* data = sObjectMgr->GetNpcVendorItemList(it->first)) - { - for (VendorItemList::const_iterator it2 = data->m_items.begin(); it2 != data->m_items.end(); ++it2) - tempItems.insert((*it2)->item); - } - } + if (VendorItemData const* data = sObjectMgr->GetNpcVendorItemList(it->first)) + for (VendorItem const& it2 : data->m_items) + tempItems.insert(it2.item); + for (std::set::const_iterator it = tempItems.begin(); it != tempItems.end(); ++it) npcItems.push_back(*it); @@ -110,7 +113,6 @@ bool AuctionBotSeller::Initialize() for (uint32 itemId = 0; itemId < sItemStore.GetNumRows(); ++itemId) { ItemTemplate const* prototype = sObjectMgr->GetItemTemplate(itemId); - if (!prototype) continue; @@ -988,13 +990,13 @@ void AuctionBotSeller::AddNewAuctions(SellerConfiguration& config) Item* item = Item::CreateItem(itemId, stackCount); if (!item) { - TC_LOG_ERROR("ahbot", "AHBot: Item::CreateItem() returned NULL for item %u (stack: %u)", itemId, stackCount); + TC_LOG_ERROR("ahbot", "AHBot: Item::CreateItem() returned nullptr for item %u (stack: %u)", itemId, stackCount); return; } // Update the just created item so that if it needs random properties it has them. // Ex: Notched Shortsword of Stamina will only generate as a Notched Shortsword without this. - if (int32 randomPropertyId = Item::GenerateItemRandomPropertyId(itemId)) + if (int32 randomPropertyId = GenerateItemRandomPropertyId(itemId)) item->SetItemRandomProperties(randomPropertyId); uint32 buyoutPrice; @@ -1033,7 +1035,7 @@ void AuctionBotSeller::AddNewAuctions(SellerConfiguration& config) auctionEntry->bid = 0; auctionEntry->deposit = sAuctionMgr->GetAuctionDeposit(ahEntry, etime, item, stackCount); auctionEntry->auctionHouseEntry = ahEntry; - auctionEntry->expire_time = time(NULL) + urand(config.GetMinTime(), config.GetMaxTime()) * HOUR; + auctionEntry->expire_time = time(nullptr) + urand(config.GetMinTime(), config.GetMaxTime()) * HOUR; item->SaveToDB(trans); sAuctionMgr->AddAItem(item); diff --git a/src/server/game/Battlefield/Battlefield.cpp b/src/server/game/Battlefield/Battlefield.cpp index c93b72804d2..a5e3592cff3 100644 --- a/src/server/game/Battlefield/Battlefield.cpp +++ b/src/server/game/Battlefield/Battlefield.cpp @@ -20,15 +20,19 @@ #include "Battleground.h" #include "CellImpl.h" #include "CreatureTextMgr.h" +#include "DBCStores.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "Group.h" #include "GroupMgr.h" +#include "Log.h" #include "Map.h" #include "MapManager.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "WorldPacket.h" +#include "WorldSession.h" +#include Battlefield::Battlefield() { @@ -562,7 +566,7 @@ BfGraveyard* Battlefield::GetGraveyardById(uint32 id) const return nullptr; } -WorldSafeLocsEntry const* Battlefield::GetClosestGraveYard(Player* player) +WorldSafeLocsEntry const* Battlefield::GetClosestGraveyard(Player* player) { BfGraveyard* closestGY = nullptr; float maxdist = -1; @@ -737,7 +741,7 @@ void BfGraveyard::RelocateDeadPlayers() player->TeleportTo(player->GetMapId(), closestGrave->x, closestGrave->y, closestGrave->z, player->GetOrientation()); else { - closestGrave = m_Bf->GetClosestGraveYard(player); + closestGrave = m_Bf->GetClosestGraveyard(player); if (closestGrave) player->TeleportTo(player->GetMapId(), closestGrave->x, closestGrave->y, closestGrave->z, player->GetOrientation()); } @@ -793,7 +797,7 @@ Creature* Battlefield::SpawnCreature(uint32 entry, Position const& pos) } // Method for spawning gameobject on map -GameObject* Battlefield::SpawnGameObject(uint32 entry, Position const& pos, G3D::Quat const& rot) +GameObject* Battlefield::SpawnGameObject(uint32 entry, Position const& pos, QuaternionData const& rot) { // Get map object Map* map = sMapMgr->CreateBaseMap(m_MapId); diff --git a/src/server/game/Battlefield/Battlefield.h b/src/server/game/Battlefield/Battlefield.h index b04d6e28377..33072e3f7a1 100644 --- a/src/server/game/Battlefield/Battlefield.h +++ b/src/server/game/Battlefield/Battlefield.h @@ -18,8 +18,10 @@ #ifndef BATTLEFIELD_H_ #define BATTLEFIELD_H_ +#include "Position.h" #include "SharedDefines.h" #include "ZoneScript.h" +#include enum BattlefieldTypes { @@ -64,14 +66,17 @@ enum BattlefieldTimers }; // some class predefs -class Player; -class GameObject; -class WorldPacket; -class Creature; -class Unit; - class Battlefield; class BfGraveyard; +class Creature; +class GameObject; +class Group; +class Map; +class Player; +class Unit; +class WorldPacket; +struct QuaternionData; +struct WorldSafeLocsEntry; typedef std::vector GraveyardVect; typedef std::map PlayerTimerMap; @@ -284,7 +289,7 @@ class TC_GAME_API Battlefield : public ZoneScript // Graveyard methods // Find which graveyard the player must be teleported to to be resurrected by spiritguide - WorldSafeLocsEntry const* GetClosestGraveYard(Player* player); + WorldSafeLocsEntry const* GetClosestGraveyard(Player* player); virtual void AddPlayerToResurrectQueue(ObjectGuid npc_guid, ObjectGuid player_guid); void RemovePlayerFromResurrectQueue(ObjectGuid player_guid); @@ -293,7 +298,7 @@ class TC_GAME_API Battlefield : public ZoneScript // Misc methods Creature* SpawnCreature(uint32 entry, Position const& pos); - GameObject* SpawnGameObject(uint32 entry, Position const& pos, G3D::Quat const& rot); + GameObject* SpawnGameObject(uint32 entry, Position const& pos, QuaternionData const& rot); Creature* GetCreature(ObjectGuid guid); GameObject* GetGameObject(ObjectGuid guid); @@ -419,7 +424,7 @@ class TC_GAME_API Battlefield : public ZoneScript Battlefield::BfCapturePointMap::const_iterator itr = m_capturePoints.find(lowguid); if (itr != m_capturePoints.end()) return itr->second; - return NULL; + return nullptr; } void RegisterZone(uint32 zoneid); diff --git a/src/server/game/Battlefield/BattlefieldMgr.cpp b/src/server/game/Battlefield/BattlefieldMgr.cpp index 88564ed12c5..fcab7d67d13 100644 --- a/src/server/game/Battlefield/BattlefieldMgr.cpp +++ b/src/server/game/Battlefield/BattlefieldMgr.cpp @@ -18,6 +18,7 @@ #include "BattlefieldMgr.h" #include "BattlefieldWG.h" #include "BattlefieldTB.h" +#include "Log.h" #include "Player.h" BattlefieldMgr::BattlefieldMgr() @@ -132,7 +133,7 @@ Battlefield* BattlefieldMgr::GetBattlefieldByGUID(ObjectGuid guid) if ((*itr)->GetGUID() == guid) return *itr; - return NULL; + return nullptr; } ZoneScript* BattlefieldMgr::GetZoneScript(uint32 zoneId) diff --git a/src/server/game/Battlefield/Zones/BattlefieldTB.cpp b/src/server/game/Battlefield/Zones/BattlefieldTB.cpp index a2f2d772398..321fa2bddd9 100644 --- a/src/server/game/Battlefield/Zones/BattlefieldTB.cpp +++ b/src/server/game/Battlefield/Zones/BattlefieldTB.cpp @@ -24,16 +24,14 @@ // - Check and script achievements #include "BattlefieldTB.h" -#include "AchievementMgr.h" -#include "CreatureTextMgr.h" #include "Battleground.h" +#include "Creature.h" +#include "GameObject.h" #include "MapManager.h" -#include "ObjectMgr.h" -#include "Opcodes.h" +#include "ObjectAccessor.h" #include "Player.h" -#include "SpellAuras.h" -#include "TemporarySummon.h" -#include "WorldSession.h" +#include "Random.h" +#include "World.h" const uint32 TBFactions[BG_TEAMS_COUNT] = { 1610, 1732 }; @@ -144,7 +142,7 @@ uint32 const RandomQuestgivers[BG_TEAMS_COUNT][CELLBLOCK_MAX] = struct TBCapturePointSpawnData { Position pos; - G3D::Quat rot; + QuaternionData rot; TBCapturePointId id; uint32 entryFlagPole[2]; uint32 wsControlled[2]; @@ -164,7 +162,7 @@ TBCapturePointSpawnData const TBCapturePoints[TB_BASE_COUNT] = struct TBTowerInfo { Position pos; - G3D::Quat rot; + QuaternionData rot; uint32 entry; uint32 textDamaged; uint32 textDestroyed; @@ -196,7 +194,7 @@ uint32 const TBBannerEntry[BG_TEAMS_COUNT] = { GO_BARADINS_WARDEN_BANNER, GO_HEL struct TBBannerData { Position pos; - G3D::Quat rot; + QuaternionData rot; }; uint8 const TB_BANNER_MAX = 23; @@ -232,7 +230,7 @@ uint32 const TBPortalEntry[BG_TEAMS_COUNT] = { TB_PORTAL_ALLIANCE, TB_PORTAL_HOR struct TBPortalData { Position pos; - G3D::Quat rot; + QuaternionData rot; }; uint8 const TB_PORTAL_MAX = 2; @@ -571,8 +569,8 @@ void BattlefieldTB::FillInitialWorldStates(WorldPacket& data) data << uint32(TB_WS_ALLIANCE_CONTROLS_SHOW) << int32(!IsWarTime() && GetDefenderTeam() == TEAM_ALLIANCE ? 1 : 0); data << uint32(TB_WS_HORDE_CONTROLS_SHOW) << int32(!IsWarTime() && GetDefenderTeam() == TEAM_HORDE ? 1 : 0); - data << uint32(TB_WS_TIME_BATTLE_END) << int32(IsWarTime() ? time(NULL) + (m_Timer / 1000) : 0); - data << uint32(TB_WS_TIME_NEXT_BATTLE) << int32(!IsWarTime() ? time(NULL) + (m_Timer / 1000) : 0); + data << uint32(TB_WS_TIME_BATTLE_END) << int32(IsWarTime() ? time(nullptr) + (m_Timer / 1000) : 0); + data << uint32(TB_WS_TIME_NEXT_BATTLE) << int32(!IsWarTime() ? time(nullptr) + (m_Timer / 1000) : 0); // Not sure if TB //packet.Worldstates.emplace_back(uint32(TB_WS_65_UNKNOWN), int32(0)); @@ -970,7 +968,7 @@ void BattlefieldTB::TowerDestroyed(TBTowerId tbTowerId) // Add 5 minute bonus time m_Timer += m_BonusTime; - SendUpdateWorldState(TB_WS_TIME_BATTLE_END, uint32(time(NULL) + (m_Timer / 1000))); + SendUpdateWorldState(TB_WS_TIME_BATTLE_END, uint32(time(nullptr) + (m_Timer / 1000))); SendWarning(TBTowers[tbTowerId].textDamaged); @@ -1092,5 +1090,5 @@ void TolBaradCapturePoint::ChangeTeam(TeamId /*oldTeam*/) } // Update counter - m_Bf->ProcessEvent(NULL, EVENT_COUNT_CAPTURED_BASE); + m_Bf->ProcessEvent(nullptr, EVENT_COUNT_CAPTURED_BASE); } diff --git a/src/server/game/Battlefield/Zones/BattlefieldWG.cpp b/src/server/game/Battlefield/Zones/BattlefieldWG.cpp index b7ad251c0ae..8fcd2705f07 100644 --- a/src/server/game/Battlefield/Zones/BattlefieldWG.cpp +++ b/src/server/game/Battlefield/Zones/BattlefieldWG.cpp @@ -21,14 +21,19 @@ #include "BattlefieldWG.h" #include "AchievementMgr.h" -#include "CreatureTextMgr.h" #include "Battleground.h" +#include "CreatureTextMgr.h" +#include "GameObject.h" +#include "Log.h" #include "MapManager.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Opcodes.h" #include "Player.h" +#include "Random.h" #include "SpellAuras.h" #include "TemporarySummon.h" +#include "World.h" #include "WorldSession.h" struct BfWGCoordGY @@ -40,7 +45,7 @@ struct BfWGCoordGY }; // 7 in sql, 7 in header -BfWGCoordGY const WGGraveYard[BATTLEFIELD_WG_GRAVEYARD_MAX] = +BfWGCoordGY const WGGraveyard[BATTLEFIELD_WG_GRAVEYARD_MAX] = { { { 5104.750f, 2300.940f, 368.579f, 0.733038f }, 1329, BATTLEFIELD_WG_GOSSIPTEXT_GY_NE, TEAM_NEUTRAL }, { { 5099.120f, 3466.036f, 368.484f, 5.317802f }, 1330, BATTLEFIELD_WG_GOSSIPTEXT_GY_NW, TEAM_NEUTRAL }, @@ -57,7 +62,7 @@ uint32 const WintergraspFaction[] = { FACTION_ALLIANCE_GENERIC_WG, FACTION_ Position const WintergraspStalkerPos = { 4948.985f, 2937.789f, 550.5172f, 1.815142f }; Position const WintergraspRelicPos = { 5440.379f, 2840.493f, 430.2816f, -1.832595f }; -G3D::Quat const WintergraspRelicRot = { 0.f, 0.f, -0.7933531f, 0.6087617f }; +QuaternionData const WintergraspRelicRot = { 0.f, 0.f, -0.7933531f, 0.6087617f }; uint8 const WG_MAX_OBJ = 32; uint8 const WG_MAX_TURRET = 15; @@ -74,7 +79,7 @@ struct WintergraspBuildingSpawnData uint32 entry; uint32 WorldState; Position pos; - G3D::Quat rot; + QuaternionData rot; WintergraspGameObjectBuildingType type; }; @@ -177,7 +182,7 @@ struct WintergraspObjectPositionData struct WintergraspGameObjectData { Position Pos; - G3D::Quat Rot; + QuaternionData Rot; uint32 HordeEntry; uint32 AllianceEntry; }; @@ -431,7 +436,7 @@ bool BattlefieldWG::SetupBattlefield() m_saveTimer = 60000; - // Init GraveYards + // Init Graveyards SetGraveyardNumber(BATTLEFIELD_WG_GRAVEYARD_MAX); // Load from db @@ -463,12 +468,12 @@ bool BattlefieldWG::SetupBattlefield() BfGraveyardWG* graveyard = new BfGraveyardWG(this); // When between games, the graveyard is controlled by the defending team - if (WGGraveYard[i].StartControl == TEAM_NEUTRAL) - graveyard->Initialize(m_DefenderTeam, WGGraveYard[i].GraveyardID); + if (WGGraveyard[i].StartControl == TEAM_NEUTRAL) + graveyard->Initialize(m_DefenderTeam, WGGraveyard[i].GraveyardID); else - graveyard->Initialize(WGGraveYard[i].StartControl, WGGraveYard[i].GraveyardID); + graveyard->Initialize(WGGraveyard[i].StartControl, WGGraveyard[i].GraveyardID); - graveyard->SetTextId(WGGraveYard[i].TextID); + graveyard->SetTextId(WGGraveyard[i].TextID); m_GraveyardList[i] = graveyard; } diff --git a/src/server/game/Battlegrounds/Arena.cpp b/src/server/game/Battlegrounds/Arena.cpp index 40f345806e7..daf5ac2556a 100644 --- a/src/server/game/Battlegrounds/Arena.cpp +++ b/src/server/game/Battlegrounds/Arena.cpp @@ -20,11 +20,96 @@ #include "ArenaTeamMgr.h" #include "GuildMgr.h" #include "Guild.h" +#include "Log.h" +#include "Map.h" #include "ObjectAccessor.h" #include "Player.h" #include "World.h" #include "WorldSession.h" +void ArenaScore::AppendToPacket(WorldPacket& data, ByteBuffer& content) +{ + uint32 primaryTree = 0; + if (Player* player = ObjectAccessor::FindPlayer(PlayerGuid)) + primaryTree = player->GetPrimaryTalentTree(player->GetActiveSpec()); + + data.WriteBit(0); // Unk 1 + data.WriteBit(0); // Unk 2 + data.WriteBit(PlayerGuid[2]); + data.WriteBit(/*!IsArena*/ 0); // IsArena + data.WriteBit(0); // Unk 4 + data.WriteBit(0); // Unk 5 + data.WriteBit(0); // Unk 6 + data.WriteBit(PlayerGuid[3]); + data.WriteBit(PlayerGuid[0]); + data.WriteBit(PlayerGuid[5]); + data.WriteBit(PlayerGuid[1]); + data.WriteBit(PlayerGuid[6]); + data.WriteBit(TeamId); + data.WriteBit(PlayerGuid[7]); + + content << uint32(HealingDone); // healing done + content << uint32(DamageDone); // damage done + + content.WriteByteSeq(PlayerGuid[4]); + content << uint32(KillingBlows); + + //if (unk5) + // content << int32(RatingChange); // RatingChange + + content.WriteByteSeq(PlayerGuid[5]); + + //if (unk 6) + // content << uint32(); + + //if (unk 2) + // content << uint32(); + + content.WriteByteSeq(PlayerGuid[1]); + content.WriteByteSeq(PlayerGuid[6]); + + content << int32(primaryTree); + + BuildObjectivesBlock(data, content); + + data.WriteBit(PlayerGuid[4]); + + content.WriteByteSeq(PlayerGuid[0]); + content.WriteByteSeq(PlayerGuid[3]); + + //if (unk 4) + // content << uint32() unk + + content.WriteByteSeq(PlayerGuid[7]); + content.WriteByteSeq(PlayerGuid[2]); +} + +void ArenaScore::BuildObjectivesBlock(WorldPacket& data, ByteBuffer& /*content*/) +{ + data.WriteBits(0, 24); // Objectives Count +} + +void ArenaTeamScore::BuildRatingInfoBlock(WorldPacket& data) +{ + uint32 ratingLost = std::abs(std::min(RatingChange, 0)); + uint32 ratingWon = std::max(RatingChange, 0); + + // should be old rating, new rating, and client will calculate rating change itself + data << uint32(MatchmakerRating); + data << uint32(ratingLost); + data << uint32(ratingWon); +} + +void ArenaTeamScore::BuildTeamInfoLengthBlock(WorldPacket& data) +{ + data.WriteBits(TeamName.length(), 8); +} + +void ArenaTeamScore::BuildTeamInfoBlock(WorldPacket& data) +{ + data.WriteString(TeamName); +} + Arena::Arena() { StartDelayTimes[BG_STARTING_EVENT_FIRST] = BG_START_DELAY_1M; @@ -243,7 +328,7 @@ void Arena::EndBattleground(uint32 winner) guildAwarded = true; if (uint32 guildId = GetBgMap()->GetOwnerGuildId(player->GetBGTeam())) if (Guild* guild = sGuildMgr->GetGuildById(guildId)) - guild->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA, std::max(winnerArenaTeam->GetRating(), 1), 0, 0, NULL, player); + guild->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA, std::max(winnerArenaTeam->GetRating(), 1), 0, 0, nullptr, player); } winnerArenaTeam->MemberWon(player, loserMatchmakerRating, winnerMatchmakerChange); diff --git a/src/server/game/Battlegrounds/ArenaScore.h b/src/server/game/Battlegrounds/ArenaScore.h index 805b41e1ef2..b10ecd5eeee 100644 --- a/src/server/game/Battlegrounds/ArenaScore.h +++ b/src/server/game/Battlegrounds/ArenaScore.h @@ -19,9 +19,7 @@ #define TRINITY_ARENA_SCORE_H #include "BattlegroundScore.h" -#include "SharedDefines.h" -#include "Player.h" -#include "ObjectAccessor.h" +#include struct TC_GAME_API ArenaScore : public BattlegroundScore { @@ -30,67 +28,8 @@ struct TC_GAME_API ArenaScore : public BattlegroundScore protected: ArenaScore(ObjectGuid playerGuid, uint32 team) : BattlegroundScore(playerGuid, team), TeamId(team == ALLIANCE ? BG_TEAM_ALLIANCE : BG_TEAM_HORDE) { } - void AppendToPacket(WorldPacket& data, ByteBuffer& content) final override - { - uint32 primaryTree = 0; - if (Player* player = ObjectAccessor::FindPlayer(PlayerGuid)) - primaryTree = player->GetPrimaryTalentTree(player->GetActiveSpec()); - - data.WriteBit(0); // Unk 1 - data.WriteBit(0); // Unk 2 - data.WriteBit(PlayerGuid[2]); - data.WriteBit(/*!IsArena*/ 0); // IsArena - data.WriteBit(0); // Unk 4 - data.WriteBit(0); // Unk 5 - data.WriteBit(0); // Unk 6 - data.WriteBit(PlayerGuid[3]); - data.WriteBit(PlayerGuid[0]); - data.WriteBit(PlayerGuid[5]); - data.WriteBit(PlayerGuid[1]); - data.WriteBit(PlayerGuid[6]); - data.WriteBit(TeamId); - data.WriteBit(PlayerGuid[7]); - - content << uint32(HealingDone); // healing done - content << uint32(DamageDone); // damage done - - content.WriteByteSeq(PlayerGuid[4]); - content << uint32(KillingBlows); - - //if (unk5) - // content << int32(RatingChange); // RatingChange - - content.WriteByteSeq(PlayerGuid[5]); - - //if (unk 6) - // content << uint32(); - - //if (unk 2) - // content << uint32(); - - content.WriteByteSeq(PlayerGuid[1]); - content.WriteByteSeq(PlayerGuid[6]); - - content << int32(primaryTree); - - BuildObjectivesBlock(data, content); - - data.WriteBit(PlayerGuid[4]); - - content.WriteByteSeq(PlayerGuid[0]); - content.WriteByteSeq(PlayerGuid[3]); - - //if (unk 4) - // content << uint32() unk - - content.WriteByteSeq(PlayerGuid[7]); - content.WriteByteSeq(PlayerGuid[2]); - } - - void BuildObjectivesBlock(WorldPacket& data, ByteBuffer& /*content*/) final override - { - data.WriteBits(0, 24); // Objectives Count - } + void AppendToPacket(WorldPacket& data, ByteBuffer& content) final override; + void BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) final override; // For Logging purpose std::string ToString() const override @@ -127,26 +66,9 @@ struct TC_GAME_API ArenaTeamScore TeamName = teamName; } - void BuildRatingInfoBlock(WorldPacket& data) - { - uint32 ratingLost = std::abs(std::min(RatingChange, 0)); - uint32 ratingWon = std::max(RatingChange, 0); - - // should be old rating, new rating, and client will calculate rating change itself - data << uint32(MatchmakerRating); - data << uint32(ratingLost); - data << uint32(ratingWon); - } - - void BuildTeamInfoLengthBlock(WorldPacket& data) - { - data.WriteBits(TeamName.length(), 8); - } - - void BuildTeamInfoBlock(WorldPacket& data) - { - data.WriteString(TeamName); - } + void BuildRatingInfoBlock(WorldPacket& data); + void BuildTeamInfoLengthBlock(WorldPacket& data); + void BuildTeamInfoBlock(WorldPacket& data); int32 RatingChange; uint32 MatchmakerRating; diff --git a/src/server/game/Battlegrounds/ArenaTeam.cpp b/src/server/game/Battlegrounds/ArenaTeam.cpp index bd8141bed42..27e64a47b49 100644 --- a/src/server/game/Battlegrounds/ArenaTeam.cpp +++ b/src/server/game/Battlegrounds/ArenaTeam.cpp @@ -16,16 +16,19 @@ * with this program. If not, see . */ +#include "ArenaTeam.h" +#include "ArenaTeamMgr.h" +#include "CharacterCache.h" +#include "DatabaseEnv.h" +#include "Group.h" +#include "Log.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Player.h" -#include "WorldPacket.h" -#include "ArenaTeam.h" #include "World.h" -#include "Group.h" -#include "ArenaTeamMgr.h" +#include "WorldPacket.h" #include "WorldSession.h" -#include "Opcodes.h" -#include "CharacterCache.h" ArenaTeam::ArenaTeam() : TeamId(0), Type(0), TeamName(), CaptainGuid(), BackgroundColor(0), EmblemStyle(0), EmblemColor(0), @@ -397,7 +400,7 @@ void ArenaTeam::Disband() void ArenaTeam::Roster(WorldSession* session) { - Player* player = NULL; + Player* player = nullptr; uint8 unk308 = 0; @@ -514,7 +517,7 @@ void ArenaTeam::BroadcastPacket(WorldPacket* packet) { for (MemberList::const_iterator itr = Members.begin(); itr != Members.end(); ++itr) if (Player* player = ObjectAccessor::FindConnectedPlayer(itr->Guid)) - player->GetSession()->SendPacket(packet); + player->SendDirectMessage(packet); } void ArenaTeam::BroadcastEvent(ArenaTeamEvents event, ObjectGuid guid, uint8 strCount, std::string const& str1, std::string const& str2, std::string const& str3) @@ -795,7 +798,7 @@ void ArenaTeam::OfflineMemberLost(ObjectGuid guid, uint32 againstMatchmakerRatin { // update personal rating int32 mod = GetRatingMod(itr->PersonalRating, againstMatchmakerRating, false); - itr->ModifyPersonalRating(NULL, mod, GetType()); + itr->ModifyPersonalRating(nullptr, mod, GetType()); // update matchmaker rating itr->ModifyMatchmakerRating(MatchmakerRatingChange, GetSlot()); @@ -904,7 +907,7 @@ ArenaTeamMember* ArenaTeam::GetMember(const std::string& name) if (itr->Name == name) return &(*itr); - return NULL; + return nullptr; } ArenaTeamMember* ArenaTeam::GetMember(ObjectGuid guid) @@ -913,5 +916,5 @@ ArenaTeamMember* ArenaTeam::GetMember(ObjectGuid guid) if (itr->Guid == guid) return &(*itr); - return NULL; + return nullptr; } diff --git a/src/server/game/Battlegrounds/ArenaTeam.h b/src/server/game/Battlegrounds/ArenaTeam.h index efc9109cef4..08285f5d424 100644 --- a/src/server/game/Battlegrounds/ArenaTeam.h +++ b/src/server/game/Battlegrounds/ArenaTeam.h @@ -128,7 +128,7 @@ class TC_GAME_API ArenaTeam static uint8 GetTypeBySlot(uint8 slot); ObjectGuid GetCaptain() const { return CaptainGuid; } std::string const& GetName() const { return TeamName; } - const ArenaTeamStats& GetStats() const { return Stats; } + ArenaTeamStats const& GetStats() const { return Stats; } uint32 GetRating() const { return Stats.Rating; } uint32 GetAverageMMR(Group* group) const; diff --git a/src/server/game/Battlegrounds/ArenaTeamMgr.cpp b/src/server/game/Battlegrounds/ArenaTeamMgr.cpp index 349b00cd487..785874c6edd 100644 --- a/src/server/game/Battlegrounds/ArenaTeamMgr.cpp +++ b/src/server/game/Battlegrounds/ArenaTeamMgr.cpp @@ -48,7 +48,7 @@ ArenaTeam* ArenaTeamMgr::GetArenaTeamById(uint32 arenaTeamId) const if (itr != ArenaTeamStore.end()) return itr->second; - return NULL; + return nullptr; } ArenaTeam* ArenaTeamMgr::GetArenaTeamByName(const std::string& arenaTeamName) const @@ -62,7 +62,7 @@ ArenaTeam* ArenaTeamMgr::GetArenaTeamByName(const std::string& arenaTeamName) co if (search == teamName) return itr->second; } - return NULL; + return nullptr; } ArenaTeam* ArenaTeamMgr::GetArenaTeamByCaptain(ObjectGuid guid) const @@ -71,7 +71,7 @@ ArenaTeam* ArenaTeamMgr::GetArenaTeamByCaptain(ObjectGuid guid) const if (itr->second->GetCaptain() == guid) return itr->second; - return NULL; + return nullptr; } void ArenaTeamMgr::AddArenaTeam(ArenaTeam* arenaTeam) @@ -127,7 +127,7 @@ void ArenaTeamMgr::LoadArenaTeams() if (!newArenaTeam->LoadArenaTeamFromDB(result) || !newArenaTeam->LoadMembersFromDB(result2)) { - newArenaTeam->Disband(NULL); + newArenaTeam->Disband(nullptr); delete newArenaTeam; continue; } diff --git a/src/server/game/Battlegrounds/ArenaTeamMgr.h b/src/server/game/Battlegrounds/ArenaTeamMgr.h index 052b8f5e511..bd32044e295 100644 --- a/src/server/game/Battlegrounds/ArenaTeamMgr.h +++ b/src/server/game/Battlegrounds/ArenaTeamMgr.h @@ -19,6 +19,7 @@ #define _ARENATEAMMGR_H #include "ArenaTeam.h" +#include class TC_GAME_API ArenaTeamMgr { diff --git a/src/server/game/Battlegrounds/Battleground.cpp b/src/server/game/Battlegrounds/Battleground.cpp index e98f94629f4..e203a260210 100644 --- a/src/server/game/Battlegrounds/Battleground.cpp +++ b/src/server/game/Battlegrounds/Battleground.cpp @@ -16,27 +16,96 @@ * with this program. If not, see . */ -#include "ArenaScore.h" #include "Battleground.h" +#include "ArenaScore.h" #include "BattlegroundMgr.h" #include "BattlegroundScore.h" +#include "Chat.h" +#include "ChatTextBuilder.h" #include "Creature.h" #include "CreatureTextMgr.h" -#include "ChatTextBuilder.h" +#include "DatabaseEnv.h" #include "Formulas.h" +#include "GameTime.h" #include "GridNotifiersImpl.h" #include "Group.h" -#include "GuildMgr.h" #include "Guild.h" +#include "GuildMgr.h" #include "Object.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Player.h" #include "ReputationMgr.h" #include "SpellAuras.h" +#include "TemporarySummon.h" +#include "Transport.h" #include "Util.h" #include "WorldPacket.h" -#include "Transport.h" -#include "GameTime.h" +#include + +void BattlegroundScore::AppendToPacket(WorldPacket& data, ByteBuffer& content) +{ + uint32 primaryTree = 0; + if (Player* player = ObjectAccessor::FindPlayer(PlayerGuid)) + primaryTree = player->GetPrimaryTalentTree(player->GetActiveSpec()); + + data.WriteBit(0); // Unk 1 + data.WriteBit(0); // Unk 2 + data.WriteBit(PlayerGuid[2]); + data.WriteBit(/*!IsArena*/ 1); // IsArena + data.WriteBit(0); // Unk 4 + data.WriteBit(0); // Unk 5 + data.WriteBit(0); // Unk 6 + data.WriteBit(PlayerGuid[3]); + data.WriteBit(PlayerGuid[0]); + data.WriteBit(PlayerGuid[5]); + data.WriteBit(PlayerGuid[1]); + data.WriteBit(PlayerGuid[6]); + data.WriteBit(TeamId); + data.WriteBit(PlayerGuid[7]); + + content << uint32(HealingDone); // healing done + content << uint32(DamageDone); // damage done + + //if (!IsArena) + //{ + content << uint32(BonusHonor / 100); + content << uint32(Deaths); + content << uint32(HonorableKills); + //} + + content.WriteByteSeq(PlayerGuid[4]); + content << uint32(KillingBlows); + + //if (unk 5) + // data << uint32() unk + + content.WriteByteSeq(PlayerGuid[5]); + + //if (unk 6) + // data << uint32() unk + + //if (unk 2) + // data << uint32() unk + + content.WriteByteSeq(PlayerGuid[1]); + content.WriteByteSeq(PlayerGuid[6]); + + content << int32(primaryTree); + + BuildObjectivesBlock(data, content); + + data.WriteBit(PlayerGuid[4]); + + content.WriteByteSeq(PlayerGuid[0]); + content.WriteByteSeq(PlayerGuid[3]); + + //if (unk 4) + // data << uint32() unk + + content.WriteByteSeq(PlayerGuid[7]); + content.WriteByteSeq(PlayerGuid[2]); +} template void Battleground::BroadcastWorker(Do& _do) @@ -81,7 +150,7 @@ Battleground::Battleground() m_MinPlayers = 0; m_MapId = 0; - m_Map = NULL; + m_Map = nullptr; m_StartMaxDist = 0.0f; ScriptId = 0; @@ -91,8 +160,8 @@ Battleground::Battleground() m_ArenaTeamMMR[TEAM_ALLIANCE] = 0; m_ArenaTeamMMR[TEAM_HORDE] = 0; - m_BgRaids[TEAM_ALLIANCE] = NULL; - m_BgRaids[TEAM_HORDE] = NULL; + m_BgRaids[TEAM_ALLIANCE] = nullptr; + m_BgRaids[TEAM_HORDE] = nullptr; m_PlayersCount[TEAM_ALLIANCE] = 0; m_PlayersCount[TEAM_HORDE] = 0; @@ -134,8 +203,8 @@ Battleground::~Battleground() { m_Map->SetUnload(); //unlink to prevent crash, always unlink all pointer reference before destruction - m_Map->SetBG(NULL); - m_Map = NULL; + m_Map->SetBG(nullptr); + m_Map = nullptr; } // remove from bg free slot queue RemoveFromBGFreeSlotQueue(); @@ -283,7 +352,7 @@ inline void Battleground::_ProcessResurrect(uint32 diff) { for (std::map::iterator itr = m_ReviveQueue.begin(); itr != m_ReviveQueue.end(); ++itr) { - Creature* sh = NULL; + Creature* sh = nullptr; for (GuidVector::const_iterator itr2 = (itr->second).begin(); itr2 != (itr->second).end(); ++itr2) { Player* player = ObjectAccessor::FindPlayer(*itr2); @@ -364,13 +433,13 @@ inline void Battleground::_ProcessProgress(uint32 diff) if (newtime > (MINUTE * IN_MILLISECONDS)) { if (newtime / (MINUTE * IN_MILLISECONDS) != m_PrematureCountDownTimer / (MINUTE * IN_MILLISECONDS)) - PSendMessageToAll(LANG_BATTLEGROUND_PREMATURE_FINISH_WARNING, CHAT_MSG_SYSTEM, NULL, (uint32)(m_PrematureCountDownTimer / (MINUTE * IN_MILLISECONDS))); + PSendMessageToAll(LANG_BATTLEGROUND_PREMATURE_FINISH_WARNING, CHAT_MSG_SYSTEM, nullptr, (uint32)(m_PrematureCountDownTimer / (MINUTE * IN_MILLISECONDS))); } else { //announce every 15 seconds if (newtime / (15 * IN_MILLISECONDS) != m_PrematureCountDownTimer / (15 * IN_MILLISECONDS)) - PSendMessageToAll(LANG_BATTLEGROUND_PREMATURE_FINISH_WARNING_SECS, CHAT_MSG_SYSTEM, NULL, (uint32)(m_PrematureCountDownTimer / IN_MILLISECONDS)); + PSendMessageToAll(LANG_BATTLEGROUND_PREMATURE_FINISH_WARNING_SECS, CHAT_MSG_SYSTEM, nullptr, (uint32)(m_PrematureCountDownTimer / IN_MILLISECONDS)); } m_PrematureCountDownTimer = newtime; } @@ -406,7 +475,7 @@ inline void Battleground::_ProcessJoin(uint32 diff) for (BattlegroundPlayerMap::const_iterator itr = GetPlayers().begin(); itr != GetPlayers().end(); ++itr) if (Player* player = ObjectAccessor::FindPlayer(itr->first)) - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); m_CountdownTimer = 0; } @@ -474,7 +543,7 @@ inline void Battleground::_ProcessJoin(uint32 diff) uint32 queueSlot = player->GetBattlegroundQueueIndex(bgQueueTypeId); sBattlegroundMgr->BuildBattlegroundStatusPacket(&status, this, player, queueSlot, STATUS_IN_PROGRESS, player->GetBattlegroundQueueJoinTime(m_TypeID), GetElapsedTime(), GetArenaType()); - player->GetSession()->SendPacket(&status); + player->SendDirectMessage(&status); // Correctly display EnemyUnitFrame player->SetByteValue(PLAYER_BYTES_3, 3, player->GetBGTeam()); @@ -542,7 +611,7 @@ inline void Battleground::_ProcessLeave(uint32 diff) Player* Battleground::_GetPlayer(ObjectGuid guid, bool offlineRemove, char const* context) const { - Player* player = NULL; + Player* player = nullptr; if (!offlineRemove) { // should this be ObjectAccessor::FindConnectedPlayer() to return players teleporting ? @@ -563,7 +632,7 @@ Player* Battleground::_GetPlayerForTeam(uint32 teamId, BattlegroundPlayerMap::co if (!team) team = player->GetTeam(); if (team != teamId) - player = NULL; + player = nullptr; } return player; } @@ -599,7 +668,7 @@ void Battleground::SendPacketToTeam(uint32 TeamID, WorldPacket* packet, Player* } } -void Battleground::SendChatMessage(Creature* source, uint8 textId, WorldObject* target /*= NULL*/) +void Battleground::SendChatMessage(Creature* source, uint8 textId, WorldObject* target /*= nullptr*/) { sCreatureTextMgr->SendChat(source, textId, target); } @@ -825,7 +894,7 @@ void Battleground::EndBattleground(uint32 winner) if (uint32 guildId = GetBgMap()->GetOwnerGuildId(player->GetBGTeam())) { if (Guild* guild = sGuildMgr->GetGuildById(guildId)) - guild->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_BG, 1, 0, 0, NULL, player); + guild->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_BG, 1, 0, 0, nullptr, player); } } } @@ -924,7 +993,7 @@ void Battleground::RemovePlayerAtLeave(ObjectGuid guid, bool Transport, bool Sen bgTypeId = BATTLEGROUND_AA; // set the bg type to all arenas (it will be used for queue refreshing) // unsummon current and summon old pet if there was one and there isn't a current pet - player->RemovePet(NULL, PET_SAVE_NOT_IN_SLOT); + player->RemovePet(nullptr, PET_SAVE_NOT_IN_SLOT); player->ResummonPetTemporaryUnSummonedIfAny(); } @@ -943,7 +1012,7 @@ void Battleground::RemovePlayerAtLeave(ObjectGuid guid, bool Transport, bool Sen if (Group* group = GetBgRaid(team)) { if (!group->RemoveMember(guid)) // group was disbanded - SetBgRaid(team, NULL); + SetBgRaid(team, nullptr); } DecreaseInvitedCount(team); //we should update battleground queue, but only if bg isn't ending @@ -1052,7 +1121,7 @@ void Battleground::AddPlayer(Player* player) uint32 queueSlot = player->GetBattlegroundQueueIndex(bgQueueTypeId); sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, this, player, queueSlot, STATUS_IN_PROGRESS, player->GetBattlegroundQueueJoinTime(m_TypeID), GetElapsedTime(), GetArenaType()); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); player->RemoveAurasByType(SPELL_AURA_MOUNTED); @@ -1080,7 +1149,7 @@ void Battleground::AddPlayer(Player* player) data << uint32(0); // unk data << uint32(countdownMaxForBGType - (GetElapsedTime() / 1000)); data << uint32(countdownMaxForBGType); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } } @@ -1322,7 +1391,7 @@ bool Battleground::UpdatePlayerScore(Player* player, uint32 type, uint32 value, return false; if (type == SCORE_BONUS_HONOR && doAddHonor && isBattleground()) - player->RewardHonor(NULL, 1, value); // RewardHonor calls UpdatePlayerScore with doAddHonor = false + player->RewardHonor(nullptr, 1, value); // RewardHonor calls UpdatePlayerScore with doAddHonor = false else itr->second->UpdateScore(type, value); @@ -1363,7 +1432,7 @@ void Battleground::RelocateDeadPlayers(ObjectGuid guideGuid) GuidVector& ghostList = m_ReviveQueue[guideGuid]; if (!ghostList.empty()) { - WorldSafeLocsEntry const* closestGrave = NULL; + WorldSafeLocsEntry const* closestGrave = nullptr; for (GuidVector::const_iterator itr = ghostList.begin(); itr != ghostList.end(); ++itr) { Player* player = ObjectAccessor::FindPlayer(*itr); @@ -1371,7 +1440,7 @@ void Battleground::RelocateDeadPlayers(ObjectGuid guideGuid) continue; if (!closestGrave) - closestGrave = GetClosestGraveYard(player); + closestGrave = GetClosestGraveyard(player); if (closestGrave) player->TeleportTo(GetMapId(), closestGrave->x, closestGrave->y, closestGrave->z, player->GetOrientation()); @@ -1389,14 +1458,14 @@ bool Battleground::AddObject(uint32 type, uint32 entry, float x, float y, float if (!map) return false; - G3D::Quat rot(rotation0, rotation1, rotation2, rotation3); + QuaternionData 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); + rot = QuaternionData::fromEulerAnglesZYX(o, 0.f, 0.f); } // Must be created this way, adding to godatamap would add it to the base map of the instance @@ -1531,7 +1600,7 @@ Creature* Battleground::AddCreature(uint32 entry, uint32 type, float x, float y, Map* map = FindBgMap(); if (!map) - return NULL; + return nullptr; if (transport) { @@ -1541,7 +1610,7 @@ Creature* Battleground::AddCreature(uint32 entry, uint32 type, float x, float y, return creature; } - return NULL; + return nullptr; } Creature* creature = new Creature(); @@ -1550,7 +1619,7 @@ Creature* Battleground::AddCreature(uint32 entry, uint32 type, float x, float y, TC_LOG_ERROR("bg.battleground", "Battleground::AddCreature: cannot create creature (entry: %u) for BG (map: %u, instance id: %u)!", entry, m_MapId, m_InstanceID); delete creature; - return NULL; + return nullptr; } creature->SetHomePosition(x, y, z, o); @@ -1561,13 +1630,13 @@ Creature* Battleground::AddCreature(uint32 entry, uint32 type, float x, float y, TC_LOG_ERROR("bg.battleground", "Battleground::AddCreature: creature template (entry: %u) does not exist for BG (map: %u, instance id: %u)!", entry, m_MapId, m_InstanceID); delete creature; - return NULL; + return nullptr; } if (!map->AddToMap(creature)) { delete creature; - return NULL; + return nullptr; } BgCreatures[type] = creature->GetGUID(); @@ -1829,15 +1898,15 @@ void Battleground::SetBgRaid(uint32 TeamID, Group* bg_raid) { Group*& old_raid = TeamID == ALLIANCE ? m_BgRaids[TEAM_ALLIANCE] : m_BgRaids[TEAM_HORDE]; if (old_raid) - old_raid->SetBattlegroundGroup(NULL); + old_raid->SetBattlegroundGroup(nullptr); if (bg_raid) bg_raid->SetBattlegroundGroup(this); old_raid = bg_raid; } -WorldSafeLocsEntry const* Battleground::GetClosestGraveYard(Player* player) +WorldSafeLocsEntry const* Battleground::GetClosestGraveyard(Player* player) { - return sObjectMgr->GetClosestGraveYard(*player, player->GetTeam(), player); + return sObjectMgr->GetClosestGraveyard(*player, player->GetTeam(), player); } void Battleground::StartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry) diff --git a/src/server/game/Battlegrounds/Battleground.h b/src/server/game/Battlegrounds/Battleground.h index d8daaf8050a..dd57323c948 100644 --- a/src/server/game/Battlegrounds/Battleground.h +++ b/src/server/game/Battlegrounds/Battleground.h @@ -20,23 +20,23 @@ #define __BATTLEGROUND_H #include "ArenaScore.h" -#include "Common.h" -#include "SharedDefines.h" #include "DBCEnums.h" -#include "WorldPacket.h" -#include "Object.h" -#include "GameObject.h" -#include "EventMap.h" +#include "ObjectGuid.h" +#include "Position.h" +#include "SharedDefines.h" +#include +class BattlegroundMap; class Creature; class GameObject; class Group; class Player; +class Transport; class Unit; class WorldObject; class WorldPacket; -class BattlegroundMap; +struct BattlegroundScore; struct PvPDifficultyEntry; struct WorldSafeLocsEntry; @@ -186,7 +186,7 @@ struct BattlegroundPlayer struct BattlegroundObjectInfo { - BattlegroundObjectInfo() : object(NULL), timer(0), spellid(0) { } + BattlegroundObjectInfo() : object(nullptr), timer(0), spellid(0) { } GameObject *object; int32 timer; @@ -257,7 +257,7 @@ class TC_GAME_API Battleground /* achievement req. */ virtual bool IsAllNodesControlledByTeam(uint32 /*team*/) const { return false; } void StartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry); - virtual bool CheckAchievementCriteriaMeet(uint32 /*criteriaId*/, Player const* /*player*/, Unit const* /*target*/ = NULL, uint32 /*miscvalue1*/ = 0); + virtual bool CheckAchievementCriteriaMeet(uint32 /*criteriaId*/, Player const* /*player*/, Unit const* /*target*/ = nullptr, uint32 /*miscvalue1*/ = 0); /* Battleground */ // Get methods: @@ -389,7 +389,7 @@ class TC_GAME_API Battleground void BlockMovement(Player* player); void SendWarningToAll(uint32 entry, ...); - void SendMessageToAll(uint32 entry, ChatMsg type, Player const* source = NULL); + void SendMessageToAll(uint32 entry, ChatMsg type, Player const* source = nullptr); void PSendMessageToAll(uint32 entry, ChatMsg type, Player const* source, ...); // Raid Group @@ -431,7 +431,7 @@ class TC_GAME_API Battleground virtual void EventPlayerClickedOnFlag(Player* /*player*/, GameObject* /*target_obj*/) { } void EventPlayerLoggedIn(Player* player); void EventPlayerLoggedOut(Player* player); - virtual void ProcessEvent(WorldObject* /*obj*/, uint32 /*eventId*/, WorldObject* /*invoker*/ = NULL) { } + virtual void ProcessEvent(WorldObject* /*obj*/, uint32 /*eventId*/, WorldObject* /*invoker*/ = nullptr) { } // this function can be used by spell to interact with the BG map virtual void DoAction(uint32 /*action*/, ObjectGuid /*var*/) { } @@ -439,7 +439,7 @@ class TC_GAME_API Battleground virtual void HandlePlayerResurrect(Player* /*player*/) { } // Death related - virtual WorldSafeLocsEntry const* GetClosestGraveYard(Player* player); + virtual WorldSafeLocsEntry const* GetClosestGraveyard(Player* player); virtual void AddPlayer(Player* player); // must be implemented in BG subclass @@ -457,8 +457,8 @@ class TC_GAME_API Battleground void SpawnBGObject(uint32 type, uint32 respawntime); virtual bool AddObject(uint32 type, uint32 entry, float x, float y, float z, float o, float rotation0, float rotation1, float rotation2, float rotation3, uint32 respawnTime = 0, GOState goState = GO_STATE_READY); bool AddObject(uint32 type, uint32 entry, Position const& pos, float rotation0, float rotation1, float rotation2, float rotation3, uint32 respawnTime = 0, GOState goState = GO_STATE_READY); - virtual Creature* AddCreature(uint32 entry, uint32 type, float x, float y, float z, float o, TeamId teamId = TEAM_NEUTRAL, uint32 respawntime = 0, Transport* transport = NULL); - Creature* AddCreature(uint32 entry, uint32 type, Position const& pos, TeamId teamId = TEAM_NEUTRAL, uint32 respawntime = 0, Transport* transport = NULL); + virtual Creature* AddCreature(uint32 entry, uint32 type, float x, float y, float z, float o, TeamId teamId = TEAM_NEUTRAL, uint32 respawntime = 0, Transport* transport = nullptr); + Creature* AddCreature(uint32 entry, uint32 type, Position const& pos, TeamId teamId = TEAM_NEUTRAL, uint32 respawntime = 0, Transport* transport = nullptr); bool DelCreature(uint32 type); bool DelObject(uint32 type); virtual bool AddSpiritGuide(uint32 type, float x, float y, float z, float o, TeamId teamId = TEAM_NEUTRAL); @@ -498,10 +498,10 @@ class TC_GAME_API Battleground void EndNow(); void PlayerAddedToBGCheckIfBGIsRunning(Player* player); - Player* _GetPlayer(ObjectGuid guid, bool offlineRemove, const char* context) const; - Player* _GetPlayer(BattlegroundPlayerMap::iterator itr, const char* context) { return _GetPlayer(itr->first, itr->second.OfflineRemoveTime != 0, context); } - Player* _GetPlayer(BattlegroundPlayerMap::const_iterator itr, const char* context) const { return _GetPlayer(itr->first, itr->second.OfflineRemoveTime != 0, context); } - Player* _GetPlayerForTeam(uint32 teamId, BattlegroundPlayerMap::const_iterator itr, const char* context) const; + Player* _GetPlayer(ObjectGuid guid, bool offlineRemove, char const* context) const; + Player* _GetPlayer(BattlegroundPlayerMap::iterator itr, char const* context) { return _GetPlayer(itr->first, itr->second.OfflineRemoveTime != 0, context); } + Player* _GetPlayer(BattlegroundPlayerMap::const_iterator itr, char const* context) const { return _GetPlayer(itr->first, itr->second.OfflineRemoveTime != 0, context); } + Player* _GetPlayerForTeam(uint32 teamId, BattlegroundPlayerMap::const_iterator itr, char const* context) const; void _ProcessOfflineQueue(); void _ProcessResurrect(uint32 diff); diff --git a/src/server/game/Battlegrounds/BattlegroundMgr.cpp b/src/server/game/Battlegrounds/BattlegroundMgr.cpp index 3087e7be708..eb5f0ca800e 100644 --- a/src/server/game/Battlegrounds/BattlegroundMgr.cpp +++ b/src/server/game/Battlegrounds/BattlegroundMgr.cpp @@ -16,12 +16,7 @@ * with this program. If not, see . */ -#include "Common.h" -#include "ObjectMgr.h" #include "ArenaTeamMgr.h" -#include "World.h" -#include "WorldPacket.h" - #include "BattlegroundMgr.h" #include "BattlegroundAV.h" #include "BattlegroundAB.h" @@ -36,16 +31,27 @@ #include "BattlegroundIC.h" #include "BattlegroundTP.h" #include "BattlegroundBFG.h" +#include "Common.h" +#include "Containers.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "DisableMgr.h" +#include "Formulas.h" +#include "GameEventMgr.h" #include "Language.h" #include "Map.h" #include "MapManager.h" -#include "Player.h" -#include "GameEventMgr.h" #include "SharedDefines.h" -#include "Formulas.h" -#include "DisableMgr.h" +#include "ObjectMgr.h" #include "Opcodes.h" +#include "Player.h" +#include "World.h" +#include "WorldPacket.h" + +bool BattlegroundTemplate::IsArena() const +{ + return BattlemasterEntry->type == MAP_ARENA; +} /*********************************************************/ /*** BATTLEGROUND MANAGER ***/ @@ -100,7 +106,7 @@ void BattlegroundMgr::Update(uint32 diff) bg->Update(diff); if (bg->ToBeDeleted()) { - itrDelete->second = NULL; + itrDelete->second = nullptr; bgs.erase(itrDelete); BattlegroundClientIdsContainer& clients = itr1->second.m_ClientBattlegroundIds[bg->GetBracketId()]; if (!clients.empty()) @@ -497,14 +503,14 @@ Battleground* BattlegroundMgr::GetBattlegroundThroughClientInstance(uint32 insta //SMSG_BATTLEFIELD_LIST we need to find the battleground with this clientinstance-id Battleground* bg = GetBattlegroundTemplate(bgTypeId); if (!bg) - return NULL; + return nullptr; if (bg->isArena()) return GetBattleground(instanceId, bgTypeId); BattlegroundDataContainer::const_iterator it = bgDataStore.find(bgTypeId); if (it == bgDataStore.end()) - return NULL; + return nullptr; for (BattlegroundContainer::const_iterator itr = it->second.m_Battlegrounds.begin(); itr != it->second.m_Battlegrounds.end(); ++itr) { @@ -512,13 +518,13 @@ Battleground* BattlegroundMgr::GetBattlegroundThroughClientInstance(uint32 insta return itr->second; } - return NULL; + return nullptr; } Battleground* BattlegroundMgr::GetBattleground(uint32 instanceId, BattlegroundTypeId bgTypeId) { if (!instanceId) - return NULL; + return nullptr; BattlegroundDataContainer::const_iterator begin, end; @@ -531,7 +537,7 @@ Battleground* BattlegroundMgr::GetBattleground(uint32 instanceId, BattlegroundTy { end = bgDataStore.find(bgTypeId); if (end == bgDataStore.end()) - return NULL; + return nullptr; begin = end++; } @@ -543,18 +549,18 @@ Battleground* BattlegroundMgr::GetBattleground(uint32 instanceId, BattlegroundTy return itr->second; } - return NULL; + return nullptr; } Battleground* BattlegroundMgr::GetBattlegroundTemplate(BattlegroundTypeId bgTypeId) { BattlegroundDataContainer::const_iterator itr = bgDataStore.find(bgTypeId); if (itr == bgDataStore.end()) - return NULL; + return nullptr; BattlegroundContainer const& bgs = itr->second.m_Battlegrounds; // map is sorted and we can be sure that lowest instance id has only BG template - return bgs.empty() ? NULL : bgs.begin()->second; + return bgs.empty() ? nullptr : bgs.begin()->second; } uint32 BattlegroundMgr::CreateClientVisibleInstanceId(BattlegroundTypeId bgTypeId, BattlegroundBracketId bracket_id) @@ -593,10 +599,10 @@ Battleground* BattlegroundMgr::CreateNewBattleground(BattlegroundTypeId original if (!bg_template) { TC_LOG_ERROR("bg.battleground", "Battleground: CreateNewBattleground - bg template not found for %u", bgTypeId); - return NULL; + return nullptr; } - Battleground* bg = NULL; + Battleground* bg = nullptr; // create a copy of the BG template switch (bgTypeId) { @@ -642,7 +648,7 @@ Battleground* BattlegroundMgr::CreateNewBattleground(BattlegroundTypeId original case BATTLEGROUND_RB: case BATTLEGROUND_AA: default: - return NULL; + return nullptr; } bool isRandom = bgTypeId != originalBgTypeId && !bg->isArena(); @@ -790,7 +796,7 @@ void BattlegroundMgr::LoadBattlegroundTemplates() BattlegroundTypeId bgTypeId = BattlegroundTypeId(fields[0].GetUInt32()); - if (DisableMgr::IsDisabledFor(DISABLE_TYPE_BATTLEGROUND, bgTypeId, NULL)) + if (DisableMgr::IsDisabledFor(DISABLE_TYPE_BATTLEGROUND, bgTypeId, nullptr)) continue; // can be overwrite by values from DB @@ -959,7 +965,7 @@ void BattlegroundMgr::SendAreaSpiritHealerQueryOpcode(Player* player, Battlegrou if (time_ == uint32(-1)) time_ = 0; data << guid << time_; - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } bool BattlegroundMgr::IsArenaType(BattlegroundTypeId bgTypeId) @@ -1214,9 +1220,11 @@ BattlegroundTypeId BattlegroundMgr::GetRandomBG(BattlegroundTypeId bgTypeId) { if (BattlegroundTemplate const* bgTemplate = GetBattlegroundTemplateByTypeId(bgTypeId)) { - uint32 weight = 0; BattlegroundSelectionWeightMap selectionWeights; - + std::vector ids; + ids.reserve(16); + std::vector weights; + weights.reserve(16); for (int32 mapId : bgTemplate->BattlemasterEntry->mapid) { if (mapId == -1) @@ -1224,28 +1232,12 @@ BattlegroundTypeId BattlegroundMgr::GetRandomBG(BattlegroundTypeId bgTypeId) if (BattlegroundTemplate const* bg = GetBattlegroundTemplateByMapId(mapId)) { - weight += bg->Weight; - selectionWeights[bg->Id] = bg->Weight; + ids.push_back(bg->Id); + weights.push_back(bg->Weight); } } - // there is only one bg to select - if (selectionWeights.size() == 1) - return selectionWeights.begin()->first; - - if (weight) - { - // Select a random value - uint32 selectedWeight = urand(0, weight - 1); - // Select the correct bg (if we have in DB A(10), B(20), C(10), D(15) --> [0---A---9|10---B---29|30---C---39|40---D---54]) - weight = 0; - for (auto it : selectionWeights) - { - weight += it.second; - if (selectedWeight < weight) - return it.first; - } - } + return *Trinity::Containers::SelectRandomWeightedContainerElement(ids, weights); } return BATTLEGROUND_TYPE_NONE; diff --git a/src/server/game/Battlegrounds/BattlegroundMgr.h b/src/server/game/Battlegrounds/BattlegroundMgr.h index 5adb3675c40..cb0b34b4c0c 100644 --- a/src/server/game/Battlegrounds/BattlegroundMgr.h +++ b/src/server/game/Battlegrounds/BattlegroundMgr.h @@ -23,6 +23,9 @@ #include "DBCEnums.h" #include "Battleground.h" #include "BattlegroundQueue.h" +#include + +struct BattlemasterListEntry; typedef std::map BattlegroundContainer; typedef std::set BattlegroundClientIdsContainer; @@ -49,7 +52,7 @@ struct BattlegroundTemplate uint32 ScriptId; BattlemasterListEntry const* BattlemasterEntry; - bool IsArena() const { return BattlemasterEntry->type == MAP_ARENA; } + bool IsArena() const; }; class TC_GAME_API BattlegroundMgr diff --git a/src/server/game/Battlegrounds/BattlegroundQueue.cpp b/src/server/game/Battlegrounds/BattlegroundQueue.cpp index f5596b94cc4..90fc6318002 100644 --- a/src/server/game/Battlegrounds/BattlegroundQueue.cpp +++ b/src/server/game/Battlegrounds/BattlegroundQueue.cpp @@ -16,17 +16,20 @@ * with this program. If not, see . */ +#include "BattlegroundQueue.h" #include "ArenaTeam.h" #include "ArenaTeamMgr.h" #include "BattlegroundMgr.h" -#include "BattlegroundQueue.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "GameTime.h" #include "Group.h" -#include "Log.h" #include "Language.h" -#include "Player.h" +#include "Log.h" #include "ObjectAccessor.h" +#include "Player.h" +#include "World.h" /*********************************************************/ /*** BATTLEGROUND QUEUE SYSTEM ***/ @@ -127,7 +130,7 @@ bool BattlegroundQueue::SelectionPool::AddGroup(GroupQueueInfo* ginfo, uint32 de /*** BATTLEGROUND QUEUES ***/ /*********************************************************/ -// add group or player (grp == NULL) to bg queue with the given leader and bg specifications +// add group or player (grp == nullptr) to bg queue with the given leader and bg specifications GroupQueueInfo* BattlegroundQueue::AddGroup(Player* leader, Group* grp, BattlegroundTypeId BgTypeId, PvPDifficultyEntry const* bracketEntry, uint8 ArenaType, bool isRated, bool isPremade, uint32 ArenaRating, uint32 MatchmakerRating, uint32 arenateamid) { BattlegroundBracketId bracketId = bracketEntry->GetBracketId(); @@ -170,7 +173,7 @@ GroupQueueInfo* BattlegroundQueue::AddGroup(Player* leader, Group* grp, Battlegr //add players from group to ginfo if (grp) { - for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* member = itr->GetSource(); if (!member) @@ -397,7 +400,7 @@ void BattlegroundQueue::RemovePlayer(ObjectGuid guid, bool decreaseInvitedCount) // queue->removeplayer, it causes bugs WorldPacket data; sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, plr2, queueSlot, STATUS_NONE, plr2->GetBattlegroundQueueJoinTime(group->BgTypeId), 0, group->ArenaType); - plr2->GetSession()->SendPacket(&data); + plr2->SendDirectMessage(&data); } // then actually delete, this may delete the group as well! RemovePlayer(group->Players.begin()->first, decreaseInvitedCount); @@ -482,7 +485,7 @@ bool BattlegroundQueue::InviteGroupToBG(GroupQueueInfo* ginfo, Battleground* bg, // send status packet sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, player, queueSlot, STATUS_WAIT_JOIN, INVITE_ACCEPT_WAIT_TIME, player->GetBattlegroundQueueJoinTime(bgTypeId), ginfo->ArenaType); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } return true; } @@ -891,8 +894,8 @@ void BattlegroundQueue::BattlegroundQueueUpdate(uint32 /*diff*/, BattlegroundTyp // 0 is on (automatic update call) and we must set it to team's with longest wait time if (!arenaRating) { - GroupQueueInfo* front1 = NULL; - GroupQueueInfo* front2 = NULL; + GroupQueueInfo* front1 = nullptr; + GroupQueueInfo* front2 = nullptr; if (!m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].empty()) { front1 = m_QueuedGroups[bracket_id][BG_QUEUE_PREMADE_ALLIANCE].front(); @@ -1032,7 +1035,7 @@ bool BGQueueInviteEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/) WorldPacket data; //we must send remaining time in queue sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, player, queueSlot, STATUS_WAIT_JOIN, INVITE_ACCEPT_WAIT_TIME - INVITATION_REMIND_TIME, player->GetBattlegroundQueueJoinTime(m_BgTypeId), m_ArenaType); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } } return true; //event will be deleted @@ -1061,7 +1064,7 @@ bool BGQueueRemoveEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/) Battleground* bg = sBattlegroundMgr->GetBattleground(m_BgInstanceGUID, m_BgTypeId); //battleground can be deleted already when we are removing queue info - //bg pointer can be NULL! so use it carefully! + //bg pointer can be nullptr! so use it carefully! uint32 queueSlot = player->GetBattlegroundQueueIndex(m_BgQueueTypeId); if (queueSlot < PLAYER_MAX_BATTLEGROUND_QUEUES) // player is in queue, or in Battleground @@ -1090,7 +1093,7 @@ bool BGQueueRemoveEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/) WorldPacket data; sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, player, queueSlot, STATUS_NONE, player->GetBattlegroundQueueJoinTime(m_BgTypeId), 0, m_ArenaType); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } } diff --git a/src/server/game/Battlegrounds/BattlegroundScore.h b/src/server/game/Battlegrounds/BattlegroundScore.h index b90a06c6cc6..fcda199f78a 100644 --- a/src/server/game/Battlegrounds/BattlegroundScore.h +++ b/src/server/game/Battlegrounds/BattlegroundScore.h @@ -18,9 +18,11 @@ #ifndef TRINITY_BATTLEGROUND_SCORE_H #define TRINITY_BATTLEGROUND_SCORE_H -#include "WorldPacket.h" -#include "Player.h" -#include "ObjectAccessor.h" +#include "Errors.h" +#include "ObjectGuid.h" +#include "SharedDefines.h" + +class WorldPacket; enum ScoreType { @@ -90,70 +92,7 @@ struct BattlegroundScore } } - virtual void AppendToPacket(WorldPacket& data, ByteBuffer& content) - { - uint32 primaryTree = 0; - if (Player* player = ObjectAccessor::FindPlayer(PlayerGuid)) - primaryTree = player->GetPrimaryTalentTree(player->GetActiveSpec()); - - data.WriteBit(0); // Unk 1 - data.WriteBit(0); // Unk 2 - data.WriteBit(PlayerGuid[2]); - data.WriteBit(/*!IsArena*/ 1); // IsArena - data.WriteBit(0); // Unk 4 - data.WriteBit(0); // Unk 5 - data.WriteBit(0); // Unk 6 - data.WriteBit(PlayerGuid[3]); - data.WriteBit(PlayerGuid[0]); - data.WriteBit(PlayerGuid[5]); - data.WriteBit(PlayerGuid[1]); - data.WriteBit(PlayerGuid[6]); - data.WriteBit(TeamId); - data.WriteBit(PlayerGuid[7]); - - content << uint32(HealingDone); // healing done - content << uint32(DamageDone); // damage done - - //if (!IsArena) - //{ - content << uint32(BonusHonor / 100); - content << uint32(Deaths); - content << uint32(HonorableKills); - //} - - content.WriteByteSeq(PlayerGuid[4]); - content << uint32(KillingBlows); - - //if (unk 5) - // data << uint32() unk - - content.WriteByteSeq(PlayerGuid[5]); - - //if (unk 6) - // data << uint32() unk - - //if (unk 2) - // data << uint32() unk - - content.WriteByteSeq(PlayerGuid[1]); - content.WriteByteSeq(PlayerGuid[6]); - - content << int32(primaryTree); - - BuildObjectivesBlock(data, content); - - data.WriteBit(PlayerGuid[4]); - - content.WriteByteSeq(PlayerGuid[0]); - content.WriteByteSeq(PlayerGuid[3]); - - //if (unk 4) - // data << uint32() unk - - content.WriteByteSeq(PlayerGuid[7]); - content.WriteByteSeq(PlayerGuid[2]); - } - + virtual void AppendToPacket(WorldPacket& data, ByteBuffer& content); virtual void BuildObjectivesBlock(WorldPacket& /*data*/, ByteBuffer& /*content*/) = 0; // For Logging purpose diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundAB.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundAB.cpp index 36f6e19c68a..d9f4a51db97 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundAB.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundAB.cpp @@ -17,13 +17,25 @@ */ #include "BattlegroundAB.h" -#include "WorldPacket.h" #include "BattlegroundMgr.h" #include "Creature.h" +#include "DBCStores.h" +#include "GameObject.h" +#include "Log.h" +#include "Map.h" #include "Player.h" +#include "Random.h" #include "Util.h" +#include "WorldPacket.h" #include "WorldSession.h" +void BattlegroundABScore::BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) +{ + data.WriteBits(2, 24); // Objectives Count + content << uint32(BasesAssaulted); + content << uint32(BasesDefended); +} + BattlegroundAB::BattlegroundAB() { m_IsInformedNearVictory = false; @@ -367,7 +379,7 @@ void BattlegroundAB::_NodeOccupied(uint8 node, Team team) if (capturedNodes >= 4) CastSpellOnTeam(SPELL_AB_QUEST_REWARD_4_BASES, team); - Creature* trigger = !BgCreatures[node + 7] ? GetBGCreature(node + 7) : NULL; // 0-6 spirit guides + Creature* trigger = !BgCreatures[node + 7] ? GetBGCreature(node + 7) : nullptr; // 0-6 spirit guides if (!trigger) trigger = AddCreature(WORLD_TRIGGER, node+7, BG_AB_NodePositions[node], GetTeamIndexByTeamId(team)); @@ -388,7 +400,7 @@ void BattlegroundAB::_NodeDeOccupied(uint8 node) return; //remove bonus honor aura trigger creature when node is lost - DelCreature(node+7);//NULL checks are in DelCreature! 0-6 spirit guides + DelCreature(node+7);//nullptr checks are in DelCreature! 0-6 spirit guides RelocateDeadPlayers(BgCreatures[node]); @@ -623,7 +635,7 @@ void BattlegroundAB::EndBattleground(uint32 winner) Battleground::EndBattleground(winner); } -WorldSafeLocsEntry const* BattlegroundAB::GetClosestGraveYard(Player* player) +WorldSafeLocsEntry const* BattlegroundAB::GetClosestGraveyard(Player* player) { TeamId teamIndex = GetTeamIndexByTeamId(player->GetTeam()); @@ -633,7 +645,7 @@ WorldSafeLocsEntry const* BattlegroundAB::GetClosestGraveYard(Player* player) if (m_Nodes[i] == teamIndex + 3) nodes.push_back(i); - WorldSafeLocsEntry const* good_entry = NULL; + WorldSafeLocsEntry const* good_entry = nullptr; // If so, select the closest node to place ghost on if (!nodes.empty()) { diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundAB.h b/src/server/game/Battlegrounds/Zones/BattlegroundAB.h index 05f589d475e..1547ab33451 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundAB.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundAB.h @@ -288,12 +288,7 @@ struct BattlegroundABScore final : public BattlegroundScore } } - void BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) final override - { - data.WriteBits(2, 24); // Objectives Count - content << uint32(BasesAssaulted); - content << uint32(BasesDefended); - } + void BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) final override; uint32 GetAttr1() const final override { return BasesAssaulted; } uint32 GetAttr2() const final override { return BasesDefended; } @@ -316,7 +311,7 @@ class BattlegroundAB : public Battleground bool SetupBattleground() override; void Reset() override; void EndBattleground(uint32 winner) override; - WorldSafeLocsEntry const* GetClosestGraveYard(Player* player) override; + WorldSafeLocsEntry const* GetClosestGraveyard(Player* player) override; /* Scorekeeping */ bool UpdatePlayerScore(Player* player, uint32 type, uint32 value, bool doAddHonor = true) override; diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundAV.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundAV.cpp index d6bf87e4584..1bb1e766199 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundAV.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundAV.cpp @@ -17,15 +17,27 @@ */ #include "BattlegroundAV.h" - -#include "ObjectMgr.h" -#include "WorldPacket.h" - +#include "Creature.h" +#include "CreatureAI.h" +#include "DBCStores.h" #include "GameObject.h" +#include "Language.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectMgr.h" #include "Player.h" -#include "ScriptedCreature.h" #include "WorldSession.h" +void BattlegroundAVScore::BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) +{ + data.WriteBits(5, 24); // Objectives Count + content << uint32(GraveyardsAssaulted); + content << uint32(GraveyardsDefended); + content << uint32(TowersAssaulted); + content << uint32(TowersDefended); + content << uint32(MinesCaptured); +} + BattlegroundAV::BattlegroundAV() { BgObjects.resize(BG_AV_OBJECT_MAX); @@ -274,7 +286,7 @@ void BattlegroundAV::UpdateScore(uint16 team, int16 points) Creature* BattlegroundAV::AddAVCreature(uint16 cinfoid, uint16 type) { bool isStatic = false; - Creature* creature = NULL; + Creature* creature = nullptr; ASSERT(type < AV_CPLACE_MAX + AV_STATICCPLACE_MAX); if (type >= AV_CPLACE_MAX) //static { @@ -293,7 +305,7 @@ Creature* BattlegroundAV::AddAVCreature(uint16 cinfoid, uint16 type) creature = AddCreature(BG_AV_CreatureInfo[cinfoid], type, BG_AV_CreaturePos[type]); } if (!creature) - return NULL; + return nullptr; if (creature->GetEntry() == BG_AV_CreatureInfo[AV_NPC_A_CAPTAIN] || creature->GetEntry() == BG_AV_CreatureInfo[AV_NPC_H_CAPTAIN]) creature->SetRespawnDelay(RESPAWN_ONE_DAY); /// @todo look if this can be done by database + also add this for the wingcommanders @@ -393,7 +405,7 @@ void BattlegroundAV::PostUpdateImpl(uint32 diff) } } if (m_Mine_Timer <= 0) - m_Mine_Timer=AV_MINE_TICK_TIMER; //this is at the end, cause we need to update both mines + m_Mine_Timer = AV_MINE_TICK_TIMER; //this is at the end, cause we need to update both mines //looks for all timers of the nodes and destroy the building (for graveyards the building wont get destroyed, it goes just to the other team for (BG_AV_Nodes i = BG_AV_NODES_FIRSTAID_STATION; i < BG_AV_NODES_MAX; ++i) @@ -769,7 +781,7 @@ void BattlegroundAV::DePopulateNode(BG_AV_Nodes node) //remove bonus honor aura trigger creature when node is lost if (node < BG_AV_NODES_MAX)//fail safe - DelCreature(node + 302);//NULL checks are in DelCreature! 0-302 spirit guides + DelCreature(node + 302);//nullptr checks are in DelCreature! 0-302 spirit guides } BG_AV_Nodes BattlegroundAV::GetNodeThroughObject(uint32 object) @@ -1093,10 +1105,10 @@ void BattlegroundAV::SendMineWorldStates(uint32 mine) UpdateWorldState(BG_AV_MineWorldStates[mine2][prevowner], 0); } -WorldSafeLocsEntry const* BattlegroundAV::GetClosestGraveYard(Player* player) +WorldSafeLocsEntry const* BattlegroundAV::GetClosestGraveyard(Player* player) { - WorldSafeLocsEntry const* pGraveyard = NULL; - WorldSafeLocsEntry const* entry = NULL; + WorldSafeLocsEntry const* pGraveyard = nullptr; + WorldSafeLocsEntry const* entry = nullptr; float dist = 0; float minDist = 0; float x, y; @@ -1487,7 +1499,7 @@ void BattlegroundAV::ResetBGSubclass() InitNode(i, HORDE, true); InitNode(BG_AV_NODES_SNOWFALL_GRAVE, AV_NEUTRAL_TEAM, false); //give snowfall neutral owner - m_Mine_Timer=AV_MINE_TICK_TIMER; + m_Mine_Timer = AV_MINE_TICK_TIMER; for (uint16 i = 0; i < AV_CPLACE_MAX+AV_STATICCPLACE_MAX; i++) if (BgCreatures[i]) DelCreature(i); diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundAV.h b/src/server/game/Battlegrounds/Zones/BattlegroundAV.h index c63f5447821..964f7b3a5e2 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundAV.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundAV.h @@ -1591,15 +1591,7 @@ struct BattlegroundAVScore final : public BattlegroundScore } } - void BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) final override - { - data.WriteBits(5, 24); // Objectives Count - content << uint32(GraveyardsAssaulted); - content << uint32(GraveyardsDefended); - content << uint32(TowersAssaulted); - content << uint32(TowersDefended); - content << uint32(MinesCaptured); - } + void BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) final override; uint32 GetAttr1() const final override { return GraveyardsAssaulted; } uint32 GetAttr2() const final override { return GraveyardsDefended; } @@ -1643,7 +1635,7 @@ class BattlegroundAV : public Battleground void EndBattleground(uint32 winner) override; - WorldSafeLocsEntry const* GetClosestGraveYard(Player* player) override; + WorldSafeLocsEntry const* GetClosestGraveyard(Player* player) override; // Achievement: Av perfection and Everything counts bool CheckAchievementCriteriaMeet(uint32 criteriaId, Player const* source, Unit const* target = nullptr, uint32 miscvalue1 = 0) override; diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundBE.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundBE.cpp index dbdc0cc86c4..8e01f04df1f 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundBE.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundBE.cpp @@ -17,6 +17,7 @@ */ #include "BattlegroundBE.h" +#include "Log.h" #include "Player.h" #include "WorldPacket.h" diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundBFG.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundBFG.cpp index bb02e671123..012e8da453a 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundBFG.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundBFG.cpp @@ -15,18 +15,16 @@ * with this program. If not, see . */ -#include "Battleground.h" #include "BattlegroundBFG.h" -#include "Creature.h" -#include "GameObject.h" -#include "Language.h" -#include "Object.h" -#include "ObjectMgr.h" -#include "BattlegroundMgr.h" -#include "Player.h" -#include "World.h" #include "WorldPacket.h" +void BattlegroundBFGScore::BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) +{ + data.WriteBits(2, 24); // Objectives Count + content << uint32(BasesAssaulted); + content << uint32(BasesDefended); +} + BattlegroundBFG::BattlegroundBFG() { } diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundBFG.h b/src/server/game/Battlegrounds/Zones/BattlegroundBFG.h index e72a1ee841b..e2c79c3cc26 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundBFG.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundBFG.h @@ -42,12 +42,7 @@ class BattlegroundBFGScore final : public BattlegroundScore } } - void BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) final - { - data.WriteBits(2, 24); // Objectives Count - content << uint32(BasesAssaulted); - content << uint32(BasesDefended); - } + void BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) final override; uint32 GetAttr1() const final override { return BasesAssaulted; } uint32 GetAttr2() const final override { return BasesDefended; } diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundDS.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundDS.cpp index 027f2ee4484..77c075c8fbc 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundDS.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundDS.cpp @@ -18,7 +18,9 @@ #include "BattlegroundDS.h" #include "Creature.h" +#include "Log.h" #include "Player.h" +#include "Random.h" #include "WorldPacket.h" BattlegroundDS::BattlegroundDS() diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundDS.h b/src/server/game/Battlegrounds/Zones/BattlegroundDS.h index c5727f67ddc..b93930968d4 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundDS.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundDS.h @@ -20,6 +20,7 @@ #define __BATTLEGROUNDDS_H #include "Arena.h" +#include "EventMap.h" enum BattlegroundDSObjectTypes { @@ -109,4 +110,5 @@ class BattlegroundDS : public Arena uint32 _pipeKnockBackTimer; uint8 _pipeKnockBackCount; }; + #endif diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp index 03e0a4e58c0..c7875d615c2 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundEY.cpp @@ -20,7 +20,12 @@ #include "WorldPacket.h" #include "BattlegroundMgr.h" #include "Creature.h" +#include "DBCStores.h" +#include "GameObject.h" +#include "Log.h" +#include "Map.h" #include "Player.h" +#include "Random.h" #include "Util.h" #include "ObjectAccessor.h" @@ -31,6 +36,12 @@ uint32 BG_EY_HonorScoreTicks[BG_HONOR_MODE_NUM] = 160 // holiday }; +void BattlegroundEYScore::BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) +{ + data.WriteBits(1, 24); // Objectives Count + content << uint32(FlagCaptures); +} + BattlegroundEY::BattlegroundEY() { m_BuffChange = true; @@ -152,7 +163,7 @@ void BattlegroundEY::AddPoints(uint32 Team, uint32 Points) void BattlegroundEY::CheckSomeoneJoinedPoint() { - GameObject* obj = NULL; + GameObject* obj = nullptr; for (uint8 i = 0; i < EY_POINTS_MAX; ++i) { obj = GetBgMap()->GetGameObject(BgObjects[BG_EY_OBJECT_TOWER_CAP_FEL_REAVER + i]); @@ -193,7 +204,7 @@ void BattlegroundEY::CheckSomeoneLeftPoint() //reset current point counts for (uint8 i = 0; i < 2*EY_POINTS_MAX; ++i) m_CurrentPointPlayersCount[i] = 0; - GameObject* obj = NULL; + GameObject* obj = nullptr; for (uint8 i = 0; i < EY_POINTS_MAX; ++i) { obj = GetBgMap()->GetGameObject(BgObjects[BG_EY_OBJECT_TOWER_CAP_FEL_REAVER + i]); @@ -703,7 +714,7 @@ void BattlegroundEY::EventTeamLostPoint(Player* player, uint32 Point) UpdatePointsCount(Team); //remove bonus honor aura trigger creature when node is lost - DelCreature(Point + 6);//NULL checks are in DelCreature! 0-5 spirit guides + DelCreature(Point + 6);//nullptr checks are in DelCreature! 0-5 spirit guides } void BattlegroundEY::EventTeamCapturedPoint(Player* player, uint32 Point) @@ -869,7 +880,7 @@ void BattlegroundEY::FillInitialWorldStates(WorldPacket& data) data << uint32(0xc0d) << uint32(0x17b); } -WorldSafeLocsEntry const* BattlegroundEY::GetClosestGraveYard(Player* player) +WorldSafeLocsEntry const* BattlegroundEY::GetClosestGraveyard(Player* player) { uint32 g_id = 0; @@ -877,20 +888,20 @@ WorldSafeLocsEntry const* BattlegroundEY::GetClosestGraveYard(Player* player) { case ALLIANCE: g_id = EY_GRAVEYARD_MAIN_ALLIANCE; break; case HORDE: g_id = EY_GRAVEYARD_MAIN_HORDE; break; - default: return NULL; + default: return nullptr; } float distance, nearestDistance; - WorldSafeLocsEntry const* entry = NULL; - WorldSafeLocsEntry const* nearestEntry = NULL; + WorldSafeLocsEntry const* entry = nullptr; + WorldSafeLocsEntry const* nearestEntry = nullptr; entry = sWorldSafeLocsStore.LookupEntry(g_id); nearestEntry = entry; if (!entry) { TC_LOG_ERROR("bg.battleground", "BattlegroundEY: The main team graveyard could not be found. The graveyard system will not be operational!"); - return NULL; + return nullptr; } float plr_x = player->GetPositionX(); diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundEY.h b/src/server/game/Battlegrounds/Zones/BattlegroundEY.h index 0e14db82c89..7328039e392 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundEY.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundEY.h @@ -371,11 +371,7 @@ struct BattlegroundEYScore final : public BattlegroundScore } } - void BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) final override - { - data.WriteBits(1, 24); // Objectives Count - content << uint32(FlagCaptures); - } + void BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) final override; uint32 GetAttr1() const final override { return FlagCaptures; } @@ -404,7 +400,7 @@ class BattlegroundEY : public Battleground void RemovePlayer(Player* player, ObjectGuid guid, uint32 team) override; void HandleAreaTrigger(Player* Source, uint32 Trigger) override; void HandleKillPlayer(Player* player, Player* killer) override; - WorldSafeLocsEntry const* GetClosestGraveYard(Player* player) override; + WorldSafeLocsEntry const* GetClosestGraveyard(Player* player) override; bool SetupBattleground() override; void Reset() override; void UpdateTeamScore(uint32 Team); diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundIC.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundIC.cpp index 075377d4e6d..12980d7b57c 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundIC.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundIC.cpp @@ -16,15 +16,24 @@ * with this program. If not, see . */ -#include "Player.h" -#include "Battleground.h" #include "BattlegroundIC.h" -#include "WorldPacket.h" +#include "Battleground.h" #include "GameObject.h" +#include "Log.h" +#include "Map.h" #include "ObjectMgr.h" -#include "Vehicle.h" -#include "Transport.h" +#include "Player.h" #include "ScriptedCreature.h" +#include "Transport.h" +#include "Vehicle.h" +#include "WorldPacket.h" + +void BattlegroundICScore::BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) +{ + data.WriteBits(2, 24); // Objectives Count + content << uint32(BasesAssaulted); + content << uint32(BasesDefended); +} BattlegroundIC::BattlegroundIC() { @@ -47,8 +56,8 @@ BattlegroundIC::BattlegroundIC() siegeEngineWorkshopTimer = WORKSHOP_UPDATE_TIME; - gunshipHorde = NULL; - gunshipAlliance = NULL; + gunshipHorde = nullptr; + gunshipAlliance = nullptr; } BattlegroundIC::~BattlegroundIC() { } @@ -853,7 +862,7 @@ void BattlegroundIC::DestroyGate(Player* player, GameObject* go) SendBroadcastText(textId, msgType); } -WorldSafeLocsEntry const* BattlegroundIC::GetClosestGraveYard(Player* player) +WorldSafeLocsEntry const* BattlegroundIC::GetClosestGraveyard(Player* player) { TeamId teamIndex = GetTeamIndexByTeamId(player->GetTeam()); @@ -863,7 +872,7 @@ WorldSafeLocsEntry const* BattlegroundIC::GetClosestGraveYard(Player* player) if (nodePoint[i].faction == player->GetTeamId()) nodes.push_back(i); - WorldSafeLocsEntry const* good_entry = NULL; + WorldSafeLocsEntry const* good_entry = nullptr; // If so, select the closest node to place ghost on if (!nodes.empty()) { diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundIC.h b/src/server/game/Battlegrounds/Zones/BattlegroundIC.h index c30847282fb..c7685e04c48 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundIC.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundIC.h @@ -931,12 +931,7 @@ struct BattlegroundICScore final : public BattlegroundScore } } - void BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) final override - { - data.WriteBits(2, 24); // Objectives Count - content << uint32(BasesAssaulted); - content << uint32(BasesDefended); - } + void BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) final override; uint32 GetAttr1() const final override { return BasesAssaulted; } uint32 GetAttr2() const final override { return BasesDefended; } @@ -967,7 +962,7 @@ class BattlegroundIC : public Battleground void DestroyGate(Player* player, GameObject* go) override; - WorldSafeLocsEntry const* GetClosestGraveYard(Player* player) override; + WorldSafeLocsEntry const* GetClosestGraveyard(Player* player) override; /* Scorekeeping */ void FillInitialWorldStates(WorldPacket& data) override; diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundNA.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundNA.cpp index 0186b1e8e73..5e742b57980 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundNA.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundNA.cpp @@ -17,6 +17,7 @@ */ #include "BattlegroundNA.h" +#include "Log.h" #include "Player.h" #include "WorldPacket.h" diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundRL.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundRL.cpp index a240bb8eab3..3db0f588e01 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundRL.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundRL.cpp @@ -17,6 +17,7 @@ */ #include "BattlegroundRL.h" +#include "Log.h" #include "Player.h" #include "WorldPacket.h" diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundRV.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundRV.cpp index 54e84dd8a73..b8d67e52749 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundRV.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundRV.cpp @@ -18,6 +18,7 @@ #include "BattlegroundRV.h" #include "GameObject.h" +#include "Log.h" #include "ObjectAccessor.h" #include "Player.h" #include "WorldPacket.h" diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundSA.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundSA.cpp index 1abd3211dd2..cdcde68a1e2 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundSA.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundSA.cpp @@ -17,13 +17,25 @@ */ #include "BattlegroundSA.h" +#include "DBCStores.h" #include "GameObject.h" #include "GameTime.h" +#include "Log.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Player.h" #include "ScriptedCreature.h" +#include "UpdateData.h" #include "WorldPacket.h" +void BattlegroundSAScore::BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) +{ + data.WriteBits(2, 24); // Objectives Count + content << uint32(DemolishersDestroyed); + content << uint32(GatesDestroyed); +} + BattlegroundSA::BattlegroundSA() { StartMessageIds[BG_STARTING_EVENT_FOURTH] = 0; // handle by Kanrethad @@ -148,8 +160,8 @@ bool BattlegroundSA::ResetObjs() } // MAD props for Kiper for discovering those values - 4 hours of his work. - 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)); + GetBGObject(BG_SA_BOAT_ONE)->SetParentRotation(QuaternionData(0.f, 0.f, 1.0f, 0.0002f)); + GetBGObject(BG_SA_BOAT_TWO)->SetParentRotation(QuaternionData(0.f, 0.f, 1.0f, 0.00001f)); SpawnBGObject(BG_SA_BOAT_ONE, RESPAWN_IMMEDIATELY); SpawnBGObject(BG_SA_BOAT_TWO, RESPAWN_IMMEDIATELY); @@ -536,7 +548,7 @@ void BattlegroundSA::TeleportToEntrancePosition(Player* player) player->TeleportTo(607, 1209.7f, -65.16f, 70.1f, 0.0f, 0); } -void BattlegroundSA::ProcessEvent(WorldObject* obj, uint32 eventId, WorldObject* invoker /*= NULL*/) +void BattlegroundSA::ProcessEvent(WorldObject* obj, uint32 eventId, WorldObject* invoker /*= nullptr*/) { if (GameObject* go = obj->ToGameObject()) { @@ -681,7 +693,7 @@ void BattlegroundSA::DestroyGate(Player* /*player*/, GameObject* /*go*/) { } -WorldSafeLocsEntry const* BattlegroundSA::GetClosestGraveYard(Player* player) +WorldSafeLocsEntry const* BattlegroundSA::GetClosestGraveyard(Player* player) { uint32 safeloc = 0; WorldSafeLocsEntry const* ret; diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundSA.h b/src/server/game/Battlegrounds/Zones/BattlegroundSA.h index fc26bc2115d..bed5244115c 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundSA.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundSA.h @@ -540,12 +540,7 @@ struct BattlegroundSAScore final : public BattlegroundScore } } - void BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) final override - { - data.WriteBits(2, 24); // Objectives Count - content << uint32(DemolishersDestroyed); - content << uint32(GatesDestroyed); - } + void BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) final override; uint32 GetAttr1() const final override { return DemolishersDestroyed; } uint32 GetAttr2() const final override { return GatesDestroyed; } @@ -582,9 +577,9 @@ class BattlegroundSA : public Battleground /// Called when a player kill a unit in bg void HandleKillUnit(Creature* creature, Player* killer) override; /// Return the nearest graveyard where player can respawn - WorldSafeLocsEntry const* GetClosestGraveYard(Player* player) override; + WorldSafeLocsEntry const* GetClosestGraveyard(Player* player) override; /// Called when someone activates an event - void ProcessEvent(WorldObject* /*obj*/, uint32 /*eventId*/, WorldObject* /*invoker*/ = NULL) override; + void ProcessEvent(WorldObject* /*obj*/, uint32 /*eventId*/, WorldObject* /*invoker*/ = nullptr) override; /// Called when a player click on flag (graveyard flag) void EventPlayerClickedOnFlag(Player* source, GameObject* go) override; /// Called when a player clicked on relic @@ -596,7 +591,7 @@ class BattlegroundSA : public Battleground for (uint8 i = 0; i < MAX_GATES; ++i) if (Gates[i].GameObjectId == entry) return &Gates[i]; - return NULL; + return nullptr; } /// Called on battleground ending @@ -609,7 +604,7 @@ class BattlegroundSA : public Battleground /* Scorekeeping */ // Achievement: Not Even a Scratch - bool CheckAchievementCriteriaMeet(uint32 criteriaId, Player const* source, Unit const* target = NULL, uint32 miscValue = 0) override; + bool CheckAchievementCriteriaMeet(uint32 criteriaId, Player const* source, Unit const* target = nullptr, uint32 miscValue = 0) override; // Control Phase Shift bool IsSpellAllowed(uint32 spellId, Player const* player) const override; diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundTP.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundTP.cpp index c50019a6867..0766ba24394 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundTP.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundTP.cpp @@ -27,6 +27,13 @@ #include "World.h" #include "WorldPacket.h" +void BattlegroundTPScore::BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) +{ + data.WriteBits(2, 24); // Objectives Count + content << uint32(FlagCaptures); + content << uint32(FlagReturns); +} + BattlegroundTP::BattlegroundTP() { } diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundTP.h b/src/server/game/Battlegrounds/Zones/BattlegroundTP.h index cbb06e33717..4e6a0e37fbc 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundTP.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundTP.h @@ -42,12 +42,7 @@ class BattlegroundTPScore final : public BattlegroundScore } } - void BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) final - { - data.WriteBits(2, 24); // Objectives Count - content << uint32(FlagCaptures); - content << uint32(FlagReturns); - } + void BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) final override; uint32 GetAttr1() const final override { return FlagCaptures; } uint32 GetAttr2() const final override { return FlagReturns; } diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundWS.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundWS.cpp index 405d6c7ba2f..82072c9337d 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundWS.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundWS.cpp @@ -17,12 +17,15 @@ */ #include "BattlegroundWS.h" -#include "GameObject.h" -#include "Object.h" #include "BattlegroundMgr.h" +#include "DBCStores.h" +#include "GameObject.h" +#include "Log.h" +#include "Map.h" +#include "Object.h" +#include "ObjectAccessor.h" #include "Player.h" #include "WorldPacket.h" -#include "ObjectAccessor.h" // these variables aren't used outside of this file, so declare them only here enum BG_WSG_Rewards @@ -68,6 +71,13 @@ BattlegroundWS::BattlegroundWS() _minutesElapsed = 0; } +void BattlegroundWGScore::BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) +{ + data.WriteBits(2, 24); // Objectives Count + content << uint32(FlagCaptures); + content << uint32(FlagReturns); +} + BattlegroundWS::~BattlegroundWS() { } void BattlegroundWS::PostUpdateImpl(uint32 diff) @@ -785,7 +795,7 @@ bool BattlegroundWS::UpdatePlayerScore(Player* player, uint32 type, uint32 value return true; } -WorldSafeLocsEntry const* BattlegroundWS::GetClosestGraveYard(Player* player) +WorldSafeLocsEntry const* BattlegroundWS::GetClosestGraveyard(Player* player) { //if status in progress, it returns main graveyards with spiritguides //else it will return the graveyard in the flagroom - this is especially good diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundWS.h b/src/server/game/Battlegrounds/Zones/BattlegroundWS.h index 88bc385456b..4b9a0030d1b 100644 --- a/src/server/game/Battlegrounds/Zones/BattlegroundWS.h +++ b/src/server/game/Battlegrounds/Zones/BattlegroundWS.h @@ -187,12 +187,7 @@ struct BattlegroundWGScore final : public BattlegroundScore } } - void BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) final override - { - data.WriteBits(2, 24); // Objectives Count - content << uint32(FlagCaptures); - content << uint32(FlagReturns); - } + void BuildObjectivesBlock(WorldPacket& data, ByteBuffer& content) final override; uint32 GetAttr1() const final override { return FlagCaptures; } uint32 GetAttr2() const final override { return FlagReturns; } @@ -239,7 +234,7 @@ class BattlegroundWS : public Battleground bool SetupBattleground() override; void Reset() override; void EndBattleground(uint32 winner) override; - WorldSafeLocsEntry const* GetClosestGraveYard(Player* player) override; + WorldSafeLocsEntry const* GetClosestGraveyard(Player* player) override; void UpdateFlagState(uint32 team, uint32 value); void SetLastFlagCapture(uint32 team) { _lastFlagCaptureTeam = team; } diff --git a/src/server/game/CMakeLists.txt b/src/server/game/CMakeLists.txt index 7f7f6853773..2cfdff37361 100644 --- a/src/server/game/CMakeLists.txt +++ b/src/server/game/CMakeLists.txt @@ -16,10 +16,6 @@ CollectSourceFiles( if (USE_COREPCH) set(PRIVATE_PCH_HEADER PrecompiledHeaders/gamePCH.h) - set(PRIVATE_PCH_SOURCE PrecompiledHeaders/gamePCH.cpp) - if (MSVC) - list(INSERT PRIVATE_SOURCES 0 PrecompiledHeaders/gamePCH.cpp) - endif (MSVC) endif () GroupSources(${CMAKE_CURRENT_SOURCE_DIR}) @@ -53,11 +49,12 @@ target_include_directories(game ${CMAKE_CURRENT_BINARY_DIR}) target_link_libraries(game + PRIVATE + trinity-core-interface + efsw PUBLIC ipc - game-interface - PRIVATE - efsw) + game-interface) set_target_properties(game PROPERTIES @@ -78,5 +75,5 @@ endif() # Generate precompiled header if (USE_COREPCH) - add_cxx_pch(game ${PRIVATE_PCH_HEADER} ${PRIVATE_PCH_SOURCE}) + add_cxx_pch(game ${PRIVATE_PCH_HEADER}) endif () diff --git a/src/server/game/Calendar/CalendarMgr.cpp b/src/server/game/Calendar/CalendarMgr.cpp index 570ad2afe5e..d34b7c87e31 100644 --- a/src/server/game/Calendar/CalendarMgr.cpp +++ b/src/server/game/Calendar/CalendarMgr.cpp @@ -17,12 +17,15 @@ #include "CalendarMgr.h" #include "CharacterCache.h" -#include "QueryResult.h" -#include "Log.h" -#include "Player.h" +#include "DatabaseEnv.h" +#include "Guild.h" #include "GuildMgr.h" +#include "Log.h" +#include "Mail.h" #include "ObjectAccessor.h" #include "Opcodes.h" +#include "Player.h" +#include "WorldPacket.h" CalendarInvite::~CalendarInvite() { @@ -300,7 +303,7 @@ CalendarEvent* CalendarMgr::GetEvent(uint64 eventId) const return *itr; TC_LOG_DEBUG("calendar", "CalendarMgr::GetEvent: [" UI64FMTD "] not found!", eventId); - return NULL; + return nullptr; } CalendarInvite* CalendarMgr::GetInvite(uint64 inviteId) const @@ -311,7 +314,7 @@ CalendarInvite* CalendarMgr::GetInvite(uint64 inviteId) const return *itr2; TC_LOG_DEBUG("calendar", "CalendarMgr::GetInvite: [" UI64FMTD "] not found!", inviteId); - return NULL; + return nullptr; } void CalendarMgr::FreeEventId(uint64 id) @@ -357,7 +360,7 @@ CalendarEventStore CalendarMgr::GetPlayerEvents(ObjectGuid guid) for (CalendarEventInviteStore::const_iterator itr = _invites.begin(); itr != _invites.end(); ++itr) for (CalendarInviteStore::const_iterator itr2 = itr->second.begin(); itr2 != itr->second.end(); ++itr2) if ((*itr2)->GetInviteeGUID() == guid) - if (CalendarEvent* event = GetEvent(itr->first)) // NULL check added as attempt to fix #11512 + if (CalendarEvent* event = GetEvent(itr->first)) // nullptr check added as attempt to fix #11512 events.insert(event); if (Player* player = ObjectAccessor::FindConnectedPlayer(guid)) @@ -627,7 +630,7 @@ void CalendarMgr::SendCalendarClearPendingAction(ObjectGuid guid) } } -void CalendarMgr::SendCalendarCommandResult(ObjectGuid guid, CalendarError err, char const* param /*= NULL*/) +void CalendarMgr::SendCalendarCommandResult(ObjectGuid guid, CalendarError err, char const* param /*= nullptr*/) { if (Player* player = ObjectAccessor::FindConnectedPlayer(guid)) { diff --git a/src/server/game/Calendar/CalendarMgr.h b/src/server/game/Calendar/CalendarMgr.h index 80ad3b28e5a..aa83dc0eb6d 100644 --- a/src/server/game/Calendar/CalendarMgr.h +++ b/src/server/game/Calendar/CalendarMgr.h @@ -19,9 +19,14 @@ #define TRINITY_CALENDARMGR_H #include "Common.h" -#include "DatabaseEnv.h" -#include "WorldPacket.h" +#include "DatabaseEnvFwd.h" #include "ObjectGuid.h" +#include +#include +#include +#include + +class WorldPacket; enum CalendarMailAnswers { @@ -142,7 +147,7 @@ struct TC_GAME_API CalendarInvite _text = calendarInvite.GetText(); } - CalendarInvite() : _inviteId(1), _eventId(0), _invitee(), _senderGUID(), _statusTime(time(NULL)), + CalendarInvite() : _inviteId(1), _eventId(0), _invitee(), _senderGUID(), _statusTime(time(nullptr)), _status(CALENDAR_STATUS_INVITED), _rank(CALENDAR_RANK_PLAYER), _text("") { } CalendarInvite(uint64 inviteId, uint64 eventId, ObjectGuid invitee, ObjectGuid senderGUID, time_t statusTime, @@ -325,7 +330,7 @@ class TC_GAME_API CalendarMgr void SendCalendarEventRemovedAlert(CalendarEvent const& calendarEvent); void SendCalendarEventModeratorStatusAlert(CalendarEvent const& calendarEvent, CalendarInvite const& invite); void SendCalendarClearPendingAction(ObjectGuid guid); - void SendCalendarCommandResult(ObjectGuid guid, CalendarError err, char const* param = NULL); + void SendCalendarCommandResult(ObjectGuid guid, CalendarError err, char const* param = nullptr); void SendPacketToAllEventRelatives(WorldPacket& packet, CalendarEvent const& calendarEvent); }; diff --git a/src/server/game/Chat/Channels/Channel.cpp b/src/server/game/Chat/Channels/Channel.cpp index 036074d49ef..d15a9383932 100644 --- a/src/server/game/Chat/Channels/Channel.cpp +++ b/src/server/game/Chat/Channels/Channel.cpp @@ -17,17 +17,19 @@ */ #include "Channel.h" +#include "AccountMgr.h" #include "ChannelAppenders.h" #include "Chat.h" -#include "GridNotifiers.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "GridNotifiersImpl.h" -#include "ObjectMgr.h" #include "Language.h" +#include "Log.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Player.h" #include "SocialMgr.h" #include "World.h" -#include "DatabaseEnv.h" -#include "AccountMgr.h" -#include "Player.h" Channel::Channel(uint32 channelId, uint32 team /*= 0*/, AreaTableEntry const* zoneEntry /*= nullptr*/) : _announceEnabled(false), // no join/leave announces diff --git a/src/server/game/Chat/Channels/Channel.h b/src/server/game/Chat/Channels/Channel.h index 113803fd479..b3f112c73b1 100644 --- a/src/server/game/Chat/Channels/Channel.h +++ b/src/server/game/Chat/Channels/Channel.h @@ -20,11 +20,12 @@ #define _CHANNEL_H #include "Common.h" - -#include "WorldSession.h" -#include "WorldPacket.h" +#include "ObjectGuid.h" +#include +#include class Player; +struct AreaTableEntry; enum ChatNotify { diff --git a/src/server/game/Chat/Channels/ChannelAppenders.h b/src/server/game/Chat/Channels/ChannelAppenders.h index 6de6bb24c0a..31fc8859214 100644 --- a/src/server/game/Chat/Channels/ChannelAppenders.h +++ b/src/server/game/Chat/Channels/ChannelAppenders.h @@ -20,6 +20,8 @@ #include "Channel.h" #include "CharacterCache.h" +#include "World.h" +#include "WorldPacket.h" // initial packet data (notify type and channel name) template @@ -185,10 +187,7 @@ struct ChannelOwnerAppend { explicit ChannelOwnerAppend(Channel const* channel, ObjectGuid const& ownerGuid) : _channel(channel), _ownerGuid(ownerGuid) { - CharacterCacheEntry const* cInfo = sCharacterCache->GetCharacterCacheByGuid(_ownerGuid); - if (!cInfo || cInfo->Name.empty()) - _ownerName = "PLAYER_NOT_FOUND"; - else + if (CharacterCacheEntry const* cInfo = sCharacterCache->GetCharacterCacheByGuid(_ownerGuid)) _ownerName = cInfo->Name; } diff --git a/src/server/game/Chat/Channels/ChannelMgr.h b/src/server/game/Chat/Channels/ChannelMgr.h index 3133d78ec8b..5c71f94e5aa 100644 --- a/src/server/game/Chat/Channels/ChannelMgr.h +++ b/src/server/game/Chat/Channels/ChannelMgr.h @@ -18,9 +18,15 @@ #ifndef __TRINITY_CHANNELMGR_H #define __TRINITY_CHANNELMGR_H -#include "Common.h" +#include "Define.h" +#include "Hash.h" +#include +#include class Channel; +class Player; +class WorldPacket; +struct AreaTableEntry; class TC_GAME_API ChannelMgr { diff --git a/src/server/game/Chat/Chat.cpp b/src/server/game/Chat/Chat.cpp index 9b563b716c0..4e7b8f51743 100644 --- a/src/server/game/Chat/Chat.cpp +++ b/src/server/game/Chat/Chat.cpp @@ -16,25 +16,30 @@ * with this program. If not, see . */ -#include "Common.h" -#include "ObjectMgr.h" -#include "World.h" -#include "WorldSession.h" -#include "DatabaseEnv.h" - +#include "Chat.h" #include "AccountMgr.h" #include "CellImpl.h" #include "CharacterCache.h" -#include "Chat.h" +#include "ChatLink.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "GridNotifiersImpl.h" #include "Language.h" #include "Log.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Optional.h" #include "Player.h" +#include "Realm.h" #include "ScriptMgr.h" -#include "ChatLink.h" -#include "Group.h" +#include "World.h" #include +ChatCommand::ChatCommand(char const* name, uint32 permission, bool allowConsole, pHandler handler, std::string help, std::vector childCommands /*= std::vector()*/) + : Name(ASSERT_NOTNULL(name)), Permission(permission), AllowConsole(allowConsole), Handler(handler), Help(std::move(help)), ChildCommands(std::move(childCommands)) +{ +} + // 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 @@ -82,6 +87,16 @@ bool ChatHandler::isAvailable(ChatCommand const& cmd) const return HasPermission(cmd.Permission); } +bool ChatHandler::HasPermission(uint32 permission) const +{ + return m_session->HasPermission(permission); +} + +std::string ChatHandler::GetNameLink() const +{ + return GetNameLink(m_session->GetPlayer()); +} + bool ChatHandler::HasLowerSecurity(Player* target, ObjectGuid guid, bool strong) { WorldSession* target_session = nullptr; @@ -453,7 +468,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) diff --git a/src/server/game/Chat/Chat.h b/src/server/game/Chat/Chat.h index ef6c5b2c66f..8fb44a4c29f 100644 --- a/src/server/game/Chat/Chat.h +++ b/src/server/game/Chat/Chat.h @@ -19,20 +19,21 @@ #ifndef TRINITYCORE_CHAT_H #define TRINITYCORE_CHAT_H +#include "Common.h" +#include "ObjectGuid.h" #include "SharedDefines.h" #include "StringFormat.h" -#include "WorldSession.h" -#include "RBAC.h" - #include class ChatHandler; class Creature; +class GameObject; class Group; class Player; class Unit; class WorldSession; class WorldObject; +class WorldPacket; struct GameTele; @@ -41,8 +42,7 @@ class TC_GAME_API ChatCommand typedef bool(*pHandler)(ChatHandler*, char const*); public: - ChatCommand(char const* name, uint32 permission, bool allowConsole, pHandler handler, std::string help, std::vector childCommands = std::vector()) - : Name(ASSERT_NOTNULL(name)), Permission(permission), AllowConsole(allowConsole), Handler(handler), Help(std::move(help)), ChildCommands(std::move(childCommands)) { } + ChatCommand(char const* name, uint32 permission, bool allowConsole, pHandler handler, std::string help, std::vector childCommands = std::vector()); char const* Name; uint32 Permission; // function pointer required correct align (use uint32) @@ -108,8 +108,8 @@ class TC_GAME_API ChatHandler // function with different implementation for chat/console virtual bool isAvailable(ChatCommand const& cmd) const; virtual bool IsHumanReadable() const { return true; } - virtual bool HasPermission(uint32 permission) const { return m_session->HasPermission(permission); } - virtual std::string GetNameLink() const { return GetNameLink(m_session->GetPlayer()); } + virtual bool HasPermission(uint32 permission) const; + virtual std::string GetNameLink() const; virtual bool needReportToTarget(Player* chr) const; virtual LocaleConstant GetSessionDbcLocale() const; virtual LocaleConstant GetSessionDbLocaleIndex() const; diff --git a/src/server/game/Chat/ChatLink.cpp b/src/server/game/Chat/ChatLink.cpp index b7cf6cff200..98a1d7f7857 100644 --- a/src/server/game/Chat/ChatLink.cpp +++ b/src/server/game/Chat/ChatLink.cpp @@ -16,11 +16,12 @@ */ #include "ChatLink.h" -#include "SpellMgr.h" +#include "AchievementMgr.h" +#include "DBCStores.h" +#include "Log.h" #include "ObjectMgr.h" #include "SpellInfo.h" -#include "DBCStores.h" -#include "AchievementMgr.h" +#include "SpellMgr.h" // Supported shift-links (client generated and server side) // |color|Hachievement:achievement_id:player_guid:0:0:0:0:0:0:0:0|h[name]|h|r diff --git a/src/server/game/Chat/ChatLink.h b/src/server/game/Chat/ChatLink.h index e8d53f2396c..931754abf3e 100644 --- a/src/server/game/Chat/ChatLink.h +++ b/src/server/game/Chat/ChatLink.h @@ -18,10 +18,12 @@ #ifndef TRINITYCORE_CHATLINK_H #define TRINITYCORE_CHATLINK_H +#include "Common.h" #include "SharedDefines.h" -#include -#include #include +#include +#include +#include struct ItemLocale; struct ItemTemplate; @@ -152,7 +154,7 @@ public: 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; diff --git a/src/server/game/Combat/ThreatManager.cpp b/src/server/game/Combat/ThreatManager.cpp index 8d7b015fa70..02e4cc51afb 100644 --- a/src/server/game/Combat/ThreatManager.cpp +++ b/src/server/game/Combat/ThreatManager.cpp @@ -44,7 +44,7 @@ float ThreatCalcHelper::calcThreat(Unit* hatedUnit, Unit* /*hatingUnit*/, float return threat; if (Player* modOwner = hatedUnit->GetSpellModOwner()) - modOwner->ApplySpellMod(threatSpell->Id, threat); + modOwner->ApplySpellMod(threatSpell->Id, SPELLMOD_THREAT, threat); } return hatedUnit->ApplyTotalThreatModifier(threat, schoolMask); @@ -262,11 +262,11 @@ void ThreatContainer::clearReferences() } //============================================================ -// Return the HostileReference of NULL, if not found +// Return the HostileReference of nullptr, if not found HostileReference* ThreatContainer::getReferenceByTarget(Unit* victim) const { if (!victim) - return NULL; + return nullptr; ObjectGuid guid = victim->GetGUID(); for (ThreatContainer::StorageType::const_iterator i = iThreatList.begin(); i != iThreatList.end(); ++i) @@ -276,7 +276,7 @@ HostileReference* ThreatContainer::getReferenceByTarget(Unit* victim) const return ref; } - return NULL; + return nullptr; } //============================================================ @@ -315,7 +315,7 @@ void ThreatContainer::update() HostileReference* ThreatContainer::selectNextVictim(Creature* attacker, HostileReference* currentVictim) const { - HostileReference* currentRef = NULL; + HostileReference* currentRef = nullptr; bool found = false; bool noPriorityTargetFound = false; @@ -380,7 +380,7 @@ HostileReference* ThreatContainer::selectNextVictim(Creature* attacker, HostileR ++iter; } if (!found) - currentRef = NULL; + currentRef = nullptr; return currentRef; } @@ -389,7 +389,7 @@ HostileReference* ThreatContainer::selectNextVictim(Creature* attacker, HostileR //=================== ThreatManager ========================== //============================================================ -ThreatManager::ThreatManager(Unit* owner) : iCurrentVictim(NULL), iOwner(owner), iUpdateTimer(THREAT_UPDATE_INTERVAL) { } +ThreatManager::ThreatManager(Unit* owner) : iCurrentVictim(nullptr), iOwner(owner), iUpdateTimer(THREAT_UPDATE_INTERVAL) { } //============================================================ @@ -397,7 +397,7 @@ void ThreatManager::clearReferences() { iThreatContainer.clearReferences(); iThreatOfflineContainer.clearReferences(); - iCurrentVictim = NULL; + iCurrentVictim = nullptr; iUpdateTimer = THREAT_UPDATE_INTERVAL; } @@ -465,7 +465,7 @@ Unit* ThreatManager::getHostilTarget() iThreatContainer.update(); HostileReference* nextVictim = iThreatContainer.selectNextVictim(GetOwner()->ToCreature(), getCurrentVictim()); setCurrentVictim(nextVictim); - return getCurrentVictim() != NULL ? getCurrentVictim()->getTarget() : NULL; + return getCurrentVictim() != nullptr ? getCurrentVictim()->getTarget() : nullptr; } //============================================================ @@ -535,7 +535,7 @@ void ThreatManager::processThreatEvent(ThreatRefStatusChangeEvent* threatRefStat { if (hostilRef == getCurrentVictim()) { - setCurrentVictim(NULL); + setCurrentVictim(nullptr); setDirty(true); } iOwner->SendRemoveFromThreatListOpcode(hostilRef); @@ -553,7 +553,7 @@ void ThreatManager::processThreatEvent(ThreatRefStatusChangeEvent* threatRefStat case UEV_THREAT_REF_REMOVE_FROM_LIST: if (hostilRef == getCurrentVictim()) { - setCurrentVictim(NULL); + setCurrentVictim(nullptr); setDirty(true); } iOwner->SendRemoveFromThreatListOpcode(hostilRef); diff --git a/src/server/game/Combat/ThreatManager.h b/src/server/game/Combat/ThreatManager.h index 95230f335b5..afcdf6a9d35 100644 --- a/src/server/game/Combat/ThreatManager.h +++ b/src/server/game/Combat/ThreatManager.h @@ -212,7 +212,7 @@ class TC_GAME_API ThreatManager void clearReferences(); - void addThreat(Unit* victim, float threat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* threatSpell = NULL); + void addThreat(Unit* victim, float threat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* threatSpell = nullptr); void doAddThreat(Unit* victim, float threat); diff --git a/src/server/game/Combat/UnitEvents.h b/src/server/game/Combat/UnitEvents.h index e5b89dabc44..bcce15c7b26 100644 --- a/src/server/game/Combat/UnitEvents.h +++ b/src/server/game/Combat/UnitEvents.h @@ -48,7 +48,7 @@ enum UNIT_EVENT_TYPE // New target should be fetched, could tbe the current target as well UEV_THREAT_SET_NEXT_TARGET = 1<<5, - // A new victim (target) was set. Could be NULL + // A new victim (target) was set. Could be nullptr UEV_THREAT_VICTIM_CHANGED = 1<<6 // Future use diff --git a/src/server/game/Conditions/ConditionMgr.cpp b/src/server/game/Conditions/ConditionMgr.cpp index e3a656d9ea6..4f83707b80c 100644 --- a/src/server/game/Conditions/ConditionMgr.cpp +++ b/src/server/game/Conditions/ConditionMgr.cpp @@ -18,17 +18,22 @@ #include "ConditionMgr.h" #include "AchievementMgr.h" +#include "DatabaseEnv.h" #include "GameEventMgr.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Log.h" +#include "LootMgr.h" +#include "Map.h" #include "ObjectMgr.h" #include "PhasingHandler.h" #include "Player.h" #include "Pet.h" #include "ReputationMgr.h" -#include "ScriptedCreature.h" #include "ScriptMgr.h" #include "SpellAuras.h" #include "SpellMgr.h" +#include "World.h" char const* const ConditionMgr::StaticSourceTypeData[CONDITION_SOURCE_TYPE_MAX] = { @@ -290,12 +295,12 @@ bool Condition::Meets(ConditionSourceInfo& sourceInfo) const } case CONDITION_NEAR_CREATURE: { - condMeets = GetClosestCreatureWithEntry(object, ConditionValue1, (float)ConditionValue2, bool(!ConditionValue3)) ? true : false; + condMeets = object->FindNearestCreature(ConditionValue1, (float)ConditionValue2, bool(!ConditionValue3)) != nullptr; break; } case CONDITION_NEAR_GAMEOBJECT: { - condMeets = GetClosestGameObjectWithEntry(object, ConditionValue1, (float)ConditionValue2) ? true : false; + condMeets = object->FindNearestGameObject(ConditionValue1, (float)ConditionValue2) != nullptr; break; } case CONDITION_OBJECT_ENTRY_GUID: @@ -1091,7 +1096,7 @@ void ConditionMgr::LoadConditions(bool isReload) } cond->ReferenceId = uint32(abs(iConditionTypeOrReference)); - const char* rowType = "reference template"; + char const* rowType = "reference template"; if (iSourceTypeOrReferenceId >= 0) rowType = "reference"; //check for useless data diff --git a/src/server/game/Conditions/ConditionMgr.h b/src/server/game/Conditions/ConditionMgr.h index 7c586027aab..f19c5d23973 100644 --- a/src/server/game/Conditions/ConditionMgr.h +++ b/src/server/game/Conditions/ConditionMgr.h @@ -19,7 +19,11 @@ #ifndef TRINITY_CONDITIONMGR_H #define TRINITY_CONDITIONMGR_H -#include "Common.h" +#include "Define.h" +#include "Hash.h" +#include +#include +#include class Creature; class Player; diff --git a/src/server/game/Conditions/DisableMgr.cpp b/src/server/game/Conditions/DisableMgr.cpp index 80665bf781f..6c56566ed44 100644 --- a/src/server/game/Conditions/DisableMgr.cpp +++ b/src/server/game/Conditions/DisableMgr.cpp @@ -18,10 +18,13 @@ #include "DisableMgr.h" #include "AchievementMgr.h" +#include "DatabaseEnv.h" +#include "Log.h" #include "ObjectMgr.h" #include "OutdoorPvP.h" -#include "SpellMgr.h" #include "Player.h" +#include "SpellMgr.h" +#include "VMapManager2.h" #include "World.h" namespace DisableMgr @@ -391,13 +394,13 @@ bool IsDisabledFor(DisableType type, uint32 entry, Unit const* unit, uint8 flags bool IsVMAPDisabledFor(uint32 entry, uint8 flags) { - return IsDisabledFor(DISABLE_TYPE_VMAP, entry, NULL, flags); + return IsDisabledFor(DISABLE_TYPE_VMAP, entry, nullptr, flags); } bool IsPathfindingEnabled(uint32 mapId) { return sWorld->getBoolConfig(CONFIG_ENABLE_MMAPS) - && !IsDisabledFor(DISABLE_TYPE_MMAP, mapId, NULL, MMAP_DISABLE_PATHFINDING); + && !IsDisabledFor(DISABLE_TYPE_MMAP, mapId, nullptr, MMAP_DISABLE_PATHFINDING); } } // Namespace diff --git a/src/server/game/Conditions/DisableMgr.h b/src/server/game/Conditions/DisableMgr.h index 04a77c8c3ae..b7f6aa6bd2a 100644 --- a/src/server/game/Conditions/DisableMgr.h +++ b/src/server/game/Conditions/DisableMgr.h @@ -19,7 +19,6 @@ #ifndef TRINITY_DISABLEMGR_H #define TRINITY_DISABLEMGR_H -#include "VMapManager2.h" #include "Define.h" class Unit; diff --git a/src/server/game/DataStores/DB2Stores.cpp b/src/server/game/DataStores/DB2Stores.cpp index a47b10ae5f9..d1f3f39cd47 100644 --- a/src/server/game/DataStores/DB2Stores.cpp +++ b/src/server/game/DataStores/DB2Stores.cpp @@ -16,11 +16,13 @@ */ #include "DB2Stores.h" +#include "Common.h" #include "DB2fmt.h" #include "DB2Utility.h" -#include "Common.h" +#include "Errors.h" #include "Log.h" #include "World.h" +#include DB2Storage sItemStore(Itemfmt, &DB2Utilities::HasItemEntry, &DB2Utilities::WriteItemDbReply); DB2Storage sItemCurrencyCostStore(ItemCurrencyCostfmt); @@ -135,5 +137,5 @@ DB2StorageBase const* GetDB2Storage(uint32 type) if (itr != DB2Stores.end()) return itr->second; - return NULL; + return nullptr; } diff --git a/src/server/game/DataStores/DB2Utility.cpp b/src/server/game/DataStores/DB2Utility.cpp index 8b411382a5b..e9b483a766c 100644 --- a/src/server/game/DataStores/DB2Utility.cpp +++ b/src/server/game/DataStores/DB2Utility.cpp @@ -20,7 +20,7 @@ inline bool ItemExists(uint32 id) { - return sObjectMgr->GetItemTemplate(id) != NULL; + return sObjectMgr->GetItemTemplate(id) != nullptr; } bool DB2Utilities::HasItemEntry(DB2Storage const& /*store*/, uint32 id) @@ -53,7 +53,7 @@ void DB2Utilities::WriteItemSparseDbReply(DB2Storage const& /*s ItemTemplate const* proto = sObjectMgr->GetItemTemplate(id); ASSERT(proto); - ItemLocale const* localeData = localeConstant ? sObjectMgr->GetItemLocale(id) : NULL; + ItemLocale const* localeData = localeConstant ? sObjectMgr->GetItemLocale(id) : nullptr; buffer << uint32(proto->ItemId); buffer << uint32(proto->Quality); diff --git a/src/server/game/DataStores/DB2Utility.h b/src/server/game/DataStores/DB2Utility.h index d02cd5af075..59b80c683eb 100644 --- a/src/server/game/DataStores/DB2Utility.h +++ b/src/server/game/DataStores/DB2Utility.h @@ -25,6 +25,7 @@ class DB2Storage; class ByteBuffer; struct ItemEntry; struct ItemSparseEntry; +enum LocaleConstant : uint8; namespace DB2Utilities { diff --git a/src/server/game/DataStores/DBCEnums.h b/src/server/game/DataStores/DBCEnums.h index e8a8c2f70a3..18eeb8995f9 100644 --- a/src/server/game/DataStores/DBCEnums.h +++ b/src/server/game/DataStores/DBCEnums.h @@ -19,6 +19,9 @@ #ifndef DBCENUMS_H #define DBCENUMS_H +#include "Define.h" +#include + enum LevelLimit { // Client expected level limitation, like as used in DBC item max levels for "until max player level" @@ -172,7 +175,7 @@ enum AchievementCriteriaFlags ACHIEVEMENT_CRITERIA_FLAG_MONEY_COUNTER = 0x00000020 // Displays counter as money }; -enum AchievementCriteriaTimedTypes +enum AchievementCriteriaTimedTypes : uint8 { ACHIEVEMENT_TIMED_TYPE_EVENT = 1, // Timer is started by internal event with id in timerStartEvent ACHIEVEMENT_TIMED_TYPE_QUEST = 2, // Timer is started by accepting quest with entry in timerStartEvent @@ -185,7 +188,7 @@ enum AchievementCriteriaTimedTypes ACHIEVEMENT_TIMED_TYPE_MAX }; -enum AchievementCriteriaTypes +enum AchievementCriteriaTypes : uint8 { ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE = 0, ACHIEVEMENT_CRITERIA_TYPE_WIN_BG = 1, @@ -353,7 +356,7 @@ enum AreaMountFlags AREA_MOUNT_FLAG_UNDERWATER_ALLOWED = 0x8 }; -enum Difficulty +enum Difficulty : uint8 { REGULAR_DIFFICULTY = 0, @@ -500,6 +503,25 @@ enum SpellCategoryFlags SPELL_CATEGORY_FLAG_COOLDOWN_EXPIRES_AT_DAILY_RESET = 0x08 }; +#define MAX_SPELL_EFFECTS 3 +#define MAX_EFFECT_MASK 7 +#define MAX_SPELL_REAGENTS 8 + +enum EnchantmentSlotMask +{ + ENCHANTMENT_CAN_SOULBOUND = 0x01, + ENCHANTMENT_UNK1 = 0x02, + ENCHANTMENT_UNK2 = 0x04, + ENCHANTMENT_UNK3 = 0x08 +}; + +#define MAX_TALENT_RANK 5 +#define MAX_PET_TALENT_RANK 3 // use in calculations, expected <= MAX_TALENT_RANK +#define MAX_TALENT_TABS 3 + +#define TaxiMaskSize 114 +typedef std::array TaxiMask; + enum TotemCategoryType { TOTEM_CATEGORY_TYPE_KNIFE = 1, diff --git a/src/server/game/DataStores/DBCStores.cpp b/src/server/game/DataStores/DBCStores.cpp index 6a608eff843..69bf3a8a371 100644 --- a/src/server/game/DataStores/DBCStores.cpp +++ b/src/server/game/DataStores/DBCStores.cpp @@ -17,39 +17,28 @@ */ #include "DBCStores.h" -#include "Log.h" -#include "SharedDefines.h" -#include "SpellMgr.h" -#include "TransportMgr.h" +#include "Containers.h" +#include "DBCFileLoader.h" #include "DBCfmt.h" +#include "Errors.h" #include "ItemTemplate.h" -#include "Timer.h" +#include "Log.h" #include "ObjectDefines.h" #include "Regex.h" +#include "SharedDefines.h" +#include "SpellMgr.h" +#include "Timer.h" -#include + // temporary hack until includes are sorted out (don't want to pull in Windows.h) +#ifdef GetClassName +#undef GetClassName +#endif typedef std::map AreaFlagByAreaID; typedef std::map AreaFlagByMapID; -struct WMOAreaTableTripple -{ - WMOAreaTableTripple(int32 r, int32 a, int32 g) : groupId(g), rootId(r), adtId(a) - { - } - - bool operator <(const WMOAreaTableTripple& b) const - { - return memcmp(this, &b, sizeof(WMOAreaTableTripple))<0; - } - - // ordered by entropy; that way memcmp will have a minimal medium runtime - int32 groupId; - int32 rootId; - int32 adtId; -}; - -typedef std::map WMOAreaInfoByTripple; +typedef std::tuple WMOAreaTableKey; +typedef std::map WMOAreaInfoByTripple; typedef std::multimap CharSectionsMap; DBCStorage sAreaTableStore(AreaTableEntryfmt); @@ -162,20 +151,15 @@ DBCStorage sLockStore(LockEntryfmt); DBCStorage sMailTemplateStore(MailTemplateEntryfmt); DBCStorage sMapStore(MapEntryfmt); -// DBC used only for initialization sMapDifficultyMap at startup. -DBCStorage sMapDifficultyStore(MapDifficultyEntryfmt); // only for loading MapDifficultyMap sMapDifficultyMap; DBCStorage sMovieStore(MovieEntryfmt); DBCStorage sMountCapabilityStore(MountCapabilityfmt); DBCStorage sMountTypeStore(MountTypefmt); -DBCStorage sNameGenStore(NameGenfmt); NameGenVectorArraysMap sGenNameVectoArraysMap; DBCStorage sNumTalentsAtLevelStore(NumTalentsAtLevelfmt); -DBCStorage sNamesProfanityStore(NamesProfanityEntryfmt); -DBCStorage sNamesReservedStore(NamesReservedEntryfmt); typedef std::array, TOTAL_LOCALES> NameValidationRegexContainer; NameValidationRegexContainer NamesProfaneValidators; NameValidationRegexContainer NamesReservedValidators; @@ -242,8 +226,7 @@ DBCStorage sSummonPropertiesStore(SummonPropertiesfmt); DBCStorage sTalentStore(TalentEntryfmt); TalentSpellPosMap sTalentSpellPosMap; DBCStorage sTalentTabStore(TalentTabEntryfmt); -DBCStorage sTalentTreePrimarySpellsStore(TalentTreePrimarySpellsfmt); -typedef std::map > TalentTreePrimarySpellsMap; +typedef std::map> TalentTreePrimarySpellsMap; TalentTreePrimarySpellsMap sTalentTreePrimarySpellsMap; // store absolute bit position for first rank for talent inspect @@ -256,13 +239,12 @@ TaxiMask sHordeTaxiNodesMask; TaxiMask sAllianceTaxiNodesMask; TaxiMask sDeathKnightTaxiNodesMask; -// DBC used only for initialization sTaxiPathSetBySource at startup. TaxiPathSetBySource sTaxiPathSetBySource; DBCStorage sTaxiPathStore(TaxiPathEntryfmt); // DBC used only for initialization sTaxiPathNodeStore at startup. TaxiPathNodesByPath sTaxiPathNodesByPath; -static DBCStorage sTaxiPathNodeStore(TaxiPathNodeEntryfmt); +DBCStorage sTaxiPathNodeStore(TaxiPathNodeEntryfmt); DBCStorage sTotemCategoryStore(TotemCategoryEntryfmt); DBCStorage sTransportAnimationStore(TransportAnimationfmt); @@ -275,7 +257,6 @@ DBCStorage sWorldMapAreaStore(WorldMapAreaEntryfmt); DBCStorage sWorldMapOverlayStore(WorldMapOverlayEntryfmt); DBCStorage sWorldSafeLocsStore(WorldSafeLocsEntryfmt); DBCStorage sPhaseStore(PhaseEntryfmt); -DBCStorage sPhaseGroupStore(PhaseGroupfmt); PhaseGroupContainer sPhasesByGroup; @@ -292,18 +273,15 @@ static bool LoadDBC_assert_print(uint32 fsize, uint32 rsize, const std::string& } template -inline void LoadDBC(uint32& availableDbcLocales, StoreProblemList& errors, DBCStorage& storage, std::string const& dbcPath, std::string const& filename, std::string const* customFormat = NULL, std::string const* customIndexName = NULL) +inline void LoadDBC(uint32& availableDbcLocales, StoreProblemList& errors, DBCStorage& storage, std::string const& dbcPath, std::string const& filename, std::string const& customFormat = std::string(), std::string const& customIndexName = std::string()) { // compatibility format and C++ structure sizes ASSERT(DBCFileLoader::GetFormatRecordSize(storage.GetFormat()) == sizeof(T) || LoadDBC_assert_print(DBCFileLoader::GetFormatRecordSize(storage.GetFormat()), sizeof(T), filename)); ++DBCFileCount; std::string dbcFilename = dbcPath + filename; - SqlDbc * sql = NULL; - if (customFormat) - sql = new SqlDbc(&filename, customFormat, customIndexName, storage.GetFormat()); - if (storage.Load(dbcFilename.c_str(), sql)) + if (storage.Load(dbcFilename)) { for (uint8 i = 0; i < TOTAL_LOCALES; ++i) { @@ -316,8 +294,11 @@ inline void LoadDBC(uint32& availableDbcLocales, StoreProblemList& errors, DBCSt localizedName.append(filename); if (!storage.LoadStringsFrom(localizedName.c_str())) - availableDbcLocales &= ~(1< sMapDifficultyStore(MapDifficultyEntryfmt); + DBCStorage sNameGenStore(NameGenfmt); + DBCStorage sNamesProfanityStore(NamesProfanityEntryfmt); + DBCStorage sNamesReservedStore(NamesReservedEntryfmt); + DBCStorage sPhaseGroupStore(PhaseGroupfmt); + DBCStorage sTalentTreePrimarySpellsStore(TalentTreePrimarySpellsfmt); - LoadDBC(availableDbcLocales, bad_dbc_files, sAchievementStore, dbcPath, "Achievement.dbc", &CustomAchievementfmt, &CustomAchievementIndex);//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sAnimKitStore, dbcPath, "AnimKit.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sAchievementCriteriaStore, dbcPath, "Achievement_Criteria.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sAreaTriggerStore, dbcPath, "AreaTrigger.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sAreaGroupStore, dbcPath, "AreaGroup.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sAreaPOIStore, dbcPath, "AreaPOI.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sAuctionHouseStore, dbcPath, "AuctionHouse.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sArmorLocationStore, dbcPath, "ArmorLocation.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sBankBagSlotPricesStore, dbcPath, "BankBagSlotPrices.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sBannedAddOnsStore, dbcPath, "BannedAddOns.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sBattlemasterListStore, dbcPath, "BattlemasterList.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sBarberShopStyleStore, dbcPath, "BarberShopStyle.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sCharStartOutfitStore, dbcPath, "CharStartOutfit.dbc");//15595 - for (uint32 i = 0; i < sCharStartOutfitStore.GetNumRows(); ++i) - if (CharStartOutfitEntry const* outfit = sCharStartOutfitStore.LookupEntry(i)) - sCharStartOutfitMap[outfit->Race | (outfit->Class << 8) | (outfit->Gender << 16)] = outfit; +#define LOAD_DBC(store, file) LoadDBC(availableDbcLocales, bad_dbc_files, store, dbcPath, file) - LoadDBC(availableDbcLocales, bad_dbc_files, sCharSectionsStore, dbcPath, "CharSections.dbc"); - for (uint32 i = 0; i < sCharSectionsStore.GetNumRows(); ++i) - if (CharSectionsEntry const* entry = sCharSectionsStore.LookupEntry(i)) - if (entry->Race && ((1 << (entry->Race - 1)) & RACEMASK_ALL_PLAYABLE) != 0) //ignore Nonplayable races - sCharSectionMap.insert({ entry->GenType | (entry->Gender << 8) | (entry->Race << 16), entry }); + LOAD_DBC(sAreaTableStore, "AreaTable.dbc"); + LOAD_DBC(sAnimKitStore, "AnimKit.dbc");//15595 + LOAD_DBC(sAchievementCriteriaStore, "Achievement_Criteria.dbc");//15595 + LOAD_DBC(sAreaTriggerStore, "AreaTrigger.dbc");//15595 + LOAD_DBC(sAreaGroupStore, "AreaGroup.dbc");//15595 + LOAD_DBC(sAreaPOIStore, "AreaPOI.dbc");//15595 + LOAD_DBC(sAuctionHouseStore, "AuctionHouse.dbc");//15595 + LOAD_DBC(sArmorLocationStore, "ArmorLocation.dbc");//15595 + LOAD_DBC(sBankBagSlotPricesStore, "BankBagSlotPrices.dbc");//15595 + LOAD_DBC(sBannedAddOnsStore, "BannedAddOns.dbc"); + LOAD_DBC(sBattlemasterListStore, "BattlemasterList.dbc");//15595 + LOAD_DBC(sBarberShopStyleStore, "BarberShopStyle.dbc");//15595 + LOAD_DBC(sCharStartOutfitStore, "CharStartOutfit.dbc");//15595 + LOAD_DBC(sCharSectionsStore, "CharSections.dbc"); + LOAD_DBC(sCharTitlesStore, "CharTitles.dbc");//15595 + LOAD_DBC(sChatChannelsStore, "ChatChannels.dbc");//15595 + LOAD_DBC(sChrClassesStore, "ChrClasses.dbc");//15595 + LOAD_DBC(sChrRacesStore, "ChrRaces.dbc");//15595 + LOAD_DBC(sChrPowerTypesStore, "ChrClassesXPowerTypes.dbc");//15595 + LOAD_DBC(sEmotesTextSoundStore, "EmotesTextSound.dbc"); + LOAD_DBC(sCinematicCameraStore, "CinematicCamera.dbc"); + LOAD_DBC(sCinematicSequencesStore, "CinematicSequences.dbc");//15595 + LOAD_DBC(sCreatureDisplayInfoStore, "CreatureDisplayInfo.dbc");//15595 + LOAD_DBC(sCreatureDisplayInfoExtraStore, "CreatureDisplayInfoExtra.dbc");//15595 + LOAD_DBC(sCreatureFamilyStore, "CreatureFamily.dbc");//15595 + LOAD_DBC(sCreatureModelDataStore, "CreatureModelData.dbc");//15595 + LOAD_DBC(sCreatureSpellDataStore, "CreatureSpellData.dbc");//15595 + LOAD_DBC(sCreatureTypeStore, "CreatureType.dbc");//15595 + LOAD_DBC(sCurrencyTypesStore, "CurrencyTypes.dbc");//15595 + LOAD_DBC(sDestructibleModelDataStore, "DestructibleModelData.dbc");//15595 + LOAD_DBC(sDungeonEncounterStore, "DungeonEncounter.dbc");//15595 + LOAD_DBC(sDurabilityCostsStore, "DurabilityCosts.dbc");//15595 + LOAD_DBC(sDurabilityQualityStore, "DurabilityQuality.dbc");//15595 + LOAD_DBC(sEmotesStore, "Emotes.dbc");//15595 + LOAD_DBC(sEmotesTextStore, "EmotesText.dbc");//15595 + LOAD_DBC(sFactionStore, "Faction.dbc");//15595 + LOAD_DBC(sFactionTemplateStore, "FactionTemplate.dbc");//15595 + LOAD_DBC(sGameObjectDisplayInfoStore, "GameObjectDisplayInfo.dbc");//15595 + LOAD_DBC(sGemPropertiesStore, "GemProperties.dbc");//15595 + LOAD_DBC(sGlyphPropertiesStore, "GlyphProperties.dbc");//15595 + LOAD_DBC(sGlyphSlotStore, "GlyphSlot.dbc");//15595 + LOAD_DBC(sGtBarberShopCostBaseStore, "gtBarberShopCostBase.dbc");//15595 + LOAD_DBC(sGtCombatRatingsStore, "gtCombatRatings.dbc");//15595 + LOAD_DBC(sGtChanceToMeleeCritBaseStore, "gtChanceToMeleeCritBase.dbc");//15595 + LOAD_DBC(sGtChanceToMeleeCritStore, "gtChanceToMeleeCrit.dbc");//15595 + LOAD_DBC(sGtChanceToSpellCritBaseStore, "gtChanceToSpellCritBase.dbc");//15595 + LOAD_DBC(sGtChanceToSpellCritStore, "gtChanceToSpellCrit.dbc");//15595 + LOAD_DBC(sGtNPCManaCostScalerStore, "gtNPCManaCostScaler.dbc"); + LOAD_DBC(sGtOCTClassCombatRatingScalarStore, "gtOCTClassCombatRatingScalar.dbc");//15595 + //LOAD_DBC(sGtOCTRegenHPStore, "gtOCTRegenHP.dbc");//15595 + LOAD_DBC(sGtOCTHpPerStaminaStore, "gtOCTHpPerStamina.dbc");//15595 + //LOAD_DBC(sGtOCTRegenMPStore, "gtOCTRegenMP.dbc"); -- not used currently + LOAD_DBC(sGtRegenMPPerSptStore, "gtRegenMPPerSpt.dbc");//15595 + LOAD_DBC(sGtSpellScalingStore, "gtSpellScaling.dbc");//15595 + LOAD_DBC(sGtOCTBaseHPByClassStore, "gtOCTBaseHPByClass.dbc");//15595 + LOAD_DBC(sGtOCTBaseMPByClassStore, "gtOCTBaseMPByClass.dbc");//15595 + LOAD_DBC(sGuildPerkSpellsStore, "GuildPerkSpells.dbc");//15595 + LOAD_DBC(sHolidaysStore, "Holidays.dbc");//15595 + LOAD_DBC(sImportPriceArmorStore, "ImportPriceArmor.dbc"); // 15595 + LOAD_DBC(sImportPriceQualityStore, "ImportPriceQuality.dbc"); // 15595 + LOAD_DBC(sImportPriceShieldStore, "ImportPriceShield.dbc"); // 15595 + LOAD_DBC(sImportPriceWeaponStore, "ImportPriceWeapon.dbc"); // 15595 + LOAD_DBC(sItemPriceBaseStore, "ItemPriceBase.dbc"); // 15595 + LOAD_DBC(sItemReforgeStore, "ItemReforge.dbc"); // 15595 + LOAD_DBC(sItemBagFamilyStore, "ItemBagFamily.dbc");//15595 + LOAD_DBC(sItemClassStore, "ItemClass.dbc"); // 15595 + //LOAD_DBC(sItemDisplayInfoStore, "ItemDisplayInfo.dbc"); -- not used currently + LOAD_DBC(sItemLimitCategoryStore, "ItemLimitCategory.dbc");//15595 + LOAD_DBC(sItemRandomPropertiesStore, "ItemRandomProperties.dbc");//15595 + LOAD_DBC(sItemRandomSuffixStore, "ItemRandomSuffix.dbc");//15595 + LOAD_DBC(sItemSetStore, "ItemSet.dbc");//15595 + LOAD_DBC(sItemArmorQualityStore, "ItemArmorQuality.dbc");//15595 + LOAD_DBC(sItemArmorShieldStore, "ItemArmorShield.dbc");//15595 + LOAD_DBC(sItemArmorTotalStore, "ItemArmorTotal.dbc");//15595 + LOAD_DBC(sItemDamageAmmoStore, "ItemDamageAmmo.dbc");//15595 + LOAD_DBC(sItemDamageOneHandStore, "ItemDamageOneHand.dbc");//15595 + LOAD_DBC(sItemDamageOneHandCasterStore, "ItemDamageOneHandCaster.dbc");//15595 + LOAD_DBC(sItemDamageRangedStore, "ItemDamageRanged.dbc");//15595 + LOAD_DBC(sItemDamageThrownStore, "ItemDamageThrown.dbc");//15595 + LOAD_DBC(sItemDamageTwoHandStore, "ItemDamageTwoHand.dbc");//15595 + LOAD_DBC(sItemDamageTwoHandCasterStore, "ItemDamageTwoHandCaster.dbc");//15595 + LOAD_DBC(sItemDamageWandStore, "ItemDamageWand.dbc");//15595 + LOAD_DBC(sItemDisenchantLootStore, "ItemDisenchantLoot.dbc"); + LOAD_DBC(sLFGDungeonStore, "LFGDungeons.dbc");//15595 + LOAD_DBC(sLightStore, "Light.dbc"); //15595 + LOAD_DBC(sLiquidTypeStore, "LiquidType.dbc");//15595 + LOAD_DBC(sLockStore, "Lock.dbc");//15595 + LOAD_DBC(sMailTemplateStore, "MailTemplate.dbc");//15595 + LOAD_DBC(sMapStore, "Map.dbc");//15595 + LOAD_DBC(sMapDifficultyStore, "MapDifficulty.dbc");//15595 + LOAD_DBC(sMountCapabilityStore, "MountCapability.dbc");//15595 + LOAD_DBC(sMountTypeStore, "MountType.dbc");//15595 + LOAD_DBC(sNumTalentsAtLevelStore, "NumTalentsAtLevel.dbc");//15595 + LOAD_DBC(sMovieStore, "Movie.dbc");//15595 + LOAD_DBC(sOverrideSpellDataStore, "OverrideSpellData.dbc");//15595 + LOAD_DBC(sNamesProfanityStore, "NamesProfanity.dbc"); + LOAD_DBC(sNamesReservedStore, "NamesReserved.dbc"); + LOAD_DBC(sNameGenStore, "NameGen.dbc");//15595 + LOAD_DBC(sPhaseStore, "Phase.dbc"); // 15595 + LOAD_DBC(sPhaseGroupStore, "PhaseXPhaseGroup.dbc"); // 15595 + LOAD_DBC(sPowerDisplayStore, "PowerDisplay.dbc"); + LOAD_DBC(sPvPDifficultyStore, "PvpDifficulty.dbc");//15595 + LOAD_DBC(sQuestXPStore, "QuestXP.dbc");//15595 + LOAD_DBC(sQuestFactionRewardStore, "QuestFactionReward.dbc");//15595 + LOAD_DBC(sQuestPOIBlobStore, "QuestPOIBlob.dbc");//15595 + LOAD_DBC(sQuestPOIPointStore, "QuestPOIPoint.dbc");//15595 + LOAD_DBC(sQuestSortStore, "QuestSort.dbc");//15595 + LOAD_DBC(sRandomPropertiesPointsStore, "RandPropPoints.dbc");//15595 + LOAD_DBC(sResearchBranchStore, "ResearchBranch.dbc");//15595 + LOAD_DBC(sResearchFieldStore, "ResearchField.dbc");//15595 + LOAD_DBC(sResearchProjectStore, "ResearchProject.dbc");//15595 + LOAD_DBC(sResearchSiteStore, "ResearchSite.dbc");//15595 + LOAD_DBC(sScalingStatDistributionStore, "ScalingStatDistribution.dbc");//15595 + LOAD_DBC(sScalingStatValuesStore, "ScalingStatValues.dbc");//15595 + LOAD_DBC(sSkillLineStore, "SkillLine.dbc");//15595 + LOAD_DBC(sSkillLineAbilityStore, "SkillLineAbility.dbc");//15595 + LOAD_DBC(sSkillRaceClassInfoStore, "SkillRaceClassInfo.dbc"); + LOAD_DBC(sSkillTiersStore, "SkillTiers.dbc"); + LOAD_DBC(sSoundEntriesStore, "SoundEntries.dbc");//15595 + LOAD_DBC(sSpellCategoriesStore, "SpellCategories.dbc");//15595 + LOAD_DBC(sSpellCategoryStore, "SpellCategory.dbc"); + LOAD_DBC(sSpellReagentsStore, "SpellReagents.dbc");//15595 + LOAD_DBC(sSpellScalingStore, "SpellScaling.dbc");//15595 + LOAD_DBC(sSpellTotemsStore, "SpellTotems.dbc");//15595 + LOAD_DBC(sSpellTargetRestrictionsStore, "SpellTargetRestrictions.dbc");//15595 + LOAD_DBC(sSpellPowerStore, "SpellPower.dbc");//15595 + LOAD_DBC(sSpellLevelsStore, "SpellLevels.dbc");//15595 + LOAD_DBC(sSpellInterruptsStore, "SpellInterrupts.dbc");//15595 + LOAD_DBC(sSpellEquippedItemsStore, "SpellEquippedItems.dbc");//15595 + LOAD_DBC(sSpellClassOptionsStore, "SpellClassOptions.dbc");//15595 + LOAD_DBC(sSpellCooldownsStore, "SpellCooldowns.dbc");//15595 + LOAD_DBC(sSpellAuraOptionsStore, "SpellAuraOptions.dbc");//15595 + LOAD_DBC(sSpellAuraRestrictionsStore, "SpellAuraRestrictions.dbc");//15595 + LOAD_DBC(sSpellCastingRequirementsStore, "SpellCastingRequirements.dbc");//15595 + LOAD_DBC(sSpellCastTimesStore, "SpellCastTimes.dbc");//15595 + LOAD_DBC(sSpellDurationStore, "SpellDuration.dbc");//15595 + LOAD_DBC(sSpellFocusObjectStore, "SpellFocusObject.dbc");//15595 + LOAD_DBC(sSpellItemEnchantmentStore, "SpellItemEnchantment.dbc");//15595 + LOAD_DBC(sSpellItemEnchantmentConditionStore, "SpellItemEnchantmentCondition.dbc");//15595 + LOAD_DBC(sSpellRadiusStore, "SpellRadius.dbc");//15595 + LOAD_DBC(sSpellRangeStore, "SpellRange.dbc");//15595 + LOAD_DBC(sSpellRuneCostStore, "SpellRuneCost.dbc");//15595 + LOAD_DBC(sSpellShapeshiftStore, "SpellShapeshift.dbc");//15595 + LOAD_DBC(sSpellShapeshiftFormStore, "SpellShapeshiftForm.dbc");//15595 + //LOAD_DBC(sStableSlotPricesStore, "StableSlotPrices.dbc"); + LOAD_DBC(sSummonPropertiesStore, "SummonProperties.dbc");//15595 + LOAD_DBC(sTalentStore, "Talent.dbc");//15595 + LOAD_DBC(sTalentTabStore, "TalentTab.dbc");//15595 + LOAD_DBC(sTalentTreePrimarySpellsStore, "TalentTreePrimarySpells.dbc"); + LOAD_DBC(sTaxiNodesStore, "TaxiNodes.dbc");//15595 + LOAD_DBC(sTaxiPathStore, "TaxiPath.dbc");//15595 + LOAD_DBC(sTaxiPathNodeStore, "TaxiPathNode.dbc");//15595 + //LOAD_DBC(sTeamContributionPointsStore, "TeamContributionPoints.dbc"); + LOAD_DBC(sTotemCategoryStore, "TotemCategory.dbc");//15595 + LOAD_DBC(sTransportAnimationStore, "TransportAnimation.dbc"); + LOAD_DBC(sTransportRotationStore, "TransportRotation.dbc"); + LOAD_DBC(sUnitPowerBarStore, "UnitPowerBar.dbc");//15595 + LOAD_DBC(sVehicleStore, "Vehicle.dbc");//15595 + LOAD_DBC(sVehicleSeatStore, "VehicleSeat.dbc");//15595 + LOAD_DBC(sWMOAreaTableStore, "WMOAreaTable.dbc");//15595 + LOAD_DBC(sWorldMapAreaStore, "WorldMapArea.dbc");//15595 + LOAD_DBC(sWorldMapOverlayStore, "WorldMapOverlay.dbc");//15595 + LOAD_DBC(sWorldSafeLocsStore, "WorldSafeLocs.dbc");//15595 + +#undef LOAD_DBC + +#define LOAD_DBC_EXT(store, file, dbformat, dbpk) LoadDBC(availableDbcLocales, bad_dbc_files, store, dbcPath, file, dbformat, dbpk) + + LOAD_DBC_EXT(sAchievementStore, "Achievement.dbc", CustomAchievementfmt, CustomAchievementIndex);//15595 + LOAD_DBC_EXT(sSpellStore, "Spell.dbc", CustomSpellEntryfmt, CustomSpellEntryIndex);// + LOAD_DBC_EXT(sSpellEffectStore, "SpellEffect.dbc", CustomSpellEffectEntryfmt, CustomSpellEffectEntryIndex);//15595 + LOAD_DBC_EXT(sSpellDifficultyStore, "SpellDifficulty.dbc", CustomSpellDifficultyfmt, CustomSpellDifficultyIndex);//15595 + +#undef LOAD_DBC_EXT + + for (CharStartOutfitEntry const* outfit : sCharStartOutfitStore) + sCharStartOutfitMap[outfit->Race | (outfit->Class << 8) | (outfit->Gender << 16)] = outfit; + + for (CharSectionsEntry const* entry : sCharSectionsStore) + if (entry->Race && ((1 << (entry->Race - 1)) & RACEMASK_ALL_PLAYABLE) != 0) //ignore Nonplayable races + sCharSectionMap.insert({ entry->GenType | (entry->Gender << 8) | (entry->Race << 16), entry }); - LoadDBC(availableDbcLocales, bad_dbc_files, sCharTitlesStore, dbcPath, "CharTitles.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sChatChannelsStore, dbcPath, "ChatChannels.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sChrClassesStore, dbcPath, "ChrClasses.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sChrRacesStore, dbcPath, "ChrRaces.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sChrPowerTypesStore, dbcPath, "ChrClassesXPowerTypes.dbc");//15595 for (uint32 i = 0; i < MAX_CLASSES; ++i) for (uint32 j = 0; j < MAX_POWERS; ++j) PowersByClass[i][j] = MAX_POWERS; @@ -393,135 +534,38 @@ void LoadDBCStores(const std::string& dataPath) } } - LoadDBC(availableDbcLocales, bad_dbc_files, sEmotesTextSoundStore, dbcPath, "EmotesTextSound.dbc"); - for (uint32 i = 0; i < sEmotesTextSoundStore.GetNumRows(); ++i) - if (EmotesTextSoundEntry const* entry = sEmotesTextSoundStore.LookupEntry(i)) - sEmotesTextSoundMap[EmotesTextSoundKey(entry->EmotesTextId, entry->RaceId, entry->SexId)] = entry; - LoadDBC(availableDbcLocales, bad_dbc_files, sCinematicCameraStore, dbcPath, "CinematicCamera.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sCinematicSequencesStore, dbcPath, "CinematicSequences.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sCreatureDisplayInfoStore, dbcPath, "CreatureDisplayInfo.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sCreatureDisplayInfoExtraStore, dbcPath, "CreatureDisplayInfoExtra.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sCreatureFamilyStore, dbcPath, "CreatureFamily.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sCreatureModelDataStore, dbcPath, "CreatureModelData.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sCreatureSpellDataStore, dbcPath, "CreatureSpellData.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sCreatureTypeStore, dbcPath, "CreatureType.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sCurrencyTypesStore, dbcPath, "CurrencyTypes.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sDestructibleModelDataStore, dbcPath, "DestructibleModelData.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sDungeonEncounterStore, dbcPath, "DungeonEncounter.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sDurabilityCostsStore, dbcPath, "DurabilityCosts.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sDurabilityQualityStore, dbcPath, "DurabilityQuality.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sEmotesStore, dbcPath, "Emotes.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sEmotesTextStore, dbcPath, "EmotesText.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sFactionStore, dbcPath, "Faction.dbc");//15595 - for (uint32 i=0; iEmotesTextId, entry->RaceId, entry->SexId)] = entry; + + for (FactionEntry const* faction : sFactionStore) { - FactionEntry const* faction = sFactionStore.LookupEntry(i); - if (faction && faction->team) + if (faction->team) { - SimpleFactionsList &flist = sFactionTeamMap[faction->team]; - flist.push_back(i); + SimpleFactionsList& flist = sFactionTeamMap[faction->team]; + flist.push_back(faction->ID); } } - LoadDBC(availableDbcLocales, bad_dbc_files, sFactionTemplateStore, dbcPath, "FactionTemplate.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sGameObjectDisplayInfoStore, dbcPath, "GameObjectDisplayInfo.dbc");//15595 - for (uint32 i = 0; i < sGameObjectDisplayInfoStore.GetNumRows(); ++i) + for (GameObjectDisplayInfoEntry const* info : sGameObjectDisplayInfoStore) { - if (GameObjectDisplayInfoEntry const* info = sGameObjectDisplayInfoStore.LookupEntry(i)) - { - if (info->maxX < info->minX) - std::swap(*(float*)(&info->maxX), *(float*)(&info->minX)); - if (info->maxY < info->minY) - std::swap(*(float*)(&info->maxY), *(float*)(&info->minY)); - if (info->maxZ < info->minZ) - std::swap(*(float*)(&info->maxZ), *(float*)(&info->minZ)); - } + if (info->maxX < info->minX) + std::swap(*(float*)(&info->maxX), *(float*)(&info->minX)); + if (info->maxY < info->minY) + std::swap(*(float*)(&info->maxY), *(float*)(&info->minY)); + if (info->maxZ < info->minZ) + std::swap(*(float*)(&info->maxZ), *(float*)(&info->minZ)); } - LoadDBC(availableDbcLocales, bad_dbc_files, sGemPropertiesStore, dbcPath, "GemProperties.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sGlyphPropertiesStore, dbcPath, "GlyphProperties.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sGlyphSlotStore, dbcPath, "GlyphSlot.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sGtBarberShopCostBaseStore, dbcPath, "gtBarberShopCostBase.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sGtCombatRatingsStore, dbcPath, "gtCombatRatings.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sGtChanceToMeleeCritBaseStore, dbcPath, "gtChanceToMeleeCritBase.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sGtChanceToMeleeCritStore, dbcPath, "gtChanceToMeleeCrit.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sGtChanceToSpellCritBaseStore, dbcPath, "gtChanceToSpellCritBase.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sGtChanceToSpellCritStore, dbcPath, "gtChanceToSpellCrit.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sGtNPCManaCostScalerStore, dbcPath, "gtNPCManaCostScaler.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sGtOCTClassCombatRatingScalarStore, dbcPath, "gtOCTClassCombatRatingScalar.dbc");//15595 - //LoadDBC(availableDbcLocales, bad_dbc_files, sGtOCTRegenHPStore, dbcPath, "gtOCTRegenHP.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sGtOCTHpPerStaminaStore, dbcPath, "gtOCTHpPerStamina.dbc");//15595 - //LoadDBC(dbcCount, availableDbcLocales, bad_dbc_files, sGtOCTRegenMPStore, dbcPath, "gtOCTRegenMP.dbc"); -- not used currently - LoadDBC(availableDbcLocales, bad_dbc_files, sGtRegenMPPerSptStore, dbcPath, "gtRegenMPPerSpt.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sGtSpellScalingStore, dbcPath, "gtSpellScaling.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sGtOCTBaseHPByClassStore, dbcPath, "gtOCTBaseHPByClass.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sGtOCTBaseMPByClassStore, dbcPath, "gtOCTBaseMPByClass.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sGuildPerkSpellsStore, dbcPath, "GuildPerkSpells.dbc");//15595 - - LoadDBC(availableDbcLocales, bad_dbc_files, sHolidaysStore, dbcPath, "Holidays.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sImportPriceArmorStore, dbcPath, "ImportPriceArmor.dbc"); // 15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sImportPriceQualityStore, dbcPath, "ImportPriceQuality.dbc"); // 15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sImportPriceShieldStore, dbcPath, "ImportPriceShield.dbc"); // 15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sImportPriceWeaponStore, dbcPath, "ImportPriceWeapon.dbc"); // 15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sItemPriceBaseStore, dbcPath, "ItemPriceBase.dbc"); // 15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sItemReforgeStore, dbcPath, "ItemReforge.dbc"); // 15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sItemBagFamilyStore, dbcPath, "ItemBagFamily.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sItemClassStore, dbcPath, "ItemClass.dbc"); // 15595 - //LoadDBC(dbcCount, availableDbcLocales, bad_dbc_files, sItemDisplayInfoStore, dbcPath, "ItemDisplayInfo.dbc"); -- not used currently - LoadDBC(availableDbcLocales, bad_dbc_files, sItemLimitCategoryStore, dbcPath, "ItemLimitCategory.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sItemRandomPropertiesStore, dbcPath, "ItemRandomProperties.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sItemRandomSuffixStore, dbcPath, "ItemRandomSuffix.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sItemSetStore, dbcPath, "ItemSet.dbc");//15595 - - LoadDBC(availableDbcLocales, bad_dbc_files, sItemArmorQualityStore, dbcPath, "ItemArmorQuality.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sItemArmorShieldStore, dbcPath, "ItemArmorShield.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sItemArmorTotalStore, dbcPath, "ItemArmorTotal.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sItemDamageAmmoStore, dbcPath, "ItemDamageAmmo.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sItemDamageOneHandStore, dbcPath, "ItemDamageOneHand.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sItemDamageOneHandCasterStore, dbcPath, "ItemDamageOneHandCaster.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sItemDamageRangedStore, dbcPath, "ItemDamageRanged.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sItemDamageThrownStore, dbcPath, "ItemDamageThrown.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sItemDamageTwoHandStore, dbcPath, "ItemDamageTwoHand.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sItemDamageTwoHandCasterStore, dbcPath, "ItemDamageTwoHandCaster.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sItemDamageWandStore, dbcPath, "ItemDamageWand.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sItemDisenchantLootStore, dbcPath, "ItemDisenchantLoot.dbc"); - - LoadDBC(availableDbcLocales, bad_dbc_files, sLFGDungeonStore, dbcPath, "LFGDungeons.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sLightStore, dbcPath, "Light.dbc"); //15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sLiquidTypeStore, dbcPath, "LiquidType.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sLockStore, dbcPath, "Lock.dbc");//15595 - - LoadDBC(availableDbcLocales, bad_dbc_files, sMailTemplateStore, dbcPath, "MailTemplate.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sMapStore, dbcPath, "Map.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sMapDifficultyStore, dbcPath, "MapDifficulty.dbc");//15595 // fill data - sMapDifficultyMap[MAKE_PAIR32(0, 0)] = MapDifficulty(0, 0, false);//map 0 is missingg from MapDifficulty.dbc use this till its ported to sql - for (uint32 i = 0; i < sMapDifficultyStore.GetNumRows(); ++i) - if (MapDifficultyEntry const* entry = sMapDifficultyStore.LookupEntry(i)) - sMapDifficultyMap[MAKE_PAIR32(entry->MapId, entry->Difficulty)] = MapDifficulty(entry->resetTime, entry->maxPlayers, entry->areaTriggerText[0] > 0); - sMapDifficultyStore.Clear(); + sMapDifficultyMap[MAKE_PAIR32(0, 0)] = MapDifficulty(0, 0, false);//map 0 is missing from MapDifficulty.dbc use this till its ported to sql + for (MapDifficultyEntry const* entry : sMapDifficultyStore) + sMapDifficultyMap[MAKE_PAIR32(entry->MapId, entry->Difficulty)] = MapDifficulty(entry->resetTime, entry->maxPlayers, entry->areaTriggerText[0] > 0); - LoadDBC(availableDbcLocales, bad_dbc_files, sMountCapabilityStore, dbcPath, "MountCapability.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sMountTypeStore, dbcPath, "MountType.dbc");//15595 + for (NameGenEntry const* entry : sNameGenStore) + sGenNameVectoArraysMap[entry->race].stringVectorArray[entry->gender].push_back(std::string(entry->name)); - LoadDBC(availableDbcLocales, bad_dbc_files, sNameGenStore, dbcPath, "NameGen.dbc");//15595 - for (uint32 i = 0; i < sNameGenStore.GetNumRows(); ++i) - if (NameGenEntry const* entry = sNameGenStore.LookupEntry(i)) - sGenNameVectoArraysMap[entry->race].stringVectorArray[entry->gender].push_back(std::string(entry->name)); - sNameGenStore.Clear(); - - LoadDBC(availableDbcLocales, bad_dbc_files, sNumTalentsAtLevelStore, dbcPath, "NumTalentsAtLevel.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sMovieStore, dbcPath, "Movie.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sOverrideSpellDataStore, dbcPath, "OverrideSpellData.dbc");//15595 - - LoadDBC(availableDbcLocales, bad_dbc_files, sNamesProfanityStore, dbcPath, "NamesProfanity.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sNamesReservedStore, dbcPath, "NamesReserved.dbc"); - for (uint32 i = 0; i < sNamesProfanityStore.GetNumRows(); ++i) + for (NamesProfanityEntry const* namesProfanity : sNamesProfanityStore) { - NamesProfanityEntry const* namesProfanity = sNamesProfanityStore.LookupEntry(i); - if (!namesProfanity) - continue; - ASSERT(namesProfanity->Language < TOTAL_LOCALES || namesProfanity->Language == -1); std::wstring wname; bool conversionResult = Utf8toWStr(namesProfanity->Name, wname); @@ -534,12 +578,8 @@ void LoadDBCStores(const std::string& dataPath) NamesProfaneValidators[i].emplace_back(wname, Trinity::regex::perl | Trinity::regex::icase | Trinity::regex::optimize); } - for (uint32 i = 0; i < sNamesReservedStore.GetNumRows(); ++i) + for (NamesReservedEntry const* namesReserved : sNamesReservedStore) { - NamesReservedEntry const* namesReserved = sNamesReservedStore.LookupEntry(i); - if (!namesReserved) - continue; - ASSERT(namesReserved->Language < TOTAL_LOCALES || namesReserved->Language == -1); std::wstring wname; bool conversionResult = Utf8toWStr(namesReserved->Name, wname); @@ -552,85 +592,21 @@ void LoadDBCStores(const std::string& dataPath) NamesReservedValidators[i].emplace_back(wname, Trinity::regex::perl | Trinity::regex::icase | Trinity::regex::optimize); } - LoadDBC(availableDbcLocales, bad_dbc_files, sPhaseStore, dbcPath, "Phase.dbc"); // 15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sPhaseGroupStore, dbcPath, "PhaseXPhaseGroup.dbc"); // 15595 + for (PhaseGroupEntry const* group : sPhaseGroupStore) + if (PhaseEntry const* phase = sPhaseStore.LookupEntry(group->PhaseId)) + sPhasesByGroup[group->GroupId].push_back(phase->ID); - for (uint32 i = 0; i < sPhaseGroupStore.GetNumRows(); ++i) - if (PhaseGroupEntry const* group = sPhaseGroupStore.LookupEntry(i)) - if (PhaseEntry const* phase = sPhaseStore.LookupEntry(group->PhaseId)) - sPhasesByGroup[group->GroupId].push_back(phase->ID); + for (PvPDifficultyEntry const* entry : sPvPDifficultyStore) + if (entry->bracketId > MAX_BATTLEGROUND_BRACKETS) + ASSERT(false && "Need update MAX_BATTLEGROUND_BRACKETS by DBC data"); - LoadDBC(availableDbcLocales, bad_dbc_files, sPowerDisplayStore, dbcPath, "PowerDisplay.dbc"); - - LoadDBC(availableDbcLocales, bad_dbc_files, sPvPDifficultyStore, dbcPath, "PvpDifficulty.dbc");//15595 - - for (uint32 i = 0; i < sPvPDifficultyStore.GetNumRows(); ++i) - if (PvPDifficultyEntry const* entry = sPvPDifficultyStore.LookupEntry(i)) - if (entry->bracketId > MAX_BATTLEGROUND_BRACKETS) - ASSERT(false && "Need update MAX_BATTLEGROUND_BRACKETS by DBC data"); - - LoadDBC(availableDbcLocales, bad_dbc_files, sQuestXPStore, dbcPath, "QuestXP.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sQuestFactionRewardStore, dbcPath, "QuestFactionReward.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sQuestPOIBlobStore, dbcPath, "QuestPOIBlob.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sQuestPOIPointStore, dbcPath, "QuestPOIPoint.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sQuestSortStore, dbcPath, "QuestSort.dbc");//15595 - - LoadDBC(availableDbcLocales, bad_dbc_files, sRandomPropertiesPointsStore, dbcPath, "RandPropPoints.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sResearchBranchStore, dbcPath, "ResearchBranch.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sResearchFieldStore, dbcPath, "ResearchField.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sResearchProjectStore, dbcPath, "ResearchProject.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sResearchSiteStore, dbcPath, "ResearchSite.dbc");//15595 - - LoadDBC(availableDbcLocales, bad_dbc_files, sScalingStatDistributionStore, dbcPath, "ScalingStatDistribution.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sScalingStatValuesStore, dbcPath, "ScalingStatValues.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSkillLineStore, dbcPath, "SkillLine.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSkillLineAbilityStore, dbcPath, "SkillLineAbility.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSkillRaceClassInfoStore, dbcPath, "SkillRaceClassInfo.dbc"); - for (uint32 i = 0; i < sSkillRaceClassInfoStore.GetNumRows(); ++i) - if (SkillRaceClassInfoEntry const* entry = sSkillRaceClassInfoStore.LookupEntry(i)) - if (sSkillLineStore.LookupEntry(entry->SkillId)) - SkillRaceClassInfoBySkill.emplace(entry->SkillId, entry); - - LoadDBC(availableDbcLocales, bad_dbc_files, sSkillTiersStore, dbcPath, "SkillTiers.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sSoundEntriesStore, dbcPath, "SoundEntries.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellStore, dbcPath, "Spell.dbc", &CustomSpellEntryfmt, &CustomSpellEntryIndex);// - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellCategoriesStore, dbcPath,"SpellCategories.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellCategoryStore, dbcPath, "SpellCategory.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellReagentsStore, dbcPath,"SpellReagents.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellScalingStore, dbcPath,"SpellScaling.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellTotemsStore, dbcPath,"SpellTotems.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellTargetRestrictionsStore, dbcPath,"SpellTargetRestrictions.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellPowerStore, dbcPath,"SpellPower.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellLevelsStore, dbcPath,"SpellLevels.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellInterruptsStore, dbcPath,"SpellInterrupts.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellEquippedItemsStore, dbcPath,"SpellEquippedItems.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellClassOptionsStore, dbcPath,"SpellClassOptions.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellCooldownsStore, dbcPath,"SpellCooldowns.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellAuraOptionsStore, dbcPath,"SpellAuraOptions.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellAuraRestrictionsStore, dbcPath,"SpellAuraRestrictions.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellCastingRequirementsStore, dbcPath,"SpellCastingRequirements.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellEffectStore, dbcPath,"SpellEffect.dbc", &CustomSpellEffectEntryfmt, &CustomSpellEffectEntryIndex);//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellCastTimesStore, dbcPath, "SpellCastTimes.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellDifficultyStore, dbcPath, "SpellDifficulty.dbc", &CustomSpellDifficultyfmt, &CustomSpellDifficultyIndex);//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellDurationStore, dbcPath, "SpellDuration.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellFocusObjectStore, dbcPath, "SpellFocusObject.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellItemEnchantmentStore, dbcPath, "SpellItemEnchantment.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellItemEnchantmentConditionStore, dbcPath, "SpellItemEnchantmentCondition.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellRadiusStore, dbcPath, "SpellRadius.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellRangeStore, dbcPath, "SpellRange.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellRuneCostStore, dbcPath, "SpellRuneCost.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellShapeshiftStore, dbcPath, "SpellShapeshift.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sSpellShapeshiftFormStore, dbcPath, "SpellShapeshiftForm.dbc");//15595 - //LoadDBC(availableDbcLocales, bad_dbc_files, sStableSlotPricesStore, dbcPath, "StableSlotPrices.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sSummonPropertiesStore, dbcPath, "SummonProperties.dbc");//15595 + for (SkillRaceClassInfoEntry const* entry : sSkillRaceClassInfoStore) + if (sSkillLineStore.LookupEntry(entry->SkillId)) + SkillRaceClassInfoBySkill.emplace(entry->SkillId, entry); // Must be done when sSkillLineAbilityStore, sSpellStore, sSpellLevelsStore and sCreatureFamilyStore are all loaded - for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j) + for (SkillLineAbilityEntry const* skillLine : sSkillLineAbilityStore) { - SkillLineAbilityEntry const* skillLine = sSkillLineAbilityStore.LookupEntry(j); - if (!skillLine) - continue; - SpellEntry const* spellInfo = sSpellStore.LookupEntry(skillLine->spellId); if (!spellInfo) continue; @@ -641,34 +617,24 @@ void LoadDBCStores(const std::string& dataPath) if (spellInfo && spellInfo->Attributes & SPELL_ATTR0_PASSIVE) { - for (uint32 i = 1; i < sCreatureFamilyStore.GetNumRows(); ++i) + for (CreatureFamilyEntry const* cFamily : sCreatureFamilyStore) { - CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(i); - if (!cFamily) - continue; - if (skillLine->skillId != cFamily->skillLine[0] && skillLine->skillId != cFamily->skillLine[1]) continue; if (skillLine->AutolearnType != SKILL_LINE_ABILITY_LEARNED_ON_SKILL_LEARN) continue; - sPetFamilySpellsStore[i].insert(spellInfo->Id); + sPetFamilySpellsStore[cFamily->ID].insert(spellInfo->Id); } } } - LoadDBC(availableDbcLocales, bad_dbc_files, sTalentStore, dbcPath, "Talent.dbc");//15595 - // Create Spelldifficulty searcher - for (uint32 i = 0; i < sSpellDifficultyStore.GetNumRows(); ++i) + for (SpellDifficultyEntry const* spellDiff : sSpellDifficultyStore) { - SpellDifficultyEntry const* spellDiff = sSpellDifficultyStore.LookupEntry(i); - if (!spellDiff) - continue; - SpellDifficultyEntry newEntry; - memset(newEntry.SpellID, 0, 4*sizeof(uint32)); + memset(newEntry.SpellID, 0, 4 * sizeof(uint32)); for (uint32 x = 0; x < MAX_DIFFICULTY; ++x) { if (spellDiff->SpellID[x] <= 0 || !sSpellStore.LookupEntry(spellDiff->SpellID[x])) @@ -690,28 +656,18 @@ void LoadDBCStores(const std::string& dataPath) } // create talent spells set - for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i) + for (TalentEntry const* talentInfo : sTalentStore) { - TalentEntry const* talentInfo = sTalentStore.LookupEntry(i); - if (!talentInfo) - continue; - - for (int j = 0; j < MAX_TALENT_RANK; j++) + for (uint8 j = 0; j < MAX_TALENT_RANK; ++j) if (talentInfo->RankID[j]) - sTalentSpellPosMap[talentInfo->RankID[j]] = TalentSpellPos(i, j); + sTalentSpellPosMap[talentInfo->RankID[j]] = TalentSpellPos(talentInfo->TalentID, j); } - LoadDBC(availableDbcLocales, bad_dbc_files, sTalentTabStore, dbcPath, "TalentTab.dbc");//15595 - // prepare fast data access to bit pos of talent ranks for use at inspecting { // now have all max ranks (and then bit amount used for store talent ranks in inspect) - for (uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId) + for (TalentTabEntry const* talentTabInfo : sTalentTabStore) { - TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentTabId); - if (!talentTabInfo) - continue; - // prevent memory corruption; otherwise cls will become 12 below if ((talentTabInfo->ClassMask & CLASSMASK_ALL_PLAYABLE) == 0) continue; @@ -719,64 +675,51 @@ void LoadDBCStores(const std::string& dataPath) // store class talent tab pages for (uint32 cls = 1; cls < MAX_CLASSES; ++cls) if (talentTabInfo->ClassMask & (1 << (cls - 1))) - sTalentTabPages[cls][talentTabInfo->tabpage] = talentTabId; + sTalentTabPages[cls][talentTabInfo->tabpage] = talentTabInfo->TalentTabID; } } - LoadDBC(availableDbcLocales, bad_dbc_files, sTalentTreePrimarySpellsStore, dbcPath, "TalentTreePrimarySpells.dbc"); - for (uint32 i = 0; i < sTalentTreePrimarySpellsStore.GetNumRows(); ++i) - if (TalentTreePrimarySpellsEntry const* talentSpell = sTalentTreePrimarySpellsStore.LookupEntry(i)) - sTalentTreePrimarySpellsMap[talentSpell->TalentTree].push_back(talentSpell->SpellId); - sTalentTreePrimarySpellsStore.Clear(); + for (TalentTreePrimarySpellsEntry const* talentSpell : sTalentTreePrimarySpellsStore) + sTalentTreePrimarySpellsMap[talentSpell->TalentTree].push_back(talentSpell->SpellId); + + for (TaxiPathEntry const* entry : sTaxiPathStore) + sTaxiPathSetBySource[entry->from][entry->to] = TaxiPathBySourceAndDestination(entry->ID, entry->price); - LoadDBC(availableDbcLocales, bad_dbc_files, sTaxiNodesStore, dbcPath, "TaxiNodes.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sTaxiPathStore, dbcPath, "TaxiPath.dbc");//15595 - for (uint32 i = 1; i < sTaxiPathStore.GetNumRows(); ++i) - if (TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(i)) - sTaxiPathSetBySource[entry->from][entry->to] = TaxiPathBySourceAndDestination(entry->ID, entry->price); uint32 pathCount = sTaxiPathStore.GetNumRows(); - - //## TaxiPathNode.dbc ## Loaded only for initialization different structures - LoadDBC(availableDbcLocales, bad_dbc_files, sTaxiPathNodeStore, dbcPath, "TaxiPathNode.dbc");//15595 // Calculate path nodes count std::vector pathLength; pathLength.resize(pathCount); // 0 and some other indexes not used - for (uint32 i = 1; i < sTaxiPathNodeStore.GetNumRows(); ++i) - if (TaxiPathNodeEntry const* entry = sTaxiPathNodeStore.LookupEntry(i)) - { - if (pathLength[entry->PathID] < entry->NodeIndex + 1) - pathLength[entry->PathID] = entry->NodeIndex + 1; - } + for (TaxiPathNodeEntry const* entry : sTaxiPathNodeStore) + { + if (pathLength[entry->PathID] < entry->NodeIndex + 1) + pathLength[entry->PathID] = entry->NodeIndex + 1; + } + // Set path length sTaxiPathNodesByPath.resize(pathCount); // 0 and some other indexes not used for (uint32 i = 1; i < sTaxiPathNodesByPath.size(); ++i) sTaxiPathNodesByPath[i].resize(pathLength[i]); + // fill data - for (uint32 i = 1; i < sTaxiPathNodeStore.GetNumRows(); ++i) - if (TaxiPathNodeEntry const* entry = sTaxiPathNodeStore.LookupEntry(i)) - sTaxiPathNodesByPath[entry->PathID][entry->NodeIndex] = entry; + for (TaxiPathNodeEntry const* entry : sTaxiPathNodeStore) + sTaxiPathNodesByPath[entry->PathID][entry->NodeIndex] = entry; // Initialize global taxinodes mask // include existed nodes that have at least single not spell base (scripted) path { std::set spellPaths; - for (uint32 i = 1; i < sSpellEffectStore.GetNumRows(); ++i) - if (SpellEffectEntry const* sInfo = sSpellEffectStore.LookupEntry (i)) - if (sInfo->Effect == SPELL_EFFECT_SEND_TAXI) - spellPaths.insert(sInfo->EffectMiscValue); + for (SpellEffectEntry const* sInfo : sSpellEffectStore) + if (sInfo->Effect == SPELL_EFFECT_SEND_TAXI) + spellPaths.insert(sInfo->EffectMiscValue); - memset(sTaxiNodesMask, 0, sizeof(sTaxiNodesMask)); - memset(sOldContinentsNodesMask, 0, sizeof(sOldContinentsNodesMask)); - memset(sHordeTaxiNodesMask, 0, sizeof(sHordeTaxiNodesMask)); - memset(sAllianceTaxiNodesMask, 0, sizeof(sAllianceTaxiNodesMask)); - memset(sDeathKnightTaxiNodesMask, 0, sizeof(sDeathKnightTaxiNodesMask)); - for (uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i) + sTaxiNodesMask.fill(0); + sOldContinentsNodesMask.fill(0); + sHordeTaxiNodesMask.fill(0); + sAllianceTaxiNodesMask.fill(0); + sDeathKnightTaxiNodesMask.fill(0); + for (TaxiNodesEntry const* node : sTaxiNodesStore) { - TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(i); - if (!node) - continue; - - TaxiPathSetBySource::const_iterator src_i = sTaxiPathSetBySource.find(i); + TaxiPathSetBySource::const_iterator src_i = sTaxiPathSetBySource.find(node->ID); if (src_i != sTaxiPathSetBySource.end() && !src_i->second.empty()) { bool ok = false; @@ -795,8 +738,8 @@ void LoadDBCStores(const std::string& dataPath) } // valid taxi network node - uint8 field = (uint8)((i - 1) / 8); - uint32 submask = 1 << ((i-1) % 8); + uint8 field = (uint8)((node->ID - 1) / 8); + uint32 submask = 1 << ((node->ID - 1) % 8); sTaxiNodesMask[field] |= submask; if (node->MountCreatureID[0] && node->MountCreatureID[0] != 32981) @@ -807,49 +750,17 @@ void LoadDBCStores(const std::string& dataPath) sDeathKnightTaxiNodesMask[field] |= submask; // old continent node (+ nodes virtually at old continents, check explicitly to avoid loading map files for zone info) - if (node->map_id < 2 || i == 82 || i == 83 || i == 93 || i == 94) + if (node->map_id < 2 || node->ID == 82 || node->ID == 83 || node->ID == 93 || node->ID == 94) sOldContinentsNodesMask[field] |= submask; // fix DK node at Ebon Hold and Shadow Vault flight master - if (i == 315 || i == 333) - ((TaxiNodesEntry*)node)->MountCreatureID[1] = 32981; + if (node->ID == 315 || node->ID == 333) + const_cast(node)->MountCreatureID[1] = 32981; } } - //LoadDBC(availableDbcLocales, bad_dbc_files, sTeamContributionPointsStore, dbcPath, "TeamContributionPoints.dbc"); - LoadDBC(availableDbcLocales, bad_dbc_files, sTotemCategoryStore, dbcPath, "TotemCategory.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sTransportAnimationStore, dbcPath, "TransportAnimation.dbc"); - for (uint32 i = 0; i < sTransportAnimationStore.GetNumRows(); ++i) - { - TransportAnimationEntry const* anim = sTransportAnimationStore.LookupEntry(i); - if (!anim) - continue; - - sTransportMgr->AddPathNodeToTransport(anim->TransportEntry, anim->TimeSeg, anim); - } - - LoadDBC(availableDbcLocales, bad_dbc_files, sTransportRotationStore, dbcPath, "TransportRotation.dbc"); - for (uint32 i = 0; i < sTransportRotationStore.GetNumRows(); ++i) - { - TransportRotationEntry const* rot = sTransportRotationStore.LookupEntry(i); - if (!rot) - continue; - - sTransportMgr->AddPathRotationToTransport(rot->TransportEntry, rot->TimeSeg, rot); - } - - LoadDBC(availableDbcLocales, bad_dbc_files, sUnitPowerBarStore, dbcPath, "UnitPowerBar.dbc");//15595 - - LoadDBC(availableDbcLocales, bad_dbc_files, sVehicleStore, dbcPath, "Vehicle.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sVehicleSeatStore, dbcPath, "VehicleSeat.dbc");//15595 - - LoadDBC(availableDbcLocales, bad_dbc_files, sWMOAreaTableStore, dbcPath, "WMOAreaTable.dbc");//15595 - for (uint32 i = 0; i < sWMOAreaTableStore.GetNumRows(); ++i) - if (WMOAreaTableEntry const* entry = sWMOAreaTableStore.LookupEntry(i)) - sWMOAreaInfoByTripple.insert(WMOAreaInfoByTripple::value_type(WMOAreaTableTripple(entry->rootId, entry->adtId, entry->groupId), entry)); - LoadDBC(availableDbcLocales, bad_dbc_files, sWorldMapAreaStore, dbcPath, "WorldMapArea.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sWorldMapOverlayStore, dbcPath, "WorldMapOverlay.dbc");//15595 - LoadDBC(availableDbcLocales, bad_dbc_files, sWorldSafeLocsStore, dbcPath, "WorldSafeLocs.dbc");//15595 + for (WMOAreaTableEntry const* entry : sWMOAreaTableStore) + sWMOAreaInfoByTripple[WMOAreaTableKey(entry->rootId, entry->adtId, entry->groupId)] = entry; // error checks if (bad_dbc_files.size() >= DBCFileCount) @@ -881,12 +792,9 @@ void LoadDBCStores(const std::string& dataPath) TC_LOG_INFO("server.loading", ">> Initialized %d DBC data stores in %u ms", DBCFileCount, GetMSTimeDiffToNow(oldMSTime)); } -const std::string* GetRandomCharacterName(uint8 race, uint8 gender) +std::string const& GetRandomCharacterName(uint8 race, uint8 gender) { - uint32 size = sGenNameVectoArraysMap[race].stringVectorArray[gender].size(); - uint32 randPos = urand(0, size-1); - - return &sGenNameVectoArraysMap[race].stringVectorArray[gender][randPos]; + return Trinity::Containers::SelectRandomContainerElement(sGenNameVectoArraysMap[race].stringVectorArray[gender]); } SimpleFactionsList const* GetFactionTeamList(uint32 faction) @@ -895,24 +803,24 @@ SimpleFactionsList const* GetFactionTeamList(uint32 faction) if (itr != sFactionTeamMap.end()) return &itr->second; - return NULL; + return nullptr; } char const* GetPetName(uint32 petfamily, uint32 /*dbclang*/) { if (!petfamily) - return NULL; + return nullptr; CreatureFamilyEntry const* pet_family = sCreatureFamilyStore.LookupEntry(petfamily); if (!pet_family) - return NULL; - return pet_family->Name ? pet_family->Name : NULL; + return nullptr; + return pet_family->Name ? pet_family->Name : nullptr; } TalentSpellPos const* GetTalentSpellPos(uint32 spellId) { TalentSpellPosMap::const_iterator itr = sTalentSpellPosMap.find(spellId); if (itr == sTalentSpellPosMap.end()) - return NULL; + return nullptr; return &itr->second; } @@ -925,25 +833,25 @@ uint32 GetTalentSpellCost(uint32 spellId) return 0; } - WMOAreaTableEntry const* GetWMOAreaTableEntryByTripple(int32 rootid, int32 adtid, int32 groupid) { - WMOAreaInfoByTripple::iterator i = sWMOAreaInfoByTripple.find(WMOAreaTableTripple(rootid, adtid, groupid)); - if (i == sWMOAreaInfoByTripple.end()) - return NULL; - return i->second; + auto i = sWMOAreaInfoByTripple.find(WMOAreaTableKey(int16(rootid), int8(adtid), groupid)); + if (i != sWMOAreaInfoByTripple.end()) + return i->second; + + return nullptr; } char const* GetRaceName(uint8 race, uint8 /*locale*/) { ChrRacesEntry const* raceEntry = sChrRacesStore.LookupEntry(race); - return raceEntry ? raceEntry->name : NULL; + return raceEntry ? raceEntry->name : nullptr; } char const* GetClassName(uint8 class_, uint8 /*locale*/) { ChrClassesEntry const* classEntry = sChrClassesStore.LookupEntry(class_); - return classEntry ? classEntry->name : NULL; + return classEntry ? classEntry->name : nullptr; } uint32 GetVirtualMapForMapAndZone(uint32 mapid, uint32 zoneId) @@ -1052,7 +960,7 @@ void Map2ZoneCoordinates(float& x, float& y, uint32 zone) MapDifficulty const* GetMapDifficultyData(uint32 mapId, Difficulty difficulty) { MapDifficultyMap::const_iterator itr = sMapDifficultyMap.find(MAKE_PAIR32(mapId, difficulty)); - return itr != sMapDifficultyMap.end() ? &itr->second : NULL; + return itr != sMapDifficultyMap.end() ? &itr->second : nullptr; } MapDifficulty const* GetDownscaledMapDifficultyData(uint32 mapId, Difficulty &difficulty) @@ -1081,7 +989,7 @@ MapDifficulty const* GetDownscaledMapDifficultyData(uint32 mapId, Difficulty &di PvPDifficultyEntry const* GetBattlegroundBracketByLevel(uint32 mapid, uint32 level) { - PvPDifficultyEntry const* maxEntry = NULL; // used for level > max listed level case + PvPDifficultyEntry const* maxEntry = nullptr; // used for level > max listed level case for (uint32 i = 0; i < sPvPDifficultyStore.GetNumRows(); ++i) { if (PvPDifficultyEntry const* entry = sPvPDifficultyStore.LookupEntry(i)) @@ -1110,7 +1018,7 @@ PvPDifficultyEntry const* GetBattlegroundBracketById(uint32 mapid, BattlegroundB if (entry->mapId == mapid && entry->GetBracketId() == id) return entry; - return NULL; + return nullptr; } uint32 const* GetTalentTabPages(uint8 cls) @@ -1122,7 +1030,7 @@ std::vector const* GetTalentTreePrimarySpells(uint32 talentTree) { TalentTreePrimarySpellsMap::const_iterator itr = sTalentTreePrimarySpellsMap.find(talentTree); if (itr == sTalentTreePrimarySpellsMap.end()) - return NULL; + return nullptr; return &itr->second; } @@ -1139,7 +1047,7 @@ CharStartOutfitEntry const* GetCharStartOutfitEntry(uint8 race, uint8 class_, ui { std::map::const_iterator itr = sCharStartOutfitMap.find(race | (class_ << 8) | (gender << 16)); if (itr == sCharStartOutfitMap.end()) - return NULL; + return nullptr; return itr->second; } @@ -1153,7 +1061,7 @@ CharSectionsEntry const* GetCharSectionEntry(uint8 race, CharSectionType genType return itr->second; } - return NULL; + return nullptr; } uint32 GetPowerIndexByClass(uint32 powerType, uint32 classId) @@ -1326,7 +1234,7 @@ LFGDungeonEntry const* GetLFGDungeon(uint32 mapId, Difficulty difficulty) return dungeon; } - return NULL; + return nullptr; } uint32 GetDefaultMapLight(uint32 mapId) @@ -1357,7 +1265,7 @@ SkillRaceClassInfoEntry const* GetSkillRaceClassInfo(uint32 skill, uint8 race, u return itr->second; } - return NULL; + return nullptr; } std::vector const* GetPhasesForGroup(uint32 group) diff --git a/src/server/game/DataStores/DBCStores.h b/src/server/game/DataStores/DBCStores.h index 448a64759ee..391be99a7b6 100644 --- a/src/server/game/DataStores/DBCStores.h +++ b/src/server/game/DataStores/DBCStores.h @@ -19,12 +19,19 @@ #ifndef TRINITY_DBCSTORES_H #define TRINITY_DBCSTORES_H -#include "Common.h" #include "DBCStore.h" #include "DBCStructure.h" #include "SharedDefines.h" - #include +#include +#include + +enum LocaleConstant : uint8; + +// temporary hack until includes are sorted out (don't want to pull in Windows.h) +#ifdef GetClassName +#undef GetClassName +#endif typedef std::list SimpleFactionsList; TC_GAME_API SimpleFactionsList const* GetFactionTeamList(uint32 faction); @@ -40,16 +47,7 @@ TC_GAME_API WMOAreaTableEntry const* GetWMOAreaTableEntryByTripple(int32 rootid, TC_GAME_API uint32 GetVirtualMapForMapAndZone(uint32 mapid, uint32 zoneId); -const std::string* GetRandomCharacterName(uint8 race, uint8 gender); - -enum ContentLevels -{ - CONTENT_1_60 = 0, - CONTENT_61_70 = 1, - CONTENT_71_80 = 2, - CONTENT_81_85 = 3, - MAX_CONTENT -}; +std::string const& GetRandomCharacterName(uint8 race, uint8 gender); uint32 GetMaxLevelForExpansion(uint32 expansion); @@ -182,7 +180,7 @@ TC_GAME_API extern DBCStorage sMailTemplateStore; TC_GAME_API extern DBCStorage sMapStore; TC_GAME_API extern DBCStorage sMountCapabilityStore; TC_GAME_API extern DBCStorage sMountTypeStore; -TC_GAME_API extern DBCStorage sNameGenStore; +//TC_GAME_API extern DBCStorage sNameGenStore; -- use GetRandomCharacterName instead TC_GAME_API extern DBCStorage sNumTalentsAtLevelStore; TC_GAME_API extern DBCStorage sPhaseStore; TC_GAME_API extern DBCStorage sPhaseGroupStore; @@ -249,6 +247,8 @@ TC_GAME_API extern TaxiMask sAllianceTaxiNodesM TC_GAME_API extern TaxiMask sDeathKnightTaxiNodesMask; TC_GAME_API extern TaxiPathSetBySource sTaxiPathSetBySource; TC_GAME_API extern TaxiPathNodesByPath sTaxiPathNodesByPath; +TC_GAME_API extern DBCStorage sTransportAnimationStore; +TC_GAME_API extern DBCStorage sTransportRotationStore; TC_GAME_API extern DBCStorage sTotemCategoryStore; TC_GAME_API extern DBCStorage sUnitPowerBarStore; TC_GAME_API extern DBCStorage sVehicleStore; diff --git a/src/server/game/DataStores/DBCStructure.h b/src/server/game/DataStores/DBCStructure.h index 33288f6cc12..362c583bb81 100644 --- a/src/server/game/DataStores/DBCStructure.h +++ b/src/server/game/DataStores/DBCStructure.h @@ -19,9 +19,13 @@ #ifndef TRINITY_DBCSTRUCTURE_H #define TRINITY_DBCSTRUCTURE_H -#include "Common.h" +#include "Define.h" #include "DBCEnums.h" +#include "SharedDefines.h" #include "Util.h" +#include +#include +#include // Structures using to access raw DBC data and required packing to portability #pragma pack(push, 1) @@ -979,8 +983,6 @@ struct CreatureModelDataEntry //float Unks[11] }; -#define MAX_CREATURE_SPELL_DATA_SLOT 4 - struct CreatureSpellDataEntry { uint32 ID; // 0 m_ID @@ -1999,10 +2001,6 @@ struct SpellEffectEntry //uint32 Unk0 // 26 4.2.0 only 0 or 1 }; -#define MAX_SPELL_EFFECTS 3 -#define MAX_EFFECT_MASK 7 -#define MAX_SPELL_REAGENTS 8 - // SpellAuraOptions.dbc struct SpellAuraOptionsEntry { @@ -2114,7 +2112,7 @@ struct SpellCategoriesEntry }; typedef std::set PetFamilySpellsSet; -typedef std::map PetFamilySpellsStore; +typedef std::map PetFamilySpellsStore; struct SpellCastTimesEntry { @@ -2355,10 +2353,6 @@ struct SummonPropertiesEntry uint32 Flags; // 5 }; -#define MAX_TALENT_RANK 5 -#define MAX_PET_TALENT_RANK 3 // use in calculations, expected <= MAX_TALENT_RANK -#define MAX_TALENT_TABS 3 - struct TalentEntry { uint32 TalentID; // 0 @@ -2731,8 +2725,5 @@ typedef std::map TaxiPathSetBySource; typedef std::vector TaxiPathNodeList; typedef std::vector TaxiPathNodesByPath; -#define TaxiMaskSize 114 -typedef uint8 TaxiMask[TaxiMaskSize]; - typedef std::unordered_map> PhaseGroupContainer; #endif diff --git a/src/server/game/DataStores/M2Stores.cpp b/src/server/game/DataStores/M2Stores.cpp index 2812b0dd748..0a845bb4b30 100644 --- a/src/server/game/DataStores/M2Stores.cpp +++ b/src/server/game/DataStores/M2Stores.cpp @@ -16,17 +16,18 @@ */ #include "DBCStores.h" -#include "M2Structure.h" -#include "M2Stores.h" #include "Common.h" #include "Containers.h" #include "Log.h" +#include "M2Structure.h" +#include "M2Stores.h" #include "World.h" +#include #include #include #include -#include +typedef std::vector FlyByCameraCollection; std::unordered_map sFlyByCameraStore; // Convert the geomoetry from a spline value, to an actual WoW XYZ @@ -90,10 +91,7 @@ bool readCamera(M2Camera const* cam, uint32 buffSize, M2Header const* header, Ci // 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; + thisCam.locations.Relocate(newPos.x, newPos.y, newPos.z, 0.0f); targetcam.push_back(thisCam); targPositions++; currPos += sizeof(M2SplineKey); @@ -127,9 +125,7 @@ bool readCamera(M2Camera const* cam, uint32 buffSize, M2Header const* header, Ci // Add to vector FlyByCamera thisCam; thisCam.timeStamp = posTimestamps[i]; - thisCam.locations.x = newPos.x; - thisCam.locations.y = newPos.y; - thisCam.locations.z = newPos.z; + thisCam.locations.Relocate(newPos.x, newPos.y, newPos.z); if (targetcam.size() > 0) { @@ -149,28 +145,24 @@ bool readCamera(M2Camera const* cam, uint32 buffSize, M2Header const* header, Ci lastTarget = targetcam[j]; } - float x = lastTarget.locations.x; - float y = lastTarget.locations.y; - float z = lastTarget.locations.z; + float x, y, z; + lastTarget.locations.GetPosition(x, y, 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 = nextTarget.locations.GetPositionX() - lastTarget.locations.GetPositionX(); + float yDiff = nextTarget.locations.GetPositionY() - lastTarget.locations.GetPositionY(); + float zDiff = nextTarget.locations.GetPositionZ() - lastTarget.locations.GetPositionZ(); + x = lastTarget.locations.GetPositionX() + (xDiff * (float(timeDiffThis) / float(timeDiffTarget))); + y = lastTarget.locations.GetPositionY() + (yDiff * (float(timeDiffThis) / float(timeDiffTarget))); + z = lastTarget.locations.GetPositionZ() + (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); + float xDiff = x - thisCam.locations.GetPositionX(); + float yDiff = y - thisCam.locations.GetPositionY(); + thisCam.locations.SetOrientation(std::atan2(yDiff, xDiff)); } cameras.push_back(thisCam); @@ -189,78 +181,80 @@ void LoadM2Cameras(std::string const& dataPath) TC_LOG_INFO("server.loading", ">> Loading Cinematic Camera files"); uint32 oldMSTime = getMSTime(); - for (uint32 i = 0; i < sCinematicCameraStore.GetNumRows(); ++i) + for (CinematicCameraEntry const* dbcentry : sCinematicCameraStore) { - 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(fileSize) < sizeof(M2Header)) { - 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(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 buffer(fileSize); - m2file.seekg(0, std::ios::beg); - if (!m2file.read(buffer.data(), fileSize)) - { - m2file.close(); - continue; - } + TC_LOG_ERROR("server.loading", "Camera file %s is damaged. File is smaller than header size", filename.string().c_str()); m2file.close(); - - // Read header - M2Header const* header = reinterpret_cast(buffer.data()); - - if (header->ofsCameras + sizeof(M2Camera) > static_cast(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(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()); + 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 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(buffer.data()); + + if (header->ofsCameras + sizeof(M2Camera) > static_cast(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(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)); } + +std::vector const* GetFlyByCameras(uint32 cinematicCameraId) +{ + return Trinity::Containers::MapGetValuePtr(sFlyByCameraStore, cinematicCameraId); +} diff --git a/src/server/game/DataStores/M2Stores.h b/src/server/game/DataStores/M2Stores.h index bcd16cf7cfe..d6ffed20fde 100644 --- a/src/server/game/DataStores/M2Stores.h +++ b/src/server/game/DataStores/M2Stores.h @@ -18,19 +18,18 @@ #ifndef TRINITY_M2STORES_H #define TRINITY_M2STORES_H -#include "Common.h" -#include "G3D/Vector4.h" +#include "Define.h" +#include "Position.h" +#include struct FlyByCamera { uint32 timeStamp; - G3D::Vector4 locations; + Position locations; }; -typedef std::vector FlyByCameraCollection; - -TC_GAME_API extern std::unordered_map sFlyByCameraStore; - void LoadM2Cameras(std::string const& dataPath); +TC_GAME_API std::vector const* GetFlyByCameras(uint32 cinematicCameraId); + #endif diff --git a/src/server/game/DungeonFinding/LFG.h b/src/server/game/DungeonFinding/LFG.h index dadcf20c8c7..3da98b4276d 100644 --- a/src/server/game/DungeonFinding/LFG.h +++ b/src/server/game/DungeonFinding/LFG.h @@ -18,8 +18,11 @@ #ifndef _LFG_H #define _LFG_H -#include "Common.h" +#include "Define.h" #include "ObjectGuid.h" +#include +#include +#include namespace lfg { diff --git a/src/server/game/DungeonFinding/LFGMgr.cpp b/src/server/game/DungeonFinding/LFGMgr.cpp index 4399bb766e1..1c8ac09ab29 100644 --- a/src/server/game/DungeonFinding/LFGMgr.cpp +++ b/src/server/game/DungeonFinding/LFGMgr.cpp @@ -15,28 +15,48 @@ * with this program. If not, see . */ +#include "LFGMgr.h" #include "Common.h" -#include "SharedDefines.h" +#include "DatabaseEnv.h" #include "DBCStores.h" #include "DisableMgr.h" -#include "ObjectMgr.h" -#include "SocialMgr.h" -#include "LFGMgr.h" -#include "LFGScripts.h" +#include "GameEventMgr.h" +#include "Group.h" +#include "GroupMgr.h" +#include "InstanceSaveMgr.h" #include "LFGGroupData.h" #include "LFGPlayerData.h" +#include "LFGScripts.h" #include "LFGQueue.h" -#include "Group.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Player.h" #include "RBAC.h" -#include "GroupMgr.h" -#include "GameEventMgr.h" +#include "SharedDefines.h" +#include "SocialMgr.h" +#include "World.h" #include "WorldSession.h" -#include "InstanceSaveMgr.h" namespace lfg { +LFGDungeonData::LFGDungeonData() : id(0), name(), map(0), type(0), expansion(0), group(0), minlevel(0), + maxlevel(0), difficulty(REGULAR_DIFFICULTY), seasonal(false), x(0.0f), y(0.0f), z(0.0f), o(0.0f), + requiredItemLevel(0) +{ +} + +LFGDungeonData::LFGDungeonData(LFGDungeonEntry const* dbc) : id(dbc->ID), name(dbc->name), map(dbc->map), + type(dbc->type), expansion(dbc->expansion), group(dbc->grouptype), + minlevel(dbc->minlevel), maxlevel(dbc->maxlevel), difficulty(Difficulty(dbc->difficulty)), + seasonal((dbc->flags & LFG_FLAG_SEASONAL) != 0), x(0.0f), y(0.0f), z(0.0f), o(0.0f), + requiredItemLevel(0) +{ +} + LFGMgr::LFGMgr(): m_QueueTimer(0), m_lfgProposalId(1), m_options(sWorld->getIntConfig(CONFIG_LFG_OPTIONSMASK)) { @@ -117,7 +137,7 @@ void LFGMgr::LoadRewards() uint32 count = 0; - Field* fields = NULL; + Field* fields = nullptr; do { fields = result->Fetch(); @@ -164,7 +184,7 @@ LFGDungeonData const* LFGMgr::GetLFGDungeon(uint32 id) if (itr != LfgDungeonStore.end()) return &(itr->second); - return NULL; + return nullptr; } void LFGMgr::LoadLFGDungeons(bool reload /* = false */) @@ -267,7 +287,7 @@ void LFGMgr::Update(uint32 diff) if (!isOptionEnabled(LFG_OPTION_ENABLE_DUNGEON_FINDER | LFG_OPTION_ENABLE_RAID_BROWSER)) return; - time_t currTime = time(NULL); + time_t currTime = time(nullptr); // Remove obsolete role checks for (LfgRoleCheckContainer::iterator it = RoleChecksStore.begin(); it != RoleChecksStore.end();) @@ -421,7 +441,7 @@ void LFGMgr::JoinLfg(Player* player, uint8 roles, LfgDungeonSet& dungeons, const else { uint8 memberCount = 0; - for (GroupReference* itr = grp->GetFirstMember(); itr != NULL && joinData.result == LFG_JOIN_OK; itr = itr->next()) + for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr && joinData.result == LFG_JOIN_OK; itr = itr->next()) { if (Player* plrg = itr->GetSource()) { @@ -517,7 +537,7 @@ void LFGMgr::JoinLfg(Player* player, uint8 roles, LfgDungeonSet& dungeons, const { // Create new rolecheck LfgRoleCheck& roleCheck = RoleChecksStore[gguid]; - roleCheck.cancelTime = time_t(time(NULL)) + LFG_TIME_ROLECHECK; + roleCheck.cancelTime = time_t(time(nullptr)) + LFG_TIME_ROLECHECK; roleCheck.state = LFG_ROLECHECK_INITIALITING; roleCheck.leader = guid; roleCheck.dungeons = dungeons; @@ -532,7 +552,7 @@ void LFGMgr::JoinLfg(Player* player, uint8 roles, LfgDungeonSet& dungeons, const SetState(gguid, LFG_STATE_ROLECHECK); // Send update to player LfgUpdateData updateData = LfgUpdateData(LFG_UPDATETYPE_JOIN_QUEUE, dungeons, comment); - for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr; itr = itr->next()) { if (Player* plrg = itr->GetSource()) { @@ -555,7 +575,7 @@ void LFGMgr::JoinLfg(Player* player, uint8 roles, LfgDungeonSet& dungeons, const LfgRolesMap rolesMap; rolesMap[guid] = roles; LFGQueue& queue = GetQueue(guid); - queue.AddQueueData(guid, time(NULL), dungeons, rolesMap); + queue.AddQueueData(guid, time(nullptr), dungeons, rolesMap); if (!isContinue) { @@ -580,7 +600,7 @@ void LFGMgr::JoinLfg(Player* player, uint8 roles, LfgDungeonSet& dungeons, const /** Leaves Dungeon System. Player/Group is removed from queue, rolechecks, proposals - or votekicks. Player or group needs to be not NULL and using Dungeon System + or votekicks. Player or group needs to be not nullptr and using Dungeon System @param[in] guid Player or group guid */ @@ -733,7 +753,7 @@ void LFGMgr::UpdateRoleCheck(ObjectGuid gguid, ObjectGuid guid /* = ObjectGuid:: { SetState(gguid, LFG_STATE_QUEUED); LFGQueue& queue = GetQueue(gguid); - queue.AddQueueData(gguid, time_t(time(NULL)), roleCheck.dungeons, roleCheck.roles); + queue.AddQueueData(gguid, time_t(time(nullptr)), roleCheck.dungeons, roleCheck.roles); RoleChecksStore.erase(itRoleCheck); } else if (roleCheck.state != LFG_ROLECHECK_INITIALITING) @@ -894,7 +914,7 @@ void LFGMgr::MakeNewGroup(LfgProposal const& proposal) LFGDungeonData const* dungeon = GetLFGDungeon(proposal.dungeonId); ASSERT(dungeon); - Group* grp = proposal.group ? sGroupMgr->GetGroupByGUID(proposal.group.GetCounter()) : NULL; + Group* grp = proposal.group ? sGroupMgr->GetGroupByGUID(proposal.group.GetCounter()) : nullptr; for (GuidList::const_iterator it = players.begin(); it != players.end(); ++it) { ObjectGuid pguid = (*it); @@ -996,7 +1016,7 @@ void LFGMgr::UpdateProposal(uint32 proposalId, ObjectGuid guid, bool accept) bool sendUpdate = proposal.state != LFG_PROPOSAL_SUCCESS; proposal.state = LFG_PROPOSAL_SUCCESS; - time_t joinTime = time(NULL); + time_t joinTime = time(nullptr); LFGQueue& queue = GetQueue(guid); LfgUpdateData updateData = LfgUpdateData(LFG_UPDATETYPE_GROUP_FOUND); @@ -1165,7 +1185,7 @@ void LFGMgr::InitBoot(ObjectGuid gguid, ObjectGuid kicker, ObjectGuid victim, st LfgPlayerBoot& boot = BootsStore[gguid]; boot.inProgress = true; - boot.cancelTime = time_t(time(NULL)) + LFG_TIME_BOOT; + boot.cancelTime = time_t(time(nullptr)) + LFG_TIME_BOOT; boot.reason = reason; boot.victim = victim; @@ -1253,7 +1273,7 @@ void LFGMgr::UpdateBoot(ObjectGuid guid, bool accept) */ void LFGMgr::TeleportPlayer(Player* player, bool out, bool fromOpcode /*= false*/) { - LFGDungeonData const* dungeon = NULL; + LFGDungeonData const* dungeon = nullptr; Group* group = player->GetGroup(); if (group && group->isLFGGroup()) @@ -1302,7 +1322,7 @@ void LFGMgr::TeleportPlayer(Player* player, bool out, bool fromOpcode /*= false* if (!fromOpcode) { // Select a player inside to be teleported to - for (GroupReference* itr = group->GetFirstMember(); itr != NULL && !mapid; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr && !mapid; itr = itr->next()) { Player* plrg = itr->GetSource(); if (plrg && plrg != player && plrg->GetMapId() == uint32(dungeon->map)) @@ -1420,7 +1440,7 @@ void LFGMgr::FinishDungeon(ObjectGuid gguid, const uint32 dungeonId, Map const* // if we can take the quest, means that we haven't done this kind of "run", IE: First Heroic Random of Day. if (player->CanRewardQuest(quest, false)) - player->RewardQuest(quest, 0, NULL, false); + player->RewardQuest(quest, 0, nullptr, false); else { done = true; @@ -1428,7 +1448,7 @@ void LFGMgr::FinishDungeon(ObjectGuid gguid, const uint32 dungeonId, Map const* if (!quest) continue; // we give reward without informing client (retail does this) - player->RewardQuest(quest, 0, NULL, false); + player->RewardQuest(quest, 0, nullptr, false); } // Give rewards @@ -1464,7 +1484,7 @@ LfgDungeonSet const& LFGMgr::GetDungeonsByRandom(uint32 randomdungeon) */ LfgReward const* LFGMgr::GetRandomDungeonReward(uint32 dungeon, uint8 level) { - LfgReward const* rew = NULL; + LfgReward const* rew = nullptr; LfgRewardContainerBounds bounds = RewardMapStore.equal_range(dungeon & 0x00FFFFFF); for (LfgRewardContainer::const_iterator itr = bounds.first; itr != bounds.second; ++itr) { diff --git a/src/server/game/DungeonFinding/LFGMgr.h b/src/server/game/DungeonFinding/LFGMgr.h index b4685965646..e7ab2b86a50 100644 --- a/src/server/game/DungeonFinding/LFGMgr.h +++ b/src/server/game/DungeonFinding/LFGMgr.h @@ -18,17 +18,20 @@ #ifndef _LFGMGR_H #define _LFGMGR_H -#include "DBCStructure.h" -#include "Field.h" +#include "Common.h" +#include "DatabaseEnvFwd.h" #include "LFG.h" #include "LFGQueue.h" #include "LFGGroupData.h" #include "LFGPlayerData.h" +#include class Group; class Player; class Quest; class Map; +struct LFGDungeonEntry; +enum Difficulty : uint8; namespace lfg { @@ -268,16 +271,8 @@ struct LfgPlayerBoot struct LFGDungeonData { - LFGDungeonData(): id(0), name(""), map(0), type(0), expansion(0), group(0), minlevel(0), - maxlevel(0), difficulty(REGULAR_DIFFICULTY), seasonal(false), x(0.0f), y(0.0f), z(0.0f), o(0.0f), - requiredItemLevel(0) - { } - LFGDungeonData(LFGDungeonEntry const* dbc): id(dbc->ID), name(dbc->name), map(dbc->map), - type(dbc->type), expansion(dbc->expansion), group(dbc->grouptype), - minlevel(dbc->minlevel), maxlevel(dbc->maxlevel), difficulty(Difficulty(dbc->difficulty)), - seasonal((dbc->flags & LFG_FLAG_SEASONAL) != 0), x(0.0f), y(0.0f), z(0.0f), o(0.0f), - requiredItemLevel(0) - { } + LFGDungeonData(); + LFGDungeonData(LFGDungeonEntry const* dbc); uint32 id; std::string name; diff --git a/src/server/game/DungeonFinding/LFGQueue.cpp b/src/server/game/DungeonFinding/LFGQueue.cpp index bf8ea5d342f..5fd1903ac94 100644 --- a/src/server/game/DungeonFinding/LFGQueue.cpp +++ b/src/server/game/DungeonFinding/LFGQueue.cpp @@ -283,7 +283,7 @@ LfgCompatibilityData* LFGQueue::GetCompatibilityData(std::string const& key) if (itr != CompatibleMapStore.end()) return &(itr->second); - return NULL; + return nullptr; } uint8 LFGQueue::FindGroups() @@ -540,7 +540,7 @@ LfgCompatibility LFGQueue::CheckCompatibility(GuidList check) } // Create a new proposal - proposal.cancelTime = time(NULL) + LFG_TIME_PROPOSAL; + proposal.cancelTime = time(nullptr) + LFG_TIME_PROPOSAL; proposal.state = LFG_PROPOSAL_INITIATING; proposal.leader.Clear(); proposal.dungeonId = Trinity::Containers::SelectRandomContainerElement(proposalDungeons); diff --git a/src/server/game/DungeonFinding/LFGQueue.h b/src/server/game/DungeonFinding/LFGQueue.h index 86a036e367c..aa61242a0d9 100644 --- a/src/server/game/DungeonFinding/LFGQueue.h +++ b/src/server/game/DungeonFinding/LFGQueue.h @@ -51,7 +51,7 @@ struct LfgCompatibilityData /// Stores player or group queue info struct LfgQueueData { - LfgQueueData(): joinTime(time_t(time(NULL))), tanks(LFG_TANKS_NEEDED), + LfgQueueData(): joinTime(time_t(time(nullptr))), tanks(LFG_TANKS_NEEDED), healers(LFG_HEALERS_NEEDED), dps(LFG_DPS_NEEDED) { } diff --git a/src/server/game/DungeonFinding/LFGScripts.cpp b/src/server/game/DungeonFinding/LFGScripts.cpp index 0f88dd29d75..e0a222288df 100644 --- a/src/server/game/DungeonFinding/LFGScripts.cpp +++ b/src/server/game/DungeonFinding/LFGScripts.cpp @@ -19,14 +19,16 @@ * Interaction between core and LFGScripts */ -#include "Common.h" -#include "SharedDefines.h" -#include "Player.h" -#include "Group.h" #include "LFGScripts.h" +#include "Common.h" +#include "Group.h" #include "LFGMgr.h" -#include "ScriptMgr.h" +#include "Log.h" +#include "Map.h" #include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptMgr.h" +#include "SharedDefines.h" #include "WorldSession.h" namespace lfg @@ -93,7 +95,7 @@ void LFGPlayerScript::OnMapChanged(Player* player) return; } - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) if (Player* member = itr->GetSource()) player->GetSession()->SendNameQueryOpcode(member->GetGUID()); diff --git a/src/server/game/DungeonFinding/LFGScripts.h b/src/server/game/DungeonFinding/LFGScripts.h index 0cc037ac4e8..e5893ddd9d4 100644 --- a/src/server/game/DungeonFinding/LFGScripts.h +++ b/src/server/game/DungeonFinding/LFGScripts.h @@ -15,6 +15,9 @@ * with this program. If not, see . */ +#ifndef LFGScripts_h__ +#define LFGScripts_h__ + /* * Interaction between core and LFGScripts */ @@ -56,3 +59,5 @@ class TC_GAME_API LFGGroupScript : public GroupScript /*keep private*/ void AddSC_LFGScripts(); } // namespace lfg + +#endif // LFGScripts_h__ diff --git a/src/server/game/Entities/AreaTrigger/AreaTrigger.cpp b/src/server/game/Entities/AreaTrigger/AreaTrigger.cpp index 42e78d066d9..0282b35004c 100644 --- a/src/server/game/Entities/AreaTrigger/AreaTrigger.cpp +++ b/src/server/game/Entities/AreaTrigger/AreaTrigger.cpp @@ -15,12 +15,14 @@ * with this program. If not, see . */ +#include "AreaTrigger.h" +#include "Log.h" +#include "Map.h" #include "ObjectAccessor.h" #include "PhasingHandler.h" -#include "Unit.h" #include "SpellInfo.h" -#include "Log.h" -#include "AreaTrigger.h" +#include "Unit.h" +#include "UpdateData.h" AreaTrigger::AreaTrigger() : WorldObject(false), _duration(0) { diff --git a/src/server/game/Entities/AreaTrigger/AreaTrigger.h b/src/server/game/Entities/AreaTrigger/AreaTrigger.h index 4b63c7a7cd4..9396d7ef64d 100644 --- a/src/server/game/Entities/AreaTrigger/AreaTrigger.h +++ b/src/server/game/Entities/AreaTrigger/AreaTrigger.h @@ -19,6 +19,7 @@ #define TRINITYCORE_AREATRIGGER_H #include "Object.h" +#include "MapObject.h" class Unit; class SpellInfo; diff --git a/src/server/game/Entities/Corpse/Corpse.cpp b/src/server/game/Entities/Corpse/Corpse.cpp index 83df48db009..8c604565f6b 100644 --- a/src/server/game/Entities/Corpse/Corpse.cpp +++ b/src/server/game/Entities/Corpse/Corpse.cpp @@ -16,14 +16,17 @@ * with this program. If not, see . */ +#include "Corpse.h" #include "CharacterCache.h" #include "Common.h" -#include "Corpse.h" -#include "Player.h" -#include "UpdateMask.h" +#include "DatabaseEnv.h" +#include "Log.h" +#include "Map.h" #include "ObjectAccessor.h" #include "PhasingHandler.h" -#include "DatabaseEnv.h" +#include "Player.h" +#include "UpdateData.h" +#include "UpdateMask.h" #include "World.h" Corpse::Corpse(CorpseType type) : WorldObject(type != CORPSE_BONES), m_type(type) @@ -35,10 +38,10 @@ Corpse::Corpse(CorpseType type) : WorldObject(type != CORPSE_BONES), m_type(type m_valuesCount = CORPSE_END; - m_time = time(NULL); + m_time = time(nullptr); lootForBody = false; - lootRecipient = NULL; + lootRecipient = nullptr; } Corpse::~Corpse() { } diff --git a/src/server/game/Entities/Corpse/Corpse.h b/src/server/game/Entities/Corpse/Corpse.h index 72cac1255fc..721c90da8e3 100644 --- a/src/server/game/Entities/Corpse/Corpse.h +++ b/src/server/game/Entities/Corpse/Corpse.h @@ -20,9 +20,9 @@ #define TRINITYCORE_CORPSE_H #include "Object.h" -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "GridDefines.h" -#include "LootMgr.h" +#include "Loot.h" enum CorpseType { @@ -67,7 +67,7 @@ class TC_GAME_API Corpse : public WorldObject, public GridObject ObjectGuid GetOwnerGUID() const { return GetGuidValue(CORPSE_FIELD_OWNER); } time_t const& GetGhostTime() const { return m_time; } - void ResetGhostTime() { m_time = time(NULL); } + void ResetGhostTime() { m_time = time(nullptr); } CorpseType GetType() const { return m_type; } CellCoord const& GetCellCoord() const { return _cellCoord; } diff --git a/src/server/game/Entities/Creature/Creature.cpp b/src/server/game/Entities/Creature/Creature.cpp index 1c3ed3dd08d..ec1934d550e 100644 --- a/src/server/game/Entities/Creature/Creature.cpp +++ b/src/server/game/Entities/Creature/Creature.cpp @@ -35,21 +35,24 @@ #include "InstanceScript.h" #include "Log.h" #include "LootMgr.h" +#include "MotionMaster.h" #include "MoveSpline.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "PhasingHandler.h" #include "Player.h" #include "PoolMgr.h" #include "QuestDef.h" +#include "ScriptedGossip.h" #include "SpellAuraEffects.h" #include "SpellMgr.h" #include "TemporarySummon.h" +#include "Transport.h" #include "Util.h" #include "Vehicle.h" #include "World.h" #include "WorldPacket.h" -#include "Transport.h" -#include "ScriptedGossip.h" +#include TrainerSpell const* TrainerSpellData::Find(uint32 spell_id) const { @@ -60,27 +63,28 @@ TrainerSpell const* TrainerSpellData::Find(uint32 spell_id) const return nullptr; } +bool VendorItem::IsGoldRequired(ItemTemplate const* pProto) const +{ + return (pProto->Flags2 & ITEM_FLAG2_DONT_IGNORE_BUY_PRICE) || !ExtendedCost; +} + bool VendorItemData::RemoveItem(uint32 item_id, uint8 type) { - bool found = false; - for (VendorItemList::iterator i = m_items.begin(); i != m_items.end();) + auto newEnd = std::remove_if(m_items.begin(), m_items.end(), [=](VendorItem const& vendorItem) { - if ((*i)->item == item_id && (*i)->Type == type) - { - i = m_items.erase(i++); - found = true; - } - else - ++i; - } + return vendorItem.item == item_id && vendorItem.Type == type; + }); + + bool found = (newEnd != m_items.end()); + m_items.erase(newEnd, m_items.end()); return found; } VendorItem const* VendorItemData::FindItemCostPair(uint32 item_id, uint32 extendedCost, uint8 type) const { - for (VendorItemList::const_iterator i = m_items.begin(); i != m_items.end(); ++i) - if ((*i)->item == item_id && (*i)->ExtendedCost == extendedCost && (*i)->Type == type) - return *i; + for (VendorItem const& vendorItem : m_items) + if (vendorItem.item == item_id && vendorItem.ExtendedCost == extendedCost && vendorItem.Type == type) + return &vendorItem; return nullptr; } @@ -284,7 +288,7 @@ void Creature::RemoveCorpse(bool setSpawnTime) if (getDeathState() != CORPSE) return; - m_corpseRemoveTime = time(NULL); + m_corpseRemoveTime = time(nullptr); setDeathState(DEAD); RemoveAllAuras(); DestroyForNearbyPlayers(); // old UpdateObjectVisibility() @@ -520,7 +524,7 @@ void Creature::Update(uint32 diff) break; case DEAD: { - time_t now = time(NULL); + time_t now = time(nullptr); if (m_respawnTime <= now) { // First check if there are any scripts that object to us respawning @@ -573,7 +577,7 @@ void Creature::Update(uint32 diff) } else m_groupLootTimer -= diff; } - else if (m_corpseRemoveTime <= time(NULL)) + else if (m_corpseRemoveTime <= time(nullptr)) { RemoveCorpse(false); TC_LOG_DEBUG("entities.unit", "Removing corpse... %u ", GetUInt32Value(OBJECT_FIELD_ENTRY)); @@ -641,7 +645,7 @@ void Creature::Update(uint32 diff) if (m_combatPulseTime == 0) { - Map::PlayerList const &players = GetMap()->GetPlayers(); + Map::PlayerList const& players = GetMap()->GetPlayers(); if (!players.isEmpty()) for (Map::PlayerList::const_iterator it = players.begin(); it != players.end(); ++it) { @@ -1430,7 +1434,7 @@ bool Creature::LoadCreatureFromDB(ObjectGuid::LowType spawnId, Map* map, bool ad // Is the creature script objecting to us spawning? If yes, delay by one second (then re-check in ::Update) if (!m_respawnTime && !sScriptMgr->CanSpawn(spawnId, GetEntry(), GetCreatureTemplate(), GetCreatureData(), map)) - m_respawnTime = time(NULL)+1; + m_respawnTime = time(nullptr)+1; if (m_respawnTime) // respawn on Update { @@ -1564,7 +1568,7 @@ bool Creature::IsInvisibleDueToDespawn() const if (Unit::IsInvisibleDueToDespawn()) return true; - if (IsAlive() || isDying() || m_corpseRemoveTime > time(NULL)) + if (IsAlive() || isDying() || m_corpseRemoveTime > time(nullptr)) return false; return true; @@ -1690,11 +1694,11 @@ void Creature::setDeathState(DeathState s) if (s == JUST_DIED) { - m_corpseRemoveTime = time(NULL) + m_corpseDelay; + m_corpseRemoveTime = time(nullptr) + m_corpseDelay; if (IsDungeonBoss() && !m_respawnDelay) m_respawnTime = std::numeric_limits::max(); // never respawn in this instance else - m_respawnTime = time(NULL) + m_respawnDelay + m_corpseDelay; + m_respawnTime = time(nullptr) + m_respawnDelay + m_corpseDelay; // always save boss respawn time at death to prevent crash cheating if (sWorld->getBoolConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATELY) || isWorldBoss()) @@ -1849,7 +1853,7 @@ void Creature::ForcedDespawn(uint32 timeMSToDespawn, Seconds const& forceRespawn else { m_corpseRemoveTime = time(nullptr); - m_respawnTime = time(NULL) + forceRespawnTimer.count(); + m_respawnTime = time(nullptr) + forceRespawnTimer.count(); } } else @@ -2364,8 +2368,7 @@ void Creature::SetInCombatWithZone() return; } - Map::PlayerList const &PlList = map->GetPlayers(); - + Map::PlayerList const& PlList = map->GetPlayers(); if (PlList.isEmpty()) return; @@ -2397,7 +2400,7 @@ bool Creature::HasSpell(uint32 spellID) const time_t Creature::GetRespawnTimeEx() const { - time_t now = time(NULL); + time_t now = time(nullptr); if (m_respawnTime > now) return m_respawnTime; else @@ -2437,7 +2440,7 @@ void Creature::AllLootRemovedFromCorpse() if (LootTemplates_Skinning.HaveLootFor(GetCreatureTemplate()->SkinLootId)) SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); - time_t now = time(NULL); + time_t now = time(nullptr); // Do not reset corpse remove time if corpse is already removed if (m_corpseRemoveTime <= now) return; @@ -2505,7 +2508,7 @@ uint32 Creature::GetVendorItemCurrentCount(VendorItem const* vItem) VendorItemCount* vCount = &*itr; - time_t ptime = time(NULL); + time_t ptime = time(nullptr); if (time_t(vCount->lastIncrementTime + vItem->incrtime) <= ptime) if (ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(vItem->item)) @@ -2543,7 +2546,7 @@ uint32 Creature::UpdateVendorItemCurrentCount(VendorItem const* vItem, uint32 us VendorItemCount* vCount = &*itr; - time_t ptime = time(NULL); + time_t ptime = time(nullptr); if (time_t(vCount->lastIncrementTime + vItem->incrtime) <= ptime) if (ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(vItem->item)) @@ -2680,7 +2683,7 @@ Unit* Creature::SelectNearestHostileUnitInAggroRange(bool useLOS) const // Selects nearest hostile target within creature's aggro range. Used primarily by // pets set to aggressive. Will not return neutral or friendly targets. - Unit* target = NULL; + Unit* target = nullptr; Trinity::NearestHostileUnitInAggroRangeCheck u_check(this, useLOS); Trinity::UnitSearcher searcher(this, target, u_check); @@ -2880,7 +2883,7 @@ void Creature::ReleaseFocus(Spell const* focusSpell, bool withDelay) void Creature::StartPickPocketRefillTimer() { - _pickpocketLootRestore = time(NULL) + sWorld->getIntConfig(CONFIG_CREATURE_PICKPOCKET_REFILL); + _pickpocketLootRestore = time(nullptr) + sWorld->getIntConfig(CONFIG_CREATURE_PICKPOCKET_REFILL); } void Creature::SetTextRepeatId(uint8 textGroup, uint8 id) diff --git a/src/server/game/Entities/Creature/Creature.h b/src/server/game/Entities/Creature/Creature.h index bad63dbd7c8..456d85b98a7 100644 --- a/src/server/game/Entities/Creature/Creature.h +++ b/src/server/game/Entities/Creature/Creature.h @@ -19,14 +19,13 @@ #ifndef TRINITYCORE_CREATURE_H #define TRINITYCORE_CREATURE_H -#include "Common.h" #include "Unit.h" -#include "UpdateMask.h" -#include "ItemTemplate.h" -#include "LootMgr.h" -#include "DatabaseEnv.h" -#include "Cell.h" - +#include "Common.h" +#include "CreatureData.h" +#include "DatabaseEnvFwd.h" +#include "Duration.h" +#include "Loot.h" +#include "MapObject.h" #include class CreatureAI; @@ -36,374 +35,12 @@ class Quest; class Player; class SpellInfo; class WorldSession; - -enum CreatureFlagsExtra : uint32 -{ - CREATURE_FLAG_EXTRA_INSTANCE_BIND = 0x00000001, // creature kill bind instance with killer and killer's group - CREATURE_FLAG_EXTRA_CIVILIAN = 0x00000002, // not aggro (ignore faction/reputation hostility) - CREATURE_FLAG_EXTRA_NO_PARRY = 0x00000004, // creature can't parry - CREATURE_FLAG_EXTRA_NO_PARRY_HASTEN = 0x00000008, // creature can't counter-attack at parry - CREATURE_FLAG_EXTRA_NO_BLOCK = 0x00000010, // creature can't block - CREATURE_FLAG_EXTRA_NO_CRUSH = 0x00000020, // creature can't do crush attacks - CREATURE_FLAG_EXTRA_NO_XP_AT_KILL = 0x00000040, // creature kill not provide XP - CREATURE_FLAG_EXTRA_TRIGGER = 0x00000080, // trigger creature - CREATURE_FLAG_EXTRA_NO_TAUNT = 0x00000100, // creature is immune to taunt auras and effect attack me - CREATURE_FLAG_EXTRA_NO_MOVE_FLAGS_UPDATE = 0x00000200, // creature won't update movement flags - CREATURE_FLAG_EXTRA_GHOST_VISIBILITY = 0x00000400, // creature will be only visible for dead players - CREATURE_FLAG_EXTRA_USE_OFFHAND_ATTACK = 0x00000800, // creature will use offhand attacks - CREATURE_FLAG_EXTRA_UNUSED_12 = 0x00001000, - CREATURE_FLAG_EXTRA_UNUSED_13 = 0x00002000, - CREATURE_FLAG_EXTRA_WORLDEVENT = 0x00004000, // custom flag for world event creatures (left room for merging) - CREATURE_FLAG_EXTRA_GUARD = 0x00008000, // Creature is guard - CREATURE_FLAG_EXTRA_UNUSED_16 = 0x00010000, - CREATURE_FLAG_EXTRA_NO_CRIT = 0x00020000, // creature can't do critical strikes - CREATURE_FLAG_EXTRA_NO_SKILLGAIN = 0x00040000, // creature won't increase weapon skills - CREATURE_FLAG_EXTRA_TAUNT_DIMINISH = 0x00080000, // Taunt is a subject to diminishing returns on this creautre - CREATURE_FLAG_EXTRA_ALL_DIMINISH = 0x00100000, // creature is subject to all diminishing returns as player are - CREATURE_FLAG_EXTRA_NO_PLAYER_DAMAGE_REQ = 0x00200000, // creature does not need to take player damage for kill credit - CREATURE_FLAG_EXTRA_UNUSED_22 = 0x00400000, - CREATURE_FLAG_EXTRA_UNUSED_23 = 0x00800000, - CREATURE_FLAG_EXTRA_UNUSED_24 = 0x01000000, - CREATURE_FLAG_EXTRA_UNUSED_25 = 0x02000000, - CREATURE_FLAG_EXTRA_UNUSED_26 = 0x04000000, - CREATURE_FLAG_EXTRA_UNUSED_27 = 0x08000000, - CREATURE_FLAG_EXTRA_DUNGEON_BOSS = 0x10000000, // creature is a dungeon boss (SET DYNAMICALLY, DO NOT ADD IN DB) - CREATURE_FLAG_EXTRA_IGNORE_PATHFINDING = 0x20000000, // creature ignore pathfinding - CREATURE_FLAG_EXTRA_IMMUNITY_KNOCKBACK = 0x40000000, // creature is immune to knockback effects - CREATURE_FLAG_EXTRA_UNUSED_31 = 0x80000000, - - // Masks - CREATURE_FLAG_EXTRA_UNUSED = (CREATURE_FLAG_EXTRA_UNUSED_12 | CREATURE_FLAG_EXTRA_UNUSED_13 | CREATURE_FLAG_EXTRA_UNUSED_16 | - CREATURE_FLAG_EXTRA_UNUSED_22 | CREATURE_FLAG_EXTRA_UNUSED_23 | CREATURE_FLAG_EXTRA_UNUSED_24 | - CREATURE_FLAG_EXTRA_UNUSED_25 | CREATURE_FLAG_EXTRA_UNUSED_26 | CREATURE_FLAG_EXTRA_UNUSED_27 | - CREATURE_FLAG_EXTRA_UNUSED_31), - - CREATURE_FLAG_EXTRA_DB_ALLOWED = (0xFFFFFFFF & ~(CREATURE_FLAG_EXTRA_UNUSED | CREATURE_FLAG_EXTRA_DUNGEON_BOSS)) -}; - -const uint32 CREATURE_REGEN_INTERVAL = 2 * IN_MILLISECONDS; -const uint32 CREATURE_NOPATH_EVADE_TIME = 5 * IN_MILLISECONDS; - -const uint8 MAX_KILL_CREDIT = 2; -const uint32 MAX_CREATURE_MODELS = 4; -const uint32 MAX_CREATURE_QUEST_ITEMS = 6; -const uint32 MAX_CREATURE_SPELLS = 8; - -// from `creature_template` table -struct TC_GAME_API CreatureTemplate -{ - uint32 Entry; - uint32 DifficultyEntry[MAX_DIFFICULTY - 1]; - uint32 KillCredit[MAX_KILL_CREDIT]; - uint32 Modelid1; - uint32 Modelid2; - uint32 Modelid3; - uint32 Modelid4; - std::string Name; - std::string FemaleName; - std::string Title; - std::string IconName; - uint32 GossipMenuId; - uint8 minlevel; - uint8 maxlevel; - uint32 expansion; - uint32 expansionUnknown; // either 0 or 3, sent to the client / wdb - uint32 faction; - uint32 npcflag; - float speed_walk; - float speed_run; - float scale; - uint32 rank; - uint32 dmgschool; - uint32 BaseAttackTime; - uint32 RangeAttackTime; - float BaseVariance; - float RangeVariance; - uint32 unit_class; // enum Classes. Note only 4 classes are known for creatures. - uint32 unit_flags; // enum UnitFlags mask values - uint32 unit_flags2; // enum UnitFlags2 mask values - uint32 dynamicflags; - CreatureFamily family; // enum CreatureFamily values (optional) - uint32 trainer_type; - uint32 trainer_class; - uint32 trainer_race; - uint32 type; // enum CreatureType values - uint32 type_flags; // enum CreatureTypeFlags mask values - uint32 type_flags2; // unknown enum, only set for 4 creatures (with value 1) - uint32 lootid; - uint32 pickpocketLootId; - uint32 SkinLootId; - int32 resistance[MAX_SPELL_SCHOOL]; - uint32 spells[MAX_CREATURE_SPELLS]; - uint32 PetSpellDataId; - uint32 VehicleId; - uint32 mingold; - uint32 maxgold; - std::string AIName; - uint32 MovementType; - uint32 InhabitType; - float HoverHeight; - float ModHealth; - float ModHealthExtra; - float ModMana; - float ModManaExtra; // Added in 4.x, this value is usually 2 for a small group of creatures with double mana - float ModArmor; - float ModDamage; - float ModExperience; - bool RacialLeader; - uint32 movementId; - bool RegenHealth; - uint32 MechanicImmuneMask; - uint32 SpellSchoolImmuneMask; - uint32 flags_extra; - uint32 ScriptID; - uint32 GetRandomValidModelId() const; - uint32 GetFirstValidModelId() const; - uint32 GetFirstInvisibleModel() const; - uint32 GetFirstVisibleModel() const; - - // helpers - SkillType GetRequiredLootSkill() const - { - if (type_flags & CREATURE_TYPE_FLAG_HERB_SKINNING_SKILL) - return SKILL_HERBALISM; - else if (type_flags & CREATURE_TYPE_FLAG_MINING_SKINNING_SKILL) - return SKILL_MINING; - else if (type_flags & CREATURE_TYPE_FLAG_ENGINEERING_SKINNING_SKILL) - return SKILL_ENGINEERING; - else - return SKILL_SKINNING; // normal case - } - - bool IsExotic() const - { - return (type_flags & CREATURE_TYPE_FLAG_EXOTIC_PET) != 0; - } - - bool IsTameable(bool canTameExotic) const - { - 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 - return canTameExotic || !IsExotic(); - } -}; - -typedef std::vector CreatureQuestItemList; -typedef std::unordered_map CreatureQuestItemMap; - -// Benchmarked: Faster than std::map (insert/find) -typedef std::unordered_map CreatureTemplateContainer; - -#pragma pack(push, 1) - -// Defines base stats for creatures (used to calculate HP/mana/armor/attackpower/rangedattackpower/all damage). -struct TC_GAME_API CreatureBaseStats -{ - uint32 BaseHealth[MAX_EXPANSIONS]; - uint32 BaseMana; - uint32 BaseArmor; - uint32 AttackPower; - uint32 RangedAttackPower; - float BaseDamage[MAX_EXPANSIONS]; - - // Helpers - - uint32 GenerateHealth(CreatureTemplate const* info) const - { - return uint32(ceil(BaseHealth[info->expansion] * info->ModHealth * info->ModHealthExtra)); - } - - uint32 GenerateMana(CreatureTemplate const* info) const - { - // Mana can be 0. - if (!BaseMana) - return 0; - - return uint32(ceil(BaseMana * info->ModMana * info->ModManaExtra)); - } - - uint32 GenerateArmor(CreatureTemplate const* info) const - { - return uint32(ceil(BaseArmor * info->ModArmor)); - } - - float GenerateBaseDamage(CreatureTemplate const* info) const - { - return BaseDamage[info->expansion]; - } - - static CreatureBaseStats const* GetBaseStats(uint8 level, uint8 unitClass); -}; - -typedef std::unordered_map CreatureBaseStatsContainer; - -struct CreatureLocale -{ - StringVector Name; - StringVector FemaleName; - StringVector Title; -}; - -struct GossipMenuItemsLocale -{ - StringVector OptionText; - StringVector BoxText; -}; - -struct PointOfInterestLocale -{ - StringVector Name; -}; - -#define MAX_EQUIPMENT_ITEMS 3 - -struct EquipmentInfo -{ - uint32 ItemEntry[MAX_EQUIPMENT_ITEMS]; -}; - -// Benchmarked: Faster than std::map (insert/find) -typedef std::unordered_map EquipmentInfoContainerInternal; -typedef std::unordered_map EquipmentInfoContainer; - -// from `creature` table -struct CreatureData -{ - CreatureData() : id(0), mapid(0), phaseMask(0), displayid(0), equipmentId(0), - posX(0.0f), posY(0.0f), posZ(0.0f), orientation(0.0f), spawntimesecs(0), - spawndist(0.0f), currentwaypoint(0), curhealth(0), curmana(0), movementType(0), - spawnMask(0), npcflag(0), unit_flags(0), dynamicflags(0), phaseUseFlags(0), - phaseId(0), phaseGroup(0), terrainSwapMap(-1), ScriptId(0), dbData(true) { } - uint32 id; // entry in creature_template - uint16 mapid; - uint32 phaseMask; - uint32 displayid; - int8 equipmentId; - float posX; - float posY; - float posZ; - float orientation; - uint32 spawntimesecs; - float spawndist; - uint32 currentwaypoint; - uint32 curhealth; - uint32 curmana; - uint8 movementType; - uint8 spawnMask; - uint32 npcflag; - uint32 unit_flags; // enum UnitFlags mask values - uint32 dynamicflags; - uint8 phaseUseFlags; - uint32 phaseId; - uint32 phaseGroup; - int32 terrainSwapMap; - uint32 ScriptId; - bool dbData; -}; - -struct CreatureModelInfo -{ - float bounding_radius; - float combat_reach; - uint8 gender; - uint32 modelid_other_gender; - bool is_trigger; -}; - -// Benchmarked: Faster than std::map (insert/find) -typedef std::unordered_map CreatureModelContainer; - -enum InhabitTypeValues -{ - INHABIT_GROUND = 1, - INHABIT_WATER = 2, - INHABIT_AIR = 4, - INHABIT_ROOT = 8, - INHABIT_ANYWHERE = INHABIT_GROUND | INHABIT_WATER | INHABIT_AIR | INHABIT_ROOT -}; - -// Enums used by StringTextData::Type (CreatureEventAI) -enum ChatType -{ - CHAT_TYPE_SAY = 0, - CHAT_TYPE_YELL = 1, - CHAT_TYPE_TEXT_EMOTE = 2, - CHAT_TYPE_BOSS_EMOTE = 3, - CHAT_TYPE_WHISPER = 4, - CHAT_TYPE_BOSS_WHISPER = 5, - CHAT_TYPE_ZONE_YELL = 6, - CHAT_TYPE_END = 255 -}; - -#pragma pack(pop) - -// `creature_addon` table -struct CreatureAddon -{ - uint32 path_id; - uint32 mount; - uint32 bytes1; - uint32 bytes2; - uint32 emote; - uint16 aiAnimKit; - uint16 movementAnimKit; - uint16 meleeAnimKit; - std::vector auras; -}; - -typedef std::unordered_map CreatureAddonContainer; -typedef std::unordered_map CreatureAddonTemplateContainer; - -// Vendors -struct VendorItem -{ - VendorItem(uint32 _item, int32 _maxcount, uint32 _incrtime, uint32 _ExtendedCost, uint8 _Type) - : item(_item), maxcount(_maxcount), incrtime(_incrtime), ExtendedCost(_ExtendedCost), Type(_Type) { } - - uint32 item; - uint32 maxcount; // 0 for infinity item amount - uint32 incrtime; // time for restore items amount if maxcount != 0 - uint32 ExtendedCost; - uint8 Type; - - //helpers - bool IsGoldRequired(ItemTemplate const* pProto) const { return (pProto->Flags2 & ITEM_FLAG2_DONT_IGNORE_BUY_PRICE) || !ExtendedCost; } -}; -typedef std::vector VendorItemList; - -struct VendorItemData -{ - VendorItemList m_items; - - VendorItem* GetItem(uint32 slot) const - { - if (slot >= m_items.size()) - return NULL; - - return m_items[slot]; - } - bool Empty() const { return m_items.empty(); } - uint32 GetItemCount() const { return m_items.size(); } - void AddItem(uint32 item, int32 maxcount, uint32 ptime, uint32 ExtendedCost, uint8 type) - { - m_items.push_back(new VendorItem(item, maxcount, ptime, ExtendedCost, type)); - } - bool RemoveItem(uint32 item_id, uint8 type); - VendorItem const* FindItemCostPair(uint32 item_id, uint32 extendedCost, uint8 type) const; - void Clear() - { - for (VendorItemList::const_iterator itr = m_items.begin(); itr != m_items.end(); ++itr) - delete (*itr); - m_items.clear(); - } -}; +enum MovementGeneratorType : uint8; struct VendorItemCount { - explicit VendorItemCount(uint32 _item, uint32 _count) - : itemId(_item), count(_count), lastIncrementTime(time(NULL)) { } + VendorItemCount(uint32 _item, uint32 _count) + : itemId(_item), count(_count), lastIncrementTime(time(nullptr)) { } uint32 itemId; uint32 count; @@ -412,39 +49,6 @@ struct VendorItemCount typedef std::list VendorItemCounts; -struct TrainerSpell -{ - TrainerSpell() : SpellID(0), MoneyCost(0), ReqSkillLine(0), ReqSkillRank(0), ReqLevel(0), Index(0) - { - for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) - ReqAbility[i] = 0; - } - - uint32 SpellID; - uint32 MoneyCost; - uint32 ReqSkillLine; - uint32 ReqSkillRank; - uint32 ReqLevel; - uint32 ReqAbility[3]; - uint32 Index; - - // helpers - bool IsCastable() const { return ReqAbility[0] != SpellID; } -}; - -typedef std::unordered_map TrainerSpellMap; - -struct TC_GAME_API TrainerSpellData -{ - TrainerSpellData() : trainerType(0) { } - ~TrainerSpellData() { spellList.clear(); } - - TrainerSpellMap spellList; - uint32 trainerType; // trainer type based at trainer spells, can be different from creature_template value. - // req. for correct show non-prof. trainers like weaponmaster, allowed values 0 and 2. - TrainerSpell const* Find(uint32 spell_id) const; -}; - // max different by z coordinate for creature aggro reaction #define CREATURE_Z_ATTACK_RANGE 3 @@ -457,7 +61,6 @@ typedef std::unordered_map CreatureTextRepeatGroup class TC_GAME_API Creature : public Unit, public GridObject, public MapObject { public: - explicit Creature(bool isWorldObject = false); virtual ~Creature(); @@ -575,7 +178,7 @@ class TC_GAME_API Creature : public Unit, public GridObject, public Ma Loot loot; void StartPickPocketRefillTimer(); void ResetPickPocketRefillTimer() { _pickpocketLootRestore = 0; } - bool CanGeneratePickPocketLoot() const { return _pickpocketLootRestore <= time(NULL); } + bool CanGeneratePickPocketLoot() const { return _pickpocketLootRestore <= time(nullptr); } void SetSkinner(ObjectGuid guid) { _skinner = guid; } ObjectGuid GetSkinner() const { return _skinner; } // Returns the player who skinned this creature Player* GetLootRecipient() const; @@ -627,7 +230,7 @@ class TC_GAME_API Creature : public Unit, public GridObject, public Ma time_t const& GetRespawnTime() const { return m_respawnTime; } time_t GetRespawnTimeEx() const; - void SetRespawnTime(uint32 respawn) { m_respawnTime = respawn ? time(NULL) + respawn : 0; } + void SetRespawnTime(uint32 respawn) { m_respawnTime = respawn ? time(nullptr) + respawn : 0; } void Respawn(bool force = false); void SaveRespawnTime() override; diff --git a/src/server/game/Entities/Creature/CreatureData.h b/src/server/game/Entities/Creature/CreatureData.h new file mode 100644 index 00000000000..3c6c0c0f5aa --- /dev/null +++ b/src/server/game/Entities/Creature/CreatureData.h @@ -0,0 +1,383 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef CreatureData_h__ +#define CreatureData_h__ + +#include "DBCEnums.h" +#include "SharedDefines.h" +#include "UnitDefines.h" +#include "WorldPacket.h" +#include +#include +#include +#include + +struct ItemTemplate; + +enum CreatureFlagsExtra : uint32 +{ + CREATURE_FLAG_EXTRA_INSTANCE_BIND = 0x00000001, // creature kill bind instance with killer and killer's group + CREATURE_FLAG_EXTRA_CIVILIAN = 0x00000002, // not aggro (ignore faction/reputation hostility) + CREATURE_FLAG_EXTRA_NO_PARRY = 0x00000004, // creature can't parry + CREATURE_FLAG_EXTRA_NO_PARRY_HASTEN = 0x00000008, // creature can't counter-attack at parry + CREATURE_FLAG_EXTRA_NO_BLOCK = 0x00000010, // creature can't block + CREATURE_FLAG_EXTRA_NO_CRUSH = 0x00000020, // creature can't do crush attacks + CREATURE_FLAG_EXTRA_NO_XP_AT_KILL = 0x00000040, // creature kill not provide XP + CREATURE_FLAG_EXTRA_TRIGGER = 0x00000080, // trigger creature + CREATURE_FLAG_EXTRA_NO_TAUNT = 0x00000100, // creature is immune to taunt auras and effect attack me + CREATURE_FLAG_EXTRA_NO_MOVE_FLAGS_UPDATE = 0x00000200, // creature won't update movement flags + CREATURE_FLAG_EXTRA_GHOST_VISIBILITY = 0x00000400, // creature will be only visible for dead players + CREATURE_FLAG_EXTRA_USE_OFFHAND_ATTACK = 0x00000800, // creature will use offhand attacks + CREATURE_FLAG_EXTRA_UNUSED_12 = 0x00001000, + CREATURE_FLAG_EXTRA_UNUSED_13 = 0x00002000, + CREATURE_FLAG_EXTRA_WORLDEVENT = 0x00004000, // custom flag for world event creatures (left room for merging) + CREATURE_FLAG_EXTRA_GUARD = 0x00008000, // Creature is guard + CREATURE_FLAG_EXTRA_UNUSED_16 = 0x00010000, + CREATURE_FLAG_EXTRA_NO_CRIT = 0x00020000, // creature can't do critical strikes + CREATURE_FLAG_EXTRA_NO_SKILLGAIN = 0x00040000, // creature won't increase weapon skills + CREATURE_FLAG_EXTRA_TAUNT_DIMINISH = 0x00080000, // Taunt is a subject to diminishing returns on this creautre + CREATURE_FLAG_EXTRA_ALL_DIMINISH = 0x00100000, // creature is subject to all diminishing returns as player are + CREATURE_FLAG_EXTRA_NO_PLAYER_DAMAGE_REQ = 0x00200000, // creature does not need to take player damage for kill credit + CREATURE_FLAG_EXTRA_UNUSED_22 = 0x00400000, + CREATURE_FLAG_EXTRA_UNUSED_23 = 0x00800000, + CREATURE_FLAG_EXTRA_UNUSED_24 = 0x01000000, + CREATURE_FLAG_EXTRA_UNUSED_25 = 0x02000000, + CREATURE_FLAG_EXTRA_UNUSED_26 = 0x04000000, + CREATURE_FLAG_EXTRA_UNUSED_27 = 0x08000000, + CREATURE_FLAG_EXTRA_DUNGEON_BOSS = 0x10000000, // creature is a dungeon boss (SET DYNAMICALLY, DO NOT ADD IN DB) + CREATURE_FLAG_EXTRA_IGNORE_PATHFINDING = 0x20000000, // creature ignore pathfinding + CREATURE_FLAG_EXTRA_IMMUNITY_KNOCKBACK = 0x40000000, // creature is immune to knockback effects + CREATURE_FLAG_EXTRA_UNUSED_31 = 0x80000000, + + // Masks + CREATURE_FLAG_EXTRA_UNUSED = (CREATURE_FLAG_EXTRA_UNUSED_12 | CREATURE_FLAG_EXTRA_UNUSED_13 | CREATURE_FLAG_EXTRA_UNUSED_16 | + CREATURE_FLAG_EXTRA_UNUSED_22 | CREATURE_FLAG_EXTRA_UNUSED_23 | CREATURE_FLAG_EXTRA_UNUSED_24 | + CREATURE_FLAG_EXTRA_UNUSED_25 | CREATURE_FLAG_EXTRA_UNUSED_26 | CREATURE_FLAG_EXTRA_UNUSED_27 | + CREATURE_FLAG_EXTRA_UNUSED_31), + + CREATURE_FLAG_EXTRA_DB_ALLOWED = (0xFFFFFFFF & ~(CREATURE_FLAG_EXTRA_UNUSED | CREATURE_FLAG_EXTRA_DUNGEON_BOSS)) +}; + +static uint32 const CREATURE_REGEN_INTERVAL = 2 * IN_MILLISECONDS; +static uint32 const CREATURE_NOPATH_EVADE_TIME = 5 * IN_MILLISECONDS; + +static uint8 const MAX_KILL_CREDIT = 2; +static uint32 const MAX_CREATURE_MODELS = 4; +static uint32 const MAX_CREATURE_QUEST_ITEMS = 6; +static uint32 const MAX_CREATURE_SPELLS = 8; + +// from `creature_template` table +struct TC_GAME_API CreatureTemplate +{ + uint32 Entry; + uint32 DifficultyEntry[MAX_DIFFICULTY - 1]; + uint32 KillCredit[MAX_KILL_CREDIT]; + uint32 Modelid1; + uint32 Modelid2; + uint32 Modelid3; + uint32 Modelid4; + std::string Name; + std::string FemaleName; + std::string Title; + std::string IconName; + uint32 GossipMenuId; + uint8 minlevel; + uint8 maxlevel; + uint32 expansion; + uint32 expansionUnknown; // either 0 or 3, sent to the client / wdb + uint32 faction; + uint32 npcflag; + float speed_walk; + float speed_run; + float scale; + uint32 rank; + uint32 dmgschool; + uint32 BaseAttackTime; + uint32 RangeAttackTime; + float BaseVariance; + float RangeVariance; + uint32 unit_class; // enum Classes. Note only 4 classes are known for creatures. + uint32 unit_flags; // enum UnitFlags mask values + uint32 unit_flags2; // enum UnitFlags2 mask values + uint32 dynamicflags; + CreatureFamily family; // enum CreatureFamily values (optional) + uint32 trainer_type; + uint32 trainer_class; + uint32 trainer_race; + uint32 type; // enum CreatureType values + uint32 type_flags; // enum CreatureTypeFlags mask values + uint32 type_flags2; // unknown enum, only set for 4 creatures (with value 1) + uint32 lootid; + uint32 pickpocketLootId; + uint32 SkinLootId; + int32 resistance[MAX_SPELL_SCHOOL]; + uint32 spells[MAX_CREATURE_SPELLS]; + uint32 PetSpellDataId; + uint32 VehicleId; + uint32 mingold; + uint32 maxgold; + std::string AIName; + uint32 MovementType; + uint32 InhabitType; + float HoverHeight; + float ModHealth; + float ModHealthExtra; + float ModMana; + float ModManaExtra; // Added in 4.x, this value is usually 2 for a small group of creatures with double mana + float ModArmor; + float ModDamage; + float ModExperience; + bool RacialLeader; + uint32 movementId; + bool RegenHealth; + uint32 MechanicImmuneMask; + uint32 SpellSchoolImmuneMask; + uint32 flags_extra; + uint32 ScriptID; + uint32 GetRandomValidModelId() const; + uint32 GetFirstValidModelId() const; + uint32 GetFirstInvisibleModel() const; + uint32 GetFirstVisibleModel() const; + + // helpers + SkillType GetRequiredLootSkill() const + { + if (type_flags & CREATURE_TYPE_FLAG_HERB_SKINNING_SKILL) + return SKILL_HERBALISM; + else if (type_flags & CREATURE_TYPE_FLAG_MINING_SKINNING_SKILL) + return SKILL_MINING; + else if (type_flags & CREATURE_TYPE_FLAG_ENGINEERING_SKINNING_SKILL) + return SKILL_ENGINEERING; + else + return SKILL_SKINNING; // normal case + } + + bool IsExotic() const + { + return (type_flags & CREATURE_TYPE_FLAG_EXOTIC_PET) != 0; + } + + bool IsTameable(bool canTameExotic) const + { + 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 + return canTameExotic || !IsExotic(); + } +}; + +#pragma pack(push, 1) + +// Defines base stats for creatures (used to calculate HP/mana/armor/attackpower/rangedattackpower/all damage). +struct TC_GAME_API CreatureBaseStats +{ + uint32 BaseHealth[MAX_EXPANSIONS]; + uint32 BaseMana; + uint32 BaseArmor; + uint32 AttackPower; + uint32 RangedAttackPower; + float BaseDamage[MAX_EXPANSIONS]; + + // Helpers + + uint32 GenerateHealth(CreatureTemplate const* info) const + { + return uint32(ceil(BaseHealth[info->expansion] * info->ModHealth * info->ModHealthExtra)); + } + + uint32 GenerateMana(CreatureTemplate const* info) const + { + // Mana can be 0. + if (!BaseMana) + return 0; + + return uint32(ceil(BaseMana * info->ModMana * info->ModManaExtra)); + } + + uint32 GenerateArmor(CreatureTemplate const* info) const + { + return uint32(ceil(BaseArmor * info->ModArmor)); + } + + float GenerateBaseDamage(CreatureTemplate const* info) const + { + return BaseDamage[info->expansion]; + } + + static CreatureBaseStats const* GetBaseStats(uint8 level, uint8 unitClass); +}; + +typedef std::unordered_map CreatureBaseStatsContainer; + +struct CreatureLocale +{ + std::vector Name; + std::vector FemaleName; + std::vector Title; +}; + +struct EquipmentInfo +{ + uint32 ItemEntry[MAX_EQUIPMENT_ITEMS]; +}; + +// from `creature` table +struct CreatureData +{ + CreatureData() : id(0), mapid(0), phaseMask(0), displayid(0), equipmentId(0), + posX(0.0f), posY(0.0f), posZ(0.0f), orientation(0.0f), spawntimesecs(0), + spawndist(0.0f), currentwaypoint(0), curhealth(0), curmana(0), movementType(0), + spawnMask(0), npcflag(0), unit_flags(0), dynamicflags(0), phaseUseFlags(0), + phaseId(0), phaseGroup(0), terrainSwapMap(-1), ScriptId(0), dbData(true) { } + uint32 id; // entry in creature_template + uint16 mapid; + uint32 phaseMask; + uint32 displayid; + int8 equipmentId; + float posX; + float posY; + float posZ; + float orientation; + uint32 spawntimesecs; + float spawndist; + uint32 currentwaypoint; + uint32 curhealth; + uint32 curmana; + uint8 movementType; + uint8 spawnMask; + uint32 npcflag; + uint32 unit_flags; // enum UnitFlags mask values + uint32 dynamicflags; + uint8 phaseUseFlags; + uint32 phaseId; + uint32 phaseGroup; + int32 terrainSwapMap; + uint32 ScriptId; + bool dbData; +}; + +struct CreatureModelInfo +{ + float bounding_radius; + float combat_reach; + uint8 gender; + uint32 modelid_other_gender; + bool is_trigger; +}; + +enum InhabitTypeValues +{ + INHABIT_GROUND = 1, + INHABIT_WATER = 2, + INHABIT_AIR = 4, + INHABIT_ROOT = 8, + INHABIT_ANYWHERE = INHABIT_GROUND | INHABIT_WATER | INHABIT_AIR | INHABIT_ROOT +}; + +#pragma pack(pop) + +// `creature_addon` table +struct CreatureAddon +{ + uint32 path_id; + uint32 mount; + uint32 bytes1; + uint32 bytes2; + uint32 emote; + uint16 aiAnimKit; + uint16 movementAnimKit; + uint16 meleeAnimKit; + std::vector auras; +}; + +// Vendors +struct VendorItem +{ + VendorItem(uint32 _item, int32 _maxcount, uint32 _incrtime, uint32 _ExtendedCost, uint8 _Type) + : item(_item), maxcount(_maxcount), incrtime(_incrtime), ExtendedCost(_ExtendedCost), Type(_Type) { } + + uint32 item; + uint32 maxcount; // 0 for infinity item amount + uint32 incrtime; // time for restore items amount if maxcount != 0 + uint32 ExtendedCost; + uint8 Type; + + //helpers + bool IsGoldRequired(ItemTemplate const* pProto) const; +}; + +struct VendorItemData +{ + std::vector m_items; + + VendorItem const* GetItem(uint32 slot) const + { + if (slot >= m_items.size()) + return nullptr; + + return &m_items[slot]; + } + bool Empty() const { return m_items.empty(); } + uint32 GetItemCount() const { return m_items.size(); } + void AddItem(uint32 item, int32 maxcount, uint32 ptime, uint32 ExtendedCost, uint8 type) + { + m_items.emplace_back(item, maxcount, ptime, ExtendedCost, type); + } + bool RemoveItem(uint32 item_id, uint8 type); + VendorItem const* FindItemCostPair(uint32 item_id, uint32 extendedCost, uint8 type) const; + void Clear() + { + m_items.clear(); + } +}; + +struct TrainerSpell +{ + TrainerSpell() : SpellID(0), MoneyCost(0), ReqSkillLine(0), ReqSkillRank(0), ReqLevel(0), Index(0) + { + for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) + ReqAbility[i] = 0; + } + + uint32 SpellID; + uint32 MoneyCost; + uint32 ReqSkillLine; + uint32 ReqSkillRank; + uint32 ReqLevel; + uint32 ReqAbility[3]; + uint32 Index; + + // helpers + bool IsCastable() const { return ReqAbility[0] != SpellID; } +}; + +typedef std::unordered_map TrainerSpellMap; + +struct TC_GAME_API TrainerSpellData +{ + TrainerSpellData() : trainerType(0) { } + ~TrainerSpellData() { spellList.clear(); } + + TrainerSpellMap spellList; + uint32 trainerType; // trainer type based at trainer spells, can be different from creature_template value. + // req. for correct show non-prof. trainers like weaponmaster, allowed values 0 and 2. + TrainerSpell const* Find(uint32 spell_id) const; +}; + +#endif // CreatureData_h__ diff --git a/src/server/game/Entities/Creature/CreatureGroups.cpp b/src/server/game/Entities/Creature/CreatureGroups.cpp index 7c16538e334..25e513c5328 100644 --- a/src/server/game/Entities/Creature/CreatureGroups.cpp +++ b/src/server/game/Entities/Creature/CreatureGroups.cpp @@ -16,11 +16,14 @@ * with this program. If not, see . */ -#include "Creature.h" #include "CreatureGroups.h" -#include "ObjectMgr.h" - +#include "Creature.h" #include "CreatureAI.h" +#include "DatabaseEnv.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectMgr.h" #define MAX_DESYNC 5.0f @@ -164,10 +167,10 @@ void CreatureGroup::AddMember(Creature* member) void CreatureGroup::RemoveMember(Creature* member) { if (m_leader == member) - m_leader = NULL; + m_leader = nullptr; m_members.erase(member); - member->SetFormation(NULL); + member->SetFormation(nullptr); } void CreatureGroup::MemberAttackStart(Creature* member, Unit* target) diff --git a/src/server/game/Entities/Creature/CreatureGroups.h b/src/server/game/Entities/Creature/CreatureGroups.h index 41dff797181..f49dfcbdfab 100644 --- a/src/server/game/Entities/Creature/CreatureGroups.h +++ b/src/server/game/Entities/Creature/CreatureGroups.h @@ -20,6 +20,7 @@ #define _FORMATIONS_H #include "Define.h" +#include "ObjectGuid.h" #include #include @@ -34,6 +35,7 @@ enum GroupAIFlags class Creature; class CreatureGroup; +class Unit; struct FormationInfo { @@ -74,7 +76,7 @@ class TC_GAME_API CreatureGroup public: //Group cannot be created empty - explicit CreatureGroup(uint32 id) : m_leader(NULL), m_groupID(id), m_Formed(false) { } + explicit CreatureGroup(uint32 id) : m_leader(nullptr), m_groupID(id), m_Formed(false) { } ~CreatureGroup() { } Creature* getLeader() const { return m_leader; } diff --git a/src/server/game/Entities/Creature/GossipDef.cpp b/src/server/game/Entities/Creature/GossipDef.cpp index 4d0df8b3b7d..9ddc55908ba 100644 --- a/src/server/game/Entities/Creature/GossipDef.cpp +++ b/src/server/game/Entities/Creature/GossipDef.cpp @@ -16,11 +16,11 @@ * with this program. If not, see . */ -#include "QuestDef.h" #include "GossipDef.h" -#include "ObjectMgr.h" -#include "WorldSession.h" #include "Formulas.h" +#include "ObjectMgr.h" +#include "QuestDef.h" +#include "WorldSession.h" GossipMenu::GossipMenu() { @@ -229,7 +229,7 @@ void PlayerMenu::SendGossipMenu(uint32 titleTextId, ObjectGuid objectGUID) std::string title = quest->GetTitle(); LocaleConstant localeConstant = _session->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(questID)) ObjectMgr::GetLocaleString(localeData->Title, localeConstant, title); @@ -263,7 +263,7 @@ void PlayerMenu::SendPointOfInterest(uint32 id) const std::string name = poi->Name; LocaleConstant localeConstant = _session->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) if (PointOfInterestLocale const* localeData = sObjectMgr->GetPointOfInterestLocale(id)) ObjectMgr::GetLocaleString(localeData->Name, localeConstant, name); @@ -365,7 +365,7 @@ void PlayerMenu::SendQuestGiverQuestList(QEmote const& eEmote, const std::string std::string title = quest->GetTitle(); LocaleConstant localeConstant = _session->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) if (QuestLocale const* questTemplateLocaleData = sObjectMgr->GetQuestLocale(questID)) ObjectMgr::GetLocaleString(questTemplateLocaleData->Title, localeConstant, title); @@ -408,7 +408,7 @@ void PlayerMenu::SendQuestGiverQuestDetails(Quest const* quest, ObjectGuid npcGU std::string questTurnTargetName = quest->GetQuestTurnTargetName(); LocaleConstant localeConstant = _session->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) { if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(quest->GetQuestId())) { @@ -476,7 +476,7 @@ void PlayerMenu::SendQuestQueryResponse(Quest const* quest) const questObjectiveText[i] = quest->ObjectiveText[i]; LocaleConstant localeConstant = _session->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) { if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(quest->GetQuestId())) { @@ -640,7 +640,7 @@ void PlayerMenu::SendQuestGiverOfferReward(Quest const* quest, ObjectGuid npcGUI std::string questTurnTargetName = quest->GetQuestTurnTargetName(); LocaleConstant localeConstant = _session->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) { if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(quest->GetQuestId())) { @@ -703,7 +703,7 @@ void PlayerMenu::SendQuestGiverRequestItems(Quest const* quest, ObjectGuid npcGU std::string requestItemsText = quest->GetRequestItemsText(); LocaleConstant localeConstant = _session->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) { if (QuestLocale const* localeData = sObjectMgr->GetQuestLocale(quest->GetQuestId())) { diff --git a/src/server/game/Entities/Creature/GossipDef.h b/src/server/game/Entities/Creature/GossipDef.h index 91b95dff407..63469e22bf3 100644 --- a/src/server/game/Entities/Creature/GossipDef.h +++ b/src/server/game/Entities/Creature/GossipDef.h @@ -21,9 +21,10 @@ #include "Common.h" #include "ObjectGuid.h" -#include "QuestDef.h" #include "NPCHandler.h" +#include +class Quest; class WorldSession; #define GOSSIP_MAX_MENU_ITEMS 32 @@ -193,7 +194,7 @@ class TC_GAME_API GossipMenu if (itr != _menuItems.end()) return &itr->second; - return NULL; + return nullptr; } GossipMenuItemData const* GetItemData(uint32 indexId) const @@ -202,7 +203,7 @@ class TC_GAME_API GossipMenu if (itr != _menuItemData.end()) return &itr->second; - return NULL; + return nullptr; } uint32 GetMenuItemSender(uint32 menuItemId) const; diff --git a/src/server/game/Entities/Creature/TemporarySummon.cpp b/src/server/game/Entities/Creature/TemporarySummon.cpp index b6cfb855f1a..f1f3074b92d 100644 --- a/src/server/game/Entities/Creature/TemporarySummon.cpp +++ b/src/server/game/Entities/Creature/TemporarySummon.cpp @@ -16,10 +16,12 @@ * with this program. If not, see . */ -#include "Log.h" -#include "ObjectAccessor.h" -#include "CreatureAI.h" #include "TemporarySummon.h" +#include "CreatureAI.h" +#include "DBCStructure.h" +#include "Log.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "Pet.h" #include "Player.h" @@ -35,12 +37,12 @@ m_timer(0), m_lifetime(0) Unit* TempSummon::GetSummoner() const { - return m_summonerGUID ? ObjectAccessor::GetUnit(*this, m_summonerGUID) : NULL; + return m_summonerGUID ? ObjectAccessor::GetUnit(*this, m_summonerGUID) : nullptr; } Creature* TempSummon::GetSummonerCreatureBase() const { - return m_summonerGUID ? ObjectAccessor::GetCreature(*this, m_summonerGUID) : NULL; + return m_summonerGUID ? ObjectAccessor::GetCreature(*this, m_summonerGUID) : nullptr; } void TempSummon::Update(uint32 diff) @@ -401,6 +403,6 @@ void Puppet::RemoveFromWorld() if (!IsInWorld()) return; - RemoveCharmedBy(NULL); + RemoveCharmedBy(nullptr); Minion::RemoveFromWorld(); } diff --git a/src/server/game/Entities/Creature/TemporarySummon.h b/src/server/game/Entities/Creature/TemporarySummon.h index 40d2ffc090c..19a907ef8bb 100644 --- a/src/server/game/Entities/Creature/TemporarySummon.h +++ b/src/server/game/Entities/Creature/TemporarySummon.h @@ -21,21 +21,7 @@ #include "Creature.h" -enum SummonerType -{ - SUMMONER_TYPE_CREATURE = 0, - SUMMONER_TYPE_GAMEOBJECT = 1, - SUMMONER_TYPE_MAP = 2 -}; - -/// Stores data for temp summons -struct TempSummonData -{ - uint32 entry; ///< Entry of summoned creature - Position pos; ///< Position, where should be creature spawned - TempSummonType type; ///< Summon type, see TempSummonType for available types - uint32 time; ///< Despawn time, usable only with certain temp summon types -}; +struct SummonPropertiesEntry; class TC_GAME_API TempSummon : public Creature { @@ -56,7 +42,7 @@ class TC_GAME_API TempSummon : public Creature TempSummonType const& GetSummonType() { return m_type; } uint32 GetTimer() const { return m_timer; } - const SummonPropertiesEntry* const m_Properties; + SummonPropertiesEntry const* const m_Properties; private: TempSummonType m_type; uint32 m_timer; diff --git a/src/server/game/Entities/DynamicObject/DynamicObject.cpp b/src/server/game/Entities/DynamicObject/DynamicObject.cpp index dee0038150d..ecacdf8f253 100644 --- a/src/server/game/Entities/DynamicObject/DynamicObject.cpp +++ b/src/server/game/Entities/DynamicObject/DynamicObject.cpp @@ -16,19 +16,22 @@ * with this program. If not, see . */ +#include "DynamicObject.h" #include "Common.h" -#include "UpdateMask.h" -#include "World.h" -#include "ObjectAccessor.h" -#include "DatabaseEnv.h" #include "GameTime.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" +#include "Log.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "SpellAuras.h" +#include "SpellMgr.h" #include "ScriptMgr.h" #include "Transport.h" +#include "Unit.h" +#include "UpdateData.h" DynamicObject::DynamicObject(bool isWorldObject) : WorldObject(isWorldObject), - _aura(NULL), _removedAura(NULL), _caster(NULL), _duration(0), _isViewpoint(false) + _aura(nullptr), _removedAura(nullptr), _caster(nullptr), _duration(0), _isViewpoint(false) { m_objectType |= TYPEMASK_DYNAMICOBJECT; m_objectTypeId = TYPEID_DYNAMICOBJECT; @@ -197,7 +200,7 @@ void DynamicObject::RemoveAura() { ASSERT(_aura && !_removedAura); _removedAura = _aura; - _aura = NULL; + _aura = nullptr; if (!_removedAura->IsRemoved()) _removedAura->_Remove(AURA_REMOVE_BY_DEFAULT); } @@ -233,5 +236,10 @@ void DynamicObject::UnbindFromCaster() { ASSERT(_caster); _caster->_UnregisterDynObject(this); - _caster = NULL; + _caster = nullptr; +} + +SpellInfo const* DynamicObject::GetSpellInfo() const +{ + return sSpellMgr->GetSpellInfo(GetSpellId()); } diff --git a/src/server/game/Entities/DynamicObject/DynamicObject.h b/src/server/game/Entities/DynamicObject/DynamicObject.h index 1f748fef062..85f479780bd 100644 --- a/src/server/game/Entities/DynamicObject/DynamicObject.h +++ b/src/server/game/Entities/DynamicObject/DynamicObject.h @@ -20,6 +20,7 @@ #define TRINITYCORE_DYNAMICOBJECT_H #include "Object.h" +#include "MapObject.h" class Unit; class Aura; @@ -55,7 +56,8 @@ class TC_GAME_API DynamicObject : public WorldObject, public GridObject. */ -#include "GameObjectAI.h" +#include "GameObject.h" +#include "ArchaeologyMgr.h" #include "Battleground.h" #include "CellImpl.h" #include "CreatureAISelector.h" +#include "DatabaseEnv.h" +#include "GameObjectAI.h" #include "GameObjectModel.h" #include "GameTime.h" +#include "GossipDef.h" #include "GridNotifiersImpl.h" #include "Group.h" #include "GroupMgr.h" +#include "Log.h" +#include "LootMgr.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "OutdoorPvPMgr.h" #include "PhasingHandler.h" #include "PoolMgr.h" #include "ScriptMgr.h" #include "SpellMgr.h" +#include "Transport.h" #include "UpdateFieldFlags.h" #include "World.h" -#include "Transport.h" -#include "GossipDef.h" +#include + +bool QuaternionData::isUnit() const +{ + return fabs(x * x + y * y + z * z + w * w - 1.0f) < 1e-5f; +} + +QuaternionData QuaternionData::fromEulerAnglesZYX(float Z, float Y, float X) +{ + G3D::Quat quat(G3D::Matrix3::fromEulerAnglesZYX(Z, Y, X)); + return QuaternionData(quat.x, quat.y, quat.z, quat.w); +} GameObject::GameObject() : WorldObject(false), MapObject(), m_model(nullptr), m_goValue(), m_AI(nullptr) @@ -178,7 +196,7 @@ void GameObject::RemoveFromWorld() } } -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*/) +bool GameObject::Create(ObjectGuid::LowType guidlow, uint32 name_id, Map* map, uint32 /*phaseMask*/, Position const& pos, QuaternionData const& rotation, uint32 animprogress, GOState go_state, uint32 artKit /*= 0*/) { ASSERT(map); @@ -227,11 +245,11 @@ bool GameObject::Create(ObjectGuid::LowType guidlow, uint32 name_id, Map* map, u return false; } - SetWorldRotation(rotation); + SetWorldRotation(rotation.x, rotation.y, rotation.z, rotation.w); 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; + QuaternionData parentRotation; if (gameObjectAddon) parentRotation = gameObjectAddon->ParentRotation; @@ -388,7 +406,10 @@ void GameObject::Update(uint32 diff) { m_goValue.Transport.CurrentSeg = node->TimeSeg; - G3D::Quat rotation = m_goValue.Transport.AnimationInfo->GetAnimRotation(timer); + G3D::Quat rotation; + if (TransportRotationEntry const* rot = m_goValue.Transport.AnimationInfo->GetAnimRotation(timer)) + rotation = G3D::Quat(rot->X, rot->Y, rot->Z, rot->W); + G3D::Vector3 pos = rotation.toRotationMatrix() * G3D::Matrix3::fromEulerAnglesZYX(GetOrientation(), 0.0f, 0.0f) * G3D::Vector3(node->X, node->Y, node->Z); @@ -420,7 +441,7 @@ void GameObject::Update(uint32 diff) case GAMEOBJECT_TYPE_FISHINGNODE: { // fishing code (bobber ready) - if (time(NULL) > m_respawnTime - FISHING_BOBBER_READY_TIME) + if (time(nullptr) > m_respawnTime - FISHING_BOBBER_READY_TIME) { // splash bobber (bobber ready now) Unit* caster = GetOwner(); @@ -452,7 +473,7 @@ void GameObject::Update(uint32 diff) { if (m_respawnTime > 0) // timer on { - time_t now = time(NULL); + time_t now = time(nullptr); if (m_respawnTime <= now) // timer expired { ObjectGuid dbtableHighGuid(HighGuid::GameObject, GetEntry(), m_spawnId); @@ -712,7 +733,7 @@ void GameObject::Update(uint32 diff) return; } - m_respawnTime = time(NULL) + m_respawnDelayTime; + m_respawnTime = time(nullptr) + m_respawnDelayTime; // if option not set then object will be saved at grid unload if (sWorld->getBoolConfig(CONFIG_SAVE_RESPAWN_TIME_IMMEDIATELY)) @@ -829,8 +850,7 @@ void GameObject::SaveToDB() void GameObject::SaveToDB(uint32 mapid, uint8 spawnMask, uint32 phaseMask) { - const GameObjectTemplate* goI = GetGOInfo(); - + GameObjectTemplate const* goI = GetGOInfo(); if (!goI) return; @@ -1029,7 +1049,7 @@ Unit* GameObject::GetOwner() const void GameObject::SaveRespawnTime() { - if (m_goData && m_goData->dbData && m_respawnTime > time(NULL) && m_spawnedByDefault) + if (m_goData && m_goData->dbData && m_respawnTime > time(nullptr) && m_spawnedByDefault) GetMap()->SaveGORespawnTime(m_spawnId, m_respawnTime); } @@ -1082,11 +1102,19 @@ bool GameObject::IsInvisibleDueToDespawn() const return false; } +uint8 GameObject::getLevelForTarget(WorldObject const* target) const +{ + if (Unit* owner = GetOwner()) + return owner->getLevelForTarget(target); + + return 1; +} + void GameObject::Respawn() { if (m_spawnedByDefault && m_respawnTime > 0) { - m_respawnTime = time(NULL); + m_respawnTime = time(nullptr); GetMap()->RemoveGORespawnTime(m_spawnId); } } @@ -1198,7 +1226,7 @@ void GameObject::SetGoArtKit(uint8 kit) void GameObject::SetGoArtKit(uint8 artkit, GameObject* go, ObjectGuid::LowType lowguid) { - const GameObjectData* data = nullptr; + GameObjectData const* data = nullptr; if (go) { go->SetGoArtKit(artkit); @@ -1971,13 +1999,18 @@ void GameObject::UpdatePackedRotation() m_packedRotation = z | (y << 21) | (x << 42); } -void GameObject::SetWorldRotation(G3D::Quat const& rot) +void GameObject::SetWorldRotation(float qx, float qy, float qz, float qw) { - m_worldRotation = rot.toUnit(); + G3D::Quat rotation(qx, qy, qz, qw); + rotation.unitize(); + m_worldRotation.x = rotation.x; + m_worldRotation.y = rotation.y; + m_worldRotation.z = rotation.z; + m_worldRotation.w = rotation.w; UpdatePackedRotation(); } -void GameObject::SetParentRotation(G3D::Quat const& rotation) +void GameObject::SetParentRotation(QuaternionData const& rotation) { SetFloatValue(GAMEOBJECT_PARENTROTATION + 0, rotation.x); SetFloatValue(GAMEOBJECT_PARENTROTATION + 1, rotation.y); @@ -1987,7 +2020,8 @@ void GameObject::SetParentRotation(G3D::Quat const& rotation) void GameObject::SetWorldRotationAngles(float z_rot, float y_rot, float x_rot) { - SetWorldRotation(G3D::Quat(G3D::Matrix3::fromEulerAnglesZYX(z_rot, y_rot, x_rot))); + G3D::Quat quat(G3D::Matrix3::fromEulerAnglesZYX(z_rot, y_rot, x_rot)); + SetWorldRotation(quat.x, quat.y, quat.z, quat.w); } void GameObject::ModifyHealth(int32 change, Unit* attackerOrHealer /*= nullptr*/, uint32 spellId /*= 0*/) diff --git a/src/server/game/Entities/GameObject/GameObject.h b/src/server/game/Entities/GameObject/GameObject.h index 5780342bab8..0b82b915935 100644 --- a/src/server/game/Entities/GameObject/GameObject.h +++ b/src/server/game/Entities/GameObject/GameObject.h @@ -19,568 +19,21 @@ #ifndef TRINITYCORE_GAMEOBJECT_H #define TRINITYCORE_GAMEOBJECT_H -#include "Common.h" -#include "SharedDefines.h" -#include "Unit.h" #include "Object.h" -#include "LootMgr.h" -#include "DatabaseEnv.h" -#include +#include "DatabaseEnvFwd.h" +#include "GameObjectData.h" +#include "Loot.h" +#include "MapObject.h" +#include "SharedDefines.h" class GameObjectAI; +class GameObjectModel; class Group; -class Transport; - -#define MAX_GAMEOBJECT_QUEST_ITEMS 6 - -// from `gameobject_template` -struct GameObjectTemplate -{ - uint32 entry; - uint32 type; - uint32 displayId; - std::string name; - std::string IconName; - std::string castBarCaption; - std::string unk1; - float size; - int32 RequiredLevel; - union // different GO types have different data field - { - //0 GAMEOBJECT_TYPE_DOOR - struct - { - uint32 startOpen; //0 used client side to determine GO_ACTIVATED means open/closed - uint32 lockId; //1 -> Lock.dbc - uint32 autoCloseTime; //2 secs till autoclose = autoCloseTime / 0x10000 - uint32 noDamageImmune; //3 break opening whenever you recieve damage? - uint32 openTextID; //4 can be used to replace castBarCaption? - uint32 closeTextID; //5 - uint32 ignoredByPathing; //6 - uint32 conditionID1; //7 - } door; - //1 GAMEOBJECT_TYPE_BUTTON - struct - { - uint32 startOpen; //0 - uint32 lockId; //1 -> Lock.dbc - uint32 autoCloseTime; //2 secs till autoclose = autoCloseTime / 0x10000 - uint32 linkedTrap; //3 - uint32 noDamageImmune; //4 isBattlegroundObject - uint32 large; //5 - uint32 openTextID; //6 can be used to replace castBarCaption? - uint32 closeTextID; //7 - uint32 losOK; //8 - uint32 conditionID1; //9 - } button; - //2 GAMEOBJECT_TYPE_QUESTGIVER - struct - { - uint32 lockId; //0 -> Lock.dbc - uint32 questList; //1 - uint32 pageMaterial; //2 - uint32 gossipID; //3 - uint32 customAnim; //4 - uint32 noDamageImmune; //5 - uint32 openTextID; //6 can be used to replace castBarCaption? - 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 - { - uint32 lockId; //0 -> Lock.dbc - uint32 lootId; //1 - uint32 chestRestockTime; //2 - uint32 consumable; //3 - uint32 minSuccessOpens; //4 Deprecated, pre 3.0 was used for mining nodes but since WotLK all mining nodes are usable once and grant all loot with a single use - uint32 maxSuccessOpens; //5 Deprecated, pre 3.0 was used for mining nodes but since WotLK all mining nodes are usable once and grant all loot with a single use - uint32 eventId; //6 lootedEvent - uint32 linkedTrapId; //7 - uint32 questId; //8 not used currently but store quest required for GO activation for player - uint32 level; //9 - uint32 losOK; //10 - uint32 leaveLoot; //11 - uint32 notInCombat; //12 - uint32 logLoot; //13 - 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 - struct - { - uint32 floatingTooltip; //0 - uint32 highlight; //1 - uint32 serverOnly; //2 - uint32 large; //3 - uint32 floatOnWater; //4 - int32 questID; //5 - uint32 conditionID1; //6 - } _generic; - //6 GAMEOBJECT_TYPE_TRAP - struct - { - uint32 lockId; //0 -> Lock.dbc - uint32 level; //1 - uint32 diameter; //2 diameter for trap activation - uint32 spellId; //3 - uint32 type; //4 0 trap with no despawn after cast. 1 trap despawns after cast. 2 bomb casts on spawn. - uint32 cooldown; //5 time in secs - int32 autoCloseTime; //6 - uint32 startDelay; //7 - uint32 serverOnly; //8 - uint32 stealthed; //9 - uint32 large; //10 - uint32 invisible; //11 - uint32 openTextID; //12 can be used to replace castBarCaption? - uint32 closeTextID; //13 - uint32 ignoreTotems; //14 - uint32 conditionID1; //15 - } trap; - //7 GAMEOBJECT_TYPE_CHAIR - struct - { - uint32 slots; //0 - uint32 height; //1 - uint32 onlyCreatorUse; //2 - uint32 triggeredEvent; //3 - uint32 conditionID1; //4 - } chair; - //8 GAMEOBJECT_TYPE_SPELL_FOCUS - struct - { - uint32 focusId; //0 - uint32 dist; //1 - uint32 linkedTrapId; //2 - uint32 serverOnly; //3 - uint32 questID; //4 - uint32 large; //5 - uint32 floatingTooltip; //6 - uint32 floatOnWater; //7 - uint32 conditionID1; //8 - } spellFocus; - //9 GAMEOBJECT_TYPE_TEXT - struct - { - uint32 pageID; //0 - 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 - { - uint32 lockId; //0 -> Lock.dbc - int32 questId; //1 - uint32 eventId; //2 - uint32 autoCloseTime; //3 - uint32 customAnim; //4 - uint32 consumable; //5 - uint32 cooldown; //6 - uint32 pageId; //7 - uint32 language; //8 - uint32 pageMaterial; //9 - uint32 spellId; //10 - uint32 noDamageImmune; //11 - uint32 linkedTrapId; //12 - uint32 large; //13 - uint32 openTextID; //14 can be used to replace castBarCaption? - uint32 closeTextID; //15 - uint32 losOK; //16 isBattlegroundObject - uint32 allowMounted; //17 Is usable while on mount/vehicle. (0/1) - uint32 floatingTooltip; //18 - uint32 gossipID; //19 - uint32 WorldStateSetsState; //20 - uint32 floatOnWater; //21 - uint32 conditionID1; //22 - } goober; - //11 GAMEOBJECT_TYPE_TRANSPORT - struct - { - int32 stopFrame1; //0 - uint32 startOpen; //1 - uint32 autoCloseTime; //2 secs till autoclose = autoCloseTime / 0x10000 - uint32 pause1EventID; //3 - uint32 pause2EventID; //4 - uint32 mapId; //5 - int32 stopFrame2; //6 - uint32 unknown; - int32 stopFrame3; //8 - uint32 unknown2; - int32 stopFrame4; //10 - } transport; - //12 GAMEOBJECT_TYPE_AREADAMAGE - struct - { - uint32 lockId; //0 - uint32 radius; //1 - uint32 damageMin; //2 - uint32 damageMax; //3 - uint32 damageSchool; //4 - uint32 autoCloseTime; //5 secs till autoclose = autoCloseTime / 0x10000 - uint32 openTextID; //6 - uint32 closeTextID; //7 - } areadamage; - //13 GAMEOBJECT_TYPE_CAMERA - struct - { - uint32 lockId; //0 -> Lock.dbc - 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 - struct - { - uint32 taxiPathId; //0 - uint32 moveSpeed; //1 - uint32 accelRate; //2 - uint32 startEventID; //3 - uint32 stopEventID; //4 - uint32 transportPhysics; //5 - uint32 mapID; //6 - uint32 worldState1; //7 - uint32 canBeStopped; //8 - } moTransport; - //16 GAMEOBJECT_TYPE_DUELFLAG - empty - //17 GAMEOBJECT_TYPE_FISHINGNODE - empty - //18 GAMEOBJECT_TYPE_SUMMONING_RITUAL - struct - { - uint32 reqParticipants; //0 - uint32 spellId; //1 - uint32 animSpell; //2 - uint32 ritualPersistent; //3 - uint32 casterTargetSpell; //4 - uint32 casterTargetSpellTargets; //5 - uint32 castersGrouped; //6 - uint32 ritualNoTargetCheck; //7 - } summoningRitual; - //19 GAMEOBJECT_TYPE_MAILBOX - struct - { - uint32 conditionID1; //0 - } mailbox; - //20 GAMEOBJECT_TYPE_DO_NOT_USE - empty - //21 GAMEOBJECT_TYPE_GUARDPOST - struct - { - uint32 creatureID; //0 - uint32 charges; //1 - } guardpost; - //22 GAMEOBJECT_TYPE_SPELLCASTER - struct - { - uint32 spellId; //0 - uint32 charges; //1 - 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 - { - uint32 minLevel; //0 - uint32 maxLevel; //1 - uint32 areaID; //2 - } meetingstone; - //24 GAMEOBJECT_TYPE_FLAGSTAND - struct - { - uint32 lockId; //0 - uint32 pickupSpell; //1 - uint32 radius; //2 - uint32 returnAura; //3 - uint32 returnSpell; //4 - uint32 noDamageImmune; //5 - uint32 openTextID; //6 - uint32 losOK; //7 - } flagstand; - //25 GAMEOBJECT_TYPE_FISHINGHOLE - struct - { - uint32 radius; //0 how close bobber must land for sending loot - uint32 lootId; //1 - uint32 minSuccessOpens; //2 - uint32 maxSuccessOpens; //3 - uint32 lockId; //4 -> Lock.dbc; possibly 1628 for all? - } fishinghole; - //26 GAMEOBJECT_TYPE_FLAGDROP - struct - { - uint32 lockId; //0 - uint32 eventID; //1 - uint32 pickupSpell; //2 - uint32 noDamageImmune; //3 - uint32 openTextID; //4 - } flagdrop; - //27 GAMEOBJECT_TYPE_MINI_GAME - struct - { - uint32 gameType; //0 - } miniGame; - //29 GAMEOBJECT_TYPE_CAPTURE_POINT - struct - { - uint32 radius; //0 - uint32 spell; //1 - uint32 worldState1; //2 - uint32 worldstate2; //3 - uint32 winEventID1; //4 - uint32 winEventID2; //5 - uint32 contestedEventID1; //6 - uint32 contestedEventID2; //7 - uint32 progressEventID1; //8 - uint32 progressEventID2; //9 - uint32 neutralEventID1; //10 - uint32 neutralEventID2; //11 - uint32 neutralPercent; //12 - uint32 worldstate3; //13 - uint32 minSuperiority; //14 - uint32 maxSuperiority; //15 - uint32 minTime; //16 - uint32 maxTime; //17 - uint32 large; //18 - uint32 highlight; //19 - uint32 startingValue; //20 - uint32 unidirectional; //21 - } capturePoint; - //30 GAMEOBJECT_TYPE_AURA_GENERATOR - struct - { - uint32 startOpen; //0 - uint32 radius; //1 - uint32 auraID1; //2 - uint32 conditionID1; //3 - uint32 auraID2; //4 - uint32 conditionID2; //5 - uint32 serverOnly; //6 - } auraGenerator; - //31 GAMEOBJECT_TYPE_DUNGEON_DIFFICULTY - struct - { - uint32 mapID; //0 - uint32 difficulty; //1 - } dungeonDifficulty; - //32 GAMEOBJECT_TYPE_BARBER_CHAIR - struct - { - uint32 chairheight; //0 - uint32 heightOffset; //1 - } barberChair; - //33 GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING - struct - { - uint32 intactNumHits; //0 - uint32 creditProxyCreature; //1 - uint32 empty1; //2 - uint32 intactEvent; //3 - uint32 empty2; //4 - uint32 damagedNumHits; //5 - uint32 empty3; //6 - uint32 empty4; //7 - uint32 empty5; //8 - uint32 damagedEvent; //9 - uint32 empty6; //10 - uint32 empty7; //11 - uint32 empty8; //12 - uint32 empty9; //13 - uint32 destroyedEvent; //14 - uint32 empty10; //15 - uint32 rebuildingTimeSecs; //16 - uint32 empty11; //17 - uint32 destructibleData; //18 - uint32 rebuildingEvent; //19 - uint32 empty12; //20 - uint32 empty13; //21 - uint32 damageEvent; //22 - uint32 empty14; //23 - } building; - //34 GAMEOBJECT_TYPE_GUILDBANK - struct - { - uint32 conditionID1; //0 - } guildbank; - //35 GAMEOBJECT_TYPE_TRAPDOOR - struct - { - uint32 whenToPause; // 0 - uint32 startOpen; // 1 - uint32 autoClose; // 2 - } trapDoor; - - // not use for specific field access (only for output with loop by all filed), also this determinate max union size - struct - { - uint32 data[MAX_GAMEOBJECT_DATA]; - } raw; - }; - - std::string AIName; - uint32 ScriptId; - - // helpers - bool IsDespawnAtAction() const - { - switch (type) - { - case GAMEOBJECT_TYPE_CHEST: return chest.consumable != 0; - case GAMEOBJECT_TYPE_GOOBER: return goober.consumable != 0; - default: return false; - } - } - - bool IsUsableMounted() const - { - switch (type) - { - case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.allowMounted != 0; - case GAMEOBJECT_TYPE_TEXT: return text.allowMounted != 0; - case GAMEOBJECT_TYPE_GOOBER: return goober.allowMounted != 0; - case GAMEOBJECT_TYPE_SPELLCASTER: return spellcaster.allowMounted != 0; - default: return false; - } - } - - uint32 GetLockId() const - { - switch (type) - { - case GAMEOBJECT_TYPE_DOOR: return door.lockId; - case GAMEOBJECT_TYPE_BUTTON: return button.lockId; - case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.lockId; - case GAMEOBJECT_TYPE_CHEST: return chest.lockId; - case GAMEOBJECT_TYPE_TRAP: return trap.lockId; - case GAMEOBJECT_TYPE_GOOBER: return goober.lockId; - case GAMEOBJECT_TYPE_AREADAMAGE: return areadamage.lockId; - case GAMEOBJECT_TYPE_CAMERA: return camera.lockId; - case GAMEOBJECT_TYPE_FLAGSTAND: return flagstand.lockId; - case GAMEOBJECT_TYPE_FISHINGHOLE:return fishinghole.lockId; - case GAMEOBJECT_TYPE_FLAGDROP: return flagdrop.lockId; - default: return 0; - } - } - - bool GetDespawnPossibility() const // despawn at targeting of cast? - { - switch (type) - { - case GAMEOBJECT_TYPE_DOOR: return door.noDamageImmune != 0; - case GAMEOBJECT_TYPE_BUTTON: return button.noDamageImmune != 0; - case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.noDamageImmune != 0; - case GAMEOBJECT_TYPE_GOOBER: return goober.noDamageImmune != 0; - case GAMEOBJECT_TYPE_FLAGSTAND: return flagstand.noDamageImmune != 0; - case GAMEOBJECT_TYPE_FLAGDROP: return flagdrop.noDamageImmune != 0; - default: return true; - } - } - - uint32 GetCharges() const // despawn at uses amount - { - switch (type) - { - //case GAMEOBJECT_TYPE_TRAP: return trap.charges; - case GAMEOBJECT_TYPE_GUARDPOST: return guardpost.charges; - case GAMEOBJECT_TYPE_SPELLCASTER: return spellcaster.charges; - default: return 0; - } - } - - uint32 GetLinkedGameObjectEntry() const - { - switch (type) - { - case GAMEOBJECT_TYPE_BUTTON: return button.linkedTrap; - case GAMEOBJECT_TYPE_CHEST: return chest.linkedTrapId; - case GAMEOBJECT_TYPE_SPELL_FOCUS: return spellFocus.linkedTrapId; - case GAMEOBJECT_TYPE_GOOBER: return goober.linkedTrapId; - default: return 0; - } - } - - uint32 GetAutoCloseTime() const - { - uint32 autoCloseTime = 0; - switch (type) - { - case GAMEOBJECT_TYPE_DOOR: autoCloseTime = door.autoCloseTime; break; - case GAMEOBJECT_TYPE_BUTTON: autoCloseTime = button.autoCloseTime; break; - case GAMEOBJECT_TYPE_TRAP: autoCloseTime = trap.autoCloseTime; break; - case GAMEOBJECT_TYPE_GOOBER: autoCloseTime = goober.autoCloseTime; break; - case GAMEOBJECT_TYPE_TRANSPORT: autoCloseTime = transport.autoCloseTime; break; - case GAMEOBJECT_TYPE_AREADAMAGE: autoCloseTime = areadamage.autoCloseTime; break; - default: break; - } - return autoCloseTime; // prior to 3.0.3, conversion was / 0x10000; - } - - uint32 GetLootId() const - { - switch (type) - { - case GAMEOBJECT_TYPE_CHEST: return chest.lootId; - case GAMEOBJECT_TYPE_FISHINGHOLE: return fishinghole.lootId; - default: return 0; - } - } - - uint32 GetGossipMenuId() const - { - switch (type) - { - case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.gossipID; - case GAMEOBJECT_TYPE_GOOBER: return goober.gossipID; - default: return 0; - } - } - - uint32 GetEventScriptId() const - { - switch (type) - { - case GAMEOBJECT_TYPE_GOOBER: return goober.eventId; - case GAMEOBJECT_TYPE_CHEST: return chest.eventId; - case GAMEOBJECT_TYPE_CAMERA: return camera.eventID; - default: return 0; - } - } - - uint32 GetCooldown() const // Cooldown preventing goober and traps to cast spell - { - switch (type) - { - case GAMEOBJECT_TYPE_TRAP: return trap.cooldown; - case GAMEOBJECT_TYPE_GOOBER: return goober.cooldown; - default: return 0; - } - } -}; - -// From `gameobject_template_addon` -struct GameObjectTemplateAddon -{ - uint32 entry; - uint32 faction; - uint32 flags; - uint32 mingold; - uint32 maxgold; -}; - -// Benchmarked: Faster than std::map (insert/find) -typedef std::unordered_map GameObjectTemplateContainer; -typedef std::unordered_map GameObjectTemplateAddonContainer; - class OPvPCapturePoint; +class Transport; +class Unit; struct TransportAnimation; +enum TriggerCastFlags : uint32; union GameObjectValue { @@ -611,65 +64,6 @@ union GameObjectValue } Building; }; -struct GameObjectLocale -{ - StringVector Name; - StringVector CastBarCaption; -}; - -// `gameobject_addon` table -struct GameObjectAddon -{ - G3D::Quat ParentRotation; - InvisibilityType invisibilityType; - uint32 InvisibilityValue; -}; - -typedef std::unordered_map GameObjectAddonContainer; - -// client side GO show states -enum GOState -{ - GO_STATE_ACTIVE = 0, // show in world as used and not reset (closed door open) - GO_STATE_READY = 1, // show in world as ready (closed door close) - GO_STATE_ACTIVE_ALTERNATIVE = 2, // show in world as used in alt way and not reset (closed door open by cannon fire) - GO_STATE_TRANSPORT_ACTIVE = 24, - GO_STATE_TRANSPORT_STOPPED = 25 -}; - -#define MAX_GO_STATE 3 -#define MAX_GO_STATE_TRANSPORT_STOP_FRAMES 9 - -// from `gameobject` -struct GameObjectData -{ - 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), phaseUseFlags(0), phaseId(0), - phaseGroup(0), terrainSwapMap(-1), ScriptId(0), dbData(true) { } - uint32 id; // entry in gamobject_template - uint16 mapid; - uint32 phaseMask; - float posX; - float posY; - float posZ; - float orientation; - G3D::Quat rotation; - int32 spawntimesecs; - uint32 animprogress; - GOState go_state; - uint8 spawnMask; - uint8 artKit; - uint8 phaseUseFlags; - uint32 phaseId; - uint32 phaseGroup; - int32 terrainSwapMap; - uint32 ScriptId; - bool dbData; -}; - -typedef std::vector GameObjectQuestItemList; -typedef std::unordered_map GameObjectQuestItemMap; - // For containers: [GO_NOT_READY]->GO_READY (close)->GO_ACTIVATED (open) ->GO_JUST_DEACTIVATED->GO_READY -> ... // For bobber: GO_NOT_READY ->GO_READY (close)->GO_ACTIVATED (open) ->GO_JUST_DEACTIVATED-> // For door(closed):[GO_NOT_READY]->GO_READY (close)->GO_ACTIVATED (open) ->GO_JUST_DEACTIVATED->GO_READY(close) -> ... @@ -682,9 +76,6 @@ enum LootState GO_JUST_DEACTIVATED }; -class Unit; -class GameObjectModel; - // 5 sec for bobber catch #define FISHING_BOBBER_READY_TIME 5 @@ -700,7 +91,7 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject void RemoveFromWorld() override; void CleanupsBeforeDelete(bool finalCleanup = true) override; - 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); + bool Create(ObjectGuid::LowType guidlow, uint32 name_id, Map* map, uint32 phaseMask, Position const& pos, QuaternionData const& rotation, uint32 animprogress, GOState go_state, uint32 artKit = 0); void Update(uint32 p_time) override; GameObjectTemplate const* GetGOInfo() const { return m_goInfo; } GameObjectTemplateAddon const* GetTemplateAddon() const { return m_goTemplateAddon; } @@ -715,9 +106,8 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject // 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); - G3D::Quat const& GetWorldRotation() const { return m_worldRotation; } - void SetParentRotation(G3D::Quat const& rotation); // transforms(rotates) transport's path + void SetWorldRotation(float qx, float qy, float qz, float qw); + void SetParentRotation(QuaternionData const& rotation); // transforms(rotates) transport's path int64 GetPackedWorldRotation() const { return m_packedRotation; } // overwrite WorldObject function for proper name localization @@ -752,7 +142,7 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject time_t GetRespawnTime() const { return m_respawnTime; } time_t GetRespawnTimeEx() const { - time_t now = time(NULL); + time_t now = time(nullptr); if (m_respawnTime > now) return m_respawnTime; else @@ -761,7 +151,7 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject void SetRespawnTime(int32 respawn) { - m_respawnTime = respawn > 0 ? time(NULL) + respawn : 0; + m_respawnTime = respawn > 0 ? time(nullptr) + respawn : 0; m_respawnDelayTime = respawn > 0 ? respawn : 0; } void Respawn(); @@ -798,7 +188,7 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject LootState getLootState() const { return m_lootState; } // Note: unit is only used when s = GO_ACTIVATED - void SetLootState(LootState s, Unit* unit = NULL); + void SetLootState(LootState s, Unit* unit = nullptr); uint16 GetLootMode() const { return m_LootMode; } bool HasLootMode(uint16 lootMode) const { return (m_LootMode & lootMode) != 0; } @@ -844,7 +234,7 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject bool hasQuest(uint32 quest_id) const override; bool hasInvolvedQuest(uint32 quest_id) const override; bool ActivateToQuest(Player* target) const; - void UseDoorOrButton(uint32 time_to_restore = 0, bool alternative = false, Unit* user = NULL); + void UseDoorOrButton(uint32 time_to_restore = 0, bool alternative = false, Unit* user = nullptr); // 0 = use `gameobject`.`spawntimesecs` void ResetDoorOrButton(); @@ -855,13 +245,7 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject bool IsAlwaysVisibleFor(WorldObject const* seer) const override; bool IsInvisibleDueToDespawn() const override; - uint8 getLevelForTarget(WorldObject const* target) const override - { - if (Unit* owner = GetOwner()) - return owner->getLevelForTarget(target); - - return 1; - } + uint8 getLevelForTarget(WorldObject const* target) const override; GameObject* LookupFishingHoleAround(float range); @@ -870,9 +254,9 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject void SendCustomAnim(uint32 anim); bool IsInRange(float x, float y, float z, float radius) const; - void ModifyHealth(int32 change, Unit* attackerOrHealer = NULL, uint32 spellId = 0); + void ModifyHealth(int32 change, Unit* attackerOrHealer = nullptr, uint32 spellId = 0); // sets GameObject type 33 destruction flags and optionally default health for that state - void SetDestructibleState(GameObjectDestructibleState state, Player* eventInvoker = NULL, bool setHealth = false); + void SetDestructibleState(GameObjectDestructibleState state, Player* eventInvoker = nullptr, bool setHealth = false); GameObjectDestructibleState GetDestructibleState() const { if (HasFlag(GAMEOBJECT_FLAGS, GO_FLAG_DESTROYED)) @@ -882,7 +266,7 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject return GO_DESTRUCTIBLE_INTACT; } - void EventInform(uint32 eventId, WorldObject* invoker = NULL); + void EventInform(uint32 eventId, WorldObject* invoker = nullptr); virtual uint32 GetScriptId() const; GameObjectAI* AI() const { return m_AI; } @@ -895,10 +279,10 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject void SetFaction(uint32 faction) { SetUInt32Value(GAMEOBJECT_FACTION, faction); } GameObjectModel* m_model; - void GetRespawnPosition(float &x, float &y, float &z, float* ori = NULL) const; + void GetRespawnPosition(float &x, float &y, float &z, float* ori = nullptr) const; - Transport* ToTransport() { if (GetGOInfo()->type == GAMEOBJECT_TYPE_MO_TRANSPORT) return reinterpret_cast(this); else return NULL; } - Transport const* ToTransport() const { if (GetGOInfo()->type == GAMEOBJECT_TYPE_MO_TRANSPORT) return reinterpret_cast(this); else return NULL; } + Transport* ToTransport() { if (GetGOInfo()->type == GAMEOBJECT_TYPE_MO_TRANSPORT) return reinterpret_cast(this); else return nullptr; } + Transport const* ToTransport() const { if (GetGOInfo()->type == GAMEOBJECT_TYPE_MO_TRANSPORT) return reinterpret_cast(this); else return nullptr; } float GetStationaryX() const override { if (GetGOInfo()->type != GAMEOBJECT_TYPE_MO_TRANSPORT) return m_stationaryPosition.GetPositionX(); return GetPositionX(); } float GetStationaryY() const override { if (GetGOInfo()->type != GAMEOBJECT_TYPE_MO_TRANSPORT) return m_stationaryPosition.GetPositionY(); return GetPositionY(); } @@ -942,7 +326,7 @@ class TC_GAME_API GameObject : public WorldObject, public GridObject GameObjectValue m_goValue; int64 m_packedRotation; - G3D::Quat m_worldRotation; + QuaternionData m_worldRotation; Position m_stationaryPosition; ObjectGuid m_lootRecipient; diff --git a/src/server/game/Entities/GameObject/GameObjectData.h b/src/server/game/Entities/GameObject/GameObjectData.h new file mode 100644 index 00000000000..d86d2bd4448 --- /dev/null +++ b/src/server/game/Entities/GameObject/GameObjectData.h @@ -0,0 +1,624 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef GameObjectData_h__ +#define GameObjectData_h__ + +#include "Common.h" +#include "SharedDefines.h" +#include "WorldPacket.h" +#include +#include + + +#define MAX_GAMEOBJECT_QUEST_ITEMS 6 + +// from `gameobject_template` +struct GameObjectTemplate +{ + uint32 entry; + uint32 type; + uint32 displayId; + std::string name; + std::string IconName; + std::string castBarCaption; + std::string unk1; + float size; + int32 RequiredLevel; + union // different GO types have different data field + { + //0 GAMEOBJECT_TYPE_DOOR + struct + { + uint32 startOpen; //0 used client side to determine GO_ACTIVATED means open/closed + uint32 lockId; //1 -> Lock.dbc + uint32 autoCloseTime; //2 secs till autoclose = autoCloseTime / 0x10000 + uint32 noDamageImmune; //3 break opening whenever you recieve damage? + uint32 openTextID; //4 can be used to replace castBarCaption? + uint32 closeTextID; //5 + uint32 ignoredByPathing; //6 + uint32 conditionID1; //7 + } door; + //1 GAMEOBJECT_TYPE_BUTTON + struct + { + uint32 startOpen; //0 + uint32 lockId; //1 -> Lock.dbc + uint32 autoCloseTime; //2 secs till autoclose = autoCloseTime / 0x10000 + uint32 linkedTrap; //3 + uint32 noDamageImmune; //4 isBattlegroundObject + uint32 large; //5 + uint32 openTextID; //6 can be used to replace castBarCaption? + uint32 closeTextID; //7 + uint32 losOK; //8 + uint32 conditionID1; //9 + } button; + //2 GAMEOBJECT_TYPE_QUESTGIVER + struct + { + uint32 lockId; //0 -> Lock.dbc + uint32 questList; //1 + uint32 pageMaterial; //2 + uint32 gossipID; //3 + uint32 customAnim; //4 + uint32 noDamageImmune; //5 + uint32 openTextID; //6 can be used to replace castBarCaption? + 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 + { + uint32 lockId; //0 -> Lock.dbc + uint32 lootId; //1 + uint32 chestRestockTime; //2 + uint32 consumable; //3 + uint32 minSuccessOpens; //4 Deprecated, pre 3.0 was used for mining nodes but since WotLK all mining nodes are usable once and grant all loot with a single use + uint32 maxSuccessOpens; //5 Deprecated, pre 3.0 was used for mining nodes but since WotLK all mining nodes are usable once and grant all loot with a single use + uint32 eventId; //6 lootedEvent + uint32 linkedTrapId; //7 + uint32 questId; //8 not used currently but store quest required for GO activation for player + uint32 level; //9 + uint32 losOK; //10 + uint32 leaveLoot; //11 + uint32 notInCombat; //12 + uint32 logLoot; //13 + 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 + struct + { + uint32 floatingTooltip; //0 + uint32 highlight; //1 + uint32 serverOnly; //2 + uint32 large; //3 + uint32 floatOnWater; //4 + int32 questID; //5 + uint32 conditionID1; //6 + } _generic; + //6 GAMEOBJECT_TYPE_TRAP + struct + { + uint32 lockId; //0 -> Lock.dbc + uint32 level; //1 + uint32 diameter; //2 diameter for trap activation + uint32 spellId; //3 + uint32 type; //4 0 trap with no despawn after cast. 1 trap despawns after cast. 2 bomb casts on spawn. + uint32 cooldown; //5 time in secs + int32 autoCloseTime; //6 + uint32 startDelay; //7 + uint32 serverOnly; //8 + uint32 stealthed; //9 + uint32 large; //10 + uint32 invisible; //11 + uint32 openTextID; //12 can be used to replace castBarCaption? + uint32 closeTextID; //13 + uint32 ignoreTotems; //14 + uint32 conditionID1; //15 + } trap; + //7 GAMEOBJECT_TYPE_CHAIR + struct + { + uint32 slots; //0 + uint32 height; //1 + uint32 onlyCreatorUse; //2 + uint32 triggeredEvent; //3 + uint32 conditionID1; //4 + } chair; + //8 GAMEOBJECT_TYPE_SPELL_FOCUS + struct + { + uint32 focusId; //0 + uint32 dist; //1 + uint32 linkedTrapId; //2 + uint32 serverOnly; //3 + uint32 questID; //4 + uint32 large; //5 + uint32 floatingTooltip; //6 + uint32 floatOnWater; //7 + uint32 conditionID1; //8 + } spellFocus; + //9 GAMEOBJECT_TYPE_TEXT + struct + { + uint32 pageID; //0 + 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 + { + uint32 lockId; //0 -> Lock.dbc + int32 questId; //1 + uint32 eventId; //2 + uint32 autoCloseTime; //3 + uint32 customAnim; //4 + uint32 consumable; //5 + uint32 cooldown; //6 + uint32 pageId; //7 + uint32 language; //8 + uint32 pageMaterial; //9 + uint32 spellId; //10 + uint32 noDamageImmune; //11 + uint32 linkedTrapId; //12 + uint32 large; //13 + uint32 openTextID; //14 can be used to replace castBarCaption? + uint32 closeTextID; //15 + uint32 losOK; //16 isBattlegroundObject + uint32 allowMounted; //17 Is usable while on mount/vehicle. (0/1) + uint32 floatingTooltip; //18 + uint32 gossipID; //19 + uint32 WorldStateSetsState; //20 + uint32 floatOnWater; //21 + uint32 conditionID1; //22 + } goober; + //11 GAMEOBJECT_TYPE_TRANSPORT + struct + { + int32 stopFrame1; //0 + uint32 startOpen; //1 + uint32 autoCloseTime; //2 secs till autoclose = autoCloseTime / 0x10000 + uint32 pause1EventID; //3 + uint32 pause2EventID; //4 + uint32 mapId; //5 + int32 stopFrame2; //6 + uint32 unknown; + int32 stopFrame3; //8 + uint32 unknown2; + int32 stopFrame4; //10 + } transport; + //12 GAMEOBJECT_TYPE_AREADAMAGE + struct + { + uint32 lockId; //0 + uint32 radius; //1 + uint32 damageMin; //2 + uint32 damageMax; //3 + uint32 damageSchool; //4 + uint32 autoCloseTime; //5 secs till autoclose = autoCloseTime / 0x10000 + uint32 openTextID; //6 + uint32 closeTextID; //7 + } areadamage; + //13 GAMEOBJECT_TYPE_CAMERA + struct + { + uint32 lockId; //0 -> Lock.dbc + 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 + struct + { + uint32 taxiPathId; //0 + uint32 moveSpeed; //1 + uint32 accelRate; //2 + uint32 startEventID; //3 + uint32 stopEventID; //4 + uint32 transportPhysics; //5 + uint32 mapID; //6 + uint32 worldState1; //7 + uint32 canBeStopped; //8 + } moTransport; + //16 GAMEOBJECT_TYPE_DUELFLAG - empty + //17 GAMEOBJECT_TYPE_FISHINGNODE - empty + //18 GAMEOBJECT_TYPE_SUMMONING_RITUAL + struct + { + uint32 reqParticipants; //0 + uint32 spellId; //1 + uint32 animSpell; //2 + uint32 ritualPersistent; //3 + uint32 casterTargetSpell; //4 + uint32 casterTargetSpellTargets; //5 + uint32 castersGrouped; //6 + uint32 ritualNoTargetCheck; //7 + } summoningRitual; + //19 GAMEOBJECT_TYPE_MAILBOX + struct + { + uint32 conditionID1; //0 + } mailbox; + //20 GAMEOBJECT_TYPE_DO_NOT_USE - empty + //21 GAMEOBJECT_TYPE_GUARDPOST + struct + { + uint32 creatureID; //0 + uint32 charges; //1 + } guardpost; + //22 GAMEOBJECT_TYPE_SPELLCASTER + struct + { + uint32 spellId; //0 + uint32 charges; //1 + 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 + { + uint32 minLevel; //0 + uint32 maxLevel; //1 + uint32 areaID; //2 + } meetingstone; + //24 GAMEOBJECT_TYPE_FLAGSTAND + struct + { + uint32 lockId; //0 + uint32 pickupSpell; //1 + uint32 radius; //2 + uint32 returnAura; //3 + uint32 returnSpell; //4 + uint32 noDamageImmune; //5 + uint32 openTextID; //6 + uint32 losOK; //7 + } flagstand; + //25 GAMEOBJECT_TYPE_FISHINGHOLE + struct + { + uint32 radius; //0 how close bobber must land for sending loot + uint32 lootId; //1 + uint32 minSuccessOpens; //2 + uint32 maxSuccessOpens; //3 + uint32 lockId; //4 -> Lock.dbc; possibly 1628 for all? + } fishinghole; + //26 GAMEOBJECT_TYPE_FLAGDROP + struct + { + uint32 lockId; //0 + uint32 eventID; //1 + uint32 pickupSpell; //2 + uint32 noDamageImmune; //3 + uint32 openTextID; //4 + } flagdrop; + //27 GAMEOBJECT_TYPE_MINI_GAME + struct + { + uint32 gameType; //0 + } miniGame; + //29 GAMEOBJECT_TYPE_CAPTURE_POINT + struct + { + uint32 radius; //0 + uint32 spell; //1 + uint32 worldState1; //2 + uint32 worldstate2; //3 + uint32 winEventID1; //4 + uint32 winEventID2; //5 + uint32 contestedEventID1; //6 + uint32 contestedEventID2; //7 + uint32 progressEventID1; //8 + uint32 progressEventID2; //9 + uint32 neutralEventID1; //10 + uint32 neutralEventID2; //11 + uint32 neutralPercent; //12 + uint32 worldstate3; //13 + uint32 minSuperiority; //14 + uint32 maxSuperiority; //15 + uint32 minTime; //16 + uint32 maxTime; //17 + uint32 large; //18 + uint32 highlight; //19 + uint32 startingValue; //20 + uint32 unidirectional; //21 + } capturePoint; + //30 GAMEOBJECT_TYPE_AURA_GENERATOR + struct + { + uint32 startOpen; //0 + uint32 radius; //1 + uint32 auraID1; //2 + uint32 conditionID1; //3 + uint32 auraID2; //4 + uint32 conditionID2; //5 + uint32 serverOnly; //6 + } auraGenerator; + //31 GAMEOBJECT_TYPE_DUNGEON_DIFFICULTY + struct + { + uint32 mapID; //0 + uint32 difficulty; //1 + } dungeonDifficulty; + //32 GAMEOBJECT_TYPE_BARBER_CHAIR + struct + { + uint32 chairheight; //0 + uint32 heightOffset; //1 + } barberChair; + //33 GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING + struct + { + uint32 intactNumHits; //0 + uint32 creditProxyCreature; //1 + uint32 empty1; //2 + uint32 intactEvent; //3 + uint32 empty2; //4 + uint32 damagedNumHits; //5 + uint32 empty3; //6 + uint32 empty4; //7 + uint32 empty5; //8 + uint32 damagedEvent; //9 + uint32 empty6; //10 + uint32 empty7; //11 + uint32 empty8; //12 + uint32 empty9; //13 + uint32 destroyedEvent; //14 + uint32 empty10; //15 + uint32 rebuildingTimeSecs; //16 + uint32 empty11; //17 + uint32 destructibleData; //18 + uint32 rebuildingEvent; //19 + uint32 empty12; //20 + uint32 empty13; //21 + uint32 damageEvent; //22 + uint32 empty14; //23 + } building; + //34 GAMEOBJECT_TYPE_GUILDBANK + struct + { + uint32 conditionID1; //0 + } guildbank; + //35 GAMEOBJECT_TYPE_TRAPDOOR + struct + { + uint32 whenToPause; // 0 + uint32 startOpen; // 1 + uint32 autoClose; // 2 + } trapDoor; + + // not use for specific field access (only for output with loop by all filed), also this determinate max union size + struct + { + uint32 data[MAX_GAMEOBJECT_DATA]; + } raw; + }; + + std::string AIName; + uint32 ScriptId; + + // helpers + bool IsDespawnAtAction() const + { + switch (type) + { + case GAMEOBJECT_TYPE_CHEST: return chest.consumable != 0; + case GAMEOBJECT_TYPE_GOOBER: return goober.consumable != 0; + default: return false; + } + } + + bool IsUsableMounted() const + { + switch (type) + { + case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.allowMounted != 0; + case GAMEOBJECT_TYPE_TEXT: return text.allowMounted != 0; + case GAMEOBJECT_TYPE_GOOBER: return goober.allowMounted != 0; + case GAMEOBJECT_TYPE_SPELLCASTER: return spellcaster.allowMounted != 0; + default: return false; + } + } + + uint32 GetLockId() const + { + switch (type) + { + case GAMEOBJECT_TYPE_DOOR: return door.lockId; + case GAMEOBJECT_TYPE_BUTTON: return button.lockId; + case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.lockId; + case GAMEOBJECT_TYPE_CHEST: return chest.lockId; + case GAMEOBJECT_TYPE_TRAP: return trap.lockId; + case GAMEOBJECT_TYPE_GOOBER: return goober.lockId; + case GAMEOBJECT_TYPE_AREADAMAGE: return areadamage.lockId; + case GAMEOBJECT_TYPE_CAMERA: return camera.lockId; + case GAMEOBJECT_TYPE_FLAGSTAND: return flagstand.lockId; + case GAMEOBJECT_TYPE_FISHINGHOLE:return fishinghole.lockId; + case GAMEOBJECT_TYPE_FLAGDROP: return flagdrop.lockId; + default: return 0; + } + } + + bool GetDespawnPossibility() const // despawn at targeting of cast? + { + switch (type) + { + case GAMEOBJECT_TYPE_DOOR: return door.noDamageImmune != 0; + case GAMEOBJECT_TYPE_BUTTON: return button.noDamageImmune != 0; + case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.noDamageImmune != 0; + case GAMEOBJECT_TYPE_GOOBER: return goober.noDamageImmune != 0; + case GAMEOBJECT_TYPE_FLAGSTAND: return flagstand.noDamageImmune != 0; + case GAMEOBJECT_TYPE_FLAGDROP: return flagdrop.noDamageImmune != 0; + default: return true; + } + } + + uint32 GetCharges() const // despawn at uses amount + { + switch (type) + { + //case GAMEOBJECT_TYPE_TRAP: return trap.charges; + case GAMEOBJECT_TYPE_GUARDPOST: return guardpost.charges; + case GAMEOBJECT_TYPE_SPELLCASTER: return spellcaster.charges; + default: return 0; + } + } + + uint32 GetLinkedGameObjectEntry() const + { + switch (type) + { + case GAMEOBJECT_TYPE_BUTTON: return button.linkedTrap; + case GAMEOBJECT_TYPE_CHEST: return chest.linkedTrapId; + case GAMEOBJECT_TYPE_SPELL_FOCUS: return spellFocus.linkedTrapId; + case GAMEOBJECT_TYPE_GOOBER: return goober.linkedTrapId; + default: return 0; + } + } + + uint32 GetAutoCloseTime() const + { + uint32 autoCloseTime = 0; + switch (type) + { + case GAMEOBJECT_TYPE_DOOR: autoCloseTime = door.autoCloseTime; break; + case GAMEOBJECT_TYPE_BUTTON: autoCloseTime = button.autoCloseTime; break; + case GAMEOBJECT_TYPE_TRAP: autoCloseTime = trap.autoCloseTime; break; + case GAMEOBJECT_TYPE_GOOBER: autoCloseTime = goober.autoCloseTime; break; + case GAMEOBJECT_TYPE_TRANSPORT: autoCloseTime = transport.autoCloseTime; break; + case GAMEOBJECT_TYPE_AREADAMAGE: autoCloseTime = areadamage.autoCloseTime; break; + default: break; + } + return autoCloseTime; // prior to 3.0.3, conversion was / 0x10000; + } + + uint32 GetLootId() const + { + switch (type) + { + case GAMEOBJECT_TYPE_CHEST: return chest.lootId; + case GAMEOBJECT_TYPE_FISHINGHOLE: return fishinghole.lootId; + default: return 0; + } + } + + uint32 GetGossipMenuId() const + { + switch (type) + { + case GAMEOBJECT_TYPE_QUESTGIVER: return questgiver.gossipID; + case GAMEOBJECT_TYPE_GOOBER: return goober.gossipID; + default: return 0; + } + } + + uint32 GetEventScriptId() const + { + switch (type) + { + case GAMEOBJECT_TYPE_GOOBER: return goober.eventId; + case GAMEOBJECT_TYPE_CHEST: return chest.eventId; + case GAMEOBJECT_TYPE_CAMERA: return camera.eventID; + default: return 0; + } + } + + uint32 GetCooldown() const // Cooldown preventing goober and traps to cast spell + { + switch (type) + { + case GAMEOBJECT_TYPE_TRAP: return trap.cooldown; + case GAMEOBJECT_TYPE_GOOBER: return goober.cooldown; + default: return 0; + } + } +}; + +// From `gameobject_template_addon` +struct GameObjectTemplateAddon +{ + uint32 entry; + uint32 faction; + uint32 flags; + uint32 mingold; + uint32 maxgold; +}; + +struct GameObjectLocale +{ + std::vector Name; + std::vector CastBarCaption; +}; + +struct TC_GAME_API QuaternionData +{ + float x, y, z, w; + + QuaternionData() : x(0.0f), y(0.0f), z(0.0f), w(1.0f) { } + QuaternionData(float X, float Y, float Z, float W) : x(X), y(Y), z(Z), w(W) { } + + bool isUnit() const; + static QuaternionData fromEulerAnglesZYX(float Z, float Y, float X); +}; + +// `gameobject_addon` table +struct GameObjectAddon +{ + QuaternionData ParentRotation; + InvisibilityType invisibilityType; + uint32 InvisibilityValue; +}; + +// from `gameobject` +struct GameObjectData +{ + 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), phaseUseFlags(0), phaseId(0), + phaseGroup(0), terrainSwapMap(-1), ScriptId(0), dbData(true) { } + uint32 id; // entry in gamobject_template + uint16 mapid; + uint32 phaseMask; + float posX; + float posY; + float posZ; + float orientation; + QuaternionData rotation; + int32 spawntimesecs; + uint32 animprogress; + GOState go_state; + uint8 spawnMask; + uint8 artKit; + uint8 phaseUseFlags; + uint32 phaseId; + uint32 phaseGroup; + int32 terrainSwapMap; + uint32 ScriptId; + bool dbData; +}; + +#endif // GameObjectData_h__ diff --git a/src/server/game/Entities/Item/Container/Bag.cpp b/src/server/game/Entities/Item/Container/Bag.cpp index 89fc7ed910f..3cb96f9834f 100644 --- a/src/server/game/Entities/Item/Container/Bag.cpp +++ b/src/server/game/Entities/Item/Container/Bag.cpp @@ -98,7 +98,7 @@ bool Bag::Create(ObjectGuid::LowType guidlow, uint32 itemid, Player const* owner for (uint8 i = 0; i < MAX_BAG_SIZE; ++i) { SetGuidValue(CONTAINER_FIELD_SLOT_1 + (i*2), ObjectGuid::Empty); - m_bagslot[i] = NULL; + m_bagslot[i] = nullptr; } return true; @@ -121,7 +121,7 @@ bool Bag::LoadFromDB(ObjectGuid::LowType guid, ObjectGuid owner_guid, Field* fie { SetGuidValue(CONTAINER_FIELD_SLOT_1 + (i * 2), ObjectGuid::Empty); delete m_bagslot[i]; - m_bagslot[i] = NULL; + m_bagslot[i] = nullptr; } return true; @@ -151,9 +151,9 @@ void Bag::RemoveItem(uint8 slot, bool /*update*/) ASSERT(slot < MAX_BAG_SIZE); if (m_bagslot[slot]) - m_bagslot[slot]->SetContainer(NULL); + m_bagslot[slot]->SetContainer(nullptr); - m_bagslot[slot] = NULL; + m_bagslot[slot] = nullptr; SetGuidValue(CONTAINER_FIELD_SLOT_1 + (slot * 2), ObjectGuid::Empty); } @@ -243,5 +243,5 @@ Item* Bag::GetItemByPos(uint8 slot) const if (slot < GetBagSize()) return m_bagslot[slot]; - return NULL; + return nullptr; } diff --git a/src/server/game/Entities/Item/Container/Bag.h b/src/server/game/Entities/Item/Container/Bag.h index 867c0998820..f7b3edaee3b 100644 --- a/src/server/game/Entities/Item/Container/Bag.h +++ b/src/server/game/Entities/Item/Container/Bag.h @@ -23,7 +23,6 @@ #define MAX_BAG_SIZE 36 // 2.0.12 #include "Item.h" -#include "ItemTemplate.h" class TC_GAME_API Bag : public Item { @@ -42,8 +41,8 @@ class TC_GAME_API Bag : public Item void RemoveItem(uint8 slot, bool update); Item* GetItemByPos(uint8 slot) const; - uint32 GetItemCount(uint32 item, Item* eItem = NULL) const; - uint32 GetItemCountWithLimitCategory(uint32 limitCategory, Item* skipItem = NULL) const; + uint32 GetItemCount(uint32 item, Item* eItem = nullptr) const; + uint32 GetItemCountWithLimitCategory(uint32 limitCategory, Item* skipItem = nullptr) const; uint8 GetSlotByItemGUID(ObjectGuid guid) const; bool IsEmpty() const; diff --git a/src/server/game/Entities/Item/Item.cpp b/src/server/game/Entities/Item/Item.cpp index 5843903e610..35bd3e2b0ff 100644 --- a/src/server/game/Entities/Item/Item.cpp +++ b/src/server/game/Entities/Item/Item.cpp @@ -16,20 +16,27 @@ * with this program. If not, see . */ -#include "Common.h" #include "Item.h" -#include "ObjectMgr.h" -#include "WorldPacket.h" -#include "DatabaseEnv.h" -#include "ItemEnchantmentMgr.h" -#include "SpellMgr.h" -#include "SpellInfo.h" -#include "ScriptMgr.h" +#include "Bag.h" +#include "Common.h" #include "ConditionMgr.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "ItemEnchantmentMgr.h" +#include "Log.h" +#include "LootItemStorage.h" +#include "LootMgr.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Player.h" -#include "Opcodes.h" -#include "WorldSession.h" +#include "ScriptMgr.h" +#include "SpellInfo.h" +#include "SpellMgr.h" #include "TradeData.h" +#include "UpdateData.h" +#include "WorldPacket.h" +#include "WorldSession.h" void AddItemsSetItem(Player* player, Item* item) { @@ -47,7 +54,7 @@ void AddItemsSetItem(Player* player, Item* item) if (set->required_skill_id && player->GetSkillValue(set->required_skill_id) < set->required_skill_value) return; - ItemSetEffect* eff = NULL; + ItemSetEffect* eff = nullptr; for (size_t x = 0; x < player->ItemSetEff.size(); ++x) { @@ -105,7 +112,7 @@ void AddItemsSetItem(Player* player, Item* item) } // spell cast only if fit form requirement, in other case will cast at form change - player->ApplyEquipSpell(spellInfo, NULL, true); + player->ApplyEquipSpell(spellInfo, nullptr, true); eff->spells[y] = spellInfo; break; } @@ -125,7 +132,7 @@ void RemoveItemsSetItem(Player*player, ItemTemplate const* proto) return; } - ItemSetEffect* eff = NULL; + ItemSetEffect* eff = nullptr; size_t setindex = 0; for (; setindex < player->ItemSetEff.size(); setindex++) { @@ -156,8 +163,8 @@ void RemoveItemsSetItem(Player*player, ItemTemplate const* proto) if (eff->spells[z] && eff->spells[z]->Id == set->spells[x]) { // spell can be not active if not fit form requirement - player->ApplyEquipSpell(eff->spells[z], NULL, false); - eff->spells[z]=NULL; + player->ApplyEquipSpell(eff->spells[z], nullptr, false); + eff->spells[z] = nullptr; break; } } @@ -167,7 +174,7 @@ void RemoveItemsSetItem(Player*player, ItemTemplate const* proto) { ASSERT(eff == player->ItemSetEff[setindex]); delete eff; - player->ItemSetEff[setindex] = NULL; + player->ItemSetEff[setindex] = nullptr; } } @@ -251,10 +258,10 @@ Item::Item() m_slot = 0; uState = ITEM_NEW; uQueuePos = -1; - m_container = NULL; + m_container = nullptr; m_lootGenerated = false; mb_in_trade = false; - m_lastPlayedTimeUpdate = time(NULL); + m_lastPlayedTimeUpdate = time(nullptr); m_refundRecipient = 0; m_paidMoney = 0; @@ -389,7 +396,7 @@ void Item::SaveToDB(SQLTransaction& trans) // Delete the items if this is a container if (!loot.isLooted()) - ItemContainerDeleteLootMoneyAndLootItemsFromDB(); + sLootItemStorage->RemoveStoredLootForContainer(GetGUID().GetCounter()); delete this; return; @@ -500,7 +507,7 @@ void Item::DeleteFromDB(SQLTransaction& trans) // Delete the items if this is a container if (!loot.isLooted()) - ItemContainerDeleteLootMoneyAndLootItemsFromDB(); + sLootItemStorage->RemoveStoredLootForContainer(GetGUID().GetCounter()); } /*static*/ @@ -533,52 +540,6 @@ uint32 Item::GetSkill() return proto->GetSkill(); } -int32 Item::GenerateItemRandomPropertyId(uint32 item_id) -{ - ItemTemplate const* itemProto = sObjectMgr->GetItemTemplate(item_id); - - if (!itemProto) - return 0; - - // item must have one from this field values not null if it can have random enchantments - if ((!itemProto->RandomProperty) && (!itemProto->RandomSuffix)) - return 0; - - // item can have not null only one from field values - if ((itemProto->RandomProperty) && (itemProto->RandomSuffix)) - { - TC_LOG_ERROR("sql.sql", "Item template %u have RandomProperty == %u and RandomSuffix == %u, but must have one from field =0", itemProto->ItemId, itemProto->RandomProperty, itemProto->RandomSuffix); - return 0; - } - - // RandomProperty case - if (itemProto->RandomProperty) - { - uint32 randomPropId = GetItemEnchantMod(itemProto->RandomProperty); - ItemRandomPropertiesEntry const* random_id = sItemRandomPropertiesStore.LookupEntry(randomPropId); - if (!random_id) - { - TC_LOG_ERROR("sql.sql", "Enchantment id #%u used but it doesn't have records in 'ItemRandomProperties.dbc'", randomPropId); - return 0; - } - - return random_id->ID; - } - // RandomSuffix case - else - { - uint32 randomPropId = GetItemEnchantMod(itemProto->RandomSuffix); - ItemRandomSuffixEntry const* random_id = sItemRandomSuffixStore.LookupEntry(randomPropId); - if (!random_id) - { - TC_LOG_ERROR("sql.sql", "Enchantment id #%u used but it doesn't have records in sItemRandomSuffixStore.", randomPropId); - return 0; - } - - return -int32(random_id->ID); - } -} - void Item::SetItemRandomProperties(int32 randomPropId) { if (!randomPropId) @@ -632,7 +593,7 @@ void Item::SetState(ItemUpdateState state, Player* forplayer) // pretend the item never existed if (forplayer) { - RemoveFromUpdateQueueOf(forplayer); + RemoveItemFromUpdateQueueOf(this, forplayer); forplayer->DeleteRefundReference(GetGUID()); } delete this; @@ -645,7 +606,7 @@ void Item::SetState(ItemUpdateState state, Player* forplayer) uState = state; if (forplayer) - AddToUpdateQueueOf(forplayer); + AddItemToUpdateQueueOf(this, forplayer); } else { @@ -656,46 +617,46 @@ void Item::SetState(ItemUpdateState state, Player* forplayer) } } -void Item::AddToUpdateQueueOf(Player* player) +void AddItemToUpdateQueueOf(Item* item, Player* player) { - if (IsInUpdateQueue()) + if (item->IsInUpdateQueue()) return; - ASSERT(player != NULL); + ASSERT(player != nullptr); - if (player->GetGUID() != GetOwnerGUID()) + if (player->GetGUID() != item->GetOwnerGUID()) { - TC_LOG_DEBUG("entities.player.items", "Item::AddToUpdateQueueOf - Owner's guid (%s) and player's guid (%s) don't match!", - GetOwnerGUID().ToString().c_str(), player->GetGUID().ToString().c_str()); + TC_LOG_DEBUG("entities.player.items", "AddItemToUpdateQueueOf - Owner's guid (%s) and player's guid (%s) don't match!", + item->GetOwnerGUID().ToString().c_str(), player->GetGUID().ToString().c_str()); return; } if (player->m_itemUpdateQueueBlocked) return; - player->m_itemUpdateQueue.push_back(this); - uQueuePos = player->m_itemUpdateQueue.size()-1; + player->m_itemUpdateQueue.push_back(item); + item->uQueuePos = player->m_itemUpdateQueue.size() - 1; } -void Item::RemoveFromUpdateQueueOf(Player* player) +void RemoveItemFromUpdateQueueOf(Item* item, Player* player) { - if (!IsInUpdateQueue()) + if (!item->IsInUpdateQueue()) return; - ASSERT(player != NULL); + ASSERT(player != nullptr); - if (player->GetGUID() != GetOwnerGUID()) + if (player->GetGUID() != item->GetOwnerGUID()) { - TC_LOG_DEBUG("entities.player.items", "Item::RemoveFromUpdateQueueOf - Owner's guid (%s) and player's guid (%s) don't match!", - GetOwnerGUID().ToString().c_str(), player->GetGUID().ToString().c_str()); + TC_LOG_DEBUG("entities.player.items", "RemoveItemFromUpdateQueueOf - Owner's guid (%s) and player's guid (%s) don't match!", + item->GetOwnerGUID().ToString().c_str(), player->GetGUID().ToString().c_str()); return; } if (player->m_itemUpdateQueueBlocked) return; - player->m_itemUpdateQueue[uQueuePos] = NULL; - uQueuePos = -1; + player->m_itemUpdateQueue[item->uQueuePos] = nullptr; + item->uQueuePos = -1; } uint8 Item::GetBagSlot() const @@ -716,7 +677,7 @@ bool Item::CanBeTraded(bool mail, bool trade) const if ((!mail || !IsBoundAccountWide()) && (IsSoulBound() && (!HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_BOP_TRADEABLE) || !trade))) return false; - if (IsBag() && (Player::IsBagPos(GetPos()) || !((Bag const*)this)->IsEmpty())) + if (IsBag() && (Player::IsBagPos(GetPos()) || !ToBag()->IsEmpty())) return false; if (Player* owner = GetOwner()) @@ -733,7 +694,7 @@ bool Item::CanBeTraded(bool mail, bool trade) const return true; } -bool Item::HasEnchantRequiredSkill(const Player* player) const +bool Item::HasEnchantRequiredSkill(Player const* player) const { // Check all enchants for required skill for (uint32 enchant_slot = PERM_ENCHANTMENT_SLOT; enchant_slot < MAX_ENCHANTMENT_SLOT; ++enchant_slot) @@ -982,7 +943,7 @@ void Item::SendUpdateSockets() for (uint32 i = SOCK_ENCHANTMENT_SLOT; i <= BONUS_ENCHANTMENT_SLOT; ++i) data << uint32(GetEnchantmentId(EnchantmentSlot(i))); - GetOwner()->GetSession()->SendPacket(&data); + GetOwner()->SendDirectMessage(&data); } // Though the client has the information in the item's data field, @@ -997,7 +958,7 @@ void Item::SendTimeUpdate(Player* owner) WorldPacket data(SMSG_ITEM_TIME_UPDATE, (8+4)); data << uint64(GetGUID()); data << uint32(duration); - owner->GetSession()->SendPacket(&data); + owner->SendDirectMessage(&data); } Item* Item::CreateItem(uint32 itemEntry, uint32 count, Player const* player /*= nullptr*/) @@ -1037,7 +998,7 @@ Item* Item::CloneItem(uint32 count, Player const* player /*= nullptr*/) const newItem->SetGuidValue(ITEM_FIELD_GIFTCREATOR, GetGuidValue(ITEM_FIELD_GIFTCREATOR)); newItem->SetUInt32Value(ITEM_FIELD_FLAGS, GetUInt32Value(ITEM_FIELD_FLAGS) & ~(ITEM_FIELD_FLAG_REFUNDABLE | ITEM_FIELD_FLAG_BOP_TRADEABLE)); newItem->SetUInt32Value(ITEM_FIELD_DURATION, GetUInt32Value(ITEM_FIELD_DURATION)); - // player CAN be NULL in which case we must not update random properties because that accesses player's item update queue + // player CAN be nullptr in which case we must not update random properties because that accesses player's item update queue if (player) newItem->SetItemRandomProperties(GetItemRandomPropertyId()); return newItem; @@ -1054,7 +1015,7 @@ bool Item::IsBindedNotWith(Player const* player) const return false; if (HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_BOP_TRADEABLE)) - if (allowedGUIDs.find(player->GetGUID().GetCounter()) != allowedGUIDs.end()) + if (allowedGUIDs.find(player->GetGUID()) != allowedGUIDs.end()) return false; // BOA item case @@ -1112,7 +1073,7 @@ void Item::DeleteRefundDataFromDB(SQLTransaction* trans) } } -void Item::SetNotRefundable(Player* owner, bool changestate /*=true*/, SQLTransaction* trans /*=NULL*/) +void Item::SetNotRefundable(Player* owner, bool changestate /*= true*/, SQLTransaction* trans /*=nullptr*/) { if (!HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_REFUNDABLE)) return; @@ -1139,7 +1100,7 @@ void Item::UpdatePlayedTime(Player* owner) // Get current played time uint32 current_playtime = GetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME); // Calculate time elapsed since last played time update - time_t curtime = time(NULL); + time_t curtime = time(nullptr); uint32 elapsed = uint32(curtime - m_lastPlayedTimeUpdate); uint32 new_playtime = current_playtime + elapsed; // Check if the refund timer has expired yet @@ -1160,7 +1121,7 @@ void Item::UpdatePlayedTime(Player* owner) uint32 Item::GetPlayedTime() { - time_t curtime = time(NULL); + time_t curtime = time(nullptr); uint32 elapsed = uint32(curtime - m_lastPlayedTimeUpdate); return GetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME) + elapsed; } @@ -1170,7 +1131,7 @@ bool Item::IsRefundExpired() return (GetPlayedTime() > 2*HOUR); } -void Item::SetSoulboundTradeable(AllowedLooterSet const& allowedLooters) +void Item::SetSoulboundTradeable(GuidSet const& allowedLooters) { SetFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_BOP_TRADEABLE); allowedGUIDs = allowedLooters; @@ -1500,194 +1461,6 @@ int32 Item::GetReforgableStat(ItemModType statType) const return 0; } -void Item::ItemContainerSaveLootToDB() -{ - // Saves the money and item loot associated with an openable item to the DB - if (loot.isLooted()) // no money and no loot - return; - - ObjectGuid::LowType container_id = GetGUID().GetCounter(); - SQLTransaction trans = CharacterDatabase.BeginTransaction(); - - loot.containerID = container_id; // Save this for when a LootItem is removed - - // Save money - if (loot.gold > 0) - { - PreparedStatement* stmt_money = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_MONEY); - stmt_money->setUInt32(0, container_id); - trans->Append(stmt_money); - - stmt_money = CharacterDatabase.GetPreparedStatement(CHAR_INS_ITEMCONTAINER_MONEY); - stmt_money->setUInt32(0, container_id); - stmt_money->setUInt32(1, loot.gold); - trans->Append(stmt_money); - } - - // Save items - if (!loot.isLooted()) - { - PreparedStatement* stmt_items = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_ITEMS); - stmt_items->setUInt32(0, container_id); - trans->Append(stmt_items); - - // Now insert the items - for (LootItemList::const_iterator _li = loot.items.begin(); _li != loot.items.end(); ++_li) - { - // When an item is looted, it doesn't get removed from the items collection - // but we don't want to resave it. - if (!_li->canSave) - continue; - // Conditions are not checked when loot is generated, it is checked when loot is sent to a player. - // For items that are lootable, loot is saved to the DB immediately, that means that loot can be - // saved to the DB that the player never should have gotten. This check prevents that, so that only - // items that the player should get in loot are in the DB. - // IE: Horde items are not saved to the DB for Ally players. - Player* const guid = GetOwner(); - if (!_li->AllowedForPlayer(guid)) - continue; - - stmt_items = CharacterDatabase.GetPreparedStatement(CHAR_INS_ITEMCONTAINER_ITEMS); - - // container_id, item_id, item_count, follow_rules, ffa, blocked, counted, under_threshold, needs_quest, rnd_prop, rnd_suffix - stmt_items->setUInt32(0, container_id); - stmt_items->setUInt32(1, _li->itemid); - stmt_items->setUInt32(2, _li->count); - stmt_items->setBool(3, _li->follow_loot_rules); - stmt_items->setBool(4, _li->freeforall); - stmt_items->setBool(5, _li->is_blocked); - stmt_items->setBool(6, _li->is_counted); - stmt_items->setBool(7, _li->is_underthreshold); - stmt_items->setBool(8, _li->needs_quest); - stmt_items->setInt32(9, _li->randomPropertyId); - stmt_items->setUInt32(10, _li->randomSuffix); - trans->Append(stmt_items); - } - } - - CharacterDatabase.CommitTransaction(trans); -} - -bool Item::ItemContainerLoadLootFromDB() -{ - // Loads the money and item loot associated with an openable item from the DB - // Default. If there are no records for this item then it will be rolled for in Player::SendLoot() - m_lootGenerated = false; - - ObjectGuid::LowType container_id = GetGUID().GetCounter(); - - // Save this for later use - loot.containerID = container_id; - - // First, see if there was any money loot. This gets added directly to the container. - PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ITEMCONTAINER_MONEY); - stmt->setUInt32(0, container_id); - PreparedQueryResult money_result = CharacterDatabase.Query(stmt); - - if (money_result) - { - Field* fields = money_result->Fetch(); - loot.gold = fields[0].GetUInt32(); - } - - // Next, load any items that were saved - stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ITEMCONTAINER_ITEMS); - stmt->setUInt32(0, container_id); - PreparedQueryResult item_result = CharacterDatabase.Query(stmt); - - if (item_result) - { - // Get a LootTemplate for the container item. This is where - // the saved loot was originally rolled from, we will copy conditions from it - LootTemplate const* lt = LootTemplates_Item.GetLootFor(GetEntry()); - if (lt) - { - do - { - // Create an empty LootItem - LootItem loot_item = LootItem(); - - // Fill in the rest of the LootItem from the DB - Field* fields = item_result->Fetch(); - - // item_id, itm_count, follow_rules, ffa, blocked, counted, under_threshold, needs_quest, rnd_prop, rnd_suffix - loot_item.itemid = fields[0].GetUInt32(); - loot_item.count = fields[1].GetUInt32(); - loot_item.follow_loot_rules = fields[2].GetBool(); - loot_item.freeforall = fields[3].GetBool(); - loot_item.is_blocked = fields[4].GetBool(); - loot_item.is_counted = fields[5].GetBool(); - loot_item.canSave = true; - loot_item.is_underthreshold = fields[6].GetBool(); - loot_item.needs_quest = fields[7].GetBool(); - loot_item.randomPropertyId = fields[8].GetInt32(); - loot_item.randomSuffix = fields[9].GetUInt32(); - - // Copy the extra loot conditions from the item in the loot template - lt->CopyConditions(&loot_item); - - // If container item is in a bag, add that player as an allowed looter - if (GetBagSlot()) - loot_item.AddAllowedLooter(GetOwner()); - - // Finally add the LootItem to the container - loot.items.push_back(loot_item); - - // Increment unlooted count - loot.unlootedCount++; - - } - while (item_result->NextRow()); - } - } - - // Mark the item if it has loot so it won't be generated again on open - m_lootGenerated = !loot.isLooted(); - - return m_lootGenerated; -} - -void Item::ItemContainerDeleteLootItemsFromDB() -{ - // Deletes items associated with an openable item from the DB - ObjectGuid::LowType containerId = GetGUID().GetCounter(); - PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_ITEMS); - stmt->setUInt32(0, containerId); - SQLTransaction trans = CharacterDatabase.BeginTransaction(); - trans->Append(stmt); - CharacterDatabase.CommitTransaction(trans); -} - -void Item::ItemContainerDeleteLootItemFromDB(uint32 itemID) -{ - // Deletes a single item associated with an openable item from the DB - ObjectGuid::LowType containerId = GetGUID().GetCounter(); - PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_ITEM); - stmt->setUInt32(0, containerId); - stmt->setUInt32(1, itemID); - SQLTransaction trans = CharacterDatabase.BeginTransaction(); - trans->Append(stmt); - CharacterDatabase.CommitTransaction(trans); -} - -void Item::ItemContainerDeleteLootMoneyFromDB() -{ - // Deletes the money loot associated with an openable item from the DB - ObjectGuid::LowType containerId = GetGUID().GetCounter(); - PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_MONEY); - stmt->setUInt32(0, containerId); - SQLTransaction trans = CharacterDatabase.BeginTransaction(); - trans->Append(stmt); - CharacterDatabase.CommitTransaction(trans); -} - -void Item::ItemContainerDeleteLootMoneyAndLootItemsFromDB() -{ - // Deletes money and items associated with an openable item from the DB - ItemContainerDeleteLootMoneyFromDB(); - ItemContainerDeleteLootItemsFromDB(); -} - void Item::SetCount(uint32 value) { SetUInt32Value(ITEM_FIELD_STACK_COUNT, value); diff --git a/src/server/game/Entities/Item/Item.h b/src/server/game/Entities/Item/Item.h index 124125b9348..796f35163e7 100644 --- a/src/server/game/Entities/Item/Item.h +++ b/src/server/game/Entities/Item/Item.h @@ -19,11 +19,13 @@ #ifndef TRINITYCORE_ITEM_H #define TRINITYCORE_ITEM_H -#include "Common.h" #include "Object.h" -#include "LootMgr.h" +#include "Common.h" +#include "DatabaseEnvFwd.h" +#include "ItemDefines.h" +#include "ItemEnchantmentMgr.h" #include "ItemTemplate.h" -#include "DatabaseEnv.h" +#include "Loot.h" class SpellInfo; class Bag; @@ -36,151 +38,6 @@ struct ItemSetEffect SpellInfo const* spells[8]; }; -enum InventoryResult -{ - EQUIP_ERR_OK = 0, - EQUIP_ERR_CANT_EQUIP_LEVEL_I = 1, // You must reach level %d to use that item. - EQUIP_ERR_CANT_EQUIP_SKILL = 2, // You aren't skilled enough to use that item. - EQUIP_ERR_WRONG_SLOT = 3, // That item does not go in that slot. - EQUIP_ERR_BAG_FULL = 4, // That bag is full. - EQUIP_ERR_BAG_IN_BAG = 5, // Can't put non-empty bags in other bags. - EQUIP_ERR_TRADE_EQUIPPED_BAG = 6, // You can't trade equipped bags. - EQUIP_ERR_AMMO_ONLY = 7, // Only ammo can go there. - EQUIP_ERR_PROFICIENCY_NEEDED = 8, // You do not have the required proficiency for that item. - EQUIP_ERR_NO_SLOT_AVAILABLE = 9, // No equipment slot is available for that item. - EQUIP_ERR_CANT_EQUIP_EVER = 10, // You can never use that item. - EQUIP_ERR_CANT_EQUIP_EVER_2 = 11, // You can never use that item. - EQUIP_ERR_NO_SLOT_AVAILABLE_2 = 12, // No equipment slot is available for that item. - EQUIP_ERR_2HANDED_EQUIPPED = 13, // Cannot equip that with a two-handed weapon. - EQUIP_ERR_2HSKILLNOTFOUND = 14, // You cannot dual-wield - EQUIP_ERR_WRONG_BAG_TYPE = 15, // That item doesn't go in that container. - EQUIP_ERR_WRONG_BAG_TYPE_2 = 16, // That item doesn't go in that container. - EQUIP_ERR_ITEM_MAX_COUNT = 17, // You can't carry any more of those items. - EQUIP_ERR_NO_SLOT_AVAILABLE_3 = 18, // No equipment slot is available for that item. - EQUIP_ERR_CANT_STACK = 19, // This item cannot stack. - EQUIP_ERR_NOT_EQUIPPABLE = 20, // This item cannot be equipped. - EQUIP_ERR_CANT_SWAP = 21, // These items can't be swapped. - EQUIP_ERR_SLOT_EMPTY = 22, // That slot is empty. - EQUIP_ERR_ITEM_NOT_FOUND = 23, // The item was not found. - EQUIP_ERR_DROP_BOUND_ITEM = 24, // You can't drop a soulbound item. - EQUIP_ERR_OUT_OF_RANGE = 25, // Out of range. - EQUIP_ERR_TOO_FEW_TO_SPLIT = 26, // Tried to split more than number in stack. - EQUIP_ERR_SPLIT_FAILED = 27, // Couldn't split those items. - EQUIP_ERR_SPELL_FAILED_REAGENTS_GENERIC = 28, // Missing reagent - EQUIP_ERR_NOT_ENOUGH_MONEY = 29, // You don't have enough money. - EQUIP_ERR_NOT_A_BAG = 30, // Not a bag. - EQUIP_ERR_DESTROY_NONEMPTY_BAG = 31, // You can only do that with empty bags. - EQUIP_ERR_NOT_OWNER = 32, // You don't own that item. - EQUIP_ERR_ONLY_ONE_QUIVER = 33, // You can only equip one quiver. - EQUIP_ERR_NO_BANK_SLOT = 34, // You must purchase that bag slot first - EQUIP_ERR_NO_BANK_HERE = 35, // You are too far away from a bank. - EQUIP_ERR_ITEM_LOCKED = 36, // Item is locked. - EQUIP_ERR_GENERIC_STUNNED = 37, // You are stunned - EQUIP_ERR_PLAYER_DEAD = 38, // You can't do that when you're dead. - EQUIP_ERR_CLIENT_LOCKED_OUT = 39, // You can't do that right now. - EQUIP_ERR_INTERNAL_BAG_ERROR = 40, // Internal Bag Error - EQUIP_ERR_ONLY_ONE_BOLT = 41, // You can only equip one quiver. - EQUIP_ERR_ONLY_ONE_AMMO = 42, // You can only equip one ammo pouch. - EQUIP_ERR_CANT_WRAP_STACKABLE = 43, // Stackable items can't be wrapped. - EQUIP_ERR_CANT_WRAP_EQUIPPED = 44, // Equipped items can't be wrapped. - EQUIP_ERR_CANT_WRAP_WRAPPED = 45, // Wrapped items can't be wrapped. - EQUIP_ERR_CANT_WRAP_BOUND = 46, // Bound items can't be wrapped. - EQUIP_ERR_CANT_WRAP_UNIQUE = 47, // Unique items can't be wrapped. - EQUIP_ERR_CANT_WRAP_BAGS = 48, // Bags can't be wrapped. - EQUIP_ERR_LOOT_GONE = 49, // Already looted - EQUIP_ERR_INV_FULL = 50, // Inventory is full. - EQUIP_ERR_BANK_FULL = 51, // Your bank is full - EQUIP_ERR_VENDOR_SOLD_OUT = 52, // That item is currently sold out. - EQUIP_ERR_BAG_FULL_2 = 53, // That bag is full. - EQUIP_ERR_ITEM_NOT_FOUND_2 = 54, // The item was not found. - EQUIP_ERR_CANT_STACK_2 = 55, // This item cannot stack. - EQUIP_ERR_BAG_FULL_3 = 56, // That bag is full. - EQUIP_ERR_VENDOR_SOLD_OUT_2 = 57, // That item is currently sold out. - EQUIP_ERR_OBJECT_IS_BUSY = 58, // That object is busy. - EQUIP_ERR_CANT_BE_DISENCHANTED = 59, - EQUIP_ERR_NOT_IN_COMBAT = 60, // You can't do that while in combat - EQUIP_ERR_NOT_WHILE_DISARMED = 61, // You can't do that while disarmed - EQUIP_ERR_BAG_FULL_4 = 62, // That bag is full. - EQUIP_ERR_CANT_EQUIP_RANK = 63, // You don't have the required rank for that item - EQUIP_ERR_CANT_EQUIP_REPUTATION = 64, // You don't have the required reputation for that item - EQUIP_ERR_TOO_MANY_SPECIAL_BAGS = 65, // You cannot equip another bag of that type - EQUIP_ERR_LOOT_CANT_LOOT_THAT_NOW = 66, // You can't loot that item now. - EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE = 67, // You cannot equip more than one of those. - EQUIP_ERR_VENDOR_MISSING_TURNINS = 68, // You do not have the required items for that purchase - EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS = 69, // You don't have enough honor points - EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS = 70, // You don't have enough arena points - EQUIP_ERR_ITEM_MAX_COUNT_SOCKETED = 71, // You have the maximum number of those gems in your inventory or socketed into items. - EQUIP_ERR_MAIL_BOUND_ITEM = 72, // You can't mail soulbound items. - EQUIP_ERR_INTERNAL_BAG_ERROR_2 = 73, // Internal Bag Error - EQUIP_ERR_BAG_FULL_5 = 74, // That bag is full. - EQUIP_ERR_ITEM_MAX_COUNT_EQUIPPED_SOCKETED = 75, // You have the maximum number of those gems socketed into equipped items. - EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED = 76, // You cannot socket more than one of those gems into a single item. - EQUIP_ERR_TOO_MUCH_GOLD = 77, // At gold limit - EQUIP_ERR_NOT_DURING_ARENA_MATCH = 78, // You can't do that while in an arena match - EQUIP_ERR_TRADE_BOUND_ITEM = 79, // You can't trade a soulbound item. - EQUIP_ERR_CANT_EQUIP_RATING = 80, // You don't have the personal, team, or battleground rating required to buy that item - EQUIP_ERR_NO_OUTPUT = 81, - EQUIP_ERR_NOT_SAME_ACCOUNT = 82, // Account-bound items can only be given to your own characters. - EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS = 84, // You can only carry %d %s - EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED_IS = 85, // You can only equip %d |4item:items in the %s category - EQUIP_ERR_SCALING_STAT_ITEM_LEVEL_EXCEEDED = 86, // Your level is too high to use that item - EQUIP_ERR_PURCHASE_LEVEL_TOO_LOW = 87, // You must reach level %d to purchase that item. - EQUIP_ERR_CANT_EQUIP_NEED_TALENT = 88, // You do not have the required talent to equip that. - EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS = 89, // You can only equip %d |4item:items in the %s category - EQUIP_ERR_SHAPESHIFT_FORM_CANNOT_EQUIP = 90, // Cannot equip item in this form - EQUIP_ERR_ITEM_INVENTORY_FULL_SATCHEL = 91, // Your inventory is full. Your satchel has been delivered to your mailbox. - EQUIP_ERR_SCALING_STAT_ITEM_LEVEL_TOO_LOW = 92, // Your level is too low to use that item - EQUIP_ERR_CANT_BUY_QUANTITY = 93, // You can't buy the specified quantity of that item. -}; - -enum BuyResult -{ - BUY_ERR_CANT_FIND_ITEM = 0, - BUY_ERR_ITEM_ALREADY_SOLD = 1, - BUY_ERR_NOT_ENOUGHT_MONEY = 2, - BUY_ERR_SELLER_DONT_LIKE_YOU = 4, - BUY_ERR_DISTANCE_TOO_FAR = 5, - BUY_ERR_ITEM_SOLD_OUT = 7, - BUY_ERR_CANT_CARRY_MORE = 8, - BUY_ERR_RANK_REQUIRE = 11, - BUY_ERR_REPUTATION_REQUIRE = 12 -}; - -enum SellResult -{ - SELL_ERR_CANT_FIND_ITEM = 1, - SELL_ERR_CANT_SELL_ITEM = 2, // merchant doesn't like that item - SELL_ERR_CANT_FIND_VENDOR = 3, // merchant doesn't like you - SELL_ERR_YOU_DONT_OWN_THAT_ITEM = 4, // you don't own that item - SELL_ERR_UNK = 5, // nothing appears... - SELL_ERR_ONLY_EMPTY_BAG = 6 // can only do with empty bags -}; - -// -1 from client enchantment slot number -enum EnchantmentSlot -{ - PERM_ENCHANTMENT_SLOT = 0, - TEMP_ENCHANTMENT_SLOT = 1, - SOCK_ENCHANTMENT_SLOT = 2, - SOCK_ENCHANTMENT_SLOT_2 = 3, - SOCK_ENCHANTMENT_SLOT_3 = 4, - BONUS_ENCHANTMENT_SLOT = 5, - PRISMATIC_ENCHANTMENT_SLOT = 6, // added at apply special permanent enchantment - //TODO: 7, - REFORGE_ENCHANTMENT_SLOT = 8, - TRANSMOGRIFY_ENCHANTMENT_SLOT = 9, - MAX_INSPECTED_ENCHANTMENT_SLOT = 10, - - PROP_ENCHANTMENT_SLOT_0 = 10, // used with RandomSuffix - PROP_ENCHANTMENT_SLOT_1 = 11, // used with RandomSuffix - PROP_ENCHANTMENT_SLOT_2 = 12, // used with RandomSuffix and RandomProperty - PROP_ENCHANTMENT_SLOT_3 = 13, // used with RandomProperty - PROP_ENCHANTMENT_SLOT_4 = 14, // used with RandomProperty - MAX_ENCHANTMENT_SLOT = 15 -}; - -#define MAX_VISIBLE_ITEM_OFFSET 2 // 2 fields per visible item (entry+enchantment) - #define MAX_GEM_SOCKETS MAX_ITEM_PROTO_SOCKETS// (BONUS_ENCHANTMENT_SLOT-SOCK_ENCHANTMENT_SLOT) and item proto size, equal value expected enum EnchantmentOffset @@ -192,14 +49,6 @@ enum EnchantmentOffset #define MAX_ENCHANTMENT_OFFSET 3 -enum EnchantmentSlotMask -{ - ENCHANTMENT_CAN_SOULBOUND = 0x01, - ENCHANTMENT_UNK1 = 0x02, - ENCHANTMENT_UNK2 = 0x04, - ENCHANTMENT_UNK3 = 0x08 -}; - enum ItemUpdateState { ITEM_UNCHANGED = 0, @@ -212,6 +61,9 @@ bool ItemCanGoIntoBag(ItemTemplate const* proto, ItemTemplate const* pBagProto); class TC_GAME_API Item : public Object { + friend void AddItemToUpdateQueueOf(Item* item, Player* player); + friend void RemoveItemFromUpdateQueueOf(Item* item, Player* player); + public: static Item* CreateItem(uint32 itemEntry, uint32 count, Player const* player = nullptr); Item* CloneItem(uint32 count, Player const* player = nullptr) const; @@ -238,20 +90,12 @@ class TC_GAME_API Item : public Object virtual void DeleteFromDB(SQLTransaction& trans); static void DeleteFromInventoryDB(SQLTransaction& trans, ObjectGuid::LowType itemGuid); - // Lootable items and their contents - void ItemContainerSaveLootToDB(); - bool ItemContainerLoadLootFromDB(); - void ItemContainerDeleteLootItemsFromDB(); - void ItemContainerDeleteLootItemFromDB(uint32 itemID); - void ItemContainerDeleteLootMoneyFromDB(); - void ItemContainerDeleteLootMoneyAndLootItemsFromDB(); - void DeleteFromInventoryDB(SQLTransaction& trans); void SaveRefundDataToDB(); void DeleteRefundDataFromDB(SQLTransaction* trans); - Bag* ToBag() { if (IsBag()) return reinterpret_cast(this); else return NULL; } - const Bag* ToBag() const { if (IsBag()) return reinterpret_cast(this); else return NULL; } + Bag* ToBag() { if (IsBag()) return reinterpret_cast(this); else return nullptr; } + Bag const* ToBag() const { if (IsBag()) return reinterpret_cast(this); else return nullptr; } bool IsLocked() const { return !HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_UNLOCKED); } bool IsBag() const { return GetTemplate()->InventoryType == INVTYPE_BAG; } @@ -262,7 +106,7 @@ class TC_GAME_API Item : public Object void SetInTrade(bool b = true) { mb_in_trade = b; } bool IsInTrade() const { return mb_in_trade; } - bool HasEnchantRequiredSkill(const Player* player) const; + bool HasEnchantRequiredSkill(Player const* player) const; uint32 GetEnchantRequiredLevel() const; bool IsFitToSpellRequirements(SpellInfo const* spellInfo) const; @@ -283,7 +127,7 @@ class TC_GAME_API Item : public Object uint16 GetPos() const { return uint16(GetBagSlot()) << 8 | GetSlot(); } void SetContainer(Bag* container) { m_container = container; } - bool IsInBag() const { return m_container != NULL; } + bool IsInBag() const { return m_container != nullptr; } bool IsEquipped() const; uint32 GetSkill(); @@ -293,7 +137,6 @@ class TC_GAME_API Item : public Object uint32 GetItemSuffixFactor() const { return GetUInt32Value(ITEM_FIELD_PROPERTY_SEED); } void SetItemRandomProperties(int32 randomPropId); void UpdateItemSuffixFactor(); - static int32 GenerateItemRandomPropertyId(uint32 item_id); void SetEnchantment(EnchantmentSlot slot, uint32 id, uint32 duration, uint32 charges, ObjectGuid caster = ObjectGuid::Empty); void SetEnchantmentDuration(EnchantmentSlot slot, uint32 duration, Player* owner); void SetEnchantmentCharges(EnchantmentSlot slot, uint32 charges); @@ -319,9 +162,7 @@ class TC_GAME_API Item : public Object // Update States ItemUpdateState GetState() const { return uState; } - void SetState(ItemUpdateState state, Player* forplayer = NULL); - void AddToUpdateQueueOf(Player* player); - void RemoveFromUpdateQueueOf(Player* player); + void SetState(ItemUpdateState state, Player* forplayer = nullptr); bool IsInUpdateQueue() const { return uQueuePos != -1; } uint16 GetQueuePos() const { return uQueuePos; } void FSetState(ItemUpdateState state) // forced @@ -338,7 +179,7 @@ class TC_GAME_API Item : public Object bool IsRangedWeapon() const { return GetTemplate()->IsRangedWeapon(); } // Item Refund system - void SetNotRefundable(Player* owner, bool changestate = true, SQLTransaction* trans = NULL); + void SetNotRefundable(Player* owner, bool changestate = true, SQLTransaction* trans = nullptr); void SetRefundRecipient(ObjectGuid::LowType pGuidLow) { m_refundRecipient = pGuidLow; } void SetPaidMoney(uint32 money) { m_paidMoney = money; } void SetPaidExtendedCost(uint32 iece) { m_paidExtendedCost = iece; } @@ -352,7 +193,7 @@ class TC_GAME_API Item : public Object bool IsRefundExpired(); // Soulbound trade system - void SetSoulboundTradeable(AllowedLooterSet const& allowedLooters); + void SetSoulboundTradeable(GuidSet const& allowedLooters); void ClearSoulboundTradeable(Player* currentOwner); bool CheckSoulboundTradeExpire(); @@ -391,6 +232,6 @@ class TC_GAME_API Item : public Object ObjectGuid::LowType m_refundRecipient; uint32 m_paidMoney; uint32 m_paidExtendedCost; - AllowedLooterSet allowedGUIDs; + GuidSet allowedGUIDs; }; #endif diff --git a/src/server/game/Entities/Item/ItemDefines.h b/src/server/game/Entities/Item/ItemDefines.h new file mode 100644 index 00000000000..b0ff4e24208 --- /dev/null +++ b/src/server/game/Entities/Item/ItemDefines.h @@ -0,0 +1,168 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef ItemDefines_h__ +#define ItemDefines_h__ + +#include "Define.h" + +enum InventoryResult : uint8 +{ + EQUIP_ERR_OK = 0, + EQUIP_ERR_CANT_EQUIP_LEVEL_I = 1, // You must reach level %d to use that item. + EQUIP_ERR_CANT_EQUIP_SKILL = 2, // You aren't skilled enough to use that item. + EQUIP_ERR_WRONG_SLOT = 3, // That item does not go in that slot. + EQUIP_ERR_BAG_FULL = 4, // That bag is full. + EQUIP_ERR_BAG_IN_BAG = 5, // Can't put non-empty bags in other bags. + EQUIP_ERR_TRADE_EQUIPPED_BAG = 6, // You can't trade equipped bags. + EQUIP_ERR_AMMO_ONLY = 7, // Only ammo can go there. + EQUIP_ERR_PROFICIENCY_NEEDED = 8, // You do not have the required proficiency for that item. + EQUIP_ERR_NO_SLOT_AVAILABLE = 9, // No equipment slot is available for that item. + EQUIP_ERR_CANT_EQUIP_EVER = 10, // You can never use that item. + EQUIP_ERR_CANT_EQUIP_EVER_2 = 11, // You can never use that item. + EQUIP_ERR_NO_SLOT_AVAILABLE_2 = 12, // No equipment slot is available for that item. + EQUIP_ERR_2HANDED_EQUIPPED = 13, // Cannot equip that with a two-handed weapon. + EQUIP_ERR_2HSKILLNOTFOUND = 14, // You cannot dual-wield + EQUIP_ERR_WRONG_BAG_TYPE = 15, // That item doesn't go in that container. + EQUIP_ERR_WRONG_BAG_TYPE_2 = 16, // That item doesn't go in that container. + EQUIP_ERR_ITEM_MAX_COUNT = 17, // You can't carry any more of those items. + EQUIP_ERR_NO_SLOT_AVAILABLE_3 = 18, // No equipment slot is available for that item. + EQUIP_ERR_CANT_STACK = 19, // This item cannot stack. + EQUIP_ERR_NOT_EQUIPPABLE = 20, // This item cannot be equipped. + EQUIP_ERR_CANT_SWAP = 21, // These items can't be swapped. + EQUIP_ERR_SLOT_EMPTY = 22, // That slot is empty. + EQUIP_ERR_ITEM_NOT_FOUND = 23, // The item was not found. + EQUIP_ERR_DROP_BOUND_ITEM = 24, // You can't drop a soulbound item. + EQUIP_ERR_OUT_OF_RANGE = 25, // Out of range. + EQUIP_ERR_TOO_FEW_TO_SPLIT = 26, // Tried to split more than number in stack. + EQUIP_ERR_SPLIT_FAILED = 27, // Couldn't split those items. + EQUIP_ERR_SPELL_FAILED_REAGENTS_GENERIC = 28, // Missing reagent + EQUIP_ERR_NOT_ENOUGH_MONEY = 29, // You don't have enough money. + EQUIP_ERR_NOT_A_BAG = 30, // Not a bag. + EQUIP_ERR_DESTROY_NONEMPTY_BAG = 31, // You can only do that with empty bags. + EQUIP_ERR_NOT_OWNER = 32, // You don't own that item. + EQUIP_ERR_ONLY_ONE_QUIVER = 33, // You can only equip one quiver. + EQUIP_ERR_NO_BANK_SLOT = 34, // You must purchase that bag slot first + EQUIP_ERR_NO_BANK_HERE = 35, // You are too far away from a bank. + EQUIP_ERR_ITEM_LOCKED = 36, // Item is locked. + EQUIP_ERR_GENERIC_STUNNED = 37, // You are stunned + EQUIP_ERR_PLAYER_DEAD = 38, // You can't do that when you're dead. + EQUIP_ERR_CLIENT_LOCKED_OUT = 39, // You can't do that right now. + EQUIP_ERR_INTERNAL_BAG_ERROR = 40, // Internal Bag Error + EQUIP_ERR_ONLY_ONE_BOLT = 41, // You can only equip one quiver. + EQUIP_ERR_ONLY_ONE_AMMO = 42, // You can only equip one ammo pouch. + EQUIP_ERR_CANT_WRAP_STACKABLE = 43, // Stackable items can't be wrapped. + EQUIP_ERR_CANT_WRAP_EQUIPPED = 44, // Equipped items can't be wrapped. + EQUIP_ERR_CANT_WRAP_WRAPPED = 45, // Wrapped items can't be wrapped. + EQUIP_ERR_CANT_WRAP_BOUND = 46, // Bound items can't be wrapped. + EQUIP_ERR_CANT_WRAP_UNIQUE = 47, // Unique items can't be wrapped. + EQUIP_ERR_CANT_WRAP_BAGS = 48, // Bags can't be wrapped. + EQUIP_ERR_LOOT_GONE = 49, // Already looted + EQUIP_ERR_INV_FULL = 50, // Inventory is full. + EQUIP_ERR_BANK_FULL = 51, // Your bank is full + EQUIP_ERR_VENDOR_SOLD_OUT = 52, // That item is currently sold out. + EQUIP_ERR_BAG_FULL_2 = 53, // That bag is full. + EQUIP_ERR_ITEM_NOT_FOUND_2 = 54, // The item was not found. + EQUIP_ERR_CANT_STACK_2 = 55, // This item cannot stack. + EQUIP_ERR_BAG_FULL_3 = 56, // That bag is full. + EQUIP_ERR_VENDOR_SOLD_OUT_2 = 57, // That item is currently sold out. + EQUIP_ERR_OBJECT_IS_BUSY = 58, // That object is busy. + EQUIP_ERR_CANT_BE_DISENCHANTED = 59, + EQUIP_ERR_NOT_IN_COMBAT = 60, // You can't do that while in combat + EQUIP_ERR_NOT_WHILE_DISARMED = 61, // You can't do that while disarmed + EQUIP_ERR_BAG_FULL_4 = 62, // That bag is full. + EQUIP_ERR_CANT_EQUIP_RANK = 63, // You don't have the required rank for that item + EQUIP_ERR_CANT_EQUIP_REPUTATION = 64, // You don't have the required reputation for that item + EQUIP_ERR_TOO_MANY_SPECIAL_BAGS = 65, // You cannot equip another bag of that type + EQUIP_ERR_LOOT_CANT_LOOT_THAT_NOW = 66, // You can't loot that item now. + EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE = 67, // You cannot equip more than one of those. + EQUIP_ERR_VENDOR_MISSING_TURNINS = 68, // You do not have the required items for that purchase + EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS = 69, // You don't have enough honor points + EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS = 70, // You don't have enough arena points + EQUIP_ERR_ITEM_MAX_COUNT_SOCKETED = 71, // You have the maximum number of those gems in your inventory or socketed into items. + EQUIP_ERR_MAIL_BOUND_ITEM = 72, // You can't mail soulbound items. + EQUIP_ERR_INTERNAL_BAG_ERROR_2 = 73, // Internal Bag Error + EQUIP_ERR_BAG_FULL_5 = 74, // That bag is full. + EQUIP_ERR_ITEM_MAX_COUNT_EQUIPPED_SOCKETED = 75, // You have the maximum number of those gems socketed into equipped items. + EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED = 76, // You cannot socket more than one of those gems into a single item. + EQUIP_ERR_TOO_MUCH_GOLD = 77, // At gold limit + EQUIP_ERR_NOT_DURING_ARENA_MATCH = 78, // You can't do that while in an arena match + EQUIP_ERR_TRADE_BOUND_ITEM = 79, // You can't trade a soulbound item. + EQUIP_ERR_CANT_EQUIP_RATING = 80, // You don't have the personal, team, or battleground rating required to buy that item + EQUIP_ERR_NO_OUTPUT = 81, + EQUIP_ERR_NOT_SAME_ACCOUNT = 82, // Account-bound items can only be given to your own characters. + EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS = 84, // You can only carry %d %s + EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED_IS = 85, // You can only equip %d |4item:items in the %s category + EQUIP_ERR_SCALING_STAT_ITEM_LEVEL_EXCEEDED = 86, // Your level is too high to use that item + EQUIP_ERR_PURCHASE_LEVEL_TOO_LOW = 87, // You must reach level %d to purchase that item. + EQUIP_ERR_CANT_EQUIP_NEED_TALENT = 88, // You do not have the required talent to equip that. + EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS = 89, // You can only equip %d |4item:items in the %s category + EQUIP_ERR_SHAPESHIFT_FORM_CANNOT_EQUIP = 90, // Cannot equip item in this form + EQUIP_ERR_ITEM_INVENTORY_FULL_SATCHEL = 91, // Your inventory is full. Your satchel has been delivered to your mailbox. + EQUIP_ERR_SCALING_STAT_ITEM_LEVEL_TOO_LOW = 92, // Your level is too low to use that item + EQUIP_ERR_CANT_BUY_QUANTITY = 93, // You can't buy the specified quantity of that item. +}; + +enum BuyResult +{ + BUY_ERR_CANT_FIND_ITEM = 0, + BUY_ERR_ITEM_ALREADY_SOLD = 1, + BUY_ERR_NOT_ENOUGHT_MONEY = 2, + BUY_ERR_SELLER_DONT_LIKE_YOU = 4, + BUY_ERR_DISTANCE_TOO_FAR = 5, + BUY_ERR_ITEM_SOLD_OUT = 7, + BUY_ERR_CANT_CARRY_MORE = 8, + BUY_ERR_RANK_REQUIRE = 11, + BUY_ERR_REPUTATION_REQUIRE = 12 +}; + +enum SellResult +{ + SELL_ERR_CANT_FIND_ITEM = 1, + SELL_ERR_CANT_SELL_ITEM = 2, // merchant doesn't like that item + SELL_ERR_CANT_FIND_VENDOR = 3, // merchant doesn't like you + SELL_ERR_YOU_DONT_OWN_THAT_ITEM = 4, // you don't own that item + SELL_ERR_UNK = 5, // nothing appears... + SELL_ERR_ONLY_EMPTY_BAG = 6 // can only do with empty bags +}; + +// -1 from client enchantment slot number +enum EnchantmentSlot : uint16 +{ + PERM_ENCHANTMENT_SLOT = 0, + TEMP_ENCHANTMENT_SLOT = 1, + SOCK_ENCHANTMENT_SLOT = 2, + SOCK_ENCHANTMENT_SLOT_2 = 3, + SOCK_ENCHANTMENT_SLOT_3 = 4, + BONUS_ENCHANTMENT_SLOT = 5, + PRISMATIC_ENCHANTMENT_SLOT = 6, // added at apply special permanent enchantment + //TODO: 7, + REFORGE_ENCHANTMENT_SLOT = 8, + TRANSMOGRIFY_ENCHANTMENT_SLOT = 9, + MAX_INSPECTED_ENCHANTMENT_SLOT = 10, + + PROP_ENCHANTMENT_SLOT_0 = 10, // used with RandomSuffix + PROP_ENCHANTMENT_SLOT_1 = 11, // used with RandomSuffix + PROP_ENCHANTMENT_SLOT_2 = 12, // used with RandomSuffix and RandomProperty + PROP_ENCHANTMENT_SLOT_3 = 13, // used with RandomProperty + PROP_ENCHANTMENT_SLOT_4 = 14, // used with RandomProperty + MAX_ENCHANTMENT_SLOT = 15 +}; + +#define MAX_VISIBLE_ITEM_OFFSET 2 // 2 fields per visible item (entry+enchantment) + +#endif // ItemDefines_h__ diff --git a/src/server/game/Entities/Item/ItemEnchantmentMgr.cpp b/src/server/game/Entities/Item/ItemEnchantmentMgr.cpp index 84794b0aa4b..05774b1e00f 100644 --- a/src/server/game/Entities/Item/ItemEnchantmentMgr.cpp +++ b/src/server/game/Entities/Item/ItemEnchantmentMgr.cpp @@ -22,6 +22,8 @@ #include "ObjectMgr.h" #include "Util.h" #include "DBCStores.h" +#include "Random.h" +#include "Timer.h" #include #include @@ -118,6 +120,51 @@ uint32 GetItemEnchantMod(int32 entry) return 0; } +int32 GenerateItemRandomPropertyId(uint32 item_id) +{ + ItemTemplate const* itemProto = sObjectMgr->GetItemTemplate(item_id); + if (!itemProto) + return 0; + + // item must have one from this field values not null if it can have random enchantments + if ((!itemProto->RandomProperty) && (!itemProto->RandomSuffix)) + return 0; + + // item can have not null only one from field values + if ((itemProto->RandomProperty) && (itemProto->RandomSuffix)) + { + TC_LOG_ERROR("sql.sql", "Item template %u have RandomProperty == %u and RandomSuffix == %u, but must have one from field =0", itemProto->ItemId, itemProto->RandomProperty, itemProto->RandomSuffix); + return 0; + } + + // RandomProperty case + if (itemProto->RandomProperty) + { + uint32 randomPropId = GetItemEnchantMod(itemProto->RandomProperty); + ItemRandomPropertiesEntry const* random_id = sItemRandomPropertiesStore.LookupEntry(randomPropId); + if (!random_id) + { + TC_LOG_ERROR("sql.sql", "Enchantment id #%u used but it doesn't have records in 'ItemRandomProperties.dbc'", randomPropId); + return 0; + } + + return random_id->ID; + } + // RandomSuffix case + else + { + uint32 randomPropId = GetItemEnchantMod(itemProto->RandomSuffix); + ItemRandomSuffixEntry const* random_id = sItemRandomSuffixStore.LookupEntry(randomPropId); + if (!random_id) + { + TC_LOG_ERROR("sql.sql", "Enchantment id #%u used but it doesn't have records in sItemRandomSuffixStore.", randomPropId); + return 0; + } + + return -int32(random_id->ID); + } +} + uint32 GenerateEnchSuffixFactor(uint32 item_id) { ItemTemplate const* itemProto = sObjectMgr->GetItemTemplate(item_id); diff --git a/src/server/game/Entities/Item/ItemEnchantmentMgr.h b/src/server/game/Entities/Item/ItemEnchantmentMgr.h index 54bd78d863d..da50f466095 100644 --- a/src/server/game/Entities/Item/ItemEnchantmentMgr.h +++ b/src/server/game/Entities/Item/ItemEnchantmentMgr.h @@ -22,6 +22,7 @@ #include "Common.h" TC_GAME_API void LoadRandomEnchantmentsTable(); +TC_GAME_API int32 GenerateItemRandomPropertyId(uint32 item_id); 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.h b/src/server/game/Entities/Item/ItemTemplate.h index 6a723a26008..afd00ce6a0a 100644 --- a/src/server/game/Entities/Item/ItemTemplate.h +++ b/src/server/game/Entities/Item/ItemTemplate.h @@ -21,6 +21,8 @@ #include "Common.h" #include "SharedDefines.h" +#include "WorldPacket.h" +#include enum ItemModType { @@ -284,7 +286,7 @@ enum SocketColor #define SOCKET_COLOR_ALL (SOCKET_COLOR_META | SOCKET_COLOR_RED | SOCKET_COLOR_YELLOW | SOCKET_COLOR_BLUE | SOCKET_COLOR_COGWHEEL) -enum InventoryType +enum InventoryType : uint8 { INVTYPE_NON_EQUIP = 0, INVTYPE_HEAD = 1, @@ -319,7 +321,7 @@ enum InventoryType #define MAX_INVTYPE 29 -enum ItemClass +enum ItemClass : uint8 { ITEM_CLASS_CONSUMABLE = 0, ITEM_CLASS_CONTAINER = 1, @@ -744,13 +746,10 @@ struct ItemTemplate } }; -// Benchmarked: Faster than std::map (insert/find) -typedef std::unordered_map ItemTemplateContainer; - struct ItemLocale { - StringVector Name; - StringVector Description; + std::vector Name; + std::vector Description; }; #endif diff --git a/src/server/game/Entities/Object/MovementInfo.h b/src/server/game/Entities/Object/MovementInfo.h new file mode 100644 index 00000000000..3c7b40e19aa --- /dev/null +++ b/src/server/game/Entities/Object/MovementInfo.h @@ -0,0 +1,111 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef MovementInfo_h__ +#define MovementInfo_h__ + +#include "ObjectGuid.h" +#include "Position.h" + +struct MovementInfo +{ + // common + ObjectGuid guid; + uint32 flags; + uint16 flags2; + Position pos; + uint32 time; + + // transport + struct TransportInfo + { + void Reset() + { + guid.Clear(); + pos.Relocate(0.0f, 0.0f, 0.0f, 0.0f); + seat = -1; + time = 0; + time2 = 0; + vehicleId = 0; + } + + ObjectGuid guid; + Position pos; + int8 seat; + uint32 time; + uint32 time2; + uint32 vehicleId; + } transport; + + // swimming/flying + float pitch; + + // jumping + struct JumpInfo + { + void Reset() + { + fallTime = 0; + zspeed = sinAngle = cosAngle = xyspeed = 0.0f; + } + + uint32 fallTime; + + float zspeed, sinAngle, cosAngle, xyspeed; + + } jump; + + // spline + float splineElevation; + + MovementInfo() : + flags(0), flags2(0), time(0), pitch(0.0f), splineElevation(0.0f) + { + pos.Relocate(0.0f, 0.0f, 0.0f, 0.0f); + transport.Reset(); + jump.Reset(); + } + + uint32 GetMovementFlags() const { return flags; } + void SetMovementFlags(uint32 flag) { flags = flag; } + void AddMovementFlag(uint32 flag) { flags |= flag; } + void RemoveMovementFlag(uint32 flag) { flags &= ~flag; } + bool HasMovementFlag(uint32 flag) const { return (flags & flag) != 0; } + + uint16 GetExtraMovementFlags() const { return flags2; } + void SetExtraMovementFlags(uint16 flag) { flags2 = flag; } + void AddExtraMovementFlag(uint16 flag) { flags2 |= flag; } + void RemoveExtraMovementFlag(uint16 flag) { flags2 &= ~flag; } + bool HasExtraMovementFlag(uint16 flag) const { return (flags2 & flag) != 0; } + + uint32 GetFallTime() const { return jump.fallTime; } + void SetFallTime(uint32 time) { jump.fallTime = time; } + + void ResetTransport() + { + transport.Reset(); + } + + void ResetJump() + { + jump.Reset(); + } + + void OutDebug(); +}; + +#endif // MovementInfo_h__ diff --git a/src/server/game/Entities/Object/Object.cpp b/src/server/game/Entities/Object/Object.cpp index d754ae9a583..c823c89613b 100644 --- a/src/server/game/Entities/Object/Object.cpp +++ b/src/server/game/Entities/Object/Object.cpp @@ -17,43 +17,44 @@ */ #include "Object.h" -#include "Common.h" -#include "SharedDefines.h" -#include "WorldPacket.h" -#include "Opcodes.h" -#include "Log.h" -#include "World.h" -#include "Creature.h" -#include "Player.h" -#include "Vehicle.h" -#include "ObjectMgr.h" -#include "UpdateData.h" -#include "UpdateMask.h" -#include "Util.h" -#include "MapManager.h" -#include "ObjectAccessor.h" -#include "Log.h" -#include "Transport.h" -#include "TargetedMovementGenerator.h" -#include "WaypointMovementGenerator.h" -#include "VMapFactory.h" -#include "CellImpl.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "SpellAuraEffects.h" -#include "UpdateFieldFlags.h" -#include "TemporarySummon.h" -#include "Totem.h" -#include "OutdoorPvPMgr.h" -#include "PhasingHandler.h" -#include "MovementPacketBuilder.h" -#include "DynamicTree.h" -#include "Unit.h" -#include "Group.h" #include "BattlefieldMgr.h" #include "Battleground.h" +#include "CellImpl.h" #include "Chat.h" +#include "CinematicMgr.h" +#include "Common.h" +#include "Creature.h" +#include "DynamicTree.h" #include "GameTime.h" +#include "GridNotifiers.h" +#include "GridNotifiersImpl.h" +#include "Group.h" +#include "Item.h" +#include "Log.h" +#include "MapManager.h" +#include "MovementPacketBuilder.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Opcodes.h" +#include "OutdoorPvPMgr.h" +#include "PhasingHandler.h" +#include "Player.h" +#include "SharedDefines.h" +#include "SpellAuraEffects.h" +#include "TargetedMovementGenerator.h" +#include "TemporarySummon.h" +#include "Totem.h" +#include "Transport.h" +#include "Unit.h" +#include "UpdateData.h" +#include "UpdateFieldFlags.h" +#include "UpdateMask.h" +#include "Util.h" +#include "Vehicle.h" +#include "VMapFactory.h" +#include "WaypointMovementGenerator.h" +#include "World.h" +#include "WorldPacket.h" Object::Object() : m_PackGUID(sizeof(uint64)+1) { @@ -61,7 +62,7 @@ Object::Object() : m_PackGUID(sizeof(uint64)+1) m_objectType = TYPEMASK_OBJECT; m_updateFlag = UPDATEFLAG_NONE; - m_uint32Values = NULL; + m_uint32Values = nullptr; m_valuesCount = 0; _fieldNotifyFlags = UF_FLAG_DYNAMIC; @@ -251,7 +252,7 @@ void Object::SendUpdateToPlayer(Player* player) else BuildCreateUpdateBlockForPlayer(&upd, player); upd.BuildPacket(&packet); - player->GetSession()->SendPacket(&packet); + player->SendDirectMessage(&packet); } void Object::BuildValuesUpdateBlockForPlayer(UpdateData* data, Player* target) const @@ -328,7 +329,7 @@ ObjectGuid Object::GetGuidValue(uint16 index) const void Object::BuildMovementUpdate(ByteBuffer* data, uint16 flags) const { - Unit const* self = NULL; + Unit const* self = nullptr; ObjectGuid guid = GetGUID(); uint32 movementFlags = 0; uint16 movementFlagsExtra = 0; @@ -674,7 +675,7 @@ void Object::BuildValuesUpdate(uint8 updateType, ByteBuffer* data, Player* targe UpdateMask updateMask; updateMask.SetCount(m_valuesCount); - uint32* flags = NULL; + uint32* flags = nullptr; uint32 visibleFlag = GetUpdateFieldData(target, flags); ASSERT(flags); @@ -1164,7 +1165,7 @@ void MovementInfo::OutDebug() TC_LOG_DEBUG("misc", "%s", guid.ToString().c_str()); TC_LOG_DEBUG("misc", "flags %u", flags); TC_LOG_DEBUG("misc", "flags2 %u", flags2); - TC_LOG_DEBUG("misc", "time %u current time " UI64FMTD "", flags2, uint64(::time(NULL))); + TC_LOG_DEBUG("misc", "time %u current time " UI64FMTD "", flags2, uint64(::time(nullptr))); TC_LOG_DEBUG("misc", "position: `%s`", pos.ToString().c_str()); if (transport.guid) { @@ -1313,7 +1314,7 @@ void WorldObject::RemoveFromWorld() InstanceScript* WorldObject::GetInstanceScript() const { Map* map = GetMap(); - return map->IsDungeon() ? ((InstanceMap*)map)->GetInstanceScript() : NULL; + return map->IsDungeon() ? ((InstanceMap*)map)->GetInstanceScript() : nullptr; } float WorldObject::GetDistanceZ(const WorldObject* obj) const @@ -1998,7 +1999,7 @@ void WorldObject::ResetMap() ASSERT(!IsInWorld()); if (IsWorldObject()) m_currMap->RemoveWorldObject(this); - m_currMap = NULL; + m_currMap = nullptr; //maybe not for corpse //m_mapId = 0; //m_InstanceId = 0; @@ -2070,11 +2071,11 @@ TempSummon* Map::SummonCreature(uint32 entry, Position const& pos, SummonPropert break; } default: - return NULL; + return nullptr; } } - TempSummon* summon = NULL; + TempSummon* summon = nullptr; switch (mask) { case UNIT_MASK_SUMMON: @@ -2097,7 +2098,7 @@ TempSummon* Map::SummonCreature(uint32 entry, Position const& pos, SummonPropert if (!summon->Create(GenerateLowGuid(), this, 0, entry, pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), nullptr, vehId)) { delete summon; - return NULL; + return nullptr; } // Set the summon to the summoner's phase @@ -2126,14 +2127,14 @@ TempSummon* Map::SummonCreature(uint32 entry, Position const& pos, SummonPropert * @param list List to store pointers to summoned creatures. */ -void Map::SummonCreatureGroup(uint8 group, std::list* list /*= NULL*/) +void Map::SummonCreatureGroup(uint8 group, std::list* list /*= nullptr*/) { std::vector const* data = sObjectMgr->GetSummonGroup(GetId(), SUMMONER_TYPE_MAP, group); if (!data) return; for (std::vector::const_iterator itr = data->begin(); itr != data->end(); ++itr) - if (TempSummon* summon = SummonCreature(itr->entry, itr->pos, NULL, itr->time)) + if (TempSummon* summon = SummonCreature(itr->entry, itr->pos, nullptr, itr->time)) if (list) list->push_back(summon); } @@ -2163,7 +2164,7 @@ TempSummon* WorldObject::SummonCreature(uint32 entry, Position const& pos, TempS { if (Map* map = FindMap()) { - if (TempSummon* summon = map->SummonCreature(entry, pos, NULL, duration, isType(TYPEMASK_UNIT) ? (Unit*)this : NULL)) + if (TempSummon* summon = map->SummonCreature(entry, pos, nullptr, duration, isType(TYPEMASK_UNIT) ? (Unit*)this : nullptr)) { summon->SetTempSummonType(spwtype); return summon; @@ -2186,7 +2187,7 @@ TempSummon* WorldObject::SummonCreature(uint32 id, float x, float y, float z, fl return SummonCreature(id, pos, spwtype, despwtime, 0); } -GameObject* WorldObject::SummonGameObject(uint32 entry, Position const& pos, G3D::Quat const& rot, uint32 respawnTime, GOSummonType summonType) +GameObject* WorldObject::SummonGameObject(uint32 entry, Position const& pos, QuaternionData const& rot, uint32 respawnTime, GOSummonType summonType) { if (!IsInWorld()) return nullptr; @@ -2218,7 +2219,7 @@ GameObject* WorldObject::SummonGameObject(uint32 entry, Position const& pos, G3D return go; } -GameObject* WorldObject::SummonGameObject(uint32 entry, float x, float y, float z, float ang, G3D::Quat const& rot, uint32 respawnTime) +GameObject* WorldObject::SummonGameObject(uint32 entry, float x, float y, float z, float ang, QuaternionData const& rot, uint32 respawnTime) { if (!x && !y && !z) { @@ -2255,7 +2256,7 @@ Creature* WorldObject::SummonTrigger(float x, float y, float z, float ang, uint3 * @param group Id of group to summon. * @param list List to store pointers to summoned creatures. */ -void WorldObject::SummonCreatureGroup(uint8 group, std::list* list /*= NULL*/) +void WorldObject::SummonCreatureGroup(uint8 group, std::list* list /*= nullptr*/) { ASSERT((GetTypeId() == TYPEID_GAMEOBJECT || GetTypeId() == TYPEID_UNIT) && "Only GOs and creatures can summon npc groups!"); @@ -2560,7 +2561,7 @@ void WorldObject::SetPhaseMask(uint32 newPhaseMask, bool update) UpdateObjectVisibility(); } -void WorldObject::PlayDistanceSound(uint32 sound_id, Player* target /*= NULL*/) +void WorldObject::PlayDistanceSound(uint32 sound_id, Player* target /*= nullptr*/) { WorldPacket data(SMSG_PLAY_OBJECT_SOUND, 4 + 8); data << uint32(sound_id); @@ -2571,7 +2572,7 @@ void WorldObject::PlayDistanceSound(uint32 sound_id, Player* target /*= NULL*/) SendMessageToSet(&data, true); } -void WorldObject::PlayDirectSound(uint32 sound_id, Player* target /*= NULL*/) +void WorldObject::PlayDirectSound(uint32 sound_id, Player* target /*= nullptr*/) { WorldPacket data(SMSG_PLAY_SOUND, 4 + 8); data << uint32(sound_id); @@ -2582,7 +2583,7 @@ void WorldObject::PlayDirectSound(uint32 sound_id, Player* target /*= NULL*/) SendMessageToSet(&data, true); } -void WorldObject::PlayDirectMusic(uint32 music_id, Player* target /*= NULL*/) +void WorldObject::PlayDirectMusic(uint32 music_id, Player* target /*= nullptr*/) { WorldPacket data(SMSG_PLAY_MUSIC, 4); data << uint32(music_id); @@ -2634,7 +2635,7 @@ struct WorldObjectChangeAccumulator WorldObjectChangeAccumulator(WorldObject &obj, UpdateDataMapType &d) : i_updateDatas(d), i_object(obj) { } void Visit(PlayerMapType &m) { - Player* source = NULL; + Player* source = nullptr; for (PlayerMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { source = iter->GetSource(); @@ -2652,7 +2653,7 @@ struct WorldObjectChangeAccumulator void Visit(CreatureMapType &m) { - Creature* source = NULL; + Creature* source = nullptr; for (CreatureMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { source = iter->GetSource(); @@ -2667,7 +2668,7 @@ struct WorldObjectChangeAccumulator void Visit(DynamicObjectMapType &m) { - DynamicObject* source = NULL; + DynamicObject* source = nullptr; for (DynamicObjectMapType::iterator iter = m.begin(); iter != m.end(); ++iter) { source = iter->GetSource(); @@ -2675,7 +2676,7 @@ struct WorldObjectChangeAccumulator if (guid.IsPlayer()) { - //Caster may be NULL if DynObj is in removelist + //Caster may be nullptr if DynObj is in removelist if (Player* caster = ObjectAccessor::FindPlayer(guid)) if (caster->GetGuidValue(PLAYER_FARSIGHT) == source->GetGUID()) BuildPacket(caster); diff --git a/src/server/game/Entities/Object/Object.h b/src/server/game/Entities/Object/Object.h index 70e4c68acb5..c1942694dfa 100644 --- a/src/server/game/Entities/Object/Object.h +++ b/src/server/game/Entities/Object/Object.h @@ -20,66 +20,29 @@ #define _OBJECT_H #include "Common.h" -#include "Position.h" -#include "UpdateMask.h" #include "GridReference.h" -#include "ObjectDefines.h" -#include "PhaseShift.h" -#include "Map.h" +#include "GridRefManager.h" #include "ModelIgnoreFlags.h" +#include "MovementInfo.h" +#include "ObjectDefines.h" +#include "ObjectGuid.h" +#include "PhaseShift.h" +#include "Position.h" +#include "SharedDefines.h" +#include "UpdateFields.h" +#include "UpdateMask.h" +#include +#include +#include -#include -#include - -#define CONTACT_DISTANCE 0.5f -#define INTERACTION_DISTANCE 5.0f -#define ATTACK_DISTANCE 5.0f -#define INSPECT_DISTANCE 28.0f -#define TRADE_DISTANCE 11.11f -#define MAX_VISIBILITY_DISTANCE SIZE_OF_GRIDS // max distance for visible objects -#define SIGHT_RANGE_UNIT 50.0f -#define DEFAULT_VISIBILITY_DISTANCE 90.0f // default visible distance, 90 yards on continents -#define DEFAULT_VISIBILITY_INSTANCE 170.0f // default visible distance in instances, 170 yards -#define DEFAULT_VISIBILITY_BGARENAS 533.0f // default visible distance in BG/Arenas, roughly 533 yards - -#define DEFAULT_WORLD_OBJECT_SIZE 0.388999998569489f // player size, also currently used (correctly?) for any non Unit world objects -#define DEFAULT_COMBAT_REACH 1.5f -#define MIN_MELEE_REACH 2.0f -#define NOMINAL_MELEE_RANGE 5.0f -#define MELEE_RANGE (NOMINAL_MELEE_RANGE - MIN_MELEE_REACH * 2) //center to center for players - -enum TempSummonType -{ - TEMPSUMMON_TIMED_OR_DEAD_DESPAWN = 1, // despawns after a specified time OR when the creature disappears - TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN = 2, // despawns after a specified time OR when the creature dies - TEMPSUMMON_TIMED_DESPAWN = 3, // despawns after a specified time - TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT = 4, // despawns after a specified time after the creature is out of combat - TEMPSUMMON_CORPSE_DESPAWN = 5, // despawns instantly after death - TEMPSUMMON_CORPSE_TIMED_DESPAWN = 6, // despawns after a specified time after death - TEMPSUMMON_DEAD_DESPAWN = 7, // despawns when the creature disappears - TEMPSUMMON_MANUAL_DESPAWN = 8 // despawns when UnSummon() is called -}; - -enum PhaseMasks -{ - PHASEMASK_NORMAL = 0x00000001, - PHASEMASK_ANYWHERE = 0xFFFFFFFF -}; - -enum NotifyFlags -{ - NOTIFY_NONE = 0x00, - NOTIFY_AI_RELOCATION = 0x01, - NOTIFY_VISIBILITY_CHANGED = 0x02, - NOTIFY_ALL = 0xFF -}; - +class AreaTrigger; class Corpse; class Creature; class CreatureAI; class DynamicObject; class GameObject; class InstanceScript; +class Map; class Player; class TempSummon; class Transport; @@ -88,6 +51,8 @@ class UpdateData; class WorldObject; class WorldPacket; class ZoneScript; +struct PositionFullTerrainStatus; +struct QuaternionData; typedef std::unordered_map UpdateDataMapType; @@ -183,26 +148,26 @@ class TC_GAME_API Object // FG: some hacky helpers void ForceValuesUpdateAtIndex(uint32); - Player* ToPlayer() { if (GetTypeId() == TYPEID_PLAYER) return reinterpret_cast(this); else return NULL; } - Player const* ToPlayer() const { if (GetTypeId() == TYPEID_PLAYER) return reinterpret_cast(this); else return NULL; } + Player* ToPlayer() { if (GetTypeId() == TYPEID_PLAYER) return reinterpret_cast(this); else return nullptr; } + Player const* ToPlayer() const { if (GetTypeId() == TYPEID_PLAYER) return reinterpret_cast(this); else return nullptr; } - Creature* ToCreature() { if (GetTypeId() == TYPEID_UNIT) return reinterpret_cast(this); else return NULL; } - Creature const* ToCreature() const { if (GetTypeId() == TYPEID_UNIT) return reinterpret_cast(this); else return NULL; } + Creature* ToCreature() { if (GetTypeId() == TYPEID_UNIT) return reinterpret_cast(this); else return nullptr; } + Creature const* ToCreature() const { if (GetTypeId() == TYPEID_UNIT) return reinterpret_cast(this); else return nullptr; } - Unit* ToUnit() { if (isType(TYPEMASK_UNIT)) return reinterpret_cast(this); else return NULL; } - Unit const* ToUnit() const { if (isType(TYPEMASK_UNIT)) return reinterpret_cast(this); else return NULL; } + Unit* ToUnit() { if (isType(TYPEMASK_UNIT)) return reinterpret_cast(this); else return nullptr; } + Unit const* ToUnit() const { if (isType(TYPEMASK_UNIT)) return reinterpret_cast(this); else return nullptr; } - GameObject* ToGameObject() { if (GetTypeId() == TYPEID_GAMEOBJECT) return reinterpret_cast(this); else return NULL; } - GameObject const* ToGameObject() const { if (GetTypeId() == TYPEID_GAMEOBJECT) return reinterpret_cast(this); else return NULL; } + GameObject* ToGameObject() { if (GetTypeId() == TYPEID_GAMEOBJECT) return reinterpret_cast(this); else return nullptr; } + GameObject const* ToGameObject() const { if (GetTypeId() == TYPEID_GAMEOBJECT) return reinterpret_cast(this); else return nullptr; } - Corpse* ToCorpse() { if (GetTypeId() == TYPEID_CORPSE) return reinterpret_cast(this); else return NULL; } - Corpse const* ToCorpse() const { if (GetTypeId() == TYPEID_CORPSE) return reinterpret_cast(this); else return NULL; } + Corpse* ToCorpse() { if (GetTypeId() == TYPEID_CORPSE) return reinterpret_cast(this); else return nullptr; } + Corpse const* ToCorpse() const { if (GetTypeId() == TYPEID_CORPSE) return reinterpret_cast(this); else return nullptr; } - DynamicObject* ToDynObject() { if (GetTypeId() == TYPEID_DYNAMICOBJECT) return reinterpret_cast(this); else return NULL; } - DynamicObject const* ToDynObject() const { if (GetTypeId() == TYPEID_DYNAMICOBJECT) return reinterpret_cast(this); else return NULL; } + DynamicObject* ToDynObject() { if (GetTypeId() == TYPEID_DYNAMICOBJECT) return reinterpret_cast(this); else return nullptr; } + DynamicObject const* ToDynObject() const { if (GetTypeId() == TYPEID_DYNAMICOBJECT) return reinterpret_cast(this); else return nullptr; } - AreaTrigger* ToAreaTrigger() { if (GetTypeId() == TYPEID_AREATRIGGER) return reinterpret_cast(this); else return NULL; } - AreaTrigger const* ToAreaTrigger() const { if (GetTypeId() == TYPEID_AREATRIGGER) return reinterpret_cast(this); else return NULL; } + AreaTrigger* ToAreaTrigger() { if (GetTypeId() == TYPEID_AREATRIGGER) return reinterpret_cast(this); else return nullptr; } + AreaTrigger const* ToAreaTrigger() const { if (GetTypeId() == TYPEID_AREATRIGGER) return reinterpret_cast(this); else return nullptr; } protected: Object(); @@ -252,129 +217,6 @@ class TC_GAME_API Object Object& operator=(Object const& right) = delete; }; -struct MovementInfo -{ - // common - ObjectGuid guid; - uint32 flags; - uint16 flags2; - Position pos; - uint32 time; - - // transport - struct TransportInfo - { - void Reset() - { - guid.Clear(); - pos.Relocate(0.0f, 0.0f, 0.0f, 0.0f); - seat = -1; - time = 0; - time2 = 0; - vehicleId = 0; - } - - ObjectGuid guid; - Position pos; - int8 seat; - uint32 time; - uint32 time2; - uint32 vehicleId; - } transport; - - // swimming/flying - float pitch; - - // jumping - struct JumpInfo - { - void Reset() - { - fallTime = 0; - zspeed = sinAngle = cosAngle = xyspeed = 0.0f; - } - - uint32 fallTime; - - float zspeed, sinAngle, cosAngle, xyspeed; - - } jump; - - // spline - float splineElevation; - - MovementInfo() : - flags(0), flags2(0), time(0), pitch(0.0f), splineElevation(0.0f) - { - pos.Relocate(0.0f, 0.0f, 0.0f, 0.0f); - transport.Reset(); - jump.Reset(); - } - - uint32 GetMovementFlags() const { return flags; } - void SetMovementFlags(uint32 flag) { flags = flag; } - void AddMovementFlag(uint32 flag) { flags |= flag; } - void RemoveMovementFlag(uint32 flag) { flags &= ~flag; } - bool HasMovementFlag(uint32 flag) const { return (flags & flag) != 0; } - - uint16 GetExtraMovementFlags() const { return flags2; } - void SetExtraMovementFlags(uint16 flag) { flags2 = flag; } - void AddExtraMovementFlag(uint16 flag) { flags2 |= flag; } - void RemoveExtraMovementFlag(uint16 flag) { flags2 &= ~flag; } - bool HasExtraMovementFlag(uint16 flag) const { return (flags2 & flag) != 0; } - - uint32 GetFallTime() const { return jump.fallTime; } - void SetFallTime(uint32 time) { jump.fallTime = time; } - - void ResetTransport() - { - transport.Reset(); - } - - void ResetJump() - { - jump.Reset(); - } - - void OutDebug(); -}; - -#define MAPID_INVALID 0xFFFFFFFF - -class WorldLocation : public Position -{ - public: - explicit WorldLocation(uint32 _mapId = MAPID_INVALID, float _x = 0.f, float _y = 0.f, float _z = 0.f, float _o = 0.f) - : Position(_x, _y, _z, _o), m_mapId(_mapId) { } - - WorldLocation(uint32 mapId, Position const& position) - : Position(position), m_mapId(mapId) { } - - WorldLocation(WorldLocation const& loc) - : Position(loc), m_mapId(loc.GetMapId()) { } - - void WorldRelocate(WorldLocation const& loc) - { - m_mapId = loc.GetMapId(); - Relocate(loc); - } - - void WorldRelocate(uint32 _mapId = MAPID_INVALID, float _x = 0.f, float _y = 0.f, float _z = 0.f, float _o = 0.f) - { - m_mapId = _mapId; - Relocate(_x, _y, _z, _o); - } - - WorldLocation GetWorldLocation() const - { - return *this; - } - - uint32 GetMapId() const { return m_mapId; } - - uint32 m_mapId; -}; - template class GridObject { @@ -394,7 +236,8 @@ class FlaggedValuesArray32 public: FlaggedValuesArray32() { - memset(&m_values, 0x00, sizeof(T_VALUES) * ARRAY_SIZE); + for (uint32 i = 0; i < ARRAY_SIZE; ++i) + m_values[i] = T_VALUES(0); m_flags = 0; } @@ -412,38 +255,6 @@ class FlaggedValuesArray32 T_FLAGS m_flags; }; -enum MapObjectCellMoveState -{ - MAP_OBJECT_CELL_MOVE_NONE, //not in move list - MAP_OBJECT_CELL_MOVE_ACTIVE, //in move list - MAP_OBJECT_CELL_MOVE_INACTIVE, //in move list but should not move -}; - -class TC_GAME_API MapObject -{ - friend class Map; //map for moving creatures - friend class ObjectGridLoader; //grid loader for loading creatures - - protected: - MapObject() : _moveState(MAP_OBJECT_CELL_MOVE_NONE) - { - _newPosition.Relocate(0.0f, 0.0f, 0.0f, 0.0f); - } - - private: - Cell _currentCell; - Cell const& GetCurrentCell() const { return _currentCell; } - void SetCurrentCell(Cell const& cell) { _currentCell = cell; } - - MapObjectCellMoveState _moveState; - Position _newPosition; - void SetNewCellPosition(float x, float y, float z, float o) - { - _moveState = MAP_OBJECT_CELL_MOVE_ACTIVE; - _newPosition.Relocate(x, y, z, o); - } -}; - enum GOSummonType { GO_SUMMON_TIMED_OR_CORPSE_DESPAWN = 0, // despawns after a specified time OR when the summoner dies @@ -477,8 +288,8 @@ class TC_GAME_API WorldObject : public Object, public WorldLocation void UpdateGroundPositionZ(float x, float y, float &z) const; void UpdateAllowedPositionZ(float x, float y, float &z) const; - void GetRandomPoint(Position const &srcPos, float distance, float &rand_x, float &rand_y, float &rand_z) const; - Position GetRandomPoint(Position const &srcPos, float distance) const; + void GetRandomPoint(Position const& srcPos, float distance, float& rand_x, float& rand_y, float& rand_z) const; + Position GetRandomPoint(Position const& srcPos, float distance) const; uint32 GetInstanceId() const { return m_InstanceId; } @@ -505,12 +316,12 @@ class TC_GAME_API WorldObject : public Object, public WorldLocation InstanceScript* GetInstanceScript() const; std::string const& GetName() const { return m_name; } - void SetName(std::string const& newname) { m_name=newname; } + void SetName(std::string const& newname) { m_name = newname; } virtual std::string const& GetNameForLocaleIdx(LocaleConstant /*locale_idx*/) const { return m_name; } float GetDistance(WorldObject const* obj) const; - float GetDistance(Position const &pos) const; + float GetDistance(Position const& pos) const; float GetDistance(float x, float y, float z) const; float GetDistance2d(WorldObject const* obj) const; float GetDistance2d(float x, float y) const; @@ -547,16 +358,16 @@ class TC_GAME_API WorldObject : public Object, public WorldLocation virtual uint8 getLevelForTarget(WorldObject const* /*target*/) const { return 1; } - void PlayDistanceSound(uint32 sound_id, Player* target = NULL); - void PlayDirectSound(uint32 sound_id, Player* target = NULL); - void PlayDirectMusic(uint32 music_id, Player* target = NULL); + void PlayDistanceSound(uint32 sound_id, Player* target = nullptr); + void PlayDirectSound(uint32 sound_id, Player* target = nullptr); + void PlayDirectMusic(uint32 music_id, Player* target = nullptr); virtual void SaveRespawnTime() { } void AddObjectToRemoveList(); float GetGridActivationRange() const; float GetVisibilityRange() const; - float GetSightRange(WorldObject const* target = NULL) const; + float GetSightRange(WorldObject const* target = nullptr) const; bool CanSeeOrDetect(WorldObject const* obj, bool ignoreStealth = false, bool distanceCheck = false, bool checkAlert = false) const; FlaggedValuesArray32 m_stealth; @@ -583,10 +394,10 @@ class TC_GAME_API WorldObject : public Object, public WorldLocation 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, Position const& pos, G3D::Quat const& rot, uint32 respawnTime /* s */, GOSummonType summonType = GO_SUMMON_TIMED_OR_CORPSE_DESPAWN); - 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* list = NULL); + GameObject* SummonGameObject(uint32 entry, Position const& pos, QuaternionData const& rot, uint32 respawnTime /* s */, GOSummonType summonType = GO_SUMMON_TIMED_OR_CORPSE_DESPAWN); + GameObject* SummonGameObject(uint32 entry, float x, float y, float z, float ang, QuaternionData const& rot, uint32 respawnTime /* s */); + Creature* SummonTrigger(float x, float y, float z, float ang, uint32 dur, CreatureAI* (*GetAI)(Creature*) = nullptr); + void SummonCreatureGroup(uint8 group, std::list* list = nullptr); Creature* FindNearestCreature(uint32 entry, float range, bool alive = true) const; GameObject* FindNearestGameObject(uint32 entry, float range) const; @@ -639,6 +450,7 @@ class TC_GAME_API WorldObject : public Object, public WorldLocation float GetTransOffsetY() const { return m_movementInfo.transport.pos.GetPositionY(); } float GetTransOffsetZ() const { return m_movementInfo.transport.pos.GetPositionZ(); } float GetTransOffsetO() const { return m_movementInfo.transport.pos.GetOrientation(); } + Position const& GetTransOffset() const { return m_movementInfo.transport.pos; } uint32 GetTransTime() const { return m_movementInfo.transport.time; } int8 GetTransSeat() const { return m_movementInfo.transport.seat; } virtual ObjectGuid GetTransGUID() const; diff --git a/src/server/game/Entities/Object/ObjectDefines.h b/src/server/game/Entities/Object/ObjectDefines.h index e8455f6b1b1..4891da4e61c 100644 --- a/src/server/game/Entities/Object/ObjectDefines.h +++ b/src/server/game/Entities/Object/ObjectDefines.h @@ -20,48 +20,81 @@ #define TRINITY_OBJECTDEFINES_H #include "Define.h" -#include "ObjectGuid.h" -// used for creating values for respawn for example -inline uint64 MAKE_PAIR64(uint32 l, uint32 h); -inline uint32 PAIR64_HIPART(uint64 x); -inline uint32 PAIR64_LOPART(uint64 x); -inline uint16 MAKE_PAIR16(uint8 l, uint8 h); -inline uint32 MAKE_PAIR32(uint16 l, uint16 h); -inline uint16 PAIR32_HIPART(uint32 x); -inline uint16 PAIR32_LOPART(uint32 x); +#define CONTACT_DISTANCE 0.5f +#define INTERACTION_DISTANCE 5.0f +#define ATTACK_DISTANCE 5.0f +#define INSPECT_DISTANCE 28.0f +#define TRADE_DISTANCE 11.11f +#define MAX_VISIBILITY_DISTANCE SIZE_OF_GRIDS // max distance for visible objects +#define SIGHT_RANGE_UNIT 50.0f +#define DEFAULT_VISIBILITY_DISTANCE 90.0f // default visible distance, 90 yards on continents +#define DEFAULT_VISIBILITY_INSTANCE 170.0f // default visible distance in instances, 170 yards +#define DEFAULT_VISIBILITY_BGARENAS 533.0f // default visible distance in BG/Arenas, roughly 533 yards -uint64 MAKE_PAIR64(uint32 l, uint32 h) +#define DEFAULT_WORLD_OBJECT_SIZE 0.388999998569489f // player size, also currently used (correctly?) for any non Unit world objects +#define DEFAULT_COMBAT_REACH 1.5f +#define MIN_MELEE_REACH 2.0f +#define NOMINAL_MELEE_RANGE 5.0f +#define MELEE_RANGE (NOMINAL_MELEE_RANGE - MIN_MELEE_REACH * 2) //center to center for players + +enum TempSummonType +{ + TEMPSUMMON_TIMED_OR_DEAD_DESPAWN = 1, // despawns after a specified time OR when the creature disappears + TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN = 2, // despawns after a specified time OR when the creature dies + TEMPSUMMON_TIMED_DESPAWN = 3, // despawns after a specified time + TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT = 4, // despawns after a specified time after the creature is out of combat + TEMPSUMMON_CORPSE_DESPAWN = 5, // despawns instantly after death + TEMPSUMMON_CORPSE_TIMED_DESPAWN = 6, // despawns after a specified time after death + TEMPSUMMON_DEAD_DESPAWN = 7, // despawns when the creature disappears + TEMPSUMMON_MANUAL_DESPAWN = 8 // despawns when UnSummon() is called +}; + +enum PhaseMasks +{ + PHASEMASK_NORMAL = 0x00000001, + PHASEMASK_ANYWHERE = 0xFFFFFFFF +}; + +enum NotifyFlags +{ + NOTIFY_NONE = 0x00, + NOTIFY_AI_RELOCATION = 0x01, + NOTIFY_VISIBILITY_CHANGED = 0x02, + NOTIFY_ALL = 0xFF +}; + +inline uint64 MAKE_PAIR64(uint32 l, uint32 h) { return uint64(l | (uint64(h) << 32)); } -uint32 PAIR64_HIPART(uint64 x) +inline uint32 PAIR64_HIPART(uint64 x) { return (uint32)((x >> 32) & UI64LIT(0x00000000FFFFFFFF)); } -uint32 PAIR64_LOPART(uint64 x) +inline uint32 PAIR64_LOPART(uint64 x) { return (uint32)(x & UI64LIT(0x00000000FFFFFFFF)); } -uint16 MAKE_PAIR16(uint8 l, uint8 h) +inline uint16 MAKE_PAIR16(uint8 l, uint8 h) { return uint16(l | (uint16(h) << 8)); } -uint32 MAKE_PAIR32(uint16 l, uint16 h) +inline uint32 MAKE_PAIR32(uint16 l, uint16 h) { return uint32(l | (uint32(h) << 16)); } -uint16 PAIR32_HIPART(uint32 x) +inline uint16 PAIR32_HIPART(uint32 x) { return (uint16)((x >> 16) & 0x0000FFFF); } -uint16 PAIR32_LOPART(uint32 x) +inline uint16 PAIR32_LOPART(uint32 x) { return (uint16)(x & 0x0000FFFF); } diff --git a/src/server/game/Entities/Object/ObjectGuid.cpp b/src/server/game/Entities/Object/ObjectGuid.cpp index dd25eab42de..b8e5e9290a8 100644 --- a/src/server/game/Entities/Object/ObjectGuid.cpp +++ b/src/server/game/Entities/Object/ObjectGuid.cpp @@ -17,13 +17,27 @@ */ #include "ObjectGuid.h" +#include "Errors.h" +#include "Hash.h" +#include "Log.h" #include "World.h" -#include "ObjectMgr.h" -#include #include +#include ObjectGuid const ObjectGuid::Empty = ObjectGuid(); +uint8& ObjectGuid::operator[](uint32 index) +{ + ASSERT(index < sizeof(uint64)); + return _data._bytes[index]; +} + +uint8 const& ObjectGuid::operator[](uint32 index) const +{ + ASSERT(index < sizeof(uint64)); + return _data._bytes[index]; +} + char const* ObjectGuid::GetTypeName(HighGuid high) { switch (high) @@ -90,7 +104,7 @@ ByteBuffer& operator<<(ByteBuffer& buf, PackedGuid const& guid) ByteBuffer& operator>>(ByteBuffer& buf, PackedGuidReader const& guid) { - buf.readPackGUID(*reinterpret_cast(guid.GuidPtr)); + buf.readPackGUID(reinterpret_cast(guid.Guid)); return buf; } diff --git a/src/server/game/Entities/Object/ObjectGuid.h b/src/server/game/Entities/Object/ObjectGuid.h index 0482fd5d0b2..97edc5e7e26 100644 --- a/src/server/game/Entities/Object/ObjectGuid.h +++ b/src/server/game/Entities/Object/ObjectGuid.h @@ -19,10 +19,15 @@ #ifndef ObjectGuid_h__ #define ObjectGuid_h__ -#include "Common.h" +#include "Define.h" #include "ByteBuffer.h" -#include +#include #include +#include +#include +#include +#include +#include enum TypeID { @@ -119,8 +124,8 @@ class PackedGuid; struct PackedGuidReader { - explicit PackedGuidReader(ObjectGuid& guid) : GuidPtr(&guid) { } - ObjectGuid* GuidPtr; + explicit PackedGuidReader(ObjectGuid& guid) : Guid(guid) { } + ObjectGuid& Guid; }; class TC_GAME_API ObjectGuid @@ -174,17 +179,8 @@ class TC_GAME_API ObjectGuid ObjectGuid::LowType GetMaxCounter() const { return GetMaxCounter(GetHigh()); } - uint8& operator[](uint32 index) - { - ASSERT(index < sizeof(uint64)); - return _data._bytes[index]; - } - - uint8 const& operator[](uint32 index) const - { - ASSERT(index < sizeof(uint64)); - return _data._bytes[index]; - } + uint8& operator[](uint32 index); + uint8 const& operator[](uint32 index) const; bool IsEmpty() const { return _data._guid == 0; } bool IsCreature() const { return GetHigh() == HighGuid::Unit; } @@ -235,9 +231,9 @@ class TC_GAME_API ObjectGuid TypeID GetTypeId() const { return GetTypeId(GetHigh()); } bool operator!() const { return IsEmpty(); } - bool operator== (ObjectGuid const& guid) const { return GetRawValue() == guid.GetRawValue(); } - bool operator!= (ObjectGuid const& guid) const { return GetRawValue() != guid.GetRawValue(); } - bool operator< (ObjectGuid const& guid) const { return GetRawValue() < guid.GetRawValue(); } + bool operator==(ObjectGuid const& guid) const { return GetRawValue() == guid.GetRawValue(); } + bool operator!=(ObjectGuid const& guid) const { return GetRawValue() != guid.GetRawValue(); } + bool operator<(ObjectGuid const& guid) const { return GetRawValue() < guid.GetRawValue(); } static char const* GetTypeName(HighGuid high); char const* GetTypeName() const { return !IsEmpty() ? GetTypeName(GetHigh()) : "None"; } @@ -294,7 +290,7 @@ typedef std::unordered_set GuidUnorderedSet; class TC_GAME_API PackedGuid { - friend TC_GAME_API 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); } @@ -304,7 +300,7 @@ class TC_GAME_API PackedGuid void Set(uint64 guid) { _packedGuid.wpos(0); _packedGuid.appendPackGUID(guid); } void Set(ObjectGuid guid) { _packedGuid.wpos(0); _packedGuid.appendPackGUID(guid.GetRawValue()); } - size_t size() const { return _packedGuid.size(); } + std::size_t size() const { return _packedGuid.size(); } private: ByteBuffer _packedGuid; @@ -355,7 +351,7 @@ namespace std public: size_t operator()(ObjectGuid const& key) const { - return hash()(key.GetRawValue()); + return std::hash()(key.GetRawValue()); } }; } diff --git a/src/server/game/Entities/Object/ObjectPosSelector.cpp b/src/server/game/Entities/Object/ObjectPosSelector.cpp index 22c3dc9916f..02814141c77 100644 --- a/src/server/game/Entities/Object/ObjectPosSelector.cpp +++ b/src/server/game/Entities/Object/ObjectPosSelector.cpp @@ -32,8 +32,8 @@ ObjectPosSelector::ObjectPosSelector(float x, float y, float size, float dist) m_smallStepOk[USED_POS_PLUS] = false; m_smallStepOk[USED_POS_MINUS] = false; - m_smallStepNextUsedPos[USED_POS_PLUS] = NULL; - m_smallStepNextUsedPos[USED_POS_MINUS] = NULL; + m_smallStepNextUsedPos[USED_POS_PLUS] = nullptr; + m_smallStepNextUsedPos[USED_POS_MINUS] = nullptr; } ObjectPosSelector::UsedPosList::value_type const* ObjectPosSelector::nextUsedPos(UsedPosType uptype) @@ -47,7 +47,7 @@ ObjectPosSelector::UsedPosList::value_type const* ObjectPosSelector::nextUsedPos if (!m_UsedPosLists[~uptype].empty()) return &*m_UsedPosLists[~uptype].rbegin(); else - return NULL; + return nullptr; } else return &*itr; diff --git a/src/server/game/Entities/Object/Position.cpp b/src/server/game/Entities/Object/Position.cpp index e9feaded99b..60b9d93a8e6 100644 --- a/src/server/game/Entities/Object/Position.cpp +++ b/src/server/game/Entities/Object/Position.cpp @@ -18,21 +18,12 @@ #include "Position.h" #include "ByteBuffer.h" #include "GridDefines.h" +#include "Random.h" #include -#include +#include -Position::Position(G3D::Vector3 const& vect) -{ - Relocate(vect.x, vect.y, vect.z, 0.f); -} - -Position::operator G3D::Vector3() const -{ - return { m_positionX, m_positionY, m_positionZ }; -} - -bool Position::operator==(Position const &a) +bool Position::operator==(Position const& a) { return (G3D::fuzzyEq(a.m_positionX, m_positionX) && G3D::fuzzyEq(a.m_positionY, m_positionY) && @@ -40,7 +31,7 @@ bool Position::operator==(Position const &a) G3D::fuzzyEq(a.m_orientation, m_orientation)); } -void Position::RelocateOffset(const Position & offset) +void Position::RelocateOffset(Position const& offset) { m_positionX = GetPositionX() + (offset.GetPositionX() * std::cos(GetOrientation()) + offset.GetPositionY() * std::sin(GetOrientation() + float(M_PI))); m_positionY = GetPositionY() + (offset.GetPositionY() * std::cos(GetOrientation()) + offset.GetPositionX() * std::sin(GetOrientation())); @@ -53,7 +44,27 @@ bool Position::IsPositionValid() const return Trinity::IsValidMapCoord(m_positionX, m_positionY, m_positionZ, m_orientation); } -void Position::GetPositionOffsetTo(const Position & endPos, Position & retOffset) const +float Position::GetExactDist2d(float x, float y) const +{ + return std::sqrt(GetExactDist2dSq(x, y)); +} + +float Position::GetExactDist2d(Position const* pos) const +{ + return std::sqrt(GetExactDist2dSq(pos)); +} + +float Position::GetExactDist(float x, float y, float z) const +{ + return std::sqrt(GetExactDistSq(x, y, z)); +} + +float Position::GetExactDist(Position const* pos) const +{ + return std::sqrt(GetExactDistSq(pos)); +} + +void Position::GetPositionOffsetTo(Position const& endPos, Position& retOffset) const { float dx = endPos.GetPositionX() - GetPositionX(); float dy = endPos.GetPositionY() - GetPositionY(); @@ -175,14 +186,28 @@ std::string Position::ToString() const return sstr.str(); } -ByteBuffer& operator<<(ByteBuffer& buf, Position::PositionXYStreamer const& streamer) +float Position::NormalizeOrientation(float o) +{ + // fmod only supports positive numbers. Thus we have + // to emulate negative numbers + if (o < 0) + { + float mod = o * -1; + mod = std::fmod(mod, 2.0f * static_cast(M_PI)); + mod = -mod + 2.0f * static_cast(M_PI); + return mod; + } + return std::fmod(o, 2.0f * static_cast(M_PI)); +} + +ByteBuffer& operator<<(ByteBuffer& buf, Position::ConstStreamer const& streamer) { buf << streamer.Pos->GetPositionX(); buf << streamer.Pos->GetPositionY(); return buf; } -ByteBuffer& operator>>(ByteBuffer& buf, Position::PositionXYStreamer const& streamer) +ByteBuffer& operator>>(ByteBuffer& buf, Position::Streamer const& streamer) { float x, y; buf >> x >> y; @@ -190,7 +215,7 @@ ByteBuffer& operator>>(ByteBuffer& buf, Position::PositionXYStreamer const& stre return buf; } -ByteBuffer& operator<<(ByteBuffer& buf, Position::PositionXYZStreamer const& streamer) +ByteBuffer& operator<<(ByteBuffer& buf, Position::ConstStreamer const& streamer) { buf << streamer.Pos->GetPositionX(); buf << streamer.Pos->GetPositionY(); @@ -198,7 +223,7 @@ ByteBuffer& operator<<(ByteBuffer& buf, Position::PositionXYZStreamer const& str return buf; } -ByteBuffer& operator>>(ByteBuffer& buf, Position::PositionXYZStreamer const& streamer) +ByteBuffer& operator>>(ByteBuffer& buf, Position::Streamer const& streamer) { float x, y, z; buf >> x >> y >> z; @@ -206,7 +231,7 @@ ByteBuffer& operator>>(ByteBuffer& buf, Position::PositionXYZStreamer const& str return buf; } -ByteBuffer& operator<<(ByteBuffer& buf, Position::PositionXYZOStreamer const& streamer) +ByteBuffer& operator<<(ByteBuffer& buf, Position::ConstStreamer const& streamer) { buf << streamer.Pos->GetPositionX(); buf << streamer.Pos->GetPositionY(); @@ -215,10 +240,16 @@ ByteBuffer& operator<<(ByteBuffer& buf, Position::PositionXYZOStreamer const& st return buf; } -ByteBuffer& operator>>(ByteBuffer& buf, Position::PositionXYZOStreamer const& streamer) +ByteBuffer& operator>>(ByteBuffer& buf, Position::Streamer const& streamer) { float x, y, z, o; buf >> x >> y >> z >> o; streamer.Pos->Relocate(x, y, z, o); return buf; } + +ByteBuffer& operator<<(ByteBuffer& buf, Position::ConstStreamer const& streamer) +{ + buf.appendPackXYZ(streamer.Pos->GetPositionX(), streamer.Pos->GetPositionY(), streamer.Pos->GetPositionZ()); + return buf; +} diff --git a/src/server/game/Entities/Object/Position.h b/src/server/game/Entities/Object/Position.h index eb1a2ea1bbe..1724a3cf917 100644 --- a/src/server/game/Entities/Object/Position.h +++ b/src/server/game/Entities/Object/Position.h @@ -18,12 +18,9 @@ #ifndef Trinity_game_Position_h__ #define Trinity_game_Position_h__ -#include "Common.h" - -namespace G3D -{ - class Vector3; -} +#include "Define.h" +#include +#include class ByteBuffer; @@ -34,25 +31,24 @@ struct TC_GAME_API Position Position(Position const& loc) { Relocate(loc); } - Position(G3D::Vector3 const& vect); + // streamer tags + struct XY; + struct XYZ; + struct XYZO; + struct PackedXYZ; - operator G3D::Vector3() const; - - struct PositionXYStreamer + template + struct ConstStreamer { - explicit PositionXYStreamer(Position& pos) : Pos(&pos) { } - Position* Pos; + explicit ConstStreamer(Position const& pos) : Pos(&pos) { } + Position const* Pos; }; - struct PositionXYZStreamer + template + struct Streamer { - explicit PositionXYZStreamer(Position& pos) : Pos(&pos) { } - Position* Pos; - }; - - struct PositionXYZOStreamer - { - explicit PositionXYZOStreamer(Position& pos) : Pos(&pos) { } + explicit Streamer(Position& pos) : Pos(&pos) { } + operator ConstStreamer() const { return ConstStreamer(*Pos); } Position* Pos; }; @@ -64,9 +60,9 @@ private: float m_orientation; public: - bool operator==(Position const &a); + bool operator==(Position const& a); - inline bool operator!=(Position const &a) + inline bool operator!=(Position const& a) { return !(operator==(a)); } @@ -86,7 +82,7 @@ public: m_positionX = x; m_positionY = y; m_positionZ = z; SetOrientation(orientation); } - void Relocate(Position const &pos) + void Relocate(Position const& pos) { m_positionX = pos.m_positionX; m_positionY = pos.m_positionY; m_positionZ = pos.m_positionZ; SetOrientation(pos.m_orientation); } @@ -96,7 +92,7 @@ public: m_positionX = pos->m_positionX; m_positionY = pos->m_positionY; m_positionZ = pos->m_positionZ; SetOrientation(pos->m_orientation); } - void RelocateOffset(Position const &offset); + void RelocateOffset(Position const& offset); void SetOrientation(float orientation) { @@ -125,21 +121,23 @@ public: Position GetPosition() const { return *this; } - Position::PositionXYStreamer PositionXYStream() { return PositionXYStreamer(*this); } - Position::PositionXYZStreamer PositionXYZStream() { return PositionXYZStreamer(*this); } - Position::PositionXYZOStreamer PositionXYZOStream() { return PositionXYZOStreamer(*this); } + Streamer PositionXYStream() { return Streamer(*this); } + ConstStreamer PositionXYStream() const { return ConstStreamer(*this); } + Streamer PositionXYZStream() { return Streamer(*this); } + ConstStreamer PositionXYZStream() const { return ConstStreamer(*this); } + Streamer PositionXYZOStream() { return Streamer(*this); } + ConstStreamer PositionXYZOStream() const { return ConstStreamer(*this); } + Streamer PositionPackedXYZStream() { return Streamer(*this); } + ConstStreamer PositionPackedXYZStream() const { return ConstStreamer(*this); } bool IsPositionValid() const; - float GetExactDist2dSq(const float x, const float y) const + float GetExactDist2dSq(float x, float y) const { float dx = m_positionX - x; float dy = m_positionY - y; return dx*dx + dy*dy; } - float GetExactDist2d(const float x, const float y) const - { - return std::sqrt(GetExactDist2dSq(x, y)); - } + float GetExactDist2d(float x, float y) const; float GetExactDist2dSq(Position const& pos) const { @@ -156,20 +154,14 @@ public: float dx = m_positionX - pos->m_positionX; float dy = m_positionY - pos->m_positionY; return dx*dx + dy*dy; } - float GetExactDist2d(Position const* pos) const - { - return std::sqrt(GetExactDist2dSq(pos)); - } + float GetExactDist2d(Position const* pos) const; float GetExactDistSq(float x, float y, float z) const { float dz = m_positionZ - z; return GetExactDist2dSq(x, y) + dz*dz; } - float GetExactDist(float x, float y, float z) const - { - return std::sqrt(GetExactDistSq(x, y, z)); - } + float GetExactDist(float x, float y, float z) const; float GetExactDistSq(Position const& pos) const { @@ -186,12 +178,9 @@ public: float dx = m_positionX - pos->m_positionX; float dy = m_positionY - pos->m_positionY; float dz = m_positionZ - pos->m_positionZ; return dx*dx + dy*dy + dz*dz; } - float GetExactDist(Position const* pos) const - { - return std::sqrt(GetExactDistSq(pos)); - } + float GetExactDist(Position const* pos) const; - void GetPositionOffsetTo(Position const & endPos, Position & retOffset) const; + void GetPositionOffsetTo(Position const& endPos, Position& retOffset) const; Position GetPositionWithOffset(Position const& offset) const; float GetAngle(Position const* pos) const; @@ -234,26 +223,72 @@ public: std::string ToString() const; // modulos a radian orientation to the range of 0..2PI - static float NormalizeOrientation(float o) - { - // fmod only supports positive numbers. Thus we have - // to emulate negative numbers - if (o < 0) - { - float mod = o *-1; - mod = std::fmod(mod, 2.0f * static_cast(M_PI)); - mod = -mod + 2.0f * static_cast(M_PI); - return mod; - } - return std::fmod(o, 2.0f * static_cast(M_PI)); - } + static float NormalizeOrientation(float o); }; -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); +#define MAPID_INVALID 0xFFFFFFFF + +class WorldLocation : public Position +{ + public: + explicit WorldLocation(uint32 _mapId = MAPID_INVALID, float _x = 0.f, float _y = 0.f, float _z = 0.f, float _o = 0.f) + : Position(_x, _y, _z, _o), m_mapId(_mapId) { } + + WorldLocation(uint32 mapId, Position const& position) + : Position(position), m_mapId(mapId) { } + + WorldLocation(WorldLocation const& loc) + : Position(loc), m_mapId(loc.GetMapId()) { } + + void WorldRelocate(WorldLocation const& loc) + { + m_mapId = loc.GetMapId(); + Relocate(loc); + } + + void WorldRelocate(uint32 _mapId = MAPID_INVALID, float _x = 0.f, float _y = 0.f, float _z = 0.f, float _o = 0.f) + { + m_mapId = _mapId; + Relocate(_x, _y, _z, _o); + } + + WorldLocation GetWorldLocation() const + { + return *this; + } + + uint32 GetMapId() const { return m_mapId; } + + uint32 m_mapId; +}; + + +TC_GAME_API ByteBuffer& operator<<(ByteBuffer& buf, Position::ConstStreamer const& streamer); +TC_GAME_API ByteBuffer& operator>>(ByteBuffer& buf, Position::Streamer const& streamer); +TC_GAME_API ByteBuffer& operator<<(ByteBuffer& buf, Position::ConstStreamer const& streamer); +TC_GAME_API ByteBuffer& operator>>(ByteBuffer& buf, Position::Streamer const& streamer); +TC_GAME_API ByteBuffer& operator<<(ByteBuffer& buf, Position::ConstStreamer const& streamer); +TC_GAME_API ByteBuffer& operator>>(ByteBuffer& buf, Position::Streamer const& streamer); +TC_GAME_API ByteBuffer& operator<<(ByteBuffer& buf, Position::ConstStreamer const& streamer); + +template +struct TaggedPosition +{ + TaggedPosition(float x = 0.0f, float y = 0.0f, float z = 0.0f, float o = 0.0f) : Pos(x, y, z, o) { } + TaggedPosition(Position const& pos) : Pos(pos) { } + + TaggedPosition& operator=(Position const& pos) + { + Pos.Relocate(pos); + return *this; + } + + operator Position() const { return Pos; } + + friend ByteBuffer& operator<<(ByteBuffer& buf, TaggedPosition const& tagged) { return buf << Position::ConstStreamer(tagged.Pos); } + friend ByteBuffer& operator>>(ByteBuffer& buf, TaggedPosition& tagged) { return buf >> Position::Streamer(tagged.Pos); } + + Position Pos; +}; #endif // Trinity_game_Position_h__ diff --git a/src/server/game/Entities/Object/Updates/UpdateData.cpp b/src/server/game/Entities/Object/Updates/UpdateData.cpp index c2da619aa64..a2feb07efaf 100644 --- a/src/server/game/Entities/Object/Updates/UpdateData.cpp +++ b/src/server/game/Entities/Object/Updates/UpdateData.cpp @@ -16,13 +16,11 @@ * with this program. If not, see . */ -#include "Common.h" -#include "ByteBuffer.h" -#include "WorldPacket.h" #include "UpdateData.h" +#include "Errors.h" #include "Opcodes.h" #include "World.h" -#include "zlib.h" +#include "WorldPacket.h" UpdateData::UpdateData(uint16 map) : m_map(map), m_blockCount(0) { } diff --git a/src/server/game/Entities/Object/Updates/UpdateData.h b/src/server/game/Entities/Object/Updates/UpdateData.h index bbc42b84146..dc436eb3ce2 100644 --- a/src/server/game/Entities/Object/Updates/UpdateData.h +++ b/src/server/game/Entities/Object/Updates/UpdateData.h @@ -19,6 +19,7 @@ #ifndef __UPDATEDATA_H #define __UPDATEDATA_H +#include "Define.h" #include "ByteBuffer.h" #include "ObjectGuid.h" #include diff --git a/src/server/game/Entities/Object/Updates/UpdateMask.h b/src/server/game/Entities/Object/Updates/UpdateMask.h index 50de0a8b5b7..59708ff2770 100644 --- a/src/server/game/Entities/Object/Updates/UpdateMask.h +++ b/src/server/game/Entities/Object/Updates/UpdateMask.h @@ -34,9 +34,9 @@ class UpdateMask CLIENT_UPDATE_MASK_BITS = sizeof(ClientUpdateMaskType) * 8, }; - UpdateMask() : _fieldCount(0), _blockCount(0), _bits(NULL) { } + UpdateMask() : _fieldCount(0), _blockCount(0), _bits(nullptr) { } - UpdateMask(UpdateMask const& right) : _bits(NULL) + UpdateMask(UpdateMask const& right) : _bits(nullptr) { SetCount(right.GetCount()); memcpy(_bits, right._bits, sizeof(uint8) * _blockCount * 32); diff --git a/src/server/game/Entities/Pet/Pet.cpp b/src/server/game/Entities/Pet/Pet.cpp index fbedb7b3479..3eea820e335 100644 --- a/src/server/game/Entities/Pet/Pet.cpp +++ b/src/server/game/Entities/Pet/Pet.cpp @@ -37,9 +37,9 @@ #define PET_XP_FACTOR 0.05f Pet::Pet(Player* owner, PetType type) : - Guardian(NULL, owner, true), m_usedTalentCount(0), m_removed(false), + Guardian(nullptr, owner, true), m_usedTalentCount(0), m_removed(false), m_petType(type), m_duration(0), m_auraRaidUpdateMask(0), m_loading(false), - m_declinedname(NULL) + m_declinedname(nullptr) { ASSERT(GetOwner()); @@ -236,7 +236,7 @@ bool Pet::LoadPetFromDB(Player* owner, uint32 petEntry, uint32 petnumber, bool c break; } - SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(NULL))); // cast can't be helped here + SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(nullptr))); // cast can't be helped here SetCreatorGUID(owner->GetGUID()); InitStatsForLevel(petlevel); @@ -318,7 +318,7 @@ bool Pet::LoadPetFromDB(Player* owner, uint32 petEntry, uint32 petnumber, bool c InitTalentForLevel(); // set original talents points before spell loading - uint32 timediff = uint32(time(NULL) - fields[13].GetUInt32()); + uint32 timediff = uint32(time(nullptr) - fields[13].GetUInt32()); _LoadAuras(timediff); // load action bar, if data broken will fill later by default spells. @@ -477,7 +477,7 @@ void Pet::SavePetToDB(PetSaveMode mode) }; ss << "', " - << time(NULL) << ',' + << time(nullptr) << ',' << GetUInt32Value(UNIT_CREATED_BY_SPELL) << ',' << uint32(getPetType()) << ')'; @@ -552,7 +552,7 @@ void Pet::Update(uint32 diff) { case CORPSE: { - if (getPetType() != HUNTER_PET || m_corpseRemoveTime <= time(NULL)) + if (getPetType() != HUNTER_PET || m_corpseRemoveTime <= time(nullptr)) { Remove(PET_SAVE_NOT_IN_SLOT); //hunters' pets never get removed because of death, NEVER! return; @@ -1172,7 +1172,7 @@ void Pet::_LoadAuras(uint32 timediff) int32 baseDamage[3]; Field* fields = result->Fetch(); ObjectGuid caster_guid(fields[0].GetUInt64()); - // NULL guid stored - pet is the caster of the spell - see Pet::_SaveAuras + // nullptr guid stored - pet is the caster of the spell - see Pet::_SaveAuras if (!caster_guid) caster_guid = GetGUID(); uint32 spellid = fields[1].GetUInt32(); @@ -1214,7 +1214,7 @@ void Pet::_LoadAuras(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()) { @@ -1432,7 +1432,7 @@ bool Pet::learnSpell(uint32 spell_id) { WorldPacket data(SMSG_PET_LEARNED_SPELL, 4); data << uint32(spell_id); - GetOwner()->GetSession()->SendPacket(&data); + GetOwner()->SendDirectMessage(&data); GetOwner()->PetSpellInitialize(); } return true; @@ -1442,7 +1442,7 @@ void Pet::InitLevelupSpellsForLevel() { uint8 level = getLevel(); - if (PetLevelupSpellSet const* levelupSpells = GetCreatureTemplate()->family ? sSpellMgr->GetPetLevelupSpellList(GetCreatureTemplate()->family) : NULL) + if (PetLevelupSpellSet const* levelupSpells = GetCreatureTemplate()->family ? sSpellMgr->GetPetLevelupSpellList(GetCreatureTemplate()->family) : nullptr) { // PetLevelupSpellSet ordered by levels, process in reversed order for (PetLevelupSpellSet::const_reverse_iterator itr = levelupSpells->rbegin(); itr != levelupSpells->rend(); ++itr) @@ -1485,7 +1485,7 @@ bool Pet::unlearnSpell(uint32 spell_id, bool learn_prev, bool clear_ab) { WorldPacket data(SMSG_PET_REMOVED_SPELL, 4); data << uint32(spell_id); - GetOwner()->GetSession()->SendPacket(&data); + GetOwner()->SendDirectMessage(&data); } return true; } @@ -1638,7 +1638,7 @@ bool Pet::resetTalents() return true; } -void Pet::resetTalentsForAllPetsOf(Player* owner, Pet* onlinePet /*= NULL*/) +void Pet::resetTalentsForAllPetsOf(Player* owner, Pet* onlinePet /*= nullptr*/) { // not need after this call if (owner->HasAtLoginFlag(AT_LOGIN_RESET_PET_TALENTS)) @@ -1885,7 +1885,7 @@ void Pet::CastPetAura(PetAura const* aura) if (auraId == 35696) // Demonic Knowledge { int32 basePoints = CalculatePct(aura->GetDamage(), GetStat(STAT_STAMINA) + GetStat(STAT_INTELLECT)); - CastCustomSpell(this, auraId, &basePoints, NULL, NULL, true); + CastCustomSpell(this, auraId, &basePoints, nullptr, nullptr, true); } else CastSpell(this, auraId, true); diff --git a/src/server/game/Entities/Player/CUFProfile.h b/src/server/game/Entities/Player/CUFProfile.h new file mode 100644 index 00000000000..18bbdb05568 --- /dev/null +++ b/src/server/game/Entities/Player/CUFProfile.h @@ -0,0 +1,118 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef CUFProfile_h__ +#define CUFProfile_h__ + +#include "Define.h" +#include +#include + +/// Maximum number of CompactUnitFrames profiles +#define MAX_CUF_PROFILES 5 + +/// Bit index used in the many bool options of CompactUnitFrames +enum CUFBoolOptions +{ + CUF_KEEP_GROUPS_TOGETHER, + CUF_DISPLAY_PETS, + CUF_DISPLAY_MAIN_TANK_AND_ASSIST, + CUF_DISPLAY_HEAL_PREDICTION, + CUF_DISPLAY_AGGRO_HIGHLIGHT, + CUF_DISPLAY_ONLY_DISPELLABLE_DEBUFFS, + CUF_DISPLAY_POWER_BAR, + CUF_DISPLAY_BORDER, + CUF_USE_CLASS_COLORS, + CUF_DISPLAY_NON_BOSS_DEBUFFS, + CUF_DISPLAY_HORIZONTAL_GROUPS, + CUF_LOCKED, + CUF_SHOWN, + CUF_AUTO_ACTIVATE_2_PLAYERS, + CUF_AUTO_ACTIVATE_3_PLAYERS, + CUF_AUTO_ACTIVATE_5_PLAYERS, + CUF_AUTO_ACTIVATE_10_PLAYERS, + CUF_AUTO_ACTIVATE_15_PLAYERS, + CUF_AUTO_ACTIVATE_25_PLAYERS, + CUF_AUTO_ACTIVATE_40_PLAYERS, + CUF_AUTO_ACTIVATE_SPEC_1, + CUF_AUTO_ACTIVATE_SPEC_2, + CUF_AUTO_ACTIVATE_PVP, + CUF_AUTO_ACTIVATE_PVE, + CUF_UNK_145, + CUF_UNK_156, + CUF_UNK_157, + + // The unks is _LOCKED and _SHOWN and _DYNAMIC, unknown order + + CUF_BOOL_OPTIONS_COUNT +}; + +/// Represents a CompactUnitFrame profile +struct CUFProfile +{ + CUFProfile() : ProfileName(), BoolOptions() // might want to change default value for options + { + FrameHeight = 0; + FrameWidth = 0; + SortBy = 0; + HealthText = 0; + TopPoint = 0; + BottomPoint = 0; + LeftPoint = 0; + TopOffset = 0; + BottomOffset = 0; + LeftOffset = 0; + } + + CUFProfile(std::string const& name, uint16 frameHeight, uint16 frameWidth, uint8 sortBy, uint8 healthText, uint32 boolOptions, + uint8 topPoint, uint8 bottomPoint, uint8 leftPoint, uint16 topOffset, uint16 bottomOffset, uint16 leftOffset) + : ProfileName(name), BoolOptions((int)boolOptions) + { + FrameHeight = frameHeight; + FrameWidth = frameWidth; + SortBy = sortBy; + HealthText = healthText; + TopPoint = topPoint; + BottomPoint = bottomPoint; + LeftPoint = leftPoint; + TopOffset = topOffset; + BottomOffset = bottomOffset; + LeftOffset = leftOffset; + } + + std::string ProfileName; + uint16 FrameHeight; + uint16 FrameWidth; + uint8 SortBy; + uint8 HealthText; + + // LeftAlign, TopAlight, BottomAlign + uint8 TopPoint; + uint8 BottomPoint; + uint8 LeftPoint; + + // LeftOffset, TopOffset and BottomOffset + uint16 TopOffset; + uint16 BottomOffset; + uint16 LeftOffset; + + std::bitset BoolOptions; + + // More fields can be added to BoolOptions without changing DB schema (up to 32, currently 27) +}; + +#endif // CUFProfile_h__ diff --git a/src/server/game/Entities/Player/CinematicMgr.cpp b/src/server/game/Entities/Player/CinematicMgr.cpp index 58b2dee9883..5df823cd22f 100644 --- a/src/server/game/Entities/Player/CinematicMgr.cpp +++ b/src/server/game/Entities/Player/CinematicMgr.cpp @@ -16,7 +16,9 @@ */ #include "CinematicMgr.h" -#include "Creature.h" +#include "Map.h" +#include "M2Stores.h" +#include "MotionMaster.h" #include "Player.h" #include "TemporarySummon.h" @@ -44,21 +46,20 @@ void CinematicMgr::BeginCinematic() if (m_activeCinematicCameraId == 0) return; - auto itr = sFlyByCameraStore.find(m_activeCinematicCameraId); - if (itr != sFlyByCameraStore.end()) + if (std::vector const* flyByCameras = GetFlyByCameras(m_activeCinematicCameraId)) { // Initialize diff, and set camera m_cinematicDiff = 0; - m_cinematicCamera = &itr->second; + m_cinematicCamera = flyByCameras; - FlyByCameraCollection::const_iterator camitr = m_cinematicCamera->begin(); + auto camitr = m_cinematicCamera->begin(); if (camitr != m_cinematicCamera->end()) { - Position pos(camitr->locations.x, camitr->locations.y, camitr->locations.z, camitr->locations.w); + Position const& pos = camitr->locations; if (!pos.IsPositionValid()) return; - player->GetMap()->LoadGrid(camitr->locations.x, camitr->locations.y); + player->GetMap()->LoadGrid(pos.GetPositionX(), pos.GetPositionY()); 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) { @@ -67,11 +68,7 @@ void CinematicMgr::BeginCinematic() } // Get cinematic length - FlyByCameraCollection::const_reverse_iterator camrevitr = m_cinematicCamera->rbegin(); - if (camrevitr != m_cinematicCamera->rend()) - m_cinematicLength = camrevitr->timeStamp; - else - m_cinematicLength = 0; + m_cinematicLength = flyByCameras->back().timeStamp; } } } @@ -109,11 +106,11 @@ void CinematicMgr::UpdateCinematicLocation(uint32 /*diff*/) { if (cam.timeStamp > m_cinematicDiff) { - nextPosition = Position(cam.locations.x, cam.locations.y, cam.locations.z, cam.locations.w); + nextPosition.Relocate(cam.locations); nextTimestamp = cam.timeStamp; break; } - lastPosition = Position(cam.locations.x, cam.locations.y, cam.locations.z, cam.locations.w); + lastPosition.Relocate(cam.locations); lastTimestamp = cam.timeStamp; } float angle = lastPosition.GetAngle(&nextPosition); @@ -128,7 +125,7 @@ void CinematicMgr::UpdateCinematicLocation(uint32 /*diff*/) workDiff += static_cast(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(); + auto endItr = m_cinematicCamera->rbegin(); if (endItr != m_cinematicCamera->rend() && workDiff > static_cast(endItr->timeStamp)) workDiff = endItr->timeStamp; @@ -141,11 +138,11 @@ void CinematicMgr::UpdateCinematicLocation(uint32 /*diff*/) { if (static_cast(cam.timeStamp) >= workDiff) { - nextPosition = Position(cam.locations.x, cam.locations.y, cam.locations.z, cam.locations.w); + nextPosition.Relocate(cam.locations); nextTimestamp = cam.timeStamp; break; } - lastPosition = Position(cam.locations.x, cam.locations.y, cam.locations.z, cam.locations.w); + lastPosition.Relocate(cam.locations); lastTimestamp = cam.timeStamp; } diff --git a/src/server/game/Entities/Player/CinematicMgr.h b/src/server/game/Entities/Player/CinematicMgr.h index e141a50e818..585f5f07019 100644 --- a/src/server/game/Entities/Player/CinematicMgr.h +++ b/src/server/game/Entities/Player/CinematicMgr.h @@ -20,12 +20,12 @@ #include "Define.h" #include "Object.h" -#include "M2Stores.h" #define CINEMATIC_LOOKAHEAD (2 * IN_MILLISECONDS) #define CINEMATIC_UPDATEDIFF 500 class Player; +struct FlyByCamera; class CinematicMgr { @@ -50,7 +50,7 @@ protected: uint32 m_lastCinematicCheck; uint32 m_activeCinematicCameraId; uint32 m_cinematicLength; - FlyByCameraCollection* m_cinematicCamera; + std::vector const* m_cinematicCamera; Position m_remoteSightPosition; TempSummon* m_CinematicObject; }; diff --git a/src/server/game/Entities/Player/EquipmentSet.h b/src/server/game/Entities/Player/EquipmentSet.h new file mode 100644 index 00000000000..5646bec2662 --- /dev/null +++ b/src/server/game/Entities/Player/EquipmentSet.h @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef EquipmentSet_h__ +#define EquipmentSet_h__ + +#include "Define.h" +#include "ObjectGuid.h" +#include +#include + +enum EquipmentSetUpdateState +{ + EQUIPMENT_SET_UNCHANGED = 0, + EQUIPMENT_SET_CHANGED = 1, + EQUIPMENT_SET_NEW = 2, + EQUIPMENT_SET_DELETED = 3 +}; + +#define EQUIPMENT_SET_SLOTS 19 + +struct EquipmentSetInfo +{ + /// Data sent in EquipmentSet related packets + struct EquipmentSetData + { + uint64 Guid = 0; ///< Set Identifier + uint32 SetID = 0; ///< Index + uint32 IgnoreMask = 0; ///< Mask of EquipmentSlot + std::string SetName; + std::string SetIcon; + std::array Pieces; + EquipmentSetUpdateState state; + } Data; + + /// Server-side data + EquipmentSetUpdateState State = EQUIPMENT_SET_NEW; +}; + +#define MAX_EQUIPMENT_SET_INDEX 10 // client limit + +typedef std::map EquipmentSetContainer; + +#endif // EquipmentSet_h__ diff --git a/src/server/game/Entities/Player/KillRewarder.cpp b/src/server/game/Entities/Player/KillRewarder.cpp index 0c9228d7012..c4b2395a7de 100644 --- a/src/server/game/Entities/Player/KillRewarder.cpp +++ b/src/server/game/Entities/Player/KillRewarder.cpp @@ -274,7 +274,7 @@ void KillRewarder::Reward() { if (victim->IsDungeonBoss()) if (InstanceScript* instance = _victim->GetInstanceScript()) - instance->UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, _victim->GetEntry(), _victim); + instance->UpdateEncounterStateForKilledCreature(_victim->GetEntry(), _victim); if (uint32 guildId = victim->GetMap()->GetOwnerGuildId()) if (Guild* guild = sGuildMgr->GetGuildById(guildId)) diff --git a/src/server/game/Entities/Player/Player.cpp b/src/server/game/Entities/Player/Player.cpp index abd947dcd98..56c9eaa3a1f 100644 --- a/src/server/game/Entities/Player/Player.cpp +++ b/src/server/game/Entities/Player/Player.cpp @@ -22,10 +22,11 @@ #include "Archaeology.h" #include "ArenaTeam.h" #include "ArenaTeamMgr.h" +#include "Bag.h" #include "Battlefield.h" #include "BattlefieldMgr.h" -#include "BattlefieldWG.h" #include "BattlefieldTB.h" +#include "BattlefieldWG.h" #include "Battleground.h" #include "BattlegroundMgr.h" #include "BattlegroundScore.h" @@ -35,6 +36,7 @@ #include "CharacterCache.h" #include "CharacterDatabaseCleaner.h" #include "Chat.h" +#include "CinematicMgr.h" #include "Common.h" #include "ConditionMgr.h" #include "CreatureAI.h" @@ -43,7 +45,9 @@ #include "DisableMgr.h" #include "Formulas.h" #include "GameEventMgr.h" +#include "GameObjectAI.h" #include "GameTime.h" +#include "GitRevision.h" #include "GossipDef.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" @@ -54,11 +58,16 @@ #include "InstanceSaveMgr.h" #include "InstanceScript.h" #include "KillRewarder.h" -#include "LFGMgr.h" #include "Language.h" +#include "LFGMgr.h" #include "Log.h" +#include "LootItemStorage.h" +#include "LootMgr.h" +#include "Mail.h" #include "MapInstanced.h" #include "MapManager.h" +#include "MotionMaster.h" +#include "MovementStructures.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Opcodes.h" @@ -67,18 +76,20 @@ #include "Pet.h" #include "PhasingHandler.h" #include "QueryCallback.h" +#include "QueryHolder.h" #include "QuestDef.h" +#include "Realm.h" #include "ReputationMgr.h" -#include "GitRevision.h" #include "SkillDiscovery.h" #include "SocialMgr.h" #include "Spell.h" #include "SpellAuraEffects.h" #include "SpellAuras.h" -#include "SpellMgr.h" #include "SpellHistory.h" -#include "Transport.h" +#include "SpellMgr.h" #include "TicketMgr.h" +#include "TradeData.h" +#include "Transport.h" #include "UpdateData.h" #include "UpdateFieldFlags.h" #include "UpdateMask.h" @@ -89,8 +100,7 @@ #include "World.h" #include "WorldPacket.h" #include "WorldSession.h" -#include "MovementStructures.h" -#include "GameObjectAI.h" +#include #define ZONE_UPDATE_INTERVAL (1*IN_MILLISECONDS) @@ -163,149 +173,7 @@ uint32 const MasterySpells[MAX_CLASSES] = uint64 const MAX_MONEY_AMOUNT = 9999999999ULL; -// == PlayerTaxi ================================================ - -PlayerTaxi::PlayerTaxi() -{ - memset(m_taximask, 0, sizeof(m_taximask)); -} - -void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint8 level) -{ - // class specific initial known nodes - switch (chrClass) - { - case CLASS_DEATH_KNIGHT: - { - for (uint8 i = 0; i < TaxiMaskSize; ++i) - m_taximask[i] |= sOldContinentsNodesMask[i]; - break; - } - } - - // race specific initial known nodes: capital and taxi hub masks - switch (race) - { - case RACE_HUMAN: SetTaximaskNode(2); break; // Human - case RACE_ORC: SetTaximaskNode(23); break; // Orc - case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf - case RACE_NIGHTELF: SetTaximaskNode(26); - SetTaximaskNode(27); break; // Night Elf - case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead - case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren - case RACE_GNOME: SetTaximaskNode(6); break; // Gnome - case RACE_TROLL: SetTaximaskNode(23); break; // Troll - case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf - case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei - } - - // new continent starting masks (It will be accessible only at new map) - switch (Player::TeamForRace(race)) - { - case ALLIANCE: SetTaximaskNode(100); break; - case HORDE: SetTaximaskNode(99); break; - } - // level dependent taxi hubs - if (level >= 68) - SetTaximaskNode(213); //Shattered Sun Staging Area -} - -void PlayerTaxi::LoadTaxiMask(std::string const &data) -{ - Tokenizer tokens(data, ' '); - - uint8 index = 0; - for (Tokenizer::const_iterator iter = tokens.begin(); index < TaxiMaskSize && iter != tokens.end(); ++iter, ++index) - { - // load and set bits only for existing taxi nodes - m_taximask[index] = sTaxiNodesMask[index] & atoul(*iter); - } -} - -void PlayerTaxi::AppendTaximaskTo(ByteBuffer& data, bool all) -{ - data << uint32(TaxiMaskSize); - if (all) - { - for (uint8 i = 0; i < TaxiMaskSize; ++i) - data << uint8(sTaxiNodesMask[i]); // all existing nodes - } - else - { - for (uint8 i = 0; i < TaxiMaskSize; ++i) - data << uint8(m_taximask[i]); // known nodes - } -} - -bool PlayerTaxi::LoadTaxiDestinationsFromString(const std::string& values, uint32 team) -{ - ClearTaxiDestinations(); - - Tokenizer Tokenizer(values, ' '); - - for (Tokenizer::const_iterator iter = Tokenizer.begin(); iter != Tokenizer.end(); ++iter) - { - uint32 node = atoul(*iter); - AddTaxiDestination(node); - } - - if (m_TaxiDestinations.empty()) - return true; - - // Check integrity - if (m_TaxiDestinations.size() < 2) - return false; - - for (size_t i = 1; i < m_TaxiDestinations.size(); ++i) - { - uint32 cost; - uint32 path; - sObjectMgr->GetTaxiPath(m_TaxiDestinations[i-1], m_TaxiDestinations[i], path, cost); - if (!path) - return false; - } - - // can't load taxi path without mount set (quest taxi path?) - if (!sObjectMgr->GetTaxiMountDisplayId(GetTaxiSource(), team, true)) - return false; - - return true; -} - -std::string PlayerTaxi::SaveTaxiDestinationsToString() -{ - if (m_TaxiDestinations.empty()) - return ""; - - std::ostringstream ss; - - for (size_t i=0; i < m_TaxiDestinations.size(); ++i) - ss << m_TaxiDestinations[i] << ' '; - - return ss.str(); -} - -uint32 PlayerTaxi::GetCurrentTaxiPath() const -{ - if (m_TaxiDestinations.size() < 2) - return 0; - - uint32 path; - uint32 cost; - - sObjectMgr->GetTaxiPath(m_TaxiDestinations[0], m_TaxiDestinations[1], path, cost); - - return path; -} - -std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi) -{ - for (uint8 i = 0; i < TaxiMaskSize; ++i) - ss << uint32(taxi.m_taximask[i]) << ' '; - return ss; -} - -Player::Player(WorldSession* session): Unit(true), _archaeology(this) +Player::Player(WorldSession* session): Unit(true) { m_speakTime = 0; m_speakCount = 0; @@ -347,7 +215,7 @@ Player::Player(WorldSession* session): Unit(true), _archaeology(this) m_nextSave = sWorld->getIntConfig(CONFIG_INTERVAL_SAVE); - _resurrectionData = NULL; + _resurrectionData = nullptr; memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT); @@ -535,18 +403,19 @@ Player::Player(WorldSession* session): Unit(true), _archaeology(this) _maxPersonalArenaRate = 0; memset(_voidStorageItems, 0, VOID_STORAGE_MAX_SLOT * sizeof(VoidStorageItem*)); - memset(_CUFProfiles, 0, MAX_CUF_PROFILES * sizeof(CUFProfile*)); _cinematicMgr = new CinematicMgr(this); m_achievementMgr = new AchievementMgr(this); m_reputationMgr = new ReputationMgr(this); + + _archaeology = new Archaeology(this); } Player::~Player() { // it must be unloaded already in PlayerLogout and accessed only for logged player - //m_social = NULL; + //m_social = nullptr; // Note: buy back item already deleted from DB when player was saved for (uint8 i = 0; i < PLAYER_SLOTS_COUNT; ++i) @@ -574,14 +443,11 @@ Player::~Player() delete m_achievementMgr; delete m_reputationMgr; delete _cinematicMgr; - + delete _archaeology; for (uint8 i = 0; i < VOID_STORAGE_MAX_SLOT; ++i) delete _voidStorageItems[i]; - for (uint8 i = 0; i < MAX_CUF_PROFILES; ++i) - delete _CUFProfiles[i]; - ClearResurrectRequestData(); sWorld->DecreasePlayerCount(); @@ -847,7 +713,7 @@ bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount) InventoryResult msg = CanStoreNewItem(INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount); if (msg == EQUIP_ERR_OK) { - StoreNewItem(sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id)); + StoreNewItem(sDest, titem_id, true, GenerateItemRandomPropertyId(titem_id)); return true; // stored } @@ -872,7 +738,7 @@ void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 Curre data << Regen; data << (uint8)0; data << (uint32)0; // spell id - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::StopMirrorTimer(MirrorTimerType Type) @@ -880,7 +746,7 @@ void Player::StopMirrorTimer(MirrorTimerType Type) m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER; WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4); data << (uint32)Type; - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } bool Player::IsImmuneToEnvironmentalDamage() const @@ -1004,14 +870,14 @@ void Player::HandleDrowning(uint32 time_diff) } else // If activated - do tick { - m_MirrorTimer[BREATH_TIMER]-=time_diff; + m_MirrorTimer[BREATH_TIMER] -= time_diff; // Timer limit - need deal damage if (m_MirrorTimer[BREATH_TIMER] < 0) { - m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILLISECONDS; + m_MirrorTimer[BREATH_TIMER] += 1 * IN_MILLISECONDS; // Calculate and deal damage /// @todo Check this formula - uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1); + uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel() - 1); EnvironmentalDamage(DAMAGE_DROWNING, damage); } else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need @@ -1022,7 +888,7 @@ void Player::HandleDrowning(uint32 time_diff) { int32 UnderWaterTime = getMaxTimer(BREATH_TIMER); // Need breath regen - m_MirrorTimer[BREATH_TIMER]+=10*time_diff; + m_MirrorTimer[BREATH_TIMER] += 10 * time_diff; if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !IsAlive()) StopMirrorTimer(BREATH_TIMER); else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER) @@ -1040,14 +906,14 @@ void Player::HandleDrowning(uint32 time_diff) } else { - m_MirrorTimer[FATIGUE_TIMER]-=time_diff; + m_MirrorTimer[FATIGUE_TIMER] -= time_diff; // Timer limit - need deal damage or teleport ghost to graveyard if (m_MirrorTimer[FATIGUE_TIMER] < 0) { - m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILLISECONDS; + m_MirrorTimer[FATIGUE_TIMER] += 1 * IN_MILLISECONDS; if (IsAlive()) // Calculate and deal damage { - uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1); + uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel() - 1); EnvironmentalDamage(DAMAGE_EXHAUSTED, damage); } else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard @@ -1060,7 +926,7 @@ void Player::HandleDrowning(uint32 time_diff) else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer { int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER); - m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff; + m_MirrorTimer[FATIGUE_TIMER] += 10 * time_diff; if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !IsAlive()) StopMirrorTimer(FATIGUE_TIMER); else if (m_MirrorTimerFlagsLast & UNDERWATER_INDARKWATER) @@ -1077,7 +943,7 @@ void Player::HandleDrowning(uint32 time_diff) m_MirrorTimer[FIRE_TIMER] -= time_diff; if (m_MirrorTimer[FIRE_TIMER] < 0) { - m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILLISECONDS; + m_MirrorTimer[FIRE_TIMER] += 1 * IN_MILLISECONDS; // Calculate and deal damage /// @todo Check this formula uint32 damage = urand(600, 700); @@ -1094,11 +960,11 @@ void Player::HandleDrowning(uint32 time_diff) m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER; // Recheck timers flag - m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS; - for (uint8 i = 0; i< MAX_TIMERS; ++i) + m_MirrorTimerFlags &= ~UNDERWATER_EXIST_TIMERS; + for (uint8 i = 0; i < MAX_TIMERS; ++i) if (m_MirrorTimer[i] != DISABLED_MIRROR_TIMER) { - m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS; + m_MirrorTimerFlags |= UNDERWATER_EXIST_TIMERS; break; } m_MirrorTimerFlagsLast = m_MirrorTimerFlags; @@ -1703,7 +1569,7 @@ bool Player::BuildEnumData(PreparedQueryResult result, ByteBuffer* dataBuffer, B continue; } - SpellItemEnchantmentEntry const* enchant = NULL; + SpellItemEnchantmentEntry const* enchant = nullptr; uint32 enchants = GetUInt32ValueFromArray(equipment, visualbase + 1); for (uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot) { @@ -1906,7 +1772,7 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati return false; // far teleport to another map - Map* oldmap = IsInWorld() ? GetMap() : NULL; + Map* oldmap = IsInWorld() ? GetMap() : nullptr; // check if we can enter before stopping combat / removing pet / totems / interrupting spells // Check enter rights before map getting to avoid creating instance copy for player @@ -1990,7 +1856,7 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati data.WriteBit(0); // has transport data << uint32(mapid); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } // remove from old map now @@ -2011,7 +1877,7 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati data << uint32(mapid); data << float(m_teleport_dest.GetPositionY()); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); SendSavedInstances(); } @@ -2025,7 +1891,7 @@ bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientati return true; } -bool Player::TeleportTo(WorldLocation const &loc, uint32 options /*= 0*/) +bool Player::TeleportTo(WorldLocation const& loc, uint32 options /*= 0*/) { return TeleportTo(loc.GetMapId(), loc.GetPositionX(), loc.GetPositionY(), loc.GetPositionZ(), loc.GetOrientation(), options); } @@ -2065,7 +1931,7 @@ void Player::ProcessDelayedOperations() SetPower(POWER_ECLIPSE, 0); if (uint32 aura = _resurrectionData->Aura) - CastSpell(this, aura, true, NULL, NULL, _resurrectionData->GUID); + CastSpell(this, aura, true, nullptr, nullptr, _resurrectionData->GUID); SpawnCorpseBones(); } @@ -2582,7 +2448,7 @@ void Player::SetInWater(bool apply) getHostileRefManager().updateThreatTables(); } -bool Player::IsInAreaTriggerRadius(const AreaTriggerEntry* trigger) const +bool Player::IsInAreaTriggerRadius(AreaTriggerEntry const* trigger) const { if (!trigger) return false; @@ -2737,7 +2603,7 @@ void Player::UninviteFromGroup() } } -void Player::RemoveFromGroup(Group* group, ObjectGuid guid, RemoveMethod method /* = GROUP_REMOVEMETHOD_DEFAULT*/, ObjectGuid kicker /* = ObjectGuid::Empty */, const char* reason /* = NULL */) +void Player::RemoveFromGroup(Group* group, ObjectGuid guid, RemoveMethod method /*= GROUP_REMOVEMETHOD_DEFAULT*/, ObjectGuid kicker /*= ObjectGuid::Empty*/, char const* reason /*= nullptr*/) { if (!group) return; @@ -2761,7 +2627,7 @@ void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 BonusXP, bool re } data << uint8(recruitAFriend ? 1 : 0); // does the GivenXP include a RaF bonus? - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::GiveXP(uint32 xp, Unit* victim, float group_rate) @@ -2846,7 +2712,7 @@ void Player::GiveLevel(uint8 level) for (uint8 i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4) data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i))); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr->GetXPForLevel(level)); @@ -3156,7 +3022,7 @@ void Player::SendInitialSpells() GetSpellHistory()->WritePacket(data); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::RemoveMail(uint32 id) @@ -3185,7 +3051,7 @@ void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResp data << uint32(item_guid); // item guid low? data << uint32(item_count); // item count? } - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendNewMail() const @@ -3193,7 +3059,7 @@ void Player::SendNewMail() const // deliver undelivered mail WorldPacket data(SMSG_RECEIVED_MAIL, 4); data << (uint32) 0; - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::UpdateNextMailTimeAndUnreads() @@ -3409,7 +3275,7 @@ bool Player::AddSpell(uint32 spellId, bool active, bool learning, bool dependent { WorldPacket data(SMSG_REMOVED_SPELL, 4); data << uint32(spellId); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } } @@ -3715,7 +3581,7 @@ void Player::LearnSpell(uint32 spell_id, bool dependent, uint32 fromSkill /*= 0* WorldPacket data(SMSG_LEARNED_SPELL, 8); data << uint32(spell_id); data << uint32(0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } // learn all disabled higher ranks and required spells (recursive) @@ -3867,7 +3733,7 @@ void Player::RemoveSpell(uint32 spell_id, bool disabled, bool learn_low_rank) // learnSpell(prev_id, false); } // if ranked non-stackable spell: need activate lesser rank and update dendence state - /// No need to check for spellInfo != NULL here because if cur_active is true, then that means that the spell was already in m_spells, and only valid spells can be pushed there. + /// No need to check for spellInfo != nullptr here because if cur_active is true, then that means that the spell was already in m_spells, and only valid spells can be pushed there. else if (cur_active && !spellInfo->IsStackableWithRanks() && spellInfo->IsRanked()) { // need manually update dependence state (learn spell ignore like attempts) @@ -3923,7 +3789,7 @@ void Player::RemoveSpell(uint32 spell_id, bool disabled, bool learn_low_rank) { WorldPacket data(SMSG_REMOVED_SPELL, 4); data << uint32(spell_id); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } } @@ -4029,7 +3895,7 @@ bool Player::ResetTalents(bool no_cost) // skip non-existing talent ranks if (talentInfo->RankID[rank] == 0) continue; - const SpellInfo* _spellEntry = sSpellMgr->GetSpellInfo(talentInfo->RankID[rank]); + SpellInfo const* _spellEntry = sSpellMgr->GetSpellInfo(talentInfo->RankID[rank]); if (!_spellEntry) continue; RemoveSpell(talentInfo->RankID[rank], true); @@ -4074,14 +3940,14 @@ bool Player::ResetTalents(bool no_cost) UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1); SetTalentResetCost(cost); - SetTalentResetTime(time(NULL)); + SetTalentResetTime(time(nullptr)); } /* when prev line will dropped use next line if (Pet* pet = GetPet()) { if (pet->getPetType() == HUNTER_PET && !pet->GetCreatureTemplate()->IsTameable(CanTameExoticPets())) - RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true); + RemovePet(nullptr, PET_SAVE_NOT_IN_SLOT, true); } */ @@ -4666,7 +4532,7 @@ void Player::BuildPlayerRepop() { WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size()); data << GetPackGUID(); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); if (getRace() == RACE_NIGHTELF) CastSpell(this, 20584, true); @@ -4726,7 +4592,7 @@ void Player::ResurrectPlayer(float restore_percent, bool applySickness) data << float(0); data << float(0); data << float(0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); // speed change, land walk @@ -5148,13 +5014,13 @@ void Player::RepopAtGraveyard() // Special handle for battleground maps if (Battleground* bg = GetBattleground()) - ClosestGrave = bg->GetClosestGraveYard(this); + ClosestGrave = bg->GetClosestGraveyard(this); else { if (Battlefield* bf = sBattlefieldMgr->GetBattlefieldToZoneId(GetZoneId())) - ClosestGrave = bf->GetClosestGraveYard(this); + ClosestGrave = bf->GetClosestGraveyard(this); else - ClosestGrave = sObjectMgr->GetClosestGraveYard(*this, GetTeam(), this); + ClosestGrave = sObjectMgr->GetClosestGraveyard(*this, GetTeam(), this); } // stop countdown until repop @@ -5173,7 +5039,7 @@ void Player::RepopAtGraveyard() data << ClosestGrave->x; data << ClosestGrave->y; data << ClosestGrave->z; - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } } else if (GetPositionZ() < zone->MaxDepth) @@ -5654,6 +5520,11 @@ void Player::SetRegularAttackTime() } } +void Player::StoreRaidMapDifficulty() +{ + m_raidMapDifficulty = GetMap()->GetDifficulty(); +} + //skill+step, checking for max value bool Player::UpdateSkill(uint32 skill_id, uint32 step) { @@ -5687,7 +5558,7 @@ bool Player::UpdateSkill(uint32 skill_id, uint32 step) UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, skill_id); if (skill_id == SKILL_ARCHAEOLOGY) - _archaeology.Update(); + _archaeology->Update(); return true; } @@ -5804,6 +5675,36 @@ bool Player::UpdateFishingSkill() return false; } +void Player::SurveyDigSite() +{ + _archaeology->UseSite(); +} + +void Player::NotifyRequestResearchHistory() +{ + _archaeology->SendResearchHistory(); +} + +bool Player::ArchProjectCompleteable(uint16 projectId) +{ + return _archaeology->ProjectCompleteable(projectId); +} + +bool Player::HasArchProject(uint16 projectId) +{ + return _archaeology->ProjectExists(projectId); +} + +void Player::CompleteArchProject(uint16 projectId) +{ + _archaeology->CompleteProject(projectId); +} + +void Player::SetArchData(ArchData const& data) +{ + _archaeology->SetArchData(data); +} + bool Player::UpdateSkillPro(uint16 skillId, int32 chance, uint32 step) { // levels sync. with spell requirement for skill levels to learn @@ -5986,7 +5887,7 @@ void Player::SetSkill(uint16 id, uint16 step, uint16 newVal, uint16 maxVal) // archaeology skill updated if (id == SKILL_ARCHAEOLOGY) - _archaeology.Update(); + _archaeology->Update(); UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL, id); UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL, id); @@ -6023,7 +5924,7 @@ void Player::SetSkill(uint16 id, uint16 step, uint16 newVal, uint16 maxVal) // archaeology skill unlearned if (id == SKILL_ARCHAEOLOGY) - _archaeology.UnLearn(); + _archaeology->UnLearn(); } } else if (newVal) //add @@ -6086,7 +5987,7 @@ void Player::SetSkill(uint16 id, uint16 step, uint16 newVal, uint16 maxVal) // archaeology skill learned if (id == SKILL_ARCHAEOLOGY) - _archaeology.Learn(); + _archaeology->Learn(); // Learn all spells for skill LearnSkillRewardedSpells(id, newVal); @@ -6254,7 +6155,7 @@ void Player::SendActionButtons(uint32 state) const data.resize(MAX_ACTION_BUTTONS * 4); // insert crap, client doesnt even parse this for state == 2 data << uint8(state); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); TC_LOG_DEBUG("network", "SMSG_ACTION_BUTTONS sent '%u' spec '%u' Sent", GetGUID().GetCounter(), GetActiveSpec()); } @@ -6385,7 +6286,7 @@ bool Player::UpdatePosition(float x, float y, float z, float orientation, bool t void Player::SendMessageToSetInRange(WorldPacket* data, float dist, bool self) { if (self) - GetSession()->SendPacket(data); + SendDirectMessage(data); Trinity::MessageDistDeliverer notifier(this, data, dist); Cell::VisitWorldObjects(this, notifier, dist); @@ -6394,7 +6295,7 @@ void Player::SendMessageToSetInRange(WorldPacket* data, float dist, bool self) void Player::SendMessageToSetInRange(WorldPacket* data, float dist, bool self, bool own_team_only) { if (self) - GetSession()->SendPacket(data); + SendDirectMessage(data); Trinity::MessageDistDeliverer notifier(this, data, dist, own_team_only); Cell::VisitWorldObjects(this, notifier, dist); @@ -6403,7 +6304,7 @@ void Player::SendMessageToSetInRange(WorldPacket* data, float dist, bool self, b void Player::SendMessageToSet(WorldPacket* data, Player const* skipped_rcvr) { if (skipped_rcvr != this) - GetSession()->SendPacket(data); + SendDirectMessage(data); // we use World::GetMaxVisibleDistance() because i cannot see why not use a distance // update: replaced by GetMap()->GetVisibilityDistance() @@ -6868,7 +6769,7 @@ bool Player::RewardHonor(Unit* victim, uint32 groupsize, int32 honor, bool pvpto data << uint64(victim_guid); data << uint32(victim_rank); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); // add honor points ModifyCurrency(CURRENCY_TYPE_HONOR_POINTS, int32(honor)); @@ -6934,7 +6835,7 @@ void Player::_LoadCurrency(PreparedQueryResult result) void Player::_SaveCurrency(SQLTransaction& trans) { - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; for (PlayerCurrenciesMap::iterator itr = _currencyStorage.begin(); itr != _currencyStorage.end(); ++itr) { CurrencyTypesEntry const* entry = sCurrencyTypesStore.LookupEntry(itr->first); @@ -7003,7 +6904,7 @@ void Player::SendNewCurrency(uint32 id) const packet.FlushBits(); packet.append(currencyData); - GetSession()->SendPacket(&packet); + SendDirectMessage(&packet); } void Player::SendCurrencies() const @@ -7048,7 +6949,7 @@ void Player::SendCurrencies() const packet.FlushBits(); packet.append(currencyData); packet.PutBits(count_pos, count, 23); - GetSession()->SendPacket(&packet); + SendDirectMessage(&packet); } void Player::SendPvpRewards() const @@ -7061,7 +6962,7 @@ void Player::SendPvpRewards() const packet << GetCurrencyOnWeek(CURRENCY_TYPE_CONQUEST_META_ARENA, true); packet << GetCurrencyWeekCap(CURRENCY_TYPE_CONQUEST_POINTS, true); - GetSession()->SendPacket(&packet); + SendDirectMessage(&packet); } uint32 Player::GetCurrency(uint32 id, bool usePrecision) const @@ -7177,7 +7078,7 @@ void Player::ModifyCurrency(uint32 id, int32 count, bool printLog/* = true*/, bo if (itr->second.state == PLAYERCURRENCY_NEW && HasSkill(SKILL_ARCHAEOLOGY) && currency->Category == CURRENCY_CATEGORY_ARCHAEOLOGY) - _archaeology.ActivateBranch(sArchaeologyMgr->Currency2BranchId(currency->ID)); + _archaeology->ActivateBranch(sArchaeologyMgr->Currency2BranchId(currency->ID)); WorldPacket packet(SMSG_UPDATE_CURRENCY, 12); @@ -7192,7 +7093,7 @@ void Player::ModifyCurrency(uint32 id, int32 count, bool printLog/* = true*/, bo if (weekCap) packet << uint32(newWeekCount / precision); - GetSession()->SendPacket(&packet); + SendDirectMessage(&packet); } } @@ -7302,7 +7203,7 @@ void Player::UpdateConquestCurrencyCap(uint32 currency) WorldPacket packet(SMSG_UPDATE_CURRENCY_WEEK_LIMIT, 8); packet << uint32(cap / precision); packet << uint32(currenciesToUpdate[i]); - GetSession()->SendPacket(&packet); + SendDirectMessage(&packet); } } @@ -7516,7 +7417,7 @@ void Player::CheckDuelDistance(time_t currTime) duel->outOfBound = currTime; WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } } else @@ -7526,7 +7427,7 @@ void Player::CheckDuelDistance(time_t currTime) duel->outOfBound = 0; WorldPacket data(SMSG_DUEL_INBOUNDS, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } else if (currTime >= (duel->outOfBound+10)) DuelComplete(DUEL_FLED); @@ -7556,10 +7457,10 @@ void Player::DuelComplete(DuelCompleteType type) WorldPacket data(SMSG_DUEL_COMPLETE, (1)); data << (uint8)((type != DUEL_INTERRUPTED) ? 1 : 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); if (duel->opponent->GetSession()) - duel->opponent->GetSession()->SendPacket(&data); + duel->opponent->SendDirectMessage(&data); if (type != DUEL_INTERRUPTED) { @@ -7696,7 +7597,7 @@ void Player::_ApplyItemBonuses(ItemTemplate const* proto, uint8 slot, bool apply if (slot >= INVENTORY_SLOT_BAG_END || !proto) return; - ScalingStatDistributionEntry const* ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : NULL; + ScalingStatDistributionEntry const* ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : nullptr; if (only_level_scale && !ssd) return; @@ -7705,7 +7606,7 @@ void Player::_ApplyItemBonuses(ItemTemplate const* proto, uint8 slot, bool apply if (ssd && ssd_level > ssd->MaxLevel) ssd_level = ssd->MaxLevel; - ScalingStatValuesEntry const* ssv = ssd ? sScalingStatValuesStore.LookupEntry(ssd_level) : NULL; + ScalingStatValuesEntry const* ssv = ssd ? sScalingStatValuesStore.LookupEntry(ssd_level) : nullptr; if (only_level_scale && !ssv) return; @@ -8156,8 +8057,8 @@ void Player::UpdateEquipSpellsAtFormChange() if (!spellInfo) continue; - ApplyEquipSpell(spellInfo, NULL, false, true); // remove spells that not fit to form - ApplyEquipSpell(spellInfo, NULL, true, true); // add spells that fit form but not active + ApplyEquipSpell(spellInfo, nullptr, false, true); // remove spells that not fit to form + ApplyEquipSpell(spellInfo, nullptr, true, true); // add spells that fit form but not active } } } @@ -8307,7 +8208,7 @@ void Player::CastItemCombatSpell(DamageInfo const& damageInfo, Item* item, ItemT } // Apply spell mods - ApplySpellMod(pEnchant->spellid[s], chance); + ApplySpellMod(pEnchant->spellid[s], SPELLMOD_CHANCE_OF_SUCCESS, chance); // Shiv has 100% chance to apply the poison if (FindCurrentSpellBySpellId(5938) && e_slot == TEMP_ENCHANTMENT_SLOT) @@ -8337,7 +8238,7 @@ void Player::CastItemUseSpell(Item* item, SpellCastTargets const& targets, uint8 if (!spellInfo) { TC_LOG_ERROR("entities.player", "Player::CastItemUseSpell: Item (Entry: %u) has wrong spell id %u, ignoring.", proto->ItemId, learn_spell_id); - SendEquipError(EQUIP_ERR_INTERNAL_BAG_ERROR, item, NULL); + SendEquipError(EQUIP_ERR_INTERNAL_BAG_ERROR, item, nullptr); return; } @@ -8705,9 +8606,12 @@ void Player::SendLoot(ObjectGuid guid, LootType loot_type) loot = &item->loot; + // Store container id + loot->containerID = item->GetGUID().GetCounter(); + // If item doesn't already have loot, attempt to load it. If that - // fails then this is first time opening, generate loot - if (!item->m_lootGenerated && !item->ItemContainerLoadLootFromDB()) + // fails then this is first time opening, generate loot + if (!item->m_lootGenerated && !sLootItemStorage->LoadStoredLoot(item, this)) { item->m_lootGenerated = true; loot->clear(); @@ -8730,7 +8634,7 @@ void Player::SendLoot(ObjectGuid guid, LootType loot_type) // Force save the loot and money items that were just rolled // Also saves the container item ID in Loot struct (not to DB) if (loot->gold > 0 || loot->unlootedCount > 0) - item->ItemContainerSaveLootToDB(); + sLootItemStorage->AddNewStoredLoot(loot, this); break; } @@ -8932,21 +8836,21 @@ void Player::SendLootError(ObjectGuid guid, LootError error) const void Player::SendNotifyLootMoneyRemoved() const { WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendNotifyLootItemRemoved(uint8 lootSlot) const { WorldPacket data(SMSG_LOOT_REMOVED, 1); data << uint8(lootSlot); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendNotifyCurrencyLootRemoved(uint8 lootSlot) { WorldPacket data(SMSG_CURRENCY_LOOT_REMOVED, 1); data << uint8(lootSlot); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendUpdateWorldState(uint32 Field, uint32 Value) const @@ -8955,7 +8859,7 @@ void Player::SendUpdateWorldState(uint32 Field, uint32 Value) const data << Field; data << Value; data << uint8(0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid) @@ -9587,7 +9491,7 @@ void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid) uint16 length = (data.wpos() - countPos) / 8; data.put(countPos, length); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); SendBGWeekendWorldStates(); SendBattlefieldWorldStates(); } @@ -9649,7 +9553,7 @@ void Player::SetBindPoint(ObjectGuid guid) const { WorldPacket data(SMSG_BINDER_CONFIRM, 8); data << uint64(guid); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendTalentWipeConfirm(ObjectGuid guid) const @@ -9658,7 +9562,7 @@ void Player::SendTalentWipeConfirm(ObjectGuid guid) const data << uint64(guid); uint32 cost = sWorld->getBoolConfig(CONFIG_NO_RESET_TALENT_COST) ? 0 : GetNextResetTalentsCost(); data << cost; - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::ResetPetTalents() @@ -10052,7 +9956,7 @@ Item* Player::GetItemByPos(uint8 bag, uint8 slot) const Item* Player::GetUseableItemByPos(uint8 bag, uint8 slot) const { if (!CanUseAttackType(GetAttackBySlot(slot))) - return NULL; + return nullptr; return GetItemByPos(bag, slot); } @@ -10095,19 +9999,19 @@ Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable /*= f Item* Player::GetShield(bool useable) const { - Item* item = NULL; + Item* item = nullptr; 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; } @@ -10371,7 +10275,7 @@ bool Player::HasGemWithLimitCategoryEquipped(uint32 limitCategory, uint32 count, return false; } -InventoryResult Player::CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count /*= NULL*/, uint32* itemLimitCategory /*= NULL*/) const +InventoryResult Player::CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count /*= nullptr*/, uint32* itemLimitCategory /*= nullptr*/) const { ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(entry); if (!pProto) @@ -10427,7 +10331,12 @@ InventoryResult Player::CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item return EQUIP_ERR_OK; } -InventoryResult Player::CanStoreNewItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 item, uint32 count, uint32* no_space_count /*= NULL*/) const +InventoryResult Player::CanTakeMoreSimilarItems(Item* pItem, uint32* itemLimitCategory /*= nullptr*/) const +{ + return CanTakeMoreSimilarItems(pItem->GetEntry(), pItem->GetCount(), pItem, nullptr, itemLimitCategory); +} + +InventoryResult Player::CanStoreNewItem(uint8 bag, uint8 slot, ItemPosCountVec& dest, uint32 item, uint32 count, uint32* no_space_count /*= nullptr*/) const { return CanStoreItem(bag, slot, dest, item, count, nullptr, false, no_space_count); } @@ -11712,7 +11621,7 @@ InventoryResult Player::CanRollForItemInLFG(ItemTemplate const* proto, WorldObje } // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case. -Item* Player::StoreNewItem(ItemPosCountVec const& dest, uint32 item, bool update, int32 randomPropertyId, AllowedLooterSet const& allowedLooters) +Item* Player::StoreNewItem(ItemPosCountVec const& dest, uint32 item, bool update, int32 randomPropertyId, GuidSet const& allowedLooters) { uint32 count = 0; for (ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr) @@ -11736,10 +11645,10 @@ Item* Player::StoreNewItem(ItemPosCountVec const& dest, uint32 item, bool update // save data std::ostringstream ss; - AllowedLooterSet::const_iterator itr = allowedLooters.begin(); + GuidSet::const_iterator itr = allowedLooters.begin(); ss << *itr; for (++itr; itr != allowedLooters.end(); ++itr) - ss << ' ' << *itr; + ss << ' ' << itr->GetCounter(); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ITEM_BOP_TRADE); stmt->setUInt32(0, pItem->GetGUID().GetCounter()); @@ -11803,7 +11712,7 @@ Item* Player::_StoreItem(uint16 pos, Item* pItem, uint32 count, bool clone, bool (pItem->GetTemplate()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos))) pItem->SetBinding(true); - Bag* pBag = (bag == INVENTORY_SLOT_BAG_0) ? NULL : GetBagByPos(bag); + Bag* pBag = (bag == INVENTORY_SLOT_BAG_0) ? nullptr : GetBagByPos(bag); if (!pBag) { m_items[slot] = pItem; @@ -11885,7 +11794,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) @@ -11927,7 +11836,7 @@ Item* Player::EquipItem(uint16 pos, Item* pItem, bool update) GetSpellHistory()->AddGlobalCooldown(spellProto, m_weaponChangeTimer); WorldPacket data; GetSpellHistory()->BuildCooldownPacket(data, SPELL_COOLDOWN_FLAG_INCLUDE_GCD, cooldownSpell, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } } } @@ -12158,7 +12067,7 @@ void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update) ItemRemovedQuestCheck(it->GetEntry(), it->GetCount()); RemoveItem(bag, slot, update); it->SetNotRefundable(this, false); - it->RemoveFromUpdateQueueOf(this); + RemoveItemFromUpdateQueueOf(it, this); if (it->IsInWorld()) { it->RemoveFromWorld(); @@ -12227,6 +12136,7 @@ void Player::DestroyItem(uint8 bag, uint8 slot, bool update) ItemRemovedQuestCheck(pItem->GetEntry(), pItem->GetCount()); sScriptMgr->OnItemRemove(this, pItem); + ItemTemplate const* pProto = pItem->GetTemplate(); if (bag == INVENTORY_SLOT_BAG_0) { SetGuidValue(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), ObjectGuid::Empty); @@ -12234,8 +12144,6 @@ void Player::DestroyItem(uint8 bag, uint8 slot, bool update) // equipment and equipped bags can have applied bonuses if (slot < INVENTORY_SLOT_BAG_END) { - ItemTemplate const* pProto = pItem->GetTemplate(); - // item set bonuses applied only at equip and removed at unequip, and still active for broken items if (pProto->ItemSet) RemoveItemsSetItem(this, pProto); @@ -12272,9 +12180,8 @@ 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_FLAG_HAS_LOOT) - pItem->ItemContainerDeleteLootMoneyAndLootItemsFromDB(); + if (pProto->Flags & ITEM_FLAG_HAS_LOOT) + sLootItemStorage->RemoveStoredLootForContainer(pItem->GetGUID().GetCounter()); if (IsInWorld() && update) { @@ -12751,7 +12658,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; } @@ -12766,7 +12673,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; } @@ -12780,7 +12687,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; } @@ -12988,7 +12895,7 @@ void Player::SwapItem(uint16 src, uint16 dst) { if (Item* bagItem = bag->GetItemByPos(i)) { - if (bagItem->m_lootGenerated) + if (bagItem->GetGUID() == GetLootGUID()) { m_session->DoLootRelease(GetLootGUID()); released = true; // so we don't need to look at dstBag @@ -13005,7 +12912,7 @@ void Player::SwapItem(uint16 src, uint16 dst) { if (Item* bagItem = bag->GetItemByPos(i)) { - if (bagItem->m_lootGenerated) + if (bagItem->GetGUID() == GetLootGUID()) { m_session->DoLootRelease(GetLootGUID()); released = true; // not realy needed here @@ -13094,7 +13001,13 @@ void Player::RemoveItemFromBuyBackSlot(uint32 slot, bool del) { pItem->RemoveFromWorld(); if (del) + { + if (ItemTemplate const* itemTemplate = pItem->GetTemplate()) + if (itemTemplate->Flags & ITEM_FLAG_HAS_LOOT) + sLootItemStorage->RemoveStoredLootForContainer(pItem->GetGUID().GetCounter()); + pItem->SetState(ITEM_REMOVED, this); + } } m_items[slot] = nullptr; @@ -13149,7 +13062,7 @@ void Player::SendEquipError(InventoryResult msg, Item* pItem, Item* pItem2, uint break; } } - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendBuyError(BuyResult msg, Creature* creature, uint32 item, uint32 /*param*/) const @@ -13158,7 +13071,7 @@ void Player::SendBuyError(BuyResult msg, Creature* creature, uint32 item, uint32 data << uint64(creature ? creature->GetGUID() : ObjectGuid::Empty); data << uint32(item); data << uint8(msg); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendSellError(SellResult msg, Creature* creature, ObjectGuid guid) const @@ -13167,7 +13080,7 @@ void Player::SendSellError(SellResult msg, Creature* creature, ObjectGuid guid) data << uint64(creature ? creature->GetGUID() : ObjectGuid::Empty); data << uint64(guid); data << uint8(msg); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } bool Player::IsUseEquipedWeapon(bool mainhand) const @@ -14137,7 +14050,7 @@ void Player::SendNewItem(Item* item, uint32 count, bool received, bool created, if (broadcast && GetGroup()) GetGroup()->BroadcastPacket(&data, true); else - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } /*********************************************************/ @@ -14652,7 +14565,7 @@ void Player::SendPreparedQuest(ObjectGuid guid) title = gossiptext->Options[0].Text_0; LocaleConstant localeConstant = GetSession()->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) if (NpcTextLocale const* nl = sObjectMgr->GetNpcTextLocale(textid)) ObjectMgr::GetLocaleString(nl->Text_0[0], localeConstant, title); } @@ -14661,7 +14574,7 @@ void Player::SendPreparedQuest(ObjectGuid guid) title = gossiptext->Options[0].Text_1; LocaleConstant localeConstant = GetSession()->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) if (NpcTextLocale const* nl = sObjectMgr->GetNpcTextLocale(textid)) ObjectMgr::GetLocaleString(nl->Text_1[0], localeConstant, title); } @@ -14693,7 +14606,7 @@ Quest const* Player::GetNextQuest(ObjectGuid guid, Quest const* quest) const if (Creature* creature = ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid)) objectQR = sObjectMgr->GetCreatureQuestRelationBounds(creature->GetEntry()); else - return NULL; + return nullptr; break; } case HighGuid::GameObject: @@ -14705,11 +14618,11 @@ Quest const* Player::GetNextQuest(ObjectGuid guid, Quest const* quest) const if (GameObject* gameObject = _map->GetGameObject(guid)) objectQR = sObjectMgr->GetGOQuestRelationBounds(gameObject->GetEntry()); else - return NULL; + return nullptr; break; } default: - return NULL; + return nullptr; } // for unit and go state @@ -15165,7 +15078,7 @@ void Player::RewardQuest(Quest const* quest, uint32 reward, Object* questGiver, ItemPosCountVec dest; if (CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, quest->RewardItemIdCount[i]) == EQUIP_ERR_OK) { - Item* item = StoreNewItem(dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId)); + Item* item = StoreNewItem(dest, itemId, true, GenerateItemRandomPropertyId(itemId)); SendNewItem(item, quest->RewardItemIdCount[i], true, false, false, false); } else if (quest->IsDFQuest()) @@ -15188,7 +15101,7 @@ void Player::RewardQuest(Quest const* quest, uint32 reward, Object* questGiver, ItemPosCountVec dest; if (CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, itemId, quest->RewardChoiceItemCount[reward]) == EQUIP_ERR_OK) { - Item* item = StoreNewItem(dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId)); + Item* item = StoreNewItem(dest, itemId, true, GenerateItemRandomPropertyId(itemId)); SendNewItem(item, quest->RewardChoiceItemCount[reward], true, false, false, false); } } @@ -15464,7 +15377,7 @@ bool Player::SatisfyQuestLog(bool msg) const if (msg) { WorldPacket data(SMSG_QUESTLOG_FULL, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } return false; } @@ -16757,7 +16670,7 @@ void Player::SendQuestComplete(Quest const* quest) const { WorldPacket data(SMSG_QUESTUPDATE_COMPLETE, 4); data << uint32(quest->GetQuestId()); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); TC_LOG_DEBUG("network", "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest->GetQuestId()); } } @@ -16794,7 +16707,7 @@ void Player::SendQuestReward(Quest const* quest, uint32 XP) const data.WriteBit(1); data.FlushBits(); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendQuestFailed(uint32 questId, InventoryResult reason) const @@ -16804,7 +16717,7 @@ void Player::SendQuestFailed(uint32 questId, InventoryResult reason) const WorldPacket data(SMSG_QUESTGIVER_QUEST_FAILED, 4 + 4); data << uint32(questId); data << uint32(reason); // failed reason (valid reasons: 4, 16, 50, 17, 74, other values show default message) - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } } @@ -16814,7 +16727,7 @@ void Player::SendQuestTimerFailed(uint32 quest_id) const { WorldPacket data(SMSG_QUESTUPDATE_FAILEDTIMER, 4); data << uint32(quest_id); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); TC_LOG_DEBUG("network", "WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER"); } } @@ -16823,26 +16736,26 @@ void Player::SendCanTakeQuestResponse(QuestFailedReason msg) const { WorldPacket data(SMSG_QUESTGIVER_QUEST_INVALID, 4); data << uint32(msg); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); TC_LOG_DEBUG("network", "WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID"); } -void Player::SendQuestConfirmAccept(const Quest* quest, Player* pReceiver) const +void Player::SendQuestConfirmAccept(Quest const* quest, Player* pReceiver) const { if (pReceiver) { std::string strTitle = quest->GetTitle(); LocaleConstant localeConstant = pReceiver->GetSession()->GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) - if (const QuestLocale* pLocale = sObjectMgr->GetQuestLocale(quest->GetQuestId())) + if (localeConstant != LOCALE_enUS) + if (QuestLocale const* pLocale = sObjectMgr->GetQuestLocale(quest->GetQuestId())) ObjectMgr::GetLocaleString(pLocale->Title, localeConstant, strTitle); WorldPacket data(SMSG_QUEST_CONFIRM_ACCEPT, (4 + strTitle.size() + 8)); data << uint32(quest->GetQuestId()); data << strTitle; data << uint64(GetGUID()); - pReceiver->GetSession()->SendPacket(&data); + pReceiver->SendDirectMessage(&data); TC_LOG_DEBUG("network", "WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT"); } @@ -16855,7 +16768,7 @@ void Player::SendPushToPartyResponse(Player* player, uint8 msg) const WorldPacket data(MSG_QUEST_PUSH_RESULT, 8 + 1); data << uint64(player->GetGUID()); data << uint8(msg); // valid values: 0-8 - GetSession()->SendPacket(&data); + SendDirectMessage(&data); TC_LOG_DEBUG("network", "WORLD: Sent MSG_QUEST_PUSH_RESULT"); } } @@ -16876,7 +16789,7 @@ void Player::SendQuestUpdateAddCreatureOrGo(Quest const* quest, ObjectGuid guid, data << uint32(old_count + add_count); data << uint32(quest->RequiredNpcOrGoCount[ creatureOrGO_idx ]); data << uint64(guid); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); uint16 log_slot = FindQuestSlot(quest->GetQuestId()); if (log_slot < MAX_QUEST_LOG_SIZE) @@ -16891,7 +16804,7 @@ void Player::SendQuestUpdateAddPlayer(Quest const* quest, uint16 old_count, uint data << uint32(quest->GetQuestId()); data << uint32(old_count + add_count); data << uint32(quest->GetPlayersSlain()); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); uint16 log_slot = FindQuestSlot(quest->GetQuestId()); if (log_slot < MAX_QUEST_LOG_SIZE) @@ -16939,7 +16852,7 @@ void Player::SendQuestGiverStatusMultiple() } data.put(0, count); // write real count - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } bool Player::HasPvPForcingQuest() const @@ -17029,30 +16942,28 @@ void Player::_LoadEquipmentSets(PreparedQueryResult result) if (!result) return; - uint32 count = 0; do { Field* fields = result->Fetch(); - EquipmentSet eqSet; + EquipmentSetInfo eqSet; - eqSet.Guid = fields[0].GetUInt64(); - uint8 index = fields[1].GetUInt8(); - eqSet.Name = fields[2].GetString(); - eqSet.IconName = fields[3].GetString(); - eqSet.IgnoreMask = fields[4].GetUInt32(); - eqSet.state = EQUIPMENT_SET_UNCHANGED; + eqSet.Data.Guid = fields[0].GetUInt64(); + eqSet.Data.SetID = fields[1].GetUInt8(); + eqSet.Data.SetName = fields[2].GetString(); + eqSet.Data.SetIcon = fields[3].GetString(); + eqSet.Data.IgnoreMask = fields[4].GetUInt32(); + eqSet.State = EQUIPMENT_SET_UNCHANGED; for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i) - eqSet.Items[i] = fields[5+i].GetUInt32(); + if (ObjectGuid::LowType guid = fields[5 + i].GetUInt32()) + eqSet.Data.Pieces[i] = ObjectGuid::Create(guid); - m_EquipmentSets[index] = eqSet; + // client limit + if (eqSet.Data.SetID >= MAX_EQUIPMENT_SET_INDEX) + continue; - ++count; - - if (count >= MAX_EQUIPMENT_SET_INDEX) // client limit - break; - } - while (result->NextRow()); + _equipmentSets[eqSet.Data.Guid] = eqSet; + } while (result->NextRow()); } void Player::_LoadBGData(PreparedQueryResult result) @@ -17137,7 +17048,7 @@ bool Player::IsLoading() const return GetSession()->PlayerLoading(); } -bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder) +bool Player::LoadFromDB(ObjectGuid guid, SQLQueryHolder* holder) { //// 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, " @@ -17914,19 +17825,19 @@ void Player::_LoadCUFProfiles(PreparedQueryResult result) // SELECT id, name, frameHeight, frameWidth, sortBy, healthText, boolOptions, unk146, unk147, unk148, unk150, unk152, unk154 FROM character_cuf_profiles WHERE guid = ? Field* fields = result->Fetch(); - uint8 id = fields[0].GetUInt8(); - std::string name = fields[1].GetString(); - uint16 frameHeight = fields[2].GetUInt16(); - uint16 frameWidth = fields[3].GetUInt16(); - uint8 sortBy = fields[4].GetUInt8(); - uint8 healthText = fields[5].GetUInt8(); - uint32 boolOptions = fields[6].GetUInt32(); - uint8 unk146 = fields[7].GetUInt8(); - uint8 unk147 = fields[8].GetUInt8(); - uint8 unk148 = fields[9].GetUInt8(); - uint16 unk150 = fields[10].GetUInt16(); - uint16 unk152 = fields[11].GetUInt16(); - uint16 unk154 = fields[12].GetUInt16(); + uint8 id = fields[0].GetUInt8(); + std::string name = fields[1].GetString(); + uint16 frameHeight = fields[2].GetUInt16(); + uint16 frameWidth = fields[3].GetUInt16(); + uint8 sortBy = fields[4].GetUInt8(); + uint8 healthText = fields[5].GetUInt8(); + uint32 boolOptions = fields[6].GetUInt32(); + uint8 topPoint = fields[7].GetUInt8(); + uint8 bottomPoint = fields[8].GetUInt8(); + uint8 leftPoint = fields[9].GetUInt8(); + uint16 topOffset = fields[10].GetUInt16(); + uint16 bottomOffset = fields[11].GetUInt16(); + uint16 leftOffset = fields[12].GetUInt16(); if (id > MAX_CUF_PROFILES) { @@ -17934,12 +17845,12 @@ void Player::_LoadCUFProfiles(PreparedQueryResult result) continue; } - _CUFProfiles[id] = new CUFProfile(name, frameHeight, frameWidth, sortBy, healthText, boolOptions, unk146, unk147, unk148, unk150, unk152, unk154); + _CUFProfiles[id] = Trinity::make_unique(name, frameHeight, frameWidth, sortBy, healthText, boolOptions, topPoint, bottomPoint, leftPoint, topOffset, bottomOffset, leftOffset); } while (result->NextRow()); } -bool Player::isAllowedToLoot(const Creature* creature) +bool Player::isAllowedToLoot(Creature const* creature) { if (!creature->isDead() || !creature->IsDamageEnoughForLootingAndReward()) return false; @@ -17947,7 +17858,7 @@ bool Player::isAllowedToLoot(const Creature* creature) if (HasPendingBind()) return false; - const Loot* loot = &creature->loot; + Loot const* 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 @@ -18078,7 +17989,7 @@ void Player::_LoadAuras(PreparedQueryResult result, uint32 timediff) else remaincharges = 0; - if (Aura* aura = Aura::TryCreate(spellInfo, effmask, this, nullptr, &baseDamage[0], NULL, caster_guid)) + if (Aura* aura = Aura::TryCreate(spellInfo, effmask, this, nullptr, &baseDamage[0], nullptr, caster_guid)) { if (!aura->CanBeSaved()) { @@ -18392,9 +18303,9 @@ Item* Player::_LoadItem(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, F { std::string strGUID = (*result)[0].GetString(); Tokenizer GUIDlist(strGUID, ' '); - AllowedLooterSet looters; + GuidSet looters; for (Tokenizer::const_iterator itr = GUIDlist.begin(); itr != GUIDlist.end(); ++itr) - looters.insert(atol(*itr)); + looters.insert(ObjectGuid::Create(uint32(atoul(*itr)))); if (looters.size() > 1 && item->GetTemplate()->GetMaxStackSize() == 1 && item->IsSoulBound()) { @@ -18970,7 +18881,7 @@ InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty InstanceSave* Player::GetInstanceSave(uint32 mapid, bool raid) { InstancePlayerBind* pBind = GetBoundInstance(mapid, GetDifficulty(raid)); - InstanceSave* pSave = pBind ? pBind->save : NULL; + InstanceSave* pSave = pBind ? pBind->save : nullptr; if (!pBind || !pBind->perm) if (Group* group = GetGroup()) if (InstanceGroupBind* groupBind = group->GetBoundInstance(GetDifficulty(raid), mapid)) @@ -19076,12 +18987,12 @@ InstancePlayerBind* Player::BindToInstance(InstanceSave* save, bool permanent, B void Player::BindToInstance() { InstanceSave* mapSave = sInstanceSaveMgr->GetInstanceSave(_pendingBindId); - if (!mapSave) //it seems sometimes mapSave is NULL, but I did not check why + if (!mapSave) //it seems sometimes mapSave is nullptr, but I did not check why return; WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4); data << uint32(0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); if (!IsGameMaster()) { BindToInstance(mapSave, true, EXTEND_STATE_KEEP); @@ -19137,7 +19048,7 @@ void Player::SendRaidInfo() } data.put(p_counter, counter); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } /* @@ -19163,7 +19074,7 @@ void Player::SendSavedInstances() //Send opcode SMSG_UPDATE_INSTANCE_OWNERSHIP. true or false means, whether you have current raid/heroic instances data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP, 4); data << uint32(hasBeenSaved); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); if (!hasBeenSaved) return; @@ -19176,7 +19087,7 @@ void Player::SendSavedInstances() { data.Initialize(SMSG_UPDATE_LAST_INSTANCE, 4); data << uint32(itr->second.save->GetMapId()); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } } } @@ -19439,6 +19350,8 @@ void Player::SaveToDB(bool create /*=false*/) stmt->setUInt32(0, GetGUID().GetCounter()); trans->Append(stmt); + auto finiteAlways = [](float f) { return std::isfinite(f) ? f : 0.0f; }; + if (create) { //! Insert query @@ -19877,9 +19790,18 @@ void Player::_SaveInventory(SQLTransaction& trans) for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i) { Item* item = m_items[i]; - if (!item || item->GetState() == ITEM_NEW) + if (!item) continue; + if (item->GetState() == ITEM_NEW) + { + if (ItemTemplate const* itemTemplate = item->GetTemplate()) + if (itemTemplate->Flags & ITEM_FLAG_HAS_LOOT) + sLootItemStorage->RemoveStoredLootForContainer(item->GetGUID().GetCounter()); + + continue; + } + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_INVENTORY_BY_ITEM); stmt->setUInt32(0, item->GetGUID().GetCounter()); trans->Append(stmt); @@ -19888,6 +19810,10 @@ void Player::_SaveInventory(SQLTransaction& trans) stmt->setUInt32(0, item->GetGUID().GetCounter()); trans->Append(stmt); m_items[i]->FSetState(ITEM_NEW); + + if (ItemTemplate const* itemTemplate = item->GetTemplate()) + if (itemTemplate->Flags & ITEM_FLAG_HAS_LOOT) + sLootItemStorage->RemoveStoredLootForContainer(item->GetGUID().GetCounter()); } // Updated played time for refundable items. We don't do this in Player::Update because there's simply no need for it, @@ -19999,7 +19925,7 @@ void Player::_SaveInventory(SQLTransaction& trans) void Player::_SaveVoidStorage(SQLTransaction& trans) { - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; uint32 lowGuid = GetGUID().GetCounter(); for (uint8 i = 0; i < VOID_STORAGE_MAX_SLOT; ++i) @@ -20031,7 +19957,7 @@ void Player::_SaveVoidStorage(SQLTransaction& trans) void Player::_SaveCUFProfiles(SQLTransaction& trans) { - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; uint32 lowGuid = GetGUID().GetCounter(); for (uint8 i = 0; i < MAX_CUF_PROFILES; ++i) @@ -20055,12 +19981,12 @@ void Player::_SaveCUFProfiles(SQLTransaction& trans) stmt->setUInt8(5, _CUFProfiles[i]->SortBy); stmt->setUInt8(6, _CUFProfiles[i]->HealthText); stmt->setUInt32(7, _CUFProfiles[i]->BoolOptions.to_ulong()); // 27 of 32 fields used, fits in an int - stmt->setUInt8(8, _CUFProfiles[i]->Unk146); - stmt->setUInt8(9, _CUFProfiles[i]->Unk147); - stmt->setUInt8(10, _CUFProfiles[i]->Unk148); - stmt->setUInt16(11, _CUFProfiles[i]->Unk150); - stmt->setUInt16(12, _CUFProfiles[i]->Unk152); - stmt->setUInt16(13, _CUFProfiles[i]->Unk154); + stmt->setUInt8(8, _CUFProfiles[i]->TopPoint); + stmt->setUInt8(9, _CUFProfiles[i]->BottomPoint); + stmt->setUInt8(10, _CUFProfiles[i]->LeftPoint); + stmt->setUInt16(11, _CUFProfiles[i]->TopOffset); + stmt->setUInt16(12, _CUFProfiles[i]->BottomOffset); + stmt->setUInt16(13, _CUFProfiles[i]->LeftOffset); } trans->Append(stmt); @@ -20532,7 +20458,7 @@ bool Player::CanSpeak() const void Player::SendAttackSwingNotInRange() const { WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SavePositionInDB(WorldLocation const& loc, uint16 zoneId, ObjectGuid guid, SQLTransaction& trans) @@ -20579,25 +20505,25 @@ void Player::Customize(CharacterCustomizeInfo const* customizeInfo, SQLTransacti void Player::SendAttackSwingDeadTarget() const { WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendAttackSwingCantAttack() const { WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendAttackSwingCancelAttack() const { WorldPacket data(SMSG_CANCEL_COMBAT, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendAttackSwingBadFacingAttack() const { WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendAutoRepeatCancel(Unit* target) @@ -20612,7 +20538,7 @@ void Player::SendExplorationExperience(uint32 Area, uint32 Experience) const WorldPacket data(SMSG_EXPLORATION_EXPERIENCE, 8); data << uint32(Area); data << uint32(Experience); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendDungeonDifficulty(bool IsInGroup) const @@ -20622,7 +20548,7 @@ void Player::SendDungeonDifficulty(bool IsInGroup) const data << (uint32)GetDungeonDifficulty(); data << uint32(val); data << uint32(IsInGroup); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendRaidDifficulty(bool IsInGroup, int32 forcedDifficulty) const @@ -20632,13 +20558,13 @@ void Player::SendRaidDifficulty(bool IsInGroup, int32 forcedDifficulty) const data << uint32(forcedDifficulty == -1 ? GetRaidDifficulty() : forcedDifficulty); data << uint32(val); data << uint32(IsInGroup); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendResetFailedNotify(uint32 /*mapid*/) const { WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } /// Reset all solo instances and optionally send a message on success for each @@ -20652,7 +20578,7 @@ void Player::ResetInstances(uint8 method, bool isRaid) for (BoundInstancesMap::iterator itr = m_boundInstances[diff].begin(); itr != m_boundInstances[diff].end();) { InstanceSave* p = itr->second.save; - const MapEntry* entry = sMapStore.LookupEntry(itr->first); + MapEntry const* entry = sMapStore.LookupEntry(itr->first); if (!entry || entry->IsRaid() != isRaid || !p->CanReset()) { ++itr; @@ -20694,7 +20620,7 @@ void Player::SendResetInstanceSuccess(uint32 MapId) const { WorldPacket data(SMSG_INSTANCE_RESET, 4); data << uint32(MapId); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId) const @@ -20707,7 +20633,7 @@ void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId) const WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 8); data << uint32(reason); data << uint32(MapId); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } /*********************************************************/ @@ -20864,7 +20790,7 @@ void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent) { WorldPacket data(SMSG_PET_SPELLS, 8); data << uint64(0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); if (GetGroup()) SetGroupUpdateFlag(GROUP_UPDATE_PET); @@ -20969,7 +20895,7 @@ void Player::WhisperAddon(std::string const& text, const std::string& prefix, Pl WorldPacket data; ChatHandler::BuildChatPacket(data, CHAT_MSG_WHISPER, LANG_ADDON, this, this, text, 0, "", DEFAULT_LOCALE, prefix); - receiver->GetSession()->SendPacket(&data); + receiver->SendDirectMessage(&data); } void Player::Whisper(std::string const& text, Language language, Player* target, bool /*= false*/) @@ -20986,14 +20912,14 @@ void Player::Whisper(std::string const& text, Language language, Player* target, WorldPacket data; ChatHandler::BuildChatPacket(data, CHAT_MSG_WHISPER, Language(language), this, this, _text); - target->GetSession()->SendPacket(&data); + target->SendDirectMessage(&data); // rest stuff shouldn't happen in case of addon message if (isAddonMessage) return; ChatHandler::BuildChatPacket(data, CHAT_MSG_WHISPER_INFORM, Language(language), target, target, _text); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); if (!isAcceptWhispers() && !IsGameMaster() && !target->IsGameMaster()) { @@ -21029,7 +20955,7 @@ void Player::Whisper(uint32 textId, Player* target, bool /*isBossWhisper = false Item* Player::GetMItem(uint32 id) { ItemMap::const_iterator itr = mMitems.find(id); - return itr != mMitems.end() ? itr->second : NULL; + return itr != mMitems.end() ? itr->second : nullptr; } void Player::AddMItem(Item* it) @@ -21047,7 +20973,7 @@ bool Player::RemoveMItem(uint32 id) void Player::SendOnCancelExpectedVehicleRideAura() const { WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::PetSpellInitialize() @@ -21096,7 +21022,7 @@ void Player::PetSpellInitialize() //Cooldowns pet->GetSpellHistory()->WritePacket(data); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::PossessSpellInitialize() @@ -21124,7 +21050,7 @@ void Player::PossessSpellInitialize() data << uint8(0); // spells count data << uint8(0); // cooldowns count - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::VehicleSpellInitialize() @@ -21175,7 +21101,7 @@ void Player::VehicleSpellInitialize() // Cooldowns vehicle->GetSpellHistory()->WritePacket(data); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::CharmSpellInitialize() @@ -21230,14 +21156,14 @@ void Player::CharmSpellInitialize() data << uint8(0); // cooldowns count - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendRemoveControlBar() const { WorldPacket data(SMSG_PET_SPELLS, 8); data << uint64(0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } bool Player::IsAffectedBySpellmod(SpellInfo const* spellInfo, SpellModifier* mod, Spell* spell) @@ -21256,6 +21182,118 @@ bool Player::IsAffectedBySpellmod(SpellInfo const* spellInfo, SpellModifier* mod return spellInfo->IsAffectedBySpellMod(mod); } +template +void Player::ApplySpellMod(uint32 spellId, SpellModOp op, T& basevalue, Spell* spell /*= nullptr*/) const +{ + SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId); + if (!spellInfo) + return; + float totalmul = 1.0f; + int32 totalflat = 0; + + // Drop charges for triggering spells instead of triggered ones + if (m_spellModTakingSpell) + spell = m_spellModTakingSpell; + + switch (op) + { + // special case, if a mod makes spell instant, only consume that mod + case SPELLMOD_CASTING_TIME: + { + SpellModifier* modInstantSpell = nullptr; + for (SpellModifier* mod : m_spellMods[op]) + { + if (!IsAffectedBySpellmod(spellInfo, mod, spell)) + continue; + + if (mod->type == SPELLMOD_PCT && basevalue < T(10000) && mod->value <= -100) + { + modInstantSpell = mod; + break; + } + } + + if (modInstantSpell) + { + Player::ApplyModToSpell(modInstantSpell, spell); + basevalue = T(0); + return; + } + break; + } + // special case if two mods apply 100% critical chance, only consume one + case SPELLMOD_CRITICAL_CHANCE: + { + SpellModifier* modCritical = nullptr; + for (SpellModifier* mod : m_spellMods[op]) + { + if (!IsAffectedBySpellmod(spellInfo, mod, spell)) + continue; + + if (mod->type == SPELLMOD_FLAT && mod->value >= 100) + { + modCritical = mod; + break; + } + } + + if (modCritical) + { + Player::ApplyModToSpell(modCritical, spell); + basevalue = T(100); + return; + } + break; + } + default: + break; + } + + for (SpellModifier* mod : m_spellMods[op]) + { + if (!IsAffectedBySpellmod(spellInfo, mod, spell)) + continue; + + switch (mod->type) + { + case SPELLMOD_FLAT: + totalflat += mod->value; + break; + case SPELLMOD_PCT: + { + // skip percent mods with null basevalue (most important for spell mods with charges) + if (basevalue == T(0)) + continue; + + // special case (skip > 10sec spell casts for instant cast setting) + if (op == SPELLMOD_CASTING_TIME && mod->value <= -100 && basevalue >= T(10000)) + continue; + else if (!Player::HasSpellModApplied(mod, spell)) + { + // special case for Surge of Light, don't apply critical chance reduction if other mods not applied (ie procs while casting another spell) + // (Surge of Light is the only PCT_MOD on critical chance) + if (op == SPELLMOD_CRITICAL_CHANCE) + continue; + // special case for Backdraft, dont' apply GCD reduction if cast time reduction wasn't applied (ie when Backlash is consumed first) + // (Backdraft is the only PCT_MOD on global cooldown) + else if (op == SPELLMOD_GLOBAL_COOLDOWN) + continue; + } + + totalmul += CalculatePct(1.0f, mod->value); + break; + } + } + + Player::ApplyModToSpell(mod, spell); + } + basevalue = T(float(basevalue + totalflat) * totalmul); +} + +template TC_GAME_API void Player::ApplySpellMod(uint32 spellId, SpellModOp op, int32& basevalue, Spell* spell) const; +template TC_GAME_API void Player::ApplySpellMod(uint32 spellId, SpellModOp op, uint32& basevalue, Spell* spell) const; +template TC_GAME_API void Player::ApplySpellMod(uint32 spellId, SpellModOp op, float& basevalue, Spell* spell) const; + void Player::AddSpellMod(SpellModifier* mod, bool apply) { TC_LOG_DEBUG("spells", "Player::AddSpellMod: Player '%s' (%s), SpellID: %d", GetName().c_str(), GetGUID().ToString().c_str(), mod->spellId); @@ -21335,7 +21373,7 @@ void Player::SendProficiency(ItemClass itemClass, uint32 itemSubclassMask) const { WorldPacket data(SMSG_SET_PROFICIENCY, 1 + 4); data << uint8(itemClass) << uint32(itemSubclassMask); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::RemovePetitionsAndSigns(ObjectGuid guid, uint32 type) @@ -21579,7 +21617,7 @@ bool Player::ActivateTaxiPathTo(std::vector const& nodes, Creature* npc prevnode = lastnode; } - // get mount model (in case non taximaster (npc == NULL) allow more wide lookup) + // get mount model (in case non taximaster (npc == nullptr) allow more wide lookup) // // Hack-Fix for Alliance not being able to use Acherus taxi. There is // only one mount ID for both sides. Probably not good to use 315 in case DBC nodes @@ -21850,7 +21888,7 @@ inline bool Player::_StoreOrEquipNewItem(uint32 vendorslot, uint32 item, uint8 c data << uint32(vendorslot + 1); // numbered from 1 at client data << int32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF); data << uint32(count); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); SendNewItem(it, count, true, false, false); if (!bStore) @@ -21880,7 +21918,7 @@ bool Player::BuyCurrencyFromVendorSlot(ObjectGuid vendorGuid, uint32 vendorSlot, CurrencyTypesEntry const* proto = sCurrencyTypesStore.LookupEntry(currency); if (!proto) { - SendBuyError(BUY_ERR_CANT_FIND_ITEM, NULL, currency, 0); + SendBuyError(BUY_ERR_CANT_FIND_ITEM, nullptr, currency, 0); return false; } @@ -21888,7 +21926,7 @@ bool Player::BuyCurrencyFromVendorSlot(ObjectGuid vendorGuid, uint32 vendorSlot, if (!creature) { TC_LOG_DEBUG("network", "WORLD: BuyCurrencyFromVendorSlot - %s not found or you can't interact with him.", vendorGuid.ToString().c_str()); - SendBuyError(BUY_ERR_DISTANCE_TOO_FAR, NULL, currency, 0); + SendBuyError(BUY_ERR_DISTANCE_TOO_FAR, nullptr, currency, 0); return false; } @@ -21915,12 +21953,12 @@ bool Player::BuyCurrencyFromVendorSlot(ObjectGuid vendorGuid, uint32 vendorSlot, if (count % crItem->maxcount) { - SendEquipError(EQUIP_ERR_CANT_BUY_QUANTITY, NULL, NULL); + SendEquipError(EQUIP_ERR_CANT_BUY_QUANTITY, nullptr, nullptr); return false; } uint32 stacks = count / crItem->maxcount; - ItemExtendedCostEntry const* iece = NULL; + ItemExtendedCostEntry const* iece = nullptr; if (crItem->ExtendedCost) { iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost); @@ -21934,7 +21972,7 @@ bool Player::BuyCurrencyFromVendorSlot(ObjectGuid vendorGuid, uint32 vendorSlot, { if (iece->RequiredItem[i] && !HasItemCount(iece->RequiredItem[i], (iece->RequiredItemCount[i] * stacks))) { - SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL); + SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, nullptr, nullptr); return false; } } @@ -21954,12 +21992,12 @@ bool Player::BuyCurrencyFromVendorSlot(ObjectGuid vendorGuid, uint32 vendorSlot, if (iece->RequirementFlags & (ITEM_EXT_COST_CURRENCY_REQ_IS_SEASON_EARNED_1 << i)) { // Not implemented - SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL); // Find correct error + SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, nullptr, nullptr); // Find correct error return false; } else if (!HasCurrency(iece->RequiredCurrency[i], (iece->RequiredCurrencyCount[i] * stacks))) { - SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL); // Find correct error + SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, nullptr, nullptr); // Find correct error return false; } } @@ -21968,7 +22006,7 @@ bool Player::BuyCurrencyFromVendorSlot(ObjectGuid vendorGuid, uint32 vendorSlot, if (GetMaxPersonalArenaRatingRequirement(iece->RequiredArenaSlot) < iece->RequiredPersonalArenaRating) { // probably not the proper equip err - SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK, NULL, NULL); + SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK, nullptr, nullptr); return false; } @@ -21980,25 +22018,25 @@ bool Player::BuyCurrencyFromVendorSlot(ObjectGuid vendorGuid, uint32 vendorSlot, if (iece->RequirementFlags & ITEM_EXT_COST_FLAG_REQUIRE_GUILD && !GetGuildId()) { - SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL); // Find correct error + SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, nullptr, nullptr); // Find correct error return false; } if (iece->RequiredGuildLevel && iece->RequiredGuildLevel < GetGuildLevel()) { - SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL); // Find correct error + SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, nullptr, nullptr); // Find correct error return false; } if (iece->RequiredAchievement && !HasAchieved(iece->RequiredAchievement)) { - SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL); // Find correct error + SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, nullptr, nullptr); // Find correct error return false; } } else // currencies have no price defined, can only be bought with ExtendedCost { - SendBuyError(BUY_ERR_CANT_FIND_ITEM, NULL, currency, 0); + SendBuyError(BUY_ERR_CANT_FIND_ITEM, nullptr, currency, 0); return false; } @@ -22116,7 +22154,7 @@ bool Player::BuyItemFromVendorSlot(ObjectGuid vendorguid, uint32 vendorslot, uin // Can only buy full stacks for extended cost if (count % pProto->BuyCount) { - SendEquipError(EQUIP_ERR_CANT_BUY_QUANTITY, NULL, NULL); + SendEquipError(EQUIP_ERR_CANT_BUY_QUANTITY, nullptr, nullptr); return false; } @@ -22228,7 +22266,7 @@ bool Player::BuyItemFromVendorSlot(ObjectGuid vendorguid, uint32 vendorslot, uin { if (count != 1) { - SendEquipError(EQUIP_ERR_NOT_EQUIPPABLE, NULL, NULL); + SendEquipError(EQUIP_ERR_NOT_EQUIPPABLE, nullptr, nullptr); return false; } if (!_StoreOrEquipNewItem(vendorslot, item, count, bag, slot, price, pProto, creature, crItem, false)) @@ -22236,7 +22274,7 @@ bool Player::BuyItemFromVendorSlot(ObjectGuid vendorguid, uint32 vendorslot, uin } else { - SendEquipError(EQUIP_ERR_WRONG_SLOT, NULL, NULL); + SendEquipError(EQUIP_ERR_WRONG_SLOT, nullptr, nullptr); return false; } @@ -22282,7 +22320,7 @@ void Player::UpdateHomebindTime(uint32 time) WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4); data << uint32(0); data << uint32(0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } // instance is valid, reset homebind timer m_HomebindTimer = 0; @@ -22305,7 +22343,7 @@ void Player::UpdateHomebindTime(uint32 time) WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4); data << uint32(m_HomebindTimer); data << uint32(1); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); TC_LOG_DEBUG("maps", "Player::UpdateHomebindTime: Player '%s' (%s) will be teleported to homebind in 60 seconds", GetName().c_str(), GetGUID().ToString().c_str()); } @@ -22596,7 +22634,7 @@ void Player::SetBattlegroundEntryPoint() // If map is dungeon find linked graveyard if (GetMap()->IsDungeon()) { - if (const WorldSafeLocsEntry* entry = sObjectMgr->GetClosestGraveYard(*this, GetTeam(), this)) + if (const WorldSafeLocsEntry* entry = sObjectMgr->GetClosestGraveyard(*this, GetTeam(), this)) m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f); else TC_LOG_ERROR("entities.player", "Player::SetBattlegroundEntryPoint: Dungeon (MapID: %u) has no linked graveyard, setting home location as entry point.", GetMapId()); @@ -22748,7 +22786,7 @@ bool Player::IsAlwaysDetectableFor(WorldObject const* seer) const if (Unit::IsAlwaysDetectableFor(seer)) return true; - if (const Player* seerPlayer = seer->ToPlayer()) + if (Player const* seerPlayer = seer->ToPlayer()) if (IsGroupVisibleFor(seerPlayer)) return !(seerPlayer->duel && seerPlayer->duel->startTime != 0 && seerPlayer->duel->opponent == this); @@ -22892,7 +22930,7 @@ void Player::UpdateTriggerVisibility() return; udata.BuildPacket(&packet); - GetSession()->SendPacket(&packet); + SendDirectMessage(&packet); } void Player::SendInitialVisiblePackets(Unit* target) const @@ -23041,7 +23079,7 @@ void Player::SendComboPoints() data.Initialize(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1); data << combotarget->GetPackGUID(); data << uint8(m_comboPoints); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } } @@ -23118,7 +23156,7 @@ void Player::SetGroup(Group* group, int8 subgroup) m_group.unlink(); else { - // never use SetGroup without a subgroup unless you specify NULL for group + // never use SetGroup without a subgroup unless you specify nullptr for group ASSERT(subgroup >= 0); m_group.link(group, this); m_group.setSubGroup((uint8)subgroup); @@ -23139,7 +23177,7 @@ void Player::SendInitialPacketsBeforeAddToMap() data << m_homebindX << m_homebindY << m_homebindZ; data << (uint32) m_homebindMapId; data << (uint32) m_homebindAreaId; - GetSession()->SendPacket(&data); + SendDirectMessage(&data); // SMSG_SET_PROFICIENCY // SMSG_SET_PCT_SPELL_MODIFIER @@ -23164,13 +23202,13 @@ void Player::SendInitialPacketsBeforeAddToMap() data << uint32(sWorld->GetNextWeeklyQuestsResetTime() - WEEK); // LastWeeklyReset (not instance reset) data << uint32(GetMap()->GetDifficulty()); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); SendInitialSpells(); data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4); data << uint32(0); // count, for (count) uint32; - GetSession()->SendPacket(&data); + SendDirectMessage(&data); SendInitialActionButtons(); m_reputationMgr->SendInitialReputations(); @@ -23182,7 +23220,7 @@ void Player::SendInitialPacketsBeforeAddToMap() data.AppendPackedTime(GameTime::GetGameTime()); data << float(0.01666667f); // game speed data << uint32(0); // added in 3.1.2 - GetSession()->SendPacket(&data); + SendDirectMessage(&data); GetReputationMgr().SendForceReactions(); // SMSG_SET_FORCED_REACTIONS @@ -23246,11 +23284,11 @@ void Player::SendInitialPacketsAfterAddToMap() if (GetMap()->GetDifficulty() != GetRaidDifficulty()) { StoreRaidMapDifficulty(); - SendRaidDifficulty(GetGroup() != NULL, GetStoredRaidDifficulty()); + SendRaidDifficulty(GetGroup() != nullptr, GetStoredRaidDifficulty()); } } else if (GetRaidDifficulty() != GetStoredRaidDifficulty()) - SendRaidDifficulty(GetGroup() != NULL); + SendRaidDifficulty(GetGroup() != nullptr); if (GetPlayerSharingQuest()) { @@ -23282,7 +23320,7 @@ void Player::SendTransferAborted(uint32 mapid, TransferAbortReason reason, uint8 data << uint32(mapid); data << uint8(reason); // transfer abort reason data << uint8(arg); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint32 time, bool welcome) const @@ -23310,7 +23348,7 @@ void Player::SendInstanceResetWarning(uint32 mapid, Difficulty difficulty, uint3 data << uint8(0); // is locked data << uint8(0); // is extended, ignored if prev field is 0 } - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::ApplyEquipCooldown(Item* pItem) @@ -23352,7 +23390,7 @@ void Player::ApplyEquipCooldown(Item* pItem) WorldPacket data(SMSG_ITEM_COOLDOWN, 8 + 4); data << uint64(pItem->GetGUID()); data << uint32(spellData.SpellId); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } } @@ -23647,7 +23685,7 @@ void Player::SendAurasForTarget(Unit* target) const auraApp->BuildUpdatePacket(data, false); } - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::SetDailyQuestStatus(uint32 quest_id) @@ -23896,6 +23934,11 @@ float Player::GetReputationPriceDiscount(Creature const* creature) const return 1.0f - 0.05f* (rank - REP_NEUTRAL); } +Player* Player::GetTrader() const +{ + return m_trade ? m_trade->GetTrader() : nullptr; +} + bool Player::IsSpellFitByClassAndRace(uint32 spell_id) const { uint32 racemask = getRaceMask(); @@ -24003,7 +24046,7 @@ void Player::UpdateForQuestWorldObjects() } } udata.BuildPacket(&packet); - GetSession()->SendPacket(&packet); + SendDirectMessage(&packet); } bool Player::HasSummonPending() const @@ -24031,7 +24074,7 @@ void Player::SendSummonRequestFrom(Unit* summoner) 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); + SendDirectMessage(&data); } void Player::SummonIfPossible(bool agree) @@ -24295,7 +24338,7 @@ bool Player::GetsRecruitAFriendBonus(bool forXP) bool recruitAFriend = false; if (getLevel() <= sWorld->getIntConfig(CONFIG_MAX_RECRUIT_A_FRIEND_BONUS_PLAYER_LEVEL) || !forXP) { - if (Group* group = this->GetGroup()) + if (Group* group = GetGroup()) { for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { @@ -24369,7 +24412,7 @@ bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const if (!pRewardSource || !IsInMap(pRewardSource)) return false; - const WorldObject* player = GetCorpse(); + WorldObject const* player = GetCorpse(); if (!player || IsAlive()) player = this; @@ -24384,7 +24427,7 @@ bool Player::IsAtRecruitAFriendDistance(WorldObject const* pOther) const if (!pOther || !IsInMap(pOther)) return false; - const WorldObject* player = GetCorpse(); + WorldObject const* player = GetCorpse(); if (!player || IsAlive()) player = this; @@ -24422,7 +24465,7 @@ void Player::ResurrectUsingRequestData() SetPower(POWER_ECLIPSE, 0); if (uint32 aura = _resurrectionData->Aura) - CastSpell(this, aura, true, NULL, NULL, _resurrectionData->GUID); + CastSpell(this, aura, true, nullptr, nullptr, _resurrectionData->GUID); SpawnCorpseBones(); } @@ -24432,7 +24475,7 @@ void Player::SetClientControl(Unit* target, bool allowMove) WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1); data << target->GetPackGUID(); data << uint8(allowMove ? 1 : 0); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); if (this != target) SetViewpoint(target, allowMove); @@ -24587,7 +24630,7 @@ void Player::SendCorpseReclaimDelay(uint32 delay) const { WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4); data << uint32(delay); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } Player* Player::GetNextRandomRaidMember(float radius) @@ -24710,7 +24753,7 @@ void Player::SetOriginalGroup(Group* group, int8 subgroup) m_originalGroup.unlink(); else { - // never use SetOriginalGroup without a subgroup unless you specify NULL for group + // never use SetOriginalGroup without a subgroup unless you specify nullptr for group ASSERT(subgroup >= 0); m_originalGroup.link(group, this); m_originalGroup.setSubGroup((uint8)subgroup); @@ -24841,7 +24884,7 @@ void Player::SetViewpoint(WorldObject* target, bool apply) SetSeer(this); //WorldPacket data(SMSG_CLEAR_FAR_SIGHT_IMMEDIATE, 0); - //GetSession()->SendPacket(&data); + //SendDirectMessage(&data); } } @@ -24965,6 +25008,11 @@ bool Player::HasTitle(uint32 bitIndex) const return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag); } +bool Player::HasTitle(CharTitlesEntry const* title) const +{ + return HasTitle(title->bit_index); +} + void Player::SetTitle(CharTitlesEntry const* title, bool lost) { uint32 fieldIndexOffset = title->bit_index / 32; @@ -24988,7 +25036,7 @@ void Player::SetTitle(CharTitlesEntry const* title, bool lost) WorldPacket data(SMSG_TITLE_EARNED, 4 + 4); data << uint32(title->bit_index); data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } bool Player::isTotalImmunity() const @@ -25088,7 +25136,7 @@ void Player::ConvertRune(uint8 index, RuneType newType) WorldPacket data(SMSG_CONVERT_RUNE, 2); data << uint8(index); data << uint8(newType); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::ResyncRunes(uint8 count) const @@ -25100,14 +25148,14 @@ void Player::ResyncRunes(uint8 count) const data << uint8(GetCurrentRune(i)); // rune type data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255) } - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::AddRunePower(uint8 index) const { WorldPacket data(SMSG_ADD_RUNE_POWER, 4); data << uint32(1 << index); // mask (0x00-0x3F probably) - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } static RuneType runeSlotTypes[MAX_RUNES] = @@ -25219,7 +25267,7 @@ void Player::StoreLootItem(uint8 lootSlot, Loot* loot) InventoryResult msg = CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, item->itemid, item->count); if (msg == EQUIP_ERR_OK) { - AllowedLooterSet looters = item->GetAllowedLooters(); + GuidSet looters = item->GetAllowedLooters(); Item* newitem = StoreNewItem(dest, item->itemid, true, item->randomPropertyId, looters); if (qitem) @@ -25266,7 +25314,7 @@ void Player::StoreLootItem(uint8 lootSlot, Loot* loot) // LootItem is being removed (looted) from the container, delete it from the DB. if (loot->containerID > 0) - loot->DeleteLootItemFromContainerItemDB(item->itemid); + sLootItemStorage->RemoveStoredLootItemForContainer(loot->containerID, item->itemid, item->count); } else @@ -25414,7 +25462,7 @@ void Player::_LoadSkills(PreparedQueryResult result) loadedSkillValues[skill] = value; if (skill == SKILL_ARCHAEOLOGY) - _archaeology.Initialize(); + _archaeology->Initialize(); ++count; @@ -25606,7 +25654,7 @@ void Player::ResetAchievementCriteria(AchievementCriteriaTypes type, uint64 misc m_achievementMgr->ResetAchievementCriteria(type, miscValue1, miscValue2, evenIfCriteriaComplete); } -void Player::UpdateAchievementCriteria(AchievementCriteriaTypes type, uint64 miscValue1 /*= 0*/, uint64 miscValue2 /*= 0*/, uint64 miscValue3 /*= 0*/, Unit* unit /*= NULL*/) +void Player::UpdateAchievementCriteria(AchievementCriteriaTypes type, uint64 miscValue1 /*= 0*/, uint64 miscValue2 /*= 0*/, uint64 miscValue3 /*= 0*/, Unit* unit /*= nullptr*/) { m_achievementMgr->UpdateAchievementCriteria(type, miscValue1, miscValue2, miscValue3, unit, this); Guild* guild = sGuildMgr->GetGuildById(GetGuildId()); @@ -25853,7 +25901,7 @@ void Player::LearnPetTalent(ObjectGuid petGuid, uint32 talentId, uint32 talentRa for (uint32 i = 0; i < numRows; ++i) // Loop through all talents. { // Someday, someone needs to revamp - const TalentEntry* tmpTalent = sTalentStore.LookupEntry(i); + TalentEntry const* tmpTalent = sTalentStore.LookupEntry(i); if (tmpTalent) // the way talents are tracked { if (tmpTalent->TalentTab == tTab) @@ -26117,7 +26165,7 @@ void Player::SendTalentsInfoData(bool pet) BuildPetTalentsInfoData(&data); else BuildPlayerTalentsInfoData(&data); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::BuildEnchantmentsInfoData(WorldPacket* data) @@ -26166,123 +26214,110 @@ void Player::BuildEnchantmentsInfoData(WorldPacket* data) void Player::SendEquipmentSetList() { uint32 count = 0; - WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4); + WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 1000); // guess size size_t count_pos = data.wpos(); data << uint32(count); // count placeholder - for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr) + for (EquipmentSetContainer::value_type const& eqSet : _equipmentSets) { - if (itr->second.state == EQUIPMENT_SET_DELETED) + if (eqSet.second.State == EQUIPMENT_SET_DELETED) continue; - data.appendPackGUID(itr->second.Guid); - data << uint32(itr->first); - data << itr->second.Name; - data << itr->second.IconName; + data.appendPackGUID(eqSet.first); + data << uint32(eqSet.second.Data.SetID); + data << eqSet.second.Data.SetName; + data << eqSet.second.Data.SetIcon; for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i) { // ignored slots stored in IgnoreMask, client wants "1" as raw GUID, so no HighGuid::Item - if (itr->second.IgnoreMask & (1 << i)) + if (eqSet.second.Data.IgnoreMask & (1 << i)) data.appendPackGUID(uint64(1)); - else if (itr->second.Items[i] > 0) // send proper data (do not append 0 with high guid) - data << ObjectGuid(HighGuid::Item, 0, itr->second.Items[i]).WriteAsPacked(); else - data.appendPackGUID(uint64(0)); + data.appendPackGUID(eqSet.second.Data.Pieces[i]); } ++count; // client have limit but it checked at loading and set } data.put(count_pos, count); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } -void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset) +void Player::SetEquipmentSet(EquipmentSetInfo::EquipmentSetData const& eqSet) { - if (eqset.Guid != 0) + if (eqSet.Guid != 0) { - bool found = false; - - for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr) - { - if ((itr->second.Guid == eqset.Guid) && (itr->first == index)) - { - found = true; - break; - } - } - - if (!found) // something wrong... + // something wrong... + auto itr = _equipmentSets.find(eqSet.Guid); + if (itr == _equipmentSets.end() || itr->second.Data.Guid != eqSet.Guid) { 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); + GetName().c_str(), GetGUID().ToString().c_str(), eqSet.Guid, eqSet.SetID); return; } } - EquipmentSet& eqslot = m_EquipmentSets[index]; + EquipmentSetInfo& eqSlot = _equipmentSets[eqSet.Guid]; - EquipmentSetUpdateState old_state = eqslot.state; + EquipmentSetUpdateState oldState = eqSlot.State; + eqSlot.Data = eqSet; - eqslot = eqset; - - if (eqset.Guid == 0) + if (eqSet.Guid == 0) { - eqslot.Guid = sObjectMgr->GenerateEquipmentSetGuid(); + eqSlot.Data.Guid = sObjectMgr->GenerateEquipmentSetGuid(); WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1); - data << uint32(index); - data.appendPackGUID(eqslot.Guid); - GetSession()->SendPacket(&data); + data << uint32(eqSlot.Data.SetID); + data.appendPackGUID(eqSlot.Data.Guid); + SendDirectMessage(&data); } - eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED; + eqSlot.State = (oldState == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED); } void Player::_SaveEquipmentSets(SQLTransaction& trans) { - for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();) + for (EquipmentSetContainer::iterator itr = _equipmentSets.begin(); itr != _equipmentSets.end();) { - uint32 index = itr->first; - EquipmentSet& eqset = itr->second; - PreparedStatement* stmt = nullptr; + EquipmentSetInfo& eqSet = itr->second; + PreparedStatement* stmt; uint8 j = 0; - switch (eqset.state) + switch (eqSet.State) { case EQUIPMENT_SET_UNCHANGED: ++itr; break; // nothing do case EQUIPMENT_SET_CHANGED: stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_EQUIP_SET); - stmt->setString(j++, eqset.Name.c_str()); - stmt->setString(j++, eqset.IconName.c_str()); - stmt->setUInt32(j++, eqset.IgnoreMask); - for (uint8 i=0; isetUInt32(j++, eqset.Items[i]); + stmt->setString(j++, eqSet.Data.SetName); + stmt->setString(j++, eqSet.Data.SetIcon); + stmt->setUInt32(j++, eqSet.Data.IgnoreMask); + for (uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i) + stmt->setUInt32(j++, eqSet.Data.Pieces[i].GetCounter()); stmt->setUInt32(j++, GetGUID().GetCounter()); - stmt->setUInt64(j++, eqset.Guid); - stmt->setUInt32(j, index); + stmt->setUInt64(j++, eqSet.Data.Guid); + stmt->setUInt32(j, eqSet.Data.SetID); trans->Append(stmt); - eqset.state = EQUIPMENT_SET_UNCHANGED; + eqSet.State = EQUIPMENT_SET_UNCHANGED; ++itr; break; case EQUIPMENT_SET_NEW: stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_EQUIP_SET); stmt->setUInt32(j++, GetGUID().GetCounter()); - stmt->setUInt64(j++, eqset.Guid); - stmt->setUInt32(j++, index); - stmt->setString(j++, eqset.Name.c_str()); - stmt->setString(j++, eqset.IconName.c_str()); - stmt->setUInt32(j++, eqset.IgnoreMask); - for (uint8 i=0; isetUInt32(j++, eqset.Items[i]); + stmt->setUInt64(j++, eqSet.Data.Guid); + stmt->setUInt32(j++, eqSet.Data.SetID); + stmt->setString(j++, eqSet.Data.SetName); + stmt->setString(j++, eqSet.Data.SetIcon); + stmt->setUInt32(j++, eqSet.Data.IgnoreMask); + for (uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i) + stmt->setUInt32(j++, eqSet.Data.Pieces[i].GetCounter()); trans->Append(stmt); - eqset.state = EQUIPMENT_SET_UNCHANGED; + eqSet.State = EQUIPMENT_SET_UNCHANGED; ++itr; break; case EQUIPMENT_SET_DELETED: stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_EQUIP_SET); - stmt->setUInt64(0, eqset.Guid); + stmt->setUInt64(0, eqSet.Data.Guid); trans->Append(stmt); - m_EquipmentSets.erase(itr++); + itr = _equipmentSets.erase(itr); break; } } @@ -26311,16 +26346,17 @@ void Player::_SaveBGData(SQLTransaction& trans) void Player::DeleteEquipmentSet(uint64 setGuid) { - for (EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr) + for (auto itr = _equipmentSets.begin(); itr != _equipmentSets.end();) { - if (itr->second.Guid == setGuid) + if (itr->second.Data.Guid == setGuid) { - if (itr->second.state == EQUIPMENT_SET_NEW) - m_EquipmentSets.erase(itr); + if (itr->second.State == EQUIPMENT_SET_NEW) + itr = _equipmentSets.erase(itr); else - itr->second.state = EQUIPMENT_SET_DELETED; + itr->second.State = EQUIPMENT_SET_DELETED; break; } + ++itr; } } @@ -26345,7 +26381,7 @@ void Player::ResetMap() // after decrement+unlink, ++m_mapRefIter will continue correctly // when the first element of the list is being removed // nocheck_prev will return the padding element of the RefManager - // instead of NULL in the case of prev + // instead of nullptr in the case of prev GetMap()->UpdateIteratorBack(this); Unit::ResetMap(); GetMapRef().unlink(); @@ -26538,7 +26574,7 @@ void Player::ActivateSpec(uint8 spec) if (GetPet()) GetPet()->RemoveAllAurasOnDeath();*/ - //RemoveAllAuras(GetGUID(), NULL, false, true); // removes too many auras + //RemoveAllAuras(GetGUID(), nullptr, false, true); // removes too many auras //ExitVehicle(); // should be impossible to switch specs from inside a vehicle.. // Let client clear his current Actions @@ -26568,7 +26604,7 @@ void Player::ActivateSpec(uint8 spec) if (talentInfo->RankID[rank] == 0) continue; RemoveSpell(talentInfo->RankID[rank], true); // removes the talent, and all dependant, learned, and chained spells.. - if (const SpellInfo* _spellEntry = sSpellMgr->GetSpellInfo(talentInfo->RankID[rank])) + if (SpellInfo const* _spellEntry = sSpellMgr->GetSpellInfo(talentInfo->RankID[rank])) for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) // search through the SpellInfo for valid trigger spells if (_spellEntry->Effects[i].TriggerSpell > 0 && _spellEntry->Effects[i].Effect == SPELL_EFFECT_LEARN_SPELL) RemoveSpell(_spellEntry->Effects[i].TriggerSpell, true); // and remove any spells that the talent teaches @@ -26717,7 +26753,7 @@ void Player::SendTimeSync() WorldPacket data(SMSG_TIME_SYNC_REQ, 4); data << uint32(m_timeSyncQueue.back()); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); // Schedule next sync in 10 sec m_timeSyncTimer = 10000; @@ -26745,7 +26781,7 @@ void Player::SendDuelCountdown(uint32 counter) { WorldPacket data(SMSG_DUEL_COUNTDOWN, 4); data << uint32(counter); // seconds - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::AddRefundReference(ObjectGuid it) @@ -26830,7 +26866,7 @@ void Player::SendRefundInfo(Item* item) data << uint32(0); data.WriteByteSeq(guid[0]); data << uint32(item->GetPaidMoney()); // money cost - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } bool Player::AddItem(uint32 itemId, uint32 count) @@ -26848,7 +26884,7 @@ bool Player::AddItem(uint32 itemId, uint32 count) return false; } - Item* item = StoreNewItem(dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId)); + Item* item = StoreNewItem(dest, itemId, true, GenerateItemRandomPropertyId(itemId)); if (item) SendNewItem(item, count, true, false); else @@ -26908,7 +26944,7 @@ void Player::SendItemRefundResult(Item* item, ItemExtendedCostEntry const* iece, data.WriteByteSeq(guid[5]); data << uint8(error); // error code - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } void Player::RefundItem(Item* item) @@ -26922,7 +26958,7 @@ void Player::RefundItem(Item* item) if (item->IsRefundExpired()) // item refund has expired { item->SetNotRefundable(this); - SendItemRefundResult(item, NULL, 10); + SendItemRefundResult(item, nullptr, 10); return; } @@ -27130,7 +27166,7 @@ uint8 Player::GetNumOfVoidStorageFreeSlots() const return count; } -uint8 Player::AddVoidStorageItem(const VoidStorageItem& item) +uint8 Player::AddVoidStorageItem(VoidStorageItem const& item) { int8 slot = GetNextVoidStorageFreeSlot(); @@ -27173,7 +27209,7 @@ void Player::DeleteVoidStorageItem(uint8 slot) } delete _voidStorageItems[slot]; - _voidStorageItems[slot] = NULL; + _voidStorageItems[slot] = nullptr; } bool Player::SwapVoidStorageItem(uint8 oldSlot, uint8 newSlot) @@ -27190,7 +27226,7 @@ VoidStorageItem* Player::GetVoidStorageItem(uint8 slot) const if (slot >= VOID_STORAGE_MAX_SLOT) { GetSession()->SendVoidStorageTransferResult(VOID_TRANSFER_ERROR_INTERNAL_ERROR_1); - return NULL; + return nullptr; } return _voidStorageItems[slot]; @@ -27207,7 +27243,7 @@ VoidStorageItem* Player::GetVoidStorageItem(uint64 id, uint8& slot) const } } - return NULL; + return nullptr; } void Player::SendMovementSetCanTransitionBetweenSwimAndFly(bool apply) @@ -27286,7 +27322,7 @@ std::string Player::GetCoordsMapAreaAndZoneString() const Guild* Player::GetGuild() { uint32 guildId = GetGuildId(); - return guildId ? sGuildMgr->GetGuildById(guildId) : NULL; + return guildId ? sGuildMgr->GetGuildById(guildId) : nullptr; } Pet* Player::SummonPet(uint32 entry, float x, float y, float z, float ang, PetType petType, uint32 duration) @@ -27409,7 +27445,7 @@ bool Player::CanUseMastery() const return HasSpell(MasterySpells[getClass()]); } -void Player::ReadMovementInfo(WorldPacket& data, MovementInfo* mi, Movement::ExtraMovementStatusElement* extras /*= NULL*/) +void Player::ReadMovementInfo(WorldPacket& data, MovementInfo* mi, Movement::ExtraMovementStatusElement* extras /*= nullptr*/) { MovementStatusElements const* sequence = GetMovementStatusElementsSequence(data.GetOpcode()); if (!sequence) @@ -27714,7 +27750,7 @@ void Player::SendSupercededSpell(uint32 oldSpell, uint32 newSpell) const { WorldPacket data(SMSG_SUPERCEDED_SPELL, 8); data << uint32(newSpell) << uint32(oldSpell); - GetSession()->SendPacket(&data); + SendDirectMessage(&data); } bool Player::ValidateAppearance(uint8 race, uint8 class_, uint8 gender, uint8 hairID, uint8 hairColor, uint8 faceID, uint8 facialStyle, uint8 skinColor, bool create /*=false*/) diff --git a/src/server/game/Entities/Player/Player.h b/src/server/game/Entities/Player/Player.h index fff5bbf8ada..05553055719 100644 --- a/src/server/game/Entities/Player/Player.h +++ b/src/server/game/Entities/Player/Player.h @@ -19,49 +19,70 @@ #ifndef _PLAYER_H #define _PLAYER_H -#include "DBCStores.h" -#include "GroupReference.h" -#include "MapReference.h" - -#include "Archaeology.h" -#include "Item.h" -#include "PetDefines.h" -#include "QuestDef.h" -#include "SpellMgr.h" -#include "SpellHistory.h" #include "Unit.h" -#include "TradeData.h" -#include "CinematicMgr.h" - -#include -#include -#include +#include "CUFProfile.h" +#include "DatabaseEnvFwd.h" +#include "DBCEnums.h" +#include "EquipmentSet.h" +#include "GroupReference.h" +#include "ItemDefines.h" +#include "ItemEnchantmentMgr.h" +#include "MapReference.h" +#include "PetDefines.h" +#include "PlayerTaxi.h" +#include "QuestDef.h" +#include +struct AccessRequirement; +struct AchievementEntry; +struct AreaTableEntry; +struct AreaTriggerEntry; +struct ArchData; +struct BarberShopStyleEntry; +struct CharacterCustomizeInfo; +struct CharTitlesEntry; +struct ChatChannelsEntry; struct CreatureTemplate; -struct Mail; +struct CurrencyTypesEntry; +struct FactionEntry; struct ItemExtendedCostEntry; +struct ItemSetEffect; +struct ItemTemplate; +struct Loot; +struct Mail; +struct ScalingStatValuesEntry; struct TrainerSpell; struct VendorItem; -template class AchievementMgr; -class ReputationMgr; +template +class AchievementMgr; + +class Archaeology; +class Bag; +class Battleground; +class CinematicMgr; class Channel; class CharacterCreateInfo; class Creature; class DynamicObject; class Group; class Guild; +class Item; +class LootStore; class OutdoorPvP; class Pet; class PetAura; +class PlayerAI; class PlayerMenu; class PlayerSocial; +class ReputationMgr; class SpellCastTargets; -class UpdateMask; -class PlayerAI; -class Archaeology; +class TradeData; -struct CharacterCustomizeInfo; +enum InventoryType : uint8; +enum ItemClass : uint8; +enum LootError : uint8; +enum LootType : uint8; typedef std::deque PlayerMails; @@ -189,99 +210,6 @@ typedef std::unordered_map PlayerSpellMap; typedef std::unordered_set SpellModContainer; typedef std::unordered_map PlayerCurrenciesMap; -/// Maximum number of CompactUnitFrames profiles -#define MAX_CUF_PROFILES 5 - -/// Bit index used in the many bool options of CompactUnitFrames -enum CUFBoolOptions -{ - CUF_KEEP_GROUPS_TOGETHER, - CUF_DISPLAY_PETS, - CUF_DISPLAY_MAIN_TANK_AND_ASSIST, - CUF_DISPLAY_HEAL_PREDICTION, - CUF_DISPLAY_AGGRO_HIGHLIGHT, - CUF_DISPLAY_ONLY_DISPELLABLE_DEBUFFS, - CUF_DISPLAY_POWER_BAR, - CUF_DISPLAY_BORDER, - CUF_USE_CLASS_COLORS, - CUF_DISPLAY_NON_BOSS_DEBUFFS, - CUF_DISPLAY_HORIZONTAL_GROUPS, - CUF_LOCKED, - CUF_SHOWN, - CUF_AUTO_ACTIVATE_2_PLAYERS, - CUF_AUTO_ACTIVATE_3_PLAYERS, - CUF_AUTO_ACTIVATE_5_PLAYERS, - CUF_AUTO_ACTIVATE_10_PLAYERS, - CUF_AUTO_ACTIVATE_15_PLAYERS, - CUF_AUTO_ACTIVATE_25_PLAYERS, - CUF_AUTO_ACTIVATE_40_PLAYERS, - CUF_AUTO_ACTIVATE_SPEC_1, - CUF_AUTO_ACTIVATE_SPEC_2, - CUF_AUTO_ACTIVATE_PVP, - CUF_AUTO_ACTIVATE_PVE, - CUF_UNK_145, - CUF_UNK_156, - CUF_UNK_157, - - // The unks is _LOCKED and _SHOWN and _DYNAMIC, unknown order - - CUF_BOOL_OPTIONS_COUNT, -}; - -/// Represents a CompactUnitFrame profile -struct CUFProfile -{ - CUFProfile() : ProfileName(), BoolOptions() // might want to change default value for options - { - FrameHeight = 0; - FrameWidth = 0; - SortBy = 0; - HealthText = 0; - Unk146 = 0; - Unk147 = 0; - Unk148 = 0; - Unk150 = 0; - Unk152 = 0; - Unk154 = 0; - } - - CUFProfile(const std::string& name, uint16 frameHeight, uint16 frameWidth, uint8 sortBy, uint8 healthText, uint32 boolOptions, - uint8 unk146, uint8 unk147, uint8 unk148, uint16 unk150, uint16 unk152, uint16 unk154) - : ProfileName(name), BoolOptions((int)boolOptions) - { - FrameHeight = frameHeight; - FrameWidth = frameWidth; - SortBy = sortBy; - HealthText = healthText; - Unk146 = unk146; - Unk147 = unk147; - Unk148 = unk148; - Unk150 = unk150; - Unk152 = unk152; - Unk154 = unk154; - } - - std::string ProfileName; - uint16 FrameHeight; - uint16 FrameWidth; - uint8 SortBy; - uint8 HealthText; - - // LeftAlign, TopAlight, BottomAllign (unk order) - uint8 Unk146; - uint8 Unk147; - uint8 Unk148; - - // LeftOffset, TopOffset and BottomOffset (unk order) - uint16 Unk150; - uint16 Unk152; - uint16 Unk154; - - std::bitset BoolOptions; - - // More fields can be added to BoolOptions without changing DB schema (up to 32, currently 27) -}; - typedef std::unordered_map InstanceTimeMap; enum TrainerSpellState @@ -352,67 +280,6 @@ struct ActionButton typedef std::map ActionButtonList; -struct PlayerCreateInfoItem -{ - PlayerCreateInfoItem(uint32 id, uint32 amount) : item_id(id), item_amount(amount) { } - - uint32 item_id; - uint32 item_amount; -}; - -typedef std::list PlayerCreateInfoItems; - -struct PlayerLevelInfo -{ - PlayerLevelInfo() { for (uint8 i=0; i < MAX_STATS; ++i) stats[i] = 0; } - - uint8 stats[MAX_STATS]; -}; - -typedef std::list PlayerCreateInfoSpells; - -struct PlayerCreateInfoAction -{ - PlayerCreateInfoAction() : button(0), type(0), action(0) { } - PlayerCreateInfoAction(uint8 _button, uint32 _action, uint8 _type) : button(_button), type(_type), action(_action) { } - - uint8 button; - uint8 type; - uint32 action; -}; - -typedef std::list PlayerCreateInfoActions; - -struct PlayerCreateInfoSkill -{ - uint16 SkillId; - uint16 Rank; -}; - -typedef std::list 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(nullptr) { } - - uint32 mapId; - uint32 areaId; - float positionX; - float positionY; - float positionZ; - float orientation; - uint16 displayId_m; - uint16 displayId_f; - PlayerCreateInfoItems item; - PlayerCreateInfoSpells customSpells; - PlayerCreateInfoSpells castSpells; - PlayerCreateInfoActions action; - PlayerCreateInfoSkills skills; - - PlayerLevelInfo* levelInfo; //[level-1] 0..MaxPlayerLevel-1 -}; - struct PvPInfo { PvPInfo() : IsHostile(false), IsInHostileArea(false), IsInNoPvPArea(false), IsInFFAPvPArea(false), EndTimer(0) { } @@ -769,34 +636,6 @@ enum BuyBackSlots // 12 slots BUYBACK_SLOT_END = 86 }; -enum EquipmentSetUpdateState -{ - EQUIPMENT_SET_UNCHANGED = 0, - EQUIPMENT_SET_CHANGED = 1, - EQUIPMENT_SET_NEW = 2, - EQUIPMENT_SET_DELETED = 3 -}; - -struct EquipmentSet -{ - EquipmentSet() : Guid(0), IgnoreMask(0), state(EQUIPMENT_SET_NEW) - { - for (uint8 i = 0; i < EQUIPMENT_SLOT_END; ++i) - Items[i] = 0; - } - - uint64 Guid; - std::string Name; - std::string IconName; - uint32 IgnoreMask; - uint32 Items[EQUIPMENT_SLOT_END]; - EquipmentSetUpdateState state; -}; - -#define MAX_EQUIPMENT_SET_INDEX 10 // client limit - -typedef std::map EquipmentSets; - struct ItemPosCount { ItemPosCount(uint16 _pos, uint32 _count) : pos(_pos), count(_count) { } @@ -982,18 +821,6 @@ struct InstancePlayerBind InstancePlayerBind() : save(nullptr), perm(false), extendState(EXTEND_STATE_NORMAL) { } }; -struct AccessRequirement -{ - uint8 levelMin; - uint8 levelMax; - uint32 item; - uint32 item2; - uint32 quest_A; - uint32 quest_H; - uint32 achievement; - std::string questFailedText; -}; - enum CharDeleteMethod { CHAR_DELETE_REMOVE = 0, // Completely remove from the database @@ -1036,61 +863,6 @@ enum PlayerCommandStates CHEAT_WATERWALK = 0x10 }; -class TC_GAME_API PlayerTaxi -{ - public: - PlayerTaxi(); - ~PlayerTaxi() { } - // Nodes - void InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint8 level); - void LoadTaxiMask(std::string const& data); - - bool IsTaximaskNodeKnown(uint32 nodeidx) const - { - uint8 field = uint8((nodeidx - 1) / 8); - uint32 submask = 1 << ((nodeidx-1) % 8); - return (m_taximask[field] & submask) == submask; - } - bool SetTaximaskNode(uint32 nodeidx) - { - uint8 field = uint8((nodeidx - 1) / 8); - uint32 submask = 1 << ((nodeidx- 1) % 8); - if ((m_taximask[field] & submask) != submask) - { - m_taximask[field] |= submask; - return true; - } - else - return false; - } - void AppendTaximaskTo(ByteBuffer& data, bool all); - - // Destinations - bool LoadTaxiDestinationsFromString(std::string const& values, uint32 team); - std::string SaveTaxiDestinationsToString(); - - void ClearTaxiDestinations() { m_TaxiDestinations.clear(); } - void AddTaxiDestination(uint32 dest) { m_TaxiDestinations.push_back(dest); } - uint32 GetTaxiSource() const { return m_TaxiDestinations.empty() ? 0 : m_TaxiDestinations.front(); } - uint32 GetTaxiDestination() const { return m_TaxiDestinations.size() < 2 ? 0 : m_TaxiDestinations[1]; } - uint32 GetCurrentTaxiPath() const; - uint32 NextTaxiDestination() - { - m_TaxiDestinations.pop_front(); - return GetTaxiDestination(); - } - - std::deque const& GetPath() const { return m_TaxiDestinations; } - bool empty() const { return m_TaxiDestinations.empty(); } - - friend std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi); - private: - TaxiMask m_taximask; - std::deque m_TaxiDestinations; -}; - -std::ostringstream& operator << (std::ostringstream& ss, PlayerTaxi const& taxi); - class Player; /// Holder for Battleground data @@ -1216,8 +988,8 @@ class TC_GAME_API Player : public Unit, public GridObject { friend class WorldSession; friend class CinematicMgr; - friend void Item::AddToUpdateQueueOf(Player* player); - friend void Item::RemoveFromUpdateQueueOf(Player* player); + friend void AddItemToUpdateQueueOf(Item* item, Player* player); + friend void RemoveItemFromUpdateQueueOf(Item* item, Player* player); public: explicit Player(WorldSession* session); ~Player(); @@ -1232,7 +1004,7 @@ class TC_GAME_API Player : public Unit, public GridObject void SetObjectScale(float scale) override; bool TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options = 0); - bool TeleportTo(WorldLocation const &loc, uint32 options = 0); + bool TeleportTo(WorldLocation const& loc, uint32 options = 0); bool TeleportToBGEntryPoint(); bool HasSummonPending() const; @@ -1251,7 +1023,7 @@ class TC_GAME_API Player : public Unit, public GridObject bool IsInWater() const override { return m_isInWater; } bool IsUnderWater() const override; - bool IsInAreaTriggerRadius(const AreaTriggerEntry* trigger) const; + bool IsInAreaTriggerRadius(AreaTriggerEntry const* trigger) const; void SendInitialPacketsBeforeAddToMap(); void SendInitialPacketsAfterAddToMap(); @@ -1385,8 +1157,8 @@ class TC_GAME_API Player : public Unit, public GridObject bool HasItemOrGemWithIdEquipped(uint32 item, uint32 count, uint8 except_slot = NULL_SLOT) const; bool HasItemWithLimitCategoryEquipped(uint32 limitCategory, uint32 count, uint8 except_slot = NULL_SLOT) const; bool HasGemWithLimitCategoryEquipped(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 CanTakeMoreSimilarItems(Item* pItem, uint32* itemLimitCategory = nullptr) const; + InventoryResult CanTakeMoreSimilarItems(uint32 entry, uint32 count, uint32* itemLimitCategory = nullptr) const { return CanTakeMoreSimilarItems(entry, count, nullptr, nullptr, itemLimitCategory); } 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; @@ -1403,7 +1175,7 @@ class TC_GAME_API Player : public Unit, public GridObject InventoryResult CanUseItem(ItemTemplate const* pItem) const; InventoryResult CanUseAmmo(uint32 item) const; InventoryResult CanRollForItemInLFG(ItemTemplate const* item, WorldObject const* lootedObject) const; - Item* StoreNewItem(ItemPosCountVec const& pos, uint32 item, bool update, int32 randomPropertyId = 0, AllowedLooterSet const& allowedLooters = AllowedLooterSet()); + Item* StoreNewItem(ItemPosCountVec const& pos, uint32 item, bool update, int32 randomPropertyId = 0, GuidSet const& allowedLooters = GuidSet()); Item* StoreItem(ItemPosCountVec const& pos, Item* pItem, bool update); Item* EquipNewItem(uint16 pos, uint32 item, bool update); Item* EquipItem(uint16 pos, Item* pItem, bool update); @@ -1414,8 +1186,8 @@ class TC_GAME_API Player : public Unit, public GridObject void StoreLootItem(uint8 lootSlot, Loot* loot); void StoreLootCurrency(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 CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count = nullptr, uint32* itemLimitCategory = nullptr) 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); @@ -1487,7 +1259,7 @@ class TC_GAME_API Player : public Unit, public GridObject float GetReputationPriceDiscount(Creature const* creature) const; - Player* GetTrader() const { return m_trade ? m_trade->GetTrader() : nullptr; } + Player* GetTrader() const; TradeData* GetTradeData() const { return m_trade; } void TradeCancel(bool sendback); @@ -1645,8 +1417,9 @@ class TC_GAME_API Player : public Unit, public GridObject void AddTimedQuest(uint32 questId) { m_timedquests.insert(questId); } void RemoveTimedQuest(uint32 questId) { m_timedquests.erase(questId); } - void SaveCUFProfile(uint8 id, CUFProfile* profile) { delete _CUFProfiles[id]; _CUFProfiles[id] = profile; } ///> Replaces a CUF profile at position 0-4 - CUFProfile* GetCUFProfile(uint8 id) const { return _CUFProfiles[id]; } ///> Retrieves a CUF profile at position 0-4 + void SaveCUFProfile(uint8 id, std::nullptr_t) { _CUFProfiles[id] = nullptr; } ///> Empties a CUF profile at position 0-4 + void SaveCUFProfile(uint8 id, std::unique_ptr profile) { _CUFProfiles[id] = std::move(profile); } ///> Replaces a CUF profile at position 0-4 + CUFProfile* GetCUFProfile(uint8 id) const { return _CUFProfiles[id].get(); } ///> Retrieves a CUF profile at position 0-4 uint8 GetCUFProfilesCount() const { uint8 count = 0; @@ -1662,7 +1435,7 @@ class TC_GAME_API Player : public Unit, public GridObject /*** LOAD SYSTEM ***/ /*********************************************************/ - bool LoadFromDB(ObjectGuid guid, SQLQueryHolder *holder); + bool LoadFromDB(ObjectGuid guid, SQLQueryHolder* holder); bool IsLoading() const override; void Initialize(ObjectGuid::LowType guid); @@ -1849,8 +1622,8 @@ class TC_GAME_API Player : public Unit, public GridObject void AddSpellMod(SpellModifier* mod, bool apply); static bool IsAffectedBySpellmod(SpellInfo const* spellInfo, SpellModifier* mod, Spell* spell = nullptr); - template - void ApplySpellMod(uint32 spellId, T& basevalue, Spell* spell = nullptr) const; + template + void ApplySpellMod(uint32 spellId, SpellModOp op, T& basevalue, Spell* spell = nullptr) const; static void ApplyModToSpell(SpellModifier* mod, Spell* spell); static bool HasSpellModApplied(SpellModifier* mod, Spell* spell); void SetSpellModTakingSpell(Spell* spell, bool apply); @@ -1864,7 +1637,7 @@ class TC_GAME_API Player : public Unit, public GridObject void ClearResurrectRequestData() { delete _resurrectionData; - _resurrectionData = NULL; + _resurrectionData = nullptr; } bool IsResurrectRequestedBy(ObjectGuid const& guid) const @@ -1875,7 +1648,7 @@ class TC_GAME_API Player : public Unit, public GridObject return _resurrectionData->GUID == guid; } - bool IsResurrectRequested() const { return _resurrectionData != NULL; } + bool IsResurrectRequested() const { return _resurrectionData != nullptr; } void ResurrectUsingRequestData(); uint8 getCinematic() const { return m_cinematic; } @@ -1891,7 +1664,7 @@ class TC_GAME_API Player : public Unit, public GridObject PvPInfo pvpInfo; void UpdatePvPState(bool onlyFFA = false); void SetPvP(bool state) override; - void UpdatePvP(bool state, bool override=false); + void UpdatePvP(bool state, bool override = false); void UpdateZone(uint32 newZone, uint32 newArea); void UpdateArea(uint32 newArea); void SetNeedsZoneUpdate(bool needsUpdate) { m_needsZoneUpdate = needsUpdate; } @@ -1916,7 +1689,7 @@ class TC_GAME_API Player : public Unit, public GridObject 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 = nullptr); + static void RemoveFromGroup(Group* group, ObjectGuid guid, RemoveMethod method = GROUP_REMOVEMETHOD_DEFAULT, ObjectGuid kicker = ObjectGuid::Empty, char const* reason = nullptr); void RemoveFromGroup(RemoveMethod method = GROUP_REMOVEMETHOD_DEFAULT) { RemoveFromGroup(GetGroup(), GetGUID(), method); } void SendUpdateToOutOfRangeGroupMembers(); @@ -1947,7 +1720,7 @@ class TC_GAME_API Player : public Unit, public GridObject Difficulty GetStoredRaidDifficulty() const { return m_raidMapDifficulty; } // only for use in difficulty packet after exiting to raid map void SetDungeonDifficulty(Difficulty dungeon_difficulty) { m_dungeonDifficulty = dungeon_difficulty; } void SetRaidDifficulty(Difficulty raid_difficulty) { m_raidDifficulty = raid_difficulty; } - void StoreRaidMapDifficulty() { m_raidMapDifficulty = GetMap()->GetDifficulty(); } + void StoreRaidMapDifficulty(); bool UpdateSkill(uint32 skill_id, uint32 step); bool UpdateSkillPro(uint16 skillId, int32 chance, uint32 step); @@ -1956,12 +1729,12 @@ class TC_GAME_API Player : public Unit, public GridObject bool UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator = 1); bool UpdateFishingSkill(); - inline void SurveyDigSite() { _archaeology.UseSite(); } - inline void NotifyRequestResearchHistory() { _archaeology.SendResearchHistory(); } - inline bool ArchProjectCompleteable(uint32 projectId) { return _archaeology.ProjectCompleteable(uint16(projectId)); } - inline bool HasArchProject(uint32 projectId) { return _archaeology.ProjectExists(uint16(projectId)); } - inline void CompleteArchProject(uint32 projectId) { _archaeology.CompleteProject(uint16(projectId)); } - inline void SetArchData(struct ArchData *data) { _archaeology.SetArchData(data); } + void SurveyDigSite(); + void NotifyRequestResearchHistory(); + bool ArchProjectCompleteable(uint16 projectId); + bool HasArchProject(uint16 projectId); + void CompleteArchProject(uint16 projectId); + void SetArchData(ArchData const& data); float GetHealthBonusFromStamina(); float GetManaBonusFromIntellect(); @@ -2046,7 +1819,7 @@ class TC_GAME_API Player : public Unit, public GridObject void SendResetFailedNotify(uint32 mapid) const; 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); } + bool UpdatePosition(Position const& pos, bool teleport = false) override { return UpdatePosition(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), teleport); } void ProcessTerrainStatusUpdate(ZLiquidStatus status, Optional const& liquidData) override; void SendMessageToSet(WorldPacket* data, bool self) override { SendMessageToSetInRange(data, GetVisibilityRange(), self); } @@ -2210,7 +1983,7 @@ class TC_GAME_API Player : public Unit, public GridObject void CastItemUseSpell(Item* item, SpellCastTargets const& targets, uint8 cast_count, uint32 glyphIndex); void SendEquipmentSetList(); - void SetEquipmentSet(uint32 index, EquipmentSet eqset); + void SetEquipmentSet(EquipmentSetInfo::EquipmentSetData const& eqset); void DeleteEquipmentSet(uint64 setGuid); void SendInitWorldStates(uint32 zone, uint32 area); @@ -2455,7 +2228,7 @@ class TC_GAME_API Player : public Unit, public GridObject void SetMap(Map* map) override; void ResetMap() override; - bool isAllowedToLoot(const Creature* creature); + bool isAllowedToLoot(Creature const* creature); DeclinedName const* GetDeclinedNames() const { return m_declinedname; } uint8 GetRunesState() const { return m_runes->runeState; } @@ -2484,13 +2257,13 @@ class TC_GAME_API Player : public Unit, public GridObject bool HasAchieved(uint32 achievementId) const; void ResetAchievements(); void ResetAchievementCriteria(AchievementCriteriaTypes type, uint64 miscValue1 = 0, uint64 miscValue2 = 0, bool evenIfCriteriaComplete = false); - void UpdateAchievementCriteria(AchievementCriteriaTypes type, uint64 miscValue1 = 0, uint64 miscValue2 = 0, uint64 miscValue3 = 0, Unit* unit = NULL); + void UpdateAchievementCriteria(AchievementCriteriaTypes type, uint64 miscValue1 = 0, uint64 miscValue2 = 0, uint64 miscValue3 = 0, Unit* unit = nullptr); void StartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry, uint32 timeLost = 0); void RemoveTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry); void CompletedAchievement(AchievementEntry const* entry); bool HasTitle(uint32 bitIndex) const; - bool HasTitle(CharTitlesEntry const* title) const { return HasTitle(title->bit_index); } + bool HasTitle(CharTitlesEntry const* title) const; void SetTitle(CharTitlesEntry const* title, bool lost = false); //bool isActiveObject() const { return true; } @@ -2508,7 +2281,7 @@ class TC_GAME_API Player : public Unit, public GridObject bool IsInWhisperWhiteList(ObjectGuid guid); void RemoveFromWhisperWhiteList(ObjectGuid guid) { WhisperList.remove(guid); } - void ReadMovementInfo(WorldPacket& data, MovementInfo* mi, Movement::ExtraMovementStatusElement* extras = NULL); + void ReadMovementInfo(WorldPacket& data, MovementInfo* mi, Movement::ExtraMovementStatusElement* extras = nullptr); /*! These methods send different packets to the client in apply and unapply case. These methods are only sent to the current unit. @@ -2530,7 +2303,7 @@ class TC_GAME_API Player : public Unit, public GridObject void LockVoidStorage() { RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_VOID_UNLOCKED); } uint8 GetNextVoidStorageFreeSlot() const; uint8 GetNumOfVoidStorageFreeSlots() const; - uint8 AddVoidStorageItem(const VoidStorageItem& item); + uint8 AddVoidStorageItem(VoidStorageItem const& item); void AddVoidStorageItemAtSlot(uint8 slot, const VoidStorageItem& item); void DeleteVoidStorageItem(uint8 slot); bool SwapVoidStorageItem(uint8 oldSlot, uint8 newSlot); @@ -2798,9 +2571,9 @@ class TC_GAME_API Player : public Unit, public GridObject // Recall position WorldLocation m_recall_location; - DeclinedName *m_declinedname; - Runes *m_runes; - EquipmentSets m_EquipmentSets; + DeclinedName* m_declinedname; + Runes* m_runes; + EquipmentSetContainer _equipmentSets; bool CanAlwaysSee(WorldObject const* obj) const override; @@ -2812,7 +2585,7 @@ class TC_GAME_API Player : public Unit, public GridObject bool m_needsZoneUpdate; - CUFProfile* _CUFProfiles[MAX_CUF_PROFILES]; + std::array, MAX_CUF_PROFILES> _CUFProfiles; private: // internal common parts for CanStore/StoreItem functions @@ -2893,119 +2666,10 @@ class TC_GAME_API Player : public Unit, public GridObject WorldLocation _corpseLocation; - Archaeology _archaeology; + Archaeology* _archaeology; }; 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 -void Player::ApplySpellMod(uint32 spellId, T& basevalue, Spell* spell /*= nullptr*/) const -{ - SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId); - if (!spellInfo) - return; - float totalmul = 1.0f; - int32 totalflat = 0; - - // Drop charges for triggering spells instead of triggered ones - if (m_spellModTakingSpell) - spell = m_spellModTakingSpell; - - switch (op) - { - // special case, if a mod makes spell instant, only consume that mod - case SPELLMOD_CASTING_TIME: - { - SpellModifier* modInstantSpell = nullptr; - for (SpellModifier* mod : m_spellMods[op]) - { - if (!IsAffectedBySpellmod(spellInfo, mod, spell)) - continue; - - if (mod->type == SPELLMOD_PCT && basevalue < T(10000) && mod->value <= -100) - { - modInstantSpell = mod; - break; - } - } - - if (modInstantSpell) - { - Player::ApplyModToSpell(modInstantSpell, spell); - basevalue = T(0); - return; - } - break; - } - // special case if two mods apply 100% critical chance, only consume one - case SPELLMOD_CRITICAL_CHANCE: - { - SpellModifier* modCritical = nullptr; - for (SpellModifier* mod : m_spellMods[op]) - { - if (!IsAffectedBySpellmod(spellInfo, mod, spell)) - continue; - - if (mod->type == SPELLMOD_FLAT && mod->value >= 100) - { - modCritical = mod; - break; - } - } - - if (modCritical) - { - Player::ApplyModToSpell(modCritical, spell); - basevalue = T(100); - return; - } - break; - } - default: - break; - } - - for (SpellModifier* mod : m_spellMods[op]) - { - if (!IsAffectedBySpellmod(spellInfo, mod, spell)) - continue; - - switch (mod->type) - { - case SPELLMOD_FLAT: - totalflat += mod->value; - break; - case SPELLMOD_PCT: - { - // skip percent mods with null basevalue (most important for spell mods with charges) - if (basevalue == T(0)) - continue; - - // special case (skip > 10sec spell casts for instant cast setting) - if (op == SPELLMOD_CASTING_TIME && mod->value <= -100 && basevalue >= T(10000)) - continue; - else if (!Player::HasSpellModApplied(mod, spell)) - { - // special case for Surge of Light, don't apply critical chance reduction if other mods not applied (ie procs while casting another spell) - // (Surge of Light is the only PCT_MOD on critical chance) - if (op == SPELLMOD_CRITICAL_CHANCE) - continue; - // special case for Backdraft, dont' apply GCD reduction if cast time reduction wasn't applied (ie when Backlash is consumed first) - // (Backdraft is the only PCT_MOD on global cooldown) - else if (op == SPELLMOD_GLOBAL_COOLDOWN) - continue; - } - - totalmul += CalculatePct(1.0f, mod->value); - break; - } - } - - Player::ApplyModToSpell(mod, spell); - } - basevalue = T(float(basevalue + totalflat) * totalmul); -} - #endif diff --git a/src/server/game/Entities/Player/PlayerTaxi.cpp b/src/server/game/Entities/Player/PlayerTaxi.cpp new file mode 100644 index 00000000000..9193b961327 --- /dev/null +++ b/src/server/game/Entities/Player/PlayerTaxi.cpp @@ -0,0 +1,157 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#include "PlayerTaxi.h" +#include "DBCStores.h" +#include "ObjectMgr.h" +#include "Player.h" +#include + +void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint8 level) +{ + // class specific initial known nodes + switch (chrClass) + { + case CLASS_DEATH_KNIGHT: + { + for (uint8 i = 0; i < TaxiMaskSize; ++i) + m_taximask[i] |= sOldContinentsNodesMask[i]; + break; + } + } + + // race specific initial known nodes: capital and taxi hub masks + switch (race) + { + case RACE_HUMAN: SetTaximaskNode(2); break; // Human + case RACE_ORC: SetTaximaskNode(23); break; // Orc + case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf + case RACE_NIGHTELF: SetTaximaskNode(26); + SetTaximaskNode(27); break; // Night Elf + case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead + case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren + case RACE_GNOME: SetTaximaskNode(6); break; // Gnome + case RACE_TROLL: SetTaximaskNode(23); break; // Troll + case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf + case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei + } + + // new continent starting masks (It will be accessible only at new map) + switch (Player::TeamForRace(race)) + { + case ALLIANCE: SetTaximaskNode(100); break; + case HORDE: SetTaximaskNode(99); break; + } + // level dependent taxi hubs + if (level >= 68) + SetTaximaskNode(213); //Shattered Sun Staging Area +} + +void PlayerTaxi::LoadTaxiMask(std::string const &data) +{ + Tokenizer tokens(data, ' '); + + uint8 index = 0; + for (Tokenizer::const_iterator iter = tokens.begin(); index < TaxiMaskSize && iter != tokens.end(); ++iter, ++index) + { + // load and set bits only for existing taxi nodes + m_taximask[index] = sTaxiNodesMask[index] & atoul(*iter); + } +} + +void PlayerTaxi::AppendTaximaskTo(ByteBuffer& data, bool all) +{ + data << uint32(TaxiMaskSize); + if (all) + { + for (uint8 i = 0; i < TaxiMaskSize; ++i) + data << uint8(sTaxiNodesMask[i]); // all existing nodes + } + else + { + for (uint8 i = 0; i < TaxiMaskSize; ++i) + data << uint8(m_taximask[i]); // known nodes + } +} + +bool PlayerTaxi::LoadTaxiDestinationsFromString(std::string const& values, uint32 team) +{ + ClearTaxiDestinations(); + + Tokenizer Tokenizer(values, ' '); + + for (Tokenizer::const_iterator iter = Tokenizer.begin(); iter != Tokenizer.end(); ++iter) + { + uint32 node = atoul(*iter); + AddTaxiDestination(node); + } + + if (m_TaxiDestinations.empty()) + return true; + + // Check integrity + if (m_TaxiDestinations.size() < 2) + return false; + + for (size_t i = 1; i < m_TaxiDestinations.size(); ++i) + { + uint32 cost; + uint32 path; + sObjectMgr->GetTaxiPath(m_TaxiDestinations[i - 1], m_TaxiDestinations[i], path, cost); + if (!path) + return false; + } + + // can't load taxi path without mount set (quest taxi path?) + if (!sObjectMgr->GetTaxiMountDisplayId(GetTaxiSource(), team, true)) + return false; + + return true; +} + +std::string PlayerTaxi::SaveTaxiDestinationsToString() +{ + if (m_TaxiDestinations.empty()) + return ""; + + std::ostringstream ss; + + for (size_t i = 0; i < m_TaxiDestinations.size(); ++i) + ss << m_TaxiDestinations[i] << ' '; + + return ss.str(); +} + +uint32 PlayerTaxi::GetCurrentTaxiPath() const +{ + if (m_TaxiDestinations.size() < 2) + return 0; + + uint32 path; + uint32 cost; + + sObjectMgr->GetTaxiPath(m_TaxiDestinations[0], m_TaxiDestinations[1], path, cost); + + return path; +} + +std::ostringstream& operator<<(std::ostringstream& ss, PlayerTaxi const& taxi) +{ + for (uint8 i = 0; i < TaxiMaskSize; ++i) + ss << uint32(taxi.m_taximask[i]) << ' '; + return ss; +} diff --git a/src/server/game/Entities/Player/PlayerTaxi.h b/src/server/game/Entities/Player/PlayerTaxi.h new file mode 100644 index 00000000000..dd85475cdfb --- /dev/null +++ b/src/server/game/Entities/Player/PlayerTaxi.h @@ -0,0 +1,84 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef PlayerTaxi_h__ +#define PlayerTaxi_h__ + +#include "DBCEnums.h" +#include "Define.h" +#include +#include + +class ByteBuffer; + +class TC_GAME_API PlayerTaxi +{ + public: + PlayerTaxi() { m_taximask.fill(0); } + ~PlayerTaxi() { } + // Nodes + void InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint8 level); + void LoadTaxiMask(std::string const& data); + + bool IsTaximaskNodeKnown(uint32 nodeidx) const + { + uint8 field = uint8((nodeidx - 1) / 8); + uint32 submask = 1 << ((nodeidx-1) % 8); + return (m_taximask[field] & submask) == submask; + } + bool SetTaximaskNode(uint32 nodeidx) + { + uint8 field = uint8((nodeidx - 1) / 8); + uint32 submask = 1 << ((nodeidx- 1) % 8); + if ((m_taximask[field] & submask) != submask) + { + m_taximask[field] |= submask; + return true; + } + else + return false; + } + void AppendTaximaskTo(ByteBuffer& data, bool all); + + // Destinations + bool LoadTaxiDestinationsFromString(std::string const& values, uint32 team); + std::string SaveTaxiDestinationsToString(); + + void ClearTaxiDestinations() { m_TaxiDestinations.clear(); } + void AddTaxiDestination(uint32 dest) { m_TaxiDestinations.push_back(dest); } + uint32 GetTaxiSource() const { return m_TaxiDestinations.empty() ? 0 : m_TaxiDestinations.front(); } + uint32 GetTaxiDestination() const { return m_TaxiDestinations.size() < 2 ? 0 : m_TaxiDestinations[1]; } + uint32 GetCurrentTaxiPath() const; + uint32 NextTaxiDestination() + { + m_TaxiDestinations.pop_front(); + return GetTaxiDestination(); + } + + std::deque const& GetPath() const { return m_TaxiDestinations; } + bool empty() const { return m_TaxiDestinations.empty(); } + + friend std::ostringstream& operator<<(std::ostringstream& ss, PlayerTaxi const& taxi); + + private: + TaxiMask m_taximask; + std::deque m_TaxiDestinations; +}; + +std::ostringstream& operator<<(std::ostringstream& ss, PlayerTaxi const& taxi); + +#endif // PlayerTaxi_h__ diff --git a/src/server/game/Entities/Player/SocialMgr.cpp b/src/server/game/Entities/Player/SocialMgr.cpp index 59e2d890b58..5ca872ffbb7 100644 --- a/src/server/game/Entities/Player/SocialMgr.cpp +++ b/src/server/game/Entities/Player/SocialMgr.cpp @@ -17,16 +17,17 @@ */ #include "SocialMgr.h" -#include "WorldSession.h" -#include "WorldPacket.h" #include "DatabaseEnv.h" #include "ObjectAccessor.h" #include "Player.h" +#include "RBAC.h" #include "World.h" +#include "WorldPacket.h" #include "WorldSession.h" PlayerSocial::PlayerSocial(): _playerGUID() -{ } +{ +} uint32 PlayerSocial::GetNumberOfSocialsWithFlag(SocialFlag flag) { diff --git a/src/server/game/Entities/Player/SocialMgr.h b/src/server/game/Entities/Player/SocialMgr.h index 4f47bbe6314..4611fe0bb35 100644 --- a/src/server/game/Entities/Player/SocialMgr.h +++ b/src/server/game/Entities/Player/SocialMgr.h @@ -19,9 +19,10 @@ #ifndef __TRINITY_SOCIALMGR_H #define __TRINITY_SOCIALMGR_H -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "Common.h" #include "ObjectGuid.h" +#include class Player; class WorldPacket; diff --git a/src/server/game/Entities/Player/TradeData.cpp b/src/server/game/Entities/Player/TradeData.cpp index bce76f69308..2b3384ad75b 100644 --- a/src/server/game/Entities/Player/TradeData.cpp +++ b/src/server/game/Entities/Player/TradeData.cpp @@ -16,6 +16,7 @@ */ #include "TradeData.h" +#include "Item.h" #include "Player.h" #include "WorldSession.h" diff --git a/src/server/game/Entities/Totem/Totem.cpp b/src/server/game/Entities/Totem/Totem.cpp index 3c14fea8b33..0b4bba5089d 100644 --- a/src/server/game/Entities/Totem/Totem.cpp +++ b/src/server/game/Entities/Totem/Totem.cpp @@ -127,7 +127,7 @@ void Totem::UnSummon(uint32 msTime) if (Group* group = owner->GetGroup()) { - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* target = itr->GetSource(); if (target && target->IsInMap(owner) && group->SameSubGroup(owner, target)) diff --git a/src/server/game/Entities/Transport/Transport.cpp b/src/server/game/Entities/Transport/Transport.cpp index a85bcc4aa53..67567843778 100644 --- a/src/server/game/Entities/Transport/Transport.cpp +++ b/src/server/game/Entities/Transport/Transport.cpp @@ -16,22 +16,24 @@ * with this program. If not, see . */ -#include "Common.h" #include "Transport.h" +#include "CellImpl.h" +#include "Common.h" +#include "DBCStores.h" +#include "GameObjectAI.h" +#include "Log.h" #include "MapManager.h" #include "ObjectMgr.h" #include "PhasingHandler.h" -#include "ScriptMgr.h" -#include "DBCStores.h" -#include "GameObjectAI.h" -#include "Vehicle.h" #include "Player.h" -#include "Cell.h" -#include "CellImpl.h" +#include "ScriptMgr.h" +#include "Spline.h" #include "Totem.h" +#include "UpdateData.h" +#include "Vehicle.h" Transport::Transport() : GameObject(), - _transportInfo(NULL), _isMoving(true), _pendingStop(false), + _transportInfo(nullptr), _isMoving(true), _pendingStop(false), _triggeredArrivalEvent(false), _triggeredDepartureEvent(false), _passengerTeleportItr(_passengers.begin()), _delayedAddModel(false), _delayedTeleport(false) { @@ -97,8 +99,8 @@ bool Transport::Create(ObjectGuid::LowType guidlow, uint32 entry, uint32 mapid, SetGoType(GAMEOBJECT_TYPE_MO_TRANSPORT); SetGoAnimProgress(animprogress); SetName(goinfo->name); - SetWorldRotation(G3D::Quat()); - SetParentRotation(G3D::Quat()); + SetWorldRotation(0.0f, 0.0f, 0.0f, 1.0f); + SetParentRotation(QuaternionData()); m_model = CreateModel(); return true; @@ -280,7 +282,7 @@ void Transport::RemovePassenger(WorldObject* passenger) if (erased || _staticPassengers.erase(passenger)) // static passenger can remove itself in case of grid unload { - passenger->SetTransport(NULL); + passenger->SetTransport(nullptr); passenger->m_movementInfo.transport.Reset(); TC_LOG_DEBUG("entities.transport", "Object %s removed from transport %s.", passenger->GetName().c_str(), GetName().c_str()); @@ -300,7 +302,7 @@ Creature* Transport::CreateNPCPassenger(ObjectGuid::LowType guid, CreatureData c if (!creature->LoadCreatureFromDB(guid, map, false)) { delete creature; - return NULL; + return nullptr; } float x = data->posX; @@ -324,7 +326,7 @@ Creature* Transport::CreateNPCPassenger(ObjectGuid::LowType guid, CreatureData c { TC_LOG_ERROR("entities.transport", "Creature (guidlow %d, entry %d) not created. Suggested coordinates aren't valid (X: %f Y: %f)",creature->GetGUID().GetCounter(),creature->GetEntry(),creature->GetPositionX(),creature->GetPositionY()); delete creature; - return NULL; + return nullptr; } PhasingHandler::InitDbPhaseShift(creature->GetPhaseShift(), data->phaseUseFlags, data->phaseId, data->phaseGroup); @@ -333,7 +335,7 @@ Creature* Transport::CreateNPCPassenger(ObjectGuid::LowType guid, CreatureData c if (!map->AddToMap(creature)) { delete creature; - return NULL; + return nullptr; } _staticPassengers.insert(creature); @@ -349,7 +351,7 @@ GameObject* Transport::CreateGOPassenger(ObjectGuid::LowType guid, GameObjectDat if (!go->LoadGameObjectFromDB(guid, map, false)) { delete go; - return NULL; + return nullptr; } ASSERT(data); @@ -370,7 +372,7 @@ GameObject* Transport::CreateGOPassenger(ObjectGuid::LowType guid, GameObjectDat { TC_LOG_ERROR("entities.transport", "GameObject (guidlow %d, entry %d) not created. Suggested coordinates aren't valid (X: %f Y: %f)", go->GetGUID().GetCounter(), go->GetEntry(), go->GetPositionX(), go->GetPositionY()); delete go; - return NULL; + return nullptr; } PhasingHandler::InitDbPhaseShift(go->GetPhaseShift(), data->phaseUseFlags, data->phaseId, data->phaseGroup); @@ -379,18 +381,18 @@ GameObject* Transport::CreateGOPassenger(ObjectGuid::LowType guid, GameObjectDat if (!map->AddToMap(go)) { delete go; - return NULL; + return nullptr; } _staticPassengers.insert(go); return go; } -TempSummon* Transport::SummonPassenger(uint32 entry, Position const& pos, TempSummonType summonType, SummonPropertiesEntry const* properties /*= NULL*/, uint32 duration /*= 0*/, Unit* summoner /*= NULL*/, uint32 spellId /*= 0*/, uint32 vehId /*= 0*/) +TempSummon* Transport::SummonPassenger(uint32 entry, Position const& pos, TempSummonType summonType, SummonPropertiesEntry const* properties /*= nullptr*/, uint32 duration /*= 0*/, Unit* summoner /*= nullptr*/, uint32 spellId /*= 0*/, uint32 vehId /*= 0*/) { Map* map = FindMap(); if (!map) - return NULL; + return nullptr; uint32 mask = UNIT_MASK_SUMMON; if (properties) @@ -436,11 +438,11 @@ TempSummon* Transport::SummonPassenger(uint32 entry, Position const& pos, TempSu break; } default: - return NULL; + return nullptr; } } - TempSummon* summon = NULL; + TempSummon* summon = nullptr; switch (mask) { case UNIT_MASK_SUMMON: @@ -467,7 +469,7 @@ TempSummon* Transport::SummonPassenger(uint32 entry, Position const& pos, TempSu if (!summon->Create(map->GenerateLowGuid(), map, 0, entry, x, y, z, o, nullptr, vehId)) { delete summon; - return NULL; + return nullptr; } PhasingHandler::InheritPhaseShift(summon, summoner ? static_cast(summoner) : static_cast(this)); @@ -490,7 +492,7 @@ TempSummon* Transport::SummonPassenger(uint32 entry, Position const& pos, TempSu if (!map->AddToMap(summon)) { delete summon; - return NULL; + return nullptr; } _staticPassengers.insert(summon); diff --git a/src/server/game/Entities/Transport/Transport.h b/src/server/game/Entities/Transport/Transport.h index b3bdcae034c..5a65148de6b 100644 --- a/src/server/game/Entities/Transport/Transport.h +++ b/src/server/game/Entities/Transport/Transport.h @@ -66,16 +66,16 @@ class TC_GAME_API Transport : public GameObject, public TransportBase * * @return Summoned creature. */ - TempSummon* SummonPassenger(uint32 entry, Position const& pos, TempSummonType summonType, SummonPropertiesEntry const* properties = NULL, uint32 duration = 0, Unit* summoner = NULL, uint32 spellId = 0, uint32 vehId = 0); + TempSummon* SummonPassenger(uint32 entry, Position const& pos, TempSummonType summonType, SummonPropertiesEntry const* properties = nullptr, uint32 duration = 0, Unit* summoner = nullptr, uint32 spellId = 0, uint32 vehId = 0); /// This method transforms supplied transport offsets into global coordinates - void CalculatePassengerPosition(float& x, float& y, float& z, float* o = NULL) const override + void CalculatePassengerPosition(float& x, float& y, float& z, float* o = nullptr) const override { TransportBase::CalculatePassengerPosition(x, y, z, o, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); } /// This method transforms supplied global coordinates into local offsets - void CalculatePassengerOffset(float& x, float& y, float& z, float* o = NULL) const override + void CalculatePassengerOffset(float& x, float& y, float& z, float* o = nullptr) const override { TransportBase::CalculatePassengerOffset(x, y, z, o, GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation()); } diff --git a/src/server/game/Entities/Unit/StatSystem.cpp b/src/server/game/Entities/Unit/StatSystem.cpp index f26cf8a5ef2..96b7d870249 100644 --- a/src/server/game/Entities/Unit/StatSystem.cpp +++ b/src/server/game/Entities/Unit/StatSystem.cpp @@ -17,13 +17,18 @@ */ #include "Unit.h" -#include "Player.h" -#include "Pet.h" #include "Creature.h" +#include "DBCStores.h" +#include "Item.h" +#include "Pet.h" +#include "Player.h" #include "SharedDefines.h" -#include "SpellAuras.h" #include "SpellAuraEffects.h" +#include "SpellAuras.h" +#include "SpellMgr.h" #include "World.h" +#include +#include inline bool _ModifyUInt32(bool apply, uint32& baseValue, int32& amount) { diff --git a/src/server/game/Entities/Unit/Unit.cpp b/src/server/game/Entities/Unit/Unit.cpp index c827b31c517..2a9fa53de87 100644 --- a/src/server/game/Entities/Unit/Unit.cpp +++ b/src/server/game/Entities/Unit/Unit.cpp @@ -17,57 +17,59 @@ */ #include "Unit.h" -#include "CharacterCache.h" -#include "Common.h" #include "Battlefield.h" #include "BattlefieldMgr.h" #include "Battleground.h" #include "BattlegroundScore.h" #include "CellImpl.h" +#include "CharacterCache.h" #include "Chat.h" #include "ChatTextBuilder.h" +#include "Common.h" #include "ConditionMgr.h" #include "CreatureAI.h" #include "CreatureAIImpl.h" #include "CreatureGroups.h" -#include "Creature.h" #include "Formulas.h" #include "GameTime.h" #include "GridNotifiersImpl.h" #include "Group.h" #include "InstanceSaveMgr.h" #include "InstanceScript.h" +#include "Item.h" #include "Log.h" +#include "LootMgr.h" +#include "MotionMaster.h" +#include "MovementStructures.h" #include "MoveSpline.h" +#include "MoveSplineInit.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Opcodes.h" #include "OutdoorPvP.h" #include "PassiveAI.h" -#include "PetAI.h" #include "Pet.h" +#include "PetAI.h" #include "PhasingHandler.h" #include "Player.h" #include "PlayerAI.h" #include "QuestDef.h" #include "ReputationMgr.h" +#include "Spell.h" #include "SpellAuraEffects.h" #include "SpellAuras.h" -#include "Spell.h" -#include "SpellInfo.h" #include "SpellHistory.h" +#include "SpellInfo.h" #include "SpellMgr.h" #include "TemporarySummon.h" -#include "Transport.h" #include "Totem.h" +#include "Transport.h" #include "UpdateFieldFlags.h" #include "Util.h" #include "Vehicle.h" #include "World.h" #include "WorldPacket.h" -#include "MovementStructures.h" #include "WorldSession.h" - #include float baseMoveSpeed[MAX_MOVE_TYPE] = @@ -263,13 +265,26 @@ SpellSchoolMask ProcEventInfo::GetSchoolMask() const return SPELL_SCHOOL_MASK_NONE; } +DispelableAura::DispelableAura(Aura* aura, int32 dispelChance, uint8 dispelCharges) : + _aura(aura), _chance(dispelChance), _charges(dispelCharges) +{ +} + +DispelableAura::~DispelableAura() = default; + +bool DispelableAura::RollDispel() const +{ + return roll_chance_i(_chance); +} + + Unit::Unit(bool isWorldObject) : - WorldObject(isWorldObject), m_playerMovingMe(NULL), m_lastSanctuaryTime(0), + WorldObject(isWorldObject), m_playerMovingMe(nullptr), m_lastSanctuaryTime(0), IsAIEnabled(false), NeedChangeAI(false), LastCharmerGUID(), m_ControlledByPlayer(false), movespline(new Movement::MoveSpline()), - i_AI(NULL), i_disabledAI(NULL), m_AutoRepeatFirstCast(false), m_procDeep(0), + i_AI(nullptr), i_disabledAI(nullptr), m_AutoRepeatFirstCast(false), m_procDeep(0), m_removedAurasCount(0), i_motionMaster(new MotionMaster(this)), m_regenTimer(0), m_ThreatManager(this), - m_vehicle(NULL), m_vehicleKit(NULL), m_unitTypeMask(UNIT_MASK_NONE), + m_vehicle(nullptr), m_vehicleKit(nullptr), m_unitTypeMask(UNIT_MASK_NONE), m_Diminishing(), m_HostileRefManager(this), _lastDamagedTime(0), m_spellHistory(new SpellHistory(this)) { m_objectType |= TYPEMASK_UNIT; @@ -293,7 +308,7 @@ Unit::Unit(bool isWorldObject) : m_deathState = ALIVE; for (uint8 i = 0; i < CURRENT_MAX_SPELL; ++i) - m_currentSpells[i] = NULL; + m_currentSpells[i] = nullptr; for (uint8 i = 0; i < MAX_SUMMON_SLOT; ++i) m_SummonSlot[i].Clear(); @@ -353,7 +368,7 @@ Unit::Unit(bool isWorldObject) : m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_ALIVE); - _lastLiquid = NULL; + _lastLiquid = nullptr; _oldFactionId = 0; _isWalkingBeforeCharm = false; @@ -539,7 +554,7 @@ void Unit::resetAttackTimer(WeaponAttackType type) m_attackTimer[type] = uint32(GetAttackTime(type) * m_modAttackSpeedPct[type]); } -bool Unit::IsWithinCombatRange(const Unit* obj, float dist2compare) const +bool Unit::IsWithinCombatRange(Unit const* obj, float dist2compare) const { if (!obj || !IsInMap(obj) || !IsInPhase(obj)) return false; @@ -586,7 +601,7 @@ bool Unit::IsWithinBoundaryRadius(const Unit* obj) const return IsInDist(obj, objBoundaryRadius); } -void Unit::GetRandomContactPoint(const Unit* obj, float &x, float &y, float &z, float distance2dMin, float distance2dMax) const +void Unit::GetRandomContactPoint(Unit const* obj, float &x, float &y, float &z, float distance2dMin, float distance2dMax) const { float combat_reach = GetCombatReach(); if (combat_reach < 0.1f) // sometimes bugged for players @@ -655,7 +670,7 @@ bool Unit::HasBreakableByDamageAuraType(AuraType type, uint32 excludeAura) const bool Unit::HasBreakableByDamageCrowdControlAura(Unit* excludeCasterChannel) const { uint32 excludeAura = 0; - if (Spell* currentChanneledSpell = excludeCasterChannel ? excludeCasterChannel->GetCurrentSpell(CURRENT_CHANNELED_SPELL) : NULL) + if (Spell* currentChanneledSpell = excludeCasterChannel ? excludeCasterChannel->GetCurrentSpell(CURRENT_CHANNELED_SPELL) : nullptr) excludeAura = currentChanneledSpell->GetSpellInfo()->Id; //Avoid self interrupt of channeled Crowd Control spells like Seduction return ( HasBreakableByDamageAuraType(SPELL_AURA_MOD_CONFUSE, excludeAura) @@ -744,8 +759,8 @@ uint32 Unit::DealDamage(Unit* victim, uint32 damage, CleanDamage const* cleanDam uint32 share = CalculatePct(damage, (*i)->GetAmount()); /// @todo check packets if damage is done by victim, or by attacker of victim - DealDamageMods(shareDamageTarget, share, NULL); - DealDamage(shareDamageTarget, share, NULL, NODAMAGE, spell->GetSchoolMask(), spell, false); + DealDamageMods(shareDamageTarget, share, nullptr); + DealDamage(shareDamageTarget, share, nullptr, NODAMAGE, spell->GetSchoolMask(), spell, false); } } @@ -915,7 +930,7 @@ uint32 Unit::DealDamage(Unit* victim, uint32 damage, CleanDamage const* cleanDam ASSERT(he && he->duel); - if (duel_wasMounted) // In this case victim==mount + if (duel_wasMounted) // In this case victim == mount victim->SetHealth(1); else he->SetHealth(1); @@ -1109,7 +1124,7 @@ void Unit::CalculateSpellDamageTaken(SpellNonMeleeDamage* damageInfo, int32 dama uint32 crit_bonus = damage; // Apply crit_damage bonus for melee spells if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellInfo->Id, crit_bonus); + modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus); damage += crit_bonus; // Apply SPELL_AURA_MOD_ATTACKER_RANGED_CRIT_DAMAGE or SPELL_AURA_MOD_ATTACKER_MELEE_CRIT_DAMAGE @@ -1201,7 +1216,7 @@ void Unit::DealSpellDamage(SpellNonMeleeDamage* damageInfo, bool durabilityLoss) return; SpellInfo const* spellProto = sSpellMgr->GetSpellInfo(damageInfo->SpellID); - if (spellProto == NULL) + if (spellProto == nullptr) { TC_LOG_DEBUG("entities.unit", "Unit::DealSpellDamage has wrong damageInfo->SpellID: %u", damageInfo->SpellID); return; @@ -1275,7 +1290,7 @@ void Unit::CalculateMeleeDamage(Unit* victim, uint32 damage, CalcDamageInfo* dam // Calculate armor reduction if (IsDamageReducedByArmor((SpellSchoolMask)(damageInfo->damageSchoolMask))) { - damageInfo->damage = CalcArmorReducedDamage(damageInfo->target, damage, NULL, damageInfo->attackType); + damageInfo->damage = CalcArmorReducedDamage(damageInfo->target, damage, nullptr, damageInfo->attackType); damageInfo->cleanDamage += damage - damageInfo->damage; } else @@ -1441,7 +1456,7 @@ void Unit::DealMeleeDamage(CalcDamageInfo* damageInfo, bool durabilityLoss) // Call default DealDamage CleanDamage cleanDamage(damageInfo->cleanDamage, damageInfo->absorb, damageInfo->attackType, damageInfo->hitOutCome); - DealDamage(victim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->damageSchoolMask), NULL, durabilityLoss); + DealDamage(victim, damageInfo->damage, &cleanDamage, DIRECT_DAMAGE, SpellSchoolMask(damageInfo->damageSchoolMask), nullptr, durabilityLoss); // If this is a creature and it attacks from behind it has a probability to daze it's victim if ((damageInfo->hitOutCome == MELEE_HIT_CRIT || damageInfo->hitOutCome == MELEE_HIT_CRUSHING || damageInfo->hitOutCome == MELEE_HIT_NORMAL || damageInfo->hitOutCome == MELEE_HIT_GLANCING) && @@ -1537,7 +1552,7 @@ void Unit::HandleEmoteCommand(uint32 anim_id) SendMessageToSet(&data, true); } -bool Unit::IsDamageReducedByArmor(SpellSchoolMask schoolMask, SpellInfo const* spellInfo, uint8 effIndex) +bool Unit::IsDamageReducedByArmor(SpellSchoolMask schoolMask, SpellInfo const* spellInfo /*= nullptr*/, int8 effIndex /*= -1*/) { // only physical spells damage gets reduced by armor if ((schoolMask & SPELL_SCHOOL_MASK_NORMAL) == 0) @@ -1549,7 +1564,7 @@ bool Unit::IsDamageReducedByArmor(SpellSchoolMask schoolMask, SpellInfo const* s return false; // bleeding effects are not reduced by armor - if (effIndex != MAX_SPELL_EFFECTS) + if (effIndex != -1) { if (spellInfo->Effects[effIndex].ApplyAuraName == SPELL_AURA_PERIODIC_DAMAGE || spellInfo->Effects[effIndex].Effect == SPELL_EFFECT_SCHOOL_DAMAGE) @@ -1577,7 +1592,7 @@ uint32 Unit::CalcArmorReducedDamage(Unit* victim, const uint32 damage, SpellInfo if (spellInfo) if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellInfo->Id, armor); + modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_IGNORE_ARMOR, armor); AuraEffectList const& resIgnoreAuras = GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_TARGET_RESIST); for (AuraEffectList::const_iterator j = resIgnoreAuras.begin(); j != resIgnoreAuras.end(); ++j) @@ -2530,7 +2545,7 @@ SpellMissInfo Unit::MagicSpellHitResult(Unit* victim, SpellInfo const* spellInfo // Spellmod from SPELLMOD_RESIST_MISS_CHANCE if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellInfo->Id, modHitChance); + modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_RESIST_MISS_CHANCE, modHitChance); // Spells with SPELL_ATTR3_IGNORE_HIT_RESULT will ignore target's avoidance effects if (!spellInfo->HasAttribute(SPELL_ATTR3_IGNORE_HIT_RESULT)) @@ -2801,7 +2816,7 @@ void Unit::_UpdateSpells(uint32 time) if (m_currentSpells[i] && m_currentSpells[i]->getState() == SPELL_STATE_FINISHED) { m_currentSpells[i]->SetReferencedFromCurrent(false); - m_currentSpells[i] = NULL; // remove pointer + m_currentSpells[i] = nullptr; // remove pointer } } @@ -2850,7 +2865,7 @@ void Unit::_UpdateSpells(uint32 time) void Unit::_UpdateAutoRepeatSpell() { - const SpellInfo* autoRepeatSpellInfo = m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo; + SpellInfo const* autoRepeatSpellInfo = m_currentSpells[CURRENT_AUTOREPEAT_SPELL]->m_spellInfo; // check "realtime" interrupts // don't cancel spells which are affected by a SPELL_AURA_CAST_WHILE_WALKING effect @@ -2895,7 +2910,7 @@ void Unit::_UpdateAutoRepeatSpell() void Unit::SetCurrentCastSpell(Spell* pSpell) { - ASSERT(pSpell); // NULL may be never passed here, use InterruptSpell or InterruptNonMeleeSpells + ASSERT(pSpell); // nullptr may be never passed here, use InterruptSpell or InterruptNonMeleeSpells CurrentSpellTypes CSpellType = pSpell->GetCurrentContainer(); @@ -3060,7 +3075,7 @@ Spell* Unit::FindCurrentSpellBySpellId(uint32 spell_id) const for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++) if (m_currentSpells[i] && m_currentSpells[i]->m_spellInfo->Id == spell_id) return m_currentSpells[i]; - return NULL; + return nullptr; } int32 Unit::GetCurrentSpellCastTime(uint32 spell_id) const @@ -3264,7 +3279,7 @@ AuraApplication * Unit::_CreateAuraApplication(Aura* aura, uint8 effMask) // ghost spell check, allow apply any auras at player loading in ghost mode (will be cleanup after load) if (!IsAlive() && !aurSpellInfo->IsDeathPersistent() && (GetTypeId() != TYPEID_PLAYER || !ToPlayer()->GetSession()->PlayerLoading())) - return NULL; + return nullptr; Unit* caster = aura->GetCaster(); @@ -3557,7 +3572,7 @@ Aura* Unit::GetOwnedAura(uint32 spellId, ObjectGuid casterGUID, ObjectGuid itemC return itr->second; } } - return NULL; + return nullptr; } void Unit::RemoveAura(AuraApplicationMap::iterator &i, AuraRemoveMode mode) @@ -4221,7 +4236,7 @@ AuraEffect* Unit::GetAuraEffect(uint32 spellId, uint8 effIndex, ObjectGuid caste return itr->second->GetBase()->GetEffect(effIndex); } } - return NULL; + return nullptr; } AuraEffect* Unit::GetAuraEffectOfRankedSpell(uint32 spellId, uint8 effIndex, ObjectGuid caster) const @@ -4233,7 +4248,7 @@ AuraEffect* Unit::GetAuraEffectOfRankedSpell(uint32 spellId, uint8 effIndex, Obj return aurEff; rankSpell = sSpellMgr->GetNextSpellInChain(rankSpell); } - return NULL; + return nullptr; } AuraEffect* Unit::GetAuraEffect(AuraType type, SpellFamilyNames name, uint32 iconId, uint8 effIndex) const @@ -4247,7 +4262,7 @@ AuraEffect* Unit::GetAuraEffect(AuraType type, SpellFamilyNames name, uint32 ico if (spell->SpellIconID == iconId && spell->SpellFamilyName == uint32(name) && !spell->SpellFamilyFlags) return *itr; } - return NULL; + return nullptr; } AuraEffect* Unit::GetAuraEffect(AuraType type, SpellFamilyNames family, uint32 familyFlag1, uint32 familyFlag2, uint32 familyFlag3, ObjectGuid casterGUID) const @@ -4263,7 +4278,7 @@ AuraEffect* Unit::GetAuraEffect(AuraType type, SpellFamilyNames family, uint32 f return (*i); } } - return NULL; + return nullptr; } AuraEffect* Unit::GetDummyAuraEffect(SpellFamilyNames name, uint32 iconId, uint8 effIndex) const @@ -4287,13 +4302,13 @@ AuraApplication * Unit::GetAuraApplication(uint32 spellId, ObjectGuid casterGUID return app; } } - return NULL; + return nullptr; } Aura* Unit::GetAura(uint32 spellId, ObjectGuid casterGUID, ObjectGuid itemCasterGUID, uint8 reqEffMask) const { AuraApplication * aurApp = GetAuraApplication(spellId, casterGUID, itemCasterGUID, reqEffMask); - return aurApp ? aurApp->GetBase() : NULL; + return aurApp ? aurApp->GetBase() : nullptr; } AuraApplication * Unit::GetAuraApplicationOfRankedSpell(uint32 spellId, ObjectGuid casterGUID, ObjectGuid itemCasterGUID, uint8 reqEffMask, AuraApplication* except) const @@ -4305,13 +4320,13 @@ AuraApplication * Unit::GetAuraApplicationOfRankedSpell(uint32 spellId, ObjectGu return aurApp; rankSpell = sSpellMgr->GetNextSpellInChain(rankSpell); } - return NULL; + return nullptr; } Aura* Unit::GetAuraOfRankedSpell(uint32 spellId, ObjectGuid casterGUID, ObjectGuid itemCasterGUID, uint8 reqEffMask) const { AuraApplication * aurApp = GetAuraApplicationOfRankedSpell(spellId, casterGUID, itemCasterGUID, reqEffMask); - return aurApp ? aurApp->GetBase() : NULL; + return aurApp ? aurApp->GetBase() : nullptr; } void Unit::GetDispellableAuraList(Unit* caster, uint32 dispelMask, DispelChargesList& dispelList, bool isReflect /*= false*/) const @@ -4492,7 +4507,7 @@ AuraEffect* Unit::IsScriptOverriden(SpellInfo const* spell, int32 script) const if ((*i)->IsAffectingSpell(spell)) return (*i); } - return NULL; + return nullptr; } uint32 Unit::GetDiseasesByCaster(ObjectGuid casterGUID, bool remove) @@ -5684,7 +5699,7 @@ void Unit::ModifyAuraState(AuraStateType flag, bool apply) if (!spellInfo || !spellInfo->IsPassive()) continue; if (spellInfo->CasterAuraState == uint32(flag)) - CastSpell(this, itr->first, true, NULL); + CastSpell(this, itr->first, true, nullptr); } } else if (Pet* pet = ToCreature()->ToPet()) @@ -5697,7 +5712,7 @@ void Unit::ModifyAuraState(AuraStateType flag, bool apply) if (!spellInfo || !spellInfo->IsPassive()) continue; if (spellInfo->CasterAuraState == uint32(flag)) - CastSpell(this, itr->first, true, NULL); + CastSpell(this, itr->first, true, nullptr); } } } @@ -5789,7 +5804,7 @@ Unit* Unit::GetOwner() const if (ObjectGuid ownerGUID = GetOwnerGUID()) return ObjectAccessor::GetUnit(*this, ownerGUID); - return NULL; + return nullptr; } Unit* Unit::GetCharmer() const @@ -5817,7 +5832,7 @@ Player* Unit::GetAffectingPlayer() const if (Unit* owner = GetCharmerOrOwner()) return owner->GetCharmerOrOwnerPlayerOrPlayerItself(); - return NULL; + return nullptr; } Minion* Unit::GetFirstMinion() const @@ -5832,7 +5847,7 @@ Minion* Unit::GetFirstMinion() const const_cast(this)->SetMinionGUID(ObjectGuid::Empty); } - return NULL; + return nullptr; } Guardian* Unit::GetGuardianPet() const @@ -5847,7 +5862,7 @@ Guardian* Unit::GetGuardianPet() const const_cast(this)->SetPetGUID(ObjectGuid::Empty); } - return NULL; + return nullptr; } Unit* Unit::GetCharm() const @@ -5861,7 +5876,7 @@ Unit* Unit::GetCharm() const const_cast(this)->SetGuidValue(UNIT_FIELD_CHARM, ObjectGuid::Empty); } - return NULL; + return nullptr; } Unit* Unit::GetCharmerOrOwner() const @@ -6282,7 +6297,7 @@ bool Unit::isPossessing() const Unit* Unit::GetNextRandomRaidMemberOrPet(float radius) { - Player* player = NULL; + Player* player = nullptr; if (GetTypeId() == TYPEID_PLAYER) player = ToPlayer(); // Should we enable this also for charmed units? @@ -6290,27 +6305,27 @@ Unit* Unit::GetNextRandomRaidMemberOrPet(float radius) player = GetOwner()->ToPlayer(); if (!player) - return NULL; + return nullptr; Group* group = player->GetGroup(); // When there is no group check pet presence if (!group) { // We are pet now, return owner if (player != this) - return IsWithinDistInMap(player, radius) ? player : NULL; + return IsWithinDistInMap(player, radius) ? player : nullptr; Unit* pet = GetGuardianPet(); // No pet, no group, nothing to return if (!pet) - return NULL; + return nullptr; // We are owner now, return pet - return IsWithinDistInMap(pet, radius) ? pet : NULL; + return IsWithinDistInMap(pet, radius) ? pet : nullptr; } std::vector nearMembers; // reserve place for players and pets because resizing vector every unit push is unefficient (vector is reallocated then) nearMembers.reserve(group->GetMembersCount() * 2); - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) if (Player* Target = itr->GetSource()) { // IsHostileTo check duel and controlled by enemy @@ -6324,7 +6339,7 @@ Unit* Unit::GetNextRandomRaidMemberOrPet(float radius) } if (nearMembers.empty()) - return NULL; + return nullptr; uint32 randTarget = urand(0, nearMembers.size()-1); return nearMembers[randTarget]; @@ -6534,7 +6549,7 @@ uint32 Unit::SpellDamageBonusDone(Unit* victim, SpellInfo const* spellProto, uin if (Player* modOwner = GetSpellModOwner()) { coeff *= 100.0f; - modOwner->ApplySpellMod(spellProto->Id, coeff); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_BONUS_MULTIPLIER, coeff); coeff /= 100.0f; } DoneTotal += int32(DoneAdvertisedBenefit * coeff * stack); @@ -6550,7 +6565,7 @@ uint32 Unit::SpellDamageBonusDone(Unit* victim, SpellInfo const* spellProto, uin // apply spellmod to Done damage (flat and pct) if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellProto->Id, tmpDamage); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, tmpDamage); } return uint32(std::max(tmpDamage, 0.0f)); @@ -6827,7 +6842,7 @@ uint32 Unit::SpellDamageBonusTaken(Unit* caster, SpellInfo const* spellProto, ui if (Player* modOwner = GetSpellModOwner()) { coeff *= 100.0f; - modOwner->ApplySpellMod(spellProto->Id, coeff); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_BONUS_MULTIPLIER, coeff); coeff /= 100.0f; } TakenTotal += int32(TakenAdvertisedBenefit * coeff * stack); @@ -7111,7 +7126,7 @@ float Unit::GetUnitSpellCriticalChance(Unit* victim, SpellInfo const* spellProto // percent done // only players use intelligence for critical chance computations if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellProto->Id, crit_chance); + 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) @@ -7163,7 +7178,7 @@ uint32 Unit::SpellCriticalDamageBonus(SpellInfo const* spellProto, uint32 damage { // adds additional damage to critBonus (from talents) if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellProto->Id, crit_bonus); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_CRIT_DAMAGE_BONUS, crit_bonus); } crit_bonus += damage; @@ -7279,7 +7294,7 @@ uint32 Unit::SpellHealingBonusDone(Unit* victim, SpellInfo const* spellProto, ui if (Player* modOwner = GetSpellModOwner()) { coeff *= 100.0f; - modOwner->ApplySpellMod(spellProto->Id, coeff); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_BONUS_MULTIPLIER, coeff); coeff /= 100.0f; } @@ -7310,7 +7325,7 @@ uint32 Unit::SpellHealingBonusDone(Unit* victim, SpellInfo const* spellProto, ui // apply spellmod to Done amount if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellProto->Id, heal); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, heal); } return uint32(std::max(heal, 0.0f)); @@ -7455,7 +7470,7 @@ uint32 Unit::SpellHealingBonusTaken(Unit* caster, SpellInfo const* spellProto, u if (Player* modOwner = GetSpellModOwner()) { coeff *= 100.0f; - modOwner->ApplySpellMod(spellProto->Id, coeff); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_BONUS_MULTIPLIER, coeff); coeff /= 100.0f; } @@ -7801,7 +7816,7 @@ uint32 Unit::MeleeDamageBonusDone(Unit* victim, uint32 pdamage, WeaponAttackType // apply spellmod to Done damage if (spellProto) if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellProto->Id, tmpDamage); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, tmpDamage); // bonus result can be negative return uint32(std::max(tmpDamage, 0.0f)); @@ -7957,7 +7972,7 @@ float Unit::GetWeaponProcChance() const return 0; } -float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM, const SpellInfo* spellProto) const +float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM, SpellInfo const* spellProto) const { // proc per minute chance calculation if (PPM <= 0) @@ -7966,7 +7981,7 @@ float Unit::GetPPMProcChance(uint32 WeaponSpeed, float PPM, const SpellInfo* spe // Apply chance modifer aura if (spellProto) if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellProto->Id, PPM); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_PROC_PER_MINUTE, PPM); return std::floor((WeaponSpeed * PPM) / 600.0f); // result is chance in percents (probability = Speed_in_sec * (PPM / 60)) } @@ -8334,7 +8349,7 @@ bool Unit::isTargetableForAttack(bool checkFakeDeath) const bool Unit::IsValidAttackTarget(Unit const* target) const { - return _IsValidAttackTarget(target, NULL); + return _IsValidAttackTarget(target, nullptr); } // function based on function Unit::CanAttack from 13850 client @@ -8465,7 +8480,7 @@ bool Unit::_IsValidAttackTarget(Unit const* target, SpellInfo const* bySpell, Wo bool Unit::IsValidAssistTarget(Unit const* target) const { - return _IsValidAssistTarget(target, NULL); + return _IsValidAssistTarget(target, nullptr); } // function based on function Unit::CanAssist from 13850 client @@ -9228,17 +9243,17 @@ float Unit::ApplyEffectModifiers(SpellInfo const* spellProto, uint8 effect_index { if (Player* modOwner = GetSpellModOwner()) { - modOwner->ApplySpellMod(spellProto->Id, value); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_ALL_EFFECTS, value); switch (effect_index) { case EFFECT_0: - modOwner->ApplySpellMod(spellProto->Id, value); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT1, value); break; case EFFECT_1: - modOwner->ApplySpellMod(spellProto->Id, value); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT2, value); break; case EFFECT_2: - modOwner->ApplySpellMod(spellProto->Id, value); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT3, value); break; } } @@ -9367,7 +9382,7 @@ void Unit::ModSpellCastTime(SpellInfo const* spellInfo, int32 & castTime, Spell* // called from caster if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellInfo->Id, castTime, spell); + modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CASTING_TIME, castTime, spell); float castSpeedMod = 1; castSpeedMod = castSpeedMod - GetTotalAuraMultiplier(SPELL_AURA_HASTE_SPELLS) + 1.0f; @@ -9391,7 +9406,7 @@ void Unit::ModSpellDurationTime(SpellInfo const* spellInfo, int32 & duration, Sp // called from caster if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellInfo->Id, duration, spell); + modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_CASTING_TIME, duration, spell); if (!(spellInfo->HasAttribute(SPELL_ATTR0_ABILITY) || spellInfo->HasAttribute(SPELL_ATTR0_TRADESPELL) || spellInfo->HasAttribute(SPELL_ATTR3_NO_DONE_BONUS)) && ((GetTypeId() == TYPEID_PLAYER && spellInfo->SpellFamilyName) || GetTypeId() == TYPEID_UNIT)) @@ -9502,8 +9517,8 @@ void Unit::ApplyDiminishingAura(DiminishingGroup group, bool apply) void Unit::ClearDiminishings() { - for (uint32 i = 0; i < DIMINISHING_MAX; ++i) - m_Diminishing[i].Clear(); + for (DiminishingReturn& dim : m_Diminishing) + dim.Clear(); } float Unit::GetSpellMaxRangeForTarget(Unit const* target, SpellInfo const* spellInfo) const @@ -10186,7 +10201,7 @@ void Unit::DeleteCharmInfo() m_charmInfo->RestoreState(); delete m_charmInfo; - m_charmInfo = NULL; + m_charmInfo = nullptr; } CharmInfo::CharmInfo(Unit* unit) @@ -10738,7 +10753,7 @@ void Unit::SendPetActionFeedback(uint8 msg) WorldPacket data(SMSG_PET_ACTION_FEEDBACK, 1); data << uint8(msg); - owner->ToPlayer()->GetSession()->SendPacket(&data); + owner->ToPlayer()->SendDirectMessage(&data); } void Unit::SendPetTalk(uint32 pettalk) @@ -10750,7 +10765,7 @@ void Unit::SendPetTalk(uint32 pettalk) WorldPacket data(SMSG_PET_ACTION_SOUND, 8 + 4); data << uint64(GetGUID()); data << uint32(pettalk); - owner->ToPlayer()->GetSession()->SendPacket(&data); + owner->ToPlayer()->SendDirectMessage(&data); } void Unit::SendPetAIReaction(ObjectGuid guid) @@ -10762,11 +10777,16 @@ void Unit::SendPetAIReaction(ObjectGuid guid) WorldPacket data(SMSG_AI_REACTION, 8 + 4); data << uint64(guid); data << uint32(AI_REACTION_HOSTILE); - owner->ToPlayer()->GetSession()->SendPacket(&data); + owner->ToPlayer()->SendDirectMessage(&data); } ///----------End of Pet responses methods---------- +void Unit::PropagateSpeedChange() +{ + GetMotionMaster()->PropagateSpeedChange(); +} + void Unit::StopMoving() { ClearUnitState(UNIT_STATE_MOVING); @@ -10807,7 +10827,7 @@ void Unit::SetStandState(uint8 state) { WorldPacket data(SMSG_STANDSTATE_UPDATE, 1); data << (uint8)state; - ToPlayer()->GetSession()->SendPacket(&data); + ToPlayer()->SendDirectMessage(&data); } } @@ -10966,7 +10986,7 @@ Unit* Unit::SelectNearbyTarget(Unit* exclude, float dist) const // no appropriate targets if (targets.empty()) - return NULL; + return nullptr; // select random return Trinity::Containers::SelectRandomContainerElement(targets); @@ -11283,14 +11303,14 @@ void Unit::SetContestedPvP(Player* attackedPlayer) Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget, uint32 spell_id) { if (GetTypeId() != TYPEID_PLAYER) - return NULL; + return nullptr; Pet* pet = new Pet(ToPlayer(), HUNTER_PET); if (!pet->CreateBaseAtCreature(creatureTarget)) { delete pet; - return NULL; + return nullptr; } uint8 level = creatureTarget->getLevel() + 5 < getLevel() ? (getLevel() - 5) : creatureTarget->getLevel(); @@ -11303,18 +11323,18 @@ Pet* Unit::CreateTamedPetFrom(Creature* creatureTarget, uint32 spell_id) Pet* Unit::CreateTamedPetFrom(uint32 creatureEntry, uint32 spell_id) { if (GetTypeId() != TYPEID_PLAYER) - return NULL; + return nullptr; CreatureTemplate const* creatureInfo = sObjectMgr->GetCreatureTemplate(creatureEntry); if (!creatureInfo) - return NULL; + return nullptr; Pet* pet = new Pet(ToPlayer(), HUNTER_PET); if (!pet->CreateBaseAtCreatureInfo(creatureInfo, this) || !InitTamedPet(pet, getLevel(), spell_id)) { delete pet; - return NULL; + return nullptr; } return pet; @@ -11349,7 +11369,7 @@ void Unit::SendDurabilityLoss(Player* receiver, uint32 percent) { WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 4); data << uint32(percent); - receiver->GetSession()->SendPacket(&data); + receiver->SendDirectMessage(&data); } void Unit::PlayOneShotAnimKitId(uint16 animKitId) @@ -11375,7 +11395,7 @@ void Unit::Kill(Unit* victim, bool durabilityLoss) { isRewardAllowed = creature->IsDamageEnoughForLootingAndReward(); if (!isRewardAllowed) - creature->SetLootRecipient(NULL); + creature->SetLootRecipient(nullptr); } if (isRewardAllowed && creature && creature->GetLootRecipient()) @@ -11445,7 +11465,7 @@ void Unit::Kill(Unit* victim, bool durabilityLoss) if (hasLooterGuid) group->SendLooter(creature, looter); else - group->SendLooter(creature, NULL); + group->SendLooter(creature, nullptr); // Update round robin looter only if the creature had loot if (!loot->empty()) @@ -11515,7 +11535,7 @@ void Unit::Kill(Unit* victim, bool durabilityLoss) { // remember victim PvP death for corpse type and corpse reclaim delay // at original death (not at SpiritOfRedemtionTalent timeout) - plrVictim->SetPvPDeath(player != NULL); + plrVictim->SetPvPDeath(player != nullptr); // only if not player and not controlled by player pet. And not at BG if ((durabilityLoss && !player && !victim->ToPlayer()->InBattleground()) || (player && sWorld->getBoolConfig(CONFIG_DURABILITY_LOSS_IN_PVP))) @@ -11807,13 +11827,13 @@ void Unit::SetFeared(bool apply) { SetTarget(ObjectGuid::Empty); - Unit* caster = NULL; + Unit* caster = nullptr; Unit::AuraEffectList const& fearAuras = GetAuraEffectsByType(SPELL_AURA_MOD_FEAR); if (!fearAuras.empty()) caster = ObjectAccessor::GetUnit(*this, fearAuras.front()->GetCasterGUID()); if (!caster) caster = getAttackerForHelper(); - GetMotionMaster()->MoveFleeing(caster, fearAuras.empty() ? sWorld->getIntConfig(CONFIG_CREATURE_FAMILY_FLEE_DELAY) : 0); // caster == NULL processed in MoveFleeing + GetMotionMaster()->MoveFleeing(caster, fearAuras.empty() ? sWorld->getIntConfig(CONFIG_CREATURE_FAMILY_FLEE_DELAY) : 0); // caster == nullptr processed in MoveFleeing } else { @@ -11999,7 +12019,7 @@ bool Unit::SetCharmedBy(Unit* charmer, CharmType type, AuraApplication const* au GetCharmInfo()->SetPetNumber(sObjectMgr->GeneratePetNumber(), true); // if charmed two demons the same session, the 2nd gets the 1st one's name - SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(NULL))); // cast can't be helped + SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(nullptr))); // cast can't be helped } } playerCharmer->CharmSpellInitialize(); @@ -12146,7 +12166,7 @@ void Unit::RestoreFaction() Unit* Unit::GetRedirectThreatTarget() { - return _redirectThreadInfo.GetTargetGUID() ? ObjectAccessor::GetUnit(*this, _redirectThreadInfo.GetTargetGUID()) : NULL; + return _redirectThreadInfo.GetTargetGUID() ? ObjectAccessor::GetUnit(*this, _redirectThreadInfo.GetTargetGUID()) : nullptr; } bool Unit::CreateVehicleKit(uint32 id, uint32 creatureEntry) @@ -12169,21 +12189,21 @@ void Unit::RemoveVehicleKit() m_vehicleKit->Uninstall(); delete m_vehicleKit; - m_vehicleKit = NULL; + m_vehicleKit = nullptr; m_updateFlag &= ~UPDATEFLAG_VEHICLE; m_unitTypeMask &= ~UNIT_MASK_VEHICLE; RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK | UNIT_NPC_FLAG_PLAYER_VEHICLE); } -bool Unit::IsOnVehicle(const Unit* vehicle) const +bool Unit::IsOnVehicle(Unit const* vehicle) const { return m_vehicle && m_vehicle == vehicle->GetVehicleKit(); } Unit* Unit::GetVehicleBase() const { - return m_vehicle ? m_vehicle->GetBase() : NULL; + return m_vehicle ? m_vehicle->GetBase() : nullptr; } Creature* Unit::GetVehicleCreatureBase() const @@ -12192,7 +12212,7 @@ Creature* Unit::GetVehicleCreatureBase() const if (Creature* c = veh->ToCreature()) return c; - return NULL; + return nullptr; } ObjectGuid Unit::GetTransGUID() const @@ -12253,7 +12273,7 @@ bool Unit::IsInRaidWith(Unit const* unit) const void Unit::GetPartyMembers(std::list &TagUnitMap) { Unit* owner = GetCharmerOrOwnerOrSelf(); - Group* group = NULL; + Group* group = nullptr; if (owner->GetTypeId() == TYPEID_PLAYER) group = owner->ToPlayer()->GetGroup(); @@ -12261,7 +12281,7 @@ void Unit::GetPartyMembers(std::list &TagUnitMap) { uint8 subgroup = owner->ToPlayer()->GetSubGroup(); - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* Target = itr->GetSource(); @@ -12306,14 +12326,14 @@ void Unit::SetPvP(bool state) Aura* Unit::AddAura(uint32 spellId, Unit* target) { if (!target) - return NULL; + return nullptr; SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId); if (!spellInfo) - return NULL; + return nullptr; if (!target->IsAlive() && !spellInfo->IsPassive() && !spellInfo->HasAttribute(SPELL_ATTR2_CAN_TARGET_DEAD)) - return NULL; + return nullptr; return AddAura(spellInfo, MAX_EFFECT_MASK, target); } @@ -12321,10 +12341,10 @@ Aura* Unit::AddAura(uint32 spellId, Unit* target) Aura* Unit::AddAura(SpellInfo const* spellInfo, uint8 effMask, Unit* target) { if (!spellInfo) - return NULL; + return nullptr; if (target->IsImmunedToSpell(spellInfo, this)) - return NULL; + return nullptr; for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) { @@ -12339,7 +12359,7 @@ Aura* Unit::AddAura(SpellInfo const* spellInfo, uint8 effMask, Unit* target) aura->ApplyForTargets(); return aura; } - return NULL; + return nullptr; } void Unit::SetAuraStack(uint32 spellId, Unit* target, uint32 stack) @@ -12389,7 +12409,7 @@ void Unit::ApplyResilience(Unit const* victim, int32* damage) const if (!GetCharmerOrOwnerPlayerOrPlayerItself()) return; - Unit const* target = NULL; + Unit const* target = nullptr; if (victim->GetTypeId() == TYPEID_PLAYER) target = victim; else if (victim->GetTypeId() == TYPEID_UNIT && victim->GetOwner() && victim->GetOwner()->GetTypeId() == TYPEID_PLAYER) @@ -12418,7 +12438,7 @@ float Unit::MeleeSpellMissChance(const Unit* victim, WeaponAttackType attType, u if (spellId) { if (Player* modOwner = GetSpellModOwner()) - modOwner->ApplySpellMod(spellId, hitChance); + modOwner->ApplySpellMod(spellId, SPELLMOD_RESIST_MISS_CHANCE, hitChance); } missChance += hitChance - 100.0f; @@ -12519,7 +12539,7 @@ void Unit::SendMoveKnockBack(Player* player, float speedXY, float speedZ, float data.WriteByteSeq(guid[2]); data.WriteByteSeq(guid[0]); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } void Unit::KnockbackFrom(float x, float y, float speedXY, float speedZ) @@ -12531,7 +12551,7 @@ void Unit::KnockbackFrom(float x, float y, float speedXY, float speedZ) { player = charmer->ToPlayer(); if (player && player->m_unitMovedByMe != this) - player = NULL; + player = nullptr; } } @@ -13089,7 +13109,7 @@ bool Unit::HandleSpellClick(Unit* clicker, int8 seatId) } if (IsInMap(caster)) - caster->CastCustomSpell(itr->second.spellId, SpellValueMod(SPELLVALUE_BASE_POINT0+i), seatId + 1, target, flags, NULL, NULL, origCasterGUID); + caster->CastCustomSpell(itr->second.spellId, SpellValueMod(SPELLVALUE_BASE_POINT0+i), seatId + 1, target, flags, nullptr, nullptr, origCasterGUID); else // This can happen during Player::_LoadAuras { int32 bp0[MAX_SPELL_EFFECTS]; @@ -13097,15 +13117,15 @@ bool Unit::HandleSpellClick(Unit* clicker, int8 seatId) bp0[j] = spellEntry->Effects[j].BasePoints; bp0[i] = seatId; - Aura::TryRefreshStackOrCreate(spellEntry, MAX_EFFECT_MASK, this, clicker, bp0, NULL, origCasterGUID); + Aura::TryRefreshStackOrCreate(spellEntry, MAX_EFFECT_MASK, this, clicker, bp0, nullptr, origCasterGUID); } } else { if (IsInMap(caster)) - caster->CastSpell(target, spellEntry, flags, NULL, NULL, origCasterGUID); + caster->CastSpell(target, spellEntry, flags, nullptr, nullptr, origCasterGUID); else - Aura::TryRefreshStackOrCreate(spellEntry, MAX_EFFECT_MASK, this, clicker, NULL, NULL, origCasterGUID); + Aura::TryRefreshStackOrCreate(spellEntry, MAX_EFFECT_MASK, this, clicker, nullptr, nullptr, origCasterGUID); } result = true; @@ -13178,7 +13198,7 @@ void Unit::ChangeSeat(int8 seatId, bool next) if (seat == m_vehicle->Seats.end() || !seat->second.IsEmpty()) return; - AuraEffect* rideVehicleEffect = NULL; + AuraEffect* rideVehicleEffect = nullptr; AuraEffectList const& vehicleAuras = m_vehicle->GetBase()->GetAuraEffectsByType(SPELL_AURA_CONTROL_VEHICLE); for (AuraEffectList::const_iterator itr = vehicleAuras.begin(); itr != vehicleAuras.end(); ++itr) { @@ -13217,7 +13237,7 @@ void Unit::ExitVehicle(Position const* /*exitPosition*/) void Unit::_ExitVehicle(Position const* exitPosition) { - /// It's possible m_vehicle is NULL, when this function is called indirectly from @VehicleJoinEvent::Abort. + /// It's possible m_vehicle is nullptr, when this function is called indirectly from @VehicleJoinEvent::Abort. /// In that case it was not possible to add the passenger to the vehicle. The vehicle aura has already been removed /// from the target in the aforementioned function and we don't need to do anything else at this point. if (!m_vehicle) @@ -13298,7 +13318,7 @@ void Unit::NearTeleportTo(Position const& pos, bool casting /*= false*/) } } -void Unit::WriteMovementInfo(WorldPacket& data, Movement::ExtraMovementStatusElement* extras /*= NULL*/) +void Unit::WriteMovementInfo(WorldPacket& data, Movement::ExtraMovementStatusElement* extras /*= nullptr*/) { MovementInfo const& mi = m_movementInfo; @@ -13639,7 +13659,7 @@ bool Unit::UpdatePosition(float x, float y, float z, float orientation, bool tel return (relocated || turn); } -bool Unit::UpdatePosition(const Position &pos, bool teleport) +bool Unit::UpdatePosition(Position const& pos, bool teleport) { return UpdatePosition(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), teleport); } @@ -13670,7 +13690,7 @@ void Unit::SendThreatListUpdate() WorldPacket data(SMSG_THREAT_UPDATE, 8 + count * 8); data << GetPackGUID(); data << uint32(count); - ThreatContainer::StorageType const &tlist = getThreatManager().getThreatList(); + ThreatContainer::StorageType const& tlist = getThreatManager().getThreatList(); for (ThreatContainer::StorageType::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr) { data << (*itr)->getUnitGuid().WriteAsPacked(); @@ -13691,7 +13711,7 @@ void Unit::SendChangeCurrentVictimOpcode(HostileReference* pHostileReference) data << GetPackGUID(); data << pHostileReference->getUnitGuid().WriteAsPacked(); data << uint32(count); - ThreatContainer::StorageType const &tlist = getThreatManager().getThreatList(); + ThreatContainer::StorageType const& tlist = getThreatManager().getThreatList(); for (ThreatContainer::StorageType::const_iterator itr = tlist.begin(); itr != tlist.end(); ++itr) { data << (*itr)->getUnitGuid().WriteAsPacked(); @@ -14182,7 +14202,6 @@ bool Unit::IsSplineEnabled() const return movespline->Initialized() && !movespline->Finalized(); } - void Unit::BuildValuesUpdate(uint8 updateType, ByteBuffer* data, Player* target) const { if (!target) @@ -14355,7 +14374,7 @@ void Unit::DestroyForPlayer(Player* target) const { WorldPacket data(SMSG_ARENA_UNIT_DESTROYED, 8); data << GetGUID(); - target->GetSession()->SendPacket(&data); + target->SendDirectMessage(&data); } } @@ -14394,7 +14413,7 @@ void Unit::UpdateLastDamagedTime(SpellInfo const* spellProto) if (spellProto && spellProto->HasAura(SPELL_AURA_DAMAGE_SHIELD)) return; - SetLastDamagedTime(time(NULL)); + SetLastDamagedTime(time(nullptr)); } bool Unit::IsHighestExclusiveAura(Aura const* aura, bool removeOtherAuraApplications /*= false*/) diff --git a/src/server/game/Entities/Unit/Unit.h b/src/server/game/Entities/Unit/Unit.h index ba8f25f0a72..0c16ac03718 100644 --- a/src/server/game/Entities/Unit/Unit.h +++ b/src/server/game/Entities/Unit/Unit.h @@ -19,16 +19,18 @@ #ifndef __UNIT_H #define __UNIT_H -#include "DBCStructure.h" +#include "Object.h" #include "EventProcessor.h" #include "FollowerReference.h" #include "FollowerRefManager.h" #include "HostileRefManager.h" -#include "MotionMaster.h" -#include "Object.h" +#include "OptionalFwd.h" #include "SpellAuraDefines.h" #include "ThreatManager.h" -#include "MoveSplineInit.h" +#include "Timer.h" +#include "UnitDefines.h" +#include "Util.h" +#include #define WORLD_TRIGGER 12999 @@ -119,7 +121,7 @@ enum SpellModOp : uint8 MAX_SPELLMOD }; -enum SpellValueMod +enum SpellValueMod : uint8 { SPELLVALUE_BASE_POINT0, SPELLVALUE_BASE_POINT1, @@ -162,69 +164,6 @@ enum SpellFacingFlags SPELL_FACING_FLAG_INFRONT = 0x0001 }; -#define BASE_MINDAMAGE 1.0f -#define BASE_MAXDAMAGE 2.0f -#define BASE_ATTACK_TIME 2000 - -// byte value (UNIT_FIELD_BYTES_1, 0) -enum UnitStandStateType -{ - UNIT_STAND_STATE_STAND = 0, - UNIT_STAND_STATE_SIT = 1, - UNIT_STAND_STATE_SIT_CHAIR = 2, - UNIT_STAND_STATE_SLEEP = 3, - UNIT_STAND_STATE_SIT_LOW_CHAIR = 4, - UNIT_STAND_STATE_SIT_MEDIUM_CHAIR = 5, - UNIT_STAND_STATE_SIT_HIGH_CHAIR = 6, - UNIT_STAND_STATE_DEAD = 7, - UNIT_STAND_STATE_KNEEL = 8, - UNIT_STAND_STATE_SUBMERGED = 9 -}; - -// byte flag value (UNIT_FIELD_BYTES_1, 2) -enum UnitStandFlags -{ - UNIT_STAND_FLAGS_UNK1 = 0x01, - UNIT_STAND_FLAGS_CREEP = 0x02, - UNIT_STAND_FLAGS_UNTRACKABLE = 0x04, - UNIT_STAND_FLAGS_UNK4 = 0x08, - UNIT_STAND_FLAGS_UNK5 = 0x10, - 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_FLAGS = 2, - UNIT_BYTES_2_OFFSET_SHAPESHIFT_FORM = 3, -}; - -// byte flags value (UNIT_FIELD_BYTES_1, 3) -enum UnitBytes1_Flags -{ - UNIT_BYTE1_FLAG_ALWAYS_STAND = 0x01, - UNIT_BYTE1_FLAG_HOVER = 0x02, - UNIT_BYTE1_FLAG_UNK_3 = 0x04, - UNIT_BYTE1_FLAG_ALL = 0xFF -}; - // high byte (3 from 0..3) of UNIT_FIELD_BYTES_2 enum ShapeshiftForm { @@ -261,36 +200,6 @@ enum ShapeshiftForm FORM_SPIRITOFREDEMPTION = 0x20 }; -// low byte (0 from 0..3) of UNIT_FIELD_BYTES_2 -enum SheathState -{ - SHEATH_STATE_UNARMED = 0, // non prepared weapon - SHEATH_STATE_MELEE = 1, // prepared melee weapon - SHEATH_STATE_RANGED = 2 // prepared ranged weapon -}; - -#define MAX_SHEATH_STATE 3 - -// byte (1 from 0..3) of UNIT_FIELD_BYTES_2 -enum UnitPVPStateFlags -{ - UNIT_BYTE2_FLAG_PVP = 0x01, - UNIT_BYTE2_FLAG_UNK1 = 0x02, - UNIT_BYTE2_FLAG_FFA_PVP = 0x04, - UNIT_BYTE2_FLAG_SANCTUARY = 0x08, - UNIT_BYTE2_FLAG_UNK4 = 0x10, - UNIT_BYTE2_FLAG_UNK5 = 0x20, - UNIT_BYTE2_FLAG_UNK6 = 0x40, - UNIT_BYTE2_FLAG_UNK7 = 0x80 -}; - -// byte (2 from 0..3) of UNIT_FIELD_BYTES_2 -enum UnitRename -{ - UNIT_CAN_BE_RENAMED = 0x01, - UNIT_CAN_BE_ABANDONED = 0x02 -}; - #define MAX_SPELL_CHARM 4 #define MAX_SPELL_VEHICLE 6 #define MAX_SPELL_POSSESS 8 @@ -312,36 +221,6 @@ enum VictimState VICTIMSTATE_DEFLECTS = 8 }; -enum HitInfo -{ - HITINFO_NORMALSWING = 0x00000000, - HITINFO_UNK1 = 0x00000001, // req correct packet structure - HITINFO_AFFECTS_VICTIM = 0x00000002, - HITINFO_OFFHAND = 0x00000004, - HITINFO_UNK2 = 0x00000008, - HITINFO_MISS = 0x00000010, - HITINFO_FULL_ABSORB = 0x00000020, - HITINFO_PARTIAL_ABSORB = 0x00000040, - HITINFO_FULL_RESIST = 0x00000080, - HITINFO_PARTIAL_RESIST = 0x00000100, - HITINFO_CRITICALHIT = 0x00000200, // critical hit - HITINFO_UNK10 = 0x00000400, - HITINFO_UNK11 = 0x00000800, - HITINFO_UNK12 = 0x00001000, - HITINFO_BLOCK = 0x00002000, // blocked damage - HITINFO_UNK14 = 0x00004000, // set only if meleespellid is present// no world text when victim is hit for 0 dmg(HideWorldTextForNoDamage?) - HITINFO_UNK15 = 0x00008000, // player victim?// something related to blod sprut visual (BloodSpurtInBack?) - HITINFO_GLANCING = 0x00010000, - HITINFO_CRUSHING = 0x00020000, - HITINFO_NO_ANIMATION = 0x00040000, - HITINFO_UNK19 = 0x00080000, - HITINFO_UNK20 = 0x00100000, - HITINFO_SWINGNOHITSOUND = 0x00200000, // unused? - HITINFO_UNK22 = 0x00400000, - HITINFO_RAGE_GAIN = 0x00800000, - HITINFO_FAKE_DAMAGE = 0x01000000 // enables damage animation even if no damage done, set only if no damage -}; - //i would like to remove this: (it is defined in item.h enum InventorySlot { @@ -350,33 +229,41 @@ enum InventorySlot }; struct FactionTemplateEntry; +struct LiquidData; +struct LiquidTypeEntry; +struct MountCapabilityEntry; struct SpellValue; -class AuraApplication; class Aura; -class UnitAura; +class AuraApplication; class AuraEffect; class Creature; -class Spell; -class SpellInfo; -class SpellHistory; class DynamicObject; class GameObject; -class Item; -class Pet; -class Minion; class Guardian; -class UnitAI; +class Item; +class Minion; +class MotionMaster; +class Pet; +class Spell; +class SpellCastTargets; +class SpellHistory; +class SpellInfo; class Totem; class Transport; +class TransportBase; +class UnitAI; +class UnitAura; class Vehicle; class VehicleJoinEvent; -class TransportBase; -class SpellCastTargets; + +enum ZLiquidStatus : uint32; + namespace Movement { class ExtraMovementStatusElement; class MoveSpline; + enum AnimType : uint8; } typedef std::list UnitList; @@ -384,11 +271,11 @@ typedef std::list UnitList; class DispelableAura { public: - DispelableAura(Aura* aura, int32 dispelChance, uint8 dispelCharges) : - _aura(aura), _chance(dispelChance), _charges(dispelCharges) { } + DispelableAura(Aura* aura, int32 dispelChance, uint8 dispelCharges); + ~DispelableAura(); Aura* GetAura() const { return _aura; } - bool RollDispel() const { return roll_chance_i(_chance); } + bool RollDispel() const; uint8 GetDispelCharges() const { return _charges; } void IncrementCharges() { ++_charges; } @@ -425,17 +312,7 @@ enum WeaponDamageRange MAXDAMAGE }; -enum AuraRemoveMode -{ - AURA_REMOVE_NONE = 0, - AURA_REMOVE_BY_DEFAULT = 1, // scripted remove, remove by stack with aura with different ids and sc aura remove - AURA_REMOVE_BY_CANCEL, - AURA_REMOVE_BY_ENEMY_SPELL, // dispel and absorb aura destroy - AURA_REMOVE_BY_EXPIRE, // aura duration has ended - AURA_REMOVE_BY_DEATH -}; - -enum TriggerCastFlags +enum TriggerCastFlags : uint32 { TRIGGERED_NONE = 0x00000000, //! Not triggered TRIGGERED_IGNORE_GCD = 0x00000001, //! Will ignore GCD @@ -632,7 +509,7 @@ enum CombatRating #define MAX_COMBAT_RATING 26 -enum DamageEffectType +enum DamageEffectType : uint8 { DIRECT_DAMAGE = 0, // used for normal weapon damage (not for class abilities or spells) SPELL_DIRECT_DAMAGE = 1, // spell/class abilities damage @@ -642,185 +519,6 @@ enum DamageEffectType SELF_DAMAGE = 5 }; -// Value masks for UNIT_FIELD_FLAGS -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_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 - UNIT_FLAG_UNK_6 = 0x00000040, - UNIT_FLAG_NOT_ATTACKABLE_1 = 0x00000080, // ?? (UNIT_FLAG_PVP_ATTACKABLE | UNIT_FLAG_NOT_ATTACKABLE_1) is NON_PVP_ATTACKABLE - UNIT_FLAG_IMMUNE_TO_PC = 0x00000100, // disables combat/assistance with PlayerCharacters (PC) - see Unit::_IsValidAttackTarget, Unit::_IsValidAssistTarget - UNIT_FLAG_IMMUNE_TO_NPC = 0x00000200, // disables combat/assistance with NonPlayerCharacters (NPC) - see Unit::_IsValidAttackTarget, Unit::_IsValidAssistTarget - UNIT_FLAG_LOOTING = 0x00000400, // loot animation - 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_CANNOT_SWIM = 0x00004000, // 2.0.8 - UNIT_FLAG_UNK_15 = 0x00008000, - UNIT_FLAG_UNK_16 = 0x00010000, - UNIT_FLAG_PACIFIED = 0x00020000, // 3.0.3 ok - UNIT_FLAG_STUNNED = 0x00040000, // 3.0.3 ok - UNIT_FLAG_IN_COMBAT = 0x00080000, - UNIT_FLAG_TAXI_FLIGHT = 0x00100000, // disable casting at client side spell not allowed by taxi flight (mounted?), probably used with 0x4 flag - UNIT_FLAG_DISARMED = 0x00200000, // 3.0.3, disable melee spells casting..., "Required melee weapon" added to melee spells tooltip. - UNIT_FLAG_CONFUSED = 0x00400000, - UNIT_FLAG_FLEEING = 0x00800000, - UNIT_FLAG_PLAYER_CONTROLLED = 0x01000000, // used in spell Eyes of the Beast for pet... let attack by controlled creature - UNIT_FLAG_NOT_SELECTABLE = 0x02000000, - UNIT_FLAG_SKINNABLE = 0x04000000, - UNIT_FLAG_MOUNT = 0x08000000, - UNIT_FLAG_UNK_28 = 0x10000000, - UNIT_FLAG_UNK_29 = 0x20000000, // used in Feing Death spell - UNIT_FLAG_SHEATHE = 0x40000000, - UNIT_FLAG_UNK_31 = 0x80000000, - MAX_UNIT_FLAGS = 33 -}; - -// Value masks for UNIT_FIELD_FLAGS_2 -enum UnitFlags2 -{ - UNIT_FLAG2_FEIGN_DEATH = 0x00000001, - UNIT_FLAG2_UNK1 = 0x00000002, // Hide unit model (show only player equip) - UNIT_FLAG2_IGNORE_REPUTATION = 0x00000004, - UNIT_FLAG2_COMPREHEND_LANG = 0x00000008, - UNIT_FLAG2_MIRROR_IMAGE = 0x00000010, - UNIT_FLAG2_INSTANTLY_APPEAR_MODEL = 0x00000020, // Unit model instantly appears when summoned (does not fade in) - UNIT_FLAG2_FORCE_MOVEMENT = 0x00000040, - UNIT_FLAG2_DISARM_OFFHAND = 0x00000080, - UNIT_FLAG2_DISABLE_PRED_STATS = 0x00000100, // Player has disabled predicted stats (Used by raid frames) - UNIT_FLAG2_DISARM_RANGED = 0x00000400, // this does not disable ranged weapon display (maybe additional flag needed?) - UNIT_FLAG2_REGENERATE_POWER = 0x00000800, - UNIT_FLAG2_RESTRICT_PARTY_INTERACTION = 0x00001000, // Restrict interaction to party or raid - UNIT_FLAG2_PREVENT_SPELL_CLICK = 0x00002000, // Prevent spellclick - UNIT_FLAG2_ALLOW_ENEMY_INTERACT = 0x00004000, - UNIT_FLAG2_DISABLE_TURN = 0x00008000, - UNIT_FLAG2_UNK2 = 0x00010000, - UNIT_FLAG2_PLAY_DEATH_ANIM = 0x00020000, // Plays special death animation upon death - UNIT_FLAG2_ALLOW_CHEAT_SPELLS = 0x00040000, // Allows casting spells with AttributesEx7 & SPELL_ATTR7_IS_CHEAT_SPELL - UNIT_FLAG2_NO_ACTIONS = 0x00800000 -}; - -/// Non Player Character flags -enum NPCFlags -{ - UNIT_NPC_FLAG_NONE = 0x00000000, - UNIT_NPC_FLAG_GOSSIP = 0x00000001, // 100% - UNIT_NPC_FLAG_QUESTGIVER = 0x00000002, // 100% - UNIT_NPC_FLAG_UNK1 = 0x00000004, - UNIT_NPC_FLAG_UNK2 = 0x00000008, - UNIT_NPC_FLAG_TRAINER = 0x00000010, // 100% - UNIT_NPC_FLAG_TRAINER_CLASS = 0x00000020, // 100% - UNIT_NPC_FLAG_TRAINER_PROFESSION = 0x00000040, // 100% - UNIT_NPC_FLAG_VENDOR = 0x00000080, // 100% - UNIT_NPC_FLAG_VENDOR_AMMO = 0x00000100, // 100%, general goods vendor - UNIT_NPC_FLAG_VENDOR_FOOD = 0x00000200, // 100% - UNIT_NPC_FLAG_VENDOR_POISON = 0x00000400, // guessed - UNIT_NPC_FLAG_VENDOR_REAGENT = 0x00000800, // 100% - UNIT_NPC_FLAG_REPAIR = 0x00001000, // 100% - UNIT_NPC_FLAG_FLIGHTMASTER = 0x00002000, // 100% - UNIT_NPC_FLAG_SPIRITHEALER = 0x00004000, // guessed - UNIT_NPC_FLAG_SPIRITGUIDE = 0x00008000, // guessed - UNIT_NPC_FLAG_INNKEEPER = 0x00010000, // 100% - UNIT_NPC_FLAG_BANKER = 0x00020000, // 100% - UNIT_NPC_FLAG_PETITIONER = 0x00040000, // 100% 0xC0000 = guild petitions, 0x40000 = arena team petitions - UNIT_NPC_FLAG_TABARDDESIGNER = 0x00080000, // 100% - UNIT_NPC_FLAG_BATTLEMASTER = 0x00100000, // 100% - UNIT_NPC_FLAG_AUCTIONEER = 0x00200000, // 100% - UNIT_NPC_FLAG_STABLEMASTER = 0x00400000, // 100% - UNIT_NPC_FLAG_GUILD_BANKER = 0x00800000, // cause client to send 997 opcode - UNIT_NPC_FLAG_SPELLCLICK = 0x01000000, // cause client to send 1015 opcode (spell click) - UNIT_NPC_FLAG_PLAYER_VEHICLE = 0x02000000, // players with mounts that have vehicle data should have it set - UNIT_NPC_FLAG_MAILBOX = 0x04000000, // mailbox - UNIT_NPC_FLAG_REFORGER = 0x08000000, // reforging - UNIT_NPC_FLAG_TRANSMOGRIFIER = 0x10000000, // transmogrification - UNIT_NPC_FLAG_VAULTKEEPER = 0x20000000 // void storage -}; - -enum MovementFlags -{ - MOVEMENTFLAG_NONE = 0x00000000, - MOVEMENTFLAG_FORWARD = 0x00000001, - MOVEMENTFLAG_BACKWARD = 0x00000002, - MOVEMENTFLAG_STRAFE_LEFT = 0x00000004, - MOVEMENTFLAG_STRAFE_RIGHT = 0x00000008, - MOVEMENTFLAG_LEFT = 0x00000010, - MOVEMENTFLAG_RIGHT = 0x00000020, - MOVEMENTFLAG_PITCH_UP = 0x00000040, - MOVEMENTFLAG_PITCH_DOWN = 0x00000080, - MOVEMENTFLAG_WALKING = 0x00000100, // Walking - MOVEMENTFLAG_DISABLE_GRAVITY = 0x00000200, // Former MOVEMENTFLAG_LEVITATING. This is used when walking is not possible. - MOVEMENTFLAG_ROOT = 0x00000400, // Must not be set along with MOVEMENTFLAG_MASK_MOVING - MOVEMENTFLAG_FALLING = 0x00000800, // damage dealt on that type of falling - MOVEMENTFLAG_FALLING_FAR = 0x00001000, - MOVEMENTFLAG_PENDING_STOP = 0x00002000, - MOVEMENTFLAG_PENDING_STRAFE_STOP = 0x00004000, - MOVEMENTFLAG_PENDING_FORWARD = 0x00008000, - MOVEMENTFLAG_PENDING_BACKWARD = 0x00010000, - MOVEMENTFLAG_PENDING_STRAFE_LEFT = 0x00020000, - MOVEMENTFLAG_PENDING_STRAFE_RIGHT = 0x00040000, - MOVEMENTFLAG_PENDING_ROOT = 0x00080000, - MOVEMENTFLAG_SWIMMING = 0x00100000, // appears with fly flag also - MOVEMENTFLAG_ASCENDING = 0x00200000, // press "space" when flying - MOVEMENTFLAG_DESCENDING = 0x00400000, - MOVEMENTFLAG_CAN_FLY = 0x00800000, // Appears when unit can fly AND also walk - MOVEMENTFLAG_FLYING = 0x01000000, // unit is actually flying. pretty sure this is only used for players. creatures use disable_gravity - MOVEMENTFLAG_SPLINE_ELEVATION = 0x02000000, // used for flight paths - MOVEMENTFLAG_WATERWALKING = 0x04000000, // prevent unit from falling through water - MOVEMENTFLAG_FALLING_SLOW = 0x08000000, // active rogue safe fall spell (passive) - MOVEMENTFLAG_HOVER = 0x10000000, // hover, cannot jump - MOVEMENTFLAG_DISABLE_COLLISION = 0x20000000, - - MOVEMENTFLAG_MASK_MOVING = - MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_BACKWARD | MOVEMENTFLAG_STRAFE_LEFT | MOVEMENTFLAG_STRAFE_RIGHT | - MOVEMENTFLAG_FALLING | MOVEMENTFLAG_FALLING_FAR | MOVEMENTFLAG_ASCENDING | MOVEMENTFLAG_DESCENDING | - MOVEMENTFLAG_SPLINE_ELEVATION, - - MOVEMENTFLAG_MASK_TURNING = - MOVEMENTFLAG_LEFT | MOVEMENTFLAG_RIGHT | MOVEMENTFLAG_PITCH_UP | MOVEMENTFLAG_PITCH_DOWN, - - MOVEMENTFLAG_MASK_MOVING_FLY = - MOVEMENTFLAG_FLYING | MOVEMENTFLAG_ASCENDING | MOVEMENTFLAG_DESCENDING, - - // Movement flags allowed for creature in CreateObject - we need to keep all other enabled serverside - // to properly calculate all movement - MOVEMENTFLAG_MASK_CREATURE_ALLOWED = - MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_DISABLE_GRAVITY | MOVEMENTFLAG_ROOT | MOVEMENTFLAG_SWIMMING | - MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_WATERWALKING | MOVEMENTFLAG_FALLING_SLOW | MOVEMENTFLAG_HOVER, - - /// @todo if needed: add more flags to this masks that are exclusive to players - MOVEMENTFLAG_MASK_PLAYER_ONLY = - MOVEMENTFLAG_FLYING, - - /// Movement flags that have change status opcodes associated for players - MOVEMENTFLAG_MASK_HAS_PLAYER_STATUS_OPCODE = MOVEMENTFLAG_DISABLE_GRAVITY | MOVEMENTFLAG_ROOT | - MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_WATERWALKING | MOVEMENTFLAG_FALLING_SLOW | MOVEMENTFLAG_HOVER -}; - -enum MovementFlags2 -{ - MOVEMENTFLAG2_NONE = 0x00000000, - MOVEMENTFLAG2_NO_STRAFE = 0x00000001, - MOVEMENTFLAG2_NO_JUMPING = 0x00000002, - MOVEMENTFLAG2_FULL_SPEED_TURNING = 0x00000004, - MOVEMENTFLAG2_FULL_SPEED_PITCHING = 0x00000008, - MOVEMENTFLAG2_ALWAYS_ALLOW_PITCHING = 0x00000010, - MOVEMENTFLAG2_UNK5 = 0x00000020, - MOVEMENTFLAG2_UNK6 = 0x00000040, - MOVEMENTFLAG2_UNK7 = 0x00000080, - MOVEMENTFLAG2_UNK8 = 0x00000100, - MOVEMENTFLAG2_UNK9 = 0x00000200, - MOVEMENTFLAG2_CAN_SWIM_TO_FLY_TRANS = 0x00000400, - MOVEMENTFLAG2_UNK11 = 0x00000800, - MOVEMENTFLAG2_UNK12 = 0x00001000, - MOVEMENTFLAG2_INTERPOLATED_MOVEMENT = 0x00002000, - MOVEMENTFLAG2_INTERPOLATED_TURNING = 0x00004000, - MOVEMENTFLAG2_INTERPOLATED_PITCHING = 0x00008000 -}; - enum UnitTypeMask { UNIT_MASK_NONE = 0x00000000, @@ -1077,14 +775,7 @@ struct RedirectThreatInfo } }; -#define MAX_DECLINED_NAME_CASES 5 - -struct DeclinedName -{ - std::string name[MAX_DECLINED_NAME_CASES]; -}; - -enum CurrentSpellTypes +enum CurrentSpellTypes : uint8 { CURRENT_MELEE_SPELL = 0, CURRENT_GENERIC_SPELL = 1, @@ -1095,32 +786,6 @@ enum CurrentSpellTypes #define CURRENT_FIRST_NON_MELEE_SPELL 1 #define CURRENT_MAX_SPELL 4 -enum ActiveStates -{ - ACT_PASSIVE = 0x01, // 0x01 - passive - ACT_DISABLED = 0x81, // 0x80 - castable - ACT_ENABLED = 0xC1, // 0x40 | 0x80 - auto cast + castable - ACT_COMMAND = 0x07, // 0x01 | 0x02 | 0x04 - ACT_REACTION = 0x06, // 0x02 | 0x04 - ACT_DECIDE = 0x00 // custom -}; - -enum ReactStates -{ - REACT_PASSIVE = 0, - REACT_DEFENSIVE = 1, - REACT_AGGRESSIVE = 2 -}; - -enum CommandStates : uint8 -{ - COMMAND_STAY = 0, - COMMAND_FOLLOW = 1, - COMMAND_ATTACK = 2, - COMMAND_ABANDON = 3, - COMMAND_MOVE_TO = 4 -}; - #define UNIT_ACTION_BUTTON_ACTION(X) (uint32(X) & 0x00FFFFFF) #define UNIT_ACTION_BUTTON_TYPE(X) ((uint32(X) & 0xFF000000) >> 24) #define MAKE_UNIT_ACTION_BUTTON(A, T) (uint32(A) | (uint32(T) << 24)) @@ -1298,7 +963,6 @@ class TC_GAME_API Unit : public WorldObject typedef std::list AuraEffectList; typedef std::list AuraList; typedef std::list AuraApplicationList; - typedef std::array Diminishing; typedef std::vector> AuraApplicationProcContainer; @@ -1336,11 +1000,11 @@ class TC_GAME_API Unit : public WorldObject virtual void SetCanDualWield(bool value) { m_canDualWield = value; } float GetCombatReach() const { return m_floatValues[UNIT_FIELD_COMBATREACH]; } float GetBoundaryRadius() const { return m_floatValues[UNIT_FIELD_BOUNDINGRADIUS]; } - bool IsWithinCombatRange(const Unit* obj, float dist2compare) const; + bool IsWithinCombatRange(Unit const* obj, float dist2compare) const; bool IsWithinMeleeRange(Unit const* obj) const; bool IsWithinBoundaryRadius(const Unit* obj) const; float GetMeleeRange(Unit const* target) const; - void GetRandomContactPoint(const Unit* target, float &x, float &y, float &z, float distance2dMin, float distance2dMax) const; + void GetRandomContactPoint(Unit const* target, float& x, float& y, float& z, float distance2dMin, float distance2dMax) const; uint32 m_extraAttacks; bool m_canDualWield; @@ -1364,8 +1028,8 @@ class TC_GAME_API Unit : public WorldObject void CombatStop(bool includingCast = false); void CombatStopWithPets(bool includingCast = false); void StopAttackFaction(uint32 faction_id); - Unit* SelectNearbyTarget(Unit* exclude = NULL, float dist = NOMINAL_MELEE_RANGE) const; - void SendMeleeAttackStop(Unit* victim = NULL); + Unit* SelectNearbyTarget(Unit* exclude = nullptr, float dist = NOMINAL_MELEE_RANGE) const; + void SendMeleeAttackStop(Unit* victim = nullptr); void SendMeleeAttackStart(Unit* victim); void AddUnitState(uint32 f) { m_state |= f; } @@ -1479,9 +1143,9 @@ class TC_GAME_API Unit : public WorldObject void SendDurabilityLoss(Player* receiver, uint32 percent); void PlayOneShotAnimKitId(uint16 animKitId); - uint16 GetMaxSkillValueForLevel(Unit const* target = NULL) const { return (target ? getLevelForTarget(target) : getLevel()) * 5; } + uint16 GetMaxSkillValueForLevel(Unit const* target = nullptr) const { return (target ? getLevelForTarget(target) : getLevel()) * 5; } void DealDamageMods(Unit const* victim, uint32 &damage, uint32* absorb) const; - uint32 DealDamage(Unit* victim, uint32 damage, CleanDamage const* cleanDamage = NULL, DamageEffectType damagetype = DIRECT_DAMAGE, SpellSchoolMask damageSchoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* spellProto = NULL, bool durabilityLoss = true); + uint32 DealDamage(Unit* victim, uint32 damage, CleanDamage const* cleanDamage = nullptr, DamageEffectType damagetype = DIRECT_DAMAGE, SpellSchoolMask damageSchoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* spellProto = nullptr, bool durabilityLoss = true); void Kill(Unit* victim, bool durabilityLoss = true); void KillSelf(bool durabilityLoss = true) { Kill(this, durabilityLoss); } void DealHeal(HealInfo& healInfo); @@ -1528,10 +1192,10 @@ class TC_GAME_API Unit : public WorldObject virtual uint32 GetBlockPercent() const { return 30; } - uint32 GetUnitMeleeSkill(Unit const* target = NULL) const; + uint32 GetUnitMeleeSkill(Unit const* target = nullptr) const; float GetWeaponProcChance() const; - float GetPPMProcChance(uint32 WeaponSpeed, float PPM, const SpellInfo* spellProto) const; + float GetPPMProcChance(uint32 WeaponSpeed, float PPM, SpellInfo const* spellProto) const; MeleeHitOutcome RollMeleeOutcomeAgainst (const Unit* victim, WeaponAttackType attType) const; MeleeHitOutcome RollMeleeOutcomeAgainst (const Unit* victim, WeaponAttackType attType, int32 crit_chance, int32 miss_chance, int32 dodge_chance, int32 parry_chance, int32 block_chance) const; @@ -1560,7 +1224,7 @@ class TC_GAME_API Unit : public WorldObject bool IsPetInCombat() const { return HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PET_IN_COMBAT); } bool IsInCombatWith(Unit const* who) const; void CombatStart(Unit* target, bool initialAggro = true); - void SetInCombatState(bool PvP, Unit* enemy = NULL); + void SetInCombatState(bool PvP, Unit* enemy = nullptr); void SetInCombatWith(Unit* enemy); void ClearInCombat(); void ClearInPetCombat(); @@ -1569,7 +1233,7 @@ class TC_GAME_API Unit : public WorldObject bool HasAuraTypeWithFamilyFlags(AuraType auraType, uint32 familyName, uint32 familyFlags) const; bool virtual HasSpell(uint32 /*spellID*/) const { return false; } bool HasBreakableByDamageAuraType(AuraType type, uint32 excludeAura = 0) const; - bool HasBreakableByDamageCrowdControlAura(Unit* excludeCasterChannel = NULL) const; + bool HasBreakableByDamageCrowdControlAura(Unit* excludeCasterChannel = nullptr) const; bool HasStealthAura() const { return HasAuraType(SPELL_AURA_MOD_STEALTH); } bool HasInvisibilityAura() const { return HasAuraType(SPELL_AURA_MOD_INVISIBILITY); } @@ -1582,7 +1246,7 @@ class TC_GAME_API Unit : public WorldObject bool isTargetableForAttack(bool checkFakeDeath = true) const; bool IsValidAttackTarget(Unit const* target) const; - bool _IsValidAttackTarget(Unit const* target, SpellInfo const* bySpell, WorldObject const* obj = NULL) const; + bool _IsValidAttackTarget(Unit const* target, SpellInfo const* bySpell, WorldObject const* obj = nullptr) const; bool IsValidAssistTarget(Unit const* target) const; bool _IsValidAssistTarget(Unit const* target, SpellInfo const* bySpell) const; @@ -1642,7 +1306,6 @@ class TC_GAME_API Unit : public WorldObject void MonsterMoveWithSpeed(float x, float y, float z, float speed, bool generatePath = false, bool forceDestination = false); - void SendSetPlayHoverAnim(bool enable); void SendMovementSetSplineAnim(Movement::AnimType anim); @@ -1711,7 +1374,7 @@ class TC_GAME_API Unit : public WorldObject void RemoveAllMinionsByEntry(uint32 entry); void SetCharm(Unit* target, bool apply); Unit* GetNextRandomRaidMemberOrPet(float radius); - bool SetCharmedBy(Unit* charmer, CharmType type, AuraApplication const* aurApp = NULL); + bool SetCharmedBy(Unit* charmer, CharmType type, AuraApplication const* aurApp = nullptr); void RemoveCharmedBy(Unit* charmer); void RestoreFaction(); @@ -1767,7 +1430,7 @@ class TC_GAME_API Unit : public WorldObject void RemoveOwnedAura(uint32 spellId, ObjectGuid casterGUID = ObjectGuid::Empty, uint8 reqEffMask = 0, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); void RemoveOwnedAura(Aura* aura, AuraRemoveMode removeMode = AURA_REMOVE_BY_DEFAULT); - Aura* GetOwnedAura(uint32 spellId, ObjectGuid casterGUID = ObjectGuid::Empty, ObjectGuid itemCasterGUID = ObjectGuid::Empty, uint8 reqEffMask = 0, Aura* except = NULL) const; + Aura* GetOwnedAura(uint32 spellId, ObjectGuid casterGUID = ObjectGuid::Empty, ObjectGuid itemCasterGUID = ObjectGuid::Empty, uint8 reqEffMask = 0, Aura* except = nullptr) const; // m_appliedAuras container management AuraApplicationMap & GetAppliedAuras() { return m_appliedAuras; } @@ -1793,7 +1456,7 @@ class TC_GAME_API Unit : public WorldObject void RemoveAurasDueToSpellByDispel(uint32 spellId, uint32 dispellerSpellId, ObjectGuid casterGUID, Unit* dispeller, uint8 chargesRemoved = 1); void RemoveAurasDueToSpellBySteal(uint32 spellId, ObjectGuid casterGUID, Unit* stealer); void RemoveAurasDueToItemSpell(uint32 spellId, ObjectGuid castItemGuid); - void RemoveAurasByType(AuraType auraType, ObjectGuid casterGUID = ObjectGuid::Empty, Aura* except = NULL, bool negative = true, bool positive = true); + void RemoveAurasByType(AuraType auraType, ObjectGuid casterGUID = ObjectGuid::Empty, Aura* except = nullptr, bool negative = true, bool positive = true); void RemoveNotOwnSingleTargetAuras(bool onPhaseChange = false); void RemoveAurasWithInterruptFlags(uint32 flag, uint32 except = 0); void RemoveAurasWithAttribute(uint32 flags); @@ -1825,10 +1488,10 @@ class TC_GAME_API Unit : public WorldObject AuraEffect* GetAuraEffect(AuraType type, SpellFamilyNames family, uint32 familyFlag1, uint32 familyFlag2, uint32 familyFlag3, ObjectGuid casterGUID = ObjectGuid::Empty) const; AuraEffect* GetDummyAuraEffect(SpellFamilyNames name, uint32 iconId, uint8 effIndex) const; - AuraApplication * GetAuraApplication(uint32 spellId, ObjectGuid casterGUID = ObjectGuid::Empty, ObjectGuid itemCasterGUID = ObjectGuid::Empty, uint8 reqEffMask = 0, AuraApplication * except = NULL) const; + AuraApplication * GetAuraApplication(uint32 spellId, ObjectGuid casterGUID = ObjectGuid::Empty, ObjectGuid itemCasterGUID = ObjectGuid::Empty, uint8 reqEffMask = 0, AuraApplication * except = nullptr) const; Aura* GetAura(uint32 spellId, ObjectGuid casterGUID = ObjectGuid::Empty, ObjectGuid itemCasterGUID = ObjectGuid::Empty, uint8 reqEffMask = 0) const; - AuraApplication * GetAuraApplicationOfRankedSpell(uint32 spellId, ObjectGuid casterGUID = ObjectGuid::Empty, ObjectGuid itemCasterGUID = ObjectGuid::Empty, uint8 reqEffMask = 0, AuraApplication * except = NULL) const; + AuraApplication * GetAuraApplicationOfRankedSpell(uint32 spellId, ObjectGuid casterGUID = ObjectGuid::Empty, ObjectGuid itemCasterGUID = ObjectGuid::Empty, uint8 reqEffMask = 0, AuraApplication * except = nullptr) const; Aura* GetAuraOfRankedSpell(uint32 spellId, ObjectGuid casterGUID = ObjectGuid::Empty, ObjectGuid itemCasterGUID = ObjectGuid::Empty, uint8 reqEffMask = 0) const; void GetDispellableAuraList(Unit* caster, uint32 dispelMask, DispelChargesList& dispelList, bool isReflect = false) const; @@ -1984,7 +1647,7 @@ class TC_GAME_API Unit : public WorldObject // Threat related methods bool CanHaveThreatList(bool skipAliveCheck = false) const; - void AddThreat(Unit* victim, float fThreat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* threatSpell = NULL); + void AddThreat(Unit* victim, float fThreat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL, SpellInfo const* threatSpell = nullptr); float ApplyTotalThreatModifier(float fThreat, SpellSchoolMask schoolMask = SPELL_SCHOOL_MASK_NORMAL); void DeleteThreatList(); void TauntApply(Unit* victim); @@ -2028,11 +1691,11 @@ class TC_GAME_API Unit : public WorldObject void ModifyAuraState(AuraStateType flag, bool apply); uint32 BuildAuraStateUpdateForTarget(Unit* target) const; - bool HasAuraState(AuraStateType flag, SpellInfo const* spellProto = NULL, Unit const* Caster = NULL) const; + bool HasAuraState(AuraStateType flag, SpellInfo const* spellProto = nullptr, Unit const* Caster = nullptr) const; void UnsummonAllTotems(); bool IsMagnet() const; Unit* GetMagicHitRedirectTarget(Unit* victim, SpellInfo const* spellInfo); - Unit* GetMeleeHitRedirectTarget(Unit* victim, SpellInfo const* spellInfo = NULL); + Unit* GetMeleeHitRedirectTarget(Unit* victim, SpellInfo const* spellInfo = nullptr); int32 SpellBaseDamageBonusDone(SpellSchoolMask schoolMask) const; int32 SpellBaseDamageBonusTaken(SpellSchoolMask schoolMask) const; @@ -2045,8 +1708,8 @@ class TC_GAME_API Unit : public WorldObject float SpellHealingPctDone(Unit* victim, SpellInfo const* spellProto) const; uint32 SpellHealingBonusTaken(Unit* caster, SpellInfo const* spellProto, uint32 healamount, DamageEffectType damagetype, uint32 stack = 1) const; - uint32 MeleeDamageBonusDone(Unit* pVictim, uint32 damage, WeaponAttackType attType, SpellInfo const* spellProto = NULL); - uint32 MeleeDamageBonusTaken(Unit* attacker, uint32 pdamage, WeaponAttackType attType, SpellInfo const* spellProto = NULL); + uint32 MeleeDamageBonusDone(Unit* pVictim, uint32 damage, WeaponAttackType attType, SpellInfo const* spellProto = nullptr); + uint32 MeleeDamageBonusTaken(Unit* attacker, uint32 pdamage, WeaponAttackType attType, SpellInfo const* spellProto = nullptr); bool isSpellBlocked(Unit* victim, SpellInfo const* spellProto, WeaponAttackType attackType = BASE_ATTACK); bool isBlockCritical(); @@ -2055,7 +1718,7 @@ class TC_GAME_API Unit : public WorldObject uint32 SpellCriticalDamageBonus(SpellInfo const* spellProto, uint32 damage, Unit* victim); uint32 SpellCriticalHealingBonus(SpellInfo const* spellProto, uint32 damage, Unit* victim); - void SetContestedPvP(Player* attackedPlayer = NULL); + void SetContestedPvP(Player* attackedPlayer = nullptr); uint32 GetCastingTimeForBonus(SpellInfo const* spellProto, DamageEffectType damagetype, uint32 CastingTime) const; float CalculateDefaultCoefficient(SpellInfo const* spellInfo, DamageEffectType damagetype) const; @@ -2071,7 +1734,7 @@ class TC_GAME_API Unit : public WorldObject bool IsImmunedToDamage(SpellInfo const* spellInfo) const; virtual bool IsImmunedToSpellEffect(SpellInfo const* spellInfo, uint32 index, Unit* caster) const; // redefined in Creature - static bool IsDamageReducedByArmor(SpellSchoolMask damageSchoolMask, SpellInfo const* spellInfo = NULL, uint8 effIndex = MAX_SPELL_EFFECTS); + static bool IsDamageReducedByArmor(SpellSchoolMask damageSchoolMask, SpellInfo const* spellInfo = nullptr, int8 effIndex = -1); uint32 CalcArmorReducedDamage(Unit* victim, const uint32 damage, SpellInfo const* spellInfo, WeaponAttackType attackType = MAX_ATTACK); uint32 CalcSpellResistance(Unit* victim, SpellSchoolMask schoolMask, SpellInfo const* spellInfo) const; void CalcAbsorbResist(DamageInfo& damageInfo); @@ -2084,17 +1747,17 @@ class TC_GAME_API Unit : public WorldObject 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; + int32 CalculateSpellDamage(Unit const* target, SpellInfo const* spellProto, uint8 effect_index, int32 const* basePoints = nullptr) const; int32 CalcSpellDuration(SpellInfo const* spellProto); int32 ModSpellDuration(SpellInfo const* spellProto, Unit const* target, int32 duration, bool positive, uint32 effectMask); - void ModSpellCastTime(SpellInfo const* spellProto, int32& castTime, Spell* spell = NULL); - void ModSpellDurationTime(SpellInfo const* spellProto, int32& castTime, Spell* spell = NULL); + void ModSpellCastTime(SpellInfo const* spellProto, int32& castTime, Spell* spell = nullptr); + void ModSpellDurationTime(SpellInfo const* spellProto, int32& castTime, Spell* spell = nullptr); void addFollower(FollowerReference* pRef) { m_FollowingRefManager.insertFirst(pRef); } void removeFollower(FollowerReference* /*pRef*/) { /* nothing to do yet */ } MotionMaster* GetMotionMaster() { return i_motionMaster; } - const MotionMaster* GetMotionMaster() const { return i_motionMaster; } + MotionMaster const* GetMotionMaster() const { return i_motionMaster; } bool IsStopped() const { return !(HasUnitState(UNIT_STATE_MOVING)); } void StopMoving(); @@ -2126,7 +1789,7 @@ class TC_GAME_API Unit : public WorldObject void SendPetAIReaction(ObjectGuid guid); ///----------End of Pet responses methods---------- - void PropagateSpeedChange() { GetMotionMaster()->PropagateSpeedChange(); } + void PropagateSpeedChange(); // reactive attacks void ClearAllReactives(); @@ -2158,7 +1821,7 @@ class TC_GAME_API Unit : public WorldObject Vehicle* GetVehicleKit()const { return m_vehicleKit; } Vehicle* GetVehicle() const { return m_vehicle; } void SetVehicle(Vehicle* vehicle) { m_vehicle = vehicle; } - bool IsOnVehicle(const Unit* vehicle) const; + bool IsOnVehicle(Unit const* vehicle) const; Unit* GetVehicleBase() const; Creature* GetVehicleCreatureBase() const; ObjectGuid GetTransGUID() const override; @@ -2169,14 +1832,14 @@ class TC_GAME_API Unit : public WorldObject bool HandleSpellClick(Unit* clicker, int8 seatId = -1); void EnterVehicle(Unit* base, int8 seatId = -1); - void ExitVehicle(Position const* exitPosition = NULL); + void ExitVehicle(Position const* exitPosition = nullptr); void ChangeSeat(int8 seatId, bool next = true); // Should only be called by AuraEffect::HandleAuraControlVehicle(AuraApplication const* auraApp, uint8 mode, bool apply) const; - void _ExitVehicle(Position const* exitPosition = NULL); - void _EnterVehicle(Vehicle* vehicle, int8 seatId, AuraApplication const* aurApp = NULL); + void _ExitVehicle(Position const* exitPosition = nullptr); + void _EnterVehicle(Vehicle* vehicle, int8 seatId, AuraApplication const* aurApp = nullptr); - void WriteMovementInfo(WorldPacket& data, Movement::ExtraMovementStatusElement* extras = NULL); + void WriteMovementInfo(WorldPacket& data, Movement::ExtraMovementStatusElement* extras = nullptr); bool isMoving() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_MASK_MOVING); } bool isTurning() const { return m_movementInfo.HasMovementFlag(MOVEMENTFLAG_MASK_TURNING); } @@ -2192,14 +1855,14 @@ class TC_GAME_API Unit : public WorldObject virtual bool IsLoading() const { return false; } bool IsDuringRemoveFromWorld() const {return m_duringRemoveFromWorld;} - Pet* ToPet() { if (IsPet()) return reinterpret_cast(this); else return NULL; } - Pet const* ToPet() const { if (IsPet()) return reinterpret_cast(this); else return NULL; } + Pet* ToPet() { if (IsPet()) return reinterpret_cast(this); else return nullptr; } + Pet const* ToPet() const { if (IsPet()) return reinterpret_cast(this); else return nullptr; } - Totem* ToTotem() { if (IsTotem()) return reinterpret_cast(this); else return NULL; } - Totem const* ToTotem() const { if (IsTotem()) return reinterpret_cast(this); else return NULL; } + Totem* ToTotem() { if (IsTotem()) return reinterpret_cast(this); else return nullptr; } + Totem const* ToTotem() const { if (IsTotem()) return reinterpret_cast(this); else return nullptr; } - TempSummon* ToTempSummon() { if (IsSummon()) return reinterpret_cast(this); else return NULL; } - TempSummon const* ToTempSummon() const { if (IsSummon()) return reinterpret_cast(this); else return NULL; } + TempSummon* ToTempSummon() { if (IsSummon()) return reinterpret_cast(this); else return nullptr; } + TempSummon const* ToTempSummon() const { if (IsSummon()) return reinterpret_cast(this); else return nullptr; } ObjectGuid GetTarget() const { return GetGuidValue(UNIT_FIELD_TARGET); } virtual void SetTarget(ObjectGuid /*guid*/) = 0; @@ -2332,7 +1995,7 @@ class TC_GAME_API Unit : public WorldObject uint32 m_CombatTimer; TimeTrackerSmall m_movesplineTimer; - Diminishing m_Diminishing; + DiminishingReturn m_Diminishing[DIMINISHING_MAX]; // Manage all Units that are threatened by us HostileRefManager m_HostileRefManager; @@ -2408,4 +2071,5 @@ namespace Trinity bool const _ascending; }; } + #endif diff --git a/src/server/game/Entities/Unit/UnitDefines.h b/src/server/game/Entities/Unit/UnitDefines.h new file mode 100644 index 00000000000..b2f5fa2f7df --- /dev/null +++ b/src/server/game/Entities/Unit/UnitDefines.h @@ -0,0 +1,362 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * Copyright (C) 2005-2009 MaNGOS + * + * 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 . + */ + +#ifndef UnitDefines_h__ +#define UnitDefines_h__ + +#include "Define.h" +#include + +#define BASE_MINDAMAGE 1.0f +#define BASE_MAXDAMAGE 2.0f +#define BASE_ATTACK_TIME 2000 + +#define MAX_EQUIPMENT_ITEMS 3 + +// byte value (UNIT_FIELD_BYTES_1, 0) +enum UnitStandStateType : uint8 +{ + UNIT_STAND_STATE_STAND = 0, + UNIT_STAND_STATE_SIT = 1, + UNIT_STAND_STATE_SIT_CHAIR = 2, + UNIT_STAND_STATE_SLEEP = 3, + UNIT_STAND_STATE_SIT_LOW_CHAIR = 4, + UNIT_STAND_STATE_SIT_MEDIUM_CHAIR = 5, + UNIT_STAND_STATE_SIT_HIGH_CHAIR = 6, + UNIT_STAND_STATE_DEAD = 7, + UNIT_STAND_STATE_KNEEL = 8, + UNIT_STAND_STATE_SUBMERGED = 9 +}; + +// byte flag value (UNIT_FIELD_BYTES_1, 2) +enum UnitStandFlags : uint8 +{ + UNIT_STAND_FLAGS_UNK1 = 0x01, + UNIT_STAND_FLAGS_CREEP = 0x02, + UNIT_STAND_FLAGS_UNTRACKABLE = 0x04, + UNIT_STAND_FLAGS_UNK4 = 0x08, + UNIT_STAND_FLAGS_UNK5 = 0x10, + UNIT_STAND_FLAGS_ALL = 0xFF +}; + +enum UnitBytes0Offsets : uint8 +{ + 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 : uint8 +{ + 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 : uint8 +{ + UNIT_BYTES_2_OFFSET_SHEATH_STATE = 0, + UNIT_BYTES_2_OFFSET_PVP_FLAG = 1, + UNIT_BYTES_2_OFFSET_PET_FLAGS = 2, + UNIT_BYTES_2_OFFSET_SHAPESHIFT_FORM = 3, +}; + +// byte flags value (UNIT_FIELD_BYTES_1, 3) +enum UnitBytes1_Flags : uint8 +{ + UNIT_BYTE1_FLAG_ALWAYS_STAND = 0x01, + UNIT_BYTE1_FLAG_HOVER = 0x02, + UNIT_BYTE1_FLAG_UNK_3 = 0x04, + UNIT_BYTE1_FLAG_ALL = 0xFF +}; + +// low byte (0 from 0..3) of UNIT_FIELD_BYTES_2 +enum SheathState : uint8 +{ + SHEATH_STATE_UNARMED = 0, // non prepared weapon + SHEATH_STATE_MELEE = 1, // prepared melee weapon + SHEATH_STATE_RANGED = 2 // prepared ranged weapon +}; + +#define MAX_SHEATH_STATE 3 + +// byte (1 from 0..3) of UNIT_FIELD_BYTES_2 +enum UnitPVPStateFlags : uint8 +{ + UNIT_BYTE2_FLAG_PVP = 0x01, + UNIT_BYTE2_FLAG_UNK1 = 0x02, + UNIT_BYTE2_FLAG_FFA_PVP = 0x04, + UNIT_BYTE2_FLAG_SANCTUARY = 0x08, + UNIT_BYTE2_FLAG_UNK4 = 0x10, + UNIT_BYTE2_FLAG_UNK5 = 0x20, + UNIT_BYTE2_FLAG_UNK6 = 0x40, + UNIT_BYTE2_FLAG_UNK7 = 0x80 +}; + +// byte (2 from 0..3) of UNIT_FIELD_BYTES_2 +enum UnitRename : uint8 +{ + UNIT_CAN_BE_RENAMED = 0x01, + UNIT_CAN_BE_ABANDONED = 0x02 +}; + +// Value masks for UNIT_FIELD_FLAGS +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_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 + UNIT_FLAG_UNK_6 = 0x00000040, + UNIT_FLAG_NOT_ATTACKABLE_1 = 0x00000080, // ?? (UNIT_FLAG_PVP_ATTACKABLE | UNIT_FLAG_NOT_ATTACKABLE_1) is NON_PVP_ATTACKABLE + UNIT_FLAG_IMMUNE_TO_PC = 0x00000100, // disables combat/assistance with PlayerCharacters (PC) - see Unit::_IsValidAttackTarget, Unit::_IsValidAssistTarget + UNIT_FLAG_IMMUNE_TO_NPC = 0x00000200, // disables combat/assistance with NonPlayerCharacters (NPC) - see Unit::_IsValidAttackTarget, Unit::_IsValidAssistTarget + UNIT_FLAG_LOOTING = 0x00000400, // loot animation + 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_CANNOT_SWIM = 0x00004000, // 2.0.8 + UNIT_FLAG_UNK_15 = 0x00008000, + UNIT_FLAG_UNK_16 = 0x00010000, + UNIT_FLAG_PACIFIED = 0x00020000, // 3.0.3 ok + UNIT_FLAG_STUNNED = 0x00040000, // 3.0.3 ok + UNIT_FLAG_IN_COMBAT = 0x00080000, + UNIT_FLAG_TAXI_FLIGHT = 0x00100000, // disable casting at client side spell not allowed by taxi flight (mounted?), probably used with 0x4 flag + UNIT_FLAG_DISARMED = 0x00200000, // 3.0.3, disable melee spells casting..., "Required melee weapon" added to melee spells tooltip. + UNIT_FLAG_CONFUSED = 0x00400000, + UNIT_FLAG_FLEEING = 0x00800000, + UNIT_FLAG_PLAYER_CONTROLLED = 0x01000000, // used in spell Eyes of the Beast for pet... let attack by controlled creature + UNIT_FLAG_NOT_SELECTABLE = 0x02000000, + UNIT_FLAG_SKINNABLE = 0x04000000, + UNIT_FLAG_MOUNT = 0x08000000, + UNIT_FLAG_UNK_28 = 0x10000000, + UNIT_FLAG_UNK_29 = 0x20000000, // used in Feing Death spell + UNIT_FLAG_SHEATHE = 0x40000000, + UNIT_FLAG_UNK_31 = 0x80000000, + MAX_UNIT_FLAGS = 33 +}; + +// Value masks for UNIT_FIELD_FLAGS_2 +enum UnitFlags2 : uint32 +{ + UNIT_FLAG2_FEIGN_DEATH = 0x00000001, + UNIT_FLAG2_UNK1 = 0x00000002, // Hide unit model (show only player equip) + UNIT_FLAG2_IGNORE_REPUTATION = 0x00000004, + UNIT_FLAG2_COMPREHEND_LANG = 0x00000008, + UNIT_FLAG2_MIRROR_IMAGE = 0x00000010, + UNIT_FLAG2_INSTANTLY_APPEAR_MODEL = 0x00000020, // Unit model instantly appears when summoned (does not fade in) + UNIT_FLAG2_FORCE_MOVEMENT = 0x00000040, + UNIT_FLAG2_DISARM_OFFHAND = 0x00000080, + UNIT_FLAG2_DISABLE_PRED_STATS = 0x00000100, // Player has disabled predicted stats (Used by raid frames) + UNIT_FLAG2_DISARM_RANGED = 0x00000400, // this does not disable ranged weapon display (maybe additional flag needed?) + UNIT_FLAG2_REGENERATE_POWER = 0x00000800, + UNIT_FLAG2_RESTRICT_PARTY_INTERACTION = 0x00001000, // Restrict interaction to party or raid + UNIT_FLAG2_PREVENT_SPELL_CLICK = 0x00002000, // Prevent spellclick + UNIT_FLAG2_ALLOW_ENEMY_INTERACT = 0x00004000, + UNIT_FLAG2_DISABLE_TURN = 0x00008000, + UNIT_FLAG2_UNK2 = 0x00010000, + UNIT_FLAG2_PLAY_DEATH_ANIM = 0x00020000, // Plays special death animation upon death + UNIT_FLAG2_ALLOW_CHEAT_SPELLS = 0x00040000, // Allows casting spells with AttributesEx7 & SPELL_ATTR7_IS_CHEAT_SPELL + UNIT_FLAG2_NO_ACTIONS = 0x00800000 +}; + +/// Non Player Character flags +enum NPCFlags : uint32 +{ + UNIT_NPC_FLAG_NONE = 0x00000000, + UNIT_NPC_FLAG_GOSSIP = 0x00000001, // 100% + UNIT_NPC_FLAG_QUESTGIVER = 0x00000002, // 100% + UNIT_NPC_FLAG_UNK1 = 0x00000004, + UNIT_NPC_FLAG_UNK2 = 0x00000008, + UNIT_NPC_FLAG_TRAINER = 0x00000010, // 100% + UNIT_NPC_FLAG_TRAINER_CLASS = 0x00000020, // 100% + UNIT_NPC_FLAG_TRAINER_PROFESSION = 0x00000040, // 100% + UNIT_NPC_FLAG_VENDOR = 0x00000080, // 100% + UNIT_NPC_FLAG_VENDOR_AMMO = 0x00000100, // 100%, general goods vendor + UNIT_NPC_FLAG_VENDOR_FOOD = 0x00000200, // 100% + UNIT_NPC_FLAG_VENDOR_POISON = 0x00000400, // guessed + UNIT_NPC_FLAG_VENDOR_REAGENT = 0x00000800, // 100% + UNIT_NPC_FLAG_REPAIR = 0x00001000, // 100% + UNIT_NPC_FLAG_FLIGHTMASTER = 0x00002000, // 100% + UNIT_NPC_FLAG_SPIRITHEALER = 0x00004000, // guessed + UNIT_NPC_FLAG_SPIRITGUIDE = 0x00008000, // guessed + UNIT_NPC_FLAG_INNKEEPER = 0x00010000, // 100% + UNIT_NPC_FLAG_BANKER = 0x00020000, // 100% + UNIT_NPC_FLAG_PETITIONER = 0x00040000, // 100% 0xC0000 = guild petitions, 0x40000 = arena team petitions + UNIT_NPC_FLAG_TABARDDESIGNER = 0x00080000, // 100% + UNIT_NPC_FLAG_BATTLEMASTER = 0x00100000, // 100% + UNIT_NPC_FLAG_AUCTIONEER = 0x00200000, // 100% + UNIT_NPC_FLAG_STABLEMASTER = 0x00400000, // 100% + UNIT_NPC_FLAG_GUILD_BANKER = 0x00800000, // cause client to send 997 opcode + UNIT_NPC_FLAG_SPELLCLICK = 0x01000000, // cause client to send 1015 opcode (spell click) + UNIT_NPC_FLAG_PLAYER_VEHICLE = 0x02000000, // players with mounts that have vehicle data should have it set + UNIT_NPC_FLAG_MAILBOX = 0x04000000, // mailbox + UNIT_NPC_FLAG_REFORGER = 0x08000000, // reforging + UNIT_NPC_FLAG_TRANSMOGRIFIER = 0x10000000, // transmogrification + UNIT_NPC_FLAG_VAULTKEEPER = 0x20000000 // void storage +}; + +enum MovementFlags : uint32 +{ + MOVEMENTFLAG_NONE = 0x00000000, + MOVEMENTFLAG_FORWARD = 0x00000001, + MOVEMENTFLAG_BACKWARD = 0x00000002, + MOVEMENTFLAG_STRAFE_LEFT = 0x00000004, + MOVEMENTFLAG_STRAFE_RIGHT = 0x00000008, + MOVEMENTFLAG_LEFT = 0x00000010, + MOVEMENTFLAG_RIGHT = 0x00000020, + MOVEMENTFLAG_PITCH_UP = 0x00000040, + MOVEMENTFLAG_PITCH_DOWN = 0x00000080, + MOVEMENTFLAG_WALKING = 0x00000100, // Walking + MOVEMENTFLAG_DISABLE_GRAVITY = 0x00000200, // Former MOVEMENTFLAG_LEVITATING. This is used when walking is not possible. + MOVEMENTFLAG_ROOT = 0x00000400, // Must not be set along with MOVEMENTFLAG_MASK_MOVING + MOVEMENTFLAG_FALLING = 0x00000800, // damage dealt on that type of falling + MOVEMENTFLAG_FALLING_FAR = 0x00001000, + MOVEMENTFLAG_PENDING_STOP = 0x00002000, + MOVEMENTFLAG_PENDING_STRAFE_STOP = 0x00004000, + MOVEMENTFLAG_PENDING_FORWARD = 0x00008000, + MOVEMENTFLAG_PENDING_BACKWARD = 0x00010000, + MOVEMENTFLAG_PENDING_STRAFE_LEFT = 0x00020000, + MOVEMENTFLAG_PENDING_STRAFE_RIGHT = 0x00040000, + MOVEMENTFLAG_PENDING_ROOT = 0x00080000, + MOVEMENTFLAG_SWIMMING = 0x00100000, // appears with fly flag also + MOVEMENTFLAG_ASCENDING = 0x00200000, // press "space" when flying + MOVEMENTFLAG_DESCENDING = 0x00400000, + MOVEMENTFLAG_CAN_FLY = 0x00800000, // Appears when unit can fly AND also walk + MOVEMENTFLAG_FLYING = 0x01000000, // unit is actually flying. pretty sure this is only used for players. creatures use disable_gravity + MOVEMENTFLAG_SPLINE_ELEVATION = 0x02000000, // used for flight paths + MOVEMENTFLAG_WATERWALKING = 0x04000000, // prevent unit from falling through water + MOVEMENTFLAG_FALLING_SLOW = 0x08000000, // active rogue safe fall spell (passive) + MOVEMENTFLAG_HOVER = 0x10000000, // hover, cannot jump + MOVEMENTFLAG_DISABLE_COLLISION = 0x20000000, + + MOVEMENTFLAG_MASK_MOVING = + MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_BACKWARD | MOVEMENTFLAG_STRAFE_LEFT | MOVEMENTFLAG_STRAFE_RIGHT | + MOVEMENTFLAG_FALLING | MOVEMENTFLAG_FALLING_FAR | MOVEMENTFLAG_ASCENDING | MOVEMENTFLAG_DESCENDING | + MOVEMENTFLAG_SPLINE_ELEVATION, + + MOVEMENTFLAG_MASK_TURNING = + MOVEMENTFLAG_LEFT | MOVEMENTFLAG_RIGHT | MOVEMENTFLAG_PITCH_UP | MOVEMENTFLAG_PITCH_DOWN, + + MOVEMENTFLAG_MASK_MOVING_FLY = + MOVEMENTFLAG_FLYING | MOVEMENTFLAG_ASCENDING | MOVEMENTFLAG_DESCENDING, + + // Movement flags allowed for creature in CreateObject - we need to keep all other enabled serverside + // to properly calculate all movement + MOVEMENTFLAG_MASK_CREATURE_ALLOWED = + MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_DISABLE_GRAVITY | MOVEMENTFLAG_ROOT | MOVEMENTFLAG_SWIMMING | + MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_WATERWALKING | MOVEMENTFLAG_FALLING_SLOW | MOVEMENTFLAG_HOVER, + + /// @todo if needed: add more flags to this masks that are exclusive to players + MOVEMENTFLAG_MASK_PLAYER_ONLY = + MOVEMENTFLAG_FLYING, + + /// Movement flags that have change status opcodes associated for players + MOVEMENTFLAG_MASK_HAS_PLAYER_STATUS_OPCODE = MOVEMENTFLAG_DISABLE_GRAVITY | MOVEMENTFLAG_ROOT | + MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_WATERWALKING | MOVEMENTFLAG_FALLING_SLOW | MOVEMENTFLAG_HOVER +}; + +enum MovementFlags2 : uint32 +{ + MOVEMENTFLAG2_NONE = 0x00000000, + MOVEMENTFLAG2_NO_STRAFE = 0x00000001, + MOVEMENTFLAG2_NO_JUMPING = 0x00000002, + MOVEMENTFLAG2_FULL_SPEED_TURNING = 0x00000004, + MOVEMENTFLAG2_FULL_SPEED_PITCHING = 0x00000008, + MOVEMENTFLAG2_ALWAYS_ALLOW_PITCHING = 0x00000010, + MOVEMENTFLAG2_UNK5 = 0x00000020, + MOVEMENTFLAG2_UNK6 = 0x00000040, + MOVEMENTFLAG2_UNK7 = 0x00000080, + MOVEMENTFLAG2_UNK8 = 0x00000100, + MOVEMENTFLAG2_UNK9 = 0x00000200, + MOVEMENTFLAG2_CAN_SWIM_TO_FLY_TRANS = 0x00000400, + MOVEMENTFLAG2_UNK11 = 0x00000800, + MOVEMENTFLAG2_UNK12 = 0x00001000, + MOVEMENTFLAG2_INTERPOLATED_MOVEMENT = 0x00002000, + MOVEMENTFLAG2_INTERPOLATED_TURNING = 0x00004000, + MOVEMENTFLAG2_INTERPOLATED_PITCHING = 0x00008000 +}; + +enum HitInfo +{ + HITINFO_NORMALSWING = 0x00000000, + HITINFO_UNK1 = 0x00000001, // req correct packet structure + HITINFO_AFFECTS_VICTIM = 0x00000002, + HITINFO_OFFHAND = 0x00000004, + HITINFO_UNK2 = 0x00000008, + HITINFO_MISS = 0x00000010, + HITINFO_FULL_ABSORB = 0x00000020, + HITINFO_PARTIAL_ABSORB = 0x00000040, + HITINFO_FULL_RESIST = 0x00000080, + HITINFO_PARTIAL_RESIST = 0x00000100, + HITINFO_CRITICALHIT = 0x00000200, // critical hit + HITINFO_UNK10 = 0x00000400, + HITINFO_UNK11 = 0x00000800, + HITINFO_UNK12 = 0x00001000, + HITINFO_BLOCK = 0x00002000, // blocked damage + HITINFO_UNK14 = 0x00004000, // set only if meleespellid is present// no world text when victim is hit for 0 dmg(HideWorldTextForNoDamage?) + HITINFO_UNK15 = 0x00008000, // player victim?// something related to blod sprut visual (BloodSpurtInBack?) + HITINFO_GLANCING = 0x00010000, + HITINFO_CRUSHING = 0x00020000, + HITINFO_NO_ANIMATION = 0x00040000, + HITINFO_UNK19 = 0x00080000, + HITINFO_UNK20 = 0x00100000, + HITINFO_SWINGNOHITSOUND = 0x00200000, // unused? + HITINFO_UNK22 = 0x00400000, + HITINFO_RAGE_GAIN = 0x00800000, + HITINFO_FAKE_DAMAGE = 0x01000000 // enables damage animation even if no damage done, set only if no damage +}; + +#define MAX_DECLINED_NAME_CASES 5 + +struct DeclinedName +{ + std::string name[MAX_DECLINED_NAME_CASES]; +}; + +enum ActiveStates +{ + ACT_PASSIVE = 0x01, // 0x01 - passive + ACT_DISABLED = 0x81, // 0x80 - castable + ACT_ENABLED = 0xC1, // 0x40 | 0x80 - auto cast + castable + ACT_COMMAND = 0x07, // 0x01 | 0x02 | 0x04 + ACT_REACTION = 0x06, // 0x02 | 0x04 + ACT_DECIDE = 0x00 // custom +}; + +enum ReactStates +{ + REACT_PASSIVE = 0, + REACT_DEFENSIVE = 1, + REACT_AGGRESSIVE = 2 +}; + +enum CommandStates : uint8 +{ + COMMAND_STAY = 0, + COMMAND_FOLLOW = 1, + COMMAND_ATTACK = 2, + COMMAND_ABANDON = 3, + COMMAND_MOVE_TO = 4 +}; + +#endif // UnitDefines_h__ diff --git a/src/server/game/Entities/Vehicle/Vehicle.cpp b/src/server/game/Entities/Vehicle/Vehicle.cpp index 0fd8ec92ed2..aebaa09b2c2 100644 --- a/src/server/game/Entities/Vehicle/Vehicle.cpp +++ b/src/server/game/Entities/Vehicle/Vehicle.cpp @@ -16,19 +16,21 @@ * with this program. If not, see . */ -#include "Common.h" -#include "Log.h" -#include "ObjectMgr.h" #include "Vehicle.h" +#include "Battleground.h" +#include "Common.h" +#include "CreatureAI.h" +#include "DBCStores.h" +#include "EventProcessor.h" +#include "Log.h" +#include "MoveSplineInit.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "ScriptMgr.h" +#include "TemporarySummon.h" #include "Unit.h" #include "Util.h" -#include "ScriptMgr.h" -#include "CreatureAI.h" -#include "MoveSplineInit.h" -#include "TemporarySummon.h" -#include "EventProcessor.h" -#include "Player.h" -#include "Battleground.h" Vehicle::Vehicle(Unit* unit, VehicleEntry const* vehInfo, uint32 creatureEntry) : UsableSeatNum(0), _me(unit), _vehicleInfo(vehInfo), _creatureEntry(creatureEntry), _status(STATUS_NONE), _lastShootPos() @@ -281,7 +283,7 @@ void Vehicle::RemoveAllPassengers() /// This will properly "reset" the pending join process for the passenger. { /// Update vehicle pointer in every pending join event - Abort may be called after vehicle is deleted - Vehicle* eventVehicle = _status != STATUS_UNINSTALLING ? this : NULL; + Vehicle* eventVehicle = _status != STATUS_UNINSTALLING ? this : nullptr; while (!_pendingJoinEvents.empty()) { @@ -342,7 +344,7 @@ Unit* Vehicle::GetPassenger(int8 seatId) const { SeatMap::const_iterator seat = Seats.find(seatId); if (seat == Seats.end()) - return NULL; + return nullptr; return ObjectAccessor::GetUnit(*GetBase(), seat->second.Passenger.Guid); } @@ -522,7 +524,7 @@ bool Vehicle::AddPassenger(Unit* unit, int8 seatId) Vehicle* Vehicle::RemovePassenger(Unit* unit) { if (unit->GetVehicle() != this) - return NULL; + return nullptr; SeatMap::iterator seat = GetSeatIteratorForPassenger(unit); ASSERT(seat != Seats.end()); @@ -560,7 +562,7 @@ Vehicle* Vehicle::RemovePassenger(Unit* unit) if (GetBase()->GetTypeId() == TYPEID_UNIT) sScriptMgr->OnRemovePassenger(this, unit); - unit->SetVehicle(NULL); + unit->SetVehicle(nullptr); return this; } @@ -662,7 +664,7 @@ VehicleSeatEntry const* Vehicle::GetSeatForPassenger(Unit const* passenger) cons if (itr->second.Passenger.Guid == passenger->GetGUID()) return itr->second.SeatInfo; - return NULL; + return nullptr; } /** diff --git a/src/server/game/Entities/Vehicle/Vehicle.h b/src/server/game/Entities/Vehicle/Vehicle.h index 2b0022637bd..8dd20beef33 100644 --- a/src/server/game/Entities/Vehicle/Vehicle.h +++ b/src/server/game/Entities/Vehicle/Vehicle.h @@ -87,7 +87,7 @@ class TC_GAME_API Vehicle : public TransportBase void InitMovementInfoForBase(); /// This method transforms supplied transport offsets into global coordinates - void CalculatePassengerPosition(float& x, float& y, float& z, float* o /*= NULL*/) const override + void CalculatePassengerPosition(float& x, float& y, float& z, float* o /*= nullptr*/) const override { TransportBase::CalculatePassengerPosition(x, y, z, o, GetBase()->GetPositionX(), GetBase()->GetPositionY(), @@ -95,7 +95,7 @@ class TC_GAME_API Vehicle : public TransportBase } /// This method transforms supplied global coordinates into local offsets - void CalculatePassengerOffset(float& x, float& y, float& z, float* o /*= NULL*/) const override + void CalculatePassengerOffset(float& x, float& y, float& z, float* o /*= nullptr*/) const override { TransportBase::CalculatePassengerOffset(x, y, z, o, GetBase()->GetPositionX(), GetBase()->GetPositionY(), diff --git a/src/server/game/Entities/Vehicle/VehicleDefines.h b/src/server/game/Entities/Vehicle/VehicleDefines.h index 9e4b90beb41..b3d5238b541 100644 --- a/src/server/game/Entities/Vehicle/VehicleDefines.h +++ b/src/server/game/Entities/Vehicle/VehicleDefines.h @@ -124,10 +124,10 @@ protected: public: /// This method transforms supplied transport offsets into global coordinates - virtual void CalculatePassengerPosition(float& x, float& y, float& z, float* o = NULL) const = 0; + virtual void CalculatePassengerPosition(float& x, float& y, float& z, float* o = nullptr) const = 0; /// This method transforms supplied global coordinates into local offsets - virtual void CalculatePassengerOffset(float& x, float& y, float& z, float* o = NULL) const = 0; + virtual void CalculatePassengerOffset(float& x, float& y, float& z, float* o = nullptr) const = 0; protected: static void CalculatePassengerPosition(float& x, float& y, float& z, float* o, float transX, float transY, float transZ, float transO) diff --git a/src/server/game/Events/GameEventMgr.cpp b/src/server/game/Events/GameEventMgr.cpp index 2afac887fc5..fab4f09bb09 100644 --- a/src/server/game/Events/GameEventMgr.cpp +++ b/src/server/game/Events/GameEventMgr.cpp @@ -17,17 +17,21 @@ */ #include "GameEventMgr.h" -#include "World.h" -#include "ObjectMgr.h" -#include "WorldPacket.h" -#include "PoolMgr.h" +#include "BattlegroundMgr.h" +#include "CreatureAI.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "GameObjectAI.h" +#include "GameTime.h" #include "Language.h" #include "Log.h" #include "MapManager.h" +#include "ObjectMgr.h" #include "Player.h" -#include "BattlegroundMgr.h" +#include "PoolMgr.h" #include "UnitAI.h" -#include "GameObjectAI.h" +#include "World.h" +#include "WorldPacket.h" GameEventMgr* GameEventMgr::instance() { @@ -141,7 +145,7 @@ bool GameEventMgr::StartEvent(uint16 event_id, bool overwrite) } // When event is started, set its worldstate to current time - sWorld->setWorldState(event_id, time(NULL)); + sWorld->setWorldState(event_id, time(nullptr)); return false; } else @@ -182,7 +186,7 @@ void GameEventMgr::StopEvent(uint16 event_id, bool overwrite) if (overwrite && !serverwide_evt) { - data.start = time(NULL) - data.length * MINUTE; + data.start = time(nullptr) - data.length * MINUTE; if (data.end <= data.start) data.end = data.start + data.length; } @@ -844,7 +848,7 @@ void GameEventMgr::LoadFromDB() newEntry.entry = data->id; // check validity with event's npcflag - if (!sObjectMgr->IsVendorItemValid(newEntry.entry, newEntry.item, newEntry.maxcount, newEntry.incrtime, newEntry.ExtendedCost, newEntry.Type, NULL, NULL, event_npc_flag)) + if (!sObjectMgr->IsVendorItemValid(newEntry.entry, newEntry.item, newEntry.maxcount, newEntry.incrtime, newEntry.ExtendedCost, newEntry.Type, nullptr, nullptr, event_npc_flag)) continue; vendors.push_back(newEntry); diff --git a/src/server/game/Events/GameEventMgr.h b/src/server/game/Events/GameEventMgr.h index e77295e32ce..1ef330d7237 100644 --- a/src/server/game/Events/GameEventMgr.h +++ b/src/server/game/Events/GameEventMgr.h @@ -23,6 +23,11 @@ #include "ObjectGuid.h" #include "SharedDefines.h" #include "Define.h" +#include +#include +#include +#include +#include #define max_ge_check_delay DAY // 1 day in seconds diff --git a/src/server/game/Globals/ObjectAccessor.cpp b/src/server/game/Globals/ObjectAccessor.cpp index 1fbe8c99247..6a0addb4f83 100644 --- a/src/server/game/Globals/ObjectAccessor.cpp +++ b/src/server/game/Globals/ObjectAccessor.cpp @@ -37,6 +37,10 @@ template void HashMapHolder::Insert(T* o) { + static_assert(std::is_same::value + || std::is_same::value, + "Only Player and Transport can be registered in global HashMapHolder"); + boost::unique_lock lock(*GetLock()); GetContainer()[o->GetGUID()] = o; @@ -56,7 +60,7 @@ T* HashMapHolder::Find(ObjectGuid guid) boost::shared_lock lock(*GetLock()); typename MapType::iterator itr = GetContainer().find(guid); - return (itr != GetContainer().end()) ? itr->second : NULL; + return (itr != GetContainer().end()) ? itr->second : nullptr; } template diff --git a/src/server/game/Globals/ObjectAccessor.h b/src/server/game/Globals/ObjectAccessor.h index fcebdac8efc..074ac6f981e 100644 --- a/src/server/game/Globals/ObjectAccessor.h +++ b/src/server/game/Globals/ObjectAccessor.h @@ -19,27 +19,26 @@ #ifndef TRINITY_OBJECTACCESSOR_H #define TRINITY_OBJECTACCESSOR_H -#include -#include +#include "ObjectGuid.h" #include -#include -#include -#include "Define.h" -#include "GridDefines.h" -#include "UpdateData.h" -#include "Object.h" - -class Creature; +class AreaTrigger; class Corpse; -class Unit; -class GameObject; +class Creature; class DynamicObject; -class WorldObject; -class Vehicle; +class GameObject; class Map; -class WorldRunnable; +class Object; +class Pet; +class Player; class Transport; +class Unit; +class WorldObject; + +namespace boost +{ + class shared_mutex; +} template class TC_GAME_API HashMapHolder @@ -48,10 +47,6 @@ class TC_GAME_API HashMapHolder HashMapHolder() { } public: - static_assert(std::is_same::value - || std::is_same::value, - "Only Player and Transport can be registered in global HashMapHolder"); - typedef std::unordered_map MapType; static void Insert(T* o); diff --git a/src/server/game/Globals/ObjectMgr.cpp b/src/server/game/Globals/ObjectMgr.cpp index d6b425de866..cb5484b961b 100644 --- a/src/server/game/Globals/ObjectMgr.cpp +++ b/src/server/game/Globals/ObjectMgr.cpp @@ -16,19 +16,19 @@ * with this program. If not, see . */ +#include "ObjectMgr.h" #include "AccountMgr.h" #include "AchievementMgr.h" -#include "ArenaTeam.h" #include "ArenaTeamMgr.h" -#include "BattlegroundMgr.h" +#include "Bag.h" #include "Chat.h" -#include "Common.h" #include "Containers.h" #include "CreatureAIFactory.h" #include "DatabaseEnv.h" #include "DB2Structure.h" #include "DB2Stores.h" #include "DisableMgr.h" +#include "GameObject.h" #include "GameObjectAIFactory.h" #include "GossipDef.h" #include "GroupMgr.h" @@ -37,16 +37,21 @@ #include "Language.h" #include "LFGMgr.h" #include "Log.h" +#include "LootMgr.h" +#include "Mail.h" #include "MapManager.h" -#include "Object.h" -#include "ObjectMgr.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "PhasingHandler.h" +#include "Player.h" #include "PoolMgr.h" +#include "Random.h" #include "ReputationMgr.h" #include "ScriptMgr.h" #include "SpellAuras.h" #include "SpellMgr.h" #include "SpellScript.h" +#include "TemporarySummon.h" #include "UpdateMask.h" #include "Util.h" #include "Vehicle.h" @@ -280,7 +285,7 @@ ObjectMgr::~ObjectMgr() delete itr->second; } -void ObjectMgr::AddLocaleString(std::string const& value, LocaleConstant localeConstant, StringVector& data) +void ObjectMgr::AddLocaleString(std::string const& value, LocaleConstant localeConstant, std::vector& data) { if (!value.empty()) { @@ -1219,7 +1224,7 @@ void ObjectMgr::LoadGameObjectAddons() } GameObjectAddon& gameObjectAddon = _gameObjectAddonStore[guid]; - gameObjectAddon.ParentRotation = G3D::Quat(fields[1].GetFloat(), fields[2].GetFloat(), fields[3].GetFloat(), fields[4].GetFloat()); + gameObjectAddon.ParentRotation = QuaternionData(fields[1].GetFloat(), fields[2].GetFloat(), fields[3].GetFloat(), fields[4].GetFloat()); gameObjectAddon.invisibilityType = InvisibilityType(fields[5].GetUInt8()); gameObjectAddon.InvisibilityValue = fields[6].GetUInt32(); @@ -1239,7 +1244,7 @@ void ObjectMgr::LoadGameObjectAddons() if (!gameObjectAddon.ParentRotation.isUnit()) { TC_LOG_ERROR("sql.sql", "GameObject (GUID: %u) has invalid parent rotation in `gameobject_addon`, set to default", guid); - gameObjectAddon.ParentRotation = G3D::Quat(); + gameObjectAddon.ParentRotation = QuaternionData(); } ++count; @@ -1401,7 +1406,7 @@ uint32 ObjectMgr::ChooseDisplayId(CreatureTemplate const* cinfo, CreatureData co return cinfo->GetFirstInvisibleModel(); } -void ObjectMgr::ChooseCreatureFlags(const CreatureTemplate* cinfo, uint32& npcflag, uint32& unit_flags, uint32& dynamicflags, const CreatureData* data /*= nullptr*/) +void ObjectMgr::ChooseCreatureFlags(CreatureTemplate const* cinfo, uint32& npcflag, uint32& unit_flags, uint32& dynamicflags, CreatureData const* data /*= nullptr*/) { npcflag = cinfo->npcflag; unit_flags = cinfo->unit_flags; @@ -1531,7 +1536,7 @@ void ObjectMgr::LoadLinkedRespawn() { case CREATURE_TO_CREATURE: { - const CreatureData* slave = GetCreatureData(guidLow); + CreatureData const* slave = GetCreatureData(guidLow); if (!slave) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Creature (guid) '%u' not found in creature table", guidLow); @@ -1539,7 +1544,7 @@ void ObjectMgr::LoadLinkedRespawn() break; } - const CreatureData* master = GetCreatureData(linkedGuidLow); + CreatureData const* master = GetCreatureData(linkedGuidLow); if (!master) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Creature (linkedGuid) '%u' not found in creature table", linkedGuidLow); @@ -1547,7 +1552,7 @@ void ObjectMgr::LoadLinkedRespawn() break; } - const MapEntry* const map = sMapStore.LookupEntry(master->mapid); + MapEntry const* const map = sMapStore.LookupEntry(master->mapid); if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Creature '%u' linking to Creature '%u' on an unpermitted map.", guidLow, linkedGuidLow); @@ -1568,7 +1573,7 @@ void ObjectMgr::LoadLinkedRespawn() } case CREATURE_TO_GO: { - const CreatureData* slave = GetCreatureData(guidLow); + CreatureData const* slave = GetCreatureData(guidLow); if (!slave) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Creature (guid) '%u' not found in creature table", guidLow); @@ -1576,7 +1581,7 @@ void ObjectMgr::LoadLinkedRespawn() break; } - const GameObjectData* master = GetGOData(linkedGuidLow); + GameObjectData const* master = GetGOData(linkedGuidLow); if (!master) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Gameobject (linkedGuid) '%u' not found in gameobject table", linkedGuidLow); @@ -1584,7 +1589,7 @@ void ObjectMgr::LoadLinkedRespawn() break; } - const MapEntry* const map = sMapStore.LookupEntry(master->mapid); + MapEntry const* const map = sMapStore.LookupEntry(master->mapid); if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Creature '%u' linking to Gameobject '%u' on an unpermitted map.", guidLow, linkedGuidLow); @@ -1605,7 +1610,7 @@ void ObjectMgr::LoadLinkedRespawn() } case GO_TO_GO: { - const GameObjectData* slave = GetGOData(guidLow); + GameObjectData const* slave = GetGOData(guidLow); if (!slave) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Gameobject (guid) '%u' not found in gameobject table", guidLow); @@ -1613,7 +1618,7 @@ void ObjectMgr::LoadLinkedRespawn() break; } - const GameObjectData* master = GetGOData(linkedGuidLow); + GameObjectData const* master = GetGOData(linkedGuidLow); if (!master) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Gameobject (linkedGuid) '%u' not found in gameobject table", linkedGuidLow); @@ -1621,7 +1626,7 @@ void ObjectMgr::LoadLinkedRespawn() break; } - const MapEntry* const map = sMapStore.LookupEntry(master->mapid); + MapEntry const* const map = sMapStore.LookupEntry(master->mapid); if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Gameobject '%u' linking to Gameobject '%u' on an unpermitted map.", guidLow, linkedGuidLow); @@ -1642,7 +1647,7 @@ void ObjectMgr::LoadLinkedRespawn() } case GO_TO_CREATURE: { - const GameObjectData* slave = GetGOData(guidLow); + GameObjectData const* slave = GetGOData(guidLow); if (!slave) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Gameobject (guid) '%u' not found in gameobject table", guidLow); @@ -1650,7 +1655,7 @@ void ObjectMgr::LoadLinkedRespawn() break; } - const CreatureData* master = GetCreatureData(linkedGuidLow); + CreatureData const* master = GetCreatureData(linkedGuidLow); if (!master) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Creature (linkedGuid) '%u' not found in creature table", linkedGuidLow); @@ -1658,7 +1663,7 @@ void ObjectMgr::LoadLinkedRespawn() break; } - const MapEntry* const map = sMapStore.LookupEntry(master->mapid); + MapEntry const* const map = sMapStore.LookupEntry(master->mapid); if (!map || !map->Instanceable() || (master->mapid != slave->mapid)) { TC_LOG_ERROR("sql.sql", "LinkedRespawn: Gameobject '%u' linking to Creature '%u' on an unpermitted map.", guidLow, linkedGuidLow); @@ -2070,7 +2075,7 @@ void ObjectMgr::RemoveCreatureFromGrid(ObjectGuid::LowType guid, CreatureData co } } -ObjectGuid::LowType ObjectMgr::AddGOData(uint32 entry, uint32 mapId, Position const& pos, G3D::Quat const& rot, uint32 spawntimedelay /*= 0*/) +ObjectGuid::LowType ObjectMgr::AddGOData(uint32 entry, uint32 mapId, Position const& pos, QuaternionData const& rot, uint32 spawntimedelay /*= 0*/) { GameObjectTemplate const* goinfo = GetGameObjectTemplate(entry); if (!goinfo) @@ -4822,6 +4827,18 @@ void ObjectMgr::LoadQuests() TC_LOG_INFO("server.loading", ">> Loaded %lu quests definitions in %u ms", (unsigned long)_questTemplates.size(), GetMSTimeDiffToNow(oldMSTime)); } +void ObjectMgr::LoadQuestStartersAndEnders() +{ + TC_LOG_INFO("server.loading", "Loading GO Start Quest Data..."); + LoadGameobjectQuestStarters(); + TC_LOG_INFO("server.loading", "Loading GO End Quest Data..."); + LoadGameobjectQuestEnders(); + TC_LOG_INFO("server.loading", "Loading Creature Start Quest Data..."); + LoadCreatureQuestStarters(); + TC_LOG_INFO("server.loading", "Loading Creature End Quest Data..."); + LoadCreatureQuestEnders(); +} + void ObjectMgr::LoadQuestLocales() { uint32 oldMSTime = getMSTime(); @@ -6264,7 +6281,7 @@ 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, GhostZone, Faction FROM graveyard_zone"); @@ -6313,14 +6330,14 @@ void ObjectMgr::LoadGraveyardZones() continue; } - if (!AddGraveYardLink(safeLocId, zoneId, team, false)) + if (!AddGraveyardLink(safeLocId, zoneId, team, false)) 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)); } -WorldSafeLocsEntry const* ObjectMgr::GetDefaultGraveYard(uint32 team) const +WorldSafeLocsEntry const* ObjectMgr::GetDefaultGraveyard(uint32 team) const { enum DefaultGraveyard { @@ -6335,7 +6352,7 @@ WorldSafeLocsEntry const* ObjectMgr::GetDefaultGraveYard(uint32 team) const else return nullptr; } -WorldSafeLocsEntry const* ObjectMgr::GetClosestGraveYard(WorldLocation const& location, uint32 team, WorldObject* conditionObject) const +WorldSafeLocsEntry const* ObjectMgr::GetClosestGraveyard(WorldLocation const& location, uint32 team, WorldObject* conditionObject) const { float x, y, z; location.GetPosition(x, y, z); @@ -6349,7 +6366,7 @@ WorldSafeLocsEntry const* ObjectMgr::GetClosestGraveYard(WorldLocation const& lo if (z > -500) { TC_LOG_ERROR("misc", "ZoneId not found for map %u coords (%f, %f, %f)", MapId, x, y, z); - return GetDefaultGraveYard(team); + return GetDefaultGraveyard(team); } } @@ -6360,7 +6377,7 @@ WorldSafeLocsEntry const* ObjectMgr::GetClosestGraveYard(WorldLocation const& lo // then check faction // if mapId != graveyard.mapId (ghost in instance) and search any graveyard associated // then check faction - GraveYardMapBounds range = GraveYardStore.equal_range(zoneId); + GraveyardMapBounds range = GraveyardStore.equal_range(zoneId); MapEntry const* map = sMapStore.LookupEntry(MapId); // not need to check validity of map object; MapId _MUST_ be valid here @@ -6368,7 +6385,7 @@ WorldSafeLocsEntry const* ObjectMgr::GetClosestGraveYard(WorldLocation const& lo { if (zoneId != 0) // zone == 0 can't be fixed, used by bliz for bugged zones TC_LOG_ERROR("sql.sql", "Table `graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.", zoneId, team); - return GetDefaultGraveYard(team); + return GetDefaultGraveyard(team); } // at corpse map @@ -6390,7 +6407,7 @@ WorldSafeLocsEntry const* ObjectMgr::GetClosestGraveYard(WorldLocation const& lo for (; range.first != range.second; ++range.first) { - GraveYardData const& data = range.first->second; + GraveyardData const& data = range.first->second; WorldSafeLocsEntry const* entry = sWorldSafeLocsStore.AssertEntry(data.safeLocId); @@ -6470,29 +6487,39 @@ WorldSafeLocsEntry const* ObjectMgr::GetClosestGraveYard(WorldLocation const& lo return entryFar; } -GraveYardData const* ObjectMgr::FindGraveYardData(uint32 id, uint32 zoneId) const +GraveyardData const* ObjectMgr::FindGraveyardData(uint32 id, uint32 zoneId) const { - GraveYardMapBounds range = GraveYardStore.equal_range(zoneId); + GraveyardMapBounds range = GraveyardStore.equal_range(zoneId); for (; range.first != range.second; ++range.first) { - GraveYardData const& data = range.first->second; + GraveyardData const& data = range.first->second; if (data.safeLocId == id) return &data; } return nullptr; } -bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool persist /*= true*/) +AreaTriggerStruct const* ObjectMgr::GetAreaTrigger(uint32 trigger) const { - if (FindGraveYardData(id, zoneId)) + return Trinity::Containers::MapGetValuePtr(_areaTriggerStore, trigger); +} + +AccessRequirement const* ObjectMgr::GetAccessRequirement(uint32 mapid, Difficulty difficulty) const +{ + return Trinity::Containers::MapGetValuePtr(_accessRequirementStore, MAKE_PAIR32(mapid, difficulty)); +} + +bool ObjectMgr::AddGraveyardLink(uint32 id, uint32 zoneId, uint32 team, bool persist /*= true*/) +{ + if (FindGraveyardData(id, zoneId)) return false; // add link to loaded data - GraveYardData data; + GraveyardData data; data.safeLocId = id; data.team = team; - GraveYardStore.insert(GraveYardContainer::value_type(zoneId, data)); + GraveyardStore.insert(GraveyardContainer::value_type(zoneId, data)); // add link to DB if (persist) @@ -6509,9 +6536,9 @@ bool ObjectMgr::AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool per return true; } -void ObjectMgr::RemoveGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool persist /*= false*/) +void ObjectMgr::RemoveGraveyardLink(uint32 id, uint32 zoneId, uint32 team, bool persist /*= false*/) { - GraveYardMapBoundsNonConst range = GraveYardStore.equal_range(zoneId); + GraveyardMapBoundsNonConst range = GraveyardStore.equal_range(zoneId); if (range.first == range.second) { //TC_LOG_ERROR("sql.sql", "Table `graveyard_zone` incomplete: Zone %u Team %u does not have a linked graveyard.", zoneId, team); @@ -6523,7 +6550,7 @@ void ObjectMgr::RemoveGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool for (; range.first != range.second; ++range.first) { - GraveYardData & data = range.first->second; + GraveyardData & data = range.first->second; // skip not matching safezone id if (data.safeLocId != id) @@ -6543,7 +6570,7 @@ void ObjectMgr::RemoveGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool return; // remove from links - GraveYardStore.erase(range.first); + GraveyardStore.erase(range.first); // remove link from DB if (persist) @@ -6720,13 +6747,13 @@ AreaTriggerStruct const* ObjectMgr::GetGoBackTrigger(uint32 Map) const { bool useParentDbValue = false; uint32 parentId = 0; - const MapEntry* mapEntry = sMapStore.LookupEntry(Map); + MapEntry const* mapEntry = sMapStore.LookupEntry(Map); if (!mapEntry || mapEntry->entrance_map < 0) return nullptr; if (mapEntry->IsDungeon()) { - const InstanceTemplate* iTemplate = sObjectMgr->GetInstanceTemplate(Map); + InstanceTemplate const* iTemplate = sObjectMgr->GetInstanceTemplate(Map); if (!iTemplate) return nullptr; @@ -7311,12 +7338,12 @@ void ObjectMgr::LoadPetNumber() TC_LOG_INFO("server.loading", ">> Loaded the max pet number: %d in %u ms", _hiPetNumber-1, GetMSTimeDiffToNow(oldMSTime)); } -std::string ObjectMgr::GeneratePetName(uint32 entry) +std::string ObjectMgr::GeneratePetName(uint32 entry) const { - StringVector& list0 = _petHalfName0[entry]; - StringVector& list1 = _petHalfName1[entry]; + auto it0 = _petHalfName0.find(entry); + auto it1 = _petHalfName1.find(entry); - if (list0.empty() || list1.empty()) + if (it0 == _petHalfName0.end() || it0->second.empty() || it1 == _petHalfName1.end() || it1->second.empty()) { CreatureTemplate const* cinfo = GetCreatureTemplate(entry); if (!cinfo) @@ -7329,7 +7356,7 @@ std::string ObjectMgr::GeneratePetName(uint32 entry) return cinfo->Name; } - return *(list0.begin()+urand(0, list0.size()-1)) + *(list1.begin()+urand(0, list1.size()-1)); + return Trinity::Containers::SelectRandomContainerElement(it0->second) + Trinity::Containers::SelectRandomContainerElement(it1->second); } void ObjectMgr::LoadReputationRewardRate() @@ -9828,6 +9855,11 @@ VehicleAccessoryList const* ObjectMgr::GetVehicleAccessoryList(Vehicle* veh) con return nullptr; } +DungeonEncounterList const* ObjectMgr::GetDungeonEncounterList(uint32 mapid, Difficulty difficulty) const +{ + return Trinity::Containers::MapGetValuePtr(_dungeonEncounterStore, MAKE_PAIR32(mapid, difficulty)); +} + PlayerInfo const* ObjectMgr::GetPlayerInfo(uint32 race, uint32 class_) const { if (race >= MAX_RACES) diff --git a/src/server/game/Globals/ObjectMgr.h b/src/server/game/Globals/ObjectMgr.h index 7d443adc5f7..820fd883fed 100644 --- a/src/server/game/Globals/ObjectMgr.h +++ b/src/server/game/Globals/ObjectMgr.h @@ -19,38 +19,34 @@ #ifndef _OBJECTMGR_H #define _OBJECTMGR_H -#include "Log.h" -#include "Object.h" -#include "Bag.h" -#include "Creature.h" -#include "DynamicObject.h" -#include "GameObject.h" -#include "TemporarySummon.h" +#include "Common.h" +#include "ConditionMgr.h" #include "Corpse.h" -#include "QuestDef.h" +#include "CreatureData.h" +#include "DatabaseEnvFwd.h" +#include "GameObjectData.h" #include "ItemTemplate.h" #include "NPCHandler.h" -#include "DatabaseEnv.h" -#include "Mail.h" -#include "Map.h" -#include "ObjectAccessor.h" #include "ObjectDefines.h" +#include "ObjectGuid.h" +#include "Position.h" +#include "QuestDef.h" +#include "SharedDefines.h" #include "VehicleDefines.h" -#include "ConditionMgr.h" -#include "DB2Stores.h" -#include -#include #include -#include -#include -#include +#include class Item; +class Unit; +class Vehicle; struct AccessRequirement; +struct DeclinedName; +struct DungeonEncounterEntry; +struct FactionEntry; struct PlayerInfo; struct PlayerLevelInfo; - -#pragma pack(push, 1) +struct SkillRaceClassInfoEntry; +struct WorldSafeLocsEntry; struct PageText { @@ -58,6 +54,15 @@ struct PageText uint32 NextPageID; }; +enum SummonerType +{ + SUMMONER_TYPE_CREATURE = 0, + SUMMONER_TYPE_GAMEOBJECT = 1, + SUMMONER_TYPE_MAP = 2 +}; + +#pragma pack(push, 1) + /// Key for storing temp summon data in TempSummonDataContainer struct TempSummonGroupKey { @@ -80,6 +85,15 @@ private: #pragma pack(pop) +/// Stores data for temp summons +struct TempSummonData +{ + uint32 entry; ///< Entry of summoned creature + Position pos; ///< Position, where should be creature spawned + TempSummonType type; ///< Summon type, see TempSummonType for available types + uint32 time; ///< Despawn time, usable only with certain temp summon types +}; + // DB scripting commands enum ScriptCommands { @@ -117,10 +131,28 @@ enum ScriptCommands SCRIPT_COMMAND_PLAY_ANIMKIT = 36 // source = Creature, datalong = AnimKit id }; +enum ChatType +{ + CHAT_TYPE_SAY = 0, + CHAT_TYPE_YELL = 1, + CHAT_TYPE_TEXT_EMOTE = 2, + CHAT_TYPE_BOSS_EMOTE = 3, + CHAT_TYPE_WHISPER = 4, + CHAT_TYPE_BOSS_WHISPER = 5, + CHAT_TYPE_ZONE_YELL = 6, + CHAT_TYPE_END = 255 +}; + // Benchmarked: Faster than std::unordered_map (insert/find) typedef std::map PageTextContainer; -// Benchmarked: Faster than std::map (insert/find) +struct InstanceTemplate +{ + uint32 Parent; + uint32 ScriptId; + bool AllowMount; +}; + typedef std::unordered_map InstanceTemplateContainer; struct GameTele @@ -415,6 +447,18 @@ struct AreaTriggerStruct float target_Orientation; }; +struct AccessRequirement +{ + uint8 levelMin; + uint8 levelMax; + uint32 item; + uint32 item2; + uint32 quest_A; + uint32 quest_H; + uint32 achievement; + std::string questFailedText; +}; + struct BroadcastText { BroadcastText() : Id(0), Language(0), EmoteId0(0), EmoteId1(0), EmoteId2(0), @@ -426,8 +470,8 @@ struct BroadcastText uint32 Id; uint32 Language; - StringVector MaleText; - StringVector FemaleText; + std::vector MaleText; + std::vector FemaleText; uint32 EmoteId0; uint32 EmoteId1; uint32 EmoteId2; @@ -470,30 +514,57 @@ typedef std::unordered_map LinkedRespawnContainer; +typedef std::unordered_map CreatureTemplateContainer; +typedef std::unordered_map CreatureTemplateAddonContainer; +typedef std::unordered_map CreatureDataContainer; +typedef std::unordered_map CreatureAddonContainer; +typedef std::unordered_map CreatureBaseStatsContainer; +typedef std::unordered_map EquipmentInfoContainerInternal; +typedef std::unordered_map EquipmentInfoContainer; +typedef std::unordered_map CreatureModelContainer; +typedef std::unordered_map> CreatureQuestItemMap; +typedef std::unordered_map GameObjectTemplateContainer; +typedef std::unordered_map GameObjectTemplateAddonContainer; +typedef std::unordered_map GameObjectDataContainer; +typedef std::unordered_map GameObjectAddonContainer; +typedef std::unordered_map> GameObjectQuestItemMap; +typedef std::map> TempSummonDataContainer; +typedef std::unordered_map CreatureLocaleContainer; +typedef std::unordered_map GameObjectLocaleContainer; +typedef std::unordered_map ItemTemplateContainer; +typedef std::unordered_map ItemLocaleContainer; +typedef std::unordered_map QuestLocaleContainer; +typedef std::unordered_map NpcTextLocaleContainer; +typedef std::unordered_map PageTextLocaleContainer; + +struct GossipMenuItemsLocale { - StringVector Content; + std::vector OptionText; + std::vector BoxText; }; +typedef std::unordered_map GossipMenuItemsLocaleContainer; + +struct PointOfInterestLocale +{ + std::vector Name; +}; + +typedef std::unordered_map PointOfInterestLocaleContainer; + struct QuestGreetingLocale { std::vector greeting; }; -typedef std::map LinkedRespawnContainer; -typedef std::unordered_map CreatureDataContainer; -typedef std::unordered_map GameObjectDataContainer; -typedef std::map > TempSummonDataContainer; -typedef std::unordered_map CreatureLocaleContainer; -typedef std::unordered_map GameObjectLocaleContainer; -typedef std::unordered_map ItemLocaleContainer; -typedef std::unordered_map QuestLocaleContainer; -typedef std::unordered_map NpcTextLocaleContainer; -typedef std::unordered_map PageTextLocaleContainer; -typedef std::unordered_map GossipMenuItemsLocaleContainer; -typedef std::unordered_map PointOfInterestLocaleContainer; typedef std::unordered_map QuestGreetingLocaleContainer; +struct TrinityString +{ + std::vector Content; +}; + typedef std::unordered_map TrinityStringContainer; typedef std::multimap QuestRelations; // unit/go -> quest @@ -501,14 +572,72 @@ typedef std::multimap QuestRelationsReverse; // quest -> unit/go typedef std::pair QuestRelationBounds; typedef std::pair QuestRelationReverseBounds; +struct PlayerCreateInfoItem +{ + PlayerCreateInfoItem(uint32 id, uint32 amount) : item_id(id), item_amount(amount) { } + + uint32 item_id; + uint32 item_amount; +}; + +typedef std::vector PlayerCreateInfoItems; + +struct PlayerLevelInfo +{ + PlayerLevelInfo() { for (uint8 i = 0; i < MAX_STATS; ++i) stats[i] = 0; } + + uint8 stats[MAX_STATS]; +}; + +typedef std::vector PlayerCreateInfoSpells; + +struct PlayerCreateInfoAction +{ + PlayerCreateInfoAction(uint8 _button, uint32 _action, uint8 _type) : button(_button), type(_type), action(_action) { } + + uint8 button; + uint8 type; + uint32 action; +}; + +typedef std::vector PlayerCreateInfoActions; + +struct PlayerCreateInfoSkill +{ + uint16 SkillId; + uint16 Rank; +}; + +typedef std::vector PlayerCreateInfoSkills; + +// existence checked by displayId != 0 +struct PlayerInfo +{ + uint32 mapId = 0; + uint32 areaId = 0; + float positionX = 0.0f; + float positionY = 0.0f; + float positionZ = 0.0f; + float orientation = 0.0f; + uint16 displayId_m = 0; + uint16 displayId_f = 0; + PlayerCreateInfoItems item; + PlayerCreateInfoSpells customSpells; + PlayerCreateInfoSpells castSpells; + PlayerCreateInfoActions action; + PlayerCreateInfoSkills skills; + + //[level-1] 0..MaxPlayerLevel-1 + PlayerLevelInfo* levelInfo = nullptr; +}; + + struct PetLevelInfo { - PetLevelInfo() : health(0), mana(0), armor(0) { for (uint8 i=0; i < MAX_STATS; ++i) stats[i] = 0; } - - uint16 stats[MAX_STATS]; - uint16 health; - uint16 mana; - uint16 armor; + uint16 stats[MAX_STATS] = { }; + uint16 health = 0; + uint16 mana = 0; + uint16 armor = 0; }; struct MailLevelReward @@ -639,16 +768,16 @@ struct QuestGreeting typedef std::unordered_map> QuestGreetingContainer; -struct GraveYardData +struct GraveyardData { uint32 safeLocId; uint32 team; }; -typedef std::multimap GraveYardContainer; +typedef std::multimap GraveyardContainer; typedef std::unordered_map GraveyardOrientationContainer; -typedef std::pair GraveYardMapBounds; -typedef std::pair GraveYardMapBoundsNonConst; +typedef std::pair GraveyardMapBounds; +typedef std::pair GraveyardMapBoundsNonConst; typedef std::unordered_map CacheVendorItemContainer; typedef std::unordered_map CacheTrainerSpellContainer; @@ -681,7 +810,7 @@ struct LanguageDesc TC_GAME_API extern LanguageDesc lang_description[LANGUAGES_COUNT]; LanguageDesc const* GetLanguageDescByID(uint32 lang); -enum EncounterCreditType +enum EncounterCreditType : uint8 { ENCOUNTER_CREDIT_KILL_CREATURE = 0, ENCOUNTER_CREDIT_CAST_SPELL = 1 @@ -752,8 +881,6 @@ class TC_GAME_API ObjectMgr static ObjectMgr* instance(); - typedef std::unordered_map ItemMap; - typedef std::unordered_map QuestMap; typedef std::unordered_map AreaTriggerContainer; @@ -804,21 +931,21 @@ class TC_GAME_API ObjectMgr void GetPlayerLevelInfo(uint32 race, uint32 class_, uint8 level, PlayerLevelInfo* info) const; - GameObjectQuestItemList const* GetGameObjectQuestItemList(uint32 id) const + std::vector const* GetGameObjectQuestItemList(uint32 id) const { GameObjectQuestItemMap::const_iterator itr = _gameObjectQuestItemStore.find(id); if (itr != _gameObjectQuestItemStore.end()) return &itr->second; - return NULL; + return nullptr; } GameObjectQuestItemMap const* GetGameObjectQuestItemMap() const { return &_gameObjectQuestItemStore; } - CreatureQuestItemList const* GetCreatureQuestItemList(uint32 id) const + std::vector const* GetCreatureQuestItemList(uint32 id) const { CreatureQuestItemMap::const_iterator itr = _creatureQuestItemStore.find(id); if (itr != _creatureQuestItemStore.end()) return &itr->second; - return NULL; + return nullptr; } CreatureQuestItemMap const* GetCreatureQuestItemMap() const { return &_creatureQuestItemStore; } @@ -855,29 +982,15 @@ class TC_GAME_API ObjectMgr GossipText const* GetGossipText(uint32 Text_ID) const; QuestGreeting const* GetQuestGreeting(ObjectGuid guid) const; - WorldSafeLocsEntry const* GetDefaultGraveYard(uint32 team) const; - WorldSafeLocsEntry const* GetClosestGraveYard(WorldLocation const& location, uint32 team, WorldObject* conditionObject) const; - bool AddGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool persist = true); - void RemoveGraveYardLink(uint32 id, uint32 zoneId, uint32 team, bool persist = false); + WorldSafeLocsEntry const* GetDefaultGraveyard(uint32 team) const; + WorldSafeLocsEntry const* GetClosestGraveyard(WorldLocation const& location, uint32 team, WorldObject* conditionObject) const; + bool AddGraveyardLink(uint32 id, uint32 zoneId, uint32 team, bool persist = true); + void RemoveGraveyardLink(uint32 id, uint32 zoneId, uint32 team, bool persist = false); void LoadGraveyardZones(); - GraveYardData const* FindGraveYardData(uint32 id, uint32 zone) const; - - AreaTriggerStruct const* GetAreaTrigger(uint32 trigger) const - { - AreaTriggerContainer::const_iterator itr = _areaTriggerStore.find(trigger); - if (itr != _areaTriggerStore.end()) - return &itr->second; - return nullptr; - } - - AccessRequirement const* GetAccessRequirement(uint32 mapid, Difficulty difficulty) const - { - AccessRequirementContainer::const_iterator itr = _accessRequirementStore.find(MAKE_PAIR32(mapid, difficulty)); - if (itr != _accessRequirementStore.end()) - return itr->second; - return nullptr; - } + GraveyardData const* FindGraveyardData(uint32 id, uint32 zone) const; + AreaTriggerStruct const* GetAreaTrigger(uint32 trigger) const; + AccessRequirement const* GetAccessRequirement(uint32 mapid, Difficulty difficulty) const; AreaTriggerStruct const* GetGoBackTrigger(uint32 Map) const; AreaTriggerStruct const* GetMapEntranceTrigger(uint32 Map) const; @@ -930,26 +1043,10 @@ class TC_GAME_API ObjectMgr VehicleAccessoryList const* GetVehicleAccessoryList(Vehicle* veh) const; - DungeonEncounterList const* GetDungeonEncounterList(uint32 mapId, Difficulty difficulty) const - { - std::unordered_map::const_iterator itr = _dungeonEncounterStore.find(MAKE_PAIR32(mapId, difficulty)); - if (itr != _dungeonEncounterStore.end()) - return &itr->second; - return nullptr; - } + DungeonEncounterList const* GetDungeonEncounterList(uint32 mapId, Difficulty difficulty) const; void LoadQuests(); - void LoadQuestStartersAndEnders() - { - TC_LOG_INFO("server.loading", "Loading GO Start Quest Data..."); - LoadGameobjectQuestStarters(); - TC_LOG_INFO("server.loading", "Loading GO End Quest Data..."); - LoadGameobjectQuestEnders(); - TC_LOG_INFO("server.loading", "Loading Creature Start Quest Data..."); - LoadCreatureQuestStarters(); - TC_LOG_INFO("server.loading", "Loading Creature End Quest Data..."); - LoadCreatureQuestEnders(); - } + void LoadQuestStartersAndEnders(); void LoadGameobjectQuestStarters(); void LoadGameobjectQuestEnders(); void LoadCreatureQuestStarters(); @@ -1085,7 +1182,7 @@ class TC_GAME_API ObjectMgr void LoadTerrainWorldMaps(); void LoadAreaPhases(); - std::string GeneratePetName(uint32 entry); + std::string GeneratePetName(uint32 entry) const; uint32 GetBaseXP(uint8 level); uint32 GetXPForLevel(uint8 level) const; @@ -1266,7 +1363,7 @@ class TC_GAME_API ObjectMgr void RemoveCreatureFromGrid(ObjectGuid::LowType guid, CreatureData const* data); void AddGameobjectToGrid(ObjectGuid::LowType guid, GameObjectData const* data); void RemoveGameobjectFromGrid(ObjectGuid::LowType guid, GameObjectData const* data); - ObjectGuid::LowType AddGOData(uint32 entry, uint32 map, Position const& pos, G3D::Quat const& rot, uint32 spawntimedelay = 0); + ObjectGuid::LowType AddGOData(uint32 entry, uint32 map, Position const& pos, QuaternionData const& rot, uint32 spawntimedelay = 0); ObjectGuid::LowType AddCreatureData(uint32 entry, uint32 map, Position const& pos, uint32 spawntimedelay = 0); // reserved names @@ -1321,7 +1418,7 @@ class TC_GAME_API ObjectMgr void AddVendorItem(uint32 entry, uint32 item, int32 maxcount, uint32 incrtime, uint32 extendedCost, uint8 type, bool persist = true); // for event bool RemoveVendorItem(uint32 entry, uint32 item, uint8 type, bool persist = true); // for event - bool IsVendorItemValid(uint32 vendor_entry, uint32 id, int32 maxcount, uint32 ptime, uint32 ExtendedCost, uint8 type, Player* player = NULL, std::set* skip_vendors = NULL, uint32 ORnpcflag = 0) const; + bool IsVendorItemValid(uint32 vendor_entry, uint32 id, int32 maxcount, uint32 ptime, uint32 ExtendedCost, uint8 type, Player* player = nullptr, std::set* skip_vendors = nullptr, uint32 ORnpcflag = 0) const; void LoadScriptNames(); ScriptNameContainer const& GetAllScriptNames() const; @@ -1353,10 +1450,10 @@ class TC_GAME_API ObjectMgr } // for wintergrasp only - GraveYardContainer GraveYardStore; + GraveyardContainer GraveyardStore; - static void AddLocaleString(std::string const& value, LocaleConstant localeConstant, StringVector& data); - static inline void GetLocaleString(StringVector const& data, LocaleConstant localeConstant, std::string& value) + static void AddLocaleString(std::string const& value, LocaleConstant localeConstant, std::vector& data); + static inline void GetLocaleString(std::vector const& data, LocaleConstant localeConstant, std::string& value) { if (data.size() > size_t(localeConstant) && !data[localeConstant].empty()) value = data[localeConstant]; @@ -1509,7 +1606,7 @@ class TC_GAME_API ObjectMgr typedef std::map FishingBaseSkillContainer; // [areaId][base skill level] FishingBaseSkillContainer _fishingBaseForAreaStore; - typedef std::map HalfNameContainer; + typedef std::map> HalfNameContainer; HalfNameContainer _petHalfName0; HalfNameContainer _petHalfName1; @@ -1518,7 +1615,7 @@ class TC_GAME_API ObjectMgr CreatureTemplateContainer _creatureTemplateStore; CreatureModelContainer _creatureModelStore; CreatureAddonContainer _creatureAddonStore; - CreatureAddonTemplateContainer _creatureTemplateAddonStore; + CreatureTemplateAddonContainer _creatureTemplateAddonStore; GameObjectAddonContainer _gameObjectAddonStore; GameObjectQuestItemMap _gameObjectQuestItemStore; CreatureQuestItemMap _creatureQuestItemStore; diff --git a/src/server/game/Grids/GridRefManager.h b/src/server/game/Grids/GridRefManager.h index 9afd611ceb3..d4d43c8c048 100644 --- a/src/server/game/Grids/GridRefManager.h +++ b/src/server/game/Grids/GridRefManager.h @@ -34,6 +34,6 @@ class GridRefManager : public RefManager, OBJECT> GridReference* getLast() { return (GridReference*)RefManager, OBJECT>::getLast(); } iterator begin() { return iterator(getFirst()); } - iterator end() { return iterator(NULL); } + iterator end() { return iterator(nullptr); } }; #endif diff --git a/src/server/game/Grids/GridStates.cpp b/src/server/game/Grids/GridStates.cpp index 9f54aa505a2..19c9c7a65bb 100644 --- a/src/server/game/Grids/GridStates.cpp +++ b/src/server/game/Grids/GridStates.cpp @@ -19,9 +19,12 @@ #include "GridStates.h" #include "GridNotifiers.h" #include "Log.h" +#include "Map.h" +#include "ObjectGridLoader.h" void InvalidState::Update(Map&, NGridType&, GridInfo&, uint32) const -{ } +{ +} void ActiveState::Update(Map& map, NGridType& grid, GridInfo& info, uint32 diff) const { diff --git a/src/server/game/Grids/NGrid.cpp b/src/server/game/Grids/NGrid.cpp new file mode 100644 index 00000000000..effedbfdb66 --- /dev/null +++ b/src/server/game/Grids/NGrid.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#include "NGrid.h" +#include "Random.h" + +GridInfo::GridInfo() + : i_timer(0), vis_Update(0, irand(0, DEFAULT_VISIBILITY_NOTIFY_PERIOD)), + i_unloadActiveLockCount(0), i_unloadExplicitLock(false), i_unloadReferenceLock(false) +{ +} + +GridInfo::GridInfo(time_t expiry, bool unload /*= true*/) + : i_timer(expiry), vis_Update(0, irand(0, DEFAULT_VISIBILITY_NOTIFY_PERIOD)), + i_unloadActiveLockCount(0), i_unloadExplicitLock(!unload), i_unloadReferenceLock(false) +{ +} diff --git a/src/server/game/Grids/NGrid.h b/src/server/game/Grids/NGrid.h index ec5f7942cae..b1e81002fad 100644 --- a/src/server/game/Grids/NGrid.h +++ b/src/server/game/Grids/NGrid.h @@ -29,23 +29,19 @@ #define DEFAULT_VISIBILITY_NOTIFY_PERIOD 1000 -class GridInfo +class TC_GAME_API GridInfo { public: - GridInfo() - : i_timer(0), vis_Update(0, irand(0, DEFAULT_VISIBILITY_NOTIFY_PERIOD)), - i_unloadActiveLockCount(0), i_unloadExplicitLock(false), i_unloadReferenceLock(false) { } - GridInfo(time_t expiry, bool unload = true ) - : i_timer(expiry), vis_Update(0, irand(0, DEFAULT_VISIBILITY_NOTIFY_PERIOD)), - i_unloadActiveLockCount(0), i_unloadExplicitLock(!unload), i_unloadReferenceLock(false) { } - const TimeTracker& getTimeTracker() const { return i_timer; } + GridInfo(); + GridInfo(time_t expiry, bool unload = true); + TimeTracker const& getTimeTracker() const { return i_timer; } bool getUnloadLock() const { return i_unloadActiveLockCount || i_unloadExplicitLock || i_unloadReferenceLock; } void setUnloadExplicitLock(bool on) { i_unloadExplicitLock = on; } void setUnloadReferenceLock(bool on) { i_unloadReferenceLock = on; } void incUnloadActiveLock() { ++i_unloadActiveLockCount; } void decUnloadActiveLock() { if (i_unloadActiveLockCount) --i_unloadActiveLockCount; } - void setTimer(const TimeTracker& pTimer) { i_timer = pTimer; } + void setTimer(TimeTracker const& pTimer) { i_timer = pTimer; } void ResetTimeTracker(time_t interval) { i_timer.Reset(interval); } void UpdateTimeTracker(time_t diff) { i_timer.Update(diff); } PeriodicTimer& getRelocationTimer() { return vis_Update; } @@ -110,7 +106,7 @@ class NGrid void setGridObjectDataLoaded(bool pLoaded) { i_GridObjectDataLoaded = pLoaded; } GridInfo* getGridInfoRef() { return &i_GridInfo; } - const TimeTracker& getTimeTracker() const { return i_GridInfo.getTimeTracker(); } + TimeTracker const& getTimeTracker() const { return i_GridInfo.getTimeTracker(); } bool getUnloadLock() const { return i_GridInfo.getUnloadLock(); } void setUnloadExplicitLock(bool on) { i_GridInfo.setUnloadExplicitLock(on); } void setUnloadReferenceLock(bool on) { i_GridInfo.setUnloadReferenceLock(on); } diff --git a/src/server/game/Grids/Notifiers/GridNotifiers.cpp b/src/server/game/Grids/Notifiers/GridNotifiers.cpp index 4039915efed..0a8028994df 100644 --- a/src/server/game/Grids/Notifiers/GridNotifiers.cpp +++ b/src/server/game/Grids/Notifiers/GridNotifiers.cpp @@ -80,7 +80,7 @@ void VisibleNotifier::SendToSelf() WorldPacket packet; i_data.BuildPacket(&packet); - i_player.GetSession()->SendPacket(&packet); + i_player.SendDirectMessage(&packet); for (std::set::const_iterator it = i_visibleNow.begin(); it != i_visibleNow.end(); ++it) i_player.SendInitialVisiblePackets(*it); diff --git a/src/server/game/Grids/Notifiers/GridNotifiers.h b/src/server/game/Grids/Notifiers/GridNotifiers.h index 0de5aeb84e4..d4e997a83fb 100644 --- a/src/server/game/Grids/Notifiers/GridNotifiers.h +++ b/src/server/game/Grids/Notifiers/GridNotifiers.h @@ -19,23 +19,17 @@ #ifndef TRINITY_GRIDNOTIFIERS_H #define TRINITY_GRIDNOTIFIERS_H -#include "ObjectGridLoader.h" -#include "UpdateData.h" -#include - -#include "Corpse.h" -#include "Object.h" #include "AreaTrigger.h" +#include "Corpse.h" +#include "Creature.h" +#include "CreatureAI.h" #include "DynamicObject.h" #include "GameObject.h" #include "Player.h" -#include "Unit.h" -#include "CreatureAI.h" #include "Spell.h" -#include "WorldSession.h" - -class Player; -//class Map; +#include "SpellInfo.h" +#include "UnitAI.h" +#include "UpdateData.h" namespace Trinity { @@ -129,7 +123,7 @@ namespace Trinity float i_distSq; uint32 team; Player const* skipped_receiver; - MessageDistDeliverer(WorldObject* src, WorldPacket* msg, float dist, bool own_team_only = false, Player const* skipped = NULL) + MessageDistDeliverer(WorldObject* src, WorldPacket* msg, float dist, bool own_team_only = false, Player const* skipped = nullptr) : i_source(src), i_message(msg), i_distSq(dist * dist) , team(0) , skipped_receiver(skipped) @@ -153,8 +147,7 @@ namespace Trinity if (!player->HaveAtClient(i_source)) return; - if (WorldSession* session = player->GetSession()) - session->SendPacket(i_message); + player->SendDirectMessage(i_message); } }; @@ -181,8 +174,7 @@ namespace Trinity if (player == i_source || !player->HaveAtClient(i_source) || player->IsFriendlyTo(i_source)) return; - if (WorldSession* session = player->GetSession()) - session->SendPacket(i_message); + player->SendDirectMessage(i_message); } }; @@ -654,7 +646,7 @@ namespace Trinity { public: AnyDeadUnitSpellTargetInRangeCheck(Unit* searchObj, float range, SpellInfo const* spellInfo, SpellTargetCheckTypes check) - : AnyDeadUnitObjectInRangeCheck(searchObj, range), i_spellInfo(spellInfo), i_check(searchObj, searchObj, spellInfo, check, NULL) + : AnyDeadUnitObjectInRangeCheck(searchObj, range), i_spellInfo(spellInfo), i_check(searchObj, searchObj, spellInfo, check, nullptr) { } bool operator()(Player* u); bool operator()(Corpse* u); @@ -948,9 +940,6 @@ namespace Trinity AnyGroupedUnitInObjectRangeCheck(WorldObject const* obj, Unit const* funit, float range, bool raid, bool playerOnly = false) : _source(obj), _refUnit(funit), _range(range), _raid(raid), _playerOnly(playerOnly) { } bool operator()(Unit* u) { - if (G3D::fuzzyEq(_range, 0.0f)) - return false; - if (_playerOnly && u->GetTypeId() != TYPEID_PLAYER) return false; @@ -1028,7 +1017,7 @@ namespace Trinity if (!_spellInfo) if (DynamicObject const* dynObj = i_obj->ToDynObject()) - _spellInfo = sSpellMgr->GetSpellInfo(dynObj->GetSpellId()); + _spellInfo = dynObj->GetSpellInfo(); } bool operator()(Unit* u) { @@ -1072,8 +1061,8 @@ namespace Trinity if (!u->IsWithinLOSInMap(i_enemy)) return; - if (u->AI()) - u->AI()->AttackStart(i_enemy); + if (u->GetAI() && u->IsAIEnabled) + u->GetAI()->AttackStart(i_enemy); } private: Unit* const i_funit; @@ -1341,7 +1330,7 @@ namespace Trinity class AllGameObjectsWithEntryInRange { public: - AllGameObjectsWithEntryInRange(const WorldObject* object, uint32 entry, float maxRange) : m_pObject(object), m_uiEntry(entry), m_fRange(maxRange) { } + AllGameObjectsWithEntryInRange(WorldObject const* object, uint32 entry, float maxRange) : m_pObject(object), m_uiEntry(entry), m_fRange(maxRange) { } bool operator() (GameObject* go) { if ((!m_uiEntry || go->GetEntry() == m_uiEntry) && m_pObject->IsWithinDist(go, m_fRange, false)) @@ -1358,7 +1347,7 @@ namespace Trinity class AllCreaturesOfEntryInRange { public: - AllCreaturesOfEntryInRange(const WorldObject* object, uint32 entry, float maxRange) : m_pObject(object), m_uiEntry(entry), m_fRange(maxRange) { } + AllCreaturesOfEntryInRange(WorldObject const* object, uint32 entry, float maxRange) : m_pObject(object), m_uiEntry(entry), m_fRange(maxRange) { } bool operator() (Unit* unit) { if ((!m_uiEntry || unit->GetEntry() == m_uiEntry) && m_pObject->IsWithinDist(unit, m_fRange, false)) @@ -1410,7 +1399,7 @@ namespace Trinity class AllWorldObjectsInRange { public: - AllWorldObjectsInRange(const WorldObject* object, float maxRange) : m_pObject(object), m_fRange(maxRange) { } + AllWorldObjectsInRange(WorldObject const* object, float maxRange) : m_pObject(object), m_fRange(maxRange) { } bool operator() (WorldObject* go) { return m_pObject->IsWithinDist(go, m_fRange, false) && m_pObject->IsInPhase(go); diff --git a/src/server/game/Grids/Notifiers/GridNotifiersImpl.h b/src/server/game/Grids/Notifiers/GridNotifiersImpl.h index 9f29511fc19..666194a8ab6 100644 --- a/src/server/game/Grids/Notifiers/GridNotifiersImpl.h +++ b/src/server/game/Grids/Notifiers/GridNotifiersImpl.h @@ -20,13 +20,13 @@ #define TRINITY_GRIDNOTIFIERSIMPL_H #include "GridNotifiers.h" -#include "WorldPacket.h" #include "Corpse.h" -#include "Player.h" -#include "UpdateData.h" #include "CreatureAI.h" +#include "Player.h" #include "SpellAuras.h" -#include "Opcodes.h" +#include "UpdateData.h" +#include "WorldPacket.h" +#include "WorldSession.h" template inline void Trinity::VisibleNotifier::Visit(GridRefManager &m) diff --git a/src/server/game/Grids/ObjectGridLoader.cpp b/src/server/game/Grids/ObjectGridLoader.cpp index f8b14bec41d..3083d504061 100644 --- a/src/server/game/Grids/ObjectGridLoader.cpp +++ b/src/server/game/Grids/ObjectGridLoader.cpp @@ -17,16 +17,17 @@ */ #include "ObjectGridLoader.h" +#include "AreaTrigger.h" +#include "CellImpl.h" +#include "Corpse.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "DynamicObject.h" +#include "Log.h" +#include "GameObject.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" -#include "Creature.h" -#include "GameObject.h" -#include "DynamicObject.h" -#include "Corpse.h" -#include "AreaTrigger.h" #include "World.h" -#include "CellImpl.h" -#include "CreatureAI.h" void ObjectGridEvacuator::Visit(CreatureMapType &m) { diff --git a/src/server/game/Grids/ObjectGridLoader.h b/src/server/game/Grids/ObjectGridLoader.h index d20627f3cb7..a778641cd45 100644 --- a/src/server/game/Grids/ObjectGridLoader.h +++ b/src/server/game/Grids/ObjectGridLoader.h @@ -32,7 +32,7 @@ class TC_GAME_API ObjectGridLoader friend class ObjectWorldLoader; public: - ObjectGridLoader(NGridType &grid, Map* map, const Cell &cell) + ObjectGridLoader(NGridType& grid, Map* map, Cell const& cell) : i_cell(cell), i_grid(grid), i_map(map), i_gameObjects(0), i_creatures(0), i_corpses (0) { } diff --git a/src/server/game/Groups/Group.cpp b/src/server/game/Groups/Group.cpp index 11e32cd7494..02db1cd37e5 100644 --- a/src/server/game/Groups/Group.cpp +++ b/src/server/game/Groups/Group.cpp @@ -16,26 +16,32 @@ * with this program. If not, see . */ -#include "CharacterCache.h" -#include "Common.h" -#include "Opcodes.h" -#include "WorldPacket.h" -#include "WorldSession.h" -#include "Player.h" -#include "World.h" -#include "ObjectMgr.h" -#include "GroupMgr.h" #include "Group.h" -#include "Formulas.h" -#include "ObjectAccessor.h" #include "Battleground.h" #include "BattlegroundMgr.h" -#include "MapManager.h" +#include "CharacterCache.h" +#include "Common.h" +#include "DatabaseEnv.h" +#include "DynamicObject.h" +#include "Formulas.h" +#include "GameObject.h" +#include "GroupMgr.h" #include "InstanceSaveMgr.h" -#include "Util.h" #include "LFGMgr.h" -#include "UpdateFieldFlags.h" +#include "LootMgr.h" +#include "MapManager.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Opcodes.h" +#include "Player.h" +#include "Random.h" #include "SpellAuras.h" +#include "UpdateData.h" +#include "UpdateFieldFlags.h" +#include "Util.h" +#include "World.h" +#include "WorldPacket.h" +#include "WorldSession.h" Roll::Roll(ObjectGuid _guid, LootItem const& li) : itemGUID(_guid), itemid(li.itemid), itemRandomPropId(li.randomPropertyId), itemRandomSuffix(li.randomSuffix), itemCount(li.count), @@ -56,8 +62,8 @@ Loot* Roll::getLoot() Group::Group() : m_leaderGuid(), m_leaderName(""), m_groupType(GROUPTYPE_NORMAL), m_dungeonDifficulty(DUNGEON_DIFFICULTY_NORMAL), m_raidDifficulty(RAID_DIFFICULTY_10MAN_NORMAL), -m_bgGroup(NULL), m_bfGroup(NULL), m_lootMethod(FREE_FOR_ALL), m_lootThreshold(ITEM_QUALITY_UNCOMMON), m_looterGuid(), -m_masterLooterGuid(), m_subGroupsCounts(NULL), m_guid(), m_counter(0), m_maxEnchantingLevel(0), m_dbStoreId(0) +m_bgGroup(nullptr), m_bfGroup(nullptr), m_lootMethod(FREE_FOR_ALL), m_lootThreshold(ITEM_QUALITY_UNCOMMON), m_looterGuid(), +m_masterLooterGuid(), m_subGroupsCounts(nullptr), m_guid(), m_counter(0), m_maxEnchantingLevel(0), m_dbStoreId(0) { for (uint8 i = 0; i < TARGETICONCOUNT; ++i) m_targetIcons[i].Clear(); @@ -68,8 +74,8 @@ Group::~Group() if (m_bgGroup) { TC_LOG_DEBUG("bg.battleground", "Group::~Group: battleground group being deleted."); - if (m_bgGroup->GetBgRaid(ALLIANCE) == this) m_bgGroup->SetBgRaid(ALLIANCE, NULL); - else if (m_bgGroup->GetBgRaid(HORDE) == this) m_bgGroup->SetBgRaid(HORDE, NULL); + if (m_bgGroup->GetBgRaid(ALLIANCE) == this) m_bgGroup->SetBgRaid(ALLIANCE, nullptr); + else if (m_bgGroup->GetBgRaid(HORDE) == this) m_bgGroup->SetBgRaid(HORDE, nullptr); else TC_LOG_ERROR("misc", "Group::~Group: battleground group is not linked to the correct battleground."); } Rolls::iterator itr; @@ -276,7 +282,7 @@ void Group::ConvertToGroup() if (m_subGroupsCounts) { delete[] m_subGroupsCounts; - m_subGroupsCounts = NULL; + m_subGroupsCounts = nullptr; } if (!isBGGroup() && !isBFGroup()) @@ -333,7 +339,7 @@ void Group::RemoveInvite(Player* player) if (player) { m_invitees.erase(player); - player->SetGroupInvite(NULL); + player->SetGroupInvite(nullptr); } } @@ -341,7 +347,7 @@ void Group::RemoveAllInvites() { for (InvitesList::iterator itr=m_invitees.begin(); itr != m_invitees.end(); ++itr) if (*itr) - (*itr)->SetGroupInvite(NULL); + (*itr)->SetGroupInvite(nullptr); m_invitees.clear(); } @@ -353,7 +359,7 @@ Player* Group::GetInvited(ObjectGuid guid) const if ((*itr) && (*itr)->GetGUID() == guid) return (*itr); } - return NULL; + return nullptr; } Player* Group::GetInvited(const std::string& name) const @@ -363,7 +369,7 @@ Player* Group::GetInvited(const std::string& name) const if ((*itr) && (*itr)->GetName() == name) return (*itr); } - return NULL; + return nullptr; } bool Group::AddMember(Player* player) @@ -396,7 +402,7 @@ bool Group::AddMember(Player* player) SubGroupCounterIncrease(subGroup); - player->SetGroupInvite(NULL); + player->SetGroupInvite(nullptr); if (player->GetGroup()) { if (isBGGroup() || isBFGroup()) // if player is in group and he is being added to BG raid group, then call SetBattlegroundRaid() @@ -470,7 +476,7 @@ bool Group::AddMember(Player* player) WorldPacket groupDataPacket; // Broadcast group members' fields to player - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { if (itr->GetSource() == player) continue; @@ -513,7 +519,7 @@ bool Group::AddMember(Player* player) return true; } -bool Group::RemoveMember(ObjectGuid guid, const RemoveMethod& method /*= GROUP_REMOVEMETHOD_DEFAULT*/, ObjectGuid kicker /*= 0*/, const char* reason /*= NULL*/) +bool Group::RemoveMember(ObjectGuid guid, const RemoveMethod& method /*= GROUP_REMOVEMETHOD_DEFAULT*/, ObjectGuid kicker /*= 0*/, char const* reason /*= nullptr*/) { BroadcastGroupUpdate(); @@ -551,9 +557,9 @@ bool Group::RemoveMember(ObjectGuid guid, const RemoveMethod& method /*= GROUP_R // Regular group { if (player->GetOriginalGroup() == this) - player->SetOriginalGroup(NULL); + player->SetOriginalGroup(nullptr); else - player->SetGroup(NULL); + player->SetGroup(nullptr); // quest related GO state dependent from raid membership player->UpdateForQuestWorldObjects(); @@ -564,14 +570,14 @@ bool Group::RemoveMember(ObjectGuid guid, const RemoveMethod& method /*= GROUP_R if (method == GROUP_REMOVEMETHOD_KICK || method == GROUP_REMOVEMETHOD_KICK_LFG) { data.Initialize(SMSG_GROUP_UNINVITE, 0); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } // Do we really need to send this opcode? data.Initialize(SMSG_GROUP_LIST, 1+1+1+1+8+4+4+8); data << uint8(0x10) << uint8(0) << uint8(0) << uint8(0); data << uint64(m_guid) << uint32(m_counter) << uint32(0) << uint64(0); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); _homebindIfInstance(player); } @@ -785,9 +791,9 @@ void Group::Disband(bool hideDestroy /* = false */) { //we can remove player who is in battleground from his original group if (player->GetOriginalGroup() == this) - player->SetOriginalGroup(NULL); + player->SetOriginalGroup(nullptr); else - player->SetGroup(NULL); + player->SetGroup(nullptr); } // quest related GO state dependent from raid membership @@ -801,7 +807,7 @@ void Group::Disband(bool hideDestroy /* = false */) if (!hideDestroy) { data.Initialize(SMSG_GROUP_DESTROYED, 0); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } //we already removed player from group and in player->GetGroup() is his original group, send update @@ -814,7 +820,7 @@ void Group::Disband(bool hideDestroy /* = false */) data.Initialize(SMSG_GROUP_LIST, 1+1+1+1+8+4+4+8); data << uint8(0x10) << uint8(0) << uint8(0) << uint8(0); data << uint64(m_guid) << uint32(m_counter) << uint32(0) << uint64(0); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } _homebindIfInstance(player); @@ -845,8 +851,8 @@ void Group::Disband(bool hideDestroy /* = false */) CharacterDatabase.CommitTransaction(trans); - ResetInstances(INSTANCE_RESET_GROUP_DISBAND, false, NULL); - ResetInstances(INSTANCE_RESET_GROUP_DISBAND, true, NULL); + ResetInstances(INSTANCE_RESET_GROUP_DISBAND, false, nullptr); + ResetInstances(INSTANCE_RESET_GROUP_DISBAND, true, nullptr); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_LFG_DATA); stmt->setUInt32(0, m_dbStoreId); @@ -863,7 +869,7 @@ void Group::Disband(bool hideDestroy /* = false */) /*** LOOT SYSTEM ***/ /*********************************************************/ -void Group::SendLootStartRoll(uint32 countDown, uint32 mapid, const Roll &r) +void Group::SendLootStartRoll(uint32 countDown, uint32 mapid, Roll const& r) { WorldPacket data(SMSG_LOOT_START_ROLL, (8+4+4+4+4+4+4+1)); data << uint64(r.itemGUID); // guid of rolled item @@ -884,7 +890,7 @@ void Group::SendLootStartRoll(uint32 countDown, uint32 mapid, const Roll &r) continue; if (itr->second == NOT_EMITED_YET) - p->GetSession()->SendPacket(&data); + p->SendDirectMessage(&data); } } @@ -908,7 +914,7 @@ void Group::SendLootStartRollToPlayer(uint32 countDown, uint32 mapId, Player* p, data << uint8(voteMask); // roll type mask data << uint8(r.totalPlayersRolling); // maybe the number of players rolling for it??? - p->GetSession()->SendPacket(&data); + p->SendDirectMessage(&data); } void Group::SendLootRoll(ObjectGuid sourceGuid, ObjectGuid targetGuid, uint8 rollNumber, uint8 rollType, Roll const& roll) @@ -931,7 +937,7 @@ void Group::SendLootRoll(ObjectGuid sourceGuid, ObjectGuid targetGuid, uint8 rol continue; if (itr->second != NOT_VALID) - p->GetSession()->SendPacket(&data); + p->SendDirectMessage(&data); } } @@ -954,7 +960,7 @@ void Group::SendLootRollWon(ObjectGuid sourceGuid, ObjectGuid targetGuid, uint8 continue; if (itr->second != NOT_VALID) - p->GetSession()->SendPacket(&data); + p->SendDirectMessage(&data); } } @@ -974,7 +980,7 @@ void Group::SendLootAllPassed(Roll const& roll) continue; if (itr->second != NOT_VALID) - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } } @@ -1025,7 +1031,7 @@ void Group::GroupLoot(Loot* loot, WorldObject* pLootedObject) Roll* r = new Roll(newitemGUID, *i); //a vector is filled with only near party members - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* member = itr->GetSource(); if (!member || !member->GetSession()) @@ -1107,7 +1113,7 @@ void Group::GroupLoot(Loot* loot, WorldObject* pLootedObject) Roll* r = new Roll(newitemGUID, *i); //a vector is filled with only near party members - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* member = itr->GetSource(); if (!member || !member->GetSession()) @@ -1165,7 +1171,7 @@ void Group::NeedBeforeGreed(Loot* loot, WorldObject* lootedObject) Roll* r = new Roll(newitemGUID, *i); - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* playerToRoll = itr->GetSource(); if (!playerToRoll || !playerToRoll->GetSession()) @@ -1240,7 +1246,7 @@ void Group::NeedBeforeGreed(Loot* loot, WorldObject* lootedObject) Roll* r = new Roll(newitemGUID, *i); - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* playerToRoll = itr->GetSource(); if (!playerToRoll || !playerToRoll->GetSession()) @@ -1316,7 +1322,7 @@ void Group::MasterLoot(Loot* loot, WorldObject* pLootedObject) WorldPacket data(SMSG_LOOT_MASTER_LIST, 1 + GetMembersCount() * 8); data << uint8(GetMembersCount()); - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* looter = itr->GetSource(); if (!looter->IsInWorld()) @@ -1331,11 +1337,11 @@ void Group::MasterLoot(Loot* loot, WorldObject* pLootedObject) data.put(0, real_count); - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* looter = itr->GetSource(); if (looter->IsAtGroupRewardDistance(pLootedObject)) - looter->GetSession()->SendPacket(&data); + looter->SendDirectMessage(&data); } } @@ -1460,7 +1466,7 @@ void Group::CountTheRoll(Rolls::iterator rollI, Map* allowedMap) { item->is_blocked = false; item->rollWinnerGUID = player->GetGUID(); - player->SendEquipError(msg, NULL, NULL, roll->itemid); + player->SendEquipError(msg, nullptr, nullptr, roll->itemid); } } } @@ -1485,7 +1491,7 @@ void Group::CountTheRoll(Rolls::iterator rollI, Map* allowedMap) continue; player = ObjectAccessor::FindPlayer(itr->first); - if (!player || (allowedMap != NULL && player->FindMap() != allowedMap)) + if (!player || (allowedMap != nullptr && player->FindMap() != allowedMap)) { --roll->totalGreed; continue; @@ -1527,7 +1533,7 @@ void Group::CountTheRoll(Rolls::iterator rollI, Map* allowedMap) { item->is_blocked = false; item->rollWinnerGUID = player->GetGUID(); - player->SendEquipError(msg, NULL, NULL, roll->itemid); + player->SendEquipError(msg, nullptr, nullptr, roll->itemid); } } else if (rollvote == DISENCHANT) @@ -1552,7 +1558,7 @@ void Group::CountTheRoll(Rolls::iterator rollI, Map* allowedMap) for (uint32 i = 0; i < max_slot; ++i) { LootItem* lootItem = loot.LootItemInSlot(i, player); - player->SendEquipError(msg, NULL, NULL, lootItem->itemid); + player->SendEquipError(msg, nullptr, nullptr, lootItem->itemid); player->SendItemRetrievalMail(lootItem->itemid, lootItem->count); } } @@ -1629,7 +1635,7 @@ void Group::SendRaidMarkerUpdate() if (!player || !player->GetSession()) continue; - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } } @@ -1641,7 +1647,7 @@ void Group::SendRaidMarkerUpdateToPlayer(ObjectGuid playerGUID, bool remove) WorldPacket data(SMSG_RAID_MARKERS_CHANGED, 4); data << uint32(remove ? 0 : m_markerMask); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } DynamicObject* Group::GetMarkerGuidBySpell(uint32 spell) @@ -1656,7 +1662,7 @@ DynamicObject* Group::GetMarkerGuidBySpell(uint32 spell) } } - return NULL; + return nullptr; } void Group::RemoveMarker() @@ -1751,7 +1757,7 @@ void Group::SendUpdateToPlayer(ObjectGuid playerGUID, MemberSlot* slot) data << uint8(m_raidDifficulty); // Raid Difficulty } - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } void Group::UpdatePlayerOutOfRange(Player* player) @@ -1763,17 +1769,17 @@ void Group::UpdatePlayerOutOfRange(Player* player) player->GetSession()->BuildPartyMemberStatsChangedPacket(player, &data); Player* member; - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { member = itr->GetSource(); if (member && member != player && (!member->IsInMap(player) || !member->IsWithinDist(player, member->GetSightRange(), false))) - member->GetSession()->SendPacket(&data); + member->SendDirectMessage(&data); } } void Group::BroadcastAddonMessagePacket(WorldPacket* packet, const std::string& prefix, bool ignorePlayersInBGRaid, int group, uint64 ignore) { - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* player = itr->GetSource(); if (!player || (ignore != 0 && player->GetGUID() == ignore) || (ignorePlayersInBGRaid && player->GetGroup() != this)) @@ -1788,25 +1794,25 @@ void Group::BroadcastAddonMessagePacket(WorldPacket* packet, const std::string& void Group::BroadcastPacket(WorldPacket* packet, bool ignorePlayersInBGRaid, int group, ObjectGuid ignoredPlayer) { - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* player = itr->GetSource(); if (!player || (!ignoredPlayer.IsEmpty() && player->GetGUID() == ignoredPlayer) || (ignorePlayersInBGRaid && player->GetGroup() != this)) continue; if (player->GetSession() && (group == -1 || itr->getSubGroup() == group)) - player->GetSession()->SendPacket(packet); + player->SendDirectMessage(packet); } } void Group::BroadcastReadyCheck(WorldPacket* packet) { - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* player = itr->GetSource(); if (player && player->GetSession()) if (IsLeader(player->GetGUID()) || IsAssistant(player->GetGUID())) - player->GetSession()->SendPacket(packet); + player->SendDirectMessage(packet); } } @@ -1946,7 +1952,7 @@ void Group::UpdateLooterGuid(WorldObject* pLootedObject, bool ifneed) } // search next after current - Player* pNewLooter = NULL; + Player* pNewLooter = nullptr; for (member_citerator itr = guid_itr; itr != m_memberSlots.end(); ++itr) { if (Player* player = ObjectAccessor::FindPlayer(itr->guid)) @@ -2019,7 +2025,7 @@ GroupJoinBattlegroundResult Group::CanJoinBattlegroundQueue(Battleground const* // check every member of the group to be able to join memberscount = 0; - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next(), ++memberscount) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next(), ++memberscount) { Player* member = itr->GetSource(); // offline member? don't let join @@ -2088,7 +2094,7 @@ void Group::SetDungeonDifficulty(Difficulty difficulty) CharacterDatabase.Execute(stmt); } - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* player = itr->GetSource(); if (!player->GetSession()) @@ -2112,7 +2118,7 @@ void Group::SetRaidDifficulty(Difficulty difficulty) CharacterDatabase.Execute(stmt); } - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* player = itr->GetSource(); if (!player->GetSession()) @@ -2125,7 +2131,7 @@ void Group::SetRaidDifficulty(Difficulty difficulty) bool Group::InCombatToInstance(uint32 instanceId) { - for (GroupReference* itr = GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* player = itr->GetSource(); if (player && player->GetInstanceId() == instanceId && !player->getAttackers().empty() && (player->GetMap()->IsRaidOrHeroicDungeon())) @@ -2185,7 +2191,7 @@ void Group::ResetInstances(uint8 method, bool isRaid, Player* SendMsgTo) { if (Group* group = SendMsgTo->GetGroup()) { - for (GroupReference* groupRef = group->GetFirstMember(); groupRef != NULL; groupRef = groupRef->next()) + for (GroupReference* groupRef = group->GetFirstMember(); groupRef != nullptr; groupRef = groupRef->next()) if (Player* player = groupRef->GetSource()) player->SendResetInstanceSuccess(instanceSave->GetMapId()); } @@ -2241,7 +2247,7 @@ InstanceGroupBind* Group::GetBoundInstance(Map* aMap) InstanceGroupBind* Group::GetBoundInstance(MapEntry const* mapEntry) { if (!mapEntry || !mapEntry->IsDungeon()) - return NULL; + return nullptr; Difficulty difficulty = GetDifficulty(mapEntry->IsRaid()); return GetBoundInstance(difficulty, mapEntry->MapID); @@ -2256,13 +2262,13 @@ InstanceGroupBind* Group::GetBoundInstance(Difficulty difficulty, uint32 mapId) if (itr != m_boundInstances[difficulty].end()) return &itr->second; else - return NULL; + return nullptr; } InstanceGroupBind* Group::BindToInstance(InstanceSave* save, bool permanent, bool load) { if (!save || isBGGroup() || isBFGroup()) - return NULL; + return nullptr; InstanceGroupBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()]; if (!load && (!bind.save || permanent != bind.perm || save != bind.save)) @@ -2337,7 +2343,7 @@ void Group::BroadcastGroupUpdate(void) void Group::ResetMaxEnchantingLevel() { m_maxEnchantingLevel = 0; - Player* member = NULL; + Player* member = nullptr; for (member_citerator citr = m_memberSlots.begin(); citr != m_memberSlots.end(); ++citr) { member = ObjectAccessor::FindPlayer(citr->guid); @@ -2393,12 +2399,12 @@ bool Group::isRaidGroup() const bool Group::isBGGroup() const { - return m_bgGroup != NULL; + return m_bgGroup != nullptr; } bool Group::isBFGroup() const { - return m_bfGroup != NULL; + return m_bfGroup != nullptr; } bool Group::IsCreated() const diff --git a/src/server/game/Groups/Group.h b/src/server/game/Groups/Group.h index c5228cf0625..09e49629348 100644 --- a/src/server/game/Groups/Group.h +++ b/src/server/game/Groups/Group.h @@ -20,14 +20,16 @@ #define TRINITYCORE_GROUP_H #include "DBCEnums.h" +#include "DatabaseEnvFwd.h" #include "GroupRefManager.h" -#include "LootMgr.h" -#include "QueryResult.h" +#include "Loot.h" #include "SharedDefines.h" +#include class Battlefield; class Battleground; class Creature; +class DynamicObject; class InstanceSave; class Map; class Player; @@ -107,7 +109,7 @@ enum GroupUpdateFlags GROUP_UPDATE_FLAG_POSITION = 0x00000200, // uint16 (x), uint16 (y), uint16 (z) GROUP_UPDATE_FLAG_AURAS = 0x00000400, // uint8 (unk), uint64 (mask), uint32 (count), for each bit set: uint32 (spell id) + uint16 (AuraFlags) (if has flags Scalable -> 3x int32 (bps)) GROUP_UPDATE_FLAG_PET_GUID = 0x00000800, // uint64 (pet guid) - GROUP_UPDATE_FLAG_PET_NAME = 0x00001000, // cstring (name, NULL terminated string) + GROUP_UPDATE_FLAG_PET_NAME = 0x00001000, // cstring (name, nullptr terminated string) GROUP_UPDATE_FLAG_PET_MODEL_ID = 0x00002000, // uint16 (model id) GROUP_UPDATE_FLAG_PET_CUR_HP = 0x00004000, // uint32 (HP) GROUP_UPDATE_FLAG_PET_MAX_HP = 0x00008000, // uint32 (HP) @@ -157,7 +159,7 @@ struct InstanceGroupBind bool perm; /* permanent InstanceGroupBinds exist if the leader has a permanent PlayerInstanceBind for the same instance. */ - InstanceGroupBind() : save(NULL), perm(false) { } + InstanceGroupBind() : save(nullptr), perm(false) { } }; /** request member stats checken **/ @@ -196,7 +198,7 @@ class TC_GAME_API Group void RemoveAllInvites(); bool AddLeaderInvite(Player* player); bool AddMember(Player* player); - bool RemoveMember(ObjectGuid guid, const RemoveMethod &method = GROUP_REMOVEMETHOD_DEFAULT, ObjectGuid kicker = ObjectGuid::Empty, const char* reason = NULL); + bool RemoveMember(ObjectGuid guid, const RemoveMethod &method = GROUP_REMOVEMETHOD_DEFAULT, ObjectGuid kicker = ObjectGuid::Empty, char const* reason = nullptr); void ChangeLeader(ObjectGuid guid); static void ConvertLeaderInstancesToGroup(Player* player, Group* group, bool switchLeader); void SetLootMethod(LootMethod method); @@ -292,7 +294,7 @@ class TC_GAME_API Group void SendRaidMarkerUpdate(); void SendRaidMarkerUpdateToPlayer(ObjectGuid playerGUID, bool remove = false); void SendUpdate(); - void SendUpdateToPlayer(ObjectGuid playerGUID, MemberSlot* slot = NULL); + void SendUpdateToPlayer(ObjectGuid playerGUID, MemberSlot* slot = nullptr); void UpdatePlayerOutOfRange(Player* player); template @@ -319,10 +321,10 @@ class TC_GAME_API Group /*********************************************************/ bool isRollLootActive() const; - void SendLootStartRoll(uint32 CountDown, uint32 mapid, const Roll &r); + void SendLootStartRoll(uint32 CountDown, uint32 mapid, Roll const& r); void SendLootStartRollToPlayer(uint32 countDown, uint32 mapId, Player* p, bool canNeed, Roll const& r); - void SendLootRoll(ObjectGuid SourceGuid, ObjectGuid TargetGuid, uint8 RollNumber, uint8 RollType, const Roll &r); - void SendLootRollWon(ObjectGuid SourceGuid, ObjectGuid TargetGuid, uint8 RollNumber, uint8 RollType, const Roll &r); + void SendLootRoll(ObjectGuid SourceGuid, ObjectGuid TargetGuid, uint8 RollNumber, uint8 RollType, Roll const& r); + void SendLootRollWon(ObjectGuid SourceGuid, ObjectGuid TargetGuid, uint8 RollNumber, uint8 RollType, Roll const& r); void SendLootAllPassed(Roll const& roll); void SendLooter(Creature* creature, Player* pLooter); void GroupLoot(Loot* loot, WorldObject* pLootedObject); @@ -388,4 +390,5 @@ class TC_GAME_API Group typedef std::list DynObjectList; DynObjectList m_dynObj; }; + #endif diff --git a/src/server/game/Groups/GroupMgr.cpp b/src/server/game/Groups/GroupMgr.cpp index 371928fb5bb..81f9498716b 100644 --- a/src/server/game/Groups/GroupMgr.cpp +++ b/src/server/game/Groups/GroupMgr.cpp @@ -15,11 +15,13 @@ * with this program. If not, see . */ -#include "Common.h" #include "GroupMgr.h" -#include "InstanceSaveMgr.h" -#include "World.h" +#include "Common.h" +#include "DatabaseEnv.h" #include "DBCStores.h" +#include "InstanceSaveMgr.h" +#include "Log.h" +#include "World.h" GroupMgr::GroupMgr() { @@ -39,7 +41,7 @@ uint32 GroupMgr::GenerateNewGroupDbStoreId() for (uint32 i = ++NextGroupDbStoreId; i < 0xFFFFFFFF; ++i) { - if ((i < GroupDbStore.size() && GroupDbStore[i] == NULL) || i >= GroupDbStore.size()) + if ((i < GroupDbStore.size() && GroupDbStore[i] == nullptr) || i >= GroupDbStore.size()) { NextGroupDbStoreId = i; break; @@ -71,7 +73,7 @@ void GroupMgr::FreeGroupDbStoreId(Group* group) if (storageId < NextGroupDbStoreId) NextGroupDbStoreId = storageId; - GroupDbStore[storageId] = NULL; + GroupDbStore[storageId] = nullptr; } Group* GroupMgr::GetGroupByDbStoreId(uint32 storageId) const @@ -79,7 +81,7 @@ Group* GroupMgr::GetGroupByDbStoreId(uint32 storageId) const if (storageId < GroupDbStore.size()) return GroupDbStore[storageId]; - return NULL; + return nullptr; } ObjectGuid::LowType GroupMgr::GenerateGroupId() @@ -104,7 +106,7 @@ Group* GroupMgr::GetGroupByGUID(ObjectGuid::LowType groupId) const if (itr != GroupStore.end()) return itr->second; - return NULL; + return nullptr; } void GroupMgr::AddGroup(Group* group) @@ -219,7 +221,7 @@ void GroupMgr::LoadGroups() { Field* fields = result->Fetch(); Group* group = GetGroupByDbStoreId(fields[0].GetUInt32()); - // group will never be NULL (we have run consistency sql's before loading) + // group will never be nullptr (we have run consistency sql's before loading) MapEntry const* mapEntry = sMapStore.LookupEntry(fields[1].GetUInt16()); if (!mapEntry || !mapEntry->IsDungeon()) diff --git a/src/server/game/Guilds/Guild.cpp b/src/server/game/Guilds/Guild.cpp index e8027ed709b..b203845fcd6 100644 --- a/src/server/game/Guilds/Guild.cpp +++ b/src/server/game/Guilds/Guild.cpp @@ -16,20 +16,28 @@ * with this program. If not, see . */ +#include "Guild.h" #include "AccountMgr.h" +#include "AchievementMgr.h" +#include "Bag.h" #include "CalendarMgr.h" #include "CharacterCache.h" #include "Chat.h" #include "Config.h" #include "DatabaseEnv.h" -#include "Guild.h" #include "GuildFinderMgr.h" #include "GuildMgr.h" #include "Language.h" #include "Log.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Opcodes.h" +#include "Player.h" #include "ScriptMgr.h" #include "SocialMgr.h" -#include "Opcodes.h" +#include "World.h" +#include "WorldSession.h" #define MAX_GUILD_BANK_TAB_TEXT_LEN 500 #define EMBLEM_PRICE 10 * GOLD @@ -232,7 +240,7 @@ void Guild::EventLogEntry::WritePacket(WorldPacket& data, ByteBuffer& content) c content.WriteByteSeq(guid1[4]); // Event timestamp - content << uint32(::time(NULL) - m_timestamp); + content << uint32(::time(nullptr) - m_timestamp); content.WriteByteSeq(guid1[7]); content.WriteByteSeq(guid1[3]); @@ -314,7 +322,7 @@ void Guild::BankEventLogEntry::WritePacket(WorldPacket& data, ByteBuffer& conten if (hasItem) content << uint32(m_itemOrMoney); - content << uint32(time(NULL) - m_timestamp); + content << uint32(time(nullptr) - m_timestamp); if (IsMoneyEvent()) content << uint64(m_itemOrMoney); @@ -488,6 +496,11 @@ void Guild::RankInfo::SetBankTabSlotsAndRights(GuildBankRightsAndSlots rightsAnd } // BankTab +Guild::BankTab::BankTab(ObjectGuid::LowType guildId, uint8 tabId) : m_guildId(guildId), m_tabId(tabId) +{ + memset(m_items, 0, GUILD_BANK_MAX_SLOTS * sizeof(Item*)); +} + void Guild::BankTab::LoadFromDB(Field* fields) { m_name = fields[2].GetString(); @@ -549,6 +562,12 @@ void Guild::BankTab::Delete(SQLTransaction& trans, bool removeItemsFromDB) } } +void Guild::BankTab::WriteInfoPacket(WorldPacket& data) const +{ + data << m_name; + data << m_icon; +} + void Guild::BankTab::SetInfo(std::string const& name, std::string const& icon) { if (m_name == name && m_icon == icon) @@ -634,6 +653,25 @@ void Guild::BankTab::SendText(Guild const* guild, WorldSession* session) const } // Member +Guild::Member::Member(ObjectGuid::LowType guildId, ObjectGuid guid, uint8 rankId) : + m_guildId(guildId), + m_guid(guid), + m_zoneId(0), + m_level(0), + m_class(0), + m_flags(GUILDMEMBER_STATUS_NONE), + m_logoutTime(::time(nullptr)), + m_accountId(0), + m_rankId(rankId), + m_achievementPoints(0), + m_totalActivity(0), + m_weekActivity(0), + m_totalReputation(0), + m_weekReputation(0) +{ + memset(m_bankWithdraw, 0, (GUILD_BANK_MAX_TABS + 1) * sizeof(int32)); +} + void Guild::Member::SetStats(Player* player) { m_name = player->GetName(); @@ -757,6 +795,16 @@ bool Guild::Member::CheckStats() const return true; } +Player* Guild::Member::FindPlayer() const +{ + return ObjectAccessor::FindPlayer(m_guid); +} + +Player* Guild::Member::FindConnectedPlayer() const +{ + return ObjectAccessor::FindConnectedPlayer(m_guid); +} + // Decreases amount of money/slots left for today. // If (tabId == GUILD_BANK_MAX_TABS) decrease money amount. // Otherwise decrease remaining items amount for specified tab. @@ -836,6 +884,15 @@ void EmblemInfo::SaveToDB(ObjectGuid::LowType guildId) const } // MoveItemData +Guild::MoveItemData::MoveItemData(Guild* guild, Player* player, uint8 container, uint8 slotId) : m_pGuild(guild), m_pPlayer(player), +m_container(container), m_slotId(slotId), m_pItem(nullptr), m_pClonedItem(nullptr) +{ +} + +Guild::MoveItemData::~MoveItemData() +{ +} + bool Guild::MoveItemData::CheckItem(uint32& splitedAmount) { ASSERT(m_pItem); @@ -945,7 +1002,7 @@ inline InventoryResult Guild::PlayerMoveItemData::CanStore(Item* pItem, bool swa bool Guild::BankMoveItemData::InitItem() { m_pItem = m_pGuild->_GetItem(m_container, m_slotId); - return (m_pItem != NULL); + return (m_pItem != nullptr); } bool Guild::BankMoveItemData::HasStoreRights(MoveItemData* pOther) const @@ -1169,12 +1226,13 @@ Guild::Guild(): m_bankMoney(0), m_eventLog(nullptr), m_newsLog(nullptr), - m_achievementMgr(this), _level(1), _experience(0), _todayExperience(0) { memset(&m_bankEventLog, 0, (GUILD_BANK_MAX_TABS + 1) * sizeof(LogHolder*)); + + m_achievementMgr = new AchievementMgr(this); } Guild::~Guild() @@ -1199,6 +1257,8 @@ Guild::~Guild() delete itr->second; itr->second = nullptr; } + + delete m_achievementMgr; } // Creates new guild with default data and saves it to database. @@ -1328,7 +1388,7 @@ void Guild::SaveToDB() stmt->setUInt32(3, GetId()); trans->Append(stmt); - m_achievementMgr.SaveToDB(trans); + m_achievementMgr->SaveToDB(trans); CharacterDatabase.CommitTransaction(trans); } @@ -1460,7 +1520,7 @@ void Guild::HandleRoster(WorldSession* session) memberData.WriteByteSeq(guid[4]); memberData << uint8(0); // unk memberData.WriteByteSeq(guid[1]); - memberData << float(member->IsOnline() ? 0.0f : float(::time(NULL) - member->GetLogoutTime()) / DAY); + memberData << float(member->IsOnline() ? 0.0f : float(::time(nullptr) - member->GetLogoutTime()) / DAY); if (offNoteLength) memberData.WriteString(member->GetOfficerNote()); @@ -1588,7 +1648,7 @@ void Guild::HandleSetAchievementTracking(WorldSession* session, std::set } member->SetTrackedCriteriaIds(criteriaIds); - m_achievementMgr.SendAllTrackedCriterias(player, member->GetTrackedCriteriaIds()); + m_achievementMgr->SendAllTrackedCriterias(player, member->GetTrackedCriteriaIds()); } } @@ -1634,7 +1694,7 @@ void Guild::HandleSetInfo(WorldSession* session, std::string const& info) } } -void Guild::HandleSetEmblem(WorldSession* session, const EmblemInfo& emblemInfo) +void Guild::HandleSetEmblem(WorldSession* session, EmblemInfo const& emblemInfo) { Player* player = session->GetPlayer(); if (!_IsLeader(player)) @@ -1704,7 +1764,7 @@ void Guild::HandleSetMemberNote(WorldSession* session, std::string const& note, } } -void Guild::HandleSetRankInfo(WorldSession* session, uint8 rankId, std::string const& name, uint32 rights, uint32 moneyPerDay, const GuildBankRightsAndSlotsVec& rightsAndSlots) +void Guild::HandleSetRankInfo(WorldSession* session, uint8 rankId, std::string const& name, uint32 rights, uint32 moneyPerDay, GuildBankRightsAndSlotsVec const& rightsAndSlots) { // Only leader can modify ranks if (!_IsLeader(session->GetPlayer())) @@ -1868,7 +1928,7 @@ void Guild::HandleInviteMember(WorldSession* session, std::string const& name) data.WriteByteSeq(newGuildGuid[5]); data.WriteByteSeq(newGuildGuid[3]); data.WriteByteSeq(oldGuildGuid[4]); - pInvitee->GetSession()->SendPacket(&data); + pInvitee->SendDirectMessage(&data); TC_LOG_DEBUG("guild", "SMSG_GUILD_INVITE [%s]", pInvitee->GetName().c_str()); } @@ -2389,7 +2449,7 @@ void Guild::SendLoginInfo(WorldSession* session) SendGuildReputationWeeklyCap(session, member->GetWeekReputation()); - m_achievementMgr.SendAllAchievementData(player); + m_achievementMgr->SendAllAchievementData(player); member->SetStats(player); member->AddFlag(GUILDMEMBER_STATUS_ONLINE); @@ -2661,7 +2721,7 @@ void Guild::BroadcastToGuild(WorldSession* session, bool officerOnly, std::strin if (Player* player = itr->second->FindConnectedPlayer()) if (player->GetSession() && _HasRankRight(player, officerOnly ? GR_RIGHT_OFFCHATLISTEN : GR_RIGHT_GCHATLISTEN) && !player->GetSocial()->HasIgnore(session->GetPlayer()->GetGUID())) - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } } @@ -2670,13 +2730,13 @@ void Guild::BroadcastAddonToGuild(WorldSession* session, bool officerOnly, std:: if (session && session->GetPlayer() && _HasRankRight(session->GetPlayer(), officerOnly ? GR_RIGHT_OFFCHATSPEAK : GR_RIGHT_GCHATSPEAK)) { WorldPacket data; - ChatHandler::BuildChatPacket(data, officerOnly ? CHAT_MSG_OFFICER : CHAT_MSG_GUILD, LANG_ADDON, session->GetPlayer(), NULL, msg, 0, "", DEFAULT_LOCALE, prefix); + ChatHandler::BuildChatPacket(data, officerOnly ? CHAT_MSG_OFFICER : CHAT_MSG_GUILD, LANG_ADDON, session->GetPlayer(), nullptr, msg, 0, "", DEFAULT_LOCALE, prefix); for (Members::const_iterator itr = m_members.begin(); itr != m_members.end(); ++itr) if (Player* player = itr->second->FindPlayer()) if (player->GetSession() && _HasRankRight(player, officerOnly ? GR_RIGHT_OFFCHATLISTEN : GR_RIGHT_GCHATLISTEN) && !player->GetSocial()->HasIgnore(session->GetPlayer()->GetGUID()) && player->GetSession()->IsAddonRegistered(prefix)) - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } } @@ -2685,14 +2745,14 @@ void Guild::BroadcastPacketToRank(WorldPacket* packet, uint8 rankId) const for (auto itr = m_members.begin(); itr != m_members.end(); ++itr) if (itr->second->IsRank(rankId)) if (Player* player = itr->second->FindConnectedPlayer()) - player->GetSession()->SendPacket(packet); + player->SendDirectMessage(packet); } void Guild::BroadcastPacket(WorldPacket* packet) const { for (auto itr = m_members.begin(); itr != m_members.end(); ++itr) if (Player* player = itr->second->FindPlayer()) - player->GetSession()->SendPacket(packet); + player->SendDirectMessage(packet); } void Guild::BroadcastPacketIfTrackingAchievement(WorldPacket* packet, uint32 criteriaId) const @@ -2700,7 +2760,7 @@ void Guild::BroadcastPacketIfTrackingAchievement(WorldPacket* packet, uint32 cri for (Members::const_iterator itr = m_members.begin(); itr != m_members.end(); ++itr) if (itr->second->IsTrackingCriteriaId(criteriaId)) if (Player* player = itr->second->FindPlayer()) - player->GetSession()->SendPacket(packet); + player->SendDirectMessage(packet); } void Guild::MassInviteToEvent(WorldSession* session, uint32 minLevel, uint32 maxLevel, uint32 minRank) @@ -2736,6 +2796,21 @@ void Guild::MassInviteToEvent(WorldSession* session, uint32 minLevel, uint32 max session->SendPacket(&data); } +bool Guild::_HasRankRight(Player const* player, uint32 right) const +{ + if (player) + if (Member const* member = GetMember(player->GetGUID())) + return (_GetRankRights(member->GetRankId()) & right) != GR_RIGHT_EMPTY; + return false; +} + +void Guild::_DeleteMemberFromDB(SQLTransaction& trans, ObjectGuid::LowType lowguid) const +{ + PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_MEMBER); + stmt->setUInt32(0, lowguid); + CharacterDatabase.ExecuteOrAppend(trans, stmt); +} + // Members handling bool Guild::AddMember(SQLTransaction& trans, ObjectGuid guid, uint8 rankId) { @@ -3035,7 +3110,7 @@ bool Guild::_IsLeader(Player* player) const { if (player->GetGUID() == m_leaderGuid) return true; - if (const Member* member = GetMember(player->GetGUID())) + if (Member const* member = GetMember(player->GetGUID())) return member->IsRank(GR_GUILDMASTER); return false; } @@ -3104,21 +3179,21 @@ void Guild::_SetRankBankTabRightsAndSlots(uint8 rankId, GuildBankRightsAndSlots inline std::string Guild::_GetRankName(uint8 rankId) const { - if (const RankInfo* rankInfo = GetRankInfo(rankId)) + if (RankInfo const* rankInfo = GetRankInfo(rankId)) return rankInfo->GetName(); return ""; } inline uint32 Guild::_GetRankRights(uint8 rankId) const { - if (const RankInfo* rankInfo = GetRankInfo(rankId)) + if (RankInfo const* rankInfo = GetRankInfo(rankId)) return rankInfo->GetRights(); return 0; } inline int32 Guild::_GetRankBankMoneyPerDay(uint8 rankId) const { - if (const RankInfo* rankInfo = GetRankInfo(rankId)) + if (RankInfo const* rankInfo = GetRankInfo(rankId)) return rankInfo->GetBankMoneyPerDay(); return 0; } @@ -3126,14 +3201,14 @@ inline int32 Guild::_GetRankBankMoneyPerDay(uint8 rankId) const inline int32 Guild::_GetRankBankTabSlotsPerDay(uint8 rankId, uint8 tabId) const { if (tabId < _GetPurchasedTabsSize()) - if (const RankInfo* rankInfo = GetRankInfo(rankId)) + if (RankInfo const* rankInfo = GetRankInfo(rankId)) return rankInfo->GetBankTabSlotsPerDay(tabId); return 0; } inline int8 Guild::_GetRankBankTabRights(uint8 rankId, uint8 tabId) const { - if (const RankInfo* rankInfo = GetRankInfo(rankId)) + if (RankInfo const* rankInfo = GetRankInfo(rankId)) return rankInfo->GetBankTabRights(tabId); return 0; } @@ -3186,7 +3261,7 @@ inline void Guild::_UpdateMemberWithdrawSlots(SQLTransaction& trans, ObjectGuid inline bool Guild::_MemberHasTabRights(ObjectGuid guid, uint8 tabId, uint32 rights) const { - if (const Member* member = GetMember(guid)) + if (Member const* member = GetMember(guid)) { // Leader always has full rights if (member->IsRank(GR_GUILDMASTER) || m_leaderGuid == guid) @@ -3437,14 +3512,14 @@ void Guild::_SendBankContentUpdate(uint8 tabId, SlotIds slots) const if (Player* player = itr->second->FindPlayer()) { data.put(rempos, uint32(_GetMemberRemainingSlots(itr->second, tabId))); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } TC_LOG_DEBUG("guild", "WORLD: Sent (SMSG_GUILD_BANK_LIST)"); } } -void Guild::_BroadcastEvent(GuildEvents guildEvent, ObjectGuid guid, const char* param1, const char* param2, const char* param3) const +void Guild::_BroadcastEvent(GuildEvents guildEvent, ObjectGuid guid, char const* param1, char const* param2, char const* param3) const { uint8 count = !param3 ? (!param2 ? (!param1 ? 0 : 1) : 2) : 3; @@ -3624,7 +3699,7 @@ void Guild::GiveXP(uint32 xp, Player* source) WorldPacket data(SMSG_GUILD_XP_GAIN, 8); data << uint64(xp); - source->GetSession()->SendPacket(&data); + source->SendDirectMessage(&data); _experience += xp; _todayExperience += xp; @@ -3659,13 +3734,13 @@ void Guild::GiveXP(uint32 xp, Player* source) } AddGuildNews(GUILD_NEWS_LEVEL_UP, ObjectGuid::Empty, 0, _level); - UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_GUILD_LEVEL, GetLevel(), 0, 0, NULL, source); + UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_GUILD_LEVEL, GetLevel(), 0, 0, nullptr, source); ++oldLevel; } } -void Guild::SendGuildXP(WorldSession* session /* = NULL */) const +void Guild::SendGuildXP(WorldSession* session /* = nullptr */) const { //Member const* member = GetMember(session->GetGUID().GetCounter()); @@ -3698,7 +3773,7 @@ void Guild::ResetTimes(bool weekly) { //SendGuildXP(player->GetSession()); WorldPacket data(SMSG_GUILD_MEMBER_DAILY_RESET, 0); // tells the client to request bank withdrawal limit - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } } } @@ -3721,12 +3796,12 @@ void Guild::AddGuildNews(uint8 type, ObjectGuid guid, uint32 flags, uint32 value bool Guild::HasAchieved(uint32 achievementId) const { - return m_achievementMgr.HasAchieved(achievementId); + return m_achievementMgr->HasAchieved(achievementId); } void Guild::UpdateAchievementCriteria(AchievementCriteriaTypes type, uint64 miscValue1, uint64 miscValue2, uint64 miscValue3, Unit* unit, Player* player) { - m_achievementMgr.UpdateAchievementCriteria(type, miscValue1, miscValue2, miscValue3, unit, player); + m_achievementMgr->UpdateAchievementCriteria(type, miscValue1, miscValue2, miscValue3, unit, player); } void Guild::HandleNewsSetSticky(WorldSession* session, uint32 newsId, bool sticky) diff --git a/src/server/game/Guilds/Guild.h b/src/server/game/Guilds/Guild.h index 3115864b6e1..ef5ed39f440 100644 --- a/src/server/game/Guilds/Guild.h +++ b/src/server/game/Guilds/Guild.h @@ -19,15 +19,23 @@ #ifndef TRINITYCORE_GUILD_H #define TRINITYCORE_GUILD_H -#include "AchievementMgr.h" -#include "World.h" -#include "Item.h" -#include "WorldPacket.h" -#include "ObjectMgr.h" -#include "Player.h" -#include "DBCStore.h" +#include "DatabaseEnvFwd.h" +#include "ObjectGuid.h" +#include "SharedDefines.h" +#include + +template +class AchievementMgr; class Item; +class Player; +class Unit; +class WorldPacket; +class WorldSession; +struct ItemPosCount; +enum AchievementCriteriaTypes : uint8; +enum InventoryResult : uint8; +enum LocaleConstant : uint8; enum GuildMisc { @@ -257,24 +265,15 @@ enum GuildNews GUILD_NEWS_LEVEL_UP = 6, }; -struct GuildReward -{ - uint32 Entry; - int32 Racemask; - uint64 Price; - uint32 AchievementId; - uint8 Standing; -}; - uint32 const MinNewsItemLevel[MAX_CONTENT] = { 61, 90, 200, 353 }; // Guild Challenge #define GUILD_CHALLENGES_TYPES 4 -const uint32 GuildChallengeGoldReward[GUILD_CHALLENGES_TYPES] = { 0, 250, 1000, 500 }; -const uint32 GuildChallengeMaxLevelGoldReward[GUILD_CHALLENGES_TYPES] = { 0, 125, 500, 250 }; -const uint32 GuildChallengeXPReward[GUILD_CHALLENGES_TYPES] = { 0, 300000, 3000000, 1500000 }; -const uint32 GuildChallengesPerWeek[GUILD_CHALLENGES_TYPES] = { 0, 7, 1, 3 }; +uint32 const GuildChallengeGoldReward[GUILD_CHALLENGES_TYPES] = { 0, 250, 1000, 500 }; +uint32 const GuildChallengeMaxLevelGoldReward[GUILD_CHALLENGES_TYPES] = { 0, 125, 500, 250 }; +uint32 const GuildChallengeXPReward[GUILD_CHALLENGES_TYPES] = { 0, 300000, 3000000, 1500000 }; +uint32 const GuildChallengesPerWeek[GUILD_CHALLENGES_TYPES] = { 0, 7, 1, 3 }; // Emblem info class TC_GAME_API EmblemInfo @@ -340,24 +339,7 @@ private: class Member { public: - Member(ObjectGuid::LowType guildId, ObjectGuid guid, uint8 rankId) : - m_guildId(guildId), - m_guid(guid), - m_zoneId(0), - m_level(0), - m_class(0), - m_flags(GUILDMEMBER_STATUS_NONE), - m_logoutTime(::time(NULL)), - m_accountId(0), - m_rankId(rankId), - m_achievementPoints(0), - m_totalActivity(0), - m_weekActivity(0), - m_totalReputation(0), - m_weekReputation(0) - { - memset(m_bankWithdraw, 0, (GUILD_BANK_MAX_TABS + 1) * sizeof(int32)); - } + Member(ObjectGuid::LowType guildId, ObjectGuid guid, uint8 rankId); void SetStats(Player* player); void SetStats(std::string const& name, uint8 level, uint8 _class, uint32 zoneId, uint32 accountId, uint32 reputation); @@ -368,8 +350,6 @@ private: void SetZoneId(uint32 id) { m_zoneId = id; } void SetAchievementPoints(uint32 val) { m_achievementPoints = val; } void SetLevel(uint8 var) { m_level = var; } - void AddReputation(uint32& reputation); - void AddActivity(uint64 activity); void AddFlag(uint8 var) { m_flags |= var; } void RemFlag(uint8 var) { m_flags &= ~var; } @@ -412,8 +392,8 @@ private: int32 GetBankWithdrawValue(uint8 tabId) const; void ResetValues(bool weekly = false); - inline Player* FindPlayer() const { return ObjectAccessor::FindPlayer(m_guid); } - inline Player* FindConnectedPlayer() const { return ObjectAccessor::FindConnectedPlayer(m_guid); } + Player* FindPlayer() const; + Player* FindConnectedPlayer() const; private: ObjectGuid::LowType m_guildId; @@ -445,7 +425,7 @@ private: class LogEntry { public: - LogEntry(ObjectGuid::LowType guildId, uint32 guid) : m_guildId(guildId), m_guid(guid), m_timestamp(::time(NULL)) { } + LogEntry(ObjectGuid::LowType guildId, uint32 guid) : m_guildId(guildId), m_guid(guid), m_timestamp(::time(nullptr)) { } LogEntry(ObjectGuid::LowType guildId, uint32 guid, time_t timestamp) : m_guildId(guildId), m_guid(guid), m_timestamp(timestamp) { } virtual ~LogEntry() { } @@ -634,22 +614,13 @@ private: class BankTab { public: - BankTab(ObjectGuid::LowType guildId, uint8 tabId) : m_guildId(guildId), m_tabId(tabId) - { - memset(m_items, 0, GUILD_BANK_MAX_SLOTS * sizeof(Item*)); - } + BankTab(ObjectGuid::LowType guildId, uint8 tabId); void LoadFromDB(Field* fields); bool LoadItemFromDB(Field* fields); void Delete(SQLTransaction& trans, bool removeItemsFromDB = false); - void WritePacket(WorldPacket& data) const; - bool WriteSlotPacket(WorldPacket& data, uint8 slotId, bool ignoreEmpty = true) const; - void WriteInfoPacket(WorldPacket& data) const - { - data << m_name; - data << m_icon; - } + void WriteInfoPacket(WorldPacket& data) const; void SetInfo(std::string const& name, std::string const& icon); void SetText(std::string const& text); @@ -659,7 +630,7 @@ private: std::string const& GetIcon() const { return m_icon; } std::string const& GetText() const { return m_text; } - inline Item* GetItem(uint8 slotId) const { return slotId < GUILD_BANK_MAX_SLOTS ? m_items[slotId] : NULL; } + inline Item* GetItem(uint8 slotId) const { return slotId < GUILD_BANK_MAX_SLOTS ? m_items[slotId] : nullptr; } bool SetItem(SQLTransaction& trans, uint8 slotId, Item* item); private: @@ -676,9 +647,8 @@ private: class MoveItemData { public: - MoveItemData(Guild* guild, Player* player, uint8 container, uint8 slotId) : m_pGuild(guild), m_pPlayer(player), - m_container(container), m_slotId(slotId), m_pItem(NULL), m_pClonedItem(NULL) { } - virtual ~MoveItemData() { } + MoveItemData(Guild* guild, Player* player, uint8 container, uint8 slotId); + virtual ~MoveItemData(); virtual bool IsBank() const = 0; // Initializes item pointer. Returns true, if item exists, false otherwise. @@ -717,7 +687,7 @@ private: uint8 m_slotId; Item* m_pItem; Item* m_pClonedItem; - ItemPosCountVec m_vec; + std::vector m_vec; }; class PlayerMoveItemData : public MoveItemData @@ -794,7 +764,7 @@ public: void HandleSetAchievementTracking(WorldSession* session, std::set const& achievementIds); void HandleSetMOTD(WorldSession* session, std::string const& motd); void HandleSetInfo(WorldSession* session, std::string const& info); - void HandleSetEmblem(WorldSession* session, const EmblemInfo& emblemInfo); + void HandleSetEmblem(WorldSession* session, EmblemInfo const& emblemInfo); void HandleSetNewGuildMaster(WorldSession* session, std::string const& name); void HandleSetBankTabInfo(WorldSession* session, uint8 tabId, std::string const& name, std::string const& icon); void HandleSetMemberNote(WorldSession* session, std::string const& note, ObjectGuid guid, bool isPublic); @@ -824,7 +794,7 @@ public: void SendEventLog(WorldSession* session) const; void SendBankLog(WorldSession* session, uint8 tabId) const; void SendBankList(WorldSession* session, uint8 tabId, bool withContent, bool withTabInfo) const; - void SendGuildXP(WorldSession* session = NULL) const; + void SendGuildXP(WorldSession* session = nullptr) const; void SendBankTabText(WorldSession* session, uint8 tabId) const; void SendPermissions(WorldSession* session) const; void SendMoneyInfo(WorldSession* session) const; @@ -877,8 +847,8 @@ public: // Bank tabs void SetBankTabText(uint8 tabId, std::string const& text); - AchievementMgr& GetAchievementMgr() { return m_achievementMgr; } - AchievementMgr const& GetAchievementMgr() const { return m_achievementMgr; } + AchievementMgr& GetAchievementMgr() { return *m_achievementMgr; } + AchievementMgr const& GetAchievementMgr() const { return *m_achievementMgr; } // Guild leveling uint8 GetLevel() const { return _level; } @@ -914,7 +884,7 @@ protected: LogHolder* m_eventLog; LogHolder* m_bankEventLog[GUILD_BANK_MAX_TABS + 1]; LogHolder* m_newsLog; - AchievementMgr m_achievementMgr; + AchievementMgr* m_achievementMgr; uint8 _level; uint64 _experience; @@ -924,13 +894,7 @@ private: inline uint8 _GetRanksSize() const { return uint8(m_ranks.size()); } inline const RankInfo* GetRankInfo(uint8 rankId) const { return rankId < _GetRanksSize() ? &m_ranks[rankId] : nullptr; } inline RankInfo* GetRankInfo(uint8 rankId) { return rankId < _GetRanksSize() ? &m_ranks[rankId] : nullptr; } - inline bool _HasRankRight(Player const* player, uint32 right) const - { - if (player) - if (Member const* member = GetMember(player->GetGUID())) - return (_GetRankRights(member->GetRankId()) & right) != GR_RIGHT_EMPTY; - return false; - } + bool _HasRankRight(Player const* player, uint32 right) const; inline uint8 _GetLowestRankId() const { return uint8(m_ranks.size() - 1); } @@ -959,12 +923,7 @@ private: return nullptr; } - inline void _DeleteMemberFromDB(SQLTransaction& trans, ObjectGuid::LowType lowguid) const - { - PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_MEMBER); - stmt->setUInt32(0, lowguid); - CharacterDatabase.ExecuteOrAppend(trans, stmt); - } + void _DeleteMemberFromDB(SQLTransaction& trans, ObjectGuid::LowType lowguid) const; // Creates log holders (either when loading or when creating guild) void _CreateLogHolders(); @@ -1007,6 +966,6 @@ private: void SendGuildReputationWeeklyCap(WorldSession* session, uint32 reputation) const; void SendGuildRanksUpdate(ObjectGuid setterGuid, ObjectGuid targetGuid, uint32 rank); - void _BroadcastEvent(GuildEvents guildEvent, ObjectGuid guid, const char* param1 = NULL, const char* param2 = NULL, const char* param3 = NULL) const; + void _BroadcastEvent(GuildEvents guildEvent, ObjectGuid guid, char const* param1 = nullptr, char const* param2 = nullptr, char const* param3 = nullptr) const; }; #endif diff --git a/src/server/game/Guilds/GuildFinderMgr.cpp b/src/server/game/Guilds/GuildFinderMgr.cpp index b6df2a89ebc..af47d604d34 100644 --- a/src/server/game/Guilds/GuildFinderMgr.cpp +++ b/src/server/game/Guilds/GuildFinderMgr.cpp @@ -15,11 +15,41 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "GuildFinderMgr.h" +#include "CharacterCache.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "Guild.h" #include "GuildMgr.h" +#include "Log.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "World.h" +MembershipRequest::MembershipRequest() : _guildId(0), _availability(0), _classRoles(0), _interests(0), _time(time(nullptr)) +{ +} + +MembershipRequest::MembershipRequest(ObjectGuid playerGUID, uint32 guildId, uint32 availability, uint32 classRoles, uint32 interests, std::string comment, time_t submitTime) : + _comment(std::move(comment)), _guildId(guildId), _playerGUID(playerGUID), _availability(availability), _classRoles(classRoles), _interests(interests), _time(submitTime) +{ +} + +uint8 MembershipRequest::GetClass() const +{ + return sCharacterCache->GetCharacterCacheByGuid(GetPlayerGUID())->Class; +} + +uint8 MembershipRequest::GetLevel() const +{ + return sCharacterCache->GetCharacterCacheByGuid(GetPlayerGUID())->Level; +} + +std::string const& MembershipRequest::GetName() const +{ + return sCharacterCache->GetCharacterCacheByGuid(GetPlayerGUID())->Name; +} + GuildFinderMgr::GuildFinderMgr() { } diff --git a/src/server/game/Guilds/GuildFinderMgr.h b/src/server/game/Guilds/GuildFinderMgr.h index dd4db89799b..4ae4128e2a5 100644 --- a/src/server/game/Guilds/GuildFinderMgr.h +++ b/src/server/game/Guilds/GuildFinderMgr.h @@ -18,11 +18,13 @@ #ifndef __TRINITY_GUILDFINDER_H #define __TRINITY_GUILDFINDER_H -#include "CharacterCache.h" #include "Common.h" #include "ObjectGuid.h" -#include "World.h" -#include "GuildMgr.h" +#include "SharedDefines.h" +#include + +class Guild; +class Player; enum GuildFinderOptionsInterest { @@ -60,34 +62,21 @@ enum GuildFinderOptionsLevel struct MembershipRequest { public: - MembershipRequest(MembershipRequest const& settings) : _comment(settings.GetComment()) - { - _availability = settings.GetAvailability(); - _classRoles = settings.GetClassRoles(); - _interests = settings.GetInterests(); - _guildId = settings.GetGuildId(); - _playerGUID = settings.GetPlayerGUID(); - _time = settings.GetSubmitTime(); - } - - MembershipRequest(ObjectGuid playerGUID, uint32 guildId, uint32 availability, uint32 classRoles, uint32 interests, std::string& comment, time_t submitTime) : - _comment(comment), _guildId(guildId), _playerGUID(playerGUID), _availability(availability), - _classRoles(classRoles), _interests(interests), _time(submitTime) {} - - MembershipRequest() : _guildId(0), _availability(0), _classRoles(0), - _interests(0), _time(time(NULL)) {} + MembershipRequest(); + MembershipRequest(ObjectGuid playerGUID, uint32 guildId, uint32 availability, uint32 classRoles, uint32 interests, std::string comment, time_t submitTime); uint32 GetGuildId() const { return _guildId; } ObjectGuid GetPlayerGUID() const { return _playerGUID; } uint8 GetAvailability() const { return _availability; } uint8 GetClassRoles() const { return _classRoles; } uint8 GetInterests() const { return _interests; } - uint8 GetClass() const { return sCharacterCache->GetCharacterCacheByGuid(GetPlayerGUID())->Class; } - uint8 GetLevel() const { return sCharacterCache->GetCharacterCacheByGuid(GetPlayerGUID())->Level; } + uint8 GetClass() const; + uint8 GetLevel() const; time_t GetSubmitTime() const { return _time; } time_t GetExpiryTime() const { return time_t(_time + 30 * 24 * 3600); } // Adding 30 days std::string const& GetComment() const { return _comment; } - std::string const& GetName() const { return sCharacterCache->GetCharacterCacheByGuid(GetPlayerGUID())->Name; } + std::string const& GetName() const; + private: std::string _comment; @@ -184,14 +173,16 @@ struct LFGuildSettings : public LFGuildPlayer TeamId _team; }; -typedef std::map LFGuildStore; -typedef std::map > MembershipRequestStore; +typedef std::unordered_map LFGuildStore; +typedef std::unordered_map> MembershipRequestStore; class GuildFinderMgr { private: GuildFinderMgr(); ~GuildFinderMgr(); + GuildFinderMgr(GuildFinderMgr const&) = delete; + GuildFinderMgr& operator=(GuildFinderMgr const&) = delete; LFGuildStore _guildSettings; diff --git a/src/server/game/Guilds/GuildMgr.cpp b/src/server/game/Guilds/GuildMgr.cpp index 98aab76838c..2315dd893ec 100644 --- a/src/server/game/Guilds/GuildMgr.cpp +++ b/src/server/game/Guilds/GuildMgr.cpp @@ -15,8 +15,13 @@ * with this program. If not, see . */ -#include "Common.h" #include "GuildMgr.h" +#include "AchievementMgr.h" +#include "DatabaseEnv.h" +#include "Guild.h" +#include "Log.h" +#include "ObjectMgr.h" +#include "World.h" GuildMgr::GuildMgr() : NextGuildId(1) { } @@ -60,7 +65,7 @@ Guild* GuildMgr::GetGuildById(ObjectGuid::LowType guildId) const if (itr != GuildStore.end()) return itr->second; - return NULL; + return nullptr; } Guild* GuildMgr::GetGuildByGuid(ObjectGuid guid) const @@ -71,7 +76,7 @@ Guild* GuildMgr::GetGuildByGuid(ObjectGuid guid) const if (uint32 guildId = guid.GetCounter()) return GetGuildById(guildId); - return NULL; + return nullptr; } Guild* GuildMgr::GetGuildByName(const std::string& guildName) const @@ -85,7 +90,7 @@ Guild* GuildMgr::GetGuildByName(const std::string& guildName) const if (search == gname) return itr->second; } - return NULL; + return nullptr; } std::string GuildMgr::GetGuildNameById(ObjectGuid::LowType guildId) const @@ -108,7 +113,7 @@ Guild* GuildMgr::GetGuildByLeader(ObjectGuid guid) const if (itr->second->GetLeaderGUID() == guid) return itr->second; - return NULL; + return nullptr; } uint32 GuildMgr::GetXPForGuildLevel(uint8 level) const diff --git a/src/server/game/Guilds/GuildMgr.h b/src/server/game/Guilds/GuildMgr.h index bcf229e9ce5..b28cae694f2 100644 --- a/src/server/game/Guilds/GuildMgr.h +++ b/src/server/game/Guilds/GuildMgr.h @@ -18,13 +18,29 @@ #ifndef _GUILDMGR_H #define _GUILDMGR_H -#include "Guild.h" +#include "Define.h" +#include "ObjectGuid.h" +#include +#include + +class Guild; + +struct GuildReward +{ + uint32 Entry; + int32 Racemask; + uint64 Price; + uint32 AchievementId; + uint8 Standing; +}; class TC_GAME_API GuildMgr { private: GuildMgr(); ~GuildMgr(); + GuildMgr(GuildMgr const&) = delete; + GuildMgr& operator=(GuildMgr const&) = delete; public: static GuildMgr* instance(); @@ -44,8 +60,6 @@ public: void SaveGuilds(); - void ResetReputationCaps(); - ObjectGuid::LowType GenerateGuildId(); void SetNextGuildId(ObjectGuid::LowType Id) { NextGuildId = Id; } diff --git a/src/server/game/Handlers/ArenaTeamHandler.cpp b/src/server/game/Handlers/ArenaTeamHandler.cpp index 9cfbf0b7935..6916da5bcd4 100644 --- a/src/server/game/Handlers/ArenaTeamHandler.cpp +++ b/src/server/game/Handlers/ArenaTeamHandler.cpp @@ -16,16 +16,18 @@ * with this program. If not, see . */ -#include "Player.h" -#include "WorldPacket.h" #include "WorldSession.h" #include "ArenaTeam.h" -#include "SocialMgr.h" #include "ArenaTeamMgr.h" -#include "Opcodes.h" +#include "CharacterCache.h" +#include "Log.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" -#include "CharacterCache.h" +#include "Opcodes.h" +#include "Player.h" +#include "SocialMgr.h" +#include "World.h" +#include "WorldPacket.h" void WorldSession::HandleInspectArenaTeamsOpcode(WorldPacket& recvData) { @@ -136,7 +138,7 @@ void WorldSession::HandleArenaTeamInviteOpcode(WorldPacket& recvData) uint32 arenaTeamId; // arena team id std::string invitedName; - Player* player = NULL; + Player* player = nullptr; recvData >> arenaTeamId >> invitedName; @@ -214,7 +216,7 @@ void WorldSession::HandleArenaTeamInviteOpcode(WorldPacket& recvData) WorldPacket data(SMSG_ARENA_TEAM_INVITE, (8+10)); data << GetPlayer()->GetName(); data << arenaTeam->GetName(); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); TC_LOG_DEBUG("network", "WORLD: Sent SMSG_ARENA_TEAM_INVITE"); } diff --git a/src/server/game/Handlers/AuctionHouseHandler.cpp b/src/server/game/Handlers/AuctionHouseHandler.cpp index e43018b55c4..668439e6fa3 100644 --- a/src/server/game/Handlers/AuctionHouseHandler.cpp +++ b/src/server/game/Handlers/AuctionHouseHandler.cpp @@ -16,19 +16,24 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" -#include "Player.h" -#include "World.h" -#include "WorldPacket.h" #include "WorldSession.h" - +#include "AccountMgr.h" #include "AuctionHouseMgr.h" #include "CharacterCache.h" -#include "Log.h" +#include "Creature.h" +#include "DatabaseEnv.h" +#include "DBCStructure.h" +#include "Item.h" #include "Language.h" +#include "Log.h" +#include "Mail.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Player.h" #include "UpdateMask.h" #include "Util.h" -#include "AccountMgr.h" +#include "World.h" +#include "WorldPacket.h" //void called when player click on auctioneer npc void WorldSession::HandleAuctionHelloOpcode(WorldPacket& recvData) @@ -149,7 +154,7 @@ void WorldSession::HandleAuctionSellItem(WorldPacket& recvData) if (itemsCount > MAX_AUCTION_ITEMS) { - SendAuctionCommandResult(NULL, AUCTION_SELL_ITEM, ERR_AUCTION_DATABASE_ERROR); + SendAuctionCommandResult(nullptr, AUCTION_SELL_ITEM, ERR_AUCTION_DATABASE_ERROR); recvData.rfinish(); return; } @@ -176,7 +181,7 @@ void WorldSession::HandleAuctionSellItem(WorldPacket& recvData) if (bid > MAX_MONEY_AMOUNT || buyout > MAX_MONEY_AMOUNT) { TC_LOG_DEBUG("network", "WORLD: HandleAuctionSellItem - Player %s (GUID %u) attempted to sell item with higher price than max gold amount.", _player->GetName().c_str(), _player->GetGUID().GetCounter()); - SendAuctionCommandResult(NULL, AUCTION_SELL_ITEM, ERR_AUCTION_DATABASE_ERROR); + SendAuctionCommandResult(nullptr, AUCTION_SELL_ITEM, ERR_AUCTION_DATABASE_ERROR); return; } @@ -220,7 +225,7 @@ void WorldSession::HandleAuctionSellItem(WorldPacket& recvData) if (!item) { - SendAuctionCommandResult(NULL, AUCTION_SELL_ITEM, ERR_AUCTION_ITEM_NOT_FOUND); + SendAuctionCommandResult(nullptr, AUCTION_SELL_ITEM, ERR_AUCTION_ITEM_NOT_FOUND); return; } @@ -231,7 +236,7 @@ void WorldSession::HandleAuctionSellItem(WorldPacket& recvData) (item->GetTemplate()->Flags & ITEM_FLAG_CONJURED) || item->GetUInt32Value(ITEM_FIELD_DURATION) || item->GetCount() < count[i] || itemEntry != item->GetTemplate()->ItemId) { - SendAuctionCommandResult(NULL, AUCTION_SELL_ITEM, ERR_AUCTION_DATABASE_ERROR); + SendAuctionCommandResult(nullptr, AUCTION_SELL_ITEM, ERR_AUCTION_DATABASE_ERROR); return; } @@ -241,7 +246,7 @@ void WorldSession::HandleAuctionSellItem(WorldPacket& recvData) if (!finalCount) { - SendAuctionCommandResult(NULL, AUCTION_SELL_ITEM, ERR_AUCTION_DATABASE_ERROR); + SendAuctionCommandResult(nullptr, AUCTION_SELL_ITEM, ERR_AUCTION_DATABASE_ERROR); return; } @@ -264,7 +269,7 @@ void WorldSession::HandleAuctionSellItem(WorldPacket& recvData) if (item->GetMaxStackCount() < finalCount) { - SendAuctionCommandResult(NULL, AUCTION_SELL_ITEM, ERR_AUCTION_DATABASE_ERROR); + SendAuctionCommandResult(nullptr, AUCTION_SELL_ITEM, ERR_AUCTION_DATABASE_ERROR); return; } } @@ -277,7 +282,7 @@ void WorldSession::HandleAuctionSellItem(WorldPacket& recvData) uint32 deposit = sAuctionMgr->GetAuctionDeposit(auctionHouseEntry, etime, item, finalCount); if (!_player->HasEnoughMoney((uint64)deposit)) { - SendAuctionCommandResult(NULL, AUCTION_SELL_ITEM, ERR_AUCTION_NOT_ENOUGHT_MONEY); + SendAuctionCommandResult(nullptr, AUCTION_SELL_ITEM, ERR_AUCTION_NOT_ENOUGHT_MONEY); return; } @@ -305,7 +310,7 @@ void WorldSession::HandleAuctionSellItem(WorldPacket& recvData) return; } - const AuctionHouseEntry* AHEntry = sAuctionMgr->GetAuctionHouseEntry(auctioneerInfo->faction); + AuctionHouseEntry const* AHEntry = sAuctionMgr->GetAuctionHouseEntry(auctioneerInfo->faction); AH->houseId = AHEntry->houseId; } @@ -327,7 +332,7 @@ void WorldSession::HandleAuctionSellItem(WorldPacket& recvData) AH->bidder = 0; AH->bid = 0; AH->buyout = buyout; - AH->expire_time = time(NULL) + auctionTime; + AH->expire_time = time(nullptr) + auctionTime; AH->deposit = deposit; AH->etime = etime; AH->auctionHouseEntry = auctionHouseEntry; @@ -364,7 +369,7 @@ void WorldSession::HandleAuctionSellItem(WorldPacket& recvData) if (!newItem) { TC_LOG_ERROR("network", "CMSG_AUCTION_SELL_ITEM: Could not create clone of item %u", item->GetEntry()); - SendAuctionCommandResult(NULL, AUCTION_SELL_ITEM, ERR_AUCTION_DATABASE_ERROR); + SendAuctionCommandResult(nullptr, AUCTION_SELL_ITEM, ERR_AUCTION_DATABASE_ERROR); delete AH; return; } @@ -384,7 +389,7 @@ void WorldSession::HandleAuctionSellItem(WorldPacket& recvData) AH->bidder = 0; AH->bid = 0; AH->buyout = buyout; - AH->expire_time = time(NULL) + auctionTime; + AH->expire_time = time(nullptr) + auctionTime; AH->deposit = deposit; AH->etime = etime; AH->auctionHouseEntry = auctionHouseEntry; @@ -475,7 +480,7 @@ void WorldSession::HandleAuctionPlaceBid(WorldPacket& recvData) if (!auction || auction->owner == player->GetGUID().GetCounter()) { //you cannot bid your own auction: - SendAuctionCommandResult(NULL, AUCTION_PLACE_BID, ERR_AUCTION_BID_OWN); + SendAuctionCommandResult(nullptr, AUCTION_PLACE_BID, ERR_AUCTION_BID_OWN); return; } @@ -485,7 +490,7 @@ void WorldSession::HandleAuctionPlaceBid(WorldPacket& recvData) if (!auction_owner && sCharacterCache->GetCharacterAccountIdByGuid(ownerGuid) == player->GetSession()->GetAccountId()) { //you cannot bid your another character auction: - SendAuctionCommandResult(NULL, AUCTION_PLACE_BID, ERR_AUCTION_BID_OWN); + SendAuctionCommandResult(nullptr, AUCTION_PLACE_BID, ERR_AUCTION_BID_OWN); return; } @@ -629,15 +634,15 @@ void WorldSession::HandleAuctionRemoveItem(WorldPacket& recvData) else { TC_LOG_ERROR("network", "Auction id: %u got non existing item (item guid : %u)!", auction->Id, auction->itemGUIDLow); - SendAuctionCommandResult(NULL, AUCTION_CANCEL, ERR_AUCTION_DATABASE_ERROR); + SendAuctionCommandResult(nullptr, AUCTION_CANCEL, ERR_AUCTION_DATABASE_ERROR); return; } } else { - SendAuctionCommandResult(NULL, AUCTION_CANCEL, ERR_AUCTION_DATABASE_ERROR); + SendAuctionCommandResult(nullptr, AUCTION_CANCEL, ERR_AUCTION_DATABASE_ERROR); //this code isn't possible ... maybe there should be assert - TC_LOG_INFO("entities.player.cheat", "CHEATER : %u, he tried to cancel auction (id: %u) of another player, or auction is NULL", player->GetGUID().GetCounter(), auctionId); + TC_LOG_INFO("entities.player.cheat", "CHEATER : %u, he tried to cancel auction (id: %u) of another player, or auction is nullptr", player->GetGUID().GetCounter(), auctionId); return; } diff --git a/src/server/game/Handlers/BattleGroundHandler.cpp b/src/server/game/Handlers/BattleGroundHandler.cpp index ba68a63ce93..926e97b22c4 100644 --- a/src/server/game/Handlers/BattleGroundHandler.cpp +++ b/src/server/game/Handlers/BattleGroundHandler.cpp @@ -16,25 +16,29 @@ * with this program. If not, see . */ -#include "Common.h" -#include "ObjectAccessor.h" -#include "ObjectMgr.h" -#include "ArenaTeamMgr.h" -#include "WorldPacket.h" #include "WorldSession.h" - #include "ArenaTeam.h" -#include "BattlegroundMgr.h" +#include "ArenaTeamMgr.h" #include "Battleground.h" +#include "BattlegroundMgr.h" #include "Chat.h" +#include "Common.h" +#include "Creature.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "DisableMgr.h" #include "GameTime.h" +#include "Group.h" #include "Language.h" #include "Log.h" -#include "Player.h" +#include "MotionMaster.h" #include "Object.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Opcodes.h" -#include "DisableMgr.h" -#include "Group.h" +#include "Player.h" +#include "World.h" +#include "WorldPacket.h" void WorldSession::HandleBattlemasterHelloOpcode(WorldPacket& recvData) { @@ -42,7 +46,7 @@ void WorldSession::HandleBattlemasterHelloOpcode(WorldPacket& recvData) recvData >> guid; TC_LOG_DEBUG("network", "WORLD: Recvd CMSG_BATTLEMASTER_HELLO Message from %s", guid.ToString().c_str()); - Creature* unit = GetPlayer()->GetMap()->GetCreature(guid); + Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_BATTLEMASTER); if (!unit) return; @@ -77,7 +81,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) uint32 instanceId; uint8 asGroup; bool isPremade = false; - Group* grp = NULL; + Group* grp = nullptr; ObjectGuid guid; recvData >> instanceId; // Instance Id @@ -109,7 +113,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) return; } - if (DisableMgr::IsDisabledFor(DISABLE_TYPE_BATTLEGROUND, bgTypeId_, NULL)) + if (DisableMgr::IsDisabledFor(DISABLE_TYPE_BATTLEGROUND, bgTypeId_, nullptr)) { ChatHandler(this).PSendSysMessage(LANG_BG_DISABLED); return; @@ -127,7 +131,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) return; // get bg instance or bg template if instance not found - Battleground* bg = NULL; + Battleground* bg = nullptr; if (instanceId) bg = sBattlegroundMgr->GetBattlegroundThroughClientInstance(instanceId, bgTypeId); @@ -150,7 +154,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) { WorldPacket data; sBattlegroundMgr->BuildStatusFailedPacket(&data, bg, _player, 0, ERR_LFG_CANT_USE_BATTLEGROUND); - GetPlayer()->GetSession()->SendPacket(&data); + GetPlayer()->SendDirectMessage(&data); return; } @@ -159,7 +163,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) { WorldPacket data; sBattlegroundMgr->BuildStatusFailedPacket(&data, bg, _player, 0, ERR_GROUP_JOIN_BATTLEGROUND_DESERTERS); - _player->GetSession()->SendPacket(&data); + _player->SendDirectMessage(&data); return; } @@ -168,7 +172,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) // player is already in random queue WorldPacket data; sBattlegroundMgr->BuildStatusFailedPacket(&data, bg, _player, 0, ERR_IN_RANDOM_BG); - _player->GetSession()->SendPacket(&data); + _player->SendDirectMessage(&data); return; } @@ -177,7 +181,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) // player is already in queue, can't start random queue WorldPacket data; sBattlegroundMgr->BuildStatusFailedPacket(&data, bg, _player, 0, ERR_IN_NON_RANDOM_BG); - _player->GetSession()->SendPacket(&data); + _player->SendDirectMessage(&data); return; } @@ -191,7 +195,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) { WorldPacket data; sBattlegroundMgr->BuildStatusFailedPacket(&data, bg, _player, 0, ERR_BATTLEGROUND_TOO_MANY_QUEUES); - _player->GetSession()->SendPacket(&data); + _player->SendDirectMessage(&data); return; } @@ -200,7 +204,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) return; BattlegroundQueue& bgQueue = sBattlegroundMgr->GetBattlegroundQueue(bgQueueTypeId); - GroupQueueInfo* ginfo = bgQueue.AddGroup(_player, NULL, bgTypeId, bracketEntry, 0, false, isPremade, 0, 0); + GroupQueueInfo* ginfo = bgQueue.AddGroup(_player, nullptr, bgTypeId, bracketEntry, 0, false, isPremade, 0, 0); uint32 avgTime = bgQueue.GetAverageQueueWaitTime(ginfo, bracketEntry->GetBracketId()); uint32 queueSlot = _player->AddBattlegroundQueueId(bgQueueTypeId); @@ -229,7 +233,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) isPremade = (grp->GetMembersCount() >= bg->GetMinPlayersPerTeam()); BattlegroundQueue& bgQueue = sBattlegroundMgr->GetBattlegroundQueue(bgQueueTypeId); - GroupQueueInfo* ginfo = NULL; + GroupQueueInfo* ginfo = nullptr; uint32 avgTime = 0; if (!err) @@ -239,7 +243,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) avgTime = bgQueue.GetAverageQueueWaitTime(ginfo, bracketEntry->GetBracketId()); } - for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* member = itr->GetSource(); if (!member) @@ -249,7 +253,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) { WorldPacket data; sBattlegroundMgr->BuildStatusFailedPacket(&data, bg, _player, 0, err); - member->GetSession()->SendPacket(&data); + member->SendDirectMessage(&data); continue; } @@ -261,7 +265,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket& recvData) WorldPacket data; // send status packet (in queue) sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, member, queueSlot, STATUS_WAIT_QUEUE, avgTime, ginfo->JoinTime, ginfo->ArenaType); - member->GetSession()->SendPacket(&data); + member->SendDirectMessage(&data); TC_LOG_DEBUG("bg.battleground", "Battleground: player joined queue for bg queue type %u bg type %u: GUID %u, NAME %s", bgQueueTypeId, bgTypeId, member->GetGUID().GetCounter(), member->GetName().c_str()); } @@ -281,8 +285,8 @@ void WorldSession::HandleBattlegroundPlayerPositionsOpcode(WorldPacket& /*recvDa uint32 acount = 0; uint32 hcount = 0; - Player* aplr = NULL; - Player* hplr = NULL; + Player* aplr = nullptr; + Player* hplr = nullptr; if (ObjectGuid guid = bg->GetFlagPickerGUID(TEAM_ALLIANCE)) { @@ -508,7 +512,7 @@ void WorldSession::HandleBattleFieldPortOpcode(WorldPacket &recvData) //send bg command result to show nice message WorldPacket data2; sBattlegroundMgr->BuildStatusFailedPacket(&data2, bg, _player, 0, ERR_GROUP_JOIN_BATTLEGROUND_DESERTERS); - _player->GetSession()->SendPacket(&data2); + _player->SendDirectMessage(&data2); action = 0; TC_LOG_DEBUG("bg.battleground", "Player %s (%u) has a deserter debuff, do not port him to battleground!", _player->GetName().c_str(), _player->GetGUID().GetCounter()); } @@ -548,7 +552,7 @@ void WorldSession::HandleBattleFieldPortOpcode(WorldPacket &recvData) } sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, _player, queueSlot, STATUS_IN_PROGRESS, _player->GetBattlegroundQueueJoinTime(bgTypeId), bg->GetElapsedTime(), bg->GetArenaType()); - _player->GetSession()->SendPacket(&data); + _player->SendDirectMessage(&data); // remove battleground queue status from BGmgr bgQueue.RemovePlayer(_player->GetGUID(), false); @@ -624,7 +628,7 @@ void WorldSession::HandleBattlefieldStatusOpcode(WorldPacket & /*recvData*/) WorldPacket data; // we must update all queues here - Battleground* bg = NULL; + Battleground* bg = nullptr; for (uint8 i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i) { BattlegroundQueueTypeId bgQueueTypeId = _player->GetBattlegroundQueueTypeId(i); @@ -707,7 +711,7 @@ void WorldSession::HandleBattlemasterJoinArena(WorldPacket& recvData) return; } - if (DisableMgr::IsDisabledFor(DISABLE_TYPE_BATTLEGROUND, BATTLEGROUND_AA, NULL)) + if (DisableMgr::IsDisabledFor(DISABLE_TYPE_BATTLEGROUND, BATTLEGROUND_AA, nullptr)) { ChatHandler(this).PSendSysMessage(LANG_ARENA_DISABLED); return; @@ -748,7 +752,7 @@ void WorldSession::HandleBattlemasterJoinArena(WorldPacket& recvData) BattlegroundQueue &bgQueue = sBattlegroundMgr->GetBattlegroundQueue(bgQueueTypeId); uint32 avgTime = 0; - GroupQueueInfo* ginfo = NULL; + GroupQueueInfo* ginfo = nullptr; err = grp->CanJoinBattlegroundQueue(bg, bgQueueTypeId, arenatype, arenatype, true, arenaslot); if (!err) @@ -759,7 +763,7 @@ void WorldSession::HandleBattlemasterJoinArena(WorldPacket& recvData) avgTime = bgQueue.GetAverageQueueWaitTime(ginfo, bracketEntry->GetBracketId()); } - for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* member = itr->GetSource(); if (!member) @@ -769,7 +773,7 @@ void WorldSession::HandleBattlemasterJoinArena(WorldPacket& recvData) { WorldPacket data; sBattlegroundMgr->BuildStatusFailedPacket(&data, bg, _player, 0, err); - member->GetSession()->SendPacket(&data); + member->SendDirectMessage(&data); continue; } @@ -781,7 +785,7 @@ void WorldSession::HandleBattlemasterJoinArena(WorldPacket& recvData) WorldPacket data; // send status packet (in queue) sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, member, queueSlot, STATUS_WAIT_QUEUE, avgTime, ginfo->JoinTime, arenatype); - member->GetSession()->SendPacket(&data); + member->SendDirectMessage(&data); TC_LOG_DEBUG("bg.battleground", "Battleground: player joined queue for arena as group bg queue type %u bg type %u: GUID %u, NAME %s", bgQueueTypeId, bgTypeId, member->GetGUID().GetCounter(), member->GetName().c_str()); } diff --git a/src/server/game/Handlers/BattlefieldHandler.cpp b/src/server/game/Handlers/BattlefieldHandler.cpp index be88002b822..142977f5ed7 100644 --- a/src/server/game/Handlers/BattlefieldHandler.cpp +++ b/src/server/game/Handlers/BattlefieldHandler.cpp @@ -15,14 +15,14 @@ * with this program. If not, see . */ +#include "WorldSession.h" +#include "Battlefield.h" +#include "BattlefieldMgr.h" +#include "Log.h" +#include "Object.h" #include "Opcodes.h" #include "Player.h" #include "WorldPacket.h" -#include "WorldSession.h" -#include "Object.h" - -#include "Battlefield.h" -#include "BattlefieldMgr.h" /** * @fn void WorldSession::SendBfInvitePlayerToWar(uint64 guid, uint32 zoneId, uint32 acceptTime) @@ -53,7 +53,7 @@ void WorldSession::SendBfInvitePlayerToWar(ObjectGuid guid, uint32 zoneId, uint3 data.WriteByteSeq(guid[4]); data.WriteByteSeq(guid[2]); data.WriteByteSeq(guid[0]); - data << uint32(time(NULL) + acceptTime); // Invite lasts until + data << uint32(time(nullptr) + acceptTime); // Invite lasts until data.WriteByteSeq(guid[7]); data.WriteByteSeq(guid[5]); SendPacket(&data); diff --git a/src/server/game/Handlers/CalendarHandler.cpp b/src/server/game/Handlers/CalendarHandler.cpp index 9658cdcf964..eaae85634cb 100644 --- a/src/server/game/Handlers/CalendarHandler.cpp +++ b/src/server/game/Handlers/CalendarHandler.cpp @@ -58,7 +58,7 @@ void WorldSession::HandleCalendarGetCalendar(WorldPacket& /*recvData*/) ObjectGuid guid = _player->GetGUID(); TC_LOG_DEBUG("network", "CMSG_CALENDAR_GET_CALENDAR [%s]", guid.ToString().c_str()); - time_t currTime = time(NULL); + time_t currTime = time(nullptr); WorldPacket data(SMSG_CALENDAR_SEND_CALENDAR, 1000); // Average size if no instance @@ -243,7 +243,7 @@ void WorldSession::HandleCalendarAddEvent(WorldPacket& recvData) // prevent events in the past // To Do: properly handle timezones and remove the "- time_t(86400L)" hack - if (time_t(eventPackedTime) < (time(NULL) - time_t(86400L))) + if (time_t(eventPackedTime) < (time(nullptr) - time_t(86400L))) { recvData.rfinish(); return; @@ -290,7 +290,7 @@ void WorldSession::HandleCalendarAddEvent(WorldPacket& recvData) catch (ByteBufferException const&) { delete calendarEvent; - calendarEvent = NULL; + calendarEvent = nullptr; throw; } @@ -336,7 +336,7 @@ void WorldSession::HandleCalendarUpdateEvent(WorldPacket& recvData) // prevent events in the past // To Do: properly handle timezones and remove the "- time_t(86400L)" hack - if (time_t(eventPackedTime) < (time(NULL) - time_t(86400L))) + if (time_t(eventPackedTime) < (time(nullptr) - time_t(86400L))) { recvData.rfinish(); return; @@ -393,7 +393,7 @@ void WorldSession::HandleCalendarCopyEvent(WorldPacket& recvData) // prevent events in the past // To Do: properly handle timezones and remove the "- time_t(86400L)" hack - if (time_t(eventTime) < (time(NULL) - time_t(86400L))) + if (time_t(eventTime) < (time(nullptr) - time_t(86400L))) { recvData.rfinish(); return; @@ -536,7 +536,7 @@ void WorldSession::HandleCalendarEventSignup(WorldPacket& recvData) } CalendarInviteStatus status = tentative ? CALENDAR_STATUS_TENTATIVE : CALENDAR_STATUS_SIGNED_UP; - CalendarInvite* invite = new CalendarInvite(sCalendarMgr->GetFreeInviteId(), eventId, guid, guid, time(NULL), status, CALENDAR_RANK_PLAYER, ""); + CalendarInvite* invite = new CalendarInvite(sCalendarMgr->GetFreeInviteId(), eventId, guid, guid, time(nullptr), status, CALENDAR_RANK_PLAYER, ""); sCalendarMgr->AddInvite(calendarEvent, invite); sCalendarMgr->SendCalendarClearPendingAction(guid); } @@ -568,7 +568,7 @@ void WorldSession::HandleCalendarEventRsvp(WorldPacket& recvData) if (CalendarInvite* invite = sCalendarMgr->GetInvite(inviteId)) { invite->SetStatus(CalendarInviteStatus(status)); - invite->SetStatusTime(time(NULL)); + invite->SetStatusTime(time(nullptr)); sCalendarMgr->UpdateInvite(invite); sCalendarMgr->SendCalendarEventStatus(*calendarEvent, *invite); @@ -631,7 +631,7 @@ void WorldSession::HandleCalendarEventStatus(WorldPacket& recvData) { invite->SetStatus((CalendarInviteStatus)status); // not sure if we should set response time when moderator changes invite status - //invite->SetStatusTime(time(NULL)); + //invite->SetStatusTime(time(nullptr)); sCalendarMgr->UpdateInvite(invite); sCalendarMgr->SendCalendarEventStatus(*calendarEvent, *invite); @@ -738,7 +738,7 @@ void WorldSession::HandleSetSavedInstanceExtend(WorldPacket& recvData) void WorldSession::SendCalendarRaidLockout(InstanceSave const* save, bool add) { TC_LOG_DEBUG("network", "%s", add ? "SMSG_CALENDAR_RAID_LOCKOUT_ADDED" : "SMSG_CALENDAR_RAID_LOCKOUT_REMOVED"); - time_t currTime = time(NULL); + time_t currTime = time(nullptr); WorldPacket data(SMSG_CALENDAR_RAID_LOCKOUT_REMOVED, (add ? 4 : 0) + 4 + 4 + 4 + 8); if (add) @@ -763,7 +763,7 @@ void WorldSession::SendCalendarRaidLockoutUpdated(InstanceSave const* save) TC_LOG_DEBUG("network", "SMSG_CALENDAR_RAID_LOCKOUT_UPDATED [%s] Map: %u, Difficulty %u", guid.ToString().c_str(), save->GetMapId(), save->GetDifficulty()); - time_t currTime = time(NULL); + time_t currTime = time(nullptr); WorldPacket data(SMSG_CALENDAR_RAID_LOCKOUT_UPDATED, 4 + 4 + 4 + 4 + 8); data.AppendPackedTime(currTime); diff --git a/src/server/game/Handlers/ChannelHandler.cpp b/src/server/game/Handlers/ChannelHandler.cpp index 8546d6099f6..1cd18499a39 100644 --- a/src/server/game/Handlers/ChannelHandler.cpp +++ b/src/server/game/Handlers/ChannelHandler.cpp @@ -16,13 +16,13 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" // for normalizePlayerName +#include "WorldSession.h" #include "Channel.h" #include "ChannelMgr.h" +#include "DBCStores.h" +#include "Log.h" +#include "ObjectMgr.h" // for normalizePlayerName #include "Player.h" -#include "WorldSession.h" - -#include static size_t const MAX_CHANNEL_PASS_STR = 31; diff --git a/src/server/game/Handlers/CharacterHandler.cpp b/src/server/game/Handlers/CharacterHandler.cpp index 0e9d1a8ead8..19594110ede 100644 --- a/src/server/game/Handlers/CharacterHandler.cpp +++ b/src/server/game/Handlers/CharacterHandler.cpp @@ -16,42 +16,43 @@ * with this program. If not, see . */ +#include "WorldSession.h" #include "AccountMgr.h" #include "ArenaTeam.h" #include "ArenaTeamMgr.h" -#include "Battleground.h" +#include "BattlenetServerManager.h" #include "CalendarMgr.h" #include "CharacterCache.h" #include "Chat.h" -#include "Common.h" #include "DatabaseEnv.h" +#include "DBCStores.h" +#include "GameObject.h" #include "GameTime.h" +#include "GitRevision.h" #include "Group.h" #include "Guild.h" #include "GuildFinderMgr.h" #include "GuildMgr.h" +#include "Item.h" #include "Language.h" #include "LFGMgr.h" #include "Log.h" +#include "Map.h" +#include "Metric.h" +#include "MotionMaster.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Opcodes.h" #include "Pet.h" -#include "PlayerDump.h" #include "Player.h" -#include "QueryCallback.h" +#include "PlayerDump.h" +#include "QueryHolder.h" #include "ReputationMgr.h" -#include "GitRevision.h" #include "ScriptMgr.h" #include "SharedDefines.h" #include "SocialMgr.h" -#include "UpdateMask.h" -#include "Util.h" #include "World.h" #include "WorldPacket.h" -#include "WorldSession.h" -#include "Metric.h" -#include "BattlenetServerManager.h" class LoginQueryHolder : public SQLQueryHolder { @@ -131,7 +132,7 @@ bool LoginQueryHolder::Initialize() stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_MAILCOUNT); stmt->setUInt32(0, lowGuid); - stmt->setUInt64(1, uint64(time(NULL))); + stmt->setUInt64(1, uint64(time(nullptr))); res &= SetPreparedQuery(PLAYER_LOGIN_QUERY_LOAD_MAIL_COUNT, stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_MAILDATE); @@ -709,7 +710,7 @@ void WorldSession::HandleCharDeleteOpcode(WorldPacket& recvData) void WorldSession::HandlePlayerLoginOpcode(WorldPacket& recvData) { - if (PlayerLoading() || GetPlayer() != NULL) + if (PlayerLoading() || GetPlayer() != nullptr) { TC_LOG_ERROR("network", "Player tries to login again, AccountId = %d", GetAccountId()); KickPlayer(); @@ -780,7 +781,7 @@ void WorldSession::HandlePlayerLogin(LoginQueryHolder* holder) // "GetAccountId() == db stored account id" checked in LoadFromDB (prevent login not own character using cheating tools) if (!pCurrChar->LoadFromDB(playerGuid, holder)) { - SetPlayer(NULL); + SetPlayer(nullptr); KickPlayer(); // disconnect client, player no set to session and it will not deleted or saved at kick delete pCurrChar; // delete it manually delete holder; // delete all unprocessed queries @@ -1619,12 +1620,11 @@ void WorldSession::HandleEquipmentSetSave(WorldPacket& recvData) std::string iconName; recvData >> iconName; - EquipmentSet eqSet; - - eqSet.Guid = setGuid; - eqSet.Name = name; - eqSet.IconName = iconName; - eqSet.state = EQUIPMENT_SET_NEW; + EquipmentSetInfo::EquipmentSetData eqData; + eqData.Guid = setGuid; + eqData.SetID = index; + eqData.SetName = name; + eqData.SetIcon = iconName; for (uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i) { @@ -1633,31 +1633,25 @@ void WorldSession::HandleEquipmentSetSave(WorldPacket& recvData) // if client sends 0, it means empty slot if (itemGuid.IsEmpty()) - { - eqSet.Items[i] = 0; continue; - } // equipment manager sends "1" (as raw GUID) for slots set to "ignore" (don't touch slot at equip set) if (itemGuid.GetRawValue() == 1) { // ignored slots saved as bit mask because we have no free special values for Items[i] - eqSet.IgnoreMask |= 1 << i; + eqData.IgnoreMask |= 1 << i; continue; } // some cheating checks Item* item = _player->GetItemByPos(INVENTORY_SLOT_BAG_0, i); if (!item || item->GetGUID() != itemGuid) - { - eqSet.Items[i] = 0; continue; - } - eqSet.Items[i] = itemGuid.GetCounter(); + eqData.Pieces[i] = itemGuid; } - _player->SetEquipmentSet(index, eqSet); + _player->SetEquipmentSet(eqData); } void WorldSession::HandleEquipmentSetDelete(WorldPacket& recvData) @@ -1713,7 +1707,7 @@ void WorldSession::HandleEquipmentSetUse(WorldPacket& recvData) _player->StoreItem(sDest, uItem, true); } else - _player->SendEquipError(msg, uItem, NULL); + _player->SendEquipError(msg, uItem, nullptr); continue; } @@ -2360,11 +2354,11 @@ void WorldSession::HandleRandomizeCharNameOpcode(WorldPacket& recvData) return; } - std::string const* name = GetRandomCharacterName(race, gender); + std::string const& name = GetRandomCharacterName(race, gender); WorldPacket data(SMSG_RANDOMIZE_CHAR_NAME, 10); data.WriteBit(0); // unk - data.WriteBits(name->size(), 7); - data.WriteString(*name); + data.WriteBits(name.size(), 7); + data.WriteString(name); SendPacket(&data); } diff --git a/src/server/game/Handlers/ChatHandler.cpp b/src/server/game/Handlers/ChatHandler.cpp index c0296a79118..cd41bc1f22d 100644 --- a/src/server/game/Handlers/ChatHandler.cpp +++ b/src/server/game/Handlers/ChatHandler.cpp @@ -16,29 +16,30 @@ * with this program. If not, see . */ -#include "Common.h" -#include "ObjectAccessor.h" -#include "ObjectMgr.h" -#include "GuildMgr.h" -#include "World.h" -#include "WorldPacket.h" #include "WorldSession.h" -#include "DatabaseEnv.h" +#include "AccountMgr.h" #include "CellImpl.h" -#include "Chat.h" #include "Channel.h" #include "ChannelMgr.h" +#include "Chat.h" +#include "Common.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "GridNotifiersImpl.h" #include "Group.h" #include "Guild.h" +#include "GuildMgr.h" #include "Language.h" #include "Log.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Opcodes.h" #include "Player.h" +#include "ScriptMgr.h" #include "SpellAuraEffects.h" #include "Util.h" -#include "ScriptMgr.h" -#include "AccountMgr.h" +#include "World.h" +#include "WorldPacket.h" void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) { @@ -212,7 +213,7 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) if (!sender->CanSpeak()) { - std::string timeStr = secsToTimeString(m_muteTime - time(NULL)); + std::string timeStr = secsToTimeString(m_muteTime - time(nullptr)); SendNotification(GetTrinityString(LANG_WAIT_BEFORE_SPEAKING), timeStr.c_str()); recvData.rfinish(); // Prevent warnings return; @@ -404,7 +405,7 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, group); WorldPacket data; - ChatHandler::BuildChatPacket(data, ChatMsg(type), Language(lang), sender, NULL, msg); + ChatHandler::BuildChatPacket(data, ChatMsg(type), Language(lang), sender, nullptr, msg); group->BroadcastPacket(&data, false, group->GetMemberGroup(GetPlayer()->GetGUID())); break; } @@ -452,7 +453,7 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, group); WorldPacket data; - ChatHandler::BuildChatPacket(data, ChatMsg(type), Language(lang), sender, NULL, msg); + ChatHandler::BuildChatPacket(data, ChatMsg(type), Language(lang), sender, nullptr, msg); group->BroadcastPacket(&data, false); break; } @@ -466,7 +467,7 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) WorldPacket data; //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); + ChatHandler::BuildChatPacket(data, CHAT_MSG_RAID_WARNING, Language(lang), sender, nullptr, msg); group->BroadcastPacket(&data, false); break; } @@ -484,7 +485,7 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket& recvData) sScriptMgr->OnPlayerChat(GetPlayer(), type, lang, msg, group); WorldPacket data; - ChatHandler::BuildChatPacket(data, ChatMsg(type), Language(lang), sender, NULL, msg); + ChatHandler::BuildChatPacket(data, ChatMsg(type), Language(lang), sender, nullptr, msg); group->BroadcastPacket(&data, false); break; } @@ -648,7 +649,7 @@ void WorldSession::HandleAddonMessagechatOpcode(WorldPacket& recvData) return; WorldPacket data; - ChatHandler::BuildChatPacket(data, type, LANG_ADDON, sender, NULL, message, 0U, "", DEFAULT_LOCALE, prefix); + ChatHandler::BuildChatPacket(data, type, LANG_ADDON, sender, nullptr, message, 0U, "", DEFAULT_LOCALE, prefix); group->BroadcastAddonMessagePacket(&data, prefix, false); break; } @@ -681,7 +682,7 @@ void WorldSession::HandleAddonMessagechatOpcode(WorldPacket& recvData) break; WorldPacket data; - ChatHandler::BuildChatPacket(data, type, LANG_ADDON, sender, NULL, message, 0U, "", DEFAULT_LOCALE, prefix); + ChatHandler::BuildChatPacket(data, type, LANG_ADDON, sender, nullptr, message, 0U, "", DEFAULT_LOCALE, prefix); group->BroadcastAddonMessagePacket(&data, prefix, true, -1, group->GetMemberGroup(sender->GetGUID())); break; } @@ -743,7 +744,7 @@ void WorldSession::HandleTextEmoteOpcode(WorldPacket& recvData) if (!GetPlayer()->CanSpeak()) { - std::string timeStr = secsToTimeString(m_muteTime - time(NULL)); + std::string timeStr = secsToTimeString(m_muteTime - time(nullptr)); SendNotification(GetTrinityString(LANG_WAIT_BEFORE_SPEAKING), timeStr.c_str()); return; } @@ -833,7 +834,7 @@ void WorldSession::HandleChatIgnoredOpcode(WorldPacket& recvData) WorldPacket data; ChatHandler::BuildChatPacket(data, CHAT_MSG_IGNORED, LANG_UNIVERSAL, _player, _player, GetPlayer()->GetName()); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } void WorldSession::HandleChannelDeclineInvite(WorldPacket &recvPacket) diff --git a/src/server/game/Handlers/CombatHandler.cpp b/src/server/game/Handlers/CombatHandler.cpp index 375e1b1afa6..a01a8524b3b 100644 --- a/src/server/game/Handlers/CombatHandler.cpp +++ b/src/server/game/Handlers/CombatHandler.cpp @@ -16,14 +16,15 @@ * with this program. If not, see . */ -#include "Common.h" -#include "Log.h" -#include "WorldPacket.h" #include "WorldSession.h" -#include "ObjectAccessor.h" +#include "Common.h" #include "CreatureAI.h" -#include "Vehicle.h" +#include "DBCStores.h" +#include "Log.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "Vehicle.h" +#include "WorldPacket.h" void WorldSession::HandleAttackSwingOpcode(WorldPacket& recvData) { @@ -37,7 +38,7 @@ void WorldSession::HandleAttackSwingOpcode(WorldPacket& recvData) if (!pEnemy) { // stop attack state at client - SendAttackStop(NULL); + SendAttackStop(nullptr); return; } diff --git a/src/server/game/Handlers/DuelHandler.cpp b/src/server/game/Handlers/DuelHandler.cpp index 77b38db670b..c90660ef022 100644 --- a/src/server/game/Handlers/DuelHandler.cpp +++ b/src/server/game/Handlers/DuelHandler.cpp @@ -43,7 +43,7 @@ void WorldSession::HandleDuelAcceptedOpcode(WorldPacket& recvPacket) TC_LOG_DEBUG("network", "Player 1 is: %u (%s)", player->GetGUID().GetCounter(), player->GetName().c_str()); TC_LOG_DEBUG("network", "Player 2 is: %u (%s)", plTarget->GetGUID().GetCounter(), plTarget->GetName().c_str()); - time_t now = time(NULL); + time_t now = time(nullptr); player->duel->startTimer = now; plTarget->duel->startTimer = now; diff --git a/src/server/game/Handlers/GroupHandler.cpp b/src/server/game/Handlers/GroupHandler.cpp index b24efc2cfa6..d9f727d7e69 100644 --- a/src/server/game/Handlers/GroupHandler.cpp +++ b/src/server/game/Handlers/GroupHandler.cpp @@ -16,24 +16,25 @@ * with this program. If not, see . */ +#include "WorldSession.h" #include "CharacterCache.h" #include "Common.h" #include "DatabaseEnv.h" #include "Group.h" #include "GroupMgr.h" #include "Log.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Pet.h" #include "PhasingHandler.h" #include "Player.h" #include "SocialMgr.h" +#include "SpellAuraEffects.h" #include "SpellAuras.h" #include "Util.h" #include "Vehicle.h" #include "World.h" #include "WorldPacket.h" -#include "WorldSession.h" -#include "SpellAuraEffects.h" class Aura; @@ -232,7 +233,7 @@ void WorldSession::HandleGroupInviteOpcode(WorldPacket& recvData) data << int32(0); - invitedPlayer->GetSession()->SendPacket(&data); + invitedPlayer->SendDirectMessage(&data); } return; @@ -336,7 +337,7 @@ void WorldSession::HandleGroupInviteOpcode(WorldPacket& recvData) data << int32(0); - invitedPlayer->GetSession()->SendPacket(&data); + invitedPlayer->SendDirectMessage(&data); SendPartyResult(PARTY_OP_INVITE, memberName, ERR_PARTY_RESULT_OK); } @@ -414,7 +415,7 @@ void WorldSession::HandleGroupInviteResponseOpcode(WorldPacket& recvData) // report WorldPacket data(SMSG_GROUP_DECLINE, GetPlayer()->GetName().size()); data << GetPlayer()->GetName(); - leader->GetSession()->SendPacket(&data); + leader->SendDirectMessage(&data); } } diff --git a/src/server/game/Handlers/GuildFinderHandler.cpp b/src/server/game/Handlers/GuildFinderHandler.cpp index 03e42e30768..1735d375e25 100644 --- a/src/server/game/Handlers/GuildFinderHandler.cpp +++ b/src/server/game/Handlers/GuildFinderHandler.cpp @@ -16,11 +16,16 @@ */ #include "WorldSession.h" -#include "WorldPacket.h" -#include "Object.h" -#include "SharedDefines.h" +#include "AchievementMgr.h" +#include "Guild.h" #include "GuildFinderMgr.h" #include "GuildMgr.h" +#include "Log.h" +#include "Object.h" +#include "Player.h" +#include "SharedDefines.h" +#include "World.h" +#include "WorldPacket.h" void WorldSession::HandleGuildFinderAddRecruit(WorldPacket& recvPacket) { @@ -69,7 +74,7 @@ void WorldSession::HandleGuildFinderAddRecruit(WorldPacket& recvPacket) if (!(guildInterests & ALL_INTERESTS) || guildInterests > ALL_INTERESTS) return; - MembershipRequest request = MembershipRequest(GetPlayer()->GetGUID(), guildLowGuid, availability, classRoles, guildInterests, comment, time(NULL)); + MembershipRequest request = MembershipRequest(GetPlayer()->GetGUID(), guildLowGuid, availability, classRoles, guildInterests, comment, time(nullptr)); sGuildFinderMgr->AddMembershipRequest(guildLowGuid, request); } @@ -241,7 +246,7 @@ void WorldSession::HandleGuildFinderGetApplications(WorldPacket& /*recvPacket*/) bufferData.WriteString(guild->GetName()); bufferData << uint32(guildSettings.GetAvailability()); - bufferData << uint32(request.GetExpiryTime() - time(NULL)); // Time left to application expiry (seconds) + bufferData << uint32(request.GetExpiryTime() - time(nullptr)); // Time left to application expiry (seconds) bufferData.WriteByteSeq(guildGuid[0]); bufferData.WriteByteSeq(guildGuid[6]); @@ -253,7 +258,7 @@ void WorldSession::HandleGuildFinderGetApplications(WorldPacket& /*recvPacket*/) bufferData.WriteByteSeq(guildGuid[4]); bufferData.WriteByteSeq(guildGuid[1]); - bufferData << uint32(time(NULL) - request.GetSubmitTime()); // Time since application (seconds) + bufferData << uint32(time(nullptr) - request.GetSubmitTime()); // Time since application (seconds) bufferData << uint32(guildSettings.GetInterests()); } @@ -302,7 +307,7 @@ void WorldSession::HandleGuildFinderGetRecruits(WorldPacket& recvPacket) dataBuffer.WriteByteSeq(playerGuid[4]); - dataBuffer << int32(time(NULL) <= request.GetExpiryTime()); + dataBuffer << int32(time(nullptr) <= request.GetExpiryTime()); dataBuffer.WriteByteSeq(playerGuid[3]); dataBuffer.WriteByteSeq(playerGuid[0]); @@ -314,11 +319,11 @@ void WorldSession::HandleGuildFinderGetRecruits(WorldPacket& recvPacket) dataBuffer.WriteByteSeq(playerGuid[7]); dataBuffer.WriteByteSeq(playerGuid[2]); - dataBuffer << int32(time(NULL) - request.GetSubmitTime()); // Time in seconds since application submitted. + dataBuffer << int32(time(nullptr) - request.GetSubmitTime()); // Time in seconds since application submitted. dataBuffer << int32(request.GetAvailability()); dataBuffer << int32(request.GetClassRoles()); dataBuffer << int32(request.GetInterests()); - dataBuffer << int32(request.GetExpiryTime() - time(NULL)); // TIme in seconds until application expires. + dataBuffer << int32(request.GetExpiryTime() - time(nullptr)); // TIme in seconds until application expires. dataBuffer.WriteString(request.GetName()); dataBuffer.WriteString(request.GetComment()); @@ -330,7 +335,7 @@ void WorldSession::HandleGuildFinderGetRecruits(WorldPacket& recvPacket) data.FlushBits(); data.append(dataBuffer); - data << uint32(time(NULL)); // Unk time + data << uint32(time(nullptr)); // Unk time player->SendDirectMessage(&data); } diff --git a/src/server/game/Handlers/GuildHandler.cpp b/src/server/game/Handlers/GuildHandler.cpp index 09570641b1b..81fd05448b9 100644 --- a/src/server/game/Handlers/GuildHandler.cpp +++ b/src/server/game/Handlers/GuildHandler.cpp @@ -16,15 +16,19 @@ * with this program. If not, see . */ -#include "Common.h" -#include "WorldPacket.h" #include "WorldSession.h" -#include "World.h" -#include "ObjectMgr.h" +#include "AchievementMgr.h" +#include "Common.h" +#include "DatabaseEnv.h" +#include "Guild.h" #include "GuildMgr.h" #include "Log.h" -#include "Guild.h" +#include "ObjectMgr.h" +#include "Player.h" #include "QueryCallback.h" +#include "SpellAuraDefines.h" +#include "World.h" +#include "WorldPacket.h" void WorldSession::HandleGuildQueryOpcode(WorldPacket& recvPacket) { @@ -533,7 +537,7 @@ void WorldSession::HandleGuildBankSwapItems(WorldPacket& recvPacket) // Player <-> Bank // Allow to work with inventory only if (!Player::IsInventoryPos(playerBag, playerSlotId) && !(playerBag == NULL_BAG && playerSlotId == NULL_SLOT)) - GetPlayer()->SendEquipError(EQUIP_ERR_INTERNAL_BAG_ERROR, NULL); + GetPlayer()->SendEquipError(EQUIP_ERR_INTERNAL_BAG_ERROR, nullptr); else guild->SwapItemsWithInventory(GetPlayer(), toChar != 0, tabId, slotId, playerBag, playerSlotId, splitedAmount); } @@ -773,7 +777,7 @@ void WorldSession::HandleGuildRewardsQueryOpcode(WorldPacket& recvPacket) data << uint32(0); // Unused data << uint32(rewards[i].AchievementId); } - data << uint32(time(NULL)); + data << uint32(time(nullptr)); SendPacket(&data); } } @@ -1031,7 +1035,7 @@ void WorldSession::HandleGuildChallengeRequest(WorldPacket& recvPacket) if (Guild::ChallengesMgr* challengesMgr = pGuild->GetChallengesMgr()) { // First check if it's time to reset the challenges. - time_t thisTime = time(NULL); + time_t thisTime = time(nullptr); if (pGuild->GetChallengesMgr()->CompletedFirstChallenge(pGuild->GetId()) && pGuild->GetChallengesMgr()->GetFirstCompletedChallengeTime(pGuild->GetId()) + WEEK <= thisTime) pGuild->GetChallengesMgr()->ResetWeeklyChallenges(); diff --git a/src/server/game/Handlers/ItemHandler.cpp b/src/server/game/Handlers/ItemHandler.cpp index fd1ed97765c..1a6beb81bb7 100644 --- a/src/server/game/Handlers/ItemHandler.cpp +++ b/src/server/game/Handlers/ItemHandler.cpp @@ -16,17 +16,19 @@ * with this program. If not, see . */ -#include "Common.h" -#include "WorldPacket.h" #include "WorldSession.h" -#include "Opcodes.h" +#include "Common.h" +#include "Creature.h" +#include "DatabaseEnv.h" +#include "DB2Stores.h" +#include "DBCStores.h" +#include "Item.h" #include "Log.h" #include "ObjectMgr.h" +#include "Opcodes.h" #include "Player.h" -#include "Item.h" #include "SpellInfo.h" -#include "DB2Stores.h" -#include +#include "WorldPacket.h" void WorldSession::HandleSplitItemOpcode(WorldPacket& recvData) { @@ -48,13 +50,13 @@ void WorldSession::HandleSplitItemOpcode(WorldPacket& recvData) if (!_player->IsValidPos(srcbag, srcslot, true)) { - _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } if (!_player->IsValidPos(dstbag, dstslot, false)) // can be autostore pos { - _player->SendEquipError(EQUIP_ERR_WRONG_SLOT, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_WRONG_SLOT, nullptr, nullptr); return; } @@ -75,13 +77,13 @@ void WorldSession::HandleSwapInvItemOpcode(WorldPacket& recvData) if (!_player->IsValidPos(INVENTORY_SLOT_BAG_0, srcslot, true)) { - _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } if (!_player->IsValidPos(INVENTORY_SLOT_BAG_0, dstslot, true)) { - _player->SendEquipError(EQUIP_ERR_WRONG_SLOT, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_WRONG_SLOT, nullptr, nullptr); return; } @@ -139,13 +141,13 @@ void WorldSession::HandleSwapItem(WorldPacket& recvData) if (!_player->IsValidPos(srcbag, srcslot, true)) { - _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } if (!_player->IsValidPos(dstbag, dstslot, true)) { - _player->SendEquipError(EQUIP_ERR_WRONG_SLOT, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_WRONG_SLOT, nullptr, nullptr); return; } @@ -180,7 +182,7 @@ void WorldSession::HandleAutoEquipItemOpcode(WorldPacket& recvData) InventoryResult msg = _player->CanEquipItem(NULL_SLOT, dest, pSrcItem, !pSrcItem->IsBag()); if (msg != EQUIP_ERR_OK) { - _player->SendEquipError(msg, pSrcItem, NULL); + _player->SendEquipError(msg, pSrcItem, nullptr); return; } @@ -203,7 +205,7 @@ void WorldSession::HandleAutoEquipItemOpcode(WorldPacket& recvData) msg = _player->CanUnequipItem(dest, !pSrcItem->IsBag()); if (msg != EQUIP_ERR_OK) { - _player->SendEquipError(msg, pDstItem, NULL); + _player->SendEquipError(msg, pDstItem, nullptr); return; } @@ -279,7 +281,7 @@ void WorldSession::HandleDestroyItemOpcode(WorldPacket& recvData) InventoryResult msg = _player->CanUnequipItem(pos, false); if (msg != EQUIP_ERR_OK) { - _player->SendEquipError(msg, _player->GetItemByPos(pos), NULL); + _player->SendEquipError(msg, _player->GetItemByPos(pos), nullptr); return; } } @@ -287,13 +289,13 @@ void WorldSession::HandleDestroyItemOpcode(WorldPacket& recvData) Item* pItem = _player->GetItemByPos(bag, slot); if (!pItem) { - _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } if (pItem->GetTemplate()->Flags & ITEM_FLAG_NO_USER_DESTROY) { - _player->SendEquipError(EQUIP_ERR_DROP_BOUND_ITEM, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_DROP_BOUND_ITEM, nullptr, nullptr); return; } @@ -327,13 +329,13 @@ void WorldSession::HandleReadItem(WorldPacket& recvData) { data.Initialize(SMSG_READ_ITEM_FAILED, 8); TC_LOG_INFO("network", "STORAGE: Unable to read item"); - _player->SendEquipError(msg, pItem, NULL); + _player->SendEquipError(msg, pItem, nullptr); } data << pItem->GetGUID(); SendPacket(&data); } else - _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); } void WorldSession::HandleSellItemOpcode(WorldPacket& recvData) @@ -351,7 +353,7 @@ void WorldSession::HandleSellItemOpcode(WorldPacket& recvData) if (!creature) { TC_LOG_DEBUG("network", "WORLD: HandleSellItemOpcode - %s not found or you can not interact with him.", vendorguid.ToString().c_str()); - _player->SendSellError(SELL_ERR_CANT_FIND_VENDOR, NULL, itemguid); + _player->SendSellError(SELL_ERR_CANT_FIND_VENDOR, nullptr, itemguid); return; } @@ -431,7 +433,7 @@ void WorldSession::HandleSellItemOpcode(WorldPacket& recvData) { _player->ItemRemovedQuestCheck(pItem->GetEntry(), pItem->GetCount()); _player->RemoveItem(pItem->GetBagSlot(), pItem->GetSlot(), true); - pItem->RemoveFromUpdateQueueOf(_player); + RemoveItemFromUpdateQueueOf(pItem, _player); _player->AddItemToBuyBackSlot(pItem); } @@ -460,7 +462,7 @@ void WorldSession::HandleBuybackItem(WorldPacket& recvData) if (!creature) { TC_LOG_DEBUG("network", "WORLD: HandleBuybackItem - Unit (%s) not found or you can not interact with him.", vendorguid.ToString().c_str()); - _player->SendSellError(SELL_ERR_CANT_FIND_VENDOR, NULL, ObjectGuid::Empty); + _player->SendSellError(SELL_ERR_CANT_FIND_VENDOR, nullptr, ObjectGuid::Empty); return; } @@ -489,7 +491,7 @@ void WorldSession::HandleBuybackItem(WorldPacket& recvData) _player->StoreItem(dest, pItem, true); } else - _player->SendEquipError(msg, pItem, NULL); + _player->SendEquipError(msg, pItem, nullptr); return; } else @@ -512,7 +514,7 @@ void WorldSession::HandleBuyItemInSlotOpcode(WorldPacket& recvData) return; // cheating uint8 bag = NULL_BAG; // init for case invalid bagGUID - Item* bagItem = NULL; + Item* bagItem = nullptr; // find bag slot by bag guid if (bagguid == _player->GetGUID()) bag = INVENTORY_SLOT_BAG_0; @@ -595,7 +597,7 @@ void WorldSession::SendListInventory(ObjectGuid vendorGuid) if (!vendor) { TC_LOG_DEBUG("network", "WORLD: SendListInventory - %s not found or you can not interact with him.", vendorGuid.ToString().c_str()); - _player->SendSellError(SELL_ERR_CANT_FIND_VENDOR, NULL, ObjectGuid::Empty); + _player->SendSellError(SELL_ERR_CANT_FIND_VENDOR, nullptr, ObjectGuid::Empty); return; } @@ -772,7 +774,7 @@ void WorldSession::HandleAutoStoreBagItemOpcode(WorldPacket& recvData) if (!_player->IsValidPos(dstbag, NULL_SLOT, false)) // can be autostore pos { - _player->SendEquipError(EQUIP_ERR_WRONG_SLOT, NULL, NULL); + _player->SendEquipError(EQUIP_ERR_WRONG_SLOT, nullptr, nullptr); return; } @@ -784,7 +786,7 @@ void WorldSession::HandleAutoStoreBagItemOpcode(WorldPacket& recvData) InventoryResult msg = _player->CanUnequipItem(src, !_player->IsBagPos (src)); if (msg != EQUIP_ERR_OK) { - _player->SendEquipError(msg, pItem, NULL); + _player->SendEquipError(msg, pItem, nullptr); return; } } @@ -793,7 +795,7 @@ void WorldSession::HandleAutoStoreBagItemOpcode(WorldPacket& recvData) InventoryResult msg = _player->CanStoreItem(dstbag, NULL_SLOT, dest, pItem, false); if (msg != EQUIP_ERR_OK) { - _player->SendEquipError(msg, pItem, NULL); + _player->SendEquipError(msg, pItem, nullptr); return; } @@ -801,7 +803,7 @@ void WorldSession::HandleAutoStoreBagItemOpcode(WorldPacket& recvData) if (dest.size() == 1 && dest[0].pos == src) { // just remove grey item state - _player->SendEquipError(EQUIP_ERR_INTERNAL_BAG_ERROR, pItem, NULL); + _player->SendEquipError(EQUIP_ERR_INTERNAL_BAG_ERROR, pItem, nullptr); return; } @@ -881,13 +883,13 @@ void WorldSession::HandleAutoBankItemOpcode(WorldPacket& recvPacket) InventoryResult msg = _player->CanBankItem(NULL_BAG, NULL_SLOT, dest, pItem, false); if (msg != EQUIP_ERR_OK) { - _player->SendEquipError(msg, pItem, NULL); + _player->SendEquipError(msg, pItem, nullptr); return; } if (dest.size() == 1 && dest[0].pos == pItem->GetPos()) { - _player->SendEquipError(EQUIP_ERR_CANT_SWAP, pItem, NULL); + _player->SendEquipError(EQUIP_ERR_CANT_SWAP, pItem, nullptr); return; } @@ -920,7 +922,7 @@ void WorldSession::HandleAutoStoreBankItemOpcode(WorldPacket& recvPacket) InventoryResult msg = _player->CanStoreItem(NULL_BAG, NULL_SLOT, dest, pItem, false); if (msg != EQUIP_ERR_OK) { - _player->SendEquipError(msg, pItem, NULL); + _player->SendEquipError(msg, pItem, nullptr); return; } @@ -934,7 +936,7 @@ void WorldSession::HandleAutoStoreBankItemOpcode(WorldPacket& recvPacket) InventoryResult msg = _player->CanBankItem(NULL_BAG, NULL_SLOT, dest, pItem, false); if (msg != EQUIP_ERR_OK) { - _player->SendEquipError(msg, pItem, NULL); + _player->SendEquipError(msg, pItem, nullptr); return; } @@ -978,13 +980,13 @@ void WorldSession::HandleWrapItemOpcode(WorldPacket& recvData) Item* gift = _player->GetItemByPos(gift_bag, gift_slot); if (!gift) { - _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, gift, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, gift, nullptr); return; } if (!(gift->GetTemplate()->Flags & ITEM_FLAG_IS_WRAPPER)) // cheating: non-wrapper wrapper { - _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, gift, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, gift, nullptr); return; } @@ -992,50 +994,50 @@ void WorldSession::HandleWrapItemOpcode(WorldPacket& recvData) if (!item) { - _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, item, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, item, nullptr); return; } if (item == gift) // not possable with pacjket from real client { - _player->SendEquipError(EQUIP_ERR_CANT_WRAP_WRAPPED, item, NULL); + _player->SendEquipError(EQUIP_ERR_CANT_WRAP_WRAPPED, item, nullptr); return; } if (item->IsEquipped()) { - _player->SendEquipError(EQUIP_ERR_CANT_WRAP_EQUIPPED, item, NULL); + _player->SendEquipError(EQUIP_ERR_CANT_WRAP_EQUIPPED, item, nullptr); return; } if (!item->GetGuidValue(ITEM_FIELD_GIFTCREATOR).IsEmpty()) // HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED); { - _player->SendEquipError(EQUIP_ERR_CANT_WRAP_WRAPPED, item, NULL); + _player->SendEquipError(EQUIP_ERR_CANT_WRAP_WRAPPED, item, nullptr); return; } if (item->IsBag()) { - _player->SendEquipError(EQUIP_ERR_CANT_WRAP_BAGS, item, NULL); + _player->SendEquipError(EQUIP_ERR_CANT_WRAP_BAGS, item, nullptr); return; } if (item->IsSoulBound()) { - _player->SendEquipError(EQUIP_ERR_CANT_WRAP_BOUND, item, NULL); + _player->SendEquipError(EQUIP_ERR_CANT_WRAP_BOUND, item, nullptr); return; } if (item->GetMaxStackCount() != 1) { - _player->SendEquipError(EQUIP_ERR_CANT_WRAP_STACKABLE, item, NULL); + _player->SendEquipError(EQUIP_ERR_CANT_WRAP_STACKABLE, item, nullptr); return; } // maybe not correct check (it is better than nothing) if (item->GetTemplate()->MaxCount > 0) { - _player->SendEquipError(EQUIP_ERR_CANT_WRAP_UNIQUE, item, NULL); + _player->SendEquipError(EQUIP_ERR_CANT_WRAP_UNIQUE, item, nullptr); return; } @@ -1066,7 +1068,7 @@ void WorldSession::HandleWrapItemOpcode(WorldPacket& recvData) if (item->GetState() == ITEM_NEW) // save new item, to have alway for `character_gifts` record in `item_instance` { // after save it will be impossible to remove the item from the queue - item->RemoveFromUpdateQueueOf(_player); + RemoveItemFromUpdateQueueOf(item, _player); item->SaveToDB(trans); // item gave inventory record unchanged and can be save standalone } CharacterDatabase.CommitTransaction(trans); @@ -1107,11 +1109,11 @@ void WorldSession::HandleSocketOpcode(WorldPacket& recvData) Item* Gems[MAX_GEM_SOCKETS]; for (int i = 0; i < MAX_GEM_SOCKETS; ++i) - Gems[i] = gem_guids[i] ? _player->GetItemByGuid(gem_guids[i]) : NULL; + Gems[i] = gem_guids[i] ? _player->GetItemByGuid(gem_guids[i]) : nullptr; GemPropertiesEntry const* GemProps[MAX_GEM_SOCKETS]; for (int i = 0; i < MAX_GEM_SOCKETS; ++i) //get geminfo from dbc storage - GemProps[i] = (Gems[i]) ? sGemPropertiesStore.LookupEntry(Gems[i]->GetTemplate()->GemProperties) : NULL; + GemProps[i] = (Gems[i]) ? sGemPropertiesStore.LookupEntry(Gems[i]->GetTemplate()->GemProperties) : nullptr; // Find first prismatic socket int32 firstPrismatic = 0; @@ -1180,7 +1182,7 @@ void WorldSession::HandleSocketOpcode(WorldPacket& recvData) { if (iGemProto->ItemId == Gems[j]->GetEntry()) { - _player->SendEquipError(EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED, itemTarget, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED, itemTarget, nullptr); return; } } @@ -1190,7 +1192,7 @@ void WorldSession::HandleSocketOpcode(WorldPacket& recvData) { if (iGemProto->ItemId == enchantEntry->GemID) { - _player->SendEquipError(EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED, itemTarget, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED, itemTarget, nullptr); return; } } @@ -1225,7 +1227,7 @@ void WorldSession::HandleSocketOpcode(WorldPacket& recvData) if (limit_newcount > 0 && uint32(limit_newcount) > limitEntry->maxCount) { - _player->SendEquipError(EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED, itemTarget, NULL); + _player->SendEquipError(EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED, itemTarget, nullptr); return; } } @@ -1236,7 +1238,7 @@ void WorldSession::HandleSocketOpcode(WorldPacket& recvData) { if (InventoryResult res = _player->CanEquipUniqueItem(Gems[i], slot, std::max(limit_newcount, 0))) { - _player->SendEquipError(res, itemTarget, NULL); + _player->SendEquipError(res, itemTarget, nullptr); return; } } @@ -1450,8 +1452,8 @@ void WorldSession::HandleTransmogrifyItems(WorldPacket& recvData) } int64 cost = 0; - std::vector transmogrifier(count, NULL); - std::vector transmogrified(count, NULL); + std::vector transmogrifier(count, nullptr); + std::vector transmogrified(count, nullptr); for (uint8 i = 0; i < count; ++i) { @@ -1471,7 +1473,7 @@ void WorldSession::HandleTransmogrifyItems(WorldPacket& recvData) } // if not resetting look - Item* itemTransmogrifier = NULL; + Item* itemTransmogrifier = nullptr; if (newEntries[i]) { // entry of the transmogrifier item diff --git a/src/server/game/Handlers/LFGHandler.cpp b/src/server/game/Handlers/LFGHandler.cpp index 1349c1aeb18..227cc100fbe 100644 --- a/src/server/game/Handlers/LFGHandler.cpp +++ b/src/server/game/Handlers/LFGHandler.cpp @@ -16,10 +16,13 @@ */ #include "LFGMgr.h" -#include "ObjectMgr.h" #include "Group.h" -#include "Player.h" +#include "Log.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Opcodes.h" +#include "Player.h" +#include "World.h" #include "WorldPacket.h" #include "WorldSession.h" @@ -311,7 +314,7 @@ void WorldSession::SendLfgPlayerLockInfo() { data << uint32(*it); // Dungeon Entry (id + type) lfg::LfgReward const* reward = sLFGMgr->GetRandomDungeonReward(*it, level); - Quest const* quest = NULL; + Quest const* quest = nullptr; bool done = false; if (reward) { @@ -370,7 +373,7 @@ void WorldSession::SendLfgPartyLockInfo() // Get the locked dungeons of the other party members lfg::LfgLockPartyMap lockMap; - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* plrg = itr->GetSource(); if (!plrg) @@ -581,7 +584,7 @@ void WorldSession::SendLfgJoinResult(lfg::LfgJoinResultData const& joinData) data << uint8(joinData.result); // Check Result data << uint32(queueId); // Queue Id data << uint8(joinData.state); // Check Value - data << uint32(time(NULL)); // Join date + data << uint32(time(nullptr)); // Join date data.WriteBit(guid[2]); data.WriteBit(guid[7]); data.WriteBit(guid[3]); @@ -709,7 +712,7 @@ void WorldSession::SendLfgBootProposalUpdate(lfg::LfgPlayerBoot const& boot) lfg::LfgAnswer playerVote = boot.votes.find(guid)->second; uint8 votesNum = 0; uint8 agreeNum = 0; - uint32 secsleft = uint8((boot.cancelTime - time(NULL)) / 1000); + uint32 secsleft = uint8((boot.cancelTime - time(nullptr)) / 1000); for (lfg::LfgAnswerContainer::const_iterator it = boot.votes.begin(); it != boot.votes.end(); ++it) { if (it->second != lfg::LFG_ANSWER_PENDING) diff --git a/src/server/game/Handlers/LootHandler.cpp b/src/server/game/Handlers/LootHandler.cpp index b2ba6877456..4895452223f 100644 --- a/src/server/game/Handlers/LootHandler.cpp +++ b/src/server/game/Handlers/LootHandler.cpp @@ -16,26 +16,30 @@ * with this program. If not, see . */ +#include "WorldSession.h" #include "Common.h" -#include "Log.h" #include "Corpse.h" #include "Creature.h" #include "GameObject.h" #include "Group.h" +#include "Guild.h" #include "GuildMgr.h" +#include "Item.h" +#include "Log.h" +#include "LootItemStorage.h" #include "LootMgr.h" -#include "ObjectAccessor.h" +#include "Map.h" #include "Object.h" +#include "ObjectAccessor.h" #include "Player.h" #include "WorldPacket.h" -#include "WorldSession.h" void WorldSession::HandleAutostoreLootItemOpcode(WorldPacket& recvData) { TC_LOG_DEBUG("network", "WORLD: CMSG_AUTOSTORE_LOOT_ITEM"); Player* player = GetPlayer(); ObjectGuid lguid = player->GetLootGUID(); - Loot* loot = NULL; + Loot* loot = nullptr; uint8 lootSlot = 0; recvData >> lootSlot; @@ -148,7 +152,7 @@ void WorldSession::HandleLootMoneyOpcode(WorldPacket& /*recvData*/) if (!guid) return; - Loot* loot = NULL; + Loot* loot = nullptr; bool shareMoney = true; switch (guid.GetHigh()) @@ -211,7 +215,7 @@ void WorldSession::HandleLootMoneyOpcode(WorldPacket& /*recvData*/) Group* group = player->GetGroup(); std::vector playersNear; - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* member = itr->GetSource(); if (!member) @@ -235,7 +239,7 @@ void WorldSession::HandleLootMoneyOpcode(WorldPacket& /*recvData*/) WorldPacket data(SMSG_LOOT_MONEY_NOTIFY, 4 + 1); data << uint32(goldPerPlayer); data << uint8(playersNear.size() <= 1); // Controls the text displayed in chat. 0 is "Your share is..." and 1 is "You loot..." - (*i)->GetSession()->SendPacket(&data); + (*i)->SendDirectMessage(&data); } } else @@ -257,7 +261,7 @@ void WorldSession::HandleLootMoneyOpcode(WorldPacket& /*recvData*/) // Delete the money loot record from the DB if (loot->containerID > 0) - loot->DeleteLootMoneyFromContainerItemDB(); + sLootItemStorage->RemoveStoredMoneyForContainer(loot->containerID); // Delete container if empty if (loot->isLooted() && guid.IsItem()) @@ -421,7 +425,7 @@ void WorldSession::DoLootRelease(ObjectGuid lguid) loot->roundRobinPlayer.Clear(); if (Group* group = player->GetGroup()) - group->SendLooter(creature, NULL); + group->SendLooter(creature, nullptr); } // force dynflag update to update looter and lootable info creature->ForceValuesUpdateAtIndex(UNIT_DYNAMIC_FLAGS); @@ -468,7 +472,7 @@ void WorldSession::HandleLootMasterGiveOpcode(WorldPacket& recvData) return; } - Loot* loot = NULL; + Loot* loot = nullptr; if (GetPlayer()->GetLootGUID().IsCreatureOrVehicle()) { @@ -512,12 +516,12 @@ void WorldSession::HandleLootMasterGiveOpcode(WorldPacket& recvData) else _player->SendLootError(lootguid, LOOT_ERROR_MASTER_OTHER); - target->SendEquipError(msg, NULL, NULL, item.itemid); + target->SendEquipError(msg, nullptr, nullptr, item.itemid); return; } // list of players allowed to receive this item in trade - AllowedLooterSet looters = item.GetAllowedLooters(); + GuidSet looters = item.GetAllowedLooters(); // now move item from loot to target inventory Item* newitem = target->StoreNewItem(dest, item.itemid, true, item.randomPropertyId, looters); diff --git a/src/server/game/Handlers/MailHandler.cpp b/src/server/game/Handlers/MailHandler.cpp index ac2154396bb..3b70fe3a461 100644 --- a/src/server/game/Handlers/MailHandler.cpp +++ b/src/server/game/Handlers/MailHandler.cpp @@ -15,22 +15,24 @@ * with this program. If not, see . */ -#include "DatabaseEnv.h" -#include "Mail.h" -#include "WorldPacket.h" #include "WorldSession.h" -#include "Opcodes.h" -#include "Log.h" -#include "World.h" -#include "ObjectMgr.h" -#include "Player.h" -#include "Language.h" -#include "DBCStores.h" -#include "Item.h" #include "AccountMgr.h" #include "BattlenetAccountMgr.h" -#include "GuildMgr.h" #include "CharacterCache.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "Guild.h" +#include "GuildMgr.h" +#include "Item.h" +#include "Language.h" +#include "Log.h" +#include "Mail.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Opcodes.h" +#include "Player.h" +#include "World.h" +#include "WorldPacket.h" bool WorldSession::CanOpenMailBox(ObjectGuid guid) { @@ -458,7 +460,7 @@ void WorldSession::HandleMailReturnToSender(WorldPacket& recvData) Player* player = _player; Mail* m = player->GetMail(mailId); - if (!m || m->state == MAIL_STATE_DELETED || m->deliver_time > time(NULL)) + if (!m || m->state == MAIL_STATE_DELETED || m->deliver_time > time(nullptr)) { player->SendMailResult(mailId, MAIL_RETURNED_TO_SENDER, MAIL_ERR_INTERNAL_ERROR); return; @@ -517,7 +519,7 @@ void WorldSession::HandleMailTakeItem(WorldPacket& recvData) Player* player = _player; Mail* m = player->GetMail(mailId); - if (!m || m->state == MAIL_STATE_DELETED || m->deliver_time > time(NULL)) + if (!m || m->state == MAIL_STATE_DELETED || m->deliver_time > time(nullptr)) { player->SendMailResult(mailId, MAIL_ITEM_TAKEN, MAIL_ERR_INTERNAL_ERROR); return; @@ -621,7 +623,7 @@ void WorldSession::HandleMailTakeMoney(WorldPacket& recvData) Player* player = _player; Mail* m = player->GetMail(mailId); - if ((!m || m->state == MAIL_STATE_DELETED || m->deliver_time > time(NULL)) || + if ((!m || m->state == MAIL_STATE_DELETED || m->deliver_time > time(nullptr)) || (money > 0 && m->money != money)) { player->SendMailResult(mailId, MAIL_MONEY_TAKEN, MAIL_ERR_INTERNAL_ERROR); @@ -671,7 +673,7 @@ void WorldSession::HandleGetMailList(WorldPacket& recvData) WorldPacket data(SMSG_MAIL_LIST_RESULT, 200); // guess size data << uint32(0); // real mail's count data << uint8(0); // mail's count - time_t cur_time = time(NULL); + time_t cur_time = time(nullptr); for (PlayerMails::iterator itr = player->GetMailBegin(); itr != player->GetMailEnd(); ++itr) { @@ -718,7 +720,7 @@ void WorldSession::HandleGetMailList(WorldPacket& recvData) data << uint32((*itr)->stationery); // stationery (Stationery.dbc) data << uint64((*itr)->money); // Gold data << uint32((*itr)->checked); // flags - data << float(float((*itr)->expire_time-time(NULL))/DAY); // Time + data << float(float((*itr)->expire_time-time(nullptr))/DAY); // Time data << uint32((*itr)->mailTemplateId); // mail template (MailTemplate.dbc) data << (*itr)->subject; // Subject string - once 00, when mail type = 3, max 256 data << (*itr)->body; // message? max 8000 @@ -783,7 +785,7 @@ void WorldSession::HandleMailCreateTextItem(WorldPacket& recvData) Player* player = _player; Mail* m = player->GetMail(mailId); - if (!m || (m->body.empty() && !m->mailTemplateId) || m->state == MAIL_STATE_DELETED || m->deliver_time > time(NULL) || (m->checked & MAIL_CHECK_MASK_COPIED)) + if (!m || (m->body.empty() && !m->mailTemplateId) || m->state == MAIL_STATE_DELETED || m->deliver_time > time(nullptr) || (m->checked & MAIL_CHECK_MASK_COPIED)) { player->SendMailResult(mailId, MAIL_MADE_PERMANENT, MAIL_ERR_INTERNAL_ERROR); return; @@ -845,7 +847,7 @@ void WorldSession::HandleQueryNextMailTime(WorldPacket& /*recvData*/) data << uint32(0); // count uint32 count = 0; - time_t now = time(NULL); + time_t now = time(nullptr); std::set sentSenders; for (PlayerMails::iterator itr = _player->GetMailBegin(); itr != _player->GetMailEnd(); ++itr) { diff --git a/src/server/game/Handlers/MiscHandler.cpp b/src/server/game/Handlers/MiscHandler.cpp index 7fda4c868bc..7e1f96b1f8f 100644 --- a/src/server/game/Handlers/MiscHandler.cpp +++ b/src/server/game/Handlers/MiscHandler.cpp @@ -16,38 +16,45 @@ * with this program. If not, see . */ -#include "Common.h" -#include "Language.h" -#include "DatabaseEnv.h" -#include "WorldPacket.h" -#include "Opcodes.h" -#include "Log.h" -#include "Player.h" -#include "GameTime.h" -#include "GossipDef.h" -#include "World.h" -#include "ObjectMgr.h" -#include "GuildMgr.h" #include "WorldSession.h" -#include "Chat.h" -#include "zlib.h" -#include "ObjectAccessor.h" -#include "Object.h" -#include "Battleground.h" -#include "OutdoorPvP.h" #include "AccountMgr.h" -#include "DBCEnums.h" -#include "ScriptMgr.h" -#include "MapManager.h" -#include "GameObjectAI.h" -#include "Group.h" -#include "Spell.h" -#include "BattlegroundMgr.h" +#include "AchievementMgr.h" #include "Battlefield.h" #include "BattlefieldMgr.h" +#include "Battleground.h" +#include "BattlegroundMgr.h" +#include "Chat.h" +#include "CinematicMgr.h" +#include "Common.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "DatabaseEnv.h" #include "DB2Stores.h" -#include "WhoListStorage.h" +#include "DBCEnums.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "GameTime.h" +#include "GossipDef.h" +#include "Group.h" +#include "Guild.h" +#include "GuildMgr.h" #include "InstanceScript.h" +#include "Language.h" +#include "Log.h" +#include "MapManager.h" +#include "Object.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Opcodes.h" +#include "OutdoorPvP.h" +#include "Player.h" +#include "ScriptMgr.h" +#include "Spell.h" +#include "SpellInfo.h" +#include "WhoListStorage.h" +#include "World.h" +#include "WorldPacket.h" +#include void WorldSession::HandleRepopRequestOpcode(WorldPacket& recvData) { @@ -74,7 +81,7 @@ void WorldSession::HandleRepopRequestOpcode(WorldPacket& recvData) } //this is spirit release confirm? - GetPlayer()->RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true); + GetPlayer()->RemovePet(nullptr, PET_SAVE_NOT_IN_SLOT, true); GetPlayer()->BuildPlayerRepop(); GetPlayer()->RepopAtGraveyard(); } @@ -103,8 +110,8 @@ void WorldSession::HandleGossipSelectOptionOpcode(WorldPacket& recvData) if (_player->PlayerTalkClass->GetGossipMenu().GetSenderGUID() != guid) return; - Creature* unit = NULL; - GameObject* go = NULL; + Creature* unit = nullptr; + GameObject* go = nullptr; if (guid.IsCreatureOrVehicle()) { unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_GOSSIP); @@ -394,7 +401,7 @@ void WorldSession::HandleLogoutRequestOpcode(WorldPacket& /*recvData*/) GetPlayer()->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED); } - LogoutRequest(time(NULL)); + LogoutRequest(time(nullptr)); } void WorldSession::HandlePlayerLogoutOpcode(WorldPacket& /*recvData*/) @@ -455,7 +462,7 @@ void WorldSession::HandleTogglePvP(WorldPacket& recvData) else { if (!GetPlayer()->pvpInfo.IsHostile && GetPlayer()->IsPvP()) - GetPlayer()->pvpInfo.EndTimer = time(NULL); // start toggle-off + GetPlayer()->pvpInfo.EndTimer = time(nullptr); // start toggle-off } //if (OutdoorPvP* pvp = _player->GetOutdoorPvP()) @@ -488,7 +495,7 @@ void WorldSession::HandleRequestCemeteryList(WorldPacket& /*recvPacket*/) uint32 team = _player->GetTeam(); std::vector graveyardIds; - auto range = sObjectMgr->GraveYardStore.equal_range(zoneId); + auto range = sObjectMgr->GraveyardStore.equal_range(zoneId); for (auto it = range.first; it != range.second && graveyardIds.size() < 16; ++it) // client max { @@ -580,7 +587,7 @@ void WorldSession::HandleReclaimCorpseOpcode(WorldPacket& recvData) return; // prevent resurrect before 30-sec delay after body release not finished - if (time_t(corpse->GetGhostTime() + _player->GetCorpseReclaimDelay(corpse->GetType() == CORPSE_RESURRECTABLE_PVP)) > time_t(time(NULL))) + if (time_t(corpse->GetGhostTime() + _player->GetCorpseReclaimDelay(corpse->GetType() == CORPSE_RESURRECTABLE_PVP)) > time_t(time(nullptr))) return; if (!corpse->IsWithinDistInMap(_player, CORPSE_RECLAIM_RADIUS, true)) @@ -631,7 +638,7 @@ void WorldSession::HandleResurrectResponseOpcode(WorldPacket& recvData) GetPlayer()->ResurrectUsingRequestData(); } -void WorldSession::SendAreaTriggerMessage(const char* Text, ...) +void WorldSession::SendAreaTriggerMessage(char const* Text, ...) { va_list ap; char szStr [1024]; @@ -744,7 +751,7 @@ void WorldSession::HandleAreaTriggerOpcode(WorldPacket& recvData) case Map::CANNOT_ENTER_CORPSE_IN_DIFFERENT_INSTANCE: { WorldPacket data(SMSG_CORPSE_NOT_IN_INSTANCE); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); TC_LOG_DEBUG("maps", "MAP: Player '%s' does not have a corpse in instance map %d and cannot enter", player->GetName().c_str(), at->target_mapId); break; } @@ -1420,7 +1427,7 @@ void WorldSession::HandleSetDungeonDifficultyOpcode(WorldPacket& recvData) { if (group->IsLeader(_player->GetGUID())) { - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* groupGuy = itr->GetSource(); if (!groupGuy) @@ -1478,7 +1485,7 @@ void WorldSession::HandleSetRaidDifficultyOpcode(WorldPacket& recvData) { if (group->IsLeader(_player->GetGUID())) { - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* groupGuy = itr->GetSource(); if (!groupGuy) @@ -1591,7 +1598,7 @@ void WorldSession::HandleWorldStateUITimerUpdate(WorldPacket& /*recvData*/) TC_LOG_DEBUG("network", "WORLD: CMSG_WORLD_STATE_UI_TIMER_UPDATE"); WorldPacket data(SMSG_WORLD_STATE_UI_TIMER_UPDATE, 4); - data << uint32(time(NULL)); + data << uint32(time(nullptr)); SendPacket(&data); } @@ -1736,7 +1743,7 @@ void WorldSession::HandleRequestHotfix(WorldPacket& recvPacket) WorldPacket data(SMSG_DB_REPLY, 4 * 4); data << -int32(entry); data << uint32(store->GetHash()); - data << uint32(time(NULL)); + data << uint32(time(nullptr)); data << uint32(0); SendPacket(&data); continue; @@ -1775,7 +1782,7 @@ void WorldSession::HandleUpdateMissileTrajectory(WorldPacket& recvPacket) recvPacket >> moveStop; Unit* caster = ObjectAccessor::GetUnit(*_player, guid); - Spell* spell = caster ? caster->GetCurrentSpell(CURRENT_GENERIC_SPELL) : NULL; + Spell* spell = caster ? caster->GetCurrentSpell(CURRENT_GENERIC_SPELL) : nullptr; if (!spell || spell->m_spellInfo->Id != spellId || !spell->m_targets.HasDst() || !spell->m_targets.HasSrc()) { recvPacket.rfinish(); @@ -1858,12 +1865,12 @@ void WorldSession::HandleSaveCUFProfiles(WorldPacket& recvPacket) return; } - CUFProfile* profiles[MAX_CUF_PROFILES]; + std::unique_ptr profiles[MAX_CUF_PROFILES]; uint8 strlens[MAX_CUF_PROFILES]; for (uint8 i = 0; i < count; ++i) { - profiles[i] = new CUFProfile; + profiles[i] = Trinity::make_unique(); profiles[i]->BoolOptions.set(CUF_AUTO_ACTIVATE_SPEC_2 , recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_AUTO_ACTIVATE_10_PLAYERS , recvPacket.ReadBit()); profiles[i]->BoolOptions.set(CUF_UNK_157 , recvPacket.ReadBit()); @@ -1894,23 +1901,23 @@ void WorldSession::HandleSaveCUFProfiles(WorldPacket& recvPacket) for (uint8 i = 0; i < count; ++i) { - recvPacket >> profiles[i]->Unk146; + recvPacket >> profiles[i]->TopPoint; profiles[i]->ProfileName = recvPacket.ReadString(strlens[i]); - recvPacket >> profiles[i]->Unk152; + recvPacket >> profiles[i]->BottomOffset; recvPacket >> profiles[i]->FrameHeight; recvPacket >> profiles[i]->FrameWidth; - recvPacket >> profiles[i]->Unk150; + recvPacket >> profiles[i]->TopOffset; recvPacket >> profiles[i]->HealthText; - recvPacket >> profiles[i]->Unk147; + recvPacket >> profiles[i]->BottomPoint; recvPacket >> profiles[i]->SortBy; - recvPacket >> profiles[i]->Unk154; - recvPacket >> profiles[i]->Unk148; + recvPacket >> profiles[i]->LeftOffset; + recvPacket >> profiles[i]->LeftPoint; - GetPlayer()->SaveCUFProfile(i, profiles[i]); + GetPlayer()->SaveCUFProfile(i, std::move(profiles[i])); } for (uint8 i = count; i < MAX_CUF_PROFILES; ++i) - GetPlayer()->SaveCUFProfile(i, NULL); + GetPlayer()->SaveCUFProfile(i, nullptr); } void WorldSession::SendLoadCUFProfiles() @@ -1925,7 +1932,7 @@ void WorldSession::SendLoadCUFProfiles() data.WriteBits(count, 20); for (uint8 i = 0; i < MAX_CUF_PROFILES; ++i) { - CUFProfile* profile = player->GetCUFProfile(i); + CUFProfile const* profile = player->GetCUFProfile(i); if (!profile) continue; @@ -1956,16 +1963,16 @@ void WorldSession::SendLoadCUFProfiles() data.WriteBit(profile->BoolOptions[CUF_DISPLAY_PETS]); data.WriteBit(profile->BoolOptions[CUF_AUTO_ACTIVATE_PVP]); - byteBuffer << uint16(profile->Unk154); + byteBuffer << uint16(profile->LeftOffset); byteBuffer << uint16(profile->FrameHeight); - byteBuffer << uint16(profile->Unk152); - byteBuffer << uint8(profile->Unk147); - byteBuffer << uint16(profile->Unk150); - byteBuffer << uint8(profile->Unk146); + byteBuffer << uint16(profile->BottomOffset); + byteBuffer << uint8(profile->BottomPoint); + byteBuffer << uint16(profile->TopOffset); + byteBuffer << uint8(profile->TopPoint); byteBuffer << uint8(profile->HealthText); byteBuffer << uint8(profile->SortBy); byteBuffer << uint16(profile->FrameWidth); - byteBuffer << uint8(profile->Unk148); + byteBuffer << uint8(profile->LeftPoint); byteBuffer.WriteString(profile->ProfileName); } diff --git a/src/server/game/Handlers/MovementHandler.cpp b/src/server/game/Handlers/MovementHandler.cpp index 404f6d5f336..6cf393fd159 100644 --- a/src/server/game/Handlers/MovementHandler.cpp +++ b/src/server/game/Handlers/MovementHandler.cpp @@ -165,7 +165,7 @@ void WorldSession::HandleMoveWorldportAckOpcode() { if (time_t timeReset = sInstanceSaveMgr->GetResetTimeFor(mEntry->MapID, diff)) { - uint32 timeleft = uint32(timeReset - time(NULL)); + uint32 timeleft = uint32(timeReset - time(nullptr)); GetPlayer()->SendInstanceResetWarning(mEntry->MapID, diff, timeleft, true); } } @@ -278,7 +278,7 @@ void WorldSession::HandleMovementOpcodes(WorldPacket& recvPacket) Unit* mover = _player->m_unitMovedByMe; - ASSERT(mover != NULL); // there must always be a mover + ASSERT(mover != nullptr); // there must always be a mover Player* plrMover = mover->ToPlayer(); diff --git a/src/server/game/Handlers/NPCHandler.cpp b/src/server/game/Handlers/NPCHandler.cpp index 676403aa1f1..2fe9d2f458d 100644 --- a/src/server/game/Handlers/NPCHandler.cpp +++ b/src/server/game/Handlers/NPCHandler.cpp @@ -16,26 +16,29 @@ * with this program. If not, see . */ -#include "Common.h" -#include "Language.h" -#include "DatabaseEnv.h" -#include "QueryCallback.h" -#include "WorldPacket.h" #include "WorldSession.h" -#include "Opcodes.h" -#include "Log.h" -#include "ObjectMgr.h" -#include "SpellMgr.h" -#include "Player.h" -#include "GossipDef.h" -#include "Creature.h" -#include "Pet.h" -#include "ReputationMgr.h" -#include "BattlegroundMgr.h" #include "Battleground.h" -#include "ScriptMgr.h" +#include "BattlegroundMgr.h" +#include "Common.h" +#include "Creature.h" #include "CreatureAI.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "GossipDef.h" +#include "Item.h" +#include "Language.h" +#include "Log.h" +#include "Map.h" +#include "ObjectMgr.h" +#include "Opcodes.h" +#include "Pet.h" +#include "Player.h" +#include "QueryCallback.h" +#include "ReputationMgr.h" +#include "ScriptMgr.h" #include "SpellInfo.h" +#include "SpellMgr.h" +#include "WorldPacket.h" enum StableResultCode { @@ -400,11 +403,11 @@ void WorldSession::SendSpiritResurrect() _player->DurabilityLossAll(0.25f, true); // get corpse nearest graveyard - WorldSafeLocsEntry const* corpseGrave = NULL; + WorldSafeLocsEntry const* corpseGrave = nullptr; WorldLocation corpseLocation = _player->GetCorpseLocation(); if (_player->HasCorpse()) { - corpseGrave = sObjectMgr->GetClosestGraveYard(corpseLocation, _player->GetTeam(), _player); + corpseGrave = sObjectMgr->GetClosestGraveyard(corpseLocation, _player->GetTeam(), _player); } // now can spawn bones @@ -413,7 +416,7 @@ void WorldSession::SendSpiritResurrect() // teleport to nearest from corpse graveyard, if different from nearest to player ghost if (corpseGrave) { - WorldSafeLocsEntry const* ghostGrave = sObjectMgr->GetClosestGraveYard(*_player, _player->GetTeam(), _player); + WorldSafeLocsEntry const* ghostGrave = sObjectMgr->GetClosestGraveyard(*_player, _player->GetTeam(), _player); if (corpseGrave != ghostGrave) _player->TeleportTo(corpseGrave->map_id, corpseGrave->x, corpseGrave->y, corpseGrave->z, _player->GetOrientation()); @@ -701,7 +704,7 @@ void WorldSession::HandleUnstablePetCallback(uint32 petId, PreparedQueryResult r if (!newPet->LoadPetFromDB(_player, petEntry, petId)) { delete newPet; - newPet = NULL; + newPet = nullptr; SendStableResult(STABLE_ERR_STABLE); return; } diff --git a/src/server/game/Handlers/NPCHandler.h b/src/server/game/Handlers/NPCHandler.h index 163eeebc1c9..6061b61eabc 100644 --- a/src/server/game/Handlers/NPCHandler.h +++ b/src/server/game/Handlers/NPCHandler.h @@ -46,14 +46,14 @@ struct GossipText struct PageTextLocale { - StringVector Text; + std::vector Text; }; struct NpcTextLocale { NpcTextLocale() { } - StringVector Text_0[MAX_GOSSIP_TEXT_OPTIONS]; - StringVector Text_1[MAX_GOSSIP_TEXT_OPTIONS]; + std::vector Text_0[MAX_GOSSIP_TEXT_OPTIONS]; + std::vector Text_1[MAX_GOSSIP_TEXT_OPTIONS]; }; #endif diff --git a/src/server/game/Handlers/PetHandler.cpp b/src/server/game/Handlers/PetHandler.cpp index 3592ec07e49..4957f1b5672 100644 --- a/src/server/game/Handlers/PetHandler.cpp +++ b/src/server/game/Handlers/PetHandler.cpp @@ -16,24 +16,25 @@ * with this program. If not, see . */ -#include "Common.h" -#include "WorldPacket.h" #include "WorldSession.h" -#include "ObjectMgr.h" -#include "SpellMgr.h" -#include "Log.h" -#include "Opcodes.h" -#include "Spell.h" -#include "ObjectAccessor.h" +#include "Common.h" #include "CreatureAI.h" -#include "PetAI.h" -#include "Util.h" -#include "Pet.h" -#include "World.h" +#include "DatabaseEnv.h" #include "Group.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Opcodes.h" +#include "Pet.h" +#include "PetAI.h" +#include "Player.h" +#include "Spell.h" #include "SpellHistory.h" #include "SpellInfo.h" -#include "Player.h" +#include "SpellMgr.h" +#include "Util.h" +#include "WorldPacket.h" void WorldSession::HandleDismissCritter(WorldPacket& recvData) { @@ -93,7 +94,7 @@ void WorldSession::HandlePetAction(WorldPacket& recvData) if (!pet->IsAlive()) { - SpellInfo const* spell = (flag == ACT_ENABLED || flag == ACT_PASSIVE) ? sSpellMgr->GetSpellInfo(spellid) : NULL; + SpellInfo const* spell = (flag == ACT_ENABLED || flag == ACT_PASSIVE) ? sSpellMgr->GetSpellInfo(spellid) : nullptr; if (!spell) return; if (!spell->HasAttribute(SPELL_ATTR0_CASTABLE_WHILE_DEAD)) @@ -305,7 +306,7 @@ void WorldSession::HandlePetActionHelper(Unit* pet, ObjectGuid guid1, uint32 spe case ACT_PASSIVE: // 0x01 case ACT_ENABLED: // 0xC1 spell { - Unit* unit_target = NULL; + Unit* unit_target = nullptr; if (guid2) unit_target = ObjectAccessor::GetUnit(*_player, guid2); @@ -444,7 +445,7 @@ void WorldSession::SendPetNameQuery(ObjectGuid petguid, uint32 petnumber) data << uint8(0); data << uint32(0); data << uint8(0); - _player->GetSession()->SendPacket(&data); + _player->SendDirectMessage(&data); return; } @@ -462,7 +463,7 @@ void WorldSession::SendPetNameQuery(ObjectGuid petguid, uint32 petnumber) else data << uint8(0); - _player->GetSession()->SendPacket(&data); + _player->SendDirectMessage(&data); } bool WorldSession::CheckStableMaster(ObjectGuid guid) @@ -629,13 +630,13 @@ void WorldSession::HandlePetRename(WorldPacket& recvData) PetNameInvalidReason res = ObjectMgr::CheckPetName(name, GetSessionDbcLocale()); if (res != PET_NAME_SUCCESS) { - SendPetNameInvalid(res, name, NULL); + SendPetNameInvalid(res, name, nullptr); return; } if (sObjectMgr->IsReservedName(name)) { - SendPetNameInvalid(PET_NAME_RESERVED, name, NULL); + SendPetNameInvalid(PET_NAME_RESERVED, name, nullptr); return; } @@ -688,7 +689,7 @@ void WorldSession::HandlePetRename(WorldPacket& recvData) CharacterDatabase.CommitTransaction(trans); - pet->SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(NULL))); // cast can't be helped + pet->SetUInt32Value(UNIT_FIELD_PET_NAME_TIMESTAMP, uint32(time(nullptr))); // cast can't be helped } void WorldSession::HandlePetAbandon(WorldPacket& recvData) @@ -805,7 +806,7 @@ void WorldSession::HandlePetCastSpellOpcode(WorldPacket& recvPacket) spell->m_cast_count = castCount; // probably pending spell cast spell->m_targets = targets; - SpellCastResult result = spell->CheckPetCast(NULL); + SpellCastResult result = spell->CheckPetCast(nullptr); if (result == SPELL_CAST_OK) { diff --git a/src/server/game/Handlers/PetitionsHandler.cpp b/src/server/game/Handlers/PetitionsHandler.cpp index f0837c517a7..6b682b857c2 100644 --- a/src/server/game/Handlers/PetitionsHandler.cpp +++ b/src/server/game/Handlers/PetitionsHandler.cpp @@ -16,18 +16,24 @@ * with this program. If not, see . */ -#include "Common.h" -#include "WorldPacket.h" #include "WorldSession.h" -#include "World.h" -#include "ObjectMgr.h" -#include "ArenaTeamMgr.h" -#include "GuildMgr.h" -#include "Log.h" -#include "Opcodes.h" -#include "Guild.h" #include "ArenaTeam.h" +#include "ArenaTeamMgr.h" #include "CharacterCache.h" +#include "Common.h" +#include "Creature.h" +#include "DatabaseEnv.h" +#include "Guild.h" +#include "GuildMgr.h" +#include "Item.h" +#include "Log.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Opcodes.h" +#include "Player.h" +#include "SpellAuraDefines.h" +#include "World.h" +#include "WorldPacket.h" #define CHARTER_DISPLAY_ID 16161 @@ -168,7 +174,7 @@ void WorldSession::HandlePetitionBuyOpcode(WorldPacket& recvData) ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(charterid); if (!pProto) { - _player->SendBuyError(BUY_ERR_CANT_FIND_ITEM, NULL, charterid, 0); + _player->SendBuyError(BUY_ERR_CANT_FIND_ITEM, nullptr, charterid, 0); return; } @@ -182,7 +188,7 @@ void WorldSession::HandlePetitionBuyOpcode(WorldPacket& recvData) InventoryResult msg = _player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, charterid, pProto->BuyCount); if (msg != EQUIP_ERR_OK) { - _player->SendEquipError(msg, NULL, NULL, charterid); + _player->SendEquipError(msg, nullptr, nullptr, charterid); return; } @@ -269,7 +275,7 @@ void WorldSession::HandlePetitionShowSignOpcode(WorldPacket& recvData) result = CharacterDatabase.Query(stmt); - // result == NULL also correct in case no sign yet + // result == nullptr also correct in case no sign yet if (result) signs = uint8(result->GetRowCount()); @@ -572,7 +578,7 @@ void WorldSession::HandlePetitionSignOpcode(WorldPacket& recvData) // update for owner if online if (Player* owner = ObjectAccessor::FindConnectedPlayer(ownerGuid)) - owner->GetSession()->SendPacket(&data); + owner->SendDirectMessage(&data); } void WorldSession::HandlePetitionDeclineOpcode(WorldPacket& recvData) @@ -600,7 +606,7 @@ void WorldSession::HandlePetitionDeclineOpcode(WorldPacket& recvData) { WorldPacket data(MSG_PETITION_DECLINE, 8); data << uint64(_player->GetGUID()); - owner->GetSession()->SendPacket(&data); + owner->SendDirectMessage(&data); } } @@ -691,7 +697,7 @@ void WorldSession::HandleOfferPetitionOpcode(WorldPacket& recvData) result = CharacterDatabase.Query(stmt); - // result == NULL also correct charter without signs + // result == nullptr also correct charter without signs if (result) signs = uint8(result->GetRowCount()); @@ -710,7 +716,7 @@ void WorldSession::HandleOfferPetitionOpcode(WorldPacket& recvData) result->NextRow(); } - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } void WorldSession::HandleTurnInPetitionOpcode(WorldPacket& recvData) @@ -764,7 +770,7 @@ void WorldSession::HandleTurnInPetitionOpcode(WorldPacket& recvData) { data.Initialize(SMSG_TURN_IN_PETITION_RESULTS, 4); data << uint32(PETITION_TURN_ALREADY_IN_GUILD); - _player->GetSession()->SendPacket(&data); + _player->SendDirectMessage(&data); return; } diff --git a/src/server/game/Handlers/QueryHandler.cpp b/src/server/game/Handlers/QueryHandler.cpp index 618e73295bb..aa915d7f2a9 100644 --- a/src/server/game/Handlers/QueryHandler.cpp +++ b/src/server/game/Handlers/QueryHandler.cpp @@ -16,18 +16,20 @@ * with this program. If not, see . */ +#include "WorldSession.h" +#include "CharacterCache.h" #include "Common.h" #include "DatabaseEnv.h" -#include "WorldPacket.h" -#include "WorldSession.h" +#include "DBCStores.h" #include "Log.h" -#include "World.h" +#include "MapManager.h" +#include "NPCHandler.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Player.h" #include "UpdateMask.h" -#include "NPCHandler.h" -#include "MapManager.h" -#include "CharacterCache.h" +#include "World.h" +#include "WorldPacket.h" void WorldSession::SendNameQueryOpcode(ObjectGuid guid) { @@ -50,7 +52,7 @@ void WorldSession::SendNameQueryOpcode(ObjectGuid guid) data << uint8(nameData->Sex); data << uint8(nameData->Class); - if (DeclinedName const* names = (player ? player->GetDeclinedNames() : NULL)) + if (DeclinedName const* names = (player ? player->GetDeclinedNames() : nullptr)) { data << uint8(1); // Name is declined for (uint8 i = 0; i < MAX_DECLINED_NAME_CASES; ++i) @@ -81,8 +83,8 @@ void WorldSession::HandleQueryTimeOpcode(WorldPacket & /*recvData*/) void WorldSession::SendQueryTimeResponse() { WorldPacket data(SMSG_QUERY_TIME_RESPONSE, 4+4); - data << uint32(time(NULL)); - data << uint32(sWorld->GetNextDailyQuestsResetTime() - time(NULL)); + data << uint32(time(nullptr)); + data << uint32(sWorld->GetNextDailyQuestsResetTime() - time(nullptr)); SendPacket(&data); } @@ -103,7 +105,7 @@ void WorldSession::HandleCreatureQueryOpcode(WorldPacket& recvData) Title = creatureInfo->Title; LocaleConstant locale = GetSessionDbLocaleIndex(); - if (static_cast(locale >= LOCALE_enUS)) + if (locale != LOCALE_enUS) { if (CreatureLocale const* creatureLocale = sObjectMgr->GetCreatureLocale(entry)) { @@ -144,7 +146,7 @@ void WorldSession::HandleCreatureQueryOpcode(WorldPacket& recvData) data << float(creatureInfo->ModMana); // dmg/mana modifier data << uint8(creatureInfo->RacialLeader); // RacialLeader - CreatureQuestItemList const* items = sObjectMgr->GetCreatureQuestItemList(entry); + std::vector const* items = sObjectMgr->GetCreatureQuestItemList(entry); if (items) for (uint32 i = 0; i < MAX_CREATURE_QUEST_ITEMS; ++i) data << (i < items->size() ? uint32((*items)[i]) : uint32(0)); @@ -180,7 +182,7 @@ void WorldSession::HandleGameObjectQueryOpcode(WorldPacket& recvData) ObjectGuid guid; recvData >> guid; - const GameObjectTemplate* info = sObjectMgr->GetGameObjectTemplate(entry); + GameObjectTemplate const* info = sObjectMgr->GetGameObjectTemplate(entry); if (info) { std::string Name; @@ -192,12 +194,14 @@ void WorldSession::HandleGameObjectQueryOpcode(WorldPacket& recvData) CastBarCaption = info->castBarCaption; LocaleConstant localeConstant = GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) + { if (GameObjectLocale const* gameObjectLocale = sObjectMgr->GetGameObjectLocale(entry)) { ObjectMgr::GetLocaleString(gameObjectLocale->Name, localeConstant, Name); ObjectMgr::GetLocaleString(gameObjectLocale->CastBarCaption, localeConstant, CastBarCaption); } + } TC_LOG_DEBUG("network", "WORLD: CMSG_GAMEOBJECT_QUERY '%s' - Entry: %u. ", info->name.c_str(), entry); WorldPacket data (SMSG_GAMEOBJECT_QUERY_RESPONSE, 150); @@ -213,7 +217,7 @@ void WorldSession::HandleGameObjectQueryOpcode(WorldPacket& recvData) data << float(info->size); // go size data << int32(info->RequiredLevel); // 4.x, Required level - GameObjectQuestItemList const* items = sObjectMgr->GetGameObjectQuestItemList(entry); + std::vector const* items = sObjectMgr->GetGameObjectQuestItemList(entry); if (items) for (size_t i = 0; i < MAX_GAMEOBJECT_QUEST_ITEMS; ++i) data << (i < items->size() ? uint32((*items)[i]) : uint32(0)); @@ -396,7 +400,7 @@ void WorldSession::HandlePageTextQueryOpcode(WorldPacket& recvData) std::string Text = pageText->Text; LocaleConstant localeConstant = GetSessionDbLocaleIndex(); - if (localeConstant >= LOCALE_enUS) + if (localeConstant != LOCALE_enUS) if (PageTextLocale const* pageTextLocale = sObjectMgr->GetPageTextLocale(pageID)) ObjectMgr::GetLocaleString(pageTextLocale->Text, localeConstant, Text); diff --git a/src/server/game/Handlers/QuestHandler.cpp b/src/server/game/Handlers/QuestHandler.cpp index 0cccae34dfe..37d04f52285 100644 --- a/src/server/game/Handlers/QuestHandler.cpp +++ b/src/server/game/Handlers/QuestHandler.cpp @@ -16,20 +16,24 @@ * with this program. If not, see . */ -#include "Common.h" -#include "Log.h" -#include "WorldPacket.h" #include "WorldSession.h" -#include "World.h" +#include "Battleground.h" +#include "Common.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "DatabaseEnv.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "GossipDef.h" +#include "Group.h" +#include "Log.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Player.h" -#include "GossipDef.h" #include "QuestDef.h" -#include "ObjectAccessor.h" -#include "Group.h" -#include "Battleground.h" #include "ScriptMgr.h" -#include "GameObjectAI.h" +#include "World.h" +#include "WorldPacket.h" void WorldSession::HandleQuestgiverStatusQueryOpcode(WorldPacket& recvData) { @@ -181,7 +185,7 @@ void WorldSession::HandleQuestgiverAcceptQuestOpcode(WorldPacket& recvData) { if (Group* group = _player->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(); @@ -481,7 +485,7 @@ void WorldSession::HandleQuestConfirmAccept(WorldPacket& recvData) if (_player->CanAddQuest(quest, true)) { - _player->AddQuestAndCheckCompletion(quest, NULL); // NULL, this prevent DB script from duplicate running + _player->AddQuestAndCheckCompletion(quest, nullptr); // nullptr, this prevent DB script from duplicate running if (quest->GetSrcSpell() > 0) _player->CastSpell(_player, quest->GetSrcSpell(), true); @@ -583,7 +587,7 @@ void WorldSession::HandlePushQuestToParty(WorldPacket& recvPacket) if (!group) return; - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* receiver = itr->GetSource(); diff --git a/src/server/game/Handlers/ReferAFriendHandler.cpp b/src/server/game/Handlers/ReferAFriendHandler.cpp index d4dd308eecd..035b3304c66 100644 --- a/src/server/game/Handlers/ReferAFriendHandler.cpp +++ b/src/server/game/Handlers/ReferAFriendHandler.cpp @@ -16,9 +16,11 @@ */ #include "WorldSession.h" -#include "Player.h" -#include "ObjectMgr.h" #include "Log.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "World.h" void WorldSession::HandleGrantLevel(WorldPacket& recvData) { @@ -60,7 +62,7 @@ void WorldSession::HandleGrantLevel(WorldPacket& recvData) WorldPacket data2(SMSG_PROPOSE_LEVEL_GRANT, 8); data2 << _player->GetPackGUID(); - target->GetSession()->SendPacket(&data2); + target->SendDirectMessage(&data2); } void WorldSession::HandleAcceptGrantLevel(WorldPacket& recvData) diff --git a/src/server/game/Handlers/SkillHandler.cpp b/src/server/game/Handlers/SkillHandler.cpp index 1ebfcef96c7..216ffb403d1 100644 --- a/src/server/game/Handlers/SkillHandler.cpp +++ b/src/server/game/Handlers/SkillHandler.cpp @@ -16,13 +16,14 @@ * with this program. If not, see . */ +#include "WorldSession.h" #include "Common.h" +#include "DBCStores.h" #include "Log.h" #include "ObjectAccessor.h" -#include "Player.h" #include "Pet.h" +#include "Player.h" #include "WorldPacket.h" -#include "WorldSession.h" void WorldSession::HandleLearnTalentOpcode(WorldPacket& recvData) { diff --git a/src/server/game/Handlers/SocialHandler.cpp b/src/server/game/Handlers/SocialHandler.cpp index 29bdf795e36..36eb314dd39 100644 --- a/src/server/game/Handlers/SocialHandler.cpp +++ b/src/server/game/Handlers/SocialHandler.cpp @@ -15,12 +15,18 @@ * with this program. If not, see . */ -#include "CharacterCache.h" #include "WorldSession.h" +#include "AccountMgr.h" +#include "CharacterCache.h" +#include "Log.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Player.h" #include "QueryCallback.h" +#include "RBAC.h" +#include "Realm.h" #include "SocialMgr.h" -#include "ObjectMgr.h" +#include "World.h" void WorldSession::HandleContactListOpcode(WorldPacket& recvData) { diff --git a/src/server/game/Handlers/SpellHandler.cpp b/src/server/game/Handlers/SpellHandler.cpp index 23e202579d1..a97e5a58f63 100644 --- a/src/server/game/Handlers/SpellHandler.cpp +++ b/src/server/game/Handlers/SpellHandler.cpp @@ -16,23 +16,30 @@ * with this program. If not, see . */ -#include "Common.h" -#include "DBCStores.h" -#include "WorldPacket.h" #include "WorldSession.h" -#include "ObjectMgr.h" -#include "GuildMgr.h" -#include "SpellMgr.h" -#include "Log.h" -#include "Opcodes.h" -#include "Spell.h" -#include "Totem.h" -#include "ScriptMgr.h" -#include "GameObjectAI.h" -#include "SpellAuraEffects.h" -#include "Player.h" +#include "Archaeology.h" +#include "Common.h" #include "Config.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "Guild.h" +#include "GuildMgr.h" +#include "Item.h" +#include "Log.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Opcodes.h" +#include "Player.h" #include "QueryCallback.h" +#include "ScriptMgr.h" +#include "Spell.h" +#include "SpellAuraEffects.h" +#include "SpellMgr.h" +#include "Totem.h" +#include "World.h" +#include "WorldPacket.h" void WorldSession::HandleClientCastFlags(WorldPacket& recvPacket, uint8 castFlags, SpellCastTargets& targets) { @@ -54,7 +61,7 @@ void WorldSession::HandleClientCastFlags(WorldPacket& recvPacket, uint8 castFlag } else if (castFlags & 0x8) // Archaeology { - ArchData* archData = new ArchData(); + ArchData archData; uint32 count; uint8 type; recvPacket >> count; @@ -64,15 +71,16 @@ void WorldSession::HandleClientCastFlags(WorldPacket& recvPacket, uint8 castFlag switch (type) { case 2: // Keystones - recvPacket >> archData->keyId; // Item id - recvPacket >> archData->keyCount; // Item count + recvPacket >> archData.KeyId; // Item id + recvPacket >> archData.KeyCount; // Item count break; case 1: // Fragments - recvPacket >> archData->fragId; // Currency id - recvPacket >> archData->fragCount; // Currency count + recvPacket >> archData.FragId; // Currency id + recvPacket >> archData.FragCount; // Currency count break; } } + if (Player* player = GetPlayer()) player->SetArchData(archData); } @@ -97,20 +105,20 @@ void WorldSession::HandleUseItemOpcode(WorldPacket& recvPacket) if (glyphIndex >= MAX_GLYPH_SLOT_INDEX) { - pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } Item* pItem = pUser->GetUseableItemByPos(bagIndex, slot); if (!pItem) { - pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } if (pItem->GetGUID() != itemGUID) { - pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } @@ -119,35 +127,35 @@ void WorldSession::HandleUseItemOpcode(WorldPacket& recvPacket) ItemTemplate const* proto = pItem->GetTemplate(); if (!proto) { - pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, pItem, NULL); + pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, pItem, nullptr); return; } // some item classes can be used only in equipped state if (proto->InventoryType != INVTYPE_NON_EQUIP && !pItem->IsEquipped()) { - pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, pItem, NULL); + pUser->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, pItem, nullptr); return; } InventoryResult msg = pUser->CanUseItem(pItem); if (msg != EQUIP_ERR_OK) { - pUser->SendEquipError(msg, pItem, NULL); + pUser->SendEquipError(msg, pItem, nullptr); return; } // only allow conjured consumable, bandage, poisons (all should have the 2^21 item flag set in DB) if (proto->Class == ITEM_CLASS_CONSUMABLE && !(proto->Flags & ITEM_FLAG_IGNORE_DEFAULT_ARENA_RESTRICTIONS) && pUser->InArena()) { - pUser->SendEquipError(EQUIP_ERR_NOT_DURING_ARENA_MATCH, pItem, NULL); + pUser->SendEquipError(EQUIP_ERR_NOT_DURING_ARENA_MATCH, pItem, nullptr); return; } // don't allow items banned in arena if ((proto->Flags & ITEM_FLAG_NOT_USEABLE_IN_ARENA) && pUser->InArena()) { - pUser->SendEquipError(EQUIP_ERR_NOT_DURING_ARENA_MATCH, pItem, NULL); + pUser->SendEquipError(EQUIP_ERR_NOT_DURING_ARENA_MATCH, pItem, nullptr); return; } @@ -159,7 +167,7 @@ void WorldSession::HandleUseItemOpcode(WorldPacket& recvPacket) { if (!spellInfo->CanBeUsedInCombat()) { - pUser->SendEquipError(EQUIP_ERR_NOT_IN_COMBAT, pItem, NULL); + pUser->SendEquipError(EQUIP_ERR_NOT_IN_COMBAT, pItem, nullptr); return; } } @@ -227,7 +235,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_FLAG_HAS_LOOT) && !item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_WRAPPED)) { - player->SendEquipError(EQUIP_ERR_CLIENT_LOCKED_OUT, item, NULL); + player->SendEquipError(EQUIP_ERR_CLIENT_LOCKED_OUT, item, nullptr); TC_LOG_INFO("entities.player.cheat", "Possible hacking attempt: Player %s [guid: %u] tried to open item [guid: %u, entry: %u] which is not openable!", player->GetName().c_str(), player->GetGUID().GetCounter(), item->GetGUID().GetCounter(), proto->ItemId); return; @@ -393,7 +401,7 @@ void WorldSession::HandleCastSpellOpcode(WorldPacket& recvPacket) } if (caster->GetTypeId() == TYPEID_PLAYER && !caster->ToPlayer()->HasActiveSpell(spellInfo->Id) && !spellInfo->IsRaidMarker() && - !caster->ToPlayer()->HasArchProject(spellInfo->ResearchProjectId)) + !caster->ToPlayer()->HasArchProject(static_cast(spellInfo->ResearchProjectId))) { // not have spell in spellbook recvPacket.rfinish(); // prevent spam at ignore packet @@ -435,7 +443,7 @@ void WorldSession::HandleCastSpellOpcode(WorldPacket& recvPacket) { SpellInfo const* actualSpellInfo = spellInfo->GetAuraRankForLevel(targets.GetUnitTarget()->getLevel()); - // if rank not found then function return NULL but in explicit cast case original spell can be cast and later failed with appropriate error message + // if rank not found then function return nullptr but in explicit cast case original spell can be cast and later failed with appropriate error message if (actualSpellInfo) spellInfo = actualSpellInfo; } @@ -523,8 +531,7 @@ void WorldSession::HandlePetCancelAuraOpcode(WorldPacket& recvPacket) return; } - Creature* pet=ObjectAccessor::GetCreatureOrPetOrVehicle(*_player, guid); - + Creature* pet = ObjectAccessor::GetCreatureOrPetOrVehicle(*_player, guid); if (!pet) { TC_LOG_ERROR("network", "HandlePetCancelAura: Attempt to cancel an aura for non-existant %s by player '%s'", guid.ToString().c_str(), GetPlayer()->GetName().c_str()); @@ -585,7 +592,7 @@ void WorldSession::HandleTotemDestroyed(WorldPacket& recvPacket) if (!_player->m_SummonSlot[slotId]) return; - Creature* totem = GetPlayer()->GetMap()->GetCreature(_player->m_SummonSlot[slotId]); + Creature* totem = ObjectAccessor::GetCreature(*GetPlayer(), _player->m_SummonSlot[slotId]); if (totem && totem->IsTotem() && totem->GetGUID() == guid) totem->ToTotem()->UnSummon(); } @@ -655,7 +662,7 @@ void WorldSession::HandleMirrorImageDataRequest(WorldPacket& recvData) if (creator->GetTypeId() == TYPEID_PLAYER) { Player* player = creator->ToPlayer(); - Guild* guild = NULL; + Guild* guild = nullptr; if (uint32 guildId = player->GetGuildId()) guild = sGuildMgr->GetGuildById(guildId); diff --git a/src/server/game/Handlers/TaxiHandler.cpp b/src/server/game/Handlers/TaxiHandler.cpp index 4ece77add28..1b57eab620c 100644 --- a/src/server/game/Handlers/TaxiHandler.cpp +++ b/src/server/game/Handlers/TaxiHandler.cpp @@ -16,16 +16,17 @@ * with this program. If not, see . */ +#include "WorldSession.h" #include "Common.h" #include "DatabaseEnv.h" -#include "WorldPacket.h" -#include "WorldSession.h" -#include "Opcodes.h" +#include "DBCStores.h" #include "Log.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" +#include "Opcodes.h" #include "Player.h" #include "WaypointMovementGenerator.h" +#include "WorldPacket.h" void WorldSession::HandleTaxiNodeStatusQueryOpcode(WorldPacket& recvData) { diff --git a/src/server/game/Handlers/TicketHandler.cpp b/src/server/game/Handlers/TicketHandler.cpp index 7df32606b7f..d8d6fc9e744 100644 --- a/src/server/game/Handlers/TicketHandler.cpp +++ b/src/server/game/Handlers/TicketHandler.cpp @@ -16,16 +16,20 @@ * with this program. If not, see . */ -#include "zlib.h" +#include "WorldSession.h" #include "Common.h" +#include "DatabaseEnv.h" #include "Language.h" +#include "Log.h" #include "ObjectMgr.h" #include "Opcodes.h" #include "Player.h" +#include "Random.h" #include "TicketMgr.h" #include "Util.h" +#include "World.h" #include "WorldPacket.h" -#include "WorldSession.h" +#include void WorldSession::HandleGMTicketCreateOpcode(WorldPacket& recvData) { @@ -126,7 +130,7 @@ void WorldSession::HandleGMTicketUpdateOpcode(WorldPacket& recvData) GMTicketResponse response = GMTICKET_RESPONSE_UPDATE_ERROR; if (GmTicket* ticket = sTicketMgr->GetTicketByPlayer(GetPlayer()->GetGUID())) { - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); ticket->SetMessage(message); ticket->SaveToDB(trans); @@ -151,7 +155,7 @@ void WorldSession::HandleGMTicketDeleteOpcode(WorldPacket & /*recvData*/) sWorld->SendGMText(LANG_COMMAND_TICKETPLAYERABANDON, GetPlayer()->GetName().c_str(), ticket->GetId()); sTicketMgr->CloseTicket(ticket->GetId(), GetPlayer()->GetGUID()); - sTicketMgr->SendTicket(this, NULL); + sTicketMgr->SendTicket(this, nullptr); } } @@ -167,7 +171,7 @@ void WorldSession::HandleGMTicketGetTicketOpcode(WorldPacket & /*recvData*/) sTicketMgr->SendTicket(this, ticket); } else - sTicketMgr->SendTicket(this, NULL); + sTicketMgr->SendTicket(this, nullptr); } void WorldSession::HandleGMTicketSystemStatusOpcode(WorldPacket & /*recvData*/) @@ -247,7 +251,7 @@ void WorldSession::HandleReportLag(WorldPacket& recvData) stmt->setFloat (4, y); stmt->setFloat (5, z); stmt->setUInt32(6, GetLatency()); - stmt->setUInt32(7, time(NULL)); + stmt->setUInt32(7, time(nullptr)); CharacterDatabase.Execute(stmt); } @@ -269,6 +273,6 @@ void WorldSession::HandleGMResponseResolve(WorldPacket& /*recvPacket*/) SendPacket(&data2); sTicketMgr->CloseTicket(ticket->GetId(), GetPlayer()->GetGUID()); - sTicketMgr->SendTicket(this, NULL); + sTicketMgr->SendTicket(this, nullptr); } } diff --git a/src/server/game/Handlers/TradeHandler.cpp b/src/server/game/Handlers/TradeHandler.cpp index 5763b92de9c..9e50ba015db 100644 --- a/src/server/game/Handlers/TradeHandler.cpp +++ b/src/server/game/Handlers/TradeHandler.cpp @@ -16,19 +16,21 @@ * with this program. If not, see . */ -#include "Common.h" -#include "WorldPacket.h" #include "WorldSession.h" -#include "World.h" -#include "ObjectAccessor.h" -#include "Log.h" -#include "Player.h" -#include "Item.h" -#include "Spell.h" -#include "SocialMgr.h" -#include "Language.h" #include "AccountMgr.h" +#include "Common.h" +#include "DatabaseEnv.h" +#include "Item.h" +#include "Language.h" +#include "Log.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "SocialMgr.h" +#include "Spell.h" +#include "SpellMgr.h" #include "TradeData.h" +#include "World.h" +#include "WorldPacket.h" void WorldSession::SendTradeStatus(TradeStatusInfo const& info) { @@ -214,8 +216,8 @@ void WorldSession::moveItems(Item* myItems[], Item* hisItems[]) { ItemPosCountVec traderDst; ItemPosCountVec playerDst; - bool traderCanTrade = (myItems[i] == NULL || trader->CanStoreItem(NULL_BAG, NULL_SLOT, traderDst, myItems[i], false) == EQUIP_ERR_OK); - bool playerCanTrade = (hisItems[i] == NULL || _player->CanStoreItem(NULL_BAG, NULL_SLOT, playerDst, hisItems[i], false) == EQUIP_ERR_OK); + bool traderCanTrade = (myItems[i] == nullptr || trader->CanStoreItem(NULL_BAG, NULL_SLOT, traderDst, myItems[i], false) == EQUIP_ERR_OK); + bool playerCanTrade = (hisItems[i] == nullptr || _player->CanStoreItem(NULL_BAG, NULL_SLOT, playerDst, hisItems[i], false) == EQUIP_ERR_OK); if (traderCanTrade && playerCanTrade) { // Ok, if trade item exists and can be stored @@ -298,7 +300,7 @@ static void setAcceptTradeMode(TradeData* myTrade, TradeData* hisTrade, Item* *m if (Item* item = myTrade->GetItem(TradeSlots(i))) { TC_LOG_DEBUG("network", "player trade item %u bag: %u slot: %u", item->GetGUID().GetCounter(), item->GetBagSlot(), item->GetSlot()); - //Can return NULL + //Can return nullptr myItems[i] = item; myItems[i]->SetInTrade(); } @@ -342,8 +344,8 @@ void WorldSession::HandleAcceptTradeOpcode(WorldPacket& /*recvPacket*/) if (!his_trade) return; - Item* myItems[TRADE_SLOT_TRADED_COUNT] = { NULL, NULL, NULL, NULL, NULL, NULL }; - Item* hisItems[TRADE_SLOT_TRADED_COUNT] = { NULL, NULL, NULL, NULL, NULL, NULL }; + Item* myItems[TRADE_SLOT_TRADED_COUNT] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr }; + Item* hisItems[TRADE_SLOT_TRADED_COUNT] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr }; // set before checks for propertly undo at problems (it already set in to client) my_trade->SetAccepted(true); @@ -437,10 +439,10 @@ void WorldSession::HandleAcceptTradeOpcode(WorldPacket& /*recvPacket*/) { setAcceptTradeMode(my_trade, his_trade, myItems, hisItems); - Spell* my_spell = NULL; + Spell* my_spell = nullptr; SpellCastTargets my_targets; - Spell* his_spell = NULL; + Spell* his_spell = nullptr; SpellCastTargets his_targets; // not accept if spell can't be cast now (cheating) @@ -609,9 +611,9 @@ void WorldSession::HandleAcceptTradeOpcode(WorldPacket& /*recvPacket*/) // cleanup clearAcceptTradeMode(my_trade, his_trade); delete _player->m_trade; - _player->m_trade = NULL; + _player->m_trade = nullptr; delete trader->m_trade; - trader->m_trade = NULL; + trader->m_trade = nullptr; // desynchronized with the other saves here (SaveInventoryAndGoldToDB() not have own transaction guards) SQLTransaction trans = CharacterDatabase.BeginTransaction(); @@ -890,5 +892,5 @@ void WorldSession::HandleClearTradeItemOpcode(WorldPacket& recvPacket) if (tradeSlot >= TRADE_SLOT_COUNT) return; - my_trade->SetItem(TradeSlots(tradeSlot), NULL); + my_trade->SetItem(TradeSlots(tradeSlot), nullptr); } diff --git a/src/server/game/Handlers/VehicleHandler.cpp b/src/server/game/Handlers/VehicleHandler.cpp index 5abc4164155..3809cb4756a 100644 --- a/src/server/game/Handlers/VehicleHandler.cpp +++ b/src/server/game/Handlers/VehicleHandler.cpp @@ -15,13 +15,15 @@ * with this program. If not, see . */ -#include "WorldPacket.h" #include "WorldSession.h" -#include "Vehicle.h" -#include "Player.h" +#include "DBCStructure.h" #include "Log.h" -#include "ObjectAccessor.h" +#include "Map.h" #include "MovementStructures.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "Vehicle.h" +#include "WorldPacket.h" void WorldSession::HandleDismissControlledVehicle(WorldPacket &recvData) { diff --git a/src/server/game/Handlers/VoiceChatHandler.cpp b/src/server/game/Handlers/VoiceChatHandler.cpp index 378eab0eab0..aa36eb2fc65 100644 --- a/src/server/game/Handlers/VoiceChatHandler.cpp +++ b/src/server/game/Handlers/VoiceChatHandler.cpp @@ -17,6 +17,7 @@ */ #include "Common.h" +#include "Log.h" #include "WorldPacket.h" #include "WorldSession.h" diff --git a/src/server/game/Handlers/VoidStorageHandler.cpp b/src/server/game/Handlers/VoidStorageHandler.cpp index 0813bc173c6..b3fafd81652 100644 --- a/src/server/game/Handlers/VoidStorageHandler.cpp +++ b/src/server/game/Handlers/VoidStorageHandler.cpp @@ -15,18 +15,16 @@ * with this program. If not, see . */ -#include "Common.h" -#include "WorldPacket.h" #include "WorldSession.h" -#include "World.h" +#include "Bag.h" +#include "Common.h" +#include "Log.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" -#include "Log.h" #include "Opcodes.h" #include "Player.h" -#include -#include -#include +#include "World.h" +#include "WorldPacket.h" void WorldSession::SendVoidStorageTransferResult(VoidTransferError result) { @@ -538,8 +536,8 @@ void WorldSession::HandleVoidSwapItem(WorldPacket& recvData) return; } - bool usedSrcSlot = player->GetVoidStorageItem(oldSlot) != NULL; // should be always true - bool usedDestSlot = player->GetVoidStorageItem(newSlot) != NULL; + bool usedSrcSlot = player->GetVoidStorageItem(oldSlot) != nullptr; // should be always true + bool usedDestSlot = player->GetVoidStorageItem(newSlot) != nullptr; ObjectGuid itemIdDest; if (usedDestSlot) itemIdDest.Set(player->GetVoidStorageItem(newSlot)->ItemId); diff --git a/src/server/game/Instances/InstanceSaveMgr.cpp b/src/server/game/Instances/InstanceSaveMgr.cpp index 7f173225fb9..c07861a5416 100644 --- a/src/server/game/Instances/InstanceSaveMgr.cpp +++ b/src/server/game/Instances/InstanceSaveMgr.cpp @@ -16,21 +16,23 @@ * with this program. If not, see . */ -#include "Common.h" -#include "Player.h" -#include "GridNotifiers.h" -#include "Log.h" -#include "GridStates.h" -#include "Map.h" -#include "MapManager.h" -#include "MapInstanced.h" #include "InstanceSaveMgr.h" -#include "Timer.h" +#include "Common.h" #include "Config.h" -#include "ObjectMgr.h" -#include "World.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "GridNotifiers.h" +#include "GridStates.h" #include "Group.h" #include "InstanceScript.h" +#include "Log.h" +#include "Map.h" +#include "MapInstanced.h" +#include "MapManager.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "Timer.h" +#include "World.h" uint16 InstanceSaveManager::ResetTimeDelay[] = {3600, 900, 300, 60}; @@ -76,23 +78,23 @@ InstanceSave* InstanceSaveManager::AddInstanceSave(uint32 mapId, uint32 instance if (InstanceSave* old_save = GetInstanceSave(instanceId)) return old_save; - const MapEntry* entry = sMapStore.LookupEntry(mapId); + MapEntry const* entry = sMapStore.LookupEntry(mapId); if (!entry) { TC_LOG_ERROR("misc", "InstanceSaveManager::AddInstanceSave: wrong mapid = %d, instanceid = %d!", mapId, instanceId); - return NULL; + return nullptr; } if (instanceId == 0) { TC_LOG_ERROR("misc", "InstanceSaveManager::AddInstanceSave: mapid = %d, wrong instanceid = %d!", mapId, instanceId); - return NULL; + return nullptr; } if (difficulty >= (entry->IsRaid() ? MAX_RAID_DIFFICULTY : MAX_DUNGEON_DIFFICULTY)) { TC_LOG_ERROR("misc", "InstanceSaveManager::AddInstanceSave: mapid = %d, instanceid = %d, wrong dificalty %u!", mapId, instanceId, difficulty); - return NULL; + return nullptr; } if (!resetTime) @@ -103,7 +105,7 @@ InstanceSave* InstanceSaveManager::AddInstanceSave(uint32 mapId, uint32 instance resetTime = GetResetTimeFor(mapId, difficulty); else { - resetTime = time(NULL) + 2 * HOUR; + resetTime = time(nullptr) + 2 * HOUR; // normally this will be removed soon after in InstanceMap::Add, prevent error ScheduleReset(true, resetTime, InstResetEvent(0, mapId, difficulty, instanceId)); } @@ -122,7 +124,7 @@ InstanceSave* InstanceSaveManager::AddInstanceSave(uint32 mapId, uint32 instance InstanceSave* InstanceSaveManager::GetInstanceSave(uint32 InstanceId) { InstanceSaveHashMap::iterator itr = m_instanceSaveById.find(InstanceId); - return itr != m_instanceSaveById.end() ? itr->second : NULL; + return itr != m_instanceSaveById.end() ? itr->second : nullptr; } void InstanceSaveManager::DeleteInstanceFromDB(uint32 instanceid) @@ -219,7 +221,7 @@ void InstanceSave::SaveToDB() time_t InstanceSave::GetResetTimeForDB() { // only save the reset time for normal instances - const MapEntry* entry = sMapStore.LookupEntry(GetMapId()); + MapEntry const* entry = sMapStore.LookupEntry(GetMapId()); if (!entry || entry->map_type == MAP_RAID || GetDifficulty() == DUNGEON_DIFFICULTY_HEROIC) return 0; else @@ -298,7 +300,7 @@ void InstanceSaveManager::LoadInstances() void InstanceSaveManager::LoadResetTimes() { - time_t now = time(NULL); + time_t now = time(nullptr); time_t today = (now / DAY) * DAY; // NOTE: Use DirectPExecute for tables that will be queried later @@ -457,6 +459,13 @@ time_t InstanceSaveManager::GetSubsequentResetTime(uint32 mapid, Difficulty diff return ((resetTime + MINUTE) / DAY * DAY) + period + diff; } +void InstanceSaveManager::SetResetTimeFor(uint32 mapid, Difficulty d, time_t t) +{ + ResetTimeByMapDifficultyMap::iterator itr = m_resetTimeByMapDifficulty.find(MAKE_PAIR32(mapid, d)); + ASSERT(itr != m_resetTimeByMapDifficulty.end()); + itr->second = t; +} + void InstanceSaveManager::ScheduleReset(bool add, time_t time, InstResetEvent event) { if (!add) @@ -507,7 +516,7 @@ void InstanceSaveManager::ForceGlobalReset(uint32 mapId, Difficulty difficulty) void InstanceSaveManager::Update() { - time_t now = time(NULL); + time_t now = time(nullptr); time_t t; while (!m_resetTimeQueue.empty()) @@ -624,7 +633,7 @@ void InstanceSaveManager::_ResetOrWarnAll(uint32 mapid, Difficulty difficulty, b return; TC_LOG_DEBUG("misc", "InstanceSaveManager::ResetOrWarnAll: Processing map %s (%u) on difficulty %u (warn? %u)", mapEntry->name, mapid, uint8(difficulty), warn); - time_t now = time(NULL); + time_t now = time(nullptr); if (!warn) { diff --git a/src/server/game/Instances/InstanceSaveMgr.h b/src/server/game/Instances/InstanceSaveMgr.h index 1697413ae04..03597b23aa4 100644 --- a/src/server/game/Instances/InstanceSaveMgr.h +++ b/src/server/game/Instances/InstanceSaveMgr.h @@ -25,7 +25,7 @@ #include #include "Define.h" -#include "DatabaseEnv.h" +#include "DatabaseEnvFwd.h" #include "DBCEnums.h" #include "ObjectDefines.h" @@ -174,7 +174,7 @@ class TC_GAME_API InstanceSaveManager InstResetEvent() : type(0), difficulty(DUNGEON_DIFFICULTY_NORMAL), mapid(0), instanceId(0) { } InstResetEvent(uint8 t, uint32 _mapid, Difficulty d, uint16 _instanceid) : type(t), difficulty(d), mapid(_mapid), instanceId(_instanceid) { } - bool operator == (const InstResetEvent& e) const { return e.instanceId == instanceId; } + bool operator==(InstResetEvent const& e) const { return e.instanceId == instanceId; } }; typedef std::multimap ResetTimeQueue; @@ -195,12 +195,7 @@ class TC_GAME_API InstanceSaveManager } // Use this only when updating existing reset times - void SetResetTimeFor(uint32 mapid, Difficulty d, time_t t) - { - ResetTimeByMapDifficultyMap::iterator itr = m_resetTimeByMapDifficulty.find(MAKE_PAIR32(mapid, d)); - ASSERT(itr != m_resetTimeByMapDifficulty.end()); - itr->second = t; - } + void SetResetTimeFor(uint32 mapid, Difficulty d, time_t t); ResetTimeByMapDifficultyMap const& GetResetTimeMap() const { diff --git a/src/server/game/Instances/InstanceScript.cpp b/src/server/game/Instances/InstanceScript.cpp index 2290fe42f48..8ba41990865 100644 --- a/src/server/game/Instances/InstanceScript.cpp +++ b/src/server/game/Instances/InstanceScript.cpp @@ -16,22 +16,30 @@ * with this program. If not, see . */ +#include "InstanceScript.h" +#include "AreaBoundary.h" #include "Creature.h" #include "CreatureAI.h" +#include "CreatureAIImpl.h" #include "DatabaseEnv.h" +#include "DBCStructure.h" #include "GameObject.h" #include "Group.h" -#include "InstanceScript.h" #include "LFGMgr.h" #include "Log.h" #include "Map.h" -#include "Player.h" +#include "ObjectMgr.h" +#include "Opcodes.h" #include "Pet.h" #include "PhasingHandler.h" -#include "WorldSession.h" -#include "Opcodes.h" -#include "ScriptReloadMgr.h" +#include "Player.h" +#include "RBAC.h" #include "ScriptMgr.h" +#include "ScriptReloadMgr.h" +#include "World.h" +#include "WorldSession.h" +#include +#include BossBoundaryData::~BossBoundaryData() { @@ -110,6 +118,16 @@ ObjectGuid InstanceScript::GetGuidData(uint32 type) const return GetObjectGuid(type); } +Creature* InstanceScript::GetCreature(uint32 type) +{ + return instance->GetCreature(GetObjectGuid(type)); +} + +GameObject* InstanceScript::GetGameObject(uint32 type) +{ + return instance->GetGameObject(GetObjectGuid(type)); +} + void InstanceScript::SetHeaders(std::string const& dataHeaders) { for (char header : dataHeaders) @@ -117,14 +135,14 @@ void InstanceScript::SetHeaders(std::string const& dataHeaders) headers.push_back(header); } -void InstanceScript::LoadBossBoundaries(const BossBoundaryData& data) +void InstanceScript::LoadBossBoundaries(BossBoundaryData const& data) { for (BossBoundaryEntry const& entry : data) if (entry.BossId < bosses.size()) bosses[entry.BossId].boundary.push_back(entry.Boundary); } -void InstanceScript::LoadMinionData(const MinionData* data) +void InstanceScript::LoadMinionData(MinionData const* data) { while (data->entry) { @@ -136,7 +154,7 @@ void InstanceScript::LoadMinionData(const MinionData* data) TC_LOG_DEBUG("scripts", "InstanceScript::LoadMinionData: " UI64FMTD " minions loaded.", uint64(minions.size())); } -void InstanceScript::LoadDoorData(const DoorData* data) +void InstanceScript::LoadDoorData(DoorData const* data) { while (data->entry) { @@ -544,9 +562,9 @@ void InstanceScript::DoSendNotifyToInstance(char const* format, ...) } // Update Achievement Criteria for all players in instance -void InstanceScript::DoUpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 /*= 0*/, uint32 miscValue2 /*= 0*/, Unit* unit /*= NULL*/) +void InstanceScript::DoUpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 /*= 0*/, uint32 miscValue2 /*= 0*/, Unit* unit /*= nullptr*/) { - Map::PlayerList const &PlayerList = instance->GetPlayers(); + Map::PlayerList const& PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -557,7 +575,7 @@ void InstanceScript::DoUpdateAchievementCriteria(AchievementCriteriaTypes type, // Start timed achievement for all players in instance void InstanceScript::DoStartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry) { - Map::PlayerList const &PlayerList = instance->GetPlayers(); + Map::PlayerList const& PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -568,7 +586,7 @@ void InstanceScript::DoStartTimedAchievement(AchievementCriteriaTimedTypes type, // Stop timed achievement for all players in instance void InstanceScript::DoStopTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry) { - Map::PlayerList const &PlayerList = instance->GetPlayers(); + Map::PlayerList const& PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -597,7 +615,7 @@ void InstanceScript::DoRemoveAurasDueToSpellOnPlayers(uint32 spell) // Cast spell on all players in instance void InstanceScript::DoCastSpellOnPlayers(uint32 spell) { - Map::PlayerList const &PlayerList = instance->GetPlayers(); + Map::PlayerList const& PlayerList = instance->GetPlayers(); if (!PlayerList.isEmpty()) for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -605,14 +623,19 @@ void InstanceScript::DoCastSpellOnPlayers(uint32 spell) player->CastSpell(player, spell, true); } -bool InstanceScript::CheckAchievementCriteriaMeet(uint32 criteria_id, Player const* /*source*/, Unit const* /*target*/ /*= NULL*/, uint32 /*miscvalue1*/ /*= 0*/) +bool InstanceScript::ServerAllowsTwoSideGroups() +{ + return sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP); +} + +bool InstanceScript::CheckAchievementCriteriaMeet(uint32 criteria_id, Player const* /*source*/, Unit const* /*target*/ /*= nullptr*/, uint32 /*miscvalue1*/ /*= 0*/) { TC_LOG_ERROR("misc", "Achievement system call InstanceScript::CheckAchievementCriteriaMeet but instance script for map %u not have implementation for achievement criteria %u", instance->GetId(), criteria_id); return false; } -void InstanceScript::SendEncounterUnit(uint32 type, Unit* unit /*= NULL*/, uint8 param1 /*= 0*/, uint8 param2 /*= 0*/) +void InstanceScript::SendEncounterUnit(uint32 type, Unit* unit /*= nullptr*/, uint8 param1 /*= 0*/, uint8 param2 /*= 0*/) { // size of this packet is at most 15 (usually less) WorldPacket data(SMSG_UPDATE_INSTANCE_ENCOUNTER_UNIT, 15); @@ -687,6 +710,16 @@ void InstanceScript::UpdateEncounterState(EncounterCreditType type, uint32 credi } } +void InstanceScript::UpdateEncounterStateForKilledCreature(uint32 creatureId, Unit* source) +{ + UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, creatureId, source); +} + +void InstanceScript::UpdateEncounterStateForSpellCast(uint32 spellId, Unit* source) +{ + UpdateEncounterState(ENCOUNTER_CREDIT_CAST_SPELL, spellId, source); +} + std::string InstanceScript::GetBossStateName(uint8 state) { // See enum EncounterState in InstanceScript.h @@ -709,6 +742,14 @@ std::string InstanceScript::GetBossStateName(uint8 state) } } +bool InstanceHasScript(WorldObject const* obj, char const* scriptName) +{ + if (InstanceMap* instance = obj->GetMap()->ToInstanceMap()) + return instance->GetScriptName() == scriptName; + + return false; +} + void InstanceScript::UpdatePhasing() { Map::PlayerList const& players = instance->GetPlayers(); diff --git a/src/server/game/Instances/InstanceScript.h b/src/server/game/Instances/InstanceScript.h index d882c92f544..747ffaf1ad8 100644 --- a/src/server/game/Instances/InstanceScript.h +++ b/src/server/game/Instances/InstanceScript.h @@ -19,11 +19,11 @@ #ifndef TRINITY_INSTANCE_DATA_H #define TRINITY_INSTANCE_DATA_H -#include #include "ZoneScript.h" -#include "World.h" -#include "ObjectMgr.h" -#include "CreatureAI.h" +#include "Common.h" +#include +#include +#include #define OUT_SAVE_INST_DATA TC_LOG_DEBUG("scripts", "Saving Instance Data for Instance %s (Map %d, Instance Id %d)", instance->GetMapName(), instance->GetId(), instance->GetInstanceId()) #define OUT_SAVE_INST_DATA_COMPLETE TC_LOG_DEBUG("scripts", "Saving Instance Data for Instance %s (Map %d, Instance Id %d) completed.", instance->GetMapName(), instance->GetId(), instance->GetInstanceId()) @@ -31,12 +31,17 @@ #define OUT_LOAD_INST_DATA_COMPLETE TC_LOG_DEBUG("scripts", "Instance Data Load for Instance %s (Map %d, Instance Id: %d) is complete.", instance->GetMapName(), instance->GetId(), instance->GetInstanceId()) #define OUT_LOAD_INST_DATA_FAIL TC_LOG_ERROR("scripts", "Unable to load Instance Data for Instance %s (Map %d, Instance Id: %d).", instance->GetMapName(), instance->GetId(), instance->GetInstanceId()) -class Map; -class Unit; -class Player; -class GameObject; +class AreaBoundary; class Creature; +class GameObject; +class Map; class ModuleReference; +class Player; +class Unit; +class WorldPacket; +enum AchievementCriteriaTypes : uint8; +enum AchievementCriteriaTimedTypes : uint8; +enum EncounterCreditType : uint8; enum EncounterFrameType { @@ -108,6 +113,8 @@ struct ObjectData uint32 type; }; +typedef std::vector CreatureBoundary; + struct BossInfo { BossInfo() : state(TO_BE_DECIDED) { } @@ -178,21 +185,15 @@ class TC_GAME_API InstanceScript : public ZoneScript ObjectGuid GetObjectGuid(uint32 type) const; virtual ObjectGuid GetGuidData(uint32 type) const override; - inline Creature* GetCreature(uint32 type) - { - return instance->GetCreature(GetObjectGuid(type)); - } - inline GameObject* GetGameObject(uint32 type) - { - return instance->GetGameObject(GetObjectGuid(type)); - } + Creature* GetCreature(uint32 type); + GameObject* GetGameObject(uint32 type); // Called when a player successfully enters the instance. virtual void OnPlayerEnter(Player* /*player*/) { } // Handle open / close objects // * use HandleGameObject(0, boolen, GO); in OnObjectCreate in instance scripts - // * use HandleGameObject(GUID, boolen, NULL); in any other script + // * use HandleGameObject(GUID, boolen, nullptr); in any other script void HandleGameObject(ObjectGuid guid, bool open, GameObject* go = nullptr); // Change active state of doors or buttons @@ -209,7 +210,7 @@ class TC_GAME_API InstanceScript : public ZoneScript void DoSendNotifyToInstance(char const* format, ...); // Update Achievement Criteria for all players in instance - void DoUpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 = 0, uint32 miscValue2 = 0, Unit* unit = NULL); + void DoUpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 = 0, uint32 miscValue2 = 0, Unit* unit = nullptr); // Start/Stop Timed Achievement Criteria for all players in instance void DoStartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry); @@ -222,22 +223,23 @@ class TC_GAME_API InstanceScript : public ZoneScript void DoCastSpellOnPlayers(uint32 spell); // Return wether server allow two side groups or not - bool ServerAllowsTwoSideGroups() { return sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP); } + static bool ServerAllowsTwoSideGroups(); virtual bool SetBossState(uint32 id, EncounterState state); EncounterState GetBossState(uint32 id) const { return id < bosses.size() ? bosses[id].state : TO_BE_DECIDED; } static std::string GetBossStateName(uint8 state); - CreatureBoundary const* GetBossBoundary(uint32 id) const { return id < bosses.size() ? &bosses[id].boundary : NULL; } + CreatureBoundary const* GetBossBoundary(uint32 id) const { return id < bosses.size() ? &bosses[id].boundary : nullptr; } // Achievement criteria additional requirements check // NOTE: not use this if same can be checked existed requirement types from AchievementCriteriaRequirementType - virtual bool CheckAchievementCriteriaMeet(uint32 /*criteria_id*/, Player const* /*source*/, Unit const* /*target*/ = NULL, uint32 /*miscvalue1*/ = 0); + virtual bool CheckAchievementCriteriaMeet(uint32 /*criteria_id*/, Player const* /*source*/, Unit const* /*target*/ = nullptr, uint32 /*miscvalue1*/ = 0); // Checks boss requirements (one boss required to kill other) virtual bool CheckRequiredBosses(uint32 /*bossId*/, Player const* /*player*/ = nullptr) const { return true; } // Checks encounter state at kill/spellcast - void UpdateEncounterState(EncounterCreditType type, uint32 creditEntry, Unit* source); + void UpdateEncounterStateForKilledCreature(uint32 creatureId, Unit* source); + void UpdateEncounterStateForSpellCast(uint32 spellId, Unit* source); // Used only during loading void SetCompletedEncountersMask(uint32 newMask) { completedEncounters = newMask; } @@ -245,7 +247,7 @@ class TC_GAME_API InstanceScript : public ZoneScript // Returns completed encounters mask for packets uint32 GetCompletedEncounterMask() const { return completedEncounters; } - void SendEncounterUnit(uint32 type, Unit* unit = NULL, uint8 param1 = 0, uint8 param2 = 0); + void SendEncounterUnit(uint32 type, Unit* unit = nullptr, uint8 param1 = 0, uint8 param2 = 0); virtual void FillInitialWorldStates(WorldPacket& /*data*/) { } @@ -300,6 +302,7 @@ class TC_GAME_API InstanceScript : public ZoneScript private: static void LoadObjectData(ObjectData const* creatureData, ObjectInfoMap& objectInfo); + void UpdateEncounterState(EncounterCreditType type, uint32 creditEntry, Unit* source); std::vector headers; std::vector bosses; @@ -320,25 +323,4 @@ class TC_GAME_API InstanceScript : public ZoneScript #endif // #ifndef TRINITY_API_USE_DYNAMIC_LINKING }; -template -AI* GetInstanceAI(T* obj, char const* scriptName) -{ - if (InstanceMap* instance = obj->GetMap()->ToInstanceMap()) - if (instance->GetInstanceScript()) - if (instance->GetScriptId() == sObjectMgr->GetScriptId(scriptName)) - return new AI(obj); - - return NULL; -} - -template -AI* GetInstanceAI(T* obj) -{ - if (InstanceMap* instance = obj->GetMap()->ToInstanceMap()) - if (instance->GetInstanceScript()) - return new AI(obj); - - return NULL; -} - #endif // TRINITY_INSTANCE_DATA_H diff --git a/src/server/game/Loot/Loot.cpp b/src/server/game/Loot/Loot.cpp new file mode 100644 index 00000000000..845f734d9b1 --- /dev/null +++ b/src/server/game/Loot/Loot.cpp @@ -0,0 +1,807 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#include "Loot.h" +#include "Group.h" +#include "ItemEnchantmentMgr.h" +#include "ItemTemplate.h" +#include "Log.h" +#include "LootMgr.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "Random.h" +#include "World.h" + +// +// --------- LootItem --------- +// + +// Constructor, copies most fields from LootStoreItem and generates random count +LootItem::LootItem(LootStoreItem const& li) +{ + itemid = li.itemid; + conditions = li.conditions; + + ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemid); + freeforall = proto && (proto->Flags & ITEM_FLAG_MULTI_DROP); + follow_loot_rules = proto && (proto->FlagsCu & ITEM_FLAGS_CU_FOLLOW_LOOT_RULES); + + needs_quest = li.needs_quest; + + randomSuffix = GenerateEnchSuffixFactor(itemid); + randomPropertyId = GenerateItemRandomPropertyId(itemid); + count = 0; + is_looted = 0; + is_blocked = 0; + is_underthreshold = 0; + is_counted = 0; + rollWinnerGUID = ObjectGuid::Empty; +} + +// Basic checks for player/item compatibility - if false no chance to see the item in the loot +bool LootItem::AllowedForPlayer(Player const* player) const +{ + // DB conditions check + if (!sConditionMgr->IsObjectMeetToConditions(const_cast(player), conditions)) + return false; + + ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(itemid); + if (!pProto) + return false; + + // not show loot for players without profession or those who already know the recipe + if ((pProto->Flags & ITEM_FLAG_HIDE_UNUSABLE_RECIPE) && (!player->HasSkill(pProto->RequiredSkill) || player->HasSpell(pProto->Spells[1].SpellId))) + return false; + + // not show loot for not own team + if ((pProto->Flags2 & ITEM_FLAG2_FACTION_HORDE) && player->GetTeam() != HORDE) + return false; + + if ((pProto->Flags2 & ITEM_FLAG2_FACTION_ALLIANCE) && player->GetTeam() != ALLIANCE) + return false; + + // check quest requirements + if (!(pProto->FlagsCu & ITEM_FLAGS_CU_IGNORE_QUEST_STATUS) && ((needs_quest || (pProto->StartQuest && player->GetQuestStatus(pProto->StartQuest) != QUEST_STATUS_NONE)) && !player->HasQuestForItem(itemid))) + return false; + + return true; +} + +void LootItem::AddAllowedLooter(Player const* player) +{ + allowedGUIDs.insert(player->GetGUID()); +} + +// +// --------- Loot --------- +// + +Loot::Loot(uint32 _gold /*= 0*/) : gold(_gold), unlootedCount(0), unlootedCurrency(0), roundRobinPlayer(), loot_type(LOOT_CORPSE), maxDuplicates(1), containerID(0) +{ +} + +Loot::~Loot() +{ + clear(); +} + +// Inserts the item into the loot (called by LootTemplate processors) +void Loot::AddItem(LootStoreItem const& item) +{ + ItemTemplate const* proto = sObjectMgr->GetItemTemplate(item.itemid); + if (!proto) + return; + + uint32 count = urand(item.mincount, item.maxcount); + uint32 stacks = count / proto->GetMaxStackSize() + ((count % proto->GetMaxStackSize()) ? 1 : 0); + + std::vector& lootItems = item.needs_quest ? quest_items : items; + uint32 limit = item.needs_quest ? MAX_NR_QUEST_ITEMS : MAX_NR_LOOT_ITEMS; + + for (uint32 i = 0; i < stacks && lootItems.size() < limit; ++i) + { + LootItem generatedLoot(item); + generatedLoot.count = std::min(count, proto->GetMaxStackSize()); + lootItems.push_back(generatedLoot); + count -= proto->GetMaxStackSize(); + + // 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_FLAG_MULTI_DROP)) + ++unlootedCount; + } +} + +void Loot::AddCurrency(uint32 entry, uint32 min, uint32 max) +{ + uint32 amount = urand(min, max); + + currencies.push_back(LootCurrency(entry, amount)); + + unlootedCurrency++; +} + +LootCurrency* Loot::LootCurrencyInSlot(uint32 lootSlot, Player* /*player*/) +{ + if (currencies[lootSlot].looted) + return nullptr; + + currencies[lootSlot].looted = true; + + unlootedCurrency--; + + return &(currencies[lootSlot]); +} + +// Calls processor of corresponding LootTemplate (which handles everything including references) +bool Loot::FillLoot(uint32 lootId, LootStore const& store, Player* lootOwner, bool personal, bool noEmptyError, uint16 lootMode /*= LOOT_MODE_DEFAULT*/) +{ + // Must be provided + if (!lootOwner) + return false; + + LootTemplate const* tab = store.GetLootFor(lootId); + + if (!tab) + { + if (!noEmptyError) + TC_LOG_ERROR("sql.sql", "Table '%s' loot id #%u used but it doesn't have records.", store.GetName(), lootId); + return false; + } + + items.reserve(MAX_NR_LOOT_ITEMS); + quest_items.reserve(MAX_NR_QUEST_ITEMS); + + tab->Process(*this, store.IsRatesAllowed(), lootMode); // Processing is done there, callback via Loot::AddItem() + + // Setting access rights for group loot case + Group* group = lootOwner->GetGroup(); + if (!personal && group) + { + roundRobinPlayer = lootOwner->GetGUID(); + + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) + if (Player* player = itr->GetSource()) // should actually be looted object instead of lootOwner but looter has to be really close so doesnt really matter + if (player->IsInMap(lootOwner)) + FillNotNormalLootFor(player, player->IsAtGroupRewardDistance(lootOwner)); + + for (uint8 i = 0; i < items.size(); ++i) + { + if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(items[i].itemid)) + if (proto->Quality < uint32(group->GetLootThreshold())) + items[i].is_underthreshold = true; + } + } + // ... for personal loot + else + FillNotNormalLootFor(lootOwner, true); + + return true; +} + +void Loot::FillNotNormalLootFor(Player* player, bool presentAtLooting) +{ + ObjectGuid plguid = player->GetGUID(); + + NotNormalLootItemMap::const_iterator qmapitr = PlayerQuestItems.find(plguid); + if (qmapitr == PlayerQuestItems.end()) + FillQuestLoot(player); + + qmapitr = PlayerFFAItems.find(plguid); + if (qmapitr == PlayerFFAItems.end()) + FillFFALoot(player); + + qmapitr = PlayerNonQuestNonFFAConditionalItems.find(plguid); + if (qmapitr == PlayerNonQuestNonFFAConditionalItems.end()) + FillNonQuestNonFFAConditionalLoot(player, presentAtLooting); + + // if not auto-processed player will have to come and pick it up manually + if (!presentAtLooting) + return; + + // Process currency items + uint32 max_slot = GetMaxSlotInLootFor(player); + LootItem const* item = nullptr; + uint32 itemsSize = uint32(items.size()); + for (uint32 i = 0; i < max_slot; ++i) + { + if (i < items.size()) + item = &items[i]; + else + item = &quest_items[i-itemsSize]; + + if (!item->is_looted && item->freeforall && item->AllowedForPlayer(player)) + if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(item->itemid)) + if (proto->IsCurrencyToken()) + player->StoreLootItem(i, this); + } +} + +NotNormalLootItemList* Loot::FillFFALoot(Player* player) +{ + NotNormalLootItemList* ql = new NotNormalLootItemList(); + + for (uint8 i = 0; i < items.size(); ++i) + { + LootItem &item = items[i]; + if (!item.is_looted && item.freeforall && item.AllowedForPlayer(player)) + { + ql->push_back(NotNormalLootItem(i)); + ++unlootedCount; + } + } + if (ql->empty()) + { + delete ql; + return nullptr; + } + + PlayerFFAItems[player->GetGUID()] = ql; + return ql; +} + +NotNormalLootItemList* Loot::FillQuestLoot(Player* player) +{ + if (items.size() == MAX_NR_LOOT_ITEMS) + return nullptr; + + NotNormalLootItemList* ql = new NotNormalLootItemList(); + + for (uint8 i = 0; i < quest_items.size(); ++i) + { + LootItem &item = quest_items[i]; + + if (!item.is_looted && (item.AllowedForPlayer(player) || (item.follow_loot_rules && player->GetGroup() && ((player->GetGroup()->GetLootMethod() == MASTER_LOOT && player->GetGroup()->GetMasterLooterGuid() == player->GetGUID()) || player->GetGroup()->GetLootMethod() != MASTER_LOOT)))) + { + ql->push_back(NotNormalLootItem(i)); + + // quest items get blocked when they first appear in a + // player's quest vector + // + // increase once if one looter only, looter-times if free for all + if (item.freeforall || !item.is_blocked) + ++unlootedCount; + if (!player->GetGroup() || (player->GetGroup()->GetLootMethod() != GROUP_LOOT && player->GetGroup()->GetLootMethod() != ROUND_ROBIN)) + item.is_blocked = true; + + if (items.size() + ql->size() == MAX_NR_LOOT_ITEMS) + break; + } + } + if (ql->empty()) + { + delete ql; + return nullptr; + } + + PlayerQuestItems[player->GetGUID()] = ql; + return ql; +} + +NotNormalLootItemList* Loot::FillNonQuestNonFFAConditionalLoot(Player* player, bool presentAtLooting) +{ + NotNormalLootItemList* ql = new NotNormalLootItemList(); + + for (uint8 i = 0; i < items.size(); ++i) + { + LootItem &item = items[i]; + if (!item.is_looted && !item.freeforall && (item.AllowedForPlayer(player))) + { + if (presentAtLooting) + item.AddAllowedLooter(player); + if (!item.conditions.empty()) + { + ql->push_back(NotNormalLootItem(i)); + if (!item.is_counted) + { + ++unlootedCount; + item.is_counted = true; + } + } + } + } + if (ql->empty()) + { + delete ql; + return nullptr; + } + + PlayerNonQuestNonFFAConditionalItems[player->GetGUID()] = ql; + return ql; +} + +//=================================================== + +void Loot::NotifyItemRemoved(uint8 lootIndex) +{ + // notify all players that are looting this that the item was removed + // convert the index to the slot the player sees + GuidSet::iterator i_next; + for (GuidSet::iterator i = PlayersLooting.begin(); i != PlayersLooting.end(); i = i_next) + { + i_next = i; + ++i_next; + if (Player* player = ObjectAccessor::FindPlayer(*i)) + player->SendNotifyLootItemRemoved(lootIndex); + else + PlayersLooting.erase(i); + } +} + +void Loot::NotifyMoneyRemoved() +{ + // notify all players that are looting this that the money was removed + GuidSet::iterator i_next; + for (GuidSet::iterator i = PlayersLooting.begin(); i != PlayersLooting.end(); i = i_next) + { + i_next = i; + ++i_next; + if (Player* player = ObjectAccessor::FindPlayer(*i)) + player->SendNotifyLootMoneyRemoved(); + else + PlayersLooting.erase(i); + } +} + +void Loot::NotifyCurrencyRemoved(uint8 lootIndex) +{ + // notify all players that are looting this that the currency was removed + GuidSet::iterator i_next; + for (GuidSet::iterator i = PlayersLooting.begin(); i != PlayersLooting.end(); i = i_next) + { + i_next = i; + ++i_next; + if (Player* player = ObjectAccessor::FindPlayer(*i)) + player->SendNotifyCurrencyLootRemoved(lootIndex); + else + PlayersLooting.erase(i); + } +} + +void Loot::NotifyQuestItemRemoved(uint8 questIndex) +{ + // when a free for all questitem is looted + // all players will get notified of it being removed + // (other questitems can be looted by each group member) + // bit inefficient but isn't called often + + GuidSet::iterator i_next; + for (GuidSet::iterator i = PlayersLooting.begin(); i != PlayersLooting.end(); i = i_next) + { + i_next = i; + ++i_next; + if (Player* player = ObjectAccessor::FindPlayer(*i)) + { + NotNormalLootItemMap::const_iterator pq = PlayerQuestItems.find(player->GetGUID()); + if (pq != PlayerQuestItems.end() && pq->second) + { + // find where/if the player has the given item in it's vector + NotNormalLootItemList& pql = *pq->second; + + uint8 j; + for (j = 0; j < pql.size(); ++j) + if (pql[j].index == questIndex) + break; + + if (j < pql.size()) + player->SendNotifyLootItemRemoved(items.size()+j); + } + } + else + PlayersLooting.erase(i); + } +} + +void Loot::generateMoneyLoot(uint32 minAmount, uint32 maxAmount) +{ + if (maxAmount > 0) + { + if (maxAmount <= minAmount) + gold = uint32(maxAmount * sWorld->getRate(RATE_DROP_MONEY)); + else if ((maxAmount - minAmount) < 32700) + gold = uint32(urand(minAmount, maxAmount) * sWorld->getRate(RATE_DROP_MONEY)); + else + gold = uint32(urand(minAmount >> 8, maxAmount >> 8) * sWorld->getRate(RATE_DROP_MONEY)) << 8; + } +} + +LootItem* Loot::LootItemInSlot(uint32 lootSlot, Player* player, NotNormalLootItem* *qitem, NotNormalLootItem* *ffaitem, NotNormalLootItem* *conditem) +{ + LootItem* item = nullptr; + bool is_looted = true; + if (lootSlot >= items.size()) + { + uint32 questSlot = lootSlot - items.size(); + NotNormalLootItemMap::const_iterator itr = PlayerQuestItems.find(player->GetGUID()); + if (itr != PlayerQuestItems.end() && questSlot < itr->second->size()) + { + NotNormalLootItem* qitem2 = &itr->second->at(questSlot); + if (qitem) + *qitem = qitem2; + item = &quest_items[qitem2->index]; + is_looted = qitem2->is_looted; + } + } + else + { + item = &items[lootSlot]; + is_looted = item->is_looted; + if (item->freeforall) + { + NotNormalLootItemMap::const_iterator itr = PlayerFFAItems.find(player->GetGUID()); + if (itr != PlayerFFAItems.end()) + { + for (NotNormalLootItemList::const_iterator iter=itr->second->begin(); iter!= itr->second->end(); ++iter) + if (iter->index == lootSlot) + { + NotNormalLootItem* ffaitem2 = (NotNormalLootItem*)&(*iter); + if (ffaitem) + *ffaitem = ffaitem2; + is_looted = ffaitem2->is_looted; + break; + } + } + } + else if (!item->conditions.empty()) + { + NotNormalLootItemMap::const_iterator itr = PlayerNonQuestNonFFAConditionalItems.find(player->GetGUID()); + if (itr != PlayerNonQuestNonFFAConditionalItems.end()) + { + for (NotNormalLootItemList::const_iterator iter=itr->second->begin(); iter!= itr->second->end(); ++iter) + { + if (iter->index == lootSlot) + { + NotNormalLootItem* conditem2 = (NotNormalLootItem*)&(*iter); + if (conditem) + *conditem = conditem2; + is_looted = conditem2->is_looted; + break; + } + } + } + } + } + + if (is_looted) + return nullptr; + + return item; +} + +uint32 Loot::GetMaxSlotInLootFor(Player* player) const +{ + NotNormalLootItemMap::const_iterator itr = PlayerQuestItems.find(player->GetGUID()); + 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 +{ + NotNormalLootItemMap const& lootPlayerQuestItems = GetPlayerQuestItems(); + NotNormalLootItemMap::const_iterator q_itr = lootPlayerQuestItems.find(player->GetGUID()); + if (q_itr != lootPlayerQuestItems.end()) + { + NotNormalLootItemList* q_list = q_itr->second; + for (NotNormalLootItemList::const_iterator qi = q_list->begin(); qi != q_list->end(); ++qi) + { + const LootItem &item = quest_items[qi->index]; + if (!qi->is_looted && !item.is_looted) + return true; + } + } + + NotNormalLootItemMap const& lootPlayerFFAItems = GetPlayerFFAItems(); + NotNormalLootItemMap::const_iterator ffa_itr = lootPlayerFFAItems.find(player->GetGUID()); + if (ffa_itr != lootPlayerFFAItems.end()) + { + NotNormalLootItemList* ffa_list = ffa_itr->second; + for (NotNormalLootItemList::const_iterator fi = ffa_list->begin(); fi != ffa_list->end(); ++fi) + { + const LootItem &item = items[fi->index]; + if (!fi->is_looted && !item.is_looted) + return true; + } + } + + NotNormalLootItemMap const& lootPlayerNonQuestNonFFAConditionalItems = GetPlayerNonQuestNonFFAConditionalItems(); + NotNormalLootItemMap::const_iterator nn_itr = lootPlayerNonQuestNonFFAConditionalItems.find(player->GetGUID()); + if (nn_itr != lootPlayerNonQuestNonFFAConditionalItems.end()) + { + NotNormalLootItemList* conditional_list = nn_itr->second; + for (NotNormalLootItemList::const_iterator ci = conditional_list->begin(); ci != conditional_list->end(); ++ci) + { + const LootItem &item = items[ci->index]; + if (!ci->is_looted && !item.is_looted) + return true; + } + } + + return false; +} + +// return true if there is any item over the group threshold (i.e. not underthreshold). +bool Loot::hasOverThresholdItem() const +{ + for (uint8 i = 0; i < items.size(); ++i) + { + if (!items[i].is_looted && !items[i].is_underthreshold && !items[i].freeforall) + return true; + } + + return false; +} + +ByteBuffer& operator<<(ByteBuffer& b, LootItem const& li) +{ + b << uint32(li.itemid); + b << uint32(li.count); // nr of items of this type + b << uint32(ASSERT_NOTNULL(sObjectMgr->GetItemTemplate(li.itemid))->DisplayInfoID); + b << uint32(li.randomSuffix); + b << uint32(li.randomPropertyId); + //b << uint8(0); // slot type - will send after this function call + return b; +} + +ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv) +{ + if (lv.permission == NONE_PERMISSION) + { + b << uint32(0); // gold + b << uint8(0); // item count + b << uint8(0); // currency count + return b; + } + + Loot &l = lv.loot; + + uint8 itemsShown = 0; + uint8 currenciesShown = 0; + + b << uint32(l.gold); //gold + + size_t count_pos = b.wpos(); // pos of item count byte + b << uint8(0); // item count placeholder + size_t currency_count_pos = b.wpos(); // pos of currency count byte + b << uint8(0); // currency count placeholder + + switch (lv.permission) + { + case GROUP_PERMISSION: + case MASTER_PERMISSION: + case RESTRICTED_PERMISSION: + { + // if you are not the round-robin group looter, you can only see + // blocked rolled items and quest items, and !ffa items + for (uint8 i = 0; i < l.items.size(); ++i) + { + if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) + { + uint8 slot_type; + + if (l.items[i].is_blocked) // for ML & restricted is_blocked = !is_underthreshold + { + switch (lv.permission) + { + case GROUP_PERMISSION: + slot_type = LOOT_SLOT_TYPE_ROLL_ONGOING; + break; + case MASTER_PERMISSION: + { + if (lv.viewer->GetGroup() && lv.viewer->GetGroup()->GetMasterLooterGuid() == lv.viewer->GetGUID()) + slot_type = LOOT_SLOT_TYPE_MASTER; + else + slot_type = LOOT_SLOT_TYPE_LOCKED; + break; + } + case RESTRICTED_PERMISSION: + slot_type = LOOT_SLOT_TYPE_LOCKED; + break; + default: + continue; + } + } + else if (!l.items[i].rollWinnerGUID.IsEmpty()) + { + if (l.items[i].rollWinnerGUID == lv.viewer->GetGUID()) + slot_type = LOOT_SLOT_TYPE_OWNER; + else + continue; + } + else if (l.roundRobinPlayer.IsEmpty() || lv.viewer->GetGUID() == l.roundRobinPlayer || !l.items[i].is_underthreshold) + { + // no round robin owner or he has released the loot + // or it IS the round robin group owner + // => item is lootable + slot_type = LOOT_SLOT_TYPE_ALLOW_LOOT; + } + else + // item shall not be displayed. + continue; + + b << uint8(i) << l.items[i]; + b << uint8(slot_type); + ++itemsShown; + } + } + break; + } + case ROUND_ROBIN_PERMISSION: + { + for (uint8 i = 0; i < l.items.size(); ++i) + { + if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) + { + if (!l.roundRobinPlayer.IsEmpty() && lv.viewer->GetGUID() != l.roundRobinPlayer) + // item shall not be displayed. + continue; + + b << uint8(i) << l.items[i]; + b << uint8(LOOT_SLOT_TYPE_ALLOW_LOOT); + ++itemsShown; + } + } + break; + } + case ALL_PERMISSION: + case OWNER_PERMISSION: + { + uint8 slot_type = lv.permission == OWNER_PERMISSION ? LOOT_SLOT_TYPE_OWNER : LOOT_SLOT_TYPE_ALLOW_LOOT; + for (uint8 i = 0; i < l.items.size(); ++i) + { + if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) + { + b << uint8(i) << l.items[i]; + b << uint8(slot_type); + ++itemsShown; + } + } + break; + } + default: + return b; + } + + LootSlotType slotType = lv.permission == OWNER_PERMISSION ? LOOT_SLOT_TYPE_OWNER : LOOT_SLOT_TYPE_ALLOW_LOOT; + NotNormalLootItemMap const& lootPlayerQuestItems = l.GetPlayerQuestItems(); + NotNormalLootItemMap::const_iterator q_itr = lootPlayerQuestItems.find(lv.viewer->GetGUID()); + if (q_itr != lootPlayerQuestItems.end()) + { + NotNormalLootItemList* q_list = q_itr->second; + for (NotNormalLootItemList::const_iterator qi = q_list->begin(); qi != q_list->end(); ++qi) + { + LootItem &item = l.quest_items[qi->index]; + if (!qi->is_looted && !item.is_looted) + { + b << uint8(l.items.size() + (qi - q_list->begin())); + b << item; + if (item.follow_loot_rules) + { + switch (lv.permission) + { + case MASTER_PERMISSION: + b << uint8(LOOT_SLOT_TYPE_MASTER); + break; + case RESTRICTED_PERMISSION: + b << (item.is_blocked ? uint8(LOOT_SLOT_TYPE_LOCKED) : uint8(slotType)); + break; + case GROUP_PERMISSION: + case ROUND_ROBIN_PERMISSION: + if (!item.is_blocked) + b << uint8(LOOT_SLOT_TYPE_ALLOW_LOOT); + else + b << uint8(LOOT_SLOT_TYPE_ROLL_ONGOING); + break; + default: + b << uint8(slotType); + break; + } + } + else + b << uint8(slotType); + ++itemsShown; + } + } + } + + NotNormalLootItemMap const& lootPlayerFFAItems = l.GetPlayerFFAItems(); + NotNormalLootItemMap::const_iterator ffa_itr = lootPlayerFFAItems.find(lv.viewer->GetGUID()); + if (ffa_itr != lootPlayerFFAItems.end()) + { + NotNormalLootItemList* ffa_list = ffa_itr->second; + for (NotNormalLootItemList::const_iterator fi = ffa_list->begin(); fi != ffa_list->end(); ++fi) + { + LootItem &item = l.items[fi->index]; + if (!fi->is_looted && !item.is_looted) + { + b << uint8(fi->index); + b << item; + b << uint8(slotType); + ++itemsShown; + } + } + } + + NotNormalLootItemMap const& lootPlayerNonQuestNonFFAConditionalItems = l.GetPlayerNonQuestNonFFAConditionalItems(); + NotNormalLootItemMap::const_iterator nn_itr = lootPlayerNonQuestNonFFAConditionalItems.find(lv.viewer->GetGUID()); + if (nn_itr != lootPlayerNonQuestNonFFAConditionalItems.end()) + { + NotNormalLootItemList* conditional_list = nn_itr->second; + for (NotNormalLootItemList::const_iterator ci = conditional_list->begin(); ci != conditional_list->end(); ++ci) + { + LootItem &item = l.items[ci->index]; + if (!ci->is_looted && !item.is_looted) + { + b << uint8(ci->index); + b << item; + switch (lv.permission) + { + case MASTER_PERMISSION: + b << uint8(LOOT_SLOT_TYPE_MASTER); + break; + case RESTRICTED_PERMISSION: + b << (item.is_blocked ? uint8(LOOT_SLOT_TYPE_LOCKED) : uint8(slotType)); + break; + case GROUP_PERMISSION: + case ROUND_ROBIN_PERMISSION: + if (!item.is_blocked) + b << uint8(LOOT_SLOT_TYPE_ALLOW_LOOT); + else + b << uint8(LOOT_SLOT_TYPE_ROLL_ONGOING); + break; + default: + b << uint8(slotType); + break; + } + ++itemsShown; + } + } + } + + for (uint8 i = 0; i < l.currencies.size(); ++i) + { + if (l.currencies[i].count == 0 || l.currencies[i].id == 0 || l.currencies[i].looted) + continue; + + l.currencies[i].index = currenciesShown + itemsShown; + + b << uint8(l.currencies[i].index); + b << uint32(l.currencies[i].id); + b << uint32(l.currencies[i].count); + ++currenciesShown; + } + + //update number of items and currencies shown + b.put(count_pos, itemsShown); + b.put(currency_count_pos, currenciesShown); + + return b; +} diff --git a/src/server/game/Loot/Loot.h b/src/server/game/Loot/Loot.h new file mode 100644 index 00000000000..e42d7ca89e7 --- /dev/null +++ b/src/server/game/Loot/Loot.h @@ -0,0 +1,328 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef Loot_h__ +#define Loot_h__ + +#include "Define.h" +#include "ConditionMgr.h" +#include "ObjectGuid.h" +#include "RefManager.h" +#include "SharedDefines.h" +#include +#include + +class Item; +class LootStore; +class Player; +struct Loot; +struct LootStoreItem; + +enum RollType +{ + ROLL_PASS = 0, + ROLL_NEED = 1, + ROLL_GREED = 2, + ROLL_DISENCHANT = 3, + MAX_ROLL_TYPE = 4 +}; + +enum RollMask +{ + ROLL_FLAG_TYPE_PASS = 0x01, + ROLL_FLAG_TYPE_NEED = 0x02, + ROLL_FLAG_TYPE_GREED = 0x04, + ROLL_FLAG_TYPE_DISENCHANT = 0x08, + + ROLL_ALL_TYPE_NO_DISENCHANT = 0x07, + ROLL_ALL_TYPE_MASK = 0x0F +}; + +#define MAX_NR_LOOT_ITEMS 16 +// note: the client cannot show more than 16 items total +#define MAX_NR_QUEST_ITEMS 32 +// unrelated to the number of quest items shown, just for reserve + +enum LootMethod : uint8 +{ + FREE_FOR_ALL = 0, + ROUND_ROBIN = 1, + MASTER_LOOT = 2, + GROUP_LOOT = 3, + NEED_BEFORE_GREED = 4 +}; + +enum PermissionTypes +{ + ALL_PERMISSION = 0, + GROUP_PERMISSION = 1, + MASTER_PERMISSION = 2, + RESTRICTED_PERMISSION = 3, + ROUND_ROBIN_PERMISSION = 4, + OWNER_PERMISSION = 5, + NONE_PERMISSION = 6 +}; + +enum LootType : uint8 +{ + LOOT_NONE = 0, + + LOOT_CORPSE = 1, + LOOT_PICKPOCKETING = 2, + LOOT_FISHING = 3, + LOOT_DISENCHANTING = 4, + // ignored always by client + LOOT_SKINNING = 6, + LOOT_PROSPECTING = 7, + LOOT_MILLING = 8, + + LOOT_ARCHAEOLOGY = 10, + + LOOT_FISHINGHOLE = 20, // unsupported by client, sending LOOT_FISHING instead + LOOT_INSIGNIA = 21, // unsupported by client, sending LOOT_CORPSE instead + LOOT_FISHING_JUNK = 22 // unsupported by client, sending LOOT_FISHING instead +}; + + +enum LootError : uint8 +{ + LOOT_ERROR_DIDNT_KILL = 0, // You don't have permission to loot that corpse. + LOOT_ERROR_TOO_FAR = 4, // You are too far away to loot that corpse. + LOOT_ERROR_BAD_FACING = 5, // You must be facing the corpse to loot it. + LOOT_ERROR_LOCKED = 6, // Someone is already looting that corpse. + LOOT_ERROR_NOTSTANDING = 8, // You need to be standing up to loot something! + LOOT_ERROR_STUNNED = 9, // You can't loot anything while stunned! + LOOT_ERROR_PLAYER_NOT_FOUND = 10, // Player not found + LOOT_ERROR_PLAY_TIME_EXCEEDED = 11, // Maximum play time exceeded + LOOT_ERROR_MASTER_INV_FULL = 12, // That player's inventory is full + LOOT_ERROR_MASTER_UNIQUE_ITEM = 13, // Player has too many of that item already + LOOT_ERROR_MASTER_OTHER = 14, // Can't assign item to that player + LOOT_ERROR_ALREADY_PICKPOCKETED = 15, // Your target has already had its pockets picked + LOOT_ERROR_NOT_WHILE_SHAPESHIFTED = 16 // You can't do that while shapeshifted. +}; + +// type of Loot Item in Loot View +enum LootSlotType +{ + LOOT_SLOT_TYPE_ALLOW_LOOT = 0, // player can loot the item. + LOOT_SLOT_TYPE_ROLL_ONGOING = 1, // roll is ongoing. player cannot loot. + LOOT_SLOT_TYPE_MASTER = 2, // item can only be distributed by group loot master. + LOOT_SLOT_TYPE_LOCKED = 3, // item is shown in red. player cannot loot. + LOOT_SLOT_TYPE_OWNER = 4 // ignore binding confirmation and etc, for single player looting +}; + +struct TC_GAME_API LootItem +{ + uint32 itemid; + uint32 randomSuffix; + int32 randomPropertyId; + ConditionContainer conditions; // additional loot condition + GuidSet allowedGUIDs; + ObjectGuid rollWinnerGUID; // Stores the guid of person who won loot, if his bags are full only he can see the item in loot list! + uint8 count : 8; + bool is_looted : 1; + bool is_blocked : 1; + bool freeforall : 1; // free for all + bool is_underthreshold : 1; + bool is_counted : 1; + bool needs_quest : 1; // quest drop + bool follow_loot_rules : 1; + + // Constructor, copies most fields from LootStoreItem, generates random count and random suffixes/properties + // Should be called for non-reference LootStoreItem entries only (reference = 0) + explicit LootItem(LootStoreItem const& li); + + // Empty constructor for creating an empty LootItem to be filled in with DB data + LootItem() : itemid(0), randomSuffix(0), randomPropertyId(0), count(0), is_looted(false), is_blocked(false), + freeforall(false), is_underthreshold(false), is_counted(false), needs_quest(false), follow_loot_rules(false) + { }; + + // Basic checks for player/item compatibility - if false no chance to see the item in the loot + bool AllowedForPlayer(Player const* player) const; + void AddAllowedLooter(Player const* player); + GuidSet const& GetAllowedLooters() const { return allowedGUIDs; } +}; + +struct NotNormalLootItem +{ + uint8 index; // position in quest_items or items; + bool is_looted; + + NotNormalLootItem() + : index(0), is_looted(false) { } + + NotNormalLootItem(uint8 _index, bool _islooted = false) + : index(_index), is_looted(_islooted) { } +}; + +struct LootCurrency +{ + uint8 index; + uint32 id; + uint32 count; + bool looted; + + LootCurrency() + : index(0), id(0), count(0), looted(false) { } + + LootCurrency(uint32 _id, uint32 _count) + : index(0), id(_id), count(_count), looted(false) { } +}; + +typedef std::vector NotNormalLootItemList; +typedef std::vector LootItemList; +typedef std::unordered_map NotNormalLootItemMap; + +//===================================================== + +class LootValidatorRef : public Reference +{ + public: + LootValidatorRef() { } + void targetObjectDestroyLink() override { } + void sourceObjectDestroyLink() override { } +}; + +//===================================================== + +class LootValidatorRefManager : public RefManager +{ + public: + typedef LinkedListHead::Iterator< LootValidatorRef > iterator; + + LootValidatorRef* getFirst() { return (LootValidatorRef*)RefManager::getFirst(); } + + iterator begin() { return iterator(getFirst()); } + iterator end() { return iterator(nullptr); } +}; + +//===================================================== + +struct LootView; + +ByteBuffer& operator<<(ByteBuffer& b, LootItem const& li); +ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv); + +struct TC_GAME_API Loot +{ + friend ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv); + + NotNormalLootItemMap const& GetPlayerQuestItems() const { return PlayerQuestItems; } + NotNormalLootItemMap const& GetPlayerFFAItems() const { return PlayerFFAItems; } + NotNormalLootItemMap const& GetPlayerNonQuestNonFFAConditionalItems() const { return PlayerNonQuestNonFFAConditionalItems; } + + std::vector items; + std::vector quest_items; + std::vector currencies; + + uint32 gold; + uint8 unlootedCount; + uint8 unlootedCurrency; + ObjectGuid roundRobinPlayer; // GUID of the player having the Round-Robin ownership for the loot. If 0, round robin owner has released. + LootType loot_type; // required for achievement system + uint8 maxDuplicates; // Max amount of items with the same entry that can drop (default is 1; on 25 man raid mode 3) + + // GUIDLow of container that holds this loot (item_instance.entry) + // Only set for inventory items that can be right-click looted + uint32 containerID; + + Loot(uint32 _gold = 0); + ~Loot(); + + // if loot becomes invalid this reference is used to inform the listener + void addLootValidatorRef(LootValidatorRef* pLootValidatorRef) + { + i_LootValidatorRefManager.insertFirst(pLootValidatorRef); + } + + // void clear(); + void clear() + { + for (NotNormalLootItemMap::const_iterator itr = PlayerQuestItems.begin(); itr != PlayerQuestItems.end(); ++itr) + delete itr->second; + PlayerQuestItems.clear(); + + for (NotNormalLootItemMap::const_iterator itr = PlayerFFAItems.begin(); itr != PlayerFFAItems.end(); ++itr) + delete itr->second; + PlayerFFAItems.clear(); + + for (NotNormalLootItemMap::const_iterator itr = PlayerNonQuestNonFFAConditionalItems.begin(); itr != PlayerNonQuestNonFFAConditionalItems.end(); ++itr) + delete itr->second; + PlayerNonQuestNonFFAConditionalItems.clear(); + + PlayersLooting.clear(); + items.clear(); + quest_items.clear(); + gold = 0; + unlootedCount = 0; + unlootedCurrency = 0; + roundRobinPlayer.Clear(); + loot_type = LOOT_NONE; + i_LootValidatorRefManager.clearReferences(); + } + + bool empty() const { return items.empty() && gold == 0; } + bool isLooted() const { return gold == 0 && unlootedCount == 0 && unlootedCurrency == 0; } + + void NotifyItemRemoved(uint8 lootIndex); + void NotifyQuestItemRemoved(uint8 questIndex); + void NotifyCurrencyRemoved(uint8 lootIndex); + void NotifyMoneyRemoved(); + void AddLooter(ObjectGuid GUID) { PlayersLooting.insert(GUID); } + void RemoveLooter(ObjectGuid GUID) { PlayersLooting.erase(GUID); } + + void generateMoneyLoot(uint32 minAmount, uint32 maxAmount); + bool FillLoot(uint32 lootId, LootStore const& store, Player* lootOwner, bool personal, bool noEmptyError = false, uint16 lootMode = LOOT_MODE_DEFAULT); + + // Inserts the item into the loot (called by LootTemplate processors) + void AddItem(LootStoreItem const & item); + + LootItem* LootItemInSlot(uint32 lootslot, Player* player, NotNormalLootItem** qitem = nullptr, NotNormalLootItem** ffaitem = nullptr, NotNormalLootItem** conditem = nullptr); + uint32 GetMaxSlotInLootFor(Player* player) const; + bool hasItemForAll() const; + bool hasItemFor(Player* player) const; + bool hasOverThresholdItem() const; + + void AddCurrency(uint32 entry, uint32 min, uint32 max); + LootCurrency* LootCurrencyInSlot(uint32 lootSlot, Player* player); + + private: + void FillNotNormalLootFor(Player* player, bool presentAtLooting); + NotNormalLootItemList* FillFFALoot(Player* player); + NotNormalLootItemList* FillQuestLoot(Player* player); + NotNormalLootItemList* FillNonQuestNonFFAConditionalLoot(Player* player, bool presentAtLooting); + + GuidSet PlayersLooting; + NotNormalLootItemMap PlayerQuestItems; + NotNormalLootItemMap PlayerFFAItems; + NotNormalLootItemMap PlayerNonQuestNonFFAConditionalItems; + + // All rolls are registered here. They need to know, when the loot is not valid anymore + LootValidatorRefManager i_LootValidatorRefManager; +}; + +struct LootView +{ + Loot &loot; + Player* viewer; + PermissionTypes permission; + LootView(Loot &_loot, Player* _viewer, PermissionTypes _permission = ALL_PERMISSION) + : loot(_loot), viewer(_viewer), permission(_permission) + { } +}; + +#endif // Loot_h__ diff --git a/src/server/game/Loot/LootItemStorage.cpp b/src/server/game/Loot/LootItemStorage.cpp new file mode 100644 index 00000000000..07b01379904 --- /dev/null +++ b/src/server/game/Loot/LootItemStorage.cpp @@ -0,0 +1,356 @@ +/* +* Copyright (C) 2008-2017 TrinityCore +* +* 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 . +*/ + +#include "LootItemStorage.h" +#include "DatabaseEnv.h" +#include "Item.h" +#include "ItemTemplate.h" +#include "Log.h" +#include "Loot.h" +#include "LootMgr.h" +#include "ObjectMgr.h" +#include "Player.h" + +#include +#include + +#include + +namespace +{ + std::unordered_map _lootItemStore; +} + +StoredLootItem::StoredLootItem(LootItem const& lootItem) : ItemId(lootItem.itemid), Count(lootItem.count), FollowRules(lootItem.follow_loot_rules), +FFA(lootItem.freeforall), Blocked(lootItem.is_blocked), Counted(lootItem.is_counted), UnderThreshold(lootItem.is_underthreshold), +NeedsQuest(lootItem.needs_quest), RandomPropertyId(lootItem.randomPropertyId), RandomSuffix(lootItem.randomSuffix) +{ +} + +LootItemStorage* LootItemStorage::instance() +{ + static LootItemStorage instance; + return &instance; +} + +boost::shared_mutex* LootItemStorage::GetLock() +{ + static boost::shared_mutex _lock; + return &_lock; +} + +void LootItemStorage::LoadStorageFromDB() +{ + uint32 oldMSTime = getMSTime(); + _lootItemStore.clear(); + uint32 count = 0; + + SQLTransaction trans = SQLTransaction(nullptr); + PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ITEMCONTAINER_ITEMS); + PreparedQueryResult result = CharacterDatabase.Query(stmt); + if (result) + { + do + { + Field* fields = result->Fetch(); + + uint32 key = fields[0].GetUInt32(); + auto itr = _lootItemStore.find(key); + if (itr == _lootItemStore.end()) + { + bool added; + std::tie(itr, added) = _lootItemStore.emplace(std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple(key)); + + ASSERT(added); + } + + StoredLootContainer& storedContainer = itr->second; + + LootItem lootItem; + lootItem.itemid = fields[1].GetUInt32(); + lootItem.count = fields[2].GetUInt32(); + lootItem.follow_loot_rules = fields[3].GetBool(); + lootItem.freeforall = fields[4].GetBool(); + lootItem.is_blocked = fields[5].GetBool(); + lootItem.is_counted = fields[6].GetBool(); + lootItem.is_underthreshold = fields[7].GetBool(); + lootItem.needs_quest = fields[8].GetBool(); + lootItem.randomPropertyId = fields[9].GetInt32(); + lootItem.randomSuffix = fields[10].GetUInt32(); + + storedContainer.AddLootItem(lootItem, trans); + + ++count; + } while (result->NextRow()); + + TC_LOG_INFO("server.loading", ">> Loaded %u stored item loots in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + } + else + TC_LOG_INFO("server.loading", ">> Loaded 0 stored item loots"); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ITEMCONTAINER_MONEY); + result = CharacterDatabase.Query(stmt); + if (result) + { + count = 0; + do + { + Field* fields = result->Fetch(); + + uint32 key = fields[0].GetUInt32(); + auto itr = _lootItemStore.find(key); + if (itr == _lootItemStore.end()) + { + bool added; + std::tie(itr, added) = _lootItemStore.emplace(std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple(key)); + + ASSERT(added); + } + + StoredLootContainer& storedContainer = itr->second; + storedContainer.AddMoney(fields[1].GetUInt32(), trans); + + ++count; + } while (result->NextRow()); + + TC_LOG_INFO("server.loading", ">> Loaded %u stored item money in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); + } + else + TC_LOG_INFO("server.loading", ">> Loaded 0 stored item money"); +} + +bool LootItemStorage::LoadStoredLoot(Item* item, Player* player) +{ + Loot* loot = &item->loot; + StoredLootContainer const* container = nullptr; + + // read + { + boost::shared_lock lock(*GetLock()); + + auto itr = _lootItemStore.find(loot->containerID); + if (itr == _lootItemStore.end()) + return false; + + container = &itr->second; + } + + // container is never null at this point + loot->gold = container->GetMoney(); + + if (LootTemplate const* lt = LootTemplates_Item.GetLootFor(item->GetEntry())) + { + for (auto const& storedItemPair : container->GetLootItems()) + { + LootItem li; + li.itemid = storedItemPair.first; + li.count = storedItemPair.second.Count; + li.follow_loot_rules = storedItemPair.second.FollowRules; + li.freeforall = storedItemPair.second.FFA; + li.is_blocked = storedItemPair.second.Blocked; + li.is_counted = storedItemPair.second.Counted; + li.is_underthreshold = storedItemPair.second.UnderThreshold; + li.needs_quest = storedItemPair.second.NeedsQuest; + li.randomPropertyId = storedItemPair.second.RandomPropertyId; + li.randomSuffix = storedItemPair.second.RandomSuffix; + + // Copy the extra loot conditions from the item in the loot template + lt->CopyConditions(&li); + + // If container item is in a bag, add that player as an allowed looter + if (item->GetBagSlot()) + li.AddAllowedLooter(player); + + // Finally add the LootItem to the container + loot->items.push_back(li); + + // Increment unlooted count + ++loot->unlootedCount; + } + } + + // Mark the item if it has loot so it won't be generated again on open + item->m_lootGenerated = true; + return true; +} + +void LootItemStorage::RemoveStoredMoneyForContainer(uint32 containerId) +{ + // write + boost::unique_lock lock(*GetLock()); + + auto itr = _lootItemStore.find(containerId); + if (itr == _lootItemStore.end()) + return; + + itr->second.RemoveMoney(); +} + +void LootItemStorage::RemoveStoredLootForContainer(uint32 containerId) +{ + // write + { + boost::unique_lock lock(*GetLock()); + _lootItemStore.erase(containerId); + } + + SQLTransaction trans = CharacterDatabase.BeginTransaction(); + PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_ITEMS); + stmt->setUInt32(0, containerId); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_MONEY); + stmt->setUInt32(0, containerId); + trans->Append(stmt); + + CharacterDatabase.CommitTransaction(trans); +} + +void LootItemStorage::RemoveStoredLootItemForContainer(uint32 containerId, uint32 itemId, uint32 count) +{ + // write + boost::unique_lock lock(*GetLock()); + + auto itr = _lootItemStore.find(containerId); + if (itr == _lootItemStore.end()) + return; + + itr->second.RemoveItem(itemId, count); +} + +void LootItemStorage::AddNewStoredLoot(Loot* loot, Player* player) +{ + // Saves the money and item loot associated with an openable item to the DB + if (loot->isLooted()) // no money and no loot + return; + + // read + { + boost::shared_lock lock(*GetLock()); + + auto itr = _lootItemStore.find(loot->containerID); + if (itr != _lootItemStore.end()) + { + TC_LOG_ERROR("misc", "Trying to store item loot by player: %s for container id: %u that is already in storage!", player->GetGUID().ToString().c_str(), loot->containerID); + return; + } + } + + StoredLootContainer container(loot->containerID); + + SQLTransaction trans = CharacterDatabase.BeginTransaction(); + if (loot->gold) + container.AddMoney(loot->gold, trans); + + PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_ITEMS); + stmt->setUInt32(0, loot->containerID); + trans->Append(stmt); + + for (LootItem const& li : loot->items) + { + // Conditions are not checked when loot is generated, it is checked when loot is sent to a player. + // For items that are lootable, loot is saved to the DB immediately, that means that loot can be + // saved to the DB that the player never should have gotten. This check prevents that, so that only + // items that the player should get in loot are in the DB. + // IE: Horde items are not saved to the DB for Ally players. + if (!li.AllowedForPlayer(player)) + continue; + + // Don't save currency tokens + ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(li.itemid); + if (!itemTemplate || itemTemplate->IsCurrencyToken()) + continue; + + container.AddLootItem(li, trans); + } + + CharacterDatabase.CommitTransaction(trans); + + // write + { + boost::unique_lock lock(*GetLock()); + _lootItemStore.emplace(loot->containerID, std::move(container)); + } +} + +void StoredLootContainer::AddLootItem(LootItem const& lootItem, SQLTransaction& trans) +{ + _lootItems.emplace(std::piecewise_construct, std::forward_as_tuple(lootItem.itemid), std::forward_as_tuple(lootItem)); + if (!trans) + return; + + PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ITEMCONTAINER_ITEMS); + + // container_id, item_id, item_count, follow_rules, ffa, blocked, counted, under_threshold, needs_quest, rnd_prop, rnd_suffix + stmt->setUInt32(0, _containerId); + stmt->setUInt32(1, lootItem.itemid); + stmt->setUInt32(2, lootItem.count); + stmt->setBool(3, lootItem.follow_loot_rules); + stmt->setBool(4, lootItem.freeforall); + stmt->setBool(5, lootItem.is_blocked); + stmt->setBool(6, lootItem.is_counted); + stmt->setBool(7, lootItem.is_underthreshold); + stmt->setBool(8, lootItem.needs_quest); + stmt->setInt32(9, lootItem.randomPropertyId); + stmt->setUInt32(10, lootItem.randomSuffix); + trans->Append(stmt); +} + +void StoredLootContainer::AddMoney(uint32 money, SQLTransaction& trans) +{ + _money = money; + if (!trans) + return; + + PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_MONEY); + stmt->setUInt32(0, _containerId); + trans->Append(stmt); + + stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_ITEMCONTAINER_MONEY); + stmt->setUInt32(0, _containerId); + stmt->setUInt32(1, _money); + trans->Append(stmt); +} + +void StoredLootContainer::RemoveMoney() +{ + _money = 0; + + PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_MONEY); + stmt->setUInt32(0, _containerId); + CharacterDatabase.Execute(stmt); +} + +void StoredLootContainer::RemoveItem(uint32 itemId, uint32 count) +{ + auto bounds = _lootItems.equal_range(itemId); + for (auto itr = bounds.first; itr != bounds.second; ++itr) + { + if (itr->second.Count == count) + { + _lootItems.erase(itr); + break; + } + } + + // Deletes a single item associated with an openable item from the DB + PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_ITEM); + stmt->setUInt32(0, _containerId); + stmt->setUInt32(1, itemId); + stmt->setUInt32(2, count); + CharacterDatabase.Execute(stmt); +} diff --git a/src/server/game/Loot/LootItemStorage.h b/src/server/game/Loot/LootItemStorage.h new file mode 100644 index 00000000000..822e14c2d20 --- /dev/null +++ b/src/server/game/Loot/LootItemStorage.h @@ -0,0 +1,94 @@ +/* +* Copyright (C) 2008-2017 TrinityCore +* +* 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 . +*/ + +#ifndef __LOOTITEMSTORAGE_H +#define __LOOTITEMSTORAGE_H + +#include "Define.h" +#include "DatabaseEnvFwd.h" + +#include + +class Item; +class Player; +struct Loot; +struct LootItem; +namespace boost +{ + class shared_mutex; +} + +struct StoredLootItem +{ + explicit StoredLootItem(LootItem const& lootItem); + + uint32 ItemId; + uint32 Count; + bool FollowRules; + bool FFA; + bool Blocked; + bool Counted; + bool UnderThreshold; + bool NeedsQuest; + int32 RandomPropertyId; + uint32 RandomSuffix; +}; + +class StoredLootContainer +{ + public: + typedef std::unordered_multimap StoredLootItemContainer; + + explicit StoredLootContainer(uint32 containerId) : _containerId(containerId), _money(0) { } + + void AddLootItem(LootItem const& lootItem, SQLTransaction& trans); + void AddMoney(uint32 money, SQLTransaction& trans); + + void RemoveMoney(); + void RemoveItem(uint32 itemId, uint32 count); + + uint32 GetContainer() const { return _containerId; } + uint32 GetMoney() const { return _money; } + StoredLootItemContainer const& GetLootItems() const { return _lootItems; } + + private: + StoredLootItemContainer _lootItems; + uint32 const _containerId; + uint32 _money; +}; + +class LootItemStorage +{ + public: + static LootItemStorage* instance(); + static boost::shared_mutex* GetLock(); + + void LoadStorageFromDB(); + bool LoadStoredLoot(Item* item, Player* player); + void RemoveStoredMoneyForContainer(uint32 containerId); + void RemoveStoredLootForContainer(uint32 containerId); + void RemoveStoredLootItemForContainer(uint32 containerId, uint32 itemId, uint32 count); + void AddNewStoredLoot(Loot* loot, Player* player); + + private: + LootItemStorage() { } + ~LootItemStorage() { } +}; + +#define sLootItemStorage LootItemStorage::instance() + +#endif diff --git a/src/server/game/Loot/LootMgr.cpp b/src/server/game/Loot/LootMgr.cpp index 689d7c12df6..a04115039ef 100644 --- a/src/server/game/Loot/LootMgr.cpp +++ b/src/server/game/Loot/LootMgr.cpp @@ -17,16 +17,18 @@ */ #include "LootMgr.h" +#include "Containers.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "Group.h" #include "Log.h" #include "ObjectMgr.h" -#include "World.h" -#include "Util.h" -#include "SharedDefines.h" -#include "SpellMgr.h" -#include "SpellInfo.h" -#include "Group.h" #include "Player.h" -#include "Containers.h" +#include "SharedDefines.h" +#include "SpellInfo.h" +#include "SpellMgr.h" +#include "Util.h" +#include "World.h" static Rates const qualityToRate[MAX_ITEM_QUALITY] = { @@ -53,7 +55,7 @@ LootStore LootTemplates_Skinning("skinning_loot_template", "creature s LootStore LootTemplates_Spell("spell_loot_template", "spell id (random item creating)", false); // Selects invalid loot items to be removed from group possible entries (before rolling) -struct LootGroupInvalidSelector : public std::unary_function +struct LootGroupInvalidSelector { explicit LootGroupInvalidSelector(Loot const& loot, uint16 lootMode) : _loot(loot), _lootMode(lootMode) { } @@ -100,7 +102,7 @@ class LootTemplate::LootGroup // A set of loot def LootStoreItemList ExplicitlyChanced; // Entries with chances defined in DB LootStoreItemList EqualChanced; // Zero chances - every entry takes the same chance - LootStoreItem const* Roll(Loot& loot, uint16 lootMode) const; // Rolls an item from the group, returns NULL if all miss their chances + LootStoreItem const* Roll(Loot& loot, uint16 lootMode) const; // Rolls an item from the group, returns nullptr if all miss their chances // This class must never be copied - storing pointers LootGroup(LootGroup const&); @@ -134,7 +136,6 @@ uint32 LootStore::LoadLootTable() // 0 1 2 3 4 5 6 QueryResult result = WorldDatabase.PQuery("SELECT Entry, Item, Reference, Chance, QuestRequired, LootMode, GroupId, MinCount, MaxCount FROM %s", GetName()); - if (!result) return 0; @@ -228,7 +229,7 @@ LootTemplate const* LootStore::GetLootFor(uint32 loot_id) const LootTemplateMap::const_iterator tab = m_LootTemplates.find(loot_id); if (tab == m_LootTemplates.end()) - return NULL; + return nullptr; return tab->second; } @@ -238,7 +239,7 @@ LootTemplate* LootStore::GetLootForConditionFill(uint32 loot_id) LootTemplateMap::iterator tab = m_LootTemplates.find(loot_id); if (tab == m_LootTemplates.end()) - return NULL; + return nullptr; return tab->second; } @@ -271,7 +272,7 @@ void LootStore::ReportNonExistingId(uint32 lootId) const TC_LOG_ERROR("sql.sql", "Table '%s' Entry %d does not exist", GetName(), lootId); } -void LootStore::ReportNonExistingId(uint32 lootId, const char* ownerType, uint32 ownerId) const +void LootStore::ReportNonExistingId(uint32 lootId, char const* ownerType, uint32 ownerId) const { TC_LOG_ERROR("sql.sql", "Table '%s' Entry %d does not exist but it is used by %s %d", GetName(), lootId, ownerType, ownerId); } @@ -347,804 +348,6 @@ bool LootStoreItem::IsValid(LootStore const& store, uint32 entry) const return true; // Referenced template existence is checked at whole store level } -// -// --------- LootItem --------- -// - -// Constructor, copies most fields from LootStoreItem and generates random count -LootItem::LootItem(LootStoreItem const& li) -{ - itemid = li.itemid; - conditions = li.conditions; - - ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemid); - freeforall = proto && (proto->Flags & ITEM_FLAG_MULTI_DROP); - follow_loot_rules = proto && (proto->FlagsCu & ITEM_FLAGS_CU_FOLLOW_LOOT_RULES); - - needs_quest = li.needs_quest; - - randomSuffix = GenerateEnchSuffixFactor(itemid); - randomPropertyId = Item::GenerateItemRandomPropertyId(itemid); - count = 0; - is_looted = 0; - is_blocked = 0; - is_underthreshold = 0; - is_counted = 0; - rollWinnerGUID = ObjectGuid::Empty; - canSave = true; -} - -// Basic checks for player/item compatibility - if false no chance to see the item in the loot -bool LootItem::AllowedForPlayer(Player const* player) const -{ - // DB conditions check - if (!sConditionMgr->IsObjectMeetToConditions(const_cast(player), conditions)) - return false; - - ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(itemid); - if (!pProto) - return false; - - // not show loot for players without profession or those who already know the recipe - if ((pProto->Flags & ITEM_FLAG_HIDE_UNUSABLE_RECIPE) && (!player->HasSkill(pProto->RequiredSkill) || player->HasSpell(pProto->Spells[1].SpellId))) - return false; - - // not show loot for not own team - if ((pProto->Flags2 & ITEM_FLAG2_FACTION_HORDE) && player->GetTeam() != HORDE) - return false; - - if ((pProto->Flags2 & ITEM_FLAG2_FACTION_ALLIANCE) && player->GetTeam() != ALLIANCE) - return false; - - // check quest requirements - if (!(pProto->FlagsCu & ITEM_FLAGS_CU_IGNORE_QUEST_STATUS) && ((needs_quest || (pProto->StartQuest && player->GetQuestStatus(pProto->StartQuest) != QUEST_STATUS_NONE)) && !player->HasQuestForItem(itemid))) - return false; - - return true; -} - -void LootItem::AddAllowedLooter(const Player* player) -{ - allowedGUIDs.insert(player->GetGUID().GetCounter()); -} - -// -// --------- Loot --------- -// - -// Inserts the item into the loot (called by LootTemplate processors) -void Loot::AddItem(LootStoreItem const& item) -{ - ItemTemplate const* proto = sObjectMgr->GetItemTemplate(item.itemid); - if (!proto) - return; - - uint32 count = urand(item.mincount, item.maxcount); - uint32 stacks = count / proto->GetMaxStackSize() + ((count % proto->GetMaxStackSize()) ? 1 : 0); - - std::vector& lootItems = item.needs_quest ? quest_items : items; - uint32 limit = item.needs_quest ? MAX_NR_QUEST_ITEMS : MAX_NR_LOOT_ITEMS; - - for (uint32 i = 0; i < stacks && lootItems.size() < limit; ++i) - { - LootItem generatedLoot(item); - generatedLoot.count = std::min(count, proto->GetMaxStackSize()); - lootItems.push_back(generatedLoot); - count -= proto->GetMaxStackSize(); - - // 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_FLAG_MULTI_DROP)) - ++unlootedCount; - } -} - -void Loot::AddCurrency(uint32 entry, uint32 min, uint32 max) -{ - uint32 amount = urand(min, max); - - currencies.push_back(LootCurrency(entry, amount)); - - unlootedCurrency++; -} - -LootCurrency* Loot::LootCurrencyInSlot(uint32 lootSlot, Player* /*player*/) -{ - if (currencies[lootSlot].looted) - return NULL; - - currencies[lootSlot].looted = true; - - unlootedCurrency--; - - return &(currencies[lootSlot]); -} - -// Calls processor of corresponding LootTemplate (which handles everything including references) -bool Loot::FillLoot(uint32 lootId, LootStore const& store, Player* lootOwner, bool personal, bool noEmptyError, uint16 lootMode /*= LOOT_MODE_DEFAULT*/) -{ - // Must be provided - if (!lootOwner) - return false; - - LootTemplate const* tab = store.GetLootFor(lootId); - - if (!tab) - { - if (!noEmptyError) - TC_LOG_ERROR("sql.sql", "Table '%s' loot id #%u used but it doesn't have records.", store.GetName(), lootId); - return false; - } - - items.reserve(MAX_NR_LOOT_ITEMS); - quest_items.reserve(MAX_NR_QUEST_ITEMS); - - tab->Process(*this, store.IsRatesAllowed(), lootMode); // Processing is done there, callback via Loot::AddItem() - - // Setting access rights for group loot case - Group* group = lootOwner->GetGroup(); - if (!personal && group) - { - roundRobinPlayer = lootOwner->GetGUID(); - - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) - if (Player* player = itr->GetSource()) // should actually be looted object instead of lootOwner but looter has to be really close so doesnt really matter - if (player->IsInMap(lootOwner)) - FillNotNormalLootFor(player, player->IsAtGroupRewardDistance(lootOwner)); - - for (uint8 i = 0; i < items.size(); ++i) - { - if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(items[i].itemid)) - if (proto->Quality < uint32(group->GetLootThreshold())) - items[i].is_underthreshold = true; - } - } - // ... for personal loot - else - FillNotNormalLootFor(lootOwner, true); - - return true; -} - -void Loot::FillNotNormalLootFor(Player* player, bool presentAtLooting) -{ - ObjectGuid::LowType plguid = player->GetGUID().GetCounter(); - - NotNormalLootItemMap::const_iterator qmapitr = PlayerQuestItems.find(plguid); - if (qmapitr == PlayerQuestItems.end()) - FillQuestLoot(player); - - qmapitr = PlayerFFAItems.find(plguid); - if (qmapitr == PlayerFFAItems.end()) - FillFFALoot(player); - - qmapitr = PlayerNonQuestNonFFAConditionalItems.find(plguid); - if (qmapitr == PlayerNonQuestNonFFAConditionalItems.end()) - FillNonQuestNonFFAConditionalLoot(player, presentAtLooting); - - // if not auto-processed player will have to come and pick it up manually - if (!presentAtLooting) - return; - - // Process currency items - uint32 max_slot = GetMaxSlotInLootFor(player); - LootItem const* item = NULL; - uint32 itemsSize = uint32(items.size()); - for (uint32 i = 0; i < max_slot; ++i) - { - if (i < items.size()) - item = &items[i]; - else - item = &quest_items[i-itemsSize]; - - if (!item->is_looted && item->freeforall && item->AllowedForPlayer(player)) - if (ItemTemplate const* proto = sObjectMgr->GetItemTemplate(item->itemid)) - if (proto->IsCurrencyToken()) - player->StoreLootItem(i, this); - } -} - -NotNormalLootItemList* Loot::FillFFALoot(Player* player) -{ - NotNormalLootItemList* ql = new NotNormalLootItemList(); - - for (uint8 i = 0; i < items.size(); ++i) - { - LootItem &item = items[i]; - if (!item.is_looted && item.freeforall && item.AllowedForPlayer(player)) - { - ql->push_back(NotNormalLootItem(i)); - ++unlootedCount; - } - } - if (ql->empty()) - { - delete ql; - return NULL; - } - - PlayerFFAItems[player->GetGUID().GetCounter()] = ql; - return ql; -} - -NotNormalLootItemList* Loot::FillQuestLoot(Player* player) -{ - if (items.size() == MAX_NR_LOOT_ITEMS) - return NULL; - - NotNormalLootItemList* ql = new NotNormalLootItemList(); - - for (uint8 i = 0; i < quest_items.size(); ++i) - { - LootItem &item = quest_items[i]; - - if (!item.is_looted && (item.AllowedForPlayer(player) || (item.follow_loot_rules && player->GetGroup() && ((player->GetGroup()->GetLootMethod() == MASTER_LOOT && player->GetGroup()->GetMasterLooterGuid() == player->GetGUID()) || player->GetGroup()->GetLootMethod() != MASTER_LOOT)))) - { - ql->push_back(NotNormalLootItem(i)); - - // quest items get blocked when they first appear in a - // player's quest vector - // - // increase once if one looter only, looter-times if free for all - if (item.freeforall || !item.is_blocked) - ++unlootedCount; - if (!player->GetGroup() || (player->GetGroup()->GetLootMethod() != GROUP_LOOT && player->GetGroup()->GetLootMethod() != ROUND_ROBIN)) - item.is_blocked = true; - - if (items.size() + ql->size() == MAX_NR_LOOT_ITEMS) - break; - } - } - if (ql->empty()) - { - delete ql; - return NULL; - } - - PlayerQuestItems[player->GetGUID().GetCounter()] = ql; - return ql; -} - -NotNormalLootItemList* Loot::FillNonQuestNonFFAConditionalLoot(Player* player, bool presentAtLooting) -{ - NotNormalLootItemList* ql = new NotNormalLootItemList(); - - for (uint8 i = 0; i < items.size(); ++i) - { - LootItem &item = items[i]; - if (!item.is_looted && !item.freeforall && (item.AllowedForPlayer(player))) - { - if (presentAtLooting) - item.AddAllowedLooter(player); - if (!item.conditions.empty()) - { - ql->push_back(NotNormalLootItem(i)); - if (!item.is_counted) - { - ++unlootedCount; - item.is_counted = true; - } - } - } - } - if (ql->empty()) - { - delete ql; - return NULL; - } - - PlayerNonQuestNonFFAConditionalItems[player->GetGUID().GetCounter()] = ql; - return ql; -} - -//=================================================== - -void Loot::NotifyItemRemoved(uint8 lootIndex) -{ - // notify all players that are looting this that the item was removed - // convert the index to the slot the player sees - GuidSet::iterator i_next; - for (GuidSet::iterator i = PlayersLooting.begin(); i != PlayersLooting.end(); i = i_next) - { - i_next = i; - ++i_next; - if (Player* player = ObjectAccessor::FindPlayer(*i)) - player->SendNotifyLootItemRemoved(lootIndex); - else - PlayersLooting.erase(i); - } -} - -void Loot::NotifyMoneyRemoved() -{ - // notify all players that are looting this that the money was removed - GuidSet::iterator i_next; - for (GuidSet::iterator i = PlayersLooting.begin(); i != PlayersLooting.end(); i = i_next) - { - i_next = i; - ++i_next; - if (Player* player = ObjectAccessor::FindPlayer(*i)) - player->SendNotifyLootMoneyRemoved(); - else - PlayersLooting.erase(i); - } -} - -void Loot::NotifyCurrencyRemoved(uint8 lootIndex) -{ - // notify all players that are looting this that the currency was removed - GuidSet::iterator i_next; - for (GuidSet::iterator i = PlayersLooting.begin(); i != PlayersLooting.end(); i = i_next) - { - i_next = i; - ++i_next; - if (Player* player = ObjectAccessor::FindPlayer(*i)) - player->SendNotifyCurrencyLootRemoved(lootIndex); - else - PlayersLooting.erase(i); - } -} - -void Loot::NotifyQuestItemRemoved(uint8 questIndex) -{ - // when a free for all questitem is looted - // all players will get notified of it being removed - // (other questitems can be looted by each group member) - // bit inefficient but isn't called often - - GuidSet::iterator i_next; - for (GuidSet::iterator i = PlayersLooting.begin(); i != PlayersLooting.end(); i = i_next) - { - i_next = i; - ++i_next; - if (Player* player = ObjectAccessor::FindPlayer(*i)) - { - NotNormalLootItemMap::const_iterator pq = PlayerQuestItems.find(player->GetGUID().GetCounter()); - if (pq != PlayerQuestItems.end() && pq->second) - { - // find where/if the player has the given item in it's vector - NotNormalLootItemList& pql = *pq->second; - - uint8 j; - for (j = 0; j < pql.size(); ++j) - if (pql[j].index == questIndex) - break; - - if (j < pql.size()) - player->SendNotifyLootItemRemoved(items.size()+j); - } - } - else - PlayersLooting.erase(i); - } -} - -void Loot::generateMoneyLoot(uint32 minAmount, uint32 maxAmount) -{ - if (maxAmount > 0) - { - if (maxAmount <= minAmount) - gold = uint32(maxAmount * sWorld->getRate(RATE_DROP_MONEY)); - else if ((maxAmount - minAmount) < 32700) - gold = uint32(urand(minAmount, maxAmount) * sWorld->getRate(RATE_DROP_MONEY)); - else - gold = uint32(urand(minAmount >> 8, maxAmount >> 8) * sWorld->getRate(RATE_DROP_MONEY)) << 8; - } -} - -void Loot::DeleteLootItemFromContainerItemDB(uint32 itemID) -{ - // Deletes a single item associated with an openable item from the DB - PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_ITEM); - stmt->setUInt32(0, containerID); - stmt->setUInt32(1, itemID); - CharacterDatabase.Execute(stmt); - - // Mark the item looted to prevent resaving - for (LootItemList::iterator _itr = items.begin(); _itr != items.end(); ++_itr) - { - if (_itr->itemid != itemID) - continue; - - _itr->canSave = false; - break; - } -} - -void Loot::DeleteLootMoneyFromContainerItemDB() -{ - // Deletes money loot associated with an openable item from the DB - PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEMCONTAINER_MONEY); - stmt->setUInt32(0, containerID); - CharacterDatabase.Execute(stmt); -} - -LootItem* Loot::LootItemInSlot(uint32 lootSlot, Player* player, NotNormalLootItem* *qitem, NotNormalLootItem* *ffaitem, NotNormalLootItem* *conditem) -{ - LootItem* item = NULL; - bool is_looted = true; - if (lootSlot >= items.size()) - { - uint32 questSlot = lootSlot - items.size(); - NotNormalLootItemMap::const_iterator itr = PlayerQuestItems.find(player->GetGUID().GetCounter()); - if (itr != PlayerQuestItems.end() && questSlot < itr->second->size()) - { - NotNormalLootItem* qitem2 = &itr->second->at(questSlot); - if (qitem) - *qitem = qitem2; - item = &quest_items[qitem2->index]; - is_looted = qitem2->is_looted; - } - } - else - { - item = &items[lootSlot]; - is_looted = item->is_looted; - if (item->freeforall) - { - NotNormalLootItemMap::const_iterator itr = PlayerFFAItems.find(player->GetGUID().GetCounter()); - if (itr != PlayerFFAItems.end()) - { - for (NotNormalLootItemList::const_iterator iter=itr->second->begin(); iter!= itr->second->end(); ++iter) - if (iter->index == lootSlot) - { - NotNormalLootItem* ffaitem2 = (NotNormalLootItem*)&(*iter); - if (ffaitem) - *ffaitem = ffaitem2; - is_looted = ffaitem2->is_looted; - break; - } - } - } - else if (!item->conditions.empty()) - { - NotNormalLootItemMap::const_iterator itr = PlayerNonQuestNonFFAConditionalItems.find(player->GetGUID().GetCounter()); - if (itr != PlayerNonQuestNonFFAConditionalItems.end()) - { - for (NotNormalLootItemList::const_iterator iter=itr->second->begin(); iter!= itr->second->end(); ++iter) - { - if (iter->index == lootSlot) - { - NotNormalLootItem* conditem2 = (NotNormalLootItem*)&(*iter); - if (conditem) - *conditem = conditem2; - is_looted = conditem2->is_looted; - break; - } - } - } - } - } - - if (is_looted) - return NULL; - - return item; -} - -uint32 Loot::GetMaxSlotInLootFor(Player* player) const -{ - NotNormalLootItemMap::const_iterator itr = PlayerQuestItems.find(player->GetGUID().GetCounter()); - 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 -{ - NotNormalLootItemMap const& lootPlayerQuestItems = GetPlayerQuestItems(); - NotNormalLootItemMap::const_iterator q_itr = lootPlayerQuestItems.find(player->GetGUID().GetCounter()); - if (q_itr != lootPlayerQuestItems.end()) - { - NotNormalLootItemList* q_list = q_itr->second; - for (NotNormalLootItemList::const_iterator qi = q_list->begin(); qi != q_list->end(); ++qi) - { - const LootItem &item = quest_items[qi->index]; - if (!qi->is_looted && !item.is_looted) - return true; - } - } - - NotNormalLootItemMap const& lootPlayerFFAItems = GetPlayerFFAItems(); - NotNormalLootItemMap::const_iterator ffa_itr = lootPlayerFFAItems.find(player->GetGUID().GetCounter()); - if (ffa_itr != lootPlayerFFAItems.end()) - { - NotNormalLootItemList* ffa_list = ffa_itr->second; - for (NotNormalLootItemList::const_iterator fi = ffa_list->begin(); fi != ffa_list->end(); ++fi) - { - const LootItem &item = items[fi->index]; - if (!fi->is_looted && !item.is_looted) - return true; - } - } - - NotNormalLootItemMap const& lootPlayerNonQuestNonFFAConditionalItems = GetPlayerNonQuestNonFFAConditionalItems(); - NotNormalLootItemMap::const_iterator nn_itr = lootPlayerNonQuestNonFFAConditionalItems.find(player->GetGUID().GetCounter()); - if (nn_itr != lootPlayerNonQuestNonFFAConditionalItems.end()) - { - NotNormalLootItemList* conditional_list = nn_itr->second; - for (NotNormalLootItemList::const_iterator ci = conditional_list->begin(); ci != conditional_list->end(); ++ci) - { - const LootItem &item = items[ci->index]; - if (!ci->is_looted && !item.is_looted) - return true; - } - } - - return false; -} - -// return true if there is any item over the group threshold (i.e. not underthreshold). -bool Loot::hasOverThresholdItem() const -{ - for (uint8 i = 0; i < items.size(); ++i) - { - if (!items[i].is_looted && !items[i].is_underthreshold && !items[i].freeforall) - return true; - } - - return false; -} - -ByteBuffer& operator<<(ByteBuffer& b, LootItem const& li) -{ - b << uint32(li.itemid); - b << uint32(li.count); // nr of items of this type - b << uint32(ASSERT_NOTNULL(sObjectMgr->GetItemTemplate(li.itemid))->DisplayInfoID); - b << uint32(li.randomSuffix); - b << uint32(li.randomPropertyId); - //b << uint8(0); // slot type - will send after this function call - return b; -} - -ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv) -{ - if (lv.permission == NONE_PERMISSION) - { - b << uint32(0); // gold - b << uint8(0); // item count - b << uint8(0); // currency count - return b; - } - - Loot &l = lv.loot; - - uint8 itemsShown = 0; - uint8 currenciesShown = 0; - - b << uint32(l.gold); //gold - - size_t count_pos = b.wpos(); // pos of item count byte - b << uint8(0); // item count placeholder - size_t currency_count_pos = b.wpos(); // pos of currency count byte - b << uint8(0); // currency count placeholder - - switch (lv.permission) - { - case GROUP_PERMISSION: - case MASTER_PERMISSION: - case RESTRICTED_PERMISSION: - { - // if you are not the round-robin group looter, you can only see - // blocked rolled items and quest items, and !ffa items - for (uint8 i = 0; i < l.items.size(); ++i) - { - if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) - { - uint8 slot_type; - - if (l.items[i].is_blocked) // for ML & restricted is_blocked = !is_underthreshold - { - switch (lv.permission) - { - case GROUP_PERMISSION: - slot_type = LOOT_SLOT_TYPE_ROLL_ONGOING; - break; - case MASTER_PERMISSION: - { - if (lv.viewer->GetGroup() && lv.viewer->GetGroup()->GetMasterLooterGuid() == lv.viewer->GetGUID()) - slot_type = LOOT_SLOT_TYPE_MASTER; - else - slot_type = LOOT_SLOT_TYPE_LOCKED; - break; - } - case RESTRICTED_PERMISSION: - slot_type = LOOT_SLOT_TYPE_LOCKED; - break; - default: - continue; - } - } - else if (!l.items[i].rollWinnerGUID.IsEmpty()) - { - if (l.items[i].rollWinnerGUID == lv.viewer->GetGUID()) - slot_type = LOOT_SLOT_TYPE_OWNER; - else - continue; - } - else if (l.roundRobinPlayer.IsEmpty() || lv.viewer->GetGUID() == l.roundRobinPlayer || !l.items[i].is_underthreshold) - { - // no round robin owner or he has released the loot - // or it IS the round robin group owner - // => item is lootable - slot_type = LOOT_SLOT_TYPE_ALLOW_LOOT; - } - else - // item shall not be displayed. - continue; - - b << uint8(i) << l.items[i]; - b << uint8(slot_type); - ++itemsShown; - } - } - break; - } - case ROUND_ROBIN_PERMISSION: - { - for (uint8 i = 0; i < l.items.size(); ++i) - { - if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) - { - if (!l.roundRobinPlayer.IsEmpty() && lv.viewer->GetGUID() != l.roundRobinPlayer) - // item shall not be displayed. - continue; - - b << uint8(i) << l.items[i]; - b << uint8(LOOT_SLOT_TYPE_ALLOW_LOOT); - ++itemsShown; - } - } - break; - } - case ALL_PERMISSION: - case OWNER_PERMISSION: - { - uint8 slot_type = lv.permission == OWNER_PERMISSION ? LOOT_SLOT_TYPE_OWNER : LOOT_SLOT_TYPE_ALLOW_LOOT; - for (uint8 i = 0; i < l.items.size(); ++i) - { - if (!l.items[i].is_looted && !l.items[i].freeforall && l.items[i].conditions.empty() && l.items[i].AllowedForPlayer(lv.viewer)) - { - b << uint8(i) << l.items[i]; - b << uint8(slot_type); - ++itemsShown; - } - } - break; - } - default: - return b; - } - - LootSlotType slotType = lv.permission == OWNER_PERMISSION ? LOOT_SLOT_TYPE_OWNER : LOOT_SLOT_TYPE_ALLOW_LOOT; - NotNormalLootItemMap const& lootPlayerQuestItems = l.GetPlayerQuestItems(); - NotNormalLootItemMap::const_iterator q_itr = lootPlayerQuestItems.find(lv.viewer->GetGUID().GetCounter()); - if (q_itr != lootPlayerQuestItems.end()) - { - NotNormalLootItemList* q_list = q_itr->second; - for (NotNormalLootItemList::const_iterator qi = q_list->begin(); qi != q_list->end(); ++qi) - { - LootItem &item = l.quest_items[qi->index]; - if (!qi->is_looted && !item.is_looted) - { - b << uint8(l.items.size() + (qi - q_list->begin())); - b << item; - if (item.follow_loot_rules) - { - switch (lv.permission) - { - case MASTER_PERMISSION: - b << uint8(LOOT_SLOT_TYPE_MASTER); - break; - case RESTRICTED_PERMISSION: - b << (item.is_blocked ? uint8(LOOT_SLOT_TYPE_LOCKED) : uint8(slotType)); - break; - case GROUP_PERMISSION: - case ROUND_ROBIN_PERMISSION: - if (!item.is_blocked) - b << uint8(LOOT_SLOT_TYPE_ALLOW_LOOT); - else - b << uint8(LOOT_SLOT_TYPE_ROLL_ONGOING); - break; - default: - b << uint8(slotType); - break; - } - } - else - b << uint8(slotType); - ++itemsShown; - } - } - } - - NotNormalLootItemMap const& lootPlayerFFAItems = l.GetPlayerFFAItems(); - NotNormalLootItemMap::const_iterator ffa_itr = lootPlayerFFAItems.find(lv.viewer->GetGUID().GetCounter()); - if (ffa_itr != lootPlayerFFAItems.end()) - { - NotNormalLootItemList* ffa_list = ffa_itr->second; - for (NotNormalLootItemList::const_iterator fi = ffa_list->begin(); fi != ffa_list->end(); ++fi) - { - LootItem &item = l.items[fi->index]; - if (!fi->is_looted && !item.is_looted) - { - b << uint8(fi->index); - b << item; - b << uint8(slotType); - ++itemsShown; - } - } - } - - NotNormalLootItemMap const& lootPlayerNonQuestNonFFAConditionalItems = l.GetPlayerNonQuestNonFFAConditionalItems(); - NotNormalLootItemMap::const_iterator nn_itr = lootPlayerNonQuestNonFFAConditionalItems.find(lv.viewer->GetGUID().GetCounter()); - if (nn_itr != lootPlayerNonQuestNonFFAConditionalItems.end()) - { - NotNormalLootItemList* conditional_list = nn_itr->second; - for (NotNormalLootItemList::const_iterator ci = conditional_list->begin(); ci != conditional_list->end(); ++ci) - { - LootItem &item = l.items[ci->index]; - if (!ci->is_looted && !item.is_looted) - { - b << uint8(ci->index); - b << item; - switch (lv.permission) - { - case MASTER_PERMISSION: - b << uint8(LOOT_SLOT_TYPE_MASTER); - break; - case RESTRICTED_PERMISSION: - b << (item.is_blocked ? uint8(LOOT_SLOT_TYPE_LOCKED) : uint8(slotType)); - break; - case GROUP_PERMISSION: - case ROUND_ROBIN_PERMISSION: - if (!item.is_blocked) - b << uint8(LOOT_SLOT_TYPE_ALLOW_LOOT); - else - b << uint8(LOOT_SLOT_TYPE_ROLL_ONGOING); - break; - default: - b << uint8(slotType); - break; - } - ++itemsShown; - } - } - } - - for (uint8 i = 0; i < l.currencies.size(); ++i) - { - if (l.currencies[i].count == 0 || l.currencies[i].id == 0 || l.currencies[i].looted) - continue; - - l.currencies[i].index = currenciesShown + itemsShown; - - b << uint8(l.currencies[i].index); - b << uint32(l.currencies[i].id); - b << uint32(l.currencies[i].count); - ++currenciesShown; - } - - //update number of items and currencies shown - b.put(count_pos, itemsShown); - b.put(currency_count_pos, currenciesShown); - - return b; -} - // // --------- LootTemplate::LootGroup --------- // @@ -1173,7 +376,7 @@ void LootTemplate::LootGroup::AddEntry(LootStoreItem* item) EqualChanced.push_back(item); } -// Rolls an item from the group, returns NULL if all miss their chances +// Rolls an item from the group, returns nullptr if all miss their chances LootStoreItem const* LootTemplate::LootGroup::Roll(Loot& loot, uint16 lootMode) const { LootStoreItemList possibleLoot = ExplicitlyChanced; @@ -1200,7 +403,7 @@ LootStoreItem const* LootTemplate::LootGroup::Roll(Loot& loot, uint16 lootMode) if (!possibleLoot.empty()) // If nothing selected yet - an item is taken from equal-chanced part return Trinity::Containers::SelectRandomContainerElement(possibleLoot); - return NULL; // Empty drop from the group + return nullptr; // Empty drop from the group } // True if group includes at least 1 quest drop entry @@ -1326,7 +529,7 @@ void LootTemplate::AddEntry(LootStoreItem* item) if (item->groupid > 0 && item->reference == 0) // Group { if (item->groupid >= Groups.size()) - Groups.resize(item->groupid, NULL); // Adds new group the the loot template if needed + Groups.resize(item->groupid, nullptr); // Adds new group the the loot template if needed if (!Groups[item->groupid - 1]) Groups[item->groupid - 1] = new LootGroup(); diff --git a/src/server/game/Loot/LootMgr.h b/src/server/game/Loot/LootMgr.h index e4e66cd4167..705d8db5398 100644 --- a/src/server/game/Loot/LootMgr.h +++ b/src/server/game/Loot/LootMgr.h @@ -19,110 +19,18 @@ #ifndef TRINITY_LOOTMGR_H #define TRINITY_LOOTMGR_H -#include "ItemEnchantmentMgr.h" -#include "ByteBuffer.h" -#include "RefManager.h" -#include "SharedDefines.h" +#include "Define.h" #include "ConditionMgr.h" #include "ObjectGuid.h" -#include -#include +#include "SharedDefines.h" #include +#include -enum RollType -{ - ROLL_PASS = 0, - ROLL_NEED = 1, - ROLL_GREED = 2, - ROLL_DISENCHANT = 3, - MAX_ROLL_TYPE = 4 -}; - -enum RollMask -{ - ROLL_FLAG_TYPE_PASS = 0x01, - ROLL_FLAG_TYPE_NEED = 0x02, - ROLL_FLAG_TYPE_GREED = 0x04, - ROLL_FLAG_TYPE_DISENCHANT = 0x08, - - ROLL_ALL_TYPE_NO_DISENCHANT = 0x07, - ROLL_ALL_TYPE_MASK = 0x0F -}; - -#define MAX_NR_LOOT_ITEMS 16 -// note: the client cannot show more than 16 items total -#define MAX_NR_QUEST_ITEMS 32 -// unrelated to the number of quest items shown, just for reserve - -enum LootMethod : uint8 -{ - FREE_FOR_ALL = 0, - ROUND_ROBIN = 1, - MASTER_LOOT = 2, - GROUP_LOOT = 3, - NEED_BEFORE_GREED = 4 -}; - -enum PermissionTypes -{ - ALL_PERMISSION = 0, - GROUP_PERMISSION = 1, - MASTER_PERMISSION = 2, - RESTRICTED_PERMISSION = 3, - ROUND_ROBIN_PERMISSION = 4, - OWNER_PERMISSION = 5, - NONE_PERMISSION = 6 -}; - -enum LootType : uint8 -{ - LOOT_NONE = 0, - - LOOT_CORPSE = 1, - LOOT_PICKPOCKETING = 2, - LOOT_FISHING = 3, - LOOT_DISENCHANTING = 4, - // ignored always by client - LOOT_SKINNING = 6, - LOOT_PROSPECTING = 7, - LOOT_MILLING = 8, - - LOOT_ARCHAEOLOGY = 10, - - LOOT_FISHINGHOLE = 20, // unsupported by client, sending LOOT_FISHING instead - LOOT_INSIGNIA = 21, // unsupported by client, sending LOOT_CORPSE instead - LOOT_FISHING_JUNK = 22 // unsupported by client, sending LOOT_FISHING instead -}; - -enum LootError -{ - LOOT_ERROR_DIDNT_KILL = 0, // You don't have permission to loot that corpse. - LOOT_ERROR_TOO_FAR = 4, // You are too far away to loot that corpse. - LOOT_ERROR_BAD_FACING = 5, // You must be facing the corpse to loot it. - LOOT_ERROR_LOCKED = 6, // Someone is already looting that corpse. - LOOT_ERROR_NOTSTANDING = 8, // You need to be standing up to loot something! - LOOT_ERROR_STUNNED = 9, // You can't loot anything while stunned! - LOOT_ERROR_PLAYER_NOT_FOUND = 10, // Player not found - LOOT_ERROR_PLAY_TIME_EXCEEDED = 11, // Maximum play time exceeded - LOOT_ERROR_MASTER_INV_FULL = 12, // That player's inventory is full - LOOT_ERROR_MASTER_UNIQUE_ITEM = 13, // Player has too many of that item already - LOOT_ERROR_MASTER_OTHER = 14, // Can't assign item to that player - LOOT_ERROR_ALREADY_PICKPOCKETED = 15, // Your target has already had its pockets picked - LOOT_ERROR_NOT_WHILE_SHAPESHIFTED = 16 // You can't do that while shapeshifted. -}; - -// type of Loot Item in Loot View -enum LootSlotType -{ - LOOT_SLOT_TYPE_ALLOW_LOOT = 0, // player can loot the item. - LOOT_SLOT_TYPE_ROLL_ONGOING = 1, // roll is ongoing. player cannot loot. - LOOT_SLOT_TYPE_MASTER = 2, // item can only be distributed by group loot master. - LOOT_SLOT_TYPE_LOCKED = 3, // item is shown in red. player cannot loot. - LOOT_SLOT_TYPE_OWNER = 4 // ignore binding confirmation and etc, for single player looting -}; - -class Player; class LootStore; +class LootTemplate; +class Player; +struct Loot; +struct LootItem; struct TC_GAME_API LootStoreItem { @@ -148,73 +56,6 @@ struct TC_GAME_API LootStoreItem // Checks correctness of values }; -typedef std::set AllowedLooterSet; - -struct TC_GAME_API LootItem -{ - uint32 itemid; - uint32 randomSuffix; - int32 randomPropertyId; - ConditionContainer conditions; // additional loot condition - AllowedLooterSet allowedGUIDs; - ObjectGuid rollWinnerGUID; // Stores the guid of person who won loot, if his bags are full only he can see the item in loot list! - uint8 count : 8; - bool is_looted : 1; - bool is_blocked : 1; - bool freeforall : 1; // free for all - bool is_underthreshold : 1; - bool is_counted : 1; - bool needs_quest : 1; // quest drop - bool follow_loot_rules : 1; - bool canSave; - - // Constructor, copies most fields from LootStoreItem, generates random count and random suffixes/properties - // Should be called for non-reference LootStoreItem entries only (reference = 0) - explicit LootItem(LootStoreItem const& li); - - // Empty constructor for creating an empty LootItem to be filled in with DB data - LootItem() : itemid(0), randomSuffix(0), randomPropertyId(0), count(0), is_looted(false), is_blocked(false), - freeforall(false), is_underthreshold(false), is_counted(false), needs_quest(false), follow_loot_rules(false), - canSave(true){ }; - - // Basic checks for player/item compatibility - if false no chance to see the item in the loot - bool AllowedForPlayer(Player const* player) const; - void AddAllowedLooter(Player const* player); - const AllowedLooterSet & GetAllowedLooters() const { return allowedGUIDs; } -}; - -struct NotNormalLootItem -{ - uint8 index; // position in quest_items or items; - bool is_looted; - - NotNormalLootItem() - : index(0), is_looted(false) { } - - NotNormalLootItem(uint8 _index, bool _islooted = false) - : index(_index), is_looted(_islooted) { } -}; - -struct LootCurrency -{ - uint8 index; - uint32 id; - uint32 count; - bool looted; - - LootCurrency() - : index(0), id(0), count(0), looted(false) { } - - LootCurrency(uint32 _id, uint32 _count) - : index(0), id(_id), count(_count), looted(false) { } -}; - -struct Loot; -class LootTemplate; - -typedef std::vector NotNormalLootItemList; -typedef std::vector LootItemList; -typedef std::map NotNormalLootItemMap; typedef std::list LootStoreItemList; typedef std::unordered_map LootTemplateMap; @@ -231,10 +72,10 @@ class TC_GAME_API LootStore void Verify() const; uint32 LoadAndCollectLootIds(LootIdSet& ids_set); - void CheckLootRefs(LootIdSet* ref_set = NULL) const; // check existence reference and remove it from ref_set + void CheckLootRefs(LootIdSet* ref_set = nullptr) const; // check existence reference and remove it from ref_set void ReportUnusedIds(LootIdSet const& ids_set) const; void ReportNonExistingId(uint32 lootId) const; - void ReportNonExistingId(uint32 lootId, const char* ownerType, uint32 ownerId) const; + void ReportNonExistingId(uint32 lootId, char const* ownerType, uint32 ownerId) const; bool HaveLootFor(uint32 loot_id) const { return m_LootTemplates.find(loot_id) != m_LootTemplates.end(); } bool HaveQuestLootFor(uint32 loot_id) const; @@ -293,146 +134,6 @@ class TC_GAME_API LootTemplate LootTemplate& operator=(LootTemplate const&) = delete; }; -//===================================================== - -class LootValidatorRef : public Reference -{ - public: - LootValidatorRef() { } - void targetObjectDestroyLink() override { } - void sourceObjectDestroyLink() override { } -}; - -//===================================================== - -class LootValidatorRefManager : public RefManager -{ - public: - typedef LinkedListHead::Iterator< LootValidatorRef > iterator; - - LootValidatorRef* getFirst() { return (LootValidatorRef*)RefManager::getFirst(); } - - iterator begin() { return iterator(getFirst()); } - iterator end() { return iterator(nullptr); } -}; - -//===================================================== -struct LootView; - -ByteBuffer& operator<<(ByteBuffer& b, LootItem const& li); -ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv); - -struct TC_GAME_API Loot -{ - friend ByteBuffer& operator<<(ByteBuffer& b, LootView const& lv); - - NotNormalLootItemMap const& GetPlayerQuestItems() const { return PlayerQuestItems; } - NotNormalLootItemMap const& GetPlayerFFAItems() const { return PlayerFFAItems; } - NotNormalLootItemMap const& GetPlayerNonQuestNonFFAConditionalItems() const { return PlayerNonQuestNonFFAConditionalItems; } - - std::vector items; - std::vector quest_items; - std::vector currencies; - - uint32 gold; - uint8 unlootedCount; - uint8 unlootedCurrency; - ObjectGuid roundRobinPlayer; // GUID of the player having the Round-Robin ownership for the loot. If 0, round robin owner has released. - LootType loot_type; // required for achievement system - uint8 maxDuplicates; // Max amount of items with the same entry that can drop (default is 1; on 25 man raid mode 3) - - // GUIDLow of container that holds this loot (item_instance.entry) - // Only set for inventory items that can be right-click looted - uint32 containerID; - - Loot(uint32 _gold = 0) : gold(_gold), unlootedCount(0), unlootedCurrency(0), roundRobinPlayer(), loot_type(LOOT_CORPSE), maxDuplicates(1), containerID(0) { } - ~Loot() { clear(); } - - // For deleting items at loot removal since there is no backward interface to the Item() - void DeleteLootItemFromContainerItemDB(uint32 itemID); - void DeleteLootMoneyFromContainerItemDB(); - - // if loot becomes invalid this reference is used to inform the listener - void addLootValidatorRef(LootValidatorRef* pLootValidatorRef) - { - i_LootValidatorRefManager.insertFirst(pLootValidatorRef); - } - - // void clear(); - void clear() - { - for (NotNormalLootItemMap::const_iterator itr = PlayerQuestItems.begin(); itr != PlayerQuestItems.end(); ++itr) - delete itr->second; - PlayerQuestItems.clear(); - - for (NotNormalLootItemMap::const_iterator itr = PlayerFFAItems.begin(); itr != PlayerFFAItems.end(); ++itr) - delete itr->second; - PlayerFFAItems.clear(); - - for (NotNormalLootItemMap::const_iterator itr = PlayerNonQuestNonFFAConditionalItems.begin(); itr != PlayerNonQuestNonFFAConditionalItems.end(); ++itr) - delete itr->second; - PlayerNonQuestNonFFAConditionalItems.clear(); - - PlayersLooting.clear(); - items.clear(); - quest_items.clear(); - gold = 0; - unlootedCount = 0; - unlootedCurrency = 0; - roundRobinPlayer.Clear(); - loot_type = LOOT_NONE; - i_LootValidatorRefManager.clearReferences(); - } - - bool empty() const { return items.empty() && gold == 0; } - bool isLooted() const { return gold == 0 && unlootedCount == 0 && unlootedCurrency == 0; } - - void NotifyItemRemoved(uint8 lootIndex); - void NotifyQuestItemRemoved(uint8 questIndex); - void NotifyCurrencyRemoved(uint8 lootIndex); - void NotifyMoneyRemoved(); - void AddLooter(ObjectGuid GUID) { PlayersLooting.insert(GUID); } - void RemoveLooter(ObjectGuid GUID) { PlayersLooting.erase(GUID); } - - void generateMoneyLoot(uint32 minAmount, uint32 maxAmount); - bool FillLoot(uint32 lootId, LootStore const& store, Player* lootOwner, bool personal, bool noEmptyError = false, uint16 lootMode = LOOT_MODE_DEFAULT); - - // Inserts the item into the loot (called by LootTemplate processors) - void AddItem(LootStoreItem const & item); - - LootItem* LootItemInSlot(uint32 lootslot, Player* player, NotNormalLootItem** qitem = NULL, NotNormalLootItem** ffaitem = NULL, NotNormalLootItem** conditem = NULL); - uint32 GetMaxSlotInLootFor(Player* player) const; - bool hasItemForAll() const; - bool hasItemFor(Player* player) const; - bool hasOverThresholdItem() const; - - void AddCurrency(uint32 entry, uint32 min, uint32 max); - LootCurrency* LootCurrencyInSlot(uint32 lootSlot, Player* player); - - private: - void FillNotNormalLootFor(Player* player, bool presentAtLooting); - NotNormalLootItemList* FillFFALoot(Player* player); - NotNormalLootItemList* FillQuestLoot(Player* player); - NotNormalLootItemList* FillNonQuestNonFFAConditionalLoot(Player* player, bool presentAtLooting); - - GuidSet PlayersLooting; - NotNormalLootItemMap PlayerQuestItems; - NotNormalLootItemMap PlayerFFAItems; - NotNormalLootItemMap PlayerNonQuestNonFFAConditionalItems; - - // All rolls are registered here. They need to know, when the loot is not valid anymore - LootValidatorRefManager i_LootValidatorRefManager; -}; - -struct LootView -{ - Loot &loot; - Player* viewer; - PermissionTypes permission; - LootView(Loot &_loot, Player* _viewer, PermissionTypes _permission = ALL_PERMISSION) - : loot(_loot), viewer(_viewer), permission(_permission) { } -}; - TC_GAME_API extern LootStore LootTemplates_Creature; TC_GAME_API extern LootStore LootTemplates_Fishing; TC_GAME_API extern LootStore LootTemplates_Gameobject; diff --git a/src/server/game/Mails/Mail.cpp b/src/server/game/Mails/Mail.cpp index ede5b5c5eb3..5b6bc64b12b 100644 --- a/src/server/game/Mails/Mail.cpp +++ b/src/server/game/Mails/Mail.cpp @@ -16,17 +16,19 @@ * with this program. If not, see . */ -#include "DatabaseEnv.h" #include "Mail.h" -#include "Log.h" -#include "World.h" -#include "ObjectMgr.h" -#include "Player.h" -#include "BattlegroundMgr.h" -#include "Item.h" #include "AuctionHouseMgr.h" +#include "BattlegroundMgr.h" #include "CalendarMgr.h" #include "CharacterCache.h" +#include "DatabaseEnv.h" +#include "Item.h" +#include "Log.h" +#include "LootMgr.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "World.h" MailSender::MailSender(Object* sender, MailStationery stationery) : m_stationery(stationery) { @@ -180,7 +182,7 @@ void MailDraft::SendReturnToSender(uint32 sender_acc, ObjectGuid::LowType sender void MailDraft::SendMailTo(SQLTransaction& trans, MailReceiver const& receiver, MailSender const& sender, MailCheckMask checked, uint32 deliver_delay) { - Player* pReceiver = receiver.GetPlayer(); // can be NULL + Player* pReceiver = receiver.GetPlayer(); // can be nullptr Player* pSender = ObjectAccessor::FindPlayerByLowGUID(sender.GetSenderId()); if (pReceiver) @@ -188,7 +190,7 @@ void MailDraft::SendMailTo(SQLTransaction& trans, MailReceiver const& receiver, uint32 mailId = sObjectMgr->GenerateMailID(); - time_t deliver_time = time(NULL) + deliver_delay; + time_t deliver_time = time(nullptr) + deliver_delay; //expire time if COD 3 days, if no COD 30 days, if auction sale pending 1 hour uint32 expire_delay; @@ -279,13 +281,13 @@ void MailDraft::SendMailTo(SQLTransaction& trans, MailReceiver const& receiver, } else if (!m_items.empty()) { - SQLTransaction temp = SQLTransaction(NULL); + SQLTransaction temp = SQLTransaction(nullptr); deleteIncludedItems(temp); } } else if (!m_items.empty()) { - SQLTransaction temp = SQLTransaction(NULL); + SQLTransaction temp = SQLTransaction(nullptr); deleteIncludedItems(temp); } } diff --git a/src/server/game/Mails/Mail.h b/src/server/game/Mails/Mail.h index 5f74d5e7173..bc6f429f0e3 100644 --- a/src/server/game/Mails/Mail.h +++ b/src/server/game/Mails/Mail.h @@ -20,6 +20,7 @@ #define TRINITY_MAIL_H #include "Common.h" +#include "DatabaseEnvFwd.h" #include "ObjectGuid.h" #include @@ -104,7 +105,7 @@ class TC_GAME_API MailSender class TC_GAME_API MailReceiver { public: // Constructors - explicit MailReceiver(ObjectGuid::LowType receiver_lowguid) : m_receiver(NULL), m_receiver_lowguid(receiver_lowguid) { } + explicit MailReceiver(ObjectGuid::LowType receiver_lowguid) : m_receiver(nullptr), m_receiver_lowguid(receiver_lowguid) { } MailReceiver(Player* receiver); MailReceiver(Player* receiver, ObjectGuid::LowType receiver_lowguid); public: // Accessors diff --git a/src/server/game/Maps/Map.cpp b/src/server/game/Maps/Map.cpp index ad844fd91ee..9eb3419fbf5 100644 --- a/src/server/game/Maps/Map.cpp +++ b/src/server/game/Maps/Map.cpp @@ -18,17 +18,23 @@ #include "Map.h" #include "Battleground.h" -#include "MMapFactory.h" #include "CellImpl.h" +#include "DatabaseEnv.h" #include "DisableMgr.h" #include "DynamicTree.h" +#include "GameObjectModel.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "GridStates.h" #include "Group.h" #include "InstanceScript.h" +#include "Log.h" #include "MapInstanced.h" +#include "MapManager.h" +#include "MMapFactory.h" +#include "MotionMaster.h" #include "ObjectAccessor.h" +#include "ObjectGridLoader.h" #include "ObjectMgr.h" #include "Pet.h" #include "PhasingHandler.h" @@ -36,6 +42,7 @@ #include "Transport.h" #include "Vehicle.h" #include "VMapFactory.h" +#include "World.h" u_map_magic MapMagic = { {'M','A','P','S'} }; u_map_magic MapVersionMagic = { {'v','1','.','6'} }; @@ -391,7 +398,7 @@ void Map::SwitchGridContainers(Creature* obj, bool on) } NGridType *ngrid = getNGrid(cell.GridX(), cell.GridY()); - ASSERT(ngrid != NULL); + ASSERT(ngrid != nullptr); GridType &grid = ngrid->GetGridType(cell.CellX(), cell.CellY()); @@ -436,7 +443,7 @@ void Map::SwitchGridContainers(GameObject* obj, bool on) } NGridType *ngrid = getNGrid(cell.GridX(), cell.GridY()); - ASSERT(ngrid != NULL); + ASSERT(ngrid != nullptr); GridType &grid = ngrid->GetGridType(cell.CellX(), cell.CellY()); @@ -512,7 +519,7 @@ void Map::EnsureGridLoadedForActiveObject(const Cell &cell, WorldObject* object) { EnsureGridLoaded(cell); NGridType *grid = getNGrid(cell.GridX(), cell.GridY()); - ASSERT(grid != NULL); + ASSERT(grid != nullptr); // refresh grid state & timer if (grid->GetGridState() != GRID_STATE_ACTIVE) @@ -529,7 +536,7 @@ bool Map::EnsureGridLoaded(const Cell &cell) EnsureGridCreated(GridCoord(cell.GridX(), cell.GridY())); NGridType *grid = getNGrid(cell.GridX(), cell.GridY()); - ASSERT(grid != NULL); + ASSERT(grid != nullptr); if (!isGridObjectDataLoaded(cell.GridX(), cell.GridY())) { TC_LOG_DEBUG("maps", "Loading grid[%u, %u] for map %u instance %u", cell.GridX(), cell.GridY(), GetId(), i_InstanceId); @@ -715,7 +722,7 @@ void Map::VisitNearbyCellsOf(WorldObject* obj, TypeContainerVisitor(m);} }; -void Map::ProcessRelocationNotifies(const uint32 diff) +void Map::ProcessRelocationNotifies(uint32 diff) { for (GridRefManager::iterator i = GridRefManager::begin(); i != GridRefManager::end(); ++i) { @@ -1630,7 +1637,7 @@ bool Map::UnloadGrid(NGridType& ngrid, bool unloadAll) ASSERT(i_objectsToRemove.empty()); delete &ngrid; - setNGrid(NULL, x, y); + setNGrid(nullptr, x, y); } int gx = (MAX_NUMBER_OF_GRIDS - 1) - x; int gy = (MAX_NUMBER_OF_GRIDS - 1) - y; @@ -1739,7 +1746,7 @@ GridMap::~GridMap() unloadData(); } -bool GridMap::loadData(const char* filename) +bool GridMap::loadData(char const* filename) { // Unload old data if exist unloadData(); @@ -2791,7 +2798,7 @@ void Map::SendInitSelf(Player* player) WorldPacket packet; data.BuildPacket(&packet); - player->GetSession()->SendPacket(&packet); + player->SendDirectMessage(&packet); } void Map::SendInitTransports(Player* player) @@ -2809,7 +2816,7 @@ void Map::SendInitTransports(Player* player) WorldPacket packet; transData.BuildPacket(&packet); - player->GetSession()->SendPacket(&packet); + player->SendDirectMessage(&packet); } void Map::SendRemoveTransports(Player* player) @@ -2827,7 +2834,7 @@ void Map::SendRemoveTransports(Player* player) WorldPacket packet; transData.BuildPacket(&packet); - player->GetSession()->SendPacket(&packet); + player->SendDirectMessage(&packet); } void Map::SendUpdateTransportVisibility(Player* player) @@ -2854,7 +2861,7 @@ void Map::SendUpdateTransportVisibility(Player* player) WorldPacket packet; transData.BuildPacket(&packet); - player->GetSession()->SendPacket(&packet); + player->SendDirectMessage(&packet); } inline void Map::setNGrid(NGridType *grid, uint32 x, uint32 y) @@ -2889,7 +2896,7 @@ void Map::SendObjectUpdates() } } -void Map::DelayedUpdate(const uint32 t_diff) +void Map::DelayedUpdate(uint32 t_diff) { for (_transportsUpdateIter = _transports.begin(); _transportsUpdateIter != _transports.end();) { @@ -3032,7 +3039,7 @@ uint32 Map::GetPlayersCountExceptGMs() const void Map::SendToPlayers(WorldPacket* data) const { for (MapRefManager::const_iterator itr = m_mapRefManager.begin(); itr != m_mapRefManager.end(); ++itr) - itr->GetSource()->GetSession()->SendPacket(data); + itr->GetSource()->SendDirectMessage(data); } bool Map::ActiveObjectsNearGrid(NGridType const& ngrid) const @@ -3154,7 +3161,7 @@ template TC_GAME_API void Map::RemoveFromMap(AreaTrigger*, bool); InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 SpawnMode, Map* _parent) : Map(id, expiry, InstanceId, SpawnMode, _parent), m_resetAfterUnload(false), m_unloadWhenEmpty(false), - i_data(NULL), i_script_id(0) + i_data(nullptr), i_script_id(0) { //lets initialize visibility distance for dungeons InstanceMap::InitVisibilityDistance(); @@ -3167,7 +3174,7 @@ InstanceMap::InstanceMap(uint32 id, time_t expiry, uint32 InstanceId, uint8 Spaw InstanceMap::~InstanceMap() { delete i_data; - i_data = NULL; + i_data = nullptr; } void InstanceMap::InitVisibilityDistance() @@ -3286,7 +3293,7 @@ bool InstanceMap::AddPlayerToMap(Player* player) if (groupBind->save) TC_LOG_ERROR("maps", "GroupBind save players: %d, group count: %d", groupBind->save->GetPlayerCount(), groupBind->save->GetGroupCount()); else - TC_LOG_ERROR("maps", "GroupBind save NULL"); + TC_LOG_ERROR("maps", "GroupBind save nullptr"); return false; } // if the group/leader is permanently bound to the instance @@ -3298,7 +3305,7 @@ bool InstanceMap::AddPlayerToMap(Player* player) data << uint32(i_data ? i_data->GetCompletedEncounterMask() : 0); data << uint8(0); data << uint8(0); // events it throws: 1 : INSTANCE_LOCK_WARNING 0 : INSTANCE_LOCK_STOP / INSTANCE_LOCK_START - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); player->SetPendingBind(mapSave->GetInstanceId(), 60000); } } @@ -3335,7 +3342,7 @@ bool InstanceMap::AddPlayerToMap(Player* player) return true; } -void InstanceMap::Update(const uint32 t_diff) +void InstanceMap::Update(uint32 t_diff) { Map::Update(t_diff); @@ -3360,7 +3367,7 @@ void InstanceMap::RemovePlayerFromMap(Player* player, bool remove) void InstanceMap::CreateInstanceData(bool load) { - if (i_data != NULL) + if (i_data != nullptr) return; InstanceTemplate const* mInstance = sObjectMgr->GetInstanceTemplate(GetId()); @@ -3451,6 +3458,11 @@ bool InstanceMap::Reset(uint8 method) return m_mapRefManager.isEmpty(); } +std::string const& InstanceMap::GetScriptName() const +{ + return sObjectMgr->GetScriptName(i_script_id); +} + void InstanceMap::PermBindAllPlayers() { if (!IsDungeon()) @@ -3488,7 +3500,7 @@ void InstanceMap::PermBindAllPlayers() player->BindToInstance(save, true); WorldPacket data(SMSG_INSTANCE_SAVE_CREATED, 4); data << uint32(0); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); player->GetSession()->SendCalendarRaidLockout(save, true); // if group leader is in instance, group also gets bound @@ -3538,6 +3550,74 @@ MapDifficulty const* Map::GetMapDifficulty() const return GetMapDifficultyData(GetId(), GetDifficulty()); } +bool Map::Instanceable() const +{ + return i_mapEntry && i_mapEntry->Instanceable(); +} + +bool Map::IsDungeon() const +{ + return i_mapEntry && i_mapEntry->IsDungeon(); +} + +bool Map::IsNonRaidDungeon() const +{ + return i_mapEntry && i_mapEntry->IsNonRaidDungeon(); +} + +bool Map::IsRaid() const +{ + return i_mapEntry && i_mapEntry->IsRaid(); +} + +bool Map::IsRaidOrHeroicDungeon() const +{ + return IsRaid() || i_spawnMode > DUNGEON_DIFFICULTY_NORMAL; +} + +bool Map::IsHeroic() const +{ + return IsRaid() ? i_spawnMode >= RAID_DIFFICULTY_10MAN_HEROIC : i_spawnMode >= DUNGEON_DIFFICULTY_HEROIC; +} + +bool Map::Is25ManRaid() const +{ + // since 25man difficulties are 1 and 3, we can check them like that + return IsRaid() && i_spawnMode & RAID_DIFFICULTY_MASK_25MAN; +} + +uint32 Map::GetId() const +{ + return i_mapEntry->MapID; +} + +bool Map::IsRegularDifficulty() const +{ + return GetDifficulty() == REGULAR_DIFFICULTY; +} + +bool Map::IsBattleground() const +{ + return i_mapEntry && i_mapEntry->IsBattleground(); +} + +bool Map::IsBattleArena() const +{ + return i_mapEntry && i_mapEntry->IsBattleArena(); +} + +bool Map::IsBattlegroundOrArena() const +{ + return i_mapEntry && i_mapEntry->IsBattlegroundOrArena(); +} + +bool Map::GetEntrancePos(int32& mapid, float& x, float& y) const +{ + if (!i_mapEntry) + return false; + return i_mapEntry->GetEntrancePos(mapid, x, y); +} + bool InstanceMap::HasPermBoundPlayers() const { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_PERM_BIND_BY_INSTANCE); @@ -3563,7 +3643,7 @@ uint32 InstanceMap::GetMaxResetDelay() const /* ******* Battleground Instance Maps ******* */ BattlegroundMap::BattlegroundMap(uint32 id, time_t expiry, uint32 InstanceId, Map* _parent, uint8 spawnMode) - : Map(id, expiry, InstanceId, spawnMode, _parent), m_bg(NULL) + : Map(id, expiry, InstanceId, spawnMode, _parent), m_bg(nullptr) { //lets initialize visibility distance for BG/Arenas BattlegroundMap::InitVisibilityDistance(); @@ -3574,8 +3654,8 @@ BattlegroundMap::~BattlegroundMap() if (m_bg) { //unlink to prevent crash, always unlink all pointer reference before destruction - m_bg->SetBgMap(NULL); - m_bg = NULL; + m_bg->SetBgMap(nullptr); + m_bg = nullptr; } } @@ -3674,10 +3754,10 @@ Pet* Map::GetPet(ObjectGuid const& guid) Transport* Map::GetTransport(ObjectGuid const& guid) { if (!guid.IsMOTransport()) - return NULL; + return nullptr; GameObject* go = GetGameObject(guid); - return go ? go->ToTransport() : NULL; + return go ? go->ToTransport() : nullptr; } void Map::UpdateIteratorBack(Player* player) @@ -3927,7 +4007,7 @@ Corpse* Map::ConvertCorpseToBones(ObjectGuid const& ownerGuid, bool insignia /*= corpse->DeleteFromDB(trans); CharacterDatabase.CommitTransaction(trans); - Corpse* bones = NULL; + Corpse* bones = nullptr; // create the bones only if the map and the grid is loaded at the corpse's location // ignore bones creating option in case insignia diff --git a/src/server/game/Maps/Map.h b/src/server/game/Maps/Map.h index 5eb6502032a..28fd3b2d784 100644 --- a/src/server/game/Maps/Map.h +++ b/src/server/game/Maps/Map.h @@ -21,7 +21,6 @@ #include "Define.h" -#include "DBCStructure.h" #include "GridDefines.h" #include "Cell.h" #include "Timer.h" @@ -29,32 +28,37 @@ #include "GridRefManager.h" #include "MapRefManager.h" #include "DynamicTree.h" -#include "GameObjectModel.h" #include "ObjectGuid.h" +#include "Optional.h" #include #include #include +#include -class Unit; -class WorldPacket; -class InstanceScript; +class Battleground; +class BattlegroundMap; +class CreatureGroup; class Group; +class InstanceMap; class InstanceSave; +class InstanceScript; +class MapInstanced; class Object; class PhaseShift; -class WorldObject; -class TempSummon; class Player; -class CreatureGroup; -struct ScriptInfo; -struct ScriptAction; -struct Position; -class Battleground; -class MapInstanced; -class BattlegroundMap; -class InstanceMap; +class TempSummon; class Transport; +class Unit; +class WorldObject; +class WorldPacket; +struct MapDifficulty; +struct MapEntry; +struct Position; +struct ScriptAction; +struct ScriptInfo; +struct SummonPropertiesEntry; +enum Difficulty : uint8; namespace Trinity { struct ObjectUpdater; } namespace VMAP { enum class ModelIgnoreFlags : uint32; } @@ -127,7 +131,7 @@ struct map_liquidHeader float liquidLevel; }; -enum ZLiquidStatus +enum ZLiquidStatus : uint32 { LIQUID_MAP_NO_WATER = 0x00000000, LIQUID_MAP_ABOVE_WATER = 0x00000001, @@ -176,14 +180,6 @@ struct PositionFullTerrainStatus Optional liquidInfo; }; -enum LineOfSightChecks -{ - LINEOFSIGHT_CHECK_VMAP = 0x1, // check static floor layout data - LINEOFSIGHT_CHECK_GOBJECT = 0x2, // check dynamic game object data - - LINEOFSIGHT_ALL_CHECKS = (LINEOFSIGHT_CHECK_VMAP | LINEOFSIGHT_CHECK_GOBJECT) -}; - class TC_GAME_API GridMap { uint32 _flags; @@ -232,7 +228,7 @@ class TC_GAME_API GridMap public: GridMap(); ~GridMap(); - bool loadData(const char* filename); + bool loadData(char const* filename); void unloadData(); uint16 getArea(float x, float y) const; @@ -245,13 +241,6 @@ public: #pragma pack(push, 1) -struct InstanceTemplate -{ - uint32 Parent; - uint32 ScriptId; - bool AllowMount; -}; - enum LevelRequirementVsMode { LEVELREQUIREMENT_HEROIC = 70 @@ -285,7 +274,7 @@ class TC_GAME_API Map : public GridRefManager { friend class MapReference; public: - Map(uint32 id, time_t, uint32 InstanceId, uint8 SpawnMode, Map* _parent = NULL); + Map(uint32 id, time_t, uint32 InstanceId, uint8 SpawnMode, Map* _parent = nullptr); virtual ~Map(); MapEntry const* GetEntry() const { return i_mapEntry; } @@ -310,7 +299,7 @@ class TC_GAME_API Map : public GridRefManager template void RemoveFromMap(T *, bool); void VisitNearbyCellsOf(WorldObject* obj, TypeContainerVisitor &gridVisitor, TypeContainerVisitor &worldVisitor); - virtual void Update(const uint32); + virtual void Update(uint32); float GetVisibilityRange() const { return m_VisibleDistance; } //function for setting up visibility distance for maps on per-type/per-Id basis @@ -322,7 +311,7 @@ class TC_GAME_API Map : public GridRefManager void DynamicObjectRelocation(DynamicObject* go, float x, float y, float z, float orientation); template - void Visit(const Cell& cell, TypeContainerVisitor &visitor); + void Visit(Cell const& cell, TypeContainerVisitor &visitor); bool IsRemovalGrid(float x, float y) const { @@ -335,8 +324,8 @@ class TC_GAME_API Map : public GridRefManager return IsGridLoaded(Trinity::ComputeGridCoord(x, y)); } - 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); } + bool GetUnloadLock(GridCoord const& p) const { return getNGrid(p.x_coord, p.y_coord)->getUnloadLock(); } + void SetUnloadLock(GridCoord const& 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); @@ -348,7 +337,7 @@ class TC_GAME_API Map : public GridRefManager } time_t GetGridExpiry(void) const { return i_gridExpiry; } - uint32 GetId(void) const { return i_mapEntry->MapID; } + uint32 GetId() const; bool HasGrid(uint32 mapId, int32 gx, int32 gy) const; static bool ExistMap(uint32 mapid, int gx, int gy); @@ -412,33 +401,28 @@ class TC_GAME_API Map : public GridRefManager CANNOT_ENTER_UNSPECIFIED_REASON }; virtual EnterState CannotEnter(Player* /*player*/) { return CAN_ENTER; } - const char* GetMapName() const; + char const* GetMapName() const; // have meaning only for instanced map (that have set real difficulty) Difficulty GetDifficulty() const { return Difficulty(GetSpawnMode()); } - bool IsRegularDifficulty() const { return GetDifficulty() == REGULAR_DIFFICULTY; } + bool IsRegularDifficulty() const; MapDifficulty const* GetMapDifficulty() const; - bool Instanceable() const { return i_mapEntry && i_mapEntry->Instanceable(); } - bool IsDungeon() const { return i_mapEntry && i_mapEntry->IsDungeon(); } - bool IsNonRaidDungeon() const { return i_mapEntry && i_mapEntry->IsNonRaidDungeon(); } - bool IsRaid() const { return i_mapEntry && i_mapEntry->IsRaid(); } - bool IsRaidOrHeroicDungeon() const { return IsRaid() || i_spawnMode > DUNGEON_DIFFICULTY_NORMAL; } - bool IsHeroic() const { return IsRaid() ? i_spawnMode >= RAID_DIFFICULTY_10MAN_HEROIC : i_spawnMode >= DUNGEON_DIFFICULTY_HEROIC; } - bool Is25ManRaid() const { return IsRaid() && i_spawnMode & RAID_DIFFICULTY_MASK_25MAN; } // since 25man difficulties are 1 and 3, we can check them like that - bool IsBattleground() const { return i_mapEntry && i_mapEntry->IsBattleground(); } - bool IsBattleArena() const { return i_mapEntry && i_mapEntry->IsBattleArena(); } - bool IsBattlegroundOrArena() const { return i_mapEntry && i_mapEntry->IsBattlegroundOrArena(); } - bool GetEntrancePos(int32 &mapid, float &x, float &y) - { - if (!i_mapEntry) - return false; - return i_mapEntry->GetEntrancePos(mapid, x, y); - } + bool Instanceable() const; + bool IsDungeon() const; + bool IsNonRaidDungeon() const; + bool IsRaid() const; + bool IsRaidOrHeroicDungeon() const; + bool IsHeroic() const; + bool Is25ManRaid() const; + bool IsBattleground() const; + bool IsBattleArena() const; + bool IsBattlegroundOrArena() const; + bool GetEntrancePos(int32& mapid, float& x, float& y) const; void AddObjectToRemoveList(WorldObject* obj); void AddObjectToSwitchList(WorldObject* obj, bool on); - virtual void DelayedUpdate(const uint32 diff); + virtual void DelayedUpdate(uint32 diff); void resetMarkedCells() { marked_cells.reset(); } bool isCellMarked(uint32 pCellId) { return marked_cells.test(pCellId); } @@ -457,7 +441,7 @@ class TC_GAME_API Map : public GridRefManager PlayerList const& GetPlayers() const { return m_mapRefManager; } //per-map script storage - void ScriptsStart(std::map > const& scripts, uint32 id, Object* source, Object* target); + void ScriptsStart(std::map> const& scripts, uint32 id, Object* source, Object* target); void ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target); // must called with AddToWorld @@ -510,14 +494,14 @@ class TC_GAME_API Map : public GridRefManager return nullptr; } - MapInstanced* ToMapInstanced() { if (Instanceable()) return reinterpret_cast(this); return NULL; } - MapInstanced const* ToMapInstanced() const { if (Instanceable()) return reinterpret_cast(this); return NULL; } + MapInstanced* ToMapInstanced() { if (Instanceable()) return reinterpret_cast(this); return nullptr; } + MapInstanced const* ToMapInstanced() const { if (Instanceable()) return reinterpret_cast(this); return nullptr; } - InstanceMap* ToInstanceMap() { if (IsDungeon()) return reinterpret_cast(this); else return NULL; } - InstanceMap const* ToInstanceMap() const { if (IsDungeon()) return reinterpret_cast(this); return NULL; } + InstanceMap* ToInstanceMap() { if (IsDungeon()) return reinterpret_cast(this); else return nullptr; } + InstanceMap const* ToInstanceMap() const { if (IsDungeon()) return reinterpret_cast(this); return nullptr; } - BattlegroundMap* ToBattlegroundMap() { if (IsBattlegroundOrArena()) return reinterpret_cast(this); else return NULL; } - BattlegroundMap const* ToBattlegroundMap() const { if (IsBattlegroundOrArena()) return reinterpret_cast(this); return NULL; } + BattlegroundMap* ToBattlegroundMap() { if (IsBattlegroundOrArena()) return reinterpret_cast(this); else return nullptr; } + BattlegroundMap const* ToBattlegroundMap() const { if (IsBattlegroundOrArena()) return reinterpret_cast(this); return nullptr; } float GetWaterOrGroundLevel(PhaseShift const& phaseShift, float x, float y, float z, float* ground = nullptr, bool swim = false) const; float GetHeight(PhaseShift const& phaseShifts, float x, float y, float z, bool vmap = true, float maxSearchDist = DEFAULT_HEIGHT_SEARCH) const; @@ -692,13 +676,13 @@ class TC_GAME_API Map : public GridRefManager TransportsContainer::iterator _transportsUpdateIter; private: - Player* _GetScriptPlayerSourceOrTarget(Object* source, Object* target, const ScriptInfo* scriptInfo) const; - Creature* _GetScriptCreatureSourceOrTarget(Object* source, Object* target, const ScriptInfo* scriptInfo, bool bReverse = false) const; - Unit* _GetScriptUnit(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const; - Player* _GetScriptPlayer(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const; - Creature* _GetScriptCreature(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const; - WorldObject* _GetScriptWorldObject(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const; - void _ScriptProcessDoor(Object* source, Object* target, const ScriptInfo* scriptInfo) const; + Player* _GetScriptPlayerSourceOrTarget(Object* source, Object* target, ScriptInfo const* scriptInfo) const; + Creature* _GetScriptCreatureSourceOrTarget(Object* source, Object* target, ScriptInfo const* scriptInfo, bool bReverse = false) const; + Unit* _GetScriptUnit(Object* obj, bool isSource, ScriptInfo const* scriptInfo) const; + Player* _GetScriptPlayer(Object* obj, bool isSource, ScriptInfo const* scriptInfo) const; + Creature* _GetScriptCreature(Object* obj, bool isSource, ScriptInfo const* scriptInfo) const; + WorldObject* _GetScriptWorldObject(Object* obj, bool isSource, ScriptInfo const* scriptInfo) const; + void _ScriptProcessDoor(Object* source, Object* target, ScriptInfo const* scriptInfo) const; GameObject* _FindGameObject(WorldObject* pWorldObject, ObjectGuid::LowType guid) const; time_t i_gridExpiry; @@ -714,7 +698,7 @@ class TC_GAME_API Map : public GridRefManager //these functions used to process player/mob aggro reactions and //visibility calculations. Highly optimized for massive calculations - void ProcessRelocationNotifies(const uint32 diff); + void ProcessRelocationNotifies(uint32 diff); bool i_scriptLock; std::set i_objectsToRemove; @@ -796,10 +780,11 @@ class TC_GAME_API InstanceMap : public Map ~InstanceMap(); bool AddPlayerToMap(Player*) override; void RemovePlayerFromMap(Player*, bool) override; - void Update(const uint32) override; + void Update(uint32) override; void CreateInstanceData(bool load); bool Reset(uint8 method); uint32 GetScriptId() const { return i_script_id; } + std::string const& GetScriptName() const; InstanceScript* GetInstanceScript() { return i_data; } InstanceScript const* GetInstanceScript() const { return i_data; } void PermBindAllPlayers(); diff --git a/src/server/game/Maps/MapInstanced.cpp b/src/server/game/Maps/MapInstanced.cpp index e1169c22d2b..7728862869c 100644 --- a/src/server/game/Maps/MapInstanced.cpp +++ b/src/server/game/Maps/MapInstanced.cpp @@ -17,15 +17,17 @@ */ #include "MapInstanced.h" -#include "ObjectMgr.h" -#include "MapManager.h" #include "Battleground.h" -#include "VMapFactory.h" -#include "MMapFactory.h" -#include "InstanceSaveMgr.h" -#include "World.h" +#include "DBCStores.h" #include "Group.h" +#include "InstanceSaveMgr.h" +#include "Log.h" +#include "MapManager.h" +#include "MMapFactory.h" +#include "ObjectMgr.h" #include "Player.h" +#include "VMapFactory.h" +#include "World.h" MapInstanced::MapInstanced(uint32 id, time_t expiry) : Map(id, expiry, 0, DUNGEON_DIFFICULTY_NORMAL) { @@ -44,7 +46,7 @@ void MapInstanced::InitVisibilityDistance() } } -void MapInstanced::Update(const uint32 t) +void MapInstanced::Update(uint32 t) { // take care of loaded GridMaps (when unused, unload it!) Map::Update(t); @@ -73,7 +75,7 @@ void MapInstanced::Update(const uint32 t) } } -void MapInstanced::DelayedUpdate(const uint32 diff) +void MapInstanced::DelayedUpdate(uint32 diff) { for (InstancedMaps::iterator i = m_InstancedMaps.begin(); i != m_InstancedMaps.end(); ++i) i->second->DelayedUpdate(diff); @@ -110,7 +112,7 @@ void MapInstanced::UnloadAll() - create the instance if it's not created already - the player is not actually added to the instance (only in InstanceMap::Add) */ -Map* MapInstanced::CreateInstanceForPlayer(const uint32 mapId, Player* player, uint32 loginInstanceId) +Map* MapInstanced::CreateInstanceForPlayer(uint32 mapId, Player* player, uint32 loginInstanceId) { if (GetId() != mapId || !player) return nullptr; @@ -190,7 +192,7 @@ Map* MapInstanced::CreateInstanceForPlayer(const uint32 mapId, Player* player, u //ASSERT(!FindInstanceMap(NewInstanceId)); map = FindInstanceMap(newInstanceId); if (!map) - map = CreateInstance(newInstanceId, NULL, diff); + map = CreateInstance(newInstanceId, nullptr, diff); } } @@ -203,13 +205,13 @@ InstanceMap* MapInstanced::CreateInstance(uint32 InstanceId, InstanceSave* save, std::lock_guard lock(_mapLock); // make sure we have a valid map id - const MapEntry* entry = sMapStore.LookupEntry(GetId()); + MapEntry const* entry = sMapStore.LookupEntry(GetId()); if (!entry) { TC_LOG_ERROR("maps", "CreateInstance: no entry for map %d", GetId()); ABORT(); } - const InstanceTemplate* iTemplate = sObjectMgr->GetInstanceTemplate(GetId()); + InstanceTemplate const* iTemplate = sObjectMgr->GetInstanceTemplate(GetId()); if (!iTemplate) { TC_LOG_ERROR("maps", "CreateInstance: no instance template for map %d", GetId()); @@ -227,7 +229,7 @@ InstanceMap* MapInstanced::CreateInstance(uint32 InstanceId, InstanceSave* save, map->LoadRespawnTimes(); map->LoadCorpseData(); - bool load_data = save != NULL; + bool load_data = save != nullptr; map->CreateInstanceData(load_data); if (sWorld->getBoolConfig(CONFIG_INSTANCEMAP_LOAD_GRIDS)) diff --git a/src/server/game/Maps/MapInstanced.h b/src/server/game/Maps/MapInstanced.h index dccb6cee9a1..852e0263e8f 100644 --- a/src/server/game/Maps/MapInstanced.h +++ b/src/server/game/Maps/MapInstanced.h @@ -33,13 +33,13 @@ class TC_GAME_API MapInstanced : public Map ~MapInstanced() { } // functions overwrite Map versions - void Update(const uint32) override; - void DelayedUpdate(const uint32 diff) override; + void Update(uint32) override; + void DelayedUpdate(uint32 diff) override; //void RelocationNotify(); void UnloadAll() override; EnterState CannotEnter(Player* /*player*/) override; - Map* CreateInstanceForPlayer(const uint32 mapId, Player* player, uint32 loginInstanceId=0); + Map* CreateInstanceForPlayer(uint32 mapId, Player* player, uint32 loginInstanceId=0); Map* FindInstanceMap(uint32 instanceId) const { InstancedMaps::const_iterator i = m_InstancedMaps.find(instanceId); diff --git a/src/server/game/Maps/MapManager.cpp b/src/server/game/Maps/MapManager.cpp index f34349496d0..f1bde63a3ad 100644 --- a/src/server/game/Maps/MapManager.cpp +++ b/src/server/game/Maps/MapManager.cpp @@ -121,7 +121,7 @@ Map* MapManager::FindBaseNonInstanceMap(uint32 mapId) const { Map* map = FindBaseMap(mapId); if (map && map->Instanceable()) - return NULL; + return nullptr; return map; } @@ -139,10 +139,10 @@ Map* MapManager::FindMap(uint32 mapid, uint32 instanceId) const { Map* map = FindBaseMap(mapid); if (!map) - return NULL; + return nullptr; if (!map->Instanceable()) - return instanceId == 0 ? map : NULL; + return instanceId == 0 ? map : nullptr; return ((MapInstanced*)map)->FindInstanceMap(instanceId); } diff --git a/src/server/game/Maps/MapManager.h b/src/server/game/Maps/MapManager.h index 12cf7c0c9cd..d92dbc55c2a 100644 --- a/src/server/game/Maps/MapManager.h +++ b/src/server/game/Maps/MapManager.h @@ -77,7 +77,7 @@ class TC_GAME_API MapManager i_timer.Reset(); } - //void LoadGrid(int mapid, int instId, float x, float y, const WorldObject* obj, bool no_unload = false); + //void LoadGrid(int mapid, int instId, float x, float y, WorldObject const* obj, bool no_unload = false); void UnloadAll(); static bool ExistMapAndVMap(uint32 mapid, float x, float y); @@ -141,7 +141,7 @@ class TC_GAME_API MapManager Map* FindBaseMap(uint32 mapId) const { MapMapType::const_iterator iter = i_maps.find(mapId); - return (iter == i_maps.end() ? NULL : iter->second); + return (iter == i_maps.end() ? nullptr : iter->second); } Map* CreateBaseMap_i(MapEntry const* mapEntry); @@ -205,4 +205,5 @@ inline void MapManager::DoForAllMapsWithMapId(uint32 mapId, Worker&& worker) } #define sMapMgr MapManager::instance() + #endif diff --git a/src/server/game/Maps/MapObject.h b/src/server/game/Maps/MapObject.h new file mode 100644 index 00000000000..92e625fe715 --- /dev/null +++ b/src/server/game/Maps/MapObject.h @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef MapObject_h__ +#define MapObject_h__ + +#include "Define.h" +#include "Cell.h" +#include "Position.h" + +class Map; +class ObjectGridLoader; + +enum MapObjectCellMoveState +{ + MAP_OBJECT_CELL_MOVE_NONE, //not in move list + MAP_OBJECT_CELL_MOVE_ACTIVE, //in move list + MAP_OBJECT_CELL_MOVE_INACTIVE, //in move list but should not move +}; + +class TC_GAME_API MapObject +{ + friend class Map; //map for moving creatures + friend class ObjectGridLoader; //grid loader for loading creatures + + protected: + MapObject() : _moveState(MAP_OBJECT_CELL_MOVE_NONE) + { + _newPosition.Relocate(0.0f, 0.0f, 0.0f, 0.0f); + } + + private: + Cell _currentCell; + Cell const& GetCurrentCell() const { return _currentCell; } + void SetCurrentCell(Cell const& cell) { _currentCell = cell; } + + MapObjectCellMoveState _moveState; + Position _newPosition; + void SetNewCellPosition(float x, float y, float z, float o) + { + _moveState = MAP_OBJECT_CELL_MOVE_ACTIVE; + _newPosition.Relocate(x, y, z, o); + } +}; + +#endif // MapObject_h__ diff --git a/src/server/game/Maps/MapReference.cpp b/src/server/game/Maps/MapReference.cpp new file mode 100644 index 00000000000..72dfc4ff4da --- /dev/null +++ b/src/server/game/Maps/MapReference.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * Copyright (C) 2005-2009 MaNGOS + * + * 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 . + */ + +#include "MapReference.h" +#include "Map.h" + +void MapReference::targetObjectBuildLink() +{ + // called from link() + getTarget()->m_mapRefManager.insertFirst(this); + getTarget()->m_mapRefManager.incSize(); +} +void MapReference::targetObjectDestroyLink() +{ + // called from unlink() + if (isValid()) getTarget()->m_mapRefManager.decSize(); +} +void MapReference::sourceObjectDestroyLink() +{ + // called from invalidate() + getTarget()->m_mapRefManager.decSize(); +} diff --git a/src/server/game/Maps/MapReference.h b/src/server/game/Maps/MapReference.h index f0bb4ec7f99..ce9feb8f956 100644 --- a/src/server/game/Maps/MapReference.h +++ b/src/server/game/Maps/MapReference.h @@ -20,27 +20,17 @@ #define _MAPREFERENCE_H #include "Reference.h" -#include "Map.h" + +class Map; +class Player; class MapReference : public Reference { protected: - void targetObjectBuildLink() override - { - // called from link() - getTarget()->m_mapRefManager.insertFirst(this); - getTarget()->m_mapRefManager.incSize(); - } - void targetObjectDestroyLink() override - { - // called from unlink() - if (isValid()) getTarget()->m_mapRefManager.decSize(); - } - void sourceObjectDestroyLink() override - { - // called from invalidate() - getTarget()->m_mapRefManager.decSize(); - } + void targetObjectBuildLink() override; + void targetObjectDestroyLink() override; + void sourceObjectDestroyLink() override; + public: MapReference() : Reference() { } ~MapReference() { unlink(); } diff --git a/src/server/game/Maps/MapScripts.cpp b/src/server/game/Maps/MapScripts.cpp index 44b22c85294..0a7b933a0b6 100644 --- a/src/server/game/Maps/MapScripts.cpp +++ b/src/server/game/Maps/MapScripts.cpp @@ -16,17 +16,17 @@ * with this program. If not, see . */ +#include "Map.h" #include "CellImpl.h" #include "GameTime.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" #include "GossipDef.h" -#include "Map.h" +#include "GridNotifiers.h" +#include "Item.h" +#include "Log.h" #include "MapManager.h" +#include "MotionMaster.h" #include "ObjectMgr.h" #include "Pet.h" -#include "Item.h" -#include "ScriptedCreature.h" #include "ScriptMgr.h" #include "Transport.h" #include "WaypointManager.h" @@ -100,11 +100,11 @@ void Map::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* sou } // Helpers for ScriptProcess method. -inline Player* Map::_GetScriptPlayerSourceOrTarget(Object* source, Object* target, const ScriptInfo* scriptInfo) const +inline Player* Map::_GetScriptPlayerSourceOrTarget(Object* source, Object* target, ScriptInfo const* scriptInfo) const { - Player* player = NULL; + Player* player = nullptr; if (!source && !target) - TC_LOG_ERROR("scripts", "%s source and target objects are NULL.", scriptInfo->GetDebugInfo().c_str()); + TC_LOG_ERROR("scripts", "%s source and target objects are nullptr.", scriptInfo->GetDebugInfo().c_str()); else { // Check target first, then source. @@ -122,11 +122,11 @@ inline Player* Map::_GetScriptPlayerSourceOrTarget(Object* source, Object* targe return player; } -inline Creature* Map::_GetScriptCreatureSourceOrTarget(Object* source, Object* target, const ScriptInfo* scriptInfo, bool bReverse) const +inline Creature* Map::_GetScriptCreatureSourceOrTarget(Object* source, Object* target, ScriptInfo const* scriptInfo, bool bReverse) const { - Creature* creature = NULL; + Creature* creature = nullptr; if (!source && !target) - TC_LOG_ERROR("scripts", "%s source and target objects are NULL.", scriptInfo->GetDebugInfo().c_str()); + TC_LOG_ERROR("scripts", "%s source and target objects are nullptr.", scriptInfo->GetDebugInfo().c_str()); else { if (bReverse) @@ -155,11 +155,11 @@ inline Creature* Map::_GetScriptCreatureSourceOrTarget(Object* source, Object* t return creature; } -inline Unit* Map::_GetScriptUnit(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const +inline Unit* Map::_GetScriptUnit(Object* obj, bool isSource, ScriptInfo const* scriptInfo) const { - Unit* unit = NULL; + Unit* unit = nullptr; if (!obj) - TC_LOG_ERROR("scripts", "%s %s object is NULL.", scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target"); + TC_LOG_ERROR("scripts", "%s %s object is nullptr.", scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target"); else if (!obj->isType(TYPEMASK_UNIT)) TC_LOG_ERROR("scripts", "%s %s object is not unit (TypeId: %u, Entry: %u, GUID: %u), skipping.", scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target", obj->GetTypeId(), obj->GetEntry(), obj->GetGUID().GetCounter()); @@ -173,11 +173,11 @@ inline Unit* Map::_GetScriptUnit(Object* obj, bool isSource, const ScriptInfo* s return unit; } -inline Player* Map::_GetScriptPlayer(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const +inline Player* Map::_GetScriptPlayer(Object* obj, bool isSource, ScriptInfo const* scriptInfo) const { - Player* player = NULL; + Player* player = nullptr; if (!obj) - TC_LOG_ERROR("scripts", "%s %s object is NULL.", scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target"); + TC_LOG_ERROR("scripts", "%s %s object is nullptr.", scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target"); else { player = obj->ToPlayer(); @@ -188,11 +188,11 @@ inline Player* Map::_GetScriptPlayer(Object* obj, bool isSource, const ScriptInf return player; } -inline Creature* Map::_GetScriptCreature(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const +inline Creature* Map::_GetScriptCreature(Object* obj, bool isSource, ScriptInfo const* scriptInfo) const { - Creature* creature = NULL; + Creature* creature = nullptr; if (!obj) - TC_LOG_ERROR("scripts", "%s %s object is NULL.", scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target"); + TC_LOG_ERROR("scripts", "%s %s object is nullptr.", scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target"); else { creature = obj->ToCreature(); @@ -203,11 +203,11 @@ inline Creature* Map::_GetScriptCreature(Object* obj, bool isSource, const Scrip return creature; } -inline WorldObject* Map::_GetScriptWorldObject(Object* obj, bool isSource, const ScriptInfo* scriptInfo) const +inline WorldObject* Map::_GetScriptWorldObject(Object* obj, bool isSource, ScriptInfo const* scriptInfo) const { - WorldObject* pWorldObject = NULL; + WorldObject* pWorldObject = nullptr; if (!obj) - TC_LOG_ERROR("scripts", "%s %s object is NULL.", + TC_LOG_ERROR("scripts", "%s %s object is nullptr.", scriptInfo->GetDebugInfo().c_str(), isSource ? "source" : "target"); else { @@ -219,7 +219,7 @@ inline WorldObject* Map::_GetScriptWorldObject(Object* obj, bool isSource, const return pWorldObject; } -inline void Map::_ScriptProcessDoor(Object* source, Object* target, const ScriptInfo* scriptInfo) const +inline void Map::_ScriptProcessDoor(Object* source, Object* target, ScriptInfo const* scriptInfo) const { bool bOpen = false; ObjectGuid::LowType guid = scriptInfo->ToggleDoor.GOGuid; @@ -235,7 +235,7 @@ inline void Map::_ScriptProcessDoor(Object* source, Object* target, const Script if (!guid) TC_LOG_ERROR("scripts", "%s door guid is not specified.", scriptInfo->GetDebugInfo().c_str()); else if (!source) - TC_LOG_ERROR("scripts", "%s source object is NULL.", scriptInfo->GetDebugInfo().c_str()); + TC_LOG_ERROR("scripts", "%s source object is nullptr.", scriptInfo->GetDebugInfo().c_str()); else if (!source->isType(TYPEMASK_UNIT)) TC_LOG_ERROR("scripts", "%s source object is not unit (TypeId: %u, Entry: %u, GUID: %u), skipping.", scriptInfo->GetDebugInfo().c_str(), source->GetTypeId(), source->GetEntry(), source->GetGUID().GetCounter()); @@ -290,7 +290,7 @@ void Map::ScriptsProcess() { ScriptAction const& step = iter->second; - Object* source = NULL; + Object* source = nullptr; if (step.sourceGUID) { switch (step.sourceGUID.GetHigh()) @@ -326,7 +326,7 @@ void Map::ScriptsProcess() } } - WorldObject* target = NULL; + WorldObject* target = nullptr; if (step.targetGUID) { switch (step.targetGUID.GetHigh()) @@ -498,12 +498,12 @@ void Map::ScriptsProcess() { if (!source) { - TC_LOG_ERROR("scripts", "%s source object is NULL.", step.script->GetDebugInfo().c_str()); + TC_LOG_ERROR("scripts", "%s source object is nullptr.", step.script->GetDebugInfo().c_str()); break; } if (!target) { - TC_LOG_ERROR("scripts", "%s target object is NULL.", step.script->GetDebugInfo().c_str()); + TC_LOG_ERROR("scripts", "%s target object is nullptr.", step.script->GetDebugInfo().c_str()); break; } @@ -635,7 +635,7 @@ void Map::ScriptsProcess() // Target must be GameObject. if (!target) { - TC_LOG_ERROR("scripts", "%s target object is NULL.", step.script->GetDebugInfo().c_str()); + TC_LOG_ERROR("scripts", "%s target object is nullptr.", step.script->GetDebugInfo().c_str()); break; } @@ -665,7 +665,7 @@ void Map::ScriptsProcess() /// @todo Allow gameobjects to be targets and casters if (!source && !target) { - TC_LOG_ERROR("scripts", "%s source and target objects are NULL.", step.script->GetDebugInfo().c_str()); + TC_LOG_ERROR("scripts", "%s source and target objects are nullptr.", step.script->GetDebugInfo().c_str()); break; } @@ -675,24 +675,24 @@ void Map::ScriptsProcess() switch (step.script->CastSpell.Flags) { case SF_CASTSPELL_SOURCE_TO_TARGET: // source -> target - uSource = source ? source->ToUnit() : NULL; - uTarget = target ? target->ToUnit() : NULL; + uSource = source ? source->ToUnit() : nullptr; + uTarget = target ? target->ToUnit() : nullptr; break; case SF_CASTSPELL_SOURCE_TO_SOURCE: // source -> source - uSource = source ? source->ToUnit() : NULL; + uSource = source ? source->ToUnit() : nullptr; uTarget = uSource; break; case SF_CASTSPELL_TARGET_TO_TARGET: // target -> target - uSource = target ? target->ToUnit() : NULL; + uSource = target ? target->ToUnit() : nullptr; uTarget = uSource; break; case SF_CASTSPELL_TARGET_TO_SOURCE: // target -> source - uSource = target ? target->ToUnit() : NULL; - uTarget = source ? source->ToUnit() : NULL; + uSource = target ? target->ToUnit() : nullptr; + uTarget = source ? source->ToUnit() : nullptr; break; case SF_CASTSPELL_SEARCH_CREATURE: // source -> creature with entry - uSource = source ? source->ToUnit() : NULL; - uTarget = uSource ? GetClosestCreatureWithEntry(uSource, abs(step.script->CastSpell.CreatureEntry), step.script->CastSpell.SearchRadius) : NULL; + uSource = source ? source->ToUnit() : nullptr; + uTarget = uSource ? uSource->FindNearestCreature(abs(step.script->CastSpell.CreatureEntry), step.script->CastSpell.SearchRadius) : nullptr; break; } @@ -720,7 +720,7 @@ void Map::ScriptsProcess() if (WorldObject* object = _GetScriptWorldObject(source, true, step.script)) { // PlaySound.Flags bitmask: 0/1=anyone/target - Player* player = NULL; + Player* player = nullptr; if (step.script->PlaySound.Flags & SF_PLAYSOUND_TARGET_PLAYER) { // Target must be Player. @@ -749,7 +749,7 @@ void Map::ScriptsProcess() pReceiver->SendNewItem(item, step.script->CreateItem.Amount, false, true); } else - pReceiver->SendEquipError(msg, NULL, NULL, step.script->CreateItem.ItemEntry); + pReceiver->SendEquipError(msg, nullptr, nullptr, step.script->CreateItem.ItemEntry); } break; @@ -783,7 +783,7 @@ void Map::ScriptsProcess() break; } - Creature* cTarget = NULL; + Creature* cTarget = nullptr; auto creatureBounds = _creatureBySpawnIdStore.equal_range(step.script->CallScript.CreatureEntry); if (creatureBounds.first != creatureBounds.second) { @@ -811,7 +811,7 @@ void Map::ScriptsProcess() } // Insert script into schedule but do not start it - ScriptsStart(*datamap, step.script->CallScript.ScriptID, cTarget, NULL); + ScriptsStart(*datamap, step.script->CallScript.ScriptID, cTarget, nullptr); break; } diff --git a/src/server/game/Maps/TransportMgr.cpp b/src/server/game/Maps/TransportMgr.cpp index 7f260e42639..609aad8ce5a 100644 --- a/src/server/game/Maps/TransportMgr.cpp +++ b/src/server/game/Maps/TransportMgr.cpp @@ -16,21 +16,19 @@ */ #include "TransportMgr.h" -#include "Transport.h" +#include "DatabaseEnv.h" #include "InstanceScript.h" -#include "MoveSpline.h" +#include "Log.h" #include "MapManager.h" +#include "MoveSplineInitArgs.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "PhasingHandler.h" +#include "Spline.h" +#include "Transport.h" TransportTemplate::~TransportTemplate() { - // Collect shared pointers into a set to avoid deleting the same memory more than once - std::set splines; - for (size_t i = 0; i < keyFrames.size(); ++i) - splines.insert(keyFrames[i].Spline); - - for (std::set::iterator itr = splines.begin(); itr != splines.end(); ++itr) - delete *itr; } TransportMgr::TransportMgr() { } @@ -67,7 +65,7 @@ void TransportMgr::LoadTransportTemplates() Field* fields = result->Fetch(); uint32 entry = fields[0].GetUInt32(); GameObjectTemplate const* goInfo = sObjectMgr->GetGameObjectTemplate(entry); - if (goInfo == NULL) + if (goInfo == nullptr) { TC_LOG_ERROR("sql.sql", "Transport %u has no associated GameObjectTemplate from `gameobject_template` , skipped.", entry); continue; @@ -94,6 +92,15 @@ void TransportMgr::LoadTransportTemplates() TC_LOG_INFO("server.loading", ">> Loaded %u transport templates in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } +void TransportMgr::LoadTransportAnimationAndRotation() +{ + for (TransportAnimationEntry const* anim : sTransportAnimationStore) + AddPathNodeToTransport(anim->TransportEntry, anim->TimeSeg, anim); + + for (TransportRotationEntry const* rot : sTransportRotationStore) + AddPathRotationToTransport(rot->TransportEntry, rot->TimeSeg, rot); +} + class SplineRawInitializer { public: @@ -214,7 +221,7 @@ void TransportMgr::GeneratePath(GameObjectTemplate const* goInfo, TransportTempl if (keyFrames[i - 1].Teleport || i + 1 == keyFrames.size()) { size_t extra = !keyFrames[i - 1].Teleport ? 1 : 0; - TransportSpline* spline = new TransportSpline(); + std::shared_ptr spline = std::make_shared(); spline->init_spline(&splinePath[start], i - start + extra, Movement::SplineBase::ModeCatmullrom); spline->initLengths(); for (size_t j = start; j < i + extra; ++j) @@ -366,14 +373,14 @@ Transport* TransportMgr::CreateTransport(uint32 entry, ObjectGuid::LowType guid entry = instance->GetGameObjectEntry(0, entry); if (!entry) - return NULL; + return nullptr; } TransportTemplate const* tInfo = GetTransportTemplate(entry); if (!tInfo) { TC_LOG_ERROR("sql.sql", "Transport %u will not be loaded, `transport_template` missing", entry); - return NULL; + return nullptr; } // create transport... @@ -393,7 +400,7 @@ Transport* TransportMgr::CreateTransport(uint32 entry, ObjectGuid::LowType guid if (!trans->Create(guidLow, entry, mapId, x, y, z, o, 255)) { delete trans; - return NULL; + return nullptr; } PhasingHandler::InitDbPhaseShift(trans->GetPhaseShift(), phaseUseFlags, phaseId, phaseGroupId); @@ -404,12 +411,12 @@ Transport* TransportMgr::CreateTransport(uint32 entry, ObjectGuid::LowType guid { TC_LOG_ERROR("entities.transport", "Transport %u (name: %s) attempted creation in instance map (id: %u) but it is not an instanced transport!", entry, trans->GetName().c_str(), mapId); delete trans; - return NULL; + return nullptr; } } // use preset map for instances (need to know which instance) - trans->SetMap(map ? map : sMapMgr->CreateMap(mapId, NULL)); + trans->SetMap(map ? map : sMapMgr->CreateMap(mapId, nullptr)); if (map && map->IsDungeon()) trans->m_zoneScript = map->ToInstanceMap()->GetInstanceScript(); @@ -504,30 +511,18 @@ void TransportMgr::CreateInstanceTransports(Map* map) TransportAnimationEntry const* TransportAnimation::GetAnimNode(uint32 time) const { - if (Path.empty()) - return NULL; + auto itr = Path.lower_bound(time); + if (itr != Path.end()) + return itr->second; - for (TransportPathContainer::const_reverse_iterator itr2 = Path.rbegin(); itr2 != Path.rend(); ++itr2) - if (time >= itr2->first) - return itr2->second; - - return Path.begin()->second; + return nullptr; } -G3D::Quat TransportAnimation::GetAnimRotation(uint32 time) const +TransportRotationEntry const* TransportAnimation::GetAnimRotation(uint32 time) const { - if (Rotations.empty()) - return G3D::Quat(0.0f, 0.0f, 0.0f, 1.0f); + auto itr = Rotations.lower_bound(time); + if (itr != Rotations.end()) + return itr->second; - TransportRotationEntry const* rot = Rotations.begin()->second; - for (TransportPathRotationContainer::const_reverse_iterator itr2 = Rotations.rbegin(); itr2 != Rotations.rend(); ++itr2) - { - if (time >= itr2->first) - { - rot = itr2->second; - break; - } - } - - return G3D::Quat(rot->X, rot->Y, rot->Z, rot->W); + return nullptr; } diff --git a/src/server/game/Maps/TransportMgr.h b/src/server/game/Maps/TransportMgr.h index 14025b0fc3c..96f71ea659d 100644 --- a/src/server/game/Maps/TransportMgr.h +++ b/src/server/game/Maps/TransportMgr.h @@ -18,10 +18,9 @@ #ifndef TRANSPORTMGR_H #define TRANSPORTMGR_H -#include -#include "Spline.h" #include "DBCStores.h" #include "ObjectGuid.h" +#include struct KeyFrame; struct GameObjectTemplate; @@ -29,6 +28,11 @@ struct TransportTemplate; class Transport; class Map; +namespace Movement +{ + template class Spline; +} + typedef Movement::Spline TransportSpline; typedef std::vector KeyFrameVec; typedef std::unordered_map TransportTemplates; @@ -40,7 +44,7 @@ struct KeyFrame { explicit KeyFrame(TaxiPathNodeEntry const* node) : Index(0), Node(node), InitialOrientation(0.0f), DistSinceStop(-1.0f), DistUntilStop(-1.0f), DistFromPrev(-1.0f), TimeFrom(0.0f), TimeTo(0.0f), - Teleport(false), ArriveTime(0), DepartureTime(0), Spline(NULL), NextDistFromPrev(0.0f), NextArriveTime(0) + Teleport(false), ArriveTime(0), DepartureTime(0), Spline(nullptr), NextDistFromPrev(0.0f), NextArriveTime(0) { } @@ -55,7 +59,7 @@ struct KeyFrame bool Teleport; uint32 ArriveTime; uint32 DepartureTime; - TransportSpline* Spline; + std::shared_ptr Spline; // Data needed for next frame float NextDistFromPrev; @@ -91,15 +95,13 @@ struct TC_GAME_API TransportAnimation uint32 TotalTime; TransportAnimationEntry const* GetAnimNode(uint32 time) const; - G3D::Quat GetAnimRotation(uint32 time) const; + TransportRotationEntry const* GetAnimRotation(uint32 time) const; }; typedef std::map TransportAnimationContainer; class TC_GAME_API TransportMgr { - friend TC_GAME_API void LoadDBCStores(std::string const&); - public: static TransportMgr* instance(); @@ -107,6 +109,8 @@ class TC_GAME_API TransportMgr void LoadTransportTemplates(); + void LoadTransportAnimationAndRotation(); + // Creates a transport using given GameObject template entry Transport* CreateTransport(uint32 entry, ObjectGuid::LowType guid = 0, Map* map = nullptr, uint8 phaseUseFlags = 0, uint32 phaseId = 0, uint32 phaseGroupId = 0); @@ -121,7 +125,7 @@ class TC_GAME_API TransportMgr TransportTemplates::const_iterator itr = _transportTemplates.find(entry); if (itr != _transportTemplates.end()) return &itr->second; - return NULL; + return nullptr; } TransportAnimation const* GetTransportAnimInfo(uint32 entry) const @@ -130,14 +134,14 @@ class TC_GAME_API TransportMgr if (itr != _transportAnimations.end()) return &itr->second; - return NULL; + return nullptr; } private: TransportMgr(); ~TransportMgr(); - TransportMgr(TransportMgr const&); - TransportMgr& operator=(TransportMgr const&); + TransportMgr(TransportMgr const&) = delete; + TransportMgr& operator=(TransportMgr const&) = delete; // Generates and precaches a path for transport to avoid generation each time transport instance is created void GeneratePath(GameObjectTemplate const* goInfo, TransportTemplate* transport); diff --git a/src/server/scripts/EasternKingdoms/Deadmines/deadmines.cpp b/src/server/game/Maps/ZoneScript.cpp similarity index 81% rename from src/server/scripts/EasternKingdoms/Deadmines/deadmines.cpp rename to src/server/game/Maps/ZoneScript.cpp index 057d572ba39..8535f27a693 100644 --- a/src/server/scripts/EasternKingdoms/Deadmines/deadmines.cpp +++ b/src/server/game/Maps/ZoneScript.cpp @@ -15,13 +15,10 @@ * with this program. If not, see . */ -#include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "deadmines.h" -#include "Spell.h" -#include "Player.h" -#include "WorldSession.h" +#include "ZoneScript.h" +#include "Creature.h" -void AddSC_deadmines() +uint32 ZoneScript::GetCreatureEntry(ObjectGuid::LowType /*guidLow*/, CreatureData const* data) { + return data->id; } diff --git a/src/server/game/Maps/ZoneScript.h b/src/server/game/Maps/ZoneScript.h index 26633cf33cd..a2a1dc901d3 100644 --- a/src/server/game/Maps/ZoneScript.h +++ b/src/server/game/Maps/ZoneScript.h @@ -18,18 +18,22 @@ #ifndef ZONE_SCRIPT_H_ #define ZONE_SCRIPT_H_ -#include "Common.h" -#include "Creature.h" +#include "Define.h" +#include "ObjectGuid.h" +class Creature; class GameObject; +class Unit; +class WorldObject; +struct CreatureData; -class ZoneScript +class TC_GAME_API ZoneScript { public: ZoneScript() { } virtual ~ZoneScript() { } - virtual uint32 GetCreatureEntry(ObjectGuid::LowType /*guidLow*/, CreatureData const* data) { return data->id; } + virtual uint32 GetCreatureEntry(ObjectGuid::LowType /*guidLow*/, CreatureData const* data); virtual uint32 GetGameObjectEntry(ObjectGuid::LowType /*guidLow*/, uint32 entry) { return entry; } virtual void OnCreatureCreate(Creature* ) { } diff --git a/src/server/game/Miscellaneous/Formulas.h b/src/server/game/Miscellaneous/Formulas.h index 48078b9610b..8dbb0721758 100644 --- a/src/server/game/Miscellaneous/Formulas.h +++ b/src/server/game/Miscellaneous/Formulas.h @@ -19,10 +19,14 @@ #ifndef TRINITY_FORMULAS_H #define TRINITY_FORMULAS_H -#include "World.h" -#include "SharedDefines.h" -#include "ScriptMgr.h" +#include "DBCStores.h" +#include "Creature.h" +#include "Log.h" +#include "Map.h" #include "Player.h" +#include "ScriptMgr.h" +#include "SharedDefines.h" +#include "World.h" namespace Trinity { diff --git a/src/server/game/Miscellaneous/SharedDefines.h b/src/server/game/Miscellaneous/SharedDefines.h index b6b8ffaf6bf..4d8460cd74a 100644 --- a/src/server/game/Miscellaneous/SharedDefines.h +++ b/src/server/game/Miscellaneous/SharedDefines.h @@ -21,7 +21,6 @@ #include "Define.h" #include "DetourNavMesh.h" -#include enum SpellEffIndex : uint8 { @@ -1795,6 +1794,19 @@ enum GameObjectDynamicLowFlags GO_DYNFLAG_LO_STOPPED = 0x10 // Transport is stopped }; +// client side GO show states +enum GOState : uint8 +{ + GO_STATE_ACTIVE = 0, // show in world as used and not reset (closed door open) + GO_STATE_READY = 1, // show in world as ready (closed door close) + GO_STATE_ACTIVE_ALTERNATIVE = 2, // show in world as used in alt way and not reset (closed door open by cannon fire) + GO_STATE_TRANSPORT_ACTIVE = 24, + GO_STATE_TRANSPORT_STOPPED = 25 +}; + +#define MAX_GO_STATE 3 +#define MAX_GO_STATE_TRANSPORT_STOP_FRAMES 9 + enum GameObjectDestructibleState { GO_DESTRUCTIBLE_INTACT = 0, @@ -3859,7 +3871,7 @@ enum BattlegroundTeamId #define BG_TEAMS_COUNT 2 // indexes of BattlemasterList.dbc -enum BattlegroundTypeId +enum BattlegroundTypeId : uint32 { BATTLEGROUND_TYPE_NONE = 0, // None BATTLEGROUND_AV = 1, // Alterac Valley @@ -3974,7 +3986,7 @@ enum TradeStatus TRADE_STATUS_CLOSE_WINDOW = 31, }; -enum XPColorChar +enum XPColorChar : uint8 { XP_RED, XP_ORANGE, @@ -3983,7 +3995,7 @@ enum XPColorChar XP_GRAY }; -enum RemoveMethod +enum RemoveMethod : uint8 { GROUP_REMOVEMETHOD_DEFAULT = 0, GROUP_REMOVEMETHOD_KICK = 1, @@ -4014,7 +4026,7 @@ enum ProfessionUI MAX_SECONDARY_SKILLS = 5 }; -enum DuelCompleteType +enum DuelCompleteType : uint8 { DUEL_INTERRUPTED = 0, DUEL_WON = 1, @@ -4167,14 +4179,6 @@ enum DiminishingLevels DIMINISHING_LEVEL_TAUNT_IMMUNE = 4 }; -/// Spell cooldown flags sent in SMSG_SPELL_COOLDOWN -enum SpellCooldownFlags -{ - SPELL_COOLDOWN_FLAG_NONE = 0x0, - SPELL_COOLDOWN_FLAG_INCLUDE_GCD = 0x1, ///< Starts GCD in addition to normal cooldown specified in the packet - SPELL_COOLDOWN_FLAG_INCLUDE_EVENT_COOLDOWNS = 0x2 ///< Starts GCD for spells that should start their cooldown on events, requires SPELL_COOLDOWN_FLAG_INCLUDE_GCD set -}; - enum WeaponAttackType : uint8 { BASE_ATTACK = 0, @@ -4183,4 +4187,23 @@ enum WeaponAttackType : uint8 MAX_ATTACK }; +enum LineOfSightChecks +{ + LINEOFSIGHT_CHECK_VMAP = 0x1, // check static floor layout data + LINEOFSIGHT_CHECK_GOBJECT = 0x2, // check dynamic game object data + + LINEOFSIGHT_ALL_CHECKS = (LINEOFSIGHT_CHECK_VMAP | LINEOFSIGHT_CHECK_GOBJECT) +}; + +enum ContentLevels : uint8 +{ + CONTENT_1_60 = 0, + CONTENT_61_70 = 1, + CONTENT_71_80 = 2, + CONTENT_81_85 = 3, + MAX_CONTENT +}; + +#define MAX_CREATURE_SPELL_DATA_SLOT 4 + #endif diff --git a/src/server/game/Movement/MotionMaster.cpp b/src/server/game/Movement/MotionMaster.cpp index 418d0ff945c..fd0bd8f51b4 100644 --- a/src/server/game/Movement/MotionMaster.cpp +++ b/src/server/game/Movement/MotionMaster.cpp @@ -17,8 +17,12 @@ */ #include "MotionMaster.h" -#include "CreatureAISelector.h" #include "Creature.h" +#include "CreatureAISelector.h" +#include "DBCStores.h" +#include "Log.h" +#include "Map.h" +#include "PathGenerator.h" #include "ScriptSystem.h" #include "ConfusedMovementGenerator.h" #include "FleeingMovementGenerator.h" @@ -506,15 +510,16 @@ void MotionMaster::MoveCirclePath(float x, float y, float z, float radius, bool init.Launch(); } -void MotionMaster::MoveSmoothPath(uint32 pointId, G3D::Vector3 const* pathPoints, size_t pathSize, bool walk, bool fly) -{ - Movement::PointsArray path(pathPoints, pathPoints + pathSize); - MoveSmoothPath(pointId, path, walk, fly); -} - -void MotionMaster::MoveSmoothPath(uint32 pointId, Movement::PointsArray const& path, bool walk, bool fly) +void MotionMaster::MoveSmoothPath(uint32 pointId, Position const* pathPoints, size_t pathSize, bool walk /*= false*/, bool fly /*= false*/) { Movement::MoveSplineInit init(_owner); + Movement::PointsArray path; + path.reserve(pathSize); + std::transform(pathPoints, pathPoints + pathSize, std::back_inserter(path), [](Position const& point) + { + return G3D::Vector3(point.GetPositionX(), point.GetPositionY(), point.GetPositionZ()); + }); + if (fly) { init.SetFly(); @@ -542,7 +547,7 @@ void MotionMaster::MoveAlongSplineChain(uint32 pointId, uint16 dbChainId, bool w TC_LOG_ERROR("misc", "MotionMaster::MoveAlongSplineChain: non-creature %s tried to walk along DB spline chain. Ignoring.", _owner->GetGUID().ToString().c_str()); return; } - SplineChain const* chain = sScriptSystemMgr->GetSplineChain(owner, dbChainId); + std::vector const* chain = sScriptSystemMgr->GetSplineChain(owner, dbChainId); if (!chain) { TC_LOG_ERROR("misc", "MotionMaster::MoveAlongSplineChain: creature with entry %u tried to walk along non-existing spline chain with DB id %u.", owner->GetEntry(), dbChainId); @@ -551,7 +556,7 @@ void MotionMaster::MoveAlongSplineChain(uint32 pointId, uint16 dbChainId, bool w MoveAlongSplineChain(pointId, *chain, walk); } -void MotionMaster::MoveAlongSplineChain(uint32 pointId, SplineChain const& chain, bool walk) +void MotionMaster::MoveAlongSplineChain(uint32 pointId, std::vector const& chain, bool walk) { Mutate(new SplineChainMovementGenerator(pointId, chain, walk), MOTION_SLOT_ACTIVE); } diff --git a/src/server/game/Movement/MotionMaster.h b/src/server/game/Movement/MotionMaster.h index 8d4242923f2..a5a110eeab2 100644 --- a/src/server/game/Movement/MotionMaster.h +++ b/src/server/game/Movement/MotionMaster.h @@ -20,22 +20,24 @@ #define MOTIONMASTER_H #include "Common.h" -#include +#include "Errors.h" +#include "ObjectGuid.h" +#include "Position.h" #include "SharedDefines.h" -#include "Object.h" -#include "MoveSplineInitArgs.h" -#include "SplineChain.h" +#include class MovementGenerator; class Unit; class PathGenerator; +struct SplineChainLink; +struct SplineChainResumeInfo; // Creature Entry ID used for waypoints show, visible only for GMs #define VISUAL_WAYPOINT 1 // assume it is 25 yard per 0.6 second #define SPEED_CHARGE 42.0f -enum MovementGeneratorType +enum MovementGeneratorType : uint8 { IDLE_MOTION_TYPE = 0, // IdleMovementGenerator.h RANDOM_MOTION_TYPE = 1, // RandomMovementGenerator.h @@ -147,11 +149,10 @@ class TC_GAME_API MotionMaster } void MoveJump(float x, float y, float z, float o, float speedXY, float speedZ, uint32 id = EVENT_JUMP, bool hasOrientation = false); void MoveCirclePath(float x, float y, float z, float radius, bool clockwise, uint8 stepCount); - void MoveSmoothPath(uint32 pointId, G3D::Vector3 const* pathPoints, size_t pathSize, bool walk = false, bool fly = false); - void MoveSmoothPath(uint32 pointId, Movement::PointsArray const& points, bool walk = false, bool fly = false); + void MoveSmoothPath(uint32 pointId, Position const* pathPoints, size_t pathSize, bool walk = false, bool fly = false); // Walk along spline chain stored in DB (script_spline_chain_meta and script_spline_chain_waypoints) void MoveAlongSplineChain(uint32 pointId, uint16 dbChainId, bool walk); - void MoveAlongSplineChain(uint32 pointId, SplineChain const& chain, bool walk); + void MoveAlongSplineChain(uint32 pointId, std::vector const& chain, bool walk); void ResumeSplineChain(SplineChainResumeInfo const& info); void MoveFall(uint32 id = 0); diff --git a/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.cpp index 1c8e66e8c24..313545ac0d9 100755 --- a/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.cpp @@ -16,12 +16,13 @@ * with this program. If not, see . */ -#include "Creature.h" -#include "Player.h" -#include "PathGenerator.h" -#include "MoveSplineInit.h" -#include "MoveSpline.h" #include "ConfusedMovementGenerator.h" +#include "Creature.h" +#include "MoveSpline.h" +#include "MoveSplineInit.h" +#include "PathGenerator.h" +#include "Player.h" +#include "Random.h" template ConfusedMovementGenerator::~ConfusedMovementGenerator() @@ -40,7 +41,7 @@ void ConfusedMovementGenerator::DoInitialize(T* owner) owner->StopMoving(); _timer.Reset(0); - owner->GetPosition(_reference.x, _reference.y, _reference.z); + owner->GetPosition(_x, _y, _z); } template @@ -71,7 +72,7 @@ bool ConfusedMovementGenerator::DoUpdate(T* owner, uint32 diff) // start moving owner->AddUnitState(UNIT_STATE_CONFUSED_MOVE); - Position destination(_reference); + Position destination(_x, _y, _z); float distance = 4.0f * frand(0.0f, 1.0f) - 2.0f; float angle = frand(0.0f, 1.0f) * float(M_PI) * 2.0f; owner->MovePositionToFirstCollision(destination, distance, angle); diff --git a/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.h b/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.h index f5d5bf62fae..a217d1ea6d2 100755 --- a/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/ConfusedMovementGenerator.h @@ -26,7 +26,7 @@ template class ConfusedMovementGenerator : public MovementGeneratorMedium< T, ConfusedMovementGenerator > { public: - explicit ConfusedMovementGenerator() : _path(nullptr), _timer(0), _reference(0.f, 0.f, 0.f), _interrupt(false) { } + explicit ConfusedMovementGenerator() : _path(nullptr), _timer(0), _x(0.f), _y(0.f), _z(0.f), _interrupt(false) { } ~ConfusedMovementGenerator(); MovementGeneratorType GetMovementGeneratorType() const override { return CONFUSED_MOTION_TYPE; } @@ -39,7 +39,7 @@ class ConfusedMovementGenerator : public MovementGeneratorMedium< T, ConfusedMov private: PathGenerator* _path; TimeTracker _timer; - G3D::Vector3 _reference; + float _x, _y, _z; bool _interrupt; }; diff --git a/src/server/game/Movement/MovementGenerators/HomeMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/HomeMovementGenerator.cpp index e17a63a6968..809c8b8bccd 100644 --- a/src/server/game/Movement/MovementGenerators/HomeMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/HomeMovementGenerator.cpp @@ -16,11 +16,12 @@ * with this program. If not, see . */ +#include "HomeMovementGenerator.h" #include "Creature.h" #include "CreatureAI.h" -#include "MoveSplineInit.h" #include "MoveSpline.h" -#include "HomeMovementGenerator.h" +#include "MoveSplineInit.h" +#include "PathGenerator.h" template HomeMovementGenerator::~HomeMovementGenerator() { } diff --git a/src/server/game/Movement/MovementGenerators/PointMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/PointMovementGenerator.cpp index fdab55e29a0..07e3bd8c72a 100755 --- a/src/server/game/Movement/MovementGenerators/PointMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/PointMovementGenerator.cpp @@ -48,7 +48,7 @@ void PointMovementGenerator::DoInitialize(T* owner) owner->AddUnitState(UNIT_STATE_ROAMING_MOVE); Movement::MoveSplineInit init(owner); - init.MoveTo(_destination, _generatePath); + init.MoveTo(_x, _y, _z, _generatePath); if (_speed > 0.0f) init.SetVelocity(_speed); init.Launch(); @@ -56,7 +56,7 @@ void PointMovementGenerator::DoInitialize(T* owner) // Call for creature group update if (Creature* creature = owner->ToCreature()) if (creature->GetFormation() && creature->GetFormation()->getLeader() == creature) - creature->GetFormation()->LeaderMoveTo(_destination.x, _destination.y, _destination.z); + creature->GetFormation()->LeaderMoveTo(_x, _y, _z); } template @@ -83,14 +83,14 @@ bool PointMovementGenerator::DoUpdate(T* owner, uint32 /*diff*/) owner->AddUnitState(UNIT_STATE_ROAMING_MOVE); Movement::MoveSplineInit init(owner); - init.MoveTo(_destination, _generatePath); + init.MoveTo(_x, _y, _z, _generatePath); if (_speed > 0.0f) // Default value for point motion type is 0.0, if 0.0 spline will use GetSpeed on unit init.Launch(); // Call for creature group update if (Creature* creature = owner->ToCreature()) if (creature->GetFormation() && creature->GetFormation()->getLeader() == creature) - creature->GetFormation()->LeaderMoveTo(_destination.x, _destination.y, _destination.z); + creature->GetFormation()->LeaderMoveTo(_x, _y, _z); } return !owner->movespline->Finalized(); diff --git a/src/server/game/Movement/MovementGenerators/PointMovementGenerator.h b/src/server/game/Movement/MovementGenerators/PointMovementGenerator.h index 8fe3d7cbe24..59d8c741d7f 100644 --- a/src/server/game/Movement/MovementGenerators/PointMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/PointMovementGenerator.h @@ -21,11 +21,13 @@ #include "MovementGenerator.h" +class Creature; + template class PointMovementGenerator : public MovementGeneratorMedium< T, PointMovementGenerator > { public: - explicit PointMovementGenerator(uint32 id, float x, float y, float z, bool generatePath, float speed = 0.0f) : _movementId(id), _destination(x, y, z), _speed(speed), _generatePath(generatePath), _recalculateSpeed(false), _interrupt(false) { } + PointMovementGenerator(uint32 id, float x, float y, float z, bool generatePath, float speed = 0.0f) : _movementId(id), _x(x), _y(y), _z(z), _speed(speed), _generatePath(generatePath), _recalculateSpeed(false), _interrupt(false) { } MovementGeneratorType GetMovementGeneratorType() const override { return POINT_MOTION_TYPE; } @@ -39,7 +41,7 @@ class PointMovementGenerator : public MovementGeneratorMedium< T, PointMovementG void MovementInform(T*); uint32 _movementId; - G3D::Vector3 _destination; + float _x, _y, _z; float _speed; bool _generatePath; bool _recalculateSpeed; @@ -49,7 +51,7 @@ class PointMovementGenerator : public MovementGeneratorMedium< T, PointMovementG class AssistanceMovementGenerator : public PointMovementGenerator { public: - explicit AssistanceMovementGenerator(float _x, float _y, float _z) : PointMovementGenerator(0, _x, _y, _z, true) { } + AssistanceMovementGenerator(float _x, float _y, float _z) : PointMovementGenerator(0, _x, _y, _z, true) { } MovementGeneratorType GetMovementGeneratorType() const override { return ASSISTANCE_MOTION_TYPE; } void Finalize(Unit*) override; diff --git a/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.cpp index 8bd2b5dc9ea..29de26b3e4d 100644 --- a/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.cpp @@ -16,13 +16,14 @@ * with this program. If not, see . */ -#include "Creature.h" #include "RandomMovementGenerator.h" -#include "Map.h" -#include "Util.h" +#include "Creature.h" #include "CreatureGroups.h" -#include "MoveSplineInit.h" +#include "Map.h" #include "MoveSpline.h" +#include "MoveSplineInit.h" +#include "Random.h" +#include "Util.h" #define RUNNING_CHANCE_RANDOMMV 20 //will be "1 / RUNNING_CHANCE_RANDOMMV" @@ -170,7 +171,7 @@ template<> bool RandomMovementGenerator::GetResetPos(Creature* creature, float& x, float& y, float& z) { float radius; - creature->GetRespawnPosition(x, y, z, NULL, &radius); + creature->GetRespawnPosition(x, y, z, nullptr, &radius); // use current if in range if (creature->IsWithinDist2d(x, y, radius)) diff --git a/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.h b/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.h index 0f943966d0c..99edbaa2efd 100644 --- a/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/RandomMovementGenerator.h @@ -20,6 +20,7 @@ #define TRINITY_RANDOMMOTIONGENERATOR_H #include "MovementGenerator.h" +#include "Timer.h" template class RandomMovementGenerator : public MovementGeneratorMedium< T, RandomMovementGenerator > @@ -31,7 +32,7 @@ class RandomMovementGenerator : public MovementGeneratorMedium< T, RandomMovemen void DoInitialize(T*); void DoFinalize(T*); void DoReset(T*); - bool DoUpdate(T*, const uint32); + bool DoUpdate(T*, uint32); bool GetResetPos(T*, float& x, float& y, float& z); MovementGeneratorType GetMovementGeneratorType() const override { return RANDOM_MOTION_TYPE; } private: diff --git a/src/server/game/Movement/MovementGenerators/SplineChainMovementGenerator.h b/src/server/game/Movement/MovementGenerators/SplineChainMovementGenerator.h index 27460375f3b..44e15fa3fd8 100644 --- a/src/server/game/Movement/MovementGenerators/SplineChainMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/SplineChainMovementGenerator.h @@ -24,7 +24,7 @@ class TC_GAME_API SplineChainMovementGenerator : public MovementGenerator { public: - explicit SplineChainMovementGenerator(uint32 id, SplineChain const& chain, bool walk = false) : _id(id), _chain(chain), _chainSize(chain.size()), _walk(walk), finished(false), _nextIndex(0), _nextFirstWP(0), _msToNext(0) { } + explicit SplineChainMovementGenerator(uint32 id, std::vector const& chain, bool walk = false) : _id(id), _chain(chain), _chainSize(chain.size()), _walk(walk), finished(false), _nextIndex(0), _nextFirstWP(0), _msToNext(0) { } explicit SplineChainMovementGenerator(SplineChainResumeInfo const& info) : _id(info.PointID), _chain(*info.Chain), _chainSize(info.Chain->size()), _walk(info.IsWalkMode), finished(info.SplineIndex >= info.Chain->size()), _nextIndex(info.SplineIndex), _nextFirstWP(info.PointIndex), _msToNext(info.TimeToNext) { } void Initialize(Unit* me) override; void Finalize(Unit* me) override; @@ -41,7 +41,7 @@ class TC_GAME_API SplineChainMovementGenerator : public MovementGenerator void SendSplineFor(Unit* me, uint32 index, uint32& toNext); uint32 SendPathSpline(Unit* me, Movement::PointsArray const& wp) const; uint32 const _id; - SplineChain const& _chain; + std::vector const& _chain; uint8 const _chainSize; bool const _walk; bool finished; diff --git a/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.cpp index d2b413ca0c1..10c50ae7859 100755 --- a/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/TargetedMovementGenerator.cpp @@ -16,14 +16,15 @@ * with this program. If not, see . */ -#include "CreatureAI.h" +#include "TargetedMovementGenerator.h" #include "Creature.h" +#include "CreatureAI.h" +#include "MoveSpline.h" +#include "MoveSplineInit.h" +#include "PathGenerator.h" #include "Player.h" #include "VehicleDefines.h" -#include "MoveSplineInit.h" -#include "MoveSpline.h" #include "World.h" -#include "TargetedMovementGenerator.h" template TargetedMovementGenerator::~TargetedMovementGenerator() diff --git a/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp index 59f865eff39..0b0f907bd20 100755 --- a/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.cpp @@ -15,21 +15,18 @@ * You should have received a copy of the GNU General Public License along * with this program. If not, see . */ -//Basic headers + #include "WaypointMovementGenerator.h" -//Extended headers -#include "ObjectMgr.h" -#include "Transport.h" -//Flightmaster grid preloading -#include "MapManager.h" -//Creature-specific headers -#include "Creature.h" #include "CreatureAI.h" #include "CreatureGroups.h" -//Player-specific -#include "Player.h" -#include "MoveSplineInit.h" +#include "Log.h" +#include "MapManager.h" #include "MoveSpline.h" +#include "MoveSplineInit.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "Transport.h" +#include "World.h" void WaypointMovementGenerator::LoadPath(Creature* creature) { @@ -105,7 +102,7 @@ bool WaypointMovementGenerator::StartMove(Creature* creature) if (Stopped()) return true; - bool transportPath = creature->GetTransport() != NULL; + bool transportPath = creature->GetTransport() != nullptr; if (m_isArrivalDone) { diff --git a/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.h b/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.h index a684248fd39..a3701183221 100755 --- a/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.h +++ b/src/server/game/Movement/MovementGenerators/WaypointMovementGenerator.h @@ -26,9 +26,11 @@ */ #include "MovementGenerator.h" -#include "WaypointManager.h" +#include "Creature.h" +#include "DBCStructure.h" #include "Player.h" -#include "World.h" +#include "Timer.h" +#include "WaypointManager.h" #define FLIGHT_TRAVEL_UPDATE 100 #define TIMEDIFF_NEXT_WP 250 diff --git a/src/server/game/Movement/MovementStructures.cpp b/src/server/game/Movement/MovementStructures.cpp index ea2655c5244..0d2752a2b1d 100644 --- a/src/server/game/Movement/MovementStructures.cpp +++ b/src/server/game/Movement/MovementStructures.cpp @@ -17,6 +17,7 @@ */ #include "MovementStructures.h" +#include "Log.h" #include "Player.h" MovementStatusElements const PlayerMove[] = @@ -5486,7 +5487,7 @@ bool Movement::PrintInvalidSequenceElement(MovementStatusElements const element, return false; } -Movement::PacketSender::PacketSender(Unit* unit, Opcodes serverControl, Opcodes playerControl, Opcodes broadcast /*= SMSG_PLAYER_MOVE*/, ExtraMovementStatusElement* extras /*= NULL*/) +Movement::PacketSender::PacketSender(Unit* unit, Opcodes serverControl, Opcodes playerControl, Opcodes broadcast /*= SMSG_PLAYER_MOVE*/, ExtraMovementStatusElement* extras /*= nullptr*/) : _extraElements(extras), _unit(unit) { if (unit->GetTypeId() == TYPEID_PLAYER && unit->ToPlayer()->m_unitMovedByMe->GetTypeId() == TYPEID_PLAYER) @@ -5751,5 +5752,5 @@ MovementStatusElements const* GetMovementStatusElementsSequence(Opcodes opcode) break; } - return NULL; + return nullptr; } diff --git a/src/server/game/Movement/MovementStructures.h b/src/server/game/Movement/MovementStructures.h index ed6ac363f6e..d28a863d074 100644 --- a/src/server/game/Movement/MovementStructures.h +++ b/src/server/game/Movement/MovementStructures.h @@ -139,7 +139,7 @@ namespace Movement class PacketSender { public: - PacketSender(Unit* unit, Opcodes serverControl, Opcodes playerControl, Opcodes broadcast = SMSG_PLAYER_MOVE, ExtraMovementStatusElement* extras = NULL); + PacketSender(Unit* unit, Opcodes serverControl, Opcodes playerControl, Opcodes broadcast = SMSG_PLAYER_MOVE, ExtraMovementStatusElement* extras = nullptr); void Send() const; diff --git a/src/server/game/Movement/PathGenerator.cpp b/src/server/game/Movement/PathGenerator.cpp index f8b12913984..9af551a23fb 100644 --- a/src/server/game/Movement/PathGenerator.cpp +++ b/src/server/game/Movement/PathGenerator.cpp @@ -33,8 +33,8 @@ PathGenerator::PathGenerator(const Unit* owner) : _polyLength(0), _type(PATHFIND_BLANK), _useStraightPath(false), _forceDestination(false), _pointPathLimit(MAX_POINT_PATH_LENGTH), _straightLine(false), - _endPosition(G3D::Vector3::zero()), _sourceUnit(owner), _navMesh(NULL), - _navMeshQuery(NULL) + _endPosition(G3D::Vector3::zero()), _sourceUnit(owner), _navMesh(nullptr), + _navMeshQuery(nullptr) { memset(_pathPolyRefs, 0, sizeof(_pathPolyRefs)); @@ -105,7 +105,7 @@ dtPolyRef PathGenerator::GetPathPolyByPosition(dtPolyRef const* polyPath, uint32 for (uint32 i = 0; i < polyPathSize; ++i) { float closestPoint[VERTEX_SIZE]; - if (dtStatusFailed(_navMeshQuery->closestPointOnPoly(polyPath[i], point, closestPoint, NULL))) + if (dtStatusFailed(_navMeshQuery->closestPointOnPoly(polyPath[i], point, closestPoint, nullptr))) continue; float d = dtVdist2DSqr(point, closestPoint); @@ -186,7 +186,7 @@ void PathGenerator::BuildPolyPath(G3D::Vector3 const& startPos, G3D::Vector3 con // Check both start and end points, if they're both in water, then we can *safely* let the creature move for (uint32 i = 0; i < _pathPoints.size(); ++i) { - ZLiquidStatus status = _sourceUnit->GetBaseMap()->GetLiquidStatus(_sourceUnit->GetPhaseShift(), _pathPoints[i].x, _pathPoints[i].y, _pathPoints[i].z, MAP_ALL_LIQUIDS, NULL); + ZLiquidStatus status = _sourceUnit->GetBaseMap()->GetLiquidStatus(_sourceUnit->GetPhaseShift(), _pathPoints[i].x, _pathPoints[i].y, _pathPoints[i].z, MAP_ALL_LIQUIDS, nullptr); // One of the points is not in the water, cancel movement. if (status == LIQUID_MAP_NO_WATER) { @@ -236,7 +236,7 @@ void PathGenerator::BuildPolyPath(G3D::Vector3 const& startPos, G3D::Vector3 con { float closestPoint[VERTEX_SIZE]; // we may want to use closestPointOnPolyBoundary instead - if (dtStatusSucceed(_navMeshQuery->closestPointOnPoly(endPoly, endPoint, closestPoint, NULL))) + if (dtStatusSucceed(_navMeshQuery->closestPointOnPoly(endPoly, endPoint, closestPoint, nullptr))) { dtVcopy(endPoint, closestPoint); SetActualEndPosition(G3D::Vector3(endPoint[2], endPoint[0], endPoint[1])); @@ -335,13 +335,13 @@ void PathGenerator::BuildPolyPath(G3D::Vector3 const& startPos, G3D::Vector3 con // we need any point on our suffix start poly to generate poly-path, so we need last poly in prefix data float suffixEndPoint[VERTEX_SIZE]; - if (dtStatusFailed(_navMeshQuery->closestPointOnPoly(suffixStartPoly, endPoint, suffixEndPoint, NULL))) + if (dtStatusFailed(_navMeshQuery->closestPointOnPoly(suffixStartPoly, endPoint, suffixEndPoint, nullptr))) { // we can hit offmesh connection as last poly - closestPointOnPoly() don't like that // try to recover by using prev polyref --prefixPolyLength; suffixStartPoly = _pathPolyRefs[prefixPolyLength-1]; - if (dtStatusFailed(_navMeshQuery->closestPointOnPoly(suffixStartPoly, endPoint, suffixEndPoint, NULL))) + if (dtStatusFailed(_navMeshQuery->closestPointOnPoly(suffixStartPoly, endPoint, suffixEndPoint, nullptr))) { // suffixStartPoly is still invalid, error state BuildShortcut(); @@ -514,8 +514,8 @@ void PathGenerator::BuildPointPath(const float *startPoint, const float *endPoin _pathPolyRefs, // current path _polyLength, // lenth of current path pathPoints, // [out] path corner points - NULL, // [out] flags - NULL, // [out] shortened path + nullptr, // [out] flags + nullptr, // [out] shortened path (int*)&pointCount, _pointPathLimit); // maximum number of points/polygons to use } @@ -680,7 +680,7 @@ bool PathGenerator::HaveTile(const G3D::Vector3& p) const if (tx < 0 || ty < 0) return false; - return (_navMesh->getTileAt(tx, ty, 0) != NULL); + return (_navMesh->getTileAt(tx, ty, 0) != nullptr); } uint32 PathGenerator::FixupCorridor(dtPolyRef* path, uint32 npath, uint32 maxPath, dtPolyRef const* visited, uint32 nvisited) diff --git a/src/server/game/Movement/PathGenerator.h b/src/server/game/Movement/PathGenerator.h index 3e02e51785d..3575ef7597a 100644 --- a/src/server/game/Movement/PathGenerator.h +++ b/src/server/game/Movement/PathGenerator.h @@ -23,6 +23,7 @@ #include "DetourNavMesh.h" #include "DetourNavMeshQuery.h" #include "MoveSplineInitArgs.h" +#include class Unit; @@ -113,7 +114,7 @@ class TC_GAME_API PathGenerator float Dist3DSqr(G3D::Vector3 const& p1, G3D::Vector3 const& p2) const; bool InRangeYZX(float const* v1, float const* v2, float r, float h) const; - dtPolyRef GetPathPolyByPosition(dtPolyRef const* polyPath, uint32 polyPathSize, float const* Point, float* Distance = NULL) const; + dtPolyRef GetPathPolyByPosition(dtPolyRef const* polyPath, uint32 polyPathSize, float const* Point, float* Distance = nullptr) const; dtPolyRef GetPolyByLocation(float const* Point, float* Distance) const; bool HaveTile(G3D::Vector3 const& p) const; diff --git a/src/server/game/Movement/Spline/MoveSpline.cpp b/src/server/game/Movement/Spline/MoveSpline.cpp index 574b11aabbb..edda63fa156 100644 --- a/src/server/game/Movement/Spline/MoveSpline.cpp +++ b/src/server/game/Movement/Spline/MoveSpline.cpp @@ -117,9 +117,9 @@ struct CommonInitializer } }; -void MoveSpline::init_spline(const MoveSplineInitArgs& args) +void MoveSpline::init_spline(MoveSplineInitArgs const& args) { - const SplineBase::EvaluationMode modes[2] = {SplineBase::ModeLinear, SplineBase::ModeCatmullrom}; + static SplineBase::EvaluationMode const modes[2] = { SplineBase::ModeLinear, SplineBase::ModeCatmullrom }; if (args.flags.cyclic) { uint32 cyclic_point = 0; @@ -129,9 +129,7 @@ void MoveSpline::init_spline(const MoveSplineInitArgs& args) spline.init_cyclic_spline(&args.path[0], args.path.size(), modes[args.flags.isSmooth()], cyclic_point); } else - { spline.init_spline(&args.path[0], args.path.size(), modes[args.flags.isSmooth()]); - } // init spline timestamps if (splineflags.falling) @@ -195,6 +193,15 @@ MoveSpline::MoveSpline() : m_Id(0), time_passed(0), splineflags.done = true; } +MoveSplineInitArgs::MoveSplineInitArgs(size_t path_capacity /*= 16*/) : path_Idx_offset(0), velocity(0.f), +parabolic_amplitude(0.f), time_perc(0.f), splineId(0), initialOrientation(0.f), +HasVelocity(false), TransformForTransport(true) +{ + path.reserve(path_capacity); +} + +MoveSplineInitArgs::~MoveSplineInitArgs() = default; + /// ============================================================================================ bool MoveSplineInitArgs::Validate(Unit* unit) const diff --git a/src/server/game/Movement/Spline/MoveSpline.h b/src/server/game/Movement/Spline/MoveSpline.h index f28f8a38e08..5f246b76f7e 100644 --- a/src/server/game/Movement/Spline/MoveSpline.h +++ b/src/server/game/Movement/Spline/MoveSpline.h @@ -21,6 +21,7 @@ #include "Spline.h" #include "MoveSplineInitArgs.h" +#include namespace Movement { @@ -28,8 +29,8 @@ namespace Movement { Location() : orientation(0) { } Location(float x, float y, float z, float o) : Vector3(x, y, z), orientation(o) { } - Location(const Vector3& v) : Vector3(v), orientation(0) { } - Location(const Vector3& v, float o) : Vector3(v), orientation(o) { } + Location(Vector3 const& v) : Vector3(v), orientation(0) { } + Location(Vector3 const& v, float o) : Vector3(v), orientation(o) { } float orientation; }; @@ -69,7 +70,7 @@ namespace Movement int32 point_Idx; int32 point_Idx_offset; - void init_spline(const MoveSplineInitArgs& args); + void init_spline(MoveSplineInitArgs const& args); protected: MySpline::ControlArray const& getPath() const { return spline.getPoints(); } @@ -90,7 +91,7 @@ namespace Movement void _Interrupt() { splineflags.done = true; } public: - void Initialize(const MoveSplineInitArgs&); + void Initialize(MoveSplineInitArgs const&); bool Initialized() const { return !spline.empty(); } MoveSpline(); diff --git a/src/server/game/Movement/Spline/MoveSplineFlag.h b/src/server/game/Movement/Spline/MoveSplineFlag.h index 633eaab3ea4..07bdbe7aba4 100644 --- a/src/server/game/Movement/Spline/MoveSplineFlag.h +++ b/src/server/game/Movement/Spline/MoveSplineFlag.h @@ -18,9 +18,8 @@ #ifndef TRINITYSERVER_MOVESPLINEFLAG_H #define TRINITYSERVER_MOVESPLINEFLAG_H -#include "MovementTypedefs.h" -#include +#include "MovementTypedefs.h" namespace Movement { @@ -74,11 +73,11 @@ namespace Movement }; inline uint32& raw() { return (uint32&)*this; } - inline const uint32& raw() const { return (const uint32&)*this; } + inline uint32 const& raw() const { return (uint32 const&)*this; } MoveSplineFlag() { raw() = 0; } MoveSplineFlag(uint32 f) { raw() = f; } - MoveSplineFlag(const MoveSplineFlag& f) { raw() = f.raw(); } + MoveSplineFlag(MoveSplineFlag const& f) { raw() = f.raw(); } // Constant interface diff --git a/src/server/game/Movement/Spline/MoveSplineInit.cpp b/src/server/game/Movement/Spline/MoveSplineInit.cpp index 309a9e5b3d8..9fab0ce8519 100644 --- a/src/server/game/Movement/Spline/MoveSplineInit.cpp +++ b/src/server/game/Movement/Spline/MoveSplineInit.cpp @@ -20,9 +20,10 @@ #include "MoveSpline.h" #include "MovementPacketBuilder.h" #include "Unit.h" +#include "PathGenerator.h" #include "Transport.h" -#include "WorldPacket.h" #include "Opcodes.h" +#include "WorldPacket.h" namespace Movement { @@ -184,7 +185,19 @@ namespace Movement args.flags.smoothGroundPath = true; // enabled by default, CatmullRom mode or client config "pathSmoothing" will disable this } - void MoveSplineInit::SetFacing(const Unit* target) + MoveSplineInit::~MoveSplineInit() = default; + + void MoveSplineInit::SetFacing(Vector3 const& spot) + { + TransportPathTransform transform(unit, args.TransformForTransport); + Vector3 finalSpot = transform(spot); + args.facing.f.x = finalSpot.x; + args.facing.f.y = finalSpot.y; + args.facing.f.z = finalSpot.z; + args.flags.EnableFacingPoint(); + } + + void MoveSplineInit::SetFacing(Unit const* target) { args.flags.EnableFacingTarget(); args.facing.target = target->GetGUID().GetRawValue(); @@ -204,7 +217,19 @@ namespace Movement args.flags.EnableFacingAngle(); } - void MoveSplineInit::MoveTo(const Vector3& dest, bool generatePath, bool forceDestination) + void MoveSplineInit::MovebyPath(PointsArray const& controls, int32 path_offset) + { + args.path_Idx_offset = path_offset; + args.path.resize(controls.size()); + std::transform(controls.begin(), controls.end(), args.path.begin(), TransportPathTransform(unit, args.TransformForTransport)); + } + + void MoveSplineInit::MoveTo(float x, float y, float z, bool generatePath, bool forceDestination) + { + MoveTo(G3D::Vector3(x, y, z), generatePath, forceDestination); + } + + void MoveSplineInit::MoveTo(Vector3 const& dest, bool generatePath, bool forceDestination) { if (generatePath) { diff --git a/src/server/game/Movement/Spline/MoveSplineInit.h b/src/server/game/Movement/Spline/MoveSplineInit.h index 47ca8e131e3..e0f89a7138c 100644 --- a/src/server/game/Movement/Spline/MoveSplineInit.h +++ b/src/server/game/Movement/Spline/MoveSplineInit.h @@ -20,13 +20,12 @@ #define TRINITYSERVER_MOVESPLINEINIT_H #include "MoveSplineInitArgs.h" -#include "PathGenerator.h" class Unit; namespace Movement { - enum AnimType + enum AnimType : uint8 { ToGround = 0, // 460 = ToGround, index of AnimationData.dbc FlyToFly = 1, // 461 = FlyToFly? @@ -54,6 +53,9 @@ namespace Movement public: explicit MoveSplineInit(Unit* m); + ~MoveSplineInit(); + MoveSplineInit(MoveSplineInit const&) = delete; + MoveSplineInit& operator=(MoveSplineInit const&) = delete; /* Final pass of initialization that launches spline movement. */ @@ -80,17 +82,17 @@ namespace Movement */ void SetFacing(float angle); void SetFacing(Vector3 const& point); - void SetFacing(const Unit* target); + void SetFacing(Unit const* target); /* Initializes movement by path * @param path - array of points, shouldn't be empty * @param pointId - Id of fisrt point of the path. Example: when third path point will be done it will notify that pointId + 3 done */ - void MovebyPath(const PointsArray& path, int32 pointId = 0); + void MovebyPath(PointsArray const& path, int32 pointId = 0); /* Initializes simple A to B motion, A is current unit's position, B is destination */ - void MoveTo(const Vector3& destination, bool generatePath = true, bool forceDestination = false); + void MoveTo(Vector3 const& destination, bool generatePath = true, bool forceDestination = false); void MoveTo(float x, float y, float z, bool generatePath = true, bool forceDestination = false); /* Sets Id of fisrt point of the path. When N-th path point will be done ILisener will notify that pointId + N done @@ -168,18 +170,6 @@ namespace Movement inline void MoveSplineInit::SetTransportExit() { args.flags.EnableTransportExit(); } inline void MoveSplineInit::SetOrientationFixed(bool enable) { args.flags.orientationFixed = enable; } - inline void MoveSplineInit::MovebyPath(const PointsArray& controls, int32 path_offset) - { - args.path_Idx_offset = path_offset; - args.path.resize(controls.size()); - std::transform(controls.begin(), controls.end(), args.path.begin(), TransportPathTransform(unit, args.TransformForTransport)); - } - - inline void MoveSplineInit::MoveTo(float x, float y, float z, bool generatePath, bool forceDestination) - { - MoveTo(G3D::Vector3(x, y, z), generatePath, forceDestination); - } - inline void MoveSplineInit::SetParabolic(float amplitude, float time_shift) { args.time_perc = time_shift; @@ -193,16 +183,6 @@ namespace Movement args.flags.EnableAnimation((uint8)anim); } - inline void MoveSplineInit::SetFacing(Vector3 const& spot) - { - TransportPathTransform transform(unit, args.TransformForTransport); - Vector3 finalSpot = transform(spot); - args.facing.f.x = finalSpot.x; - args.facing.f.y = finalSpot.y; - args.facing.f.z = finalSpot.z; - args.flags.EnableFacingPoint(); - } - inline void MoveSplineInit::DisableTransportPathTransformations() { args.TransformForTransport = false; } } #endif // TRINITYSERVER_MOVESPLINEINIT_H diff --git a/src/server/game/Movement/Spline/MoveSplineInitArgs.h b/src/server/game/Movement/Spline/MoveSplineInitArgs.h index c331e1c84d3..56a936f1b4a 100644 --- a/src/server/game/Movement/Spline/MoveSplineInitArgs.h +++ b/src/server/game/Movement/Spline/MoveSplineInitArgs.h @@ -20,7 +20,7 @@ #define TRINITYSERVER_MOVESPLINEINIT_ARGS_H #include "MoveSplineFlag.h" -#include +#include class Unit; @@ -43,12 +43,8 @@ namespace Movement struct MoveSplineInitArgs { - MoveSplineInitArgs(size_t path_capacity = 16) : path_Idx_offset(0), velocity(0.f), - parabolic_amplitude(0.f), time_perc(0.f), splineId(0), initialOrientation(0.f), - HasVelocity(false), TransformForTransport(true) - { - path.reserve(path_capacity); - } + MoveSplineInitArgs(size_t path_capacity = 16); + ~MoveSplineInitArgs(); PointsArray path; FacingInfo facing; diff --git a/src/server/game/Movement/Spline/MovementUtil.cpp b/src/server/game/Movement/Spline/MovementUtil.cpp index 0e2d3fb5682..71a132234cb 100644 --- a/src/server/game/Movement/Spline/MovementUtil.cpp +++ b/src/server/game/Movement/Spline/MovementUtil.cpp @@ -184,7 +184,7 @@ namespace Movement { for (int i = 0; i < N; ++i) { - if ((t & Flags(1 << i)) && names[i] != NULL) + if ((t & Flags(1 << i)) && names[i] != nullptr) str.append(" ").append(names[i]); } } diff --git a/src/server/game/Movement/Spline/Spline.cpp b/src/server/game/Movement/Spline/Spline.cpp index 4bc44072db7..ea9eac58eb0 100644 --- a/src/server/game/Movement/Spline/Spline.cpp +++ b/src/server/game/Movement/Spline/Spline.cpp @@ -71,7 +71,7 @@ static const Matrix4 s_Bezier3Coeffs( 1.f, 0.f, 0.f, 0.f); /* classic view: -inline void C_Evaluate(const Vector3 *vertice, float t, const float (&matrix)[4][4], Vector3 &position) +inline void C_Evaluate(Vector3 const* vertice, float t, float const (&matrix)[4][4], Vector3 &position) { Vector3 tvec(t*t*t, t*t, t); int i = 0; @@ -94,7 +94,7 @@ inline void C_Evaluate(const Vector3 *vertice, float t, const float (&matrix)[4] position.z = z; }*/ -inline void C_Evaluate(const Vector3 *vertice, float t, const Matrix4& matr, Vector3 &result) +inline void C_Evaluate(Vector3 const* vertice, float t, Matrix4 const& matr, Vector3 &result) { Vector4 tvec(t*t*t, t*t, t, 1.f); Vector4 weights(tvec * matr); @@ -103,7 +103,7 @@ inline void C_Evaluate(const Vector3 *vertice, float t, const Matrix4& matr, Vec + vertice[2] * weights[2] + vertice[3] * weights[3]; } -inline void C_Evaluate_Derivative(const Vector3 *vertice, float t, const Matrix4& matr, Vector3 &result) +inline void C_Evaluate_Derivative(Vector3 const* vertice, float t, Matrix4 const& matr, Vector3 &result) { Vector4 tvec(3.f*t*t, 2.f*t, 1.f, 0.f); Vector4 weights(tvec * matr); @@ -118,7 +118,7 @@ void SplineBase::EvaluateLinear(index_type index, float u, Vector3& result) cons result = points[index] + (points[index+1] - points[index]) * u; } -void SplineBase::EvaluateCatmullRom( index_type index, float t, Vector3& result) const +void SplineBase::EvaluateCatmullRom(index_type index, float t, Vector3& result) const { ASSERT(index >= index_lo && index < index_hi); C_Evaluate(&points[index - 1], t, s_catmullRomCoeffs, result); @@ -161,7 +161,7 @@ float SplineBase::SegLengthCatmullRom(index_type index) const ASSERT(index >= index_lo && index < index_hi); Vector3 curPos, nextPos; - const Vector3 * p = &points[index - 1]; + Vector3 const* p = &points[index - 1]; curPos = nextPos = p[1]; index_type i = 1; @@ -182,7 +182,7 @@ float SplineBase::SegLengthBezier3(index_type index) const ASSERT(index >= index_lo && index < index_hi); Vector3 curPos, nextPos; - const Vector3 * p = &points[index]; + Vector3 const* p = &points[index]; C_Evaluate(p, 0.f, s_Bezier3Coeffs, nextPos); curPos = nextPos; @@ -199,7 +199,7 @@ float SplineBase::SegLengthBezier3(index_type index) const return length; } -void SplineBase::init_spline(const Vector3 * controls, index_type count, EvaluationMode m) +void SplineBase::init_spline(Vector3 const* controls, index_type count, EvaluationMode m) { m_mode = m; cyclic = false; @@ -207,7 +207,7 @@ void SplineBase::init_spline(const Vector3 * controls, index_type count, Evaluat (this->*initializers[m_mode])(controls, count, 0); } -void SplineBase::init_cyclic_spline(const Vector3 * controls, index_type count, EvaluationMode m, index_type cyclic_point) +void SplineBase::init_cyclic_spline(Vector3 const* controls, index_type count, EvaluationMode m, index_type cyclic_point) { m_mode = m; cyclic = true; @@ -215,7 +215,7 @@ void SplineBase::init_cyclic_spline(const Vector3 * controls, index_type count, (this->*initializers[m_mode])(controls, count, cyclic_point); } -void SplineBase::InitLinear(const Vector3* controls, index_type count, index_type cyclic_point) +void SplineBase::InitLinear(Vector3 const* controls, index_type count, index_type cyclic_point) { ASSERT(count >= 2); const int real_size = count + 1; @@ -235,7 +235,7 @@ void SplineBase::InitLinear(const Vector3* controls, index_type count, index_typ index_hi = cyclic ? count : (count - 1); } -void SplineBase::InitCatmullRom(const Vector3* controls, index_type count, index_type cyclic_point) +void SplineBase::InitCatmullRom(Vector3 const* controls, index_type count, index_type cyclic_point) { const int real_size = count + (cyclic ? (1+2) : (1+1)); @@ -268,7 +268,7 @@ void SplineBase::InitCatmullRom(const Vector3* controls, index_type count, index index_hi = high_index + (cyclic ? 1 : 0); } -void SplineBase::InitBezier3(const Vector3* controls, index_type count, index_type /*cyclic_point*/) +void SplineBase::InitBezier3(Vector3 const* controls, index_type count, index_type /*cyclic_point*/) { index_type c = count / 3u * 3u; index_type t = c / 3u; diff --git a/src/server/game/Movement/Spline/Spline.h b/src/server/game/Movement/Spline/Spline.h index e1155c68860..f08528769a7 100644 --- a/src/server/game/Movement/Spline/Spline.h +++ b/src/server/game/Movement/Spline/Spline.h @@ -20,8 +20,10 @@ #define TRINITYSERVER_SPLINE_H #include "MovementTypedefs.h" +#include "Errors.h" #include #include +#include namespace Movement { @@ -76,10 +78,10 @@ protected: typedef float (SplineBase::*SegLenghtMethtod)(index_type) const; static SegLenghtMethtod seglengths[ModesEnd]; - void InitLinear(const Vector3*, index_type, index_type); - void InitCatmullRom(const Vector3*, index_type, index_type); - void InitBezier3(const Vector3*, index_type, index_type); - typedef void (SplineBase::*InitMethtod)(const Vector3*, index_type, index_type); + void InitLinear(Vector3 const*, index_type, index_type); + void InitCatmullRom(Vector3 const*, index_type, index_type); + void InitBezier3(Vector3 const*, index_type, index_type); + typedef void (SplineBase::*InitMethtod)(Vector3 const*, index_type, index_type); static InitMethtod initializers[ModesEnd]; void UninitializedSpline() const { ABORT();} @@ -108,9 +110,9 @@ public: EvaluationMode mode() const { return (EvaluationMode)m_mode;} bool isCyclic() const { return cyclic;} - const ControlArray& getPoints() const { return points;} + ControlArray const& getPoints() const { return points;} index_type getPointCount() const { return points.size();} - const Vector3& getPoint(index_type i) const { return points[i];} + Vector3 const& getPoint(index_type i) const { return points[i];} /** Initializes spline. Don't call other methods while spline not initialized. */ void init_spline(const Vector3 * controls, index_type count, EvaluationMode m); @@ -169,8 +171,8 @@ public: void computeIndex(float t, index_type& out_idx, float& out_u) const; /** Initializes spline. Don't call other methods while spline not initialized. */ - void init_spline(const Vector3 * controls, index_type count, EvaluationMode m) { SplineBase::init_spline(controls, count, m);} - void init_cyclic_spline(const Vector3 * controls, index_type count, EvaluationMode m, index_type cyclic_point) { SplineBase::init_cyclic_spline(controls, count, m, cyclic_point);} + void init_spline(Vector3 const* controls, index_type count, EvaluationMode m) { SplineBase::init_spline(controls, count, m);} + void init_cyclic_spline(Vector3 const* controls, index_type count, EvaluationMode m, index_type cyclic_point) { SplineBase::init_cyclic_spline(controls, count, m, cyclic_point);} /** Initializes lengths with SplineBase::SegLength method. */ void initLengths(); diff --git a/src/server/game/Movement/Spline/SplineChain.h b/src/server/game/Movement/Spline/SplineChain.h index 1190487bedb..96722ffca82 100644 --- a/src/server/game/Movement/Spline/SplineChain.h +++ b/src/server/game/Movement/Spline/SplineChain.h @@ -19,6 +19,7 @@ #define TRINITY_SPLINECHAIN_H #include "MoveSplineInitArgs.h" +#include struct TC_GAME_API SplineChainLink { @@ -29,17 +30,16 @@ struct TC_GAME_API SplineChainLink uint32 ExpectedDuration; uint32 TimeToNext; }; -typedef std::vector SplineChain; struct TC_GAME_API SplineChainResumeInfo { SplineChainResumeInfo() : PointID(0), Chain(nullptr), IsWalkMode(false), SplineIndex(0), PointIndex(0), TimeToNext(0) { } - SplineChainResumeInfo(uint32 id, SplineChain const* chain, bool walk, uint8 splineIndex, uint8 wpIndex, uint32 msToNext) : + SplineChainResumeInfo(uint32 id, std::vector const* chain, bool walk, uint8 splineIndex, uint8 wpIndex, uint32 msToNext) : PointID(id), Chain(chain), IsWalkMode(walk), SplineIndex(splineIndex), PointIndex(wpIndex), TimeToNext(msToNext) { } bool Empty() const { return Chain == nullptr; } void Clear() { Chain = nullptr; } uint32 PointID; - SplineChain const* Chain; + std::vector const* Chain; bool IsWalkMode; uint8 SplineIndex; uint8 PointIndex; diff --git a/src/server/game/OutdoorPvP/OutdoorPvP.cpp b/src/server/game/OutdoorPvP/OutdoorPvP.cpp index 75fba9bc2c6..84f2dc90a50 100644 --- a/src/server/game/OutdoorPvP/OutdoorPvP.cpp +++ b/src/server/game/OutdoorPvP/OutdoorPvP.cpp @@ -16,16 +16,18 @@ */ #include "OutdoorPvP.h" -#include "OutdoorPvPMgr.h" +#include "CellImpl.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "GridNotifiersImpl.h" +#include "Group.h" +#include "Log.h" +#include "Map.h" +#include "MapManager.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" -#include "Map.h" -#include "Group.h" +#include "OutdoorPvPMgr.h" #include "WorldPacket.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "CellImpl.h" -#include "MapManager.h" class DefenseMessageBuilder { @@ -113,7 +115,7 @@ void OPvPCapturePoint::AddCre(uint32 type, ObjectGuid::LowType guid, uint32 entr m_CreatureTypes[m_Creatures[type]] = type; } -bool OPvPCapturePoint::AddObject(uint32 type, uint32 entry, uint32 map, Position const& pos, G3D::Quat const& rot) +bool OPvPCapturePoint::AddObject(uint32 type, uint32 entry, uint32 map, Position const& pos, QuaternionData const& rot) { if (ObjectGuid::LowType guid = sObjectMgr->AddGOData(entry, map, pos, rot, 0)) { @@ -135,7 +137,7 @@ bool OPvPCapturePoint::AddCreature(uint32 type, uint32 entry, uint32 map, Positi return false; } -bool OPvPCapturePoint::SetCapturePointData(uint32 entry, uint32 map, Position const& pos, G3D::Quat const& rot) +bool OPvPCapturePoint::SetCapturePointData(uint32 entry, uint32 map, Position const& pos, QuaternionData const& rot) { TC_LOG_DEBUG("outdoorpvp", "Creating capture point %u", entry); @@ -474,7 +476,7 @@ void OutdoorPvP::HandleKill(Player* killer, Unit* killed) { if (Group* group = killer->GetGroup()) { - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* groupGuy = itr->GetSource(); @@ -601,7 +603,7 @@ void OutdoorPvP::BroadcastPacket(WorldPacket &data) const 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); + player->SendDirectMessage(&data); } void OutdoorPvP::RegisterZone(uint32 zoneId) @@ -656,7 +658,7 @@ void OutdoorPvP::OnGameObjectRemove(GameObject* go) return; if (OPvPCapturePoint *cp = GetCapturePoint(go->GetSpawnId())) - cp->m_capturePoint = NULL; + cp->m_capturePoint = nullptr; } void OutdoorPvP::OnCreatureCreate(Creature* creature) diff --git a/src/server/game/OutdoorPvP/OutdoorPvP.h b/src/server/game/OutdoorPvP/OutdoorPvP.h index 91764d9b08b..96cf9b7211c 100644 --- a/src/server/game/OutdoorPvP/OutdoorPvP.h +++ b/src/server/game/OutdoorPvP/OutdoorPvP.h @@ -18,11 +18,11 @@ #ifndef OUTDOOR_PVP_H_ #define OUTDOOR_PVP_H_ -#include "Util.h" +#include "GameObjectData.h" +#include "Position.h" #include "SharedDefines.h" #include "ZoneScript.h" - -#include +#include enum OutdoorPvPTypes { @@ -54,7 +54,7 @@ struct go_type uint32 entry; uint32 map; Position pos; - G3D::Quat rot; + QuaternionData rot; }; // struct for creature spawning @@ -65,14 +65,14 @@ struct creature_type Position pos; }; -// some class predefs -class Player; -class GameObject; -class WorldPacket; class Creature; -class Unit; -struct GossipMenuItems; +class GameObject; +class Map; class OutdoorPvP; +class Player; +class Unit; +class WorldPacket; +struct GossipMenuItems; class TC_GAME_API OPvPCapturePoint { @@ -125,11 +125,11 @@ class TC_GAME_API OPvPCapturePoint void AddGO(uint32 type, ObjectGuid::LowType guid, uint32 entry = 0); void AddCre(uint32 type, ObjectGuid::LowType guid, uint32 entry = 0); - bool SetCapturePointData(uint32 entry, uint32 map, Position const& pos, G3D::Quat const& rot); + bool SetCapturePointData(uint32 entry, uint32 map, Position const& pos, QuaternionData const& rot); protected: - bool AddObject(uint32 type, uint32 entry, uint32 map, Position const& pos, G3D::Quat const& rot); + bool AddObject(uint32 type, uint32 entry, uint32 map, Position const& pos, QuaternionData const& rot); bool AddCreature(uint32 type, uint32 entry, uint32 map, Position const& pos, TeamId teamId = TEAM_NEUTRAL, uint32 spawntimedelay = 0); bool DelObject(uint32 type); diff --git a/src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp b/src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp index c37213d04e8..8f0329a8ee0 100644 --- a/src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp +++ b/src/server/game/OutdoorPvP/OutdoorPvPMgr.cpp @@ -16,9 +16,11 @@ */ #include "OutdoorPvPMgr.h" +#include "DatabaseEnv.h" +#include "DisableMgr.h" +#include "Log.h" #include "ObjectMgr.h" #include "Player.h" -#include "DisableMgr.h" #include "ScriptMgr.h" OutdoorPvPMgr::OutdoorPvPMgr() @@ -66,7 +68,7 @@ void OutdoorPvPMgr::InitOutdoorPvP() typeId = fields[0].GetUInt8(); - if (DisableMgr::IsDisabledFor(DISABLE_TYPE_OUTDOORPVP, typeId, NULL)) + if (DisableMgr::IsDisabledFor(DISABLE_TYPE_OUTDOORPVP, typeId, nullptr)) continue; if (typeId >= MAX_OUTDOORPVP_TYPES) @@ -94,7 +96,7 @@ void OutdoorPvPMgr::InitOutdoorPvP() pvp = sScriptMgr->CreateOutdoorPvP(m_OutdoorPvPDatas[i]); if (!pvp) { - TC_LOG_ERROR("outdoorpvp", "Could not initialize OutdoorPvP object for type ID %u; got NULL pointer from script.", uint32(i)); + TC_LOG_ERROR("outdoorpvp", "Could not initialize OutdoorPvP object for type ID %u; got nullptr pointer from script.", uint32(i)); continue; } @@ -149,7 +151,7 @@ OutdoorPvP* OutdoorPvPMgr::GetOutdoorPvPToZoneId(uint32 zoneid) if (itr == m_OutdoorPvPMap.end()) { // no handle for this zone, return - return NULL; + return nullptr; } return itr->second; } @@ -181,7 +183,7 @@ ZoneScript* OutdoorPvPMgr::GetZoneScript(uint32 zoneId) if (itr != m_OutdoorPvPMap.end()) return itr->second; else - return NULL; + return nullptr; } bool OutdoorPvPMgr::HandleOpenGo(Player* player, GameObject* go) diff --git a/src/server/game/OutdoorPvP/OutdoorPvPMgr.h b/src/server/game/OutdoorPvP/OutdoorPvPMgr.h index 5fe26e43e88..e38cf98b698 100644 --- a/src/server/game/OutdoorPvP/OutdoorPvPMgr.h +++ b/src/server/game/OutdoorPvP/OutdoorPvPMgr.h @@ -21,6 +21,8 @@ #define OUTDOORPVP_OBJECTIVE_UPDATE_INTERVAL 1000 #include "OutdoorPvP.h" +#include +#include class Player; class GameObject; diff --git a/src/server/game/Phasing/PhasingHandler.h b/src/server/game/Phasing/PhasingHandler.h index ba88d2f895d..4463ca38eaa 100644 --- a/src/server/game/Phasing/PhasingHandler.h +++ b/src/server/game/Phasing/PhasingHandler.h @@ -26,6 +26,7 @@ class Map; class PhaseShift; class Player; class WorldObject; +class WorldPacket; class TC_GAME_API PhasingHandler { diff --git a/src/server/game/Pools/PoolMgr.cpp b/src/server/game/Pools/PoolMgr.cpp index c03fa8ef5e5..4dbc5850d92 100644 --- a/src/server/game/Pools/PoolMgr.cpp +++ b/src/server/game/Pools/PoolMgr.cpp @@ -18,9 +18,10 @@ #include "PoolMgr.h" #include "Containers.h" -#include "ObjectMgr.h" +#include "DatabaseEnv.h" #include "Log.h" #include "MapManager.h" +#include "ObjectMgr.h" //////////////////////////////////////////////////////////// // template class ActivePoolData diff --git a/src/server/game/PrecompiledHeaders/gamePCH.cpp b/src/server/game/PrecompiledHeaders/gamePCH.cpp deleted file mode 100644 index 11e501ec7f2..00000000000 --- a/src/server/game/PrecompiledHeaders/gamePCH.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "gamePCH.h" diff --git a/src/server/game/PrecompiledHeaders/gamePCH.h b/src/server/game/PrecompiledHeaders/gamePCH.h index c7c6ca5d2d6..c1361e4ceea 100644 --- a/src/server/game/PrecompiledHeaders/gamePCH.h +++ b/src/server/game/PrecompiledHeaders/gamePCH.h @@ -1,10 +1,31 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + //add here most rarely modified headers to speed up debug build compilation -#include "Common.h" -#include "MapManager.h" +#include "Creature.h" +#include "DBCStores.h" +#include "DatabaseEnv.h" +#include "Errors.h" +#include "GameObject.h" #include "Log.h" #include "ObjectAccessor.h" -#include "ObjectDefines.h" -#include "Opcodes.h" -#include "SharedDefines.h" #include "ObjectMgr.h" +#include "Player.h" +#include "World.h" +#include "WorldPacket.h" +#include "WorldSession.h" diff --git a/src/server/game/Quests/QuestDef.cpp b/src/server/game/Quests/QuestDef.cpp index bc8549bcb60..66029a7991f 100644 --- a/src/server/game/Quests/QuestDef.cpp +++ b/src/server/game/Quests/QuestDef.cpp @@ -17,9 +17,12 @@ */ #include "QuestDef.h" +#include "DBCStores.h" +#include "Field.h" +#include "Log.h" +#include "ObjectMgr.h" #include "Player.h" #include "World.h" -#include "ObjectMgr.h" Quest::Quest(Field* questRecord) { diff --git a/src/server/game/Quests/QuestDef.h b/src/server/game/Quests/QuestDef.h index 7480db7bc44..2123f7836b1 100644 --- a/src/server/game/Quests/QuestDef.h +++ b/src/server/game/Quests/QuestDef.h @@ -19,19 +19,15 @@ #ifndef TRINITYCORE_QUEST_H #define TRINITYCORE_QUEST_H -#include "Define.h" -#include "DatabaseEnv.h" +#include "Common.h" +#include "DatabaseEnvFwd.h" +#include "DBCEnums.h" #include "SharedDefines.h" #include "WorldPacket.h" -#include "DBCEnums.h" - -#include #include class Player; -class ObjectMgr; - #define MAX_QUEST_LOG_SIZE 25 #define QUEST_OBJECTIVES_COUNT 4 @@ -97,7 +93,7 @@ enum QuestTradeSkill QUEST_TRSKILL_JEWELCRAFTING = 14 }; -enum QuestStatus +enum QuestStatus : uint8 { QUEST_STATUS_NONE = 0, QUEST_STATUS_COMPLETE = 1, @@ -190,19 +186,19 @@ struct QuestLocale { QuestLocale() { ObjectiveText.resize(QUEST_OBJECTIVES_COUNT); } - StringVector Title; - StringVector Details; - StringVector Objectives; - StringVector OfferRewardText; - StringVector RequestItemsText; - StringVector AreaDescription; - StringVector CompletedText; - std::vector< StringVector > ObjectiveText; + std::vector Title; + std::vector Details; + std::vector Objectives; + std::vector OfferRewardText; + std::vector RequestItemsText; + std::vector AreaDescription; + std::vector CompletedText; + std::vector> ObjectiveText; // new on 4.x - StringVector QuestGiverTextWindow; - StringVector QuestGiverTargetName; - StringVector QuestTurnTextWindow; - StringVector QuestTurnTargetName; + std::vector QuestGiverTextWindow; + std::vector QuestGiverTargetName; + std::vector QuestTurnTextWindow; + std::vector QuestTurnTargetName; }; // This Quest class provides a convenient way to access a few pretotaled (cached) quest details, diff --git a/src/server/game/Reputation/ReputationMgr.cpp b/src/server/game/Reputation/ReputationMgr.cpp index b54045f810e..d8cfc87738e 100644 --- a/src/server/game/Reputation/ReputationMgr.cpp +++ b/src/server/game/Reputation/ReputationMgr.cpp @@ -16,15 +16,16 @@ * with this program. If not, see . */ -#include "DatabaseEnv.h" #include "ReputationMgr.h" +#include "DatabaseEnv.h" #include "DBCStores.h" -#include "Player.h" -#include "WorldPacket.h" -#include "World.h" +#include "Log.h" #include "ObjectMgr.h" -#include "ScriptMgr.h" #include "Opcodes.h" +#include "Player.h" +#include "ScriptMgr.h" +#include "World.h" +#include "WorldPacket.h" #include "WorldSession.h" const int32 ReputationMgr::PointsInRank[MAX_REPUTATION_RANK] = {36000, 3000, 3000, 3000, 6000, 12000, 21000, 1000}; diff --git a/src/server/game/Reputation/ReputationMgr.h b/src/server/game/Reputation/ReputationMgr.h index fc5d42e10fb..8bf67079c23 100644 --- a/src/server/game/Reputation/ReputationMgr.h +++ b/src/server/game/Reputation/ReputationMgr.h @@ -86,13 +86,13 @@ class TC_GAME_API ReputationMgr FactionState const* GetState(FactionEntry const* factionEntry) const { - return factionEntry->CanHaveReputation() ? GetState(factionEntry->reputationListID) : NULL; + return factionEntry->CanHaveReputation() ? GetState(factionEntry->reputationListID) : nullptr; } FactionState const* GetState(RepListID id) const { FactionStateList::const_iterator repItr = _factions.find (id); - return repItr != _factions.end() ? &repItr->second : NULL; + return repItr != _factions.end() ? &repItr->second : nullptr; } bool IsAtWar(uint32 faction_id) const; @@ -112,7 +112,7 @@ class TC_GAME_API ReputationMgr ReputationRank const* GetForcedRankIfAny(FactionTemplateEntry const* factionTemplateEntry) const { ForcedReactions::const_iterator forceItr = _forcedReactions.find(factionTemplateEntry->faction); - return forceItr != _forcedReactions.end() ? &forceItr->second : NULL; + return forceItr != _forcedReactions.end() ? &forceItr->second : nullptr; } public: // modifiers diff --git a/src/server/game/Scripting/ScriptMgr.cpp b/src/server/game/Scripting/ScriptMgr.cpp index 80d4a12d4e9..e47cfd97b1e 100644 --- a/src/server/game/Scripting/ScriptMgr.cpp +++ b/src/server/game/Scripting/ScriptMgr.cpp @@ -17,27 +17,32 @@ */ #include "ScriptMgr.h" -#include "ScriptReloadMgr.h" +#include "Chat.h" #include "Config.h" +#include "Creature.h" +#include "CreatureAIImpl.h" #include "DatabaseEnv.h" #include "DBCStores.h" +#include "GossipDef.h" +#include "InstanceScript.h" +#include "Item.h" +#include "LFGScripts.h" +#include "Log.h" +#include "MapManager.h" #include "ObjectMgr.h" #include "OutdoorPvPMgr.h" +#include "Player.h" +#include "ScriptReloadMgr.h" #include "ScriptSystem.h" -#include "Transport.h" -#include "Vehicle.h" #include "SmartAI.h" #include "SpellInfo.h" +#include "SpellMgr.h" #include "SpellScript.h" -#include "GossipDef.h" -#include "CreatureAIImpl.h" -#include "Player.h" +#include "Transport.h" +#include "Vehicle.h" +#include "Weather.h" #include "WorldPacket.h" #include "WorldSession.h" -#include "Chat.h" -#include "MapManager.h" -#include "LFGScripts.h" -#include "InstanceScript.h" // Trait which indicates whether this script type // must be assigned in the database. @@ -983,7 +988,7 @@ struct TSpellSummary uint8 Effects; // set of enum SelectEffect } *SpellSummary; -ScriptObject::ScriptObject(const char* name) : _name(name) +ScriptObject::ScriptObject(char const* name) : _name(name) { sScriptMgr->IncreaseScriptCount(); } @@ -1508,7 +1513,7 @@ InstanceScript* ScriptMgr::CreateInstanceData(InstanceMap* map) { ASSERT(map); - GET_SCRIPT_RET(InstanceMapScript, map->GetScriptId(), tmpscript, NULL); + GET_SCRIPT_RET(InstanceMapScript, map->GetScriptId(), tmpscript, nullptr); return tmpscript->GetInstanceScript(map); } @@ -1579,7 +1584,7 @@ CreatureAI* ScriptMgr::GetCreatureAI(Creature* creature) { ASSERT(creature); - GET_SCRIPT_RET(CreatureScript, creature->GetScriptId(), tmpscript, NULL); + GET_SCRIPT_RET(CreatureScript, creature->GetScriptId(), tmpscript, nullptr); return tmpscript->GetAI(creature); } @@ -1587,7 +1592,7 @@ GameObjectAI* ScriptMgr::GetGameObjectAI(GameObject* gameobject) { ASSERT(gameobject); - GET_SCRIPT_RET(GameObjectScript, gameobject->GetScriptId(), tmpscript, NULL); + GET_SCRIPT_RET(GameObjectScript, gameobject->GetScriptId(), tmpscript, nullptr); return tmpscript->GetAI(gameobject); } @@ -1604,12 +1609,12 @@ Battleground* ScriptMgr::CreateBattleground(BattlegroundTypeId /*typeId*/) { /// @todo Implement script-side battlegrounds. ABORT(); - return NULL; + return nullptr; } OutdoorPvP* ScriptMgr::CreateOutdoorPvP(uint32 scriptId) { - GET_SCRIPT_RET(OutdoorPvPScript, scriptId, tmpscript, NULL); + GET_SCRIPT_RET(OutdoorPvPScript, scriptId, tmpscript, nullptr); return tmpscript->GetOutdoorPvP(); } @@ -1624,7 +1629,7 @@ std::vector ScriptMgr::GetChatCommands() } // Sort commands in alphabetical order - std::sort(table.begin(), table.end(), [](const ChatCommand& a, const ChatCommand&b) + std::sort(table.begin(), table.end(), [](ChatCommand const& a, ChatCommand const& b) { return strcmp(a.Name, b.Name) < 0; }); @@ -1807,7 +1812,7 @@ void ScriptMgr::OnShutdown() bool ScriptMgr::OnCriteriaCheck(uint32 scriptId, Player* source, Unit* target) { ASSERT(source); - // target can be NULL. + // target can be nullptr. GET_SCRIPT_RET(AchievementCriteriaScript, scriptId, tmpscript, false); return tmpscript->OnCheck(source, target); @@ -2070,7 +2075,7 @@ void ScriptMgr::OnGroupInviteMember(Group* group, ObjectGuid guid) FOREACH_SCRIPT(GroupScript)->OnInviteMember(group, guid); } -void ScriptMgr::OnGroupRemoveMember(Group* group, ObjectGuid guid, RemoveMethod method, ObjectGuid kicker, const char* reason) +void ScriptMgr::OnGroupRemoveMember(Group* group, ObjectGuid guid, RemoveMethod method, ObjectGuid kicker, char const* reason) { ASSERT(group); FOREACH_SCRIPT(GroupScript)->OnRemoveMember(group, guid, method, kicker, reason); @@ -2119,83 +2124,92 @@ void ScriptMgr::ModifySpellDamageTaken(Unit* target, Unit* attacker, int32& dama FOREACH_SCRIPT(PlayerScript)->ModifySpellDamageTaken(target, attacker, damage); } -SpellScriptLoader::SpellScriptLoader(const char* name) +SpellScriptLoader::SpellScriptLoader(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -ServerScript::ServerScript(const char* name) +ServerScript::ServerScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -WorldScript::WorldScript(const char* name) +WorldScript::WorldScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -FormulaScript::FormulaScript(const char* name) +FormulaScript::FormulaScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -UnitScript::UnitScript(const char* name, bool addToScripts) +UnitScript::UnitScript(char const* name, bool addToScripts) : ScriptObject(name) { if (addToScripts) ScriptRegistry::Instance()->AddScript(this); } -WorldMapScript::WorldMapScript(const char* name, uint32 mapId) - : ScriptObject(name), MapScript(mapId) +WorldMapScript::WorldMapScript(char const* name, uint32 mapId) + : ScriptObject(name), MapScript(sMapStore.LookupEntry(mapId)) { + if (!GetEntry()) + TC_LOG_ERROR("scripts", "Invalid WorldMapScript for %u; no such map ID.", mapId); + if (GetEntry() && !GetEntry()->IsWorldMap()) TC_LOG_ERROR("scripts", "WorldMapScript for map %u is invalid.", mapId); ScriptRegistry::Instance()->AddScript(this); } -InstanceMapScript::InstanceMapScript(const char* name, uint32 mapId) - : ScriptObject(name), MapScript(mapId) +InstanceMapScript::InstanceMapScript(char const* name, uint32 mapId) + : ScriptObject(name), MapScript(sMapStore.LookupEntry(mapId)) { + if (!GetEntry()) + TC_LOG_ERROR("scripts", "Invalid InstanceMapScript for %u; no such map ID.", mapId); + if (GetEntry() && !GetEntry()->IsDungeon()) TC_LOG_ERROR("scripts", "InstanceMapScript for map %u is invalid.", mapId); ScriptRegistry::Instance()->AddScript(this); } -BattlegroundMapScript::BattlegroundMapScript(const char* name, uint32 mapId) - : ScriptObject(name), MapScript(mapId) +BattlegroundMapScript::BattlegroundMapScript(char const* name, uint32 mapId) + : ScriptObject(name), MapScript(sMapStore.LookupEntry(mapId)) { + if (!GetEntry()) + TC_LOG_ERROR("scripts", "Invalid BattlegroundMapScript for %u; no such map ID.", mapId); + if (GetEntry() && !GetEntry()->IsBattleground()) TC_LOG_ERROR("scripts", "BattlegroundMapScript for map %u is invalid.", mapId); ScriptRegistry::Instance()->AddScript(this); } -ItemScript::ItemScript(const char* name) +ItemScript::ItemScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -CreatureScript::CreatureScript(const char* name) +CreatureScript::CreatureScript(char const* name) : UnitScript(name, false) { ScriptRegistry::Instance()->AddScript(this); } -GameObjectScript::GameObjectScript(const char* name) +GameObjectScript::GameObjectScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -AreaTriggerScript::AreaTriggerScript(const char* name) +AreaTriggerScript::AreaTriggerScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); @@ -2217,85 +2231,85 @@ void OnlyOnceAreaTriggerScript::ResetAreaTriggerDone(InstanceScript* script, uin void OnlyOnceAreaTriggerScript::ResetAreaTriggerDone(Player const* player, AreaTriggerEntry const* trigger) { if (InstanceScript* instance = player->GetInstanceScript()) ResetAreaTriggerDone(instance, trigger->id); } -BattlegroundScript::BattlegroundScript(const char* name) +BattlegroundScript::BattlegroundScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -OutdoorPvPScript::OutdoorPvPScript(const char* name) +OutdoorPvPScript::OutdoorPvPScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -CommandScript::CommandScript(const char* name) +CommandScript::CommandScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -WeatherScript::WeatherScript(const char* name) +WeatherScript::WeatherScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -AuctionHouseScript::AuctionHouseScript(const char* name) +AuctionHouseScript::AuctionHouseScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -ConditionScript::ConditionScript(const char* name) +ConditionScript::ConditionScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -VehicleScript::VehicleScript(const char* name) +VehicleScript::VehicleScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -DynamicObjectScript::DynamicObjectScript(const char* name) +DynamicObjectScript::DynamicObjectScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -TransportScript::TransportScript(const char* name) +TransportScript::TransportScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -AchievementCriteriaScript::AchievementCriteriaScript(const char* name) +AchievementCriteriaScript::AchievementCriteriaScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -PlayerScript::PlayerScript(const char* name) +PlayerScript::PlayerScript(char const* name) : UnitScript(name, false) { ScriptRegistry::Instance()->AddScript(this); } -AccountScript::AccountScript(const char* name) +AccountScript::AccountScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -GuildScript::GuildScript(const char* name) +GuildScript::GuildScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); } -GroupScript::GroupScript(const char* name) +GroupScript::GroupScript(char const* name) : ScriptObject(name) { ScriptRegistry::Instance()->AddScript(this); diff --git a/src/server/game/Scripting/ScriptMgr.h b/src/server/game/Scripting/ScriptMgr.h index a725b9bb21c..e2cec401611 100644 --- a/src/server/game/Scripting/ScriptMgr.h +++ b/src/server/game/Scripting/ScriptMgr.h @@ -20,12 +20,8 @@ #define SC_SCRIPTMGR_H #include "Common.h" -#include -#include "DBCStores.h" -#include "QuestDef.h" -#include "SharedDefines.h" -#include "World.h" -#include "Weather.h" +#include "ObjectGuid.h" +#include class AccountMgr; class AuctionHouseObject; @@ -59,17 +55,32 @@ class SpellCastTargets; class Transport; class Unit; class Vehicle; +class Weather; class WorldPacket; class WorldSocket; class WorldObject; class WorldSession; struct AuctionEntry; +struct AreaTriggerEntry; struct ConditionSourceInfo; struct Condition; struct CreatureTemplate; struct CreatureData; struct ItemTemplate; +struct MapEntry; + +enum BattlegroundTypeId : uint32; +enum ContentLevels : uint8; +enum Difficulty : uint8; +enum DuelCompleteType : uint8; +enum QuestStatus : uint8; +enum RemoveMethod : uint8; +enum ShutdownExitCode : uint32; +enum ShutdownMask : uint32; +enum SpellEffIndex : uint8; +enum WeatherState : uint32; +enum XPColorChar : uint8; #define VISIBLE_RANGE 166.0f //MAX visible range (size of grid) @@ -99,7 +110,7 @@ struct ItemTemplate; protected: - MyScriptType(const char* name, uint32 someId) + MyScriptType(char const* name, uint32 someId) : ScriptObject(name), _someId(someId) { ScriptRegistry::AddScript(this); @@ -160,7 +171,7 @@ class TC_GAME_API ScriptObject protected: - ScriptObject(const char* name); + ScriptObject(char const* name); virtual ~ScriptObject(); private: @@ -187,7 +198,7 @@ class TC_GAME_API SpellScriptLoader : public ScriptObject { protected: - SpellScriptLoader(const char* name); + SpellScriptLoader(char const* name); public: @@ -202,7 +213,7 @@ class TC_GAME_API ServerScript : public ScriptObject { protected: - ServerScript(const char* name); + ServerScript(char const* name); public: @@ -232,7 +243,7 @@ class TC_GAME_API WorldScript : public ScriptObject { protected: - WorldScript(const char* name); + WorldScript(char const* name); public: @@ -265,7 +276,7 @@ class TC_GAME_API FormulaScript : public ScriptObject { protected: - FormulaScript(const char* name); + FormulaScript(char const* name); public: @@ -297,16 +308,11 @@ template class MapScript : public UpdatableScript protected: - MapScript(uint32 mapId) - : _mapEntry(sMapStore.LookupEntry(mapId)) - { - if (!_mapEntry) - TC_LOG_ERROR("scripts", "Invalid MapScript for %u; no such map ID.", mapId); - } + MapScript(MapEntry const* mapEntry) : _mapEntry(mapEntry) { } public: - // Gets the MapEntry structure associated with this script. Can return NULL. + // Gets the MapEntry structure associated with this script. Can return nullptr. MapEntry const* GetEntry() { return _mapEntry; } // Called when the map is created. @@ -332,7 +338,7 @@ class TC_GAME_API WorldMapScript : public ScriptObject, public MapScript { protected: - WorldMapScript(const char* name, uint32 mapId); + WorldMapScript(char const* name, uint32 mapId); }; class TC_GAME_API InstanceMapScript @@ -340,26 +346,26 @@ class TC_GAME_API InstanceMapScript { protected: - InstanceMapScript(const char* name, uint32 mapId); + InstanceMapScript(char const* name, uint32 mapId); public: // Gets an InstanceScript object for this instance. - virtual InstanceScript* GetInstanceScript(InstanceMap* /*map*/) const { return NULL; } + virtual InstanceScript* GetInstanceScript(InstanceMap* /*map*/) const { return nullptr; } }; class TC_GAME_API BattlegroundMapScript : public ScriptObject, public MapScript { protected: - BattlegroundMapScript(const char* name, uint32 mapId); + BattlegroundMapScript(char const* name, uint32 mapId); }; class TC_GAME_API ItemScript : public ScriptObject { protected: - ItemScript(const char* name); + ItemScript(char const* name); public: @@ -384,7 +390,7 @@ class TC_GAME_API UnitScript : public ScriptObject { protected: - UnitScript(const char* name, bool addToScripts = true); + UnitScript(char const* name, bool addToScripts = true); public: // Called when a unit deals healing to another unit @@ -407,7 +413,7 @@ class TC_GAME_API CreatureScript : public UnitScript { protected: - CreatureScript(const char* name); + CreatureScript(char const* name); public: @@ -422,7 +428,7 @@ class TC_GAME_API GameObjectScript : public ScriptObject, public UpdatableScript { protected: - GameObjectScript(const char* name); + GameObjectScript(char const* name); public: @@ -434,7 +440,7 @@ class TC_GAME_API AreaTriggerScript : public ScriptObject { protected: - AreaTriggerScript(const char* name); + AreaTriggerScript(char const* name); public: @@ -459,7 +465,7 @@ class TC_GAME_API BattlegroundScript : public ScriptObject { protected: - BattlegroundScript(const char* name); + BattlegroundScript(char const* name); public: @@ -471,7 +477,7 @@ class TC_GAME_API OutdoorPvPScript : public ScriptObject { protected: - OutdoorPvPScript(const char* name); + OutdoorPvPScript(char const* name); public: @@ -483,7 +489,7 @@ class TC_GAME_API CommandScript : public ScriptObject { protected: - CommandScript(const char* name); + CommandScript(char const* name); public: @@ -495,7 +501,7 @@ class TC_GAME_API WeatherScript : public ScriptObject, public UpdatableScript { protected: - TransportScript(const char* name); + TransportScript(char const* name); public: @@ -595,7 +601,7 @@ class TC_GAME_API AchievementCriteriaScript : public ScriptObject { protected: - AchievementCriteriaScript(const char* name); + AchievementCriteriaScript(char const* name); public: @@ -607,7 +613,7 @@ class TC_GAME_API PlayerScript : public UnitScript { protected: - PlayerScript(const char* name); + PlayerScript(char const* name); public: @@ -707,7 +713,7 @@ class TC_GAME_API AccountScript : public ScriptObject { protected: - AccountScript(const char* name); + AccountScript(char const* name); public: @@ -734,7 +740,7 @@ class TC_GAME_API GuildScript : public ScriptObject { protected: - GuildScript(const char* name); + GuildScript(char const* name); public: @@ -775,7 +781,7 @@ class TC_GAME_API GroupScript : public ScriptObject { protected: - GroupScript(const char* name); + GroupScript(char const* name); public: @@ -786,7 +792,7 @@ class TC_GAME_API GroupScript : public ScriptObject virtual void OnInviteMember(Group* /*group*/, ObjectGuid /*guid*/) { } // Called when a member is removed from a group. - virtual void OnRemoveMember(Group* /*group*/, ObjectGuid /*guid*/, RemoveMethod /*method*/, ObjectGuid /*kicker*/, const char* /*reason*/) { } + virtual void OnRemoveMember(Group* /*group*/, ObjectGuid /*guid*/, RemoveMethod /*method*/, ObjectGuid /*kicker*/, char const* /*reason*/) { } // Called when the leader of a group is changed. virtual void OnChangeLeader(Group* /*group*/, ObjectGuid /*newLeaderGuid*/, ObjectGuid /*oldLeaderGuid*/) { } @@ -1040,7 +1046,7 @@ class TC_GAME_API ScriptMgr void OnGroupAddMember(Group* group, ObjectGuid guid); void OnGroupInviteMember(Group* group, ObjectGuid guid); - void OnGroupRemoveMember(Group* group, ObjectGuid guid, RemoveMethod method, ObjectGuid kicker, const char* reason); + void OnGroupRemoveMember(Group* group, ObjectGuid guid, RemoveMethod method, ObjectGuid kicker, char const* reason); void OnGroupChangeLeader(Group* group, ObjectGuid newLeaderGuid, ObjectGuid oldLeaderGuid); void OnGroupDisband(Group* group); diff --git a/src/server/game/Scripting/ScriptSystem.cpp b/src/server/game/Scripting/ScriptSystem.cpp index 154526e212c..2068d033358 100644 --- a/src/server/game/Scripting/ScriptSystem.cpp +++ b/src/server/game/Scripting/ScriptSystem.cpp @@ -17,10 +17,15 @@ */ #include "ScriptSystem.h" -#include "ObjectMgr.h" -#include "DatabaseEnv.h" -#include "ScriptMgr.h" #include "Creature.h" +#include "DatabaseEnv.h" +#include "Log.h" +#include "ObjectMgr.h" +#include "ScriptMgr.h" +#include "SplineChain.h" + +SystemMgr::SystemMgr() = default; +SystemMgr::~SystemMgr() = default; SystemMgr* SystemMgr::instance() { @@ -108,7 +113,7 @@ void SystemMgr::LoadScriptSplineChains() uint32 entry = fieldsMeta[0].GetUInt32(); uint16 chainId = fieldsMeta[1].GetUInt16(); uint8 splineId = fieldsMeta[2].GetUInt8(); - SplineChain& chain = m_mSplineChainsMap[{entry,chainId}]; + std::vector& chain = m_mSplineChainsMap[{entry,chainId}]; if (splineId != chain.size()) { @@ -116,8 +121,9 @@ void SystemMgr::LoadScriptSplineChains() continue; } - uint32 expectedDuration = fieldsMeta[3].GetUInt32(), msUntilNext = fieldsMeta[4].GetUInt32(); - chain.push_back(SplineChainLink(expectedDuration, msUntilNext)); + uint32 expectedDuration = fieldsMeta[3].GetUInt32(); + uint32 msUntilNext = fieldsMeta[4].GetUInt32(); + chain.emplace_back(expectedDuration, msUntilNext); if (splineId == 0) ++chainCount; @@ -137,7 +143,7 @@ void SystemMgr::LoadScriptSplineChains() TC_LOG_WARN("server.loading", "Creature #%u has waypoint data for spline chain %u. No such chain exists - entry skipped.", entry, chainId); continue; } - SplineChain& chain = it->second; + std::vector& chain = it->second; if (splineId >= chain.size()) { TC_LOG_WARN("server.loading", "Creature #%u has waypoint data for spline (%u,%u). The specified chain does not have a spline with this index - entry skipped.", entry, chainId, splineId); @@ -157,7 +163,15 @@ void SystemMgr::LoadScriptSplineChains() } } -SplineChain const* SystemMgr::GetSplineChain(Creature const* who, uint16 id) const +std::vector const* SystemMgr::GetSplineChain(uint32 entry, uint16 chainId) const +{ + auto it = m_mSplineChainsMap.find({ entry, chainId }); + if (it == m_mSplineChainsMap.end()) + return nullptr; + return &it->second; +} + +std::vector const* SystemMgr::GetSplineChain(Creature const* who, uint16 id) const { return GetSplineChain(who->GetEntry(), id); } diff --git a/src/server/game/Scripting/ScriptSystem.h b/src/server/game/Scripting/ScriptSystem.h index 1182283921d..ce51f01f565 100644 --- a/src/server/game/Scripting/ScriptSystem.h +++ b/src/server/game/Scripting/ScriptSystem.h @@ -19,10 +19,13 @@ #ifndef SC_SYSTEM_H #define SC_SYSTEM_H -#include "ScriptMgr.h" -#include "SplineChain.h" +#include "Define.h" +#include "Hash.h" +#include +#include class Creature; +struct SplineChainLink; struct ScriptPointMove { @@ -39,8 +42,8 @@ typedef std::vector ScriptPointVector; class TC_GAME_API SystemMgr { private: - SystemMgr() { } - ~SystemMgr() { } + SystemMgr(); + ~SystemMgr(); public: static SystemMgr* instance(); @@ -61,20 +64,13 @@ class TC_GAME_API SystemMgr return &itr->second; } - SplineChain const* GetSplineChain(uint32 entry, uint16 chainId) const - { - auto it = m_mSplineChainsMap.find({ entry, chainId }); - if (it == m_mSplineChainsMap.end()) - return nullptr; - return &it->second; - } - - SplineChain const* GetSplineChain(Creature const* who, uint16 id) const; + std::vector const* GetSplineChain(uint32 entry, uint16 chainId) const; + std::vector const* GetSplineChain(Creature const* who, uint16 id) const; protected: PointMoveMap m_mPointMoveMap; //coordinates for waypoints typedef std::pair ChainKeyType; // creature entry + chain ID - std::unordered_map m_mSplineChainsMap; // spline chains + std::unordered_map> m_mSplineChainsMap; // spline chains }; #define sScriptSystemMgr SystemMgr::instance() diff --git a/src/server/game/Server/Protocol/Opcodes.cpp b/src/server/game/Server/Protocol/Opcodes.cpp index d080b86d2a5..629b4cb3cdb 100644 --- a/src/server/game/Server/Protocol/Opcodes.cpp +++ b/src/server/game/Server/Protocol/Opcodes.cpp @@ -17,10 +17,24 @@ */ #include "Opcodes.h" +#include "Log.h" #include "WorldSession.h" +#include +#include OpcodeTable opcodeTable; +OpcodeTable::OpcodeTable() +{ + memset(_internalTable, 0, sizeof(_internalTable)); +} + +OpcodeTable::~OpcodeTable() +{ + for (uint16 i = 0; i < NUM_OPCODE_HANDLERS; ++i) + delete _internalTable[i]; +} + template void OpcodeTable::ValidateAndSetOpcode(uint16 /*opcode*/, char const* /*name*/, SessionStatus /*status*/, PacketProcessing /*processing*/, pOpcodeHandler /*handler*/) { @@ -30,7 +44,7 @@ void OpcodeTable::ValidateAndSetOpcode(uint16 /*opcode*/, char const* /*name*/, template<> void OpcodeTable::ValidateAndSetOpcode(uint16 opcode, char const* name, SessionStatus status, PacketProcessing processing, pOpcodeHandler handler) { - if (_internalTable[opcode] != NULL) + if (_internalTable[opcode] != nullptr) { TC_LOG_ERROR("network", "Tried to override handler of %s with %s (opcode %u)", opcodeTable[opcode]->Name, name, opcode); return; @@ -1656,4 +1670,29 @@ void OpcodeTable::Initialize() //DEFINE_OPCODE_HANDLER(SMSG_ZONE_MAP, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); #undef DEFINE_OPCODE_HANDLER -}; +} + +/// Lookup opcode name for human understandable logging +std::string GetOpcodeNameForLogging(uint32 id) +{ + uint32 opcode = uint32(id); + std::ostringstream ss; + ss << '['; + + if (id < UNKNOWN_OPCODE) + { + if (OpcodeHandler const* handler = opcodeTable[uint32(id) & 0x7FFF]) + { + ss << handler->Name; + if (opcode & COMPRESSED_OPCODE_MASK) + ss << "_COMPRESSED"; + } + else + ss << "UNKNOWN OPCODE"; + } + else + ss << "INVALID OPCODE"; + + ss << " 0x" << std::hex << std::uppercase << opcode << std::nouppercase << " (" << std::dec << opcode << ")]"; + return ss.str(); +} diff --git a/src/server/game/Server/Protocol/Opcodes.h b/src/server/game/Server/Protocol/Opcodes.h index 76720e870d4..3f9daf2a29e 100644 --- a/src/server/game/Server/Protocol/Opcodes.h +++ b/src/server/game/Server/Protocol/Opcodes.h @@ -23,7 +23,8 @@ #ifndef _OPCODES_H #define _OPCODES_H -#include "Common.h" +#include "Define.h" +#include /// List of Opcodes enum Opcodes @@ -1386,10 +1387,10 @@ enum Opcodes /// Player state enum SessionStatus { - STATUS_AUTHED = 0, // Player authenticated (_player == NULL, m_playerRecentlyLogout = false or will be reset before handler call, m_GUID have garbage) - STATUS_LOGGEDIN, // Player in game (_player != NULL, m_GUID == _player->GetGUID(), inWorld()) - STATUS_TRANSFER, // Player transferring to another map (_player != NULL, m_GUID == _player->GetGUID(), !inWorld()) - STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT, // _player != NULL or _player == NULL && m_playerRecentlyLogout && m_playerLogout, m_GUID store last _player guid) + STATUS_AUTHED = 0, // Player authenticated (_player == nullptr, m_playerRecentlyLogout = false or will be reset before handler call, m_GUID have garbage) + STATUS_LOGGEDIN, // Player in game (_player != nullptr, m_GUID == _player->GetGUID(), inWorld()) + STATUS_TRANSFER, // Player transferring to another map (_player != nullptr, m_GUID == _player->GetGUID(), !inWorld()) + STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT, // _player != nullptr or _player == nullptr && m_playerRecentlyLogout && m_playerLogout, m_GUID store last _player guid) STATUS_NEVER, // Opcode not accepted from client (deprecated or server side only) STATUS_UNHANDLED // Opcode not handled yet }; @@ -1407,11 +1408,9 @@ class WorldSession; typedef void(WorldSession::*pOpcodeHandler)(WorldPacket& recvPacket); -#pragma pack(push, 1) - struct OpcodeHandler { - OpcodeHandler() {} + OpcodeHandler() { } OpcodeHandler(char const* _name, SessionStatus _status, PacketProcessing _processing, pOpcodeHandler _handler) : Handler(_handler), Name(_name), Status(_status), ProcessingPlace(_processing) {} @@ -1424,16 +1423,8 @@ struct OpcodeHandler class OpcodeTable { public: - OpcodeTable() - { - memset(_internalTable, 0, sizeof(_internalTable)); - } - - ~OpcodeTable() - { - for (uint16 i = 0; i < NUM_OPCODE_HANDLERS; ++i) - delete _internalTable[i]; - } + OpcodeTable(); + ~OpcodeTable(); void Initialize(); @@ -1447,42 +1438,16 @@ class OpcodeTable void ValidateAndSetOpcode(uint16 opcode, char const* name, SessionStatus status, PacketProcessing processing, pOpcodeHandler handler); // Prevent copying this structure - OpcodeTable(OpcodeTable const&); - OpcodeTable& operator=(OpcodeTable const&); + OpcodeTable(OpcodeTable const&) = delete; + OpcodeTable& operator=(OpcodeTable const&) = delete; OpcodeHandler* _internalTable[NUM_OPCODE_HANDLERS]; }; extern OpcodeTable opcodeTable; -#pragma pack(pop) - -void InitOpcodes(); - /// Lookup opcode name for human understandable logging -inline std::string GetOpcodeNameForLogging(uint32 id) -{ - uint32 opcode = uint32(id); - std::ostringstream ss; - ss << '['; - - if (id < UNKNOWN_OPCODE) - { - if (OpcodeHandler const* handler = opcodeTable[uint32(id) & 0x7FFF]) - { - ss << handler->Name; - if (opcode & COMPRESSED_OPCODE_MASK) - ss << "_COMPRESSED"; - } - else - ss << "UNKNOWN OPCODE"; - } - else - ss << "INVALID OPCODE"; - - ss << " 0x" << std::hex << std::uppercase << opcode << std::nouppercase << " (" << std::dec << opcode << ")]"; - return ss.str(); -} +std::string GetOpcodeNameForLogging(uint32 id); #endif /// @} diff --git a/src/server/game/Server/Protocol/PacketLog.cpp b/src/server/game/Server/Protocol/PacketLog.cpp index f2e538075da..6ed86cae70c 100644 --- a/src/server/game/Server/Protocol/PacketLog.cpp +++ b/src/server/game/Server/Protocol/PacketLog.cpp @@ -17,8 +17,9 @@ #include "PacketLog.h" #include "Config.h" -#include "WorldPacket.h" +#include "IpAddress.h" #include "Timer.h" +#include "WorldPacket.h" #pragma pack(push, 1) @@ -56,7 +57,7 @@ struct PacketHeader #pragma pack(pop) -PacketLog::PacketLog() : _file(NULL) +PacketLog::PacketLog() : _file(nullptr) { std::call_once(_initializeFlag, &PacketLog::Initialize, this); } @@ -66,7 +67,7 @@ PacketLog::~PacketLog() if (_file) fclose(_file); - _file = NULL; + _file = nullptr; } PacketLog* PacketLog::instance() @@ -95,7 +96,7 @@ void PacketLog::Initialize() header.Build = 15595; header.Locale[0] = 'e'; header.Locale[1] = 'n'; header.Locale[2] = 'U'; header.Locale[3] = 'S'; std::memset(header.SessionKey, 0, sizeof(header.SessionKey)); - header.SniffStartUnixtime = time(NULL); + header.SniffStartUnixtime = time(nullptr); header.SniffStartTicks = getMSTime(); header.OptionalDataSize = 0; diff --git a/src/server/game/Server/Protocol/PacketLog.h b/src/server/game/Server/Protocol/PacketLog.h index 5aefa95f732..d2a9a61ac87 100644 --- a/src/server/game/Server/Protocol/PacketLog.h +++ b/src/server/game/Server/Protocol/PacketLog.h @@ -43,7 +43,7 @@ class TC_GAME_API PacketLog static PacketLog* instance(); void Initialize(); - bool CanLogPacket() const { return (_file != NULL); } + bool CanLogPacket() const { return (_file != nullptr); } void LogPacket(WorldPacket const& packet, Direction direction, boost::asio::ip::address const& addr, uint16 port); private: diff --git a/src/server/game/Server/WorldPacket.cpp b/src/server/game/Server/WorldPacket.cpp index 379ed906499..c1d934a7b75 100644 --- a/src/server/game/Server/WorldPacket.cpp +++ b/src/server/game/Server/WorldPacket.cpp @@ -15,9 +15,11 @@ * with this program. If not, see . */ -#include #include "WorldPacket.h" +#include "Errors.h" +#include "Log.h" #include "World.h" +#include //! Compresses packet in place void WorldPacket::Compress(z_stream* compressionStream) diff --git a/src/server/game/Server/WorldSession.cpp b/src/server/game/Server/WorldSession.cpp index 384ea3ee405..046c880bab3 100644 --- a/src/server/game/Server/WorldSession.cpp +++ b/src/server/game/Server/WorldSession.cpp @@ -20,36 +20,37 @@ \ingroup u2w */ -#include "WorldSocket.h" -#include "Config.h" -#include "Common.h" -#include "DatabaseEnv.h" -#include "QueryCallback.h" -#include "AccountMgr.h" -#include "Log.h" -#include "Opcodes.h" -#include "WorldPacket.h" #include "WorldSession.h" -#include "Player.h" -#include "Vehicle.h" -#include "ObjectMgr.h" -#include "GuildMgr.h" +#include "AccountMgr.h" +#include "AddonMgr.h" +#include "BattlegroundMgr.h" +#include "BattlenetServerManager.h" +#include "Common.h" +#include "Config.h" +#include "DatabaseEnv.h" #include "Group.h" #include "Guild.h" -#include "World.h" -#include "ObjectAccessor.h" -#include "BattlegroundMgr.h" -#include "OutdoorPvPMgr.h" +#include "GuildMgr.h" +#include "Log.h" #include "MapManager.h" -#include "SocialMgr.h" -#include "ScriptMgr.h" -#include "Transport.h" -#include "WardenWin.h" -#include "WardenMac.h" -#include "WardenMac.h" #include "Metric.h" -#include "BattlenetServerManager.h" - +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Opcodes.h" +#include "OutdoorPvPMgr.h" +#include "Player.h" +#include "QueryCallback.h" +#include "QueryHolder.h" +#include "ScriptMgr.h" +#include "SocialMgr.h" +#include "Transport.h" +#include "Vehicle.h" +#include "WardenMac.h" +#include "WardenMac.h" +#include "WardenWin.h" +#include "World.h" +#include "WorldPacket.h" +#include "WorldSocket.h" #include namespace { @@ -106,14 +107,14 @@ WorldSession::WorldSession(uint32 id, std::string&& name, uint32 battlenetAccoun m_timeOutTime(0), AntiDOS(this), m_GUIDLow(0), - _player(NULL), + _player(nullptr), m_Socket(sock), _security(sec), _accountId(id), _accountName(std::move(name)), _battlenetAccountId(battlenetAccountId), m_expansion(expansion), - _warden(NULL), + _warden(nullptr), _logoutTime(0), m_inQueue(false), m_playerLoading(false), @@ -128,7 +129,7 @@ WorldSession::WorldSession(uint32 id, std::string&& name, uint32 battlenetAccoun _filterAddonMessages(false), recruiterId(recruiter), isRecruiter(isARecruiter), - _RBACData(NULL), + _RBACData(nullptr), expireTime(60000), // 1 min after socket loss, session is deleted forceExit(false), m_currentBankerGUID() @@ -143,11 +144,11 @@ WorldSession::WorldSession(uint32 id, std::string&& name, uint32 battlenetAccoun } _compressionStream = new z_stream(); - _compressionStream->zalloc = (alloc_func)NULL; - _compressionStream->zfree = (free_func)NULL; - _compressionStream->opaque = (voidpf)NULL; + _compressionStream->zalloc = (alloc_func)nullptr; + _compressionStream->zfree = (free_func)nullptr; + _compressionStream->opaque = (voidpf)nullptr; _compressionStream->avail_in = 0; - _compressionStream->next_in = NULL; + _compressionStream->next_in = nullptr; int32 z_res = deflateInit(_compressionStream, sWorld->getIntConfig(CONFIG_COMPRESSION)); if (z_res != Z_OK) TC_LOG_ERROR("network", "Can't initialize packet compression (zlib: deflateInit) Error code: %i (%s)", z_res, zError(z_res)); @@ -171,7 +172,7 @@ WorldSession::~WorldSession() delete _RBACData; ///- empty incoming packet queue - WorldPacket* packet = NULL; + WorldPacket* packet = nullptr; while (_recvQueue.next(packet)) delete packet; @@ -186,7 +187,7 @@ WorldSession::~WorldSession() std::string const & WorldSession::GetPlayerName() const { - return _player != NULL ? _player->GetName() : DefaultPlayerName; + return _player != nullptr ? _player->GetName() : DefaultPlayerName; } std::string WorldSession::GetPlayerInfo() const @@ -240,21 +241,21 @@ void WorldSession::SendPacket(WorldPacket const* packet, bool forced /*= false*/ static uint64 sendPacketCount = 0; static uint64 sendPacketBytes = 0; - static time_t firstTime = time(NULL); + static time_t firstTime = time(nullptr); static time_t lastTime = firstTime; // next 60 secs start time static uint64 sendLastPacketCount = 0; static uint64 sendLastPacketBytes = 0; - time_t cur_time = time(NULL); + time_t cur_time = time(nullptr); if ((cur_time - lastTime) < 60) { - sendPacketCount+=1; - sendPacketBytes+=packet->size(); + sendPacketCount += 1; + sendPacketBytes += packet->size(); - sendLastPacketCount+=1; - sendLastPacketBytes+=packet->size(); + sendLastPacketCount += 1; + sendLastPacketBytes += packet->size(); } else { @@ -282,7 +283,7 @@ void WorldSession::QueuePacket(WorldPacket* new_packet) } /// Logging helper for unexpected opcodes -void WorldSession::LogUnexpectedOpcode(WorldPacket* packet, const char* status, const char *reason) +void WorldSession::LogUnexpectedOpcode(WorldPacket* packet, char const* status, const char *reason) { TC_LOG_ERROR("network.opcode", "Received unexpected opcode %s Status: %s Reason: %s from %s", GetOpcodeNameForLogging(packet->GetOpcode()).c_str(), status, reason, GetPlayerInfo().c_str()); @@ -312,12 +313,12 @@ bool WorldSession::Update(uint32 diff, PacketFilter& updater) ///- Retrieve packets from the receive queue and call the appropriate handlers /// not process packets if socket already closed - WorldPacket* packet = NULL; + WorldPacket* packet = nullptr; //! Delete packet after processing by default bool deletePacket = true; std::vector requeuePackets; uint32 processedPackets = 0; - time_t currentTime = time(NULL); + time_t currentTime = time(nullptr); while (m_Socket && _recvQueue.next(packet, updater)) { @@ -436,7 +437,7 @@ bool WorldSession::Update(uint32 diff, PacketFilter& updater) //logout procedure should happen only in World::UpdateSessions() method!!! if (updater.ProcessLogout()) { - time_t currTime = time(NULL); + time_t currTime = time(nullptr); ///- If necessary, log the player out if (ShouldLogOut(currTime) && !m_playerLoading) LogoutPlayer(true); @@ -526,7 +527,7 @@ void WorldSession::LogoutPlayer(bool save) } } - // Repop at GraveYard or other player far teleport will prevent saving player because of not present map + // Repop at Graveyard or other player far teleport will prevent saving player because of not present map // Teleport player immediately for correct player save while (_player->IsBeingTeleportedFar()) HandleMoveWorldportAckOpcode(); @@ -536,7 +537,7 @@ void WorldSession::LogoutPlayer(bool save) guild->HandleMemberLogout(this); ///- Remove pet - _player->RemovePet(NULL, PET_SAVE_AS_CURRENT, true); + _player->RemovePet(nullptr, PET_SAVE_AS_CURRENT, true); ///- Clear whisper whitelist _player->ClearWhisperWhiteList(); @@ -596,7 +597,7 @@ void WorldSession::LogoutPlayer(bool save) if (Map* _map = _player->FindMap()) _map->RemovePlayerFromMap(_player, true); - SetPlayer(NULL); //! Pointer already deleted during RemovePlayerFromMap + SetPlayer(nullptr); //! Pointer already deleted during RemovePlayerFromMap //! Send the 'logout complete' packet to the client //! Client will respond by sending 3x CMSG_CANCEL_TRADE, which we currently dont handle @@ -672,6 +673,11 @@ char const* WorldSession::GetTrinityString(uint32 entry) const return sObjectMgr->GetTrinityString(entry, GetSessionDbLocaleIndex()); } +void WorldSession::ResetTimeOutTime() +{ + m_timeOutTime = int32(sWorld->getIntConfig(CONFIG_SOCKET_TIMEOUTTIME)); +} + void WorldSession::Handle_NULL(WorldPacket& recvPacket) { TC_LOG_ERROR("network.opcode", "Received unhandled opcode %s from %s" @@ -764,7 +770,7 @@ void WorldSession::SetAccountData(AccountDataType type, time_t tm, std::string c } else { - // _player can be NULL and packet received after logout but m_GUID still store correct guid + // _player can be nullptr and packet received after logout but m_GUID still store correct guid if (!m_GUIDLow) return; @@ -786,7 +792,7 @@ void WorldSession::SetAccountData(AccountDataType type, time_t tm, std::string c void WorldSession::SendAccountDataTimes(uint32 mask) { WorldPacket data(SMSG_ACCOUNT_DATA_TIMES, 4 + 1 + 4 + NUM_ACCOUNT_DATA_TYPES * 4); - data << uint32(time(NULL)); // Server time + data << uint32(time(nullptr)); // Server time data << uint8(1); data << uint32(mask); // type mask for (uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i) @@ -1167,7 +1173,7 @@ void WorldSession::InvalidateRBACData() TC_LOG_DEBUG("rbac", "WorldSession::Invalidaterbac::RBACData [AccountId: %u, Name: %s, realmId: %d]", _RBACData->GetId(), _RBACData->GetName().c_str(), realm.Id.Realm); delete _RBACData; - _RBACData = NULL; + _RBACData = nullptr; } bool WorldSession::DosProtection::EvaluateOpcode(WorldPacket& p, time_t time) const @@ -1224,7 +1230,6 @@ bool WorldSession::DosProtection::EvaluateOpcode(WorldPacket& p, time_t time) co } } - uint32 WorldSession::DosProtection::GetMaxPacketCounterAllowed(uint16 opcode) const { uint32 maxPacketCounterAllowed; @@ -1472,3 +1477,7 @@ uint32 WorldSession::DosProtection::GetMaxPacketCounterAllowed(uint16 opcode) co return maxPacketCounterAllowed; } + +WorldSession::DosProtection::DosProtection(WorldSession* s) : Session(s), _policy((Policy)sWorld->getIntConfig(CONFIG_PACKET_SPOOF_POLICY)) +{ +} diff --git a/src/server/game/Server/WorldSession.h b/src/server/game/Server/WorldSession.h index 8ac314fc552..042bbddd54b 100644 --- a/src/server/game/Server/WorldSession.h +++ b/src/server/game/Server/WorldSession.h @@ -24,17 +24,14 @@ #define __WORLDSESSION_H #include "Common.h" +#include "DatabaseEnvFwd.h" +#include "LockedQueue.h" +#include "ObjectGuid.h" +#include "QueryCallbackProcessor.h" #include "SharedDefines.h" -#include "AddonMgr.h" -#include "DatabaseEnv.h" -#include "World.h" -#include "Opcodes.h" -#include "WorldPacket.h" -#include "Cryptography/BigNumber.h" -#include "Opcodes.h" -#include "AccountMgr.h" -#include +#include +class BigNumber; class Creature; class GameObject; class InstanceSave; @@ -47,13 +44,16 @@ class SpellCastTargets; class Unit; class Warden; class WorldPacket; +class WorldSession; class WorldSocket; +struct AddonInfo; struct AreaTableEntry; struct AuctionEntry; struct DeclinedName; struct ItemTemplate; struct MovementInfo; struct TradeStatusInfo; +struct z_stream_s; namespace lfg { @@ -297,7 +297,7 @@ class TC_GAME_API WorldSession void SendNotification(uint32 string_id, ...); void SendPetNameInvalid(uint32 error, std::string const& name, DeclinedName *declinedName); void SendPartyResult(PartyOperation operation, std::string const& member, PartyResult res, uint32 val = 0); - void SendAreaTriggerMessage(const char* Text, ...) ATTR_PRINTF(2, 3); + void SendAreaTriggerMessage(char const* Text, ...) ATTR_PRINTF(2, 3); void SendQueryTimeResponse(); void SendAuthResponse(uint8 code, bool queued, uint32 queuePos = 0); @@ -404,8 +404,7 @@ class TC_GAME_API WorldSession m_TutorialsChanged |= TUTORIALS_FLAG_CHANGED; } } - //used with item_page table - bool SendItemInfo(uint32 itemid, WorldPacket data); + //auction void SendAuctionHello(ObjectGuid guid, Creature* unit); void SendAuctionCommandResult(AuctionEntry* auction, uint32 Action, uint32 ErrorCode, uint32 bidError = 0); @@ -452,10 +451,7 @@ class TC_GAME_API WorldSession m_timeOutTime -= int32(diff); } - void ResetTimeOutTime() - { - m_timeOutTime = int32(sWorld->getIntConfig(CONFIG_SOCKET_TIMEOUTTIME)); - } + void ResetTimeOutTime(); bool IsConnectionIdle() const { @@ -1101,7 +1097,7 @@ class TC_GAME_API WorldSession { friend class World; public: - DosProtection(WorldSession* s) : Session(s), _policy((Policy)sWorld->getIntConfig(CONFIG_PACKET_SPOOF_POLICY)) { } + DosProtection(WorldSession* s); bool EvaluateOpcode(WorldPacket& p, time_t time) const; protected: enum Policy @@ -1132,7 +1128,7 @@ class TC_GAME_API WorldSession bool CanUseBank(ObjectGuid bankerGUID = ObjectGuid::Empty) const; // logging helper - void LogUnexpectedOpcode(WorldPacket* packet, const char* status, const char *reason); + void LogUnexpectedOpcode(WorldPacket* packet, char const* status, const char *reason); void LogUnprocessedTail(WorldPacket* packet); // EnumData helpers @@ -1160,7 +1156,7 @@ class TC_GAME_API WorldSession typedef std::list AddonsList; // Warden - Warden* _warden; // Remains NULL if Warden system is not enabled by config + Warden* _warden; // Remains nullptr if Warden system is not enabled by config time_t _logoutTime; bool m_inQueue; // session wait in auth.queue diff --git a/src/server/game/Server/WorldSocket.cpp b/src/server/game/Server/WorldSocket.cpp index bdac20064f4..b0ecd463493 100644 --- a/src/server/game/Server/WorldSocket.cpp +++ b/src/server/game/Server/WorldSocket.cpp @@ -17,13 +17,18 @@ */ #include "WorldSocket.h" +#include "BattlenetAccountMgr.h" #include "BigNumber.h" +#include "DatabaseEnv.h" #include "Opcodes.h" +#include "PacketLog.h" #include "QueryCallback.h" +#include "Random.h" +#include "RBAC.h" +#include "Realm.h" #include "ScriptMgr.h" #include "SHA1.h" -#include "PacketLog.h" -#include "BattlenetAccountMgr.h" +#include "World.h" #include class EncryptablePacket : public WorldPacket @@ -598,7 +603,7 @@ void WorldSocket::HandleAuthSessionCallback(std::shared_ptr authSes sha.UpdateData((uint8*)&t, 4); sha.UpdateData((uint8*)&authSession->LocalChallenge, 4); sha.UpdateData((uint8*)&_authSeed, 4); - sha.UpdateBigNumbers(&account.Game.SessionKey, NULL); + sha.UpdateBigNumbers(&account.Game.SessionKey, nullptr); sha.Finalize(); if (memcmp(sha.GetDigest(), authSession->Digest, SHA_DIGEST_LENGTH) != 0) @@ -639,7 +644,7 @@ void WorldSocket::HandleAuthSessionCallback(std::shared_ptr authSes //! Negative mutetime indicates amount of seconds to be muted effective on next login - which is now. if (mutetime < 0) { - mutetime = time(NULL) + llabs(mutetime); + mutetime = time(nullptr) + llabs(mutetime); stmt = LoginDatabase.GetPreparedStatement(LOGIN_UPD_MUTE_TIME_LOGIN); stmt->setInt64(0, mutetime); diff --git a/src/server/game/Server/WorldSocketMgr.cpp b/src/server/game/Server/WorldSocketMgr.cpp index ca1737b823c..e2c1a19e547 100644 --- a/src/server/game/Server/WorldSocketMgr.cpp +++ b/src/server/game/Server/WorldSocketMgr.cpp @@ -54,11 +54,11 @@ WorldSocketMgr& WorldSocketMgr::Instance() return instance; } -bool WorldSocketMgr::StartNetwork(boost::asio::io_service& service, std::string const& bindIp, uint16 port, int threadCount) +bool WorldSocketMgr::StartWorldNetwork(Trinity::Asio::IoContext& ioContext, std::string const& bindIp, uint16 port, int threadCount) { _tcpNoDelay = sConfigMgr->GetBoolDefault("Network.TcpNodelay", true); - int const max_connections = boost::asio::socket_base::max_connections; + int const max_connections = TRINITY_MAX_LISTEN_CONNECTIONS; TC_LOG_DEBUG("misc", "Max allowed socket connections %d", max_connections); // -1 means use default @@ -72,7 +72,7 @@ bool WorldSocketMgr::StartNetwork(boost::asio::io_service& service, std::string return false; } - if (!BaseSocketMgr::StartNetwork(service, bindIp, port, threadCount)) + if (!BaseSocketMgr::StartNetwork(ioContext, bindIp, port, threadCount)) return false; _acceptor->SetSocketFactory(std::bind(&BaseSocketMgr::GetSocketForAccept, this)); diff --git a/src/server/game/Server/WorldSocketMgr.h b/src/server/game/Server/WorldSocketMgr.h index da53057b158..209024c88e0 100644 --- a/src/server/game/Server/WorldSocketMgr.h +++ b/src/server/game/Server/WorldSocketMgr.h @@ -38,7 +38,7 @@ public: static WorldSocketMgr& Instance(); /// Start network, listen at address:port . - bool StartNetwork(boost::asio::io_service& service, std::string const& bindIp, uint16 port, int networkThreads) override; + bool StartWorldNetwork(Trinity::Asio::IoContext& ioContext, std::string const& bindIp, uint16 port, int networkThreads); /// Stops all network threads, It will wait for all running threads . void StopNetwork() override; diff --git a/src/server/game/Skills/Archaeology/Archaeology.cpp b/src/server/game/Skills/Archaeology/Archaeology.cpp index e380e5b7e6d..6b283aaa263 100644 --- a/src/server/game/Skills/Archaeology/Archaeology.cpp +++ b/src/server/game/Skills/Archaeology/Archaeology.cpp @@ -21,7 +21,7 @@ Archaeology::Archaeology(Player* player): _player(player) { - memset(_site, 0, sizeof(struct SiteData) * CONTINENT_SITES * COUNT_CONT); + memset(_site, 0, sizeof(SiteData) * CONTINENT_SITES * COUNT_CONT); _continentState[CONT_EASTERN] = STATE_NULL; _continentState[CONT_KALIMDOR] = STATE_NULL; diff --git a/src/server/game/Skills/Archaeology/Archaeology.h b/src/server/game/Skills/Archaeology/Archaeology.h index d76c267defe..89d193b26a8 100644 --- a/src/server/game/Skills/Archaeology/Archaeology.h +++ b/src/server/game/Skills/Archaeology/Archaeology.h @@ -18,21 +18,19 @@ #ifndef _ARCHAEOLOGY_H #define _ARCHAEOLOGY_H +#include "ArchaeologyMgr.h" #include "Common.h" #include "WorldSession.h" -#include "ArchaeologyMgr.h" #define DIGS_PER_SITE 3 class Player; struct ArchData { - ArchData() : fragId(0), fragCount(0), keyId(0), keyCount(0) { } - - uint32 fragId; - uint32 fragCount; - uint32 keyId; - uint32 keyCount; + uint32 FragId; + uint32 FragCount; + uint32 KeyId; + uint32 KeyCount; }; enum ContinentState @@ -44,60 +42,56 @@ enum ContinentState class Archaeology { -public: - Archaeology(Player* player); + public: + explicit Archaeology(Player* player); - void Initialize(); + void Initialize(); - void Learn(); - void UnLearn(); - void Update(); + void Learn(); + void UnLearn(); + void Update(); - void UseSite(); + void UseSite(); - void SendResearchHistory(); + void SendResearchHistory(); - void ActivateBranch(uint8 branchId, bool force = false); - bool ProjectCompleteable(uint16 projectId); - bool ProjectExists(uint16 projectId); + void ActivateBranch(uint8 branchId, bool force = false); + bool ProjectCompleteable(uint16 projectId); + bool ProjectExists(uint16 projectId); - void CompleteProject(uint16 projectId); - void SetArchData(struct ArchData *data) - { - ASSERT(data); - archData = data; - } + void CompleteProject(uint16 projectId); + void SetArchData(ArchData const& data); -private: - Player* _player; - ArchData *archData; + private: + Player* _player; + std::unique_ptr _archData; - // Site Functionality - ContinentState _continentState[4]; - SiteData _site[CONTINENT_SITES * COUNT_CONT]; + // Site Functionality + ContinentState _continentState[CONTINENT_SITES]; + SiteData _site[CONTINENT_SITES * COUNT_CONT]; - void LoadSitesFromDB(); - void VerifySites(); + void LoadSitesFromDB(); + void VerifySites(); - Continent GetContinent(); - uint32 GetNearestSite(float &distance); - void SetSite(uint32 posi, uint16 entry, uint32 state = 0); - void RegeneratePosition(uint32 position, Continent continent); - void RegenerateContinent(Continent continent); - void RegenerateAllSites(); + Continent GetContinent(); + uint32 GetNearestSite(float &distance); + void SetSite(uint32 posi, uint16 entry, uint32 state = 0); + void RegeneratePosition(uint32 position, Continent continent); + void RegenerateContinent(Continent continent); + void RegenerateAllSites(); - // Project Functionality - std::map > _completedProjects; - std::map _branches; + // Project Functionality + std::map> _completedProjects; + std::map _branches; - void LoadCompletedProjectsFromDB(); - void LoadCurrentProjectsFromDB(); - void InitBranches(); - void VerifyProjects(); - void CleanProjects(); + void LoadCompletedProjectsFromDB(); + void LoadCurrentProjectsFromDB(); + void InitBranches(); + void VerifyProjects(); + void CleanProjects(); - void RegenerateBranch(uint8 branch); - void VisualizeBranch(uint8 position, uint16 project); + void RegenerateBranch(uint8 branch); + void VisualizeBranch(uint8 position, uint16 project); }; #endif diff --git a/src/server/game/Skills/Archaeology/ArchaeologyMgr.cpp b/src/server/game/Skills/Archaeology/ArchaeologyMgr.cpp index c38aa3d85d8..3e7e591396c 100644 --- a/src/server/game/Skills/Archaeology/ArchaeologyMgr.cpp +++ b/src/server/game/Skills/Archaeology/ArchaeologyMgr.cpp @@ -16,13 +16,14 @@ */ #include "ArchaeologyMgr.h" +#include "DatabaseEnv.h" #include "DBCStores.h" +#include "Log.h" +#include "Random.h" +#include "SitePolygonGraph.h" #include "SpellMgr.h" #include "Timer.h" -namespace archaeology -{ - ArchaeologyMgr::ArchaeologyMgr() { } @@ -230,8 +231,8 @@ void ArchaeologyMgr::LoadData() bool ArchaeologyMgr::isSiteValid(SiteData* sites, uint16 entry) { - for (uint32 i = 0; i < CONTINENT_SITES; i++) - if (sites[i].entry == entry) + for (uint32 i = 0; i < CONTINENT_SITES; ++i) + if (sites[i].Entry == entry) return false; return true; @@ -262,14 +263,14 @@ uint16 ArchaeologyMgr::GetNewSite(Continent continent, SiteData* sites, bool ext bool ArchaeologyMgr::SetSiteCoords(SiteData &site) { - if (SitePolygonGraph* poly = _polygonMap[site.entry]) + if (SitePolygonGraph* poly = _polygonMap[site.Entry]) { // Calculate random point of interest SitePolygonGraphNode node = poly->randomize_poi(); // Get random point into Polygon - site.x = node.getX(); - site.y = node.getY(); + site.X = node.getX(); + site.Y = node.getY(); return true; } @@ -310,24 +311,23 @@ uint32 ArchaeologyMgr::GetFindCurrency(uint32 go_entry) return 0; } -uint16 ArchaeologyMgr::GetNewProject(BranchData* branch, std::map >* completedMap, uint32 playerSkill) +uint16 ArchaeologyMgr::GetNewProject(uint8 branchId, BranchData* branch, std::map>* completedMap, uint32 playerSkill) { - uint8 branchId = branch->branchId; std::vector* _rares = &_rareProjects[branchId]; std::vector* _commons = &_commonProjects[branchId]; - float rareChance = float(_rares->size() - branch->completedRares) / float(_commons->size() + _rares->size()); + float rareChance = float(_rares->size() - branch->CompletedRares) / float(_commons->size() + _rares->size()); float roll1 = frand(.0f, 1.0f); // Are we eligible for a Rare Project ? if (rareChance > roll1) { - float roll2 = frand(.0f, 1.0f); + float roll2 = float(rand_norm()); float rareChance = _branchMap[branchId].rareChance; for (std::vector::iterator itr = _rares->begin(); itr != _rares->end(); ++itr) { - float chance = (_projects[*itr].rarity == ITEM_QUALITY_RARE)? rareChance: EPIC_CHANCE; + float chance = (_projects[*itr].rarity == ITEM_QUALITY_RARE) ? rareChance : EPIC_CHANCE; // Are we in our choose range ? if (chance < roll2) @@ -354,7 +354,7 @@ uint16 ArchaeologyMgr::GetNewProject(BranchData* branch, std::mapsize()) + for (uint16 itr = begin; itr != end; itr = (itr + 1) % _commons->size()) { uint16 projectId = _commons->at(itr); @@ -376,5 +376,3 @@ uint16 ArchaeologyMgr::GetNewProject(BranchData* branch, std::map relax the non repetitive restriction return secondArtifact; } - -} // namespace archaeology diff --git a/src/server/game/Skills/Archaeology/ArchaeologyMgr.h b/src/server/game/Skills/Archaeology/ArchaeologyMgr.h index 9f85f6bc47a..b0e8db85cb1 100644 --- a/src/server/game/Skills/Archaeology/ArchaeologyMgr.h +++ b/src/server/game/Skills/Archaeology/ArchaeologyMgr.h @@ -18,10 +18,11 @@ #ifndef _ARCHAEOLOGY_MGR_H #define _ARCHAEOLOGY_MGR_H +#include "SharedDefines.h" #include #include -#include "SitePolygonGraph.h" -#include "Define.h" + +class SitePolygonGraph; #define CONTINENT_SITES 4 #define MAX_PROJECTS 16 @@ -69,13 +70,13 @@ struct SiteEntry struct SiteData { - uint16 entry; - uint16 state; - float x; - float y; - float tele_x; - float tele_y; - float tele_angle; + uint16 Entry = 0; + uint16 State = 0; + float X = 0.0f; + float Y = 0.0f; + float Tele_x = 0.0f; + float Tele_y = 0.0f; + float Tele_angle = 0.0f; }; struct BranchEntry @@ -88,9 +89,8 @@ struct BranchEntry struct BranchData { - uint8 branchId; - uint8 completedRares; - uint32 project; + uint8 CompletedRares; + uint32 Project; }; struct ProjectEntry @@ -104,49 +104,44 @@ struct ProjectEntry uint32 spell; }; -namespace archaeology -{ - class TC_GAME_API ArchaeologyMgr { -public: - static ArchaeologyMgr* instance(); - void LoadData(); + public: + static ArchaeologyMgr* instance(); + void LoadData(); - // Site Functionality - static uint32 GetFindCurrency(uint32 go_entry); - uint16 GetNewSite(Continent continent, SiteData *sites, bool extended, uint32 playerLevel); - bool SetSiteCoords(SiteData &site); - uint32 GetSiteType(uint16 entry); + // Site Functionality + static uint32 GetFindCurrency(uint32 go_entry); + uint16 GetNewSite(Continent continent, SiteData *sites, bool extended, uint32 playerLevel); + bool SetSiteCoords(SiteData &site); + uint32 GetSiteType(uint16 entry); - // Project Functionality - uint8 Currency2BranchId(uint32 currencyId) { return _currencyMap[currencyId]; } - const BranchEntry *GetBranchEntry(uint8 branchId) { return &_branchMap[branchId]; } - const ProjectEntry *GetProjectEntry(uint16 projectId) { return &_projects[projectId]; } + // Project Functionality + uint8 Currency2BranchId(uint32 currencyId) { return _currencyMap[currencyId]; } + BranchEntry const* GetBranchEntry(uint8 branchId) { return &_branchMap[branchId]; } + ProjectEntry const* GetProjectEntry(uint16 projectId) { return &_projects[projectId]; } - bool IsRareProject(uint16 project) { return _projects[project].rarity >= ITEM_QUALITY_RARE; } - uint16 GetNewProject(BranchData *branch, std::map > *completedMap, uint32 PlayerSkill); + bool IsRareProject(uint16 project) { return _projects[project].rarity >= ITEM_QUALITY_RARE; } + uint16 GetNewProject(uint8 branchId, BranchData* branch, std::map> *completedMap, uint32 PlayerSkill); -private: - ArchaeologyMgr(); - ~ArchaeologyMgr(); + private: + ArchaeologyMgr(); + ~ArchaeologyMgr(); - bool isSiteValid(SiteData *sites, uint16 entry); + bool isSiteValid(SiteData *sites, uint16 entry); - std::map > _siteMap; - std::map _polygonMap; - std::map _objectMap; + std::map> _siteMap; + std::map _polygonMap; + std::map _objectMap; - std::map _currencyMap; // currencyId -> branchId - std::map _branchMap; // branchId -> BranchEntry + std::map _currencyMap; + std::map _branchMap; - std::map _projects; - std::map > _commonProjects; - std::map > _rareProjects; + std::map _projects; + std::map> _commonProjects; + std::map> _rareProjects; }; -} // namespace archaeology - -#define sArchaeologyMgr archaeology::ArchaeologyMgr::instance() +#define sArchaeologyMgr ArchaeologyMgr::instance() #endif diff --git a/src/server/game/Skills/Archaeology/ArchaeologyProjects.cpp b/src/server/game/Skills/Archaeology/ArchaeologyProjects.cpp index 5cf2a21990f..76cfaaca55e 100644 --- a/src/server/game/Skills/Archaeology/ArchaeologyProjects.cpp +++ b/src/server/game/Skills/Archaeology/ArchaeologyProjects.cpp @@ -16,70 +16,64 @@ */ #include "Archaeology.h" -#include "DBCStore.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "Log.h" #include "Player.h" void Archaeology::LoadCompletedProjectsFromDB() { - QueryResult result; - - result = CharacterDatabase.PQuery("SELECT project, time, count FROM character_archaeology_completed WHERE guid=%u", - _player->GetGUID()); - + QueryResult result = CharacterDatabase.PQuery("SELECT project, time, count FROM character_archaeology_completed WHERE guid = %u", _player->GetGUID().GetCounter()); if (!result) return; - do { - Field *fields = result->Fetch(); + do + { + Field* fields = result->Fetch(); uint16 project = fields[0].GetUInt16(); int32 time = fields[1].GetInt32(); int32 count = fields[2].GetInt32(); - _completedProjects[project].first = time; - _completedProjects[project].second = count; - + _completedProjects.emplace(project, std::make_pair(time, count)); } while (result->NextRow()); } void Archaeology::InitBranches() { - for (uint8 i = 0; i < sResearchBranchStore.GetNumRows(); ++i) - if (const ResearchBranchEntry *branch = sResearchBranchStore.LookupEntry(i)) - if (branch->CurrencyID) - { - struct BranchData branchData; - branchData.branchId = branch->ID; - branchData.completedRares = 0; - branchData.project = 0; - _branches[i] = branchData; - } + for (ResearchBranchEntry const* branch : sResearchBranchStore) + { + if (branch->CurrencyID) + { + BranchData& branchData = _branches[uint8(branch->ID)]; + branchData.CompletedRares = 0; + branchData.Project = 0; + } + } } void Archaeology::LoadCurrentProjectsFromDB() { - QueryResult result; - InitBranches(); - result = CharacterDatabase.PQuery("SELECT branch, project FROM character_archaeology_projects WHERE guid=%u", - _player->GetGUID()); - + QueryResult result = CharacterDatabase.PQuery("SELECT branch, project FROM character_archaeology_projects WHERE guid = %u", _player->GetGUID().GetCounter()); if (!result) return; - do { - Field *fields = result->Fetch(); + do + { + Field* fields = result->Fetch(); uint8 branch = fields[0].GetUInt8(); uint16 project = fields[1].GetUInt16(); - if (uint16 old_project = _branches[branch].project) + auto itr = _branches.find(branch); + if (itr != _branches.end()) { - TC_LOG_ERROR("player.skills", "ERROR - Archaeology: Tried to assign project %u to branch %u, which already holds project %u!", - project, branch, old_project); + TC_LOG_ERROR("player.skills", "ERROR - Archaeology: Tried to assign project %u to branch %u, which already holds project %u!", project, branch, itr->second.Project); continue; } - _branches[branch].project = project; + BranchData& branchData = _branches[branch]; + branchData.Project = project; } while (result->NextRow()); } @@ -91,19 +85,19 @@ void Archaeology::VisualizeBranch(uint8 position, uint16 project) void Archaeology::RegenerateBranch(uint8 branch) { - uint16 project = sArchaeologyMgr->GetNewProject(&_branches[branch], &_completedProjects, _player->GetSkillValue(SKILL_ARCHAEOLOGY)); - _branches[branch].project = project; + uint16 project = sArchaeologyMgr->GetNewProject(branch, &_branches[branch], &_completedProjects, _player->GetSkillValue(SKILL_ARCHAEOLOGY)); + _branches[branch].Project = project; - CharacterDatabase.PExecute("REPLACE INTO character_archaeology_projects VALUES (%u, %u, %u)", - _player->GetGUID(), branch, project); + CharacterDatabase.PExecute("REPLACE INTO character_archaeology_projects VALUES (%u, %u, %u)", _player->GetGUID(), branch, project); } void Archaeology::VerifyProjects() { for (std::map::iterator itr = _branches.begin(); itr != _branches.end(); ++itr) - if (const BranchEntry* branch = sArchaeologyMgr->GetBranchEntry(itr->first)) + { + if (BranchEntry const* branch = sArchaeologyMgr->GetBranchEntry(itr->first)) { - uint16 project = itr->second.project; + uint16 project = itr->second.Project; if (project) { if (_completedProjects.find(project) != _completedProjects.end() && sArchaeologyMgr->IsRareProject(project)) @@ -114,8 +108,9 @@ void Archaeology::VerifyProjects() else continue; - VisualizeBranch(branch->fieldId, _branches[itr->first].project); + VisualizeBranch(branch->fieldId, _branches[itr->first].Project); } + } } void Archaeology::CleanProjects() @@ -131,73 +126,76 @@ void Archaeology::CleanProjects() void Archaeology::ActivateBranch(uint8 branchId, bool force) { - if (_branches[branchId].project && !force) + if (_branches[branchId].Project && !force) return; RegenerateBranch(branchId); - VisualizeBranch(sArchaeologyMgr->GetBranchEntry(branchId)->fieldId, _branches[branchId].project); + VisualizeBranch(sArchaeologyMgr->GetBranchEntry(branchId)->fieldId, _branches[branchId].Project); } bool Archaeology::ProjectExists(uint16 projectId) { - if (const ProjectEntry* project = sArchaeologyMgr->GetProjectEntry(projectId)) - return (_branches[project->branch].project == projectId); + if (ProjectEntry const* project = sArchaeologyMgr->GetProjectEntry(projectId)) + return (_branches[project->branch].Project == projectId); return false; } bool Archaeology::ProjectCompleteable(uint16 projectId) { - if (!archData) + if (!_archData) return false; - if (const ProjectEntry* project = sArchaeologyMgr->GetProjectEntry(projectId)) - if (_branches[project->branch].project == projectId) - { - const BranchEntry* branchEntry = sArchaeologyMgr->GetBranchEntry(project->branch); + ProjectEntry const* project = sArchaeologyMgr->GetProjectEntry(projectId); + if (!project) + return false; - // Check Ids - uint32 currencyId = branchEntry->currencyId; - uint32 keystoneId = branchEntry->keystoneId; - if (currencyId != archData->fragId || (archData->keyId && archData->keyId != keystoneId)) - return false; + if (_branches[project->branch].Project != projectId) + return false; - // Project can have keystones ? - if (project->keystone < archData->keyCount) - return false; + BranchEntry const* branchEntry = sArchaeologyMgr->GetBranchEntry(project->branch); + if (!branchEntry) + return false; - // Check if the given fragment/keystone usage would be enough - if (archData->fragCount + archData->keyCount * 12 != project->fragments) - return false; + // Check Ids + uint32 currencyId = branchEntry->currencyId; + uint32 keystoneId = branchEntry->keystoneId; + if (currencyId != _archData->FragId || (_archData->KeyId && _archData->KeyId != keystoneId)) + return false; - // Check if the player has the keystones - if (_player->GetCurrency(archData->fragId, false) < archData->fragCount) - return false; + // Project can have keystones ? + if (project->keystone < _archData->KeyCount) + return false; - // Check if the player has the fragments - return (!archData->keyId || _player->GetItemCount(archData->keyId) >= archData->keyCount); - } + // Check if the given fragment/keystone usage would be enough + if (_archData->FragCount + _archData->KeyCount * 12 != project->fragments) + return false; - return false; + // Check if the player has the keystones + if (_player->GetCurrency(_archData->FragId, false) < _archData->FragCount) + return false; + + // Check if the player has the fragments + return (!_archData->KeyId || _player->GetItemCount(_archData->KeyId) >= _archData->KeyCount); } void Archaeology::CompleteProject(uint16 projectId) { - const ProjectEntry *project = sArchaeologyMgr->GetProjectEntry(projectId); + ProjectEntry const* project = sArchaeologyMgr->GetProjectEntry(projectId); ASSERT(project); - ASSERT(_branches[project->branch].project == projectId); - ASSERT(archData); + ASSERT(_branches[project->branch].Project == projectId); + ASSERT(_archData); - _player->ModifyCurrency(archData->fragId, -int32(archData->fragCount), false, true); - _player->DestroyItemCount(archData->keyId, archData->keyCount, true, false); + _player->ModifyCurrency(_archData->FragId, -int32(_archData->FragCount), false, true); + _player->DestroyItemCount(_archData->KeyId, _archData->KeyCount, true, false); if (_completedProjects.find(projectId) == _completedProjects.end()) { - _completedProjects[projectId].first = time(NULL); + _completedProjects[projectId].first = time(nullptr); _completedProjects[projectId].second = 1; CharacterDatabase.PExecute("REPLACE INTO character_archaeology_completed VALUES (%u, %u, %u, 1);", - _player->GetGUID(), projectId, time(NULL)); + _player->GetGUID(), projectId, time(nullptr)); } else { @@ -209,10 +207,15 @@ void Archaeology::CompleteProject(uint16 projectId) _player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ARCHAEOLOGY_PROJECTS, projectId, 1); - delete archData; + _archData.reset(); ActivateBranch(project->branch, true); } +void Archaeology::SetArchData(ArchData const& data) +{ + _archData = Trinity::make_unique(std::move(data)); +} + void Archaeology::SendResearchHistory() { uint32 count = _completedProjects.size(); @@ -228,5 +231,5 @@ void Archaeology::SendResearchHistory() packet << uint32(itr->second.first); } - _player->GetSession()->SendPacket(&packet); + _player->SendDirectMessage(&packet); } diff --git a/src/server/game/Skills/Archaeology/ArchaeologySites.cpp b/src/server/game/Skills/Archaeology/ArchaeologySites.cpp index ec1edcf7ba3..491fd20b996 100644 --- a/src/server/game/Skills/Archaeology/ArchaeologySites.cpp +++ b/src/server/game/Skills/Archaeology/ArchaeologySites.cpp @@ -16,11 +16,13 @@ */ #include "Archaeology.h" -#include "DBCStore.h" -#include "Player.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "GameObjectData.h" #include "Language.h" -#include - +#include "Map.h" +#include "Player.h" +#include "Random.h" // use squared distances so we don't have to use the squareroot enum DigSiteDist @@ -96,32 +98,32 @@ void Archaeology::UseSite() if (dist > DIST_CLOSE) { uint32 surveyGoID; - float angle = std::atan2(_site[position].y - _player->GetPositionY(), _site[position].x - _player->GetPositionX()); - float pi = float(M_PI); + float angle = std::atan2(_site[position].Y - _player->GetPositionY(), _site[position].X - _player->GetPositionX()); + static float const pi = float(M_PI); if (dist < DIST_MED) { surveyGoID = CLOSE_SURVEYBOT; // within the med radius -> green light - angle += frand(-pi / 12, pi / 12); + angle += frand(-pi / 12.f, pi / 12.f); } else if (dist < DIST_FAR) { surveyGoID = MED_SURVEYBOT; // within the far radius -> yellow light - angle += frand(-pi / 6, pi / 6); + angle += frand(-pi / 6.f, pi / 6.f); } else { surveyGoID = FAR_SURVEYBOT; // outside far radius -> red light - angle += frand(-pi / 3, pi / 3); + angle += frand(-pi / 3.f, pi / 3.f); } float o = _player->GetOrientation(); float x = _player->GetPositionX() + cos(o) * 2.0f; float y = _player->GetPositionY() + sin(o) * 2.0f; - float z = _player->GetPositionZ(); + float z = _player->GetPositionZ(); float ground = _player->GetMap()->GetWaterOrGroundLevel(_player->GetPhaseShift(), x, y, z, &ground, _player->IsInWater()); - G3D::Quat rot = G3D::Matrix3::fromEulerAnglesZYX(angle, 0.f, 0.f); + QuaternionData rot = QuaternionData::fromEulerAnglesZYX(angle, 0.f, 0.f); if (std::abs(z - ground) < 1.5f) { _player->SummonGameObject(surveyGoID, Position(x, y, ground, angle), rot, 4); @@ -135,7 +137,7 @@ void Archaeology::UseSite() } // Spawn the correct Find Object Here - uint32 goId = sArchaeologyMgr->GetSiteType(_site[position].entry); + uint32 goId = sArchaeologyMgr->GetSiteType(_site[position].Entry); float o = _player->GetOrientation(); float x = _player->GetPositionX() + cos(o) * 2.0f; float y = _player->GetPositionY() + sin(o) * 2.0f; @@ -143,14 +145,14 @@ void Archaeology::UseSite() float ground = _player->GetMap()->GetWaterOrGroundLevel(_player->GetPhaseShift(), x, y, z, &ground, _player->IsInWater()); // Spawn object - _player->SummonGameObject(goId, Position(x, y, ground, o), G3D::Quat(), 60); - (_site[position].state)++; + _player->SummonGameObject(goId, Position(x, y, ground, o), QuaternionData(), 60); + (_site[position].State)++; - if (_site[position].state >= DIGS_PER_SITE) - RegeneratePosition(position, GetContinent()); + if (_site[position].State >= DIGS_PER_SITE) + RegeneratePosition(position, GetContinent()); else { - CharacterDatabase.PExecute("UPDATE character_archaeology_sites SET finds = %u WHERE site= %u AND guid= %u", _site[position].state, position, _player->GetGUID()); + CharacterDatabase.PExecute("UPDATE character_archaeology_sites SET finds = %u WHERE site= %u AND guid= %u", _site[position].State, position, _player->GetGUID()); sArchaeologyMgr->SetSiteCoords(_site[position]); } } @@ -183,32 +185,32 @@ uint32 Archaeology::GetNearestSite(float &distance) float pX = _player->GetPositionX(); float pY = _player->GetPositionY(); - float dist = (pX - _site[position].x) * (pX - _site[position].x) + (pY - _site[position].y) * (pY - _site[position].y); + float distSq = (pX - _site[position].X) * (pX - _site[position].X) + (pY - _site[position].Y) * (pY - _site[position].Y); - for (uint32 i = cont * CONTINENT_SITES + 1; i < (cont + 1) * CONTINENT_SITES; i++) + for (uint32 i = cont * CONTINENT_SITES + 1; i < (cont + 1) * CONTINENT_SITES; ++i) { - float dist2 = (pX -_site[i].x) * (pX -_site[i].x) + (pY - _site[i].y) * (pY - _site[i].y); - if (dist2 < dist) + float distSq2 = (pX -_site[i].X) * (pX -_site[i].X) + (pY - _site[i].Y) * (pY - _site[i].Y); + if (distSq2 < distSq) { position = i; - dist = dist2; + distSq = distSq2; } } - distance = dist; + distance = distSq; return position + 1; } void Archaeology::SetSite(uint32 position, uint16 entry, uint32 state) { - _site[position].entry = entry; - _site[position].state = state; + _site[position].Entry = entry; + _site[position].State = state; _player->SetUInt16Value(PLAYER_FIELD_RESEARCH_SITE_1 + (position / 2), position % 2, entry); if (entry == 0) { - _site[position].x = 0.f; - _site[position].y = 0.f; + _site[position].X = 0.f; + _site[position].Y = 0.f; } else sArchaeologyMgr->SetSiteCoords(_site[position]); @@ -216,12 +218,12 @@ void Archaeology::SetSite(uint32 position, uint16 entry, uint32 state) void Archaeology::RegeneratePosition(uint32 position, Continent continent) { - if (_site[position].entry && sResearchSiteStore.LookupEntry(_site[position].entry) && _site[position].state < DIGS_PER_SITE) + if (_site[position].Entry && sResearchSiteStore.LookupEntry(_site[position].Entry) && _site[position].State < DIGS_PER_SITE) return; uint16 entry = sArchaeologyMgr->GetNewSite(continent, _site, _continentState[continent] == STATE_EXT, _player->getLevel()); SetSite(position, entry); - CharacterDatabase.PExecute("REPLACE INTO character_archaeology_sites values (%u, %u, %u, %u);", _player->GetGUID(), position, entry, _site[position].state); + CharacterDatabase.PExecute("REPLACE INTO character_archaeology_sites values (%u, %u, %u, %u);", _player->GetGUID(), position, entry, _site[position].State); } void Archaeology::RegenerateContinent(Continent continent) diff --git a/src/server/game/Skills/SkillDiscovery.cpp b/src/server/game/Skills/SkillDiscovery.cpp index 4c29c996ab8..11a115c28f8 100644 --- a/src/server/game/Skills/SkillDiscovery.cpp +++ b/src/server/game/Skills/SkillDiscovery.cpp @@ -16,14 +16,15 @@ * with this program. If not, see . */ +#include "SkillDiscovery.h" #include "DatabaseEnv.h" #include "Log.h" -#include "World.h" -#include "Util.h" -#include "SkillDiscovery.h" -#include "SpellMgr.h" #include "Player.h" +#include "Random.h" #include "SpellInfo.h" +#include "SpellMgr.h" +#include "Util.h" +#include "World.h" #include struct SkillDiscoveryEntry diff --git a/src/server/game/Skills/SkillExtraItems.cpp b/src/server/game/Skills/SkillExtraItems.cpp index 534c555116c..093fc2f1bca 100644 --- a/src/server/game/Skills/SkillExtraItems.cpp +++ b/src/server/game/Skills/SkillExtraItems.cpp @@ -19,8 +19,9 @@ #include "SkillExtraItems.h" #include "DatabaseEnv.h" #include "Log.h" -#include "Player.h" #include "ObjectMgr.h" +#include "Player.h" +#include "SpellMgr.h" #include // some type definitions diff --git a/src/server/game/Spells/Auras/SpellAuraDefines.h b/src/server/game/Spells/Auras/SpellAuraDefines.h index b655213585e..33b8969ae75 100644 --- a/src/server/game/Spells/Auras/SpellAuraDefines.h +++ b/src/server/game/Spells/Auras/SpellAuraDefines.h @@ -18,6 +18,8 @@ #ifndef TRINITY_SPELLAURADEFINES_H #define TRINITY_SPELLAURADEFINES_H +#include "Define.h" + #define MAX_AURAS 64 // client support up to 255, but it will cause problems with group auras updating enum AURA_FLAGS @@ -50,6 +52,16 @@ enum AuraEffectHandleModes AURA_EFFECT_HANDLE_REAL_OR_REAPPLY_MASK = (AURA_EFFECT_HANDLE_REAPPLY | AURA_EFFECT_HANDLE_REAL) }; +enum AuraRemoveMode +{ + AURA_REMOVE_NONE = 0, + AURA_REMOVE_BY_DEFAULT = 1, // scripted remove, remove by stack with aura with different ids and sc aura remove + AURA_REMOVE_BY_CANCEL, + AURA_REMOVE_BY_ENEMY_SPELL, // dispel and absorb aura destroy + AURA_REMOVE_BY_EXPIRE, // aura duration has ended + AURA_REMOVE_BY_DEATH +}; + //m_schoolAbsorb enum DAMAGE_ABSORB_TYPE { @@ -57,7 +69,7 @@ enum DAMAGE_ABSORB_TYPE ONLY_MAGIC_ABSORB = -1 }; -enum AuraType +enum AuraType : uint32 { SPELL_AURA_NONE = 0, SPELL_AURA_BIND_SIGHT = 1, diff --git a/src/server/game/Spells/Auras/SpellAuraEffects.cpp b/src/server/game/Spells/Auras/SpellAuraEffects.cpp index 9c972139b44..1ef6efc5fc7 100644 --- a/src/server/game/Spells/Auras/SpellAuraEffects.cpp +++ b/src/server/game/Spells/Auras/SpellAuraEffects.cpp @@ -16,32 +16,37 @@ * with this program. If not, see . */ -#include "Common.h" -#include "WorldPacket.h" -#include "Opcodes.h" -#include "Log.h" -#include "ObjectMgr.h" -#include "SpellMgr.h" -#include "PhasingHandler.h" -#include "Player.h" -#include "Unit.h" -#include "ObjectAccessor.h" -#include "CellImpl.h" -#include "Util.h" -#include "Spell.h" -#include "SpellHistory.h" #include "SpellAuraEffects.h" -#include "Battleground.h" -#include "OutdoorPvPMgr.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "ScriptMgr.h" -#include "Vehicle.h" #include "Battlefield.h" #include "BattlefieldMgr.h" -#include "WeatherMgr.h" +#include "Battleground.h" +#include "CellImpl.h" +#include "Common.h" +#include "DBCStores.h" +#include "GridNotifiersImpl.h" +#include "Item.h" +#include "Log.h" +#include "LootMgr.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Opcodes.h" +#include "OutdoorPvPMgr.h" #include "Pet.h" +#include "PhasingHandler.h" +#include "Player.h" #include "ReputationMgr.h" +#include "ScriptMgr.h" +#include "Spell.h" +#include "SpellHistory.h" +#include "SpellMgr.h" +#include "Unit.h" +#include "Util.h" +#include "Vehicle.h" +#include "Weather.h" +#include "WeatherMgr.h" +#include "WorldPacket.h" +#include class Aura; // @@ -436,7 +441,7 @@ AuraEffect::AuraEffect(Aura* base, uint8 effIndex, int32 *baseAmount, Unit* cast m_base(base), m_spellInfo(base->GetSpellInfo()), m_baseAmount(baseAmount ? *baseAmount : m_spellInfo->Effects[effIndex].BasePoints), m_bonusAmount(0), m_critChance(0.0f), m_donePct(1.0f), -m_spellmod(NULL), m_periodicTimer(0), m_tickNumber(0), m_effIndex(effIndex), +m_spellmod(nullptr), m_periodicTimer(0), m_tickNumber(0), m_effIndex(effIndex), m_canBeRecalculated(true), m_isPeriodic(false) { CalculatePeriodic(caster, true, false); @@ -636,7 +641,7 @@ void AuraEffect::CalculatePeriodic(Unit* caster, bool resetPeriodicTimer /*= tru { // Apply periodic time mod if (modOwner) - modOwner->ApplySpellMod(GetId(), m_amplitude); + modOwner->ApplySpellMod(GetId(), SPELLMOD_ACTIVATION_TIME, m_amplitude); if (caster) { @@ -1303,7 +1308,7 @@ void AuraEffect::HandleShapeshiftBoosts(Unit* target, bool apply) const continue; if (spellInfo->Stances & (UI64LIT(1) << (GetMiscValue() - 1))) - target->CastSpell(target, itr->first, true, NULL, this); + target->CastSpell(target, itr->first, true, nullptr, this); } // Also do it for Glyphs @@ -1318,7 +1323,7 @@ void AuraEffect::HandleShapeshiftBoosts(Unit* target, bool apply) const continue; if (spellInfo->Stances & (UI64LIT(1) << (GetMiscValue() - 1))) - target->CastSpell(target, glyph->SpellId, true, NULL, this); + target->CastSpell(target, glyph->SpellId, true, nullptr, this); } } } @@ -1328,7 +1333,7 @@ void AuraEffect::HandleShapeshiftBoosts(Unit* target, bool apply) const { SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(24932); if (spellInfo && spellInfo->Stances & (UI64LIT(1) << (GetMiscValue() - 1))) - target->CastSpell(target, 24932, true, NULL, this); + target->CastSpell(target, 24932, true, nullptr, this); } // Heart of the Wild @@ -1352,7 +1357,7 @@ void AuraEffect::HandleShapeshiftBoosts(Unit* target, bool apply) const } if (heartOfTheWildSpellId) - target->CastCustomSpell(target, heartOfTheWildSpellId, &heartOfTheWildAmount, NULL, NULL, true, NULL, this); + target->CastCustomSpell(target, heartOfTheWildSpellId, &heartOfTheWildAmount, nullptr, nullptr, true, nullptr, this); } switch (GetMiscValue()) @@ -1374,7 +1379,7 @@ void AuraEffect::HandleShapeshiftBoosts(Unit* target, bool apply) const spellId3 = 47180; break; } - target->CastSpell(target, spellId3, true, NULL, this); + target->CastSpell(target, spellId3, true, nullptr, this); } // Master Shapeshifter - Cat if (AuraEffect const* aurEff = target->GetAuraEffect(SPELL_AURA_MOD_HEALING_DONE_PERCENT, SPELLFAMILY_GENERIC, 2851, EFFECT_0)) @@ -1852,7 +1857,7 @@ void AuraEffect::HandleAuraModShapeshift(AuraApplication const* aurApp, uint8 mo { int32 basePoints = std::min(oldPower, FurorChance); target->SetPower(POWER_ENERGY, 0); - target->CastCustomSpell(target, 17099, &basePoints, NULL, NULL, true, NULL, this); + target->CastCustomSpell(target, 17099, &basePoints, nullptr, nullptr, true, nullptr, this); } else if (roll_chance_i(FurorChance)) target->CastSpell(target, 17057, true); @@ -1899,12 +1904,12 @@ void AuraEffect::HandleAuraModShapeshift(AuraApplication const* aurApp, uint8 mo case FORM_BEAR: case FORM_CAT: if (AuraEffect* dummy = target->GetAuraEffect(37315, 0)) - target->CastSpell(target, 37316, true, NULL, dummy); + target->CastSpell(target, 37316, true, nullptr, dummy); break; // Nordrassil Regalia - bonus case FORM_MOONKIN: if (AuraEffect* dummy = target->GetAuraEffect(37324, 0)) - target->CastSpell(target, 37325, true, NULL, dummy); + target->CastSpell(target, 37325, true, nullptr, dummy); break; case FORM_BATTLESTANCE: case FORM_DEFENSIVESTANCE: @@ -1958,7 +1963,7 @@ void AuraEffect::HandleAuraModShapeshift(AuraApplication const* aurApp, uint8 mo if (!target->CanUseAttackType(BASE_ATTACK)) { if (Item* pItem = target->ToPlayer()->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND)) - target->ToPlayer()->_ApplyWeaponDamage(EQUIPMENT_SLOT_MAINHAND, pItem->GetTemplate(), NULL, apply); + target->ToPlayer()->_ApplyWeaponDamage(EQUIPMENT_SLOT_MAINHAND, pItem->GetTemplate(), nullptr, apply); } } @@ -2396,7 +2401,7 @@ void AuraEffect::HandleAuraModDisarm(AuraApplication const* aurApp, uint8 mode, player->ApplyItemDependentAuras(item, !apply); if (attacktype < MAX_ATTACK) - player->_ApplyWeaponDamage(slot, item->GetTemplate(), NULL, !apply); + player->_ApplyWeaponDamage(slot, item->GetTemplate(), nullptr, !apply); } } @@ -4386,7 +4391,7 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool case 13139: // net-o-matic // root to self part of (root_target->charge->root_self sequence if (caster) - caster->CastSpell(caster, 13138, true, NULL, this); + caster->CastSpell(caster, 13138, true, nullptr, this); break; case 34026: // kill command { @@ -4394,7 +4399,7 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool if (!pet) break; - target->CastSpell(target, 34027, true, NULL, this); + target->CastSpell(target, 34027, true, nullptr, this); // set 3 stacks and 3 charges (to make all auras not disappear at once) Aura* owner_aura = target->GetAura(34027, GetCasterGUID()); @@ -4415,15 +4420,15 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool if (caster) { if (caster->getGender() == GENDER_FEMALE) - caster->CastSpell(target, 37095, true, NULL, this); // Blood Elf Disguise + caster->CastSpell(target, 37095, true, nullptr, this); // Blood Elf Disguise else - caster->CastSpell(target, 37093, true, NULL, this); + caster->CastSpell(target, 37093, true, nullptr, this); } break; } case 39850: // Rocket Blast if (roll_chance_i(20)) // backfire stun - target->CastSpell(target, 51581, true, NULL, this); + target->CastSpell(target, 51581, true, nullptr, this); break; case 43873: // Headless Horseman Laugh target->PlayDistanceSound(11965); @@ -4432,9 +4437,9 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool if (caster) { if (caster->getGender() == GENDER_FEMALE) - caster->CastSpell(target, 46356, true, NULL, this); + caster->CastSpell(target, 46356, true, nullptr, this); else - caster->CastSpell(target, 46355, true, NULL, this); + caster->CastSpell(target, 46355, true, nullptr, this); } break; case 46361: // Reinforced Net @@ -4472,7 +4477,7 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool } if (finalSpelId) - caster->CastSpell(target, finalSpelId, true, NULL, this); + caster->CastSpell(target, finalSpelId, true, nullptr, this); } switch (m_spellInfo->SpellFamilyName) @@ -4492,7 +4497,7 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool break; case 36730: // Flame Strike { - target->CastSpell(target, 36731, true, NULL, this); + target->CastSpell(target, 36731, true, nullptr, this); break; } case 44191: // Flame Strike @@ -4515,14 +4520,14 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool break; } case 42783: // Wrath of the Astromancer - target->CastSpell(target, GetAmount(), true, NULL, this); + target->CastSpell(target, GetAmount(), true, nullptr, this); break; case 46308: // Burning Winds cast only at creatures at spawn - target->CastSpell(target, 47287, true, NULL, this); + target->CastSpell(target, 47287, true, nullptr, this); break; case 52172: // Coyote Spirit Despawn Aura case 60244: // Blood Parrot Despawn Aura - target->CastSpell((Unit*)NULL, GetAmount(), true, NULL, this); + target->CastSpell((Unit*)nullptr, GetAmount(), true, nullptr, this); break; case 91604: // Restricted Flight Area if (aurApp->GetRemoveMode() == AURA_REMOVE_BY_EXPIRE) @@ -4564,7 +4569,7 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool SpellInfo const* spell = sSpellMgr->AssertSpellInfo(spellId); for (uint32 i = 0; i < spell->StackAmount; ++i) - caster->CastSpell(target, spell->Id, true, NULL, NULL, GetCasterGUID()); + caster->CastSpell(target, spell->Id, true, nullptr, nullptr, GetCasterGUID()); break; } target->RemoveAurasDueToSpell(spellId); @@ -4578,7 +4583,7 @@ void AuraEffect::HandleAuraDummy(AuraApplication const* aurApp, uint8 mode, bool { SpellInfo const* spell = sSpellMgr->AssertSpellInfo(spellId); for (uint32 i = 0; i < spell->StackAmount; ++i) - caster->CastSpell(target, spell->Id, true, NULL, NULL, GetCasterGUID()); + caster->CastSpell(target, spell->Id, true, nullptr, nullptr, GetCasterGUID()); break; } target->RemoveAurasDueToSpell(spellId); @@ -4743,7 +4748,7 @@ void AuraEffect::HandleChannelDeathItem(AuraApplication const* aurApp, uint8 mod if (msg != EQUIP_ERR_OK) { count-=noSpaceForCount; - plCaster->SendEquipError(msg, NULL, NULL, GetSpellInfo()->Effects[m_effIndex].ItemType); + plCaster->SendEquipError(msg, nullptr, nullptr, GetSpellInfo()->Effects[m_effIndex].ItemType); if (count == 0) return; } @@ -4751,7 +4756,7 @@ void AuraEffect::HandleChannelDeathItem(AuraApplication const* aurApp, uint8 mod Item* newitem = plCaster->StoreNewItem(dest, GetSpellInfo()->Effects[m_effIndex].ItemType, true); if (!newitem) { - plCaster->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + plCaster->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } plCaster->SendNewItem(newitem, count, true, true); @@ -4902,9 +4907,9 @@ void AuraEffect::HandleAuraLinked(AuraApplication const* aurApp, uint8 mode, boo return; // If amount avalible cast with basepoints (Crypt Fever for example) if (GetAmount()) - caster->CastCustomSpell(target, triggeredSpellId, &m_amount, NULL, NULL, true, NULL, this); + caster->CastCustomSpell(target, triggeredSpellId, &m_amount, nullptr, nullptr, true, nullptr, this); else - caster->CastSpell(target, triggeredSpellId, true, NULL, this); + caster->CastSpell(target, triggeredSpellId, true, nullptr, this); } else { @@ -5085,7 +5090,7 @@ void AuraEffect::HandlePeriodicDummyAuraTick(Unit* target, Unit* caster) const } case 62292: // Blaze (Pool of Tar) // should we use custom damage? - target->CastSpell((Unit*)NULL, m_spellInfo->Effects[m_effIndex].TriggerSpell, true); + target->CastSpell((Unit*)nullptr, m_spellInfo->Effects[m_effIndex].TriggerSpell, true); break; case 62399: // Overload Circuit if (target->GetMap()->IsDungeon() && int(target->GetAppliedAuras().count(62399)) >= (target->GetMap()->IsHeroic() ? 4 : 2)) @@ -5098,7 +5103,7 @@ void AuraEffect::HandlePeriodicDummyAuraTick(Unit* target, Unit* caster) const case 64821: // Fuse Armor (Razorscale) if (GetBase()->GetStackAmount() == GetSpellInfo()->StackAmount) { - target->CastSpell(target, 64774, true, NULL, NULL, GetCasterGUID()); + target->CastSpell(target, 64774, true, nullptr, nullptr, GetCasterGUID()); target->RemoveAura(64821); } break; @@ -5109,7 +5114,7 @@ void AuraEffect::HandlePeriodicDummyAuraTick(Unit* target, Unit* caster) const // Mirror Image if (GetId() == 55342) // Set name of summons to name of caster - target->CastSpell((Unit*)NULL, m_spellInfo->Effects[m_effIndex].TriggerSpell, true); + target->CastSpell((Unit*)nullptr, m_spellInfo->Effects[m_effIndex].TriggerSpell, true); break; } case SPELLFAMILY_DRUID: @@ -5143,7 +5148,7 @@ void AuraEffect::HandlePeriodicDummyAuraTick(Unit* target, Unit* caster) const if (GetSpellInfo()->SpellFamilyFlags[1] & 0x80000000) { if (caster) - caster->CastCustomSpell(53352, SPELLVALUE_BASE_POINT0, m_amount, target, true, NULL, this); + caster->CastCustomSpell(53352, SPELLVALUE_BASE_POINT0, m_amount, target, true, nullptr, this); break; } switch (GetSpellInfo()->Id) @@ -5177,7 +5182,7 @@ void AuraEffect::HandlePeriodicDummyAuraTick(Unit* target, Unit* caster) const { case 49016: // Hysteria uint32 damage = uint32(target->CountPctFromMaxHealth(1)); - target->DealDamage(target, damage, NULL, NODAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + target->DealDamage(target, damage, nullptr, NODAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); break; } // Blood of the North @@ -5209,7 +5214,7 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) uint32 auraId = auraSpellInfo->Id; // specific code for cases with no trigger spell provided in field - if (triggeredSpellInfo == NULL) + if (triggeredSpellInfo == nullptr) { switch (auraSpellInfo->SpellFamilyName) { @@ -5253,7 +5258,7 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) // Frost Blast case 27808: if (caster) - caster->CastCustomSpell(29879, SPELLVALUE_BASE_POINT0, int32(target->CountPctFromMaxHealth(21)), target, true, NULL, this); + caster->CastCustomSpell(29879, SPELLVALUE_BASE_POINT0, int32(target->CountPctFromMaxHealth(21)), target, true, nullptr, this); return; // Inoculate Nestlewood Owlkin case 29528: @@ -5293,7 +5298,7 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) // so instakill will be naturally done before trigger spell case 31347: { - target->CastSpell(target, 31350, true, NULL, this); + target->CastSpell(target, 31350, true, nullptr, this); target->KillSelf(); return; } @@ -5309,9 +5314,9 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) { // cast 24 spells 34269-34289, 34314-34316 for (uint32 spell_id = 34269; spell_id != 34290; ++spell_id) - target->CastSpell(target, spell_id, true, NULL, this); + target->CastSpell(target, spell_id, true, nullptr, this); for (uint32 spell_id = 34314; spell_id != 34317; ++spell_id) - target->CastSpell(target, spell_id, true, NULL, this); + target->CastSpell(target, spell_id, true, nullptr, this); return; } // Remote Toy @@ -5328,7 +5333,7 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) if (!caster || target->GetTypeId() != TYPEID_UNIT) return; - caster->CastSpell(caster, 38495, true, NULL, this); + caster->CastSpell(caster, 38495, true, nullptr, this); Creature* creatureTarget = target->ToCreature(); @@ -5375,7 +5380,7 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) case 65922: case 65923: { - Unit* permafrostCaster = NULL; + Unit* permafrostCaster = nullptr; Aura* permafrostAura = target->GetAura(66193); if (!permafrostAura) permafrostAura = target->GetAura(67855); @@ -5401,22 +5406,22 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) } // Mana Tide case 16191: - target->CastCustomSpell(target, triggerSpellId, &m_amount, NULL, NULL, true, NULL, this); + target->CastCustomSpell(target, triggerSpellId, &m_amount, nullptr, nullptr, true, nullptr, this); return; // Negative Energy Periodic case 46284: - target->CastCustomSpell(triggerSpellId, SPELLVALUE_MAX_TARGETS, m_tickNumber / 10 + 1, NULL, true, NULL, this); + target->CastCustomSpell(triggerSpellId, SPELLVALUE_MAX_TARGETS, m_tickNumber / 10 + 1, nullptr, true, nullptr, this); return; // Slime Pool (Dreadscale & Acidmaw) case 66882: - target->CastCustomSpell(triggerSpellId, SPELLVALUE_RADIUS_MOD, (int32)((((float)m_tickNumber / 60) * 0.9f + 0.1f) * 10000 * 2 / 3), NULL, true, NULL, this); + target->CastCustomSpell(triggerSpellId, SPELLVALUE_RADIUS_MOD, (int32)((((float)m_tickNumber / 60) * 0.9f + 0.1f) * 10000 * 2 / 3), nullptr, true, nullptr, this); return; // Slime Spray - temporary here until preventing default effect works again // added on 9.10.2010 case 69508: { if (caster) - caster->CastSpell(target, triggerSpellId, true, NULL, NULL, caster->GetGUID()); + caster->CastSpell(target, triggerSpellId, true, nullptr, nullptr, caster->GetGUID()); return; } case 24745: // Summon Templar, Trigger @@ -5451,7 +5456,7 @@ void AuraEffect::HandlePeriodicTriggerSpellAuraTick(Unit* target, Unit* caster) { if (Unit* triggerCaster = triggeredSpellInfo->NeedsToBeTriggeredByCaster(m_spellInfo) ? caster : target) { - triggerCaster->CastSpell(target, triggeredSpellInfo, true, NULL, this); + triggerCaster->CastSpell(target, triggeredSpellInfo, true, nullptr, this); TC_LOG_DEBUG("spells", "AuraEffect::HandlePeriodicTriggerSpellAuraTick: Spell %u Trigger %u", GetId(), triggeredSpellInfo->Id); } } @@ -5535,7 +5540,7 @@ void AuraEffect::HandlePeriodicDamageAurasTick(Unit* target, Unit* caster) const damage = std::max(int32(damage * GetDonePct()), 0); if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(GetSpellInfo()->Id, damage); + modOwner->ApplySpellMod(GetSpellInfo()->Id, SPELLMOD_DOT, damage); damage = target->SpellDamageBonusTaken(caster, GetSpellInfo(), damage, DOT, GetBase()->GetStackAmount()); @@ -5669,7 +5674,7 @@ void AuraEffect::HandlePeriodicHealthLeechAuraTick(Unit* target, Unit* caster) c damage = std::max(int32(damage * GetDonePct()), 0); if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(GetSpellInfo()->Id, damage); + modOwner->ApplySpellMod(GetSpellInfo()->Id, SPELLMOD_DOT, damage); damage = target->SpellDamageBonusTaken(caster, GetSpellInfo(), damage, DOT, GetBase()->GetStackAmount()); @@ -5844,7 +5849,7 @@ void AuraEffect::HandlePeriodicHealAurasTick(Unit* target, Unit* caster) const damage = std::max(int32(damage * GetDonePct()), 0); if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(GetSpellInfo()->Id, damage); + modOwner->ApplySpellMod(GetSpellInfo()->Id, SPELLMOD_DOT, damage); damage = target->SpellHealingBonusTaken(caster, GetSpellInfo(), damage, DOT, GetBase()->GetStackAmount()); } @@ -5961,7 +5966,7 @@ void AuraEffect::HandlePeriodicManaLeechAuraTick(Unit* target, Unit* caster) con if (manaFeedVal > 0) { int32 feedAmount = CalculatePct(gainedAmount, manaFeedVal); - caster->CastCustomSpell(caster, 32554, &feedAmount, NULL, NULL, true, NULL, this); + caster->CastCustomSpell(caster, 32554, &feedAmount, nullptr, nullptr, true, nullptr, this); } } } @@ -6102,7 +6107,7 @@ void AuraEffect::HandleProcTriggerSpellAuraProc(AuraApplication* aurApp, ProcEve if (SpellInfo const* triggeredSpellInfo = sSpellMgr->GetSpellInfo(triggerSpellId)) { TC_LOG_DEBUG("spells", "AuraEffect::HandleProcTriggerSpellAuraProc: Triggering spell %u from aura %u proc", triggeredSpellInfo->Id, GetId()); - triggerCaster->CastSpell(triggerTarget, triggeredSpellInfo, true, NULL, this); + triggerCaster->CastSpell(triggerTarget, triggeredSpellInfo, true, nullptr, this); } else TC_LOG_ERROR("spells","AuraEffect::HandleProcTriggerSpellAuraProc: Could not trigger spell %u from aura %u proc, because the spell does not have an entry in Spell.dbc.", triggerSpellId, GetId()); @@ -6118,7 +6123,7 @@ void AuraEffect::HandleProcTriggerSpellWithValueAuraProc(AuraApplication* aurApp { int32 basepoints0 = GetAmount(); TC_LOG_DEBUG("spells", "AuraEffect::HandleProcTriggerSpellWithValueAuraProc: Triggering spell %u with value %d from aura %u proc", triggeredSpellInfo->Id, basepoints0, GetId()); - triggerCaster->CastCustomSpell(triggerTarget, triggerSpellId, &basepoints0, NULL, NULL, true, NULL, this); + triggerCaster->CastCustomSpell(triggerTarget, triggerSpellId, &basepoints0, nullptr, nullptr, true, nullptr, this); } else TC_LOG_ERROR("spells","AuraEffect::HandleProcTriggerSpellWithValueAuraProc: Could not trigger spell %u from aura %u proc, because the spell does not have an entry in Spell.dbc.", triggerSpellId, GetId()); @@ -6184,7 +6189,7 @@ void AuraEffect::HandleRaidProcFromChargeAuraProc(AuraApplication* aurApp, ProcE if (Unit* triggerTarget = target->GetNextRandomRaidMemberOrPet(radius)) { - target->CastSpell(triggerTarget, GetSpellInfo(), true, NULL, this, GetCasterGUID()); + target->CastSpell(triggerTarget, GetSpellInfo(), true, nullptr, this, GetCasterGUID()); if (Aura* aura = triggerTarget->GetAura(GetId(), GetCasterGUID())) aura->SetCharges(jumps); } @@ -6192,7 +6197,7 @@ void AuraEffect::HandleRaidProcFromChargeAuraProc(AuraApplication* aurApp, ProcE } TC_LOG_DEBUG("spells", "AuraEffect::HandleRaidProcFromChargeAuraProc: Triggering spell %u from aura %u proc", triggerSpellId, GetId()); - target->CastSpell(target, triggerSpellId, true, NULL, this, GetCasterGUID()); + target->CastSpell(target, triggerSpellId, true, nullptr, this, GetCasterGUID()); } @@ -6225,7 +6230,7 @@ void AuraEffect::HandleRaidProcFromChargeWithValueAuraProc(AuraApplication* aurA if (Unit* triggerTarget = target->GetNextRandomRaidMemberOrPet(radius)) { - target->CastCustomSpell(triggerTarget, GetId(), &value, NULL, NULL, true, NULL, this, GetCasterGUID()); + target->CastCustomSpell(triggerTarget, GetId(), &value, nullptr, nullptr, true, nullptr, this, GetCasterGUID()); if (Aura* aura = triggerTarget->GetAura(GetId(), GetCasterGUID())) aura->SetCharges(jumps); } @@ -6233,7 +6238,7 @@ void AuraEffect::HandleRaidProcFromChargeWithValueAuraProc(AuraApplication* aurA } TC_LOG_DEBUG("spells", "AuraEffect::HandleRaidProcFromChargeWithValueAuraProc: Triggering spell %u from aura %u proc", triggerSpellId, GetId()); - target->CastCustomSpell(target, triggerSpellId, &value, NULL, NULL, true, NULL, this, GetCasterGUID()); + target->CastCustomSpell(target, triggerSpellId, &value, nullptr, nullptr, true, nullptr, this, GetCasterGUID()); } void AuraEffect::HandleProcOnPowerAmountAuraProc(AuraApplication* aurApp, ProcEventInfo& eventInfo) @@ -6257,7 +6262,7 @@ void AuraEffect::HandleProcOnPowerAmountAuraProc(AuraApplication* aurApp, ProcEv if (SpellInfo const* triggeredSpellInfo = sSpellMgr->GetSpellInfo(triggerSpellId)) { TC_LOG_DEBUG("spells", "AuraEffect::HandleProcOnPowerAmountAuraProc: Triggering spell %u from aura %u proc", triggeredSpellInfo->Id, GetId()); - triggerCaster->CastSpell(triggerTarget, triggeredSpellInfo, true, NULL, this); + triggerCaster->CastSpell(triggerTarget, triggeredSpellInfo, true, nullptr, this); } else TC_LOG_ERROR("spells", "AuraEffect::HandleProcOnPowerAmountAuraProc: Could not trigger spell %u from aura %u proc, because the spell does not have an entry in Spell.dbc.", triggerSpellId, GetId()); @@ -6278,7 +6283,7 @@ void AuraEffect::HandleAuraForceWeather(AuraApplication const* aurApp, uint8 mod WorldPacket data(SMSG_WEATHER, (4 + 4 + 1)); data << uint32(GetMiscValue()) << 1.0f << uint8(0); - target->GetSession()->SendPacket(&data); + target->SendDirectMessage(&data); } else { diff --git a/src/server/game/Spells/Auras/SpellAuras.cpp b/src/server/game/Spells/Auras/SpellAuras.cpp index d68ff6aeba4..966b0d416b7 100644 --- a/src/server/game/Spells/Auras/SpellAuras.cpp +++ b/src/server/game/Spells/Auras/SpellAuras.cpp @@ -17,26 +17,27 @@ */ #include "Common.h" -#include "WorldPacket.h" -#include "Opcodes.h" -#include "Log.h" -#include "ObjectMgr.h" -#include "SpellMgr.h" -#include "Player.h" -#include "Unit.h" -#include "Spell.h" -#include "SpellHistory.h" -#include "SpellAuraEffects.h" -#include "DynamicObject.h" -#include "ObjectAccessor.h" -#include "Util.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" #include "CellImpl.h" -#include "ScriptMgr.h" -#include "SpellScript.h" -#include "Vehicle.h" #include "Config.h" +#include "DynamicObject.h" +#include "GridNotifiersImpl.h" +#include "Item.h" +#include "Log.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Opcodes.h" +#include "Player.h" +#include "ScriptMgr.h" +#include "Spell.h" +#include "SpellAuraEffects.h" +#include "SpellHistory.h" +#include "SpellMgr.h" +#include "SpellScript.h" +#include "Unit.h" +#include "Util.h" +#include "Vehicle.h" +#include "World.h" +#include "WorldPacket.h" AuraApplication::AuraApplication(Unit* target, Unit* caster, Aura* aura, uint8 effMask): _target(target), _base(aura), _removeMode(AURA_REMOVE_NONE), _slot(MAX_AURAS), @@ -350,7 +351,7 @@ Aura* Aura::Create(SpellInfo const* spellproto, uint8 effMask, WorldObject* owne Aura::Aura(SpellInfo const* spellproto, WorldObject* owner, Unit* caster, Item* castItem, ObjectGuid casterGUID) : m_spellInfo(spellproto), m_casterGuid(casterGUID ? casterGUID : caster->GetGUID()), -m_castItemGuid(castItem ? castItem->GetGUID() : ObjectGuid::Empty), m_applyTime(time(NULL)), +m_castItemGuid(castItem ? castItem->GetGUID() : ObjectGuid::Empty), m_applyTime(time(nullptr)), 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), @@ -372,7 +373,7 @@ AuraScript* Aura::GetScriptByName(std::string const& scriptName) const for (auto itr = m_loadedScripts.begin(); itr != m_loadedScripts.end(); ++itr) if ((*itr)->_GetScriptName()->compare(scriptName) == 0) return *itr; - return NULL; + return nullptr; } void Aura::_InitEffects(uint8 effMask, Unit* caster, int32 *baseAmount) @@ -381,9 +382,9 @@ void Aura::_InitEffects(uint8 effMask, Unit* caster, int32 *baseAmount) for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (effMask & (uint8(1) << i)) - m_effects[i] = new AuraEffect(this, i, baseAmount ? baseAmount + i : NULL, caster); + m_effects[i] = new AuraEffect(this, i, baseAmount ? baseAmount + i : nullptr, caster); else - m_effects[i] = NULL; + m_effects[i] = nullptr; } } @@ -433,7 +434,7 @@ void Aura::_ApplyForTarget(Unit* target, Unit* caster, AuraApplication * auraApp { if (m_spellInfo->IsCooldownStartedOnEvent()) { - Item* castItem = m_castItemGuid ? caster->ToPlayer()->GetItemByGuid(m_castItemGuid) : NULL; + Item* castItem = m_castItemGuid ? caster->ToPlayer()->GetItemByGuid(m_castItemGuid) : nullptr; caster->GetSpellHistory()->StartCooldown(m_spellInfo, castItem ? castItem->GetEntry() : 0, nullptr, true); } } @@ -656,8 +657,8 @@ void Aura::UpdateOwner(uint32 diff, WorldObject* owner) Unit* caster = GetCaster(); // Apply spellmods for channeled auras // used for example when triggered spell of spell:10 is modded - Spell* modSpell = NULL; - Player* modOwner = NULL; + Spell* modSpell = nullptr; + Player* modOwner = nullptr; if (caster) { modOwner = caster->GetSpellModOwner(); @@ -727,7 +728,7 @@ void Aura::Update(uint32 diff, Unit* caster) int32 Aura::CalcMaxDuration(Unit* caster) const { - Player* modOwner = NULL; + Player* modOwner = nullptr; int32 maxDuration; if (caster) @@ -743,7 +744,7 @@ int32 Aura::CalcMaxDuration(Unit* caster) const // IsPermanent() checks max duration (which we are supposed to calculate here) if (maxDuration != -1 && modOwner) - modOwner->ApplySpellMod(GetId(), maxDuration); + modOwner->ApplySpellMod(GetId(), SPELLMOD_DURATION, maxDuration); return maxDuration; } @@ -753,7 +754,7 @@ void Aura::SetDuration(int32 duration, bool withMods) if (withMods) if (Unit* caster = GetCaster()) if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(GetId(), duration); + modOwner->ApplySpellMod(GetId(), SPELLMOD_DURATION, duration); m_duration = duration; SetNeedClientUpdateForTargets(); @@ -824,7 +825,7 @@ uint8 Aura::CalcMaxCharges(Unit* caster) const if (caster) if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(GetId(), maxProcCharges); + modOwner->ApplySpellMod(GetId(), SPELLMOD_CHARGES, maxProcCharges); return uint8(maxProcCharges); } @@ -1090,7 +1091,7 @@ int32 Aura::CalcDispelChance(Unit const* auraTarget, bool offensive) const // Apply dispel mod from aura caster if (Unit* caster = GetCaster()) if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(GetId(), resistChance); + modOwner->ApplySpellMod(GetId(), SPELLMOD_RESIST_DISPEL_CHANCE, resistChance); // Dispel resistance from target SPELL_AURA_MOD_DISPEL_RESIST // Only affects offensive dispels @@ -1217,7 +1218,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b if (*itr < 0) target->RemoveAurasDueToSpell(-(*itr)); else if (removeMode != AURA_REMOVE_BY_DEATH) - target->CastSpell(target, *itr, true, NULL, NULL, GetCasterGUID()); + target->CastSpell(target, *itr, true, nullptr, nullptr, GetCasterGUID()); } } if (std::vector const* spellTriggered = sSpellMgr->GetSpellLinked(GetId() + SPELL_LINK_AURA)) @@ -1280,7 +1281,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b if (caster->HasAura(64760)) { int32 heal = GetEffect(EFFECT_0)->GetAmount(); - caster->CastCustomSpell(target, 64801, &heal, NULL, NULL, true, NULL, GetEffect(EFFECT_0)); + caster->CastCustomSpell(target, 64801, &heal, nullptr, nullptr, true, nullptr, GetEffect(EFFECT_0)); } } break; @@ -1318,7 +1319,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b { int32 damage = (devouringPlague->GetAmount() + devouringPlague->GetBonusAmount()) * devouringPlague->GetDonePct(); if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(GetSpellInfo()->Id, damage); + modOwner->ApplySpellMod(GetSpellInfo()->Id, SPELLMOD_DOT, damage); damage = target->SpellDamageBonusTaken(caster, GetSpellInfo(), damage, DOT); @@ -1372,7 +1373,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b case 66: // Invisibility if (removeMode != AURA_REMOVE_BY_EXPIRE) break; - target->CastSpell(target, 32612, true, NULL, GetEffect(1)); + target->CastSpell(target, 32612, true, nullptr, GetEffect(1)); target->CombatStop(); break; default: @@ -1428,7 +1429,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const* aurApp, Unit* caster, b { float multiplier = float(aurEff->GetAmount()); int32 basepoints0 = int32(CalculatePct(caster->GetMaxPower(POWER_MANA), multiplier)); - caster->CastCustomSpell(caster, 47755, &basepoints0, NULL, NULL, true); + caster->CastCustomSpell(caster, 47755, &basepoints0, nullptr, nullptr, true); } } } @@ -1672,7 +1673,7 @@ bool Aura::CanStackWith(Aura const* existingAura) const if (HasEffectType(SPELL_AURA_CONTROL_VEHICLE) && existingAura->HasEffectType(SPELL_AURA_CONTROL_VEHICLE)) { - Vehicle* veh = NULL; + Vehicle* veh = nullptr; if (GetOwner()->ToUnit()) veh = GetOwner()->ToUnit()->GetVehicleKit(); @@ -1865,7 +1866,7 @@ float Aura::CalcProcChance(SpellProcEntry const& procEntry, ProcEventInfo& event } // apply chance modifer aura, applies also to ppm chance (see improved judgement of light spell) if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(GetId(), chance); + modOwner->ApplySpellMod(GetId(), SPELLMOD_CHANCE_OF_SUCCESS, chance); } // proc chance is reduced by an additional 3.333% per level past 60 diff --git a/src/server/game/Spells/Auras/SpellAuras.h b/src/server/game/Spells/Auras/SpellAuras.h index 426bddcd5db..caf05545ca9 100644 --- a/src/server/game/Spells/Auras/SpellAuras.h +++ b/src/server/game/Spells/Auras/SpellAuras.h @@ -176,7 +176,7 @@ class TC_GAME_API Aura void SetLoadedState(int32 maxduration, int32 duration, int32 charges, uint8 stackamount, uint8 recalculateMask, int32 * amount); // helpers for aura effects - bool HasEffect(uint8 effIndex) const { return GetEffect(effIndex) != NULL; } + bool HasEffect(uint8 effIndex) const { return GetEffect(effIndex) != nullptr; } bool HasEffectType(AuraType type) const; AuraEffect* GetEffect(uint8 effIndex) const { ASSERT (effIndex < MAX_SPELL_EFFECTS); return m_effects[effIndex]; } uint8 GetEffectMask() const { uint8 effMask = 0; for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (m_effects[i]) effMask |= 1<second; return NULL; } - AuraApplication* GetApplicationOfTarget(ObjectGuid guid) { ApplicationMap::iterator itr = m_applications.find(guid); if (itr != m_applications.end()) return itr->second; return NULL; } + const AuraApplication* GetApplicationOfTarget(ObjectGuid guid) const { ApplicationMap::const_iterator itr = m_applications.find(guid); if (itr != m_applications.end()) return itr->second; return nullptr; } + AuraApplication* GetApplicationOfTarget(ObjectGuid guid) { ApplicationMap::iterator itr = m_applications.find(guid); if (itr != m_applications.end()) return itr->second; return nullptr; } bool IsAppliedOnTarget(ObjectGuid guid) const { return m_applications.find(guid) != m_applications.end(); } void SetNeedClientUpdateForTargets() const; @@ -234,11 +234,16 @@ class TC_GAME_API Aura bool CallScriptEffectProcHandlers(AuraEffect const* aurEff, AuraApplication const* aurApp, ProcEventInfo& eventInfo); void CallScriptAfterEffectProcHandlers(AuraEffect const* aurEff, AuraApplication const* aurApp, ProcEventInfo& eventInfo); - AuraScript* GetScriptByName(std::string const& scriptName) const; + template + Script* GetScript(std::string const& scriptName) const + { + return dynamic_cast(GetScriptByName(scriptName)); + } std::vector m_loadedScripts; private: + AuraScript* GetScriptByName(std::string const& scriptName) const; void _DeleteRemovedApplications(); protected: diff --git a/src/server/game/Spells/Spell.cpp b/src/server/game/Spells/Spell.cpp index b289c048c0f..6633cfaac0c 100644 --- a/src/server/game/Spells/Spell.cpp +++ b/src/server/game/Spells/Spell.cpp @@ -16,48 +16,49 @@ * with this program. If not, see . */ -#include "Common.h" -#include "DatabaseEnv.h" -#include "WorldPacket.h" -#include "WorldSession.h" -#include "GameTime.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "Opcodes.h" -#include "Log.h" -#include "UpdateMask.h" -#include "World.h" -#include "ObjectMgr.h" -#include "SpellMgr.h" -#include "Player.h" -#include "Pet.h" -#include "Unit.h" #include "Spell.h" -#include "DynamicObject.h" -#include "Guild.h" -#include "UpdateData.h" -#include "ObjectAccessor.h" -#include "CellImpl.h" -#include "SharedDefines.h" -#include "LootMgr.h" -#include "VMapFactory.h" -#include "Battleground.h" -#include "Util.h" -#include "TemporarySummon.h" -#include "Vehicle.h" -#include "SpellAuraEffects.h" -#include "ScriptMgr.h" -#include "ConditionMgr.h" -#include "DisableMgr.h" -#include "SpellScript.h" -#include "InstanceScript.h" -#include "SpellInfo.h" -#include "SpellHistory.h" -#include "DB2Stores.h" #include "Battlefield.h" #include "BattlefieldMgr.h" -#include "TradeData.h" +#include "Battleground.h" +#include "CellImpl.h" +#include "Common.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "DB2Stores.h" +#include "DisableMgr.h" +#include "DynamicObject.h" #include "GameObjectAI.h" +#include "GameTime.h" +#include "GridNotifiersImpl.h" +#include "Guild.h" +#include "InstanceScript.h" +#include "Item.h" +#include "Log.h" +#include "LootMgr.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Opcodes.h" +#include "PathGenerator.h" +#include "Pet.h" +#include "Player.h" +#include "ScriptMgr.h" +#include "SharedDefines.h" +#include "SpellAuraEffects.h" +#include "SpellHistory.h" +#include "SpellInfo.h" +#include "SpellMgr.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "TradeData.h" +#include "Unit.h" +#include "UpdateData.h" +#include "UpdateMask.h" +#include "Util.h" +#include "Vehicle.h" +#include "VMapFactory.h" +#include "World.h" +#include "WorldPacket.h" +#include "WorldSession.h" extern pEffect SpellEffects[TOTAL_SPELL_EFFECTS]; @@ -111,8 +112,8 @@ void SpellDestination::RelocateOffset(Position const& offset) SpellCastTargets::SpellCastTargets() : m_elevation(0), m_speed(0), m_strTarget() { - m_objectTarget = NULL; - m_itemTarget = NULL; + m_objectTarget = nullptr; + m_itemTarget = nullptr; m_itemTargetEntry = 0; @@ -246,7 +247,7 @@ Unit* SpellCastTargets::GetUnitTarget() const if (m_objectTarget) return m_objectTarget->ToUnit(); - return NULL; + return nullptr; } void SpellCastTargets::SetUnitTarget(Unit* target) @@ -272,7 +273,7 @@ GameObject* SpellCastTargets::GetGOTarget() const if (m_objectTarget) return m_objectTarget->ToGameObject(); - return NULL; + return nullptr; } void SpellCastTargets::SetGOTarget(GameObject* target) @@ -298,7 +299,7 @@ Corpse* SpellCastTargets::GetCorpseTarget() const if (m_objectTarget) return m_objectTarget->ToCorpse(); - return NULL; + return nullptr; } WorldObject* SpellCastTargets::GetObjectTarget() const @@ -313,7 +314,7 @@ ObjectGuid SpellCastTargets::GetObjectTargetGUID() const void SpellCastTargets::RemoveObjectTarget() { - m_objectTarget = NULL; + m_objectTarget = nullptr; m_objectTargetGUID.Clear(); m_targetMask &= ~(TARGET_FLAG_UNIT_MASK | TARGET_FLAG_CORPSE_MASK | TARGET_FLAG_GAMEOBJECT_MASK); } @@ -443,11 +444,21 @@ void SpellCastTargets::RemoveDst() m_targetMask &= ~(TARGET_FLAG_DEST_LOCATION); } +bool SpellCastTargets::HasSrc() const +{ + return (GetTargetMask() & TARGET_FLAG_SOURCE_LOCATION) != 0; +} + +bool SpellCastTargets::HasDst() const +{ + return (GetTargetMask() & TARGET_FLAG_DEST_LOCATION) != 0; +} + void SpellCastTargets::Update(Unit* caster) { - m_objectTarget = m_objectTargetGUID ? ((m_objectTargetGUID == caster->GetGUID()) ? caster : ObjectAccessor::GetWorldObject(*caster, m_objectTargetGUID)) : NULL; + m_objectTarget = m_objectTargetGUID ? ((m_objectTargetGUID == caster->GetGUID()) ? caster : ObjectAccessor::GetWorldObject(*caster, m_objectTargetGUID)) : nullptr; - m_itemTarget = NULL; + m_itemTarget = nullptr; if (caster->GetTypeId() == TYPEID_PLAYER) { Player* player = caster->ToPlayer(); @@ -513,14 +524,28 @@ SpellValue::SpellValue(SpellInfo const* proto) AuraStackAmount = 1; } +class TC_GAME_API SpellEvent : public BasicEvent +{ + public: + SpellEvent(Spell* spell); + ~SpellEvent(); + + virtual bool Execute(uint64 e_time, uint32 p_time) override; + virtual void Abort(uint64 e_time) override; + virtual bool IsDeletable() const override; + + protected: + Spell* m_Spell; +}; + Spell::Spell(Unit* caster, SpellInfo const* info, TriggerCastFlags triggerFlags, ObjectGuid originalCasterGUID, bool skipCheck) : m_spellInfo(sSpellMgr->GetSpellForDifficultyFromSpell(info, caster)), m_caster((info->HasAttribute(SPELL_ATTR6_CAST_BY_CHARMER) && caster->GetCharmerOrOwner()) ? caster->GetCharmerOrOwner() : caster) -, m_spellValue(new SpellValue(m_spellInfo)), m_preGeneratedPath(PathGenerator(m_caster)) +, m_spellValue(new SpellValue(m_spellInfo)) { m_customError = SPELL_CUSTOM_ERROR_NONE; m_skipCheck = skipCheck; - m_selfContainer = NULL; + m_selfContainer = nullptr; m_referencedFromCurrentSpell = false; m_executedCurrently = false; m_needComboPoints = m_spellInfo->NeedsComboPoints(); @@ -572,7 +597,7 @@ m_caster((info->HasAttribute(SPELL_ATTR6_CAST_BY_CHARMER) && caster->GetCharmerO { m_originalCaster = ObjectAccessor::GetUnit(*m_caster, m_originalCasterGUID); if (m_originalCaster && !m_originalCaster->IsInWorld()) - m_originalCaster = NULL; + m_originalCaster = nullptr; } m_spellState = SPELL_STATE_NULL; @@ -580,14 +605,14 @@ m_caster((info->HasAttribute(SPELL_ATTR6_CAST_BY_CHARMER) && caster->GetCharmerO if (info->HasAttribute(SPELL_ATTR4_CAN_CAST_WHILE_CASTING)) _triggeredCastFlags = TriggerCastFlags(uint32(_triggeredCastFlags) | TRIGGERED_IGNORE_CAST_IN_PROGRESS | TRIGGERED_CAST_DIRECTLY); - m_CastItem = NULL; + m_CastItem = nullptr; m_castItemGUID.Clear(); m_castItemEntry = 0; - unitTarget = NULL; - itemTarget = NULL; - gameObjTarget = NULL; - destTarget = NULL; + unitTarget = nullptr; + itemTarget = nullptr; + gameObjTarget = nullptr; + destTarget = nullptr; damage = 0; targetMissInfo = SPELL_MISS_NONE; effectHandleMode = SPELL_EFFECT_HANDLE_LAUNCH; @@ -596,12 +621,12 @@ m_caster((info->HasAttribute(SPELL_ATTR6_CAST_BY_CHARMER) && caster->GetCharmerO m_procAttacker = 0; m_procVictim = 0; m_hitMask = 0; - focusObject = NULL; + focusObject = nullptr; m_cast_count = 0; m_glyphIndex = 0; m_preCastSpell = 0; - m_triggeredByAuraSpell = NULL; - m_spellAura = NULL; + m_triggeredByAuraSpell = nullptr; + m_spellAura = nullptr; //Auto Shot & Shoot (wand) m_autoRepeat = m_spellInfo->IsAutoRepeatRangedSpell(); @@ -642,7 +667,7 @@ Spell::~Spell() // Clean the reference to avoid later crash. // If this error is repeating, we may have to add an ASSERT to better track down how we get into this case. TC_LOG_ERROR("spells", "SPELL: deleting spell for spell ID %u. However, spell still referenced.", m_spellInfo->Id); - *m_selfContainer = NULL; + *m_selfContainer = nullptr; } if (m_caster && m_caster->GetTypeId() == TYPEID_PLAYER) @@ -677,7 +702,7 @@ void Spell::InitExplicitTargets(SpellCastTargets const& targets) // try to select correct unit target if not provided by client or by serverside cast if (neededTargets & (TARGET_FLAG_UNIT_MASK)) { - Unit* unit = NULL; + Unit* unit = nullptr; // try to use player selection as a target if (Player* playerCaster = m_caster->ToPlayer()) { @@ -744,7 +769,7 @@ void Spell::SelectExplicitTargets() redirect = m_caster->GetMeleeHitRedirectTarget(target, m_spellInfo); break; default: - redirect = NULL; + redirect = nullptr; break; } if (redirect && (redirect != target)) @@ -1096,7 +1121,7 @@ void Spell::SelectImplicitNearbyTargets(SpellEffIndex effIndex, SpellImplicitTar CallScriptObjectTargetSelectHandlers(target, effIndex, targetType); if (!target) { - TC_LOG_DEBUG("spells", "Spell::SelectImplicitNearbyTargets: OnObjectTargetSelect script hook for spell Id %u set NULL target, effect %u", m_spellInfo->Id, effIndex); + TC_LOG_DEBUG("spells", "Spell::SelectImplicitNearbyTargets: OnObjectTargetSelect script hook for spell Id %u set nullptr target, effect %u", m_spellInfo->Id, effIndex); SendCastResult(SPELL_FAILED_BAD_IMPLICIT_TARGETS); finish(false); return; @@ -1187,7 +1212,7 @@ void Spell::SelectImplicitConeTargets(SpellEffIndex effIndex, SpellImplicitTarge void Spell::SelectImplicitAreaTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType, uint32 effMask) { - Unit* referer = NULL; + Unit* referer = nullptr; switch (targetType.GetReferenceType()) { case TARGET_REFERENCE_TYPE_SRC: @@ -1219,7 +1244,7 @@ void Spell::SelectImplicitAreaTargets(SpellEffIndex effIndex, SpellImplicitTarge if (!referer) return; - Position const* center = NULL; + Position const* center = nullptr; switch (targetType.GetReferenceType()) { case TARGET_REFERENCE_TYPE_SRC: @@ -1447,7 +1472,7 @@ void Spell::SelectImplicitDestDestTargets(SpellEffIndex effIndex, SpellImplicitT void Spell::SelectImplicitCasterObjectTargets(SpellEffIndex effIndex, SpellImplicitTargetInfo const& targetType) { - WorldObject* target = NULL; + WorldObject* target = nullptr; bool checkIfValid = true; switch (targetType.GetTarget()) @@ -1516,7 +1541,7 @@ void Spell::SelectImplicitChainTargets(SpellEffIndex effIndex, SpellImplicitTarg { uint32 maxTargets = m_spellInfo->Effects[effIndex].ChainTarget; if (Player* modOwner = m_caster->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, maxTargets, this); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_JUMP_TARGETS, maxTargets, this); if (maxTargets > 1) { @@ -1738,7 +1763,7 @@ void Spell::SelectEffectTypeImplicitTargets(uint8 effIndex) if (!targetMask) return; - WorldObject* target = NULL; + WorldObject* target = nullptr; switch (m_spellInfo->Effects[effIndex].GetImplicitTargetType()) { @@ -1851,10 +1876,10 @@ void Spell::SearchTargets(SEARCHER& searcher, uint32 containerMask, Unit* refere WorldObject* Spell::SearchNearbyTarget(float range, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionContainer* condList) { - WorldObject* target = NULL; + WorldObject* target = nullptr; uint32 containerTypeMask = GetSearcherTypeMask(objectType, condList); if (!containerTypeMask) - return NULL; + return nullptr; Trinity::WorldObjectSpellNearbyTargetCheck check(range, m_caster, m_spellInfo, selectionType, condList); Trinity::WorldObjectLastSearcher searcher(m_caster, target, check, containerTypeMask); SearchTargets > (searcher, containerTypeMask, m_caster, m_caster, range); @@ -1969,7 +1994,7 @@ void Spell::SearchChainTargets(std::list& targets, uint32 chainTar GameObject* Spell::SearchSpellFocus() { - GameObject* focus = NULL; + GameObject* focus = nullptr; Trinity::GameObjectFocusCheck check(m_caster, m_spellInfo->RequiresSpellFocus); Trinity::GameObjectSearcher searcher(m_caster, focus, check); SearchTargets > (searcher, GRID_MAP_TYPE_MASK_GAMEOBJECT, m_caster, m_caster, m_caster->GetVisibilityRange()); @@ -2318,7 +2343,7 @@ void Spell::DoAllEffectOnTarget(TargetInfo* target) // can't use default call because of threading, do stuff as fast as possible for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (farMask & (1 << i)) - HandleEffects(unit, NULL, NULL, i, SPELL_EFFECT_HANDLE_HIT_TARGET); + HandleEffects(unit, nullptr, nullptr, i, SPELL_EFFECT_HANDLE_HIT_TARGET); return; } @@ -2760,7 +2785,7 @@ SpellMissInfo Spell::DoSpellHitOnUnit(Unit* unit, uint32 effectMask, bool scaleA for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) if (effectMask & (1 << effectNumber)) - HandleEffects(unit, NULL, NULL, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); + HandleEffects(unit, nullptr, nullptr, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); return SPELL_MISS_NONE; } @@ -2856,7 +2881,7 @@ void Spell::DoAllEffectOnTarget(GOTargetInfo* target) for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) if (effectMask & (1 << effectNumber)) - HandleEffects(NULL, NULL, go, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); + HandleEffects(nullptr, nullptr, go, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); if (go->AI()) go->AI()->SpellHit(m_caster, m_spellInfo); @@ -2876,7 +2901,7 @@ void Spell::DoAllEffectOnTarget(ItemTargetInfo* target) for (uint32 effectNumber = 0; effectNumber < MAX_SPELL_EFFECTS; ++effectNumber) if (effectMask & (1 << effectNumber)) - HandleEffects(NULL, target->item, NULL, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); + HandleEffects(nullptr, target->item, nullptr, effectNumber, SPELL_EFFECT_HANDLE_HIT_TARGET); CallScriptOnHitHandlers(); @@ -2902,7 +2927,7 @@ bool Spell::UpdateChanneledTargetList() { range = m_spellInfo->GetMaxRange(m_spellInfo->IsPositive()); if (Player* modOwner = m_caster->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, range, this); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, range, this); // add little tolerance level range += std::min(MAX_SPELL_RANGE_TOLERANCE, range*0.1f); // 10% but no more than MAX_SPELL_RANGE_TOLERANCE @@ -3162,7 +3187,7 @@ void Spell::cancel() SetReferencedFromCurrent(false); if (m_selfContainer && *m_selfContainer == this) - *m_selfContainer = NULL; + *m_selfContainer = nullptr; m_caster->RemoveDynObject(m_spellInfo->Id); if (m_spellInfo->IsChanneled()) // if not channeled then the object for the current cast wasn't summoned yet @@ -3383,7 +3408,7 @@ void Spell::_cast(bool skipCheck) // Okay, everything is prepared. Now we need to distinguish between immediate and evented delayed spells if ((m_spellInfo->Speed > 0.0f && !m_spellInfo->IsChanneled()) || m_spellInfo->HasAttribute(SPELL_ATTR4_UNK4)) { - // Remove used for cast item if need (it can be already NULL after TakeReagents call + // Remove used for cast item if need (it can be already nullptr after TakeReagents call // in case delayed spell remove item at cast delay start TakeCastItem(); @@ -3456,7 +3481,7 @@ void Spell::handle_immediate() // First mod_duration then haste - see Missile Barrage // Apply duration mod if (Player* modOwner = m_caster->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, duration); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration); // Apply haste mods m_caster->ModSpellDurationTime(m_spellInfo, duration, this); @@ -3496,7 +3521,7 @@ void Spell::handle_immediate() // spell is finished, perform some last features of the spell here _handle_finish_phase(); - // Remove used for cast item if need (it can be already NULL after TakeReagents call + // Remove used for cast item if need (it can be already nullptr after TakeReagents call TakeCastItem(); // handle ammo consumption for thrown weapons @@ -3584,7 +3609,7 @@ uint64 Spell::handle_delayed(uint64 t_offset) void Spell::_handle_immediate_phase() { - m_spellAura = NULL; + m_spellAura = nullptr; // handle some immediate features of the spell here HandleThreatSpells(); @@ -3599,7 +3624,7 @@ void Spell::_handle_immediate_phase() continue; // call effect handlers to handle destination hit - HandleEffects(NULL, NULL, NULL, j, SPELL_EFFECT_HANDLE_HIT); + HandleEffects(nullptr, nullptr, nullptr, j, SPELL_EFFECT_HANDLE_HIT); } // process items @@ -4017,7 +4042,7 @@ void Spell::SendPetCastResult(SpellCastResult result) WorldPacket data(SMSG_PET_CAST_FAILED, 1 + 4 + 1); WriteCastResultInfo(data, player, m_spellInfo, m_cast_count, result, m_customError); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } void Spell::SendSpellStart() @@ -4331,7 +4356,7 @@ void Spell::SendLogExecute() data.append(*m_effectExecuteData[i]); delete m_effectExecuteData[i]; - m_effectExecuteData[i] = NULL; + m_effectExecuteData[i] = nullptr; } m_caster->SendMessageToSet(&data, true); } @@ -4538,7 +4563,7 @@ void Spell::SendResurrectRequest(Player* target) // override delay sent with SMSG_CORPSE_RECLAIM_DELAY, set instant resurrection for spells with this attribute // 4.2.2 edit : id of the spell used to resurect. (used client-side for Mass Resurect) data << uint32(m_spellInfo->Id); - target->GetSession()->SendPacket(&data); + target->SendDirectMessage(&data); } void Spell::TakeCastItem() @@ -4601,9 +4626,9 @@ void Spell::TakeCastItem() // prevent crash at access to deleted m_targets.GetItemTarget if (m_CastItem == m_targets.GetItemTarget()) - m_targets.SetItemTarget(NULL); + m_targets.SetItemTarget(nullptr); - m_CastItem = NULL; + m_CastItem = nullptr; m_castItemGUID.Clear(); m_castItemEntry = 0; } @@ -4626,8 +4651,11 @@ void Spell::TakePower() if (m_caster->GetTypeId() == TYPEID_PLAYER) { if (powerType == POWER_RAGE || powerType == POWER_ENERGY || powerType == POWER_RUNE) + { if (ObjectGuid targetGUID = m_targets.GetUnitTargetGUID()) - for (std::list::iterator ihit= m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) + { + for (std::list::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) + { if (ihit->targetGUID == targetGUID) { if (ihit->missCondition != SPELL_MISS_NONE) @@ -4635,10 +4663,13 @@ void Spell::TakePower() hit = false; //lower spell cost on fail (by talent aura) if (Player* modOwner = m_caster->ToPlayer()->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, m_powerCost); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_SPELL_COST_REFUND_ON_FAIL, m_powerCost); } break; } + } + } + } } if (powerType == POWER_RUNE) @@ -4724,7 +4755,7 @@ SpellCastResult Spell::CheckRuneCost(uint32 runeCostID) const { runeCost[i] = src->RuneCost[i]; if (Player* modOwner = m_caster->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, runeCost[i], const_cast(this)); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, runeCost[i], const_cast(this)); } runeCost[RUNE_DEATH] = MAX_RUNES; // calculated later @@ -4764,7 +4795,7 @@ void Spell::TakeRunePower(bool didHit) { runeCost[i] = runeCostData->RuneCost[i]; if (Player* modOwner = m_caster->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, runeCost[i], this); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, runeCost[i], this); } // Let's say we use a skill that requires a Frost rune. This is the order: @@ -4841,7 +4872,7 @@ void Spell::TakeReagents() if (m_caster->GetTypeId() != TYPEID_PLAYER) return; - ItemTemplate const* castItemTemplate = m_CastItem ? m_CastItem->GetTemplate() : NULL; + ItemTemplate const* castItemTemplate = m_CastItem ? m_CastItem->GetTemplate() : nullptr; // do not take reagents for these item casts if (castItemTemplate && castItemTemplate->Flags & ITEM_FLAG_NO_REAGENT_COST) @@ -4873,14 +4904,14 @@ void Spell::TakeReagents() } } - m_CastItem = NULL; + m_CastItem = nullptr; m_castItemGUID.Clear(); m_castItemEntry = 0; } // if GetItemTarget is also spell reagent if (m_targets.GetItemTargetEntry() == itemid) - m_targets.SetItemTarget(NULL); + m_targets.SetItemTarget(nullptr); p_caster->DestroyItemCount(itemid, itemcount, true); } @@ -4966,7 +4997,7 @@ void Spell::HandleHolyPower(Player* caster) // The spell did hit the target, apply aura cost mods if there are any. if (hit) { - modOwner->ApplySpellMod(m_spellInfo->Id, m_powerCost, this); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_COST, m_powerCost, this); m_caster->ModifyPower(POWER_HOLY_POWER, -m_powerCost); } } @@ -5141,7 +5172,7 @@ SpellCastResult Spell::CheckCast(bool strict, uint32* param1 /*= nullptr*/, uint ConditionSourceInfo condInfo = ConditionSourceInfo(m_caster, m_targets.GetObjectTarget()); if (!sConditionMgr->IsObjectMeetingNotGroupedConditions(CONDITION_SOURCE_TYPE_SPELL, m_spellInfo->Id, condInfo)) { - // mLastFailedCondition can be NULL if there was an error processing the condition in Condition::Meets (i.e. wrong data for ConditionTarget or others) + // mLastFailedCondition can be nullptr if there was an error processing the condition in Condition::Meets (i.e. wrong data for ConditionTarget or others) if (condInfo.mLastFailedCondition && condInfo.mLastFailedCondition->ErrorType) { if (condInfo.mLastFailedCondition->ErrorType == SPELL_FAILED_CUSTOM_ERROR) @@ -5454,26 +5485,27 @@ SpellCastResult Spell::CheckCast(bool strict, uint32* param1 /*= nullptr*/, uint float objSize = target->GetObjectSize(); float range = m_spellInfo->GetMaxRange(true, m_caster, this) * 1.5f + objSize; // can't be overly strict - m_preGeneratedPath.SetPathLengthLimit(range); + m_preGeneratedPath = Trinity::make_unique(m_caster); + m_preGeneratedPath->SetPathLengthLimit(range); // first try with raycast, if it fails fall back to normal path float targetObjectSize = std::min(target->GetObjectSize(), 4.0f); - bool result = m_preGeneratedPath.CalculatePath(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ() + targetObjectSize, false, true); - if (m_preGeneratedPath.GetPathType() & PATHFIND_SHORT) + bool result = m_preGeneratedPath->CalculatePath(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ() + targetObjectSize, false, true); + if (m_preGeneratedPath->GetPathType() & PATHFIND_SHORT) return SPELL_FAILED_OUT_OF_RANGE; - else if (!result || m_preGeneratedPath.GetPathType() & (PATHFIND_NOPATH | PATHFIND_INCOMPLETE)) + else if (!result || m_preGeneratedPath->GetPathType() & (PATHFIND_NOPATH | PATHFIND_INCOMPLETE)) { - result = m_preGeneratedPath.CalculatePath(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ() + targetObjectSize, false, false); - if (m_preGeneratedPath.GetPathType() & PATHFIND_SHORT) + result = m_preGeneratedPath->CalculatePath(target->GetPositionX(), target->GetPositionY(), target->GetPositionZ() + targetObjectSize, false, false); + if (m_preGeneratedPath->GetPathType() & PATHFIND_SHORT) return SPELL_FAILED_OUT_OF_RANGE; - else if (!result || m_preGeneratedPath.GetPathType() & (PATHFIND_NOPATH | PATHFIND_INCOMPLETE)) + 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 + 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 + else if (m_preGeneratedPath->IsInvalidDestinationZ(target)) // Check position z, if in a straight line return SPELL_FAILED_NOPATH; - m_preGeneratedPath.ReducePathLenghtByDist(objSize); // move back + m_preGeneratedPath->ReducePathLenghtByDist(objSize); // move back } break; } @@ -5510,7 +5542,7 @@ SpellCastResult Spell::CheckCast(bool strict, uint32* param1 /*= nullptr*/, uint || (m_spellInfo->Effects[i].TargetA.GetTarget() == TARGET_GAMEOBJECT_TARGET && !m_targets.GetGOTarget())) return SPELL_FAILED_BAD_TARGETS; - Item* pTempItem = NULL; + Item* pTempItem = nullptr; if (m_targets.GetTargetMask() & TARGET_FLAG_TRADE_ITEM) { if (TradeData* pTrade = m_caster->ToPlayer()->GetTradeData()) @@ -5610,7 +5642,7 @@ SpellCastResult Spell::CheckCast(bool strict, uint32* param1 /*= nullptr*/, uint { 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()); + pet->CastSpell(pet, 32752, true, nullptr, nullptr, pet->GetGUID()); } else if (!m_spellInfo->HasAttribute(SPELL_ATTR1_DISMISS_PET)) return SPELL_FAILED_ALREADY_HAVE_SUMMON; @@ -6113,6 +6145,11 @@ SpellCastResult Spell::CheckArenaAndRatedBattlegroundCastRules() const return SPELL_CAST_OK; } +int32 Spell::CalculateDamage(uint8 i, Unit const* target) const +{ + return m_caster->CalculateSpellDamage(target, m_spellInfo, i, &m_spellValue->EffectBasePoints[i]); +} + bool Spell::CanAutoCast(Unit* target) { if (!target) @@ -6168,6 +6205,18 @@ bool Spell::CanAutoCast(Unit* target) return false; } +void Spell::CheckSrc() +{ + if (!m_targets.HasSrc()) + m_targets.SetSrc(*m_caster); +} + +void Spell::CheckDst() +{ + if (!m_targets.HasDst()) + m_targets.SetDst(*m_caster); +} + SpellCastResult Spell::CheckRange(bool strict) const { // Don't check for instant cast spells @@ -6257,7 +6306,7 @@ std::pair Spell::GetMinMaxRange(bool strict) const maxRange *= ranged->GetTemplate()->RangedModRange * 0.01f; if (Player* modOwner = m_caster->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, maxRange, const_cast(this)); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_RANGE, maxRange, const_cast(this)); maxRange += rangeMod; @@ -6786,7 +6835,7 @@ void Spell::Delayed() // only called in DealDamage() //check pushback reduce int32 delaytime = 500; // spellcasting delay is normally 500ms int32 delayReduce = 100; // must be initialized to 100 for percent modifiers - m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, delayReduce, this); + m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this); delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100; if (delayReduce >= 100) return; @@ -6824,7 +6873,7 @@ void Spell::DelayedChannel() int32 delaytime = CalculatePct(duration, 25); // channeling delay is normally 25% of its time per hit int32 delayReduce = 100; // must be initialized to 100 for percent modifiers - m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, delayReduce, this); + m_caster->ToPlayer()->ApplySpellMod(m_spellInfo->Id, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this); delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100; if (delayReduce >= 100) return; @@ -6861,7 +6910,7 @@ bool Spell::UpdatePointers() { m_originalCaster = ObjectAccessor::GetUnit(*m_caster, m_originalCasterGUID); if (m_originalCaster && !m_originalCaster->IsInWorld()) - m_originalCaster = NULL; + m_originalCaster = nullptr; } if (m_castItemGUID && m_caster->GetTypeId() == TYPEID_PLAYER) @@ -6883,7 +6932,7 @@ bool Spell::UpdatePointers() return true; // cache last transport - WorldObject* transport = NULL; + WorldObject* transport = nullptr; // update effect destinations (in case of moved transport dest target) for (uint8 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) @@ -6939,11 +6988,11 @@ bool Spell::CheckEffectTarget(Unit const* target, uint32 eff, Position const* lo } // check for ignore LOS on the effect itself - if (m_spellInfo->HasAttribute(SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) || DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, NULL, SPELL_DISABLE_LOS)) + if (m_spellInfo->HasAttribute(SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) || DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_spellInfo->Id, nullptr, SPELL_DISABLE_LOS)) return true; // if spell is triggered, need to check for LOS disable on the aura triggering it and inherit that behaviour - if (IsTriggered() && m_triggeredByAuraSpell && (m_triggeredByAuraSpell->HasAttribute(SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) || DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_triggeredByAuraSpell->Id, NULL, SPELL_DISABLE_LOS))) + if (IsTriggered() && m_triggeredByAuraSpell && (m_triggeredByAuraSpell->HasAttribute(SPELL_ATTR2_CAN_TARGET_NOT_IN_LOS) || DisableMgr::IsDisabledFor(DISABLE_TYPE_SPELL, m_triggeredByAuraSpell->Id, nullptr, SPELL_DISABLE_LOS))) return true; /// @todo shit below shouldn't be here, but it's temporary @@ -6977,7 +7026,7 @@ bool Spell::CheckEffectTarget(Unit const* target, uint32 eff, Position const* lo else { // Get GO cast coordinates if original caster -> GO - WorldObject* caster = NULL; + WorldObject* caster = nullptr; if (m_originalCasterGUID.IsGameObject()) caster = m_caster->GetMap()->GetGameObject(m_originalCasterGUID); if (!caster) @@ -6992,6 +7041,26 @@ bool Spell::CheckEffectTarget(Unit const* target, uint32 eff, Position const* lo return true; } +bool Spell::IsTriggered() const +{ + return (_triggeredCastFlags & TRIGGERED_FULL_MASK) != 0; +} + +bool Spell::IsIgnoringCooldowns() const +{ + return (_triggeredCastFlags & TRIGGERED_IGNORE_SPELL_AND_CATEGORY_CD) != 0; +} + +bool Spell::IsProcDisabled() const +{ + return (_triggeredCastFlags & TRIGGERED_DISALLOW_PROC_EVENTS) != 0; +} + +bool Spell::IsChannelActive() const +{ + return m_caster->GetUInt32Value(UNIT_CHANNEL_SPELL) != 0; +} + bool Spell::IsAutoActionResetSpell() const { /// @todo changed SPELL_INTERRUPT_FLAG_AUTOATTACK -> SPELL_INTERRUPT_FLAG_INTERRUPT to fix compile - is this check correct at all? @@ -7167,7 +7236,7 @@ void Spell::HandleLaunchPhase() if (!m_spellInfo->Effects[i].IsEffect()) continue; - HandleEffects(NULL, NULL, NULL, i, SPELL_EFFECT_HANDLE_LAUNCH); + HandleEffects(nullptr, nullptr, nullptr, i, SPELL_EFFECT_HANDLE_LAUNCH); } float multiplier[MAX_SPELL_EFFECTS]; @@ -7221,7 +7290,7 @@ void Spell::HandleLaunchPhase() void Spell::DoAllEffectOnLaunchTarget(TargetInfo& targetInfo, float* multiplier) { - Unit* unit = NULL; + Unit* unit = nullptr; // In case spell hit target, do all effect on that target if (targetInfo.missCondition == SPELL_MISS_NONE) unit = m_caster->GetGUID() == targetInfo.targetGUID ? m_caster : ObjectAccessor::GetUnit(*m_caster, targetInfo.targetGUID); @@ -7238,7 +7307,7 @@ void Spell::DoAllEffectOnLaunchTarget(TargetInfo& targetInfo, float* multiplier) m_damage = 0; m_healing = 0; - HandleEffects(unit, NULL, NULL, i, SPELL_EFFECT_HANDLE_LAUNCH_TARGET); + HandleEffects(unit, nullptr, nullptr, i, SPELL_EFFECT_HANDLE_LAUNCH_TARGET); if (m_damage > 0) { @@ -7731,7 +7800,7 @@ void Spell::TriggerGlobalCooldown() { // gcd modifier auras are applied only to own spells and only players have such mods if (Player* modOwner = m_caster->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, gcd, this); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_GLOBAL_COOLDOWN, gcd, this); bool isMeleeOrRangedSpell = m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE || m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_RANGED || @@ -7770,9 +7839,9 @@ WorldObjectSpellTargetCheck::WorldObjectSpellTargetCheck(Unit* caster, Unit* ref _targetSelectionType(selectionType), _condList(condList) { if (condList) - _condSrcInfo = new ConditionSourceInfo(NULL, caster); + _condSrcInfo = new ConditionSourceInfo(nullptr, caster); else - _condSrcInfo = NULL; + _condSrcInfo = nullptr; } WorldObjectSpellTargetCheck::~WorldObjectSpellTargetCheck() @@ -7893,7 +7962,7 @@ bool WorldObjectSpellConeTargetCheck::operator()(WorldObject* target) } WorldObjectSpellTrajTargetCheck::WorldObjectSpellTrajTargetCheck(float range, Position const* position, Unit* caster, SpellInfo const* spellInfo) - : WorldObjectSpellAreaTargetCheck(range, position, caster, caster, spellInfo, TARGET_CHECK_DEFAULT, NULL) { } + : WorldObjectSpellAreaTargetCheck(range, position, caster, caster, spellInfo, TARGET_CHECK_DEFAULT, nullptr) { } bool WorldObjectSpellTrajTargetCheck::operator()(WorldObject* target) { diff --git a/src/server/game/Spells/Spell.h b/src/server/game/Spells/Spell.h index dfe12af5a01..f59eee71fb3 100644 --- a/src/server/game/Spells/Spell.h +++ b/src/server/game/Spells/Spell.h @@ -19,20 +19,40 @@ #ifndef __SPELL_H #define __SPELL_H -#include "GridDefines.h" +#include "ConditionMgr.h" +#include "DBCEnums.h" +#include "ObjectGuid.h" +#include "Position.h" #include "SharedDefines.h" -#include "ObjectMgr.h" -#include "SpellInfo.h" -#include "PathGenerator.h" +#include -class Unit; -class Player; -class GameObject; -class DynamicObject; -class WorldObject; class Aura; -class SpellScript; +class AuraEffect; class ByteBuffer; +class Corpse; +class DynamicObject; +class GameObject; +class Item; +class Object; +class PathGenerator; +class Player; +class SpellImplicitTargetInfo; +class SpellInfo; +class SpellEvent; +class SpellScript; +class Unit; +class WorldObject; +class WorldPacket; +struct SummonPropertiesEntry; +enum AuraType : uint32; +enum CurrentSpellTypes : uint8; +enum LootType : uint8; +enum SpellCastTargetFlags : uint32; +enum SpellTargetCheckTypes : uint8; +enum SpellTargetObjectTypes : uint8; +enum SpellValueMod : uint8; +enum TriggerCastFlags : uint32; +enum WeaponAttackType : uint8; #define SPELL_CHANNEL_UPDATE_INTERVAL (1 * IN_MILLISECONDS) #define MAX_SPELL_RANGE_TOLERANCE 3.0f @@ -154,8 +174,8 @@ class TC_GAME_API SpellCastTargets void ModDst(SpellDestination const& spellDest); void RemoveDst(); - bool HasSrc() const { return (GetTargetMask() & TARGET_FLAG_SOURCE_LOCATION) != 0; } - bool HasDst() const { return (GetTargetMask() & TARGET_FLAG_DEST_LOCATION) != 0; } + bool HasSrc() const; + bool HasDst() const; bool HasTraj() const { return m_speed != 0; } float GetElevation() const { return m_elevation; } @@ -223,7 +243,6 @@ static const uint32 SPELL_INTERRUPT_NONPLAYER = 32747; class TC_GAME_API Spell { - friend void Unit::SetCurrentCastSpell(Spell* pSpell); friend class SpellScript; public: @@ -390,13 +409,13 @@ class TC_GAME_API Spell uint32 GetSearcherTypeMask(SpellTargetObjectTypes objType, ConditionContainer* condList); template void SearchTargets(SEARCHER& searcher, uint32 containerMask, Unit* referer, Position const* pos, float radius); - WorldObject* SearchNearbyTarget(float range, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionContainer* condList = NULL); + WorldObject* SearchNearbyTarget(float range, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionContainer* condList = nullptr); void SearchAreaTargets(std::list& targets, float range, Position const* position, Unit* referer, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectionType, ConditionContainer* condList); void SearchChainTargets(std::list& targets, uint32 chainTargets, WorldObject* target, SpellTargetObjectTypes objectType, SpellTargetCheckTypes selectType, ConditionContainer* condList, bool isChainHeal); GameObject* SearchSpellFocus(); - void prepare(SpellCastTargets const* targets, AuraEffect const* triggeredByAura = NULL); + void prepare(SpellCastTargets const* targets, AuraEffect const* triggeredByAura = nullptr); void cancel(); void update(uint32 difftime); void cast(bool skipCheck = false); @@ -433,7 +452,7 @@ class TC_GAME_API Spell bool CheckSpellCancelsFear(uint32* param1) const; bool CheckSpellCancelsConfuse(uint32* param1) const; - int32 CalculateDamage(uint8 i, Unit const* target) const { return m_caster->CalculateSpellDamage(target, m_spellInfo, i, &m_spellValue->EffectBasePoints[i]); } + int32 CalculateDamage(uint8 i, Unit const* target) const; bool HaveTargetsForEffect(uint8 effect) const; void Delayed(); @@ -446,8 +465,8 @@ class TC_GAME_API Spell bool CheckEffectTarget(Unit const* target, uint32 eff, Position const* losPosition) const; bool CanAutoCast(Unit* target); - void CheckSrc() { if (!m_targets.HasSrc()) m_targets.SetSrc(*m_caster); } - void CheckDst() { if (!m_targets.HasDst()) m_targets.SetDst(*m_caster); } + void CheckSrc(); + void CheckDst(); static void WriteCastResultInfo(WorldPacket& data, Player* caster, SpellInfo const* spellInfo, uint8 castCount, SpellCastResult result, SpellCustomErrors customError, uint32* param1 = nullptr, uint32* param2 = nullptr); static void SendCastResult(Player* caster, SpellInfo const* spellInfo, uint8 castCount, SpellCastResult result, SpellCustomErrors customError = SPELL_CUSTOM_ERROR_NONE, uint32* param1 = nullptr, uint32* param2 = nullptr); @@ -493,10 +512,10 @@ class TC_GAME_API Spell bool IsAutoRepeat() const { return m_autoRepeat; } void SetAutoRepeat(bool rep) { m_autoRepeat = rep; } void ReSetTimer() { m_timer = m_casttime > 0 ? m_casttime : 0; } - bool IsTriggered() const { return (_triggeredCastFlags & TRIGGERED_FULL_MASK) != 0; } - bool IsIgnoringCooldowns() const { return (_triggeredCastFlags & TRIGGERED_IGNORE_SPELL_AND_CATEGORY_CD) != 0; } - bool IsProcDisabled() const { return (_triggeredCastFlags & TRIGGERED_DISALLOW_PROC_EVENTS) != 0; } - bool IsChannelActive() const { return m_caster->GetUInt32Value(UNIT_CHANNEL_SPELL) != 0; } + bool IsTriggered() const; + bool IsIgnoringCooldowns() const; + bool IsProcDisabled() const; + bool IsChannelActive() const; bool IsAutoActionResetSpell() const; bool IsTriggeredByAura(SpellInfo const* auraSpellInfo) const { return (auraSpellInfo == m_triggeredByAuraSpell); } @@ -523,6 +542,9 @@ class TC_GAME_API Spell void CleanupTargetList(); void SetSpellValue(SpellValueMod mod, int32 value); + + Spell** m_selfContainer; // pointer to our spell container (if applicable) + protected: bool HasGlobalCooldown() const; void TriggerGlobalCooldown(); @@ -540,8 +562,6 @@ class TC_GAME_API Spell // e.g. damage around area spell trigered by victim aura and damage enemies of aura caster Unit* m_originalCaster; // cached pointer for m_originalCaster, updated at Spell::UpdatePointers() - Spell** m_selfContainer; // pointer to our spell container (if applicable) - //Spell data SpellSchoolMask m_spellSchoolMask; // Spell school (can be overwrite for some spells (wand shoot for example) WeaponAttackType m_attackType; // For weapon based attack @@ -691,7 +711,7 @@ class TC_GAME_API Spell int32 chance; }; - bool CanExecuteTriggersOnHit(uint8 effMask, SpellInfo const* triggeredByAura = NULL) const; + bool CanExecuteTriggersOnHit(uint8 effMask, SpellInfo const* triggeredByAura = nullptr) const; void PrepareTriggersExecutedOnHit(); typedef std::vector HitTriggerSpellList; HitTriggerSpellList m_hitTriggerSpells; @@ -715,7 +735,7 @@ class TC_GAME_API Spell bool m_skipCheck; uint8 m_auraScaleMask; - PathGenerator m_preGeneratedPath; + std::unique_ptr m_preGeneratedPath; ByteBuffer * m_effectExecuteData[MAX_SPELL_EFFECTS]; @@ -775,16 +795,4 @@ namespace Trinity typedef void(Spell::*pEffect)(SpellEffIndex effIndex); -class TC_GAME_API SpellEvent : public BasicEvent -{ - public: - SpellEvent(Spell* spell); - virtual ~SpellEvent(); - - virtual bool Execute(uint64 e_time, uint32 p_time) override; - virtual void Abort(uint64 e_time) override; - virtual bool IsDeletable() const override; - protected: - Spell* m_Spell; -}; #endif diff --git a/src/server/game/Spells/SpellEffects.cpp b/src/server/game/Spells/SpellEffects.cpp index 3ebcfefb607..e5114bfe36f 100644 --- a/src/server/game/Spells/SpellEffects.cpp +++ b/src/server/game/Spells/SpellEffects.cpp @@ -16,50 +16,54 @@ * with this program. If not, see . */ -#include "Common.h" -#include "DatabaseEnv.h" -#include "WorldPacket.h" -#include "Opcodes.h" -#include "Log.h" -#include "UpdateMask.h" -#include "World.h" -#include "ObjectMgr.h" -#include "SpellMgr.h" -#include "PhasingHandler.h" -#include "Player.h" -#include "SkillExtraItems.h" -#include "Unit.h" #include "Spell.h" -#include "DynamicObject.h" -#include "SpellAuras.h" -#include "SpellAuraEffects.h" -#include "Group.h" -#include "SharedDefines.h" -#include "Pet.h" -#include "GameObject.h" -#include "GossipDef.h" -#include "Creature.h" -#include "Totem.h" -#include "CreatureAI.h" -#include "Battleground.h" -#include "OutdoorPvPMgr.h" -#include "Language.h" -#include "SocialMgr.h" -#include "Util.h" -#include "TemporarySummon.h" -#include "GridNotifiers.h" -#include "CellImpl.h" -#include "Formulas.h" -#include "ScriptMgr.h" -#include "SpellHistory.h" -#include "GameObjectAI.h" #include "AccountMgr.h" -#include "InstanceScript.h" -#include "PathGenerator.h" +#include "AreaTrigger.h" +#include "Battleground.h" +#include "CellImpl.h" +#include "Common.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "DatabaseEnv.h" +#include "DynamicObject.h" +#include "Formulas.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "GossipDef.h" +#include "GridNotifiers.h" +#include "Group.h" #include "Guild.h" #include "GuildMgr.h" +#include "InstanceScript.h" +#include "Item.h" +#include "Language.h" +#include "Log.h" +#include "LootMgr.h" +#include "MotionMaster.h" +#include "ObjectMgr.h" +#include "Opcodes.h" +#include "OutdoorPvPMgr.h" +#include "PathGenerator.h" +#include "Pet.h" +#include "PhasingHandler.h" +#include "Player.h" #include "ReputationMgr.h" -#include "AreaTrigger.h" +#include "ScriptMgr.h" +#include "SharedDefines.h" +#include "SkillExtraItems.h" +#include "SocialMgr.h" +#include "SpellAuraEffects.h" +#include "SpellAuras.h" +#include "SpellHistory.h" +#include "SpellMgr.h" +#include "TemporarySummon.h" +#include "Totem.h" +#include "Unit.h" +#include "UpdateMask.h" +#include "Util.h" +#include "World.h" +#include "WorldPacket.h" +#include "WorldSession.h" pEffect SpellEffects[TOTAL_SPELL_EFFECTS]= { @@ -305,7 +309,7 @@ void Spell::EffectInstaKill(SpellEffIndex /*effIndex*/) data << uint32(m_spellInfo->Id); m_caster->SendMessageToSet(&data, true); - m_caster->DealDamage(unitTarget, unitTarget->GetHealth(), NULL, NODAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + m_caster->DealDamage(unitTarget, unitTarget->GetHealth(), nullptr, NODAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); } void Spell::EffectEnvironmentalDMG(SpellEffIndex /*effIndex*/) @@ -716,7 +720,7 @@ void Spell::EffectTriggerSpell(SpellEffIndex effIndex) } // original caster guid only for GO cast - m_caster->CastSpell(targets, spellInfo, &values, TRIGGERED_FULL_MASK, NULL, NULL, m_originalCasterGUID); + m_caster->CastSpell(targets, spellInfo, &values, TRIGGERED_FULL_MASK, nullptr, nullptr, m_originalCasterGUID); } void Spell::EffectTriggerMissileSpell(SpellEffIndex effIndex) @@ -764,7 +768,7 @@ void Spell::EffectTriggerMissileSpell(SpellEffIndex effIndex) } // original caster guid only for GO cast - m_caster->CastSpell(targets, spellInfo, &values, TRIGGERED_FULL_MASK, NULL, NULL, m_originalCasterGUID); + m_caster->CastSpell(targets, spellInfo, &values, TRIGGERED_FULL_MASK, nullptr, nullptr, m_originalCasterGUID); } void Spell::EffectForceCast(SpellEffIndex effIndex) @@ -796,7 +800,7 @@ void Spell::EffectForceCast(SpellEffIndex effIndex) break; case 52463: // Hide In Mine Car case 52349: // Overtake - unitTarget->CastCustomSpell(unitTarget, spellInfo->Id, &damage, NULL, NULL, true, NULL, NULL, m_originalCasterGUID); + unitTarget->CastCustomSpell(unitTarget, spellInfo->Id, &damage, nullptr, nullptr, true, nullptr, nullptr, m_originalCasterGUID); return; } } @@ -804,7 +808,7 @@ void Spell::EffectForceCast(SpellEffIndex effIndex) switch (spellInfo->Id) { case 72298: // Malleable Goo Summon - unitTarget->CastSpell(unitTarget, spellInfo->Id, true, NULL, NULL, m_originalCasterGUID); + unitTarget->CastSpell(unitTarget, spellInfo->Id, true, nullptr, nullptr, m_originalCasterGUID); return; } @@ -840,7 +844,7 @@ void Spell::EffectTriggerRitualOfSummoning(SpellEffIndex effIndex) finish(); - m_caster->CastSpell((Unit*)NULL, spellInfo, false); + m_caster->CastSpell((Unit*)nullptr, spellInfo, false); } void Spell::EffectJump(SpellEffIndex effIndex) @@ -1095,7 +1099,7 @@ void Spell::EffectSendEvent(SpellEffIndex effIndex) && effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; - WorldObject* target = NULL; + WorldObject* target = nullptr; // call events for object target if present if (effectHandleMode == SPELL_EFFECT_HANDLE_HIT_TARGET) @@ -1204,7 +1208,7 @@ void Spell::EffectHeal(SpellEffIndex /*effIndex*/) { Unit::AuraEffectList const& RejorRegr = unitTarget->GetAuraEffectsByType(SPELL_AURA_PERIODIC_HEAL); // find most short by duration - AuraEffect* targetAura = NULL; + AuraEffect* targetAura = nullptr; for (Unit::AuraEffectList::const_iterator i = RejorRegr.begin(); i != RejorRegr.end(); ++i) { if ((*i)->GetSpellInfo()->SpellFamilyName == SPELLFAMILY_DRUID @@ -1223,7 +1227,7 @@ void Spell::EffectHeal(SpellEffIndex /*effIndex*/) int32 tickheal = (targetAura->GetAmount() + targetAura->GetBonusAmount()) * targetAura->GetDonePct(); if (Player* modOwner = m_caster->GetSpellModOwner()) - modOwner->ApplySpellMod(targetAura->GetId(), tickheal); + modOwner->ApplySpellMod(targetAura->GetId(), SPELLMOD_DOT, tickheal); unitTarget->SpellHealingBonusTaken(m_caster, targetAura->GetSpellInfo(), tickheal, DOT); @@ -1338,7 +1342,7 @@ void Spell::DoCreateItem(uint32 /*i*/, uint32 itemtype) ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(newitemid); if (!pProto) { - player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } @@ -1415,28 +1419,27 @@ void Spell::DoCreateItem(uint32 /*i*/, uint32 itemtype) else { // if not created by another reason from full inventory or unique items amount limitation - player->SendEquipError(msg, NULL, NULL, newitemid); + player->SendEquipError(msg, nullptr, nullptr, newitemid); return; } } if (num_to_add) { - uint32 projectId = GetSpellInfo()->ResearchProjectId; - + uint16 projectId = static_cast(GetSpellInfo()->ResearchProjectId); if (projectId && !player->ArchProjectCompleteable(projectId)) { - player->SendEquipError(EQUIP_ERR_SPELL_FAILED_REAGENTS_GENERIC, NULL, NULL); + player->SendEquipError(EQUIP_ERR_SPELL_FAILED_REAGENTS_GENERIC, nullptr, nullptr); return; } // create the new item and store it - Item* pItem = player->StoreNewItem(dest, newitemid, true, Item::GenerateItemRandomPropertyId(newitemid)); + Item* pItem = player->StoreNewItem(dest, newitemid, true, GenerateItemRandomPropertyId(newitemid)); // was it successful? return error if not if (!pItem) { - player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } @@ -1882,9 +1885,9 @@ void Spell::EffectSummonChangeItem(SpellEffIndex effIndex) // prevent crash at access and unexpected charges counting with item update queue corrupt if (m_CastItem == m_targets.GetItemTarget()) - m_targets.SetItemTarget(NULL); + m_targets.SetItemTarget(nullptr); - m_CastItem = NULL; + m_CastItem = nullptr; m_castItemGUID.Clear(); m_castItemEntry = 0; @@ -1903,9 +1906,9 @@ void Spell::EffectSummonChangeItem(SpellEffIndex effIndex) // prevent crash at access and unexpected charges counting with item update queue corrupt if (m_CastItem == m_targets.GetItemTarget()) - m_targets.SetItemTarget(NULL); + m_targets.SetItemTarget(nullptr); - m_CastItem = NULL; + m_CastItem = nullptr; m_castItemGUID.Clear(); m_castItemEntry = 0; @@ -1927,9 +1930,9 @@ void Spell::EffectSummonChangeItem(SpellEffIndex effIndex) // prevent crash at access and unexpected charges counting with item update queue corrupt if (m_CastItem == m_targets.GetItemTarget()) - m_targets.SetItemTarget(NULL); + m_targets.SetItemTarget(nullptr); - m_CastItem = NULL; + m_CastItem = nullptr; m_castItemGUID.Clear(); m_castItemEntry = 0; @@ -1988,9 +1991,9 @@ void Spell::EffectSummonType(SpellEffIndex effIndex) int32 duration = m_spellInfo->GetDuration(); if (Player* modOwner = m_originalCaster->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, duration); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration); - TempSummon* summon = NULL; + TempSummon* summon = nullptr; // determine how many units should be summoned uint32 numSummons; @@ -2272,11 +2275,11 @@ void Spell::EffectDispel(SpellEffIndex effIndex) if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->GetCategory() == SPELLCATEGORY_DEVOUR_MAGIC) { int32 heal_amount = m_spellInfo->Effects[EFFECT_1].CalcValue(m_caster); - m_caster->CastCustomSpell(m_caster, 19658, &heal_amount, NULL, NULL, true); + m_caster->CastCustomSpell(m_caster, 19658, &heal_amount, nullptr, nullptr, true); // Glyph of Felhunter if (Unit* owner = m_caster->GetOwner()) if (owner->GetAura(56249)) - owner->CastCustomSpell(owner, 19658, &heal_amount, NULL, NULL, true); + owner->CastCustomSpell(owner, 19658, &heal_amount, nullptr, nullptr, true); } } @@ -2459,8 +2462,8 @@ void Spell::EffectEnchantItemPerm(SpellEffIndex effIndex) unitTarget = player; // and add a scroll DoCreateItem(effIndex, m_spellInfo->Effects[effIndex].ItemType); - itemTarget = NULL; - m_targets.SetItemTarget(NULL); + itemTarget = nullptr; + m_targets.SetItemTarget(nullptr); } else { @@ -2705,7 +2708,7 @@ void Spell::EffectSummonPet(SpellEffIndex effIndex) if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; - Player* owner = NULL; + Player* owner = nullptr; if (m_originalCaster) { owner = m_originalCaster->ToPlayer(); @@ -2914,7 +2917,7 @@ void Spell::EffectWeaponDmg(SpellEffIndex effIndex) // Skyshatter Harness item set bonus // Stormstrike if (AuraEffect* aurEff = m_caster->IsScriptOverriden(m_spellInfo, 5634)) - m_caster->CastSpell(m_caster, 38430, true, NULL, aurEff); + m_caster->CastSpell(m_caster, 38430, true, nullptr, aurEff); break; } case SPELLFAMILY_DRUID: @@ -3160,7 +3163,7 @@ void Spell::EffectSummonObjectWild(SpellEffIndex effIndex) Map* map = target->GetMap(); if (!pGameObj->Create(map->GenerateLowGuid(), gameobject_id, map, - m_caster->GetPhaseMask(), Position(x, y, z, target->GetOrientation()), G3D::Quat(), 255, GO_STATE_READY)) + m_caster->GetPhaseMask(), Position(x, y, z, target->GetOrientation()), QuaternionData(), 255, GO_STATE_READY)) { delete pGameObj; return; @@ -3263,7 +3266,7 @@ void Spell::EffectScriptEffect(SpellEffIndex effIndex) uint32 spell_id = roll_chance_i(20) ? 8854 : 8855; - m_caster->CastSpell(m_caster, spell_id, true, NULL); + m_caster->CastSpell(m_caster, spell_id, true, nullptr); return; } // Brittle Armor - need remove one 24575 Brittle Armor aura @@ -3347,7 +3350,7 @@ void Spell::EffectScriptEffect(SpellEffIndex effIndex) uint8 bag = 19; uint8 slot = 0; - Item* item = NULL; + Item* item = nullptr; while (bag) // 256 = 0 due to var type { @@ -3593,7 +3596,7 @@ void Spell::EffectScriptEffect(SpellEffIndex effIndex) // proc a spellcast if (Aura* chargesAura = m_caster->GetAura(59907)) { - m_caster->CastSpell(unitTarget, spell_heal, true, NULL, NULL, m_caster->ToTempSummon()->GetSummonerGUID()); + m_caster->CastSpell(unitTarget, spell_heal, true, nullptr, nullptr, m_caster->ToTempSummon()->GetSummonerGUID()); if (chargesAura->ModCharges(-1)) m_caster->ToTempSummon()->UnSummon(); } @@ -3622,14 +3625,14 @@ void Spell::EffectScriptEffect(SpellEffIndex effIndex) Creature* totem = unitTarget->GetMap()->GetCreature(unitTarget->m_SummonSlot[slot]); if (totem && totem->IsTotem()) { - m_caster->CastCustomSpell(totem, 55277, &basepoints0, NULL, NULL, true); + m_caster->CastCustomSpell(totem, 55277, &basepoints0, nullptr, nullptr, true); } } // Glyph of Stoneclaw Totem if (AuraEffect* aur=unitTarget->GetAuraEffect(63298, 0)) { basepoints0 *= aur->GetAmount(); - m_caster->CastCustomSpell(unitTarget, 55277, &basepoints0, NULL, NULL, true); + m_caster->CastCustomSpell(unitTarget, 55277, &basepoints0, nullptr, nullptr, true); } break; } @@ -3770,7 +3773,7 @@ void Spell::EffectDuel(SpellEffIndex effIndex) }; Map* map = m_caster->GetMap(); - if (!pGameObj->Create(map->GenerateLowGuid(), gameobject_id, map, 0, pos, G3D::Quat(), 0, GO_STATE_READY)) + if (!pGameObj->Create(map->GenerateLowGuid(), gameobject_id, map, 0, pos, QuaternionData(), 0, GO_STATE_READY)) { delete pGameObj; return; @@ -3794,8 +3797,8 @@ void Spell::EffectDuel(SpellEffIndex effIndex) WorldPacket data(SMSG_DUEL_REQUESTED, 8 + 8); data << uint64(pGameObj->GetGUID()); data << uint64(caster->GetGUID()); - caster->GetSession()->SendPacket(&data); - target->GetSession()->SendPacket(&data); + caster->SendDirectMessage(&data); + target->SendDirectMessage(&data); // create duel-info DuelInfo* duel = new DuelInfo; @@ -4083,7 +4086,7 @@ void Spell::EffectFeedPet(SpellEffIndex effIndex) player->DestroyItemCount(foodItem, count, true); /// @todo fix crash when a spell has two effects, both pointed at the same item target - m_caster->CastCustomSpell(pet, m_spellInfo->Effects[effIndex].TriggerSpell, &benefit, NULL, NULL, true); + m_caster->CastCustomSpell(pet, m_spellInfo->Effects[effIndex].TriggerSpell, &benefit, nullptr, nullptr, true); } void Spell::EffectDismissPet(SpellEffIndex effIndex) @@ -4131,7 +4134,7 @@ void Spell::EffectSummonObject(SpellEffIndex effIndex) m_caster->GetClosePoint(x, y, z, DEFAULT_WORLD_OBJECT_SIZE); Map* map = m_caster->GetMap(); - if (!go->Create(map->GenerateLowGuid(), go_id, map, 0, Position(x, y, z, m_caster->GetOrientation()), G3D::Quat(), 255, GO_STATE_READY)) + if (!go->Create(map->GenerateLowGuid(), go_id, map, 0, Position(x, y, z, m_caster->GetOrientation()), QuaternionData(), 255, GO_STATE_READY)) { delete go; return; @@ -4436,14 +4439,14 @@ void Spell::EffectCharge(SpellEffIndex /*effIndex*/) float speed = G3D::fuzzyGt(m_spellInfo->Speed, 0.0f) ? m_spellInfo->Speed : SPEED_CHARGE; // Spell is not using explicit target - no generated path - if (m_preGeneratedPath.GetPathType() == PATHFIND_BLANK) + if (!m_preGeneratedPath) { //unitTarget->GetContactPoint(m_caster, pos.m_positionX, pos.m_positionY, pos.m_positionZ); Position pos = unitTarget->GetFirstCollisionPosition(unitTarget->GetObjectSize(), unitTarget->GetRelativeAngle(m_caster)); m_caster->GetMotionMaster()->MoveCharge(pos.m_positionX, pos.m_positionY, pos.m_positionZ, speed); } else - m_caster->GetMotionMaster()->MoveCharge(m_preGeneratedPath, speed); + m_caster->GetMotionMaster()->MoveCharge(*m_preGeneratedPath, speed); } if (effectHandleMode == SPELL_EFFECT_HANDLE_HIT_TARGET) @@ -4731,7 +4734,7 @@ void Spell::EffectDestroyAllTotems(SpellEffIndex /*effIndex*/) } ApplyPct(mana, damage); if (mana) - m_caster->CastCustomSpell(m_caster, 39104, &mana, NULL, NULL, true); + m_caster->CastCustomSpell(m_caster, 39104, &mana, nullptr, nullptr, true); } void Spell::EffectDurabilityDamage(SpellEffIndex effIndex) @@ -4845,7 +4848,7 @@ void Spell::EffectTransmitted(SpellEffIndex effIndex) GameObject* pGameObj = new GameObject; - if (!pGameObj->Create(cMap->GenerateLowGuid(), name_id, cMap, 0, Position(fx, fy, fz, m_caster->GetOrientation()), G3D::Quat(), 255, GO_STATE_READY)) + if (!pGameObj->Create(cMap->GenerateLowGuid(), name_id, cMap, 0, Position(fx, fy, fz, m_caster->GetOrientation()), QuaternionData(), 255, GO_STATE_READY)) { delete pGameObj; return; @@ -5386,7 +5389,7 @@ void Spell::SummonGuardian(uint32 i, uint32 entry, SummonPropertiesEntry const* int32 duration = m_spellInfo->GetDuration(); if (Player* modOwner = m_originalCaster->GetSpellModOwner()) - modOwner->ApplySpellMod(m_spellInfo->Id, duration); + modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration); //TempSummonType summonType = (duration == 0) ? TEMPSUMMON_DEAD_DESPAWN : TEMPSUMMON_TIMED_DESPAWN; Map* map = caster->GetMap(); @@ -5461,7 +5464,7 @@ void Spell::EffectPlayMusic(SpellEffIndex effIndex) WorldPacket data(SMSG_PLAY_MUSIC, 4); data << uint32(soundid); data << uint64(unitTarget->GetGUID()); - unitTarget->ToPlayer()->GetSession()->SendPacket(&data); + unitTarget->ToPlayer()->SendDirectMessage(&data); } void Spell::EffectSpecCount(SpellEffIndex /*effIndex*/) @@ -5612,7 +5615,7 @@ void Spell::EffectRechargeManaGem(SpellEffIndex /*effIndex*/) ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item_id); if (!pProto) { - player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL); + player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } diff --git a/src/server/game/Spells/SpellHistory.cpp b/src/server/game/Spells/SpellHistory.cpp index 10362cd764f..614c31e973c 100644 --- a/src/server/game/Spells/SpellHistory.cpp +++ b/src/server/game/Spells/SpellHistory.cpp @@ -15,14 +15,19 @@ * with this program. If not, see . */ -#include "WorldPacket.h" #include "SpellHistory.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "Item.h" +#include "ObjectMgr.h" +#include "Opcodes.h" #include "Pet.h" #include "Player.h" -#include "SpellInfo.h" #include "Spell.h" +#include "SpellInfo.h" +#include "SpellMgr.h" #include "World.h" -#include "Opcodes.h" +#include "WorldPacket.h" SpellHistory::Clock::duration const SpellHistory::InfinityCooldownDelay = std::chrono::duration_cast(std::chrono::seconds(MONTH)); @@ -307,10 +312,10 @@ void SpellHistory::StartCooldown(SpellInfo const* spellInfo, uint32 itemId, Spel if (Player* modOwner = _owner->GetSpellModOwner()) { if (cooldown >= 0) - modOwner->ApplySpellMod(spellInfo->Id, cooldown, spell); + modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, cooldown, spell); if (categoryCooldown >= 0 && !spellInfo->HasAttribute(SPELL_ATTR6_IGNORE_CATEGORY_COOLDOWN_MODS)) - modOwner->ApplySpellMod(spellInfo->Id, categoryCooldown, spell); + modOwner->ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, categoryCooldown, spell); } if (_owner->HasAuraTypeWithAffectMask(SPELL_AURA_MOD_SPELL_COOLDOWN_BY_HASTE, spellInfo)) diff --git a/src/server/game/Spells/SpellHistory.h b/src/server/game/Spells/SpellHistory.h index 35d756fc0a5..210fa7cc633 100644 --- a/src/server/game/Spells/SpellHistory.h +++ b/src/server/game/Spells/SpellHistory.h @@ -19,18 +19,28 @@ #define SpellHistory_h__ #include "SharedDefines.h" -#include "QueryResult.h" -#include "Transaction.h" +#include "DatabaseEnvFwd.h" #include "GameTime.h" #include +#include +#include class Item; class Player; class Spell; class SpellInfo; class Unit; +class WorldPacket; struct SpellCategoryEntry; +/// Spell cooldown flags sent in SMSG_SPELL_COOLDOWN +enum SpellCooldownFlags +{ + SPELL_COOLDOWN_FLAG_NONE = 0x0, + SPELL_COOLDOWN_FLAG_INCLUDE_GCD = 0x1, ///< Starts GCD in addition to normal cooldown specified in the packet + SPELL_COOLDOWN_FLAG_INCLUDE_EVENT_COOLDOWNS = 0x2 ///< Starts GCD for spells that should start their cooldown on events, requires SPELL_COOLDOWN_FLAG_INCLUDE_GCD set +}; + class TC_GAME_API SpellHistory { public: diff --git a/src/server/game/Spells/SpellInfo.cpp b/src/server/game/Spells/SpellInfo.cpp index c45bda78a39..212475b05ef 100644 --- a/src/server/game/Spells/SpellInfo.cpp +++ b/src/server/game/Spells/SpellInfo.cpp @@ -15,19 +15,23 @@ * with this program. If not, see . */ -#include "SpellAuras.h" #include "SpellInfo.h" +#include "Battleground.h" +#include "Corpse.h" +#include "Creature.h" +#include "DBCStores.h" +#include "InstanceScript.h" +#include "Item.h" +#include "ItemTemplate.h" +#include "Log.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "Random.h" +#include "Spell.h" #include "SpellAuraDefines.h" #include "SpellAuraEffects.h" #include "SpellMgr.h" -#include "Spell.h" -#include "DBCStores.h" -#include "ConditionMgr.h" -#include "Player.h" -#include "Battleground.h" #include "Vehicle.h" -#include "Pet.h" -#include "InstanceScript.h" uint32 GetTargetFlagMask(SpellTargetObjectTypes objType) { @@ -362,13 +366,13 @@ SpellEffectInfo::SpellEffectInfo(SpellEntry const* /*spellEntry*/, SpellInfo con Mechanic = Mechanics(_effect ? _effect->EffectMechanic : 0); TargetA = SpellImplicitTargetInfo(_effect ? _effect->EffectImplicitTargetA : 0); TargetB = SpellImplicitTargetInfo(_effect ? _effect->EffectImplicitTargetB : 0); - RadiusEntry = _effect && _effect->EffectRadiusIndex ? sSpellRadiusStore.LookupEntry(_effect->EffectRadiusIndex) : NULL; - MaxRadiusEntry = _effect && _effect->EffectRadiusMaxIndex ? sSpellRadiusStore.LookupEntry(_effect->EffectRadiusMaxIndex) : NULL; + RadiusEntry = _effect && _effect->EffectRadiusIndex ? sSpellRadiusStore.LookupEntry(_effect->EffectRadiusIndex) : nullptr; + MaxRadiusEntry = _effect && _effect->EffectRadiusMaxIndex ? sSpellRadiusStore.LookupEntry(_effect->EffectRadiusMaxIndex) : nullptr; ChainTarget = _effect ? _effect->EffectChainTarget : 0; ItemType = _effect ? _effect->EffectItemType : 0; TriggerSpell = _effect ? _effect->EffectTriggerSpell : 0; SpellClassMask = _effect ? _effect->EffectSpellClassMask : flag96(0); - ImplicitTargetConditions = NULL; + ImplicitTargetConditions = nullptr; ScalingMultiplier = scaling ? scaling->Multiplier[_effIndex] : 0.0f; DeltaScalingMultiplier = scaling ? scaling->RandomMultiplier[_effIndex] : 0.0f; ComboScalingMultiplier = scaling ? scaling->OtherMultiplier[_effIndex] : 0.0f; @@ -591,27 +595,27 @@ int32 SpellEffectInfo::CalcBaseValue(int32 value) const float SpellEffectInfo::CalcValueMultiplier(Unit* caster, Spell* spell) const { float multiplier = ValueMultiplier; - if (Player* modOwner = (caster ? caster->GetSpellModOwner() : NULL)) - modOwner->ApplySpellMod(_spellInfo->Id, multiplier, spell); + if (Player* modOwner = (caster ? caster->GetSpellModOwner() : nullptr)) + modOwner->ApplySpellMod(_spellInfo->Id, SPELLMOD_VALUE_MULTIPLIER, multiplier, spell); return multiplier; } float SpellEffectInfo::CalcDamageMultiplier(Unit* caster, Spell* spell) const { float multiplierPercent = DamageMultiplier * 100.0f; - if (Player* modOwner = (caster ? caster->GetSpellModOwner() : NULL)) - modOwner->ApplySpellMod(_spellInfo->Id, multiplierPercent, spell); + if (Player* modOwner = (caster ? caster->GetSpellModOwner() : nullptr)) + modOwner->ApplySpellMod(_spellInfo->Id, SPELLMOD_DAMAGE_MULTIPLIER, multiplierPercent, spell); return multiplierPercent / 100.0f; } bool SpellEffectInfo::HasRadius() const { - return RadiusEntry != NULL; + return RadiusEntry != nullptr; } bool SpellEffectInfo::HasMaxRadius() const { - return MaxRadiusEntry != NULL; + return MaxRadiusEntry != nullptr; } float SpellEffectInfo::CalcRadius(Unit* caster, Spell* spell) const @@ -629,7 +633,7 @@ float SpellEffectInfo::CalcRadius(Unit* caster, Spell* spell) const radius += entry->RadiusPerLevel * caster->getLevel(); radius = std::min(radius, entry->RadiusMax); if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(_spellInfo->Id, radius, spell); + modOwner->ApplySpellMod(_spellInfo->Id, SPELLMOD_RADIUS, radius, spell); } return radius; @@ -877,10 +881,10 @@ SpellInfo::SpellInfo(SpellEntry const* spellEntry, SpellEffectEntry const** effe AttributesEx9 = spellEntry->AttributesEx9; AttributesEx10 = spellEntry->AttributesEx10; AttributesCu = 0; - CastTimeEntry = spellEntry->CastingTimeIndex ? sSpellCastTimesStore.LookupEntry(spellEntry->CastingTimeIndex) : NULL; - DurationEntry = spellEntry->DurationIndex ? sSpellDurationStore.LookupEntry(spellEntry->DurationIndex) : NULL; + CastTimeEntry = spellEntry->CastingTimeIndex ? sSpellCastTimesStore.LookupEntry(spellEntry->CastingTimeIndex) : nullptr; + DurationEntry = spellEntry->DurationIndex ? sSpellDurationStore.LookupEntry(spellEntry->DurationIndex) : nullptr; PowerType = spellEntry->powerType; - RangeEntry = spellEntry->rangeIndex ? sSpellRangeStore.LookupEntry(spellEntry->rangeIndex) : NULL; + RangeEntry = spellEntry->rangeIndex ? sSpellRangeStore.LookupEntry(spellEntry->rangeIndex) : nullptr; Speed = spellEntry->speed; for (uint8 i = 0; i < 2; ++i) @@ -949,7 +953,7 @@ SpellInfo::SpellInfo(SpellEntry const* spellEntry, SpellEffectEntry const** effe // SpellCategoriesEntry SpellCategoriesEntry const* _categorie = GetSpellCategories(); - CategoryEntry = _categorie ? sSpellCategoryStore.LookupEntry(_categorie->Category) : NULL; + CategoryEntry = _categorie ? sSpellCategoryStore.LookupEntry(_categorie->Category) : nullptr; Dispel = _categorie ? _categorie->Dispel : 0; Mechanic = _categorie ? _categorie->Mechanic : 0; StartRecoveryCategory = _categorie ? _categorie->StartRecoveryCategory : 0; @@ -1026,7 +1030,7 @@ SpellInfo::SpellInfo(SpellEntry const* spellEntry, SpellEffectEntry const** effe for (uint8 i = 0; i < 2; ++i) Totem[i] = _totem ? _totem->Totem[i] : 0; - ChainEntry = NULL; + ChainEntry = nullptr; ExplicitTargetMask = 0; _spellSpecific = SPELL_SPECIFIC_NORMAL; @@ -1586,7 +1590,7 @@ SpellCastResult SpellInfo::CheckShapeshift(uint32 form) const return SPELL_CAST_OK; bool actAsShifted = false; - SpellShapeshiftFormEntry const* shapeInfo = NULL; + SpellShapeshiftFormEntry const* shapeInfo = nullptr; if (form > 0) { shapeInfo = sSpellShapeshiftFormStore.LookupEntry(form); @@ -1811,10 +1815,10 @@ SpellCastResult SpellInfo::CheckTarget(Unit const* caster, WorldObject const* ta if (HasAttribute(SPELL_ATTR0_CU_PICKPOCKET)) { - if (unitTarget->GetTypeId() == TYPEID_PLAYER) - return SPELL_FAILED_BAD_TARGETS; - else if ((unitTarget->GetCreatureTypeMask() & CREATURE_TYPEMASK_HUMANOID_OR_UNDEAD) == 0) - return SPELL_FAILED_TARGET_NO_POCKETS; + if (unitTarget->GetTypeId() == TYPEID_PLAYER) + return SPELL_FAILED_BAD_TARGETS; + else if ((unitTarget->GetCreatureTypeMask() & CREATURE_TYPEMASK_HUMANOID_OR_UNDEAD) == 0) + return SPELL_FAILED_TARGET_NO_POCKETS; } // Not allow disarm unarmed player @@ -1850,14 +1854,14 @@ SpellCastResult SpellInfo::CheckTarget(Unit const* caster, WorldObject const* ta // corpseOwner and unit specific target checks if (HasAttribute(SPELL_ATTR3_ONLY_TARGET_PLAYERS) && unitTarget->GetTypeId() != TYPEID_PLAYER) - return SPELL_FAILED_TARGET_NOT_PLAYER; + return SPELL_FAILED_TARGET_NOT_PLAYER; if (!IsAllowingDeadTarget() && !unitTarget->IsAlive()) - return SPELL_FAILED_TARGETS_DEAD; + return SPELL_FAILED_TARGETS_DEAD; // check this flag only for implicit targets (chain and area), allow to explicitly target units for spells like Shield of Righteousness if (implicit && HasAttribute(SPELL_ATTR6_CANT_TARGET_CROWD_CONTROLLED) && !unitTarget->CanFreeMove()) - return SPELL_FAILED_BAD_TARGETS; + return SPELL_FAILED_BAD_TARGETS; // checked in Unit::IsValidAttack/AssistTarget, shouldn't be checked for ENTRY targets //if (!HasAttribute(SPELL_ATTR6_CAN_TARGET_UNTARGETABLE) && target->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE)) @@ -1913,12 +1917,10 @@ SpellCastResult SpellInfo::CheckTarget(Unit const* caster, WorldObject const* ta if (HasEffect(SPELL_EFFECT_SELF_RESURRECT) || HasEffect(SPELL_EFFECT_RESURRECT) || HasEffect(SPELL_EFFECT_RESURRECT_NEW)) return SPELL_FAILED_TARGET_CANNOT_BE_RESURRECTED; - if (HasAttribute(SPELL_ATTR8_BATTLE_RESURRECTION)) - if (Map* map = caster->GetMap()) - if (InstanceMap* iMap = map->ToInstanceMap()) - if (InstanceScript* instance = iMap->GetInstanceScript()) - if (instance->GetCombatResurrectionCharges() == 0 && instance->IsEncounterInProgress()) - return SPELL_FAILED_TARGET_CANNOT_BE_RESURRECTED; + if (HasAttribute(SPELL_ATTR8_BATTLE_RESURRECTION)) + if (InstanceScript* instance = caster->GetInstanceScript()) + if (instance->GetCombatResurrectionCharges() == 0 && instance->IsEncounterInProgress()) + return SPELL_FAILED_TARGET_CANNOT_BE_RESURRECTED; return SPELL_CAST_OK; } @@ -3197,7 +3199,7 @@ float SpellInfo::GetMaxRange(bool positive, Unit* caster, Spell* spell) const range = RangeEntry->maxRangeHostile; if (caster) if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(Id, range, spell); + modOwner->ApplySpellMod(Id, SPELLMOD_RANGE, range, spell); return range; } @@ -3215,7 +3217,7 @@ int32 SpellInfo::GetMaxDuration() const return (DurationEntry->Duration[2] == -1) ? -1 : abs(DurationEntry->Duration[2]); } -uint32 SpellInfo::CalcCastTime(uint8 level, Spell* spell /*= NULL*/) const +uint32 SpellInfo::CalcCastTime(uint8 level, Spell* spell /*= nullptr*/) const { int32 castTime = 0; if (!level && spell) @@ -3363,7 +3365,7 @@ int32 SpellInfo::CalcPowerCost(Unit const* caster, SpellSchoolMask schoolMask, S // Apply cost mod by spell if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(Id, powerCost, spell); + modOwner->ApplySpellMod(Id, SPELLMOD_COST, powerCost, spell); if (!caster->IsControlledByPlayer()) { @@ -3393,7 +3395,7 @@ int32 SpellInfo::CalcPowerCost(Unit const* caster, SpellSchoolMask schoolMask, S bool SpellInfo::IsRanked() const { - return ChainEntry != NULL; + return ChainEntry != nullptr; } uint8 SpellInfo::GetRank() const @@ -3412,19 +3414,19 @@ SpellInfo const* SpellInfo::GetFirstRankSpell() const SpellInfo const* SpellInfo::GetLastRankSpell() const { if (!ChainEntry) - return NULL; + return nullptr; return ChainEntry->last; } SpellInfo const* SpellInfo::GetNextRankSpell() const { if (!ChainEntry) - return NULL; + return nullptr; return ChainEntry->next; } SpellInfo const* SpellInfo::GetPrevRankSpell() const { if (!ChainEntry) - return NULL; + return nullptr; return ChainEntry->prev; } @@ -3456,7 +3458,7 @@ SpellInfo const* SpellInfo::GetAuraRankForLevel(uint8 level) const if (!needRankSelection) return this; - for (SpellInfo const* nextSpellInfo = this; nextSpellInfo != NULL; nextSpellInfo = nextSpellInfo->GetPrevRankSpell()) + for (SpellInfo const* nextSpellInfo = this; nextSpellInfo != nullptr; nextSpellInfo = nextSpellInfo->GetPrevRankSpell()) { // if found appropriate level if (uint32(level + 10) >= nextSpellInfo->SpellLevel) @@ -3466,7 +3468,7 @@ SpellInfo const* SpellInfo::GetAuraRankForLevel(uint8 level) const } // not found - return NULL; + return nullptr; } bool SpellInfo::IsRankOf(SpellInfo const* spellInfo) const @@ -3812,77 +3814,77 @@ bool SpellInfo::_IsPositiveTarget(uint32 targetA, uint32 targetB) SpellTargetRestrictionsEntry const* SpellInfo::GetSpellTargetRestrictions() const { - return SpellTargetRestrictionsId ? sSpellTargetRestrictionsStore.LookupEntry(SpellTargetRestrictionsId) : NULL; + return SpellTargetRestrictionsId ? sSpellTargetRestrictionsStore.LookupEntry(SpellTargetRestrictionsId) : nullptr; } SpellEquippedItemsEntry const* SpellInfo::GetSpellEquippedItems() const { - return SpellEquippedItemsId ? sSpellEquippedItemsStore.LookupEntry(SpellEquippedItemsId) : NULL; + return SpellEquippedItemsId ? sSpellEquippedItemsStore.LookupEntry(SpellEquippedItemsId) : nullptr; } SpellInterruptsEntry const* SpellInfo::GetSpellInterrupts() const { - return SpellInterruptsId ? sSpellInterruptsStore.LookupEntry(SpellInterruptsId) : NULL; + return SpellInterruptsId ? sSpellInterruptsStore.LookupEntry(SpellInterruptsId) : nullptr; } SpellLevelsEntry const* SpellInfo::GetSpellLevels() const { - return SpellLevelsId ? sSpellLevelsStore.LookupEntry(SpellLevelsId) : NULL; + return SpellLevelsId ? sSpellLevelsStore.LookupEntry(SpellLevelsId) : nullptr; } SpellPowerEntry const* SpellInfo::GetSpellPower() const { - return SpellPowerId ? sSpellPowerStore.LookupEntry(SpellPowerId) : NULL; + return SpellPowerId ? sSpellPowerStore.LookupEntry(SpellPowerId) : nullptr; } SpellReagentsEntry const* SpellInfo::GetSpellReagents() const { - return SpellReagentsId ? sSpellReagentsStore.LookupEntry(SpellReagentsId) : NULL; + return SpellReagentsId ? sSpellReagentsStore.LookupEntry(SpellReagentsId) : nullptr; } SpellScalingEntry const* SpellInfo::GetSpellScaling() const { - return SpellScalingId ? sSpellScalingStore.LookupEntry(SpellScalingId) : NULL; + return SpellScalingId ? sSpellScalingStore.LookupEntry(SpellScalingId) : nullptr; } SpellShapeshiftEntry const* SpellInfo::GetSpellShapeshift() const { - return SpellShapeshiftId ? sSpellShapeshiftStore.LookupEntry(SpellShapeshiftId) : NULL; + return SpellShapeshiftId ? sSpellShapeshiftStore.LookupEntry(SpellShapeshiftId) : nullptr; } SpellTotemsEntry const* SpellInfo::GetSpellTotems() const { - return SpellTotemsId ? sSpellTotemsStore.LookupEntry(SpellTotemsId) : NULL; + return SpellTotemsId ? sSpellTotemsStore.LookupEntry(SpellTotemsId) : nullptr; } SpellAuraOptionsEntry const* SpellInfo::GetSpellAuraOptions() const { - return SpellAuraOptionsId ? sSpellAuraOptionsStore.LookupEntry(SpellAuraOptionsId) : NULL; + return SpellAuraOptionsId ? sSpellAuraOptionsStore.LookupEntry(SpellAuraOptionsId) : nullptr; } SpellAuraRestrictionsEntry const* SpellInfo::GetSpellAuraRestrictions() const { - return SpellAuraRestrictionsId ? sSpellAuraRestrictionsStore.LookupEntry(SpellAuraRestrictionsId) : NULL; + return SpellAuraRestrictionsId ? sSpellAuraRestrictionsStore.LookupEntry(SpellAuraRestrictionsId) : nullptr; } SpellCastingRequirementsEntry const* SpellInfo::GetSpellCastingRequirements() const { - return SpellCastingRequirementsId ? sSpellCastingRequirementsStore.LookupEntry(SpellCastingRequirementsId) : NULL; + return SpellCastingRequirementsId ? sSpellCastingRequirementsStore.LookupEntry(SpellCastingRequirementsId) : nullptr; } SpellCategoriesEntry const* SpellInfo::GetSpellCategories() const { - return SpellCategoriesId ? sSpellCategoriesStore.LookupEntry(SpellCategoriesId) : NULL; + return SpellCategoriesId ? sSpellCategoriesStore.LookupEntry(SpellCategoriesId) : nullptr; } SpellClassOptionsEntry const* SpellInfo::GetSpellClassOptions() const { - return SpellClassOptionsId ? sSpellClassOptionsStore.LookupEntry(SpellClassOptionsId) : NULL; + return SpellClassOptionsId ? sSpellClassOptionsStore.LookupEntry(SpellClassOptionsId) : nullptr; } SpellCooldownsEntry const* SpellInfo::GetSpellCooldowns() const { - return SpellCooldownsId ? sSpellCooldownsStore.LookupEntry(SpellCooldownsId) : NULL; + return SpellCooldownsId ? sSpellCooldownsStore.LookupEntry(SpellCooldownsId) : nullptr; } void SpellInfo::_UnloadImplicitTargetConditionLists() @@ -3896,7 +3898,7 @@ void SpellInfo::_UnloadImplicitTargetConditionLists() for (uint8 j = i; j < MAX_SPELL_EFFECTS; ++j) { if (Effects[j].ImplicitTargetConditions == cur) - Effects[j].ImplicitTargetConditions = NULL; + Effects[j].ImplicitTargetConditions = nullptr; } delete cur; } diff --git a/src/server/game/Spells/SpellInfo.h b/src/server/game/Spells/SpellInfo.h index 58bb9979bc6..8746ccceb2f 100644 --- a/src/server/game/Spells/SpellInfo.h +++ b/src/server/game/Spells/SpellInfo.h @@ -42,7 +42,7 @@ struct SpellEntry; struct SpellCastTimesEntry; struct Condition; -enum SpellCastTargetFlags +enum SpellCastTargetFlags : uint32 { TARGET_FLAG_NONE = 0x00000000, TARGET_FLAG_UNUSED_1 = 0x00000001, // not used @@ -94,7 +94,7 @@ enum SpellTargetReferenceTypes TARGET_REFERENCE_TYPE_DEST }; -enum SpellTargetObjectTypes +enum SpellTargetObjectTypes : uint8 { TARGET_OBJECT_TYPE_NONE = 0, TARGET_OBJECT_TYPE_SRC, @@ -110,7 +110,7 @@ enum SpellTargetObjectTypes TARGET_OBJECT_TYPE_CORPSE_ALLY }; -enum SpellTargetCheckTypes +enum SpellTargetCheckTypes : uint8 { TARGET_CHECK_DEFAULT, TARGET_CHECK_ENTRY, @@ -261,10 +261,10 @@ public: float DeltaScalingMultiplier; float ComboScalingMultiplier; - SpellEffectInfo() : _spellInfo(NULL), _effIndex(0), Effect(0), ApplyAuraName(0), Amplitude(0), DieSides(0), + SpellEffectInfo() : _spellInfo(nullptr), _effIndex(0), Effect(0), ApplyAuraName(0), Amplitude(0), DieSides(0), RealPointsPerLevel(0), BasePoints(0), PointsPerComboPoint(0), ValueMultiplier(0), DamageMultiplier(0), - BonusMultiplier(0), MiscValue(0), MiscValueB(0), Mechanic(MECHANIC_NONE), RadiusEntry(NULL), ChainTarget(0), - ItemType(0), TriggerSpell(0), ImplicitTargetConditions(NULL) {} + BonusMultiplier(0), MiscValue(0), MiscValueB(0), Mechanic(MECHANIC_NONE), RadiusEntry(nullptr), ChainTarget(0), + ItemType(0), TriggerSpell(0), ImplicitTargetConditions(nullptr) {} SpellEffectInfo(SpellEntry const* spellEntry, SpellInfo const* spellInfo, uint8 effIndex, SpellEffectEntry const* effect); bool IsEffect() const; @@ -277,14 +277,14 @@ public: bool IsFarDestTargetEffect() const; bool IsUnitOwnedAuraEffect() const; - int32 CalcValue(Unit const* caster = NULL, int32 const* basePoints = NULL, Unit const* target = NULL) const; + int32 CalcValue(Unit const* caster = nullptr, int32 const* basePoints = nullptr, Unit const* target = nullptr) const; int32 CalcBaseValue(int32 value) const; - float CalcValueMultiplier(Unit* caster, Spell* spell = NULL) const; - float CalcDamageMultiplier(Unit* caster, Spell* spell = NULL) const; + float CalcValueMultiplier(Unit* caster, Spell* spell = nullptr) const; + float CalcDamageMultiplier(Unit* caster, Spell* spell = nullptr) const; bool HasRadius() const; bool HasMaxRadius() const; - float CalcRadius(Unit* caster = NULL, Spell* = NULL) const; + float CalcRadius(Unit* caster = nullptr, Spell* = nullptr) const; uint32 GetProvidedTargetMask() const; uint32 GetMissingTargetMask(bool srcSet = false, bool destSet = false, uint32 mask = 0) const; @@ -520,9 +520,9 @@ class TC_GAME_API SpellInfo bool IsAuraExclusiveBySpecificPerCasterWith(SpellInfo const* spellInfo) const; SpellCastResult CheckShapeshift(uint32 form) const; - SpellCastResult CheckLocation(uint32 map_id, uint32 zone_id, uint32 area_id, Player const* player = NULL) const; + SpellCastResult CheckLocation(uint32 map_id, uint32 zone_id, uint32 area_id, Player const* player = nullptr) const; SpellCastResult CheckTarget(Unit const* caster, WorldObject const* target, bool implicit = true) const; - SpellCastResult CheckExplicitTarget(Unit const* caster, WorldObject const* target, Item const* itemTarget = NULL) const; + SpellCastResult CheckExplicitTarget(Unit const* caster, WorldObject const* target, Item const* itemTarget = nullptr) const; SpellCastResult CheckVehicle(Unit const* caster) const; bool CheckTargetCreatureType(Unit const* target) const; diff --git a/src/server/game/Spells/SpellMgr.cpp b/src/server/game/Spells/SpellMgr.cpp index 81da7b3e566..83d551af76b 100644 --- a/src/server/game/Spells/SpellMgr.cpp +++ b/src/server/game/Spells/SpellMgr.cpp @@ -17,17 +17,21 @@ */ #include "SpellMgr.h" -#include "SpellInfo.h" -#include "Spell.h" -#include "ObjectMgr.h" -#include "SpellAuraDefines.h" -#include "SharedDefines.h" -#include "DBCStores.h" -#include "Chat.h" -#include "BattlegroundMgr.h" -#include "BattlefieldWG.h" #include "BattlefieldMgr.h" +#include "BattlefieldWG.h" +#include "BattlegroundMgr.h" +#include "Chat.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectMgr.h" #include "Player.h" +#include "SharedDefines.h" +#include "Spell.h" +#include "SpellAuraDefines.h" +#include "SpellInfo.h" #include bool IsPrimaryProfessionSkill(uint32 skill) @@ -199,7 +203,7 @@ uint32 SpellMgr::GetSpellIdForDifficulty(uint32 spellId, Unit const* caster) con if (difficultyEntry->SpellID[mode] <= 0 && mode > DUNGEON_DIFFICULTY_HEROIC) { - TC_LOG_DEBUG("spells", "SpellMgr::GetSpellIdForDifficulty: spell %u mode %u spell is NULL, using mode %u", spellId, mode, mode - 2); + TC_LOG_DEBUG("spells", "SpellMgr::GetSpellIdForDifficulty: spell %u mode %u spell is nullptr, using mode %u", spellId, mode, mode - 2); mode -= 2; } @@ -216,7 +220,7 @@ uint32 SpellMgr::GetSpellIdForDifficulty(uint32 spellId, Unit const* caster) con SpellInfo const* SpellMgr::GetSpellForDifficultyFromSpell(SpellInfo const* spell, Unit const* caster) const { if (!spell) - return NULL; + return nullptr; uint32 newSpellId = GetSpellIdForDifficulty(spell->Id, caster); SpellInfo const* newSpell = GetSpellInfo(newSpellId); @@ -234,7 +238,7 @@ SpellChainNode const* SpellMgr::GetSpellChainNode(uint32 spell_id) const { SpellChainMap::const_iterator itr = mSpellChains.find(spell_id); if (itr == mSpellChains.end()) - return NULL; + return nullptr; return &itr->second; } @@ -320,7 +324,7 @@ SpellLearnSkillNode const* SpellMgr::GetSpellLearnSkill(uint32 spell_id) const if (itr != mSpellLearnSkills.end()) return &itr->second; else - return NULL; + return nullptr; } SpellLearnSpellMapBounds SpellMgr::GetSpellLearnSpellMapBounds(uint32 spell_id) const @@ -347,7 +351,7 @@ SpellTargetPosition const* SpellMgr::GetSpellTargetPosition(uint32 spell_id, Spe SpellTargetPositionMap::const_iterator itr = mSpellTargetPositions.find(std::make_pair(spell_id, effIndex)); if (itr != mSpellTargetPositions.end()) return &itr->second; - return NULL; + return nullptr; } SpellSpellGroupMapBounds SpellMgr::GetSpellSpellGroupMapBounds(uint32 spell_id) const @@ -494,7 +498,7 @@ SpellProcEntry const* SpellMgr::GetSpellProcEntry(uint32 spellId) const SpellProcMap::const_iterator itr = mSpellProcMap.find(spellId); if (itr != mSpellProcMap.end()) return &itr->second; - return NULL; + return nullptr; } bool SpellMgr::CanSpellTriggerProcOnEvent(SpellProcEntry const& procEntry, ProcEventInfo& eventInfo) @@ -592,7 +596,7 @@ SpellBonusEntry const* SpellMgr::GetSpellBonusData(uint32 spellId) const if (itr2 != mSpellBonusMap.end()) return &itr2->second; } - return NULL; + return nullptr; } SpellThreatEntry const* SpellMgr::GetSpellThreatEntry(uint32 spellID) const @@ -607,7 +611,7 @@ SpellThreatEntry const* SpellMgr::GetSpellThreatEntry(uint32 spellID) const if (itr != mSpellThreatMap.end()) return &itr->second; } - return NULL; + return nullptr; } SkillLineAbilityMapBounds SpellMgr::GetSkillLineAbilityMapBounds(uint32 spell_id) const @@ -621,7 +625,7 @@ PetAura const* SpellMgr::GetPetAura(uint32 spell_id, uint8 eff) const if (itr != mSpellPetAuraMap.end()) return &itr->second; else - return NULL; + return nullptr; } SpellEnchantProcEntry const* SpellMgr::GetSpellEnchantProcEvent(uint32 enchId) const @@ -629,7 +633,7 @@ SpellEnchantProcEntry const* SpellMgr::GetSpellEnchantProcEvent(uint32 enchId) c SpellEnchantProcEventMap::const_iterator itr = mSpellEnchantProcEventMap.find(enchId); if (itr != mSpellEnchantProcEventMap.end()) return &itr->second; - return NULL; + return nullptr; } bool SpellMgr::IsArenaAllowedEnchancment(uint32 ench_id) const @@ -640,7 +644,7 @@ bool SpellMgr::IsArenaAllowedEnchancment(uint32 ench_id) const const std::vector* SpellMgr::GetSpellLinked(int32 spell_id) const { SpellLinkedMap::const_iterator itr = mSpellLinkedMap.find(spell_id); - return itr != mSpellLinkedMap.end() ? &(itr->second) : NULL; + return itr != mSpellLinkedMap.end() ? &(itr->second) : nullptr; } PetLevelupSpellSet const* SpellMgr::GetPetLevelupSpellList(uint32 petFamily) const @@ -649,7 +653,7 @@ PetLevelupSpellSet const* SpellMgr::GetPetLevelupSpellList(uint32 petFamily) con if (itr != mPetLevelupSpellMap.end()) return &itr->second; else - return NULL; + return nullptr; } PetDefaultSpellsEntry const* SpellMgr::GetPetDefaultSpellsEntry(int32 id) const @@ -657,7 +661,7 @@ PetDefaultSpellsEntry const* SpellMgr::GetPetDefaultSpellsEntry(int32 id) const PetDefaultSpellsMap::const_iterator itr = mPetDefaultSpellsMap.find(id); if (itr != mPetDefaultSpellsMap.end()) return &itr->second; - return NULL; + return nullptr; } SpellAreaMapBounds SpellMgr::GetSpellAreaMapBounds(uint32 spell_id) const @@ -783,7 +787,7 @@ bool SpellArea::IsFitToRequirements(Player const* player, uint32 newZone, uint32 void SpellMgr::UnloadSpellInfoChains() { for (SpellChainMap::iterator itr = mSpellChains.begin(); itr != mSpellChains.end(); ++itr) - mSpellInfoMap[itr->first]->ChainEntry = NULL; + mSpellInfoMap[itr->first]->ChainEntry = nullptr; mSpellChains.clear(); } @@ -799,7 +803,7 @@ void SpellMgr::LoadSpellTalentRanks() if (!talentInfo) continue; - SpellInfo const* lastSpell = NULL; + SpellInfo const* lastSpell = nullptr; for (uint8 rank = MAX_TALENT_RANK - 1; rank > 0; --rank) { if (talentInfo->RankID[rank]) @@ -819,7 +823,7 @@ void SpellMgr::LoadSpellTalentRanks() continue; } - SpellInfo const* prevSpell = NULL; + SpellInfo const* prevSpell = nullptr; for (uint8 rank = 0; rank < MAX_TALENT_RANK; ++rank) { uint32 spellId = talentInfo->RankID[rank]; @@ -839,7 +843,7 @@ void SpellMgr::LoadSpellTalentRanks() node.rank = rank + 1; node.prev = prevSpell; - node.next = node.rank < MAX_TALENT_RANK ? GetSpellInfo(talentInfo->RankID[node.rank]) : NULL; + node.next = node.rank < MAX_TALENT_RANK ? GetSpellInfo(talentInfo->RankID[node.rank]) : nullptr; mSpellChains[spellId] = node; mSpellInfoMap[spellId]->ChainEntry = &mSpellChains[spellId]; @@ -952,7 +956,7 @@ void SpellMgr::LoadSpellRanks() if (itr == rankChain.end()) { - mSpellChains[addedSpell].next = NULL; + mSpellChains[addedSpell].next = nullptr; break; } else @@ -2302,7 +2306,7 @@ bool LoadPetDefaultSpells_helper(CreatureTemplate const* cInfo, PetDefaultSpells return false; // remove duplicates with levelupSpells if any - if (PetLevelupSpellSet const* levelupSpells = cInfo->family ? sSpellMgr->GetPetLevelupSpellList(cInfo->family) : NULL) + if (PetLevelupSpellSet const* levelupSpells = cInfo->family ? sSpellMgr->GetPetLevelupSpellList(cInfo->family) : nullptr) { for (uint8 j = 0; j < MAX_CREATURE_SPELL_DATA_SLOT; ++j) { @@ -2608,40 +2612,25 @@ void SpellMgr::LoadSpellAreas() TC_LOG_INFO("server.loading", ">> Loaded %u spell area requirements in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); } -// Temporary structure to hold spell effect entries for faster loading -struct SpellEffectArray -{ - SpellEffectArray() - { - effects[0] = NULL; - effects[1] = NULL; - effects[2] = NULL; - } - - SpellEffectEntry const* effects[MAX_SPELL_EFFECTS]; -}; - void SpellMgr::LoadSpellInfoStore() { uint32 oldMSTime = getMSTime(); UnloadSpellInfoStore(); - mSpellInfoMap.resize(sSpellStore.GetNumRows(), NULL); + mSpellInfoMap.resize(sSpellStore.GetNumRows(), nullptr); - std::map effectsBySpell; - - for (uint32 i = 0; i < sSpellEffectStore.GetNumRows(); ++i) + // Temporary structure to hold spell effect entries for faster loading + struct SpellEffectArray { - SpellEffectEntry const* effect = sSpellEffectStore.LookupEntry(i); - if (!effect) - continue; + SpellEffectEntry const* effects[MAX_SPELL_EFFECTS] = { }; + }; + std::unordered_map effectsBySpell; + for (SpellEffectEntry const* effect : sSpellEffectStore) effectsBySpell[effect->EffectSpellId].effects[effect->EffectIndex] = effect; - } - for (uint32 i = 0; i < sSpellStore.GetNumRows(); ++i) - if (SpellEntry const* spellEntry = sSpellStore.LookupEntry(i)) - mSpellInfoMap[i] = new SpellInfo(spellEntry, effectsBySpell[i].effects); + for (SpellEntry const* spellEntry : sSpellStore) + mSpellInfoMap[spellEntry->Id] = new SpellInfo(spellEntry, effectsBySpell[spellEntry->Id].effects); for (uint32 spellIndex = 0; spellIndex < GetSpellInfoStoreSize(); ++spellIndex) { @@ -2681,7 +2670,7 @@ void SpellMgr::LoadSpellInfoCustomAttributes() { uint32 oldMSTime = getMSTime(); uint32 oldMSTime2 = oldMSTime; - SpellInfo* spellInfo = NULL; + SpellInfo* spellInfo = nullptr; QueryResult result = WorldDatabase.Query("SELECT entry, attributes FROM spell_custom_attr"); diff --git a/src/server/game/Spells/SpellMgr.h b/src/server/game/Spells/SpellMgr.h index 4bfbb2474bb..c038a5dd80c 100644 --- a/src/server/game/Spells/SpellMgr.h +++ b/src/server/game/Spells/SpellMgr.h @@ -22,7 +22,7 @@ // For static or at-server-startup loaded spell data #include "Define.h" -#include "DBCStructure.h" +#include "Duration.h" #include "SharedDefines.h" #include "Util.h" @@ -30,13 +30,13 @@ #include #include #include +#include class SpellInfo; class Player; class Unit; class ProcEventInfo; struct SkillLineAbilityEntry; -enum AuraType; // only used in code enum SpellCategories @@ -579,7 +579,7 @@ class TC_GAME_API SpellMgr static SpellMgr* instance(); // Spell correctness for client using - static bool IsSpellValid(SpellInfo const* spellInfo, Player* player = NULL, bool msg = true); + static bool IsSpellValid(SpellInfo const* spellInfo, Player* player = nullptr, bool msg = true); // Spell difficulty uint32 GetSpellDifficultyId(uint32 spellId) const; @@ -655,7 +655,7 @@ class TC_GAME_API SpellMgr SpellAreaForQuestAreaMapBounds GetSpellAreaForQuestAreaMapBounds(uint32 area_id, uint32 quest_id) const; // SpellInfo object management - SpellInfo const* GetSpellInfo(uint32 spellId) const { return spellId < GetSpellInfoStoreSize() ? mSpellInfoMap[spellId] : NULL; } + SpellInfo const* GetSpellInfo(uint32 spellId) const { return spellId < GetSpellInfoStoreSize() ? mSpellInfoMap[spellId] : nullptr; } // Use this only with 100% valid spellIds SpellInfo const* AssertSpellInfo(uint32 spellId) const { @@ -667,7 +667,7 @@ class TC_GAME_API SpellMgr uint32 GetSpellInfoStoreSize() const { return mSpellInfoMap.size(); } private: - SpellInfo* _GetSpellInfo(uint32 spellId) { return spellId < GetSpellInfoStoreSize() ? mSpellInfoMap[spellId] : NULL; } + SpellInfo* _GetSpellInfo(uint32 spellId) { return spellId < GetSpellInfoStoreSize() ? mSpellInfoMap[spellId] : nullptr; } // Modifiers public: diff --git a/src/server/game/Spells/SpellScript.cpp b/src/server/game/Spells/SpellScript.cpp index eada49fb873..e75a758d0a3 100644 --- a/src/server/game/Spells/SpellScript.cpp +++ b/src/server/game/Spells/SpellScript.cpp @@ -15,12 +15,13 @@ * with this program. If not, see . */ -#include "Spell.h" +#include "SpellScript.h" +#include "Log.h" #include "ScriptMgr.h" +#include "Spell.h" #include "SpellAuras.h" #include "SpellMgr.h" -#include "SpellScript.h" -#include "SpellMgr.h" +#include #include bool _SpellScript::_Validate(SpellInfo const* entry) @@ -33,18 +34,20 @@ bool _SpellScript::_Validate(SpellInfo const* entry) return true; } -bool _SpellScript::ValidateSpellInfo(std::vector const& spellIds) +bool _SpellScript::_ValidateSpellInfo(uint32 const* begin, uint32 const* end) { - for (uint32 spellId : spellIds) + bool allValid = true; + while (begin != end) { - if (!sSpellMgr->GetSpellInfo(spellId)) + if (!sSpellMgr->GetSpellInfo(*begin)) { - TC_LOG_ERROR("scripts.spells", "_SpellScript::ValidateSpellInfo: Spell %u does not exist.", spellId); - return false; + TC_LOG_ERROR("scripts.spells", "_SpellScript::ValidateSpellInfo: Spell %u does not exist.", *begin); + allValid = false; } - } - return true; + ++begin; + } + return allValid; } void _SpellScript::_Register() @@ -438,7 +441,7 @@ WorldLocation const* SpellScript::GetExplTargetDest() const { if (m_spell->m_targets.HasDst()) return m_spell->m_targets.GetDstPos(); - return NULL; + return nullptr; } void SpellScript::SetExplTargetDest(WorldLocation& loc) @@ -471,7 +474,7 @@ Unit* SpellScript::GetHitUnit() const if (!IsInTargetHook()) { TC_LOG_ERROR("scripts", "Script: `%s` Spell: `%u`: function SpellScript::GetHitUnit was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); - return NULL; + return nullptr; } return m_spell->unitTarget; } @@ -481,12 +484,12 @@ Creature* SpellScript::GetHitCreature() const if (!IsInTargetHook()) { TC_LOG_ERROR("scripts", "Script: `%s` Spell: `%u`: function SpellScript::GetHitCreature was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); - return NULL; + return nullptr; } if (m_spell->unitTarget) return m_spell->unitTarget->ToCreature(); else - return NULL; + return nullptr; } Player* SpellScript::GetHitPlayer() const @@ -494,12 +497,12 @@ Player* SpellScript::GetHitPlayer() const if (!IsInTargetHook()) { TC_LOG_ERROR("scripts", "Script: `%s` Spell: `%u`: function SpellScript::GetHitPlayer was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); - return NULL; + return nullptr; } if (m_spell->unitTarget) return m_spell->unitTarget->ToPlayer(); else - return NULL; + return nullptr; } Item* SpellScript::GetHitItem() const @@ -507,7 +510,7 @@ Item* SpellScript::GetHitItem() const if (!IsInTargetHook()) { TC_LOG_ERROR("scripts", "Script: `%s` Spell: `%u`: function SpellScript::GetHitItem was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); - return NULL; + return nullptr; } return m_spell->itemTarget; } @@ -517,7 +520,7 @@ GameObject* SpellScript::GetHitGObj() const if (!IsInTargetHook()) { TC_LOG_ERROR("scripts", "Script: `%s` Spell: `%u`: function SpellScript::GetHitGObj was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); - return NULL; + return nullptr; } return m_spell->gameObjTarget; } @@ -527,7 +530,7 @@ WorldLocation* SpellScript::GetHitDest() const if (!IsInEffectHook()) { TC_LOG_ERROR("scripts", "Script: `%s` Spell: `%u`: function SpellScript::GetHitDest was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); - return NULL; + return nullptr; } return m_spell->destTarget; } @@ -577,12 +580,12 @@ Aura* SpellScript::GetHitAura() const if (!IsInTargetHook()) { TC_LOG_ERROR("scripts", "Script: `%s` Spell: `%u`: function SpellScript::GetHitAura was called, but function has no effect in current hook!", m_scriptName->c_str(), m_scriptSpellId); - return NULL; + return nullptr; } if (!m_spell->m_spellAura) - return NULL; + return nullptr; if (m_spell->m_spellAura->IsRemoved()) - return NULL; + return nullptr; return m_spell->m_spellAura; } @@ -957,7 +960,7 @@ void AuraScript::EffectProcHandler::Call(AuraScript* auraScript, AuraEffect cons bool AuraScript::_Load(Aura* aura) { m_aura = aura; - _PrepareScriptCall((AuraScriptHookType)SPELL_SCRIPT_STATE_LOADING, NULL); + _PrepareScriptCall((AuraScriptHookType)SPELL_SCRIPT_STATE_LOADING, nullptr); bool load = Load(); _FinishScriptCall(); return load; @@ -1205,7 +1208,7 @@ Unit* AuraScript::GetTarget() const TC_LOG_ERROR("scripts", "Script: `%s` Spell: `%u` AuraScript::GetTarget called in a hook in which the call won't have effect!", m_scriptName->c_str(), m_scriptSpellId); } - return NULL; + return nullptr; } AuraApplication const* AuraScript::GetTargetApplication() const diff --git a/src/server/game/Spells/SpellScript.h b/src/server/game/Spells/SpellScript.h index 625fd89c6e6..ada9008551c 100644 --- a/src/server/game/Spells/SpellScript.h +++ b/src/server/game/Spells/SpellScript.h @@ -18,27 +18,34 @@ #ifndef __SPELL_SCRIPT_H #define __SPELL_SCRIPT_H -#include "Util.h" +#include "ObjectGuid.h" #include "SharedDefines.h" #include "SpellAuraDefines.h" -#include "Spell.h" -#include "ScriptReloadMgr.h" +#include "Util.h" +#include #include -class Unit; +class Aura; +class AuraApplication; +class AuraEffect; +class Creature; +class DamageInfo; +class DispelInfo; +class DynamicObject; +class GameObject; +class Item; +class ModuleReference; +class Player; +class ProcEventInfo; +class Spell; class SpellInfo; class SpellScript; -class Spell; -class Aura; -class AuraEffect; -struct SpellModifier; -class Creature; -class GameObject; -class DynamicObject; -class Player; -class Item; +class Unit; class WorldLocation; class WorldObject; +struct SpellDestination; +struct SpellModifier; +struct SpellValue; #define SPELL_EFFECT_ANY (uint16)-1 #define SPELL_AURA_ANY (uint16)-1 @@ -61,7 +68,7 @@ class TC_GAME_API _SpellScript virtual bool _Validate(SpellInfo const* entry); public: - _SpellScript() : m_currentScriptState(SPELL_SCRIPT_STATE_NONE), m_scriptName(NULL), m_scriptSpellId(0) {} + _SpellScript() : m_currentScriptState(SPELL_SCRIPT_STATE_NONE), m_scriptName(nullptr), m_scriptSpellId(0) {} virtual ~_SpellScript() { } void _Register(); void _Unload(); @@ -133,7 +140,19 @@ class TC_GAME_API _SpellScript // use for: deallocating memory allocated by script virtual void Unload() { } // Helpers - static bool ValidateSpellInfo(std::vector const& spellIds); + static bool ValidateSpellInfo(std::initializer_list spellIds) + { + return _ValidateSpellInfo(spellIds.begin(), spellIds.end()); + } + + template + static bool ValidateSpellInfo(T const& spellIds) + { + return _ValidateSpellInfo(std::begin(spellIds), std::end(spellIds)); + } + + private: + static bool _ValidateSpellInfo(uint32 const* begin, uint32 const* end); }; // SpellScript interface - enum used for runtime checks of script function calls @@ -368,38 +387,38 @@ class TC_GAME_API SpellScript : public _SpellScript // examples: // -shadowstep - explicit target is the unit you want to go behind of // -chain heal - explicit target is the unit to be healed first - // -holy nova/arcane explosion - explicit target = NULL because target you are selecting doesn't affect how spell targets are selected + // -holy nova/arcane explosion - explicit target = nullptr because target you are selecting doesn't affect how spell targets are selected // you can determine if spell requires explicit targets by dbc columns: // - Targets - mask of explicit target types // - ImplicitTargetXX set to TARGET_XXX_TARGET_YYY, _TARGET_ here means that explicit target is used by the effect, so spell needs one too - // returns: WorldLocation which was selected as a spell destination or NULL + // returns: WorldLocation which was selected as a spell destination or nullptr WorldLocation const* GetExplTargetDest() const; void SetExplTargetDest(WorldLocation& loc); - // returns: WorldObject which was selected as an explicit spell target or NULL if there's no target + // returns: WorldObject which was selected as an explicit spell target or nullptr if there's no target WorldObject* GetExplTargetWorldObject() const; - // returns: Unit which was selected as an explicit spell target or NULL if there's no target + // returns: Unit which was selected as an explicit spell target or nullptr if there's no target Unit* GetExplTargetUnit() const; - // returns: GameObject which was selected as an explicit spell target or NULL if there's no target + // returns: GameObject which was selected as an explicit spell target or nullptr if there's no target GameObject* GetExplTargetGObj() const; - // returns: Item which was selected as an explicit spell target or NULL if there's no target + // returns: Item which was selected as an explicit spell target or nullptr if there's no target Item* GetExplTargetItem() const; // methods useable only during spell hit on target, or during spell launch on target: - // returns: target of current effect if it was Unit otherwise NULL + // returns: target of current effect if it was Unit otherwise nullptr Unit* GetHitUnit() const; - // returns: target of current effect if it was Creature otherwise NULL + // returns: target of current effect if it was Creature otherwise nullptr Creature* GetHitCreature() const; - // returns: target of current effect if it was Player otherwise NULL + // returns: target of current effect if it was Player otherwise nullptr Player* GetHitPlayer() const; - // returns: target of current effect if it was Item otherwise NULL + // returns: target of current effect if it was Item otherwise nullptr Item* GetHitItem() const; - // returns: target of current effect if it was GameObject otherwise NULL + // returns: target of current effect if it was GameObject otherwise nullptr GameObject* GetHitGObj() const; // returns: destination of current effect WorldLocation* GetHitDest() const; @@ -658,11 +677,11 @@ class TC_GAME_API AuraScript : public _SpellScript #define PrepareAuraScript(CLASSNAME) AURASCRIPT_FUNCTION_TYPE_DEFINES(CLASSNAME) AURASCRIPT_FUNCTION_CAST_DEFINES(CLASSNAME) public: - AuraScript() : _SpellScript(), m_aura(NULL), m_auraApplication(NULL), m_defaultActionPrevented(false) + AuraScript() : _SpellScript(), m_aura(nullptr), m_auraApplication(nullptr), m_defaultActionPrevented(false) { } bool _Validate(SpellInfo const* entry) override; bool _Load(Aura* aura); - void _PrepareScriptCall(AuraScriptHookType hookType, AuraApplication const* aurApp = NULL); + void _PrepareScriptCall(AuraScriptHookType hookType, AuraApplication const* aurApp = nullptr); void _FinishScriptCall(); bool _IsDefaultActionPrevented(); private: @@ -834,13 +853,13 @@ class TC_GAME_API AuraScript : public _SpellScript // returns guid of object which cast the aura (m_originalCaster of the Spell class) ObjectGuid GetCasterGUID() const; - // returns unit which cast the aura or NULL if not avalible (caster logged out for example) + // returns unit which cast the aura or nullptr if not avalible (caster logged out for example) Unit* GetCaster() const; // returns object on which aura was cast, target for non-area auras, area aura source for area auras WorldObject* GetOwner() const; - // returns owner if it's unit or unit derived object, NULL otherwise (only for persistent area auras NULL is returned) + // returns owner if it's unit or unit derived object, nullptr otherwise (only for persistent area auras nullptr is returned) Unit* GetUnitOwner() const; - // returns owner if it's dynobj, NULL otherwise + // returns owner if it's dynobj, nullptr otherwise DynamicObject* GetDynobjOwner() const; // removes aura with remove mode (see AuraRemoveMode enum) @@ -885,18 +904,18 @@ class TC_GAME_API AuraScript : public _SpellScript // check if aura has effect of given effindex bool HasEffect(uint8 effIndex) const; - // returns aura effect of given effect index or NULL + // returns aura effect of given effect index or nullptr AuraEffect* GetEffect(uint8 effIndex) const; // check if aura has effect of given aura type bool HasEffectType(AuraType type) const; // AuraScript interface - functions which are redirecting to AuraApplication class - // Do not call these in hooks in which AuraApplication is not avalible, otherwise result will differ from expected (the functions will return NULL) + // Do not call these in hooks in which AuraApplication is not avalible, otherwise result will differ from expected (the functions will return nullptr) // returns currently processed target of an aura - // Return value does not need to be NULL-checked, the only situation this will (always) - // return NULL is when the call happens in an unsupported hook, in other cases, it is always valid + // Return value does not need to be nullptr-checked, the only situation this will (always) + // return nullptr is when the call happens in an unsupported hook, in other cases, it is always valid Unit* GetTarget() const; // returns AuraApplication object of currently processed target AuraApplication const* GetTargetApplication() const; diff --git a/src/server/game/Texts/CreatureTextMgr.cpp b/src/server/game/Texts/CreatureTextMgr.cpp index 6178da676fb..4bbfbed201e 100644 --- a/src/server/game/Texts/CreatureTextMgr.cpp +++ b/src/server/game/Texts/CreatureTextMgr.cpp @@ -15,15 +15,17 @@ * with this program. If not, see . */ -#include "Common.h" -#include "DatabaseEnv.h" -#include "ObjectMgr.h" -#include "Cell.h" +#include "CreatureTextMgr.h" +#include "CreatureTextMgrImpl.h" #include "CellImpl.h" #include "Chat.h" -#include "GridNotifiers.h" +#include "Common.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "GridNotifiersImpl.h" -#include "CreatureTextMgr.h" +#include "Log.h" +#include "ObjectMgr.h" +#include "World.h" class CreatureTextBuilder { @@ -224,7 +226,7 @@ uint32 CreatureTextMgr::SendChat(Creature* source, uint8 textGroup, WorldObject } CreatureTextGroup const& textGroupContainer = itr->second; //has all texts in the group - CreatureTextRepeatIds repeatGroup = GetRepeatGroup(source, textGroup);//has all textIDs from the group that were already said + CreatureTextRepeatIds repeatGroup = source->GetTextRepeatGroup(textGroup);//has all textIDs from the group that were already said CreatureTextGroup tempGroup;//will use this to talk after sorting repeatGroup for (CreatureTextGroup::const_iterator giter = textGroupContainer.begin(); giter != textGroupContainer.end(); ++giter) @@ -275,7 +277,7 @@ uint32 CreatureTextMgr::SendChat(Creature* source, uint8 textGroup, WorldObject SendChatPacket(finalSource, builder, finalType, whisperTarget, range, team, gmOnly); } - SetRepeatId(source, textGroup, iter->id); + source->SetTextRepeatId(textGroup, iter->id); return iter->duration; } @@ -333,7 +335,7 @@ void CreatureTextMgr::SendNonChatPacket(WorldObject* source, WorldPacket* data, if (!whisperTarget || whisperTarget->GetTypeId() != TYPEID_PLAYER) return; - whisperTarget->ToPlayer()->GetSession()->SendPacket(data); + whisperTarget->ToPlayer()->SendDirectMessage(data); return; } break; @@ -350,7 +352,7 @@ void CreatureTextMgr::SendNonChatPacket(WorldObject* source, WorldPacket* data, Map::PlayerList const& players = source->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) if (itr->GetSource()->GetAreaId() == areaId && (!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster())) - itr->GetSource()->GetSession()->SendPacket(data); + itr->GetSource()->SendDirectMessage(data); return; } case TEXT_RANGE_ZONE: @@ -359,7 +361,7 @@ void CreatureTextMgr::SendNonChatPacket(WorldObject* source, WorldPacket* data, Map::PlayerList const& players = source->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) if (itr->GetSource()->GetZoneId() == zoneId && (!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster())) - itr->GetSource()->GetSession()->SendPacket(data); + itr->GetSource()->SendDirectMessage(data); return; } case TEXT_RANGE_MAP: @@ -367,7 +369,7 @@ void CreatureTextMgr::SendNonChatPacket(WorldObject* source, WorldPacket* data, Map::PlayerList const& players = source->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) if ((!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster())) - itr->GetSource()->GetSession()->SendPacket(data); + itr->GetSource()->SendDirectMessage(data); return; } case TEXT_RANGE_WORLD: @@ -375,8 +377,8 @@ void CreatureTextMgr::SendNonChatPacket(WorldObject* source, WorldPacket* data, SessionMap const& smap = sWorld->GetAllSessions(); for (SessionMap::const_iterator iter = smap.begin(); iter != smap.end(); ++iter) if (Player* player = iter->second->GetPlayer()) - if (player->GetSession() && (!team || Team(player->GetTeam()) == team) && (!gmOnly || player->IsGameMaster())) - player->GetSession()->SendPacket(data); + if ((!team || Team(player->GetTeam()) == team) && (!gmOnly || player->IsGameMaster())) + player->SendDirectMessage(data); return; } case TEXT_RANGE_NORMAL: @@ -396,21 +398,6 @@ void CreatureTextMgr::SendEmote(Unit* source, uint32 emote) source->HandleEmoteCommand(emote); } -void CreatureTextMgr::SetRepeatId(Creature* source, uint8 textGroup, uint8 id) -{ - if (!source) - return; - - source->SetTextRepeatId(textGroup, id); -} - -CreatureTextRepeatIds CreatureTextMgr::GetRepeatGroup(Creature* source, uint8 textGroup) -{ - ASSERT(source);//should never happen - - return source->GetTextRepeatGroup(textGroup); -} - bool CreatureTextMgr::TextExist(uint32 sourceEntry, uint8 textGroup) { if (!sourceEntry) diff --git a/src/server/game/Texts/CreatureTextMgr.h b/src/server/game/Texts/CreatureTextMgr.h index 85a0b895103..a0077ea792e 100644 --- a/src/server/game/Texts/CreatureTextMgr.h +++ b/src/server/game/Texts/CreatureTextMgr.h @@ -18,12 +18,17 @@ #ifndef TRINITY_CREATURE_TEXT_MGR_H #define TRINITY_CREATURE_TEXT_MGR_H -#include "Creature.h" -#include "GridNotifiers.h" -#include "ObjectAccessor.h" +#include "Common.h" #include "SharedDefines.h" -#include "Opcodes.h" -#include "Group.h" +#include +#include +#include + +class Creature; +class Player; +class Unit; +class WorldObject; +class WorldPacket; enum CreatureTextRange { @@ -52,7 +57,7 @@ struct CreatureTextEntry struct CreatureTextLocale { - StringVector Text; + std::vector Text; }; struct CreatureTextId @@ -61,7 +66,7 @@ struct CreatureTextId bool operator<(CreatureTextId const& right) const { - return memcmp(this, &right, sizeof(CreatureTextId)) < 0; + return std::tie(entry, textGroup, textId) < std::tie(right.entry, right.textGroup, right.textId); } uint32 entry; @@ -86,7 +91,7 @@ class TC_GAME_API CreatureTextMgr void LoadCreatureTexts(); void LoadCreatureTextLocales(); - CreatureTextMap const& GetTextMap() const { return mTextMap; } + CreatureTextMap const& GetTextMap() const { return mTextMap; } void SendSound(Creature* source, uint32 sound, ChatMsg msgType, WorldObject const* whisperTarget, CreatureTextRange range, Team team, bool gmOnly); void SendEmote(Unit* source, uint32 emote); @@ -96,12 +101,10 @@ class TC_GAME_API CreatureTextMgr bool TextExist(uint32 sourceEntry, uint8 textGroup); std::string GetLocalizedChatString(uint32 entry, uint8 gender, uint8 textGroup, uint32 id, LocaleConstant locale) const; - template void SendChatPacket(WorldObject* source, Builder const& builder, ChatMsg msgType, WorldObject const* whisperTarget = nullptr, CreatureTextRange range = TEXT_RANGE_NORMAL, Team team = TEAM_OTHER, bool gmOnly = false) const; + template + void SendChatPacket(WorldObject* source, Builder const& builder, ChatMsg msgType, WorldObject const* whisperTarget = nullptr, CreatureTextRange range = TEXT_RANGE_NORMAL, Team team = TEAM_OTHER, bool gmOnly = false) const; private: - CreatureTextRepeatIds GetRepeatGroup(Creature* source, uint8 textGroup); - void SetRepeatId(Creature* source, uint8 textGroup, uint8 id); - void SendNonChatPacket(WorldObject* source, WorldPacket* data, ChatMsg msgType, WorldObject const* whisperTarget, CreatureTextRange range, Team team, bool gmOnly) const; float GetRangeForChatType(ChatMsg msgType) const; @@ -111,149 +114,4 @@ class TC_GAME_API CreatureTextMgr #define sCreatureTextMgr CreatureTextMgr::instance() -template -class CreatureTextLocalizer -{ - public: - CreatureTextLocalizer(Builder const& builder, ChatMsg msgType) : _builder(builder), _msgType(msgType) - { - _packetCache.resize(TOTAL_LOCALES, NULL); - } - - ~CreatureTextLocalizer() - { - for (size_t i = 0; i < _packetCache.size(); ++i) - { - if (_packetCache[i]) - delete _packetCache[i]->first; - delete _packetCache[i]; - } - } - - void operator()(Player* player) - { - LocaleConstant loc_idx = player->GetSession()->GetSessionDbLocaleIndex(); - WorldPacket* messageTemplate; - size_t whisperGUIDpos; - - // create if not cached yet - if (!_packetCache[loc_idx]) - { - messageTemplate = new WorldPacket(); - whisperGUIDpos = _builder(messageTemplate, loc_idx); - ASSERT(messageTemplate->GetOpcode() != NULL_OPCODE); - _packetCache[loc_idx] = new std::pair(messageTemplate, whisperGUIDpos); - } - else - { - messageTemplate = _packetCache[loc_idx]->first; - whisperGUIDpos = _packetCache[loc_idx]->second; - } - - WorldPacket data(*messageTemplate); - switch (_msgType) - { - case CHAT_MSG_MONSTER_WHISPER: - case CHAT_MSG_RAID_BOSS_WHISPER: - data.put(whisperGUIDpos, player->GetGUID().GetRawValue()); - break; - default: - break; - } - - player->SendDirectMessage(&data); - } - - private: - std::vector* > _packetCache; - Builder const& _builder; - ChatMsg _msgType; -}; - -template -void CreatureTextMgr::SendChatPacket(WorldObject* source, Builder const& builder, ChatMsg msgType, WorldObject const* whisperTarget /*= nullptr*/, CreatureTextRange range /*= TEXT_RANGE_NORMAL*/, Team team /*= TEAM_OTHER*/, bool gmOnly /*= false*/) const -{ - if (!source) - return; - - CreatureTextLocalizer localizer(builder, msgType); - - switch (msgType) - { - case CHAT_MSG_MONSTER_PARTY: - { - if (!whisperTarget) - return; - - if (Player* whisperPlayer = const_cast(whisperTarget->ToPlayer())) - { - if (Group* group = whisperPlayer->GetGroup()) - group->BroadcastWorker(localizer); - } - return; - } - case CHAT_MSG_MONSTER_WHISPER: - case CHAT_MSG_RAID_BOSS_WHISPER: - { - if (range == TEXT_RANGE_NORMAL) // ignores team and gmOnly - { - if (!whisperTarget || whisperTarget->GetTypeId() != TYPEID_PLAYER) - return; - - localizer(const_cast(whisperTarget->ToPlayer())); - return; - } - break; - } - default: - break; - } - - switch (range) - { - case TEXT_RANGE_AREA: - { - uint32 areaId = source->GetAreaId(); - Map::PlayerList const& players = source->GetMap()->GetPlayers(); - for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) - if (itr->GetSource()->GetAreaId() == areaId && (!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster())) - localizer(itr->GetSource()); - return; - } - case TEXT_RANGE_ZONE: - { - uint32 zoneId = source->GetZoneId(); - Map::PlayerList const& players = source->GetMap()->GetPlayers(); - for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) - if (itr->GetSource()->GetZoneId() == zoneId && (!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster())) - localizer(itr->GetSource()); - return; - } - case TEXT_RANGE_MAP: - { - Map::PlayerList const& players = source->GetMap()->GetPlayers(); - for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) - if ((!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster())) - localizer(itr->GetSource()); - return; - } - case TEXT_RANGE_WORLD: - { - SessionMap const& smap = sWorld->GetAllSessions(); - for (SessionMap::const_iterator iter = smap.begin(); iter != smap.end(); ++iter) - if (Player* player = iter->second->GetPlayer()) - if ((!team || Team(player->GetTeam()) == team) && (!gmOnly || player->IsGameMaster())) - localizer(player); - return; - } - case TEXT_RANGE_NORMAL: - default: - break; - } - - float dist = GetRangeForChatType(msgType); - Trinity::PlayerDistWorker> worker(source, dist, localizer); - Cell::VisitWorldObjects(source, worker, dist); -} - #endif diff --git a/src/server/game/Texts/CreatureTextMgrImpl.h b/src/server/game/Texts/CreatureTextMgrImpl.h new file mode 100644 index 00000000000..bb798c685d5 --- /dev/null +++ b/src/server/game/Texts/CreatureTextMgrImpl.h @@ -0,0 +1,157 @@ +#ifndef CreatureTextMgrImpl_h__ +#define CreatureTextMgrImpl_h__ + +#include "CreatureTextMgr.h" +#include "CellImpl.h" +#include "Group.h" +#include "GridNotifiers.h" +#include "World.h" +#include "WorldSession.h" + +template +class CreatureTextLocalizer +{ + public: + CreatureTextLocalizer(Builder const& builder, ChatMsg msgType) : _builder(builder), _msgType(msgType) + { + _packetCache.resize(TOTAL_LOCALES, nullptr); + } + + ~CreatureTextLocalizer() + { + for (size_t i = 0; i < _packetCache.size(); ++i) + { + if (_packetCache[i]) + delete _packetCache[i]->first; + delete _packetCache[i]; + } + } + + void operator()(Player* player) + { + LocaleConstant loc_idx = player->GetSession()->GetSessionDbLocaleIndex(); + WorldPacket* messageTemplate; + size_t whisperGUIDpos; + + // create if not cached yet + if (!_packetCache[loc_idx]) + { + messageTemplate = new WorldPacket(); + whisperGUIDpos = _builder(messageTemplate, loc_idx); + ASSERT(messageTemplate->GetOpcode() != NULL_OPCODE); + _packetCache[loc_idx] = new std::pair(messageTemplate, whisperGUIDpos); + } + else + { + messageTemplate = _packetCache[loc_idx]->first; + whisperGUIDpos = _packetCache[loc_idx]->second; + } + + WorldPacket data(*messageTemplate); + switch (_msgType) + { + case CHAT_MSG_MONSTER_WHISPER: + case CHAT_MSG_RAID_BOSS_WHISPER: + data.put(whisperGUIDpos, player->GetGUID().GetRawValue()); + break; + default: + break; + } + + player->SendDirectMessage(&data); + } + + private: + std::vector* > _packetCache; + Builder const& _builder; + ChatMsg _msgType; +}; + +template +void CreatureTextMgr::SendChatPacket(WorldObject* source, Builder const& builder, ChatMsg msgType, WorldObject const* whisperTarget /*= nullptr*/, CreatureTextRange range /*= TEXT_RANGE_NORMAL*/, Team team /*= TEAM_OTHER*/, bool gmOnly /*= false*/) const +{ + if (!source) + return; + + CreatureTextLocalizer localizer(builder, msgType); + + switch (msgType) + { + case CHAT_MSG_MONSTER_PARTY: + { + if (!whisperTarget) + return; + + if (Player* whisperPlayer = const_cast(whisperTarget->ToPlayer())) + { + if (Group* group = whisperPlayer->GetGroup()) + group->BroadcastWorker(localizer); + } + return; + } + case CHAT_MSG_MONSTER_WHISPER: + case CHAT_MSG_RAID_BOSS_WHISPER: + { + if (range == TEXT_RANGE_NORMAL) // ignores team and gmOnly + { + if (!whisperTarget || whisperTarget->GetTypeId() != TYPEID_PLAYER) + return; + + localizer(const_cast(whisperTarget->ToPlayer())); + return; + } + break; + } + default: + break; + } + + switch (range) + { + case TEXT_RANGE_AREA: + { + uint32 areaId = source->GetAreaId(); + Map::PlayerList const& players = source->GetMap()->GetPlayers(); + for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) + if (itr->GetSource()->GetAreaId() == areaId && (!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster())) + localizer(itr->GetSource()); + return; + } + case TEXT_RANGE_ZONE: + { + uint32 zoneId = source->GetZoneId(); + Map::PlayerList const& players = source->GetMap()->GetPlayers(); + for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) + if (itr->GetSource()->GetZoneId() == zoneId && (!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster())) + localizer(itr->GetSource()); + return; + } + case TEXT_RANGE_MAP: + { + Map::PlayerList const& players = source->GetMap()->GetPlayers(); + for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) + if ((!team || Team(itr->GetSource()->GetTeam()) == team) && (!gmOnly || itr->GetSource()->IsGameMaster())) + localizer(itr->GetSource()); + return; + } + case TEXT_RANGE_WORLD: + { + SessionMap const& smap = sWorld->GetAllSessions(); + for (SessionMap::const_iterator iter = smap.begin(); iter != smap.end(); ++iter) + if (Player* player = iter->second->GetPlayer()) + if ((!team || Team(player->GetTeam()) == team) && (!gmOnly || player->IsGameMaster())) + localizer(player); + return; + } + case TEXT_RANGE_NORMAL: + default: + break; + } + + float dist = GetRangeForChatType(msgType); + Trinity::PlayerDistWorker> worker(source, dist, localizer); + Cell::VisitWorldObjects(source, worker, dist); +} + + +#endif // CreatureTextMgrImpl_h__ diff --git a/src/server/game/Tickets/TicketMgr.cpp b/src/server/game/Tickets/TicketMgr.cpp index cf0ff431590..15a84fcc1aa 100644 --- a/src/server/game/Tickets/TicketMgr.cpp +++ b/src/server/game/Tickets/TicketMgr.cpp @@ -16,20 +16,21 @@ * with this program. If not, see . */ -#include "CharacterCache.h" -#include "Common.h" #include "TicketMgr.h" +#include "CharacterCache.h" +#include "Chat.h" +#include "Common.h" #include "DatabaseEnv.h" -#include "Log.h" #include "Language.h" +#include "Log.h" +#include "ObjectAccessor.h" +#include "Opcodes.h" +#include "Player.h" +#include "World.h" #include "WorldPacket.h" #include "WorldSession.h" -#include "Chat.h" -#include "World.h" -#include "Player.h" -#include "Opcodes.h" -inline float GetAge(uint64 t) { return float(time(NULL) - t) / DAY; } +inline float GetAge(uint64 t) { return float(time(nullptr) - t) / DAY; } /////////////////////////////////////////////////////////////////////////////////////////////////// // GM ticket @@ -37,7 +38,7 @@ GmTicket::GmTicket() : _id(0), _type(TICKET_TYPE_OPEN), _posX(0), _posY(0), _pos _completed(false), _escalatedStatus(TICKET_UNASSIGNED), _viewed(false), _needResponse(false), _needMoreHelp(false) { } -GmTicket::GmTicket(Player* player) : _type(TICKET_TYPE_OPEN), _posX(0), _posY(0), _posZ(0), _mapId(0), _createTime(time(NULL)), _lastModifiedTime(time(NULL)), +GmTicket::GmTicket(Player* player) : _type(TICKET_TYPE_OPEN), _posX(0), _posY(0), _posZ(0), _mapId(0), _createTime(time(nullptr)), _lastModifiedTime(time(nullptr)), _completed(false), _escalatedStatus(TICKET_UNASSIGNED), _viewed(false), _needResponse(false), _needMoreHelp(false) { @@ -46,7 +47,19 @@ GmTicket::GmTicket(Player* player) : _type(TICKET_TYPE_OPEN), _posX(0), _posY(0) _playerGuid = player->GetGUID(); } -GmTicket::~GmTicket() { } +GmTicket::~GmTicket() +{ +} + +Player* GmTicket::GetPlayer() const +{ + return ObjectAccessor::FindPlayer(_playerGuid); +} + +Player* GmTicket::GetAssignedPlayer() const +{ + return ObjectAccessor::FindPlayer(_assignedTo); +} bool GmTicket::LoadFromDB(Field* fields) { @@ -165,7 +178,7 @@ void GmTicket::SendResponse(WorldSession* session) const std::string GmTicket::FormatMessageString(ChatHandler& handler, bool detailed) const { - time_t curTime = time(NULL); + time_t curTime = time(nullptr); std::stringstream ss; ss << handler.PGetParseString(LANG_COMMAND_TICKETLISTGUID, _id); @@ -188,7 +201,7 @@ std::string GmTicket::FormatMessageString(ChatHandler& handler, bool detailed) c return ss.str(); } -std::string GmTicket::FormatMessageString(ChatHandler& handler, const char* szClosedName, const char* szAssignedToName, const char* szUnassignedName, const char* szDeletedName, const char* szCompletedName) const +std::string GmTicket::FormatMessageString(ChatHandler& handler, char const* szClosedName, char const* szAssignedToName, char const* szUnassignedName, char const* szDeletedName, char const* szCompletedName) const { std::stringstream ss; ss << handler.PGetParseString(LANG_COMMAND_TICKETLISTGUID, _id); @@ -256,7 +269,7 @@ void GmTicket::SetChatLog(std::list time, std::string const& log) /////////////////////////////////////////////////////////////////////////////////////////////////// // Ticket manager TicketMgr::TicketMgr() : _status(true), _lastTicketId(0), _lastSurveyId(0), _openTicketCount(0), - _lastChange(time(NULL)) { } + _lastChange(time(nullptr)) { } TicketMgr::~TicketMgr() { @@ -360,7 +373,7 @@ void TicketMgr::AddTicket(GmTicket* ticket) _ticketList[ticket->GetId()] = ticket; if (!ticket->IsClosed()) ++_openTicketCount; - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); ticket->SaveToDB(trans); } @@ -368,7 +381,7 @@ void TicketMgr::CloseTicket(uint32 ticketId, ObjectGuid source) { if (GmTicket* ticket = GetTicket(ticketId)) { - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); ticket->SetClosedBy(source); if (source) --_openTicketCount; diff --git a/src/server/game/Tickets/TicketMgr.h b/src/server/game/Tickets/TicketMgr.h index b807f00ac8e..42643240a97 100644 --- a/src/server/game/Tickets/TicketMgr.h +++ b/src/server/game/Tickets/TicketMgr.h @@ -18,11 +18,14 @@ #ifndef _TICKETMGR_H #define _TICKETMGR_H -#include - -#include "ObjectMgr.h" +#include "ObjectGuid.h" +#include "DatabaseEnvFwd.h" +#include class ChatHandler; +class Player; +class WorldPacket; +class WorldSession; // from blizzard lua enum GMTicketSystemStatus @@ -99,10 +102,10 @@ public: bool IsAssignedNotTo(ObjectGuid guid) const { return IsAssigned() && !IsAssignedTo(guid); } uint32 GetId() const { return _id; } - Player* GetPlayer() const { return ObjectAccessor::FindPlayer(_playerGuid); } + Player* GetPlayer() const; std::string const& GetPlayerName() const { return _playerName; } std::string const& GetMessage() const { return _message; } - Player* GetAssignedPlayer() const { return ObjectAccessor::FindPlayer(_assignedTo); } + Player* GetAssignedPlayer() const; ObjectGuid GetAssignedToGUID() const { return _assignedTo; } std::string GetAssignedToName() const; uint64 GetLastModifiedTime() const { return _lastModifiedTime; } @@ -123,7 +126,7 @@ public: void SetMessage(std::string const& message) { _message = message; - _lastModifiedTime = uint64(time(NULL)); + _lastModifiedTime = uint64(time(nullptr)); } void SetComment(std::string const& comment) { _comment = comment; } void SetViewed() { _viewed = true; } @@ -142,7 +145,7 @@ public: void TeleportTo(Player* player) const; std::string FormatMessageString(ChatHandler& handler, bool detailed = false) const; - std::string FormatMessageString(ChatHandler& handler, const char* szClosedName, const char* szAssignedToName, const char* szUnassignedName, const char* szDeletedName, const char* szCompletedName) const; + std::string FormatMessageString(ChatHandler& handler, char const* szClosedName, char const* szAssignedToName, char const* szUnassignedName, char const* szDeletedName, char const* szCompletedName) const; void SetChatLog(std::list time, std::string const& log); std::string const& GetChatLog() const { return _chatLog; } @@ -191,7 +194,7 @@ public: if (itr != _ticketList.end()) return itr->second; - return NULL; + return nullptr; } GmTicket* GetTicketByPlayer(ObjectGuid playerGuid) @@ -200,7 +203,7 @@ public: if (itr->second && itr->second->IsFromPlayer(playerGuid) && !itr->second->IsClosed()) return itr->second; - return NULL; + return nullptr; } GmTicket* GetOldestOpenTicket() @@ -209,7 +212,7 @@ public: if (itr->second && !itr->second->IsClosed() && !itr->second->IsCompleted()) return itr->second; - return NULL; + return nullptr; } void AddTicket(GmTicket* ticket); @@ -221,7 +224,7 @@ public: void SetStatus(bool status) { _status = status; } uint64 GetLastChange() const { return _lastChange; } - void UpdateLastChange() { _lastChange = uint64(time(NULL)); } + void UpdateLastChange() { _lastChange = uint64(time(nullptr)); } uint32 GenerateTicketId() { return ++_lastTicketId; } uint32 GetOpenTicketCount() const { return _openTicketCount; } @@ -236,9 +239,7 @@ public: void SendTicket(WorldSession* session, GmTicket* ticket) const; -protected: - void _RemoveTicket(uint32 ticketId, int64 source = -1, bool permanently = false); - +private: GmTicketList _ticketList; bool _status; diff --git a/src/server/game/Time/UpdateTime.cpp b/src/server/game/Time/UpdateTime.cpp index 50d47b9b6ea..c80d85f54c2 100644 --- a/src/server/game/Time/UpdateTime.cpp +++ b/src/server/game/Time/UpdateTime.cpp @@ -16,9 +16,9 @@ */ #include "UpdateTime.h" -#include "Timer.h" #include "Config.h" #include "Log.h" +#include "Timer.h" // create instance WorldUpdateTime sWorldUpdateTime; diff --git a/src/server/game/Time/UpdateTime.h b/src/server/game/Time/UpdateTime.h index b2282bf33e0..ac34f5a4618 100644 --- a/src/server/game/Time/UpdateTime.h +++ b/src/server/game/Time/UpdateTime.h @@ -19,6 +19,8 @@ #define __UPDATETIME_H #include "Define.h" +#include +#include #define AVG_DIFF_COUNT 500 diff --git a/src/server/game/Tools/CharacterDatabaseCleaner.cpp b/src/server/game/Tools/CharacterDatabaseCleaner.cpp index 7027d4345d4..6735df2c157 100644 --- a/src/server/game/Tools/CharacterDatabaseCleaner.cpp +++ b/src/server/game/Tools/CharacterDatabaseCleaner.cpp @@ -19,10 +19,11 @@ #include "Common.h" #include "AchievementMgr.h" #include "CharacterDatabaseCleaner.h" -#include "World.h" -#include "Database/DatabaseEnv.h" -#include "SpellMgr.h" +#include "DatabaseEnv.h" #include "DBCStores.h" +#include "Log.h" +#include "SpellMgr.h" +#include "World.h" void CharacterDatabaseCleaner::CleanDatabase() { @@ -67,7 +68,7 @@ void CharacterDatabaseCleaner::CleanDatabase() TC_LOG_INFO("server.loading", ">> Cleaned character database in %u ms", GetMSTimeDiffToNow(oldMSTime)); } -void CharacterDatabaseCleaner::CheckUnique(const char* column, const char* table, bool (*check)(uint32)) +void CharacterDatabaseCleaner::CheckUnique(char const* column, char const* table, bool (*check)(uint32)) { QueryResult result = CharacterDatabase.PQuery("SELECT DISTINCT %s FROM %s", column, table); if (!result) diff --git a/src/server/game/Tools/CharacterDatabaseCleaner.h b/src/server/game/Tools/CharacterDatabaseCleaner.h index 37c3a2b49c0..72c9d2cc505 100644 --- a/src/server/game/Tools/CharacterDatabaseCleaner.h +++ b/src/server/game/Tools/CharacterDatabaseCleaner.h @@ -32,7 +32,7 @@ namespace CharacterDatabaseCleaner TC_GAME_API void CleanDatabase(); - TC_GAME_API void CheckUnique(const char* column, const char* table, bool (*check)(uint32)); + TC_GAME_API void CheckUnique(char const* column, char const* table, bool (*check)(uint32)); TC_GAME_API bool AchievementProgressCheck(uint32 criteria); TC_GAME_API bool SkillCheck(uint32 skill); diff --git a/src/server/game/Tools/PlayerDump.cpp b/src/server/game/Tools/PlayerDump.cpp index 1057f8fec14..be68f0a48af 100644 --- a/src/server/game/Tools/PlayerDump.cpp +++ b/src/server/game/Tools/PlayerDump.cpp @@ -16,14 +16,15 @@ * with this program. If not, see . */ -#include "Common.h" #include "PlayerDump.h" -#include "DatabaseEnv.h" -#include "UpdateFields.h" -#include "ObjectMgr.h" -#include "Player.h" #include "AccountMgr.h" #include "CharacterCache.h" +#include "Common.h" +#include "DatabaseEnv.h" +#include "Log.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "UpdateFields.h" #include "World.h" // static data @@ -419,7 +420,7 @@ inline std::string GetTableName(std::string const& str) { // length of "INSERT INTO `" static std::string::size_type const s = 13; - std::string::size_type e = str.find(_TABLE_SIM_, s); + std::string::size_type e = str.find('`', s); if (e == std::string::npos) return ""; @@ -442,7 +443,7 @@ inline bool ValidateFields(TableStruct const& ts, std::string const& str, size_t s += 4; std::string::size_type valPos = str.find("VALUES ('"); - std::string::size_type e = str.find(_TABLE_SIM_, s); + std::string::size_type e = str.find('`', s); if (e == std::string::npos || valPos == std::string::npos) { TC_LOG_ERROR("misc", "LoadPlayerDump: (line " UI64FMTD ") unexpected end of line", lineNumber); @@ -461,7 +462,7 @@ inline bool ValidateFields(TableStruct const& ts, std::string const& str, size_t // length of "`, `" s = e + 4; - e = str.find(_TABLE_SIM_, s); + e = str.find('`', s); } while (e < valPos); return true; @@ -523,10 +524,10 @@ inline void AppendTableDump(StringTransaction& trans, TableStruct const& tableSt do { std::ostringstream ss; - ss << "INSERT INTO " << _TABLE_SIM_ << tableStruct.TableName << _TABLE_SIM_ << " ("; + ss << "INSERT INTO `" << tableStruct.TableName << "` ("; for (auto itr = tableStruct.TableFields.begin(); itr != tableStruct.TableFields.end();) { - ss << _TABLE_SIM_ << itr->FieldName << _TABLE_SIM_; + ss << '`' << itr->FieldName << '`'; ++itr; if (itr != tableStruct.TableFields.end()) @@ -544,7 +545,7 @@ inline void AppendTableDump(StringTransaction& trans, TableStruct const& tableSt // null pointer -> we have null if (!cString) - ss << "'NULL'"; + ss << "'nullptr'"; else { std::string s(cString); @@ -745,11 +746,11 @@ DumpReturn PlayerDumpWriter::WriteDump(std::string const& file, ObjectGuid::LowT // Reading - High-level functions inline void FixNULLfields(std::string& line) { - static std::string const NullString("'NULL'"); + static std::string const NullString("'nullptr'"); size_t pos = line.find(NullString); while (pos != std::string::npos) { - line.replace(pos, NullString.length(), "NULL"); + line.replace(pos, NullString.length(), "nullptr"); pos = line.find(NullString); } } @@ -908,7 +909,7 @@ DumpReturn PlayerDumpReader::LoadDump(std::string const& file, uint32 account, s break; case GUID_TYPE_NULL: { - static std::string const NullString("NULL"); + static std::string const NullString("nullptr"); if (!ChangeColumn(ts, line, field.FieldName, NullString)) return DUMP_FILE_BROKEN; break; diff --git a/src/server/game/Warden/Warden.cpp b/src/server/game/Warden/Warden.cpp index 1da01289d2d..50af936c308 100644 --- a/src/server/game/Warden/Warden.cpp +++ b/src/server/game/Warden/Warden.cpp @@ -16,21 +16,21 @@ * with this program. If not, see . */ -#include "Common.h" -#include "WorldPacket.h" -#include "WorldSession.h" -#include "Log.h" -#include "Opcodes.h" -#include "ByteBuffer.h" -#include "GameTime.h" -#include "Util.h" #include "Warden.h" #include "AccountMgr.h" - +#include "ByteBuffer.h" +#include "Common.h" +#include "GameTime.h" +#include "Log.h" +#include "Opcodes.h" +#include "Util.h" +#include "World.h" +#include "WorldPacket.h" +#include "WorldSession.h" #include -Warden::Warden() : _session(NULL), _inputCrypto(16), _outputCrypto(16), _checkTimer(10000/*10 sec*/), _clientResponseTimer(0), - _dataSent(false), _previousTimestamp(0), _module(NULL), _initialized(false) +Warden::Warden() : _session(nullptr), _inputCrypto(16), _outputCrypto(16), _checkTimer(10000/*10 sec*/), _clientResponseTimer(0), + _dataSent(false), _previousTimestamp(0), _module(nullptr), _initialized(false) { memset(_inputKey, 0, sizeof(_inputKey)); memset(_outputKey, 0, sizeof(_outputKey)); @@ -41,7 +41,7 @@ Warden::~Warden() { delete[] _module->CompressedData; delete _module; - _module = NULL; + _module = nullptr; _initialized = false; } @@ -180,7 +180,7 @@ uint32 Warden::BuildChecksum(const uint8* data, uint32 length) return checkSum; } -std::string Warden::Penalty(WardenCheck* check /*= NULL*/) +std::string Warden::Penalty(WardenCheck* check /*= nullptr*/) { WardenActions action; @@ -206,7 +206,7 @@ std::string Warden::Penalty(WardenCheck* check /*= NULL*/) AccountMgr::GetName(_session->GetAccountId(), accountName); std::stringstream banReason; banReason << "Warden Anticheat Violation"; - // Check can be NULL, for example if the client sent a wrong signature in the warden packet (CHECKSUM FAIL) + // Check can be nullptr, for example if the client sent a wrong signature in the warden packet (CHECKSUM FAIL) if (check) banReason << ": " << check->Comment << " (CheckId: " << check->CheckId << ")"; diff --git a/src/server/game/Warden/Warden.h b/src/server/game/Warden/Warden.h index 20b4034aac3..9a8984e820f 100644 --- a/src/server/game/Warden/Warden.h +++ b/src/server/game/Warden/Warden.h @@ -119,7 +119,7 @@ class TC_GAME_API Warden static uint32 BuildChecksum(const uint8 *data, uint32 length); // If no check is passed, the default action from config is executed - std::string Penalty(WardenCheck* check = NULL); + std::string Penalty(WardenCheck* check = nullptr); private: WorldSession* _session; diff --git a/src/server/game/Warden/WardenCheckMgr.cpp b/src/server/game/Warden/WardenCheckMgr.cpp index 794dd5cc085..010637ec136 100644 --- a/src/server/game/Warden/WardenCheckMgr.cpp +++ b/src/server/game/Warden/WardenCheckMgr.cpp @@ -20,9 +20,10 @@ #include "WorldPacket.h" #include "WorldSession.h" #include "Log.h" -#include "Database/DatabaseEnv.h" +#include "DatabaseEnv.h" #include "WardenCheckMgr.h" #include "Warden.h" +#include "World.h" WardenCheckMgr::WardenCheckMgr() { } @@ -204,7 +205,7 @@ WardenCheck* WardenCheckMgr::GetWardenDataById(uint16 Id) if (Id < CheckStore.size()) return CheckStore[Id]; - return NULL; + return nullptr; } WardenCheckResult* WardenCheckMgr::GetWardenResultById(uint16 Id) @@ -212,5 +213,5 @@ WardenCheckResult* WardenCheckMgr::GetWardenResultById(uint16 Id) CheckResultContainer::const_iterator itr = CheckResultStore.find(Id); if (itr != CheckResultStore.end()) return itr->second; - return NULL; + return nullptr; } diff --git a/src/server/game/Warden/WardenWin.cpp b/src/server/game/Warden/WardenWin.cpp index 5bd5fa2ccb9..fcd41cea163 100644 --- a/src/server/game/Warden/WardenWin.cpp +++ b/src/server/game/Warden/WardenWin.cpp @@ -26,11 +26,13 @@ #include "ByteBuffer.h" #include "Database/DatabaseEnv.h" #include "GameTime.h" +#include "World.h" #include "Player.h" #include "Util.h" #include "WardenWin.h" #include "WardenModuleWin.h" #include "WardenCheckMgr.h" +#include "Random.h" #include WardenWin::WardenWin() : Warden(), _serverTicks(0) {} diff --git a/src/server/game/Weather/Weather.cpp b/src/server/game/Weather/Weather.cpp index d80f9b4b76f..b0b36cbdc1e 100644 --- a/src/server/game/Weather/Weather.cpp +++ b/src/server/game/Weather/Weather.cpp @@ -21,14 +21,15 @@ */ #include "Weather.h" -#include "WorldPacket.h" -#include "Player.h" #include "GameTime.h" #include "Log.h" -#include "Util.h" -#include "ScriptMgr.h" #include "Opcodes.h" -#include "WorldSession.h" +#include "Player.h" +#include "Random.h" +#include "ScriptMgr.h" +#include "Util.h" +#include "World.h" +#include "WorldPacket.h" /// Create the Weather object Weather::Weather(uint32 zone, WeatherData const* weatherChances) @@ -197,7 +198,7 @@ void Weather::SendWeatherUpdateToPlayer(Player* player) data << uint32(GetWeatherState()); data << (float)m_grade; data << uint8(0); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } /// Send the new weather to all players in the zone diff --git a/src/server/game/Weather/Weather.h b/src/server/game/Weather/Weather.h index 7bc039fb6e7..6b11ec29e13 100644 --- a/src/server/game/Weather/Weather.h +++ b/src/server/game/Weather/Weather.h @@ -43,7 +43,7 @@ struct WeatherData uint32 ScriptId; }; -enum WeatherState +enum WeatherState : uint32 { WEATHER_STATE_FINE = 0, WEATHER_STATE_FOG = 1, // Used in some instance encounters. diff --git a/src/server/game/Weather/WeatherMgr.cpp b/src/server/game/Weather/WeatherMgr.cpp index 70f95f625ba..8861f60505a 100644 --- a/src/server/game/Weather/WeatherMgr.cpp +++ b/src/server/game/Weather/WeatherMgr.cpp @@ -21,11 +21,12 @@ */ #include "WeatherMgr.h" -#include "Weather.h" +#include "DatabaseEnv.h" #include "Log.h" #include "ObjectMgr.h" -#include "Player.h" #include "Opcodes.h" +#include "Player.h" +#include "Weather.h" #include "WorldSession.h" namespace WeatherMgr @@ -42,7 +43,7 @@ namespace WeatherData const* GetWeatherData(uint32 zone_id) { WeatherZoneMap::const_iterator itr = mWeatherZoneMap.find(zone_id); - return (itr != mWeatherZoneMap.end()) ? &itr->second : NULL; + return (itr != mWeatherZoneMap.end()) ? &itr->second : nullptr; } } @@ -70,7 +71,7 @@ Weather* AddWeather(uint32 zone_id) // zone does not have weather, ignore if (!weatherChances) - return NULL; + return nullptr; Weather* w = new Weather(zone_id, weatherChances); m_weathers[w->GetZone()].reset(w); @@ -147,7 +148,7 @@ void SendFineWeatherUpdateToPlayer(Player* player) data << (uint32)WEATHER_STATE_FINE; data << (float)0.0f; data << uint8(0); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } void Update(uint32 diff) diff --git a/src/server/game/World/World.cpp b/src/server/game/World/World.cpp index 9da562d7e46..b18f0a64eda 100644 --- a/src/server/game/World/World.cpp +++ b/src/server/game/World/World.cpp @@ -21,7 +21,10 @@ */ #include "World.h" +#include "AccountMgr.h" #include "AchievementMgr.h" +#include "AddonMgr.h" +#include "ArchaeologyMgr.h" #include "ArenaTeamMgr.h" #include "AuctionHouseBot.h" #include "AuctionHouseMgr.h" @@ -37,43 +40,54 @@ #include "CreatureGroups.h" #include "CreatureTextMgr.h" #include "DatabaseEnv.h" +#include "DB2Stores.h" #include "DisableMgr.h" #include "GameEventMgr.h" #include "GameObjectModel.h" +#include "GameTime.h" #include "GitRevision.h" #include "GridNotifiersImpl.h" #include "GroupMgr.h" #include "GuildFinderMgr.h" +#include "GuildMgr.h" #include "InstanceSaveMgr.h" #include "Language.h" #include "LFGMgr.h" +#include "Log.h" +#include "LootItemStorage.h" +#include "LootMgr.h" +#include "M2Stores.h" #include "MapManager.h" #include "Memory.h" +#include "Metric.h" #include "MMapFactory.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "OutdoorPvPMgr.h" #include "Player.h" #include "PlayerDump.h" #include "PoolMgr.h" #include "QueryCallback.h" +#include "Realm.h" #include "ScriptMgr.h" #include "ScriptReloadMgr.h" #include "SkillDiscovery.h" #include "SkillExtraItems.h" -#include "Metric.h" -#include "SmartAI.h" +#include "SmartScriptMgr.h" +#include "SpellMgr.h" #include "TicketMgr.h" #include "TransportMgr.h" #include "Unit.h" +#include "UpdateTime.h" #include "VMapFactory.h" +#include "VMapManager2.h" #include "WardenCheckMgr.h" #include "WaypointMovementGenerator.h" #include "WeatherMgr.h" -#include "WorldSession.h" -#include "M2Stores.h" #include "WhoListStorage.h" -#include "GameTime.h" -#include "UpdateTime.h" +#include "WorldSession.h" + +#include TC_GAME_API std::atomic World::m_stopEvent(false); TC_GAME_API uint8 World::m_ExitCode = SHUTDOWN_EXIT_CODE; @@ -135,7 +149,7 @@ World::~World() m_sessions.erase(m_sessions.begin()); } - CliCommandHolder* command = NULL; + CliCommandHolder* command = nullptr; while (cliCmdQueue.next(command)) delete command; @@ -168,7 +182,7 @@ Player* World::FindPlayerInZone(uint32 zone) if (player->IsInWorld() && player->GetZoneId() == zone) return player; } - return NULL; + return nullptr; } bool World::IsClosed() const @@ -191,7 +205,7 @@ void World::SetMotd(const std::string& motd) sScriptMgr->OnMotdChange(m_motd); } -const char* World::GetMotd() const +char const* World::GetMotd() const { return m_motd.c_str(); } @@ -202,9 +216,9 @@ WorldSession* World::FindSession(uint32 id) const SessionMap::const_iterator itr = m_sessions.find(id); if (itr != m_sessions.end()) - return itr->second; // also can return NULL for kicked session + return itr->second; // also can return nullptr for kicked session else - return NULL; + return nullptr; } /// Remove a given session @@ -304,7 +318,7 @@ bool World::HasRecentlyDisconnected(WorldSession* session) { for (DisconnectMap::iterator i = m_disconnects.begin(); i != m_disconnects.end();) { - if (difftime(i->second, time(NULL)) < tolerance) + if (difftime(i->second, time(nullptr)) < tolerance) { if (i->first == session->GetAccountId()) return true; @@ -1247,7 +1261,7 @@ void World::LoadConfigSettings(bool reload) #if TRINITY_PLATFORM == TRINITY_PLATFORM_UNIX || TRINITY_PLATFORM == TRINITY_PLATFORM_APPLE if (dataPath[0] == '~') { - const char* home = getenv("HOME"); + char const* home = getenv("HOME"); if (home) dataPath.replace(0, 1, home); } @@ -1437,7 +1451,7 @@ void World::SetInitialWorldSettings() uint32 startupBegin = getMSTime(); ///- Initialize the random number generator - srand((unsigned int)time(NULL)); + srand((unsigned int)time(nullptr)); ///- Initialize detour memory management dtAllocSetCustom(dtCustomAlloc, dtCustomFree); @@ -1593,6 +1607,9 @@ void World::SetInitialWorldSettings() TC_LOG_INFO("server.loading", "Loading Transport templates..."); sTransportMgr->LoadTransportTemplates(); + TC_LOG_INFO("server.loading", "Loading Transport animations and rotations..."); + sTransportMgr->LoadTransportAnimationAndRotation(); + TC_LOG_INFO("server.loading", "Loading Spell Rank Data..."); sSpellMgr->LoadSpellRanks(); @@ -1957,6 +1974,9 @@ void World::SetInitialWorldSettings() TC_LOG_INFO("server.loading", "Loading Calendar data..."); sCalendarMgr->LoadFromDB(); + TC_LOG_INFO("server.loading", "Loading Item loot..."); + sLootItemStorage->LoadStorageFromDB(); + ///- Initialize game time and timers TC_LOG_INFO("server.loading", "Initialize game time and timers"); GameTime::UpdateGameTimers(); @@ -2403,7 +2423,7 @@ namespace Trinity { public: typedef std::vector WorldPacketList; - explicit WorldWorldTextBuilder(uint32 textId, va_list* args = NULL) : i_textId(textId), i_args(args) { } + explicit WorldWorldTextBuilder(uint32 textId, va_list* args = nullptr) : i_textId(textId), i_args(args) { } void operator()(WorldPacketList& data_list, LocaleConstant loc_idx) { char const* text = sObjectMgr->GetTrinityString(i_textId, loc_idx); @@ -2424,14 +2444,14 @@ namespace Trinity do_helper(data_list, (char*)text); } private: - char* lineFromMessage(char*& pos) { char* start = strtok(pos, "\n"); pos = NULL; return start; } + char* lineFromMessage(char*& pos) { char* start = strtok(pos, "\n"); pos = nullptr; return start; } void do_helper(WorldPacketList& data_list, char* text) { char* pos = text; while (char* line = lineFromMessage(pos)) { WorldPacket* data = new WorldPacket(); - ChatHandler::BuildChatPacket(*data, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, NULL, line); + ChatHandler::BuildChatPacket(*data, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, nullptr, nullptr, line); data_list.push_back(data); } } @@ -2487,7 +2507,7 @@ void World::SendGMText(uint32 string_id, ...) } /// DEPRECATED, only for debug purpose. Send a System Message to all players (except self if mentioned) -void World::SendGlobalText(const char* text, WorldSession* self) +void World::SendGlobalText(char const* text, WorldSession* self) { WorldPacket data; @@ -2497,7 +2517,7 @@ void World::SendGlobalText(const char* text, WorldSession* self) while (char* line = ChatHandler::LineFromMessage(pos)) { - ChatHandler::BuildChatPacket(data, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, NULL, line); + ChatHandler::BuildChatPacket(data, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, nullptr, nullptr, line); SendGlobalMessage(&data, self); } @@ -2528,10 +2548,10 @@ bool World::SendZoneMessage(uint32 zone, WorldPacket* packet, WorldSession* self } /// Send a System Message to all players in the zone (except self if mentioned) -void World::SendZoneText(uint32 zone, const char* text, WorldSession* self, uint32 team) +void World::SendZoneText(uint32 zone, char const* text, WorldSession* self, uint32 team) { WorldPacket data; - ChatHandler::BuildChatPacket(data, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, NULL, text); + ChatHandler::BuildChatPacket(data, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, nullptr, nullptr, text); SendZoneMessage(zone, &data, self, team); } @@ -2564,8 +2584,8 @@ BanReturn World::BanAccount(BanMode mode, std::string const& nameOrIP, std::stri /// Ban an account or ban an IP address, duration is in seconds if positive, otherwise permban BanReturn World::BanAccount(BanMode mode, std::string const& nameOrIP, uint32 duration_secs, std::string const& reason, std::string const& author) { - PreparedQueryResult resultAccounts = PreparedQueryResult(NULL); //used for kicking - PreparedStatement* stmt = NULL; + PreparedQueryResult resultAccounts = PreparedQueryResult(nullptr); //used for kicking + PreparedStatement* stmt = nullptr; // Prevent banning an already banned account if (mode == BAN_ACCOUNT && AccountMgr::IsBannedAccount(nameOrIP)) @@ -2645,7 +2665,7 @@ BanReturn World::BanAccount(BanMode mode, std::string const& nameOrIP, uint32 du /// Remove a ban from an account or IP address bool World::RemoveBanAccount(BanMode mode, std::string const& nameOrIP) { - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; if (mode == BAN_IP) { stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_IP_NOT_BANNED); @@ -2851,7 +2871,7 @@ void World::SendServerMessage(ServerMessageType type, const char *text, Player* data << text; if (player) - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); else SendGlobalMessage(&data); } @@ -2859,7 +2879,7 @@ void World::SendServerMessage(ServerMessageType type, const char *text, Player* void World::UpdateSessions(uint32 diff) { ///- Add new sessions - WorldSession* sess = NULL; + WorldSession* sess = nullptr; while (addSessQueue.next(sess)) AddSession_ (sess); @@ -2876,7 +2896,7 @@ void World::UpdateSessions(uint32 diff) if (!pSession->Update(diff, updater)) // As interval = 0 { if (!RemoveQueuedPlayer(itr->second) && itr->second && getIntConfig(CONFIG_INTERVAL_DISCONNECT_TOLERANCE)) - m_disconnects[itr->second->GetAccountId()] = time(NULL); + m_disconnects[itr->second->GetAccountId()] = time(nullptr); RemoveQueuedPlayer(pSession); m_sessions.erase(itr); delete pSession; @@ -2888,9 +2908,9 @@ void World::UpdateSessions(uint32 diff) // This handles the issued and queued CLI commands void World::ProcessCliCommands() { - CliCommandHolder::Print* zprint = NULL; - void* callbackArg = NULL; - CliCommandHolder* command = NULL; + CliCommandHolder::Print zprint = nullptr; + void* callbackArg = nullptr; + CliCommandHolder* command = nullptr; while (cliCmdQueue.next(command)) { TC_LOG_INFO("misc", "CLI command under processing..."); @@ -3000,7 +3020,7 @@ void World::_UpdateRealmCharCount(PreparedQueryResult resultCharCount) void World::InitWeeklyQuestResetTime() { time_t wstime = uint64(sWorld->getWorldState(WS_WEEKLY_QUEST_RESET_TIME)); - time_t curtime = time(NULL); + time_t curtime = time(nullptr); m_NextWeeklyQuestReset = wstime < curtime ? curtime : time_t(wstime); } @@ -3019,7 +3039,7 @@ void World::InitDailyQuestResetTime(bool loading) } // FIX ME: client not show day start time - time_t curTime = time(NULL); + time_t curTime = time(nullptr); tm localTm; localtime_r(&curTime, &localTm); localTm.tm_hour = getIntConfig(CONFIG_DAILY_QUEST_RESET_TIME_HOUR); @@ -3042,7 +3062,7 @@ void World::InitDailyQuestResetTime(bool loading) void World::InitMonthlyQuestResetTime() { time_t wstime = uint64(sWorld->getWorldState(WS_MONTHLY_QUEST_RESET_TIME)); - time_t curtime = time(NULL); + time_t curtime = time(nullptr); m_NextMonthlyQuestReset = wstime < curtime ? curtime : time_t(wstime); } @@ -3050,10 +3070,10 @@ void World::InitRandomBGResetTime() { time_t bgtime = uint64(sWorld->getWorldState(WS_BG_DAILY_RESET_TIME)); if (!bgtime) - m_NextRandomBGReset = time_t(time(NULL)); // game time not yet init + m_NextRandomBGReset = time_t(time(nullptr)); // game time not yet init // generate time by config - time_t curTime = time(NULL); + time_t curTime = time(nullptr); tm localTm; localtime_r(&curTime, &localTm); localTm.tm_hour = getIntConfig(CONFIG_RANDOM_BG_RESET_HOUR); @@ -3078,10 +3098,10 @@ void World::InitGuildResetTime() { time_t gtime = uint64(getWorldState(WS_GUILD_DAILY_RESET_TIME)); if (!gtime) - m_NextGuildReset = time_t(time(NULL)); // game time not yet init + m_NextGuildReset = time_t(time(nullptr)); // game time not yet init // generate time by config - time_t curTime = time(NULL); + time_t curTime = time(nullptr); tm localTm; localtime_r(&curTime, &localTm); localTm.tm_hour = getIntConfig(CONFIG_GUILD_RESET_HOUR); @@ -3106,10 +3126,10 @@ void World::InitCurrencyResetTime() { time_t currencytime = uint64(sWorld->getWorldState(WS_CURRENCY_RESET_TIME)); if (!currencytime) - m_NextCurrencyReset = time_t(time(NULL)); // game time not yet init + m_NextCurrencyReset = time_t(time(nullptr)); // game time not yet init // generate time by config - time_t curTime = time(NULL); + time_t curTime = time(nullptr); tm localTm = *localtime(&curTime); localTm.tm_wday = getIntConfig(CONFIG_CURRENCY_RESET_DAY); @@ -3207,7 +3227,7 @@ void World::ResetMonthlyQuests() itr->second->GetPlayer()->ResetMonthlyQuestStatus(); // generate time - time_t curTime = time(NULL); + time_t curTime = time(nullptr); tm localTm; localtime_r(&curTime, &localTm); @@ -3336,7 +3356,16 @@ void World::LoadWorldStates() while (result->NextRow()); TC_LOG_INFO("server.loading", ">> Loaded %u world states in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); +} +bool World::IsPvPRealm() const +{ + return (getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_PVP || getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_RPPVP || getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_FFA_PVP); +} + +bool World::IsFFAPvPRealm() const +{ + return getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_FFA_PVP; } // Setting a worldstate will save it to DB @@ -3393,3 +3422,13 @@ void World::RemoveOldCorpses() } Realm realm; + +CliCommandHolder::CliCommandHolder(void* callbackArg, char const* command, Print zprint, CommandFinished commandFinished) + : m_callbackArg(callbackArg), m_command(strdup(command)), m_print(zprint), m_commandFinished(commandFinished) +{ +} + +CliCommandHolder::~CliCommandHolder() +{ + free(m_command); +} diff --git a/src/server/game/World/World.h b/src/server/game/World/World.h index f5e710d9299..ec0c4f9439c 100644 --- a/src/server/game/World/World.h +++ b/src/server/game/World/World.h @@ -24,24 +24,23 @@ #define __WORLD_H #include "Common.h" +#include "DatabaseEnvFwd.h" +#include "LockedQueue.h" #include "ObjectGuid.h" -#include "Timer.h" -#include "SharedDefines.h" -#include "QueryResult.h" #include "QueryCallbackProcessor.h" -#include "Realm/Realm.h" +#include "SharedDefines.h" +#include "Timer.h" #include -#include -#include #include +#include +#include -class Object; +class Player; class WorldPacket; class WorldSession; -class Player; class WorldSocket; -class SystemMgr; +struct Realm; // ServerMessages.dbc enum ServerMessageType @@ -61,14 +60,14 @@ enum ServerMessageType SERVER_MSG_TICKET_WAIT_TIME = 13, }; -enum ShutdownMask +enum ShutdownMask : uint32 { SHUTDOWN_MASK_RESTART = 1, SHUTDOWN_MASK_IDLE = 2, SHUTDOWN_MASK_FORCE = 4 }; -enum ShutdownExitCode +enum ShutdownExitCode : uint32 { SHUTDOWN_EXIT_CODE = 0, ERROR_EXIT_CODE = 1, @@ -561,23 +560,18 @@ enum WorldStates }; /// Storage class for commands issued for delayed execution -struct CliCommandHolder +struct TC_GAME_API CliCommandHolder { - typedef void Print(void*, const char*); - typedef void CommandFinished(void*, bool success); + typedef void(*Print)(void*, char const*); + typedef void(*CommandFinished)(void*, bool success); void* m_callbackArg; - char *m_command; - Print* m_print; + char* m_command; + Print m_print; + CommandFinished m_commandFinished; - CommandFinished* m_commandFinished; - - CliCommandHolder(void* callbackArg, const char *command, Print* zprint, CommandFinished* commandFinished) - : m_callbackArg(callbackArg), m_command(strdup(command)), m_print(zprint), m_commandFinished(commandFinished) - { - } - - ~CliCommandHolder() { free(m_command); } + CliCommandHolder(void* callbackArg, char const* command, Print zprint, CommandFinished commandFinished); + ~CliCommandHolder(); private: CliCommandHolder(CliCommandHolder const& right) = delete; @@ -612,7 +606,7 @@ class TC_GAME_API World bool RemoveSession(uint32 id); /// Get the number of current active sessions void UpdateMaxSessionCounters(); - const SessionMap& GetAllSessions() const { return m_sessions; } + SessionMap const& GetAllSessions() const { return m_sessions; } uint32 GetActiveAndQueuedSessionCount() const { return m_sessions.size(); } uint32 GetActiveSessionCount() const { return m_sessions.size() - m_QueuedPlayer.size(); } uint32 GetQueuedSessionCount() const { return m_QueuedPlayer.size(); } @@ -663,7 +657,7 @@ class TC_GAME_API World /// Set a new Message of the Day void SetMotd(std::string const& motd); /// Get the current Message of the Day - const char* GetMotd() const; + char const* GetMotd() const; /// Set the string for new characters (first login) void SetNewCharString(std::string const& str) { m_newCharString = str; } @@ -691,20 +685,20 @@ class TC_GAME_API World void LoadConfigSettings(bool reload = false); void SendWorldText(uint32 string_id, ...); - void SendGlobalText(const char* text, WorldSession* self); + void SendGlobalText(char const* text, WorldSession* self); void SendGMText(uint32 string_id, ...); - void SendServerMessage(ServerMessageType type, const char *text = "", Player* player = NULL); + void SendServerMessage(ServerMessageType type, char const* text = "", Player* player = nullptr); void SendGlobalMessage(WorldPacket* packet, WorldSession* self = nullptr, uint32 team = 0); void SendGlobalGMMessage(WorldPacket* packet, WorldSession* self = nullptr, uint32 team = 0); bool SendZoneMessage(uint32 zone, WorldPacket* packet, WorldSession* self = nullptr, uint32 team = 0); - void SendZoneText(uint32 zone, const char *text, WorldSession* self = nullptr, uint32 team = 0); + void SendZoneText(uint32 zone, char const* text, WorldSession* self = nullptr, uint32 team = 0); /// Are we in the middle of a shutdown? bool IsShuttingDown() const { return m_ShutdownTimer > 0; } uint32 GetShutDownTimeLeft() const { return m_ShutdownTimer; } void ShutdownServ(uint32 time, uint32 options, uint8 exitcode, const std::string& reason = std::string()); uint32 ShutdownCancel(); - void ShutdownMsg(bool show = false, Player* player = NULL, const std::string& reason = std::string()); + void ShutdownMsg(bool show = false, Player* player = nullptr, const std::string& reason = std::string()); static uint8 GetExitCode() { return m_ExitCode; } static void StopNow(uint8 exitcode) { m_stopEvent = true; m_ExitCode = exitcode; } static bool IsStopped() { return m_stopEvent; } @@ -761,8 +755,8 @@ class TC_GAME_API World void LoadWorldStates(); /// Are we on a "Player versus Player" server? - bool IsPvPRealm() const { return (getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_PVP || getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_RPPVP || getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_FFA_PVP); } - bool IsFFAPvPRealm() const { return getIntConfig(CONFIG_GAME_TYPE) == REALM_TYPE_FFA_PVP; } + bool IsPvPRealm() const; + bool IsFFAPvPRealm() const; void KickAll(); void KickAllLess(AccountTypes sec); diff --git a/src/server/ipc/CMakeLists.txt b/src/server/ipc/CMakeLists.txt index df996cb8bdb..1e9eb5b3c9e 100644 --- a/src/server/ipc/CMakeLists.txt +++ b/src/server/ipc/CMakeLists.txt @@ -29,6 +29,8 @@ target_include_directories(ipc ${CMAKE_CURRENT_BINARY_DIR}) target_link_libraries(ipc + PRIVATE + trinity-core-interface PUBLIC shared zmqpp) diff --git a/src/server/ipc/ZMQTask.cpp b/src/server/ipc/ZMQTask.cpp index 746b85fd651..fb27315047a 100644 --- a/src/server/ipc/ZMQTask.cpp +++ b/src/server/ipc/ZMQTask.cpp @@ -27,7 +27,7 @@ ZMQTask::ZMQTask() ZMQTask::~ZMQTask() { delete _poller; - _poller = NULL; + _poller = nullptr; delete _inproc; delete _thread; } diff --git a/src/server/scripts/CMakeLists.txt b/src/server/scripts/CMakeLists.txt index 1197a13b350..5c4d80e34dc 100644 --- a/src/server/scripts/CMakeLists.txt +++ b/src/server/scripts/CMakeLists.txt @@ -91,10 +91,6 @@ 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) - if (MSVC) - list(INSERT PRIVATE_SOURCES 0 ScriptPCH.cpp) - endif (MSVC) endif () GroupSources(${CMAKE_CURRENT_SOURCE_DIR}) @@ -161,14 +157,13 @@ foreach(SCRIPT_MODULE ${SCRIPT_MODULE_LIST}) 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}) - if (USE_SCRIPTPCH AND MSVC) - list(INSERT SCRIPT_MODULE_PRIVATE_SOURCES 0 ScriptPCH.cpp) - endif (USE_SCRIPTPCH AND MSVC) # Create the script module project add_library(${SCRIPT_MODULE_PROJECT_NAME} SHARED ${SCRIPT_MODULE_PRIVATE_SOURCES} ${SCRIPT_MODULE_PRIVATE_SCRIPTLOADER}) target_link_libraries(${SCRIPT_MODULE_PROJECT_NAME} + PRIVATE + trinity-core-interface PUBLIC game) set_target_properties(${SCRIPT_MODULE_PROJECT_NAME} @@ -209,6 +204,8 @@ add_library(scripts STATIC ${PRIVATE_SOURCES}) target_link_libraries(scripts + PRIVATE + trinity-core-interface PUBLIC game) diff --git a/src/server/scripts/Commands/cs_account.cpp b/src/server/scripts/Commands/cs_account.cpp index 70ac16d9dca..03929ded169 100644 --- a/src/server/scripts/Commands/cs_account.cpp +++ b/src/server/scripts/Commands/cs_account.cpp @@ -24,9 +24,14 @@ EndScriptData */ #include "AccountMgr.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "IpAddress.h" #include "Language.h" +#include "Log.h" #include "Player.h" #include "ScriptMgr.h" +#include "World.h" +#include "WorldSession.h" class account_commandscript : public CommandScript { @@ -43,7 +48,7 @@ public: static std::vector accountSetCommandTable = { { "addon", rbac::RBAC_PERM_COMMAND_ACCOUNT_SET_ADDON, true, &HandleAccountSetAddonCommand, "" }, - { "sec", rbac::RBAC_PERM_COMMAND_ACCOUNT_SET_SEC, true, NULL, "", accountSetSecTable }, + { "sec", rbac::RBAC_PERM_COMMAND_ACCOUNT_SET_SEC, true, nullptr, "", accountSetSecTable }, { "gmlevel", rbac::RBAC_PERM_COMMAND_ACCOUNT_SET_GMLEVEL, true, &HandleAccountSetGmLevelCommand, "" }, { "password", rbac::RBAC_PERM_COMMAND_ACCOUNT_SET_PASSWORD, true, &HandleAccountSetPasswordCommand, "" }, }; @@ -59,14 +64,14 @@ public: { "delete", rbac::RBAC_PERM_COMMAND_ACCOUNT_DELETE, true, &HandleAccountDeleteCommand, "" }, { "email", rbac::RBAC_PERM_COMMAND_ACCOUNT_EMAIL, false, &HandleAccountEmailCommand, "" }, { "onlinelist", rbac::RBAC_PERM_COMMAND_ACCOUNT_ONLINE_LIST, true, &HandleAccountOnlineListCommand, "" }, - { "lock", rbac::RBAC_PERM_COMMAND_ACCOUNT_LOCK, false, NULL, "", accountLockCommandTable }, - { "set", rbac::RBAC_PERM_COMMAND_ACCOUNT_SET, true, NULL, "", accountSetCommandTable }, + { "lock", rbac::RBAC_PERM_COMMAND_ACCOUNT_LOCK, false, nullptr, "", accountLockCommandTable }, + { "set", rbac::RBAC_PERM_COMMAND_ACCOUNT_SET, true, nullptr, "", accountSetCommandTable }, { "password", rbac::RBAC_PERM_COMMAND_ACCOUNT_PASSWORD, false, &HandleAccountPasswordCommand, "" }, { "", rbac::RBAC_PERM_COMMAND_ACCOUNT, false, &HandleAccountCommand, "" }, }; static std::vector commandTable = { - { "account", rbac::RBAC_PERM_COMMAND_ACCOUNT, true, NULL, "", accountCommandTable }, + { "account", rbac::RBAC_PERM_COMMAND_ACCOUNT, true, nullptr, "", accountCommandTable }, }; return commandTable; } @@ -113,8 +118,8 @@ public: ///- %Parse the command line arguments char* accountName = strtok((char*)args, " "); - char* password = strtok(NULL, " "); - char* possibleEmail = strtok(NULL, " ' "); + char* password = strtok(nullptr, " "); + char* possibleEmail = strtok(nullptr, " ' "); if (possibleEmail) email = possibleEmail; @@ -196,7 +201,7 @@ public: /// Commands not recommended call from chat, but support anyway /// can delete only for account with less security /// This is also reject self apply in fact - if (handler->HasLowerSecurityAccount(NULL, accountId, true)) + if (handler->HasLowerSecurityAccount(nullptr, accountId, true)) return false; AccountOpResult result = AccountMgr::DeleteAccount(accountId); @@ -286,7 +291,7 @@ public: if (param == "on") { PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_LOGON_COUNTRY); - uint32 ip = inet_addr(handler->GetSession()->GetRemoteAddress().c_str()); + uint32 ip = Trinity::Net::address_to_uint(Trinity::Net::make_address_v4(handler->GetSession()->GetRemoteAddress())); EndianConvertReverse(ip); stmt->setUInt32(0, ip); PreparedQueryResult result = LoginDatabase.Query(stmt); @@ -368,9 +373,9 @@ public: } char* oldEmail = strtok((char*)args, " "); - char* password = strtok(NULL, " "); - char* email = strtok(NULL, " "); - char* emailConfirmation = strtok(NULL, " "); + char* password = strtok(nullptr, " "); + char* email = strtok(nullptr, " "); + char* emailConfirmation = strtok(nullptr, " "); if (!oldEmail || !password || !email || !emailConfirmation) { @@ -462,9 +467,9 @@ public: // Command is supposed to be: .account password [$oldpassword] [$newpassword] [$newpasswordconfirmation] [$emailconfirmation] char* oldPassword = strtok((char*)args, " "); // This extracts [$oldpassword] - char* newPassword = strtok(NULL, " "); // This extracts [$newpassword] - char* passwordConfirmation = strtok(NULL, " "); // This extracts [$newpasswordconfirmation] - char const* emailConfirmation = strtok(NULL, " "); // This defines the emailConfirmation variable, which is optional depending on sec type. + char* newPassword = strtok(nullptr, " "); // This extracts [$newpassword] + char* passwordConfirmation = strtok(nullptr, " "); // This extracts [$newpasswordconfirmation] + char const* emailConfirmation = strtok(nullptr, " "); // This defines the emailConfirmation variable, which is optional depending on sec type. if (!emailConfirmation) // This extracts [$emailconfirmation]. If it doesn't exist, however... emailConfirmation = ""; // ... it's simply "" for emailConfirmation. @@ -580,7 +585,7 @@ public: { ///- Get the command line arguments char* account = strtok((char*)args, " "); - char* exp = strtok(NULL, " "); + char* exp = strtok(nullptr, " "); if (!account) return false; @@ -621,7 +626,7 @@ public: // Let set addon state only for lesser (strong) security level // or to self account if (handler->GetSession() && handler->GetSession()->GetAccountId() != accountId && - handler->HasLowerSecurityAccount(NULL, accountId, true)) + handler->HasLowerSecurityAccount(nullptr, accountId, true)) return false; int expansion = atoi(exp); //get int anyway (0 if error) @@ -653,8 +658,8 @@ public: uint32 targetSecurity = 0; uint32 gm = 0; char* arg1 = strtok((char*)args, " "); - char* arg2 = strtok(NULL, " "); - char* arg3 = strtok(NULL, " "); + char* arg2 = strtok(nullptr, " "); + char* arg3 = strtok(nullptr, " "); bool isAccountNameGiven = true; if (!arg3) @@ -689,7 +694,7 @@ public: return false; } - // handler->getSession() == NULL only for console + // handler->getSession() == nullptr only for console targetAccountId = (isAccountNameGiven) ? AccountMgr::GetId(targetAccountName) : handler->getSelectedPlayer()->GetSession()->GetAccountId(); int32 gmRealmID = (isAccountNameGiven) ? atoi(arg3) : atoi(arg2); uint32 playerSecurity; @@ -734,7 +739,7 @@ public: return false; } - rbac::RBACData* rbac = isAccountNameGiven ? NULL : handler->getSelectedPlayer()->GetSession()->GetRBACData(); + rbac::RBACData* rbac = isAccountNameGiven ? nullptr : handler->getSelectedPlayer()->GetSession()->GetRBACData(); sAccountMgr->UpdateAccountAccess(rbac, targetAccountId, uint8(gm), gmRealmID); handler->PSendSysMessage(LANG_YOU_CHANGE_SECURITY, targetAccountName.c_str(), gm); @@ -753,8 +758,8 @@ public: ///- Get the command line arguments char* account = strtok((char*)args, " "); - char* password = strtok(NULL, " "); - char* passwordConfirmation = strtok(NULL, " "); + char* password = strtok(nullptr, " "); + char* passwordConfirmation = strtok(nullptr, " "); if (!account || !password || !passwordConfirmation) return false; @@ -777,7 +782,7 @@ public: /// can set password only for target with less security /// This also restricts setting handler's own password - if (handler->HasLowerSecurityAccount(NULL, targetAccountId, true)) + if (handler->HasLowerSecurityAccount(nullptr, targetAccountId, true)) return false; if (strcmp(password, passwordConfirmation) != 0) @@ -818,8 +823,8 @@ public: ///- Get the command line arguments char* account = strtok((char*)args, " "); - char* email = strtok(NULL, " "); - char* emailConfirmation = strtok(NULL, " "); + char* email = strtok(nullptr, " "); + char* emailConfirmation = strtok(nullptr, " "); if (!account || !email || !emailConfirmation) { @@ -846,7 +851,7 @@ public: /// can set email only for target with less security /// This also restricts setting handler's own email. - if (handler->HasLowerSecurityAccount(NULL, targetAccountId, true)) + if (handler->HasLowerSecurityAccount(nullptr, targetAccountId, true)) return false; if (strcmp(email, emailConfirmation) != 0) @@ -894,8 +899,8 @@ public: ///- Get the command line arguments char* account = strtok((char*)args, " "); - char* email = strtok(NULL, " "); - char* emailConfirmation = strtok(NULL, " "); + char* email = strtok(nullptr, " "); + char* emailConfirmation = strtok(nullptr, " "); if (!account || !email || !emailConfirmation) { @@ -922,7 +927,7 @@ public: /// can set email only for target with less security /// This also restricts setting handler's own email. - if (handler->HasLowerSecurityAccount(NULL, targetAccountId, true)) + if (handler->HasLowerSecurityAccount(nullptr, targetAccountId, true)) return false; if (strcmp(email, emailConfirmation) != 0) diff --git a/src/server/scripts/Commands/cs_achievement.cpp b/src/server/scripts/Commands/cs_achievement.cpp index 47e6c0a744e..f3c8a43343a 100644 --- a/src/server/scripts/Commands/cs_achievement.cpp +++ b/src/server/scripts/Commands/cs_achievement.cpp @@ -22,11 +22,12 @@ Comment: All achievement related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "AchievementMgr.h" #include "Chat.h" #include "Language.h" #include "Player.h" -#include "ScriptMgr.h" +#include "RBAC.h" class achievement_commandscript : public CommandScript { @@ -41,7 +42,7 @@ public: }; static std::vector commandTable = { - { "achievement", rbac::RBAC_PERM_COMMAND_ACHIEVEMENT, false, NULL, "", achievementCommandTable }, + { "achievement", rbac::RBAC_PERM_COMMAND_ACHIEVEMENT, false, nullptr, "", achievementCommandTable }, }; return commandTable; } diff --git a/src/server/scripts/Commands/cs_ahbot.cpp b/src/server/scripts/Commands/cs_ahbot.cpp index 33a218fc407..c0d1ee4a8eb 100644 --- a/src/server/scripts/Commands/cs_ahbot.cpp +++ b/src/server/scripts/Commands/cs_ahbot.cpp @@ -16,11 +16,12 @@ */ #include "ScriptMgr.h" +#include "AuctionHouseBot.h" #include "Chat.h" #include "Language.h" -#include "AuctionHouseBot.h" +#include "RBAC.h" -static const uint32 ahbotQualityIds[MAX_AUCTION_QUALITY] = +uint32 const ahbotQualityIds[MAX_AUCTION_QUALITY] = { LANG_AHBOT_QUALITY_GRAY, LANG_AHBOT_QUALITY_WHITE, LANG_AHBOT_QUALITY_GREEN, LANG_AHBOT_QUALITY_BLUE, @@ -57,8 +58,8 @@ public: static std::vector ahbotCommandTable = { - { "items", rbac::RBAC_PERM_COMMAND_AHBOT_ITEMS, true, NULL, "", ahbotItemsAmountCommandTable }, - { "ratio", rbac::RBAC_PERM_COMMAND_AHBOT_RATIO, true, NULL, "", ahbotItemsRatioCommandTable }, + { "items", rbac::RBAC_PERM_COMMAND_AHBOT_ITEMS, true, nullptr, "", ahbotItemsAmountCommandTable }, + { "ratio", rbac::RBAC_PERM_COMMAND_AHBOT_RATIO, true, nullptr, "", ahbotItemsRatioCommandTable }, { "rebuild", rbac::RBAC_PERM_COMMAND_AHBOT_REBUILD, true, &HandleAHBotRebuildCommand, "" }, { "reload", rbac::RBAC_PERM_COMMAND_AHBOT_RELOAD, true, &HandleAHBotReloadCommand, "" }, { "status", rbac::RBAC_PERM_COMMAND_AHBOT_STATUS, true, &HandleAHBotStatusCommand, "" }, @@ -66,13 +67,13 @@ public: static std::vector commandTable = { - { "ahbot", rbac::RBAC_PERM_COMMAND_AHBOT, false, NULL, "", ahbotCommandTable }, + { "ahbot", rbac::RBAC_PERM_COMMAND_AHBOT, false, nullptr, "", ahbotCommandTable }, }; return commandTable; } - static bool HandleAHBotItemsAmountCommand(ChatHandler* handler, const char* args) + static bool HandleAHBotItemsAmountCommand(ChatHandler* handler, char const* args) { uint32 qVals[MAX_AUCTION_QUALITY]; char* arg = strtok((char*)args, " "); @@ -81,7 +82,7 @@ public: if (!arg) return false; qVals[i] = atoi(arg); - arg = strtok(NULL, " "); + arg = strtok(nullptr, " "); } sAuctionBot->SetItemsAmount(qVals); @@ -93,7 +94,7 @@ public: } template - static bool HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, const char* args) + static bool HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, char const* args) { char* arg = strtok((char*)args, " "); if (!arg) @@ -107,7 +108,7 @@ public: return true; } - static bool HandleAHBotItemsRatioCommand(ChatHandler* handler, const char* args) + static bool HandleAHBotItemsRatioCommand(ChatHandler* handler, char const* args) { uint32 rVal[MAX_AUCTION_QUALITY]; char* arg = strtok((char*)args, " "); @@ -116,7 +117,7 @@ public: if (!arg) return false; rVal[i] = atoi(arg); - arg = strtok(NULL, " "); + arg = strtok(nullptr, " "); } sAuctionBot->SetItemsRatio(rVal[0], rVal[1], rVal[2]); @@ -127,7 +128,7 @@ public: } template - static bool HandleAHBotItemsRatioHouseCommand(ChatHandler* handler, const char* args) + static bool HandleAHBotItemsRatioHouseCommand(ChatHandler* handler, char const* args) { char* arg = strtok((char*)args, " "); if (!arg) @@ -139,7 +140,7 @@ public: return true; } - static bool HandleAHBotRebuildCommand(ChatHandler* /*handler*/, const char* args) + static bool HandleAHBotRebuildCommand(ChatHandler* /*handler*/, char const* args) { char* arg = strtok((char*)args, " "); @@ -151,14 +152,14 @@ public: return true; } - static bool HandleAHBotReloadCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleAHBotReloadCommand(ChatHandler* handler, char const* /*args*/) { sAuctionBot->ReloadAllConfig(); handler->SendSysMessage(LANG_AHBOT_RELOAD_OK); return true; } - static bool HandleAHBotStatusCommand(ChatHandler* handler, const char* args) + static bool HandleAHBotStatusCommand(ChatHandler* handler, char const* args) { char* arg = strtok((char*)args, " "); if (!arg) @@ -227,17 +228,17 @@ public: }; -template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, const char*); -template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, const char*); -template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, const char*); -template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, const char*); -template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, const char*); -template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, const char*); -template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, const char*); +template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, char const*); +template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, char const*); +template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, char const*); +template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, char const*); +template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, char const*); +template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, char const*); +template bool ahbot_commandscript::HandleAHBotItemsAmountQualityCommand(ChatHandler* handler, char const*); -template bool ahbot_commandscript::HandleAHBotItemsRatioHouseCommand(ChatHandler* handler, const char*); -template bool ahbot_commandscript::HandleAHBotItemsRatioHouseCommand(ChatHandler* handler, const char*); -template bool ahbot_commandscript::HandleAHBotItemsRatioHouseCommand(ChatHandler* handler, const char*); +template bool ahbot_commandscript::HandleAHBotItemsRatioHouseCommand(ChatHandler* handler, char const*); +template bool ahbot_commandscript::HandleAHBotItemsRatioHouseCommand(ChatHandler* handler, char const*); +template bool ahbot_commandscript::HandleAHBotItemsRatioHouseCommand(ChatHandler* handler, char const*); void AddSC_ahbot_commandscript() { diff --git a/src/server/scripts/Commands/cs_arena.cpp b/src/server/scripts/Commands/cs_arena.cpp index 813f7cd67fa..a1d3b21dc6e 100644 --- a/src/server/scripts/Commands/cs_arena.cpp +++ b/src/server/scripts/Commands/cs_arena.cpp @@ -22,13 +22,16 @@ Comment: All arena team related commands Category: commandscripts EndScriptData */ -#include "ObjectMgr.h" +#include "ScriptMgr.h" +#include "ArenaTeamMgr.h" +#include "CharacterCache.h" #include "Chat.h" #include "Language.h" -#include "ArenaTeamMgr.h" +#include "Log.h" +#include "ObjectMgr.h" #include "Player.h" -#include "ScriptMgr.h" -#include "CharacterCache.h" +#include "RBAC.h" +#include "WorldSession.h" class arena_commandscript : public CommandScript { @@ -48,7 +51,7 @@ public: }; static std::vector commandTable = { - { "arena", rbac::RBAC_PERM_COMMAND_ARENA, false, NULL, "", arenaCommandTable }, + { "arena", rbac::RBAC_PERM_COMMAND_ARENA, false, nullptr, "", arenaCommandTable }, }; return commandTable; } @@ -59,10 +62,10 @@ public: return false; Player* target; - if (!handler->extractPlayerTarget(*args != '"' ? (char*)args : NULL, &target)) + if (!handler->extractPlayerTarget(*args != '"' ? (char*)args : nullptr, &target)) return false; - char* tailStr = *args != '"' ? strtok(NULL, "") : (char*)args; + char* tailStr = *args != '"' ? strtok(nullptr, "") : (char*)args; if (!tailStr) return false; @@ -70,7 +73,7 @@ public: if (!name) return false; - char* typeStr = strtok(NULL, ""); + char* typeStr = strtok(nullptr, ""); if (!typeStr) return false; @@ -168,7 +171,7 @@ public: return false; } - char const* newArenaStr = handler->extractQuotedArg(strtok(NULL, "")); + char const* newArenaStr = handler->extractQuotedArg(strtok(nullptr, "")); if (!newArenaStr) { handler->SendSysMessage(LANG_BAD_VALUE); diff --git a/src/server/scripts/Commands/cs_ban.cpp b/src/server/scripts/Commands/cs_ban.cpp index 671f07af84a..6e5f5e12637 100644 --- a/src/server/scripts/Commands/cs_ban.cpp +++ b/src/server/scripts/Commands/cs_ban.cpp @@ -22,14 +22,18 @@ Comment: All ban related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "AccountMgr.h" #include "CharacterCache.h" #include "Chat.h" +#include "DatabaseEnv.h" #include "Language.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Player.h" -#include "ScriptMgr.h" +#include "RBAC.h" +#include "World.h" +#include "WorldSession.h" class ban_commandscript : public CommandScript { @@ -66,10 +70,10 @@ public: }; static std::vector commandTable = { - { "ban", rbac::RBAC_PERM_COMMAND_BAN, true, NULL, "", banCommandTable }, - { "baninfo", rbac::RBAC_PERM_COMMAND_BANINFO, true, NULL, "", baninfoCommandTable }, - { "banlist", rbac::RBAC_PERM_COMMAND_BANLIST, true, NULL, "", banlistCommandTable }, - { "unban", rbac::RBAC_PERM_COMMAND_UNBAN, true, NULL, "", unbanCommandTable }, + { "ban", rbac::RBAC_PERM_COMMAND_BAN, true, nullptr, "", banCommandTable }, + { "baninfo", rbac::RBAC_PERM_COMMAND_BANINFO, true, nullptr, "", baninfoCommandTable }, + { "banlist", rbac::RBAC_PERM_COMMAND_BANLIST, true, nullptr, "", banlistCommandTable }, + { "unban", rbac::RBAC_PERM_COMMAND_UNBAN, true, nullptr, "", unbanCommandTable }, }; return commandTable; } @@ -90,11 +94,11 @@ public: std::string name = nameStr; - char* durationStr = strtok(NULL, " "); + char* durationStr = strtok(nullptr, " "); if (!durationStr || !atoi(durationStr)) return false; - char* reasonStr = strtok(NULL, ""); + char* reasonStr = strtok(nullptr, ""); if (!reasonStr) return false; @@ -161,11 +165,11 @@ public: std::string nameOrIP = cnameOrIP; - char* durationStr = strtok(NULL, " "); + char* durationStr = strtok(nullptr, " "); if (!durationStr || !atoi(durationStr)) return false; - char* reasonStr = strtok(NULL, ""); + char* reasonStr = strtok(nullptr, ""); if (!reasonStr) return false; @@ -281,7 +285,7 @@ public: time_t unbanDate = time_t(fields[3].GetUInt32()); bool active = false; - if (fields[2].GetBool() && (fields[1].GetUInt64() == uint64(0) || unbanDate >= time(NULL))) + if (fields[2].GetBool() && (fields[1].GetUInt64() == uint64(0) || unbanDate >= time(nullptr))) active = true; bool permanent = (fields[1].GetUInt64() == uint64(0)); std::string banTime = permanent ? handler->GetTrinityString(LANG_BANINFO_INFINITE) : secsToTimeString(fields[1].GetUInt64(), true); @@ -339,7 +343,7 @@ public: Field* fields = result->Fetch(); time_t unbanDate = time_t(fields[3].GetUInt32()); bool active = false; - if (fields[2].GetUInt8() && (!fields[1].GetUInt32() || unbanDate >= time(NULL))) + if (fields[2].GetUInt8() && (!fields[1].GetUInt32() || unbanDate >= time(nullptr))) active = true; bool permanent = (fields[1].GetUInt32() == uint32(0)); std::string banTime = permanent ? handler->GetTrinityString(LANG_BANINFO_INFINITE) : secsToTimeString(fields[1].GetUInt32(), true); @@ -385,7 +389,7 @@ public: static bool HandleBanListAccountCommand(ChatHandler* handler, char const* args) { - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; stmt = LoginDatabase.GetPreparedStatement(LOGIN_DEL_EXPIRED_IP_BANS); LoginDatabase.Execute(stmt); diff --git a/src/server/scripts/Commands/cs_battlenet_account.cpp b/src/server/scripts/Commands/cs_battlenet_account.cpp index b0e39c72393..87b76c68c58 100644 --- a/src/server/scripts/Commands/cs_battlenet_account.cpp +++ b/src/server/scripts/Commands/cs_battlenet_account.cpp @@ -15,12 +15,16 @@ * with this program. If not, see . */ -#include "BattlenetAccountMgr.h" -#include "AccountMgr.h" -#include "Chat.h" -#include "Language.h" -#include "Player.h" #include "ScriptMgr.h" +#include "AccountMgr.h" +#include "BattlenetAccountMgr.h" +#include "Chat.h" +#include "DatabaseEnv.h" +#include "Language.h" +#include "Log.h" +#include "Player.h" +#include "RBAC.h" +#include "WorldSession.h" class battlenet_account_commandscript : public CommandScript { @@ -43,14 +47,14 @@ public: static std::vector accountCommandTable = { { "create", rbac::RBAC_PERM_COMMAND_BNET_ACCOUNT_CREATE, true, &HandleAccountCreateCommand, "" }, - { "lock", rbac::RBAC_PERM_COMMAND_BNET_ACCOUNT, false, NULL, "", accountLockCommandTable }, - { "set", rbac::RBAC_PERM_COMMAND_BNET_ACCOUNT_SET, true, NULL, "", accountSetCommandTable }, + { "lock", rbac::RBAC_PERM_COMMAND_BNET_ACCOUNT, false, nullptr, "", accountLockCommandTable }, + { "set", rbac::RBAC_PERM_COMMAND_BNET_ACCOUNT_SET, true, nullptr, "", accountSetCommandTable }, { "password", rbac::RBAC_PERM_COMMAND_BNET_ACCOUNT_PASSWORD, false, &HandleAccountPasswordCommand, "" }, }; static std::vector commandTable = { - { "battlenetaccount", rbac::RBAC_PERM_COMMAND_BNET_ACCOUNT, true, NULL, "", accountCommandTable }, + { "battlenetaccount", rbac::RBAC_PERM_COMMAND_BNET_ACCOUNT, true, nullptr, "", accountCommandTable }, }; return commandTable; @@ -66,7 +70,7 @@ public: ///- %Parse the command line arguments char* accountName = strtok((char*)args, " "); - char* password = strtok(NULL, " "); + char* password = strtok(nullptr, " "); if (!accountName || !password) return false; @@ -210,8 +214,8 @@ public: // Command is supposed to be: .account password [$oldpassword] [$newpassword] [$newpasswordconfirmation] [$emailconfirmation] char* oldPassword = strtok((char*)args, " "); // This extracts [$oldpassword] - char* newPassword = strtok(NULL, " "); // This extracts [$newpassword] - char* passwordConfirmation = strtok(NULL, " "); // This extracts [$newpasswordconfirmation] + char* newPassword = strtok(nullptr, " "); // This extracts [$newpassword] + char* passwordConfirmation = strtok(nullptr, " "); // This extracts [$newpasswordconfirmation] //Is any of those variables missing for any reason ? We return false. if (!oldPassword || !newPassword || !passwordConfirmation) @@ -275,8 +279,8 @@ public: ///- Get the command line arguments char* account = strtok((char*)args, " "); - char* password = strtok(NULL, " "); - char* passwordConfirmation = strtok(NULL, " "); + char* password = strtok(nullptr, " "); + char* passwordConfirmation = strtok(nullptr, " "); if (!account || !password || !passwordConfirmation) return false; diff --git a/src/server/scripts/Commands/cs_bf.cpp b/src/server/scripts/Commands/cs_bf.cpp index 90e21792f81..299aed49626 100644 --- a/src/server/scripts/Commands/cs_bf.cpp +++ b/src/server/scripts/Commands/cs_bf.cpp @@ -23,8 +23,9 @@ Category: commandscripts EndScriptData */ #include "ScriptMgr.h" -#include "Chat.h" #include "BattlefieldMgr.h" +#include "Chat.h" +#include "RBAC.h" class bf_commandscript : public CommandScript { @@ -43,12 +44,12 @@ public: }; static std::vector commandTable = { - { "bf", rbac::RBAC_PERM_COMMAND_BF, false, NULL, "", battlefieldcommandTable }, + { "bf", rbac::RBAC_PERM_COMMAND_BF, false, nullptr, "", battlefieldcommandTable }, }; return commandTable; } - static bool HandleBattlefieldStart(ChatHandler* handler, const char* args) + static bool HandleBattlefieldStart(ChatHandler* handler, char const* args) { uint32 battleid = 0; char* battleid_str = strtok((char*)args, " "); @@ -70,7 +71,7 @@ public: return true; } - static bool HandleBattlefieldEnd(ChatHandler* handler, const char* args) + static bool HandleBattlefieldEnd(ChatHandler* handler, char const* args) { uint32 battleid = 0; char* battleid_str = strtok((char*)args, " "); @@ -92,7 +93,7 @@ public: return true; } - static bool HandleBattlefieldEnable(ChatHandler* handler, const char* args) + static bool HandleBattlefieldEnable(ChatHandler* handler, char const* args) { uint32 battleid = 0; char* battleid_str = strtok((char*)args, " "); @@ -122,7 +123,7 @@ public: return true; } - static bool HandleBattlefieldSwitch(ChatHandler* handler, const char* args) + static bool HandleBattlefieldSwitch(ChatHandler* handler, char const* args) { uint32 battleid = 0; char* battleid_str = strtok((char*)args, " "); @@ -143,14 +144,14 @@ public: return true; } - static bool HandleBattlefieldTimer(ChatHandler* handler, const char* args) + static bool HandleBattlefieldTimer(ChatHandler* handler, char const* args) { uint32 battleid = 0; uint32 time = 0; char* battleid_str = strtok((char*)args, " "); if (!battleid_str) return false; - char* time_str = strtok(NULL, " "); + char* time_str = strtok(nullptr, " "); if (!time_str) return false; diff --git a/src/server/scripts/Commands/cs_cast.cpp b/src/server/scripts/Commands/cs_cast.cpp index 1f38d8c00f5..5af66b6c0ae 100644 --- a/src/server/scripts/Commands/cs_cast.cpp +++ b/src/server/scripts/Commands/cs_cast.cpp @@ -27,6 +27,9 @@ EndScriptData */ #include "Creature.h" #include "Language.h" #include "Player.h" +#include "RBAC.h" +#include "SpellMgr.h" +#include "WorldSession.h" class cast_commandscript : public CommandScript { @@ -46,7 +49,7 @@ public: }; static std::vector commandTable = { - { "cast", rbac::RBAC_PERM_COMMAND_CAST, false, NULL, "", castCommandTable }, + { "cast", rbac::RBAC_PERM_COMMAND_CAST, false, nullptr, "", castCommandTable }, }; return commandTable; } @@ -91,7 +94,7 @@ public: if (!CheckSpellExistsAndIsValid(handler, spellId)) return false; - char* triggeredStr = strtok(NULL, " "); + char* triggeredStr = strtok(nullptr, " "); if (triggeredStr) { int l = strlen(triggeredStr); @@ -99,7 +102,7 @@ public: return false; } - TriggerCastFlags triggered = (triggeredStr != NULL) ? TRIGGERED_FULL_DEBUG_MASK : TRIGGERED_NONE; + TriggerCastFlags triggered = (triggeredStr != nullptr) ? TRIGGERED_FULL_DEBUG_MASK : TRIGGERED_NONE; handler->GetSession()->GetPlayer()->CastSpell(target, spellId, triggered); return true; @@ -123,7 +126,7 @@ public: if (!CheckSpellExistsAndIsValid(handler, spellId)) return false; - char* triggeredStr = strtok(NULL, " "); + char* triggeredStr = strtok(nullptr, " "); if (triggeredStr) { int l = strlen(triggeredStr); @@ -131,7 +134,7 @@ public: return false; } - TriggerCastFlags triggered = (triggeredStr != NULL) ? TRIGGERED_FULL_DEBUG_MASK : TRIGGERED_NONE; + TriggerCastFlags triggered = (triggeredStr != nullptr) ? TRIGGERED_FULL_DEBUG_MASK : TRIGGERED_NONE; caster->CastSpell(handler->GetSession()->GetPlayer(), spellId, triggered); return true; @@ -150,14 +153,14 @@ public: if (!CheckSpellExistsAndIsValid(handler, spellId)) return false; - char* distStr = strtok(NULL, " "); + char* distStr = strtok(nullptr, " "); float dist = 0; if (distStr) sscanf(distStr, "%f", &dist); - char* triggeredStr = strtok(NULL, " "); + char* triggeredStr = strtok(nullptr, " "); if (triggeredStr) { int l = strlen(triggeredStr); @@ -165,7 +168,7 @@ public: return false; } - TriggerCastFlags triggered = (triggeredStr != NULL) ? TRIGGERED_FULL_DEBUG_MASK : TRIGGERED_NONE; + TriggerCastFlags triggered = (triggeredStr != nullptr) ? TRIGGERED_FULL_DEBUG_MASK : TRIGGERED_NONE; float x, y, z; handler->GetSession()->GetPlayer()->GetClosePoint(x, y, z, dist); @@ -219,7 +222,7 @@ public: if (!CheckSpellExistsAndIsValid(handler, spellId)) return false; - char* triggeredStr = strtok(NULL, " "); + char* triggeredStr = strtok(nullptr, " "); if (triggeredStr) { int l = strlen(triggeredStr); @@ -227,7 +230,7 @@ public: return false; } - TriggerCastFlags triggered = (triggeredStr != NULL) ? TRIGGERED_FULL_DEBUG_MASK : TRIGGERED_NONE; + TriggerCastFlags triggered = (triggeredStr != nullptr) ? TRIGGERED_FULL_DEBUG_MASK : TRIGGERED_NONE; caster->CastSpell(caster->GetVictim(), spellId, triggered); return true; @@ -251,9 +254,9 @@ public: if (!CheckSpellExistsAndIsValid(handler, spellId)) return false; - char* posX = strtok(NULL, " "); - char* posY = strtok(NULL, " "); - char* posZ = strtok(NULL, " "); + char* posX = strtok(nullptr, " "); + char* posY = strtok(nullptr, " "); + char* posZ = strtok(nullptr, " "); if (!posX || !posY || !posZ) return false; @@ -262,7 +265,7 @@ public: float y = float(atof(posY)); float z = float(atof(posZ)); - char* triggeredStr = strtok(NULL, " "); + char* triggeredStr = strtok(nullptr, " "); if (triggeredStr) { int l = strlen(triggeredStr); @@ -270,7 +273,7 @@ public: return false; } - TriggerCastFlags triggered = (triggeredStr != NULL) ? TRIGGERED_FULL_DEBUG_MASK : TRIGGERED_NONE; + TriggerCastFlags triggered = (triggeredStr != nullptr) ? TRIGGERED_FULL_DEBUG_MASK : TRIGGERED_NONE; caster->CastSpell(x, y, z, spellId, triggered); return true; diff --git a/src/server/scripts/Commands/cs_character.cpp b/src/server/scripts/Commands/cs_character.cpp index aea4d48a81c..bd5f9ea041a 100644 --- a/src/server/scripts/Commands/cs_character.cpp +++ b/src/server/scripts/Commands/cs_character.cpp @@ -22,14 +22,21 @@ Comment: All character related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "AccountMgr.h" #include "CharacterCache.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "Log.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" -#include "PlayerDump.h" #include "Player.h" +#include "PlayerDump.h" +#include "RBAC.h" #include "ReputationMgr.h" -#include "ScriptMgr.h" +#include "World.h" +#include "WorldSession.h" class character_commandscript : public CommandScript { @@ -57,7 +64,7 @@ public: { "changefaction", rbac::RBAC_PERM_COMMAND_CHARACTER_CHANGEFACTION, true, &HandleCharacterChangeFactionCommand, "", }, { "changerace", rbac::RBAC_PERM_COMMAND_CHARACTER_CHANGERACE, true, &HandleCharacterChangeRaceCommand, "", }, { "changeaccount", rbac::RBAC_PERM_COMMAND_CHARACTER_CHANGEACCOUNT, true, &HandleCharacterChangeAccountCommand, "", }, - { "deleted", rbac::RBAC_PERM_COMMAND_CHARACTER_DELETED, true, NULL, "", characterDeletedCommandTable }, + { "deleted", rbac::RBAC_PERM_COMMAND_CHARACTER_DELETED, true, nullptr, "", characterDeletedCommandTable }, { "erase", rbac::RBAC_PERM_COMMAND_CHARACTER_ERASE, true, &HandleCharacterEraseCommand, "", }, { "level", rbac::RBAC_PERM_COMMAND_CHARACTER_LEVEL, true, &HandleCharacterLevelCommand, "", }, { "rename", rbac::RBAC_PERM_COMMAND_CHARACTER_RENAME, true, &HandleCharacterRenameCommand, "", }, @@ -67,9 +74,9 @@ public: static std::vector commandTable = { - { "character", rbac::RBAC_PERM_COMMAND_CHARACTER, true, NULL, "", characterCommandTable }, + { "character", rbac::RBAC_PERM_COMMAND_CHARACTER, true, nullptr, "", characterCommandTable }, { "levelup", rbac::RBAC_PERM_COMMAND_LEVELUP, false, &HandleLevelUpCommand, "" }, - { "pdump", rbac::RBAC_PERM_COMMAND_PDUMP, true, NULL, "", pdumpCommandTable }, + { "pdump", rbac::RBAC_PERM_COMMAND_PDUMP, true, nullptr, "", pdumpCommandTable }, }; return commandTable; } @@ -269,11 +276,9 @@ public: char const* knownStr = handler->GetTrinityString(LANG_KNOWN); // Search in CharTitles.dbc - for (uint32 id = 0; id < sCharTitlesStore.GetNumRows(); id++) + for (CharTitlesEntry const* titleInfo : sCharTitlesStore) { - CharTitlesEntry const* titleInfo = sCharTitlesStore.LookupEntry(id); - - if (titleInfo && target->HasTitle(titleInfo)) + if (target->HasTitle(titleInfo)) { std::string name = target->getGender() == GENDER_MALE ? titleInfo->nameMale : titleInfo->nameFemale; if (name.empty()) @@ -288,9 +293,9 @@ public: // send title in "id (idx:idx) - [namedlink locale]" format if (handler->GetSession()) - handler->PSendSysMessage(LANG_TITLE_LIST_CHAT, id, titleInfo->bit_index, id, titleNameStr, localeNames[loc], knownStr, activeStr); + handler->PSendSysMessage(LANG_TITLE_LIST_CHAT, titleInfo->ID, titleInfo->bit_index, titleInfo->ID, titleNameStr, localeNames[loc], knownStr, activeStr); else - handler->PSendSysMessage(LANG_TITLE_LIST_CONSOLE, id, titleInfo->bit_index, name.c_str(), localeNames[loc], knownStr, activeStr); + handler->PSendSysMessage(LANG_TITLE_LIST_CONSOLE, titleInfo->ID, titleInfo->bit_index, name.c_str(), localeNames[loc], knownStr, activeStr); } } @@ -306,7 +311,7 @@ public: if (!handler->extractPlayerTarget((char*)args, &target, &targetGuid, &targetName)) return false; - char const* newNameStr = strtok(NULL, " "); + char const* newNameStr = strtok(nullptr, " "); if (newNameStr) { @@ -324,7 +329,7 @@ public: else { // check offline security - if (handler->HasLowerSecurity(NULL, targetGuid)) + if (handler->HasLowerSecurity(nullptr, targetGuid)) return false; sCharacterCache->GetCharacterNameByGuid(targetGuid, playerOldName); @@ -410,7 +415,7 @@ public: else { // check offline security - if (handler->HasLowerSecurity(NULL, targetGuid)) + if (handler->HasLowerSecurity(nullptr, targetGuid)) return false; std::string oldNameLink = handler->playerLink(targetName); @@ -457,7 +462,7 @@ public: newlevel = STRONG_MAX_LEVEL; HandleCharacterLevel(target, targetGuid, oldlevel, newlevel, handler); - if (!handler->GetSession() || handler->GetSession()->GetPlayer() != target) // including player == NULL + if (!handler->GetSession() || handler->GetSession()->GetPlayer() != target) // including player == nullptr { std::string nameLink = handler->playerLink(targetName); handler->PSendSysMessage(LANG_YOU_CHANGE_LVL, nameLink.c_str(), newlevel); @@ -892,7 +897,7 @@ public: if (levelStr && isalpha(levelStr[0])) { nameStr = levelStr; - levelStr = NULL; // current level will be used + levelStr = nullptr; // current level will be used } Player* target; @@ -913,7 +918,7 @@ public: HandleCharacterLevel(target, targetGuid, oldlevel, newlevel, handler); - if (!handler->GetSession() || handler->GetSession()->GetPlayer() != target) // including chr == NULL + if (!handler->GetSession() || handler->GetSession()->GetPlayer() != target) // including chr == nullptr { std::string nameLink = handler->playerLink(targetName); handler->PSendSysMessage(LANG_YOU_CHANGE_LVL, nameLink.c_str(), newlevel); @@ -931,7 +936,7 @@ public: if (!fileStr) return false; - char* accountStr = strtok(NULL, " "); + char* accountStr = strtok(nullptr, " "); if (!accountStr) return false; @@ -962,8 +967,8 @@ public: return false; } - char* guidStr = NULL; - char* nameStr = strtok(NULL, " "); + char* guidStr = nullptr; + char* nameStr = strtok(nullptr, " "); std::string name; if (nameStr) @@ -984,7 +989,7 @@ public: return false; } - guidStr = strtok(NULL, " "); + guidStr = strtok(nullptr, " "); } ObjectGuid::LowType guid = 0; @@ -1039,7 +1044,7 @@ public: return false; char* fileStr = strtok((char*)args, " "); - char* playerStr = strtok(NULL, " "); + char* playerStr = strtok(nullptr, " "); if (!fileStr || !playerStr) return false; diff --git a/src/server/scripts/Commands/cs_cheat.cpp b/src/server/scripts/Commands/cs_cheat.cpp index 19522709fc5..9901d10a2d8 100644 --- a/src/server/scripts/Commands/cs_cheat.cpp +++ b/src/server/scripts/Commands/cs_cheat.cpp @@ -22,10 +22,12 @@ Comment: All cheat related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "Chat.h" #include "Language.h" #include "Player.h" -#include "ScriptMgr.h" +#include "RBAC.h" +#include "WorldSession.h" class cheat_commandscript : public CommandScript { @@ -49,12 +51,12 @@ public: static std::vector commandTable = { - { "cheat", rbac::RBAC_PERM_COMMAND_CHEAT, false, NULL, "", cheatCommandTable }, + { "cheat", rbac::RBAC_PERM_COMMAND_CHEAT, false, nullptr, "", cheatCommandTable }, }; return commandTable; } - static bool HandleGodModeCheatCommand(ChatHandler* handler, const char* args) + static bool HandleGodModeCheatCommand(ChatHandler* handler, char const* args) { std::string argstr = (char*)args; @@ -77,7 +79,7 @@ public: return false; } - static bool HandleCasttimeCheatCommand(ChatHandler* handler, const char* args) + static bool HandleCasttimeCheatCommand(ChatHandler* handler, char const* args) { std::string argstr = (char*)args; @@ -100,7 +102,7 @@ public: return false; } - static bool HandleCoolDownCheatCommand(ChatHandler* handler, const char* args) + static bool HandleCoolDownCheatCommand(ChatHandler* handler, char const* args) { std::string argstr = (char*)args; @@ -123,7 +125,7 @@ public: return false; } - static bool HandlePowerCheatCommand(ChatHandler* handler, const char* args) + static bool HandlePowerCheatCommand(ChatHandler* handler, char const* args) { std::string argstr = (char*)args; @@ -146,12 +148,12 @@ public: return false; } - static bool HandleCheatStatusCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleCheatStatusCommand(ChatHandler* handler, char const* /*args*/) { Player* player = handler->GetSession()->GetPlayer(); - const char* enabled = "ON"; - const char* disabled = "OFF"; + char const* enabled = "ON"; + char const* disabled = "OFF"; handler->SendSysMessage(LANG_COMMAND_CHEAT_STATUS); handler->PSendSysMessage(LANG_COMMAND_CHEAT_GOD, player->GetCommandStatus(CHEAT_GOD) ? enabled : disabled); @@ -164,7 +166,7 @@ public: return true; } - static bool HandleWaterWalkCheatCommand(ChatHandler* handler, const char* args) + static bool HandleWaterWalkCheatCommand(ChatHandler* handler, char const* args) { std::string argstr = (char*)args; @@ -190,7 +192,7 @@ public: return false; } - static bool HandleTaxiCheatCommand(ChatHandler* handler, const char* args) + static bool HandleTaxiCheatCommand(ChatHandler* handler, char const* args) { std::string argstr = (char*)args; Player* chr = handler->getSelectedPlayer(); diff --git a/src/server/scripts/Commands/cs_debug.cpp b/src/server/scripts/Commands/cs_debug.cpp index c5743927072..d13c0274b2c 100644 --- a/src/server/scripts/Commands/cs_debug.cpp +++ b/src/server/scripts/Commands/cs_debug.cpp @@ -23,20 +23,22 @@ Category: commandscripts EndScriptData */ #include "ScriptMgr.h" -#include "ObjectMgr.h" -#include "PhasingHandler.h" +#include "Bag.h" #include "BattlefieldMgr.h" #include "BattlegroundMgr.h" -#include "Chat.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" +#include "Chat.h" #include "GossipDef.h" -#include "Transport.h" +#include "GridNotifiersImpl.h" #include "Language.h" +#include "Log.h" #include "MapManager.h" - +#include "M2Stores.h" +#include "ObjectMgr.h" +#include "PhasingHandler.h" +#include "RBAC.h" +#include "Transport.h" +#include "WorldSession.h" #include #include @@ -122,7 +124,9 @@ public: } uint32 cinematicId = atoul(args); - if (!sCinematicSequencesStore.LookupEntry(cinematicId)) + + CinematicSequencesEntry const* cineSeq = sCinematicSequencesStore.LookupEntry(cinematicId); + if (!cineSeq) { handler->PSendSysMessage(LANG_CINEMATIC_NOT_EXIST, cinematicId); handler->SetSentErrorMessage(true); @@ -130,20 +134,16 @@ public: } // Dump camera locations - if (CinematicSequencesEntry const* cineSeq = sCinematicSequencesStore.LookupEntry(cinematicId)) + if (std::vector const* flyByCameras = GetFlyByCameras(cineSeq->cinematicCamera)) { - std::unordered_map::const_iterator itr = sFlyByCameraStore.find(cineSeq->cinematicCamera); - if (itr != sFlyByCameraStore.end()) + handler->PSendSysMessage("Waypoints for sequence %u, camera %u", cinematicId, cineSeq->cinematicCamera); + uint32 count = 1; + for (FlyByCamera const& cam : *flyByCameras) { - handler->PSendSysMessage("Waypoints for sequence %u, camera %u", cinematicId, 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->PSendSysMessage("%02u - %7ums [%s (%f degrees)]", count, cam.timeStamp, cam.locations.ToString().c_str(), cam.locations.GetOrientation() * (180 / M_PI)); + ++count; } + handler->PSendSysMessage("%u waypoints dumped", flyByCameras->size()); } handler->GetSession()->GetPlayer()->SendCinematicStart(cinematicId); @@ -251,10 +251,10 @@ public: if (failNum == 0 && *result != '0') return false; - char* fail1 = strtok(NULL, " "); + char* fail1 = strtok(nullptr, " "); uint8 failArg1 = fail1 ? (uint8)atoi(fail1) : 0; - char* fail2 = strtok(NULL, " "); + char* fail2 = strtok(nullptr, " "); uint8 failArg2 = fail2 ? (uint8)atoi(fail2) : 0; WorldPacket data(SMSG_CAST_FAILED, 5); @@ -267,7 +267,6 @@ public: data << uint32(failArg2); handler->GetSession()->SendPacket(&data); - return true; } @@ -277,7 +276,7 @@ public: return false; InventoryResult msg = InventoryResult(atoi(args)); - handler->GetSession()->GetPlayer()->SendEquipError(msg, NULL, NULL); + handler->GetSession()->GetPlayer()->SendEquipError(msg, nullptr, nullptr); return true; } @@ -304,7 +303,7 @@ public: static bool HandleDebugSendOpcodeCommand(ChatHandler* handler, char const* /*args*/) { Unit* unit = handler->getSelectedUnit(); - Player* player = NULL; + Player* player = nullptr; if (!unit || (unit->GetTypeId() != TYPEID_PLAYER)) player = handler->GetSession()->GetPlayer(); else @@ -475,7 +474,7 @@ public: static bool HandleDebugUpdateWorldStateCommand(ChatHandler* handler, char const* args) { char* w = strtok((char*)args, " "); - char* s = strtok(NULL, " "); + char* s = strtok(nullptr, " "); if (!w || !s) return false; @@ -693,9 +692,9 @@ public: continue; } - if (updateQueue[qp] == NULL) + if (updateQueue[qp] == nullptr) { - handler->PSendSysMessage("The item with slot %d and guid %d has its queuepos (%d) pointing to NULL in the queue!", item->GetSlot(), item->GetGUID().GetCounter(), qp); + handler->PSendSysMessage("The item with slot %d and guid %d has its queuepos (%d) pointing to nullptr in the queue!", item->GetSlot(), item->GetGUID().GetCounter(), qp); error = true; continue; } @@ -761,9 +760,9 @@ public: continue; } - if (updateQueue[qp] == NULL) + if (updateQueue[qp] == nullptr) { - handler->PSendSysMessage("The item in bag %d at slot %d having guid %d has a queuepos (%d) that points to NULL in the queue!", bag->GetSlot(), item2->GetSlot(), item2->GetGUID().GetCounter(), qp); + handler->PSendSysMessage("The item in bag %d at slot %d having guid %d has a queuepos (%d) that points to nullptr in the queue!", bag->GetSlot(), item2->GetSlot(), item2->GetGUID().GetCounter(), qp); error = true; continue; } @@ -810,7 +809,7 @@ public: Item* test = player->GetItemByPos(item->GetBagSlot(), item->GetSlot()); - if (test == NULL) + if (test == nullptr) { handler->PSendSysMessage("queue(%zu): The bag(%d) and slot(%d) values for %s are incorrect, the player doesn't have any item at that position!", i, item->GetBagSlot(), item->GetSlot(), item->GetGUID().ToString().c_str()); error = true; @@ -849,7 +848,7 @@ public: if (!target || target->IsTotem() || target->IsPet()) return false; - ThreatContainer::StorageType const &threatList = target->getThreatManager().getThreatList(); + ThreatContainer::StorageType const& threatList = target->getThreatManager().getThreatList(); ThreatContainer::StorageType::const_iterator itr; uint32 count = 0; handler->PSendSysMessage("Threat list of %s (guid %u)", target->GetName().c_str(), target->GetGUID().GetCounter()); @@ -918,7 +917,7 @@ public: if (!i) return false; - char* j = strtok(NULL, " "); + char* j = strtok(nullptr, " "); uint32 entry = (uint32)atoi(i); int8 seatId = j ? (int8)atoi(j) : -1; @@ -927,7 +926,7 @@ public: handler->GetSession()->GetPlayer()->EnterVehicle(target, seatId); else { - Creature* passenger = NULL; + Creature* passenger = nullptr; Trinity::AllCreaturesOfEntryInRange check(handler->GetSession()->GetPlayer(), entry, 20.0f); Trinity::CreatureSearcher searcher(handler->GetSession()->GetPlayer(), passenger, check); Cell::VisitAllObjects(handler->GetSession()->GetPlayer(), searcher, 30.0f); @@ -946,7 +945,7 @@ public: return false; char* e = strtok((char*)args, " "); - char* i = strtok(NULL, " "); + char* i = strtok(nullptr, " "); if (!e) return false; @@ -989,7 +988,7 @@ public: static bool HandleDebugSendLargePacketCommand(ChatHandler* handler, char const* /*args*/) { - const char* stuffingString = "This is a dummy string to push the packet's size beyond 128000 bytes. "; + char const* stuffingString = "This is a dummy string to push the packet's size beyond 128000 bytes. "; std::ostringstream ss; while (ss.str().size() < 128000) ss << stuffingString; @@ -1003,8 +1002,8 @@ public: return false; char* t = strtok((char*)args, " "); - char* p = strtok(NULL, " "); - char* m = strtok(NULL, " "); + char* p = strtok(nullptr, " "); + char* m = strtok(nullptr, " "); if (!t) return false; @@ -1032,7 +1031,7 @@ public: return false; char* e = strtok((char*)args, " "); - char* f = strtok(NULL, " "); + char* f = strtok(nullptr, " "); if (!e || !f) return false; @@ -1061,8 +1060,8 @@ public: return false; char* e = strtok((char*)args, " "); - char* f = strtok(NULL, " "); - char* g = strtok(NULL, " "); + char* f = strtok(nullptr, " "); + char* g = strtok(nullptr, " "); if (!e || !f || !g) return false; @@ -1168,8 +1167,8 @@ public: return false; char* x = strtok((char*)args, " "); - char* y = strtok(NULL, " "); - char* z = strtok(NULL, " "); + char* y = strtok(nullptr, " "); + char* z = strtok(nullptr, " "); if (!x || !y) return false; @@ -1217,7 +1216,7 @@ public: return false; char* x = strtok((char*)args, " "); - char* z = strtok(NULL, " "); + char* z = strtok(nullptr, " "); if (!x) return false; @@ -1263,7 +1262,7 @@ public: return false; char* x = strtok((char*)args, " "); - char* y = strtok(NULL, " "); + char* y = strtok(nullptr, " "); if (!x || !y) return false; @@ -1318,7 +1317,7 @@ public: else if (updateIndex >= UNIT_END) return true; - char* val = strtok(NULL, " "); + char* val = strtok(nullptr, " "); if (!val) { value = unit->GetUInt32Value(updateIndex); @@ -1350,7 +1349,7 @@ public: } char* x = strtok((char*)args, " "); - char* y = strtok(NULL, " "); + char* y = strtok(nullptr, " "); if (!x || !y) return false; @@ -1384,7 +1383,7 @@ public: if (!mask1) return false; - char* mask2 = strtok(NULL, " \n"); + char* mask2 = strtok(nullptr, " \n"); uint32 moveFlags = (uint32)atoi(mask1); target->SetUnitMovementFlags(moveFlags); @@ -1576,13 +1575,13 @@ public: if (stricmp(args, "linked")) { if (Battleground* bg = player->GetBattleground()) - nearestLoc = bg->GetClosestGraveYard(player); + nearestLoc = bg->GetClosestGraveyard(player); else { if (Battlefield* bf = sBattlefieldMgr->GetBattlefieldToZoneId(player->GetZoneId())) - nearestLoc = bf->GetClosestGraveYard(player); + nearestLoc = bf->GetClosestGraveyard(player); else - nearestLoc = sObjectMgr->GetClosestGraveYard(*player, player->GetTeam(), player); + nearestLoc = sObjectMgr->GetClosestGraveyard(*player, player->GetTeam(), player); } } else diff --git a/src/server/scripts/Commands/cs_deserter.cpp b/src/server/scripts/Commands/cs_deserter.cpp index e069e7a5f38..2f1dc515260 100644 --- a/src/server/scripts/Commands/cs_deserter.cpp +++ b/src/server/scripts/Commands/cs_deserter.cpp @@ -22,10 +22,11 @@ * This file contains the CommandScripts for all deserter sub-commands */ -#include "Chat.h" -#include "Player.h" -#include "Language.h" #include "ScriptMgr.h" +#include "Chat.h" +#include "Language.h" +#include "Player.h" +#include "RBAC.h" #include "SpellAuras.h" enum Spells @@ -58,12 +59,12 @@ public: static std::vector deserterCommandTable = { - { "instance", rbac::RBAC_PERM_COMMAND_DESERTER_INSTANCE, false, NULL, "", deserterInstanceCommandTable }, - { "bg", rbac::RBAC_PERM_COMMAND_DESERTER_BG, false, NULL, "", deserterBGCommandTable }, + { "instance", rbac::RBAC_PERM_COMMAND_DESERTER_INSTANCE, false, nullptr, "", deserterInstanceCommandTable }, + { "bg", rbac::RBAC_PERM_COMMAND_DESERTER_BG, false, nullptr, "", deserterBGCommandTable }, }; static std::vector commandTable = { - { "deserter", rbac::RBAC_PERM_COMMAND_DESERTER, false, NULL, "", deserterCommandTable }, + { "deserter", rbac::RBAC_PERM_COMMAND_DESERTER, false, nullptr, "", deserterCommandTable }, }; return commandTable; } diff --git a/src/server/scripts/Commands/cs_disable.cpp b/src/server/scripts/Commands/cs_disable.cpp index f1b5fcde60d..5dc4f8b9566 100644 --- a/src/server/scripts/Commands/cs_disable.cpp +++ b/src/server/scripts/Commands/cs_disable.cpp @@ -22,14 +22,16 @@ Comment: All disable related commands Category: commandscripts EndScriptData */ -#include "DisableMgr.h" +#include "ScriptMgr.h" #include "AchievementMgr.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "DisableMgr.h" #include "Language.h" #include "ObjectMgr.h" #include "OutdoorPvP.h" #include "Player.h" -#include "ScriptMgr.h" +#include "RBAC.h" #include "SpellMgr.h" class disable_commandscript : public CommandScript @@ -63,12 +65,12 @@ public: }; static std::vector disableCommandTable = { - { "add", rbac::RBAC_PERM_COMMAND_DISABLE_ADD, true, NULL, "", addDisableCommandTable }, - { "remove", rbac::RBAC_PERM_COMMAND_DISABLE_REMOVE, true, NULL, "", removeDisableCommandTable }, + { "add", rbac::RBAC_PERM_COMMAND_DISABLE_ADD, true, nullptr, "", addDisableCommandTable }, + { "remove", rbac::RBAC_PERM_COMMAND_DISABLE_REMOVE, true, nullptr, "", removeDisableCommandTable }, }; static std::vector commandTable = { - { "disable", rbac::RBAC_PERM_COMMAND_DISABLE, false, NULL, "", disableCommandTable }, + { "disable", rbac::RBAC_PERM_COMMAND_DISABLE, false, nullptr, "", disableCommandTable }, }; return commandTable; } @@ -79,10 +81,10 @@ public: if (!entryStr || !atoi(entryStr)) return false; - char* flagsStr = strtok(NULL, " "); + char* flagsStr = strtok(nullptr, " "); uint8 flags = flagsStr ? uint8(atoi(flagsStr)) : 0; - char* commentStr = strtok(NULL, ""); + char* commentStr = strtok(nullptr, ""); if (!commentStr) return false; diff --git a/src/server/scripts/Commands/cs_event.cpp b/src/server/scripts/Commands/cs_event.cpp index f5b6eeb1578..c6a32af3367 100644 --- a/src/server/scripts/Commands/cs_event.cpp +++ b/src/server/scripts/Commands/cs_event.cpp @@ -22,11 +22,12 @@ Comment: All event related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "Chat.h" #include "GameEventMgr.h" #include "Language.h" #include "Player.h" -#include "ScriptMgr.h" +#include "RBAC.h" class event_commandscript : public CommandScript { @@ -44,7 +45,7 @@ public: }; static std::vector commandTable = { - { "event", rbac::RBAC_PERM_COMMAND_EVENT, false, NULL, "", eventCommandTable }, + { "event", rbac::RBAC_PERM_COMMAND_EVENT, false, nullptr, "", eventCommandTable }, }; return commandTable; } @@ -115,8 +116,8 @@ public: std::string endTimeStr = TimeToTimestampStr(eventData.end); uint32 delay = sGameEventMgr->NextCheck(eventId); - time_t nextTime = time(NULL) + delay; - std::string nextStr = nextTime >= eventData.start && nextTime < eventData.end ? TimeToTimestampStr(time(NULL) + delay) : "-"; + time_t nextTime = time(nullptr) + delay; + std::string nextStr = nextTime >= eventData.start && nextTime < eventData.end ? TimeToTimestampStr(time(nullptr) + delay) : "-"; std::string occurenceStr = secsToTimeString(eventData.occurence * MINUTE); std::string lengthStr = secsToTimeString(eventData.length * MINUTE); diff --git a/src/server/scripts/Commands/cs_gm.cpp b/src/server/scripts/Commands/cs_gm.cpp index 1aeedff799a..50268dd1a4a 100644 --- a/src/server/scripts/Commands/cs_gm.cpp +++ b/src/server/scripts/Commands/cs_gm.cpp @@ -23,13 +23,19 @@ Category: commandscripts EndScriptData */ #include "ScriptMgr.h" -#include "ObjectMgr.h" -#include "Chat.h" #include "AccountMgr.h" +#include "Chat.h" +#include "DatabaseEnv.h" #include "Language.h" -#include "World.h" -#include "Player.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Opcodes.h" +#include "Player.h" +#include "Realm.h" +#include "World.h" +#include "WorldSession.h" +#include +#include class gm_commandscript : public CommandScript { @@ -49,7 +55,7 @@ public: }; static std::vector commandTable = { - { "gm", rbac::RBAC_PERM_COMMAND_GM, false, NULL, "", gmCommandTable }, + { "gm", rbac::RBAC_PERM_COMMAND_GM, false, nullptr, "", gmCommandTable }, }; return commandTable; } diff --git a/src/server/scripts/Commands/cs_go.cpp b/src/server/scripts/Commands/cs_go.cpp index f5d05e927db..a821dff1043 100644 --- a/src/server/scripts/Commands/cs_go.cpp +++ b/src/server/scripts/Commands/cs_go.cpp @@ -23,14 +23,18 @@ Category: commandscripts EndScriptData */ #include "ScriptMgr.h" +#include "Chat.h" +#include "DatabaseEnv.h" +#include "Language.h" +#include "MapManager.h" +#include "MotionMaster.h" #include "ObjectMgr.h" #include "PhasingHandler.h" -#include "MapManager.h" -#include "TicketMgr.h" -#include "Chat.h" -#include "Language.h" #include "Player.h" +#include "RBAC.h" +#include "TicketMgr.h" #include "Transport.h" +#include "WorldSession.h" class go_commandscript : public CommandScript { @@ -55,7 +59,7 @@ public: static std::vector commandTable = { - { "go", rbac::RBAC_PERM_COMMAND_GO, false, NULL, "", goCommandTable }, + { "go", rbac::RBAC_PERM_COMMAND_GO, false, nullptr, "", goCommandTable }, }; return commandTable; } @@ -90,7 +94,7 @@ public: { // Get the "creature_template.entry" // number or [name] Shift-click form |color|Hcreature_entry:creature_id|h[name]|h|r - char* tail = strtok(NULL, ""); + char* tail = strtok(nullptr, ""); if (!tail) return false; char* id = handler->extractKeyFromLink(tail, "Hcreature_entry"); @@ -112,7 +116,7 @@ public: { std::string name = param1; WorldDatabase.EscapeString(name); - whereClause << ", creature_template WHERE creature.id = creature_template.entry AND creature_template.name " _LIKE_" '" << name << '\''; + whereClause << ", creature_template WHERE creature.id = creature_template.entry AND creature_template.name LIKE '" << name << '\''; } else whereClause << "WHERE guid = '" << guidLow << '\''; @@ -135,7 +139,7 @@ public: float o = fields[3].GetFloat(); uint32 mapId = fields[4].GetUInt16(); - Transport* transport = NULL; + Transport* transport = nullptr; if (!MapManager::IsValidMapCoord(mapId, x, y, z, o) || sObjectMgr->IsTransportMap(mapId)) { @@ -216,8 +220,8 @@ public: Player* player = handler->GetSession()->GetPlayer(); char* gridX = strtok((char*)args, " "); - char* gridY = strtok(NULL, " "); - char* id = strtok(NULL, " "); + char* gridY = strtok(nullptr, " "); + char* id = strtok(nullptr, " "); if (!gridX || !gridY) return false; @@ -408,8 +412,8 @@ public: Player* player = handler->GetSession()->GetPlayer(); char* zoneX = strtok((char*)args, " "); - char* zoneY = strtok(NULL, " "); - char* tail = strtok(NULL, ""); + char* zoneY = strtok(nullptr, " "); + char* tail = strtok(nullptr, ""); char* id = handler->extractKeyFromLink(tail, "Harea"); // string or [name] Shift-click form |color|Harea:area_id|h[name]|h|r @@ -481,10 +485,10 @@ public: Player* player = handler->GetSession()->GetPlayer(); char* goX = strtok((char*)args, " "); - char* goY = strtok(NULL, " "); - char* goZ = strtok(NULL, " "); - char* id = strtok(NULL, " "); - char* port = strtok(NULL, " "); + char* goY = strtok(nullptr, " "); + char* goZ = strtok(nullptr, " "); + char* id = strtok(nullptr, " "); + char* port = strtok(nullptr, " "); if (!goX || !goY) return false; @@ -572,9 +576,9 @@ public: Player* player = handler->GetSession()->GetPlayer(); char* goX = strtok((char*)args, " "); - char* goY = strtok(NULL, " "); - char* goZ = strtok(NULL, " "); - char* port = strtok(NULL, " "); + char* goY = strtok(nullptr, " "); + char* goZ = strtok(nullptr, " "); + char* port = strtok(nullptr, " "); float x, y, z, o; player->GetPosition(x, y, z, o); diff --git a/src/server/scripts/Commands/cs_gobject.cpp b/src/server/scripts/Commands/cs_gobject.cpp index 620b626aa8e..dde2a8001ba 100644 --- a/src/server/scripts/Commands/cs_gobject.cpp +++ b/src/server/scripts/Commands/cs_gobject.cpp @@ -23,15 +23,21 @@ Category: commandscripts EndScriptData */ #include "ScriptMgr.h" -#include "GameEventMgr.h" -#include "ObjectMgr.h" -#include "PoolMgr.h" -#include "MapManager.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "GameEventMgr.h" #include "Language.h" -#include "Player.h" +#include "Log.h" +#include "MapManager.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Opcodes.h" #include "PhasingHandler.h" +#include "Player.h" +#include "PoolMgr.h" +#include "RBAC.h" +#include "WorldSession.h" class gobject_commandscript : public CommandScript { @@ -59,12 +65,12 @@ public: { "near", rbac::RBAC_PERM_COMMAND_GOBJECT_NEAR, false, &HandleGameObjectNearCommand, "" }, { "target", rbac::RBAC_PERM_COMMAND_GOBJECT_TARGET, false, &HandleGameObjectTargetCommand, "" }, { "turn", rbac::RBAC_PERM_COMMAND_GOBJECT_TURN, false, &HandleGameObjectTurnCommand, "" }, - { "add", rbac::RBAC_PERM_COMMAND_GOBJECT_ADD, false, NULL, "", gobjectAddCommandTable }, - { "set", rbac::RBAC_PERM_COMMAND_GOBJECT_SET, false, NULL, "", gobjectSetCommandTable }, + { "add", rbac::RBAC_PERM_COMMAND_GOBJECT_ADD, false, nullptr, "", gobjectAddCommandTable }, + { "set", rbac::RBAC_PERM_COMMAND_GOBJECT_SET, false, nullptr, "", gobjectSetCommandTable }, }; static std::vector commandTable = { - { "gobject", rbac::RBAC_PERM_COMMAND_GOBJECT, false, NULL, "", gobjectCommandTable }, + { "gobject", rbac::RBAC_PERM_COMMAND_GOBJECT, false, nullptr, "", gobjectCommandTable }, }; return commandTable; } @@ -116,9 +122,9 @@ public: if (!objectId) return false; - char* spawntimeSecs = strtok(NULL, " "); + char* spawntimeSecs = strtok(nullptr, " "); - const GameObjectTemplate* objectInfo = sObjectMgr->GetGameObjectTemplate(objectId); + GameObjectTemplate const* objectInfo = sObjectMgr->GetGameObjectTemplate(objectId); if (!objectInfo) { @@ -142,7 +148,7 @@ public: GameObject* object = new GameObject; ObjectGuid::LowType guidLow = map->GenerateLowGuid(); - if (!object->Create(guidLow, objectInfo->entry, map, 0, *player, G3D::Quat(), 255, GO_STATE_READY)) + if (!object->Create(guidLow, objectInfo->entry, map, 0, *player, QuaternionData(), 255, GO_STATE_READY)) { delete object; return false; @@ -191,13 +197,13 @@ public: Player* player = handler->GetSession()->GetPlayer(); - char* spawntime = strtok(NULL, " "); + char* spawntime = strtok(nullptr, " "); uint32 spawntm = 300; if (spawntime) spawntm = atoul(spawntime); - G3D::Quat rotation = G3D::Matrix3::fromEulerAnglesZYX(player->GetOrientation(), 0.f, 0.f); + QuaternionData rotation = QuaternionData::fromEulerAnglesZYX(player->GetOrientation(), 0.f, 0.f); uint32 objectId = atoul(id); if (!sObjectMgr->GetGameObjectTemplate(objectId)) @@ -236,7 +242,7 @@ public: WorldDatabase.EscapeString(name); result = WorldDatabase.PQuery( "SELECT guid, id, position_x, position_y, position_z, orientation, map, phaseMask, (POW(position_x - %f, 2) + POW(position_y - %f, 2) + POW(position_z - %f, 2)) AS order_ " - "FROM gameobject, gameobject_template WHERE gameobject_template.entry = gameobject.id AND map = %i AND name " _LIKE_" " _CONCAT3_("'%%'", "'%s'", "'%%'")" ORDER BY order_ ASC LIMIT 1", + "FROM gameobject LEFT JOIN gameobject_template ON gameobject_template.entry = gameobject.id WHERE map = %i AND name LIKE '%%%s%%' ORDER BY order_ ASC LIMIT 1", player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), player->GetMapId(), name.c_str()); } } @@ -318,7 +324,7 @@ public: if (target) { - int32 curRespawnDelay = int32(target->GetRespawnTimeEx() - time(NULL)); + int32 curRespawnDelay = int32(target->GetRespawnTimeEx() - time(nullptr)); if (curRespawnDelay < 0) curRespawnDelay = 0; @@ -393,18 +399,18 @@ public: return false; } - char* orientation = strtok(NULL, " "); + char* orientation = strtok(nullptr, " "); float oz = 0.f, oy = 0.f, ox = 0.f; if (orientation) { oz = float(atof(orientation)); - orientation = strtok(NULL, " "); + orientation = strtok(nullptr, " "); if (orientation) { oy = float(atof(orientation)); - orientation = strtok(NULL, " "); + orientation = strtok(nullptr, " "); if (orientation) ox = float(atof(orientation)); } @@ -444,9 +450,9 @@ public: return false; } - char* toX = strtok(NULL, " "); - char* toY = strtok(NULL, " "); - char* toZ = strtok(NULL, " "); + char* toX = strtok(nullptr, " "); + char* toY = strtok(nullptr, " "); + char* toZ = strtok(nullptr, " "); float x, y, z; if (!toX) @@ -499,7 +505,7 @@ public: return false; } - char* phase = strtok (NULL, " "); + char* phase = strtok (nullptr, " "); uint32 phaseMask = phase ? atoi(phase) : 0; if (phaseMask == 0) { @@ -581,7 +587,7 @@ public: if (!cValue) return false; ObjectGuid::LowType guidLow = atoul(cValue); - const GameObjectData* data = sObjectMgr->GetGOData(guidLow); + GameObjectData const* data = sObjectMgr->GetGOData(guidLow); if (!data) return false; entry = data->id; @@ -641,7 +647,7 @@ public: return false; } - char* type = strtok(NULL, " "); + char* type = strtok(nullptr, " "); if (!type) return false; @@ -655,7 +661,7 @@ public: return true; } - char* state = strtok(NULL, " "); + char* state = strtok(nullptr, " "); if (!state) return false; diff --git a/src/server/scripts/Commands/cs_group.cpp b/src/server/scripts/Commands/cs_group.cpp index 34114729807..2db18526685 100644 --- a/src/server/scripts/Commands/cs_group.cpp +++ b/src/server/scripts/Commands/cs_group.cpp @@ -15,15 +15,22 @@ * with this program. If not, see . */ +#include "ScriptMgr.h" #include "CharacterCache.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" +#include "GroupMgr.h" #include "Language.h" #include "LFG.h" -#include "Player.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "PhasingHandler.h" -#include "GroupMgr.h" -#include "ScriptMgr.h" +#include "Player.h" +#include "RBAC.h" +#include "WorldSession.h" class group_commandscript : public CommandScript { @@ -180,7 +187,7 @@ public: return true; } - static bool GroupFlagCommand(ChatHandler* handler, char const* args, GroupMemberFlags flag, const char* what) + static bool GroupFlagCommand(ChatHandler* handler, char const* args, GroupMemberFlags flag, char const* what) { Player* player = nullptr; Group* group = nullptr; @@ -293,7 +300,7 @@ public: ObjectGuid guidSource; ObjectGuid guidTarget; char* nameplgrStr = strtok((char*)args, " "); - char* nameplStr = strtok(NULL, " "); + char* nameplStr = strtok(nullptr, " "); if (!handler->GetPlayerGroupAndGUIDByName(nameplgrStr, playerSource, groupSource, guidSource, true)) return false; @@ -335,7 +342,7 @@ public: ObjectGuid guidTarget; std::string nameTarget; std::string zoneName; - const char* onlineState = ""; + char const* onlineState = ""; // Parse the guid to uint32... ObjectGuid parseGUID(HighGuid::Player, uint32(atoul(args))); @@ -351,7 +358,7 @@ public: return false; // Next, we need a group. So we define a group variable. - Group* groupTarget = NULL; + Group* groupTarget = nullptr; // We try to extract a group from an online player. if (playerTarget) diff --git a/src/server/scripts/Commands/cs_guild.cpp b/src/server/scripts/Commands/cs_guild.cpp index 2c7e6f66385..1e35300a1e8 100644 --- a/src/server/scripts/Commands/cs_guild.cpp +++ b/src/server/scripts/Commands/cs_guild.cpp @@ -22,14 +22,16 @@ Comment: All guild related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "AchievementMgr.h" +#include "CharacterCache.h" #include "Chat.h" -#include "Language.h" #include "Guild.h" #include "GuildMgr.h" +#include "Language.h" #include "ObjectAccessor.h" -#include "ScriptMgr.h" -#include "CharacterCache.h" +#include "Player.h" +#include "RBAC.h" #include class guild_commandscript : public CommandScript @@ -51,7 +53,7 @@ public: }; static std::vector commandTable = { - { "guild", rbac::RBAC_PERM_COMMAND_GUILD, true, NULL, "", guildCommandTable }, + { "guild", rbac::RBAC_PERM_COMMAND_GUILD, true, nullptr, "", guildCommandTable }, }; return commandTable; } @@ -71,10 +73,10 @@ public: // if not guild name only (in "") then player name Player* target; - if (!handler->extractPlayerTarget(*args != '"' ? (char*)args : NULL, &target)) + if (!handler->extractPlayerTarget(*args != '"' ? (char*)args : nullptr, &target)) return false; - char* tailStr = *args != '"' ? strtok(NULL, "") : (char*)args; + char* tailStr = *args != '"' ? strtok(nullptr, "") : (char*)args; if (!tailStr) return false; @@ -100,7 +102,6 @@ public: } sGuildMgr->AddGuild(guild); - return true; } @@ -132,10 +133,10 @@ public: // if not guild name only (in "") then player name ObjectGuid targetGuid; - if (!handler->extractPlayerTarget(*args != '"' ? (char*)args : NULL, NULL, &targetGuid)) + if (!handler->extractPlayerTarget(*args != '"' ? (char*)args : nullptr, nullptr, &targetGuid)) return false; - char* tailStr = *args != '"' ? strtok(NULL, "") : (char*)args; + char* tailStr = *args != '"' ? strtok(nullptr, "") : (char*)args; if (!tailStr) return false; @@ -215,7 +216,7 @@ public: return false; } - char const* newGuildStr = handler->extractQuotedArg(strtok(NULL, "")); + char const* newGuildStr = handler->extractQuotedArg(strtok(nullptr, "")); if (!newGuildStr) { handler->SendSysMessage(LANG_INSERT_GUILD_NAME); diff --git a/src/server/scripts/Commands/cs_honor.cpp b/src/server/scripts/Commands/cs_honor.cpp index 23435e88746..e0f7820b504 100644 --- a/src/server/scripts/Commands/cs_honor.cpp +++ b/src/server/scripts/Commands/cs_honor.cpp @@ -22,11 +22,13 @@ Comment: All honor related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "Chat.h" #include "Language.h" #include "ObjectMgr.h" #include "Player.h" -#include "ScriptMgr.h" +#include "RBAC.h" +#include "WorldSession.h" class honor_commandscript : public CommandScript { @@ -43,13 +45,13 @@ public: static std::vector honorCommandTable = { - { "add", rbac::RBAC_PERM_COMMAND_HONOR_ADD, false, NULL, "", honorAddCommandTable }, + { "add", rbac::RBAC_PERM_COMMAND_HONOR_ADD, false, nullptr, "", honorAddCommandTable }, { "update", rbac::RBAC_PERM_COMMAND_HONOR_UPDATE, false, &HandleHonorUpdateCommand, "" }, }; static std::vector commandTable = { - { "honor", rbac::RBAC_PERM_COMMAND_HONOR, false, NULL, "", honorCommandTable }, + { "honor", rbac::RBAC_PERM_COMMAND_HONOR, false, nullptr, "", honorCommandTable }, }; return commandTable; } @@ -72,7 +74,7 @@ public: return false; uint32 amount = (uint32)atoi(args); - target->RewardHonor(NULL, 1, amount); + target->RewardHonor(nullptr, 1, amount); return true; } diff --git a/src/server/scripts/Commands/cs_instance.cpp b/src/server/scripts/Commands/cs_instance.cpp index da577d4affe..dafe76e9dc0 100644 --- a/src/server/scripts/Commands/cs_instance.cpp +++ b/src/server/scripts/Commands/cs_instance.cpp @@ -27,9 +27,13 @@ EndScriptData */ #include "Group.h" #include "InstanceSaveMgr.h" #include "InstanceScript.h" -#include "MapManager.h" -#include "Player.h" #include "Language.h" +#include "MapManager.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "RBAC.h" +#include "WorldSession.h" class instance_commandscript : public CommandScript { @@ -50,7 +54,7 @@ public: static std::vector commandTable = { - { "instance", rbac::RBAC_PERM_COMMAND_INSTANCE, true, NULL, "", instanceCommandTable }, + { "instance", rbac::RBAC_PERM_COMMAND_INSTANCE, true, nullptr, "", instanceCommandTable }, }; return commandTable; @@ -81,7 +85,7 @@ public: for (Player::BoundInstancesMap::const_iterator itr = binds.begin(); itr != binds.end(); ++itr) { InstanceSave* save = itr->second.save; - std::string timeleft = GetTimeString(save->GetResetTime() - time(NULL)); + std::string timeleft = GetTimeString(save->GetResetTime() - time(nullptr)); handler->PSendSysMessage(LANG_COMMAND_LIST_BIND_INFO, itr->first, save->GetInstanceId(), itr->second.perm ? "yes" : "no", itr->second.extendState == EXTEND_STATE_EXPIRED ? "expired" : itr->second.extendState == EXTEND_STATE_EXTENDED ? "yes" : "no", save->GetDifficulty(), save->CanReset() ? "yes" : "no", timeleft.c_str()); counter++; } @@ -97,7 +101,7 @@ public: for (Group::BoundInstancesMap::const_iterator itr = binds.begin(); itr != binds.end(); ++itr) { InstanceSave* save = itr->second.save; - std::string timeleft = GetTimeString(save->GetResetTime() - time(NULL)); + std::string timeleft = GetTimeString(save->GetResetTime() - time(nullptr)); handler->PSendSysMessage(LANG_COMMAND_LIST_BIND_INFO, itr->first, save->GetInstanceId(), itr->second.perm ? "yes" : "no", "-", save->GetDifficulty(), save->CanReset() ? "yes" : "no", timeleft.c_str()); counter++; } @@ -118,7 +122,7 @@ public: player = handler->GetSession()->GetPlayer(); char* map = strtok((char*)args, " "); - char* pDiff = strtok(NULL, " "); + char* pDiff = strtok(nullptr, " "); int8 diff = -1; if (pDiff) diff = atoi(pDiff); @@ -140,7 +144,7 @@ public: InstanceSave* save = itr->second.save; if (itr->first != player->GetMapId() && (!MapId || MapId == itr->first) && (diff == -1 || diff == save->GetDifficulty())) { - std::string timeleft = GetTimeString(save->GetResetTime() - time(NULL)); + std::string timeleft = GetTimeString(save->GetResetTime() - time(nullptr)); handler->PSendSysMessage(LANG_COMMAND_INST_UNBIND_UNBINDING, itr->first, save->GetInstanceId(), itr->second.perm ? "yes" : "no", save->GetDifficulty(), save->CanReset() ? "yes" : "no", timeleft.c_str()); player->UnbindInstance(itr, Difficulty(i)); counter++; diff --git a/src/server/scripts/Commands/cs_learn.cpp b/src/server/scripts/Commands/cs_learn.cpp index ced838678a8..3cd5c80944f 100644 --- a/src/server/scripts/Commands/cs_learn.cpp +++ b/src/server/scripts/Commands/cs_learn.cpp @@ -22,14 +22,17 @@ Comment: All learn related commands Category: commandscripts EndScriptData */ -#include "Chat.h" #include "ScriptMgr.h" -#include "ObjectMgr.h" +#include "Chat.h" +#include "DBCStores.h" #include "Language.h" -#include "SpellMgr.h" -#include "SpellInfo.h" -#include "Player.h" +#include "ObjectMgr.h" #include "Pet.h" +#include "Player.h" +#include "RBAC.h" +#include "SpellInfo.h" +#include "SpellMgr.h" +#include "WorldSession.h" class learn_commandscript : public CommandScript { @@ -48,7 +51,7 @@ public: static std::vector learnAllCommandTable = { - { "my", rbac::RBAC_PERM_COMMAND_LEARN_ALL_MY, false, NULL, "", learnAllMyCommandTable }, + { "my", rbac::RBAC_PERM_COMMAND_LEARN_ALL_MY, false, nullptr, "", learnAllMyCommandTable }, { "gm", rbac::RBAC_PERM_COMMAND_LEARN_ALL_GM, false, &HandleLearnAllGMCommand, "" }, { "crafts", rbac::RBAC_PERM_COMMAND_LEARN_ALL_CRAFTS, false, &HandleLearnAllCraftsCommand, "" }, { "default", rbac::RBAC_PERM_COMMAND_LEARN_ALL_DEFAULT, false, &HandleLearnAllDefaultCommand, "" }, @@ -58,13 +61,13 @@ public: static std::vector learnCommandTable = { - { "all", rbac::RBAC_PERM_COMMAND_LEARN_ALL, false, NULL, "", learnAllCommandTable }, + { "all", rbac::RBAC_PERM_COMMAND_LEARN_ALL, false, nullptr, "", learnAllCommandTable }, { "", rbac::RBAC_PERM_COMMAND_LEARN, false, &HandleLearnCommand, "" }, }; static std::vector commandTable = { - { "learn", rbac::RBAC_PERM_COMMAND_LEARN, false, NULL, "", learnCommandTable }, + { "learn", rbac::RBAC_PERM_COMMAND_LEARN, false, nullptr, "", learnCommandTable }, { "unlearn", rbac::RBAC_PERM_COMMAND_UNLEARN, false, &HandleUnLearnCommand, "" }, }; return commandTable; @@ -86,7 +89,7 @@ public: if (!spell || !sSpellMgr->GetSpellInfo(spell)) return false; - char const* all = strtok(NULL, " "); + char const* all = strtok(nullptr, " "); bool allRanks = all ? (strncmp(all, "all", strlen(all)) == 0) : false; SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spell); @@ -150,12 +153,8 @@ public: return true; uint32 family = classEntry->spellfamily; - for (uint32 i = 0; i < sSkillLineAbilityStore.GetNumRows(); ++i) + for (SkillLineAbilityEntry const* entry : sSkillLineAbilityStore) { - SkillLineAbilityEntry const* entry = sSkillLineAbilityStore.LookupEntry(i); - if (!entry) - continue; - SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(entry->spellId); if (!spellInfo) continue; @@ -192,12 +191,8 @@ public: Player* player = handler->GetSession()->GetPlayer(); uint32 classMask = player->getClassMask(); - for (uint32 i = 0; i < sTalentStore.GetNumRows(); ++i) + for (TalentEntry const* talentInfo : sTalentStore) { - TalentEntry const* talentInfo = sTalentStore.LookupEntry(i); - if (!talentInfo) - continue; - TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab); if (!talentTabInfo) continue; @@ -269,12 +264,8 @@ public: return false; } - for (uint32 i = 0; i < sTalentStore.GetNumRows(); ++i) + for (TalentEntry const* talentInfo : sTalentStore) { - TalentEntry const* talentInfo = sTalentStore.LookupEntry(i); - if (!talentInfo) - continue; - TalentTabEntry const* talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab); if (!talentTabInfo) continue; @@ -286,7 +277,7 @@ public: // search highest talent rank uint32 spellId = 0; - for (int8 rank = MAX_TALENT_RANK-1; rank >= 0; --rank) + for (int8 rank = MAX_TALENT_RANK - 1; rank >= 0; --rank) { if (talentInfo->RankID[rank] != 0) { @@ -314,9 +305,9 @@ public: static bool HandleLearnAllLangCommand(ChatHandler* handler, char const* /*args*/) { - // skipping UNIVERSAL language (0) - for (uint8 i = 1; i < LANGUAGES_COUNT; ++i) - handler->GetSession()->GetPlayer()->LearnSpell(lang_description[i].spell_id, false); + for (LanguageDesc const& langDesc : lang_description) + if (uint32 langSpellId = langDesc.spell_id) + handler->GetSession()->GetPlayer()->LearnSpell(langSpellId, false); handler->SendSysMessage(LANG_COMMAND_LEARN_ALL_LANG); return true; @@ -384,7 +375,7 @@ public: std::string name; - SkillLineEntry const* targetSkillInfo = NULL; + SkillLineEntry const* targetSkillInfo = nullptr; for (uint32 i = 1; i < sSkillLineStore.GetNumRows(); ++i) { SkillLineEntry const* skillInfo = sSkillLineStore.LookupEntry(i); @@ -421,12 +412,8 @@ public: { uint32 classmask = player->getClassMask(); - for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j) + for (SkillLineAbilityEntry const* skillLine : sSkillLineAbilityStore) { - SkillLineAbilityEntry const* skillLine = sSkillLineAbilityStore.LookupEntry(j); - if (!skillLine) - continue; - // wrong skill if (skillLine->skillId != skillId) continue; @@ -461,7 +448,7 @@ public: if (!spellId) return false; - char const* allStr = strtok(NULL, " "); + char const* allStr = strtok(nullptr, " "); bool allRanks = allStr ? (strncmp(allStr, "all", strlen(allStr)) == 0) : false; Player* target = handler->getSelectedPlayer(); diff --git a/src/server/scripts/Commands/cs_lfg.cpp b/src/server/scripts/Commands/cs_lfg.cpp index a58e085c157..7f38666013b 100644 --- a/src/server/scripts/Commands/cs_lfg.cpp +++ b/src/server/scripts/Commands/cs_lfg.cpp @@ -18,12 +18,15 @@ #include "ScriptMgr.h" #include "CharacterCache.h" #include "Chat.h" -#include "Language.h" -#include "LFGMgr.h" -#include "ObjectMgr.h" +#include "DatabaseEnv.h" #include "Group.h" #include "GroupMgr.h" +#include "Language.h" +#include "LFGMgr.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Player.h" +#include "RBAC.h" void GetPlayerInfo(ChatHandler* handler, Player* player) { @@ -57,16 +60,16 @@ public: static std::vector commandTable = { - { "lfg", rbac::RBAC_PERM_COMMAND_LFG, true, NULL, "", lfgCommandTable }, + { "lfg", rbac::RBAC_PERM_COMMAND_LFG, true, nullptr, "", lfgCommandTable }, }; return commandTable; } static bool HandleLfgPlayerInfoCommand(ChatHandler* handler, char const* args) { - Player* target = NULL; + Player* target = nullptr; std::string playerName; - if (!handler->extractPlayerTarget((char*)args, &target, NULL, &playerName)) + if (!handler->extractPlayerTarget((char*)args, &target, nullptr, &playerName)) return false; GetPlayerInfo(handler, target); @@ -89,7 +92,7 @@ public: else if (!handler->extractPlayerTarget((char*)args, &playerTarget, &guidTarget, &nameTarget)) return false; - Group* groupTarget = NULL; + Group* groupTarget = nullptr; if (playerTarget) groupTarget = playerTarget->GetGroup(); diff --git a/src/server/scripts/Commands/cs_list.cpp b/src/server/scripts/Commands/cs_list.cpp index 934c7a0e91f..9eac8bb1829 100644 --- a/src/server/scripts/Commands/cs_list.cpp +++ b/src/server/scripts/Commands/cs_list.cpp @@ -23,13 +23,17 @@ Category: commandscripts EndScriptData */ #include "ScriptMgr.h" +#include "CharacterCache.h" #include "Chat.h" -#include "SpellAuraEffects.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "Language.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Player.h" -#include "CharacterCache.h" +#include "RBAC.h" +#include "SpellAuraEffects.h" +#include "WorldSession.h" #include class list_commandscript : public CommandScript @@ -49,7 +53,7 @@ public: }; static std::vector commandTable = { - { "list", rbac::RBAC_PERM_COMMAND_LIST,true, NULL, "", listCommandTable }, + { "list", rbac::RBAC_PERM_COMMAND_LIST,true, nullptr, "", listCommandTable }, }; return commandTable; } @@ -80,7 +84,7 @@ public: return false; } - char* countStr = strtok(NULL, " "); + char* countStr = strtok(nullptr, " "); uint32 count = countStr ? atoul(countStr) : 10; if (count == 0) @@ -152,7 +156,7 @@ public: return false; } - char* countStr = strtok(NULL, " "); + char* countStr = strtok(nullptr, " "); uint32 count = countStr ? atoul(countStr) : 10; if (count == 0) @@ -227,7 +231,7 @@ public: result = CharacterDatabase.Query(stmt); } else - result = PreparedQueryResult(NULL); + result = PreparedQueryResult(nullptr); if (result) { @@ -274,7 +278,7 @@ public: result = CharacterDatabase.Query(stmt); } else - result = PreparedQueryResult(NULL); + result = PreparedQueryResult(nullptr); if (result) { @@ -369,7 +373,7 @@ public: return false; } - char* countStr = strtok(NULL, " "); + char* countStr = strtok(nullptr, " "); uint32 count = countStr ? atoul(countStr) : 10; if (count == 0) @@ -470,7 +474,7 @@ public: Player* target; ObjectGuid targetGuid; std::string targetName; - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; if (!*args) return false; diff --git a/src/server/scripts/Commands/cs_lookup.cpp b/src/server/scripts/Commands/cs_lookup.cpp index 0a9c00367f9..8383c6c574e 100644 --- a/src/server/scripts/Commands/cs_lookup.cpp +++ b/src/server/scripts/Commands/cs_lookup.cpp @@ -22,15 +22,20 @@ Comment: All lookup related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "AccountMgr.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "GameEventMgr.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Player.h" #include "ReputationMgr.h" -#include "ScriptMgr.h" #include "SpellInfo.h" +#include "SpellMgr.h" +#include "World.h" +#include "WorldSession.h" class lookup_commandscript : public CommandScript { @@ -62,9 +67,9 @@ public: { "itemset", rbac::RBAC_PERM_COMMAND_LOOKUP_ITEMSET, true, &HandleLookupItemSetCommand, "" }, { "object", rbac::RBAC_PERM_COMMAND_LOOKUP_OBJECT, true, &HandleLookupObjectCommand, "" }, { "quest", rbac::RBAC_PERM_COMMAND_LOOKUP_QUEST, true, &HandleLookupQuestCommand, "" }, - { "player", rbac::RBAC_PERM_COMMAND_LOOKUP_PLAYER, true, NULL, "", lookupPlayerCommandTable }, + { "player", rbac::RBAC_PERM_COMMAND_LOOKUP_PLAYER, true, nullptr, "", lookupPlayerCommandTable }, { "skill", rbac::RBAC_PERM_COMMAND_LOOKUP_SKILL, true, &HandleLookupSkillCommand, "" }, - { "spell", rbac::RBAC_PERM_COMMAND_LOOKUP_SPELL, true, NULL, "", lookupSpellCommandTable }, + { "spell", rbac::RBAC_PERM_COMMAND_LOOKUP_SPELL, true, nullptr, "", lookupSpellCommandTable }, { "taxinode", rbac::RBAC_PERM_COMMAND_LOOKUP_TAXINODE, true, &HandleLookupTaxiNodeCommand, "" }, { "tele", rbac::RBAC_PERM_COMMAND_LOOKUP_TELE, true, &HandleLookupTeleCommand, "" }, { "title", rbac::RBAC_PERM_COMMAND_LOOKUP_TITLE, true, &HandleLookupTitleCommand, "" }, @@ -73,7 +78,7 @@ public: static std::vector commandTable = { - { "lookup", rbac::RBAC_PERM_COMMAND_LOOKUP, true, NULL, "", lookupCommandTable }, + { "lookup", rbac::RBAC_PERM_COMMAND_LOOKUP, true, nullptr, "", lookupCommandTable }, }; return commandTable; } @@ -97,36 +102,32 @@ public: wstrToLower(wNamePart); // Search in AreaTable.dbc - for (uint32 i = 0; i < sAreaTableStore.GetNumRows(); ++i) + for (AreaTableEntry const* areaEntry : sAreaTableStore) { - AreaTableEntry const* areaEntry = sAreaTableStore.LookupEntry(i); - if (areaEntry) + std::string name = areaEntry->area_name; + if (name.empty()) + continue; + + if (!Utf8FitTo(name, wNamePart)) + continue; + + if (maxResults && count++ == maxResults) { - std::string name = areaEntry->area_name; - if (name.empty()) - continue; - - if (!Utf8FitTo(name, wNamePart)) - continue; - - if (maxResults && count++ == maxResults) - { - handler->PSendSysMessage(LANG_COMMAND_LOOKUP_MAX_RESULTS, maxResults); - return true; - } - - // send area in "id - [name]" format - std::ostringstream ss; - if (handler->GetSession()) - ss << areaEntry->ID << " - |cffffffff|Harea:" << areaEntry->ID << "|h[" << name<< "]|h|r"; - else - ss << areaEntry->ID << " - " << name; - - handler->SendSysMessage(ss.str().c_str()); - - if (!found) - found = true; + handler->PSendSysMessage(LANG_COMMAND_LOOKUP_MAX_RESULTS, maxResults); + return true; } + + // send area in "id - [name]" format + std::ostringstream ss; + if (handler->GetSession()) + ss << areaEntry->ID << " - |cffffffff|Harea:" << areaEntry->ID << "|h[" << name << "]|h|r"; + else + ss << areaEntry->ID << " - " << name; + + handler->SendSysMessage(ss.str().c_str()); + + if (!found) + found = true; } if (!found) @@ -273,7 +274,7 @@ public: if (!*args) return false; - // Can be NULL at console call + // Can be nullptr at console call Player* target = handler->getSelectedPlayer(); std::string namePart = args; @@ -293,7 +294,7 @@ public: { if (FactionEntry const* factionEntry = sFactionStore.LookupEntry(id)) { - FactionState const* factionState = target ? target->GetReputationMgr().GetState(factionEntry) : NULL; + FactionState const* factionState = target ? target->GetReputationMgr().GetState(factionEntry) : nullptr; std::string name = factionEntry->name; if (name.empty()) @@ -316,7 +317,7 @@ public: else ss << id << " - " << name; - if (factionState) // and then target != NULL also + if (factionState) // and then target != nullptr also { uint32 index = target->GetReputationMgr().GetReputationRankStrIndex(factionEntry); std::string rankName = handler->GetTrinityString(index); @@ -568,7 +569,7 @@ public: if (!*args) return false; - // can be NULL at console call + // can be nullptr at console call Player* target = handler->getSelectedPlayerOrSelf(); std::string namePart = args; @@ -698,7 +699,7 @@ public: if (!*args) return false; - // can be NULL in console call + // can be nullptr in console call Player* target = handler->getSelectedPlayer(); std::string namePart = args; @@ -768,7 +769,7 @@ public: if (!*args) return false; - // can be NULL at console call + // can be nullptr at console call Player* target = handler->getSelectedPlayer(); std::string namePart = args; @@ -860,7 +861,7 @@ public: if (!*args) return false; - // can be NULL at console call + // can be nullptr at console call Player* target = handler->getSelectedPlayer(); uint32 id = atoi((char*)args); @@ -1044,7 +1045,7 @@ public: if (!*args) return false; - // can be NULL in console call + // can be nullptr in console call Player* target = handler->getSelectedPlayer(); // title name have single string arg for player name @@ -1184,7 +1185,7 @@ public: Player* target = handler->getSelectedPlayer(); if (!*args) { - // NULL only if used from console + // nullptr only if used from console if (!target || target == handler->GetSession()->GetPlayer()) return false; @@ -1194,7 +1195,7 @@ public: else { ip = strtok((char*)args, " "); - limitStr = strtok(NULL, " "); + limitStr = strtok(nullptr, " "); limit = limitStr ? atoi(limitStr) : -1; } @@ -1211,7 +1212,7 @@ public: return false; std::string account = strtok((char*)args, " "); - char* limitStr = strtok(NULL, " "); + char* limitStr = strtok(nullptr, " "); int32 limit = limitStr ? atoi(limitStr) : -1; if (!Utf8ToUpperOnlyLatin(account)) @@ -1230,7 +1231,7 @@ public: return false; std::string email = strtok((char*)args, " "); - char* limitStr = strtok(NULL, " "); + char* limitStr = strtok(nullptr, " "); int32 limit = limitStr ? atoi(limitStr) : -1; PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_LIST_BY_EMAIL); diff --git a/src/server/scripts/Commands/cs_message.cpp b/src/server/scripts/Commands/cs_message.cpp index ec893c52680..428ac9b3749 100644 --- a/src/server/scripts/Commands/cs_message.cpp +++ b/src/server/scripts/Commands/cs_message.cpp @@ -23,12 +23,18 @@ Category: commandscripts EndScriptData */ #include "ScriptMgr.h" -#include "Chat.h" #include "Channel.h" #include "ChannelMgr.h" +#include "Chat.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "Language.h" -#include "Player.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" +#include "Player.h" +#include "RBAC.h" +#include "World.h" +#include "WorldSession.h" class message_commandscript : public CommandScript { @@ -43,11 +49,11 @@ public: }; static std::vector channelCommandTable = { - { "set", rbac::RBAC_PERM_COMMAND_CHANNEL_SET, true, NULL, "", channelSetCommandTable }, + { "set", rbac::RBAC_PERM_COMMAND_CHANNEL_SET, true, nullptr, "", channelSetCommandTable }, }; static std::vector commandTable = { - { "channel", rbac::RBAC_PERM_COMMAND_CHANNEL, true, NULL, "", channelCommandTable }, + { "channel", rbac::RBAC_PERM_COMMAND_CHANNEL, true, nullptr, "", channelCommandTable }, { "nameannounce", rbac::RBAC_PERM_COMMAND_NAMEANNOUNCE, true, &HandleNameAnnounceCommand, "" }, { "gmnameannounce", rbac::RBAC_PERM_COMMAND_GMNAMEANNOUNCE, true, &HandleGMNameAnnounceCommand, "" }, { "announce", rbac::RBAC_PERM_COMMAND_ANNOUNCE, true, &HandleAnnounceCommand, "" }, @@ -70,26 +76,18 @@ public: return false; uint32 channelId = 0; - for (uint32 i = 0; i < sChatChannelsStore.GetNumRows(); ++i) + for (ChatChannelsEntry const* entry : sChatChannelsStore) { - ChatChannelsEntry const* entry = sChatChannelsStore.LookupEntry(i); - if (!entry) - continue; - if (strstr(entry->pattern, channelStr)) { - channelId = i; + channelId = entry->ChannelID; break; } } AreaTableEntry const* zoneEntry = nullptr; - for (uint32 i = 0; i < sAreaTableStore.GetNumRows(); ++i) + for (AreaTableEntry const* entry : sAreaTableStore) { - AreaTableEntry const* entry = sAreaTableStore.LookupEntry(i); - if (!entry) - continue; - if (strstr(entry->area_name, channelStr)) { zoneEntry = entry; @@ -232,7 +230,7 @@ public: if (argStr == "remove") { - std::string name = strtok(NULL, " "); + std::string name = strtok(nullptr, " "); if (normalizePlayerName(name)) { if (Player* player = ObjectAccessor::FindPlayerByName(name)) diff --git a/src/server/scripts/Commands/cs_misc.cpp b/src/server/scripts/Commands/cs_misc.cpp index e86ba856f82..e2049e45d3e 100644 --- a/src/server/scripts/Commands/cs_misc.cpp +++ b/src/server/scripts/Commands/cs_misc.cpp @@ -15,30 +15,41 @@ * with this program. If not, see . */ -#include "CharacterCache.h" -#include "Chat.h" #include "ScriptMgr.h" #include "AccountMgr.h" #include "ArenaTeamMgr.h" #include "CellImpl.h" +#include "CharacterCache.h" +#include "Chat.h" +#include "DatabaseEnv.h" +#include "DisableMgr.h" #include "GridNotifiers.h" #include "Group.h" +#include "GroupMgr.h" #include "InstanceSaveMgr.h" +#include "IpAddress.h" +#include "Item.h" #include "Language.h" +#include "LFG.h" +#include "Log.h" +#include "MMapFactory.h" #include "MovementGenerator.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Opcodes.h" -#include "SpellAuras.h" -#include "TargetedMovementGenerator.h" -#include "WeatherMgr.h" -#include "Player.h" #include "Pet.h" #include "PhasingHandler.h" -#include "LFG.h" -#include "GroupMgr.h" -#include "MMapFactory.h" -#include "DisableMgr.h" +#include "Player.h" +#include "Realm.h" +#include "SpellAuras.h" #include "SpellHistory.h" +#include "SpellMgr.h" +#include "TargetedMovementGenerator.h" #include "Transport.h" +#include "Weather.h" +#include "WeatherMgr.h" +#include "World.h" +#include "WorldSession.h" class misc_commandscript : public CommandScript { @@ -411,7 +422,7 @@ public: { Group* group = _player->GetGroup(); // if no bind exists, create a solo bind - InstanceGroupBind* gBind = group ? group->GetBoundInstance(target) : NULL; // if no bind exists, create a solo bind + InstanceGroupBind* gBind = group ? group->GetBoundInstance(target) : nullptr; // if no bind exists, create a solo bind if (!gBind) if (InstanceSave* save = sInstanceSaveMgr->GetInstanceSave(target->GetInstanceId())) _player->BindToInstance(save, !save->CanReset()); @@ -446,7 +457,7 @@ public: else { // check offline security - if (handler->HasLowerSecurity(NULL, targetGuid)) + if (handler->HasLowerSecurity(nullptr, targetGuid)) return false; std::string nameLink = handler->playerLink(targetName); @@ -577,7 +588,7 @@ public: else { // check offline security - if (handler->HasLowerSecurity(NULL, targetGuid)) + if (handler->HasLowerSecurity(nullptr, targetGuid)) return false; std::string nameLink = handler->playerLink(targetName); @@ -624,7 +635,7 @@ public: if (sWorld->getBoolConfig(CONFIG_DIE_COMMAND_MODE)) handler->GetSession()->GetPlayer()->Kill(target); else - handler->GetSession()->GetPlayer()->DealDamage(target, target->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + handler->GetSession()->GetPlayer()->DealDamage(target, target->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); } return true; @@ -717,7 +728,7 @@ public: if (!param1) return false; - char const* param2 = strtok(NULL, " "); + char const* param2 = strtok(nullptr, " "); if (!param2) return false; @@ -910,9 +921,9 @@ public: // kick player static bool HandleKickPlayerCommand(ChatHandler* handler, char const* args) { - Player* target = NULL; + Player* target = nullptr; std::string playerName; - if (!handler->extractPlayerTarget((char*)args, &target, NULL, &playerName)) + if (!handler->extractPlayerTarget((char*)args, &target, nullptr, &playerName)) return false; if (handler->GetSession() && target == handler->GetSession()->GetPlayer()) @@ -929,8 +940,8 @@ public: std::string kickReasonStr = handler->GetTrinityString(LANG_NO_REASON); if (*args != '\0') { - char const* kickReason = strtok(NULL, "\r"); - if (kickReason != NULL) + char const* kickReason = strtok(nullptr, "\r"); + if (kickReason != nullptr) kickReasonStr = kickReason; } @@ -963,10 +974,10 @@ public: return false; std::string location_str = "inn"; - if (char const* loc = strtok(NULL, " ")) + if (char const* loc = strtok(nullptr, " ")) location_str = loc; - Player* player = NULL; + Player* player = nullptr; if (!handler->extractPlayerTarget(player_str, &player)) return false; @@ -1018,7 +1029,7 @@ public: uint32 team; - char* px2 = strtok(NULL, " "); + char* px2 = strtok(nullptr, " "); if (!px2) team = 0; @@ -1050,7 +1061,7 @@ public: return false; } - if (sObjectMgr->AddGraveYardLink(graveyardId, zoneId, team)) + if (sObjectMgr->AddGraveyardLink(graveyardId, zoneId, team)) handler->PSendSysMessage(LANG_COMMAND_GRAVEYARDLINKED, graveyardId, zoneId); else handler->PSendSysMessage(LANG_COMMAND_GRAVEYARDALRLINKED, graveyardId, zoneId); @@ -1076,12 +1087,12 @@ public: Player* player = handler->GetSession()->GetPlayer(); uint32 zone_id = player->GetZoneId(); - WorldSafeLocsEntry const* graveyard = sObjectMgr->GetClosestGraveYard(*player, team, nullptr); + WorldSafeLocsEntry const* graveyard = sObjectMgr->GetClosestGraveyard(*player, team, nullptr); if (graveyard) { uint32 graveyardId = graveyard->ID; - GraveYardData const* data = sObjectMgr->FindGraveYardData(graveyardId, zone_id); + GraveyardData const* data = sObjectMgr->FindGraveyardData(graveyardId, zone_id); if (!data) { handler->PSendSysMessage(LANG_COMMAND_GRAVEYARDERROR, graveyardId); @@ -1233,12 +1244,12 @@ public: itemId = atoul(id); } - char const* ccount = strtok(NULL, " "); + char const* ccount = strtok(nullptr, " "); int32 count = 1; if (ccount) - count = strtol(ccount, NULL, 10); + count = strtol(ccount, nullptr, 10); if (count == 0) count = 1; @@ -1282,7 +1293,7 @@ public: return false; } - Item* item = playerTarget->StoreNewItem(dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId)); + Item* item = playerTarget->StoreNewItem(dest, itemId, true, GenerateItemRandomPropertyId(itemId)); // remove binding (let GM give it to another player later) if (player == playerTarget) @@ -1352,7 +1363,7 @@ public: } else { - player->SendEquipError(msg, NULL, NULL, itr->second.ItemId); + player->SendEquipError(msg, nullptr, nullptr, itr->second.ItemId); handler->PSendSysMessage(LANG_ITEM_CANNOT_CREATE, itr->second.ItemId, 1); } } @@ -1389,7 +1400,7 @@ public: // *Change the weather of a cell char const* px = strtok((char*)args, " "); - char const* py = strtok(NULL, " "); + char const* py = strtok(nullptr, " "); if (!px || !py) return false; @@ -1439,11 +1450,11 @@ public: if (!skillStr) return false; - char const* levelStr = strtok(NULL, " "); + char const* levelStr = strtok(nullptr, " "); if (!levelStr) return false; - char const* maxPureSkill = strtok(NULL, " "); + char const* maxPureSkill = strtok(nullptr, " "); int32 skill = atoi(skillStr); if (skill <= 0) @@ -1512,7 +1523,7 @@ public: Player* target; ObjectGuid targetGuid; std::string targetName; - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; // To make sure we get a target, we convert our guid to an omniversal... ObjectGuid parseGUID(HighGuid::Player, uint32(atoul(args))); @@ -1635,7 +1646,7 @@ public: else { // check offline security - if (handler->HasLowerSecurity(NULL, targetGuid)) + if (handler->HasLowerSecurity(nullptr, targetGuid)) return false; // Query informations from the DB @@ -1686,7 +1697,7 @@ public: lastIp = fields[4].GetString(); lastLogin = fields[5].GetString(); - uint32 ip = inet_addr(lastIp.c_str()); + uint32 ip = Trinity::Net::address_to_uint(Trinity::Net::make_address_v4(lastIp)); EndianConvertReverse(ip); // If ip2nation table is populated, it displays the country @@ -1781,7 +1792,7 @@ public: // Output III. LANG_PINFO_BANNED if ban exists and is applied if (banTime >= 0) - handler->PSendSysMessage(LANG_PINFO_BANNED, banType.c_str(), banReason.c_str(), banTime > 0 ? secsToTimeString(banTime - time(NULL), true).c_str() : handler->GetTrinityString(LANG_PERMANENTLY), bannedBy.c_str()); + handler->PSendSysMessage(LANG_PINFO_BANNED, banType.c_str(), banReason.c_str(), banTime > 0 ? secsToTimeString(banTime - time(nullptr), true).c_str() : handler->GetTrinityString(LANG_PERMANENTLY), bannedBy.c_str()); // Output IV. LANG_PINFO_MUTED if mute is applied if (muteTime > 0) @@ -1912,9 +1923,9 @@ public: if (!delayStr) return false; - char const* muteReason = strtok(NULL, "\r"); + char const* muteReason = strtok(nullptr, "\r"); std::string muteReasonStr = handler->GetTrinityString(LANG_NO_REASON); - if (muteReason != NULL) + if (muteReason != nullptr) muteReasonStr = muteReason; Player* target; @@ -1946,7 +1957,7 @@ public: if (target) { // Target is online, mute will be in effect right away. - int64 muteTime = time(NULL) + notSpeakTime * MINUTE; + int64 muteTime = time(nullptr) + notSpeakTime * MINUTE; target->GetSession()->m_muteTime = muteTime; stmt->setInt64(0, muteTime); std::string nameLink = handler->playerLink(targetName); @@ -2133,7 +2144,7 @@ public: break; case CHASE_MOTION_TYPE: { - Unit* target = NULL; + Unit* target = nullptr; if (unit->GetTypeId() == TYPEID_PLAYER) target = static_cast const*>(movementGenerator)->GetTarget(); else @@ -2149,7 +2160,7 @@ public: } case FOLLOW_MOTION_TYPE: { - Unit* target = NULL; + Unit* target = nullptr; if (unit->GetTypeId() == TYPEID_PLAYER) target = static_cast const*>(movementGenerator)->GetTarget(); else @@ -2222,7 +2233,7 @@ public: if (strcmp(str, "go") == 0) { - char* guidStr = strtok(NULL, " "); + char* guidStr = strtok(nullptr, " "); if (!guidStr) { handler->SendSysMessage(LANG_BAD_VALUE); @@ -2238,7 +2249,7 @@ public: return false; } - char* damageStr = strtok(NULL, " "); + char* damageStr = strtok(nullptr, " "); if (!damageStr) { handler->SendSysMessage(LANG_BAD_VALUE); @@ -2303,12 +2314,12 @@ public: uint32 damage = damage_int; - char* schoolStr = strtok((char*)NULL, " "); + char* schoolStr = strtok((char*)nullptr, " "); // flat melee damage without resistence/etc reduction if (!schoolStr) { - handler->GetSession()->GetPlayer()->DealDamage(target, damage, NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + handler->GetSession()->GetPlayer()->DealDamage(target, damage, nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); if (target != handler->GetSession()->GetPlayer()) handler->GetSession()->GetPlayer()->SendAttackStateUpdate (HITINFO_AFFECTS_VICTIM, target, 1, SPELL_SCHOOL_MASK_NORMAL, damage, 0, 0, VICTIMSTATE_HIT, 0); return true; @@ -2321,9 +2332,9 @@ public: SpellSchoolMask schoolmask = SpellSchoolMask(1 << school); if (Unit::IsDamageReducedByArmor(schoolmask)) - damage = handler->GetSession()->GetPlayer()->CalcArmorReducedDamage(target, damage, NULL, BASE_ATTACK); + damage = handler->GetSession()->GetPlayer()->CalcArmorReducedDamage(target, damage, nullptr, BASE_ATTACK); - char* spellStr = strtok((char*)NULL, " "); + char* spellStr = strtok((char*)nullptr, " "); // melee damage by specific school if (!spellStr) @@ -2370,7 +2381,7 @@ public: static bool HandleCombatStopCommand(ChatHandler* handler, char const* args) { - Player* target = NULL; + Player* target = nullptr; if (args && args[0] != '\0') { @@ -2444,7 +2455,7 @@ public: { // Get the args that we might have (up to 2) char const* arg1 = strtok((char*)args, " "); - char const* arg2 = strtok(NULL, " "); + char const* arg2 = strtok(nullptr, " "); // Analyze them to see if we got either a playerName or duration or both if (arg1) diff --git a/src/server/scripts/Commands/cs_mmaps.cpp b/src/server/scripts/Commands/cs_mmaps.cpp index 1877041e138..0be5761a19b 100644 --- a/src/server/scripts/Commands/cs_mmaps.cpp +++ b/src/server/scripts/Commands/cs_mmaps.cpp @@ -24,19 +24,20 @@ */ #include "ScriptMgr.h" +#include "CellImpl.h" #include "Chat.h" #include "DisableMgr.h" +#include "GridNotifiersImpl.h" +#include "Map.h" +#include "MMapFactory.h" #include "ObjectMgr.h" -#include "Player.h" -#include "PointMovementGenerator.h" #include "PathGenerator.h" #include "PhasingHandler.h" -#include "MMapFactory.h" -#include "Map.h" +#include "Player.h" +#include "PointMovementGenerator.h" +#include "RBAC.h" #include "TargetedMovementGenerator.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "CellImpl.h" +#include "WorldSession.h" class mmaps_commandscript : public CommandScript { @@ -56,7 +57,7 @@ public: static std::vector commandTable = { - { "mmap", rbac::RBAC_PERM_COMMAND_MMAP, true, NULL, "", mmapCommandTable }, + { "mmap", rbac::RBAC_PERM_COMMAND_MMAP, true, nullptr, "", mmapCommandTable }, }; return commandTable; } @@ -104,9 +105,9 @@ public: handler->PSendSysMessage("Building: %s", useStraightPath ? "StraightPath" : useStraightLine ? "Raycast" : "SmoothPath"); handler->PSendSysMessage("Result: %s - Length: %zu - Type: %u", (result ? "true" : "false"), pointPath.size(), path.GetPathType()); - G3D::Vector3 const &start = path.GetStartPosition(); - G3D::Vector3 const &end = path.GetEndPosition(); - G3D::Vector3 const &actualEnd = path.GetActualEndPosition(); + G3D::Vector3 const& start = path.GetStartPosition(); + G3D::Vector3 const& end = path.GetEndPosition(); + G3D::Vector3 const& actualEnd = path.GetActualEndPosition(); handler->PSendSysMessage("StartPosition (%.3f, %.3f, %.3f)", start.x, start.y, start.z); handler->PSendSysMessage("EndPosition (%.3f, %.3f, %.3f)", end.x, end.y, end.z); @@ -159,7 +160,7 @@ public: // navmesh poly -> navmesh tile location dtQueryFilter filter = dtQueryFilter(); dtPolyRef polyRef = INVALID_POLYREF; - if (dtStatusFailed(navmeshquery->findNearestPoly(location, extents, &filter, &polyRef, NULL))) + if (dtStatusFailed(navmeshquery->findNearestPoly(location, extents, &filter, &polyRef, nullptr))) { handler->PSendSysMessage("Dt [??,??] (invalid poly, probably no tile loaded)"); return true; diff --git a/src/server/scripts/Commands/cs_modify.cpp b/src/server/scripts/Commands/cs_modify.cpp index 0f30a37d782..e55e80f0ccb 100644 --- a/src/server/scripts/Commands/cs_modify.cpp +++ b/src/server/scripts/Commands/cs_modify.cpp @@ -22,16 +22,18 @@ Comment: All modify related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "Chat.h" -#include +#include "DBCStores.h" +#include "Log.h" #include "ObjectMgr.h" #include "Opcodes.h" #include "Pet.h" #include "PhasingHandler.h" #include "Player.h" +#include "RBAC.h" #include "ReputationMgr.h" -#include "ScriptMgr.h" - +#include "WorldSession.h" class modify_commandscript : public CommandScript { @@ -67,7 +69,7 @@ public: { "reputation", rbac::RBAC_PERM_COMMAND_MODIFY_REPUTATION, false, &HandleModifyRepCommand, "" }, { "runicpower", rbac::RBAC_PERM_COMMAND_MODIFY_RUNICPOWER, false, &HandleModifyRunicPowerCommand, "" }, { "scale", rbac::RBAC_PERM_COMMAND_MODIFY_SCALE, false, &HandleModifyScaleCommand, "" }, - { "speed", rbac::RBAC_PERM_COMMAND_MODIFY_SPEED, false, NULL, "", modifyspeedCommandTable }, + { "speed", rbac::RBAC_PERM_COMMAND_MODIFY_SPEED, false, nullptr, "", modifyspeedCommandTable }, { "spell", rbac::RBAC_PERM_COMMAND_MODIFY_SPELL, false, &HandleModifySpellCommand, "" }, { "standstate", rbac::RBAC_PERM_COMMAND_MODIFY_STANDSTATE, false, &HandleModifyStandStateCommand, "" }, { "talentpoints", rbac::RBAC_PERM_COMMAND_MODIFY_TALENTPOINTS, false, &HandleModifyTalentCommand, "" }, @@ -77,7 +79,7 @@ public: { { "morph", rbac::RBAC_PERM_COMMAND_MORPH, false, &HandleModifyMorphCommand, "" }, { "demorph", rbac::RBAC_PERM_COMMAND_DEMORPH, false, &HandleDeMorphCommand, "" }, - { "modify", rbac::RBAC_PERM_COMMAND_MODIFY, false, NULL, "", modifyCommandTable }, + { "modify", rbac::RBAC_PERM_COMMAND_MODIFY, false, nullptr, "", modifyCommandTable }, }; return commandTable; } @@ -93,7 +95,7 @@ public: } } - static bool CheckModifyResources(ChatHandler* handler, const char* args, Player* target, int32& res, int32& resmax, int8 const multiplier = 1) + static bool CheckModifyResources(ChatHandler* handler, char const* args, Player* target, int32& res, int32& resmax, int8 const multiplier = 1) { if (!*args) return false; @@ -122,7 +124,7 @@ public: } //Edit Player HP - static bool HandleModifyHPCommand(ChatHandler* handler, const char* args) + static bool HandleModifyHPCommand(ChatHandler* handler, char const* args) { int32 hp, hpmax; Player* target = handler->getSelectedPlayerOrSelf(); @@ -137,7 +139,7 @@ public: } //Edit Player Mana - static bool HandleModifyManaCommand(ChatHandler* handler, const char* args) + static bool HandleModifyManaCommand(ChatHandler* handler, char const* args) { int32 mana, manamax; Player* target = handler->getSelectedPlayerOrSelf(); @@ -153,7 +155,7 @@ public: } //Edit Player Energy - static bool HandleModifyEnergyCommand(ChatHandler* handler, const char* args) + static bool HandleModifyEnergyCommand(ChatHandler* handler, char const* args) { int32 energy, energymax; Player* target = handler->getSelectedPlayerOrSelf(); @@ -170,7 +172,7 @@ public: } //Edit Player Rage - static bool HandleModifyRageCommand(ChatHandler* handler, const char* args) + static bool HandleModifyRageCommand(ChatHandler* handler, char const* args) { int32 rage, ragemax; Player* target = handler->getSelectedPlayerOrSelf(); @@ -186,7 +188,7 @@ public: } // Edit Player Runic Power - static bool HandleModifyRunicPowerCommand(ChatHandler* handler, const char* args) + static bool HandleModifyRunicPowerCommand(ChatHandler* handler, char const* args) { int32 rune, runemax; Player* target = handler->getSelectedPlayerOrSelf(); @@ -202,7 +204,7 @@ public: } //Edit Player Faction - static bool HandleModifyFactionCommand(ChatHandler* handler, const char* args) + static bool HandleModifyFactionCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -230,13 +232,13 @@ public: uint32 factionid = atoi(pfactionid); uint32 flag; - char *pflag = strtok(NULL, " "); + char *pflag = strtok(nullptr, " "); if (!pflag) flag = target->GetUInt32Value(UNIT_FIELD_FLAGS); else flag = atoi(pflag); - char* pnpcflag = strtok(NULL, " "); + char* pnpcflag = strtok(nullptr, " "); uint32 npcflag; if (!pnpcflag) @@ -244,7 +246,7 @@ public: else npcflag = atoi(pnpcflag); - char* pdyflag = strtok(NULL, " "); + char* pdyflag = strtok(nullptr, " "); uint32 dyflag; if (!pdyflag) @@ -270,7 +272,7 @@ public: } //Edit Player Spell - static bool HandleModifySpellCommand(ChatHandler* handler, const char* args) + static bool HandleModifySpellCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -279,17 +281,17 @@ public: if (!pspellflatid) return false; - char* pop = strtok(NULL, " "); + char* pop = strtok(nullptr, " "); if (!pop) return false; - char* pval = strtok(NULL, " "); + char* pval = strtok(nullptr, " "); if (!pval) return false; uint16 mark; - char* pmark = strtok(NULL, " "); + char* pmark = strtok(nullptr, " "); uint8 spellflatid = atoi(pspellflatid); uint8 op = atoi(pop); @@ -300,7 +302,7 @@ public: mark = atoi(pmark); Player* target = handler->getSelectedPlayerOrSelf(); - if (target == NULL) + if (target == nullptr) { handler->SendSysMessage(LANG_NO_CHAR_SELECTED); handler->SetSentErrorMessage(true); @@ -320,13 +322,13 @@ public: data << uint8(op); data << uint16(val); data << uint16(mark); - target->GetSession()->SendPacket(&data); + target->SendDirectMessage(&data); return true; } //Edit Player TP - static bool HandleModifyTalentCommand (ChatHandler* handler, const char* args) + static bool HandleModifyTalentCommand (ChatHandler* handler, char const* args) { if (!*args) return false; @@ -371,7 +373,7 @@ public: return false; } - static bool CheckModifySpeed(ChatHandler* handler, const char* args, Unit* target, float& speed, float minimumBound, float maximumBound, bool checkInFlight = true) + static bool CheckModifySpeed(ChatHandler* handler, char const* args, Unit* target, float& speed, float minimumBound, float maximumBound, bool checkInFlight = true) { if (!*args) return false; @@ -409,7 +411,7 @@ public: } //Edit Player Aspeed - static bool HandleModifyASpeedCommand(ChatHandler* handler, const char* args) + static bool HandleModifyASpeedCommand(ChatHandler* handler, char const* args) { float allSpeed; Player* target = handler->getSelectedPlayerOrSelf(); @@ -426,7 +428,7 @@ public: } //Edit Player Speed - static bool HandleModifySpeedCommand(ChatHandler* handler, const char* args) + static bool HandleModifySpeedCommand(ChatHandler* handler, char const* args) { float Speed; Player* target = handler->getSelectedPlayerOrSelf(); @@ -440,7 +442,7 @@ public: } //Edit Player Swim Speed - static bool HandleModifySwimCommand(ChatHandler* handler, const char* args) + static bool HandleModifySwimCommand(ChatHandler* handler, char const* args) { float swimSpeed; Player* target = handler->getSelectedPlayerOrSelf(); @@ -454,7 +456,7 @@ public: } //Edit Player Backwards Walk Speed - static bool HandleModifyBWalkCommand(ChatHandler* handler, const char* args) + static bool HandleModifyBWalkCommand(ChatHandler* handler, char const* args) { float backSpeed; Player* target = handler->getSelectedPlayerOrSelf(); @@ -468,7 +470,7 @@ public: } //Edit Player Fly - static bool HandleModifyFlyCommand(ChatHandler* handler, const char* args) + static bool HandleModifyFlyCommand(ChatHandler* handler, char const* args) { float flySpeed; Player* target = handler->getSelectedPlayerOrSelf(); @@ -482,7 +484,7 @@ public: } //Edit Player or Creature Scale - static bool HandleModifyScaleCommand(ChatHandler* handler, const char* args) + static bool HandleModifyScaleCommand(ChatHandler* handler, char const* args) { float Scale; Unit* target = handler->getSelectedUnit(); @@ -496,7 +498,7 @@ public: } //Enable Player mount - static bool HandleModifyMountCommand(ChatHandler* handler, const char* args) + static bool HandleModifyMountCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -539,7 +541,7 @@ public: } //Edit Player money - static bool HandleModifyMoneyCommand(ChatHandler* handler, const char* args) + static bool HandleModifyMoneyCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -607,7 +609,7 @@ public: } //Edit Unit field - static bool HandleModifyBitCommand(ChatHandler* handler, const char* args) + static bool HandleModifyBitCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -628,7 +630,7 @@ public: if (!pField) return false; - char* pBit = strtok(NULL, " "); + char* pBit = strtok(nullptr, " "); if (!pBit) return false; @@ -661,7 +663,7 @@ public: return true; } - static bool HandleModifyHonorCommand(ChatHandler* handler, const char* args) + static bool HandleModifyHonorCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -687,7 +689,7 @@ public: return true; } - static bool HandleModifyDrunkCommand(ChatHandler* handler, const char* args) + static bool HandleModifyDrunkCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -702,7 +704,7 @@ public: return true; } - static bool HandleModifyRepCommand(ChatHandler* handler, const char* args) + static bool HandleModifyRepCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -726,7 +728,7 @@ public: uint32 factionId = atoi(factionTxt); int32 amount = 0; - char *rankTxt = strtok(NULL, " "); + char *rankTxt = strtok(nullptr, " "); if (!factionId || !rankTxt) return false; @@ -755,7 +757,7 @@ public: if (wrank.substr(0, wrankStr.size()) == wrankStr) { - char *deltaTxt = strtok(NULL, " "); + char *deltaTxt = strtok(nullptr, " "); if (deltaTxt) { int32 delta = atoi(deltaTxt); @@ -780,7 +782,6 @@ public: } FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionId); - if (!factionEntry) { handler->PSendSysMessage(LANG_COMMAND_FACTION_UNKNOWN, factionId); @@ -803,7 +804,7 @@ public: } //morph creature or player - static bool HandleModifyMorphCommand(ChatHandler* handler, const char* args) + static bool HandleModifyMorphCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -824,7 +825,7 @@ public: } // Toggles a phaseid on a player - static bool HandleModifyPhaseCommand(ChatHandler* handler, const char* args) + static bool HandleModifyPhaseCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -876,7 +877,7 @@ public: } //change standstate - static bool HandleModifyStandStateCommand(ChatHandler* handler, const char* args) + static bool HandleModifyStandStateCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -887,7 +888,7 @@ public: return true; } - static bool HandleModifyGenderCommand(ChatHandler* handler, const char* args) + static bool HandleModifyGenderCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -948,7 +949,7 @@ public: return true; } //demorph player or unit - static bool HandleDeMorphCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleDeMorphCommand(ChatHandler* handler, char const* /*args*/) { Unit* target = handler->getSelectedUnit(); if (!target) @@ -963,7 +964,7 @@ public: return true; } - static bool HandleModifyCurrencyCommand(ChatHandler* handler, const char* args) + static bool HandleModifyCurrencyCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -981,7 +982,7 @@ public: if (!currencyType) return false; - uint32 amount = atoi(strtok(NULL, " ")); + uint32 amount = atoi(strtok(nullptr, " ")); if (!amount) return false; @@ -991,7 +992,7 @@ public: } // mod xp command - static bool HandleModifyXPCommand(ChatHandler *handler, const char* args) + static bool HandleModifyXPCommand(ChatHandler *handler, char const* args) { if (!*args) return false; diff --git a/src/server/scripts/Commands/cs_npc.cpp b/src/server/scripts/Commands/cs_npc.cpp index 6b2480b45ef..0429ba2d9d1 100644 --- a/src/server/scripts/Commands/cs_npc.cpp +++ b/src/server/scripts/Commands/cs_npc.cpp @@ -23,16 +23,23 @@ Category: commandscripts EndScriptData */ #include "ScriptMgr.h" -#include "ObjectMgr.h" #include "Chat.h" -#include "Transport.h" -#include "CreatureGroups.h" -#include "Language.h" -#include "TargetedMovementGenerator.h" // for HandleNpcUnFollowCommand #include "CreatureAI.h" -#include "Player.h" +#include "CreatureGroups.h" +#include "DatabaseEnv.h" +#include "Language.h" +#include "Log.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Pet.h" #include "PhasingHandler.h" +#include "Player.h" +#include "RBAC.h" +#include "TargetedMovementGenerator.h" // for HandleNpcUnFollowCommand +#include "Transport.h" +#include "World.h" +#include "WorldSession.h" template struct EnumName @@ -694,7 +701,7 @@ public: uint32 nativeid = target->GetNativeDisplayId(); uint32 Entry = target->GetEntry(); - int64 curRespawnDelay = target->GetRespawnTimeEx()-time(NULL); + int64 curRespawnDelay = target->GetRespawnTimeEx()-time(nullptr); if (curRespawnDelay < 0) curRespawnDelay = 0; std::string curRespawnDelayStr = secsToTimeString(uint64(curRespawnDelay), true); diff --git a/src/server/scripts/Commands/cs_pet.cpp b/src/server/scripts/Commands/cs_pet.cpp index d893ce63387..286d4e8c750 100644 --- a/src/server/scripts/Commands/cs_pet.cpp +++ b/src/server/scripts/Commands/cs_pet.cpp @@ -15,14 +15,19 @@ * with this program. If not, see . */ +#include "ScriptMgr.h" #include "Chat.h" #include "Language.h" +#include "Log.h" +#include "Map.h" +#include "ObjectMgr.h" #include "Pet.h" #include "Player.h" -#include "ObjectMgr.h" -#include "ScriptMgr.h" +#include "RBAC.h" +#include "SpellMgr.h" +#include "WorldSession.h" -static inline Pet* GetSelectedPlayerPetOrOwn(ChatHandler* handler) +inline Pet* GetSelectedPlayerPetOrOwn(ChatHandler* handler) { if (Unit* target = handler->getSelectedUnit()) { @@ -35,6 +40,7 @@ static inline Pet* GetSelectedPlayerPetOrOwn(ChatHandler* handler) Player* player = handler->GetSession()->GetPlayer(); return player ? player->GetPet() : nullptr; } + class pet_commandscript : public CommandScript { public: @@ -52,7 +58,7 @@ public: static std::vector commandTable = { - { "pet", rbac::RBAC_PERM_COMMAND_PET, false, NULL, "", petCommandTable }, + { "pet", rbac::RBAC_PERM_COMMAND_PET, false, nullptr, "", petCommandTable }, }; return commandTable; } diff --git a/src/server/scripts/Commands/cs_quest.cpp b/src/server/scripts/Commands/cs_quest.cpp index e75610f8d46..d4bd1d2129d 100644 --- a/src/server/scripts/Commands/cs_quest.cpp +++ b/src/server/scripts/Commands/cs_quest.cpp @@ -22,11 +22,15 @@ Comment: All quest related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "ObjectMgr.h" #include "Player.h" #include "ReputationMgr.h" -#include "ScriptMgr.h" +#include "RBAC.h" +#include "World.h" class quest_commandscript : public CommandScript { @@ -44,12 +48,12 @@ public: }; static std::vector commandTable = { - { "quest", rbac::RBAC_PERM_COMMAND_QUEST, false, NULL, "", questCommandTable }, + { "quest", rbac::RBAC_PERM_COMMAND_QUEST, false, nullptr, "", questCommandTable }, }; return commandTable; } - static bool HandleQuestAdd(ChatHandler* handler, const char* args) + static bool HandleQuestAdd(ChatHandler* handler, char const* args) { Player* player = handler->getSelectedPlayerOrSelf(); if (!player) @@ -78,7 +82,10 @@ public: // check item starting quest (it can work incorrectly if added without item in inventory) ItemTemplateContainer const* itc = sObjectMgr->GetItemTemplateStore(); - ItemTemplateContainer::const_iterator result = find_if (itc->begin(), itc->end(), Finder(entry, &ItemTemplate::StartQuest)); + ItemTemplateContainer::const_iterator result = std::find_if(itc->begin(), itc->end(), [quest](ItemTemplateContainer::value_type const& value) + { + return value.second.StartQuest == quest->GetQuestId(); + }); if (result != itc->end()) { @@ -89,12 +96,12 @@ public: // ok, normal (creature/GO starting) quest if (player->CanAddQuest(quest, true)) - player->AddQuestAndCheckCompletion(quest, NULL); + player->AddQuestAndCheckCompletion(quest, nullptr); return true; } - static bool HandleQuestRemove(ChatHandler* handler, const char* args) + static bool HandleQuestRemove(ChatHandler* handler, char const* args) { Player* player = handler->getSelectedPlayer(); if (!player) @@ -157,7 +164,7 @@ public: } } - static bool HandleQuestComplete(ChatHandler* handler, const char* args) + static bool HandleQuestComplete(ChatHandler* handler, char const* args) { Player* player = handler->getSelectedPlayerOrSelf(); if (!player) diff --git a/src/server/scripts/Commands/cs_rbac.cpp b/src/server/scripts/Commands/cs_rbac.cpp index 1da04269d43..c995c164699 100644 --- a/src/server/scripts/Commands/cs_rbac.cpp +++ b/src/server/scripts/Commands/cs_rbac.cpp @@ -22,16 +22,20 @@ Comment: All role based access control related commands (including account relat Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "AccountMgr.h" -#include "Config.h" #include "Chat.h" +#include "Config.h" #include "Language.h" #include "Player.h" -#include "ScriptMgr.h" +#include "RBAC.h" +#include "Realm.h" +#include "World.h" +#include "WorldSession.h" struct RBACCommandData { - RBACCommandData(): id(0), realmId(0), rbac(NULL), needDelete(false) { } + RBACCommandData(): id(0), realmId(0), rbac(nullptr), needDelete(false) { } ~RBACCommandData() { if (needDelete) @@ -61,13 +65,13 @@ public: static std::vector rbacCommandTable = { - { "account", rbac::RBAC_PERM_COMMAND_RBAC_ACC, true, NULL, "", rbacAccountCommandTable }, + { "account", rbac::RBAC_PERM_COMMAND_RBAC_ACC, true, nullptr, "", rbacAccountCommandTable }, { "list", rbac::RBAC_PERM_COMMAND_RBAC_LIST, true, &HandleRBACListPermissionsCommand, "" }, }; static std::vector commandTable = { - { "rbac", rbac::RBAC_PERM_COMMAND_RBAC, true, NULL, "", rbacCommandTable }, + { "rbac", rbac::RBAC_PERM_COMMAND_RBAC, true, nullptr, "", rbacCommandTable }, }; return commandTable; @@ -76,18 +80,18 @@ public: static RBACCommandData* ReadParams(ChatHandler* handler, char const* args, bool checkParams = true) { if (!args) - return NULL; + return nullptr; char* param1 = strtok((char*)args, " "); - char* param2 = strtok(NULL, " "); - char* param3 = strtok(NULL, " "); + char* param2 = strtok(nullptr, " "); + char* param3 = strtok(nullptr, " "); int32 realmId = -1; uint32 accountId = 0; std::string accountName; uint32 id = 0; - RBACCommandData* data = NULL; - rbac::RBACData* rdata = NULL; + RBACCommandData* data = nullptr; + rbac::RBACData* rdata = nullptr; bool useSelectedPlayer = false; if (checkParams) @@ -112,14 +116,14 @@ public: { handler->PSendSysMessage(LANG_RBAC_WRONG_PARAMETER_ID, id); handler->SetSentErrorMessage(true); - return NULL; + return nullptr; } if (realmId < -1 || !realmId) { handler->PSendSysMessage(LANG_RBAC_WRONG_PARAMETER_REALM, realmId); handler->SetSentErrorMessage(true); - return NULL; + return nullptr; } } else if (!param1) @@ -129,7 +133,7 @@ public: { Player* player = handler->getSelectedPlayer(); if (!player) - return NULL; + return nullptr; rdata = player->GetSession()->GetRBACData(); accountId = rdata->GetId(); @@ -146,12 +150,12 @@ public: { handler->PSendSysMessage(LANG_ACCOUNT_NOT_EXIST, accountName.c_str()); handler->SetSentErrorMessage(true); - return NULL; + return nullptr; } } - if (checkParams && handler->HasLowerSecurityAccount(NULL, accountId, true)) - return NULL; + if (checkParams && handler->HasLowerSecurityAccount(nullptr, accountId, true)) + return nullptr; data = new RBACCommandData(); diff --git a/src/server/scripts/Commands/cs_reload.cpp b/src/server/scripts/Commands/cs_reload.cpp index 2c4221203eb..63cb5340dc8 100644 --- a/src/server/scripts/Commands/cs_reload.cpp +++ b/src/server/scripts/Commands/cs_reload.cpp @@ -22,18 +22,22 @@ Comment: All reload related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "AccountMgr.h" #include "AchievementMgr.h" #include "AuctionHouseMgr.h" #include "BattlegroundMgr.h" #include "Chat.h" #include "CreatureTextMgr.h" +#include "DatabaseEnv.h" #include "DisableMgr.h" +#include "ItemEnchantmentMgr.h" #include "Language.h" #include "LFGMgr.h" +#include "Log.h" +#include "LootMgr.h" #include "MapManager.h" #include "ObjectMgr.h" -#include "ScriptMgr.h" #include "SkillDiscovery.h" #include "SkillExtraItems.h" #include "SmartAI.h" @@ -41,6 +45,7 @@ EndScriptData */ #include "TicketMgr.h" #include "WardenCheckMgr.h" #include "WaypointManager.h" +#include "World.h" class reload_commandscript : public CommandScript { @@ -164,13 +169,13 @@ public: } //reload commands - static bool HandleReloadGMTicketsCommand(ChatHandler* /*handler*/, const char* /*args*/) + static bool HandleReloadGMTicketsCommand(ChatHandler* /*handler*/, char const* /*args*/) { sTicketMgr->LoadTickets(); return true; } - static bool HandleReloadAllCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAllCommand(ChatHandler* handler, char const* /*args*/) { HandleReloadSkillFishingBaseLevelCommand(handler, ""); @@ -201,14 +206,14 @@ public: return true; } - static bool HandleReloadAllAchievementCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAllAchievementCommand(ChatHandler* handler, char const* /*args*/) { HandleReloadAchievementCriteriaDataCommand(handler, ""); HandleReloadAchievementRewardCommand(handler, ""); return true; } - static bool HandleReloadAllAreaCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAllAreaCommand(ChatHandler* handler, char const* /*args*/) { HandleReloadQuestGreetingCommand(handler, ""); //HandleReloadQuestAreaTriggersCommand(handler, ""); -- reloaded in HandleReloadAllQuestCommand @@ -218,7 +223,7 @@ public: return true; } - static bool HandleReloadAllLootCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAllLootCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables..."); LoadLootTables(); @@ -227,7 +232,7 @@ public: return true; } - static bool HandleReloadAllNpcCommand(ChatHandler* handler, const char* args) + static bool HandleReloadAllNpcCommand(ChatHandler* handler, char const* args) { if (*args != 'a') // will be reloaded from all_gossips HandleReloadNpcTrainerCommand(handler, "a"); @@ -237,7 +242,7 @@ public: return true; } - static bool HandleReloadAllQuestCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAllQuestCommand(ChatHandler* handler, char const* /*args*/) { HandleReloadQuestAreaTriggersCommand(handler, "a"); HandleReloadQuestPOICommand(handler, "a"); @@ -249,7 +254,7 @@ public: return true; } - static bool HandleReloadAllScriptsCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAllScriptsCommand(ChatHandler* handler, char const* /*args*/) { if (sMapMgr->IsScriptScheduled()) { @@ -267,7 +272,7 @@ public: return true; } - static bool HandleReloadAllSpellCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAllSpellCommand(ChatHandler* handler, char const* /*args*/) { HandleReloadSkillDiscoveryTemplateCommand(handler, "a"); HandleReloadSkillExtraItemTemplateCommand(handler, "a"); @@ -285,7 +290,7 @@ public: return true; } - static bool HandleReloadAllGossipsCommand(ChatHandler* handler, const char* args) + static bool HandleReloadAllGossipsCommand(ChatHandler* handler, char const* args) { HandleReloadGossipMenuCommand(handler, "a"); HandleReloadGossipMenuOptionCommand(handler, "a"); @@ -294,14 +299,14 @@ public: return true; } - static bool HandleReloadAllItemCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAllItemCommand(ChatHandler* handler, char const* /*args*/) { HandleReloadPageTextsCommand(handler, "a"); HandleReloadItemEnchantementsCommand(handler, "a"); return true; } - static bool HandleReloadAllLocalesCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAllLocalesCommand(ChatHandler* handler, char const* /*args*/) { HandleReloadLocalesAchievementRewardCommand(handler, "a"); HandleReloadLocalesCreatureCommand(handler, "a"); @@ -317,7 +322,7 @@ public: return true; } - static bool HandleReloadConfigCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadConfigCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading config settings..."); sWorld->LoadConfigSettings(true); @@ -326,7 +331,7 @@ public: return true; } - static bool HandleReloadAccessRequirementCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAccessRequirementCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Access Requirement definitions..."); sObjectMgr->LoadAccessRequirements(); @@ -334,7 +339,7 @@ public: return true; } - static bool HandleReloadAchievementCriteriaDataCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAchievementCriteriaDataCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Additional Achievement Criteria Data..."); sAchievementMgr->LoadAchievementCriteriaData(); @@ -342,7 +347,7 @@ public: return true; } - static bool HandleReloadAchievementRewardCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAchievementRewardCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Achievement Reward Data..."); sAchievementMgr->LoadRewards(); @@ -350,7 +355,7 @@ public: return true; } - static bool HandleReloadAreaTriggerTavernCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAreaTriggerTavernCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Tavern Area Triggers..."); sObjectMgr->LoadTavernAreaTriggers(); @@ -358,7 +363,7 @@ public: return true; } - static bool HandleReloadAreaTriggerTeleportCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAreaTriggerTeleportCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading AreaTrigger teleport definitions..."); sObjectMgr->LoadAreaTriggerTeleports(); @@ -366,7 +371,7 @@ public: return true; } - static bool HandleReloadAutobroadcastCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAutobroadcastCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Autobroadcasts..."); sWorld->LoadAutobroadcasts(); @@ -382,7 +387,7 @@ public: return true; } - static bool HandleReloadBroadcastTextCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadBroadcastTextCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Broadcast texts..."); sObjectMgr->LoadBroadcastTexts(); @@ -391,14 +396,14 @@ public: return true; } - static bool HandleReloadCommandCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadCommandCommand(ChatHandler* handler, char const* /*args*/) { ChatHandler::invalidateCommandTable(); handler->SendGlobalGMSysMessage("DB table `command` will be reloaded at next chat command use."); return true; } - static bool HandleReloadOnKillReputationCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadOnKillReputationCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading creature award reputation definitions..."); sObjectMgr->LoadReputationOnKill(); @@ -406,7 +411,7 @@ public: return true; } - static bool HandleReloadCreatureSummonGroupsCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadCreatureSummonGroupsCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Reloading creature summon groups..."); sObjectMgr->LoadTempSummons(); @@ -414,7 +419,7 @@ public: return true; } - static bool HandleReloadCreatureTemplateCommand(ChatHandler* handler, const char* args) + static bool HandleReloadCreatureTemplateCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -453,7 +458,7 @@ public: return true; } - static bool HandleReloadCreatureQuestStarterCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadCreatureQuestStarterCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Loading Quests Relations... (`creature_queststarter`)"); sObjectMgr->LoadCreatureQuestStarters(); @@ -461,7 +466,7 @@ public: return true; } - static bool HandleReloadLinkedRespawnCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLinkedRespawnCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Loading Linked Respawns... (`creature_linked_respawn`)"); sObjectMgr->LoadLinkedRespawn(); @@ -469,7 +474,7 @@ public: return true; } - static bool HandleReloadCreatureQuestEnderCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadCreatureQuestEnderCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Loading Quests Relations... (`creature_questender`)"); sObjectMgr->LoadCreatureQuestEnders(); @@ -477,7 +482,7 @@ public: return true; } - static bool HandleReloadGossipMenuCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadGossipMenuCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `gossip_menu` Table!"); sObjectMgr->LoadGossipMenu(); @@ -486,7 +491,7 @@ public: return true; } - static bool HandleReloadGossipMenuOptionCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadGossipMenuOptionCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `gossip_menu_option` Table!"); sObjectMgr->LoadGossipMenuItems(); @@ -495,7 +500,7 @@ public: return true; } - static bool HandleReloadGOQuestStarterCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadGOQuestStarterCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Loading Quests Relations... (`gameobject_queststarter`)"); sObjectMgr->LoadGameobjectQuestStarters(); @@ -503,7 +508,7 @@ public: return true; } - static bool HandleReloadGOQuestEnderCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadGOQuestEnderCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Loading Quests Relations... (`gameobject_questender`)"); sObjectMgr->LoadGameobjectQuestEnders(); @@ -511,7 +516,7 @@ public: return true; } - static bool HandleReloadQuestAreaTriggersCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadQuestAreaTriggersCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Quest Area Triggers..."); sObjectMgr->LoadQuestAreaTriggers(); @@ -535,7 +540,7 @@ public: return true; } - static bool HandleReloadQuestTemplateCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadQuestTemplateCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Quest Templates..."); sObjectMgr->LoadQuests(); @@ -548,7 +553,7 @@ public: return true; } - static bool HandleReloadLootTemplatesCreatureCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesCreatureCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`creature_loot_template`)"); LoadLootTemplates_Creature(); @@ -558,7 +563,7 @@ public: return true; } - static bool HandleReloadLootTemplatesDisenchantCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesDisenchantCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`disenchant_loot_template`)"); LoadLootTemplates_Disenchant(); @@ -568,7 +573,7 @@ public: return true; } - static bool HandleReloadLootTemplatesFishingCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesFishingCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`fishing_loot_template`)"); LoadLootTemplates_Fishing(); @@ -578,7 +583,7 @@ public: return true; } - static bool HandleReloadLootTemplatesGameobjectCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesGameobjectCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`gameobject_loot_template`)"); LoadLootTemplates_Gameobject(); @@ -588,7 +593,7 @@ public: return true; } - static bool HandleReloadLootTemplatesItemCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesItemCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`item_loot_template`)"); LoadLootTemplates_Item(); @@ -598,7 +603,7 @@ public: return true; } - static bool HandleReloadLootTemplatesMillingCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesMillingCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`milling_loot_template`)"); LoadLootTemplates_Milling(); @@ -608,7 +613,7 @@ public: return true; } - static bool HandleReloadLootTemplatesPickpocketingCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesPickpocketingCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`pickpocketing_loot_template`)"); LoadLootTemplates_Pickpocketing(); @@ -618,7 +623,7 @@ public: return true; } - static bool HandleReloadLootTemplatesProspectingCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesProspectingCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`prospecting_loot_template`)"); LoadLootTemplates_Prospecting(); @@ -628,7 +633,7 @@ public: return true; } - static bool HandleReloadLootTemplatesMailCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesMailCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`mail_loot_template`)"); LoadLootTemplates_Mail(); @@ -638,7 +643,7 @@ public: return true; } - static bool HandleReloadLootTemplatesReferenceCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesReferenceCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`reference_loot_template`)"); LoadLootTemplates_Reference(); @@ -647,7 +652,7 @@ public: return true; } - static bool HandleReloadLootTemplatesSkinningCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesSkinningCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`skinning_loot_template`)"); LoadLootTemplates_Skinning(); @@ -657,7 +662,7 @@ public: return true; } - static bool HandleReloadLootTemplatesSpellCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLootTemplatesSpellCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Loot Tables... (`spell_loot_template`)"); LoadLootTemplates_Spell(); @@ -667,7 +672,7 @@ public: return true; } - static bool HandleReloadTrinityStringCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadTrinityStringCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading trinity_string Table!"); sObjectMgr->LoadTrinityStrings(); @@ -675,7 +680,7 @@ public: return true; } - static bool HandleReloadWardenactionCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadWardenactionCommand(ChatHandler* handler, char const* /*args*/) { if (!sWorld->getBoolConfig(CONFIG_WARDEN_ENABLED)) { @@ -690,7 +695,7 @@ public: return true; } - static bool HandleReloadNpcTrainerCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadNpcTrainerCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `npc_trainer` Table!"); sObjectMgr->LoadTrainerSpell(); @@ -698,7 +703,7 @@ public: return true; } - static bool HandleReloadNpcVendorCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadNpcVendorCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `npc_vendor` Table!"); sObjectMgr->LoadVendors(); @@ -706,7 +711,7 @@ public: return true; } - static bool HandleReloadPointsOfInterestCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadPointsOfInterestCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `points_of_interest` Table!"); sObjectMgr->LoadPointsOfInterest(); @@ -714,7 +719,7 @@ public: return true; } - static bool HandleReloadQuestPOICommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadQuestPOICommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Quest POI ..." ); sObjectMgr->LoadQuestPOI(); @@ -722,7 +727,7 @@ public: return true; } - static bool HandleReloadSpellClickSpellsCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellClickSpellsCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `npc_spellclick_spells` Table!"); sObjectMgr->LoadNPCSpellClickSpells(); @@ -730,7 +735,7 @@ public: return true; } - static bool HandleReloadReservedNameCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadReservedNameCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Loading ReservedNames... (`reserved_name`)"); sObjectMgr->LoadReservedPlayersNames(); @@ -738,7 +743,7 @@ public: return true; } - static bool HandleReloadReputationRewardRateCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadReputationRewardRateCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `reputation_reward_rate` Table!" ); sObjectMgr->LoadReputationRewardRate(); @@ -746,7 +751,7 @@ public: return true; } - static bool HandleReloadReputationSpilloverTemplateCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadReputationSpilloverTemplateCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading `reputation_spillover_template` Table!" ); sObjectMgr->LoadReputationSpilloverTemplate(); @@ -754,7 +759,7 @@ public: return true; } - static bool HandleReloadSkillDiscoveryTemplateCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSkillDiscoveryTemplateCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Skill Discovery Table..."); LoadSkillDiscoveryTable(); @@ -762,7 +767,7 @@ public: return true; } - static bool HandleReloadSkillPerfectItemTemplateCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSkillPerfectItemTemplateCommand(ChatHandler* handler, char const* /*args*/) { // latched onto HandleReloadSkillExtraItemTemplateCommand as it's part of that table group (and i don't want to chance all the command IDs) TC_LOG_INFO("misc", "Re-Loading Skill Perfection Data Table..."); LoadSkillPerfectItemTable(); @@ -770,7 +775,7 @@ public: return true; } - static bool HandleReloadSkillExtraItemTemplateCommand(ChatHandler* handler, const char* args) + static bool HandleReloadSkillExtraItemTemplateCommand(ChatHandler* handler, char const* args) { TC_LOG_INFO("misc", "Re-Loading Skill Extra Item Table..."); LoadSkillExtraItemTable(); @@ -779,7 +784,7 @@ public: return HandleReloadSkillPerfectItemTemplateCommand(handler, args); } - static bool HandleReloadSkillFishingBaseLevelCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSkillFishingBaseLevelCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Skill Fishing base level requirements..."); sObjectMgr->LoadFishingBaseSkillLevel(); @@ -787,7 +792,7 @@ public: return true; } - static bool HandleReloadSpellAreaCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellAreaCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading SpellArea Data..."); sSpellMgr->LoadSpellAreas(); @@ -795,7 +800,7 @@ public: return true; } - static bool HandleReloadSpellRequiredCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellRequiredCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell Required Data... "); sSpellMgr->LoadSpellRequired(); @@ -803,7 +808,7 @@ public: return true; } - static bool HandleReloadSpellGroupsCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellGroupsCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell Groups..."); sSpellMgr->LoadSpellGroups(); @@ -811,7 +816,7 @@ public: return true; } - static bool HandleReloadSpellLearnSpellCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellLearnSpellCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell Learn Spells..."); sSpellMgr->LoadSpellLearnSpells(); @@ -819,7 +824,7 @@ public: return true; } - static bool HandleReloadSpellLinkedSpellCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellLinkedSpellCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell Linked Spells..."); sSpellMgr->LoadSpellLinked(); @@ -827,7 +832,7 @@ public: return true; } - static bool HandleReloadSpellProcsCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellProcsCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell Proc conditions and data..."); sSpellMgr->LoadSpellProcs(); @@ -835,7 +840,7 @@ public: return true; } - static bool HandleReloadSpellBonusesCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellBonusesCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell Bonus Data..."); sSpellMgr->LoadSpellBonusess(); @@ -843,7 +848,7 @@ public: return true; } - static bool HandleReloadSpellTargetPositionCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellTargetPositionCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell target coordinates..."); sSpellMgr->LoadSpellTargetPositions(); @@ -851,7 +856,7 @@ public: return true; } - static bool HandleReloadSpellThreatsCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellThreatsCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Aggro Spells Definitions..."); sSpellMgr->LoadSpellThreats(); @@ -859,7 +864,7 @@ public: return true; } - static bool HandleReloadSpellGroupStackRulesCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellGroupStackRulesCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell Group Stack Rules..."); sSpellMgr->LoadSpellGroupStackRules(); @@ -867,7 +872,7 @@ public: return true; } - static bool HandleReloadSpellPetAurasCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSpellPetAurasCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Spell pet auras..."); sSpellMgr->LoadSpellPetAuras(); @@ -875,7 +880,7 @@ public: return true; } - static bool HandleReloadPageTextsCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadPageTextsCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Page Text..."); sObjectMgr->LoadPageTexts(); @@ -883,7 +888,7 @@ public: return true; } - static bool HandleReloadItemEnchantementsCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadItemEnchantementsCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Item Random Enchantments Table..."); LoadRandomEnchantmentsTable(); @@ -891,7 +896,7 @@ public: return true; } - static bool HandleReloadEventScriptsCommand(ChatHandler* handler, const char* args) + static bool HandleReloadEventScriptsCommand(ChatHandler* handler, char const* args) { if (sMapMgr->IsScriptScheduled()) { @@ -911,7 +916,7 @@ public: return true; } - static bool HandleReloadWpScriptsCommand(ChatHandler* handler, const char* args) + static bool HandleReloadWpScriptsCommand(ChatHandler* handler, char const* args) { if (sMapMgr->IsScriptScheduled()) { @@ -931,7 +936,7 @@ public: return true; } - static bool HandleReloadWpCommand(ChatHandler* handler, const char* args) + static bool HandleReloadWpCommand(ChatHandler* handler, char const* args) { if (*args != 'a') TC_LOG_INFO("misc", "Re-Loading Waypoints data from 'waypoints_data'"); @@ -944,7 +949,7 @@ public: return true; } - static bool HandleReloadSpellScriptsCommand(ChatHandler* handler, const char* args) + static bool HandleReloadSpellScriptsCommand(ChatHandler* handler, char const* args) { if (sMapMgr->IsScriptScheduled()) { @@ -964,7 +969,7 @@ public: return true; } - static bool HandleReloadGameGraveyardZoneCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadGameGraveyardZoneCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Graveyard-zone links..."); @@ -975,7 +980,7 @@ public: return true; } - static bool HandleReloadGameTeleCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadGameTeleCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Game Tele coordinates..."); @@ -986,7 +991,7 @@ public: return true; } - static bool HandleReloadDisablesCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadDisablesCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading disables table..."); DisableMgr::LoadDisables(); @@ -996,7 +1001,7 @@ public: return true; } - static bool HandleReloadLocalesAchievementRewardCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesAchievementRewardCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Achievement Reward Data Locale..."); sAchievementMgr->LoadRewardLocales(); @@ -1004,7 +1009,7 @@ public: return true; } - static bool HandleReloadLfgRewardsCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLfgRewardsCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading lfg dungeon rewards..."); sLFGMgr->LoadRewards(); @@ -1012,7 +1017,7 @@ public: return true; } - static bool HandleReloadLocalesCreatureCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesCreatureCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Creature Template Locale..."); sObjectMgr->LoadCreatureLocales(); @@ -1020,7 +1025,7 @@ public: return true; } - static bool HandleReloadLocalesCreatureTextCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesCreatureTextCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Creature Texts Locale..."); sCreatureTextMgr->LoadCreatureTextLocales(); @@ -1028,7 +1033,7 @@ public: return true; } - static bool HandleReloadLocalesGameobjectCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesGameobjectCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Gameobject Template Locale... "); sObjectMgr->LoadGameObjectLocales(); @@ -1036,7 +1041,7 @@ public: return true; } - static bool HandleReloadLocalesGossipMenuOptionCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesGossipMenuOptionCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Gossip Menu Option Locale... "); sObjectMgr->LoadGossipMenuItemsLocales(); @@ -1044,7 +1049,7 @@ public: return true; } - static bool HandleReloadLocalesItemCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesItemCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Item Template Locale... "); sObjectMgr->LoadItemLocales(); @@ -1052,7 +1057,7 @@ public: return true; } - static bool HandleReloadLocalesNpcTextCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesNpcTextCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading NPC Text Locale... "); sObjectMgr->LoadNpcTextLocales(); @@ -1060,7 +1065,7 @@ public: return true; } - static bool HandleReloadLocalesPageTextCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesPageTextCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Page Text Locale... "); sObjectMgr->LoadPageTextLocales(); @@ -1068,7 +1073,7 @@ public: return true; } - static bool HandleReloadLocalesPointsOfInterestCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesPointsOfInterestCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Points Of Interest Locale... "); sObjectMgr->LoadPointOfInterestLocales(); @@ -1076,7 +1081,7 @@ public: return true; } - static bool HandleReloadLocalesQuestCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadLocalesQuestCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Quest Template Locale... "); sObjectMgr->LoadQuestLocales(); @@ -1084,7 +1089,7 @@ public: return true; } - static bool HandleReloadMailLevelRewardCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadMailLevelRewardCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Player level dependent mail rewards..."); sObjectMgr->LoadMailLevelRewards(); @@ -1092,7 +1097,7 @@ public: return true; } - static bool HandleReloadAuctionsCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadAuctionsCommand(ChatHandler* handler, char const* /*args*/) { ///- Reload dynamic data tables from the database TC_LOG_INFO("misc", "Re-Loading Auctions..."); @@ -1102,7 +1107,7 @@ public: return true; } - static bool HandleReloadConditions(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadConditions(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Conditions..."); sConditionMgr->LoadConditions(true); @@ -1110,7 +1115,7 @@ public: return true; } - static bool HandleReloadCreatureText(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadCreatureText(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Creature Texts..."); sCreatureTextMgr->LoadCreatureTexts(); @@ -1118,7 +1123,7 @@ public: return true; } - static bool HandleReloadSmartScripts(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadSmartScripts(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Re-Loading Smart Scripts..."); sSmartScriptMgr->LoadSmartAIFromDB(); @@ -1126,7 +1131,7 @@ public: return true; } - static bool HandleReloadVehicleAccessoryCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadVehicleAccessoryCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Reloading vehicle_accessory table..."); sObjectMgr->LoadVehicleAccessories(); @@ -1134,7 +1139,7 @@ public: return true; } - static bool HandleReloadVehicleTemplateAccessoryCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadVehicleTemplateAccessoryCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Reloading vehicle_template_accessory table..."); sObjectMgr->LoadVehicleTemplateAccessories(); @@ -1142,7 +1147,7 @@ public: return true; } - static bool HandleReloadRBACCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleReloadRBACCommand(ChatHandler* handler, char const* /*args*/) { TC_LOG_INFO("misc", "Reloading RBAC tables..."); sAccountMgr->LoadRBAC(); diff --git a/src/server/scripts/Commands/cs_reset.cpp b/src/server/scripts/Commands/cs_reset.cpp index 76cbade7973..407c4975054 100644 --- a/src/server/scripts/Commands/cs_reset.cpp +++ b/src/server/scripts/Commands/cs_reset.cpp @@ -22,13 +22,20 @@ Comment: All reset related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "AchievementMgr.h" #include "Chat.h" +#include "DatabaseEnv.h" #include "Language.h" +#include "Log.h" #include "ObjectAccessor.h" -#include "Player.h" #include "Pet.h" -#include "ScriptMgr.h" +#include "Player.h" +#include "RBAC.h" +#include "World.h" +#include "WorldSession.h" +#include +#include class reset_commandscript : public CommandScript { @@ -49,7 +56,7 @@ public: }; static std::vector commandTable = { - { "reset", rbac::RBAC_PERM_COMMAND_RESET, true, NULL, "", resetCommandTable }, + { "reset", rbac::RBAC_PERM_COMMAND_RESET, true, nullptr, "", resetCommandTable }, }; return commandTable; } diff --git a/src/server/scripts/Commands/cs_send.cpp b/src/server/scripts/Commands/cs_send.cpp index 2f4565111f1..8cd21381d1f 100644 --- a/src/server/scripts/Commands/cs_send.cpp +++ b/src/server/scripts/Commands/cs_send.cpp @@ -15,12 +15,17 @@ * with this program. If not, see . */ +#include "ScriptMgr.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "Item.h" #include "Language.h" +#include "Mail.h" +#include "ObjectMgr.h" #include "Pet.h" #include "Player.h" -#include "ObjectMgr.h" -#include "ScriptMgr.h" +#include "RBAC.h" +#include "WorldSession.h" class send_commandscript : public CommandScript { @@ -39,7 +44,7 @@ public: static std::vector commandTable = { - { "send", rbac::RBAC_PERM_COMMAND_SEND, false, NULL, "", sendCommandTable }, + { "send", rbac::RBAC_PERM_COMMAND_SEND, false, nullptr, "", sendCommandTable }, }; return commandTable; } @@ -54,7 +59,7 @@ public: if (!handler->extractPlayerTarget((char*)args, &target, &targetGuid, &targetName)) return false; - char* tail1 = strtok(NULL, ""); + char* tail1 = strtok(nullptr, ""); if (!tail1) return false; @@ -62,7 +67,7 @@ public: if (!msgSubject) return false; - char* tail2 = strtok(NULL, ""); + char* tail2 = strtok(nullptr, ""); if (!tail2) return false; @@ -99,7 +104,7 @@ public: if (!handler->extractPlayerTarget((char*)args, &receiver, &receiverGuid, &receiverName)) return false; - char* tail1 = strtok(NULL, ""); + char* tail1 = strtok(nullptr, ""); if (!tail1) return false; @@ -107,7 +112,7 @@ public: if (!msgSubject) return false; - char* tail2 = strtok(NULL, ""); + char* tail2 = strtok(nullptr, ""); if (!tail2) return false; @@ -125,17 +130,17 @@ public: ItemPairs items; // get all tail string - char* tail = strtok(NULL, ""); + char* tail = strtok(nullptr, ""); // get from tail next item str while (char* itemStr = strtok(tail, " ")) { // and get new tail - tail = strtok(NULL, ""); + tail = strtok(nullptr, ""); // parse item str char const* itemIdStr = strtok(itemStr, ":"); - char const* itemCountStr = strtok(NULL, " "); + char const* itemCountStr = strtok(nullptr, " "); uint32 itemId = atoi(itemIdStr); if (!itemId) @@ -208,7 +213,7 @@ public: if (!handler->extractPlayerTarget((char*)args, &receiver, &receiverGuid, &receiverName)) return false; - char* tail1 = strtok(NULL, ""); + char* tail1 = strtok(nullptr, ""); if (!tail1) return false; @@ -216,7 +221,7 @@ public: if (!msgSubject) return false; - char* tail2 = strtok(NULL, ""); + char* tail2 = strtok(nullptr, ""); if (!tail2) return false; @@ -224,7 +229,7 @@ public: if (!msgText) return false; - char* moneyStr = strtok(NULL, ""); + char* moneyStr = strtok(nullptr, ""); int32 money = moneyStr ? atoi(moneyStr) : 0; if (money <= 0) return false; @@ -256,7 +261,7 @@ public: if (!handler->extractPlayerTarget((char*)args, &player)) return false; - char* msgStr = strtok(NULL, ""); + char* msgStr = strtok(nullptr, ""); if (!msgStr) return false; diff --git a/src/server/scripts/Commands/cs_tele.cpp b/src/server/scripts/Commands/cs_tele.cpp index 4eb2c7da7c4..912df3da810 100644 --- a/src/server/scripts/Commands/cs_tele.cpp +++ b/src/server/scripts/Commands/cs_tele.cpp @@ -22,14 +22,19 @@ Comment: All tele related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "Chat.h" +#include "DatabaseEnv.h" +#include "DBCStores.h" #include "Group.h" #include "Language.h" #include "MapManager.h" +#include "MotionMaster.h" #include "ObjectMgr.h" #include "PhasingHandler.h" #include "Player.h" -#include "ScriptMgr.h" +#include "RBAC.h" +#include "WorldSession.h" class tele_commandscript : public CommandScript { @@ -48,12 +53,12 @@ public: }; static std::vector commandTable = { - { "tele", rbac::RBAC_PERM_COMMAND_TELE, false, NULL, "", teleCommandTable }, + { "tele", rbac::RBAC_PERM_COMMAND_TELE, false, nullptr, "", teleCommandTable }, }; return commandTable; } - static bool HandleTeleAddCommand(ChatHandler* handler, const char* args) + static bool HandleTeleAddCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -93,7 +98,7 @@ public: return true; } - static bool HandleTeleDelCommand(ChatHandler* handler, const char* args) + static bool HandleTeleDelCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -113,7 +118,7 @@ public: } // teleport player to given game_tele.entry - static bool HandleTeleNameCommand(ChatHandler* handler, const char* args) + static bool HandleTeleNameCommand(ChatHandler* handler, char const* args) { char* nameStr; char* teleStr; @@ -194,7 +199,7 @@ public: else { // check offline security - if (handler->HasLowerSecurity(NULL, target_guid)) + if (handler->HasLowerSecurity(nullptr, target_guid)) return false; std::string nameLink = handler->playerLink(target_name); @@ -210,7 +215,7 @@ public: } //Teleport group to given game_tele.entry - static bool HandleTeleGroupCommand(ChatHandler* handler, const char* args) + static bool HandleTeleGroupCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -254,7 +259,7 @@ public: return false; } - for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = grp->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* player = itr->GetSource(); @@ -293,7 +298,7 @@ public: return true; } - static bool HandleTeleCommand(ChatHandler* handler, const char* args) + static bool HandleTeleCommand(ChatHandler* handler, char const* args) { if (!*args) return false; diff --git a/src/server/scripts/Commands/cs_ticket.cpp b/src/server/scripts/Commands/cs_ticket.cpp index ec372bc2ea4..b068a48d918 100644 --- a/src/server/scripts/Commands/cs_ticket.cpp +++ b/src/server/scripts/Commands/cs_ticket.cpp @@ -22,15 +22,19 @@ Comment: All ticket related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "AccountMgr.h" #include "CharacterCache.h" #include "Chat.h" #include "Language.h" +#include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Opcodes.h" #include "Player.h" +#include "Realm.h" #include "TicketMgr.h" -#include "ScriptMgr.h" +#include "World.h" +#include "WorldSession.h" class ticket_commandscript : public CommandScript { @@ -67,7 +71,7 @@ public: static std::vector commandTable = { - { "ticket", rbac::RBAC_PERM_COMMAND_TICKET, false, NULL, "", ticketCommandTable }, + { "ticket", rbac::RBAC_PERM_COMMAND_TICKET, false, nullptr, "", ticketCommandTable }, }; return commandTable; @@ -81,7 +85,7 @@ public: char* ticketIdStr = strtok((char*)args, " "); uint32 ticketId = atoi(ticketIdStr); - char* targetStr = strtok(NULL, " "); + char* targetStr = strtok(nullptr, " "); if (!targetStr) return false; @@ -122,12 +126,12 @@ public: } // Assign ticket - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); ticket->SetAssignedTo(targetGuid, AccountMgr::IsAdminAccount(AccountMgr::GetSecurity(accountId, realm.Id.Realm))); ticket->SaveToDB(trans); sTicketMgr->UpdateLastChange(); - std::string msg = ticket->FormatMessageString(*handler, NULL, target.c_str(), NULL, NULL, NULL); + std::string msg = ticket->FormatMessageString(*handler, nullptr, target.c_str(), nullptr, nullptr, nullptr); handler->SendGlobalGMSysMessage(msg.c_str()); return true; } @@ -157,7 +161,7 @@ public: sTicketMgr->ResolveAndCloseTicket(ticket->GetId(), player ? player->GetGUID() : ObjectGuid(uint64(0))); sTicketMgr->UpdateLastChange(); - std::string msg = ticket->FormatMessageString(*handler, player ? player->GetName().c_str() : "Console", NULL, NULL, NULL, NULL); + std::string msg = ticket->FormatMessageString(*handler, player ? player->GetName().c_str() : "Console", nullptr, nullptr, nullptr, nullptr); handler->SendGlobalGMSysMessage(msg.c_str()); // Inform player, who submitted this ticket, that it is closed @@ -165,7 +169,7 @@ public: { WorldPacket data(SMSG_GMTICKET_DELETETICKET, 4); data << uint32(GMTICKET_RESPONSE_TICKET_DELETED); - submitter->GetSession()->SendPacket(&data); + submitter->SendDirectMessage(&data); } return true; } @@ -178,7 +182,7 @@ public: char* ticketIdStr = strtok((char*)args, " "); uint32 ticketId = atoi(ticketIdStr); - char* comment = strtok(NULL, "\n"); + char* comment = strtok(nullptr, "\n"); if (!comment) return false; @@ -198,7 +202,7 @@ public: return true; } - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); ticket->SetComment(comment); ticket->SaveToDB(trans); sTicketMgr->UpdateLastChange(); @@ -236,7 +240,7 @@ public: return true; } - char* response = strtok(NULL, "\n"); + char* response = strtok(nullptr, "\n"); if (response) { // Cannot add response to ticket, assigned to someone else @@ -256,13 +260,13 @@ public: Player* gm = handler->GetSession() ? handler->GetSession()->GetPlayer() : nullptr; - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); ticket->SetResolvedBy(gm ? gm->GetGUID() : ObjectGuid(uint64(0))); ticket->SetCompleted(); ticket->SaveToDB(trans); - std::string msg = ticket->FormatMessageString(*handler, NULL, NULL, - NULL, NULL, handler->GetSession() ? handler->GetSession()->GetPlayer()->GetName().c_str() : "Console"); + std::string msg = ticket->FormatMessageString(*handler, nullptr, nullptr, + nullptr, nullptr, handler->GetSession() ? handler->GetSession()->GetPlayer()->GetName().c_str() : "Console"); handler->SendGlobalGMSysMessage(msg.c_str()); sTicketMgr->UpdateLastChange(); return true; @@ -287,7 +291,7 @@ public: return true; } - std::string msg = ticket->FormatMessageString(*handler, NULL, NULL, NULL, handler->GetSession() ? handler->GetSession()->GetPlayer()->GetName().c_str() : "Console", NULL); + std::string msg = ticket->FormatMessageString(*handler, nullptr, nullptr, nullptr, handler->GetSession() ? handler->GetSession()->GetPlayer()->GetName().c_str() : "Console", nullptr); handler->SendGlobalGMSysMessage(msg.c_str()); sTicketMgr->RemoveTicket(ticket->GetId()); @@ -298,7 +302,7 @@ public: // Force abandon ticket WorldPacket data(SMSG_GMTICKET_DELETETICKET, 4); data << uint32(GMTICKET_RESPONSE_TICKET_DELETED); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } return true; @@ -409,13 +413,13 @@ public: } std::string assignedTo = ticket->GetAssignedToName(); // copy assignedto name because we need it after the ticket has been unnassigned - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); ticket->SetUnassigned(); ticket->SaveToDB(trans); sTicketMgr->UpdateLastChange(); - std::string msg = ticket->FormatMessageString(*handler, NULL, assignedTo.c_str(), - handler->GetSession() ? handler->GetSession()->GetPlayer()->GetName().c_str() : "Console", NULL, NULL); + std::string msg = ticket->FormatMessageString(*handler, nullptr, assignedTo.c_str(), + handler->GetSession() ? handler->GetSession()->GetPlayer()->GetName().c_str() : "Console", nullptr, nullptr); handler->SendGlobalGMSysMessage(msg.c_str()); return true; @@ -434,7 +438,7 @@ public: return true; } - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); ticket->SetViewed(); ticket->SaveToDB(trans); @@ -473,7 +477,7 @@ public: return true; } - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); ticket->SetViewed(); ticket->SaveToDB(trans); @@ -489,7 +493,7 @@ public: char* ticketIdStr = strtok((char*)args, " "); uint32 ticketId = atoi(ticketIdStr); - char* response = strtok(NULL, "\n"); + char* response = strtok(nullptr, "\n"); if (!response) return false; @@ -509,7 +513,7 @@ public: return true; } - SQLTransaction trans = SQLTransaction(NULL); + SQLTransaction trans = SQLTransaction(nullptr); ticket->AppendResponse(response); if (newLine) ticket->AppendResponse("\n"); diff --git a/src/server/scripts/Commands/cs_titles.cpp b/src/server/scripts/Commands/cs_titles.cpp index 495f548ce15..ad8aab3e21d 100644 --- a/src/server/scripts/Commands/cs_titles.cpp +++ b/src/server/scripts/Commands/cs_titles.cpp @@ -22,11 +22,13 @@ Comment: All titles related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "Chat.h" +#include "DBCStores.h" #include "Language.h" #include "ObjectMgr.h" #include "Player.h" -#include "ScriptMgr.h" +#include "RBAC.h" class titles_commandscript : public CommandScript { @@ -44,11 +46,11 @@ public: { "add", rbac::RBAC_PERM_COMMAND_TITLES_ADD, false, &HandleTitlesAddCommand, "" }, { "current", rbac::RBAC_PERM_COMMAND_TITLES_CURRENT, false, &HandleTitlesCurrentCommand, "" }, { "remove", rbac::RBAC_PERM_COMMAND_TITLES_REMOVE, false, &HandleTitlesRemoveCommand, "" }, - { "set", rbac::RBAC_PERM_COMMAND_TITLES_SET, false, NULL, "", titlesSetCommandTable }, + { "set", rbac::RBAC_PERM_COMMAND_TITLES_SET, false, nullptr, "", titlesSetCommandTable }, }; static std::vector commandTable = { - { "titles", rbac::RBAC_PERM_COMMAND_TITLES, false, NULL, "", titlesCommandTable }, + { "titles", rbac::RBAC_PERM_COMMAND_TITLES, false, nullptr, "", titlesCommandTable }, }; return commandTable; } @@ -133,12 +135,10 @@ public: } std::string tNameLink = handler->GetNameLink(target); - - char titleNameStr[80]; - snprintf(titleNameStr, 80, target->getGender() == GENDER_MALE ? titleInfo->nameMale : titleInfo->nameFemale, target->GetName().c_str()); + std::string titleNameStr = Trinity::StringFormat(target->getGender() == GENDER_MALE ? titleInfo->nameMale : titleInfo->nameFemale, target->GetName().c_str()); target->SetTitle(titleInfo); - handler->PSendSysMessage(LANG_TITLE_ADD_RES, id, titleNameStr, tNameLink.c_str()); + handler->PSendSysMessage(LANG_TITLE_ADD_RES, id, titleNameStr.c_str(), tNameLink.c_str()); return true; } @@ -202,9 +202,7 @@ public: if (!*args) return false; - uint64 titles = 0; - - sscanf((char*)args, UI64FMTD, &titles); + uint64 titles = atoull(args); Player* target = handler->getSelectedPlayer(); if (!target) @@ -218,13 +216,11 @@ public: if (handler->HasLowerSecurity(target, ObjectGuid::Empty)) return false; - uint64 titles2 = titles; + uint64 allValidTitleMask = 0; + for (CharTitlesEntry const* tEntry : sCharTitlesStore) + allValidTitleMask |= (uint64(1) << tEntry->bit_index); - for (uint32 i = 1; i < sCharTitlesStore.GetNumRows(); ++i) - if (CharTitlesEntry const* tEntry = sCharTitlesStore.LookupEntry(i)) - titles2 &= ~(uint64(1) << tEntry->bit_index); - - titles &= ~titles2; // remove non-existing titles + titles &= allValidTitleMask; // 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 5b1decd2984..66ffb1371ea 100644 --- a/src/server/scripts/Commands/cs_wp.cpp +++ b/src/server/scripts/Commands/cs_wp.cpp @@ -22,13 +22,19 @@ Comment: All wp related commands Category: commandscripts EndScriptData */ +#include "ScriptMgr.h" #include "Chat.h" +#include "Creature.h" +#include "DatabaseEnv.h" #include "Language.h" +#include "Map.h" +#include "MotionMaster.h" #include "ObjectMgr.h" #include "PhasingHandler.h" #include "Player.h" -#include "ScriptMgr.h" +#include "RBAC.h" #include "WaypointManager.h" +#include "WorldSession.h" class wp_commandscript : public CommandScript { @@ -49,7 +55,7 @@ public: }; static std::vector commandTable = { - { "wp", rbac::RBAC_PERM_COMMAND_WP, false, NULL, "", wpCommandTable }, + { "wp", rbac::RBAC_PERM_COMMAND_WP, false, nullptr, "", wpCommandTable }, }; return commandTable; } @@ -70,14 +76,14 @@ public: * -> adds a waypoint to the currently selected creature * * - * @param args if the user did not provide a GUID, it is NULL + * @param args if the user did not provide a GUID, it is nullptr * * @return true - command did succeed, false - something went wrong */ - static bool HandleWpAddCommand(ChatHandler* handler, const char* args) + static bool HandleWpAddCommand(ChatHandler* handler, char const* args) { // optional - char* path_number = NULL; + char* path_number = nullptr; uint32 pathid = 0; if (*args) @@ -137,13 +143,13 @@ public: return true; } // HandleWpAddCommand - static bool HandleWpLoadCommand(ChatHandler* handler, const char* args) + static bool HandleWpLoadCommand(ChatHandler* handler, char const* args) { if (!*args) return false; // optional - char* path_number = NULL; + char* path_number = nullptr; if (*args) path_number = strtok((char*)args, " "); @@ -218,7 +224,7 @@ public: return true; } - static bool HandleWpReloadCommand(ChatHandler* handler, const char* args) + static bool HandleWpReloadCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -233,11 +239,11 @@ public: return true; } - static bool HandleWpUnLoadCommand(ChatHandler* handler, const char* /*args*/) + static bool HandleWpUnLoadCommand(ChatHandler* handler, char const* /*args*/) { Creature* target = handler->getSelectedCreature(); - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; if (!target) { @@ -278,20 +284,20 @@ public: return true; } - static bool HandleWpEventCommand(ChatHandler* handler, const char* args) + static bool HandleWpEventCommand(ChatHandler* handler, char const* args) { if (!*args) return false; char* show_str = strtok((char*)args, " "); std::string show = show_str; - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; // Check if ((show != "add") && (show != "mod") && (show != "del") && (show != "listid")) return false; - char* arg_id = strtok(NULL, " "); + char* arg_id = strtok(nullptr, " "); uint32 id = 0; if (show == "add") @@ -420,7 +426,7 @@ public: return true; } - char* arg_2 = strtok(NULL, " "); + char* arg_2 = strtok(nullptr, " "); if (!arg_2) { @@ -440,7 +446,7 @@ public: char* arg_3; std::string arg_str_2 = arg_2; - arg_3 = strtok(NULL, " "); + arg_3 = strtok(nullptr, " "); if (!arg_3) { @@ -535,7 +541,7 @@ public: return true; } - static bool HandleWpModifyCommand(ChatHandler* handler, const char* args) + static bool HandleWpModifyCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -558,7 +564,7 @@ public: } // Next arg is: - char* arg_str = NULL; + char* arg_str = nullptr; // Did user provide a GUID // or did the user select a creature? @@ -566,7 +572,7 @@ public: uint32 pathid = 0; uint32 point = 0; Creature* target = handler->getSelectedCreature(); - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; // User did select a visual waypoint? if (!target || target->GetEntry() != VISUAL_WAYPOINT) @@ -617,10 +623,10 @@ public: // We have the waypoint number and the GUID of the "master npc" // Text is enclosed in "<>", all other arguments not - arg_str = strtok((char*)NULL, " "); + arg_str = strtok((char*)nullptr, " "); // Check for argument - if (show != "del" && show != "move" && arg_str == NULL) + if (show != "del" && show != "move" && arg_str == nullptr) { handler->PSendSysMessage(LANG_WAYPOINT_ARGUMENTREQ, show_str); return false; @@ -697,7 +703,7 @@ public: if (text == 0) { // show_str check for present in list of correct values, no sql injection possible - WorldDatabase.PExecute("UPDATE waypoint_data SET %s=NULL WHERE id='%u' AND point='%u'", show_str, pathid, point); // Query can't be a prepared statement + WorldDatabase.PExecute("UPDATE waypoint_data SET %s=nullptr WHERE id='%u' AND point='%u'", show_str, pathid, point); // Query can't be a prepared statement } else { @@ -711,7 +717,7 @@ public: return true; } - static bool HandleWpShowCommand(ChatHandler* handler, const char* args) + static bool HandleWpShowCommand(ChatHandler* handler, char const* args) { if (!*args) return false; @@ -722,11 +728,11 @@ public: return false; // second arg: GUID (optional, if a creature is selected) - char* guid_str = strtok((char*)NULL, " "); + char* guid_str = strtok((char*)nullptr, " "); uint32 pathid = 0; Creature* target = handler->getSelectedCreature(); - PreparedStatement* stmt = NULL; + PreparedStatement* stmt = nullptr; // Did player provide a PathID? diff --git a/src/server/scripts/EasternKingdoms/AlteracValley/boss_balinda.cpp b/src/server/scripts/EasternKingdoms/AlteracValley/boss_balinda.cpp index 5c1718c1211..577c156fd83 100644 --- a/src/server/scripts/EasternKingdoms/AlteracValley/boss_balinda.cpp +++ b/src/server/scripts/EasternKingdoms/AlteracValley/boss_balinda.cpp @@ -16,6 +16,7 @@ */ #include "ScriptMgr.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" enum Spells diff --git a/src/server/scripts/EasternKingdoms/BaradinHold/baradin_hold.h b/src/server/scripts/EasternKingdoms/BaradinHold/baradin_hold.h index 99a54e39684..52d6b59b6f2 100644 --- a/src/server/scripts/EasternKingdoms/BaradinHold/baradin_hold.h +++ b/src/server/scripts/EasternKingdoms/BaradinHold/baradin_hold.h @@ -18,9 +18,7 @@ #ifndef DEF_BARADIN_HOLD_H_ #define DEF_BARADIN_HOLD_H_ -#include "Map.h" -#include "Creature.h" -#include "ObjectMgr.h" +#include "CreatureAIImpl.h" #define DataHeader "BH" #define BHScriptName "instance_baradin_hold" @@ -52,14 +50,10 @@ enum BHGameObjectIds GO_ALIZABAL_DOOR = 209849 }; -template -CreatureAI* GetBaradinHoldAI(Creature* creature) +template +inline AI* GetBaradinHoldAI(T* obj) { - if (InstanceMap* instance = creature->GetMap()->ToInstanceMap()) - if (instance->GetInstanceScript()) - if (instance->GetScriptId() == sObjectMgr->GetScriptId(BHScriptName)) - return new AI(creature); - return NULL; + return GetInstanceAI(obj, BHScriptName); } #endif diff --git a/src/server/scripts/EasternKingdoms/BaradinHold/boss_alizabal.cpp b/src/server/scripts/EasternKingdoms/BaradinHold/boss_alizabal.cpp index d9376959e9f..2f8d4aa7f1f 100644 --- a/src/server/scripts/EasternKingdoms/BaradinHold/boss_alizabal.cpp +++ b/src/server/scripts/EasternKingdoms/BaradinHold/boss_alizabal.cpp @@ -16,10 +16,12 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "Player.h" -#include "ObjectAccessor.h" #include "baradin_hold.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" enum Texts { diff --git a/src/server/scripts/EasternKingdoms/BaradinHold/boss_occuthar.cpp b/src/server/scripts/EasternKingdoms/BaradinHold/boss_occuthar.cpp index c8e800b3da2..78cb4e952d8 100644 --- a/src/server/scripts/EasternKingdoms/BaradinHold/boss_occuthar.cpp +++ b/src/server/scripts/EasternKingdoms/BaradinHold/boss_occuthar.cpp @@ -16,11 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "Vehicle.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" #include "baradin_hold.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "Vehicle.h" enum Spells { @@ -202,7 +205,7 @@ class npc_eyestalk : public CreatureScript } }; -class FocusedFireTargetSelector : public std::unary_function +class FocusedFireTargetSelector { public: FocusedFireTargetSelector(Creature* me, const Unit* victim) : _me(me), _victim(victim) { } @@ -267,9 +270,7 @@ class spell_occuthar_eyes_of_occuthar : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].CalcValue())) - return false; - return true; + return ValidateSpellInfo({ uint32(spellInfo->Effects[EFFECT_0].CalcValue()) }); } bool Load() override @@ -317,7 +318,7 @@ class spell_occuthar_eyes_of_occuthar_vehicle : public SpellScriptLoader bool Load() override { - return GetCaster()->GetInstanceScript() != NULL; + return GetCaster()->GetInstanceScript() != nullptr; } void HandleScript() @@ -363,7 +364,7 @@ class spell_occuthar_occuthars_destruction : public SpellScriptLoader if (Unit* caster = GetCaster()) { if (IsExpired()) - caster->CastSpell((Unit*)NULL, SPELL_OCCUTHARS_DESTUCTION, true, NULL, aurEff); + caster->CastSpell((Unit*)nullptr, SPELL_OCCUTHARS_DESTUCTION, true, nullptr, aurEff); caster->ToCreature()->DespawnOrUnsummon(500); } diff --git a/src/server/scripts/EasternKingdoms/BaradinHold/boss_pit_lord_argaloth.cpp b/src/server/scripts/EasternKingdoms/BaradinHold/boss_pit_lord_argaloth.cpp index 0ee1f21fc97..f1b4bd029a4 100644 --- a/src/server/scripts/EasternKingdoms/BaradinHold/boss_pit_lord_argaloth.cpp +++ b/src/server/scripts/EasternKingdoms/BaradinHold/boss_pit_lord_argaloth.cpp @@ -16,9 +16,12 @@ */ #include "ScriptMgr.h" +#include "baradin_hold.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "baradin_hold.h" /* TODO: - Fel Firestorm need completion diff --git a/src/server/scripts/EasternKingdoms/BaradinHold/instance_baradin_hold.cpp b/src/server/scripts/EasternKingdoms/BaradinHold/instance_baradin_hold.cpp index 95b09b1246f..b82515fae3a 100644 --- a/src/server/scripts/EasternKingdoms/BaradinHold/instance_baradin_hold.cpp +++ b/src/server/scripts/EasternKingdoms/BaradinHold/instance_baradin_hold.cpp @@ -16,8 +16,11 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" #include "baradin_hold.h" +#include "Creature.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" DoorData const doorData[] = { @@ -43,7 +46,7 @@ class instance_baradin_hold: public InstanceMapScript void OnCreatureCreate(Creature* creature) override { - switch(creature->GetEntry()) + switch (creature->GetEntry()) { case BOSS_ARGALOTH: ArgalothGUID = creature->GetGUID(); diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/blackrock_caverns.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/blackrock_caverns.cpp index 2088ece999f..235c976c1fb 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/blackrock_caverns.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/blackrock_caverns.cpp @@ -16,12 +16,13 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "TemporarySummon.h" #include "blackrock_caverns.h" -#include "SpellScript.h" -#include "SpellAuras.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "Spell.h" +#include "SpellAuras.h" +#include "SpellScript.h" +#include "TemporarySummon.h" /*##### # npc_fire_cyclone @@ -722,9 +723,7 @@ class spell_chains_of_woe_1 : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CHAINS_OF_WOE_1)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CHAINS_OF_WOE_1 }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -759,9 +758,7 @@ class spell_chains_of_woe_4 : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CHAINS_OF_WOE_4)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CHAINS_OF_WOE_4 }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -804,11 +801,12 @@ class spell_nether_dragon_essence_1 : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_NETHER_DRAGON_ESSENCE_2) - || !sSpellMgr->GetSpellInfo(SPELL_NETHER_DRAGON_ESSENCE_3) - || !sSpellMgr->GetSpellInfo(SPELL_NETHER_DRAGON_ESSENCE_4)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_NETHER_DRAGON_ESSENCE_2, + SPELL_NETHER_DRAGON_ESSENCE_3, + SPELL_NETHER_DRAGON_ESSENCE_4 + }); } void HandleTriggerSpell(AuraEffect const* /*aurEff*/) diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/blackrock_caverns.h b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/blackrock_caverns.h index bacce4b721a..52dea569c92 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/blackrock_caverns.h +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/blackrock_caverns.h @@ -18,6 +18,8 @@ #ifndef BLACKROCKCAVERNS_H_ #define BLACKROCKCAVERNS_H_ +#include "CreatureAIImpl.h" + #define BCScriptName "instance_blackrock_caverns" #define DataHeader "BRC" @@ -43,10 +45,10 @@ enum BRCCreatureIds NPC_ROMOGG_BONECRUSHER = 39665 }; -template -inline AI* GetBlackrockCavernsAI(Creature* creature) +template +inline AI* GetBlackrockCavernsAI(T* obj) { - return GetInstanceAI(creature, BCScriptName); + return GetInstanceAI(obj, BCScriptName); } #endif // BLACKROCKCAVERNS_H_ diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/boss_ascendant_lord_obsidius.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/boss_ascendant_lord_obsidius.cpp index 4e441b9900d..f69f7abeabf 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/boss_ascendant_lord_obsidius.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/boss_ascendant_lord_obsidius.cpp @@ -16,8 +16,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_caverns.h" +#include "ScriptedCreature.h" enum Text { diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/boss_corla.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/boss_corla.cpp index 1d8189dd0e4..937cae76650 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/boss_corla.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/boss_corla.cpp @@ -16,8 +16,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_caverns.h" +#include "ScriptedCreature.h" enum Text { diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/boss_karsh_steelbender.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/boss_karsh_steelbender.cpp index c48f699c75c..bfa639e88b4 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/boss_karsh_steelbender.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/boss_karsh_steelbender.cpp @@ -16,8 +16,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_caverns.h" +#include "ScriptedCreature.h" enum Text { diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/boss_romogg_bonecrusher.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/boss_romogg_bonecrusher.cpp index 9f39937ee49..bb827156d62 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/boss_romogg_bonecrusher.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/boss_romogg_bonecrusher.cpp @@ -16,8 +16,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_caverns.h" +#include "InstanceScript.h" +#include "ScriptedCreature.h" enum Romogg { diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/instance_blackrock_caverns.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/instance_blackrock_caverns.cpp index 7f3d28823f0..daabf15b4e0 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/instance_blackrock_caverns.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockCaverns/instance_blackrock_caverns.cpp @@ -16,8 +16,9 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" #include "blackrock_caverns.h" +#include "InstanceScript.h" +#include "Map.h" ObjectData const creatureData[] = { diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.cpp index fbf46c7d331..5f691341f35 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.cpp @@ -16,13 +16,17 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "blackrock_depths.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "InstanceScript.h" +#include "Log.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedEscortAI.h" #include "ScriptedGossip.h" -#include "blackrock_depths.h" -#include "Player.h" +#include "TemporarySummon.h" #include "WorldSession.h" -#include "GameObjectAI.h" //go_shadowforge_brazier class go_shadowforge_brazier : public GameObjectScript @@ -32,29 +36,28 @@ public: struct go_shadowforge_brazierAI : public GameObjectAI { - go_shadowforge_brazierAI(GameObject* go) : GameObjectAI(go) { } + go_shadowforge_brazierAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* /*player*/) override { - if (InstanceScript* instance = me->GetInstanceScript()) - { - if (instance->GetData(TYPE_LYCEUM) == IN_PROGRESS) - instance->SetData(TYPE_LYCEUM, DONE); - else - instance->SetData(TYPE_LYCEUM, IN_PROGRESS); - // If used brazier open linked doors (North or South) - if (me->GetGUID() == instance->GetGuidData(DATA_SF_BRAZIER_N)) - instance->HandleGameObject(instance->GetGuidData(DATA_GOLEM_DOOR_N), true); - else if (me->GetGUID() == instance->GetGuidData(DATA_SF_BRAZIER_S)) - instance->HandleGameObject(instance->GetGuidData(DATA_GOLEM_DOOR_S), true); - } + if (instance->GetData(TYPE_LYCEUM) == IN_PROGRESS) + instance->SetData(TYPE_LYCEUM, DONE); + else + instance->SetData(TYPE_LYCEUM, IN_PROGRESS); + // If used brazier open linked doors (North or South) + if (me->GetGUID() == instance->GetGuidData(DATA_SF_BRAZIER_N)) + instance->HandleGameObject(instance->GetGuidData(DATA_GOLEM_DOOR_N), true); + else if (me->GetGUID() == instance->GetGuidData(DATA_SF_BRAZIER_S)) + instance->HandleGameObject(instance->GetGuidData(DATA_GOLEM_DOOR_S), true); return false; } }; GameObjectAI* GetAI(GameObject* go) const override { - return new go_shadowforge_brazierAI(go); + return GetBlackrockDepthsAI(go); } }; @@ -93,7 +96,7 @@ class at_ring_of_law : public AreaTriggerScript public: at_ring_of_law() : AreaTriggerScript("at_ring_of_law") { } - bool OnTrigger(Player* player, const AreaTriggerEntry* /*at*/) override + bool OnTrigger(Player* player, AreaTriggerEntry const* /*at*/) override { if (InstanceScript* instance = player->GetInstanceScript()) { @@ -126,11 +129,6 @@ class npc_grimstone : public CreatureScript public: npc_grimstone() : CreatureScript("npc_grimstone") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_grimstoneAI : public npc_escortAI { npc_grimstoneAI(Creature* creature) : npc_escortAI(creature) @@ -224,7 +222,7 @@ public: Event_Timer = 5000; break; case 5: - instance->UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, NPC_GRIMSTONE, me); + instance->UpdateEncounterStateForKilledCreature(NPC_GRIMSTONE, me); instance->SetData(TYPE_RING_OF_LAW, DONE); TC_LOG_DEBUG("scripts", "npc_grimstone: event reached end and set complete."); break; @@ -348,6 +346,11 @@ public: npc_escortAI::UpdateAI(diff); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetBlackrockDepthsAI(creature); + } }; // npc_phalanx @@ -363,11 +366,6 @@ class npc_phalanx : public CreatureScript public: npc_phalanx() : CreatureScript("npc_phalanx") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_phalanxAI(creature); - } - struct npc_phalanxAI : public ScriptedAI { npc_phalanxAI(Creature* creature) : ScriptedAI(creature) @@ -424,6 +422,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetBlackrockDepthsAI(creature); + } }; // npc_lokhtos_darkbargainer @@ -489,7 +492,7 @@ class npc_lokhtos_darkbargainer : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_lokhtos_darkbargainerAI(creature); + return GetBlackrockDepthsAI(creature); } }; @@ -535,7 +538,7 @@ class npc_rocknot : public CreatureScript void DoGo(uint32 id, uint32 state) { - if (GameObject* go = instance->instance->GetGameObject(instance->GetGuidData(id))) + if (GameObject* go = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(id))) go->SetGoState((GOState)state); } @@ -629,7 +632,7 @@ class npc_rocknot : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_rocknotAI(creature); + return GetBlackrockDepthsAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.h b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.h index 02fe43a9a4a..6c81fe0c86a 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.h +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/blackrock_depths.h @@ -19,6 +19,9 @@ #ifndef DEF_BRD_H #define DEF_BRD_H +#include "CreatureAIImpl.h" + +#define BRDScriptName "instance_blackrock_depths" #define DataHeader "BRD" enum BRDFactionIds @@ -64,4 +67,10 @@ enum BRDDataTypes DATA_COREN = 28 }; +template +inline AI* GetBlackrockDepthsAI(T* obj) +{ + return GetInstanceAI(obj, BRDScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_coren_direbrew.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_coren_direbrew.cpp index d08404f2fac..7451eceed1a 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_coren_direbrew.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_coren_direbrew.cpp @@ -16,16 +16,20 @@ */ #include "ScriptMgr.h" +#include "blackrock_depths.h" +#include "GameObjectAI.h" +#include "GridNotifiers.h" +#include "Group.h" +#include "InstanceScript.h" +#include "LFGMgr.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "blackrock_depths.h" -#include "Player.h" -#include "SpellScript.h" #include "SpellAuras.h" -#include "LFGMgr.h" -#include "Group.h" -#include "GridNotifiers.h" -#include "GameObjectAI.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum DirebrewSays { @@ -274,7 +278,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockDepthsAI(creature); } }; @@ -338,7 +342,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockDepthsAI(creature); } }; @@ -370,7 +374,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockDepthsAI(creature); } }; @@ -412,7 +416,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockDepthsAI(creature); } }; @@ -455,7 +459,7 @@ public: GameObjectAI* GetAI(GameObject* go) const override { - return GetInstanceAI(go); + return GetBlackrockDepthsAI(go); } }; @@ -471,10 +475,7 @@ class spell_direbrew_disarm : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DIREBREW_DISARM) - || !sSpellMgr->GetSpellInfo(SPELL_DIREBREW_DISARM_GROW)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DIREBREW_DISARM, SPELL_DIREBREW_DISARM_GROW }); } void PeriodicTick(AuraEffect const* /*aurEff*/) @@ -517,9 +518,7 @@ class spell_direbrew_summon_mole_machine_target_picker : public SpellScriptLoade bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MOLE_MACHINE_MINION_SUMMONER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MOLE_MACHINE_MINION_SUMMONER }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -603,9 +602,7 @@ class spell_request_second_mug : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SEND_SECOND_MUG)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SEND_SECOND_MUG }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -637,9 +634,7 @@ class spell_send_mug_control_aura : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SEND_MUG_TARGET_PICKER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SEND_MUG_TARGET_PICKER }); } void PeriodicTick(AuraEffect const* /*aurEff*/) diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_emperor_dagran_thaurissan.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_emperor_dagran_thaurissan.cpp index d144eaaedc0..c28404e34fa 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_emperor_dagran_thaurissan.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_emperor_dagran_thaurissan.cpp @@ -16,8 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_depths.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Yells { @@ -112,7 +114,7 @@ class boss_emperor_dagran_thaurissan : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockDepthsAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_magmus.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_magmus.cpp index af8e1fe96c3..5ecff6cb0d1 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_magmus.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_magmus.cpp @@ -16,8 +16,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_depths.h" +#include "InstanceScript.h" +#include "ScriptedCreature.h" enum Spells { @@ -105,7 +106,7 @@ class boss_magmus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_magmusAI(creature); + return GetBlackrockDepthsAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_tomb_of_seven.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_tomb_of_seven.cpp index dc3f59e89b8..020057c918f 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_tomb_of_seven.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/boss_tomb_of_seven.cpp @@ -17,10 +17,11 @@ */ #include "ScriptMgr.h" +#include "blackrock_depths.h" +#include "InstanceScript.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "blackrock_depths.h" -#include "Player.h" enum Spells { @@ -267,7 +268,7 @@ class boss_doomrel : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockDepthsAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/instance_blackrock_depths.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/instance_blackrock_depths.cpp index 04ae339e36e..6ad7a86fe78 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/instance_blackrock_depths.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockDepths/instance_blackrock_depths.cpp @@ -17,9 +17,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "InstanceScript.h" #include "blackrock_depths.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" #define TIMER_TOMBOFTHESEVEN 15000 #define MAX_ENCOUNTER 6 @@ -68,7 +73,7 @@ enum GameObjects class instance_blackrock_depths : public InstanceMapScript { public: - instance_blackrock_depths() : InstanceMapScript("instance_blackrock_depths", 230) { } + instance_blackrock_depths() : InstanceMapScript(BRDScriptName, 230) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { @@ -130,22 +135,22 @@ public: { switch (creature->GetEntry()) { - case NPC_EMPEROR: EmperorGUID = creature->GetGUID(); break; - case NPC_PHALANX: PhalanxGUID = creature->GetGUID(); break; - case NPC_MOIRA: MoiraGUID = creature->GetGUID(); break; - case NPC_COREN: CorenGUID = creature->GetGUID(); break; - case NPC_DOOMREL: TombBossGUIDs[0] = creature->GetGUID(); break; - case NPC_DOPEREL: TombBossGUIDs[1] = creature->GetGUID(); break; - case NPC_HATEREL: TombBossGUIDs[2] = creature->GetGUID(); break; - case NPC_VILEREL: TombBossGUIDs[3] = creature->GetGUID(); break; - case NPC_SEETHREL: TombBossGUIDs[4] = creature->GetGUID(); break; - case NPC_GLOOMREL: TombBossGUIDs[5] = creature->GetGUID(); break; - case NPC_ANGERREL: TombBossGUIDs[6] = creature->GetGUID(); break; - case NPC_MAGMUS: - MagmusGUID = creature->GetGUID(); - if (!creature->IsAlive()) - HandleGameObject(GetGuidData(DATA_THRONE_DOOR), true); // if Magmus is dead open door to last boss - break; + case NPC_EMPEROR: EmperorGUID = creature->GetGUID(); break; + case NPC_PHALANX: PhalanxGUID = creature->GetGUID(); break; + case NPC_MOIRA: MoiraGUID = creature->GetGUID(); break; + case NPC_COREN: CorenGUID = creature->GetGUID(); break; + case NPC_DOOMREL: TombBossGUIDs[0] = creature->GetGUID(); break; + case NPC_DOPEREL: TombBossGUIDs[1] = creature->GetGUID(); break; + case NPC_HATEREL: TombBossGUIDs[2] = creature->GetGUID(); break; + case NPC_VILEREL: TombBossGUIDs[3] = creature->GetGUID(); break; + case NPC_SEETHREL: TombBossGUIDs[4] = creature->GetGUID(); break; + case NPC_GLOOMREL: TombBossGUIDs[5] = creature->GetGUID(); break; + case NPC_ANGERREL: TombBossGUIDs[6] = creature->GetGUID(); break; + case NPC_MAGMUS: + MagmusGUID = creature->GetGUID(); + if (!creature->IsAlive()) + HandleGameObject(GetGuidData(DATA_THRONE_DOOR), true); // if Magmus is dead open door to last boss + break; } } @@ -153,33 +158,33 @@ public: { switch (go->GetEntry()) { - case GO_ARENA1: GoArena1GUID = go->GetGUID(); break; - case GO_ARENA2: GoArena2GUID = go->GetGUID(); break; - case GO_ARENA3: GoArena3GUID = go->GetGUID(); break; - case GO_ARENA4: GoArena4GUID = go->GetGUID(); break; - case GO_SHADOW_LOCK: GoShadowLockGUID = go->GetGUID(); break; - case GO_SHADOW_MECHANISM: GoShadowMechGUID = go->GetGUID(); break; - case GO_SHADOW_GIANT_DOOR: GoShadowGiantGUID = go->GetGUID(); break; - case GO_SHADOW_DUMMY: GoShadowDummyGUID = go->GetGUID(); break; - case GO_BAR_KEG_SHOT: GoBarKegGUID = go->GetGUID(); break; - case GO_BAR_KEG_TRAP: GoBarKegTrapGUID = go->GetGUID(); break; - case GO_BAR_DOOR: GoBarDoorGUID = go->GetGUID(); break; - case GO_TOMB_ENTER: GoTombEnterGUID = go->GetGUID(); break; - case GO_TOMB_EXIT: - GoTombExitGUID = go->GetGUID(); - if (GhostKillCount >= 7) - HandleGameObject(ObjectGuid::Empty, true, go); - else - HandleGameObject(ObjectGuid::Empty, false, go); - break; - case GO_LYCEUM: GoLyceumGUID = go->GetGUID(); break; - case GO_SF_S: GoSFSGUID = go->GetGUID(); break; - case GO_SF_N: GoSFNGUID = go->GetGUID(); break; - case GO_GOLEM_ROOM_N: GoGolemNGUID = go->GetGUID(); break; - case GO_GOLEM_ROOM_S: GoGolemSGUID = go->GetGUID(); break; - case GO_THRONE_ROOM: GoThroneGUID = go->GetGUID(); break; - case GO_CHEST_SEVEN: GoChestGUID = go->GetGUID(); break; - case GO_SPECTRAL_CHALICE: GoSpectralChaliceGUID = go->GetGUID(); break; + case GO_ARENA1: GoArena1GUID = go->GetGUID(); break; + case GO_ARENA2: GoArena2GUID = go->GetGUID(); break; + case GO_ARENA3: GoArena3GUID = go->GetGUID(); break; + case GO_ARENA4: GoArena4GUID = go->GetGUID(); break; + case GO_SHADOW_LOCK: GoShadowLockGUID = go->GetGUID(); break; + case GO_SHADOW_MECHANISM: GoShadowMechGUID = go->GetGUID(); break; + case GO_SHADOW_GIANT_DOOR: GoShadowGiantGUID = go->GetGUID(); break; + case GO_SHADOW_DUMMY: GoShadowDummyGUID = go->GetGUID(); break; + case GO_BAR_KEG_SHOT: GoBarKegGUID = go->GetGUID(); break; + case GO_BAR_KEG_TRAP: GoBarKegTrapGUID = go->GetGUID(); break; + case GO_BAR_DOOR: GoBarDoorGUID = go->GetGUID(); break; + case GO_TOMB_ENTER: GoTombEnterGUID = go->GetGUID(); break; + case GO_TOMB_EXIT: + GoTombExitGUID = go->GetGUID(); + if (GhostKillCount >= 7) + HandleGameObject(ObjectGuid::Empty, true, go); + else + HandleGameObject(ObjectGuid::Empty, false, go); + break; + case GO_LYCEUM: GoLyceumGUID = go->GetGUID(); break; + case GO_SF_S: GoSFSGUID = go->GetGUID(); break; + case GO_SF_N: GoSFNGUID = go->GetGUID(); break; + case GO_GOLEM_ROOM_N: GoGolemNGUID = go->GetGUID(); break; + case GO_GOLEM_ROOM_S: GoGolemSGUID = go->GetGUID(); break; + case GO_THRONE_ROOM: GoThroneGUID = go->GetGUID(); break; + case GO_CHEST_SEVEN: GoChestGUID = go->GetGUID(); break; + case GO_SPECTRAL_CHALICE: GoSpectralChaliceGUID = go->GetGUID(); break; } } @@ -205,30 +210,30 @@ public: switch (type) { - case TYPE_RING_OF_LAW: - encounter[0] = data; - break; - case TYPE_VAULT: - encounter[1] = data; - break; - case TYPE_BAR: - if (data == SPECIAL) - ++BarAleCount; - else - encounter[2] = data; - break; - case TYPE_TOMB_OF_SEVEN: - encounter[3] = data; - break; - case TYPE_LYCEUM: - encounter[4] = data; - break; - case TYPE_IRON_HALL: - encounter[5] = data; - break; - case DATA_GHOSTKILL: - GhostKillCount += data; - break; + case TYPE_RING_OF_LAW: + encounter[0] = data; + break; + case TYPE_VAULT: + encounter[1] = data; + break; + case TYPE_BAR: + if (data == SPECIAL) + ++BarAleCount; + else + encounter[2] = data; + break; + case TYPE_TOMB_OF_SEVEN: + encounter[3] = data; + break; + case TYPE_LYCEUM: + encounter[4] = data; + break; + case TYPE_IRON_HALL: + encounter[5] = data; + break; + case DATA_GHOSTKILL: + GhostKillCount += data; + break; } if (data == DONE || GhostKillCount >= 7) @@ -250,23 +255,23 @@ public: { switch (type) { - case TYPE_RING_OF_LAW: - return encounter[0]; - case TYPE_VAULT: - return encounter[1]; - case TYPE_BAR: - if (encounter[2] == IN_PROGRESS && BarAleCount == 3) - return SPECIAL; - else - return encounter[2]; - case TYPE_TOMB_OF_SEVEN: - return encounter[3]; - case TYPE_LYCEUM: - return encounter[4]; - case TYPE_IRON_HALL: - return encounter[5]; - case DATA_GHOSTKILL: - return GhostKillCount; + case TYPE_RING_OF_LAW: + return encounter[0]; + case TYPE_VAULT: + return encounter[1]; + case TYPE_BAR: + if (encounter[2] == IN_PROGRESS && BarAleCount == 3) + return SPECIAL; + else + return encounter[2]; + case TYPE_TOMB_OF_SEVEN: + return encounter[3]; + case TYPE_LYCEUM: + return encounter[4]; + case TYPE_IRON_HALL: + return encounter[5]; + case DATA_GHOSTKILL: + return GhostKillCount; } return 0; } @@ -275,42 +280,42 @@ public: { switch (data) { - case DATA_EMPEROR: - return EmperorGUID; - case DATA_PHALANX: - return PhalanxGUID; - case DATA_MOIRA: - return MoiraGUID; - case DATA_COREN: - return CorenGUID; - case DATA_ARENA1: - return GoArena1GUID; - case DATA_ARENA2: - return GoArena2GUID; - case DATA_ARENA3: - return GoArena3GUID; - case DATA_ARENA4: - return GoArena4GUID; - case DATA_GO_BAR_KEG: - return GoBarKegGUID; - case DATA_GO_BAR_KEG_TRAP: - return GoBarKegTrapGUID; - case DATA_GO_BAR_DOOR: - return GoBarDoorGUID; - case DATA_EVENSTARTER: - return TombEventStarterGUID; - case DATA_SF_BRAZIER_N: - return GoSFNGUID; - case DATA_SF_BRAZIER_S: - return GoSFSGUID; - case DATA_THRONE_DOOR: - return GoThroneGUID; - case DATA_GOLEM_DOOR_N: - return GoGolemNGUID; - case DATA_GOLEM_DOOR_S: - return GoGolemSGUID; - case DATA_GO_CHALICE: - return GoSpectralChaliceGUID; + case DATA_EMPEROR: + return EmperorGUID; + case DATA_PHALANX: + return PhalanxGUID; + case DATA_MOIRA: + return MoiraGUID; + case DATA_COREN: + return CorenGUID; + case DATA_ARENA1: + return GoArena1GUID; + case DATA_ARENA2: + return GoArena2GUID; + case DATA_ARENA3: + return GoArena3GUID; + case DATA_ARENA4: + return GoArena4GUID; + case DATA_GO_BAR_KEG: + return GoBarKegGUID; + case DATA_GO_BAR_KEG_TRAP: + return GoBarKegTrapGUID; + case DATA_GO_BAR_DOOR: + return GoBarDoorGUID; + case DATA_EVENSTARTER: + return TombEventStarterGUID; + case DATA_SF_BRAZIER_N: + return GoSFNGUID; + case DATA_SF_BRAZIER_S: + return GoSFSGUID; + case DATA_THRONE_DOOR: + return GoThroneGUID; + case DATA_GOLEM_DOOR_N: + return GoGolemNGUID; + case DATA_GOLEM_DOOR_S: + return GoGolemSGUID; + case DATA_GO_CHALICE: + return GoSpectralChaliceGUID; } return ObjectGuid::Empty; } @@ -320,7 +325,7 @@ public: return str_data; } - void Load(const char* in) override + void Load(char const* in) override { if (!in) { @@ -375,7 +380,7 @@ public: boss->CombatStop(true); boss->LoadCreaturesAddon(); boss->GetMotionMaster()->MoveTargetedHome(); - boss->SetLootRecipient(NULL); + boss->SetLootRecipient(nullptr); } boss->SetFaction(FACTION_FRIENDLY); } diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/blackrock_spire.h b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/blackrock_spire.h index b78b6f2cbb8..2157c98e042 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/blackrock_spire.h +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/blackrock_spire.h @@ -18,6 +18,8 @@ #ifndef DEF_BLACKROCK_SPIRE_H #define DEF_BLACKROCK_SPIRE_H +#include "CreatureAIImpl.h" + uint32 const EncounterCount = 23; #define BRSScriptName "instance_blackrock_spire" @@ -120,4 +122,10 @@ enum BRSGameObjectsIds GO_PORTCULLIS_TOBOSSROOMS = 175186 }; +template +inline AI* GetBlackrockSpireAI(T* obj) +{ + return GetInstanceAI(obj, BRSScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_gizrul_the_slavener.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_gizrul_the_slavener.cpp index 5c54180d569..d4be9a658a5 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_gizrul_the_slavener.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_gizrul_the_slavener.cpp @@ -16,8 +16,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_spire.h" +#include "MotionMaster.h" +#include "ScriptedCreature.h" #include "TemporarySummon.h" enum Spells @@ -105,7 +106,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_gizrul_the_slavenerAI(creature); + return GetBlackrockSpireAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_gyth.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_gyth.cpp index e81b17ea291..5364891bb13 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_gyth.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_gyth.cpp @@ -16,8 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_spire.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ScriptedCreature.h" enum Spells { @@ -176,7 +179,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockSpireAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_lord_valthalak.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_lord_valthalak.cpp index 1764b6f9dca..cf63ed6ef69 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_lord_valthalak.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_lord_valthalak.cpp @@ -16,8 +16,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_spire.h" +#include "InstanceScript.h" +#include "ScriptedCreature.h" enum Spells { @@ -138,7 +139,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockSpireAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_overlord_wyrmthalak.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_overlord_wyrmthalak.cpp index fdcd20cb8fb..7ff7e249f43 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_overlord_wyrmthalak.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_overlord_wyrmthalak.cpp @@ -17,8 +17,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackrock_spire.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Spells { @@ -50,11 +51,6 @@ class boss_overlord_wyrmthalak : public CreatureScript public: boss_overlord_wyrmthalak() : CreatureScript("boss_overlord_wyrmthalak") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new boss_overlordwyrmthalakAI(creature); - } - struct boss_overlordwyrmthalakAI : public BossAI { boss_overlordwyrmthalakAI(Creature* creature) : BossAI(creature, DATA_OVERLORD_WYRMTHALAK) @@ -139,6 +135,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetBlackrockSpireAI(creature); + } }; void AddSC_boss_overlordwyrmthalak() diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_pyroguard_emberseer.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_pyroguard_emberseer.cpp index 537d77673ca..4bab8e6b7c1 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_pyroguard_emberseer.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_pyroguard_emberseer.cpp @@ -15,12 +15,17 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "Player.h" -#include "Spell.h" #include "blackrock_spire.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "Spell.h" +#include "SpellInfo.h" enum Text { @@ -104,10 +109,10 @@ public: break; case 2: // Close these two doors on Blackhand Incarcerators aggro - if (GameObject* door1 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_EMBERSEER_IN))) + if (GameObject* door1 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_EMBERSEER_IN))) if (door1->GetGoState() == GO_STATE_ACTIVE) door1->SetGoState(GO_STATE_READY); - if (GameObject* door2 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_DOORS))) + if (GameObject* door2 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_DOORS))) if (door2->GetGoState() == GO_STATE_ACTIVE) door2->SetGoState(GO_STATE_READY); break; @@ -166,33 +171,33 @@ public: void OpenDoors(bool Boss_Killed) { // These two doors reopen on reset or boss kill - if (GameObject* door1 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_EMBERSEER_IN))) + if (GameObject* door1 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_EMBERSEER_IN))) door1->SetGoState(GO_STATE_ACTIVE); - if (GameObject* door2 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_DOORS))) + if (GameObject* door2 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_DOORS))) door2->SetGoState(GO_STATE_ACTIVE); // This door opens on boss kill if (Boss_Killed) - if (GameObject* door3 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_EMBERSEER_OUT))) + if (GameObject* door3 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_EMBERSEER_OUT))) door3->SetGoState(GO_STATE_ACTIVE); } void UpdateRunes(GOState state) { // update all runes - if (GameObject* rune1 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_EMBERSEER_RUNE_1))) + if (GameObject* rune1 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_EMBERSEER_RUNE_1))) rune1->SetGoState(state); - if (GameObject* rune2 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_EMBERSEER_RUNE_2))) + if (GameObject* rune2 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_EMBERSEER_RUNE_2))) rune2->SetGoState(state); - if (GameObject* rune3 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_EMBERSEER_RUNE_3))) + if (GameObject* rune3 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_EMBERSEER_RUNE_3))) rune3->SetGoState(state); - if (GameObject* rune4 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_EMBERSEER_RUNE_4))) + if (GameObject* rune4 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_EMBERSEER_RUNE_4))) rune4->SetGoState(state); - if (GameObject* rune5 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_EMBERSEER_RUNE_5))) + if (GameObject* rune5 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_EMBERSEER_RUNE_5))) rune5->SetGoState(state); - if (GameObject* rune6 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_EMBERSEER_RUNE_6))) + if (GameObject* rune6 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_EMBERSEER_RUNE_6))) rune6->SetGoState(state); - if (GameObject* rune7 = me->GetMap()->GetGameObject(instance->GetGuidData(GO_EMBERSEER_RUNE_7))) + if (GameObject* rune7 = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_EMBERSEER_RUNE_7))) rune7->SetGoState(state); } @@ -250,7 +255,7 @@ public: { // Check to see if all players in instance have aura SPELL_EMBERSEER_START before starting event bool _hasAura = true; - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + Map::PlayerList const& players = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) if (Player* player = itr->GetSource()->ToPlayer()) if (!player->HasAura(SPELL_EMBERSEER_OBJECT_VISUAL)) @@ -312,7 +317,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockSpireAI(creature); } }; @@ -384,8 +389,6 @@ public: void UpdateAI(uint32 diff) override { - - if (!UpdateVictim()) { _events.Update(diff); @@ -436,7 +439,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_blackhand_incarceratorAI(creature); + return GetBlackrockSpireAI(creature); } }; 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 ca4262b3b52..7f12cff6d62 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_rend_blackhand.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/boss_rend_blackhand.cpp @@ -17,9 +17,12 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "Player.h" #include "blackrock_spire.h" +#include "GameObject.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" enum Spells { @@ -372,37 +375,37 @@ public: me->SummonCreature(NPC_GYTH, 211.762f, -397.5885f, 111.1817f, 4.747295f); break; case EVENT_WAVE_1: - if (GameObject* portcullis = me->GetMap()->GetGameObject(portcullisGUID)) + if (GameObject* portcullis = ObjectAccessor::GetGameObject(*me, portcullisGUID)) portcullis->UseDoorOrButton(); // move wave break; case EVENT_WAVE_2: // spawn wave - if (GameObject* portcullis = me->GetMap()->GetGameObject(portcullisGUID)) + if (GameObject* portcullis = ObjectAccessor::GetGameObject(*me, portcullisGUID)) portcullis->UseDoorOrButton(); // move wave break; case EVENT_WAVE_3: // spawn wave - if (GameObject* portcullis = me->GetMap()->GetGameObject(portcullisGUID)) + if (GameObject* portcullis = ObjectAccessor::GetGameObject(*me, portcullisGUID)) portcullis->UseDoorOrButton(); // move wave break; case EVENT_WAVE_4: // spawn wave - if (GameObject* portcullis = me->GetMap()->GetGameObject(portcullisGUID)) + if (GameObject* portcullis = ObjectAccessor::GetGameObject(*me, portcullisGUID)) portcullis->UseDoorOrButton(); // move wave break; case EVENT_WAVE_5: // spawn wave - if (GameObject* portcullis = me->GetMap()->GetGameObject(portcullisGUID)) + if (GameObject* portcullis = ObjectAccessor::GetGameObject(*me, portcullisGUID)) portcullis->UseDoorOrButton(); // move wave break; case EVENT_WAVE_6: // spawn wave - if (GameObject* portcullis = me->GetMap()->GetGameObject(portcullisGUID)) + if (GameObject* portcullis = ObjectAccessor::GetGameObject(*me, portcullisGUID)) portcullis->UseDoorOrButton(); // move wave break; @@ -452,7 +455,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackrockSpireAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/instance_blackrock_spire.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/instance_blackrock_spire.cpp index 3e0c246a236..7fdeaa13d69 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/instance_blackrock_spire.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackrockSpire/instance_blackrock_spire.cpp @@ -15,15 +15,14 @@ * with this program. If not, see . */ -#include "Cell.h" -#include "CellImpl.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "InstanceScript.h" -#include "Player.h" -#include "ScriptedCreature.h" #include "ScriptMgr.h" #include "blackrock_spire.h" +#include "CellImpl.h" +#include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" //uint32 const DragonspireRunes[7] = { GO_HALL_RUNE_1, GO_HALL_RUNE_2, GO_HALL_RUNE_3, GO_HALL_RUNE_4, GO_HALL_RUNE_5, GO_HALL_RUNE_6, GO_HALL_RUNE_7 }; @@ -120,7 +119,7 @@ public: switch (go->GetEntry()) { case GO_WHELP_SPAWNER: - go->CastSpell(NULL, SPELL_SUMMON_ROOKERY_WHELP); + go->CastSpell(nullptr, SPELL_SUMMON_ROOKERY_WHELP); break; case GO_EMBERSEER_IN: go_emberseerin = go->GetGUID(); @@ -419,8 +418,8 @@ public: void Dragonspireroomcheck() { - Creature* mob = NULL; - GameObject* rune = NULL; + Creature* mob = nullptr; + GameObject* rune = nullptr; for (uint8 i = 0; i < 7; ++i) { diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/blackwing_lair.h b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/blackwing_lair.h index c8deabbf989..d1c55bf1cbf 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/blackwing_lair.h +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/blackwing_lair.h @@ -18,6 +18,8 @@ #ifndef DEF_BLACKWING_LAIR_H #define DEF_BLACKWING_LAIR_H +#include "CreatureAIImpl.h" + uint32 const EncounterCount = 8; #define BRLScriptName "instance_blackwing_lair" @@ -80,4 +82,10 @@ enum BWLMisc DATA_EGG_EVENT }; +template +inline AI* GetBlackwingLairAI(T* obj) +{ + return GetInstanceAI(obj, BRLScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_broodlord_lashlayer.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_broodlord_lashlayer.cpp index e684eab8861..32a6d470bd4 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_broodlord_lashlayer.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_broodlord_lashlayer.cpp @@ -17,8 +17,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackwing_lair.h" +#include "ScriptedCreature.h" enum Say { @@ -110,7 +110,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackwingLairAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_chromaggus.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_chromaggus.cpp index 7670184c5e1..758f90e20ca 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_chromaggus.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_chromaggus.cpp @@ -17,9 +17,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "Player.h" #include "blackwing_lair.h" +#include "Map.h" +#include "Player.h" +#include "ScriptedCreature.h" enum Emotes { @@ -240,7 +241,7 @@ public: break; case EVENT_AFFLICTION: { - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + Map::PlayerList const& players = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) { if (Player* player = itr->GetSource()->ToPlayer()) @@ -290,7 +291,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackwingLairAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_ebonroc.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_ebonroc.cpp index e4db85c21fe..cd1024c3fdf 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_ebonroc.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_ebonroc.cpp @@ -17,8 +17,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackwing_lair.h" +#include "ScriptedCreature.h" enum Spells { @@ -90,7 +90,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackwingLairAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_firemaw.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_firemaw.cpp index 32b829ad8f6..f0dd53a0b0b 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_firemaw.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_firemaw.cpp @@ -17,8 +17,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackwing_lair.h" +#include "ScriptedCreature.h" enum Spells { @@ -92,7 +92,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackwingLairAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_flamegor.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_flamegor.cpp index 87fa92b7c0a..3a912e15490 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_flamegor.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_flamegor.cpp @@ -17,8 +17,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackwing_lair.h" +#include "ScriptedCreature.h" enum Emotes { @@ -98,7 +98,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackwingLairAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_nefarian.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_nefarian.cpp index a622583e548..779442ae848 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_nefarian.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_nefarian.cpp @@ -17,10 +17,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedGossip.h" -#include "ScriptedCreature.h" #include "blackwing_lair.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" +#include "TemporarySummon.h" enum Events { @@ -351,7 +355,7 @@ public: nefarian->SetFarVisible(true); nefarian->SetCanFly(true); nefarian->SetDisableGravity(true); - nefarian->CastSpell((Unit*)NULL, SPELL_SHADOWFLAME_INITIAL); + nefarian->CastSpell((Unit*)nullptr, SPELL_SHADOWFLAME_INITIAL); nefarian->GetMotionMaster()->MovePoint(1, NefarianLoc[1]); } events.CancelEvent(EVENT_MIND_CONTROL); @@ -388,7 +392,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackwingLairAI(creature); } }; @@ -594,7 +598,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackwingLairAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_razorgore.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_razorgore.cpp index 35ae604dbab..fd064b83eef 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_razorgore.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_razorgore.cpp @@ -17,11 +17,13 @@ */ #include "ScriptMgr.h" +#include "blackwing_lair.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "InstanceScript.h" +#include "Player.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "blackwing_lair.h" -#include "Player.h" -#include "GameObjectAI.h" enum Say { @@ -169,7 +171,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackwingLairAI(creature); } }; @@ -180,24 +182,27 @@ class go_orb_of_domination : public GameObjectScript struct go_orb_of_dominationAI : public GameObjectAI { - go_orb_of_dominationAI(GameObject* go) : GameObjectAI(go) { } + go_orb_of_dominationAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* player) override { - if (InstanceScript* instance = me->GetInstanceScript()) - if (instance->GetData(DATA_EGG_EVENT) != DONE) - if (Creature* razorgore = instance->GetCreature(DATA_RAZORGORE_THE_UNTAMED)) - { - razorgore->Attack(player, true); - player->CastSpell(razorgore, SPELL_MINDCONTROL); - } + if (instance->GetData(DATA_EGG_EVENT) != DONE) + { + if (Creature* razorgore = instance->GetCreature(DATA_RAZORGORE_THE_UNTAMED)) + { + razorgore->Attack(player, true); + player->CastSpell(razorgore, SPELL_MINDCONTROL); + } + } return true; } }; GameObjectAI* GetAI(GameObject* go) const override { - return new go_orb_of_dominationAI(go); + return GetBlackwingLairAI(go); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_vaelastrasz.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_vaelastrasz.cpp index 8c2163b61e3..5d87547a523 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_vaelastrasz.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/boss_vaelastrasz.cpp @@ -17,12 +17,13 @@ */ #include "ScriptMgr.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "ScriptedCreature.h" #include "blackwing_lair.h" -#include "ScriptedGossip.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Says { @@ -239,7 +240,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_vaelAI(creature); + return GetBlackwingLairAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/instance_blackwing_lair.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/instance_blackwing_lair.cpp index 0ed7e25f6dc..52d8ff2ec92 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/instance_blackwing_lair.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/BlackwingLair/instance_blackwing_lair.cpp @@ -15,10 +15,15 @@ * with this program. If not, see . */ -#include "Player.h" -#include "ScriptedCreature.h" #include "ScriptMgr.h" #include "blackwing_lair.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" DoorData const doorData[] = { @@ -238,7 +243,7 @@ public: { case EVENT_RAZOR_SPAWN: for (uint8 i = urand(2, 5); i > 0 ; --i) - if (Creature* summon = instance->SummonCreature(Entry[urand(0, 4)], SummonPosition[urand(0, 7)])) + if (Creature* summon = instance->SummonCreature(Entry[urand(0, 4)], SummonPosition[urand(0, 7)])) summon->SetInCombatWithZone(); _events.ScheduleEvent(EVENT_RAZOR_SPAWN, urand(12, 17) * IN_MILLISECONDS); break; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_golemagg.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_golemagg.cpp index 5f1282b1827..f775d831f47 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_golemagg.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_golemagg.cpp @@ -23,10 +23,12 @@ SDComment: Timers need to be confirmed, Golemagg's Trust need to be checked SDCategory: Molten Core EndScriptData */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "molten_core.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "ScriptedCreature.h" enum Texts { @@ -59,9 +61,7 @@ class boss_golemagg : public CreatureScript struct boss_golemaggAI : public BossAI { - boss_golemaggAI(Creature* creature) : BossAI(creature, BOSS_GOLEMAGG_THE_INCINERATOR) - { - } + boss_golemaggAI(Creature* creature) : BossAI(creature, BOSS_GOLEMAGG_THE_INCINERATOR) { } void Reset() override { @@ -121,7 +121,7 @@ class boss_golemagg : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_golemaggAI(creature); + return GetMoltenCoreAI(creature); } }; @@ -188,7 +188,7 @@ class npc_core_rager : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMoltenCoreAI(creature); } }; 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 09a69147019..c2bfcd4f06c 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_majordomo_executus.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_majordomo_executus.cpp @@ -23,12 +23,14 @@ SDComment: Correct spawning and Event NYI SDCategory: Molten Core EndScriptData */ -#include "ObjectMgr.h" #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "molten_core.h" +#include "Map.h" +#include "ObjectMgr.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "molten_core.h" -#include "Player.h" enum Texts { @@ -108,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); + instance->UpdateEncounterStateForKilledCreature(me->GetEntry(), me); me->SetFaction(FACTION_FRIENDLY); EnterEvadeMode(); Talk(SAY_DEFEAT); @@ -209,7 +211,7 @@ class boss_majordomo : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMoltenCoreAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_ragnaros.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_ragnaros.cpp index 4cb0da232d2..baee5fe84dc 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_ragnaros.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_ragnaros.cpp @@ -24,8 +24,11 @@ SDCategory: Molten Core EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "molten_core.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Texts { @@ -309,7 +312,7 @@ class boss_ragnaros : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMoltenCoreAI(creature); } }; @@ -344,7 +347,7 @@ class npc_son_of_flame : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMoltenCoreAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_shazzrah.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_shazzrah.cpp index 1740cf2c546..d666c6355e4 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_shazzrah.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_shazzrah.cpp @@ -16,9 +16,9 @@ */ #include "ScriptMgr.h" +#include "molten_core.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "molten_core.h" enum Spells { @@ -115,7 +115,7 @@ class boss_shazzrah : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_shazzrahAI(creature); + return GetMoltenCoreAI(creature); } }; @@ -131,9 +131,7 @@ class spell_shazzrah_gate_dummy : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAZZRAH_GATE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAZZRAH_GATE }); } void FilterTargets(std::list& targets) diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/instance_molten_core.cpp b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/instance_molten_core.cpp index 93eca4da251..25bd4498864 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/instance_molten_core.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/instance_molten_core.cpp @@ -15,29 +15,36 @@ * with this program. If not, see . */ -#include "InstanceScript.h" -#include "ScriptedCreature.h" #include "ScriptMgr.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" #include "molten_core.h" +#include "TemporarySummon.h" Position const SummonPositions[10] = { - {737.850f, -1145.35f, -120.288f, 4.71368f}, - {744.162f, -1151.63f, -119.726f, 4.58204f}, - {751.247f, -1152.82f, -119.744f, 4.49673f}, - {759.206f, -1155.09f, -120.051f, 4.30104f}, - {755.973f, -1152.33f, -120.029f, 4.25588f}, - {731.712f, -1147.56f, -120.195f, 4.95955f}, - {726.499f, -1149.80f, -120.156f, 5.24055f}, - {722.408f, -1152.41f, -120.029f, 5.33087f}, - {718.994f, -1156.36f, -119.805f, 5.75738f}, - {838.510f, -829.840f, -232.000f, 2.00000f}, + { 737.850f, -1145.35f, -120.288f, 4.71368f }, + { 744.162f, -1151.63f, -119.726f, 4.58204f }, + { 751.247f, -1152.82f, -119.744f, 4.49673f }, + { 759.206f, -1155.09f, -120.051f, 4.30104f }, + { 755.973f, -1152.33f, -120.029f, 4.25588f }, + { 731.712f, -1147.56f, -120.195f, 4.95955f }, + { 726.499f, -1149.80f, -120.156f, 5.24055f }, + { 722.408f, -1152.41f, -120.029f, 5.33087f }, + { 718.994f, -1156.36f, -119.805f, 5.75738f }, + { 838.510f, -829.840f, -232.000f, 2.00000f }, }; +Position const RagnarosTelePos = { 829.159f, -815.773f, -228.972f, 5.30500f }; +Position const RagnarosSummonPos = { 838.510f, -829.840f, -232.000f, 2.00000f }; + class instance_molten_core : public InstanceMapScript { public: - instance_molten_core() : InstanceMapScript("instance_molten_core", 409) { } + instance_molten_core() : InstanceMapScript(MCScriptName, 409) { } struct instance_molten_core_InstanceMapScript : public InstanceScript { diff --git a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/molten_core.h b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/molten_core.h index c7bd9d19283..c5925731d57 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/molten_core.h +++ b/src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/molten_core.h @@ -19,6 +19,11 @@ #ifndef DEF_MOLTEN_CORE_H #define DEF_MOLTEN_CORE_H +#include "CreatureAIImpl.h" + +struct Position; + +#define MCScriptName "instance_molten_core" #define DataHeader "MC" enum MCEncounters @@ -42,8 +47,8 @@ enum MCActions ACTION_START_RAGNAROS_ALT = 1, }; -Position const RagnarosTelePos = {829.159f, -815.773f, -228.972f, 5.30500f}; -Position const RagnarosSummonPos = {838.510f, -829.840f, -232.000f, 2.00000f}; +extern Position const RagnarosTelePos; +extern Position const RagnarosSummonPos; enum MCCreatures { @@ -71,4 +76,10 @@ enum MCData DATA_RAGNAROS_ADDS = 0, }; +template +inline AI* GetMoltenCoreAI(T* obj) +{ + return GetInstanceAI(obj, MCScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/Deadmines/boss_mr_smite.cpp b/src/server/scripts/EasternKingdoms/Deadmines/boss_mr_smite.cpp index 896c48be763..46b2d5ce0b3 100644 --- a/src/server/scripts/EasternKingdoms/Deadmines/boss_mr_smite.cpp +++ b/src/server/scripts/EasternKingdoms/Deadmines/boss_mr_smite.cpp @@ -22,8 +22,12 @@ SDComment: Timers and say taken from acid script EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "deadmines.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Spells { @@ -51,11 +55,6 @@ class boss_mr_smite : public CreatureScript public: boss_mr_smite() : CreatureScript("boss_mr_smite") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_mr_smiteAI : public ScriptedAI { boss_mr_smiteAI(Creature* creature) : ScriptedAI(creature) @@ -225,6 +224,11 @@ public: uiPhase = 2; } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetDeadminesAI(creature); + } }; void AddSC_boss_mr_smite() diff --git a/src/server/scripts/EasternKingdoms/Deadmines/deadmines.h b/src/server/scripts/EasternKingdoms/Deadmines/deadmines.h index a55645a0187..ce657bbf537 100644 --- a/src/server/scripts/EasternKingdoms/Deadmines/deadmines.h +++ b/src/server/scripts/EasternKingdoms/Deadmines/deadmines.h @@ -18,6 +18,9 @@ #ifndef DEF_DEADMINES_H #define DEF_DEADMINES_H +#include "CreatureAIImpl.h" + +#define DMScriptName "instance_deadmines" #define DataHeader "DM" enum DMCannonState @@ -61,4 +64,10 @@ enum DMInstanceTexts SAY_ALARM2 = 1 }; +template +inline AI* GetDeadminesAI(T* obj) +{ + return GetInstanceAI(obj, DMScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/Deadmines/instance_deadmines.cpp b/src/server/scripts/EasternKingdoms/Deadmines/instance_deadmines.cpp index 6f11785abaf..ef6455bbf0a 100644 --- a/src/server/scripts/EasternKingdoms/Deadmines/instance_deadmines.cpp +++ b/src/server/scripts/EasternKingdoms/Deadmines/instance_deadmines.cpp @@ -24,8 +24,12 @@ SDCategory: Deadmines EndScriptData */ #include "ScriptMgr.h" -#include "InstanceScript.h" +#include "CreatureAI.h" #include "deadmines.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" #include "TemporarySummon.h" #include "WorldPacket.h" @@ -45,10 +49,7 @@ enum Misc class instance_deadmines : public InstanceMapScript { public: - instance_deadmines() - : InstanceMapScript("instance_deadmines", 36) - { - } + instance_deadmines() : InstanceMapScript(DMScriptName, 36) { } struct instance_deadmines_InstanceMapScript : public InstanceScript { diff --git a/src/server/scripts/EasternKingdoms/Gilneas/chapter1.cpp b/src/server/scripts/EasternKingdoms/Gilneas/chapter1.cpp index 2f228ab3c1c..94d77f4132b 100644 --- a/src/server/scripts/EasternKingdoms/Gilneas/chapter1.cpp +++ b/src/server/scripts/EasternKingdoms/Gilneas/chapter1.cpp @@ -16,18 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "Vehicle.h" -#include "ObjectMgr.h" -#include "ScriptedEscortAI.h" -#include "CombatAI.h" +#include "MotionMaster.h" #include "PassiveAI.h" #include "Player.h" -#include "SpellInfo.h" -#include "CreatureTextMgr.h" -#include "MoveSplineInit.h" -#include "GameObjectAI.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" /*###### ##Quest 14098 - Evacuate the Merchant Place diff --git a/src/server/scripts/EasternKingdoms/Gnomeregan/gnomeregan.cpp b/src/server/scripts/EasternKingdoms/Gnomeregan/gnomeregan.cpp index 1bafd880b60..7bede05e103 100644 --- a/src/server/scripts/EasternKingdoms/Gnomeregan/gnomeregan.cpp +++ b/src/server/scripts/EasternKingdoms/Gnomeregan/gnomeregan.cpp @@ -23,12 +23,16 @@ SDComment: Some visual effects are not implemented. Script Data End */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" +#include "gnomeregan.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedEscortAI.h" #include "ScriptedGossip.h" #include "SpellScript.h" -#include "Player.h" -#include "gnomeregan.h" +#include "TemporarySummon.h" enum BlastmasterEmi { @@ -85,11 +89,6 @@ class npc_blastmaster_emi_shortfuse : public CreatureScript public: npc_blastmaster_emi_shortfuse() : CreatureScript("npc_blastmaster_emi_shortfuse") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_blastmaster_emi_shortfuseAI : public npc_escortAI { npc_blastmaster_emi_shortfuseAI(Creature* creature) : npc_escortAI(creature) @@ -204,7 +203,7 @@ public: void AggroAllPlayers(Creature* temp) { - Map::PlayerList const &PlList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlList = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator i = PlList.begin(); i != PlList.end(); ++i) { if (Player* player = i->GetSource()) @@ -307,7 +306,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.f, G3D::Quat(), 1)) + if (GameObject* go = me->SummonGameObject(183410, -533.140f, -105.322f, -156.016f, 0.f, QuaternionData(), 1)) { GoSummonList.push_back(go->GetGUID()); go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); //We can't use it! @@ -322,7 +321,7 @@ public: Talk(SAY_BLASTMASTER_7); break; case 4: - if (GameObject* go = me->SummonGameObject(183410, -542.199f, -96.854f, -155.790f, 0.f, G3D::Quat(), 1)) + if (GameObject* go = me->SummonGameObject(183410, -542.199f, -96.854f, -155.790f, 0.f, QuaternionData(), 1)) { GoSummonList.push_back(go->GetGUID()); go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); @@ -336,7 +335,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.f, G3D::Quat(), 1)) + if (GameObject* go = me->SummonGameObject(183410, -507.820f, -103.333f, -151.353f, 0.f, QuaternionData(), 1)) { GoSummonList.push_back(go->GetGUID()); go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); //We can't use it! @@ -344,7 +343,7 @@ public: } break; case 7: - if (GameObject* go = me->SummonGameObject(183410, -511.829f, -86.249f, -151.431f, 0.f, G3D::Quat(), 1)) + if (GameObject* go = me->SummonGameObject(183410, -511.829f, -86.249f, -151.431f, 0.f, QuaternionData(), 1)) { GoSummonList.push_back(go->GetGUID()); go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); //We can't use it! @@ -356,9 +355,9 @@ public: me->SummonCreature(NPC_CHOMPER, SpawnPosition[16], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 1800000); break; case 9: - 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); + me->SummonGameObject(GO_RED_ROCKET, SpawnPosition[17], QuaternionData(), 7200); + me->SummonGameObject(GO_RED_ROCKET, SpawnPosition[18], QuaternionData(), 7200); + me->SummonGameObject(GO_RED_ROCKET, SpawnPosition[19], QuaternionData(), 7200); break; } } @@ -497,6 +496,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetGnomereganAI(creature); + } }; class boss_grubbis : public CreatureScript @@ -504,11 +507,6 @@ class boss_grubbis : public CreatureScript public: boss_grubbis() : CreatureScript("boss_grubbis") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new boss_grubbisAI(creature); - } - struct boss_grubbisAI : public ScriptedAI { boss_grubbisAI(Creature* creature) : ScriptedAI(creature) @@ -545,6 +543,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetGnomereganAI(creature); + } }; // 12709 - Collecting Fallout diff --git a/src/server/scripts/EasternKingdoms/Gnomeregan/gnomeregan.h b/src/server/scripts/EasternKingdoms/Gnomeregan/gnomeregan.h index 82e1d2af29b..fb3c9454d82 100644 --- a/src/server/scripts/EasternKingdoms/Gnomeregan/gnomeregan.h +++ b/src/server/scripts/EasternKingdoms/Gnomeregan/gnomeregan.h @@ -18,6 +18,9 @@ #ifndef DEF_GNOMEREGAN_H #define DEF_GNOMEREGAN_H +#include "CreatureAIImpl.h" + +#define GNOScriptName "instance_gnomeregan" #define DataHeader "GNO" enum GNOGameObjectIds @@ -47,4 +50,10 @@ enum GNOData64 DATA_NPC_BASTMASTER_EMI_SHORTFUSE }; +template +inline AI* GetGnomereganAI(T* obj) +{ + return GetInstanceAI(obj, GNOScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/Gnomeregan/instance_gnomeregan.cpp b/src/server/scripts/EasternKingdoms/Gnomeregan/instance_gnomeregan.cpp index c2e01b94190..452621cef03 100644 --- a/src/server/scripts/EasternKingdoms/Gnomeregan/instance_gnomeregan.cpp +++ b/src/server/scripts/EasternKingdoms/Gnomeregan/instance_gnomeregan.cpp @@ -16,8 +16,12 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" +#include "Creature.h" +#include "GameObject.h" #include "gnomeregan.h" +#include "InstanceScript.h" +#include "Log.h" +#include "Map.h" #include "Player.h" #define MAX_ENCOUNTER 1 @@ -25,12 +29,7 @@ class instance_gnomeregan : public InstanceMapScript { public: - instance_gnomeregan() : InstanceMapScript("instance_gnomeregan", 90) { } - - InstanceScript* GetInstanceScript(InstanceMap* map) const override - { - return new instance_gnomeregan_InstanceMapScript(map); - } + instance_gnomeregan() : InstanceMapScript(GNOScriptName, 90) { } struct instance_gnomeregan_InstanceMapScript : public InstanceScript { @@ -47,7 +46,7 @@ public: ObjectGuid uiBastmasterEmiShortfuseGUID; - void Load(const char* in) override + void Load(char const* in) override { if (!in) { @@ -128,6 +127,10 @@ public: } }; + InstanceScript* GetInstanceScript(InstanceMap* map) const override + { + return new instance_gnomeregan_InstanceMapScript(map); + } }; void AddSC_instance_gnomeregan() diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_midnight.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_midnight.cpp index 1717205a6c5..8af86968be8 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_midnight.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_midnight.cpp @@ -24,9 +24,11 @@ SDCategory: Karazhan EndScriptData */ #include "ScriptMgr.h" +#include "karazhan.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellInfo.h" -#include "karazhan.h" enum Texts { @@ -222,7 +224,7 @@ public: std::bind(&BossAI::DoMeleeAttackIfReady, this)); } - void SpellHit(Unit* /*source*/, const SpellInfo* spell) override + void SpellHit(Unit* /*source*/, SpellInfo const* spell) override { if (spell->Mechanic == MECHANIC_DISARM) Talk(SAY_DISARMED); @@ -276,7 +278,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_attumenAI(creature); + return GetKarazhanAI(creature); } }; @@ -378,7 +380,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_midnightAI(creature); + return GetKarazhanAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_moroes.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_moroes.cpp index b9f2959f031..ea48aae1839 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_moroes.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_moroes.cpp @@ -24,8 +24,11 @@ SDCategory: Karazhan EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "karazhan.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Yells { @@ -96,11 +99,6 @@ class boss_moroes : public CreatureScript public: boss_moroes() : CreatureScript("boss_moroes") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_moroesAI : public ScriptedAI { boss_moroesAI(Creature* creature) : ScriptedAI(creature) @@ -326,6 +324,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; struct boss_moroes_guestAI : public ScriptedAI @@ -334,10 +337,7 @@ struct boss_moroes_guestAI : public ScriptedAI ObjectGuid GuestGUID[4]; - boss_moroes_guestAI(Creature* creature) : ScriptedAI(creature) - { - instance = creature->GetInstanceScript(); - } + boss_moroes_guestAI(Creature* creature) : ScriptedAI(creature), instance(creature->GetInstanceScript()) { } void Reset() override { @@ -379,11 +379,6 @@ class boss_baroness_dorothea_millstipe : public CreatureScript public: boss_baroness_dorothea_millstipe() : CreatureScript("boss_baroness_dorothea_millstipe") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_baroness_dorothea_millstipeAI : public boss_moroes_guestAI { //Shadow Priest @@ -443,6 +438,11 @@ public: } else ShadowWordPain_Timer -= diff; } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; class boss_baron_rafe_dreuger : public CreatureScript @@ -450,11 +450,6 @@ class boss_baron_rafe_dreuger : public CreatureScript public: boss_baron_rafe_dreuger() : CreatureScript("boss_baron_rafe_dreuger") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_baron_rafe_dreugerAI : public boss_moroes_guestAI { //Retr Pally @@ -508,6 +503,11 @@ public: } else HammerOfJustice_Timer -= diff; } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; class boss_lady_catriona_von_indi : public CreatureScript @@ -515,11 +515,6 @@ class boss_lady_catriona_von_indi : public CreatureScript public: boss_lady_catriona_von_indi() : CreatureScript("boss_lady_catriona_von_indi") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_lady_catriona_von_indiAI : public boss_moroes_guestAI { //Holy Priest @@ -586,6 +581,12 @@ public: } else DispelMagic_Timer -= diff; } }; + + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; class boss_lady_keira_berrybuck : public CreatureScript @@ -593,11 +594,6 @@ class boss_lady_keira_berrybuck : public CreatureScript public: boss_lady_keira_berrybuck() : CreatureScript("boss_lady_keira_berrybuck") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_lady_keira_berrybuckAI : public boss_moroes_guestAI { //Holy Pally @@ -668,6 +664,11 @@ public: } else Cleanse_Timer -= diff; } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; class boss_lord_robin_daris : public CreatureScript @@ -675,11 +676,6 @@ class boss_lord_robin_daris : public CreatureScript public: boss_lord_robin_daris() : CreatureScript("boss_lord_robin_daris") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_lord_robin_darisAI : public boss_moroes_guestAI { //Arms Warr @@ -732,6 +728,11 @@ public: } else WhirlWind_Timer -= diff; } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; class boss_lord_crispin_ference : public CreatureScript @@ -739,11 +740,6 @@ class boss_lord_crispin_ference : public CreatureScript public: boss_lord_crispin_ference() : CreatureScript("boss_lord_crispin_ference") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_lord_crispin_ferenceAI : public boss_moroes_guestAI { //Arms Warr @@ -804,6 +800,11 @@ public: } else ShieldWall_Timer -= diff; } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; void AddSC_boss_moroes() diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_netherspite.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_netherspite.cpp index 45e14a60f33..39dd26925fd 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_netherspite.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_netherspite.cpp @@ -24,9 +24,14 @@ SDCategory: Karazhan EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" +#include "InstanceScript.h" #include "karazhan.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Netherspite { @@ -69,11 +74,6 @@ class boss_netherspite : public CreatureScript public: boss_netherspite() : CreatureScript("boss_netherspite") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_netherspiteAI : public ScriptedAI { boss_netherspiteAI(Creature* creature) : ScriptedAI(creature) @@ -340,6 +340,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; void AddSC_boss_netherspite() diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_nightbane.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_nightbane.cpp index 6289fb2bfb1..6f930c22739 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_nightbane.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_nightbane.cpp @@ -16,11 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "karazhan.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "InstanceScript.h" +#include "karazhan.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum NightbaneSpells { @@ -376,7 +380,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } }; @@ -392,9 +396,7 @@ class spell_rain_of_bones : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_SKELETON)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_SKELETON }); } void OnTrigger(AuraEffect const* aurEff) @@ -422,15 +424,16 @@ class go_blackened_urn : public GameObjectScript struct go_blackened_urnAI : public GameObjectAI { - go_blackened_urnAI(GameObject* go) : GameObjectAI(go) { } + go_blackened_urnAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* /*player*/) override { if (me->HasFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE)) return false; - InstanceScript* instance = me->GetInstanceScript(); - if (!instance || instance->GetBossState(DATA_NIGHTBANE) == DONE || instance->GetBossState(DATA_NIGHTBANE) == IN_PROGRESS) + if (instance->GetBossState(DATA_NIGHTBANE) == DONE || instance->GetBossState(DATA_NIGHTBANE) == IN_PROGRESS) return false; if (Creature* nightbane = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NIGHTBANE))) @@ -444,7 +447,7 @@ class go_blackened_urn : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return new go_blackened_urnAI(go); + return GetKarazhanAI(go); } }; diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_prince_malchezaar.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_prince_malchezaar.cpp index e4a98b5c0af..0ca9fef840d 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_prince_malchezaar.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_prince_malchezaar.cpp @@ -24,9 +24,13 @@ SDCategory: Karazhan EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "karazhan.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" +#include "SpellMgr.h" +#include "TemporarySummon.h" // 18 Coordinates for Infernal spawns struct InfernalPoint @@ -102,15 +106,10 @@ class netherspite_infernal : public CreatureScript public: netherspite_infernal() : CreatureScript("netherspite_infernal") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new netherspite_infernalAI(creature); - } - struct netherspite_infernalAI : public ScriptedAI { netherspite_infernalAI(Creature* creature) : ScriptedAI(creature), - HellfireTimer(0), CleanupTimer(0), point(NULL) { } + HellfireTimer(0), CleanupTimer(0), point(nullptr) { } uint32 HellfireTimer; uint32 CleanupTimer; @@ -151,7 +150,7 @@ public: creature->AI()->KilledUnit(who); } - void SpellHit(Unit* /*who*/, const SpellInfo* spell) override + void SpellHit(Unit* /*who*/, SpellInfo const* spell) override { if (spell->Id == SPELL_INFERNAL_RELAY) { @@ -170,6 +169,11 @@ public: void Cleanup(); }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; class boss_malchezaar : public CreatureScript @@ -177,11 +181,6 @@ class boss_malchezaar : public CreatureScript public: boss_malchezaar() : CreatureScript("boss_malchezaar") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_malchezaarAI : public ScriptedAI { boss_malchezaarAI(Creature* creature) : ScriptedAI(creature) @@ -308,16 +307,15 @@ public: void EnfeebleHealthEffect() { - const SpellInfo* info = sSpellMgr->GetSpellInfo(SPELL_ENFEEBLE_EFFECT); + SpellInfo const* info = sSpellMgr->GetSpellInfo(SPELL_ENFEEBLE_EFFECT); if (!info) return; - ThreatContainer::StorageType const &t_list = me->getThreatManager().getThreatList(); - std::vector targets; - + ThreatContainer::StorageType const& t_list = me->getThreatManager().getThreatList(); if (t_list.empty()) return; + std::vector targets; //begin + 1, so we don't target the one with the highest threat ThreatContainer::StorageType::const_iterator itr = t_list.begin(); std::advance(itr, 1); @@ -356,7 +354,7 @@ public: void SummonInfernal(const uint32 /*diff*/) { - InfernalPoint *point = NULL; + InfernalPoint* point = nullptr; Position pos; if ((me->GetMapId() != 532) || positions.empty()) pos = me->GetRandomNearPosition(60); @@ -367,7 +365,6 @@ public: } Creature* infernal = me->SummonCreature(NETHERSPITE_INFERNAL, pos, TEMPSUMMON_TIMED_DESPAWN, 180000); - if (infernal) { infernal->SetDisplayId(INFERNAL_MODEL_INVISIBLE); @@ -524,7 +521,7 @@ public: { if (SWPainTimer <= diff) { - Unit* target = NULL; + Unit* target = nullptr; if (phase == 1) target = me->GetVictim(); // the tank else // anyone but the tank @@ -573,7 +570,7 @@ public: } } - void Cleanup(Creature* infernal, InfernalPoint *point) + void Cleanup(Creature* infernal, InfernalPoint* point) { for (GuidVector::iterator itr = infernals.begin(); itr!= infernals.end(); ++itr) { @@ -587,6 +584,11 @@ public: positions.push_back(point); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; void netherspite_infernal::netherspite_infernalAI::Cleanup() 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 bc9d8576cf3..613cfb55f89 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_shade_of_aran.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_shade_of_aran.cpp @@ -24,10 +24,13 @@ SDCategory: Karazhan EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "karazhan.h" #include "GameObject.h" +#include "InstanceScript.h" +#include "karazhan.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" +#include "TemporarySummon.h" enum ShadeOfAran { @@ -84,11 +87,6 @@ class boss_shade_of_aran : public CreatureScript public: boss_shade_of_aran() : CreatureScript("boss_shade_of_aran") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_aranAI : public ScriptedAI { boss_aranAI(Creature* creature) : ScriptedAI(creature) @@ -181,12 +179,11 @@ public: void FlameWreathEffect() { - std::vector targets; - ThreatContainer::StorageType const &t_list = me->getThreatManager().getThreatList(); - + ThreatContainer::StorageType const& t_list = me->getThreatManager().getThreatList(); if (t_list.empty()) return; + std::vector targets; //store the threat list in a different container for (ThreatContainer::StorageType::const_iterator itr = t_list.begin(); itr!= t_list.end(); ++itr) { @@ -482,7 +479,7 @@ public: DrinkInturrupted = true; } - void SpellHit(Unit* /*pAttacker*/, const SpellInfo* Spell) override + void SpellHit(Unit* /*pAttacker*/, SpellInfo const* Spell) override { //We only care about interrupt effects and only if they are durring a spell currently being cast if ((Spell->Effects[0].Effect != SPELL_EFFECT_INTERRUPT_CAST && @@ -504,6 +501,11 @@ public: } } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; class npc_aran_elemental : public CreatureScript @@ -511,11 +513,6 @@ class npc_aran_elemental : public CreatureScript public: npc_aran_elemental() : CreatureScript("npc_aran_elemental") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new water_elementalAI(creature); - } - struct water_elementalAI : public ScriptedAI { water_elementalAI(Creature* creature) : ScriptedAI(creature) @@ -549,6 +546,11 @@ public: } else CastTimer -= diff; } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; void AddSC_boss_shade_of_aran() diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_terestian_illhoof.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_terestian_illhoof.cpp index d1ae4a5f0e9..66d618834b1 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_terestian_illhoof.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_terestian_illhoof.cpp @@ -16,9 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "karazhan.h" +#include "ObjectAccessor.h" #include "PassiveAI.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" enum TerestianSays diff --git a/src/server/scripts/EasternKingdoms/Karazhan/bosses_opera.cpp b/src/server/scripts/EasternKingdoms/Karazhan/bosses_opera.cpp index b82ef9ef252..f47c6d34770 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/bosses_opera.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/bosses_opera.cpp @@ -24,11 +24,16 @@ SDCategory: Karazhan EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "karazhan.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "karazhan.h" -#include "Player.h" #include "SpellInfo.h" +#include "TemporarySummon.h" /***********************************/ /*** OPERA WIZARD OF OZ EVENT *****/ @@ -116,11 +121,6 @@ class boss_dorothee : public CreatureScript public: boss_dorothee() : CreatureScript("boss_dorothee") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_dorotheeAI : public ScriptedAI { boss_dorotheeAI(Creature* creature) : ScriptedAI(creature) @@ -229,6 +229,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; class npc_tito : public CreatureScript @@ -236,11 +241,6 @@ class npc_tito : public CreatureScript public: npc_tito() : CreatureScript("npc_tito") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_titoAI(creature); - } - struct npc_titoAI : public ScriptedAI { npc_titoAI(Creature* creature) : ScriptedAI(creature) @@ -268,7 +268,7 @@ public: { if (DorotheeGUID) { - Creature* Dorothee = (ObjectAccessor::GetCreature((*me), DorotheeGUID)); + Creature* Dorothee = ObjectAccessor::GetCreature((*me), DorotheeGUID); if (Dorothee && Dorothee->IsAlive()) { ENSURE_AI(boss_dorothee::boss_dorotheeAI, Dorothee->AI())->TitoDied = true; @@ -291,6 +291,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; void boss_dorothee::boss_dorotheeAI::SummonTito() @@ -310,11 +315,6 @@ class boss_strawman : public CreatureScript public: boss_strawman() : CreatureScript("boss_strawman") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_strawmanAI : public ScriptedAI { boss_strawmanAI(Creature* creature) : ScriptedAI(creature) @@ -368,7 +368,7 @@ public: me->DespawnOrUnsummon(); } - void SpellHit(Unit* /*caster*/, const SpellInfo* Spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* Spell) override { if ((Spell->SchoolMask == SPELL_SCHOOL_MASK_FIRE) && (!(rand32() % 10))) { @@ -423,6 +423,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; class boss_tinhead : public CreatureScript @@ -430,11 +435,6 @@ class boss_tinhead : public CreatureScript public: boss_tinhead() : CreatureScript("boss_tinhead") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_tinheadAI : public ScriptedAI { boss_tinheadAI(Creature* creature) : ScriptedAI(creature) @@ -538,6 +538,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; class boss_roar : public CreatureScript @@ -545,11 +550,6 @@ class boss_roar : public CreatureScript public: boss_roar() : CreatureScript("boss_roar") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_roarAI : public ScriptedAI { boss_roarAI(Creature* creature) : ScriptedAI(creature) @@ -652,6 +652,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; class boss_crone : public CreatureScript @@ -659,11 +664,6 @@ class boss_crone : public CreatureScript public: boss_crone() : CreatureScript("boss_crone") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_croneAI : public ScriptedAI { boss_croneAI(Creature* creature) : ScriptedAI(creature) @@ -736,6 +736,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; class npc_cyclone : public CreatureScript @@ -743,11 +748,6 @@ class npc_cyclone : public CreatureScript public: npc_cyclone() : CreatureScript("npc_cyclone") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_cycloneAI(creature); - } - struct npc_cycloneAI : public ScriptedAI { npc_cycloneAI(Creature* creature) : ScriptedAI(creature) @@ -787,6 +787,11 @@ public: } else MoveTimer -= diff; } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; /**************************************/ @@ -834,7 +839,7 @@ class npc_grandmother : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_grandmotherAI(creature); + return GetKarazhanAI(creature); } }; @@ -843,11 +848,6 @@ class boss_bigbadwolf : public CreatureScript public: boss_bigbadwolf() : CreatureScript("boss_bigbadwolf") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_bigbadwolfAI : public ScriptedAI { boss_bigbadwolfAI(Creature* creature) : ScriptedAI(creature) @@ -962,6 +962,11 @@ public: } else SwipeTimer -= diff; } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; /**********************************************/ @@ -1042,11 +1047,6 @@ class boss_julianne : public CreatureScript public: boss_julianne() : CreatureScript("boss_julianne") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_julianneAI : public ScriptedAI { boss_julianneAI(Creature* creature) : ScriptedAI(creature) @@ -1132,7 +1132,7 @@ public: me->DespawnOrUnsummon(); } - void SpellHit(Unit* /*caster*/, const SpellInfo* Spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* Spell) override { if (Spell->Id == SPELL_DRINK_POISON) { @@ -1156,6 +1156,11 @@ public: void UpdateAI(uint32 diff) override; }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; class boss_romulo : public CreatureScript @@ -1163,11 +1168,6 @@ class boss_romulo : public CreatureScript public: boss_romulo() : CreatureScript("boss_romulo") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_romuloAI : public ScriptedAI { boss_romuloAI(Creature* creature) : ScriptedAI(creature) @@ -1360,6 +1360,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; void boss_julianne::boss_julianneAI::UpdateAI(uint32 diff) diff --git a/src/server/scripts/EasternKingdoms/Karazhan/instance_karazhan.cpp b/src/server/scripts/EasternKingdoms/Karazhan/instance_karazhan.cpp index b75698ec558..2e071ae2874 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/instance_karazhan.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/instance_karazhan.cpp @@ -24,8 +24,12 @@ SDCategory: Karazhan EndScriptData */ #include "ScriptMgr.h" +#include "Creature.h" +#include "GameObject.h" #include "InstanceScript.h" #include "karazhan.h" +#include "Map.h" +#include "Random.h" /* 0 - Attumen + Midnight (optional) @@ -161,7 +165,7 @@ public: HandleGameObject(StageDoorRightGUID, true); if (GameObject* sideEntrance = instance->GetGameObject(SideEntranceDoor)) sideEntrance->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED); - UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, 16812, NULL); + UpdateEncounterStateForKilledCreature(16812, nullptr); } break; case DATA_CHESS: diff --git a/src/server/scripts/EasternKingdoms/Karazhan/karazhan.cpp b/src/server/scripts/EasternKingdoms/Karazhan/karazhan.cpp index f6ddb2c1f70..9d99fe221d6 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/karazhan.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/karazhan.cpp @@ -29,11 +29,16 @@ npc_image_of_medivh EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" +#include "InstanceScript.h" #include "karazhan.h" -#include "ScriptedEscortAI.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "TemporarySummon.h" enum Spells { @@ -309,7 +314,7 @@ public: { if (WipeTimer <= diff) { - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); if (PlayerList.isEmpty()) return; @@ -403,7 +408,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetKarazhanAI(creature); } }; @@ -430,11 +435,6 @@ class npc_image_of_medivh : public CreatureScript public: npc_image_of_medivh() : CreatureScript("npc_image_of_medivh") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_image_of_medivhAI : public ScriptedAI { npc_image_of_medivhAI(Creature* creature) : ScriptedAI(creature) @@ -476,7 +476,7 @@ public: } else { - 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(); } } @@ -571,7 +571,7 @@ public: me->SetVisible(false); me->ClearInCombat(); - InstanceMap::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + InstanceMap::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); for (InstanceMap::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) { if (i->GetSource()->IsAlive()) @@ -584,7 +584,7 @@ public: } case 15: if (Creature* arca = ObjectAccessor::GetCreature(*me, ArcanagosGUID)) - arca->DealDamage(arca, arca->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + arca->DealDamage(arca, arca->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); return 5000; default: return 9999999; @@ -619,6 +619,11 @@ public: } } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetKarazhanAI(creature); + } }; void AddSC_karazhan() diff --git a/src/server/scripts/EasternKingdoms/Karazhan/karazhan.h b/src/server/scripts/EasternKingdoms/Karazhan/karazhan.h index f799840c310..21033b456bd 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/karazhan.h +++ b/src/server/scripts/EasternKingdoms/Karazhan/karazhan.h @@ -19,6 +19,8 @@ #ifndef DEF_KARAZHAN_H #define DEF_KARAZHAN_H +#include "CreatureAIImpl.h" + #define KZScriptName "instance_karazhan" #define DataHeader "KZ" @@ -111,7 +113,7 @@ enum KZMisc OPTIONAL_BOSS_REQUIRED_DEATH_COUNT = 50 }; -template +template inline AI* GetKarazhanAI(T* obj) { return GetInstanceAI(obj, KZScriptName); diff --git a/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_felblood_kaelthas.cpp b/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_felblood_kaelthas.cpp index c50e8fdccca..0cf6f890e76 100644 --- a/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_felblood_kaelthas.cpp +++ b/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_felblood_kaelthas.cpp @@ -24,10 +24,15 @@ SDCategory: Magisters' Terrace EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" +#include "InstanceScript.h" #include "magisters_terrace.h" -#include "WorldPacket.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Opcodes.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" +#include "WorldPacket.h" enum Says { @@ -94,11 +99,6 @@ class boss_felblood_kaelthas : public CreatureScript public: boss_felblood_kaelthas() : CreatureScript("boss_felblood_kaelthas") { } - CreatureAI* GetAI(Creature* c) const override - { - return GetInstanceAI(c); - } - struct boss_felblood_kaelthasAI : public ScriptedAI { boss_felblood_kaelthasAI(Creature* creature) : ScriptedAI(creature) @@ -428,6 +428,11 @@ public: } } }; + + CreatureAI* GetAI(Creature* c) const override + { + return GetMagistersTerraceAI(c); + } }; class npc_felkael_flamestrike : public CreatureScript @@ -435,11 +440,6 @@ class npc_felkael_flamestrike : public CreatureScript public: npc_felkael_flamestrike() : CreatureScript("npc_felkael_flamestrike") { } - CreatureAI* GetAI(Creature* c) const override - { - return new npc_felkael_flamestrikeAI(c); - } - struct npc_felkael_flamestrikeAI : public ScriptedAI { npc_felkael_flamestrikeAI(Creature* creature) : ScriptedAI(creature) @@ -476,6 +476,11 @@ public: } else FlameStrikeTimer -= diff; } }; + + CreatureAI* GetAI(Creature* c) const override + { + return GetMagistersTerraceAI(c); + } }; class npc_felkael_phoenix : public CreatureScript @@ -483,11 +488,6 @@ class npc_felkael_phoenix : public CreatureScript public: npc_felkael_phoenix() : CreatureScript("npc_felkael_phoenix") { } - CreatureAI* GetAI(Creature* c) const override - { - return GetInstanceAI(c); - } - struct npc_felkael_phoenixAI : public ScriptedAI { npc_felkael_phoenixAI(Creature* creature) : ScriptedAI(creature) @@ -585,13 +585,18 @@ public: { //spell Burn should possible do this, but it doesn't, so do this for now. uint16 dmg = urand(1650, 2050); - me->DealDamage(me, dmg, 0, DOT, SPELL_SCHOOL_MASK_FIRE, NULL, false); + me->DealDamage(me, dmg, 0, DOT, SPELL_SCHOOL_MASK_FIRE, nullptr, false); BurnTimer += 2000; } BurnTimer -= diff; DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* c) const override + { + return GetMagistersTerraceAI(c); + } }; class npc_felkael_phoenix_egg : public CreatureScript @@ -599,11 +604,6 @@ class npc_felkael_phoenix_egg : public CreatureScript public: npc_felkael_phoenix_egg() : CreatureScript("npc_felkael_phoenix_egg") { } - CreatureAI* GetAI(Creature* c) const override - { - return new npc_felkael_phoenix_eggAI(c); - } - struct npc_felkael_phoenix_eggAI : public ScriptedAI { npc_felkael_phoenix_eggAI(Creature* creature) : ScriptedAI(creature) @@ -636,6 +636,11 @@ public: } else HatchTimer -= diff; } }; + + CreatureAI* GetAI(Creature* c) const override + { + return GetMagistersTerraceAI(c); + } }; class npc_arcane_sphere : public CreatureScript @@ -643,11 +648,6 @@ class npc_arcane_sphere : public CreatureScript public: npc_arcane_sphere() : CreatureScript("npc_arcane_sphere") { } - CreatureAI* GetAI(Creature* c) const override - { - return new npc_arcane_sphereAI(c); - } - struct npc_arcane_sphereAI : public ScriptedAI { npc_arcane_sphereAI(Creature* creature) : ScriptedAI(creature) { Reset(); } @@ -692,6 +692,11 @@ public: } else ChangeTargetTimer -= diff; } }; + + CreatureAI* GetAI(Creature* c) const override + { + return GetMagistersTerraceAI(c); + } }; void AddSC_boss_felblood_kaelthas() diff --git a/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_priestess_delrissa.cpp b/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_priestess_delrissa.cpp index 5ef6262be0b..1b1e13fc5fb 100644 --- a/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_priestess_delrissa.cpp +++ b/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_priestess_delrissa.cpp @@ -24,8 +24,11 @@ SDCategory: Magister's Terrace EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "magisters_terrace.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" struct Speech { @@ -108,11 +111,6 @@ class boss_priestess_delrissa : public CreatureScript public: boss_priestess_delrissa() : CreatureScript("boss_priestess_delrissa") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_priestess_delrissaAI : public ScriptedAI { boss_priestess_delrissaAI(Creature* creature) : ScriptedAI(creature) @@ -315,7 +313,7 @@ public: if (DispelTimer <= diff) { - Unit* target = NULL; + Unit* target = nullptr; if (urand(0, 1)) target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true); @@ -346,6 +344,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetMagistersTerraceAI(creature); + } }; enum HealingPotion @@ -495,11 +498,6 @@ class boss_kagani_nightstrike : public CreatureScript public: boss_kagani_nightstrike() : CreatureScript("boss_kagani_nightstrike") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_kagani_nightstrikeAI : public boss_priestess_lackey_commonAI { //Rogue @@ -589,6 +587,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetMagistersTerraceAI(creature); + } }; enum WarlockSpells @@ -607,11 +610,6 @@ class boss_ellris_duskhallow : public CreatureScript public: boss_ellris_duskhallow() : CreatureScript("boss_ellris_duskhallow") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_ellris_duskhallowAI : public boss_priestess_lackey_commonAI { //Warlock @@ -693,6 +691,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetMagistersTerraceAI(creature); + } }; enum KickDown @@ -706,11 +709,6 @@ class boss_eramas_brightblaze : public CreatureScript public: boss_eramas_brightblaze() : CreatureScript("boss_eramas_brightblaze") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_eramas_brightblazeAI : public boss_priestess_lackey_commonAI { //Monk @@ -757,6 +755,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetMagistersTerraceAI(creature); + } }; enum MageSpells @@ -775,11 +778,6 @@ class boss_yazzai : public CreatureScript public: boss_yazzai() : CreatureScript("boss_yazzai") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_yazzaiAI : public boss_priestess_lackey_commonAI { //Mage @@ -895,6 +893,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetMagistersTerraceAI(creature); + } }; enum WarriorSpells @@ -913,11 +916,6 @@ class boss_warlord_salaris : public CreatureScript public: boss_warlord_salaris() : CreatureScript("boss_warlord_salaris") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_warlord_salarisAI : public boss_priestess_lackey_commonAI { //Warrior @@ -1022,6 +1020,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetMagistersTerraceAI(creature); + } }; enum HunterSpells @@ -1041,11 +1044,6 @@ class boss_garaxxas : public CreatureScript public: boss_garaxxas() : CreatureScript("boss_garaxxas") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_garaxxasAI : public boss_priestess_lackey_commonAI { //Hunter @@ -1150,6 +1148,11 @@ public: } } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetMagistersTerraceAI(creature); + } }; class boss_apoko : public CreatureScript @@ -1157,11 +1160,6 @@ class boss_apoko : public CreatureScript public: boss_apoko() : CreatureScript("boss_apoko") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_apokoAI : public boss_priestess_lackey_commonAI { //Shaman @@ -1237,6 +1235,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetMagistersTerraceAI(creature); + } }; enum EngineerSpells @@ -1254,11 +1257,6 @@ class boss_zelfan : public CreatureScript public: boss_zelfan() : CreatureScript("boss_zelfan") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_zelfanAI : public boss_priestess_lackey_commonAI { //Engineer @@ -1339,6 +1337,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetMagistersTerraceAI(creature); + } }; /* @@ -1349,7 +1352,7 @@ public: //CreatureAI* GetAI(Creature* creature) const override //{ - // return new npc_high_explosive_sheepAI(creature); + // return GetMagistersTerraceAI(creature); //}; }; */ diff --git a/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_selin_fireheart.cpp b/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_selin_fireheart.cpp index 70ed742aec6..5f7d90c68fc 100644 --- a/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_selin_fireheart.cpp +++ b/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_selin_fireheart.cpp @@ -16,8 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "magisters_terrace.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Says { @@ -247,7 +250,7 @@ class boss_selin_fireheart : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMagistersTerraceAI(creature); }; }; @@ -273,7 +276,7 @@ class npc_fel_crystal : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMagistersTerraceAI(creature); }; }; diff --git a/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_vexallus.cpp b/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_vexallus.cpp index 94cf59f5b92..95c29ed6bf3 100644 --- a/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_vexallus.cpp +++ b/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_vexallus.cpp @@ -16,8 +16,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "magisters_terrace.h" +#include "MotionMaster.h" +#include "ScriptedCreature.h" enum Yells { @@ -177,7 +178,7 @@ class boss_vexallus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMagistersTerraceAI(creature); }; }; @@ -210,7 +211,7 @@ class npc_pure_energy : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_pure_energyAI(creature); + return GetMagistersTerraceAI(creature); }; }; diff --git a/src/server/scripts/EasternKingdoms/MagistersTerrace/instance_magisters_terrace.cpp b/src/server/scripts/EasternKingdoms/MagistersTerrace/instance_magisters_terrace.cpp index bdf0c5f1f8b..aa844e8812f 100644 --- a/src/server/scripts/EasternKingdoms/MagistersTerrace/instance_magisters_terrace.cpp +++ b/src/server/scripts/EasternKingdoms/MagistersTerrace/instance_magisters_terrace.cpp @@ -16,10 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "CreatureAI.h" +#include "EventMap.h" +#include "GameObject.h" #include "InstanceScript.h" #include "magisters_terrace.h" -#include "EventMap.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "TemporarySummon.h" /* 0 - Selin Fireheart @@ -43,7 +48,7 @@ Position const KalecgosSpawnPos = { 164.3747f, -397.1197f, 2.151798f, 1.66219f } class instance_magisters_terrace : public InstanceMapScript { public: - instance_magisters_terrace() : InstanceMapScript("instance_magisters_terrace", 585) { } + instance_magisters_terrace() : InstanceMapScript(MGTScriptName, 585) { } struct instance_magisters_terrace_InstanceMapScript : public InstanceScript { diff --git a/src/server/scripts/EasternKingdoms/MagistersTerrace/magisters_terrace.cpp b/src/server/scripts/EasternKingdoms/MagistersTerrace/magisters_terrace.cpp index fa78c2a7ffb..9406b6ed41f 100644 --- a/src/server/scripts/EasternKingdoms/MagistersTerrace/magisters_terrace.cpp +++ b/src/server/scripts/EasternKingdoms/MagistersTerrace/magisters_terrace.cpp @@ -28,11 +28,11 @@ npc_kalecgos EndContentData */ #include "ScriptMgr.h" +#include "magisters_terrace.h" +#include "MotionMaster.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "Player.h" -#include "magisters_terrace.h" -#include "EventMap.h" /*###### ## npc_kalecgos @@ -68,11 +68,6 @@ class npc_kalecgos : public CreatureScript public: npc_kalecgos() : CreatureScript("npc_kalecgos") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_kalecgosAI(creature); - } - struct npc_kalecgosAI : public ScriptedAI { npc_kalecgosAI(Creature* creature) : ScriptedAI(creature) { } @@ -157,6 +152,11 @@ public: private: EventMap events; }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetMagistersTerraceAI(creature); + } }; void AddSC_magisters_terrace() diff --git a/src/server/scripts/EasternKingdoms/MagistersTerrace/magisters_terrace.h b/src/server/scripts/EasternKingdoms/MagistersTerrace/magisters_terrace.h index d6f35e09514..d04d8b06b53 100644 --- a/src/server/scripts/EasternKingdoms/MagistersTerrace/magisters_terrace.h +++ b/src/server/scripts/EasternKingdoms/MagistersTerrace/magisters_terrace.h @@ -19,6 +19,9 @@ #ifndef DEF_MAGISTERS_TERRACE_H #define DEF_MAGISTERS_TERRACE_H +#include "CreatureAIImpl.h" + +#define MGTScriptName "instance_magisters_terrace" #define DataHeader "MT" uint32 const EncounterCount = 4; @@ -74,4 +77,10 @@ enum MTMovementData PATH_KALECGOS_FLIGHT = 248440 }; +template +inline AI* GetMagistersTerraceAI(T* obj) +{ + return GetInstanceAI(obj, MGTScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter1.cpp b/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter1.cpp index 257f6c40baa..c611c3cc273 100644 --- a/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter1.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter1.cpp @@ -16,18 +16,19 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "Vehicle.h" -#include "ObjectMgr.h" -#include "ScriptedEscortAI.h" #include "CombatAI.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "Log.h" +#include "MotionMaster.h" +#include "MoveSplineInit.h" +#include "ObjectAccessor.h" #include "PassiveAI.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" #include "SpellInfo.h" -#include "CreatureTextMgr.h" -#include "MoveSplineInit.h" -#include "GameObjectAI.h" +#include "Vehicle.h" /*###### ##Quest 12848 @@ -191,7 +192,7 @@ public: TC_LOG_ERROR("scripts", "npc_unworthy_initiateAI: unable to find anchor!"); float dist = 99.0f; - GameObject* prison = NULL; + GameObject* prison = nullptr; for (uint8 i = 0; i < 12; ++i) { @@ -511,7 +512,7 @@ public: me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNK_15); } - void SpellHit(Unit* pCaster, const SpellInfo* pSpell) override + void SpellHit(Unit* pCaster, SpellInfo const* pSpell) override { if (!m_bIsDuelInProgress && pSpell->Id == SPELL_DUEL) { @@ -769,7 +770,7 @@ public: return false; } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (spell->Id == SPELL_DELIVER_STOLEN_HORSE) { @@ -1070,7 +1071,7 @@ class npc_scarlet_miner_cart : public CreatureScript if (apply) { _playerGUID = who->GetGUID(); - me->CastSpell((Unit*)NULL, SPELL_SUMMON_MINER, true); + me->CastSpell((Unit*)nullptr, SPELL_SUMMON_MINER, true); } else { diff --git a/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter2.cpp b/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter2.cpp index 193a31325db..35cb0946424 100644 --- a/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter2.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter2.cpp @@ -16,11 +16,13 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" -#include "Player.h" -#include "SpellInfo.h" #include "CreatureTextMgr.h" +#include "GameObject.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedEscortAI.h" +#include "SpellInfo.h" //How to win friends and influence enemies // texts signed for creature 28939 but used for 28939, 28940, 28610 @@ -74,7 +76,7 @@ public: me->RestoreFaction(); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (spell->Id == SPELL_PERSUASIVE_STRIKE && caster->GetTypeId() == TYPEID_PLAYER && me->IsAlive() && !speechCounter) { @@ -91,7 +93,7 @@ public: me->SetReactState(REACT_PASSIVE); DoCastAOE(SPELL_THREAT_PULSE, true); - sCreatureTextMgr->SendChat(me, SAY_PERSUADE_RAND, NULL, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player); + sCreatureTextMgr->SendChat(me, SAY_PERSUADE_RAND, nullptr, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player); Talk(SAY_CRUSADER); } } @@ -134,7 +136,7 @@ public: break; case 5: - sCreatureTextMgr->SendChat(me, SAY_PERSUADED5, NULL, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player); + sCreatureTextMgr->SendChat(me, SAY_PERSUADED5, nullptr, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player); speechTimer = 8000; break; diff --git a/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter5.cpp b/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter5.cpp index 2f8ed573d22..a99bdbae5fd 100644 --- a/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter5.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter5.cpp @@ -16,10 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "GameObject.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "TemporarySummon.h" #define LESS_MOB // if you do not have a good server and do not want it to be laggy as hell //Light of Dawn @@ -220,7 +224,6 @@ enum mograine void UpdateWorldState(Map* map, uint32 id, uint32 state) { Map::PlayerList const& players = map->GetPlayers(); - if (!players.isEmpty()) { for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) @@ -1087,9 +1090,9 @@ public: break; case 48: // Show the cleansing effect (dawn of light) - //if (GameObject* go = me->GetMap()->GetGameObject(uiDawnofLightGUID)) + //if (GameObject* go = ObjectAccessor::GetGameObject(*me, uiDawnofLightGUID)) // go->SetPhaseMask(128, true); - me->SummonGameObject(GO_LIGHT_OF_DAWN, 2283.896f, -5287.914f, 83.066f, 0.f, G3D::Quat(), 30); + me->SummonGameObject(GO_LIGHT_OF_DAWN, 2283.896f, -5287.914f, 83.066f, 0.f, QuaternionData(), 30); if (Creature* temp = ObjectAccessor::GetCreature(*me, uiTirionGUID)) { if (temp->HasAura(SPELL_REBIRTH_OF_THE_ASHBRINGER)) @@ -1263,11 +1266,11 @@ public: break; case 71: - //if (GameObject* go = me->GetMap()->GetGameObject(uiDawnofLightGUID)) // Turn off dawn of light + //if (GameObject* go = ObjectAccessor::GetGameObject(*me, uiDawnofLightGUID)) // Turn off dawn of light // go->SetPhaseMask(0, true); { // search players with in 50 yards for quest credit - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); if (!PlayerList.isEmpty()) { for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -1499,7 +1502,7 @@ public: void SpawnNPC() { - Unit* temp = NULL; + Unit* temp = nullptr; // Death for (uint8 i = 0; i < ENCOUNTER_GHOUL_NUMBER; ++i) 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 bdad7f9a178..b9728f6777b 100644 --- a/src/server/scripts/EasternKingdoms/ScarletEnclave/zone_the_scarlet_enclave.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletEnclave/zone_the_scarlet_enclave.cpp @@ -16,9 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "MotionMaster.h" #include "PassiveAI.h" #include "Player.h" +#include "TemporarySummon.h" /*#### ## npc_valkyr_battle_maiden @@ -84,7 +85,7 @@ public: { if (FlyBackTimer <= diff) { - Player* player = NULL; + Player* player = nullptr; if (me->IsSummon()) if (Unit* summoner = me->ToTempSummon()->GetSummoner()) player = summoner->ToPlayer(); diff --git a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_headless_horseman.cpp b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_headless_horseman.cpp index 960dd836a66..892a9372997 100644 --- a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_headless_horseman.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_headless_horseman.cpp @@ -24,14 +24,20 @@ SDCategory: Scarlet Monastery EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellMgr.h" -#include "scarlet_monastery.h" -#include "LFGMgr.h" -#include "Player.h" -#include "Group.h" -#include "SpellInfo.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "Group.h" +#include "InstanceScript.h" +#include "LFGMgr.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "scarlet_monastery.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellMgr.h" +#include "TemporarySummon.h" //this texts are already used by 3975 and 3976 enum Says @@ -96,7 +102,7 @@ enum Spells SPELL_DEATH = 42566 //not correct spell }; -G3D::Vector3 const FlightPoint[]= +Position const FlightPoint[]= { {1754.00f, 1346.00f, 17.50f}, {1765.00f, 1347.00f, 19.00f}, @@ -121,7 +127,7 @@ G3D::Vector3 const FlightPoint[]= {1758.00f, 1367.00f, 19.51f} }; -G3D::Vector3 const Spawn[]= +Position const Spawn[]= { {1776.27f, 1348.74f, 19.20f}, //spawn point for pumpkin shrine mob {1765.28f, 1347.46f, 17.55f} //spawn point for smoke @@ -140,11 +146,6 @@ class npc_wisp_invis : public CreatureScript public: npc_wisp_invis() : CreatureScript("npc_wisp_invis") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_wisp_invisAI(creature); - } - struct npc_wisp_invisAI : public ScriptedAI { npc_wisp_invisAI(Creature* creature) : ScriptedAI(creature) @@ -183,7 +184,7 @@ public: DoCast(me, _spell); } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_WISP_FLIGHT_PORT && Creaturetype == 4) me->SetDisplayId(2027); @@ -212,6 +213,11 @@ public: } } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetScarletMonasteryAI(creature); + } }; class npc_head : public CreatureScript @@ -219,11 +225,6 @@ class npc_head : public CreatureScript public: npc_head() : CreatureScript("npc_head") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_headAI(creature); - } - struct npc_headAI : public ScriptedAI { npc_headAI(Creature* creature) : ScriptedAI(creature) @@ -298,7 +299,7 @@ public: } } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (!withbody) return; @@ -365,6 +366,11 @@ public: } } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetScarletMonasteryAI(creature); + } }; class boss_headless_horseman : public CreatureScript @@ -372,11 +378,6 @@ class boss_headless_horseman : public CreatureScript public: boss_headless_horseman() : CreatureScript("boss_headless_horseman") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_headless_horsemanAI : public ScriptedAI { boss_headless_horsemanAI(Creature* creature) : ScriptedAI(creature) @@ -473,7 +474,7 @@ public: break; case 1: { - if (Creature* smoke = me->SummonCreature(HELPER, Spawn[1].x, Spawn[1].y, Spawn[1].z, 0, TEMPSUMMON_TIMED_DESPAWN, 20000)) + if (Creature* smoke = me->SummonCreature(HELPER, Spawn[1], TEMPSUMMON_TIMED_DESPAWN, 20000)) ENSURE_AI(npc_wisp_invis::npc_wisp_invisAI, smoke->AI())->SetType(3); DoCast(me, SPELL_RHYME_BIG); break; @@ -536,9 +537,9 @@ public: Player* SelectRandomPlayer(float range = 0.0f, bool checkLoS = true) { - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); if (PlayerList.isEmpty()) - return NULL; + return nullptr; std::list temp; for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -552,10 +553,10 @@ public: advance(j, rand32() % temp.size()); return (*j); } - return NULL; + return nullptr; } - void SpellHitTarget(Unit* unit, const SpellInfo* spell) override + void SpellHitTarget(Unit* unit, SpellInfo const* spell) override { if (spell->Id == SPELL_CONFLAGRATION && unit->HasAura(SPELL_CONFLAGRATION)) SaySound(SAY_CONFLAGRATION, unit); @@ -581,7 +582,7 @@ public: } } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (withhead) return; @@ -682,7 +683,7 @@ public: { wp_reached = false; me->GetMotionMaster()->Clear(false); - me->GetMotionMaster()->MovePoint(id, FlightPoint[id].x, FlightPoint[id].y, FlightPoint[id].z); + me->GetMotionMaster()->MovePoint(id, FlightPoint[id]); } } } @@ -692,7 +693,7 @@ public: break; if (burn <= diff) { - if (Creature* flame = me->SummonCreature(HELPER, Spawn[0].x, Spawn[0].y, Spawn[0].z, 0, TEMPSUMMON_TIMED_DESPAWN, 17000)) + if (Creature* flame = me->SummonCreature(HELPER, Spawn[0], TEMPSUMMON_TIMED_DESPAWN, 17000)) ENSURE_AI(npc_wisp_invis::npc_wisp_invisAI, flame->AI())->SetType(2); burned = true; } @@ -775,6 +776,11 @@ public: } } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetScarletMonasteryAI(creature); + } }; class npc_pulsing_pumpkin : public CreatureScript @@ -782,11 +788,6 @@ class npc_pulsing_pumpkin : public CreatureScript public: npc_pulsing_pumpkin() : CreatureScript("npc_pulsing_pumpkin") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_pulsing_pumpkinAI(creature); - } - struct npc_pulsing_pumpkinAI : public ScriptedAI { npc_pulsing_pumpkinAI(Creature* creature) : ScriptedAI(creature) @@ -820,7 +821,7 @@ public: void JustEngagedWith(Unit* /*who*/) override { } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_SPROUTING) { @@ -868,6 +869,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetScarletMonasteryAI(creature); + } }; enum LooselyTurnedSoil @@ -882,25 +888,25 @@ class go_loosely_turned_soil : public GameObjectScript struct go_loosely_turned_soilAI : public GameObjectAI { - go_loosely_turned_soilAI(GameObject* go) : GameObjectAI(go) { } + go_loosely_turned_soilAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* player) override { - if (InstanceScript* instance = player->GetInstanceScript()) - if (instance->GetBossState(DATA_HORSEMAN_EVENT) == IN_PROGRESS || player->GetQuestStatus(QUEST_CALL_THE_HEADLESS_HORSEMAN) != QUEST_STATUS_COMPLETE) - return true; + if (instance->GetBossState(DATA_HORSEMAN_EVENT) == IN_PROGRESS || player->GetQuestStatus(QUEST_CALL_THE_HEADLESS_HORSEMAN) != QUEST_STATUS_COMPLETE) + return true; return false; } void QuestReward(Player* player, Quest const* /*quest*/, uint32 /*opt*/) override { - if (InstanceScript* instance = me->GetInstanceScript()) - if (instance->GetBossState(DATA_HORSEMAN_EVENT) == IN_PROGRESS) - return; + if (instance->GetBossState(DATA_HORSEMAN_EVENT) == IN_PROGRESS) + return; player->AreaExploredOrEventHappens(11405); - if (Creature* horseman = me->SummonCreature(HH_MOUNTED, FlightPoint[20].x, FlightPoint[20].y, FlightPoint[20].z, 0, TEMPSUMMON_MANUAL_DESPAWN, 0)) + if (Creature* horseman = me->SummonCreature(HH_MOUNTED, FlightPoint[20], 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(); @@ -910,7 +916,7 @@ class go_loosely_turned_soil : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return new go_loosely_turned_soilAI(go); + return GetScarletMonasteryAI(go); } }; diff --git a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_high_inquisitor_fairbanks.cpp b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_high_inquisitor_fairbanks.cpp index 3c1763fee9e..278b8c6f540 100644 --- a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_high_inquisitor_fairbanks.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_high_inquisitor_fairbanks.cpp @@ -24,8 +24,9 @@ SDCategory: Scarlet Monastery EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "scarlet_monastery.h" +#include "ScriptedCreature.h" enum Spells { @@ -42,11 +43,6 @@ class boss_high_inquisitor_fairbanks : public CreatureScript public: boss_high_inquisitor_fairbanks() : CreatureScript("boss_high_inquisitor_fairbanks") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_high_inquisitor_fairbanksAI : public ScriptedAI { boss_high_inquisitor_fairbanksAI(Creature* creature) : ScriptedAI(creature) @@ -154,6 +150,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetScarletMonasteryAI(creature); + } }; void AddSC_boss_high_inquisitor_fairbanks() diff --git a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_interrogator_vishas.cpp b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_interrogator_vishas.cpp index 0d51eb0c115..312c16fdd37 100644 --- a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_interrogator_vishas.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_interrogator_vishas.cpp @@ -16,8 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "scarlet_monastery.h" +#include "ScriptedCreature.h" enum Says { @@ -115,7 +117,7 @@ class boss_interrogator_vishas : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetScarletMonasteryAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_mograine_and_whitemane.cpp b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_mograine_and_whitemane.cpp index 5ff1100798b..10d429a26ea 100644 --- a/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_mograine_and_whitemane.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletMonastery/boss_mograine_and_whitemane.cpp @@ -24,8 +24,11 @@ SDCategory: Scarlet Monastery EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "scarlet_monastery.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" enum Says @@ -63,11 +66,6 @@ class boss_scarlet_commander_mograine : public CreatureScript public: boss_scarlet_commander_mograine() : CreatureScript("boss_scarlet_commander_mograine") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_scarlet_commander_mograineAI : public ScriptedAI { boss_scarlet_commander_mograineAI(Creature* creature) : ScriptedAI(creature) @@ -160,7 +158,7 @@ public: } } - void SpellHit(Unit* /*who*/, const SpellInfo* spell) override + void SpellHit(Unit* /*who*/, SpellInfo const* spell) override { //When hit with resurrection say text if (spell->Id == SPELL_SCARLETRESURRECTION) @@ -219,6 +217,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetScarletMonasteryAI(creature); + } }; class boss_high_inquisitor_whitemane : public CreatureScript @@ -226,11 +229,6 @@ class boss_high_inquisitor_whitemane : public CreatureScript public: boss_high_inquisitor_whitemane() : CreatureScript("boss_high_inquisitor_whitemane") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_high_inquisitor_whitemaneAI : public ScriptedAI { boss_high_inquisitor_whitemaneAI(Creature* creature) : ScriptedAI(creature) @@ -331,7 +329,7 @@ public: //If we are <75% hp cast healing spells at self or Mograine if (Heal_Timer <= diff) { - Creature* target = NULL; + Creature* target = nullptr; if (!HealthAbovePct(75)) target = me; @@ -369,6 +367,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetScarletMonasteryAI(creature); + } }; void AddSC_boss_mograine_and_whitemane() diff --git a/src/server/scripts/EasternKingdoms/ScarletMonastery/instance_scarlet_monastery.cpp b/src/server/scripts/EasternKingdoms/ScarletMonastery/instance_scarlet_monastery.cpp index 6fa715f3902..111c37f5a81 100644 --- a/src/server/scripts/EasternKingdoms/ScarletMonastery/instance_scarlet_monastery.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletMonastery/instance_scarlet_monastery.cpp @@ -16,7 +16,10 @@ */ #include "ScriptMgr.h" +#include "Creature.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" #include "scarlet_monastery.h" DoorData const doorData[] = diff --git a/src/server/scripts/EasternKingdoms/ScarletMonastery/scarlet_monastery.h b/src/server/scripts/EasternKingdoms/ScarletMonastery/scarlet_monastery.h index b335f400c42..5117a533599 100644 --- a/src/server/scripts/EasternKingdoms/ScarletMonastery/scarlet_monastery.h +++ b/src/server/scripts/EasternKingdoms/ScarletMonastery/scarlet_monastery.h @@ -18,6 +18,8 @@ #ifndef SCARLET_M_ #define SCARLET_M_ +#include "CreatureAIImpl.h" + #define SMScriptName "instance_scarlet_monastery" #define DataHeader "SM" @@ -60,10 +62,10 @@ enum SMGameObjectIds GO_PUMPKIN_SHRINE = 186267 }; -template -inline AI* GetScarletMonasteryAI(Creature* creature) +template +inline AI* GetScarletMonasteryAI(T* obj) { - return GetInstanceAI(creature, SMScriptName); + return GetInstanceAI(obj, SMScriptName); } #endif // SCARLET_M_ diff --git a/src/server/scripts/EasternKingdoms/Scholomance/boss_darkmaster_gandling.cpp b/src/server/scripts/EasternKingdoms/Scholomance/boss_darkmaster_gandling.cpp index dc54d93953c..f4aa05e27e2 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/boss_darkmaster_gandling.cpp +++ b/src/server/scripts/EasternKingdoms/Scholomance/boss_darkmaster_gandling.cpp @@ -23,9 +23,15 @@ Category: Scholomance */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "scholomance.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" #include "SpellScript.h" +#include "TemporarySummon.h" enum Says { @@ -59,14 +65,14 @@ class boss_darkmaster_gandling : public CreatureScript void Reset() override { _Reset(); - if (GameObject* gate = me->GetMap()->GetGameObject(instance->GetGuidData(GO_GATE_GANDLING))) + if (GameObject* gate = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_GATE_GANDLING))) gate->SetGoState(GO_STATE_ACTIVE); } void JustDied(Unit* /*killer*/) override { _JustDied(); - if (GameObject* gate = me->GetMap()->GetGameObject(instance->GetGuidData(GO_GATE_GANDLING))) + if (GameObject* gate = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_GATE_GANDLING))) gate->SetGoState(GO_STATE_ACTIVE); } @@ -78,7 +84,7 @@ class boss_darkmaster_gandling : public CreatureScript events.ScheduleEvent(EVENT_CURSE, 2000); events.ScheduleEvent(EVENT_SHADOW_PORTAL, 16000); - if (GameObject* gate = me->GetMap()->GetGameObject(instance->GetGuidData(GO_GATE_GANDLING))) + if (GameObject* gate = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_GATE_GANDLING))) gate->SetGoState(GO_STATE_READY); } @@ -131,7 +137,7 @@ class boss_darkmaster_gandling : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetScholomanceAI(creature); } }; @@ -294,13 +300,6 @@ class spell_shadow_portal_rooms : public SpellScriptLoader { PrepareSpellScript(spell_shadow_portal_rooms_SpellScript); - public: - spell_shadow_portal_rooms_SpellScript() - { - _instance = nullptr; - } - - private: bool Load() override { _instance = GetCaster()->GetInstanceScript(); @@ -353,7 +352,7 @@ class spell_shadow_portal_rooms : public SpellScriptLoader break; } - if (gate_to_close && (caster->GetMap()->GetId() == 289)) + if (gate_to_close && (caster->GetMapId() == 289)) { for (uint8 i = 0; i < 3; ++i) { @@ -374,7 +373,7 @@ class spell_shadow_portal_rooms : public SpellScriptLoader OnEffectHit += SpellEffectFn(spell_shadow_portal_rooms_SpellScript::HandleSendEvent, EFFECT_1, SPELL_EFFECT_SEND_EVENT); } - InstanceScript* _instance; + InstanceScript* _instance = nullptr; }; SpellScript* GetSpellScript() const override diff --git a/src/server/scripts/EasternKingdoms/Scholomance/boss_jandice_barov.cpp b/src/server/scripts/EasternKingdoms/Scholomance/boss_jandice_barov.cpp index f91612b050a..2faa4e419c6 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/boss_jandice_barov.cpp +++ b/src/server/scripts/EasternKingdoms/Scholomance/boss_jandice_barov.cpp @@ -16,6 +16,7 @@ */ #include "ScriptMgr.h" +#include "scholomance.h" #include "ScriptedCreature.h" enum Spells @@ -116,7 +117,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetScholomanceAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/Scholomance/boss_kirtonos_the_herald.cpp b/src/server/scripts/EasternKingdoms/Scholomance/boss_kirtonos_the_herald.cpp index 4207781273f..4b5290a43cd 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/boss_kirtonos_the_herald.cpp +++ b/src/server/scripts/EasternKingdoms/Scholomance/boss_kirtonos_the_herald.cpp @@ -16,11 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "scholomance.h" -#include "MoveSplineInit.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "MoveSplineInit.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "scholomance.h" +#include "ScriptedCreature.h" enum Says { @@ -98,9 +102,9 @@ class boss_kirtonos_the_herald : public CreatureScript void JustDied(Unit* /*killer*/) override { - if (GameObject* gate = me->GetMap()->GetGameObject(instance->GetGuidData(GO_GATE_KIRTONOS))) + if (GameObject* gate = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_GATE_KIRTONOS))) gate->SetGoState(GO_STATE_ACTIVE); - if (GameObject* brazier = me->GetMap()->GetGameObject(instance->GetGuidData(GO_BRAZIER_OF_THE_HERALD))) + if (GameObject* brazier = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_BRAZIER_OF_THE_HERALD))) { brazier->ResetDoorOrButton(); brazier->SetGoState(GO_STATE_READY); @@ -110,9 +114,9 @@ class boss_kirtonos_the_herald : public CreatureScript void EnterEvadeMode(EvadeReason /*why*/) override { - if (GameObject* gate = me->GetMap()->GetGameObject(instance->GetGuidData(GO_GATE_KIRTONOS))) + if (GameObject* gate = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_GATE_KIRTONOS))) gate->SetGoState(GO_STATE_ACTIVE); - if (GameObject* brazier = me->GetMap()->GetGameObject(instance->GetGuidData(GO_BRAZIER_OF_THE_HERALD))) + if (GameObject* brazier = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_BRAZIER_OF_THE_HERALD))) { brazier->ResetDoorOrButton(); brazier->SetGoState(GO_STATE_READY); @@ -160,13 +164,13 @@ class boss_kirtonos_the_herald : public CreatureScript events.ScheduleEvent(INTRO_3, 1000); break; case INTRO_3: - if (GameObject* gate = me->GetMap()->GetGameObject(instance->GetGuidData(GO_GATE_KIRTONOS))) + if (GameObject* gate = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_GATE_KIRTONOS))) gate->SetGoState(GO_STATE_READY); me->SetFacingTo(0.01745329f); events.ScheduleEvent(INTRO_4, 3000); break; case INTRO_4: - if (GameObject* brazier = me->GetMap()->GetGameObject(instance->GetGuidData(GO_BRAZIER_OF_THE_HERALD))) + if (GameObject* brazier = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(GO_BRAZIER_OF_THE_HERALD))) brazier->SetGoState(GO_STATE_READY); me->SetWalk(true); me->SetDisableGravity(false); @@ -256,7 +260,7 @@ class boss_kirtonos_the_herald : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetScholomanceAI(creature); } }; @@ -295,7 +299,7 @@ class go_brazier_of_the_herald : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return new go_brazier_of_the_heraldAI(go); + return GetScholomanceAI(go); } }; diff --git a/src/server/scripts/EasternKingdoms/Scholomance/boss_kormok.cpp b/src/server/scripts/EasternKingdoms/Scholomance/boss_kormok.cpp index 28f37fbbc05..7e915e7545b 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/boss_kormok.cpp +++ b/src/server/scripts/EasternKingdoms/Scholomance/boss_kormok.cpp @@ -16,9 +16,9 @@ */ #include "ScriptMgr.h" +#include "scholomance.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "scholomance.h" enum Spells { @@ -130,7 +130,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_kormokAI(creature); + return GetScholomanceAI(creature); } }; @@ -154,10 +154,7 @@ class spell_kormok_summon_bone_mages : SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - for (uint32 i = 0; i < 4; ++i) - if (!sSpellMgr->GetSpellInfo(SummonMageSpells[i])) - return false; - return true; + return ValidateSpellInfo(SummonMageSpells); } void HandleScript(SpellEffIndex effIndex) @@ -191,9 +188,7 @@ class spell_kormok_summon_bone_minions : SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_BONE_MINIONS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_BONE_MINIONS }); } void HandleScript(SpellEffIndex effIndex) diff --git a/src/server/scripts/EasternKingdoms/Scholomance/instance_scholomance.cpp b/src/server/scripts/EasternKingdoms/Scholomance/instance_scholomance.cpp index 8487d005b5d..c531ba43faa 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/instance_scholomance.cpp +++ b/src/server/scripts/EasternKingdoms/Scholomance/instance_scholomance.cpp @@ -16,7 +16,9 @@ */ #include "ScriptMgr.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" #include "Player.h" #include "scholomance.h" @@ -25,12 +27,7 @@ Position const GandlingLoc = { 180.7712f, -5.428603f, 75.57024f, 1.291544f }; class instance_scholomance : public InstanceMapScript { public: - instance_scholomance() : InstanceMapScript("instance_scholomance", 289) { } - - InstanceScript* GetInstanceScript(InstanceMap* map) const override - { - return new instance_scholomance_InstanceMapScript(map); - } + instance_scholomance() : InstanceMapScript(ScholomanceScriptName, 289) { } struct instance_scholomance_InstanceMapScript : public InstanceScript { @@ -176,6 +173,11 @@ class instance_scholomance : public InstanceMapScript ObjectGuid GateIlluciaGUID; ObjectGuid BrazierOfTheHeraldGUID; }; + + InstanceScript* GetInstanceScript(InstanceMap* map) const override + { + return new instance_scholomance_InstanceMapScript(map); + } }; void AddSC_instance_scholomance() diff --git a/src/server/scripts/EasternKingdoms/Scholomance/scholomance.h b/src/server/scripts/EasternKingdoms/Scholomance/scholomance.h index 843dbfea3d0..7b0cec3b0d0 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/scholomance.h +++ b/src/server/scripts/EasternKingdoms/Scholomance/scholomance.h @@ -18,6 +18,9 @@ #ifndef DEF_SCHOLOMANCE_H #define DEF_SCHOLOMANCE_H +#include "CreatureAIImpl.h" + +#define ScholomanceScriptName "instance_scholomance" #define DataHeader "SC" uint32 const EncounterCount = 8; @@ -53,4 +56,10 @@ enum SCGameobjectIds GO_BRAZIER_OF_THE_HERALD = 175564 }; +template +inline AI* GetScholomanceAI(T* obj) +{ + return GetInstanceAI(obj, ScholomanceScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/ShadowfangKeep/boss_apothecary_hummel.cpp b/src/server/scripts/EasternKingdoms/ShadowfangKeep/boss_apothecary_hummel.cpp index ecd4614476e..0668192d30c 100644 --- a/src/server/scripts/EasternKingdoms/ShadowfangKeep/boss_apothecary_hummel.cpp +++ b/src/server/scripts/EasternKingdoms/ShadowfangKeep/boss_apothecary_hummel.cpp @@ -16,15 +16,18 @@ */ #include "ScriptMgr.h" +#include "GridNotifiersImpl.h" +#include "Group.h" +#include "InstanceScript.h" +#include "LFGMgr.h" +#include "Map.h" +#include "MotionMaster.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "LFGMgr.h" -#include "Player.h" -#include "Group.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" #include "shadowfang_keep.h" -#include "GridNotifiersImpl.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum ApothecarySpells { @@ -273,7 +276,7 @@ class boss_apothecary_hummel : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShadowfangKeepAI(creature); } }; @@ -323,7 +326,7 @@ class npc_apothecary_frye : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShadowfangKeepAI(creature); } }; @@ -386,7 +389,7 @@ class npc_apothecary_baxter : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShadowfangKeepAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/ShadowfangKeep/instance_shadowfang_keep.cpp b/src/server/scripts/EasternKingdoms/ShadowfangKeep/instance_shadowfang_keep.cpp index 24c9c7a6437..c1747adf61f 100644 --- a/src/server/scripts/EasternKingdoms/ShadowfangKeep/instance_shadowfang_keep.cpp +++ b/src/server/scripts/EasternKingdoms/ShadowfangKeep/instance_shadowfang_keep.cpp @@ -23,9 +23,12 @@ SDComment: SDCategory: Shadowfang Keep EndScriptData */ -#include "ScriptedCreature.h" #include "ScriptMgr.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Log.h" +#include "Map.h" +#include "ScriptedCreature.h" #include "shadowfang_keep.h" #include "TemporarySummon.h" @@ -69,12 +72,7 @@ const Position SpawnLocation[] = class instance_shadowfang_keep : public InstanceMapScript { public: - instance_shadowfang_keep() : InstanceMapScript("instance_shadowfang_keep", 33) { } - - InstanceScript* GetInstanceScript(InstanceMap* map) const override - { - return new instance_shadowfang_keep_InstanceMapScript(map); - } + instance_shadowfang_keep() : InstanceMapScript(SFKScriptName, 33) { } struct instance_shadowfang_keep_InstanceMapScript : public InstanceScript { @@ -214,7 +212,7 @@ public: return str_data; } - void Load(const char* in) override + void Load(char const* in) override { if (!in) { @@ -279,6 +277,10 @@ public: } }; + InstanceScript* GetInstanceScript(InstanceMap* map) const override + { + return new instance_shadowfang_keep_InstanceMapScript(map); + } }; void AddSC_instance_shadowfang_keep() diff --git a/src/server/scripts/EasternKingdoms/ShadowfangKeep/shadowfang_keep.cpp b/src/server/scripts/EasternKingdoms/ShadowfangKeep/shadowfang_keep.cpp index 611891d4b13..708c0deef84 100644 --- a/src/server/scripts/EasternKingdoms/ShadowfangKeep/shadowfang_keep.cpp +++ b/src/server/scripts/EasternKingdoms/ShadowfangKeep/shadowfang_keep.cpp @@ -28,13 +28,13 @@ npc_shadowfang_prisoner EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "ScriptedEscortAI.h" -#include "shadowfang_keep.h" +#include "InstanceScript.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "shadowfang_keep.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" /*###### ## npc_shadowfang_prisoner @@ -67,17 +67,9 @@ class npc_shadowfang_prisoner : public CreatureScript public: npc_shadowfang_prisoner() : CreatureScript("npc_shadowfang_prisoner") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_shadowfang_prisonerAI : public npc_escortAI { - npc_shadowfang_prisonerAI(Creature* creature) : npc_escortAI(creature) - { - instance = creature->GetInstanceScript(); - } + npc_shadowfang_prisonerAI(Creature* creature) : npc_escortAI(creature), instance(creature->GetInstanceScript()) { } InstanceScript* instance; @@ -145,6 +137,10 @@ public: void JustEngagedWith(Unit* /*who*/) override { } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetShadowfangKeepAI(creature); + } }; class npc_arugal_voidwalker : public CreatureScript @@ -152,11 +148,6 @@ class npc_arugal_voidwalker : public CreatureScript public: npc_arugal_voidwalker() : CreatureScript("npc_arugal_voidwalker") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_arugal_voidwalkerAI : public ScriptedAI { npc_arugal_voidwalkerAI(Creature* creature) : ScriptedAI(creature) @@ -202,6 +193,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetShadowfangKeepAI(creature); + } }; enum ArugalSpells @@ -317,7 +312,7 @@ class boss_archmage_arugal : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShadowfangKeepAI(creature); } }; @@ -338,7 +333,7 @@ class spell_shadowfang_keep_haunting_spirits : public SpellScriptLoader void HandleDummyTick(AuraEffect const* aurEff) { - GetTarget()->CastSpell((Unit*)NULL, aurEff->GetAmount(), true); + GetTarget()->CastSpell((Unit*)nullptr, aurEff->GetAmount(), true); } void HandleUpdatePeriodic(AuraEffect* aurEff) diff --git a/src/server/scripts/EasternKingdoms/ShadowfangKeep/shadowfang_keep.h b/src/server/scripts/EasternKingdoms/ShadowfangKeep/shadowfang_keep.h index 76cbb1f7ae3..f3784fcbbbc 100644 --- a/src/server/scripts/EasternKingdoms/ShadowfangKeep/shadowfang_keep.h +++ b/src/server/scripts/EasternKingdoms/ShadowfangKeep/shadowfang_keep.h @@ -19,6 +19,9 @@ #ifndef DEF_SHADOWFANG_H #define DEF_SHADOWFANG_H +#include "CreatureAIImpl.h" + +#define SFKScriptName "instance_shadowfang_keep" #define DataHeader "SK" enum SKDataTypes @@ -31,4 +34,10 @@ enum SKDataTypes DATA_APOTHECARY_HUMMEL = 6 }; +template +inline AI* GetShadowfangKeepAI(T* obj) +{ + return GetInstanceAI(obj, SFKScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/Stratholme/boss_baron_rivendare.cpp b/src/server/scripts/EasternKingdoms/Stratholme/boss_baron_rivendare.cpp index 1aff5f8cfcb..cc420e5bcaa 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/boss_baron_rivendare.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/boss_baron_rivendare.cpp @@ -24,6 +24,7 @@ SDCategory: Stratholme EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "stratholme.h" @@ -66,11 +67,6 @@ class boss_baron_rivendare : public CreatureScript public: boss_baron_rivendare() : CreatureScript("boss_baron_rivendare") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_baron_rivendareAI : public ScriptedAI { boss_baron_rivendareAI(Creature* creature) : ScriptedAI(creature) @@ -176,6 +172,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetStratholmeAI(creature); + } }; void AddSC_boss_baron_rivendare() diff --git a/src/server/scripts/EasternKingdoms/Stratholme/boss_baroness_anastari.cpp b/src/server/scripts/EasternKingdoms/Stratholme/boss_baroness_anastari.cpp index 4d797738638..f10e466b4e0 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/boss_baroness_anastari.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/boss_baroness_anastari.cpp @@ -24,6 +24,7 @@ SDCategory: Stratholme EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "stratholme.h" @@ -40,11 +41,6 @@ class boss_baroness_anastari : public CreatureScript public: boss_baroness_anastari() : CreatureScript("boss_baroness_anastari") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_baroness_anastariAI : public ScriptedAI { boss_baroness_anastariAI(Creature* creature) : ScriptedAI(creature) @@ -118,6 +114,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetStratholmeAI(creature); + } }; void AddSC_boss_baroness_anastari() diff --git a/src/server/scripts/EasternKingdoms/Stratholme/boss_maleki_the_pallid.cpp b/src/server/scripts/EasternKingdoms/Stratholme/boss_maleki_the_pallid.cpp index 4ee45c20264..d59bf249f54 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/boss_maleki_the_pallid.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/boss_maleki_the_pallid.cpp @@ -24,6 +24,7 @@ SDCategory: Stratholme EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "stratholme.h" @@ -117,7 +118,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetStratholmeAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/Stratholme/boss_nerubenkan.cpp b/src/server/scripts/EasternKingdoms/Stratholme/boss_nerubenkan.cpp index 2ed56f52ff1..1330edde060 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/boss_nerubenkan.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/boss_nerubenkan.cpp @@ -24,6 +24,7 @@ SDCategory: Stratholme EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "stratholme.h" @@ -40,11 +41,6 @@ class boss_nerubenkan : public CreatureScript public: boss_nerubenkan() : CreatureScript("boss_nerubenkan") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_nerubenkanAI : public ScriptedAI { boss_nerubenkanAI(Creature* creature) : ScriptedAI(creature) @@ -127,6 +123,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetStratholmeAI(creature); + } }; void AddSC_boss_nerubenkan() diff --git a/src/server/scripts/EasternKingdoms/Stratholme/boss_order_of_silver_hand.cpp b/src/server/scripts/EasternKingdoms/Stratholme/boss_order_of_silver_hand.cpp index 5a5f2334d90..c98f60cda05 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/boss_order_of_silver_hand.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/boss_order_of_silver_hand.cpp @@ -24,6 +24,7 @@ SDCategory: Stratholme EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "stratholme.h" #include "Player.h" @@ -56,11 +57,6 @@ class boss_silver_hand_bosses : public CreatureScript public: boss_silver_hand_bosses() : CreatureScript("boss_silver_hand_bosses") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_silver_hand_bossesAI : public ScriptedAI { boss_silver_hand_bossesAI(Creature* creature) : ScriptedAI(creature) @@ -163,6 +159,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetStratholmeAI(creature); + } }; void AddSC_boss_order_of_silver_hand() diff --git a/src/server/scripts/EasternKingdoms/Stratholme/boss_postmaster_malown.cpp b/src/server/scripts/EasternKingdoms/Stratholme/boss_postmaster_malown.cpp index 38222441133..d5472d3749c 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/boss_postmaster_malown.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/boss_postmaster_malown.cpp @@ -131,7 +131,7 @@ class boss_postmaster_malown : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetStratholmeAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/Stratholme/boss_ramstein_the_gorger.cpp b/src/server/scripts/EasternKingdoms/Stratholme/boss_ramstein_the_gorger.cpp index 9ced8a87773..cf6f78ec719 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/boss_ramstein_the_gorger.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/boss_ramstein_the_gorger.cpp @@ -24,8 +24,10 @@ SDCategory: Stratholme EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "stratholme.h" +#include "TemporarySummon.h" enum Spells { @@ -43,11 +45,6 @@ class boss_ramstein_the_gorger : public CreatureScript public: boss_ramstein_the_gorger() : CreatureScript("boss_ramstein_the_gorger") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_ramstein_the_gorgerAI : public ScriptedAI { boss_ramstein_the_gorgerAI(Creature* creature) : ScriptedAI(creature) @@ -111,6 +108,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetStratholmeAI(creature); + } }; void AddSC_boss_ramstein_the_gorger() diff --git a/src/server/scripts/EasternKingdoms/Stratholme/instance_stratholme.cpp b/src/server/scripts/EasternKingdoms/Stratholme/instance_stratholme.cpp index e9b2a8d5982..67d3de21fd5 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/instance_stratholme.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/instance_stratholme.cpp @@ -53,7 +53,7 @@ EllipseBoundary const beforeScarletGate(Position(3671.158f, -3181.79f), 60.0f, 4 class instance_stratholme : public InstanceMapScript { public: - instance_stratholme() : InstanceMapScript("instance_stratholme", 329) { } + instance_stratholme() : InstanceMapScript(StratholmeScriptName, 329) { } struct instance_stratholme_InstanceMapScript : public InstanceScript { @@ -418,7 +418,7 @@ class instance_stratholme : public InstanceMapScript return saveStream.str(); } - void Load(const char* in) override + void Load(char const* in) override { if (!in) { diff --git a/src/server/scripts/EasternKingdoms/Stratholme/stratholme.cpp b/src/server/scripts/EasternKingdoms/Stratholme/stratholme.cpp index ea5b5cb6755..236ed024a7a 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/stratholme.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/stratholme.cpp @@ -68,7 +68,7 @@ public: if (Group* group = player->GetGroup()) { - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* pGroupie = itr->GetSource(); if (!pGroupie || !pGroupie->IsInMap(player)) @@ -149,7 +149,7 @@ public: void JustEngagedWith(Unit* /*who*/) override { } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (Tagged || spell->Id != SPELL_EGAN_BLASTER) return; @@ -240,7 +240,7 @@ public: void JustEngagedWith(Unit* /*who*/) override { } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (!Tagged && spell->Id == SPELL_EGAN_BLASTER) Tagged = true; diff --git a/src/server/scripts/EasternKingdoms/Stratholme/stratholme.h b/src/server/scripts/EasternKingdoms/Stratholme/stratholme.h index 7e66f5f5245..061fd0af701 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/stratholme.h +++ b/src/server/scripts/EasternKingdoms/Stratholme/stratholme.h @@ -19,6 +19,9 @@ #ifndef DEF_STRATHOLME_H #define DEF_STRATHOLME_H +#include "CreatureAIImpl.h" + +#define StratholmeScriptName "instance_stratholme" #define DataHeader "STR" enum STRDataTypes @@ -100,4 +103,10 @@ enum STRMisc MAX_ENCOUNTER = 6 }; +template +inline AI* GetStratholmeAI(T* obj) +{ + return GetInstanceAI(obj, StratholmeScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/SunkenTemple/instance_sunken_temple.cpp b/src/server/scripts/EasternKingdoms/SunkenTemple/instance_sunken_temple.cpp index eb84492cd47..73ad97c1449 100644 --- a/src/server/scripts/EasternKingdoms/SunkenTemple/instance_sunken_temple.cpp +++ b/src/server/scripts/EasternKingdoms/SunkenTemple/instance_sunken_temple.cpp @@ -24,7 +24,9 @@ SDCategory: Sunken Temple EndScriptData */ #include "ScriptMgr.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" #include "sunken_temple.h" enum Gameobject @@ -59,12 +61,7 @@ static Position const statuePositions[nStatues] class instance_sunken_temple : public InstanceMapScript { public: - instance_sunken_temple() : InstanceMapScript("instance_sunken_temple", 109) { } - - InstanceScript* GetInstanceScript(InstanceMap* map) const override - { - return new instance_sunken_temple_InstanceMapScript(map); - } + instance_sunken_temple() : InstanceMapScript(STScriptName, 109) { } struct instance_sunken_temple_InstanceMapScript : public InstanceScript { @@ -176,14 +173,14 @@ public: void UseStatue(GameObject* go) { - go->SummonGameObject(GO_ATALAI_LIGHT1, *go, G3D::Quat(), 0); + go->SummonGameObject(GO_ATALAI_LIGHT1, *go, QuaternionData(), 0); go->SetUInt32Value(GAMEOBJECT_FLAGS, 4); } void UseLastStatue(GameObject* go) { for (uint8 i = 0; i < nStatues; ++i) - go->SummonGameObject(GO_ATALAI_LIGHT2, statuePositions[i], G3D::Quat(), 0); + go->SummonGameObject(GO_ATALAI_LIGHT2, statuePositions[i], QuaternionData(), 0); go->SummonCreature(NPC_ATALALARION, atalalarianPos, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 7200); } @@ -202,6 +199,10 @@ public: } }; + InstanceScript* GetInstanceScript(InstanceMap* map) const override + { + return new instance_sunken_temple_InstanceMapScript(map); + } }; void AddSC_instance_sunken_temple() diff --git a/src/server/scripts/EasternKingdoms/SunkenTemple/sunken_temple.cpp b/src/server/scripts/EasternKingdoms/SunkenTemple/sunken_temple.cpp index 664b483aafe..562bae314ce 100644 --- a/src/server/scripts/EasternKingdoms/SunkenTemple/sunken_temple.cpp +++ b/src/server/scripts/EasternKingdoms/SunkenTemple/sunken_temple.cpp @@ -28,10 +28,12 @@ at_malfurion_Stormrage_trigger EndContentData */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "InstanceScript.h" +#include "Player.h" #include "ScriptedCreature.h" #include "sunken_temple.h" -#include "Player.h" -#include "GameObjectAI.h" /*##### # at_malfurion_Stormrage_trigger @@ -69,19 +71,20 @@ class go_atalai_statue : public GameObjectScript struct go_atalai_statueAI : public GameObjectAI { - go_atalai_statueAI(GameObject* go) : GameObjectAI(go) { } + go_atalai_statueAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* player) override { - if (InstanceScript* instance = player->GetInstanceScript()) - instance->SetData(EVENT_STATE, me->GetEntry()); + instance->SetData(EVENT_STATE, me->GetEntry()); return false; } }; GameObjectAI* GetAI(GameObject* go) const override { - return new go_atalai_statueAI(go); + return GetSunkenTempleAI(go); } }; diff --git a/src/server/scripts/EasternKingdoms/SunkenTemple/sunken_temple.h b/src/server/scripts/EasternKingdoms/SunkenTemple/sunken_temple.h index 02090247a07..8a2343326bb 100644 --- a/src/server/scripts/EasternKingdoms/SunkenTemple/sunken_temple.h +++ b/src/server/scripts/EasternKingdoms/SunkenTemple/sunken_temple.h @@ -19,19 +19,20 @@ #ifndef DEF_SUNKEN_TEMPLE_H #define DEF_SUNKEN_TEMPLE_H +#include "CreatureAIImpl.h" + +#define STScriptName "instance_sunken_temple" #define DataHeader "ST" -#define TROLLBOSS1_DEATH 1 -#define TROLLBOSS2_DEATH 2 -#define TROLLBOSS3_DEATH 3 -#define TROLLBOSS4_DEATH 4 -#define TROLLBOSS5_DEATH 5 -#define TROLLBOSS6_DEATH 6 -#define JAMMALAN_DEATH 7 -#define MORPHAZ_DEATH 8 -#define HAZZAS_DEATH 9 -#define ERANIKUS_DEATH 10 -#define ATALALARION_DEATH 11 //optional +enum STEvents +{ + EVENT_STATE = 1 +}; + +template +inline AI* GetSunkenTempleAI(T* obj) +{ + return GetInstanceAI(obj, STScriptName); +} -#define EVENT_STATE 1 #endif diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_brutallus.cpp b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_brutallus.cpp index eabb1d1c321..d22cee691f5 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_brutallus.cpp +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_brutallus.cpp @@ -23,6 +23,9 @@ SDComment: Find a way to start the intro, best code for the intro EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Log.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "sunwell_plateau.h" diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_eredar_twins.cpp b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_eredar_twins.cpp index fb3815f8eb9..ea243bc21fd 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_eredar_twins.cpp +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_eredar_twins.cpp @@ -16,6 +16,8 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "sunwell_plateau.h" #include "SpellInfo.h" @@ -160,7 +162,7 @@ public: me->RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); } - void SpellHitTarget(Unit* target, const SpellInfo* spell) override + void SpellHitTarget(Unit* target, SpellInfo const* spell) override { switch (spell->Id) { @@ -266,8 +268,8 @@ public: if (ShadowimageTimer <= diff) { - Unit* target = NULL; - Creature* temp = NULL; + Unit* target = nullptr; + Creature* temp = nullptr; for (uint8 i = 0; i<3; ++i) { target = SelectTarget(SELECT_TARGET_RANDOM, 0); @@ -436,7 +438,7 @@ public: me->RemoveFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); } - void SpellHitTarget(Unit* target, const SpellInfo* spell) override + void SpellHitTarget(Unit* target, SpellInfo const* spell) override { switch (spell->Id) { @@ -673,7 +675,7 @@ public: void JustEngagedWith(Unit* /*who*/) override { } - void SpellHitTarget(Unit* target, const SpellInfo* spell) override + void SpellHitTarget(Unit* target, SpellInfo const* spell) override { switch (spell->Id) { diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_felmyst.cpp b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_felmyst.cpp index 2d93bd45a15..af7b50bf9f6 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_felmyst.cpp +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_felmyst.cpp @@ -22,12 +22,14 @@ SDComment: EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "Cell.h" #include "CellImpl.h" +#include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" #include "sunwell_plateau.h" +#include "TemporarySummon.h" enum Yells { @@ -196,7 +198,7 @@ public: instance->SetBossState(DATA_FELMYST, DONE); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { // workaround for linked aura /*if (spell->Id == SPELL_VAPOR_FORCE) @@ -215,7 +217,7 @@ public: summon->CastSpell(summon, SPELL_FOG_CHARM, true); summon->CastSpell(summon, SPELL_FOG_CHARM2, true); } - me->DealDamage(caster, caster->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + me->DealDamage(caster, caster->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); } } @@ -360,7 +362,7 @@ public: } case 6: me->SetFacingTo(me->GetAngle(breathX, breathY)); - //DoTextEmote("takes a deep breath.", NULL); + //DoTextEmote("takes a deep breath.", nullptr); events.ScheduleEvent(EVENT_FLIGHT_SEQUENCE, 10000); break; case 7: @@ -515,11 +517,6 @@ class npc_felmyst_vapor : public CreatureScript public: npc_felmyst_vapor() : CreatureScript("npc_felmyst_vapor") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_felmyst_vaporAI(creature); - } - struct npc_felmyst_vaporAI : public ScriptedAI { npc_felmyst_vaporAI(Creature* creature) : ScriptedAI(creature) @@ -542,6 +539,11 @@ public: AttackStart(target); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetSunwellPlateauAI(creature); + } }; class npc_felmyst_trail : public CreatureScript @@ -549,11 +551,6 @@ class npc_felmyst_trail : public CreatureScript public: npc_felmyst_trail() : CreatureScript("npc_felmyst_trail") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_felmyst_trailAI(creature); - } - struct npc_felmyst_trailAI : public ScriptedAI { npc_felmyst_trailAI(Creature* creature) : ScriptedAI(creature) @@ -571,6 +568,11 @@ public: void UpdateAI(uint32 /*diff*/) override { } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetSunwellPlateauAI(creature); + } }; void AddSC_boss_felmyst() diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kalecgos.cpp b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kalecgos.cpp index 93e19ea87bf..2688243fa0c 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kalecgos.cpp +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kalecgos.cpp @@ -24,11 +24,18 @@ SDCategory: Sunwell_Plateau EndScriptData */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "InstanceScript.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "sunwell_plateau.h" -#include "Player.h" +#include "TemporarySummon.h" #include "WorldSession.h" -#include "GameObjectAI.h" enum Yells { @@ -430,11 +437,6 @@ class boss_kalec : public CreatureScript public: boss_kalec() : CreatureScript("boss_kalec") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_kalecAI : public ScriptedAI { InstanceScript* instance; @@ -530,6 +532,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetSunwellPlateauAI(creature); + } }; class kalecgos_teleporter : public GameObjectScript @@ -545,7 +552,7 @@ public: { #if MAX_PLAYERS_IN_SPECTRAL_REALM > 0 uint8 SpectralPlayers = 0; - Map::PlayerList const &PlayerList = go->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = go->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) { if (i->GetSource() && i->GetSource()->GetPositionZ() < DEMON_REALM_Z + 5) @@ -567,7 +574,7 @@ public: GameObjectAI* GetAI(GameObject* go) const override { - return new kalecgos_teleporterAI(go); + return GetSunwellPlateauAI(go); } }; @@ -576,11 +583,6 @@ class boss_sathrovarr : public CreatureScript public: boss_sathrovarr() : CreatureScript("boss_sathrovarr") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_sathrovarrAI : public ScriptedAI { boss_sathrovarrAI(Creature* creature) : ScriptedAI(creature) @@ -683,7 +685,7 @@ public: void TeleportAllPlayersBack() { - Map::PlayerList const &playerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& playerList = me->GetMap()->GetPlayers(); Position const& homePos = me->GetHomePosition(); for (Map::PlayerList::const_iterator itr = playerList.begin(); itr != playerList.end(); ++itr) { @@ -803,6 +805,11 @@ public: DoMeleeAttackIfReady(); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetSunwellPlateauAI(creature); + } }; void AddSC_boss_kalecgos() diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kiljaeden.cpp b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kiljaeden.cpp index 935a85b7a49..8b373a2d0cf 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kiljaeden.cpp +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kiljaeden.cpp @@ -25,11 +25,16 @@ EndScriptData */ /// @todo rewrite Armageddon #include "ScriptMgr.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "InstanceScript.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "sunwell_plateau.h" -#include -#include "Player.h" -#include "GameObjectAI.h" +#include "TemporarySummon.h" /*** Speech and sounds***/ enum Yells @@ -231,11 +236,6 @@ class boss_kalecgos_kj : public CreatureScript public: boss_kalecgos_kj() : CreatureScript("boss_kalecgos_kj") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_kalecgos_kjAI : public ScriptedAI { boss_kalecgos_kjAI(Creature* creature) : ScriptedAI(creature) @@ -281,7 +281,7 @@ public: return ObjectAccessor::GetGameObject(*me, instance->GetGuidData(DATA_ORB_OF_THE_BLUE_DRAGONFLIGHT_4)); } - return NULL; + return nullptr; } void ResetOrbs() @@ -360,6 +360,11 @@ public: } } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetSunwellPlateauAI(creature); + } }; class go_orb_of_the_blue_flight : public GameObjectScript @@ -369,13 +374,14 @@ class go_orb_of_the_blue_flight : public GameObjectScript struct go_orb_of_the_blue_flightAI : public GameObjectAI { - go_orb_of_the_blue_flightAI(GameObject* go) : GameObjectAI(go) { } + go_orb_of_the_blue_flightAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* player) override { if (me->GetFaction() == 35) { - InstanceScript* instance = me->GetInstanceScript(); player->SummonCreature(NPC_POWER_OF_THE_BLUE_DRAGONFLIGHT, player->GetPositionX(), player->GetPositionY(), player->GetPositionZ(), 0.0f, TEMPSUMMON_TIMED_DESPAWN, 121000); player->CastSpell(player, SPELL_VENGEANCE_OF_THE_BLUE_FLIGHT, false); me->SetFaction(FACTION_NONE); @@ -391,7 +397,7 @@ class go_orb_of_the_blue_flight : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return new go_orb_of_the_blue_flightAI(go); + return GetSunwellPlateauAI(go); } }; @@ -401,11 +407,6 @@ class npc_kiljaeden_controller : public CreatureScript public: npc_kiljaeden_controller() : CreatureScript("npc_kiljaeden_controller") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_kiljaeden_controllerAI : public ScriptedAI { npc_kiljaeden_controllerAI(Creature* creature) : ScriptedAI(creature), summons(me) @@ -500,6 +501,11 @@ public: } } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetSunwellPlateauAI(creature); + } }; //AI for Kil'jaeden @@ -747,7 +753,7 @@ public: case TIMER_LEGION_LIGHTNING: if (!me->IsNonMeleeSpellCast(false)) { - Unit* pRandomPlayer = NULL; + Unit* pRandomPlayer = nullptr; me->RemoveAurasDueToSpell(SPELL_SOUL_FLAY); for (uint8 z = 0; z < 6; ++z) @@ -842,7 +848,7 @@ public: TimerIsDeactivated[TIMER_ORBS_EMPOWER] = true; break; case TIMER_ARMAGEDDON: //Phase 4 - Unit* target = NULL; + Unit* target = nullptr; for (uint8 z = 0; z < 6; ++z) { target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true); @@ -990,7 +996,7 @@ public: { if (Creature* pPortal = DoSpawnCreature(NPC_FELFIRE_PORTAL, 0, 0, 0, 0, TEMPSUMMON_TIMED_DESPAWN, 20000)) { - ThreatContainer::StorageType const &threatlist = me->getThreatManager().getThreatList(); + ThreatContainer::StorageType const& threatlist = me->getThreatManager().getThreatList(); for (ThreatContainer::StorageType::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) { Unit* unit = ObjectAccessor::GetUnit(*me, (*itr)->getUnitGuid()); @@ -1017,11 +1023,6 @@ class npc_felfire_portal : public CreatureScript public: npc_felfire_portal() : CreatureScript("npc_felfire_portal") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_felfire_portalAI(creature); - } - struct npc_felfire_portalAI : public ScriptedAI { npc_felfire_portalAI(Creature* creature) : ScriptedAI(creature) @@ -1062,6 +1063,11 @@ public: } else uiSpawnFiendTimer -= diff; } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetSunwellPlateauAI(creature); + } }; //AI for Felfire Fiend @@ -1070,11 +1076,6 @@ class npc_volatile_felfire_fiend : public CreatureScript public: npc_volatile_felfire_fiend() : CreatureScript("npc_volatile_felfire_fiend") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_volatile_felfire_fiendAI(creature); - } - struct npc_volatile_felfire_fiendAI : public ScriptedAI { npc_volatile_felfire_fiendAI(Creature* creature) : ScriptedAI(creature) @@ -1127,6 +1128,11 @@ public: } } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetSunwellPlateauAI(creature); + } }; //AI for Armageddon target @@ -1135,11 +1141,6 @@ class npc_armageddon : public CreatureScript public: npc_armageddon() : CreatureScript("npc_armageddon") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_armageddonAI(creature); - } - struct npc_armageddonAI : public ScriptedAI { npc_armageddonAI(Creature* creature) : ScriptedAI(creature) @@ -1190,6 +1191,11 @@ public: } else uiTimer -=diff; } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetSunwellPlateauAI(creature); + } }; //AI for Shield Orbs @@ -1198,11 +1204,6 @@ class npc_shield_orb : public CreatureScript public: npc_shield_orb() : CreatureScript("npc_shield_orb") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_shield_orbAI : public ScriptedAI { npc_shield_orbAI(Creature* creature) : ScriptedAI(creature) @@ -1285,6 +1286,11 @@ public: bPointReached = true; } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetSunwellPlateauAI(creature); + } }; //AI for Sinister Reflection @@ -1293,11 +1299,6 @@ class npc_sinster_reflection : public CreatureScript public: npc_sinster_reflection() : CreatureScript("npc_sinster_reflection") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_sinster_reflectionAI(creature); - } - struct npc_sinster_reflectionAI : public ScriptedAI { npc_sinster_reflectionAI(Creature* creature) : ScriptedAI(creature) @@ -1463,6 +1464,11 @@ public: uiTimer[i] -= diff; } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetSunwellPlateauAI(creature); + } }; void AddSC_boss_kiljaeden() diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_muru.cpp b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_muru.cpp index e2543484e09..ebece9d4bd7 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_muru.cpp +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_muru.cpp @@ -16,10 +16,12 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "sunwell_plateau.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "sunwell_plateau.h" enum Spells { @@ -581,10 +583,7 @@ class spell_summon_blood_elves_script : SpellScriptLoader 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; + return ValidateSpellInfo(SummonBloodElvesSpells); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -616,10 +615,7 @@ class spell_muru_darkness : SpellScriptLoader 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; + return ValidateSpellInfo(SummonDarkFiendSpells); } void HandleAfterCast() diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/instance_sunwell_plateau.cpp b/src/server/scripts/EasternKingdoms/SunwellPlateau/instance_sunwell_plateau.cpp index 89a34b16080..4ff586020e1 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/instance_sunwell_plateau.cpp +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/instance_sunwell_plateau.cpp @@ -16,7 +16,11 @@ */ #include "ScriptMgr.h" +#include "Creature.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Log.h" +#include "Map.h" #include "Player.h" #include "sunwell_plateau.h" @@ -60,7 +64,6 @@ class instance_sunwell_plateau : public InstanceMapScript Player const* GetPlayerInMap() const { Map::PlayerList const& players = instance->GetPlayers(); - if (!players.isEmpty()) { for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) @@ -73,7 +76,7 @@ class instance_sunwell_plateau : public InstanceMapScript else TC_LOG_DEBUG("scripts", "Instance Sunwell Plateau: GetPlayerInMap, but PlayerList is empty!"); - return NULL; + return nullptr; } void OnCreatureCreate(Creature* creature) override diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/sunwell_plateau.h b/src/server/scripts/EasternKingdoms/SunwellPlateau/sunwell_plateau.h index 886bc196fb2..3ae80beae41 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/sunwell_plateau.h +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/sunwell_plateau.h @@ -18,6 +18,8 @@ #ifndef SUNWELL_PLATEAU_H #define SUNWELL_PLATEAU_H +#include "CreatureAIImpl.h" + #define SunwellPlateauScriptName "instance_sunwell_plateau" #define DataHeader "SWP" @@ -112,10 +114,10 @@ enum SWPGameObjectIds GO_MURUS_GATE_2 = 188118 }; -template -AI* GetSunwellPlateauAI(Creature* creature) +template +inline AI* GetSunwellPlateauAI(T* obj) { - return GetInstanceAI(creature, SunwellPlateauScriptName); + return GetInstanceAI(obj, SunwellPlateauScriptName); } #endif // SUNWELL_PLATEAU_H diff --git a/src/server/scripts/EasternKingdoms/Uldaman/boss_archaedas.cpp b/src/server/scripts/EasternKingdoms/Uldaman/boss_archaedas.cpp index a066f296520..133ed044a47 100644 --- a/src/server/scripts/EasternKingdoms/Uldaman/boss_archaedas.cpp +++ b/src/server/scripts/EasternKingdoms/Uldaman/boss_archaedas.cpp @@ -27,10 +27,14 @@ On his death the vault door opens. EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "uldaman.h" -#include "Player.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "uldaman.h" enum Says { @@ -58,11 +62,7 @@ enum Spells class boss_archaedas : public CreatureScript { public: - - boss_archaedas() - : CreatureScript("boss_archaedas") - { - } + boss_archaedas() : CreatureScript("boss_archaedas") { } struct boss_archaedasAI : public ScriptedAI { @@ -125,10 +125,10 @@ class boss_archaedas : public CreatureScript me->SetControlled(false, UNIT_STATE_ROOT); } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { // Being woken up from the altar, start the awaken sequence - if (spell == sSpellMgr->GetSpellInfo(SPELL_ARCHAEDAS_AWAKEN)) + if (spell->Id == SPELL_ARCHAEDAS_AWAKEN) { Talk(SAY_AGGRO); iAwakenTimer = 4000; @@ -212,7 +212,7 @@ class boss_archaedas : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetUldamanAI(creature); } }; @@ -226,11 +226,7 @@ EndScriptData */ class npc_archaedas_minions : public CreatureScript { public: - - npc_archaedas_minions() - : CreatureScript("npc_archaedas_minions") - { - } + npc_archaedas_minions() : CreatureScript("npc_archaedas_minions") { } struct npc_archaedas_minionsAI : public ScriptedAI { @@ -276,10 +272,10 @@ class npc_archaedas_minions : public CreatureScript bAmIAwake = true; } - void SpellHit(Unit * /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit * /*caster*/, SpellInfo const* spell) override { // time to wake up, start animation - if (spell == sSpellMgr->GetSpellInfo(SPELL_ARCHAEDAS_AWAKEN)) + if (spell->Id == SPELL_ARCHAEDAS_AWAKEN) { iAwakenTimer = 5000; bWakingUp = true; @@ -318,7 +314,7 @@ class npc_archaedas_minions : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetUldamanAI(creature); } }; @@ -332,11 +328,7 @@ EndScriptData */ class npc_stonekeepers : public CreatureScript { public: - - npc_stonekeepers() - : CreatureScript("npc_stonekeepers") - { - } + npc_stonekeepers() : CreatureScript("npc_stonekeepers") { } struct npc_stonekeepersAI : public ScriptedAI { @@ -381,7 +373,7 @@ class npc_stonekeepers : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetUldamanAI(creature); } }; @@ -399,14 +391,12 @@ class go_altar_of_archaedas : public GameObjectScript struct go_altar_of_archaedasAI : public GameObjectAI { - go_altar_of_archaedasAI(GameObject* go) : GameObjectAI(go) { } + go_altar_of_archaedasAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* player) override { - InstanceScript* instance = player->GetInstanceScript(); - if (!instance) - return false; - player->CastSpell(player, SPELL_BOSS_OBJECT_VISUAL, false); instance->SetGuidData(0, player->GetGUID()); // activate archaedas @@ -416,7 +406,7 @@ class go_altar_of_archaedas : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return new go_altar_of_archaedasAI(go); + return GetUldamanAI(go); } }; diff --git a/src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp b/src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp index 4920b7fb29d..1226c8911e4 100644 --- a/src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp +++ b/src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp @@ -24,8 +24,13 @@ SDCategory: Uldaman EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" #include "uldaman.h" enum Spells @@ -51,7 +56,7 @@ const Position IronayaPoint = { -231.228f, 246.6135f, -49.01617f, 0.0f }; class instance_uldaman : public InstanceMapScript { public: - instance_uldaman() : InstanceMapScript("instance_uldaman", 70) { } + instance_uldaman() : InstanceMapScript(UldamanScriptName, 70) { } struct instance_uldaman_InstanceMapScript : public InstanceScript { @@ -418,7 +423,7 @@ class instance_uldaman : public InstanceMapScript return str_data; } - void Load(const char* in) override + void Load(char const* in) override { if (!in) { diff --git a/src/server/scripts/EasternKingdoms/Uldaman/uldaman.cpp b/src/server/scripts/EasternKingdoms/Uldaman/uldaman.cpp index fc9dbba2766..0385da816c8 100644 --- a/src/server/scripts/EasternKingdoms/Uldaman/uldaman.cpp +++ b/src/server/scripts/EasternKingdoms/Uldaman/uldaman.cpp @@ -30,10 +30,12 @@ at_map_chamber EndContentData */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "InstanceScript.h" +#include "Player.h" #include "ScriptedCreature.h" #include "uldaman.h" -#include "Player.h" -#include "GameObjectAI.h" /*###### ## npc_jadespine_basilisk @@ -48,10 +50,7 @@ class npc_jadespine_basilisk : public CreatureScript { public: - npc_jadespine_basilisk() - : CreatureScript("npc_jadespine_basilisk") - { - } + npc_jadespine_basilisk() : CreatureScript("npc_jadespine_basilisk") { } struct npc_jadespine_basiliskAI : public ScriptedAI { @@ -107,7 +106,7 @@ class npc_jadespine_basilisk : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_jadespine_basiliskAI(creature); + return GetUldamanAI(creature); } }; @@ -122,20 +121,20 @@ class go_keystone_chamber : public GameObjectScript struct go_keystone_chamberAI : public GameObjectAI { - go_keystone_chamberAI(GameObject* go) : GameObjectAI(go) { } + go_keystone_chamberAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* /*player*/) override { - if (InstanceScript* instance = me->GetInstanceScript()) - instance->SetData(DATA_IRONAYA_SEAL, IN_PROGRESS); //door animation and save state. - + instance->SetData(DATA_IRONAYA_SEAL, IN_PROGRESS); //door animation and save state. return false; } }; GameObjectAI* GetAI(GameObject* go) const override { - return new go_keystone_chamberAI(go); + return GetUldamanAI(go); } }; @@ -152,10 +151,7 @@ class AreaTrigger_at_map_chamber : public AreaTriggerScript { public: - AreaTrigger_at_map_chamber() - : AreaTriggerScript("at_map_chamber") - { - } + AreaTrigger_at_map_chamber() : AreaTriggerScript("at_map_chamber") { } bool OnTrigger(Player* player, AreaTriggerEntry const* /*trigger*/) override { diff --git a/src/server/scripts/EasternKingdoms/Uldaman/uldaman.h b/src/server/scripts/EasternKingdoms/Uldaman/uldaman.h index 8e44d51c55b..db28cc4c485 100644 --- a/src/server/scripts/EasternKingdoms/Uldaman/uldaman.h +++ b/src/server/scripts/EasternKingdoms/Uldaman/uldaman.h @@ -19,6 +19,9 @@ #ifndef DEF_ULDAMAN_H #define DEF_ULDAMAN_H +#include "CreatureAIImpl.h" + +#define UldamanScriptName "instance_uldaman" #define DataHeader "UD" #define MAX_ENCOUNTER 3 @@ -42,4 +45,10 @@ enum UDGameObjectIds GO_KEYSTONE = 124371, }; +template +inline AI* GetUldamanAI(T* obj) +{ + return GetInstanceAI(obj, UldamanScriptName); +} + #endif diff --git a/src/server/scripts/EasternKingdoms/ZulAman/boss_akilzon.cpp b/src/server/scripts/EasternKingdoms/ZulAman/boss_akilzon.cpp index b29d4eea4c8..49c3b915f39 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/boss_akilzon.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/boss_akilzon.cpp @@ -25,13 +25,15 @@ SQLUpdate: EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "Cell.h" #include "CellImpl.h" -#include "zulaman.h" +#include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" #include "Weather.h" +#include "zulaman.h" enum Spells { @@ -170,7 +172,7 @@ class boss_akilzon : public CreatureScript if (Unit* target = (*i)) { if (Cloud && !Cloud->IsWithinDist(target, 6, false)) - Cloud->CastCustomSpell(target, SPELL_ZAP, &bp0, NULL, NULL, true, 0, 0, me->GetGUID()); + Cloud->CastCustomSpell(target, SPELL_ZAP, &bp0, nullptr, nullptr, true, 0, 0, me->GetGUID()); } } @@ -189,7 +191,7 @@ class boss_akilzon : public CreatureScript trigger->SetHealth(100000); trigger->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); if (Cloud) - Cloud->CastCustomSpell(trigger, /*43661*/SPELL_ZAP, &bp0, NULL, NULL, true, 0, 0, Cloud->GetGUID()); + Cloud->CastCustomSpell(trigger, /*43661*/SPELL_ZAP, &bp0, nullptr, nullptr, true, 0, 0, Cloud->GetGUID()); } } } @@ -203,7 +205,7 @@ class boss_akilzon : public CreatureScript me->InterruptNonMeleeSpells(false); CloudGUID.Clear(); if (Cloud) - Cloud->DealDamage(Cloud, Cloud->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + Cloud->DealDamage(Cloud, Cloud->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); SetWeather(WEATHER_STATE_FINE, 0.0f); isRaining = false; } @@ -364,7 +366,7 @@ class boss_akilzon : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulAmanAI(creature); } }; @@ -454,7 +456,7 @@ class npc_akilzon_eagle : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_akilzon_eagleAI(creature); + return GetZulAmanAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/ZulAman/boss_daakara.cpp b/src/server/scripts/EasternKingdoms/ZulAman/boss_daakara.cpp index 1a391de8a18..b214c495861 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/boss_daakara.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/boss_daakara.cpp @@ -47,7 +47,6 @@ enum Events class boss_daakara : public CreatureScript { public: - boss_daakara() : CreatureScript("boss_daakara") { } struct boss_daakaraAI : public BossAI diff --git a/src/server/scripts/EasternKingdoms/ZulAman/boss_halazzi.cpp b/src/server/scripts/EasternKingdoms/ZulAman/boss_halazzi.cpp index 64b614214f6..543e6045bec 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/boss_halazzi.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/boss_halazzi.cpp @@ -17,9 +17,12 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "zulaman.h" #include "SpellInfo.h" +#include "zulaman.h" enum Spells { @@ -139,7 +142,7 @@ class boss_halazzi : public CreatureScript damage = 0; } - void SpellHit(Unit*, const SpellInfo* spell) override + void SpellHit(Unit*, SpellInfo const* spell) override { if (spell->Id == SPELL_TRANSFORM_SPLIT2) EnterPhase(PHASE_HUMAN); @@ -320,7 +323,7 @@ class boss_halazzi : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulAmanAI(creature); } }; @@ -389,7 +392,7 @@ class npc_halazzi_lynx : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_halazzi_lynxAI(creature); + return GetZulAmanAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/ZulAman/boss_hexlord.cpp b/src/server/scripts/EasternKingdoms/ZulAman/boss_hexlord.cpp index 708fdec67c5..7872b8e9ae3 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/boss_hexlord.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/boss_hexlord.cpp @@ -24,9 +24,13 @@ SDCategory: Zul'Aman EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "TemporarySummon.h" #include "zulaman.h" enum Yells @@ -221,10 +225,7 @@ class boss_hexlord_malacrass : public CreatureScript { public: - boss_hexlord_malacrass() - : CreatureScript("boss_hexlord_malacrass") - { - } + boss_hexlord_malacrass() : CreatureScript("boss_hexlord_malacrass") { } struct boss_hex_lord_malacrassAI : public ScriptedAI { @@ -315,7 +316,7 @@ class boss_hexlord_malacrass : public CreatureScript { Unit* Temp = ObjectAccessor::GetUnit(*me, AddGUID[i]); if (Temp && Temp->IsAlive()) - Temp->DealDamage(Temp, Temp->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + Temp->DealDamage(Temp, Temp->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); } } @@ -443,7 +444,7 @@ class boss_hexlord_malacrass : public CreatureScript void UseAbility() { uint8 random = urand(0, 2); - Unit* target = NULL; + Unit* target = nullptr; switch (PlayerAbility[PlayerClass][random].target) { case ABILITY_TARGET_SELF: @@ -474,18 +475,14 @@ class boss_hexlord_malacrass : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulAmanAI(creature); } }; class boss_alyson_antille : public CreatureScript { public: - - boss_alyson_antille() - : CreatureScript("boss_alyson_antille") - { - } + boss_alyson_antille() : CreatureScript("boss_alyson_antille") { } struct boss_alyson_antilleAI : public boss_hexlord_addAI { @@ -579,14 +576,13 @@ class boss_alyson_antille : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulAmanAI(creature); } }; class boss_gazakroth : public CreatureScript { public: - boss_gazakroth() : CreatureScript("boss_gazakroth") { } struct boss_gazakrothAI : public boss_hexlord_addAI @@ -632,7 +628,7 @@ class boss_gazakroth : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulAmanAI(creature); } }; @@ -640,10 +636,7 @@ class boss_darkheart : public CreatureScript { public: - boss_darkheart() - : CreatureScript("boss_darkheart") - { - } + boss_darkheart() : CreatureScript("boss_darkheart") { } struct boss_darkheartAI : public boss_hexlord_addAI { @@ -681,7 +674,7 @@ class boss_darkheart : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulAmanAI(creature); } }; @@ -689,11 +682,7 @@ class boss_darkheart : public CreatureScript class boss_slither : public CreatureScript { public: - - boss_slither() - : CreatureScript("boss_slither") - { - } + boss_slither() : CreatureScript("boss_slither") { } struct boss_slitherAI : public boss_hexlord_addAI { @@ -748,7 +737,7 @@ class boss_slither : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulAmanAI(creature); } }; @@ -763,15 +752,13 @@ class spell_hexlord_unstable_affliction : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WL_UNSTABLE_AFFL_DISPEL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WL_UNSTABLE_AFFL_DISPEL }); } void HandleDispel(DispelInfo* dispelInfo) { if (Unit* caster = GetCaster()) - caster->CastSpell(dispelInfo->GetDispeller(), SPELL_WL_UNSTABLE_AFFL_DISPEL, true, NULL, GetEffect(EFFECT_0)); + caster->CastSpell(dispelInfo->GetDispeller(), SPELL_WL_UNSTABLE_AFFL_DISPEL, true, nullptr, GetEffect(EFFECT_0)); } void Register() override diff --git a/src/server/scripts/EasternKingdoms/ZulAman/boss_janalai.cpp b/src/server/scripts/EasternKingdoms/ZulAman/boss_janalai.cpp index dab70287d7a..f1b02fedb1e 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/boss_janalai.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/boss_janalai.cpp @@ -24,10 +24,14 @@ SDCategory: Zul'Aman EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "zulaman.h" -#include "GridNotifiers.h" #include "CellImpl.h" +#include "GridNotifiers.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" +#include "zulaman.h" enum Yells { @@ -112,10 +116,7 @@ class boss_janalai : public CreatureScript { public: - boss_janalai() - : CreatureScript("boss_janalai") - { - } + boss_janalai() : CreatureScript("boss_janalai") { } struct boss_janalaiAI : public ScriptedAI { @@ -202,7 +203,7 @@ class boss_janalai : public CreatureScript void FireWall() { uint8 WallNum; - Creature* wall = NULL; + Creature* wall = nullptr; for (uint8 i = 0; i < 4; ++i) { if (i == 0 || i == 2) @@ -426,18 +427,14 @@ class boss_janalai : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulAmanAI(creature); } }; class npc_janalai_firebomb : public CreatureScript { public: - - npc_janalai_firebomb() - : CreatureScript("npc_janalai_firebomb") - { - } + npc_janalai_firebomb() : CreatureScript("npc_janalai_firebomb") { } struct npc_janalai_firebombAI : public ScriptedAI { @@ -445,7 +442,7 @@ class npc_janalai_firebomb : public CreatureScript void Reset() override { } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_FIRE_BOMB_THROW) DoCast(me, SPELL_FIRE_BOMB_DUMMY, true); @@ -463,18 +460,14 @@ class npc_janalai_firebomb : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_janalai_firebombAI(creature); + return GetZulAmanAI(creature); } }; class npc_janalai_hatcher : public CreatureScript { public: - - npc_janalai_hatcher() - : CreatureScript("npc_janalai_hatcher") - { - } + npc_janalai_hatcher() : CreatureScript("npc_janalai_hatcher") { } struct npc_janalai_hatcherAI : public ScriptedAI { @@ -594,18 +587,14 @@ class npc_janalai_hatcher : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulAmanAI(creature); } }; class npc_janalai_hatchling : public CreatureScript { public: - - npc_janalai_hatchling() - : CreatureScript("npc_janalai_hatchling") - { - } + npc_janalai_hatchling() : CreatureScript("npc_janalai_hatchling") { } struct npc_janalai_hatchlingAI : public ScriptedAI { @@ -659,7 +648,7 @@ class npc_janalai_hatchling : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulAmanAI(creature); } }; @@ -668,11 +657,6 @@ class npc_janalai_egg : public CreatureScript public: npc_janalai_egg(): CreatureScript("npc_janalai_egg") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_janalai_eggAI(creature); - } - struct npc_janalai_eggAI : public ScriptedAI { npc_janalai_eggAI(Creature* creature) : ScriptedAI(creature){ } @@ -681,7 +665,7 @@ public: void UpdateAI(uint32 /*diff*/) override { } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_HATCH_EGG) { @@ -690,6 +674,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetZulAmanAI(creature); + } }; void AddSC_boss_janalai() diff --git a/src/server/scripts/EasternKingdoms/ZulAman/boss_nalorakk.cpp b/src/server/scripts/EasternKingdoms/ZulAman/boss_nalorakk.cpp index 85cb72a3e17..22c80fef2bf 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/boss_nalorakk.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/boss_nalorakk.cpp @@ -24,11 +24,12 @@ SDCategory: Zul'Aman EndScriptData */ #include "ScriptMgr.h" +#include "CellImpl.h" +#include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "ScriptedCreature.h" #include "zulaman.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "CellImpl.h" enum Yells { @@ -432,7 +433,7 @@ class boss_nalorakk : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulAmanAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/ZulAman/instance_zulaman.cpp b/src/server/scripts/EasternKingdoms/ZulAman/instance_zulaman.cpp index 71de631ee54..0e2706cf2b1 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/instance_zulaman.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/instance_zulaman.cpp @@ -16,7 +16,9 @@ */ #include "ScriptMgr.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" #include "ScriptedCreature.h" #include "zulaman.h" @@ -47,32 +49,32 @@ public: { switch (creature->GetEntry()) { - case NPC_AKILZON: - AkilzonGUID = creature->GetGUID(); - break; - case NPC_NALORAKK: - NalorakkGUID = creature->GetGUID(); - break; - case NPC_JANALAI: - JanalaiGUID = creature->GetGUID(); - break; - case NPC_HALAZZI: - HalazziGUID = creature->GetGUID(); - break; - case NPC_HEXLORD: - HexLordMalacrassGUID = creature->GetGUID(); - break; - case NPC_DAAKARA: - DaakaraGUID = creature->GetGUID(); - break; - case NPC_VOLJIN: - VoljinGUID = creature->GetGUID(); - break; - case NPC_HEXLORD_TRIGGER: - HexLordTriggerGUID = creature->GetGUID(); - break; - default: - break; + case NPC_AKILZON: + AkilzonGUID = creature->GetGUID(); + break; + case NPC_NALORAKK: + NalorakkGUID = creature->GetGUID(); + break; + case NPC_JANALAI: + JanalaiGUID = creature->GetGUID(); + break; + case NPC_HALAZZI: + HalazziGUID = creature->GetGUID(); + break; + case NPC_HEXLORD: + HexLordMalacrassGUID = creature->GetGUID(); + break; + case NPC_DAAKARA: + DaakaraGUID = creature->GetGUID(); + break; + case NPC_VOLJIN: + VoljinGUID = creature->GetGUID(); + break; + case NPC_HEXLORD_TRIGGER: + HexLordTriggerGUID = creature->GetGUID(); + break; + default: + break; } } @@ -80,17 +82,17 @@ public: { switch (go->GetEntry()) { - case GO_STRANGE_GONG: - StrangeGongGUID = go->GetGUID(); - break; - case GO_MASSIVE_GATE: - MasiveGateGUID = go->GetGUID(); - AddDoor(go, true); - if (ZulAmanState != NOT_STARTED) - go->SetGoState(GO_STATE_ACTIVE); - break; - default: - break; + case GO_STRANGE_GONG: + StrangeGongGUID = go->GetGUID(); + break; + case GO_MASSIVE_GATE: + MasiveGateGUID = go->GetGUID(); + AddDoor(go, true); + if (ZulAmanState != NOT_STARTED) + go->SetGoState(GO_STATE_ACTIVE); + break; + default: + break; } } @@ -98,11 +100,11 @@ public: { switch (go->GetEntry()) { - case GO_MASSIVE_GATE: - AddDoor(go, false); - break; - default: - break; + case GO_MASSIVE_GATE: + AddDoor(go, false); + break; + default: + break; } } @@ -110,26 +112,26 @@ public: { switch (type) { - case DATA_AKILZONEVENT: - return AkilzonGUID; - case DATA_NALORAKKEVENT: - return NalorakkGUID; - case DATA_JANALAIEVENT: - return JanalaiGUID; - case DATA_HALAZZIEVENT: - return HalazziGUID; - case DATA_HEXLORDEVENT: - return HexLordMalacrassGUID; - case DATA_DAAKARAEVENT: - return DaakaraGUID; - case DATA_HEXLORD_TRIGGER: - return HexLordTriggerGUID; - case DATA_STRANGE_GONG: - return StrangeGongGUID; - case DATA_MASSIVE_GATE: - return MasiveGateGUID; - default: - break; + case DATA_AKILZONEVENT: + return AkilzonGUID; + case DATA_NALORAKKEVENT: + return NalorakkGUID; + case DATA_JANALAIEVENT: + return JanalaiGUID; + case DATA_HALAZZIEVENT: + return HalazziGUID; + case DATA_HEXLORDEVENT: + return HexLordMalacrassGUID; + case DATA_DAAKARAEVENT: + return DaakaraGUID; + case DATA_HEXLORD_TRIGGER: + return HexLordTriggerGUID; + case DATA_STRANGE_GONG: + return StrangeGongGUID; + case DATA_MASSIVE_GATE: + return MasiveGateGUID; + default: + break; } return ObjectGuid::Empty; @@ -139,21 +141,21 @@ public: { switch (type) { - case DATA_ZULAMAN_STATE: - { - if (data == IN_PROGRESS) + case DATA_ZULAMAN_STATE: { - DoUpdateWorldState(WORLD_STATE_ZULAMAN_TIMER_ENABLED, 1); - DoUpdateWorldState(WORLD_STATE_ZULAMAN_TIMER, 15); - events.ScheduleEvent(EVENT_UPDATE_ZULAMAN_TIMER, 60000); - SpeedRunTimer = 15; - ZulAmanState = data; - SaveToDB(); + if (data == IN_PROGRESS) + { + DoUpdateWorldState(WORLD_STATE_ZULAMAN_TIMER_ENABLED, 1); + DoUpdateWorldState(WORLD_STATE_ZULAMAN_TIMER, 15); + events.ScheduleEvent(EVENT_UPDATE_ZULAMAN_TIMER, 60000); + SpeedRunTimer = 15; + ZulAmanState = data; + SaveToDB(); + } + break; } - break; - } - default: - break; + default: + break; } } @@ -161,10 +163,10 @@ public: { switch (type) { - case DATA_ZULAMAN_STATE: - return ZulAmanState; - default: - break; + case DATA_ZULAMAN_STATE: + return ZulAmanState; + default: + break; } return 0; @@ -197,18 +199,18 @@ public: switch (type) { - case DATA_AKILZONEVENT: - break; - case DATA_NALORAKKEVENT: - break; - case DATA_JANALAIEVENT: - break; - case DATA_HALAZZIEVENT: - case DATA_HEXLORDEVENT: - case DATA_DAAKARAEVENT: - break; - default: - break; + case DATA_AKILZONEVENT: + break; + case DATA_NALORAKKEVENT: + break; + case DATA_JANALAIEVENT: + break; + case DATA_HALAZZIEVENT: + case DATA_HEXLORDEVENT: + case DATA_DAAKARAEVENT: + break; + default: + break; } return true; @@ -218,15 +220,15 @@ public: { switch (eventId) { - case EVENT_START_ZULAMAN: - if (Creature* voljin = instance->GetCreature(VoljinGUID)) - { - if (voljin->IsAIEnabled) - voljin->AI()->DoAction(ACTION_START_ZULAMAN); - } - break; - default: - break; + case EVENT_START_ZULAMAN: + if (Creature* voljin = instance->GetCreature(VoljinGUID)) + { + if (voljin->IsAIEnabled) + voljin->AI()->DoAction(ACTION_START_ZULAMAN); + } + break; + default: + break; } } @@ -241,20 +243,20 @@ public: { switch (eventId) { - case EVENT_UPDATE_ZULAMAN_TIMER: - SaveToDB(); - DoUpdateWorldState(WORLD_STATE_ZULAMAN_TIMER, --SpeedRunTimer); - if (SpeedRunTimer) - events.ScheduleEvent(EVENT_UPDATE_ZULAMAN_TIMER, 60000); - else - { - DoUpdateWorldState(WORLD_STATE_ZULAMAN_TIMER_ENABLED, 0); - events.CancelEvent(EVENT_UPDATE_ZULAMAN_TIMER); - ZulAmanState = FAIL; - } - break; - default: - break; + case EVENT_UPDATE_ZULAMAN_TIMER: + SaveToDB(); + DoUpdateWorldState(WORLD_STATE_ZULAMAN_TIMER, --SpeedRunTimer); + if (SpeedRunTimer) + events.ScheduleEvent(EVENT_UPDATE_ZULAMAN_TIMER, 60000); + else + { + DoUpdateWorldState(WORLD_STATE_ZULAMAN_TIMER_ENABLED, 0); + events.CancelEvent(EVENT_UPDATE_ZULAMAN_TIMER); + ZulAmanState = FAIL; + } + break; + default: + break; } } } diff --git a/src/server/scripts/EasternKingdoms/ZulAman/zulaman.cpp b/src/server/scripts/EasternKingdoms/ZulAman/zulaman.cpp index 24f56f3132f..d4fd825aec7 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/zulaman.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/zulaman.cpp @@ -16,10 +16,14 @@ */ #include "ScriptMgr.h" +#include "CreatureTextMgr.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "Player.h" -#include "CreatureTextMgr.h" #include "SpellScript.h" #include "zulaman.h" @@ -215,7 +219,7 @@ class npc_voljin_zulaman : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulAmanAI(creature); } }; diff --git a/src/server/scripts/EasternKingdoms/ZulAman/zulaman.h b/src/server/scripts/EasternKingdoms/ZulAman/zulaman.h index fb986e8e125..7b21501f00a 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/zulaman.h +++ b/src/server/scripts/EasternKingdoms/ZulAman/zulaman.h @@ -18,6 +18,8 @@ #ifndef DEF_ZULAMAN_H #define DEF_ZULAMAN_H +#include "CreatureAIImpl.h" + uint32 const EncounterCount = 6; #define ZulAmanScriptName "instance_zulaman" #define DataHeader "ZA" @@ -78,14 +80,10 @@ enum ZAWorldStates WORLD_STATE_ZULAMAN_TIMER = 3106, }; -template -CreatureAI* GetZulAmanAI(Creature* creature) +template +inline AI* GetZulAmanAI(T* obj) { - if (InstanceMap* instance = creature->GetMap()->ToInstanceMap()) - if (instance->GetInstanceScript()) - if (instance->GetScriptId() == sObjectMgr->GetScriptId(ZulAmanScriptName)) - return new AI(creature); - return NULL; + return GetInstanceAI(obj, ZulAmanScriptName); } #endif diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/boss_mandokir.cpp b/src/server/scripts/EasternKingdoms/ZulGurub/boss_mandokir.cpp index ca17b847686..0cc2ae480a4 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/boss_mandokir.cpp +++ b/src/server/scripts/EasternKingdoms/ZulGurub/boss_mandokir.cpp @@ -17,11 +17,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "Player.h" #include "GridNotifiers.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" #include "zulgurub.h" enum Yells @@ -188,14 +191,11 @@ class boss_mandokir : public CreatureScript if (creatures.empty()) return; - for (std::list::iterator itr = creatures.begin(); itr != creatures.end(); ++itr) + for (Creature* chainedSpirit : creatures) { - if (Creature* chainedSpirit = ObjectAccessor::GetCreature(*me, (*itr)->GetGUID())) - { - chainedSpirit->AI()->SetGUID(_reviveGUID); - chainedSpirit->AI()->DoAction(ACTION_REVIVE); - _reviveGUID.Clear(); - } + chainedSpirit->AI()->SetGUID(_reviveGUID); + chainedSpirit->AI()->DoAction(ACTION_REVIVE); + _reviveGUID.Clear(); } break; } @@ -479,11 +479,7 @@ class spell_mandokir_bloodletting : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BLOODLETTING_DAMAGE)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_BLOODLETTING_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BLOODLETTING_DAMAGE, SPELL_BLOODLETTING_HEAL }); } void HandleEffectPeriodic(AuraEffect const* aurEff) @@ -539,7 +535,7 @@ class spell_mandokir_spirit_vengeance_cancel : public SpellScriptLoader } }; -class DevastatingSlamTargetSelector : public std::unary_function +class DevastatingSlamTargetSelector { public: DevastatingSlamTargetSelector(Creature* me, const Unit* victim) : _me(me), _victim(victim) {} @@ -706,7 +702,7 @@ class spell_mandokir_reanimate_ohgan : public SpellScriptLoader { target->RemoveAura(SPELL_PERMANENT_FEIGN_DEATH); target->CastSpell(target, SPELL_OHGAN_HEART_VISUAL, true); - target->CastSpell((Unit*)NULL, SPELL_OHGAN_ORDERS, true); + target->CastSpell((Unit*)nullptr, SPELL_OHGAN_ORDERS, true); } } diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/boss_venoxis.cpp b/src/server/scripts/EasternKingdoms/ZulGurub/boss_venoxis.cpp index 69102a9cbc1..9e6c88db4db 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/boss_venoxis.cpp +++ b/src/server/scripts/EasternKingdoms/ZulGurub/boss_venoxis.cpp @@ -16,10 +16,8 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" -#include "Spell.h" #include "zulgurub.h" enum Yells diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/boss_zanzil.cpp b/src/server/scripts/EasternKingdoms/ZulGurub/boss_zanzil.cpp index 73021b0572d..cf04e4a8f3f 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/boss_zanzil.cpp +++ b/src/server/scripts/EasternKingdoms/ZulGurub/boss_zanzil.cpp @@ -15,7 +15,6 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "zulgurub.h" diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/instance_zulgurub.cpp b/src/server/scripts/EasternKingdoms/ZulGurub/instance_zulgurub.cpp index 4522877a178..91ef8a5e7d2 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/instance_zulgurub.cpp +++ b/src/server/scripts/EasternKingdoms/ZulGurub/instance_zulgurub.cpp @@ -17,7 +17,10 @@ */ #include "ScriptMgr.h" +#include "Creature.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" #include "zulgurub.h" DoorData const doorData[] = diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/zulgurub.h b/src/server/scripts/EasternKingdoms/ZulGurub/zulgurub.h index 7a8278a2300..2da6f74fbb7 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/zulgurub.h +++ b/src/server/scripts/EasternKingdoms/ZulGurub/zulgurub.h @@ -19,6 +19,8 @@ #ifndef DEF_ZULGURUB_H #define DEF_ZULGURUB_H +#include "CreatureAIImpl.h" + #define DataHeader "ZG" #define ZGScriptName "instance_zulgurub" @@ -88,10 +90,10 @@ enum ZGGameObjectIds GO_THE_CACHE_OF_MADNESS_DOOR = 208843 }; -template -AI* GetZulGurubAI(Creature* creature) +template +inline AI* GetZulGurubAI(T* obj) { - return GetInstanceAI(creature, ZGScriptName); + return GetInstanceAI(obj, ZGScriptName); } #endif diff --git a/src/server/scripts/EasternKingdoms/eastern_kingdoms_script_loader.cpp b/src/server/scripts/EasternKingdoms/eastern_kingdoms_script_loader.cpp index 3ba242f7c10..1089dc7e5d1 100644 --- a/src/server/scripts/EasternKingdoms/eastern_kingdoms_script_loader.cpp +++ b/src/server/scripts/EasternKingdoms/eastern_kingdoms_script_loader.cpp @@ -67,8 +67,7 @@ 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_instance_deadmines(); //Deadmines void AddSC_boss_mr_smite(); void AddSC_gilneas_c1(); //Gilneas void AddSC_gnomeregan(); //Gnomeregan @@ -259,9 +258,8 @@ void AddEasternKingdomsScripts() AddSC_boss_chromaggus(); AddSC_boss_nefarian(); AddSC_instance_blackwing_lair(); - AddSC_deadmines(); //Deadmines + AddSC_instance_deadmines(); //Deadmines AddSC_boss_mr_smite(); - AddSC_instance_deadmines(); AddSC_gilneas_c1(); //Gilneas AddSC_gnomeregan(); //Gnomeregan AddSC_instance_gnomeregan(); diff --git a/src/server/scripts/EasternKingdoms/zone_blasted_lands.cpp b/src/server/scripts/EasternKingdoms/zone_blasted_lands.cpp index e2d948fd142..927c130f062 100644 --- a/src/server/scripts/EasternKingdoms/zone_blasted_lands.cpp +++ b/src/server/scripts/EasternKingdoms/zone_blasted_lands.cpp @@ -48,9 +48,7 @@ class spell_razelikh_teleport_group : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TELEPORT_SINGLE) && !sSpellMgr->GetSpellInfo(SPELL_TELEPORT_SINGLE_IN_GROUP)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TELEPORT_SINGLE, SPELL_TELEPORT_SINGLE_IN_GROUP }); } void HandleScriptEffect(SpellEffIndex /* effIndex */) @@ -59,7 +57,7 @@ class spell_razelikh_teleport_group : public SpellScriptLoader { if (Group* group = player->GetGroup()) { - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) if (Player* member = itr->GetSource()) if (member->IsWithinDistInMap(player, 20.0f) && !member->isDead()) member->CastSpell(member, SPELL_TELEPORT_SINGLE_IN_GROUP, true); diff --git a/src/server/scripts/EasternKingdoms/zone_dun_morogh.cpp b/src/server/scripts/EasternKingdoms/zone_dun_morogh.cpp index 77e5473d2b1..2c17bfe4a2b 100644 --- a/src/server/scripts/EasternKingdoms/zone_dun_morogh.cpp +++ b/src/server/scripts/EasternKingdoms/zone_dun_morogh.cpp @@ -16,6 +16,7 @@ */ #include "ScriptMgr.h" +#include "MotionMaster.h" #include "ScriptedCreature.h" enum FrozenMountaineer diff --git a/src/server/scripts/EasternKingdoms/zone_dun_morogh_area_coldridge_valley.cpp b/src/server/scripts/EasternKingdoms/zone_dun_morogh_area_coldridge_valley.cpp index 17060c30077..127bbb07d19 100644 --- a/src/server/scripts/EasternKingdoms/zone_dun_morogh_area_coldridge_valley.cpp +++ b/src/server/scripts/EasternKingdoms/zone_dun_morogh_area_coldridge_valley.cpp @@ -16,11 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "MoveSplineInit.h" -#include "SpellScript.h" #include "CombatAI.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum WoundedColdridgeMountaineer { @@ -218,8 +221,7 @@ enum MilosGyro EVENT_MILO_DESPAWN = 13 }; -uint32 const pathSize = 24; -G3D::Vector3 const kharanosPath[pathSize] = +Position const kharanosPath[] = { { -6247.328f, 299.5365f, 390.266f }, { -6247.328f, 299.5365f, 390.266f }, @@ -246,6 +248,7 @@ G3D::Vector3 const kharanosPath[pathSize] = { -5603.897f, -466.3438f, 409.8931f }, { -5566.957f, -472.5642f, 399.0056f } }; +uint32 const pathSize = std::extent::value; class npc_milos_gyro : public CreatureScript { diff --git a/src/server/scripts/EasternKingdoms/zone_duskwood.cpp b/src/server/scripts/EasternKingdoms/zone_duskwood.cpp index f3e1db7d361..5abfa3aca35 100644 --- a/src/server/scripts/EasternKingdoms/zone_duskwood.cpp +++ b/src/server/scripts/EasternKingdoms/zone_duskwood.cpp @@ -24,8 +24,9 @@ SDCategory: Duskwood EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum TwilightCorrupter { @@ -146,7 +147,7 @@ class at_twilight_grove : public AreaTriggerScript public: at_twilight_grove() : AreaTriggerScript("at_twilight_grove") { } - bool OnTrigger(Player* player, const AreaTriggerEntry* /*at*/) override + bool OnTrigger(Player* player, AreaTriggerEntry const* /*at*/) override { if (player->GetQuestStatus(QUEST_NIGHTMARES_CORRUPTION) == QUEST_STATUS_INCOMPLETE) if (!player->FindNearestCreature(NPC_TWILIGHT_CORRUPTER, 500.0f, true)) diff --git a/src/server/scripts/EasternKingdoms/zone_elwynn_forest.cpp b/src/server/scripts/EasternKingdoms/zone_elwynn_forest.cpp index 4c70966c936..99aeaeab547 100644 --- a/src/server/scripts/EasternKingdoms/zone_elwynn_forest.cpp +++ b/src/server/scripts/EasternKingdoms/zone_elwynn_forest.cpp @@ -16,11 +16,12 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "MoveSplineInit.h" -#include "SpellScript.h" -#include "CombatAI.h" +#include "CreatureAIImpl.h" +#include "GridNotifiersImpl.h" +#include "MotionMaster.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "SpellScript.h" enum Northshire { @@ -234,16 +235,13 @@ public: struct npc_injured_stormwind_infantry_dummyAI : public ScriptedAI { - npc_injured_stormwind_infantry_dummyAI(Creature* creature) : ScriptedAI(creature) - { - } + npc_injured_stormwind_infantry_dummyAI(Creature* creature) : ScriptedAI(creature) { } void Reset() override { events.ScheduleEvent(EVENT_GIVE_RIGHT_CLICK_INSTRUCTIONS, Milliseconds(1)); } - void UpdateAI(uint32 diff) override { events.Update(diff); @@ -254,20 +252,20 @@ public: { case EVENT_GIVE_RIGHT_CLICK_INSTRUCTIONS: { - std::list players; + std::vector players; Trinity::AnyPlayerInObjectRangeCheck checker(me, 50.0f); Trinity::PlayerListSearcher searcher(me, players, checker); Cell::VisitWorldObjects(me, searcher, 50.0f); - for (std::list::const_iterator itr = players.begin(); itr != players.end(); ++itr) + for (Player* player : players) { - for (uint8 i = 0; i < 9; i++) + for (uint32 questId : FearNoEvilQuests) { - if ((*itr)->GetQuestStatus(FearNoEvilQuests[i]) == QUEST_STATUS_INCOMPLETE) + if (player->GetQuestStatus(questId) == QUEST_STATUS_INCOMPLETE) { - if (!(*itr)->HasAura(SPELL_GIVEN_RIGHT_CLICK_INSTRUCTION)) + if (!player->HasAura(SPELL_GIVEN_RIGHT_CLICK_INSTRUCTION)) { - me->CastSpell((*itr), SPELL_GIVEN_RIGHT_CLICK_INSTRUCTION, true); - Talk(SAY_RIGHT_CLICK, (*itr)); + me->CastSpell(player, SPELL_GIVEN_RIGHT_CLICK_INSTRUCTION, true); + Talk(SAY_RIGHT_CLICK, player); } } } diff --git a/src/server/scripts/EasternKingdoms/zone_ghostlands.cpp b/src/server/scripts/EasternKingdoms/zone_ghostlands.cpp index 5ef3b74c2ec..7f510b46072 100644 --- a/src/server/scripts/EasternKingdoms/zone_ghostlands.cpp +++ b/src/server/scripts/EasternKingdoms/zone_ghostlands.cpp @@ -28,10 +28,11 @@ npc_ranger_lilatha EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "GameObject.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "TemporarySummon.h" #include "WorldSession.h" /*###### diff --git a/src/server/scripts/EasternKingdoms/zone_hinterlands.cpp b/src/server/scripts/EasternKingdoms/zone_hinterlands.cpp index 181a3b778e6..512a8b8a00b 100644 --- a/src/server/scripts/EasternKingdoms/zone_hinterlands.cpp +++ b/src/server/scripts/EasternKingdoms/zone_hinterlands.cpp @@ -28,9 +28,9 @@ npc_oox09hl EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" +#include "MotionMaster.h" #include "Player.h" +#include "ScriptedEscortAI.h" /*###### ## npc_oox09hl @@ -142,8 +142,7 @@ enum Sharpbeak SPELL_EJECT_ALL_PASSENGERS = 50630 }; -uint32 const campPathSize = 12; -G3D::Vector3 const campPath[campPathSize] = +Position const campPath[] = { { -75.40077f, -4037.111f, 114.6418f }, { -68.80193f, -4034.235f, 123.6844f }, @@ -158,9 +157,9 @@ G3D::Vector3 const campPath[campPathSize] = { -169.123f, -3582.08f, 282.866f }, { -241.8403f, -3625.01f, 247.4203f } }; +uint32 const campPathSize = std::extent::value; -uint32 const jinthaalorPathSize = 20; -G3D::Vector3 const jinthaalorPath[jinthaalorPathSize] = +Position const jinthaalorPath[] = { { -249.4681f, -3632.487f, 232.6947f }, { -241.606f, -3627.713f, 236.61870f }, @@ -183,6 +182,7 @@ G3D::Vector3 const jinthaalorPath[jinthaalorPathSize] = { -76.90625f, -4040.207f, 126.0433f }, { -77.51563f, -4022.026f, 123.2135f } }; +uint32 const jinthaalorPathSize = std::extent::value; class npc_sharpbeak : public CreatureScript { diff --git a/src/server/scripts/EasternKingdoms/zone_redridge_mountains.cpp b/src/server/scripts/EasternKingdoms/zone_redridge_mountains.cpp index c679eb32752..7cda4a9d27f 100644 --- a/src/server/scripts/EasternKingdoms/zone_redridge_mountains.cpp +++ b/src/server/scripts/EasternKingdoms/zone_redridge_mountains.cpp @@ -22,10 +22,10 @@ SDComment: Script Data End */ #include "ScriptMgr.h" -#include "Player.h" -#include "ScriptedCreature.h" #include "MotionMaster.h" #include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" enum DumpyKeeshan { @@ -298,8 +298,7 @@ const uint32 Emote[6] = EMOTE_ONESHOTNO }; -uint32 const pathSize = 8; -G3D::Vector3 const TownhallPath[pathSize] = +Position const TownhallPath[] = { { -9221.39f, -2198.45f, 66.34846f }, { -9221.39f, -2198.45f, 66.34846f }, @@ -310,6 +309,7 @@ G3D::Vector3 const TownhallPath[pathSize] = { -9244.14f, -2211.20f, 66.34846f }, { -9255.31f, -2211.62f, 63.93340f } }; +uint32 const pathSize = std::extent::value; class npc_redridge_citizen : public CreatureScript { diff --git a/src/server/scripts/EasternKingdoms/zone_tol_barad.cpp b/src/server/scripts/EasternKingdoms/zone_tol_barad.cpp index 04e1d1b8ada..435c5787ec9 100644 --- a/src/server/scripts/EasternKingdoms/zone_tol_barad.cpp +++ b/src/server/scripts/EasternKingdoms/zone_tol_barad.cpp @@ -15,15 +15,13 @@ * with this program. If not, see . */ -#include "BattlefieldMgr.h" +#include "ScriptMgr.h" #include "BattlefieldTB.h" -#include "Battlefield.h" -#include "ScriptSystem.h" -#include "WorldSession.h" +#include "DBCStores.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" #include "SpellScript.h" -#include "Player.h" enum TBSpiritGuide { @@ -54,7 +52,7 @@ class npc_tb_spirit_guide : public CreatureScript bool GossipSelect(Player* player, uint32 /*menuId*/, uint32 gossipListId) override { - player->PlayerTalkClass->SendCloseGossip(); + CloseGossipMenuFor(player); uint32 areaId = 0; switch (gossipListId) diff --git a/src/server/scripts/EasternKingdoms/zone_undercity.cpp b/src/server/scripts/EasternKingdoms/zone_undercity.cpp index 3559c120d02..1b020b75921 100644 --- a/src/server/scripts/EasternKingdoms/zone_undercity.cpp +++ b/src/server/scripts/EasternKingdoms/zone_undercity.cpp @@ -30,9 +30,11 @@ npc_parqual_fintallas EndContentData */ #include "ScriptMgr.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "Player.h" /*###### ## npc_lady_sylvanas_windrunner diff --git a/src/server/scripts/EasternKingdoms/zone_western_plaguelands.cpp b/src/server/scripts/EasternKingdoms/zone_western_plaguelands.cpp index 9dab028073b..a631dd417e7 100644 --- a/src/server/scripts/EasternKingdoms/zone_western_plaguelands.cpp +++ b/src/server/scripts/EasternKingdoms/zone_western_plaguelands.cpp @@ -59,7 +59,7 @@ public: void DoDie() { //summoner dies here - 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); //override any database `spawntimesecs` to prevent duplicated summons uint32 rTime = me->GetRespawnDelay(); if (rTime < 600) diff --git a/src/server/scripts/Events/childrens_week.cpp b/src/server/scripts/Events/childrens_week.cpp index 49e537d84d7..02c425c9b99 100644 --- a/src/server/scripts/Events/childrens_week.cpp +++ b/src/server/scripts/Events/childrens_week.cpp @@ -16,9 +16,11 @@ */ #include "ScriptMgr.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "SpellAuras.h" -#include "Player.h" enum Orphans { diff --git a/src/server/scripts/Events/fireworks_show.cpp b/src/server/scripts/Events/fireworks_show.cpp index bfe71f4aaad..5f70babb1c3 100644 --- a/src/server/scripts/Events/fireworks_show.cpp +++ b/src/server/scripts/Events/fireworks_show.cpp @@ -16,9 +16,12 @@ */ #include "ScriptMgr.h" -#include "GameObjectAI.h" +#include "Containers.h" #include "CreatureAIImpl.h" +#include "EventMap.h" #include "GameEventMgr.h" +#include "GameObject.h" +#include "GameObjectAI.h" #include "GameTime.h" enum FireworksShowTypeObjects @@ -857,7 +860,7 @@ public: if (_big) { - if (GameObject* firework = me->SummonGameObject(FireworksBIGOnlyPicker(), rndpos, G3D::Quat(0.f, 0.f, rndrot, rndrot2), 300)) + if (GameObject* firework = me->SummonGameObject(FireworksBIGOnlyPicker(), rndpos, QuaternionData(0.f, 0.f, rndrot, rndrot2), 300)) { firework->SetRespawnTime(0); firework->Delete(); @@ -865,7 +868,7 @@ public: } else { - if (GameObject* firework = me->SummonGameObject(FireworksPicker(), rndpos, G3D::Quat(0.f, 0.f, rndrot, rndrot2), 300)) + if (GameObject* firework = me->SummonGameObject(FireworksPicker(), rndpos, QuaternionData(0.f, 0.f, rndrot, rndrot2), 300)) { firework->SetRespawnTime(0); firework->Delete(); diff --git a/src/server/scripts/Kalimdor/BlackfathomDeeps/blackfathom_deeps.cpp b/src/server/scripts/Kalimdor/BlackfathomDeeps/blackfathom_deeps.cpp index 35b8113e9d6..f9af1df3cb2 100644 --- a/src/server/scripts/Kalimdor/BlackfathomDeeps/blackfathom_deeps.cpp +++ b/src/server/scripts/Kalimdor/BlackfathomDeeps/blackfathom_deeps.cpp @@ -15,13 +15,15 @@ * with this program. If not, see . */ -#include "GameObjectAI.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" #include "blackfathom_deeps.h" -#include "ScriptedEscortAI.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "InstanceScript.h" +#include "Map.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" enum Spells { @@ -53,7 +55,7 @@ class go_blackfathom_altar : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return new go_blackfathom_altarAI(go); + return GetBlackfathomDeepsAI(go); } }; @@ -64,24 +66,22 @@ class go_blackfathom_fire : public GameObjectScript struct go_blackfathom_fireAI : public GameObjectAI { - go_blackfathom_fireAI(GameObject* go) : GameObjectAI(go) { } + go_blackfathom_fireAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* /*player*/) override { - if (InstanceScript* instance = me->GetInstanceScript()) - { - me->SetGoState(GO_STATE_ACTIVE); - me->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); - instance->SetData(DATA_FIRE, instance->GetData(DATA_FIRE) + 1); - return true; - } - return false; + me->SetGoState(GO_STATE_ACTIVE); + me->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); + instance->SetData(DATA_FIRE, instance->GetData(DATA_FIRE) + 1); + return true; } }; GameObjectAI* GetAI(GameObject* go) const override { - return new go_blackfathom_fireAI(go); + return GetBlackfathomDeepsAI(go); } }; @@ -90,11 +90,6 @@ class npc_blackfathom_deeps_event : public CreatureScript public: npc_blackfathom_deeps_event() : CreatureScript("npc_blackfathom_deeps_event") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_blackfathom_deeps_eventAI : public ScriptedAI { npc_blackfathom_deeps_eventAI(Creature* creature) : ScriptedAI(creature) @@ -133,8 +128,7 @@ public: void AttackPlayer() { - Map::PlayerList const &PlList = me->GetMap()->GetPlayers(); - + Map::PlayerList const& PlList = me->GetMap()->GetPlayers(); if (PlList.isEmpty()) return; @@ -210,6 +204,11 @@ public: instance->SetData(DATA_EVENT, instance->GetData(DATA_EVENT) + 1); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetBlackfathomDeepsAI(creature); + } }; enum Morridune @@ -254,7 +253,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_morriduneAI(creature); + return GetBlackfathomDeepsAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/BlackfathomDeeps/blackfathom_deeps.h b/src/server/scripts/Kalimdor/BlackfathomDeeps/blackfathom_deeps.h index afcc8f6d38f..06937ac9f6e 100644 --- a/src/server/scripts/Kalimdor/BlackfathomDeeps/blackfathom_deeps.h +++ b/src/server/scripts/Kalimdor/BlackfathomDeeps/blackfathom_deeps.h @@ -19,6 +19,9 @@ #ifndef BFD_H_ #define BFD_H_ +#include "CreatureAIImpl.h" + +#define BFDScriptName "instance_blackfathom_deeps" #define DataHeader "BFD" uint32 const EncounterCount = 3; @@ -68,4 +71,10 @@ enum BFDGameObjectIds GO_ALTAR_OF_THE_DEEPS = 103016 }; +template +inline AI* GetBlackfathomDeepsAI(T* obj) +{ + return GetInstanceAI(obj, BFDScriptName); +} + #endif // BFD_H_ diff --git a/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_aku_mai.cpp b/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_aku_mai.cpp index eae2e3b94db..120374ae838 100644 --- a/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_aku_mai.cpp +++ b/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_aku_mai.cpp @@ -16,8 +16,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackfathom_deeps.h" +#include "ScriptedCreature.h" enum Spells { @@ -88,7 +88,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackfathomDeepsAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_gelihast.cpp b/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_gelihast.cpp index 76ee2f76e03..0d0445122c9 100644 --- a/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_gelihast.cpp +++ b/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_gelihast.cpp @@ -16,8 +16,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackfathom_deeps.h" +#include "ScriptedCreature.h" enum Spells { @@ -66,7 +66,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackfathomDeepsAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_kelris.cpp b/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_kelris.cpp index 5f176a1f77f..74810550603 100644 --- a/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_kelris.cpp +++ b/src/server/scripts/Kalimdor/BlackfathomDeeps/boss_kelris.cpp @@ -16,8 +16,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "blackfathom_deeps.h" +#include "ScriptedCreature.h" enum Spells { @@ -101,7 +101,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackfathomDeepsAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/BlackfathomDeeps/instance_blackfathom_deeps.cpp b/src/server/scripts/Kalimdor/BlackfathomDeeps/instance_blackfathom_deeps.cpp index f12c4caa574..ae9d2a31243 100644 --- a/src/server/scripts/Kalimdor/BlackfathomDeeps/instance_blackfathom_deeps.cpp +++ b/src/server/scripts/Kalimdor/BlackfathomDeeps/instance_blackfathom_deeps.cpp @@ -24,8 +24,11 @@ SDCategory: Blackfathom Deeps EndScriptData */ #include "ScriptMgr.h" -#include "InstanceScript.h" #include "blackfathom_deeps.h" +#include "Creature.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" const Position LorgusPosition[4] = { @@ -47,12 +50,7 @@ const Position SpawnsLocation[] = class instance_blackfathom_deeps : public InstanceMapScript { public: - instance_blackfathom_deeps() : InstanceMapScript("instance_blackfathom_deeps", 48) { } - - InstanceScript* GetInstanceScript(InstanceMap* map) const override - { - return new instance_blackfathom_deeps_InstanceMapScript(map); - } + instance_blackfathom_deeps() : InstanceMapScript(BFDScriptName, 48) { } struct instance_blackfathom_deeps_InstanceMapScript : public InstanceScript { @@ -238,6 +236,11 @@ public: uint8 countFires; uint8 deathTimes; }; + + InstanceScript* GetInstanceScript(InstanceMap* map) const override + { + return new instance_blackfathom_deeps_InstanceMapScript(map); + } }; void AddSC_instance_blackfathom_deeps() diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_anetheron.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_anetheron.cpp index c37e1f59aea..89a93e089dd 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_anetheron.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_anetheron.cpp @@ -16,10 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "hyjal.h" #include "hyjal_trash.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "SpellScript.h" enum Spells { @@ -47,11 +47,6 @@ class boss_anetheron : public CreatureScript public: boss_anetheron() : CreatureScript("boss_anetheron") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_anetheronAI : public hyjal_trashAI { boss_anetheronAI(Creature* creature) : hyjal_trashAI(creature) @@ -177,6 +172,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetHyjalAI(creature); + } }; class npc_towering_infernal : public CreatureScript @@ -184,11 +183,6 @@ class npc_towering_infernal : public CreatureScript public: npc_towering_infernal() : CreatureScript("npc_towering_infernal") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_towering_infernalAI : public ScriptedAI { npc_towering_infernalAI(Creature* creature) : ScriptedAI(creature) @@ -261,6 +255,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetHyjalAI(creature); + } }; class spell_anetheron_vampiric_aura : public SpellScriptLoader @@ -274,9 +272,7 @@ class spell_anetheron_vampiric_aura : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_VAMPIRIC_AURA_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_VAMPIRIC_AURA_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_archimonde.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_archimonde.cpp index fcc7e384ded..c2d5d35352b 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_archimonde.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_archimonde.cpp @@ -24,10 +24,13 @@ SDCategory: Caverns of Time, Mount Hyjal EndScriptData */ #include "ScriptMgr.h" +#include "hyjal.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "Player.h" -#include "hyjal.h" enum Texts { @@ -97,11 +100,6 @@ class npc_ancient_wisp : public CreatureScript public: npc_ancient_wisp() : CreatureScript("npc_ancient_wisp") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_ancient_wispAI : public ScriptedAI { npc_ancient_wispAI(Creature* creature) : ScriptedAI(creature) @@ -151,6 +149,11 @@ public: } else CheckTimer -= diff; } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetHyjalAI(creature); + } }; /* This script is merely a placeholder for the Doomfire that triggers Doomfire spell. It will @@ -160,11 +163,6 @@ class npc_doomfire : public CreatureScript public: npc_doomfire() : CreatureScript("npc_doomfire") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_doomfireAI(creature); - } - struct npc_doomfireAI : public ScriptedAI { npc_doomfireAI(Creature* creature) : ScriptedAI(creature) { } @@ -180,6 +178,11 @@ public: damage = 0; } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetHyjalAI(creature); + } }; /* This is the script for the Doomfire Spirit Mob. This mob simply follow players or @@ -189,11 +192,6 @@ class npc_doomfire_targetting : public CreatureScript public: npc_doomfire_targetting() : CreatureScript("npc_doomfire_targetting") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_doomfire_targettingAI(creature); - } - struct npc_doomfire_targettingAI : public ScriptedAI { npc_doomfire_targettingAI(Creature* creature) : ScriptedAI(creature) @@ -249,6 +247,11 @@ public: } else ChangeTargetTimer -= diff; } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetHyjalAI(creature); + } }; /* Finally, Archimonde's script. His script isn't extremely complex, most are simply spells on timers. @@ -389,7 +392,7 @@ public: DoSpawnCreature(NPC_ANCIENT_WISP, float(rand32() % 40), float(rand32() % 40), 0, 0, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 15000); ++WispCount; if (WispCount >= 30) - 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); events.ScheduleEvent(EVENT_SUMMON_WHISP, 1500); break; default: @@ -530,7 +533,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } }; @@ -546,9 +549,7 @@ class spell_archimonde_drain_world_tree_dummy : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRAIN_WORLD_TREE_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRAIN_WORLD_TREE_TRIGGERED }); } void HandleScript(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_azgalor.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_azgalor.cpp index 53c76fefae5..3f377382dbc 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_azgalor.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_azgalor.cpp @@ -16,9 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "hyjal.h" #include "hyjal_trash.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Spells { @@ -46,11 +47,6 @@ class boss_azgalor : public CreatureScript public: boss_azgalor() : CreatureScript("boss_azgalor") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_azgalorAI : public hyjal_trashAI { boss_azgalorAI(Creature* creature) : hyjal_trashAI(creature) @@ -181,6 +177,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetHyjalAI(creature); + } }; class npc_lesser_doomguard : public CreatureScript @@ -188,11 +188,6 @@ class npc_lesser_doomguard : public CreatureScript public: npc_lesser_doomguard() : CreatureScript("npc_lesser_doomguard") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_lesser_doomguardAI : public hyjal_trashAI { npc_lesser_doomguardAI(Creature* creature) : hyjal_trashAI(creature) @@ -276,6 +271,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetHyjalAI(creature); + } }; void AddSC_boss_azgalor() diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_kazrogal.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_kazrogal.cpp index 9a7163e3aec..71b63833f8d 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_kazrogal.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_kazrogal.cpp @@ -16,11 +16,12 @@ */ #include "ScriptMgr.h" +#include "hyjal_trash.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellAuraEffects.h" #include "SpellScript.h" -#include "hyjal.h" -#include "hyjal_trash.h" enum Spells { @@ -47,11 +48,6 @@ class boss_kazrogal : public CreatureScript public: boss_kazrogal() : CreatureScript("boss_kazrogal") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_kazrogalAI : public hyjal_trashAI { boss_kazrogalAI(Creature* creature) : hyjal_trashAI(creature) @@ -167,6 +163,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetHyjalAI(creature); + } }; class MarkTargetFilter @@ -206,9 +206,7 @@ class spell_mark_of_kazrogal : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MARK_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MARK_DAMAGE }); } void OnPeriodic(AuraEffect const* aurEff) @@ -217,7 +215,7 @@ class spell_mark_of_kazrogal : public SpellScriptLoader if (target->GetPower(POWER_MANA) == 0) { - target->CastSpell(target, SPELL_MARK_DAMAGE, true, NULL, aurEff); + target->CastSpell(target, SPELL_MARK_DAMAGE, true, nullptr, aurEff); // Remove aura SetDuration(0); } diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_rage_winterchill.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_rage_winterchill.cpp index 5af09c7a00e..15e01c17dcf 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_rage_winterchill.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/boss_rage_winterchill.cpp @@ -16,9 +16,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "hyjal.h" #include "hyjal_trash.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" enum Spells { @@ -42,11 +42,6 @@ class boss_rage_winterchill : public CreatureScript public: boss_rage_winterchill() : CreatureScript("boss_rage_winterchill") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_rage_winterchillAI : public hyjal_trashAI { boss_rage_winterchillAI(Creature* creature) : hyjal_trashAI(creature) @@ -162,6 +157,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetHyjalAI(creature); + } }; void AddSC_boss_rage_winterchill() diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.cpp index 584118ef81d..2c3ad28bac6 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.cpp @@ -30,10 +30,12 @@ npc_tyrande_whisperwind EndContentData */ #include "ScriptMgr.h" +#include "hyjalAI.h" +#include "InstanceScript.h" +#include "Log.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "hyjalAI.h" -#include "Player.h" #define GOSSIP_ITEM_BEGIN_ALLY "My companions and I are with you, Lady Proudmoore." #define GOSSIP_ITEM_ANETHERON "We are ready for whatever Archimonde might send our way, Lady Proudmoore." @@ -122,7 +124,7 @@ class npc_jaina_proudmoore : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_jaina_proudmooreAI(creature); + return GetHyjalAI(creature); } }; @@ -202,7 +204,7 @@ class npc_thrall : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_thrallAI(creature); + return GetHyjalAI(creature); } }; @@ -250,7 +252,7 @@ class npc_tyrande_whisperwind : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_tyrande_whisperwindAI(creature); + return GetHyjalAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.h b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.h index 09ccb129778..dd0f7d4752d 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.h +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.h @@ -19,6 +19,9 @@ #ifndef DEF_HYJAL_H #define DEF_HYJAL_H +#include "CreatureAIImpl.h" + +#define HyjalScriptName "instance_hyjal" #define DataHeader "HY" uint32 const EncounterCount = 5; @@ -93,4 +96,10 @@ enum HYGameobjectIds #define MINRAIDDAMAGE 700000 // minimal damage before trash can drop loot and reputation, resets if faction leader dies +template +inline AI* GetHyjalAI(T* obj) +{ + return GetInstanceAI(obj, HyjalScriptName); +} + #endif diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.cpp index 71a733d2f12..61d9b6f9c44 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.cpp @@ -24,14 +24,15 @@ SDCategory: Caverns of Time, Mount Hyjal EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "Cell.h" #include "CellImpl.h" -#include "hyjalAI.h" +#include "GridNotifiersImpl.h" #include "hyjal_trash.h" +#include "hyjalAI.h" +#include "InstanceScript.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "TemporarySummon.h" enum Spawns { @@ -429,7 +430,7 @@ void hyjalAI::EnterEvadeMode(EvadeReason /*why*/) if (me->IsAlive()) me->GetMotionMaster()->MoveTargetedHome(); - me->SetLootRecipient(NULL); + me->SetLootRecipient(nullptr); } void hyjalAI::JustEngagedWith(Unit* /*who*/) @@ -459,7 +460,7 @@ void hyjalAI::SummonCreature(uint32 entry, float Base[4][3]) { SpawnLoc[i] = Base[random][i]; } - Creature* creature = NULL; + Creature* creature = nullptr; switch (entry) { case 17906: //GARGOYLE @@ -652,7 +653,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], G3D::Quat(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], QuaternionData(VeinPos[i][4], VeinPos[i][5], VeinPos[i][6], VeinPos[i][7]), 0); if (gem) VeinGUID[i]=gem->GetGUID(); } @@ -664,7 +665,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], G3D::Quat(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], QuaternionData(VeinPos[i][4], VeinPos[i][5], VeinPos[i][6], VeinPos[i][7]), 0); if (gem) VeinGUID[i] = gem->GetGUID(); } @@ -676,19 +677,19 @@ void hyjalAI::DeSpawnVeins() { if (Faction == 1) { - Creature* unit=ObjectAccessor::GetCreature((*me), instance->GetGuidData(DATA_JAINAPROUDMOORE)); + Creature* unit = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_JAINAPROUDMOORE)); if (!unit)return; hyjalAI* ai = CAST_AI(hyjalAI, unit->AI()); if (!ai)return; for (uint8 i = 0; i < 7; ++i) { - if (GameObject* gem = instance->instance->GetGameObject(ai->VeinGUID[i])) + if (GameObject* gem = ObjectAccessor::GetGameObject(*me, ai->VeinGUID[i])) gem->Delete(); } } else if (Faction) { - Creature* unit=ObjectAccessor::GetCreature((*me), instance->GetGuidData(DATA_THRALL)); + Creature* unit = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_THRALL)); if (!unit) return; hyjalAI* ai = CAST_AI(hyjalAI, unit->AI()); @@ -696,7 +697,7 @@ void hyjalAI::DeSpawnVeins() return; for (uint8 i = 7; i < 14; ++i) { - if (GameObject* gem = instance->instance->GetGameObject(ai->VeinGUID[i])) + if (GameObject* gem = ObjectAccessor::GetGameObject(*me, ai->VeinGUID[i])) gem->Delete(); } } @@ -727,7 +728,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], G3D::Quat(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], QuaternionData(AllianceFirePos[i][4], AllianceFirePos[i][5], AllianceFirePos[i][6], AllianceFirePos[i][7]), 0); } else me->SetVisible(true); @@ -740,7 +741,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], G3D::Quat(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], QuaternionData(HordeFirePos[i][4], HordeFirePos[i][5], HordeFirePos[i][6], HordeFirePos[i][7]), 0); } else me->SetVisible(true); @@ -856,7 +857,7 @@ void hyjalAI::UpdateAI(uint32 diff) if (me->IsNonMeleeSpellCast(false)) me->InterruptNonMeleeSpells(false); - Unit* target = NULL; + Unit* target = nullptr; switch (Spells[i].TargetType) { @@ -1017,7 +1018,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], G3D::Quat(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], QuaternionData(AllianceFirePos[i][4], AllianceFirePos[i][5], AllianceFirePos[i][6], AllianceFirePos[i][7]), 0); for (uint8 i = 0; i < 25; ++i)//summon 25 ghouls { @@ -1061,7 +1062,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], G3D::Quat(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], QuaternionData(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 9f2af815163..cda9279ea4e 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.h +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjalAI.h @@ -204,6 +204,5 @@ struct hyjalAI : public npc_escortAI private: uint32 SpellTimer[3]; - //std::list CreatureList; }; #endif diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal_trash.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal_trash.cpp index 023c71f7d35..b6de41d6de5 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal_trash.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal_trash.cpp @@ -16,10 +16,12 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "hyjal.h" #include "hyjal_trash.h" #include "hyjalAI.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "TemporarySummon.h" enum Spells { @@ -523,7 +525,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHyjalAI(creature); } }; @@ -532,11 +534,6 @@ class npc_abomination : public CreatureScript public: npc_abomination() : CreatureScript("npc_abomination") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_abominationAI : public hyjal_trashAI { npc_abominationAI(Creature* creature) : hyjal_trashAI(creature) @@ -619,7 +616,11 @@ public: DoMeleeAttackIfReady(); } }; - + + CreatureAI* GetAI(Creature* creature) const override + { + return GetHyjalAI(creature); + } }; class npc_ghoul : public CreatureScript @@ -627,11 +628,6 @@ class npc_ghoul : public CreatureScript public: npc_ghoul() : CreatureScript("npc_ghoul") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_ghoulAI : public hyjal_trashAI { npc_ghoulAI(Creature* creature) : hyjal_trashAI(creature) @@ -719,6 +715,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetHyjalAI(creature); + } }; class npc_necromancer : public CreatureScript @@ -726,11 +726,6 @@ class npc_necromancer : public CreatureScript public: npc_necromancer() : CreatureScript("npc_necromancer") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_necromancerAI : public hyjal_trashAI { npc_necromancerAI(Creature* creature) : hyjal_trashAI(creature), summons(me) @@ -843,6 +838,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetHyjalAI(creature); + } }; class npc_banshee : public CreatureScript @@ -850,11 +849,6 @@ class npc_banshee : public CreatureScript public: npc_banshee() : CreatureScript("npc_banshee") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_bansheeAI : public hyjal_trashAI { npc_bansheeAI(Creature* creature) : hyjal_trashAI(creature) @@ -943,6 +937,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetHyjalAI(creature); + } }; class npc_crypt_fiend : public CreatureScript @@ -950,11 +948,6 @@ class npc_crypt_fiend : public CreatureScript public: npc_crypt_fiend() : CreatureScript("npc_crypt_fiend") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_crypt_fiendAI : public hyjal_trashAI { npc_crypt_fiendAI(Creature* creature) : hyjal_trashAI(creature) @@ -1029,6 +1022,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetHyjalAI(creature); + } }; class npc_fel_stalker : public CreatureScript @@ -1036,11 +1033,6 @@ class npc_fel_stalker : public CreatureScript public: npc_fel_stalker() : CreatureScript("npc_fel_stalker") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_fel_stalkerAI : public hyjal_trashAI { npc_fel_stalkerAI(Creature* creature) : hyjal_trashAI(creature) @@ -1115,6 +1107,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetHyjalAI(creature); + } }; class npc_frost_wyrm : public CreatureScript @@ -1122,11 +1118,6 @@ class npc_frost_wyrm : public CreatureScript public: npc_frost_wyrm() : CreatureScript("npc_frost_wyrm") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_frost_wyrmAI : public hyjal_trashAI { npc_frost_wyrmAI(Creature* creature) : hyjal_trashAI(creature) @@ -1172,7 +1163,7 @@ public: float x, y, z; me->GetPosition(x, y, z); - z = me->GetMap()->GetHeight(me->GetPhaseShift(), x, y, z); + me->UpdateGroundPositionZ(x, y, z); me->GetMotionMaster()->MovePoint(0, x, y, z); me->SetPosition(x, y, z, 0); } @@ -1235,6 +1226,11 @@ public: } else FrostBreathTimer -= diff; } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetHyjalAI(creature); + } }; class npc_gargoyle : public CreatureScript @@ -1242,11 +1238,6 @@ class npc_gargoyle : public CreatureScript public: npc_gargoyle() : CreatureScript("npc_gargoyle") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_gargoyleAI : public hyjal_trashAI { npc_gargoyleAI(Creature* creature) : hyjal_trashAI(creature) @@ -1290,7 +1281,7 @@ public: { float x, y, z; me->GetPosition(x, y, z); - z = me->GetMap()->GetHeight(me->GetPhaseShift(), x, y, z); + me->UpdateGroundPositionZ(x, y, z); me->GetMotionMaster()->MovePoint(0, x, y, z); me->SetPosition(x, y, z, 0); hyjal_trashAI::JustDied(killer); @@ -1373,6 +1364,11 @@ public: } else StrikeTimer -= diff; } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetHyjalAI(creature); + } }; class alliance_rifleman : public CreatureScript @@ -1380,11 +1376,6 @@ class alliance_rifleman : public CreatureScript public: alliance_rifleman() : CreatureScript("alliance_rifleman") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new alliance_riflemanAI(creature); - } - struct alliance_riflemanAI : public ScriptedAI { alliance_riflemanAI(Creature* creature) : ScriptedAI(creature) @@ -1446,7 +1437,11 @@ public: DoMeleeAttackIfReady(); } }; - + + CreatureAI* GetAI(Creature* creature) const override + { + return GetHyjalAI(creature); + } }; void AddSC_hyjal_trash() diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/instance_hyjal.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/instance_hyjal.cpp index 7633249c2ae..6a435318ee2 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/instance_hyjal.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/instance_hyjal.cpp @@ -24,12 +24,15 @@ SDCategory: Caverns of Time, Mount Hyjal EndScriptData */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "hyjal.h" #include "InstanceScript.h" -#include "ScriptedCreature.h" -#include "hyjal_trash.h" +#include "Log.h" +#include "Map.h" #include "Player.h" +#include "ScriptedCreature.h" #include "WorldPacket.h" -#include "Chat.h" #include "WorldSession.h" /* Battle of Mount Hyjal encounters: @@ -54,12 +57,7 @@ ObjectData const creatureData[] = class instance_hyjal : public InstanceMapScript { public: - instance_hyjal() : InstanceMapScript("instance_hyjal", 534) { } - - InstanceScript* GetInstanceScript(InstanceMap* map) const override - { - return new instance_mount_hyjal_InstanceMapScript(map); - } + instance_hyjal() : InstanceMapScript(HyjalScriptName, 534) { } struct instance_mount_hyjal_InstanceMapScript : public InstanceScript { @@ -281,7 +279,7 @@ public: return str_data; } - void Load(const char* in) override + void Load(char const* in) override { if (!in) { @@ -318,6 +316,11 @@ public: uint32 RaidDamage; bool ArchiYell; }; + + InstanceScript* GetInstanceScript(InstanceMap* map) const override + { + return new instance_mount_hyjal_InstanceMapScript(map); + } }; void AddSC_instance_mount_hyjal() diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_chrono_lord_epoch.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_chrono_lord_epoch.cpp index 97ab07f55b6..7c287a9a683 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_chrono_lord_epoch.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_chrono_lord_epoch.cpp @@ -24,8 +24,8 @@ SDCategory: Script Data End */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "culling_of_stratholme.h" +#include "ScriptedCreature.h" enum Spells { @@ -114,7 +114,7 @@ class boss_epoch : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetCullingOfStratholmeAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_infinite_corruptor.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_infinite_corruptor.cpp index ab5b114caf6..789c650b61e 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_infinite_corruptor.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_infinite_corruptor.cpp @@ -16,8 +16,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "culling_of_stratholme.h" +#include "ScriptedCreature.h" enum Spells { @@ -55,7 +55,7 @@ class boss_infinite_corruptor : public CreatureScript if (Creature* guardian = me->FindNearestCreature(NPC_GUARDIAN_OF_TIME, 100.0f)) { - DoCast((Unit*)NULL, SPELL_CORRUPTION_OF_TIME_CHANNEL, false); + DoCast((Unit*)nullptr, SPELL_CORRUPTION_OF_TIME_CHANNEL, false); guardian->CastSpell(guardian, SPELL_CORRUPTION_OF_TIME_TARGET, false); } } @@ -104,7 +104,7 @@ class boss_infinite_corruptor : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetCullingOfStratholmeAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_mal_ganis.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_mal_ganis.cpp index 09f5cac86f3..51a391b5e65 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_mal_ganis.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_mal_ganis.cpp @@ -24,9 +24,12 @@ SDCategory: Script Data End */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "culling_of_stratholme.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" enum Spells { @@ -62,11 +65,6 @@ class boss_mal_ganis : public CreatureScript public: boss_mal_ganis() : CreatureScript("boss_mal_ganis") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_mal_ganisAI : public ScriptedAI { boss_mal_ganisAI(Creature* creature) : ScriptedAI(creature) @@ -244,6 +242,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetCullingOfStratholmeAI(creature); + } }; void AddSC_boss_mal_ganis() diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_meathook.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_meathook.cpp index 8c311af424a..e264613c958 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_meathook.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_meathook.cpp @@ -16,8 +16,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "culling_of_stratholme.h" +#include "ScriptedCreature.h" enum Spells { @@ -99,7 +99,7 @@ class boss_meathook : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetCullingOfStratholmeAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_salramm_the_fleshcrafter.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_salramm_the_fleshcrafter.cpp index aef2c43b5c7..1d7d10a994d 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_salramm_the_fleshcrafter.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/boss_salramm_the_fleshcrafter.cpp @@ -16,8 +16,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "culling_of_stratholme.h" +#include "ScriptedCreature.h" enum Spells { @@ -120,7 +120,7 @@ class boss_salramm : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetCullingOfStratholmeAI(creature); } }; 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 a65e7aa7ba9..ac99940cead 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/culling_of_stratholme.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/culling_of_stratholme.cpp @@ -16,13 +16,17 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" #include "culling_of_stratholme.h" -#include "ScriptedEscortAI.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "PassiveAI.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" #include "SpellInfo.h" +#include "TemporarySummon.h" enum Says { @@ -254,11 +258,6 @@ class npc_arthas : public CreatureScript public: npc_arthas() : CreatureScript("npc_arthas") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_arthasAI : public npc_escortAI { npc_arthasAI(Creature* creature) : npc_escortAI(creature) @@ -1228,6 +1227,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetCullingOfStratholmeAI(creature); + } }; class npc_crate_helper : public CreatureScript @@ -1237,10 +1240,7 @@ class npc_crate_helper : public CreatureScript struct npc_crate_helperAI : public NullCreatureAI { - npc_crate_helperAI(Creature* creature) : NullCreatureAI(creature) - { - _marked = false; - } + npc_crate_helperAI(Creature* creature) : NullCreatureAI(creature), _marked(false) { } void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { @@ -1251,7 +1251,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, G3D::Quat(), DAY); + crate->SummonGameObject(GO_PLAGUED_CRATE, *crate, QuaternionData(), DAY); crate->Delete(); } } @@ -1263,7 +1263,7 @@ class npc_crate_helper : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_crate_helperAI(creature); + return GetCullingOfStratholmeAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/culling_of_stratholme.h b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/culling_of_stratholme.h index fc3ab0cdae8..27a13c7fe2d 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/culling_of_stratholme.h +++ b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/culling_of_stratholme.h @@ -18,8 +18,11 @@ #ifndef DEF_CULLING_OF_STRATHOLME_H #define DEF_CULLING_OF_STRATHOLME_H -#define DataHeader "CS" +#include "CreatureAIImpl.h" + #define CoSScriptName "instance_culling_of_stratholme" +#define DataHeader "CS" + uint32 const EncounterCount = 5; enum CSDataTypes @@ -100,4 +103,10 @@ enum CSInstanceEvents EVENT_INFINITE_TIMER = 1 }; +template +inline AI* GetCullingOfStratholmeAI(T* obj) +{ + return GetInstanceAI(obj, CoSScriptName); +} + #endif diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/instance_culling_of_stratholme.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/instance_culling_of_stratholme.cpp index cfdbcf5020a..e442af3c594 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/instance_culling_of_stratholme.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/CullingOfStratholme/instance_culling_of_stratholme.cpp @@ -16,12 +16,17 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" +#include "CreatureAI.h" #include "CreatureTextMgr.h" #include "culling_of_stratholme.h" +#include "EventMap.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" #include "Player.h" -#include "TemporarySummon.h" #include "SpellInfo.h" +#include "TemporarySummon.h" /* Culling of Stratholme encounters: 0 - Meathook diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_captain_skarloc.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_captain_skarloc.cpp index 6b066ab7167..846179483f5 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_captain_skarloc.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_captain_skarloc.cpp @@ -24,8 +24,9 @@ SDCategory: Caverns of Time, Old Hillsbrad Foothills EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "old_hillsbrad.h" +#include "ScriptedCreature.h" /*###################### # boss_captain_skarloc # @@ -52,11 +53,6 @@ class boss_captain_skarloc : public CreatureScript public: boss_captain_skarloc() : CreatureScript("boss_captain_skarloc") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_captain_skarlocAI : public ScriptedAI { boss_captain_skarlocAI(Creature* creature) : ScriptedAI(creature) @@ -161,6 +157,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetOldHillsbradAI(creature); + } }; void AddSC_boss_captain_skarloc() diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_epoch_hunter.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_epoch_hunter.cpp index 3ac0c244115..8ffb116f6ae 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_epoch_hunter.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_epoch_hunter.cpp @@ -24,8 +24,9 @@ SDCategory: Caverns of Time, Old Hillsbrad Foothills EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "old_hillsbrad.h" +#include "ScriptedCreature.h" /*################### # boss_epoch_hunter # @@ -50,11 +51,6 @@ class boss_epoch_hunter : public CreatureScript public: boss_epoch_hunter() : CreatureScript("boss_epoch_hunter") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_epoch_hunterAI : public ScriptedAI { boss_epoch_hunterAI(Creature* creature) : ScriptedAI(creature) @@ -143,6 +139,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetOldHillsbradAI(creature); + } }; void AddSC_boss_epoch_hunter() diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_leutenant_drake.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_leutenant_drake.cpp index 68ee56c0e40..589b98288d9 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_leutenant_drake.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/boss_leutenant_drake.cpp @@ -24,10 +24,12 @@ SDCategory: Caverns of Time, Old Hillsbrad Foothills EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "old_hillsbrad.h" #include "ScriptedEscortAI.h" -#include "GameObjectAI.h" /*###### ## go_barrel_old_hillsbrad @@ -40,27 +42,24 @@ public: struct go_barrel_old_hillsbradAI : public GameObjectAI { - go_barrel_old_hillsbradAI(GameObject* go) : GameObjectAI(go) { } + go_barrel_old_hillsbradAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* /*player*/) override { - if (InstanceScript* instance = me->GetInstanceScript()) - { - if (instance->GetData(TYPE_BARREL_DIVERSION) == DONE) - return false; - - instance->SetData(TYPE_BARREL_DIVERSION, IN_PROGRESS); - } + if (instance->GetData(TYPE_BARREL_DIVERSION) == DONE) + return false; + instance->SetData(TYPE_BARREL_DIVERSION, IN_PROGRESS); return false; } }; GameObjectAI* GetAI(GameObject* go) const override { - return new go_barrel_old_hillsbradAI(go); + return GetOldHillsbradAI(go); } - }; /*###### @@ -82,7 +81,7 @@ enum LieutenantDrake SPELL_FRIGHTENING_SHOUT = 33789 }; -G3D::Vector3 const DrakeWP[]= +Position const DrakeWP[]= { { 2125.84f, 88.2535f, 54.8830f }, { 2111.01f, 93.8022f, 52.6356f }, @@ -110,11 +109,6 @@ class boss_lieutenant_drake : public CreatureScript public: boss_lieutenant_drake() : CreatureScript("boss_lieutenant_drake") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new boss_lieutenant_drakeAI(creature); - } - struct boss_lieutenant_drakeAI : public ScriptedAI { boss_lieutenant_drakeAI(Creature* creature) : ScriptedAI(creature) @@ -166,7 +160,7 @@ public: /// @todo make this work if (CanPatrol && wpId == 0) { - me->GetMotionMaster()->MovePoint(wpId, DrakeWP[wpId].x, DrakeWP[wpId].y, DrakeWP[wpId].z); + me->GetMotionMaster()->MovePoint(wpId, DrakeWP[wpId]); ++wpId; } @@ -201,6 +195,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetOldHillsbradAI(creature); + } }; void AddSC_boss_lieutenant_drake() diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/instance_old_hillsbrad.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/instance_old_hillsbrad.cpp index b7963c30b4f..5302e7d4a2d 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/instance_old_hillsbrad.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/instance_old_hillsbrad.cpp @@ -24,10 +24,12 @@ SDCategory: Caverns of Time, Old Hillsbrad Foothills EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "InstanceScript.h" +#include "Log.h" +#include "Map.h" #include "old_hillsbrad.h" #include "Player.h" +#include "ScriptedCreature.h" #define MAX_ENCOUNTER 6 @@ -43,12 +45,7 @@ EndScriptData */ class instance_old_hillsbrad : public InstanceMapScript { public: - instance_old_hillsbrad() : InstanceMapScript("instance_old_hillsbrad", 560) { } - - InstanceScript* GetInstanceScript(InstanceMap* map) const override - { - return new instance_old_hillsbrad_InstanceMapScript(map); - } + instance_old_hillsbrad() : InstanceMapScript(OHScriptName, 560) { } struct instance_old_hillsbrad_InstanceMapScript : public InstanceScript { @@ -72,7 +69,6 @@ public: Player* GetPlayerInMap() { Map::PlayerList const& players = instance->GetPlayers(); - if (!players.isEmpty()) { for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) @@ -83,13 +79,12 @@ public: } TC_LOG_DEBUG("scripts", "Instance Old Hillsbrad: GetPlayerInMap, but PlayerList is empty!"); - return NULL; + return nullptr; } void UpdateQuestCredit() { Map::PlayerList const& players = instance->GetPlayers(); - if (!players.isEmpty()) { for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) @@ -234,6 +229,10 @@ public: } }; + InstanceScript* GetInstanceScript(InstanceMap* map) const override + { + return new instance_old_hillsbrad_InstanceMapScript(map); + } }; void AddSC_instance_old_hillsbrad() diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.cpp index dadf3d5524b..a80a0d486ba 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.cpp @@ -30,11 +30,13 @@ npc_taretha EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "old_hillsbrad.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" enum Erozion { @@ -101,7 +103,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_erozionAI(creature); + return GetOldHillsbradAI(creature); } }; @@ -196,11 +198,6 @@ class npc_thrall_old_hillsbrad : public CreatureScript public: npc_thrall_old_hillsbrad() : CreatureScript("npc_thrall_old_hillsbrad") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_thrall_old_hillsbradAI : public npc_escortAI { npc_thrall_old_hillsbradAI(Creature* creature) : npc_escortAI(creature) @@ -438,7 +435,7 @@ public: case 106: { //trigger taretha to run down outside - if (Creature* Taretha = instance->instance->GetCreature(instance->GetGuidData(DATA_TARETHA))) + if (Creature* Taretha = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_TARETHA))) { if (Player* player = GetPlayerForEscort()) ENSURE_AI(npc_escortAI, (Taretha->AI()))->Start(false, true, player->GetGUID()); @@ -556,6 +553,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetOldHillsbradAI(creature); + } }; /*###### @@ -575,11 +576,6 @@ class npc_taretha : public CreatureScript public: npc_taretha() : CreatureScript("npc_taretha") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_tarethaAI : public npc_escortAI { npc_tarethaAI(Creature* creature) : npc_escortAI(creature) @@ -648,6 +644,11 @@ public: npc_escortAI::UpdateAI(diff); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetOldHillsbradAI(creature); + } }; /*###### diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.h b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.h index 971d3e19c57..f3d17c75d4b 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.h +++ b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/old_hillsbrad.h @@ -19,6 +19,9 @@ #ifndef DEF_OLD_HILLSBRAD_H #define DEF_OLD_HILLSBRAD_H +#include "CreatureAIImpl.h" + +#define OHScriptName "instance_old_hillsbrad" #define DataHeader "OH" enum OHDataTypes @@ -41,4 +44,10 @@ enum OHWorldStateIds WORLD_STATE_OH = 2436 }; +template +inline AI* GetOldHillsbradAI(T* obj) +{ + return GetInstanceAI(obj, OHScriptName); +} + #endif diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_aeonus.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_aeonus.cpp index 962becd5386..b785aa0fb50 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_aeonus.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_aeonus.cpp @@ -24,6 +24,7 @@ Category: Caverns of Time, The Dark Portal */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "the_black_morass.h" @@ -79,7 +80,7 @@ public: if (me->IsWithinDistInMap(who, 20.0f)) { Talk(SAY_BANISH); - me->DealDamage(who, who->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + me->DealDamage(who, who->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); } } @@ -141,7 +142,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackMorassAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_chrono_lord_deja.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_chrono_lord_deja.cpp index 46f60b4747b..b2c89dbe4cc 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_chrono_lord_deja.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_chrono_lord_deja.cpp @@ -24,6 +24,7 @@ Category: Caverns of Time, The Black Morass */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "the_black_morass.h" @@ -82,7 +83,7 @@ public: if (me->IsWithinDistInMap(who, 20.0f)) { Talk(SAY_BANISH); - me->DealDamage(who, who->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + me->DealDamage(who, who->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); } } @@ -147,7 +148,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackMorassAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_temporus.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_temporus.cpp index 63894490648..8fa88ea7721 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_temporus.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/boss_temporus.cpp @@ -24,6 +24,7 @@ Category: Caverns of Time, The Black Morass */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "the_black_morass.h" @@ -94,7 +95,7 @@ public: { Talk(SAY_BANISH); - me->DealDamage(who, who->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + me->DealDamage(who, who->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); } } @@ -145,7 +146,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetBlackMorassAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/instance_the_black_morass.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/instance_the_black_morass.cpp index 789dd0189a5..1df6ad1e358 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/instance_the_black_morass.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/instance_the_black_morass.cpp @@ -25,11 +25,13 @@ Category: Caverns of Time, The Black Morass #include "ScriptMgr.h" #include "InstanceScript.h" -#include "the_black_morass.h" +#include "Log.h" +#include "Map.h" #include "Player.h" -#include "TemporarySummon.h" -#include "SpellInfo.h" #include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "TemporarySummon.h" +#include "the_black_morass.h" enum Misc { @@ -71,12 +73,7 @@ enum EventIds class instance_the_black_morass : public InstanceMapScript { public: - instance_the_black_morass() : InstanceMapScript("instance_the_black_morass", 269) { } - - InstanceScript* GetInstanceScript(InstanceMap* map) const override - { - return new instance_the_black_morass_InstanceMapScript(map); - } + instance_the_black_morass() : InstanceMapScript(TBMScriptName, 269) { } struct instance_the_black_morass_InstanceMapScript : public InstanceScript { @@ -180,7 +177,7 @@ public: { if (medivh->IsAlive()) { - medivh->DealDamage(medivh, medivh->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + medivh->DealDamage(medivh, medivh->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); m_auiEncounter[0] = FAIL; m_auiEncounter[1] = NOT_STARTED; } @@ -276,7 +273,7 @@ public: return summon; TC_LOG_DEBUG("scripts", "Instance The Black Morass: What just happened there? No boss, no loot, no fun..."); - return NULL; + return nullptr; } void DoSpawnPortal() @@ -347,6 +344,10 @@ public: EventMap Events; }; + InstanceScript* GetInstanceScript(InstanceMap* map) const override + { + return new instance_the_black_morass_InstanceMapScript(map); + } }; void AddSC_instance_the_black_morass() diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/the_black_morass.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/the_black_morass.cpp index 36a53162a23..d11a08ddbcc 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/the_black_morass.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/the_black_morass.cpp @@ -17,11 +17,15 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Log.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "the_black_morass.h" -#include "Player.h" #include "SpellInfo.h" +#include "the_black_morass.h" enum MedivhBm { @@ -55,11 +59,6 @@ class npc_medivh_bm : public CreatureScript public: npc_medivh_bm() : CreatureScript("npc_medivh_bm") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_medivh_bmAI : public ScriptedAI { npc_medivh_bmAI(Creature* creature) : ScriptedAI(creature) @@ -139,7 +138,7 @@ public: void JustEngagedWith(Unit* /*who*/) override { } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (SpellCorrupt_Timer) return; @@ -203,7 +202,7 @@ public: //if we reach this it means event was running but at some point reset. if (instance->GetData(TYPE_MEDIVH) == NOT_STARTED) { - 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(); me->Respawn(); return; @@ -230,6 +229,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetBlackMorassAI(creature); + } }; struct Wave @@ -249,11 +252,6 @@ class npc_time_rift : public CreatureScript public: npc_time_rift() : CreatureScript("npc_time_rift") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_time_riftAI : public ScriptedAI { npc_time_riftAI(Creature* creature) : ScriptedAI(creature) @@ -350,6 +348,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetBlackMorassAI(creature); + } }; void AddSC_the_black_morass() diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/the_black_morass.h b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/the_black_morass.h index 8d477aaf473..edc26cf2e24 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/the_black_morass.h +++ b/src/server/scripts/Kalimdor/CavernsOfTime/TheBlackMorass/the_black_morass.h @@ -19,6 +19,9 @@ #ifndef DEF_THEBLACKMORASS_H #define DEF_THEBLACKMORASS_H +#include "CreatureAIImpl.h" + +#define TBMScriptName "instance_the_black_morass" #define DataHeader "TBM" uint32 const EncounterCount = 2; @@ -65,4 +68,10 @@ enum TBMCreatureIds NPC_INFINITE_VANQUISHER = 18995 }; +template +inline AI* GetBlackMorassAI(T* obj) +{ + return GetInstanceAI(obj, TBMScriptName); +} + #endif diff --git a/src/server/scripts/Kalimdor/DireMaul/instance_dire_maul.cpp b/src/server/scripts/Kalimdor/DireMaul/instance_dire_maul.cpp index cf2a3e1f771..0da7953208f 100644 --- a/src/server/scripts/Kalimdor/DireMaul/instance_dire_maul.cpp +++ b/src/server/scripts/Kalimdor/DireMaul/instance_dire_maul.cpp @@ -24,6 +24,7 @@ gets instead the deserter debuff. #include "ScriptMgr.h" #include "InstanceScript.h" +#include "Map.h" // Bosses (East) // 0 - Pusillin diff --git a/src/server/scripts/Kalimdor/Firelands/boss_alysrazor.cpp b/src/server/scripts/Kalimdor/Firelands/boss_alysrazor.cpp index faa94906e48..e1d20d9dd74 100644 --- a/src/server/scripts/Kalimdor/Firelands/boss_alysrazor.cpp +++ b/src/server/scripts/Kalimdor/Firelands/boss_alysrazor.cpp @@ -15,17 +15,19 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "PassiveAI.h" -#include "SpellScript.h" -#include "MoveSplineInit.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" +#include "DBCStores.h" #include "firelands.h" +#include "GridNotifiersImpl.h" +#include "MotionMaster.h" +#include "MoveSplineInit.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "PassiveAI.h" +#include "ScriptedCreature.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum Texts { @@ -357,9 +359,7 @@ class npc_molten_barrage : public CreatureScript struct npc_molten_barrageAI : public NullCreatureAI { - npc_molten_barrageAI(Creature* creature) : NullCreatureAI(creature) - { - } + npc_molten_barrageAI(Creature* creature) : NullCreatureAI(creature) { } void AttackStart(Unit* target) override { @@ -541,17 +541,7 @@ class spell_alysrazor_turn_monstrosity : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GENERIC_DUMMY_CAST)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_KNOCKBACK_RIGHT)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_KNOCKBACK_LEFT)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_KNOCKBACK_FORWARD)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_KNOCKBACK_BACK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_GENERIC_DUMMY_CAST, SPELL_KNOCKBACK_RIGHT, SPELL_KNOCKBACK_LEFT, SPELL_KNOCKBACK_FORWARD, SPELL_KNOCKBACK_BACK }); } void KnockBarrage(SpellEffIndex effIndex) @@ -670,9 +660,7 @@ class spell_alysrazor_fieroblast : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FIRE_IT_UP)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FIRE_IT_UP }); } void FireItUp() diff --git a/src/server/scripts/Kalimdor/Firelands/boss_baleroc.cpp b/src/server/scripts/Kalimdor/Firelands/boss_baleroc.cpp index 927640be07b..bd98cb6dfff 100644 --- a/src/server/scripts/Kalimdor/Firelands/boss_baleroc.cpp +++ b/src/server/scripts/Kalimdor/Firelands/boss_baleroc.cpp @@ -22,13 +22,17 @@ ***Implement Vital Flame - http://www.wowhead.com/spell=99263 */ -#include "GridNotifiers.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "Player.h" #include "firelands.h" +#include "GridNotifiers.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Spells { @@ -470,7 +474,7 @@ class spell_countdown_p2 : public SpellScriptLoader void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { if (GetTargetApplication()->GetRemoveMode() == AURA_REMOVE_BY_EXPIRE) - GetTarget()->CastSpell((Unit*)NULL, SPELL_COUNTDOWN_4, true); + GetTarget()->CastSpell((Unit*)nullptr, SPELL_COUNTDOWN_4, true); GetTarget()->ToPlayer()->RemoveAurasDueToSpell(SPELL_COUNTDOWN_5); } @@ -548,9 +552,7 @@ class spell_decimating_strike : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DECIMATING_STRIKE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DECIMATING_STRIKE }); } void ChangeDamage() diff --git a/src/server/scripts/Kalimdor/Firelands/firelands.h b/src/server/scripts/Kalimdor/Firelands/firelands.h index 1681156a8df..e236a46e4bc 100644 --- a/src/server/scripts/Kalimdor/Firelands/firelands.h +++ b/src/server/scripts/Kalimdor/Firelands/firelands.h @@ -18,8 +18,7 @@ #ifndef FIRELANDS_H_ #define FIRELANDS_H_ -#include "Map.h" -#include "CreatureAI.h" +#include "CreatureAIImpl.h" #define DataHeader "FL" #define FirelandsScriptName "instance_firelands" @@ -66,29 +65,10 @@ enum GameobjectIds GO_RAGNAROS_DOOR = 209073, }; -class DelayedAttackStartEvent : public BasicEvent +template +inline AI* GetFirelandsAI(T* obj) { - public: - DelayedAttackStartEvent(Creature* owner) : _owner(owner) { } - - bool Execute(uint64 /*e_time*/, uint32 /*p_time*/) - { - _owner->AI()->DoZoneInCombat(_owner, 200.0f); - return true; - } - - private: - Creature* _owner; -}; - -template -CreatureAI* GetFirelandsAI(Creature* creature) -{ - if (InstanceMap* instance = creature->GetMap()->ToInstanceMap()) - if (instance->GetInstanceScript()) - if (instance->GetScriptId() == sObjectMgr->GetScriptId(FirelandsScriptName)) - return new AI(creature); - return NULL; + return GetInstanceAI(obj, FirelandsScriptName); } #endif // FIRELANDS_H_ diff --git a/src/server/scripts/Kalimdor/Firelands/instance_firelands.cpp b/src/server/scripts/Kalimdor/Firelands/instance_firelands.cpp index dd703a7ca97..8330713539a 100644 --- a/src/server/scripts/Kalimdor/Firelands/instance_firelands.cpp +++ b/src/server/scripts/Kalimdor/Firelands/instance_firelands.cpp @@ -16,8 +16,27 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "EventProcessor.h" #include "firelands.h" +#include "InstanceScript.h" +#include "Map.h" + +class DelayedAttackStartEvent : public BasicEvent +{ + public: + DelayedAttackStartEvent(Creature* owner) : _owner(owner) { } + + bool Execute(uint64 /*e_time*/, uint32 /*p_time*/) override + { + _owner->AI()->DoZoneInCombat(_owner, 200.0f); + return true; + } + + private: + Creature* _owner; +}; DoorData const doorData[] = { diff --git a/src/server/scripts/Kalimdor/HallsOfOrigination/boss_anraphet.cpp b/src/server/scripts/Kalimdor/HallsOfOrigination/boss_anraphet.cpp index d8eb7629658..2aaf60c3251 100644 --- a/src/server/scripts/Kalimdor/HallsOfOrigination/boss_anraphet.cpp +++ b/src/server/scripts/Kalimdor/HallsOfOrigination/boss_anraphet.cpp @@ -15,15 +15,14 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "GridNotifiers.h" -#include "Player.h" -#include "ObjectAccessor.h" #include "halls_of_origination.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellScript.h" enum Texts { @@ -543,7 +542,8 @@ public: float x = caster->GetPositionX() + dist * std::cos(angle); float y = caster->GetPositionY() + dist * std::sin(angle); - float z = caster->GetMap()->GetHeight(caster->GetPhaseShift(), x, y, caster->GetPositionZ()); + float z = caster->GetPositionZ(); + caster->UpdateGroundPositionZ(x, y, z); const_cast(GetExplTargetDest())->Relocate(x, y, z); GetHitDest()->Relocate(x, y, z); diff --git a/src/server/scripts/Kalimdor/HallsOfOrigination/boss_earthrager_ptah.cpp b/src/server/scripts/Kalimdor/HallsOfOrigination/boss_earthrager_ptah.cpp index de736261382..938149b5337 100644 --- a/src/server/scripts/Kalimdor/HallsOfOrigination/boss_earthrager_ptah.cpp +++ b/src/server/scripts/Kalimdor/HallsOfOrigination/boss_earthrager_ptah.cpp @@ -15,15 +15,14 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" +#include "halls_of_origination.h" +#include "InstanceScript.h" +#include "Map.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "Player.h" +#include "TemporarySummon.h" #include "Weather.h" -#include "WorldSession.h" -#include "halls_of_origination.h" enum Texts { @@ -76,7 +75,7 @@ class SummonScarab : public BasicEvent public: SummonScarab(Unit* owner, InstanceScript* instance) : _owner(owner), _instance(instance) { } - bool Execute(uint64 /*execTime*/, uint32 /*diff*/) + bool Execute(uint64 /*execTime*/, uint32 /*diff*/) override { if (!_instance || _instance->GetBossState(DATA_EARTHRAGER_PTAH) != IN_PROGRESS) return true; // delete event diff --git a/src/server/scripts/Kalimdor/HallsOfOrigination/boss_rajh.cpp b/src/server/scripts/Kalimdor/HallsOfOrigination/boss_rajh.cpp index 6276f287a96..53cc8f47808 100644 --- a/src/server/scripts/Kalimdor/HallsOfOrigination/boss_rajh.cpp +++ b/src/server/scripts/Kalimdor/HallsOfOrigination/boss_rajh.cpp @@ -15,15 +15,15 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "GridNotifiers.h" -#include "Player.h" -#include "ObjectAccessor.h" #include "halls_of_origination.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellScript.h" enum Spells { diff --git a/src/server/scripts/Kalimdor/HallsOfOrigination/boss_temple_guardian_anhuur.cpp b/src/server/scripts/Kalimdor/HallsOfOrigination/boss_temple_guardian_anhuur.cpp index 8a183c8efa0..238953a86bf 100644 --- a/src/server/scripts/Kalimdor/HallsOfOrigination/boss_temple_guardian_anhuur.cpp +++ b/src/server/scripts/Kalimdor/HallsOfOrigination/boss_temple_guardian_anhuur.cpp @@ -15,14 +15,16 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" #include "GridNotifiers.h" -#include "Player.h" #include "halls_of_origination.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Texts { diff --git a/src/server/scripts/Kalimdor/HallsOfOrigination/halls_of_origination.h b/src/server/scripts/Kalimdor/HallsOfOrigination/halls_of_origination.h index bcb3e727337..d496c38e9a5 100644 --- a/src/server/scripts/Kalimdor/HallsOfOrigination/halls_of_origination.h +++ b/src/server/scripts/Kalimdor/HallsOfOrigination/halls_of_origination.h @@ -18,6 +18,8 @@ #ifndef HALLS_OF_ORIGINATION_H #define HALLS_OF_ORIGINATION_H +#include "CreatureAIImpl.h" + #define DataHeader "HOO" #define HoOScriptName "instance_halls_of_origination" @@ -119,14 +121,10 @@ enum HOOGlobalActions ACTION_OMEGA_TRIGGER, }; -template -CreatureAI* GetHallsOfOriginationAI(Creature* creature) +template +inline AI* GetHallsOfOriginationAI(T* obj) { - if (InstanceMap* instance = creature->GetMap()->ToInstanceMap()) - if (instance->GetInstanceScript()) - if (instance->GetScriptId() == sObjectMgr->GetScriptId(HoOScriptName)) - return new AI(creature); - return NULL; + return GetInstanceAI(obj, HoOScriptName); } #endif // HALLS_OF_ORIGINATION_H diff --git a/src/server/scripts/Kalimdor/LostCityOfTheTolvir/boss_general_husam.cpp b/src/server/scripts/Kalimdor/LostCityOfTheTolvir/boss_general_husam.cpp index b1bb7ed2edf..7de5165aa07 100644 --- a/src/server/scripts/Kalimdor/LostCityOfTheTolvir/boss_general_husam.cpp +++ b/src/server/scripts/Kalimdor/LostCityOfTheTolvir/boss_general_husam.cpp @@ -15,14 +15,16 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "Player.h" -#include "Vehicle.h" +#include "InstanceScript.h" #include "lost_city_of_the_tolvir.h" +#include "MotionMaster.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "Vehicle.h" enum Spells { @@ -400,10 +402,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHOCKWAVE_VISUAL)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_SHOCKWAVE_VISUAL }); } void EffectScriptEffect(SpellEffIndex /*effIndex*/) @@ -434,10 +433,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHOCKWAVE_SUMMON_EFFECT)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_SHOCKWAVE_SUMMON_EFFECT }); } void FilterTargets(std::list& targets) diff --git a/src/server/scripts/Kalimdor/LostCityOfTheTolvir/boss_high_prophet_barim.cpp b/src/server/scripts/Kalimdor/LostCityOfTheTolvir/boss_high_prophet_barim.cpp index cb6b0a966e1..a275c8a4306 100644 --- a/src/server/scripts/Kalimdor/LostCityOfTheTolvir/boss_high_prophet_barim.cpp +++ b/src/server/scripts/Kalimdor/LostCityOfTheTolvir/boss_high_prophet_barim.cpp @@ -17,7 +17,10 @@ #include "ScriptMgr.h" #include "lost_city_of_the_tolvir.h" -#include "ObjectMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "MovementTypedefs.h" +#include "PassiveAI.h" #include "PhasingHandler.h" #include "Player.h" #include "ScriptedCreature.h" diff --git a/src/server/scripts/Kalimdor/LostCityOfTheTolvir/boss_lockmaw_and_augh.cpp b/src/server/scripts/Kalimdor/LostCityOfTheTolvir/boss_lockmaw_and_augh.cpp index e60b5e2f454..8372e9f6060 100644 --- a/src/server/scripts/Kalimdor/LostCityOfTheTolvir/boss_lockmaw_and_augh.cpp +++ b/src/server/scripts/Kalimdor/LostCityOfTheTolvir/boss_lockmaw_and_augh.cpp @@ -16,11 +16,12 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "lost_city_of_the_tolvir.h" -#include "ObjectMgr.h" +#include "MotionMaster.h" #include "Player.h" #include "ScriptedCreature.h" -#include "SpellAuraEffects.h" +#include "SpellInfo.h" #include "SpellScript.h" enum Texts @@ -107,15 +108,15 @@ enum Actions Position const AughMovePoint = { -11062.5f, -1662.39f, 0.7606202f, 0.8028514f }; -class ScentOfBloodTargetSelector : public std::unary_function +class ScentOfBloodTargetSelector { -public: - ScentOfBloodTargetSelector() { } + public: + ScentOfBloodTargetSelector() { } - bool operator()(Unit* unit) const - { - return (!unit->HasAura(SPELL_SCENT_OF_BLOOD) || !unit->HasAura(SPELL_SCENT_OF_BLOOD_HC)); - } + bool operator()(Unit* unit) const + { + return (!unit->HasAura(SPELL_SCENT_OF_BLOOD) || !unit->HasAura(SPELL_SCENT_OF_BLOOD_HC)); + } }; class boss_lockmaw : public CreatureScript diff --git a/src/server/scripts/Kalimdor/LostCityOfTheTolvir/instance_lost_city_of_the_tolvir.cpp b/src/server/scripts/Kalimdor/LostCityOfTheTolvir/instance_lost_city_of_the_tolvir.cpp index 55a648390b3..fe59ecd53a3 100644 --- a/src/server/scripts/Kalimdor/LostCityOfTheTolvir/instance_lost_city_of_the_tolvir.cpp +++ b/src/server/scripts/Kalimdor/LostCityOfTheTolvir/instance_lost_city_of_the_tolvir.cpp @@ -16,8 +16,15 @@ */ #include "ScriptMgr.h" +#include "Containers.h" +#include "CreatureAI.h" +#include "EventMap.h" +#include "GameObject.h" #include "InstanceScript.h" #include "lost_city_of_the_tolvir.h" +#include "Map.h" +#include "TemporarySummon.h" +#include "Weather.h" enum TimedEvents { diff --git a/src/server/scripts/Kalimdor/LostCityOfTheTolvir/lost_city_of_the_tolvir.h b/src/server/scripts/Kalimdor/LostCityOfTheTolvir/lost_city_of_the_tolvir.h index ca9b22bed3e..b2937b0e168 100644 --- a/src/server/scripts/Kalimdor/LostCityOfTheTolvir/lost_city_of_the_tolvir.h +++ b/src/server/scripts/Kalimdor/LostCityOfTheTolvir/lost_city_of_the_tolvir.h @@ -18,6 +18,8 @@ #ifndef LOST_CITY_OF_THE_TOLVIR_H_ #define LOST_CITY_OF_THE_TOLVIR_H_ +#include "CreatureAIImpl.h" + #define LCTScriptName "instance_lost_city_of_the_tolvir" #define DataHeader "LCT" @@ -85,10 +87,10 @@ enum LCTMisc ASSISTANCE_SUMMON_CROCOLISKS = 3 }; -template -AI* GetLostCityOfTheTolvirAI(Creature* creature) +template +inline AI* GetLostCityOfTheTolvirAI(T* obj) { - return GetInstanceAI(creature, LCTScriptName); + return GetInstanceAI(obj, LCTScriptName); } #endif // LOST_CITY_OF_THE_TOLVIR_H_ diff --git a/src/server/scripts/Kalimdor/Maraudon/instance_maraudon.cpp b/src/server/scripts/Kalimdor/Maraudon/instance_maraudon.cpp index d1e07046124..e796309cfcc 100644 --- a/src/server/scripts/Kalimdor/Maraudon/instance_maraudon.cpp +++ b/src/server/scripts/Kalimdor/Maraudon/instance_maraudon.cpp @@ -24,6 +24,7 @@ gets instead the deserter debuff. #include "ScriptMgr.h" #include "InstanceScript.h" +#include "Map.h" class instance_maraudon : public InstanceMapScript { diff --git a/src/server/scripts/Kalimdor/OnyxiasLair/boss_onyxia.cpp b/src/server/scripts/Kalimdor/OnyxiasLair/boss_onyxia.cpp index 4d89d8f94b4..2e76a456f5d 100644 --- a/src/server/scripts/Kalimdor/OnyxiasLair/boss_onyxia.cpp +++ b/src/server/scripts/Kalimdor/OnyxiasLair/boss_onyxia.cpp @@ -26,12 +26,14 @@ SDCategory: Onyxia's Lair EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "onyxias_lair.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Yells { @@ -194,7 +196,7 @@ public: Talk(SAY_KILL); } - void SpellHit(Unit* /*pCaster*/, const SpellInfo* Spell) override + void SpellHit(Unit* /*pCaster*/, SpellInfo const* Spell) override { if (Spell->Id == SPELL_BREATH_EAST_TO_WEST || Spell->Id == SPELL_BREATH_WEST_TO_EAST || @@ -272,7 +274,7 @@ public: } } - void SpellHitTarget(Unit* target, const SpellInfo* Spell) override + void SpellHitTarget(Unit* target, SpellInfo const* Spell) override { //Workaround - Couldn't find a way to group this spells (All Eruption) if (((Spell->Id >= 17086 && Spell->Id <= 17095) || @@ -302,7 +304,7 @@ public: return &MoveData[i]; } - return NULL; + return nullptr; } void SetNextRandomPoint() @@ -354,7 +356,7 @@ public: { DoCastVictim(SPELL_BELLOWING_ROAR); // Eruption - GameObject* Floor = NULL; + GameObject* Floor = nullptr; Trinity::GameObjectInRangeCheck check(me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), 15); Trinity::GameObjectLastSearcher searcher(me, Floor, check); Cell::VisitGridObjects(me, searcher, 30.0f); @@ -493,7 +495,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetOnyxiaAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/OnyxiasLair/instance_onyxias_lair.cpp b/src/server/scripts/Kalimdor/OnyxiasLair/instance_onyxias_lair.cpp index 0252e241e26..38a72738af2 100644 --- a/src/server/scripts/Kalimdor/OnyxiasLair/instance_onyxias_lair.cpp +++ b/src/server/scripts/Kalimdor/OnyxiasLair/instance_onyxias_lair.cpp @@ -23,11 +23,10 @@ SDCategory: Onyxia's Lair EndScriptData */ #include "ScriptMgr.h" -#include "InstanceScript.h" -#include "Cell.h" +#include "AreaBoundary.h" #include "CellImpl.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" +#include "InstanceScript.h" #include "onyxias_lair.h" #include "TemporarySummon.h" @@ -39,7 +38,7 @@ BossBoundaryData const boundaries = class instance_onyxias_lair : public InstanceMapScript { public: - instance_onyxias_lair() : InstanceMapScript("instance_onyxias_lair", 249) { } + instance_onyxias_lair() : InstanceMapScript(OnyxiaScriptName, 249) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { @@ -112,7 +111,7 @@ public: //THIS GOB IS A TRAP - What shall i do? =( //Cast it spell? Copyed Heigan method floorEruption->SendCustomAnim(floorEruption->GetGoAnimProgress()); - floorEruption->CastSpell(NULL, Difficulty(instance->GetSpawnMode()) == RAID_DIFFICULTY_10MAN_NORMAL ? 17731 : 69294); //pFloorEruption->GetGOInfo()->trap.spellId + floorEruption->CastSpell(nullptr, Difficulty(instance->GetSpawnMode()) == RAID_DIFFICULTY_10MAN_NORMAL ? 17731 : 69294); //pFloorEruption->GetGOInfo()->trap.spellId //Get all immediatly nearby floors std::list nearFloorList; @@ -240,7 +239,7 @@ public: } } - bool CheckAchievementCriteriaMeet(uint32 criteriaId, Player const* /*source*/, Unit const* /*target = NULL*/, uint32 /*miscValue1 = 0*/) override + bool CheckAchievementCriteriaMeet(uint32 criteriaId, Player const* /*source*/, Unit const* /*target = nullptr*/, uint32 /*miscValue1 = 0*/) override { switch (criteriaId) { diff --git a/src/server/scripts/Kalimdor/OnyxiasLair/onyxias_lair.h b/src/server/scripts/Kalimdor/OnyxiasLair/onyxias_lair.h index 8a934dedcd6..ab47f26c69a 100644 --- a/src/server/scripts/Kalimdor/OnyxiasLair/onyxias_lair.h +++ b/src/server/scripts/Kalimdor/OnyxiasLair/onyxias_lair.h @@ -18,6 +18,9 @@ #ifndef DEF_ONYXIAS_LAIR_H #define DEF_ONYXIAS_LAIR_H +#include "CreatureAIImpl.h" + +#define OnyxiaScriptName "instance_onyxias_lair" #define DataHeader "OL" uint32 const EncounterCount = 1; @@ -69,4 +72,11 @@ enum OLAchievementData ACHIEV_CRITERIA_DEEP_BREATH_25_PLAYER = 12569, // Criteria for achievement 4407: She Deep Breaths More (25 player) Everybody evade Deep Breath ACHIEV_TIMED_START_EVENT = 6601, // Timed event for achievement 4402, 4005: More Dots! (10, 25 player) 5 min kill }; + +template +inline AI* GetOnyxiaAI(T* obj) +{ + return GetInstanceAI(obj, OnyxiaScriptName); +} + #endif diff --git a/src/server/scripts/Kalimdor/RagefireChasm/instance_ragefire_chasm.cpp b/src/server/scripts/Kalimdor/RagefireChasm/instance_ragefire_chasm.cpp index 08a77673847..bef26ca0864 100644 --- a/src/server/scripts/Kalimdor/RagefireChasm/instance_ragefire_chasm.cpp +++ b/src/server/scripts/Kalimdor/RagefireChasm/instance_ragefire_chasm.cpp @@ -24,6 +24,7 @@ gets instead the deserter debuff. #include "ScriptMgr.h" #include "InstanceScript.h" +#include "Map.h" class instance_ragefire_chasm : public InstanceMapScript { diff --git a/src/server/scripts/Kalimdor/RazorfenDowns/instance_razorfen_downs.cpp b/src/server/scripts/Kalimdor/RazorfenDowns/instance_razorfen_downs.cpp index 8e3ceda7425..1187075dee6 100644 --- a/src/server/scripts/Kalimdor/RazorfenDowns/instance_razorfen_downs.cpp +++ b/src/server/scripts/Kalimdor/RazorfenDowns/instance_razorfen_downs.cpp @@ -16,10 +16,11 @@ */ #include "ScriptMgr.h" -#include "ObjectMgr.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" #include "razorfen_downs.h" -#include "Player.h" #include "TemporarySummon.h" Position const PosSummonTutenkash[15] = diff --git a/src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.cpp b/src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.cpp index c5a201bfc0b..767051ad524 100644 --- a/src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.cpp +++ b/src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.cpp @@ -28,15 +28,17 @@ npc_henry_stern EndContentData */ #include "ScriptMgr.h" +#include "CellImpl.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "Player.h" +#include "razorfen_downs.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "razorfen_downs.h" -#include "Player.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "Cell.h" -#include "CellImpl.h" -#include "GameObjectAI.h" +#include "TemporarySummon.h" /*### ## npc_belnistrasz for Quest 3525 "Extinguishing the Idol" @@ -203,7 +205,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, G3D::Quat(0.f, 0.f, 0.9238796f, 0.3826832f), 3600); + me->SummonGameObject(GO_BELNISTRASZS_BRAZIER, 2577.196f, 947.0781f, 53.16757f, 2.356195f, QuaternionData(0.f, 0.f, 0.9238796f, 0.3826832f), 3600); std::list ClusterList; Trinity::AllWorldObjectsInRange objects(me, 50.0f); Trinity::WorldObjectListSearcher searcher(me, ClusterList, objects); @@ -254,7 +256,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetRazorfenDownsAI(creature); } }; @@ -292,7 +294,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetRazorfenDownsAI(creature); } }; @@ -362,7 +364,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetRazorfenDownsAI(creature); } }; @@ -377,25 +379,21 @@ class go_gong : public GameObjectScript struct go_gongAI : public GameObjectAI { - go_gongAI(GameObject* go) : GameObjectAI(go) { } + go_gongAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* /*player*/) override { - InstanceScript* instance = me->GetInstanceScript(); - - if (instance) - { - me->SendCustomAnim(0); - instance->SetData(DATA_WAVE, IN_PROGRESS); - return true; - } - return false; + me->SendCustomAnim(0); + instance->SetData(DATA_WAVE, IN_PROGRESS); + return true; } }; GameObjectAI* GetAI(GameObject* go) const override { - return new go_gongAI(go); + return GetRazorfenDownsAI(go); } }; diff --git a/src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.h b/src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.h index a9840663884..b0541045a87 100644 --- a/src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.h +++ b/src/server/scripts/Kalimdor/RazorfenDowns/razorfen_downs.h @@ -18,6 +18,8 @@ #ifndef DEF_RAZORFEN_DOWNS_H #define DEF_RAZORFEN_DOWNS_H +#include "CreatureAIImpl.h" + #define RFDScriptName "instance_razorfen_downs" #define DataHeader "RFD" @@ -61,10 +63,10 @@ enum RFDGameObjectIds GO_BELNISTRASZS_BRAZIER = 152097 }; -template -AI* GetRazorfenDownsAI(Creature* creature) +template +inline AI* GetRazorfenDownsAI(T* obj) { - return GetInstanceAI(creature, RFDScriptName); + return GetInstanceAI(obj, RFDScriptName); } #endif diff --git a/src/server/scripts/Kalimdor/RazorfenKraul/instance_razorfen_kraul.cpp b/src/server/scripts/Kalimdor/RazorfenKraul/instance_razorfen_kraul.cpp index c22bbcfa2b1..9a141e95db6 100644 --- a/src/server/scripts/Kalimdor/RazorfenKraul/instance_razorfen_kraul.cpp +++ b/src/server/scripts/Kalimdor/RazorfenKraul/instance_razorfen_kraul.cpp @@ -24,9 +24,12 @@ SDCategory: Razorfen Kraul EndScriptData */ #include "ScriptMgr.h" +#include "GameObject.h" #include "InstanceScript.h" -#include "razorfen_kraul.h" +#include "Log.h" +#include "Map.h" #include "Player.h" +#include "razorfen_kraul.h" #define WARD_KEEPERS_NR 2 @@ -35,11 +38,6 @@ class instance_razorfen_kraul : public InstanceMapScript public: instance_razorfen_kraul() : InstanceMapScript("instance_razorfen_kraul", 47) { } - InstanceScript* GetInstanceScript(InstanceMap* map) const override - { - return new instance_razorfen_kraul_InstanceMapScript(map); - } - struct instance_razorfen_kraul_InstanceMapScript : public InstanceScript { instance_razorfen_kraul_InstanceMapScript(Map* map) : InstanceScript(map) @@ -60,7 +58,7 @@ public: return player; } TC_LOG_DEBUG("scripts", "Instance Razorfen Kraul: GetPlayerInMap, but PlayerList is empty!"); - return NULL; + return nullptr; } void OnGameObjectCreate(GameObject* go) override @@ -89,9 +87,12 @@ public: case EVENT_WARD_KEEPER: WardKeeperDeath++; break; } } - }; + InstanceScript* GetInstanceScript(InstanceMap* map) const override + { + return new instance_razorfen_kraul_InstanceMapScript(map); + } }; void AddSC_instance_razorfen_kraul() diff --git a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_ayamiss.cpp b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_ayamiss.cpp index c24d27096b9..bfcba6d7203 100644 --- a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_ayamiss.cpp +++ b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_ayamiss.cpp @@ -17,9 +17,12 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" #include "ruins_of_ahnqiraj.h" +#include "ScriptedCreature.h" enum Spells { @@ -208,7 +211,7 @@ class boss_ayamiss : public CreatureScript break; case EVENT_SWARMER_ATTACK: for (GuidList::iterator i = _swarmers.begin(); i != _swarmers.end(); ++i) - if (Creature* swarmer = me->GetMap()->GetCreature(*i)) + if (Creature* swarmer = ObjectAccessor::GetCreature(*me, *i)) if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM)) swarmer->AI()->AttackStart(target); @@ -241,7 +244,7 @@ class boss_ayamiss : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAQ20AI(creature); } }; @@ -295,7 +298,7 @@ class npc_hive_zara_larva : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAQ20AI(creature); } }; diff --git a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_buru.cpp b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_buru.cpp index 846739ee566..814209804a7 100644 --- a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_buru.cpp +++ b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_buru.cpp @@ -17,9 +17,11 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ruins_of_ahnqiraj.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "ruins_of_ahnqiraj.h" enum Emotes { @@ -77,7 +79,7 @@ class boss_buru : public CreatureScript BossAI::EnterEvadeMode(why); for (ObjectGuid eggGuid : Eggs) - if (Creature* egg = me->GetMap()->GetCreature(eggGuid)) + if (Creature* egg = ObjectAccessor::GetCreature(*me, eggGuid)) egg->Respawn(); Eggs.clear(); @@ -161,7 +163,7 @@ class boss_buru : public CreatureScript events.ScheduleEvent(EVENT_CREEPING_PLAGUE, 6000); break; case EVENT_RESPAWN_EGG: - if (Creature* egg = me->GetMap()->GetCreature(*Eggs.begin())) + if (Creature* egg = ObjectAccessor::GetCreature(*me, *Eggs.begin())) { egg->Respawn(); Eggs.pop_front(); @@ -189,7 +191,7 @@ class boss_buru : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_buruAI(creature); + return GetAQ20AI(creature); } }; @@ -208,7 +210,7 @@ class npc_buru_egg : public CreatureScript void JustEngagedWith(Unit* attacker) override { - if (Creature* buru = me->GetMap()->GetCreature(_instance->GetGuidData(DATA_BURU))) + if (Creature* buru = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_BURU))) if (!buru->IsInCombat()) buru->AI()->AttackStart(attacker); } @@ -216,7 +218,7 @@ class npc_buru_egg : public CreatureScript void JustSummoned(Creature* who) override { if (who->GetEntry() == NPC_HATCHLING) - if (Creature* buru = me->GetMap()->GetCreature(_instance->GetGuidData(DATA_BURU))) + if (Creature* buru = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_BURU))) if (Unit* target = buru->AI()->SelectTarget(SELECT_TARGET_RANDOM)) who->AI()->AttackStart(target); } @@ -227,7 +229,7 @@ class npc_buru_egg : public CreatureScript DoCastAOE(SPELL_EXPLODE_2, true); // Unknown purpose DoCast(me, SPELL_SUMMON_HATCHLING, true); - if (Creature* buru = me->GetMap()->GetCreature(_instance->GetGuidData(DATA_BURU))) + if (Creature* buru = ObjectAccessor::GetCreature(*me, _instance->GetGuidData(DATA_BURU))) if (boss_buru::boss_buruAI* buruAI = dynamic_cast(buru->AI())) buruAI->ManageRespawn(me->GetGUID()); } @@ -237,7 +239,7 @@ class npc_buru_egg : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAQ20AI(creature); } }; diff --git a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_kurinnaxx.cpp b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_kurinnaxx.cpp index c7fb5836ed6..4d04a982154 100644 --- a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_kurinnaxx.cpp +++ b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_kurinnaxx.cpp @@ -15,11 +15,12 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ruins_of_ahnqiraj.h" #include "CreatureTextMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ruins_of_ahnqiraj.h" +#include "ScriptedCreature.h" enum Spells { @@ -83,8 +84,8 @@ class boss_kurinnaxx : public CreatureScript void JustDied(Unit* /*killer*/) override { _JustDied(); - if (Creature* Ossirian = me->GetMap()->GetCreature(instance->GetGuidData(DATA_OSSIRIAN))) - sCreatureTextMgr->SendChat(Ossirian, SAY_KURINAXX_DEATH, NULL, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_ZONE); + if (Creature* Ossirian = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_OSSIRIAN))) + sCreatureTextMgr->SendChat(Ossirian, SAY_KURINAXX_DEATH, nullptr, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_ZONE); } void UpdateAI(uint32 diff) override @@ -136,7 +137,7 @@ class boss_kurinnaxx : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAQ20AI(creature); } }; diff --git a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_ossirian.cpp b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_ossirian.cpp index 1c02e68fd0a..cd813560ffd 100644 --- a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_ossirian.cpp +++ b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/boss_ossirian.cpp @@ -16,13 +16,19 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ruins_of_ahnqiraj.h" -#include "Player.h" -#include "SpellInfo.h" -#include "WorldPacket.h" -#include "Opcodes.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "Opcodes.h" +#include "Player.h" +#include "ruins_of_ahnqiraj.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "TemporarySummon.h" +#include "Weather.h" +#include "WorldPacket.h" enum Texts { @@ -118,7 +124,7 @@ class boss_ossirian : public CreatureScript if (spell->Id == SpellWeakness[i]) { me->RemoveAurasDueToSpell(SPELL_SUPREME); - ((TempSummon*)caster)->UnSummon(); + caster->ToTempSummon()->UnSummon(); SpawnNextCrystal(); } } @@ -127,7 +133,7 @@ class boss_ossirian : public CreatureScript void DoAction(int32 action) override { if (action == ACTION_TRIGGER_WEAKNESS) - if (Creature* Trigger = me->GetMap()->GetCreature(TriggerGUID)) + if (Creature* Trigger = ObjectAccessor::GetCreature(*me, TriggerGUID)) if (!Trigger->HasUnitState(UNIT_STATE_CASTING)) Trigger->CastSpell(Trigger, SpellWeakness[urand(0, 4)], false); } @@ -179,7 +185,7 @@ class boss_ossirian : public CreatureScript void Cleanup() { - if (GameObject* Crystal = me->GetMap()->GetGameObject(CrystalGUID)) + if (GameObject* Crystal = ObjectAccessor::GetGameObject(*me, CrystalGUID)) Crystal->Use(me); } @@ -191,7 +197,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], G3D::Quat(), uint32(-1))) + if (GameObject* Crystal = Trigger->SummonGameObject(GO_OSSIRIAN_CRYSTAL, CrystalCoordinates[CrystalIterator], QuaternionData(), uint32(-1))) { CrystalGUID = Crystal->GetGUID(); ++CrystalIterator; @@ -270,7 +276,7 @@ class boss_ossirian : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAQ20AI(creature); } }; @@ -281,16 +287,14 @@ class go_ossirian_crystal : public GameObjectScript struct go_ossirian_crystalAI : public GameObjectAI { - go_ossirian_crystalAI(GameObject* go) : GameObjectAI(go) { } + go_ossirian_crystalAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* player) override { - InstanceScript* Instance = player->GetInstanceScript(); - if (!Instance) - return false; - Creature* Ossirian = player->FindNearestCreature(NPC_OSSIRIAN, 30.0f); - if (!Ossirian || Instance->GetBossState(DATA_OSSIRIAN) != IN_PROGRESS) + if (!Ossirian || instance->GetBossState(DATA_OSSIRIAN) != IN_PROGRESS) return false; Ossirian->AI()->DoAction(ACTION_TRIGGER_WEAKNESS); @@ -300,7 +304,7 @@ class go_ossirian_crystal : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return new go_ossirian_crystalAI(go); + return GetAQ20AI(go); } }; diff --git a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/instance_ruins_of_ahnqiraj.cpp b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/instance_ruins_of_ahnqiraj.cpp index 8f80c8e5356..0ee0bdc24d3 100644 --- a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/instance_ruins_of_ahnqiraj.cpp +++ b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/instance_ruins_of_ahnqiraj.cpp @@ -16,13 +16,15 @@ */ #include "ScriptMgr.h" +#include "Creature.h" #include "InstanceScript.h" +#include "Map.h" #include "ruins_of_ahnqiraj.h" class instance_ruins_of_ahnqiraj : public InstanceMapScript { public: - instance_ruins_of_ahnqiraj() : InstanceMapScript("instance_ruins_of_ahnqiraj", 509) { } + instance_ruins_of_ahnqiraj() : InstanceMapScript(AQ20ScriptName, 509) { } struct instance_ruins_of_ahnqiraj_InstanceMapScript : public InstanceScript { diff --git a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/ruins_of_ahnqiraj.h b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/ruins_of_ahnqiraj.h index 1c8a9e8c70c..4df6196d197 100644 --- a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/ruins_of_ahnqiraj.h +++ b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/ruins_of_ahnqiraj.h @@ -18,6 +18,9 @@ #ifndef DEF_RUINS_OF_AHNQIRAJ_H #define DEF_RUINS_OF_AHNQIRAJ_H +#include "CreatureAIImpl.h" + +#define AQ20ScriptName "instance_ruins_of_ahnqiraj" #define DataHeader "AQR" enum AQRDataTypes @@ -57,4 +60,10 @@ enum AQRGameObjectIds GO_OSSIRIAN_CRYSTAL = 180619 }; +template +inline AI* GetAQ20AI(T* obj) +{ + return GetInstanceAI(obj, AQ20ScriptName); +} + #endif diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_bug_trio.cpp b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_bug_trio.cpp index 63656b2d10a..ddc9ecc9721 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_bug_trio.cpp +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_bug_trio.cpp @@ -24,8 +24,11 @@ SDCategory: Temple of Ahn'Qiraj EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "temple_of_ahnqiraj.h" +#include "TemporarySummon.h" enum Spells { @@ -46,11 +49,6 @@ class boss_kri : public CreatureScript public: boss_kri() : CreatureScript("boss_kri") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_kriAI : public ScriptedAI { boss_kriAI(Creature* creature) : ScriptedAI(creature) @@ -138,6 +136,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetAQ40AI(creature); + } }; class boss_vem : public CreatureScript @@ -145,11 +147,6 @@ class boss_vem : public CreatureScript public: boss_vem() : CreatureScript("boss_vem") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_vemAI : public ScriptedAI { boss_vemAI(Creature* creature) : ScriptedAI(creature) @@ -231,6 +228,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetAQ40AI(creature); + } }; class boss_yauj : public CreatureScript @@ -238,11 +239,6 @@ class boss_yauj : public CreatureScript public: boss_yauj() : CreatureScript("boss_yauj") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_yaujAI : public ScriptedAI { boss_yaujAI(Creature* creature) : ScriptedAI(creature) @@ -346,6 +342,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetAQ40AI(creature); + } }; void AddSC_bug_trio() diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_cthun.cpp b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_cthun.cpp index 93e61ee4958..36c527c9ab2 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_cthun.cpp +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_cthun.cpp @@ -24,9 +24,13 @@ SDCategory: Temple of Ahn'Qiraj EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "temple_of_ahnqiraj.h" -#include "Player.h" +#include "TemporarySummon.h" /* * This is a 2 phases events. Here follows an explanation of the main events and transition between phases and sub-phases. @@ -151,11 +155,6 @@ class boss_eye_of_cthun : public CreatureScript public: boss_eye_of_cthun() : CreatureScript("boss_eye_of_cthun") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct eye_of_cthunAI : public ScriptedAI { eye_of_cthunAI(Creature* creature) : ScriptedAI(creature) @@ -284,7 +283,7 @@ public: { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) { - Creature* Spawned = NULL; + Creature* Spawned = nullptr; //Spawn claw tentacle on the random target Spawned = me->SummonCreature(NPC_CLAW_TENTACLE, *target, TEMPSUMMON_CORPSE_DESPAWN, 500); @@ -444,6 +443,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetAQ40AI(creature); + } }; class boss_cthun : public CreatureScript @@ -451,11 +454,6 @@ class boss_cthun : public CreatureScript public: boss_cthun() : CreatureScript("boss_cthun") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct cthunAI : public ScriptedAI { cthunAI(Creature* creature) : ScriptedAI(creature) @@ -545,7 +543,7 @@ public: Unit* SelectRandomNotStomach() { if (Stomach_Map.empty()) - return NULL; + return nullptr; std::unordered_map::const_iterator i = Stomach_Map.begin(); @@ -566,7 +564,7 @@ public: } if (temp.empty()) - return NULL; + return nullptr; j = temp.begin(); @@ -587,7 +585,7 @@ public: if (WisperTimer <= diff) { //Play random sound to the zone - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) me->PlayDirectSound(RANDOM_SOUND_WHISPER, itr->GetSource()); @@ -754,7 +752,7 @@ public: //Set target in stomach Stomach_Map[target->GetGUID()] = true; target->InterruptNonMeleeSpells(false); - target->CastSpell(target, SPELL_MOUTH_TENTACLE, true, NULL, NULL, me->GetGUID()); + target->CastSpell(target, SPELL_MOUTH_TENTACLE, true, nullptr, nullptr, me->GetGUID()); StomachEnterTarget = target->GetGUID(); StomachEnterVisTimer = 3800; } @@ -882,6 +880,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetAQ40AI(creature); + } }; class npc_eye_tentacle : public CreatureScript @@ -889,11 +891,6 @@ class npc_eye_tentacle : public CreatureScript public: npc_eye_tentacle() : CreatureScript("npc_eye_tentacle") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new eye_tentacleAI(creature); - } - struct eye_tentacleAI : public ScriptedAI { eye_tentacleAI(Creature* creature) : ScriptedAI(creature) @@ -960,6 +957,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetAQ40AI(creature); + } }; class npc_claw_tentacle : public CreatureScript @@ -967,11 +968,6 @@ class npc_claw_tentacle : public CreatureScript public: npc_claw_tentacle() : CreatureScript("npc_claw_tentacle") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new claw_tentacleAI(creature); - } - struct claw_tentacleAI : public ScriptedAI { claw_tentacleAI(Creature* creature) : ScriptedAI(creature) @@ -1074,6 +1070,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetAQ40AI(creature); + } }; class npc_giant_claw_tentacle : public CreatureScript @@ -1081,11 +1081,6 @@ class npc_giant_claw_tentacle : public CreatureScript public: npc_giant_claw_tentacle() : CreatureScript("npc_giant_claw_tentacle") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new giant_claw_tentacleAI(creature); - } - struct giant_claw_tentacleAI : public ScriptedAI { giant_claw_tentacleAI(Creature* creature) : ScriptedAI(creature) @@ -1198,6 +1193,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetAQ40AI(creature); + } }; class npc_giant_eye_tentacle : public CreatureScript @@ -1205,11 +1204,6 @@ class npc_giant_eye_tentacle : public CreatureScript public: npc_giant_eye_tentacle() : CreatureScript("npc_giant_eye_tentacle") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new giant_eye_tentacleAI(creature); - } - struct giant_eye_tentacleAI : public ScriptedAI { giant_eye_tentacleAI(Creature* creature) : ScriptedAI(creature) @@ -1264,6 +1258,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetAQ40AI(creature); + } }; class npc_giant_flesh_tentacle : public CreatureScript @@ -1271,11 +1269,6 @@ class npc_giant_flesh_tentacle : public CreatureScript public: npc_giant_flesh_tentacle() : CreatureScript("npc_giant_flesh_tentacle") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new flesh_tentacleAI(creature); - } - struct flesh_tentacleAI : public ScriptedAI { flesh_tentacleAI(Creature* creature) : ScriptedAI(creature) @@ -1292,6 +1285,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetAQ40AI(creature); + } }; //GetAIs diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_fankriss.cpp b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_fankriss.cpp index 677427cca3a..715b21aa461 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_fankriss.cpp +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_fankriss.cpp @@ -25,6 +25,8 @@ EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" +#include "temple_of_ahnqiraj.h" +#include "TemporarySummon.h" #define SOUND_SENTENCE_YOU 8588 #define SOUND_SERVE_TO 8589 @@ -46,11 +48,6 @@ class boss_fankriss : public CreatureScript public: boss_fankriss() : CreatureScript("boss_fankriss") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new boss_fankrissAI(creature); - } - struct boss_fankrissAI : public ScriptedAI { boss_fankrissAI(Creature* creature) : ScriptedAI(creature) @@ -210,6 +207,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetAQ40AI(creature); + } }; void AddSC_boss_fankriss() diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_skeram.cpp b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_skeram.cpp index 6b73875fc2d..0148b9a2d36 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_skeram.cpp +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_skeram.cpp @@ -83,7 +83,7 @@ class boss_skeram : public CreatureScript { ScriptedAI::EnterEvadeMode(why); if (me->IsSummon()) - ((TempSummon*)me)->UnSummon(); + me->DespawnOrUnsummon(); } void JustSummoned(Creature* creature) override @@ -200,7 +200,7 @@ class boss_skeram : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_skeramAI(creature); + return GetAQ40AI(creature); } }; @@ -258,10 +258,7 @@ public: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TRUE_FULFILLMENT_2) - || !sSpellMgr->GetSpellInfo(SPELL_GENERIC_DISMOUNT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TRUE_FULFILLMENT_2, SPELL_GENERIC_DISMOUNT }); } void HandleEffect(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_twinemperors.cpp b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_twinemperors.cpp index 325aed87c6c..d72af19a9ee 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_twinemperors.cpp +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_twinemperors.cpp @@ -24,11 +24,12 @@ SDCategory: Temple of Ahn'Qiraj EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "SpellInfo.h" #include "temple_of_ahnqiraj.h" -#include "WorldPacket.h" -#include "Item.h" -#include "Spell.h" enum Spells { @@ -167,7 +168,7 @@ struct boss_twinemperorsAI : public ScriptedAI } } - void SpellHit(Unit* caster, const SpellInfo* entry) override + void SpellHit(Unit* caster, SpellInfo const* entry) override { if (caster == me) return; @@ -320,9 +321,9 @@ struct boss_twinemperorsAI : public ScriptedAI me->GetCreatureListWithEntryInGrid(lUnitList, 15317, 150.0f); if (lUnitList.empty()) - return NULL; + return nullptr; - Creature* nearb = NULL; + Creature* nearb = nullptr; for (std::list::const_iterator iter = lUnitList.begin(); iter != lUnitList.end(); ++iter) { @@ -393,11 +394,6 @@ class boss_veknilash : public CreatureScript public: boss_veknilash() : CreatureScript("boss_veknilash") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_veknilashAI : public boss_twinemperorsAI { bool IAmVeklor() override {return false;} @@ -474,6 +470,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetAQ40AI(creature); + } }; class boss_veklor : public CreatureScript @@ -481,11 +481,6 @@ class boss_veklor : public CreatureScript public: boss_veklor() : CreatureScript("boss_veklor") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_veklorAI : public boss_twinemperorsAI { bool IAmVeklor() override {return true;} @@ -598,6 +593,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetAQ40AI(creature); + } }; void AddSC_boss_twinemperors() diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_viscidus.cpp b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_viscidus.cpp index 6a7838a7030..ad95c667a5c 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_viscidus.cpp +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/boss_viscidus.cpp @@ -16,9 +16,13 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellInfo.h" #include "temple_of_ahnqiraj.h" +#include "TemporarySummon.h" enum Spells { @@ -255,7 +259,7 @@ class boss_viscidus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_viscidusAI(creature); + return GetAQ40AI(creature); } }; @@ -272,7 +276,7 @@ class npc_glob_of_viscidus : public CreatureScript { InstanceScript* Instance = me->GetInstanceScript(); - if (Creature* Viscidus = me->GetMap()->GetCreature(Instance->GetGuidData(DATA_VISCIDUS))) + if (Creature* Viscidus = ObjectAccessor::GetCreature(*me, Instance->GetGuidData(DATA_VISCIDUS))) { if (BossAI* ViscidusAI = dynamic_cast(Viscidus->GetAI())) ViscidusAI->SummonedCreatureDespawn(me); @@ -304,7 +308,7 @@ class npc_glob_of_viscidus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAQ40AI(creature); } }; diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/instance_temple_of_ahnqiraj.cpp b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/instance_temple_of_ahnqiraj.cpp index 8ddf7e7351d..f507965d9e1 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/instance_temple_of_ahnqiraj.cpp +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/instance_temple_of_ahnqiraj.cpp @@ -24,18 +24,15 @@ SDCategory: Temple of Ahn'Qiraj EndScriptData */ #include "ScriptMgr.h" +#include "Creature.h" #include "InstanceScript.h" +#include "Map.h" #include "temple_of_ahnqiraj.h" class instance_temple_of_ahnqiraj : public InstanceMapScript { public: - instance_temple_of_ahnqiraj() : InstanceMapScript("instance_temple_of_ahnqiraj", 531) { } - - InstanceScript* GetInstanceScript(InstanceMap* map) const override - { - return new instance_temple_of_ahnqiraj_InstanceMapScript(map); - } + instance_temple_of_ahnqiraj() : InstanceMapScript(AQ40ScriptName, 531) { } struct instance_temple_of_ahnqiraj_InstanceMapScript : public InstanceScript { @@ -172,6 +169,10 @@ class instance_temple_of_ahnqiraj : public InstanceMapScript } }; + InstanceScript* GetInstanceScript(InstanceMap* map) const override + { + return new instance_temple_of_ahnqiraj_InstanceMapScript(map); + } }; void AddSC_instance_temple_of_ahnqiraj() diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/mob_anubisath_sentinel.cpp b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/mob_anubisath_sentinel.cpp index 2fbc2a0aba8..cbd3660b6d0 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/mob_anubisath_sentinel.cpp +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/mob_anubisath_sentinel.cpp @@ -24,17 +24,9 @@ SDCategory: Temple of Ahn'Qiraj EndScriptData */ #include "ScriptMgr.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "WorldPacket.h" - -#include "Item.h" -#include "Player.h" -#include "Spell.h" - -#include "Cell.h" -#include "CellImpl.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" +#include "temple_of_ahnqiraj.h" enum Spells { @@ -64,11 +56,6 @@ class npc_anubisath_sentinel : public CreatureScript public: npc_anubisath_sentinel() : CreatureScript("npc_anubisath_sentinel") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new aqsentinelAI(creature); - } - struct aqsentinelAI : public ScriptedAI { uint32 ability; @@ -266,6 +253,11 @@ public: } } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetAQ40AI(creature); + } }; void AddSC_npc_anubisath_sentinel() diff --git a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/temple_of_ahnqiraj.h b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/temple_of_ahnqiraj.h index 33a3867cb0c..9722218464d 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/temple_of_ahnqiraj.h +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/temple_of_ahnqiraj.h @@ -19,6 +19,9 @@ #ifndef DEF_TEMPLE_OF_AHNQIRAJ_H #define DEF_TEMPLE_OF_AHNQIRAJ_H +#include "CreatureAIImpl.h" + +#define AQ40ScriptName "instance_temple_of_ahnqiraj" #define DataHeader "AQT" enum AQTDataTypes @@ -62,4 +65,10 @@ enum AQTCreatures NPC_VEKNILASH = 15275 }; +template +inline AI* GetAQ40AI(T* obj) +{ + return GetInstanceAI(obj, AQ40ScriptName); +} + #endif diff --git a/src/server/scripts/Kalimdor/VortexPinnacle/boss_altairus.cpp b/src/server/scripts/Kalimdor/VortexPinnacle/boss_altairus.cpp index c4bbba910e8..135f55a1bdd 100644 --- a/src/server/scripts/Kalimdor/VortexPinnacle/boss_altairus.cpp +++ b/src/server/scripts/Kalimdor/VortexPinnacle/boss_altairus.cpp @@ -16,9 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" +#include "GridNotifiers.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellScript.h" +#include "TemporarySummon.h" #include "vortex_pinnacle.h" enum Spells @@ -77,10 +83,11 @@ enum Points POINT_TWISTER_MAX = 24, }; -const Position InvisibleStalkerPos = { -1216.12f, 64.026f, 734.2573f }; -const Position platform = { -1213.83f, 62.99f, 735.2f, 0.0f }; +Position const InvisibleStalkerPos = { -1216.12f, 64.026f, 734.2573f }; +Position const platform = { -1213.83f, 62.99f, 735.2f, 0.0f }; -const Position TwisterSpawnPoints[POINT_TWISTER_MAX] = { +Position const TwisterSpawnPoints[POINT_TWISTER_MAX] = +{ { -1226.936f, 58.03993f, 734.2574f }, { -1250.604f, 78.47916f, 729.8842f }, { -1255.609f, 63.03125f, 729.05f }, @@ -104,7 +111,7 @@ const Position TwisterSpawnPoints[POINT_TWISTER_MAX] = { { -1223.229f, 40.89063f, 734.2574f }, { -1211.016f, 105.4375f, 740.8424f }, { -1189.568f, 95.77604f, 740.8668f }, - { -1204.863f, 40.49826f, 734.2564f }, + { -1204.863f, 40.49826f, 734.2564f } }; // TO-DO: @@ -148,7 +155,6 @@ class boss_altairus : public CreatureScript void CheckPlatform() { Map::PlayerList const& playerList = me->GetMap()->GetPlayers(); - if (!playerList.isEmpty()) for (Map::PlayerList::const_iterator itr = playerList.begin(); itr != playerList.end(); ++itr) if (Player* player = itr->GetSource()) @@ -195,7 +201,7 @@ class boss_altairus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetVortexPinnacleAI(creature); } }; @@ -212,7 +218,7 @@ class npc_air_current : public CreatureScript me->SetDisableGravity(true); } - void SpellHit(Unit* /*unit*/, const SpellInfo* spellInfo) override + void SpellHit(Unit* /*unit*/, SpellInfo const* spellInfo) override { if (spellInfo->Id != SPELL_CALL_THE_WIND) return; @@ -257,7 +263,7 @@ class npc_air_current : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetVortexPinnacleAI(creature); } }; @@ -273,9 +279,7 @@ class spell_call_the_wind : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CALL_THE_WIND_AURA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CALL_THE_WIND_AURA }); } void FilterTargets(std::list& targets) diff --git a/src/server/scripts/Kalimdor/VortexPinnacle/boss_asaad.cpp b/src/server/scripts/Kalimdor/VortexPinnacle/boss_asaad.cpp index 2d728fcd40b..2eac159c0e8 100644 --- a/src/server/scripts/Kalimdor/VortexPinnacle/boss_asaad.cpp +++ b/src/server/scripts/Kalimdor/VortexPinnacle/boss_asaad.cpp @@ -16,10 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" +#include "AreaBoundary.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "ObjectAccessor.h" -#include "Player.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellScript.h" +#include "TemporarySummon.h" #include "vortex_pinnacle.h" enum Spells @@ -214,7 +218,7 @@ class boss_asaad : public CreatureScript BossAI::JustSummoned(creature); } - void SpellHitTarget(Unit* target, const SpellInfo* spellInfo) override + void SpellHitTarget(Unit* target, SpellInfo const* spellInfo) override { if (spellInfo->Id != SPELL_SOTS_TARGETING || target->GetEntry() != NPC_STORM_TARGET) return; @@ -370,7 +374,7 @@ class boss_asaad : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetVortexPinnacleAI(creature); } }; @@ -427,7 +431,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetVortexPinnacleAI(creature); } }; @@ -458,18 +462,18 @@ public: { case POINT_STORM_B: if (Creature* stormTargetB = ObjectAccessor::GetCreature(*me, asaad->AI()->GetGUID(POINT_STORM_B))) - stormTargetB->CastSpell((Unit*)NULL, SPELL_STORM_RUNE_BEAM_A); + stormTargetB->CastSpell((Unit*)nullptr, SPELL_STORM_RUNE_BEAM_A); _events.ScheduleEvent(EVENT_STORM_MOVE_C, 1200); break; case POINT_STORM_C: if (Creature* stormTargetC = ObjectAccessor::GetCreature(*me, asaad->AI()->GetGUID(POINT_STORM_C))) - stormTargetC->CastSpell((Unit*)NULL, SPELL_STORM_RUNE_BEAM_B); + stormTargetC->CastSpell((Unit*)nullptr, SPELL_STORM_RUNE_BEAM_B); _events.ScheduleEvent(EVENT_STORM_MOVE_A, 1200); break; case POINT_STORM_A: { if (Creature* stormTargetA = ObjectAccessor::GetCreature(*me, asaad->AI()->GetGUID(POINT_STORM_A))) - stormTargetA->CastSpell((Unit*)NULL, SPELL_STORM_RUNE_BEAM_C); + stormTargetA->CastSpell((Unit*)nullptr, SPELL_STORM_RUNE_BEAM_C); DoCast(me, SPELL_STORM_SUMMON_GROUNDING_FIELD); @@ -538,7 +542,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetVortexPinnacleAI(creature); } }; @@ -583,7 +587,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetVortexPinnacleAI(creature); } }; @@ -633,9 +637,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_UNSTABLE_GROUNDING_FIELD)) - return false; - return true; + return ValidateSpellInfo({ SPELL_UNSTABLE_GROUNDING_FIELD }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -784,7 +786,11 @@ public: if (!stormTargetA || !stormTargetB || !stormTargetC) return; - targets.remove_if(TargetInTriangleCheck(false, stormTargetA->GetPosition(), stormTargetB->GetPosition(), stormTargetC->GetPosition())); + TriangleBoundary triangle(*stormTargetA, *stormTargetB, *stormTargetC); + targets.remove_if([&](WorldObject* target) + { + return triangle.IsWithinBoundary(target); + }); } void Register() override diff --git a/src/server/scripts/Kalimdor/VortexPinnacle/boss_grand_vizier_ertan.cpp b/src/server/scripts/Kalimdor/VortexPinnacle/boss_grand_vizier_ertan.cpp index 974b7a7215d..2d21601c821 100644 --- a/src/server/scripts/Kalimdor/VortexPinnacle/boss_grand_vizier_ertan.cpp +++ b/src/server/scripts/Kalimdor/VortexPinnacle/boss_grand_vizier_ertan.cpp @@ -16,9 +16,10 @@ */ #include "ScriptMgr.h" +#include "MotionMaster.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "Player.h" +#include "TemporarySummon.h" #include "vortex_pinnacle.h" enum Spells @@ -202,7 +203,7 @@ class boss_grand_vizier_ertan : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetVortexPinnacleAI(creature); } }; @@ -269,7 +270,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetVortexPinnacleAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/VortexPinnacle/instance_vortex_pinnacle.cpp b/src/server/scripts/Kalimdor/VortexPinnacle/instance_vortex_pinnacle.cpp index 5d84d694579..74f6e479869 100644 --- a/src/server/scripts/Kalimdor/VortexPinnacle/instance_vortex_pinnacle.cpp +++ b/src/server/scripts/Kalimdor/VortexPinnacle/instance_vortex_pinnacle.cpp @@ -16,10 +16,12 @@ */ #include "ScriptMgr.h" -#include "Player.h" -#include "CreatureGroups.h" -#include "Vehicle.h" +#include "CreatureAI.h" +#include "EventMap.h" #include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "TemporarySummon.h" #include "vortex_pinnacle.h" #define MAX_ENCOUNTER 3 @@ -91,7 +93,7 @@ ObjectData const creatureData[] = class instance_vortex_pinnacle : public InstanceMapScript { public: - instance_vortex_pinnacle() : InstanceMapScript(SCScriptName, 657) { } + instance_vortex_pinnacle() : InstanceMapScript(VPScriptName, 657) { } struct instance_vortex_pinnacle_InstanceScript : public InstanceScript { @@ -112,11 +114,11 @@ class instance_vortex_pinnacle : public InstanceMapScript { switch (creature->GetEntry()) { - case NPC_HOWLING_GALE: - creature->SetReactState(REACT_PASSIVE); - break; - default: - break; + case NPC_HOWLING_GALE: + creature->SetReactState(REACT_PASSIVE); + break; + default: + break; } InstanceScript::OnCreatureCreate(creature); @@ -211,7 +213,7 @@ class instance_vortex_pinnacle : public InstanceMapScript points[0]->CastSpell(points[2], SPELL_BEAM_C, true); if (TempSummon* top = instance->SummonCreature(NPC_GROUNDING_FIELD, positionTop)) - top->ToCreature()->GetAI()->DoAction(ACTION_GROUNDING_FIELD_TOP); + top->AI()->DoAction(ACTION_GROUNDING_FIELD_TOP); } } diff --git a/src/server/scripts/Kalimdor/VortexPinnacle/vortex_pinnacle.cpp b/src/server/scripts/Kalimdor/VortexPinnacle/vortex_pinnacle.cpp index b7ed526c8d6..28f1c896319 100644 --- a/src/server/scripts/Kalimdor/VortexPinnacle/vortex_pinnacle.cpp +++ b/src/server/scripts/Kalimdor/VortexPinnacle/vortex_pinnacle.cpp @@ -16,11 +16,12 @@ */ #include "ScriptMgr.h" +#include "AreaBoundary.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "ScriptedCreature.h" -#include "ObjectGuid.h" +#include "SpellInfo.h" #include "SpellScript.h" -#include "Player.h" -#include "Vehicle.h" #include "vortex_pinnacle.h" enum Texts @@ -155,7 +156,7 @@ public: DoCast(me, SPELL_LURK_SEARCH); } - void SpellHit(Unit* /*unit*/, const SpellInfo* spellInfo) override + void SpellHit(Unit* /*unit*/, SpellInfo const* spellInfo) override { if (spellInfo->Id == SPELL_FEIGN_DEATH) Talk(SAY_FEIGN_DEATH); @@ -183,7 +184,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetVortexPinnacleAI(creature); } }; @@ -221,7 +222,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetVortexPinnacleAI(creature); } }; @@ -251,7 +252,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetVortexPinnacleAI(creature); } }; @@ -338,7 +339,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetVortexPinnacleAI(creature); } }; @@ -392,7 +393,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetVortexPinnacleAI(creature); } }; @@ -432,7 +433,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetVortexPinnacleAI(creature); } }; @@ -495,7 +496,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetVortexPinnacleAI(creature); } }; @@ -511,11 +512,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_LURK_CHECK)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_FEIGN_DEATH_CHECK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_LURK_CHECK, SPELL_FEIGN_DEATH_CHECK }); } void HandlePeriodic(AuraEffect const* /*aurEff*/) @@ -570,20 +567,9 @@ public: { PrepareSpellScript(spell_lurk_search_check_SpellScript); - public: - spell_lurk_search_check_SpellScript() - { - countFacingUnits = 0; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FEIGN_DEATH)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_LURK_RESSURECT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FEIGN_DEATH, SPELL_LURK_RESSURECT }); } void FilterTargets(std::list& unitList) @@ -617,7 +603,7 @@ public: OnEffectLaunch += SpellEffectFn(spell_lurk_search_check_SpellScript::OnLaunch, EFFECT_0, SPELL_EFFECT_DUMMY); } - uint32 countFacingUnits; + uint32 countFacingUnits = 0; }; SpellScript* GetSpellScript() const override @@ -669,11 +655,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_LURK)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_LURK_SEARCH)) - return false; - return true; + return ValidateSpellInfo({ SPELL_LURK, SPELL_LURK_SEARCH }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -812,25 +794,9 @@ public: { PrepareAuraScript(spell_howling_gale_AuraScript); - public: - spell_howling_gale_AuraScript() - { - tickCountdown = 0; - proced = false; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HOWLING_GALE_VISUAL)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_HOWLING_GALE_KNOCKBACK)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_HOWLING_GALE_VISUAL_2)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_HOWLING_GALE_KNOCKBACK_2)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HOWLING_GALE_VISUAL, SPELL_HOWLING_GALE_KNOCKBACK, SPELL_HOWLING_GALE_VISUAL_2, SPELL_HOWLING_GALE_KNOCKBACK_2 }); } void HandleProc(AuraEffect const* /*aurEff*/, ProcEventInfo& /*eventInfo*/) @@ -863,8 +829,8 @@ public: OnEffectPeriodic += AuraEffectPeriodicFn(spell_howling_gale_AuraScript::HandlePeriodic, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL); } - uint32 tickCountdown; - bool proced; + uint32 tickCountdown = 0; + bool proced = false; }; AuraScript* GetAuraScript() const override @@ -903,8 +869,7 @@ public: if (GetCaster()->GetGUID() == groundingField->GetGUID()) continue; - GroundFieldPositions[count] = groundingField->GetPosition(); - count += 1; + GroundFieldPositions[count++] = groundingField->GetPosition(); if (count == 3) break; } @@ -912,7 +877,11 @@ public: void FilterTargets(std::list& targets) { - targets.remove_if(TargetInTriangleCheck(true, GroundFieldPositions[0], GroundFieldPositions[1], GroundFieldPositions[2])); + TriangleBoundary triangle(GroundFieldPositions[0], GroundFieldPositions[1], GroundFieldPositions[2], true); + targets.remove_if([&](WorldObject* target) + { + return triangle.IsWithinBoundary(target); + }); } void Register() override diff --git a/src/server/scripts/Kalimdor/VortexPinnacle/vortex_pinnacle.h b/src/server/scripts/Kalimdor/VortexPinnacle/vortex_pinnacle.h index b4c330ac04c..651d94fe96e 100644 --- a/src/server/scripts/Kalimdor/VortexPinnacle/vortex_pinnacle.h +++ b/src/server/scripts/Kalimdor/VortexPinnacle/vortex_pinnacle.h @@ -18,13 +18,10 @@ #ifndef DEF_VORTEX_PINNACLE_H #define DEF_VORTEX_PINNACLE_H -#define SCScriptName "instance_vortex_pinnacle" -#define DataHeader "VP" +#include "CreatureAIImpl.h" -#include "G3D/Vector3.h" -#include "G3D/Triangle.h" -#include "G3D/Plane.h" -#include "G3D/CollisionDetection.h" +#define VPScriptName "instance_vortex_pinnacle" +#define DataHeader "VP" uint32 const Slipstreams = 13; uint32 const PrismGroundingFieldPoints = 3; @@ -76,36 +73,10 @@ enum Misc PATH_ZEPHYR_NORTH = 4599101, }; -class TargetInTriangleCheck +template +inline AI* GetVortexPinnacleAI(T* obj) { -public: - TargetInTriangleCheck(bool negate, Position positionA, Position positionB, Position positionC) - : _negate(negate), _positionA(positionA), _positionB(positionB), _positionC(positionC) { } - - bool operator()(WorldObject* target) const - { - return _negate != IsInTriangle(target); - } - -private: - - bool IsInTriangle(WorldObject* target) const - { - G3D::Triangle const triangle(PositionToVector3(_positionA), PositionToVector3(_positionB), PositionToVector3(_positionC)); - G3D::Vector3 const vector(PositionToVector3(*target)); - - return G3D::CollisionDetection::isPointInsideTriangle(triangle.vertex(0), triangle.vertex(1), triangle.vertex(2), triangle.normal(), vector, triangle.primaryAxis()); - } - - inline static G3D::Vector3 PositionToVector3(Position const& position) - { - return G3D::Vector3(position.GetPositionX(), position.GetPositionY(), position.GetPositionZ()); - } - - bool _negate; - Position _positionA; - Position _positionB; - Position _positionC; -}; + return GetInstanceAI(obj, VPScriptName); +} #endif // DEF_VORTEX_PINNACLE_H diff --git a/src/server/scripts/Kalimdor/WailingCaverns/instance_wailing_caverns.cpp b/src/server/scripts/Kalimdor/WailingCaverns/instance_wailing_caverns.cpp index f78e86e7ebf..a74f1ad080b 100644 --- a/src/server/scripts/Kalimdor/WailingCaverns/instance_wailing_caverns.cpp +++ b/src/server/scripts/Kalimdor/WailingCaverns/instance_wailing_caverns.cpp @@ -23,7 +23,9 @@ SDCategory: Wailing Caverns EndScriptData */ #include "ScriptMgr.h" +#include "Creature.h" #include "InstanceScript.h" +#include "Map.h" #include "wailing_caverns.h" ObjectData const creatureData[] = diff --git a/src/server/scripts/Kalimdor/WailingCaverns/wailing_caverns.cpp b/src/server/scripts/Kalimdor/WailingCaverns/wailing_caverns.cpp index 8427061b6c5..8aad4eaf899 100644 --- a/src/server/scripts/Kalimdor/WailingCaverns/wailing_caverns.cpp +++ b/src/server/scripts/Kalimdor/WailingCaverns/wailing_caverns.cpp @@ -27,11 +27,13 @@ EndScriptData */ EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" -#include "wailing_caverns.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "wailing_caverns.h" /*###### ## npc_disciple_of_naralex @@ -90,12 +92,11 @@ public: { uint32 const action = player->PlayerTalkClass->GetGossipOptionAction(gossipListId); ClearGossipMenuFor(player); - InstanceScript* instance = me->GetInstanceScript(); + if (action == GOSSIP_ACTION_INFO_DEF + 1) { CloseGossipMenuFor(player); - if (instance) - instance->SetData(DATA_NARALEX_EVENT, IN_PROGRESS); + instance->SetData(DATA_NARALEX_EVENT, IN_PROGRESS); Talk(SAY_MAKE_PREPARATIONS); @@ -111,26 +112,21 @@ public: bool GossipHello(Player* player) override { - if (InstanceScript* instance = me->GetInstanceScript()) + me->CastSpell(player, SPELL_MARK_OF_THE_WILD_RANK_2, true); + if ((instance->GetBossState(DATA_LORD_COBRAHN) == DONE) && (instance->GetBossState(DATA_LORD_PYTHAS) == DONE) && + (instance->GetBossState(DATA_LADY_ANACONDRA) == DONE) && (instance->GetBossState(DATA_LORD_SERPENTIS) == DONE)) { - me->CastSpell(player, SPELL_MARK_OF_THE_WILD_RANK_2, true); - if ((instance->GetBossState(DATA_LORD_COBRAHN) == DONE) && (instance->GetBossState(DATA_LORD_PYTHAS) == DONE) && - (instance->GetBossState(DATA_LADY_ANACONDRA) == DONE) && (instance->GetBossState(DATA_LORD_SERPENTIS) == DONE)) - { - AddGossipItemFor(player, GOSSIP_OPTION_LET_EVENT_BEGIN, 0, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); - SendGossipMenuFor(player, NPC_TEXT_FANGLORDS_ARE_DEAD, me->GetGUID()); + AddGossipItemFor(player, GOSSIP_OPTION_LET_EVENT_BEGIN, 0, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); + SendGossipMenuFor(player, NPC_TEXT_FANGLORDS_ARE_DEAD, me->GetGUID()); - if (!instance->GetData(DATA_NARALEX_YELLED)) - { - Talk(SAY_AT_LAST); - instance->SetData(DATA_NARALEX_YELLED, 1); - } - } - else + if (!instance->GetData(DATA_NARALEX_YELLED)) { - SendGossipMenuFor(player, NPC_TEXT_NARALEX_SLEEPS_AGAIN, me->GetGUID()); + Talk(SAY_AT_LAST); + instance->SetData(DATA_NARALEX_YELLED, 1); } } + else + SendGossipMenuFor(player, NPC_TEXT_NARALEX_SLEEPS_AGAIN, me->GetGUID()); return true; } @@ -243,7 +239,7 @@ public: ++eventProgress; eventTimer = 15000; //CAST_AI(npc_escort::npc_escortAI, me->AI())->SetCanDefend(false); - if (Creature* naralex = instance->instance->GetCreature(instance->GetGuidData(DATA_NARALEX))) + if (Creature* naralex = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NARALEX))) DoCast(naralex, SPELL_NARALEXS_AWAKENING, true); Talk(EMOTE_AWAKENING_RITUAL); } @@ -252,7 +248,7 @@ public: { ++eventProgress; eventTimer = 15000; - if (Creature* naralex = instance->instance->GetCreature(instance->GetGuidData(DATA_NARALEX))) + if (Creature* naralex = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NARALEX))) naralex->AI()->Talk(EMOTE_TROUBLED_SLEEP); me->SummonCreature(NPC_DEVIATE_MOCCASIN, 135.943f, 199.701f, -103.529f, 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 15000); me->SummonCreature(NPC_DEVIATE_MOCCASIN, 151.08f, 221.13f, -103.609f, 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 15000); @@ -263,7 +259,7 @@ public: { ++eventProgress; eventTimer = 30000; - if (Creature* naralex = instance->instance->GetCreature(instance->GetGuidData(DATA_NARALEX))) + if (Creature* naralex = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NARALEX))) naralex->AI()->Talk(EMOTE_WRITHE_IN_AGONY); me->SummonCreature(NPC_NIGHTMARE_ECTOPLASM, 133.413f, 207.188f, -102.469f, 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 15000); me->SummonCreature(NPC_NIGHTMARE_ECTOPLASM, 142.857f, 218.645f, -102.905f, 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 15000); @@ -277,7 +273,7 @@ public: if (eventProgress == 5) { ++eventProgress; - if (Creature* naralex = instance->instance->GetCreature(instance->GetGuidData(DATA_NARALEX))) + if (Creature* naralex = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NARALEX))) naralex->AI()->Talk(EMOTE_HORRENDOUS_VISION); me->SummonCreature(NPC_MUTANUS_THE_DEVOURER, 150.872f, 262.905f, -103.503f, 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 300000); Talk(SAY_MUTANUS_THE_DEVOURER); @@ -288,7 +284,7 @@ public: { ++eventProgress; eventTimer = 3000; - if (Creature* naralex = instance->instance->GetCreature(instance->GetGuidData(DATA_NARALEX))) + if (Creature* naralex = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NARALEX))) { if (me->HasAura(SPELL_NARALEXS_AWAKENING)) me->RemoveAura(SPELL_NARALEXS_AWAKENING); @@ -302,7 +298,7 @@ public: { ++eventProgress; eventTimer = 6000; - if (Creature* naralex = instance->instance->GetCreature(instance->GetGuidData(DATA_NARALEX))) + if (Creature* naralex = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NARALEX))) naralex->AI()->Talk(SAY_THANK_YOU); } else @@ -310,7 +306,7 @@ public: { ++eventProgress; eventTimer = 8000; - if (Creature* naralex = instance->instance->GetCreature(instance->GetGuidData(DATA_NARALEX))) + if (Creature* naralex = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NARALEX))) { naralex->AI()->Talk(SAY_FAREWELL); naralex->AddAura(SPELL_FLIGHT_FORM, naralex); @@ -324,7 +320,7 @@ public: { ++eventProgress; eventTimer = 1500; - if (Creature* naralex = instance->instance->GetCreature(instance->GetGuidData(DATA_NARALEX))) + if (Creature* naralex = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NARALEX))) naralex->GetMotionMaster()->MovePoint(25, naralex->GetPositionX(), naralex->GetPositionY(), naralex->GetPositionZ()); } else @@ -332,7 +328,7 @@ public: { ++eventProgress; eventTimer = 2500; - if (Creature* naralex = instance->instance->GetCreature(instance->GetGuidData(DATA_NARALEX))) + if (Creature* naralex = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NARALEX))) { naralex->GetMotionMaster()->MovePoint(0, 117.095512f, 247.107971f, -96.167870f); naralex->GetMotionMaster()->MovePoint(1, 90.388809f, 276.135406f, -83.389801f); @@ -343,7 +339,7 @@ public: else if (eventProgress == 11) { - if (Creature* naralex = instance->instance->GetCreature(instance->GetGuidData(DATA_NARALEX))) + if (Creature* naralex = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_NARALEX))) naralex->SetVisible(false); me->SetVisible(false); instance->SetData(DATA_NARALEX_PART3, DONE); @@ -365,7 +361,6 @@ public: { return GetWailingCavernsAI(creature); } - }; void AddSC_wailing_caverns() diff --git a/src/server/scripts/Kalimdor/WailingCaverns/wailing_caverns.h b/src/server/scripts/Kalimdor/WailingCaverns/wailing_caverns.h index 6d08f3bf0dc..53465a5ebb7 100644 --- a/src/server/scripts/Kalimdor/WailingCaverns/wailing_caverns.h +++ b/src/server/scripts/Kalimdor/WailingCaverns/wailing_caverns.h @@ -18,6 +18,8 @@ #ifndef DEF_WAILING_CAVERNS_H #define DEF_WAILING_CAVERNS_H +#include "CreatureAIImpl.h" + #define DataHeader "WC" #define WCScriptName "instance_wailing_caverns" @@ -62,8 +64,8 @@ enum Creatures NPC_DRUID_OF_THE_FANG = 3840, }; -template -AI* GetWailingCavernsAI(T* obj) +template +inline AI* GetWailingCavernsAI(T* obj) { return GetInstanceAI(obj, WCScriptName); } diff --git a/src/server/scripts/Kalimdor/ZulFarrak/boss_zum_rah.cpp b/src/server/scripts/Kalimdor/ZulFarrak/boss_zum_rah.cpp index ab95e1c8d8a..61ab305a0d8 100644 --- a/src/server/scripts/Kalimdor/ZulFarrak/boss_zum_rah.cpp +++ b/src/server/scripts/Kalimdor/ZulFarrak/boss_zum_rah.cpp @@ -21,6 +21,7 @@ Category: Tanaris, ZulFarrak */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "zulfarrak.h" @@ -152,7 +153,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetZulFarrakAI(creature); } }; diff --git a/src/server/scripts/Kalimdor/ZulFarrak/instance_zulfarrak.cpp b/src/server/scripts/Kalimdor/ZulFarrak/instance_zulfarrak.cpp index e41038a64dd..310cd5dac0c 100644 --- a/src/server/scripts/Kalimdor/ZulFarrak/instance_zulfarrak.cpp +++ b/src/server/scripts/Kalimdor/ZulFarrak/instance_zulfarrak.cpp @@ -16,10 +16,12 @@ */ #include "ScriptMgr.h" +#include "GameObject.h" #include "InstanceScript.h" -#include "zulfarrak.h" -#include "Player.h" +#include "Map.h" +#include "MotionMaster.h" #include "TemporarySummon.h" +#include "zulfarrak.h" enum Misc { @@ -99,12 +101,7 @@ float Spawnsway[2][3] = class instance_zulfarrak : public InstanceMapScript { public: - instance_zulfarrak() : InstanceMapScript("instance_zulfarrak", 209) { } - - InstanceScript* GetInstanceScript(InstanceMap* map) const override - { - return new instance_zulfarrak_InstanceMapScript(map); - } + instance_zulfarrak() : InstanceMapScript(ZFScriptName, 209) { } struct instance_zulfarrak_InstanceMapScript : public InstanceScript { @@ -371,6 +368,10 @@ public: } }; + InstanceScript* GetInstanceScript(InstanceMap* map) const override + { + return new instance_zulfarrak_InstanceMapScript(map); + } }; void AddSC_instance_zulfarrak() diff --git a/src/server/scripts/Kalimdor/ZulFarrak/zulfarrak.cpp b/src/server/scripts/Kalimdor/ZulFarrak/zulfarrak.cpp index d6366be24d8..184b71f96e1 100644 --- a/src/server/scripts/Kalimdor/ZulFarrak/zulfarrak.cpp +++ b/src/server/scripts/Kalimdor/ZulFarrak/zulfarrak.cpp @@ -29,11 +29,15 @@ npc_weegli_blastfuse EndContentData */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" #include "zulfarrak.h" -#include "Player.h" -#include "GameObjectAI.h" /*###### ## npc_sergeant_bly @@ -58,11 +62,6 @@ class npc_sergeant_bly : public CreatureScript public: npc_sergeant_bly() : CreatureScript("npc_sergeant_bly") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_sergeant_blyAI : public ScriptedAI { npc_sergeant_blyAI(Creature* creature) : ScriptedAI(creature) @@ -102,21 +101,17 @@ public: bool GossipHello(Player* player) override { - if (InstanceScript* instance = me->GetInstanceScript()) + if (instance->GetData(EVENT_PYRAMID) == PYRAMID_KILLED_ALL_TROLLS) { - if (instance->GetData(EVENT_PYRAMID) == PYRAMID_KILLED_ALL_TROLLS) - { - AddGossipItemFor(player, GOSSIP_ICON_CHAT, GOSSIP_BLY, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); - SendGossipMenuFor(player, 1517, me->GetGUID()); - } - else - if (instance->GetData(EVENT_PYRAMID) == PYRAMID_NOT_STARTED) - SendGossipMenuFor(player, 1515, me->GetGUID()); - else - SendGossipMenuFor(player, 1516, me->GetGUID()); - return true; + AddGossipItemFor(player, GOSSIP_ICON_CHAT, GOSSIP_BLY, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF + 1); + SendGossipMenuFor(player, 1517, me->GetGUID()); } - return false; + else + if (instance->GetData(EVENT_PYRAMID) == PYRAMID_NOT_STARTED) + SendGossipMenuFor(player, 1515, me->GetGUID()); + else + SendGossipMenuFor(player, 1516, me->GetGUID()); + return true; } void Reset() override @@ -136,7 +131,7 @@ public: { case 1: //weegli doesn't fight - he goes & blows up the door - if (Creature* pWeegli = instance->instance->GetCreature(instance->GetGuidData(ENTRY_WEEGLI))) + if (Creature* pWeegli = ObjectAccessor::GetCreature(*me, instance->GetGuidData(ENTRY_WEEGLI))) pWeegli->AI()->DoAction(0); Talk(SAY_1); Text_Timer = 5000; @@ -195,6 +190,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetZulFarrakAI(creature); + } }; /*###### @@ -208,27 +207,26 @@ public: struct go_troll_cageAI : public GameObjectAI { - go_troll_cageAI(GameObject* go) : GameObjectAI(go) { } + go_troll_cageAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* /*player*/) override { - if (InstanceScript* instance = me->GetInstanceScript()) - { - instance->SetData(EVENT_PYRAMID, PYRAMID_CAGES_OPEN); - //set bly & co to aggressive & start moving to top of stairs - initBlyCrewMember(instance, ENTRY_BLY, 1884.99f, 1263, 41.52f); - initBlyCrewMember(instance, ENTRY_RAVEN, 1882.5f, 1263, 41.52f); - initBlyCrewMember(instance, ENTRY_ORO, 1886.47f, 1270.68f, 41.68f); - initBlyCrewMember(instance, ENTRY_WEEGLI, 1890, 1263, 41.52f); - initBlyCrewMember(instance, ENTRY_MURTA, 1891.19f, 1272.03f, 41.60f); - } + instance->SetData(EVENT_PYRAMID, PYRAMID_CAGES_OPEN); + //set bly & co to aggressive & start moving to top of stairs + initBlyCrewMember(ENTRY_BLY, 1884.99f, 1263, 41.52f); + initBlyCrewMember(ENTRY_RAVEN, 1882.5f, 1263, 41.52f); + initBlyCrewMember(ENTRY_ORO, 1886.47f, 1270.68f, 41.68f); + initBlyCrewMember(ENTRY_WEEGLI, 1890, 1263, 41.52f); + initBlyCrewMember(ENTRY_MURTA, 1891.19f, 1272.03f, 41.60f); return false; } private: - void initBlyCrewMember(InstanceScript* instance, uint32 entry, float x, float y, float z) const + void initBlyCrewMember(uint32 entry, float x, float y, float z) const { - if (Creature* crew = instance->instance->GetCreature(instance->GetGuidData(entry))) + if (Creature* crew = ObjectAccessor::GetCreature(*me, instance->GetGuidData(entry))) { crew->SetReactState(REACT_AGGRESSIVE); crew->SetWalk(true); @@ -241,7 +239,7 @@ public: GameObjectAI* GetAI(GameObject* go) const override { - return new go_troll_cageAI(go); + return GetZulFarrakAI(go); } }; @@ -270,11 +268,6 @@ class npc_weegli_blastfuse : public CreatureScript public: npc_weegli_blastfuse() : CreatureScript("npc_weegli_blastfuse") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_weegli_blastfuseAI : public ScriptedAI { npc_weegli_blastfuseAI(Creature* creature) : ScriptedAI(creature) @@ -394,6 +387,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetZulFarrakAI(creature); + } }; /*###### @@ -436,7 +433,7 @@ class go_shallow_grave : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return new go_shallow_graveAI(go); + return GetZulFarrakAI(go); } }; diff --git a/src/server/scripts/Kalimdor/ZulFarrak/zulfarrak.h b/src/server/scripts/Kalimdor/ZulFarrak/zulfarrak.h index 107d63cfe7d..776631685e3 100644 --- a/src/server/scripts/Kalimdor/ZulFarrak/zulfarrak.h +++ b/src/server/scripts/Kalimdor/ZulFarrak/zulfarrak.h @@ -19,6 +19,9 @@ #ifndef DEF_ZF_H #define DEF_ZF_H +#include "CreatureAIImpl.h" + +#define ZFScriptName "instance_zulfarrak" #define DataHeader "ZF" enum ZFEntries @@ -54,4 +57,10 @@ enum ZFPyramidPhases PYRAMID_KILLED_ALL_TROLLS, }; +template +inline AI* GetZulFarrakAI(T* obj) +{ + return GetInstanceAI(obj, ZFScriptName); +} + #endif diff --git a/src/server/scripts/Kalimdor/zone_ashenvale.cpp b/src/server/scripts/Kalimdor/zone_ashenvale.cpp index 3f9d06d19a6..6e3516396ea 100644 --- a/src/server/scripts/Kalimdor/zone_ashenvale.cpp +++ b/src/server/scripts/Kalimdor/zone_ashenvale.cpp @@ -28,11 +28,12 @@ npc_ruul_snowhoof EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" -#include "Player.h" -#include "SpellScript.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "Player.h" +#include "ScriptedEscortAI.h" +#include "SpellInfo.h" +#include "SpellScript.h" /*#### # npc_ruul_snowhoof diff --git a/src/server/scripts/Kalimdor/zone_azuremyst_isle.cpp b/src/server/scripts/Kalimdor/zone_azuremyst_isle.cpp index ad1aec839bd..500bb21bcec 100644 --- a/src/server/scripts/Kalimdor/zone_azuremyst_isle.cpp +++ b/src/server/scripts/Kalimdor/zone_azuremyst_isle.cpp @@ -33,14 +33,15 @@ npc_death_ravager EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "CellImpl.h" +#include "GameObjectAI.h" +#include "GridNotifiersImpl.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedEscortAI.h" #include "ScriptedGossip.h" -#include "Cell.h" -#include "CellImpl.h" -#include "GridNotifiersImpl.h" -#include "GridNotifiers.h" -#include "GameObjectAI.h" +#include "TemporarySummon.h" /*###### ## npc_draenei_survivor @@ -111,7 +112,7 @@ public: } } - void SpellHit(Unit* Caster, const SpellInfo* Spell) override + void SpellHit(Unit* Caster, SpellInfo const* Spell) override { if (Spell->SpellFamilyFlags[2] & 0x080000000) { diff --git a/src/server/scripts/Kalimdor/zone_bloodmyst_isle.cpp b/src/server/scripts/Kalimdor/zone_bloodmyst_isle.cpp index dbdc2752c6d..3326b19550d 100644 --- a/src/server/scripts/Kalimdor/zone_bloodmyst_isle.cpp +++ b/src/server/scripts/Kalimdor/zone_bloodmyst_isle.cpp @@ -27,14 +27,15 @@ EndScriptData */ npc_webbed_creature EndContentData */ -#include "Player.h" -#include "Group.h" -#include "GridNotifiersImpl.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" -#include "PassiveAI.h" #include "CellImpl.h" +#include "GridNotifiersImpl.h" +#include "Group.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "PassiveAI.h" +#include "Player.h" +#include "ScriptedEscortAI.h" /*###### ## npc_webbed_creature @@ -446,7 +447,7 @@ public: break; case EVENT_HEALING_SURGE: { - Unit* target = NULL; + Unit* target = nullptr; if (me->GetHealthPct() < 85) target = me; else if (Player* player = GetPlayerForEscort()) @@ -515,7 +516,7 @@ public: _explosivesGuids.clear(); for (uint8 i = 0; i != MAX_EXPLOSIVES; ++i) { - if (GameObject* explosive = me->SummonGameObject(GO_DRAENEI_EXPLOSIVES_1, ExplosivesPos[0][i], G3D::Quat(), 0)) + if (GameObject* explosive = me->SummonGameObject(GO_DRAENEI_EXPLOSIVES_1, ExplosivesPos[0][i], QuaternionData(), 0)) _explosivesGuids.push_back(explosive->GetGUID()); } me->HandleEmoteCommand(EMOTE_ONESHOT_NONE); // reset anim state @@ -611,7 +612,7 @@ public: _explosivesGuids.clear(); for (uint8 i = 0; i != MAX_EXPLOSIVES; ++i) { - if (GameObject* explosive = me->SummonGameObject(GO_DRAENEI_EXPLOSIVES_2, ExplosivesPos[1][i], G3D::Quat(), 0)) + if (GameObject* explosive = me->SummonGameObject(GO_DRAENEI_EXPLOSIVES_2, ExplosivesPos[1][i], QuaternionData(), 0)) _explosivesGuids.push_back(explosive->GetGUID()); } Talk(SAY_LEGOSO_15); @@ -756,7 +757,7 @@ public: SetEscortPaused(true); //Find Sironas and make it respawn if needed - Creature* sironas = NULL; + Creature* sironas = nullptr; Trinity::AllCreaturesOfEntryInRange check(me, NPC_SIRONAS, SIZE_OF_GRIDS); Trinity::CreatureSearcher searcher(me, sironas, check); Cell::VisitAllObjects(me, searcher, SIZE_OF_GRIDS); diff --git a/src/server/scripts/Kalimdor/zone_desolace.cpp b/src/server/scripts/Kalimdor/zone_desolace.cpp index 6eefac95238..7446b256617 100644 --- a/src/server/scripts/Kalimdor/zone_desolace.cpp +++ b/src/server/scripts/Kalimdor/zone_desolace.cpp @@ -29,10 +29,10 @@ go_demon_portal EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "MotionMaster.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" #include "SpellInfo.h" enum DyingKodo diff --git a/src/server/scripts/Kalimdor/zone_durotar.cpp b/src/server/scripts/Kalimdor/zone_durotar.cpp index 2c0d90da9b2..fe7e96a588f 100644 --- a/src/server/scripts/Kalimdor/zone_durotar.cpp +++ b/src/server/scripts/Kalimdor/zone_durotar.cpp @@ -16,9 +16,10 @@ */ #include "ScriptMgr.h" +#include "CreatureAIImpl.h" +#include "Player.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "Player.h" enum VoodooSpells { @@ -43,12 +44,7 @@ class spell_voodoo : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BREW) || !sSpellMgr->GetSpellInfo(SPELL_GHOSTLY) || - !sSpellMgr->GetSpellInfo(SPELL_HEX1) || !sSpellMgr->GetSpellInfo(SPELL_HEX2) || - !sSpellMgr->GetSpellInfo(SPELL_HEX3) || !sSpellMgr->GetSpellInfo(SPELL_GROW) || - !sSpellMgr->GetSpellInfo(SPELL_LAUNCH)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BREW, SPELL_GHOSTLY, SPELL_HEX1, SPELL_HEX2, SPELL_HEX3, SPELL_GROW, SPELL_LAUNCH }); } void HandleDummy(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Kalimdor/zone_felwood.cpp b/src/server/scripts/Kalimdor/zone_felwood.cpp index 0e51169749b..85d36098225 100644 --- a/src/server/scripts/Kalimdor/zone_felwood.cpp +++ b/src/server/scripts/Kalimdor/zone_felwood.cpp @@ -16,13 +16,10 @@ */ #include "ScriptMgr.h" +#include "MotionMaster.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "Player.h" -#include "Cell.h" -#include "CellImpl.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" #include "SpellScript.h" /*###### @@ -240,7 +237,7 @@ public: spell_ruumbos_silly_dance() : SpellScriptLoader("spell_ruumbos_silly_dan { player->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_DANCE); - if (player->GetMap()->GetId() == MAP_KALIMDOR) + if (player->GetMapId() == MAP_KALIMDOR) { player->SummonCreature(NPC_DRIZZLE, DrizzleSpawnPos, TEMPSUMMON_TIMED_DESPAWN, 20000); player->SummonCreature(NPC_FERLI, FerliSpawnPos, TEMPSUMMON_TIMED_DESPAWN, 20000); diff --git a/src/server/scripts/Kalimdor/zone_moonglade.cpp b/src/server/scripts/Kalimdor/zone_moonglade.cpp index 1f400bdd614..aff575107b9 100644 --- a/src/server/scripts/Kalimdor/zone_moonglade.cpp +++ b/src/server/scripts/Kalimdor/zone_moonglade.cpp @@ -16,15 +16,12 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" -#include "ScriptedGossip.h" +#include "GameObject.h" +#include "MotionMaster.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" #include "SpellInfo.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "Cell.h" -#include "CellImpl.h" /*#### @@ -89,7 +86,7 @@ public: DoCast(SPELL_OMEN_SUMMON_SPOTLIGHT); } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_ELUNE_CANDLE) { diff --git a/src/server/scripts/Kalimdor/zone_mulgore.cpp b/src/server/scripts/Kalimdor/zone_mulgore.cpp index 6ca17c78bcb..1813765ebf2 100644 --- a/src/server/scripts/Kalimdor/zone_mulgore.cpp +++ b/src/server/scripts/Kalimdor/zone_mulgore.cpp @@ -16,6 +16,7 @@ */ #include "ScriptMgr.h" +#include "MotionMaster.h" #include "ScriptedCreature.h" /*###### @@ -28,8 +29,7 @@ enum EagleSpirit SPELL_SPIRIT_FORM = 69324 }; -uint32 const EagleSpiritflightPathSize = 7; -G3D::Vector3 const EagleSpiritflightPath[EagleSpiritflightPathSize] = +Position const EagleSpiritflightPath[] = { { -2884.155f, -71.08681f, 242.0678f }, { -2720.592f, -111.0035f, 242.5955f }, @@ -39,6 +39,7 @@ G3D::Vector3 const EagleSpiritflightPath[EagleSpiritflightPathSize] = { -2465.321f, -502.4896f, 190.7347f }, { -2343.872f, -401.8281f, -8.320873f } }; +uint32 const EagleSpiritflightPathSize = std::extent::value; class npc_eagle_spirit : public CreatureScript { @@ -61,9 +62,7 @@ public: void MovementInform(uint32 type, uint32 pointId) override { if (type == EFFECT_MOTION_TYPE && pointId == EagleSpiritflightPathSize) - { DoCast(SPELL_EJECT_ALL_PASSENGERS); - } } }; diff --git a/src/server/scripts/Kalimdor/zone_silithus.cpp b/src/server/scripts/Kalimdor/zone_silithus.cpp index 41093297d56..34cd9e15a21 100644 --- a/src/server/scripts/Kalimdor/zone_silithus.cpp +++ b/src/server/scripts/Kalimdor/zone_silithus.cpp @@ -29,11 +29,16 @@ go_wind_stone EndContentData */ #include "ScriptMgr.h" +#include "CreatureAIImpl.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "Group.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "Group.h" -#include "Player.h" -#include "GameObjectAI.h" +#include "TemporarySummon.h" /*##### # Quest: A Pawn on the Eternal Board @@ -496,11 +501,11 @@ public: DoCast(player, SPELL_CALL_PRISMATIC_BARRIER, true); break; case 37: - me->SummonGameObject(GO_GATE_OF_AHN_QIRAJ, Position(-8130.f, 1525.f, 17.5f, 0.f), G3D::Quat(), 0); + me->SummonGameObject(GO_GATE_OF_AHN_QIRAJ, Position(-8130.f, 1525.f, 17.5f, 0.f), QuaternionData(), 0); break; case 38: 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); + me->SummonGameObject(GO_GLYPH_OF_AHN_QIRAJ, Position(-8130.f, 1525.f, 17.5f, 0.f), QuaternionData(), 0); break; case 39: Talk(ANACHRONOS_SAY_5, Fandral); @@ -509,7 +514,7 @@ public: Fandral->CastSpell(me, SPELL_CALL_ANCIENTS, true); break; case 41: - Fandral->SummonGameObject(GO_ROOTS_OF_AHN_QIRAJ, Position(-8130.f, 1525.f, 17.5f, 0.f), G3D::Quat(), 0); + Fandral->SummonGameObject(GO_ROOTS_OF_AHN_QIRAJ, Position(-8130.f, 1525.f, 17.5f, 0.f), QuaternionData(), 0); Fandral->AI()->Talk(FANDRAL_SAY_3); break; case 42: @@ -545,7 +550,7 @@ public: case 51: { uint32 entries[4] = { NPC_KALDOREI_INFANTRY, NPC_ANUBISATH_CONQUEROR, NPC_QIRAJI_WASP, NPC_QIRAJI_TANK }; - Unit* mob = NULL; + Unit* mob = nullptr; for (uint8 i = 0; i < 4; ++i) { mob = player->FindNearestCreature(entries[i], 50); @@ -731,7 +736,7 @@ public: } if (!hasTarget) { - Unit* target = NULL; + Unit* target = nullptr; 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) @@ -859,7 +864,7 @@ public: if (Group* EventGroup = player->GetGroup()) { - Player* groupMember = NULL; + Player* groupMember = nullptr; uint8 GroupMemberCount = 0; uint8 DeadMemberCount = 0; diff --git a/src/server/scripts/Kalimdor/zone_tanaris.cpp b/src/server/scripts/Kalimdor/zone_tanaris.cpp index 70eb58850f8..669347b71f1 100644 --- a/src/server/scripts/Kalimdor/zone_tanaris.cpp +++ b/src/server/scripts/Kalimdor/zone_tanaris.cpp @@ -29,11 +29,12 @@ npc_OOX17 EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedEscortAI.h" #include "ScriptedFollowerAI.h" -#include "Player.h" +#include "ScriptedGossip.h" #include "WorldSession.h" /*###### diff --git a/src/server/scripts/Kalimdor/zone_the_barrens.cpp b/src/server/scripts/Kalimdor/zone_the_barrens.cpp index bc134faeb06..71f799091a6 100644 --- a/src/server/scripts/Kalimdor/zone_the_barrens.cpp +++ b/src/server/scripts/Kalimdor/zone_the_barrens.cpp @@ -28,11 +28,13 @@ npc_wizzlecrank_shredder EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" #include "SpellInfo.h" +#include "TemporarySummon.h" /*###### ## npc_beaten_corpse @@ -228,7 +230,7 @@ public: me->HandleEmoteCommand(EMOTE_ONESHOT_SALUTE); } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_FLARE || spell->Id == SPELL_FOLLY) { @@ -370,7 +372,7 @@ public: { if (EventInProgress) { - Player* warrior = NULL; + Player* warrior = nullptr; if (PlayerGUID) warrior = ObjectAccessor::GetPlayer(*me, PlayerGUID); diff --git a/src/server/scripts/Kalimdor/zone_winterspring.cpp b/src/server/scripts/Kalimdor/zone_winterspring.cpp index 907f4148b22..0b30f9b2650 100644 --- a/src/server/scripts/Kalimdor/zone_winterspring.cpp +++ b/src/server/scripts/Kalimdor/zone_winterspring.cpp @@ -29,11 +29,14 @@ go_elune_fire EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" -#include "Player.h" -#include "WorldSession.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedEscortAI.h" +#include "TemporarySummon.h" +#include "WorldSession.h" enum Says { @@ -124,7 +127,7 @@ public: // The array MUST be terminated by {0, 0, 0} DialogueHelper(DialogueEntry const* dialogueArray) : _dialogueArray(dialogueArray), - _currentEntry(NULL), + _currentEntry(nullptr), _actionTimer(0) { } // The array MUST be terminated by {0, 0, 0, 0, 0} @@ -168,7 +171,7 @@ protected: /// Will be called when a dialogue step was done virtual void JustDidDialogueStep(int32 /*entry*/) { } /// Will be called to get a speaker, MUST be implemented if not used in instances - virtual Creature* GetSpeakerByEntry(int32 /*entry*/) { return NULL; } + virtual Creature* GetSpeakerByEntry(int32 /*entry*/) { return nullptr; } private: void DoNextDialogueStep() @@ -383,18 +386,18 @@ public: case 41: { // Search for all nearest lights and respawn them - std::list eluneLights; + std::vector eluneLights; GetGameObjectListWithEntryInGrid(eluneLights, me, GO_ELUNE_LIGHT, 20.0f); - for (std::list::const_iterator itr = eluneLights.begin(); itr != eluneLights.end(); ++itr) + for (GameObject* go : eluneLights) { - if ((*itr)->isSpawned()) + if (go->isSpawned()) continue; - (*itr)->SetRespawnTime(115); - (*itr)->Refresh(); + go->SetRespawnTime(115); + go->Refresh(); } - if (GameObject* altar = me->GetMap()->GetGameObject(_altarGUID)) + if (GameObject* altar = ObjectAccessor::GetGameObject(*me, _altarGUID)) me->SetFacingToObject(altar); break; } @@ -408,7 +411,7 @@ public: case 44: // Stop the escort and turn towards the altar SetEscortPaused(true); - if (GameObject* altar = me->GetMap()->GetGameObject(_altarGUID)) + if (GameObject* altar = ObjectAccessor::GetGameObject(*me, _altarGUID)) me->SetFacingToObject(altar); break; } @@ -438,7 +441,7 @@ public: break; case SAY_PRIESTESS_ALTAR_9: // move near the escort npc - if (Creature* priestess = me->GetMap()->GetCreature(_firstPriestessGUID)) + if (Creature* priestess = ObjectAccessor::GetCreature(*me, _firstPriestessGUID)) priestess->GetMotionMaster()->MovePoint(0, wingThicketLocations[6].m_positionX, wingThicketLocations[6].m_positionY, wingThicketLocations[6].m_positionZ); break; case SAY_PRIESTESS_ALTAR_13: @@ -449,7 +452,7 @@ public: _guardEluneGUID = guard->GetGUID(); } // summon the Voice of Elune - if (GameObject* altar = me->GetMap()->GetGameObject(_altarGUID)) + if (GameObject* altar = ObjectAccessor::GetGameObject(*me, _altarGUID)) { if (Creature* voice = me->SummonCreature(NPC_VOICE_ELUNE, altar->GetPositionX(), altar->GetPositionY(), altar->GetPositionZ(), 0, TEMPSUMMON_TIMED_DESPAWN, 30000)) _voiceEluneGUID = voice->GetGUID(); @@ -457,7 +460,7 @@ public: break; case SAY_VOICE_ALTAR_15: // move near the escort npc and continue dialogue - if (Creature* priestess = me->GetMap()->GetCreature(_secondPriestessGUID)) + if (Creature* priestess = ObjectAccessor::GetCreature(*me, _secondPriestessGUID)) { priestess->AI()->Talk(SAY_PRIESTESS_ALTAR_14); priestess->GetMotionMaster()->MovePoint(0, wingThicketLocations[7].m_positionX, wingThicketLocations[7].m_positionY, wingThicketLocations[7].m_positionZ); @@ -465,7 +468,7 @@ public: break; case SAY_PRIESTESS_ALTAR_19: // make the voice of elune leave - if (Creature* guard = me->GetMap()->GetCreature(_guardEluneGUID)) + if (Creature* guard = ObjectAccessor::GetCreature(*me, _guardEluneGUID)) { guard->GetMotionMaster()->MovePoint(0, wingThicketLocations[2].m_positionX, wingThicketLocations[2].m_positionY, wingThicketLocations[2].m_positionZ); guard->DespawnOrUnsummon(4000); @@ -473,7 +476,7 @@ public: break; case SAY_PRIESTESS_ALTAR_20: // make the first priestess leave - if (Creature* priestess = me->GetMap()->GetCreature(_firstPriestessGUID)) + if (Creature* priestess = ObjectAccessor::GetCreature(*me, _firstPriestessGUID)) { priestess->GetMotionMaster()->MovePoint(0, wingThicketLocations[0].m_positionX, wingThicketLocations[0].m_positionY, wingThicketLocations[0].m_positionZ); priestess->DespawnOrUnsummon(4000); @@ -481,7 +484,7 @@ public: break; case SAY_PRIESTESS_ALTAR_21: // make the second priestess leave - if (Creature* priestess = me->GetMap()->GetCreature(_secondPriestessGUID)) + if (Creature* priestess = ObjectAccessor::GetCreature(*me, _secondPriestessGUID)) { priestess->GetMotionMaster()->MovePoint(0, wingThicketLocations[1].m_positionX, wingThicketLocations[1].m_positionY, wingThicketLocations[1].m_positionZ); priestess->DespawnOrUnsummon(4000); @@ -497,7 +500,7 @@ public: break; case SAY_RANSHALLA_END_2: // Turn towards the altar and kneel - quest complete - if (GameObject* altar = me->GetMap()->GetGameObject(_altarGUID)) + if (GameObject* altar = ObjectAccessor::GetGameObject(*me, _altarGUID)) { me->SetFacingToObject(altar); altar->ResetDoorOrButton(); @@ -520,13 +523,13 @@ public: case NPC_RANSHALLA: return me; case NPC_VOICE_ELUNE: - return me->GetMap()->GetCreature(_voiceEluneGUID); + return ObjectAccessor::GetCreature(*me, _voiceEluneGUID); case NPC_PRIESTESS_DATA_1: - return me->GetMap()->GetCreature(_firstPriestessGUID); + return ObjectAccessor::GetCreature(*me, _firstPriestessGUID); case NPC_PRIESTESS_DATA_2: - return me->GetMap()->GetCreature(_secondPriestessGUID); + return ObjectAccessor::GetCreature(*me, _secondPriestessGUID); default: - return NULL; + return nullptr; } } diff --git a/src/server/scripts/Maelstrom/Stonecore/boss_corborus.cpp b/src/server/scripts/Maelstrom/Stonecore/boss_corborus.cpp index 14ab442369a..c622db4f026 100644 --- a/src/server/scripts/Maelstrom/Stonecore/boss_corborus.cpp +++ b/src/server/scripts/Maelstrom/Stonecore/boss_corborus.cpp @@ -16,8 +16,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "CreatureGroups.h" +#include "InstanceScript.h" +#include "ScriptedCreature.h" #include "stonecore.h" // TO-DO: @@ -250,7 +251,7 @@ class boss_corborus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetStonecoreAI(creature); } }; @@ -312,7 +313,7 @@ class npc_rock_borer : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetStonecoreAI(creature); } }; diff --git a/src/server/scripts/Maelstrom/Stonecore/boss_high_priestess_azil.cpp b/src/server/scripts/Maelstrom/Stonecore/boss_high_priestess_azil.cpp index 6aad1be5363..1e7e03ed11e 100644 --- a/src/server/scripts/Maelstrom/Stonecore/boss_high_priestess_azil.cpp +++ b/src/server/scripts/Maelstrom/Stonecore/boss_high_priestess_azil.cpp @@ -16,11 +16,20 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" +#include "DynamicObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MoveSplineInit.h" +#include "MoveSplineInitArgs.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" -#include "Vehicle.h" +#include "ScriptedCreature.h" +#include "Spell.h" +#include "SpellScript.h" #include "stonecore.h" +#include "Vehicle.h" +#include enum Spells { @@ -296,7 +305,7 @@ class boss_high_priestess_azil : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetStonecoreAI(creature); } }; @@ -330,7 +339,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetStonecoreAI(creature); } }; @@ -388,7 +397,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetStonecoreAI(creature); } }; @@ -407,7 +416,7 @@ public: DoCast(me, SPELL_SEISMIC_SHARD_VISUAL); Movement::MoveSplineInit init(me); - FillPath(me->GetPosition(), init.Path()); + FillPath(init.Path()); init.SetFly(); init.Launch(); @@ -435,13 +444,10 @@ public: } private: - void FillPath(Position const& pos, Movement::PointsArray& path) + void FillPath(Movement::PointsArray& path) const { G3D::Vector3 point; - - point.x = pos.GetPositionX(); - point.y = pos.GetPositionY(); - point.z = pos.GetPositionZ(); + me->GetPosition(point.x, point.y, point.z); point.x -= 1.0f; path.push_back(point); @@ -461,7 +467,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetStonecoreAI(creature); } }; @@ -477,9 +483,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_ADD_SOUTH)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_ADD_SOUTH }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -513,9 +517,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_ADD_WEST)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_ADD_WEST }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -695,8 +697,8 @@ public: return; target->ExitVehicle(); - DynamicObject* dynamicObject = GetCaster()->GetDynObject(SPELL_SEISMIC_SHARD_TARGETING); - target->CastSpell(dynamicObject->GetPositionX(), dynamicObject->GetPositionY(), dynamicObject->GetPositionZ(), SPELL_SEISMIC_SHARD_MISSLE, true); + if (DynamicObject* dynamicObject = GetCaster()->GetDynObject(SPELL_SEISMIC_SHARD_TARGETING)) + target->CastSpell(dynamicObject->GetPositionX(), dynamicObject->GetPositionY(), dynamicObject->GetPositionZ(), SPELL_SEISMIC_SHARD_MISSLE, true); } void Register() override diff --git a/src/server/scripts/Maelstrom/Stonecore/boss_ozruk.cpp b/src/server/scripts/Maelstrom/Stonecore/boss_ozruk.cpp index 0ce55b6184d..fd4abbb14af 100644 --- a/src/server/scripts/Maelstrom/Stonecore/boss_ozruk.cpp +++ b/src/server/scripts/Maelstrom/Stonecore/boss_ozruk.cpp @@ -17,10 +17,11 @@ #include "ScriptMgr.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" -#include "Vehicle.h" +#include "SpellScript.h" #include "stonecore.h" +#include "TemporarySummon.h" +#include "Vehicle.h" enum Spells { @@ -180,7 +181,7 @@ class boss_ozruk : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetStonecoreAI(creature); } }; diff --git a/src/server/scripts/Maelstrom/Stonecore/boss_slabhide.cpp b/src/server/scripts/Maelstrom/Stonecore/boss_slabhide.cpp index d1dbe8a65ac..bdde41f3d71 100644 --- a/src/server/scripts/Maelstrom/Stonecore/boss_slabhide.cpp +++ b/src/server/scripts/Maelstrom/Stonecore/boss_slabhide.cpp @@ -16,7 +16,12 @@ */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" #include "ScriptedCreature.h" +#include "Spell.h" #include "SpellScript.h" #include "stonecore.h" @@ -265,8 +270,8 @@ class boss_slabhide : public CreatureScript break; case EVENT_LAND: { - Position pos = me->GetPosition(); - pos.m_positionZ = me->GetMap()->GetHeight(me->GetPhaseShift(), pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ()); + Position pos(*me); + me->UpdateGroundPositionZ(pos.m_positionX, pos.m_positionY, pos.m_positionZ); me->GetMotionMaster()->MoveLand(POINT_SLABHIDE_LAND, pos); break; } @@ -293,18 +298,16 @@ class boss_slabhide : public CreatureScript void DespawnAll() { // Despawn stalactite triggers npcs - std::list listStalactiteTrigger; + std::vector listStalactiteTrigger; me->GetCreatureListWithEntryInGrid(listStalactiteTrigger, NPC_STALACTITE_TRIGGER, 200.0f); - if (!listStalactiteTrigger.empty()) - for (std::list::const_iterator itr = listStalactiteTrigger.begin(); itr != listStalactiteTrigger.end(); ++itr) - (*itr)->DespawnOrUnsummon(); + for (Creature* creature : listStalactiteTrigger) + creature->DespawnOrUnsummon(); // Despawn stalactite objects - std::list listStalactite; + std::vector listStalactite; me->GetGameObjectListWithEntryInGrid(listStalactite, GO_STALACTITE, 200.0f); - if (!listStalactite.empty()) - for (std::list::const_iterator itr = listStalactite.begin(); itr != listStalactite.end(); ++itr) - (*itr)->Delete(); + for (GameObject* go : listStalactite) + go->Delete(); } bool _isFlying; @@ -312,7 +315,7 @@ class boss_slabhide : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetStonecoreAI(creature); } }; @@ -355,7 +358,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetStonecoreAI(creature); } }; @@ -401,7 +404,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetStonecoreAI(creature); } }; @@ -478,8 +481,8 @@ public: void ModDestHeight(SpellDestination& dest) { Unit* caster = GetCaster(); - Position pos = caster->GetPosition(); - pos.m_positionZ = caster->GetMap()->GetHeight(caster->GetPhaseShift(), pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), true, 100.0f); + Position pos(*caster); + caster->UpdateGroundPositionZ(pos.m_positionX, pos.m_positionX, pos.m_positionZ); dest.Relocate(pos); } @@ -507,9 +510,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CRYSTAL_STORM_TRIGGER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CRYSTAL_STORM_TRIGGER }); } void HandleDummyEffect(SpellEffIndex /*eff*/) diff --git a/src/server/scripts/Maelstrom/Stonecore/instance_stonecore.cpp b/src/server/scripts/Maelstrom/Stonecore/instance_stonecore.cpp index 2207d089a63..b5740ce118a 100644 --- a/src/server/scripts/Maelstrom/Stonecore/instance_stonecore.cpp +++ b/src/server/scripts/Maelstrom/Stonecore/instance_stonecore.cpp @@ -16,9 +16,11 @@ */ #include "ScriptMgr.h" -#include "Player.h" +#include "Creature.h" #include "CreatureGroups.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" #include "stonecore.h" #define MAX_ENCOUNTER 4 diff --git a/src/server/scripts/Maelstrom/Stonecore/stonecore.cpp b/src/server/scripts/Maelstrom/Stonecore/stonecore.cpp index 0596631e0dd..b9a9cd5c7f0 100644 --- a/src/server/scripts/Maelstrom/Stonecore/stonecore.cpp +++ b/src/server/scripts/Maelstrom/Stonecore/stonecore.cpp @@ -15,12 +15,13 @@ * with this program. If not, see . */ -#include "ObjectGuid.h" -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "SpellScript.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectMgr.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "SpellScript.h" #include "stonecore.h" enum Texts @@ -264,7 +265,7 @@ class npc_sc_millhouse_manastorm : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetStonecoreAI(creature); } }; @@ -343,7 +344,7 @@ class spell_sc_twilight_documents : public SpellScriptLoader void SpawnGameObject(SpellEffIndex /*effIndex*/) { if (WorldLocation* loc = GetHitDest()) - GetCaster()->SummonGameObject(GAMEOBJECT_TWILIGHT_DOCUMENTS, *loc, G3D::Quat(), 7200); + GetCaster()->SummonGameObject(GAMEOBJECT_TWILIGHT_DOCUMENTS, *loc, QuaternionData(), 7200); } void Register() override diff --git a/src/server/scripts/Maelstrom/Stonecore/stonecore.h b/src/server/scripts/Maelstrom/Stonecore/stonecore.h index 5396cd1942f..b395041f058 100644 --- a/src/server/scripts/Maelstrom/Stonecore/stonecore.h +++ b/src/server/scripts/Maelstrom/Stonecore/stonecore.h @@ -18,6 +18,8 @@ #ifndef DEF_STONECORE_H #define DEF_STONECORE_H +#include "CreatureAIImpl.h" + #define SCScriptName "instance_stonecore" #define DataHeader "SC" @@ -74,4 +76,10 @@ enum SCMisc CREATURE_FORMATION_MILLHOUSE_EVENT_LAST_GROUP = 340492, }; +template +inline AI* GetStonecoreAI(T* obj) +{ + return GetInstanceAI(obj, SCScriptName); +} + #endif // DEF_STONECORE diff --git a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/ahnkahet.h b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/ahnkahet.h index 8443e1a125a..f33a7bfef12 100644 --- a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/ahnkahet.h +++ b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/ahnkahet.h @@ -18,6 +18,8 @@ #ifndef AHNKAHET_H_ #define AHNKAHET_H_ +#include "CreatureAIImpl.h" + #define AhnKahetScriptName "instance_ahnkahet" #define DataHeader "AK" @@ -80,10 +82,10 @@ enum AKGameObjectIds GO_SPHERE_2 = 193094 }; -template -AI* GetAhnKahetAI(Creature* creature) +template +inline AI* GetAhnKahetAI(T* obj) { - return GetInstanceAI(creature, AhnKahetScriptName); + return GetInstanceAI(obj, AhnKahetScriptName); } #endif // AHNKAHET_H_ diff --git a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_amanitar.cpp b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_amanitar.cpp index 0a3c2086d67..b8df1aab44b 100644 --- a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_amanitar.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_amanitar.cpp @@ -16,8 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "ahnkahet.h" +#include "InstanceScript.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Spells { @@ -88,7 +90,7 @@ class boss_amanitar : public CreatureScript for (uint8 i = 0; i < 30; ++i) { Position pos = me->GetRandomNearPosition(30.0f); - pos.m_positionZ = me->GetMap()->GetHeight(me->GetPhaseShift(), pos.GetPositionX(), pos.GetPositionY(), MAX_HEIGHT) + 2.0f; + me->UpdateGroundPositionZ(pos.m_positionX, pos.m_positionY, pos.m_positionZ); if (Creature* trigger = me->SummonCreature(NPC_TRIGGER, pos)) { @@ -227,7 +229,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_amanitar_mushroomsAI(creature); + return GetAhnKahetAI(creature); } }; diff --git a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_elder_nadox.cpp b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_elder_nadox.cpp index 6017ba2c89a..a0d2d423086 100644 --- a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_elder_nadox.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_elder_nadox.cpp @@ -16,10 +16,10 @@ */ #include "ScriptMgr.h" +#include "ahnkahet.h" #include "ScriptedCreature.h" #include "SpellAuras.h" #include "SpellScript.h" -#include "ahnkahet.h" enum Yells { @@ -224,7 +224,7 @@ class npc_ahnkahar_nerubian : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_ahnkahar_nerubianAI(creature); + return GetAhnKahetAI(creature); } }; @@ -238,18 +238,9 @@ class spell_ahn_kahet_swarm : public SpellScriptLoader { PrepareSpellScript(spell_ahn_kahet_swarm_SpellScript); - public: - spell_ahn_kahet_swarm_SpellScript() - { - _targetCount = 0; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SWARM_BUFF)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SWARM_BUFF }); } void CountTargets(std::list& targets) @@ -279,7 +270,7 @@ class spell_ahn_kahet_swarm : public SpellScriptLoader OnEffectHit += SpellEffectFn(spell_ahn_kahet_swarm_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); } - uint32 _targetCount; + uint32 _targetCount = 0; }; SpellScript* GetSpellScript() const override diff --git a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_herald_volazj.cpp b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_herald_volazj.cpp index af5dc4f8f43..a90c823acd7 100644 --- a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_herald_volazj.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_herald_volazj.cpp @@ -20,11 +20,16 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "ahnkahet.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "PhasingHandler.h" #include "Player.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" +#include "SpellMgr.h" +#include "TemporarySummon.h" enum Spells { @@ -106,7 +111,7 @@ public: } } - void SpellHitTarget(Unit* target, const SpellInfo* spell) override + void SpellHitTarget(Unit* target, SpellInfo const* spell) override { if (spell->Id == SPELL_INSANITY) { @@ -131,7 +136,7 @@ public: return; // summon twisted party members for this target - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + Map::PlayerList const& players = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i) { Player* player = i->GetSource(); @@ -152,7 +157,7 @@ public: void ResetPlayersPhase() { - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + Map::PlayerList const& players = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator i = players.begin(); i != players.end(); ++i) { Player* player = i->GetSource(); @@ -216,7 +221,7 @@ public: } // Roll Insanity - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); if (!PlayerList.isEmpty()) { for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -289,7 +294,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAhnKahetAI(creature); } }; 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 6c3427956af..0b45afddadf 100644 --- a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_jedoga_shadowseeker.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_jedoga_shadowseeker.cpp @@ -21,9 +21,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "ahnkahet.h" - +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Yells { @@ -326,7 +328,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAhnKahetAI(creature); } }; @@ -429,7 +431,7 @@ public: { case 1: { - Creature* boss = me->GetMap()->GetCreature(instance->GetGuidData(DATA_JEDOGA_SHADOWSEEKER)); + Creature* boss = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_JEDOGA_SHADOWSEEKER)); if (boss) { ENSURE_AI(boss_jedoga_shadowseeker::boss_jedoga_shadowseekerAI, boss->AI())->bOpFerok = true; @@ -495,7 +497,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAhnKahetAI(creature); } }; @@ -578,7 +580,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAhnKahetAI(creature); } }; 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 19badd46a51..549f06ae7b7 100644 --- a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_prince_taldaram.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/boss_prince_taldaram.cpp @@ -16,11 +16,17 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "Player.h" #include "ahnkahet.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "Spell.h" +#include "SpellScript.h" enum Spells { @@ -254,7 +260,7 @@ class boss_prince_taldaram : public CreatureScript if (_embraceTargetGUID) return ObjectAccessor::GetUnit(*me, _embraceTargetGUID); - return NULL; + return nullptr; } void RemovePrison() @@ -383,14 +389,12 @@ class go_prince_taldaram_sphere : public GameObjectScript struct go_prince_taldaram_sphereAI : public GameObjectAI { - go_prince_taldaram_sphereAI(GameObject* go) : GameObjectAI(go) { } + go_prince_taldaram_sphereAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* /*player*/) override { - InstanceScript* instance = me->GetInstanceScript(); - if (!instance) - return false; - Creature* PrinceTaldaram = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_PRINCE_TALDARAM)); if (PrinceTaldaram && PrinceTaldaram->IsAlive()) { @@ -417,7 +421,7 @@ class go_prince_taldaram_sphere : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return new go_prince_taldaram_sphereAI(go); + return GetAhnKahetAI(go); } }; @@ -433,11 +437,7 @@ class spell_prince_taldaram_conjure_flame_sphere : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FLAME_SPHERE_SUMMON_1) - || !sSpellMgr->GetSpellInfo(SPELL_FLAME_SPHERE_SUMMON_2) - || !sSpellMgr->GetSpellInfo(SPELL_FLAME_SPHERE_SUMMON_3)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FLAME_SPHERE_SUMMON_1, SPELL_FLAME_SPHERE_SUMMON_2, SPELL_FLAME_SPHERE_SUMMON_3 }); } void HandleScript(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/instance_ahnkahet.cpp b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/instance_ahnkahet.cpp index 88576ff9bc5..fbafafa5d32 100644 --- a/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/instance_ahnkahet.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/Ahnkahet/instance_ahnkahet.cpp @@ -16,9 +16,10 @@ */ #include "ScriptMgr.h" -#include "AreaBoundary.h" #include "ahnkahet.h" +#include "AreaBoundary.h" #include "Creature.h" +#include "CreatureAI.h" #include "GameObject.h" #include "InstanceScript.h" #include "Map.h" diff --git a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/azjol_nerub.h b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/azjol_nerub.h index 8a251b90d3e..63d3db5449a 100644 --- a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/azjol_nerub.h +++ b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/azjol_nerub.h @@ -18,6 +18,9 @@ #ifndef AZJOL_NERUB_H_ #define AZJOL_NERUB_H_ +#include "CreatureAIImpl.h" + +#define AzjolNerubScriptName "instance_azjol_nerub" #define DataHeader "AN" uint32 const EncounterCount = 3; @@ -63,4 +66,10 @@ enum ANGameObjectIds GO_ANUBARAK_DOOR_3 = 192398 }; +template +inline AI* GetAzjolNerubAI(T* obj) +{ + return GetInstanceAI(obj, AzjolNerubScriptName); +} + #endif // AZJOL_NERUB_H_ diff --git a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_anubarak.cpp b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_anubarak.cpp index abdb09e1568..306caa6c3f5 100644 --- a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_anubarak.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_anubarak.cpp @@ -16,10 +16,16 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "PassiveAI.h" #include "azjol_nerub.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "PassiveAI.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum Spells { @@ -405,7 +411,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -463,7 +469,7 @@ class npc_anubarak_anub_ar_darter : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -530,7 +536,7 @@ class npc_anubarak_anub_ar_assassin : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -565,7 +571,7 @@ class npc_anubarak_anub_ar_guardian : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -600,7 +606,7 @@ class npc_anubarak_anub_ar_venomancer : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -628,7 +634,7 @@ class npc_anubarak_impale_target : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -643,7 +649,7 @@ class spell_anubarak_pound : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - return sSpellMgr->GetSpellInfo(SPELL_POUND_DAMAGE) != nullptr; + return ValidateSpellInfo({ SPELL_POUND_DAMAGE }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -676,7 +682,7 @@ class spell_anubarak_carrion_beetles : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - return (sSpellMgr->GetSpellInfo(SPELL_CARRION_BEETLE) != nullptr); + return ValidateSpellInfo({ SPELL_CARRION_BEETLE }); } void HandlePeriodic(AuraEffect const* /*eff*/) diff --git a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_hadronox.cpp b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_hadronox.cpp index 6ef9fc9e0f2..cdb7b99372b 100644 --- a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_hadronox.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_hadronox.cpp @@ -16,11 +16,15 @@ */ #include "ScriptMgr.h" +#include "azjol_nerub.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "SpellAuras.h" #include "SpellAuraEffects.h" -#include "azjol_nerub.h" +#include "TemporarySummon.h" enum Events { @@ -391,7 +395,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -569,7 +573,7 @@ class npc_anub_ar_crusher : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -612,7 +616,7 @@ class npc_anub_ar_crusher_champion : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -655,7 +659,7 @@ class npc_anub_ar_crusher_crypt_fiend : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -698,7 +702,7 @@ class npc_anub_ar_crusher_necromancer : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -857,7 +861,7 @@ class npc_anub_ar_champion : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -899,7 +903,7 @@ class npc_anub_ar_crypt_fiend : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -941,7 +945,7 @@ class npc_anub_ar_necromancer : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -953,9 +957,7 @@ class spell_hadronox_periodic_summon_template_AuraScript : public AuraScript bool Validate(SpellInfo const* /*spell*/) override { - return - (sSpellMgr->GetSpellInfo(_topSpellId) != nullptr) && - (sSpellMgr->GetSpellInfo(_bottomSpellId) != nullptr); + return ValidateSpellInfo({ _topSpellId, _bottomSpellId }); } void HandleApply(AuraEffect const* /*eff*/, AuraEffectHandleModes /*mode*/) @@ -1058,7 +1060,7 @@ class spell_hadronox_leeching_poison : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - return sSpellMgr->GetSpellInfo(SPELL_LEECH_POISON_HEAL) != nullptr; + return ValidateSpellInfo({ SPELL_LEECH_POISON_HEAL }); } void HandleEffectRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1096,11 +1098,7 @@ class spell_hadronox_web_doors : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - return ( - sSpellMgr->GetSpellInfo(SPELL_SUMMON_CHAMPION_PERIODIC) && - sSpellMgr->GetSpellInfo(SPELL_SUMMON_CRYPT_FIEND_PERIODIC) && - sSpellMgr->GetSpellInfo(SPELL_SUMMON_NECROMANCER_PERIODIC) - ); + return ValidateSpellInfo({ SPELL_SUMMON_CHAMPION_PERIODIC, SPELL_SUMMON_CRYPT_FIEND_PERIODIC, SPELL_SUMMON_NECROMANCER_PERIODIC }); } void HandleDummy(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_krikthir_the_gatewatcher.cpp b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_krikthir_the_gatewatcher.cpp index 067a60021ed..00184fc36c2 100644 --- a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_krikthir_the_gatewatcher.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/boss_krikthir_the_gatewatcher.cpp @@ -19,13 +19,15 @@ * Comment: Find in the future best timers and the event is not implemented. */ -#include "Containers.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "PassiveAI.h" -#include "SpellAuras.h" #include "azjol_nerub.h" +#include "Containers.h" +#include "InstanceScript.h" +#include "PassiveAI.h" +#include "ScriptedCreature.h" +#include "SpellAuras.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum Events { @@ -318,7 +320,7 @@ class boss_krik_thir : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -481,7 +483,7 @@ class npc_watcher_gashra : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -559,7 +561,7 @@ class npc_watcher_narjil : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -637,7 +639,7 @@ class npc_watcher_silthik : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -697,7 +699,7 @@ class npc_anub_ar_warrior : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -765,7 +767,7 @@ class npc_anub_ar_skirmisher : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -826,7 +828,7 @@ class npc_anub_ar_shadowcaster : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -853,7 +855,7 @@ class npc_skittering_swarmer : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -886,7 +888,7 @@ class npc_skittering_infector : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -909,7 +911,7 @@ class npc_gatewatcher_web_wrap : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetAzjolNerubAI(creature); } }; @@ -976,7 +978,7 @@ class spell_anub_ar_skirmisher_fixtate : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - return sSpellMgr->GetSpellInfo(SPELL_FIXTATE_TRIGGERED) != nullptr; + return ValidateSpellInfo({ SPELL_FIXTATE_TRIGGERED }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -1008,7 +1010,7 @@ class spell_gatewatcher_web_wrap : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - return sSpellMgr->GetSpellInfo(SPELL_WEB_WRAP_WRAPPED) != nullptr; + return ValidateSpellInfo({ SPELL_WEB_WRAP_WRAPPED }); } void HandleEffectRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/instance_azjol_nerub.cpp b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/instance_azjol_nerub.cpp index cdeb2730c40..077e8189303 100644 --- a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/instance_azjol_nerub.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/instance_azjol_nerub.cpp @@ -16,34 +16,38 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" +#include "AreaBoundary.h" #include "azjol_nerub.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "InstanceScript.h" +#include "Map.h" DoorData const doorData[] = { - { GO_KRIKTHIR_DOOR, DATA_KRIKTHIR, DOOR_TYPE_PASSAGE }, - { GO_ANUBARAK_DOOR_1, DATA_ANUBARAK, DOOR_TYPE_ROOM }, - { GO_ANUBARAK_DOOR_2, DATA_ANUBARAK, DOOR_TYPE_ROOM }, - { GO_ANUBARAK_DOOR_3, DATA_ANUBARAK, DOOR_TYPE_ROOM }, - { 0, 0, DOOR_TYPE_ROOM } // END + { GO_KRIKTHIR_DOOR, DATA_KRIKTHIR, DOOR_TYPE_PASSAGE }, + { GO_ANUBARAK_DOOR_1, DATA_ANUBARAK, DOOR_TYPE_ROOM }, + { GO_ANUBARAK_DOOR_2, DATA_ANUBARAK, DOOR_TYPE_ROOM }, + { GO_ANUBARAK_DOOR_3, DATA_ANUBARAK, DOOR_TYPE_ROOM }, + { 0, 0, DOOR_TYPE_ROOM } // END }; ObjectData const creatureData[] = { - { NPC_KRIKTHIR, DATA_KRIKTHIR }, - { NPC_HADRONOX, DATA_HADRONOX }, - { NPC_ANUBARAK, DATA_ANUBARAK }, - { NPC_WATCHER_NARJIL, DATA_WATCHER_GASHRA }, - { NPC_WATCHER_GASHRA, DATA_WATCHER_SILTHIK }, - { NPC_WATCHER_SILTHIK, DATA_WATCHER_NARJIL }, - { 0, 0 } // END + { NPC_KRIKTHIR, DATA_KRIKTHIR }, + { NPC_HADRONOX, DATA_HADRONOX }, + { NPC_ANUBARAK, DATA_ANUBARAK }, + { NPC_WATCHER_NARJIL, DATA_WATCHER_GASHRA }, + { NPC_WATCHER_GASHRA, DATA_WATCHER_SILTHIK }, + { NPC_WATCHER_SILTHIK, DATA_WATCHER_NARJIL }, + { 0, 0 } // END }; ObjectData const gameobjectData[] = { - { GO_ANUBARAK_DOOR_1, DATA_ANUBARAK_WALL }, + { GO_ANUBARAK_DOOR_1, DATA_ANUBARAK_WALL }, { GO_ANUBARAK_DOOR_3, DATA_ANUBARAK_WALL_2 }, - { 0, 0 } // END + { 0, 0 } // END }; BossBoundaryData const boundaries = @@ -56,7 +60,7 @@ BossBoundaryData const boundaries = class instance_azjol_nerub : public InstanceMapScript { public: - instance_azjol_nerub() : InstanceMapScript("instance_azjol_nerub", 601) { } + instance_azjol_nerub() : InstanceMapScript(AzjolNerubScriptName, 601) { } struct instance_azjol_nerub_InstanceScript : public InstanceScript { diff --git a/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/boss_sartharion.cpp b/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/boss_sartharion.cpp index 893987497cb..300d0dd1f69 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/boss_sartharion.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/boss_sartharion.cpp @@ -16,12 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "Cell.h" #include "CellImpl.h" +#include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "obsidian_sanctum.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Enums { diff --git a/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/instance_obsidian_sanctum.cpp b/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/instance_obsidian_sanctum.cpp index f4e926bf3d3..2a844a5af99 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/instance_obsidian_sanctum.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/instance_obsidian_sanctum.cpp @@ -16,7 +16,10 @@ */ #include "ScriptMgr.h" +#include "AreaBoundary.h" +#include "Creature.h" #include "InstanceScript.h" +#include "Map.h" #include "obsidian_sanctum.h" /* Obsidian Sanctum encounters: diff --git a/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/obsidian_sanctum.cpp b/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/obsidian_sanctum.cpp index 14a16d60f98..1440a1241aa 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/obsidian_sanctum.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/obsidian_sanctum.cpp @@ -16,12 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "Cell.h" -#include "CellImpl.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "obsidian_sanctum.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Enums { @@ -322,7 +325,7 @@ struct dummy_dragonAI : public ScriptedAI void JustDied(Unit* /*killer*/) override { if (!_canLoot) - me->SetLootRecipient(NULL); + me->SetLootRecipient(nullptr); uint32 spellId = 0; @@ -653,7 +656,6 @@ class npc_acolyte_of_shadron : public CreatureScript instance->SetBossState(DATA_PORTAL_OPEN, NOT_STARTED); Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); - if (PlayerList.isEmpty()) return; @@ -736,8 +738,7 @@ class npc_acolyte_of_vesperon : public CreatureScript vesperon->RemoveAurasDueToSpell(SPELL_TWILIGHT_TORMENT_VESP); } - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); - + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); if (PlayerList.isEmpty()) return; @@ -904,7 +905,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_flame_tsunamiAI(creature); + return GetObsidianSanctumAI(creature); } }; @@ -958,7 +959,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_twilight_fissureAI(creature); + return GetObsidianSanctumAI(creature); } }; @@ -1012,7 +1013,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_twilight_whelpAI(creature); + return GetObsidianSanctumAI(creature); } }; diff --git a/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/obsidian_sanctum.h b/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/obsidian_sanctum.h index 2bf0ca7f8c5..d3061dce23b 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/obsidian_sanctum.h +++ b/src/server/scripts/Northrend/ChamberOfAspects/ObsidianSanctum/obsidian_sanctum.h @@ -18,6 +18,8 @@ #ifndef OBSIDIAN_SANCTUM_H_ #define OBSIDIAN_SANCTUM_H_ +#include "CreatureAIImpl.h" + #define OSScriptName "instance_obsidian_sanctum" #define DataHeader "OS" @@ -46,10 +48,10 @@ enum OSGameObjectIds GO_TWILIGHT_PORTAL = 193988 }; -template -AI* GetObsidianSanctumAI(Creature* creature) +template +inline AI* GetObsidianSanctumAI(T* obj) { - return GetInstanceAI(creature, OSScriptName); + return GetInstanceAI(obj, OSScriptName); } #endif // OBSIDIAN_SANCTUM_H_ diff --git a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_baltharus_the_warborn.cpp b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_baltharus_the_warborn.cpp index 30a6eb7bd43..929af17a605 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_baltharus_the_warborn.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_baltharus_the_warborn.cpp @@ -15,11 +15,12 @@ * with this program. If not, see . */ -#include "ScriptedCreature.h" #include "ScriptMgr.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "InstanceScript.h" #include "ruby_sanctum.h" +#include "ScriptedCreature.h" +#include "SpellAuras.h" +#include "SpellScript.h" enum Texts { diff --git a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_general_zarithrian.cpp b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_general_zarithrian.cpp index 1c3541e110c..48552a341cc 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_general_zarithrian.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_general_zarithrian.cpp @@ -16,9 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ruby_sanctum.h" +#include "ScriptedCreature.h" enum Texts { diff --git a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_halion.cpp b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_halion.cpp index a20c1bd55af..ede7e912b44 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_halion.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_halion.cpp @@ -16,15 +16,20 @@ */ #include "ScriptMgr.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "Spell.h" -#include "Vehicle.h" -#include "MapManager.h" +#include "DBCStores.h" +#include "GameObject.h" #include "GameObjectAI.h" -#include "ScriptedCreature.h" -#include "ruby_sanctum.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ruby_sanctum.h" +#include "ScriptedCreature.h" +#include "Spell.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "Vehicle.h" enum Texts { @@ -762,7 +767,7 @@ class npc_halion_controller : public CreatureScript void DoCheckEvade() { - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + 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() && CheckBoundary(player) && !player->IsGameMaster()) @@ -1444,9 +1449,7 @@ class spell_halion_combustion_consumption : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(_markSpell)) - return false; - return true; + return ValidateSpellInfo({ _markSpell }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1498,9 +1501,7 @@ class spell_halion_combustion_consumption_periodic : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].TriggerSpell)) - return false; - return true; + return ValidateSpellInfo({ spellInfo->Effects[EFFECT_0].TriggerSpell }); } void HandleTick(AuraEffect const* aurEff) @@ -1544,9 +1545,7 @@ class spell_halion_marks : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(_summonSpellId)) - return false; - return true; + return ValidateSpellInfo({ _summonSpellId, _removeSpellId }); } /// We were purged. Force removed stacks to zero and trigger the appropriated remove handler. @@ -1627,7 +1626,7 @@ class spell_halion_damage_aoe_summon : public SpellScriptLoader class spell_halion_twilight_realm_handlers : public SpellScriptLoader { public: - spell_halion_twilight_realm_handlers(const char* scriptName, uint32 beforeHitSpell, bool isApplyHandler) : SpellScriptLoader(scriptName), + spell_halion_twilight_realm_handlers(char const* scriptName, uint32 beforeHitSpell, bool isApplyHandler) : SpellScriptLoader(scriptName), _beforeHitSpell(beforeHitSpell), _isApplyHandler(isApplyHandler) { } @@ -1642,9 +1641,7 @@ class spell_halion_twilight_realm_handlers : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(_beforeHitSpellId)) - return false; - return true; + return ValidateSpellInfo({ _beforeHitSpellId }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*handle*/) @@ -1701,11 +1698,7 @@ class spell_halion_clear_debuffs : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CLEAR_DEBUFFS)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_TWILIGHT_REALM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CLEAR_DEBUFFS, SPELL_TWILIGHT_REALM }); } void HandleScript(SpellEffIndex effIndex) @@ -1789,9 +1782,7 @@ class spell_halion_twilight_phasing : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_TWILIGHT_PORTAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_TWILIGHT_PORTAL }); } void Phase() diff --git a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_saviana_ragefire.cpp b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_saviana_ragefire.cpp index 3804584a01a..3f2aef49d2c 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_saviana_ragefire.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/boss_saviana_ragefire.cpp @@ -16,9 +16,11 @@ */ #include "ScriptMgr.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ruby_sanctum.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "ruby_sanctum.h" enum Texts { @@ -229,10 +231,7 @@ class spell_saviana_conflagration_init : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FLAME_BEACON) - || !sSpellMgr->GetSpellInfo(SPELL_CONFLAGRATION_2)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FLAME_BEACON, SPELL_CONFLAGRATION_2 }); } void FilterTargets(std::list& targets) 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 de4a1f16bec..6e608d017b9 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/instance_ruby_sanctum.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/instance_ruby_sanctum.cpp @@ -15,14 +15,17 @@ * with this program. If not, see . */ -#include "InstanceScript.h" -#include "Player.h" -#include "ScriptedCreature.h" #include "ScriptMgr.h" -#include "TemporarySummon.h" -#include "WorldPacket.h" +#include "AreaBoundary.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" #include "ruby_sanctum.h" +Position const HalionControllerSpawnPos = { 3156.037f, 533.2656f, 72.97205f, 0.0f }; + BossBoundaryData const boundaries = { { DATA_GENERAL_ZARITHRIAN, new EllipseBoundary(Position(3013.409f, 529.492f), 45.0, 100.0) }, @@ -68,7 +71,6 @@ ObjectData const gameObjectData[] = { 0, 0 } //END }; - class instance_ruby_sanctum : public InstanceMapScript { public: diff --git a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.cpp b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.cpp index 73ce04363e6..512a1552ec1 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.cpp +++ b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.cpp @@ -16,11 +16,13 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "Player.h" +#include "ruby_sanctum.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" #include "SpellScript.h" -#include "ruby_sanctum.h" -#include "Player.h" enum Texts { @@ -185,9 +187,7 @@ class spell_ruby_sanctum_rallying_shout : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RALLY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RALLY }); } void CountTargets(std::list& targets) diff --git a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.h b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.h index 8c97b4a04b3..9057ad4bee0 100644 --- a/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.h +++ b/src/server/scripts/Northrend/ChamberOfAspects/RubySanctum/ruby_sanctum.h @@ -18,13 +18,13 @@ #ifndef RUBY_SANCTUM_H_ #define RUBY_SANCTUM_H_ +#include "CreatureAIImpl.h" + #define RSScriptName "instance_ruby_sanctum" #define DataHeader "RS" uint32 const EncounterCount = 4; -Position const HalionControllerSpawnPos = {3156.037f, 533.2656f, 72.97205f, 0.0f}; - enum RSDataTypes { // Encounter States/Boss GUIDs @@ -129,25 +129,10 @@ enum RSInstanceSpell SPELL_BERSERK = 26662 }; -template -CreatureAI* GetRubySanctumAI(Creature* creature) +template +inline AI* GetRubySanctumAI(T* obj) { - if (InstanceMap* instance = creature->GetMap()->ToInstanceMap()) - if (instance->GetInstanceScript()) - if (instance->GetScriptId() == sObjectMgr->GetScriptId(RSScriptName)) - return new AI(creature); - return nullptr; -} - -template -GameObjectAI* GetRubySanctumAI(GameObject* go) -{ - if (InstanceMap* instance = go->GetMap()->ToInstanceMap()) - if (instance->GetInstanceScript()) - if (instance->GetScriptId() == sObjectMgr->GetScriptId(RSScriptName)) - return new AI(go); - - return nullptr; + return GetInstanceAI(obj, RSScriptName); } #endif // RUBY_SANCTUM_H_ diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_argent_challenge.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_argent_challenge.cpp index 20a22e301b8..b99e63286e2 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_argent_challenge.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_argent_challenge.cpp @@ -23,10 +23,13 @@ SDCategory: Trial of the Champion EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "trial_of_the_champion.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedEscortAI.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "trial_of_the_champion.h" /* enum Yells { @@ -109,7 +112,7 @@ enum Spells SPELL_WAKING_NIGHTMARE_H = 67677 }; -class OrientationCheck : public std::unary_function +class OrientationCheck { public: explicit OrientationCheck(Unit* _caster) : caster(_caster) { } @@ -253,7 +256,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -415,7 +418,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -492,7 +495,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_memoryAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -605,7 +608,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -650,10 +653,7 @@ class spell_paletress_summon_memory : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - for (uint8 i = 0; i < 25; ++i) - if (!sSpellMgr->GetSpellInfo(memorySpellId[i])) - return false; - return true; + return ValidateSpellInfo(memorySpellId); } void FilterTargets(std::list& targets) @@ -668,7 +668,7 @@ class spell_paletress_summon_memory : public SpellScriptLoader void HandleScript(SpellEffIndex /*effIndex*/) { - GetHitUnit()->CastSpell(GetHitUnit(), memorySpellId[urand(0, 24)], true, NULL, NULL, GetCaster()->GetGUID()); + GetHitUnit()->CastSpell(GetHitUnit(), memorySpellId[urand(0, 24)], true, nullptr, nullptr, GetCaster()->GetGUID()); } void Register() override diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_black_knight.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_black_knight.cpp index 85238635302..57cf5d293ac 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_black_knight.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_black_knight.cpp @@ -23,7 +23,7 @@ SDCategory: Trial of the Champion EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "ScriptedEscortAI.h" #include "trial_of_the_champion.h" @@ -296,7 +296,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -345,7 +345,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_risen_ghoulAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -374,7 +374,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_black_knight_skeletal_gryphonAI(creature); + return GetTrialOfTheChampionAI(creature); } }; diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_grand_champions.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_grand_champions.cpp index 124a39edda1..02d060530b2 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_grand_champions.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_grand_champions.cpp @@ -24,11 +24,13 @@ SDCategory: Trial Of the Champion EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" -#include "Vehicle.h" -#include "trial_of_the_champion.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "trial_of_the_champion.h" +#include "Vehicle.h" enum Spells { @@ -95,8 +97,7 @@ const Point MovementPoint[] = */ void AggroAllPlayers(Creature* temp) { - Map::PlayerList const &PlList = temp->GetMap()->GetPlayers(); - + Map::PlayerList const& PlList = temp->GetMap()->GetPlayers(); if (PlList.isEmpty()) return; @@ -303,7 +304,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -440,7 +441,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -583,7 +584,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -734,7 +735,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -894,7 +895,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; @@ -1019,7 +1020,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; 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 58ab85d0c79..ecdfa11e2f0 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 @@ -22,22 +22,22 @@ SDCategory: Trial Of the Champion EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "GameObject.h" #include "InstanceScript.h" -#include "trial_of_the_champion.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" #include "Player.h" +#include "trial_of_the_champion.h" #define MAX_ENCOUNTER 4 class instance_trial_of_the_champion : public InstanceMapScript { public: - instance_trial_of_the_champion() : InstanceMapScript("instance_trial_of_the_champion", 650) { } - - InstanceScript* GetInstanceScript(InstanceMap* map) const override - { - return new instance_trial_of_the_champion_InstanceMapScript(map); - } + instance_trial_of_the_champion() : InstanceMapScript(ToCScriptName, 650) { } struct instance_trial_of_the_champion_InstanceMapScript : public InstanceScript { @@ -89,7 +89,7 @@ public: void OnCreatureCreate(Creature* creature) override { - Map::PlayerList const &players = instance->GetPlayers(); + Map::PlayerList const& players = instance->GetPlayers(); uint32 TeamInInstance = 0; if (!players.isEmpty()) @@ -160,7 +160,7 @@ public: uiMovementDone = uiData; if (uiMovementDone == 3) { - if (Creature* pAnnouncer = instance->GetCreature(uiAnnouncerGUID)) + if (Creature* pAnnouncer = instance->GetCreature(uiAnnouncerGUID)) pAnnouncer->AI()->SetData(DATA_IN_POSITION, 0); } break; @@ -171,16 +171,17 @@ public: for (GuidList::const_iterator itr = VehicleList.begin(); itr != VehicleList.end(); ++itr) if (Creature* summon = instance->GetCreature(*itr)) summon->RemoveFromWorld(); - }else if (uiData == DONE) + } + else if (uiData == DONE) { ++uiGrandChampionsDeaths; if (uiGrandChampionsDeaths == 3) { - if (Creature* pAnnouncer = instance->GetCreature(uiAnnouncerGUID)) + if (Creature* pAnnouncer = instance->GetCreature(uiAnnouncerGUID)) { 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, G3D::Quat(), 90000); + pAnnouncer->SummonGameObject(instance->IsHeroic() ? GO_CHAMPIONS_LOOT_H : GO_CHAMPIONS_LOOT, 746.59f, 618.49f, 411.09f, 1.42f, QuaternionData(), 90000); } } } @@ -189,7 +190,7 @@ public: uiArgentSoldierDeaths = uiData; if (uiArgentSoldierDeaths == 9) { - if (Creature* pBoss = instance->GetCreature(uiArgentChampionGUID)) + if (Creature* pBoss = instance->GetCreature(uiArgentChampionGUID)) { pBoss->GetMotionMaster()->MovePoint(0, 746.88f, 618.74f, 411.06f); pBoss->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); @@ -203,7 +204,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, G3D::Quat(), 90000); + pAnnouncer->SummonGameObject(instance->IsHeroic() ? GO_EADRIC_LOOT_H : GO_EADRIC_LOOT, 746.59f, 618.49f, 411.09f, 1.42f, QuaternionData(), 90000); } break; case BOSS_ARGENT_CHALLENGE_P: @@ -212,7 +213,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, G3D::Quat(), 90000); + pAnnouncer->SummonGameObject(instance->IsHeroic() ? GO_PALETRESS_LOOT_H : GO_PALETRESS_LOOT, 746.59f, 618.49f, 411.09f, 1.42f, QuaternionData(), 90000); } break; } @@ -287,7 +288,7 @@ public: return str_data; } - void Load(const char* in) override + void Load(char const* in) override { if (!in) { @@ -316,12 +317,18 @@ public: uiGrandChampionsDeaths = data4; uiMovementDone = data5; - } else OUT_LOAD_INST_DATA_FAIL; + } + else + OUT_LOAD_INST_DATA_FAIL; OUT_LOAD_INST_DATA_COMPLETE; } }; + InstanceScript* GetInstanceScript(InstanceMap* map) const override + { + return new instance_trial_of_the_champion_InstanceMapScript(map); + } }; void AddSC_instance_trial_of_the_champion() diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/trial_of_the_champion.cpp b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/trial_of_the_champion.cpp index bd8b4f07d90..1b2d2664ad2 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/trial_of_the_champion.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/trial_of_the_champion.cpp @@ -27,11 +27,17 @@ npc_announcer_toc5 EndContentData */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" +#include "TemporarySummon.h" #include "trial_of_the_champion.h" #include "Vehicle.h" -#include "Player.h" enum Yells { @@ -362,8 +368,7 @@ public: void AggroAllPlayers(Creature* temp) { - Map::PlayerList const &PlList = me->GetMap()->GetPlayers(); - + Map::PlayerList const& PlList = me->GetMap()->GetPlayers(); if (PlList.isEmpty()) return; @@ -487,7 +492,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheChampionAI(creature); } }; diff --git a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/trial_of_the_champion.h b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/trial_of_the_champion.h index c2b0031ba63..3ebc6fd1437 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/trial_of_the_champion.h +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/trial_of_the_champion.h @@ -19,6 +19,9 @@ #ifndef DEF_TOC_H #define DEF_TOC_H +#include "CreatureAIImpl.h" + +#define ToCScriptName "instance_trial_of_the_champion" #define DataHeader "TC" enum TCData @@ -127,4 +130,10 @@ enum TCVehicles VEHICLE_BLACK_KNIGHT = 35491 }; +template +inline AI* GetTrialOfTheChampionAI(T* obj) +{ + return GetInstanceAI(obj, ToCScriptName); +} + #endif 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 bea95c5fce3..2a2a0a685b9 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_anubarak_trial.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_anubarak_trial.cpp @@ -22,11 +22,15 @@ // Scarab - Kill credit isn't crediting? #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "trial_of_the_crusader.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" -#include +#include "SpellMgr.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "trial_of_the_crusader.h" enum Yells { @@ -428,7 +432,7 @@ class boss_anubarak_trial : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); }; }; @@ -507,7 +511,7 @@ class npc_swarm_scarab : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); }; }; @@ -601,7 +605,7 @@ class npc_nerubian_burrower : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); }; }; @@ -627,7 +631,8 @@ class npc_frost_sphere : public CreatureScript if (me->GetHealth() <= damage) { damage = 0; - float floorZ = me->GetMap()->GetHeight(me->GetPhaseShift(), me->GetPositionX(), me->GetPositionY(), me->GetPositionZ()); + float floorZ = me->GetPositionZ(); + me->UpdateGroundPositionZ(me->GetPositionX(), me->GetPositionY(), floorZ); if (fabs(me->GetPositionZ() - floorZ) < 0.1f) { // we are close to the ground @@ -672,7 +677,7 @@ class npc_frost_sphere : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_frost_sphereAI(creature); + return GetTrialOfTheCrusaderAI(creature); }; }; @@ -825,7 +830,7 @@ class npc_anubarak_spike : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_anubarak_spikeAI(creature); + return GetTrialOfTheCrusaderAI(creature); }; }; @@ -871,9 +876,7 @@ class spell_anubarak_leeching_swarm : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_LEECHING_SWARM_DMG) || !sSpellMgr->GetSpellInfo(SPELL_LEECHING_SWARM_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_LEECHING_SWARM_DMG, SPELL_LEECHING_SWARM_HEAL }); } void HandleEffectPeriodic(AuraEffect const* aurEff) 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 3d5fbea4cb0..6bcda472966 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_faction_champions.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_faction_champions.cpp @@ -17,12 +17,17 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "trial_of_the_crusader.h" -#include "Player.h" #include "GridNotifiers.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "trial_of_the_crusader.h" enum Yells { @@ -339,6 +344,32 @@ enum Events EVENT_SPELL_LOCK = 2 }; +Position const FactionChampionLoc[] = +{ + { 514.231f, 105.569f, 418.234f, 0 }, // 0 - Horde Initial Pos 0 + { 508.334f, 115.377f, 418.234f, 0 }, // 1 - Horde Initial Pos 1 + { 506.454f, 126.291f, 418.234f, 0 }, // 2 - Horde Initial Pos 2 + { 506.243f, 106.596f, 421.592f, 0 }, // 3 - Horde Initial Pos 3 + { 499.885f, 117.717f, 421.557f, 0 }, // 4 - Horde Initial Pos 4 + + { 613.127f, 100.443f, 419.74f, 0 }, // 5 - Ally Initial Pos 0 + { 621.126f, 128.042f, 418.231f, 0 }, // 6 - Ally Initial Pos 1 + { 618.829f, 113.606f, 418.232f, 0 }, // 7 - Ally Initial Pos 2 + { 625.845f, 112.914f, 421.575f, 0 }, // 8 - Ally Initial Pos 3 + { 615.566f, 109.653f, 418.234f, 0 }, // 9 - Ally Initial Pos 4 + + { 535.469f, 113.012f, 394.66f, 0 }, // 10 - Horde Final Pos 0 + { 526.417f, 137.465f, 394.749f, 0 }, // 11 - Horde Final Pos 1 + { 528.108f, 111.057f, 395.289f, 0 }, // 12 - Horde Final Pos 2 + { 519.92f, 134.285f, 395.289f, 0 }, // 13 - Horde Final Pos 3 + { 533.648f, 119.148f, 394.646f, 0 }, // 14 - Horde Final Pos 4 + { 531.399f, 125.63f, 394.708f, 0 }, // 15 - Horde Final Pos 5 + { 528.958f, 131.47f, 394.73f, 0 }, // 16 - Horde Final Pos 6 + { 526.309f, 116.667f, 394.833f, 0 }, // 17 - Horde Final Pos 7 + { 524.238f, 122.411f, 394.819f, 0 }, // 18 - Horde Final Pos 8 + { 521.901f, 128.488f, 394.832f, 0 } // 19 - Horde Final Pos 9 +}; + class boss_toc_champion_controller : public CreatureScript { public: @@ -545,7 +576,7 @@ class boss_toc_champion_controller : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -631,7 +662,7 @@ struct boss_faction_championsAI : public BossAI { if (who->GetTypeId() == TYPEID_PLAYER) { - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + Map::PlayerList const& players = me->GetMap()->GetPlayers(); uint32 TeamInInstance = 0; if (!players.isEmpty()) @@ -655,7 +686,7 @@ struct boss_faction_championsAI : public BossAI std::list lst = DoFindFriendlyMissingBuff(40.0f, spell); std::list::const_iterator itr = lst.begin(); if (lst.empty()) - return NULL; + return nullptr; advance(itr, rand32() % lst.size()); return (*itr); } @@ -670,7 +701,7 @@ struct boss_faction_championsAI : public BossAI if (target && target->getPowerType() == POWER_MANA) return target; } - return NULL; + return nullptr; } uint32 EnemiesInRange(float distance) @@ -835,7 +866,7 @@ class npc_toc_druid : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -928,7 +959,7 @@ class npc_toc_shaman : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1032,7 +1063,7 @@ class npc_toc_paladin : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1117,7 +1148,7 @@ class npc_toc_priest : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1215,7 +1246,7 @@ class npc_toc_shadow_priest : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1306,7 +1337,7 @@ class npc_toc_warlock : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1400,7 +1431,7 @@ class npc_toc_mage : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1502,7 +1533,7 @@ class npc_toc_hunter : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1594,7 +1625,7 @@ class npc_toc_boomkin : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1698,7 +1729,7 @@ class npc_toc_warrior : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1794,7 +1825,7 @@ class npc_toc_dk : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1899,7 +1930,7 @@ class npc_toc_rogue : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -2033,7 +2064,7 @@ class npc_toc_enh_shaman : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -2139,7 +2170,7 @@ class npc_toc_retro_paladin : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -2191,7 +2222,7 @@ class npc_toc_pet_warlock : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -2239,7 +2270,7 @@ class npc_toc_pet_hunter : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -2254,15 +2285,13 @@ class spell_faction_champion_warl_unstable_affliction : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_UNSTABLE_AFFLICTION_DISPEL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_UNSTABLE_AFFLICTION_DISPEL }); } void HandleDispel(DispelInfo* dispelInfo) { if (Unit* caster = GetCaster()) - caster->CastSpell(dispelInfo->GetDispeller(), SPELL_UNSTABLE_AFFLICTION_DISPEL, true, NULL, GetEffect(EFFECT_0)); + caster->CastSpell(dispelInfo->GetDispeller(), SPELL_UNSTABLE_AFFLICTION_DISPEL, true, nullptr, GetEffect(EFFECT_0)); } void Register() override @@ -2288,9 +2317,7 @@ class spell_faction_champion_death_grip : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DEATH_GRIP_PULL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DEATH_GRIP_PULL }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2326,9 +2353,7 @@ class spell_toc_bloodlust : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(AURA_SATED)) - return false; - return true; + return ValidateSpellInfo({ AURA_SATED }); } void RemoveInvalidTargets(std::list& targets) @@ -2367,9 +2392,7 @@ class spell_toc_heroism : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(AURA_EXHAUSTION)) - return false; - return true; + return ValidateSpellInfo({ AURA_EXHAUSTION }); } void RemoveInvalidTargets(std::list& targets) 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 16b0deafa7b..d5cadff348d 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_lord_jaraxxus.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_lord_jaraxxus.cpp @@ -17,9 +17,12 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" +#include "InstanceScript.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellMgr.h" +#include "SpellScript.h" #include "trial_of_the_crusader.h" enum Yells @@ -207,7 +210,7 @@ class boss_jaraxxus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -243,7 +246,7 @@ class npc_legion_flame : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -297,7 +300,7 @@ class npc_infernal_volcano : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_infernal_volcanoAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -350,7 +353,7 @@ class npc_fel_infernal : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -401,7 +404,7 @@ class npc_nether_portal : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_nether_portalAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -479,7 +482,7 @@ class npc_mistress_of_pain : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -591,10 +594,8 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FEL_STREAK)) - return false; - return true; - } + return ValidateSpellInfo({ SPELL_FEL_STREAK }); +} void HandleScript(SpellEffIndex /*effIndex*/) { 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 d2118ae3776..20ce49097d9 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_northrend_beasts.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_northrend_beasts.cpp @@ -17,12 +17,17 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "TemporarySummon.h" #include "trial_of_the_crusader.h" #include "Vehicle.h" -#include "Player.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" enum Yells { @@ -290,11 +295,11 @@ class boss_gormok : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; -class SnobolledTargetSelector : public std::unary_function +class SnobolledTargetSelector { public: SnobolledTargetSelector(Unit const* /*unit*/) { } @@ -463,7 +468,7 @@ class npc_snobold_vassal : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -499,7 +504,7 @@ class npc_firebomb : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -727,7 +732,7 @@ class boss_acidmaw : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -791,7 +796,7 @@ class boss_dreadscale : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -838,7 +843,7 @@ class npc_slime_pool : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1101,7 +1106,7 @@ class boss_icehowl : public CreatureScript } if (events.ExecuteEvent() == EVENT_TRAMPLE) { - Map::PlayerList const &lPlayers = me->GetMap()->GetPlayers(); + Map::PlayerList const& lPlayers = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = lPlayers.begin(); itr != lPlayers.end(); ++itr) { if (Unit* player = itr->GetSource()) @@ -1155,7 +1160,7 @@ class boss_icehowl : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -1170,9 +1175,7 @@ public: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RIDE_PLAYER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RIDE_PLAYER }); } bool Load() override @@ -1268,9 +1271,7 @@ public: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RIDE_PLAYER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RIDE_PLAYER }); } void OnPeriodic(AuraEffect const* /*aurEff*/) @@ -1302,9 +1303,7 @@ public: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PARALYSIS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PARALYSIS }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1340,7 +1339,7 @@ public: slowEff->ChangeAmount(newAmount); if (newAmount <= -100 && !GetTarget()->HasAura(SPELL_PARALYSIS)) - GetTarget()->CastSpell(GetTarget(), SPELL_PARALYSIS, true, NULL, slowEff, GetCasterGUID()); + GetTarget()->CastSpell(GetTarget(), SPELL_PARALYSIS, true, nullptr, slowEff, GetCasterGUID()); } } @@ -1362,7 +1361,7 @@ public: class spell_jormungars_snakes_spray : public SpellScriptLoader { public: - spell_jormungars_snakes_spray(const char* name, uint32 spellId) : SpellScriptLoader(name), _spellId(spellId) { } + spell_jormungars_snakes_spray(char const* name, uint32 spellId) : SpellScriptLoader(name), _spellId(spellId) { } class spell_jormungars_snakes_spray_SpellScript : public SpellScript { @@ -1373,9 +1372,7 @@ public: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(_spellId)) - return false; - return true; + return ValidateSpellInfo({ _spellId }); } void HandleScript(SpellEffIndex /*effIndex*/) 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 536160a34da..1784fec2736 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_twin_valkyr.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_twin_valkyr.cpp @@ -21,14 +21,16 @@ // - Hardcoded bullets spawner #include "ScriptMgr.h" +#include "CellImpl.h" +#include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" +#include "SpellAuras.h" +#include "SpellMgr.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "Cell.h" -#include "CellImpl.h" #include "trial_of_the_crusader.h" enum Texts @@ -128,9 +130,7 @@ enum Actions class OrbsDespawner : public BasicEvent { public: - explicit OrbsDespawner(Creature* creature) : _creature(creature) - { - } + explicit OrbsDespawner(Creature* creature) : _creature(creature) { } bool Execute(uint64 /*currTime*/, uint32 /*diff*/) override { @@ -451,7 +451,7 @@ class boss_fjola : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -484,7 +484,7 @@ class boss_eydis : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -526,7 +526,7 @@ class npc_essence_of_twin : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_essence_of_twinAI(creature); + return GetTrialOfTheCrusaderAI(creature); }; }; @@ -617,7 +617,7 @@ class npc_unleashed_dark : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_unleashed_darkAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -649,7 +649,7 @@ class npc_unleashed_light : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_unleashed_lightAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -678,7 +678,7 @@ class npc_bullet_controller : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_bullet_controllerAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -691,16 +691,8 @@ class spell_powering_up : public SpellScriptLoader { PrepareSpellScript(spell_powering_up_SpellScript); - public: - spell_powering_up_SpellScript() - { - spellId = 0; - poweringUp = 0; - } - - private: - uint32 spellId; - uint32 poweringUp; + uint32 spellId = 0; + uint32 poweringUp = 0; bool Load() override { @@ -756,14 +748,7 @@ class spell_valkyr_essences : public SpellScriptLoader { PrepareAuraScript(spell_valkyr_essences_AuraScript); - public: - spell_valkyr_essences_AuraScript() - { - spellId = 0; - } - - private: - uint32 spellId; + uint32 spellId = 0; bool Load() override { 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 ac86735c939..dcf586ec212 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 @@ -17,12 +17,18 @@ */ #include "ScriptMgr.h" +#include "AreaBoundary.h" +#include "GameObject.h" #include "InstanceScript.h" -#include "trial_of_the_crusader.h" +#include "Log.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "Player.h" #include "TemporarySummon.h" +#include "trial_of_the_crusader.h" -BossBoundaryData const boundaries = { +BossBoundaryData const boundaries = +{ { BOSS_BEASTS, new CircleBoundary(Position(563.26f, 139.6f), 75.0) }, { BOSS_JARAXXUS, new CircleBoundary(Position(563.26f, 139.6f), 75.0) }, { BOSS_CRUSADERS, new CircleBoundary(Position(563.26f, 139.6f), 75.0) }, @@ -33,7 +39,7 @@ BossBoundaryData const boundaries = { class instance_trial_of_the_crusader : public InstanceMapScript { public: - instance_trial_of_the_crusader() : InstanceMapScript("instance_trial_of_the_crusader", 649) { } + instance_trial_of_the_crusader() : InstanceMapScript(ToCrScriptName, 649) { } struct instance_trial_of_the_crusader_InstanceMapScript : public InstanceScript { @@ -234,14 +240,14 @@ class instance_trial_of_the_crusader : public InstanceMapScript ResilienceWillFixItTimer = 0; break; case SPECIAL: //Means the first blood - ResilienceWillFixItTimer = 60*IN_MILLISECONDS; + ResilienceWillFixItTimer = 60 * IN_MILLISECONDS; state = IN_PROGRESS; break; case DONE: DoUpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, SPELL_DEFEAT_FACTION_CHAMPIONS); if (ResilienceWillFixItTimer > 0) DoUpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET, SPELL_CHAMPIONS_KILLED_IN_MINUTE); - DoRespawnGameObject(CrusadersCacheGUID, 7*DAY); + DoRespawnGameObject(CrusadersCacheGUID, 7 * DAY); if (GameObject* cache = instance->GetGameObject(CrusadersCacheGUID)) cache->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); EventStage = 3100; @@ -313,8 +319,8 @@ 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, G3D::Quat(), WEEK)) + if (Creature* tirion = instance->GetCreature(TirionGUID)) + if (GameObject* chest = tirion->SummonGameObject(tributeChest, 805.62f, 134.87f, 142.16f, 3.27f, QuaternionData(), WEEK)) chest->SetRespawnTime(chest->GetRespawnDelay()); break; } @@ -404,7 +410,7 @@ class instance_trial_of_the_crusader : public InstanceMapScript NotOneButTwoJormungarsTimer = 0; break; case SNAKES_SPECIAL: - NotOneButTwoJormungarsTimer = 10*IN_MILLISECONDS; + NotOneButTwoJormungarsTimer = 10 * IN_MILLISECONDS; break; case SNAKES_DONE: if (NotOneButTwoJormungarsTimer > 0) @@ -640,7 +646,7 @@ class instance_trial_of_the_crusader : public InstanceMapScript return SaveDataBuffer; } - void Load(const char* strIn) override + void Load(char const* strIn) override { if (!strIn) { 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 a2165ffa604..d5006c84a48 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 @@ -20,10 +20,16 @@ // - Need better implementation of Gossip and correct gossip text and option #include "ScriptMgr.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" +#include "TemporarySummon.h" #include "trial_of_the_crusader.h" -#include "Player.h" enum Yells { @@ -81,6 +87,81 @@ enum Yells SAY_STAGE_4_07 = 1 }; +Position const ToCSpawnLoc[] = +{ + { 563.912f, 261.625f, 394.73f, 4.70437f }, // 0 Center + { 575.451f, 261.496f, 394.73f, 4.6541f }, // 1 Left + { 549.951f, 261.55f, 394.73f, 4.74835f } // 2 Right +}; + +Position const ToCCommonLoc[] = +{ + { 559.257996f, 90.266197f, 395.122986f, 0 }, // 0 Barrent + + { 563.672974f, 139.571f, 393.837006f, 0 }, // 1 Center + { 563.833008f, 187.244995f, 394.5f, 0 }, // 2 Backdoor + { 577.347839f, 195.338888f, 395.14f, 0 }, // 3 - Right + { 550.955933f, 195.338888f, 395.14f, 0 }, // 4 - Left + { 563.833008f, 195.244995f, 394.585561f, 0 }, // 5 - Center + { 573.5f, 180.5f, 395.14f, 0 }, // 6 Move 0 Right + { 553.5f, 180.5f, 395.14f, 0 }, // 7 Move 0 Left + { 573.0f, 170.0f, 395.14f, 0 }, // 8 Move 1 Right + { 555.5f, 170.0f, 395.14f, 0 }, // 9 Move 1 Left + { 563.8f, 216.1f, 395.1f, 0 }, // 10 Behind the door + + { 575.042358f, 195.260727f, 395.137146f, 0 }, // 5 + { 552.248901f, 195.331955f, 395.132658f, 0 }, // 6 + { 573.342285f, 195.515823f, 395.135956f, 0 }, // 7 + { 554.239929f, 195.825577f, 395.137909f, 0 }, // 8 + { 571.042358f, 195.260727f, 395.137146f, 0 }, // 9 + { 556.720581f, 195.015472f, 395.132658f, 0 }, // 10 + { 569.534119f, 195.214478f, 395.139526f, 0 }, // 11 + { 569.231201f, 195.941071f, 395.139526f, 0 }, // 12 + { 558.811610f, 195.985779f, 394.671661f, 0 }, // 13 + { 567.641724f, 195.351501f, 394.659943f, 0 }, // 14 + { 560.633972f, 195.391708f, 395.137543f, 0 }, // 15 + { 565.816956f, 195.477921f, 395.136810f, 0 } // 16 +}; + +Position const JaraxxusLoc[] = +{ + { 508.104767f, 138.247345f, 395.128052f, 0 }, // 0 - Fizzlebang start location + { 548.610596f, 139.807800f, 394.321838f, 0 }, // 1 - fizzlebang end + { 581.854187f, 138.0f, 394.319f, 0 }, // 2 - Portal Right + { 550.558838f, 138.0f, 394.319f, 0 } // 3 - Portal Left +}; + +Position const TwinValkyrsLoc[] = +{ + { 586.060242f, 117.514809f, 394.41f, 0 }, // 0 - Dark essence 1 + { 541.602112f, 161.879837f, 394.41f, 0 }, // 1 - Dark essence 2 + { 541.021118f, 117.262932f, 394.41f, 0 }, // 2 - Light essence 1 + { 586.200562f, 162.145523f, 394.41f, 0 } // 3 - Light essence 2 +}; + +Position const LichKingLoc[] = +{ + { 563.549f, 152.474f, 394.393f, 0 }, // 0 - Lich king start + { 563.547f, 141.613f, 393.908f, 0 } // 1 - Lich king end +}; + +Position const AnubarakLoc[] = +{ + { 783.9305f, 132.9722f, 142.6711f, 3.141593f }, // 0 - Anub'arak Spawn Location (sniffed) + { 695.240051f, 137.834824f, 142.200000f, 0 }, // 1 - Anub'arak move point location + { 694.886353f, 102.484665f, 142.119614f, 0 }, // 3 - Nerub Spawn + { 694.500671f, 185.363968f, 142.117905f, 0 }, // 5 - Nerub Spawn + { 731.987244f, 83.3824690f, 142.119614f, 0 }, // 2 - Nerub Spawn + { 740.184509f, 193.443390f, 142.117584f, 0 } // 4 - Nerub Spawn +}; + +Position const EndSpawnLoc[] = +{ + { 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 +}; + struct _Messages { AnnouncerMessages msgnum; @@ -211,7 +292,7 @@ class npc_announcer_toc10 : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_announcer_toc10AI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -340,7 +421,7 @@ class boss_lich_king_toc : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -510,7 +591,7 @@ class npc_fizzlebang_toc : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -756,7 +837,7 @@ class npc_tirion_toc : public CreatureScript case 6000: 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); + me->SummonGameObject(GO_PORTAL_TO_DALARAN, EndSpawnLoc[2], QuaternionData(), 0); _updateTimer = 20*IN_MILLISECONDS; _instance->SetData(TYPE_EVENT, 6005); break; @@ -797,7 +878,7 @@ class npc_tirion_toc : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -880,7 +961,7 @@ class npc_garrosh_toc : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; @@ -963,7 +1044,7 @@ class npc_varian_toc : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTrialOfTheCrusaderAI(creature); } }; 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 e98bbed7b92..77f608c8044 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 @@ -1,6 +1,6 @@ /* * Copyright (C) 2008-2018 TrinityCore - * Copyright (C) 2006 - 2010 ScriptDev2 + * Copyright (C) 2009-2010 ScriptDev2 * * 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 @@ -19,8 +19,13 @@ #ifndef DEF_CRUSADER_H #define DEF_CRUSADER_H +#include "CreatureAIImpl.h" + +#define ToCrScriptName "instance_trial_of_the_crusader" #define DataHeader "TCR" +struct Position; + enum TCRDataTypes { BOSS_BEASTS = 0, @@ -58,106 +63,8 @@ enum TCRMiscData DESPAWN_TIME = 1200000 }; -const Position ToCSpawnLoc[]= -{ - {563.912f, 261.625f, 394.73f, 4.70437f}, // 0 Center - {575.451f, 261.496f, 394.73f, 4.6541f}, // 1 Left - {549.951f, 261.55f, 394.73f, 4.74835f} // 2 Right -}; - -const Position ToCCommonLoc[]= -{ - {559.257996f, 90.266197f, 395.122986f, 0}, // 0 Barrent - - {563.672974f, 139.571f, 393.837006f, 0}, // 1 Center - {563.833008f, 187.244995f, 394.5f, 0}, // 2 Backdoor - {577.347839f, 195.338888f, 395.14f, 0}, // 3 - Right - {550.955933f, 195.338888f, 395.14f, 0}, // 4 - Left - {563.833008f, 195.244995f, 394.585561f, 0}, // 5 - Center - {573.5f, 180.5f, 395.14f, 0}, // 6 Move 0 Right - {553.5f, 180.5f, 395.14f, 0}, // 7 Move 0 Left - {573.0f, 170.0f, 395.14f, 0}, // 8 Move 1 Right - {555.5f, 170.0f, 395.14f, 0}, // 9 Move 1 Left - {563.8f, 216.1f, 395.1f, 0}, // 10 Behind the door - - {575.042358f, 195.260727f, 395.137146f, 0}, // 5 - {552.248901f, 195.331955f, 395.132658f, 0}, // 6 - {573.342285f, 195.515823f, 395.135956f, 0}, // 7 - {554.239929f, 195.825577f, 395.137909f, 0}, // 8 - {571.042358f, 195.260727f, 395.137146f, 0}, // 9 - {556.720581f, 195.015472f, 395.132658f, 0}, // 10 - {569.534119f, 195.214478f, 395.139526f, 0}, // 11 - {569.231201f, 195.941071f, 395.139526f, 0}, // 12 - {558.811610f, 195.985779f, 394.671661f, 0}, // 13 - {567.641724f, 195.351501f, 394.659943f, 0}, // 14 - {560.633972f, 195.391708f, 395.137543f, 0}, // 15 - {565.816956f, 195.477921f, 395.136810f, 0} // 16 -}; - -const Position JaraxxusLoc[]= -{ - {508.104767f, 138.247345f, 395.128052f, 0}, // 0 - Fizzlebang start location - {548.610596f, 139.807800f, 394.321838f, 0}, // 1 - fizzlebang end - {581.854187f, 138.0f, 394.319f, 0}, // 2 - Portal Right - {550.558838f, 138.0f, 394.319f, 0} // 3 - Portal Left -}; - -const Position FactionChampionLoc[]= -{ - {514.231f, 105.569f, 418.234f, 0}, // 0 - Horde Initial Pos 0 - {508.334f, 115.377f, 418.234f, 0}, // 1 - Horde Initial Pos 1 - {506.454f, 126.291f, 418.234f, 0}, // 2 - Horde Initial Pos 2 - {506.243f, 106.596f, 421.592f, 0}, // 3 - Horde Initial Pos 3 - {499.885f, 117.717f, 421.557f, 0}, // 4 - Horde Initial Pos 4 - - {613.127f, 100.443f, 419.74f, 0}, // 5 - Ally Initial Pos 0 - {621.126f, 128.042f, 418.231f, 0}, // 6 - Ally Initial Pos 1 - {618.829f, 113.606f, 418.232f, 0}, // 7 - Ally Initial Pos 2 - {625.845f, 112.914f, 421.575f, 0}, // 8 - Ally Initial Pos 3 - {615.566f, 109.653f, 418.234f, 0}, // 9 - Ally Initial Pos 4 - - {535.469f, 113.012f, 394.66f, 0}, // 10 - Horde Final Pos 0 - {526.417f, 137.465f, 394.749f, 0}, // 11 - Horde Final Pos 1 - {528.108f, 111.057f, 395.289f, 0}, // 12 - Horde Final Pos 2 - {519.92f, 134.285f, 395.289f, 0}, // 13 - Horde Final Pos 3 - {533.648f, 119.148f, 394.646f, 0}, // 14 - Horde Final Pos 4 - {531.399f, 125.63f, 394.708f, 0}, // 15 - Horde Final Pos 5 - {528.958f, 131.47f, 394.73f, 0}, // 16 - Horde Final Pos 6 - {526.309f, 116.667f, 394.833f, 0}, // 17 - Horde Final Pos 7 - {524.238f, 122.411f, 394.819f, 0}, // 18 - Horde Final Pos 8 - {521.901f, 128.488f, 394.832f, 0} // 19 - Horde Final Pos 9 -}; - -const Position TwinValkyrsLoc[]= -{ - {586.060242f, 117.514809f, 394.41f, 0}, // 0 - Dark essence 1 - {541.602112f, 161.879837f, 394.41f, 0}, // 1 - Dark essence 2 - {541.021118f, 117.262932f, 394.41f, 0}, // 2 - Light essence 1 - {586.200562f, 162.145523f, 394.41f, 0} // 3 - Light essence 2 -}; - -const Position LichKingLoc[]= -{ - {563.549f, 152.474f, 394.393f, 0}, // 0 - Lich king start - {563.547f, 141.613f, 393.908f, 0} // 1 - Lich king end -}; - -const Position AnubarakLoc[]= -{ - {783.9305f, 132.9722f, 142.6711f, 3.141593f}, // 0 - Anub'arak Spawn Location (sniffed) - {695.240051f, 137.834824f, 142.200000f, 0}, // 1 - Anub'arak move point location - {694.886353f, 102.484665f, 142.119614f, 0}, // 3 - Nerub Spawn - {694.500671f, 185.363968f, 142.117905f, 0}, // 5 - Nerub Spawn - {731.987244f, 83.3824690f, 142.119614f, 0}, // 2 - Nerub Spawn - {740.184509f, 193.443390f, 142.117584f, 0} // 4 - Nerub Spawn -}; - -const Position EndSpawnLoc[]= -{ - {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 -}; +extern Position const ToCCommonLoc[]; +extern Position const AnubarakLoc[]; enum TCRWorldStateIds { @@ -312,4 +219,10 @@ enum TCRAchievementData EVENT_START_TWINS_FIGHT = 21853 }; +template +inline AI* GetTrialOfTheCrusaderAI(T* obj) +{ + return GetInstanceAI(obj, ToCrScriptName); +} + #endif diff --git a/src/server/scripts/Northrend/DraktharonKeep/boss_king_dred.cpp b/src/server/scripts/Northrend/DraktharonKeep/boss_king_dred.cpp index 91cd0546642..8704aaf6c57 100644 --- a/src/server/scripts/Northrend/DraktharonKeep/boss_king_dred.cpp +++ b/src/server/scripts/Northrend/DraktharonKeep/boss_king_dred.cpp @@ -20,8 +20,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "drak_tharon_keep.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Spells { @@ -143,7 +145,6 @@ class boss_king_dred : public CreatureScript DoCastVictim(SPELL_RAPTOR_CALL); float x, y, z; - me->GetClosePoint(x, y, z, me->GetObjectSize() / 3, 10.0f); me->SummonCreature(RAND(NPC_DRAKKARI_GUTRIPPER, NPC_DRAKKARI_SCYTHECLAW), x, y, z, 0, TEMPSUMMON_DEAD_DESPAWN, 1000); events.ScheduleEvent(EVENT_RAPTOR_CALL, urand(20000, 25000)); diff --git a/src/server/scripts/Northrend/DraktharonKeep/boss_novos.cpp b/src/server/scripts/Northrend/DraktharonKeep/boss_novos.cpp index 4f08bd2db9a..d5af4603dbc 100644 --- a/src/server/scripts/Northrend/DraktharonKeep/boss_novos.cpp +++ b/src/server/scripts/Northrend/DraktharonKeep/boss_novos.cpp @@ -16,9 +16,13 @@ */ #include "ScriptMgr.h" -#include "SpellScript.h" -#include "ScriptedCreature.h" #include "drak_tharon_keep.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "SpellScript.h" enum Yells { @@ -239,7 +243,7 @@ public: if (Creature* crystalChannelTarget = crystal->FindNearestCreature(NPC_CRYSTAL_CHANNEL_TARGET, 5.0f)) { if (active) - crystalChannelTarget->CastSpell((Unit*)NULL, SPELL_BEAM_CHANNEL); + crystalChannelTarget->CastSpell((Unit*)nullptr, SPELL_BEAM_CHANNEL); else if (crystalChannelTarget->HasUnitState(UNIT_STATE_CASTING)) crystalChannelTarget->CastStop(); } @@ -374,15 +378,13 @@ class spell_novos_summon_minions : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_COPY_OF_MINIONS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_COPY_OF_MINIONS }); } void HandleScript(SpellEffIndex /*effIndex*/) { for (uint8 i = 0; i < 2; ++i) - GetCaster()->CastSpell((Unit*)NULL, SPELL_SUMMON_COPY_OF_MINIONS, true); + GetCaster()->CastSpell((Unit*)nullptr, SPELL_SUMMON_COPY_OF_MINIONS, true); } void Register() override diff --git a/src/server/scripts/Northrend/DraktharonKeep/boss_tharon_ja.cpp b/src/server/scripts/Northrend/DraktharonKeep/boss_tharon_ja.cpp index 680103402e4..a96e0cc9f61 100644 --- a/src/server/scripts/Northrend/DraktharonKeep/boss_tharon_ja.cpp +++ b/src/server/scripts/Northrend/DraktharonKeep/boss_tharon_ja.cpp @@ -16,11 +16,9 @@ */ #include "ScriptMgr.h" +#include "drak_tharon_keep.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "Player.h" -#include "drak_tharon_keep.h" /* * Known Issues: Spell 49356 and 53463 will be interrupted for an unknown reason @@ -219,9 +217,7 @@ class spell_tharon_ja_clear_gift_of_tharon_ja : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GIFT_OF_THARON_JA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_GIFT_OF_THARON_JA }); } void HandleScript(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/DraktharonKeep/boss_trollgore.cpp b/src/server/scripts/Northrend/DraktharonKeep/boss_trollgore.cpp index afed4d3be6d..3df5c0ed531 100644 --- a/src/server/scripts/Northrend/DraktharonKeep/boss_trollgore.cpp +++ b/src/server/scripts/Northrend/DraktharonKeep/boss_trollgore.cpp @@ -16,10 +16,13 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" #include "drak_tharon_keep.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Spells { @@ -136,7 +139,7 @@ class boss_trollgore : public CreatureScript case EVENT_SPAWN: for (uint8 i = 0; i < 3; ++i) if (Creature* trigger = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_TROLLGORE_INVADER_SUMMONER_1 + i))) - trigger->CastSpell(trigger, RAND(SPELL_SUMMON_INVADER_A, SPELL_SUMMON_INVADER_B, SPELL_SUMMON_INVADER_C), true, NULL, NULL, me->GetGUID()); + trigger->CastSpell(trigger, RAND(SPELL_SUMMON_INVADER_A, SPELL_SUMMON_INVADER_B, SPELL_SUMMON_INVADER_C), true, nullptr, nullptr, me->GetGUID()); events.ScheduleEvent(EVENT_SPAWN, urand(30000, 40000)); break; @@ -234,9 +237,7 @@ class spell_trollgore_consume : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CONSUME_BUFF)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CONSUME_BUFF }); } void HandleConsume(SpellEffIndex /*effIndex*/) @@ -269,16 +270,14 @@ class spell_trollgore_corpse_explode : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CORPSE_EXPLODE_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CORPSE_EXPLODE_DAMAGE }); } void PeriodicTick(AuraEffect const* aurEff) { if (aurEff->GetTickNumber() == 2) if (Unit* caster = GetCaster()) - caster->CastSpell(GetTarget(), SPELL_CORPSE_EXPLODE_DAMAGE, true, NULL, aurEff); + caster->CastSpell(GetTarget(), SPELL_CORPSE_EXPLODE_DAMAGE, true, nullptr, aurEff); } void HandleRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -312,9 +311,7 @@ class spell_trollgore_invader_taunt : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].CalcValue())) - return false; - return true; + return ValidateSpellInfo({ uint32(spellInfo->Effects[EFFECT_0].CalcValue()) }); } void HandleTaunt(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/DraktharonKeep/drak_tharon_keep.h b/src/server/scripts/Northrend/DraktharonKeep/drak_tharon_keep.h index bcbcb5cbe55..ac02f714c7d 100644 --- a/src/server/scripts/Northrend/DraktharonKeep/drak_tharon_keep.h +++ b/src/server/scripts/Northrend/DraktharonKeep/drak_tharon_keep.h @@ -18,6 +18,8 @@ #ifndef DRAK_THARON_KEEP_H_ #define DRAK_THARON_KEEP_H_ +#include "CreatureAIImpl.h" + #define DrakTharonKeepScriptName "instance_drak_tharon_keep" #define DataHeader "DTK" @@ -84,10 +86,10 @@ enum DTKGameObjectIds GO_NOVOS_CRYSTAL_4 = 189302 }; -template -AI* GetDrakTharonKeepAI(Creature* creature) +template +inline AI* GetDrakTharonKeepAI(T* obj) { - return GetInstanceAI(creature, DrakTharonKeepScriptName); + return GetInstanceAI(obj, DrakTharonKeepScriptName); } #endif // DRAK_THARON_KEEP_H_ diff --git a/src/server/scripts/Northrend/DraktharonKeep/instance_drak_tharon_keep.cpp b/src/server/scripts/Northrend/DraktharonKeep/instance_drak_tharon_keep.cpp index a552a150b22..47e1a9875e4 100644 --- a/src/server/scripts/Northrend/DraktharonKeep/instance_drak_tharon_keep.cpp +++ b/src/server/scripts/Northrend/DraktharonKeep/instance_drak_tharon_keep.cpp @@ -16,9 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "InstanceScript.h" #include "drak_tharon_keep.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ScriptedCreature.h" class instance_drak_tharon_keep : public InstanceMapScript { diff --git a/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/boss_bronjahm.cpp b/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/boss_bronjahm.cpp index f6d65a57189..d8d31986cc4 100644 --- a/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/boss_bronjahm.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/boss_bronjahm.cpp @@ -16,10 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" #include "forge_of_souls.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Yells { @@ -212,7 +216,7 @@ class boss_bronjahm : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature, FoSScriptName); + return GetForgeOfSoulsAI(creature); } }; @@ -252,7 +256,7 @@ class npc_corrupted_soul_fragment : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature, FoSScriptName); + return GetForgeOfSoulsAI(creature); } }; @@ -336,6 +340,11 @@ class spell_bronjahm_soulstorm_visual : public SpellScriptLoader { PrepareAuraScript(spell_bronjahm_soulstorm_visual_AuraScript); + bool Validate(SpellInfo const* /*spellInfo*/) override + { + return ValidateSpellInfo(SoulstormVisualSpells); + } + void HandlePeriodicTick(AuraEffect const* aurEff) { PreventDefaultAction(); 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 d6f51d41930..2bfb59d245e 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 @@ -16,12 +16,16 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "Player.h" -#include "SpellInfo.h" -#include "SpellAuraEffects.h" -#include "SpellScript.h" #include "forge_of_souls.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellInfo.h" +#include "SpellScript.h" +#include "TemporarySummon.h" /* * @todo @@ -217,7 +221,7 @@ class boss_devourer_of_souls : public CreatureScript } } - void SpellHitTarget(Unit* /*target*/, const SpellInfo* spell) override + void SpellHitTarget(Unit* /*target*/, SpellInfo const* spell) override { if (spell->Id == H_SPELL_PHANTOM_BLAST) threeFaced = false; @@ -342,7 +346,7 @@ class boss_devourer_of_souls : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature, FoSScriptName); + return GetForgeOfSoulsAI(creature); } }; @@ -358,9 +362,7 @@ class spell_devourer_of_souls_mirrored_soul : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MIRRORED_SOUL_PROC_AURA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MIRRORED_SOUL_PROC_AURA }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -393,9 +395,7 @@ class spell_devourer_of_souls_mirrored_soul_proc : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MIRRORED_SOUL_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MIRRORED_SOUL_DAMAGE }); } bool CheckProc(ProcEventInfo& /*eventInfo*/) @@ -439,9 +439,7 @@ class spell_devourer_of_souls_mirrored_soul_target_selector : public SpellScript bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MIRRORED_SOUL_BUFF)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MIRRORED_SOUL_BUFF }); } void FilterTargets(std::list& targets) diff --git a/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/forge_of_souls.cpp b/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/forge_of_souls.cpp index c8c07cb01b8..14f282fd169 100644 --- a/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/forge_of_souls.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/forge_of_souls.cpp @@ -16,10 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" #include "forge_of_souls.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" enum Events { @@ -163,7 +163,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetForgeOfSoulsAI(creature); } }; @@ -272,7 +272,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetForgeOfSoulsAI(creature); } }; diff --git a/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/forge_of_souls.h b/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/forge_of_souls.h index 786e6bc4e18..9461617ea96 100644 --- a/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/forge_of_souls.h +++ b/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/forge_of_souls.h @@ -18,6 +18,8 @@ #ifndef FORGE_OF_SOULS_H_ #define FORGE_OF_SOULS_H_ +#include "CreatureAIImpl.h" + #define FoSScriptName "instance_forge_of_souls" #define DataHeader "FOS" @@ -55,4 +57,10 @@ enum FOSCreatures NPC_CRUCIBLE_OF_SOULS = 37094 }; +template +inline AI* GetForgeOfSoulsAI(T* obj) +{ + return GetInstanceAI(obj, FoSScriptName); +} + #endif // FORGE_OF_SOULS_H_ diff --git a/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/instance_forge_of_souls.cpp b/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/instance_forge_of_souls.cpp index e1017b01bf3..79c4d166e88 100644 --- a/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/instance_forge_of_souls.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/ForgeOfSouls/instance_forge_of_souls.cpp @@ -16,8 +16,11 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" +#include "AreaBoundary.h" +#include "Creature.h" #include "forge_of_souls.h" +#include "InstanceScript.h" +#include "Map.h" #include "Player.h" diff --git a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_falric.cpp b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_falric.cpp index 278645a3d05..bdea7ae88d6 100644 --- a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_falric.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_falric.cpp @@ -16,8 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "boss_horAI.h" #include "halls_of_reflection.h" +#include "InstanceScript.h" +#include "SpellMgr.h" enum Texts { diff --git a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_horAI.cpp b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_horAI.cpp new file mode 100644 index 00000000000..99852fc53cc --- /dev/null +++ b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_horAI.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#include "boss_horAI.h" +#include "halls_of_reflection.h" +#include "InstanceScript.h" + +boss_horAI::boss_horAI(Creature* creature, uint32 bossId) : BossAI(creature, bossId) +{ +} + +void boss_horAI::Reset() +{ + _Reset(); + me->SetVisible(false); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC); + me->SetReactState(REACT_PASSIVE); + if (instance->GetData(DATA_WAVE_COUNT) != NOT_STARTED) + instance->ProcessEvent(nullptr, EVENT_DO_WIPE); +} + +void boss_horAI::DoAction(int32 actionId) +{ + switch (actionId) + { + case ACTION_ENTER_COMBAT: // called by InstanceScript when boss shall enter in combat. + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC); + me->SetReactState(REACT_AGGRESSIVE); + DoZoneInCombat(me, 150.0f); + break; + default: + break; + } +} + +void boss_horAI::JustSummoned(Creature* summon) +{ + summons.Summon(summon); +} diff --git a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_horAI.h b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_horAI.h new file mode 100644 index 00000000000..f2c354aa3a5 --- /dev/null +++ b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_horAI.h @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef boss_horAI_h__ +#define boss_horAI_h__ + +#include "ScriptedCreature.h" + + // Base class for FALRIC and MARWYN +struct boss_horAI : BossAI +{ + boss_horAI(Creature* creature, uint32 bossId); + void Reset() override; + void DoAction(int32 actionId) override; + void JustSummoned(Creature* summon) override; +}; + +#endif // boss_horAI_h__ diff --git a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_marwyn.cpp b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_marwyn.cpp index 28cfb3a0b74..3a02a3310d8 100644 --- a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_marwyn.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/boss_marwyn.cpp @@ -16,10 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "boss_horAI.h" #include "halls_of_reflection.h" +#include "InstanceScript.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Texts { 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 ac80a42a9d6..231580b3edd 100644 --- a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.cpp @@ -16,13 +16,18 @@ */ #include "ScriptMgr.h" +#include "halls_of_reflection.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" +#include "Spell.h" +#include "SpellInfo.h" #include "SpellScript.h" +#include "TemporarySummon.h" #include "Transport.h" -#include "Player.h" -#include "MoveSplineInit.h" -#include "halls_of_reflection.h" enum Text { @@ -338,6 +343,12 @@ Position const IceWallTargetPosition[] = { 5318.289f, 1749.184f, 771.9423f, 0.8726646f } // 4th Icewall }; +void GameObjectDeleteDelayEvent::DeleteGameObject() +{ + if (GameObject* go = ObjectAccessor::GetGameObject(*_owner, _gameObjectGUID)) + go->Delete(); +} + class npc_jaina_or_sylvanas_intro_hor : public CreatureScript { public: @@ -2818,9 +2829,9 @@ class spell_hor_gunship_cannon_fire : public SpellScriptLoader if (!urand(0, 2)) { if (GetTarget()->GetEntry() == NPC_GUNSHIP_CANNON_HORDE) - GetTarget()->CastSpell((Unit*)NULL, SPELL_GUNSHIP_CANNON_FIRE_MISSILE_HORDE, true); + GetTarget()->CastSpell((Unit*)nullptr, SPELL_GUNSHIP_CANNON_FIRE_MISSILE_HORDE, true); else - GetTarget()->CastSpell((Unit*)NULL, SPELL_GUNSHIP_CANNON_FIRE_MISSILE_ALLIANCE, true); + GetTarget()->CastSpell((Unit*)nullptr, SPELL_GUNSHIP_CANNON_FIRE_MISSILE_ALLIANCE, true); } } diff --git a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.h b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.h index 67032e2df6f..4303bc5fa5d 100644 --- a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.h +++ b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/halls_of_reflection.h @@ -18,6 +18,10 @@ #ifndef HALLS_OF_REFLECTION_H_ #define HALLS_OF_REFLECTION_H_ +#include "CreatureAIImpl.h" +#include "EventProcessor.h" +#include "ObjectGuid.h" + #define HoRScriptName "instance_halls_of_reflection" #define DataHeader "HOR" @@ -192,51 +196,12 @@ enum HORInstanceYells SAY_CAPTAIN_FINAL = 1 }; -// Base class for FALRIC and MARWYN -struct boss_horAI : BossAI -{ - boss_horAI(Creature* creature, uint32 bossId) : BossAI(creature, bossId) { } - - void Reset() override - { - _Reset(); - me->SetVisible(false); - me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC); - me->SetReactState(REACT_PASSIVE); - if (instance->GetData(DATA_WAVE_COUNT) != NOT_STARTED) - instance->ProcessEvent(NULL, EVENT_DO_WIPE); - } - - void DoAction(int32 actionId) override - { - switch (actionId) - { - case ACTION_ENTER_COMBAT: // called by InstanceScript when boss shall enter in combat. - me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC); - me->SetReactState(REACT_AGGRESSIVE); - DoZoneInCombat(me, 150.0f); - break; - default: - break; - } - } - - void JustSummoned(Creature* summon) override - { - summons.Summon(summon); - } -}; - class GameObjectDeleteDelayEvent : public BasicEvent { public: GameObjectDeleteDelayEvent(Unit* owner, ObjectGuid gameObjectGUID) : _owner(owner), _gameObjectGUID(gameObjectGUID) { } - void DeleteGameObject() - { - if (GameObject* go = ObjectAccessor::GetGameObject(*_owner, _gameObjectGUID)) - go->Delete(); - } + void DeleteGameObject(); bool Execute(uint64 /*execTime*/, uint32 /*diff*/) override { @@ -254,10 +219,10 @@ class GameObjectDeleteDelayEvent : public BasicEvent ObjectGuid _gameObjectGUID; }; -template -AI* GetHallsOfReflectionAI(Creature* creature) +template +inline AI* GetHallsOfReflectionAI(T* obj) { - return GetInstanceAI(creature, HoRScriptName); + return GetInstanceAI(obj, HoRScriptName); } #endif // HALLS_OF_REFLECTION_H_ diff --git a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/instance_halls_of_reflection.cpp b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/instance_halls_of_reflection.cpp index 2616c2d88a0..4149e595840 100644 --- a/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/instance_halls_of_reflection.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/HallsOfReflection/instance_halls_of_reflection.cpp @@ -16,12 +16,16 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "InstanceScript.h" -#include "Player.h" -#include "Transport.h" -#include "WorldPacket.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "GameObject.h" #include "halls_of_reflection.h" +#include "InstanceScript.h" +#include "Map.h" +#include "Player.h" +#include "TemporarySummon.h" +#include "Transport.h" +#include "TransportMgr.h" Position const JainaSpawnPos = { 5236.659f, 1929.894f, 707.7781f, 0.8726646f }; // Jaina Spawn Position Position const SylvanasSpawnPos = { 5236.667f, 1929.906f, 707.7781f, 0.8377581f }; // Sylvanas Spawn Position (sniffed) @@ -344,7 +348,7 @@ class instance_halls_of_reflection : public InstanceMapScript if (Creature* lichking = instance->GetCreature(TheLichKingEscapeGUID)) { - lichking->CastSpell((Unit*)NULL, SPELL_ACHIEV_CHECK, true); + lichking->CastSpell((Unit*)nullptr, SPELL_ACHIEV_CHECK, true); lichking->DespawnOrUnsummon(1); } break; @@ -438,7 +442,7 @@ class instance_halls_of_reflection : public InstanceMapScript break; case DATA_WAVE_COUNT: if (_waveCount && data == NOT_STARTED) - ProcessEvent(NULL, EVENT_DO_WIPE); + ProcessEvent(nullptr, EVENT_DO_WIPE); break; case DATA_FROSTSWORN_GENERAL: if (data == DONE) @@ -451,7 +455,7 @@ class instance_halls_of_reflection : public InstanceMapScript if (_quelDelarState == NOT_STARTED) { if (Creature* bunny = instance->GetCreature(FrostmourneAltarBunnyGUID)) - bunny->CastSpell((Unit*)NULL, SPELL_ESSENCE_OF_CAPTURED); + bunny->CastSpell((Unit*)nullptr, SPELL_ESSENCE_OF_CAPTURED); events.ScheduleEvent(EVENT_QUEL_DELAR_SUMMON_UTHER, 2000); } } @@ -516,7 +520,7 @@ class instance_halls_of_reflection : public InstanceMapScript switch (events.ExecuteEvent()) { case EVENT_NEXT_WAVE: - ProcessEvent(NULL, EVENT_ADD_WAVE); + ProcessEvent(nullptr, EVENT_ADD_WAVE); break; case EVENT_SPAWN_ESCAPE_EVENT: SpawnEscapeEvent(); diff --git a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_forgemaster_garfrost.cpp b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_forgemaster_garfrost.cpp index 90e1f04ef74..ad464e2df7c 100644 --- a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_forgemaster_garfrost.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_forgemaster_garfrost.cpp @@ -16,10 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuras.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "pit_of_saron.h" +#include "ScriptedCreature.h" +#include "SpellAuras.h" +#include "SpellScript.h" enum Yells { @@ -167,7 +171,7 @@ class boss_garfrost : public CreatureScript events.ScheduleEvent(EVENT_RESUME_ATTACK, 5000); } - void SpellHitTarget(Unit* target, const SpellInfo* spell) override + void SpellHitTarget(Unit* target, SpellInfo const* spell) override { if (spell->Id == SPELL_PERMAFROST_HELPER) { @@ -259,28 +263,21 @@ class spell_garfrost_permafrost : public SpellScriptLoader { PrepareSpellScript(spell_garfrost_permafrost_SpellScript); - public: - spell_garfrost_permafrost_SpellScript() - { - prevented = false; - } - - private: void PreventHitByLoS() { if (Unit* target = GetHitUnit()) { Unit* caster = GetCaster(); //Temporary Line of Sight Check - std::list blockList; + std::vector blockList; caster->GetGameObjectListWithEntryInGrid(blockList, GO_SARONITE_ROCK, 100.0f); if (!blockList.empty()) { - for (std::list::const_iterator itr = blockList.begin(); itr != blockList.end(); ++itr) + for (GameObject* go : blockList) { - if (!(*itr)->IsInvisibleDueToDespawn()) + if (!go->IsInvisibleDueToDespawn()) { - if ((*itr)->IsInBetween(caster, target, 4.0f)) + if (go->IsInBetween(caster, target, 4.0f)) { prevented = true; target->ApplySpellImmune(GetSpellInfo()->Id, IMMUNITY_ID, GetSpellInfo()->Id, true); @@ -312,7 +309,7 @@ class spell_garfrost_permafrost : public SpellScriptLoader AfterHit += SpellHitFn(spell_garfrost_permafrost_SpellScript::RestoreImmunity); } - bool prevented; + bool prevented = false; }; SpellScript* GetSpellScript() const override diff --git a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_krickandick.cpp b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_krickandick.cpp index 07d96e5c27c..3c38324c2d4 100644 --- a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_krickandick.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_krickandick.cpp @@ -16,12 +16,17 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "pit_of_saron.h" -#include "Vehicle.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "Vehicle.h" enum Spells { @@ -374,7 +379,7 @@ class boss_krick : public CreatureScript if (Creature* temp = ObjectAccessor::GetCreature(*me, _instanceScript->GetGuidData(DATA_JAINA_SYLVANAS_1))) temp->DespawnOrUnsummon(); - Creature* jainaOrSylvanas = NULL; + Creature* jainaOrSylvanas = nullptr; if (_instanceScript->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) jainaOrSylvanas = me->SummonCreature(NPC_JAINA_PART1, outroPos[2], TEMPSUMMON_MANUAL_DESPAWN); else @@ -521,7 +526,7 @@ class spell_krick_explosive_barrage : public SpellScriptLoader if (Unit* caster = GetCaster()) if (caster->GetTypeId() == TYPEID_UNIT) { - Map::PlayerList const &players = caster->GetMap()->GetPlayers(); + Map::PlayerList const& players = caster->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) if (Player* player = itr->GetSource()) if (player->IsWithinDist(caster, 60.0f)) // don't know correct range 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 920017b48b1..190fef0d43a 100644 --- a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_scourgelord_tyrannus.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/boss_scourgelord_tyrannus.cpp @@ -16,13 +16,16 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "pit_of_saron.h" -#include "Vehicle.h" #include "Player.h" #include "PlayerAI.h" +#include "ScriptedCreature.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "Vehicle.h" enum Yells { @@ -387,7 +390,7 @@ class boss_rimefang : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_rimefangAI(creature); + return GetPitOfSaronAI(creature); } }; @@ -400,13 +403,13 @@ class player_overlord_brandAI : public PlayerAI { if (Creature* tyrannus = ObjectAccessor::GetCreature(*me, _tyrannusGUID)) if (Unit* victim = tyrannus->GetVictim()) - me->CastCustomSpell(SPELL_OVERLORD_BRAND_DAMAGE, SPELLVALUE_BASE_POINT0, damage, victim, true, NULL, NULL, tyrannus->GetGUID()); + me->CastCustomSpell(SPELL_OVERLORD_BRAND_DAMAGE, SPELLVALUE_BASE_POINT0, damage, victim, true, nullptr, nullptr, tyrannus->GetGUID()); } void HealDone(Unit* /*target*/, uint32& addHealth) override { if (Creature* tyrannus = ObjectAccessor::GetCreature(*me, _tyrannusGUID)) - me->CastCustomSpell(SPELL_OVERLORD_BRAND_HEAL, SPELLVALUE_BASE_POINT0, int32(addHealth * 5.5f), tyrannus, true, NULL, NULL, tyrannus->GetGUID()); + me->CastCustomSpell(SPELL_OVERLORD_BRAND_HEAL, SPELLVALUE_BASE_POINT0, int32(addHealth * 5.5f), tyrannus, true, nullptr, nullptr, tyrannus->GetGUID()); } void UpdateAI(uint32 /*diff*/) override { } @@ -520,9 +523,7 @@ class spell_tyrannus_rimefang_icy_blast : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ICY_BLAST_AURA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ICY_BLAST_AURA }); } void HandleTriggerMissile(SpellEffIndex effIndex) diff --git a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/instance_pit_of_saron.cpp b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/instance_pit_of_saron.cpp index e9f638bff7d..1d95379168f 100644 --- a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/instance_pit_of_saron.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/instance_pit_of_saron.cpp @@ -16,7 +16,10 @@ */ #include "ScriptMgr.h" +#include "Creature.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" #include "pit_of_saron.h" #include "Player.h" diff --git a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/pit_of_saron.cpp b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/pit_of_saron.cpp index 22801f7fafd..d5fc0c0faf0 100644 --- a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/pit_of_saron.cpp +++ b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/pit_of_saron.cpp @@ -16,13 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "pit_of_saron.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "PassiveAI.h" -#include "Vehicle.h" +#include "pit_of_saron.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "Vehicle.h" enum Spells { @@ -40,6 +42,19 @@ enum Events EVENT_TACTICAL_BLINK = 2, }; +bool ScheduledIcicleSummons::Execute(uint64 /*time*/, uint32 /*diff*/) +{ + if (roll_chance_i(12)) + { + _trigger->CastSpell(_trigger, SPELL_ICICLE_SUMMON, true); + _trigger->m_Events.AddEvent(new ScheduledIcicleSummons(_trigger), _trigger->m_Events.CalculateTime(urand(20000, 35000))); + } + else + _trigger->m_Events.AddEvent(new ScheduledIcicleSummons(_trigger), _trigger->m_Events.CalculateTime(urand(1000, 20000))); + + return true; +} + class npc_ymirjar_flamebearer : public CreatureScript { public: @@ -101,7 +116,7 @@ class npc_ymirjar_flamebearer : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_ymirjar_flamebearerAI(creature); + return GetPitOfSaronAI(creature); } }; @@ -155,7 +170,7 @@ class npc_iceborn_protodrake : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_iceborn_protodrakeAI(creature); + return GetPitOfSaronAI(creature); } }; @@ -214,7 +229,7 @@ class npc_geist_ambusher : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_geist_ambusherAI(creature); + return GetPitOfSaronAI(creature); } }; @@ -303,12 +318,7 @@ class spell_pos_ice_shards : public SpellScriptLoader bool Load() override { // This script should execute only in Pit of Saron - if (InstanceMap* instance = GetCaster()->GetMap()->ToInstanceMap()) - if (instance->GetInstanceScript()) - if (instance->GetScriptId() == sObjectMgr->GetScriptId(PoSScriptName)) - return true; - - return false; + return InstanceHasScript(GetCaster(), PoSScriptName); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/pit_of_saron.h b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/pit_of_saron.h index 11ff37700c3..990cc58abb0 100644 --- a/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/pit_of_saron.h +++ b/src/server/scripts/Northrend/FrozenHalls/PitOfSaron/pit_of_saron.h @@ -18,6 +18,9 @@ #ifndef PIT_OF_SARON_H_ #define PIT_OF_SARON_H_ +#include "CreatureAIImpl.h" +#include "EventProcessor.h" + #define PoSScriptName "instance_pit_of_saron" #define DataHeader "POS" @@ -112,27 +115,16 @@ class ScheduledIcicleSummons : public BasicEvent public: ScheduledIcicleSummons(Creature* trigger) : _trigger(trigger) { } - bool Execute(uint64 /*time*/, uint32 /*diff*/) override - { - if (roll_chance_i(12)) - { - _trigger->CastSpell(_trigger, SPELL_ICICLE_SUMMON, true); - _trigger->m_Events.AddEvent(new ScheduledIcicleSummons(_trigger), _trigger->m_Events.CalculateTime(urand(20000, 35000))); - } - else - _trigger->m_Events. AddEvent(new ScheduledIcicleSummons(_trigger), _trigger->m_Events.CalculateTime(urand(1000,20000))); - - return true; - } + bool Execute(uint64 /*time*/, uint32 /*diff*/) override; private: Creature* _trigger; }; -template -AI* GetPitOfSaronAI(Creature* creature) +template +inline AI* GetPitOfSaronAI(T* obj) { - return GetInstanceAI(creature, PoSScriptName); + return GetInstanceAI(obj, PoSScriptName); } #endif // PIT_OF_SARON_H_ diff --git a/src/server/scripts/Northrend/Gundrak/boss_drakkari_colossus.cpp b/src/server/scripts/Northrend/Gundrak/boss_drakkari_colossus.cpp index bf96ce3603a..a33c9cf679c 100644 --- a/src/server/scripts/Northrend/Gundrak/boss_drakkari_colossus.cpp +++ b/src/server/scripts/Northrend/Gundrak/boss_drakkari_colossus.cpp @@ -20,8 +20,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "gundrak.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" enum Texts @@ -375,11 +377,6 @@ class npc_living_mojo : public CreatureScript public: npc_living_mojo() : CreatureScript("npc_living_mojo") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetGundrakAI(creature); - } - struct npc_living_mojoAI : public ScriptedAI { npc_living_mojoAI(Creature* creature) : ScriptedAI(creature) @@ -479,6 +476,11 @@ public: uint32 mojoWaveTimer; uint32 mojoPuddleTimer; }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetGundrakAI(creature); + } }; void AddSC_boss_drakkari_colossus() diff --git a/src/server/scripts/Northrend/Gundrak/boss_eck.cpp b/src/server/scripts/Northrend/Gundrak/boss_eck.cpp index 6f391e17f66..d3f659b0d30 100644 --- a/src/server/scripts/Northrend/Gundrak/boss_eck.cpp +++ b/src/server/scripts/Northrend/Gundrak/boss_eck.cpp @@ -16,8 +16,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "gundrak.h" +#include "ScriptedCreature.h" enum Texts { diff --git a/src/server/scripts/Northrend/Gundrak/boss_gal_darah.cpp b/src/server/scripts/Northrend/Gundrak/boss_gal_darah.cpp index 76e2cb065e1..da38a556474 100644 --- a/src/server/scripts/Northrend/Gundrak/boss_gal_darah.cpp +++ b/src/server/scripts/Northrend/Gundrak/boss_gal_darah.cpp @@ -16,9 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" #include "gundrak.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellScript.h" enum Spells { @@ -250,9 +252,7 @@ class spell_gal_darah_impaling_charge : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_IMPALING_CHARGE_CONTROL_VEHICLE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_IMPALING_CHARGE_CONTROL_VEHICLE }); } bool Load() override diff --git a/src/server/scripts/Northrend/Gundrak/boss_moorabi.cpp b/src/server/scripts/Northrend/Gundrak/boss_moorabi.cpp index 4d05f485c5f..edb33f4c7cf 100644 --- a/src/server/scripts/Northrend/Gundrak/boss_moorabi.cpp +++ b/src/server/scripts/Northrend/Gundrak/boss_moorabi.cpp @@ -16,10 +16,10 @@ */ #include "ScriptMgr.h" +#include "gundrak.h" #include "ScriptedCreature.h" #include "SpellInfo.h" #include "SpellScript.h" -#include "gundrak.h" enum Spells { @@ -225,9 +225,7 @@ class spell_moorabi_mojo_frenzy : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MOJO_FRENZY_CAST_SPEED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MOJO_FRENZY_CAST_SPEED }); } void HandlePeriodic(AuraEffect const* /*aurEff*/) diff --git a/src/server/scripts/Northrend/Gundrak/boss_slad_ran.cpp b/src/server/scripts/Northrend/Gundrak/boss_slad_ran.cpp index b5162207d2a..797ba774204 100644 --- a/src/server/scripts/Northrend/Gundrak/boss_slad_ran.cpp +++ b/src/server/scripts/Northrend/Gundrak/boss_slad_ran.cpp @@ -16,10 +16,12 @@ */ #include "ScriptMgr.h" +#include "gundrak.h" +#include "MotionMaster.h" +#include "Player.h" #include "ScriptedCreature.h" #include "SpellAuras.h" -#include "gundrak.h" -#include "Player.h" +#include "TemporarySummon.h" enum Spells { @@ -207,11 +209,6 @@ class npc_slad_ran_constrictor : public CreatureScript public: npc_slad_ran_constrictor() : CreatureScript("npc_slad_ran_constrictor") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_slad_ran_constrictorAI(creature); - } - struct npc_slad_ran_constrictorAI : public ScriptedAI { npc_slad_ran_constrictorAI(Creature* creature) : ScriptedAI(creature) @@ -255,6 +252,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetGundrakAI(creature); + } }; class npc_slad_ran_viper : public CreatureScript @@ -262,11 +263,6 @@ class npc_slad_ran_viper : public CreatureScript public: npc_slad_ran_viper() : CreatureScript("npc_slad_ran_viper") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_slad_ran_viperAI(creature); - } - struct npc_slad_ran_viperAI : public ScriptedAI { npc_slad_ran_viperAI(Creature* creature) : ScriptedAI(creature) @@ -294,6 +290,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetGundrakAI(creature); + } }; class achievement_snakes_whyd_it_have_to_be_snakes : public AchievementCriteriaScript diff --git a/src/server/scripts/Northrend/Gundrak/gundrak.h b/src/server/scripts/Northrend/Gundrak/gundrak.h index ec63e1dab3c..9ab31fce9e2 100644 --- a/src/server/scripts/Northrend/Gundrak/gundrak.h +++ b/src/server/scripts/Northrend/Gundrak/gundrak.h @@ -18,6 +18,8 @@ #ifndef GUNDRAK_H_ #define GUNDRAK_H_ +#include "CreatureAIImpl.h" + #define GundrakScriptName "instance_gundrak" #define DataHeader "GD" @@ -91,10 +93,10 @@ enum GDInstanceMisc TIMER_STATUE_ACTIVATION = 3500 }; -template -inline AI* GetGundrakAI(Creature* creature) +template +inline AI* GetGundrakAI(T* obj) { - return GetInstanceAI(creature, GundrakScriptName); + return GetInstanceAI(obj, GundrakScriptName); } #endif // GUNDRAK_H_ diff --git a/src/server/scripts/Northrend/Gundrak/instance_gundrak.cpp b/src/server/scripts/Northrend/Gundrak/instance_gundrak.cpp index 469aa0d3fd2..55b955c9533 100644 --- a/src/server/scripts/Northrend/Gundrak/instance_gundrak.cpp +++ b/src/server/scripts/Northrend/Gundrak/instance_gundrak.cpp @@ -15,21 +15,23 @@ * with this program. If not, see . */ -#include "InstanceScript.h" -#include "Player.h" #include "ScriptMgr.h" -#include "gundrak.h" +#include "Creature.h" #include "EventMap.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "gundrak.h" +#include "InstanceScript.h" +#include "Map.h" DoorData const doorData[] = { { GO_GAL_DARAH_DOOR_1, DATA_GAL_DARAH, DOOR_TYPE_PASSAGE }, { GO_GAL_DARAH_DOOR_2, DATA_GAL_DARAH, DOOR_TYPE_PASSAGE }, - { GO_GAL_DARAH_DOOR_3, DATA_GAL_DARAH, DOOR_TYPE_ROOM }, + { GO_GAL_DARAH_DOOR_3, DATA_GAL_DARAH, DOOR_TYPE_ROOM }, { GO_ECK_THE_FEROCIOUS_DOOR, DATA_MOORABI, DOOR_TYPE_PASSAGE }, { GO_ECK_THE_FEROCIOUS_DOOR_BEHIND, DATA_ECK_THE_FEROCIOUS, DOOR_TYPE_PASSAGE }, - { 0, 0, DOOR_TYPE_ROOM } // END + { 0, 0, DOOR_TYPE_ROOM } // END }; ObjectData const creatureData[] = 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 30fc14ed5a8..7f8d38feac4 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_blood_prince_council.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_blood_prince_council.cpp @@ -15,13 +15,19 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellAuraEffects.h" #include "icecrown_citadel.h" -#include "Player.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "PassiveAI.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "Spell.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum Texts { @@ -1242,9 +1248,7 @@ class spell_taldaram_flame_ball_visual : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BALL_OF_FLAMES)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BALL_OF_FLAMES }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1354,10 +1358,7 @@ class spell_valanar_kinetic_bomb : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_KINETIC_BOMB_EXPLOSION) - || !sSpellMgr->GetSpellInfo(SPELL_KINETIC_BOMB_VISUAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_KINETIC_BOMB_EXPLOSION, SPELL_KINETIC_BOMB_VISUAL }); } void HandleDummyTick(AuraEffect const* /*aurEff*/) @@ -1461,9 +1462,7 @@ class spell_blood_council_shadow_prison : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHADOW_PRISON_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHADOW_PRISON_DAMAGE }); } void HandleDummyTick(AuraEffect const* aurEff) 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 9bd0d48a458..8c485a8d602 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 @@ -15,13 +15,17 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "Spell.h" -#include "SpellAuraEffects.h" #include "GridNotifiers.h" #include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellMgr.h" +#include "SpellScript.h" enum Texts { @@ -376,7 +380,7 @@ class boss_blood_queen_lana_thel : public CreatureScript } case EVENT_BLOOD_MIRROR: { - // victim can be NULL when this is processed in the same update tick as EVENT_AIR_PHASE + // victim can be nullptr when this is processed in the same update tick as EVENT_AIR_PHASE if (me->GetVictim()) { Player* newOfftank = SelectRandomTarget(true); @@ -481,13 +485,13 @@ class boss_blood_queen_lana_thel : public CreatureScript private: // offtank for this encounter is the player standing closest to main tank - Player* SelectRandomTarget(bool includeOfftank, std::list* targetList = NULL) + Player* SelectRandomTarget(bool includeOfftank, std::list* targetList = nullptr) { std::list const& threatlist = me->getThreatManager().getThreatList(); std::list tempTargets; if (threatlist.empty()) - return NULL; + return nullptr; for (std::list::const_iterator itr = threatlist.begin(); itr != threatlist.end(); ++itr) if (Unit* refTarget = (*itr)->getTarget()) @@ -495,12 +499,12 @@ class boss_blood_queen_lana_thel : public CreatureScript tempTargets.push_back(refTarget->ToPlayer()); if (tempTargets.empty()) - return NULL; + return nullptr; if (targetList) { *targetList = tempTargets; - return NULL; + return nullptr; } if (includeOfftank) @@ -539,13 +543,7 @@ class spell_blood_queen_vampiric_bite : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ESSENCE_OF_THE_BLOOD_QUEEN_PLR)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_FRENZIED_BLOODTHIRST)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_PRESENCE_OF_THE_DARKFALLEN)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ESSENCE_OF_THE_BLOOD_QUEEN_PLR, SPELL_FRENZIED_BLOODTHIRST, SPELL_PRESENCE_OF_THE_DARKFALLEN }); } SpellCastResult CheckTarget() @@ -675,9 +673,7 @@ class spell_blood_queen_bloodbolt : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TWILIGHT_BLOODBOLT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TWILIGHT_BLOODBOLT }); } bool Load() override @@ -726,9 +722,7 @@ class spell_blood_queen_essence_of_the_blood_queen : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ESSENCE_OF_THE_BLOOD_QUEEN_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ESSENCE_OF_THE_BLOOD_QUEEN_HEAL }); } void OnProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -813,9 +807,7 @@ class spell_blood_queen_pact_of_the_darkfallen_dmg : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PACT_OF_THE_DARKFALLEN_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PACT_OF_THE_DARKFALLEN_DAMAGE }); } // this is an additional effect to be executed diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_deathbringer_saurfang.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_deathbringer_saurfang.cpp index 75bdb596305..70580733a03 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_deathbringer_saurfang.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_deathbringer_saurfang.cpp @@ -15,13 +15,17 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" +#include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" #include "SpellAuras.h" -#include "icecrown_citadel.h" -#include "Player.h" +#include "SpellScript.h" enum ScriptTexts { @@ -1007,11 +1011,7 @@ class spell_deathbringer_blood_link : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BLOOD_LINK_POWER)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_BLOOD_POWER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BLOOD_LINK_POWER, SPELL_BLOOD_POWER }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1043,9 +1043,7 @@ class spell_deathbringer_blood_link_aura : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MARK_OF_THE_FALLEN_CHAMPION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MARK_OF_THE_FALLEN_CHAMPION }); } void HandlePeriodicTick(AuraEffect const* /*aurEff*/) @@ -1128,9 +1126,7 @@ class spell_deathbringer_rune_of_blood : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BLOOD_LINK_DUMMY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BLOOD_LINK_DUMMY }); } void HandleScript(SpellEffIndex effIndex) @@ -1163,9 +1159,7 @@ class spell_deathbringer_blood_beast_blood_link : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BLOOD_LINK_DUMMY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BLOOD_LINK_DUMMY }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1197,9 +1191,7 @@ class spell_deathbringer_blood_nova : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BLOOD_LINK_DUMMY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BLOOD_LINK_DUMMY }); } void HandleScript(SpellEffIndex effIndex) @@ -1229,13 +1221,6 @@ class spell_deathbringer_blood_nova_targeting : public SpellScriptLoader { PrepareSpellScript(spell_deathbringer_blood_nova_targeting_SpellScript); - public: - spell_deathbringer_blood_nova_targeting_SpellScript() - { - target = nullptr; - } - - private: void FilterTargetsInitial(std::list& targets) { if (targets.empty()) @@ -1284,7 +1269,7 @@ class spell_deathbringer_blood_nova_targeting : public SpellScriptLoader OnEffectHitTarget += SpellEffectFn(spell_deathbringer_blood_nova_targeting_SpellScript::HandleForceCast, EFFECT_0, SPELL_EFFECT_FORCE_CAST); } - WorldObject* target; + WorldObject* target = nullptr; }; SpellScript* GetSpellScript() const override diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_festergut.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_festergut.cpp index 8c2922efd14..79ce2eba735 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_festergut.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_festergut.cpp @@ -15,12 +15,16 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" +#include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "SpellAuras.h" -#include "icecrown_citadel.h" -#include "Player.h" +#include "SpellMgr.h" +#include "SpellScript.h" enum ScriptTexts { @@ -197,7 +201,7 @@ class boss_festergut : public CreatureScript // just cast and dont bother with target, conditions will handle it ++_inhaleCounter; if (_inhaleCounter < 3) - me->CastSpell(me, gaseousBlight[_inhaleCounter], true, NULL, NULL, me->GetGUID()); + me->CastSpell(me, gaseousBlight[_inhaleCounter], true, nullptr, nullptr, me->GetGUID()); } events.ScheduleEvent(EVENT_INHALE_BLIGHT, urand(33500, 35000)); @@ -410,9 +414,7 @@ class spell_festergut_gastric_bloat : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GASTRIC_EXPLOSION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_GASTRIC_EXPLOSION }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -448,9 +450,7 @@ class spell_festergut_blighted_spores : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_INOCULATED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_INOCULATED }); } void ExtraEffect(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) 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 35b5c3ba23d..fe5f7c1570d 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_icecrown_gunship_battle.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_icecrown_gunship_battle.cpp @@ -15,22 +15,27 @@ * with this program. If not, see . */ +#include "ScriptMgr.h" #include "CellImpl.h" #include "CreatureTextMgr.h" -#include "GridNotifiersImpl.h" #include "GossipDef.h" +#include "GridNotifiersImpl.h" +#include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "MoveSpline.h" #include "MoveSplineInit.h" +#include "ObjectAccessor.h" #include "PassiveAI.h" -#include "ScriptMgr.h" #include "ScriptedCreature.h" -#include "SpellHistory.h" #include "SpellAuraEffects.h" +#include "SpellHistory.h" +#include "SpellMgr.h" #include "SpellScript.h" +#include "TemporarySummon.h" #include "Transport.h" #include "TransportMgr.h" #include "Vehicle.h" -#include "icecrown_citadel.h" enum Texts { @@ -217,8 +222,7 @@ Position const OrgrimsHammerTeleportExit = { 7.461699f, 0.158853f, 35.72989f, 0. Position const OrgrimsHammerTeleportPortal = { 47.550990f, -0.101778f, 37.61111f, 0.0f }; Position const SkybreakerTeleportExit = { -17.55738f, -0.090421f, 21.18366f, 0.0f }; -uint32 const MuradinExitPathSize = 10; -G3D::Vector3 const MuradinExitPath[MuradinExitPathSize] = +G3D::Vector3 const MuradinExitPath[] = { { 8.130936f, -0.2699585f, 20.31728f }, { 6.380936f, -0.2699585f, 20.31728f }, @@ -231,9 +235,9 @@ G3D::Vector3 const MuradinExitPath[MuradinExitPathSize] = { -12.24222f, 23.10601f, 21.28468f }, { -14.88477f, 25.20844f, 21.59985f }, }; +uint32 const MuradinExitPathSize = std::extent::value; -uint32 const SaurfangExitPathSize = 13; -G3D::Vector3 const SaurfangExitPath[SaurfangExitPathSize] = +G3D::Vector3 const SaurfangExitPath[] = { { 30.43987f, 0.1475817f, 36.10674f }, { 21.36141f, -3.056458f, 35.42970f }, @@ -249,6 +253,7 @@ G3D::Vector3 const SaurfangExitPath[SaurfangExitPathSize] = { 17.9247f, -29.36282f, 35.66611f }, { 15.33203f, -30.42621f, 35.93796f } }; +uint32 const SaurfangExitPathSize = std::extent::value; enum PassengerSlots { @@ -383,7 +388,7 @@ public: void ResetSlots(uint32 team) { - _transport = NULL; + _transport = nullptr; for (uint32 i = 0; i < MAX_SLOTS; ++i) _controlledSlots[i].Clear(); @@ -398,7 +403,7 @@ public: return false; bool summoned = false; - time_t now = time(NULL); + time_t now = time(nullptr); for (int32 i = first; i <= last; ++i) { if (_respawnCooldowns[i] > now) @@ -411,7 +416,7 @@ public: continue; } - if (Creature* passenger = _transport->SummonPassenger(_slotInfo[i].Entry, SelectSpawnPoint(), TEMPSUMMON_CORPSE_TIMED_DESPAWN, NULL, 15000)) + if (Creature* passenger = _transport->SummonPassenger(_slotInfo[i].Entry, SelectSpawnPoint(), TEMPSUMMON_CORPSE_TIMED_DESPAWN, nullptr, 15000)) { _controlledSlots[i] = passenger->GetGUID(); _respawnCooldowns[i] = time_t(0); @@ -426,7 +431,7 @@ public: void ClearSlot(PassengerSlots slot) { _controlledSlots[slot].Clear(); - _respawnCooldowns[slot] = time(NULL) + _slotInfo[slot].Cooldown; + _respawnCooldowns[slot] = time(nullptr) + _slotInfo[slot].Cooldown; } bool SlotsNeedRefill(PassengerSlots first, PassengerSlots last) const @@ -541,7 +546,7 @@ uint32 const BattleExperienceEvent::ExperiencedTimes[5] = { 100000, 70000, 60000 struct gunship_npc_AI : public ScriptedAI { gunship_npc_AI(Creature* creature) : ScriptedAI(creature), - Instance(creature->GetInstanceScript()), Slot(NULL), Index(uint32(-1)) + Instance(creature->GetInstanceScript()), Slot(nullptr), Index(uint32(-1)) { BurningPitchId = Instance->GetData(DATA_TEAM_IN_INSTANCE) == HORDE ? SPELL_BURNING_PITCH_A : SPELL_BURNING_PITCH_H; me->setRegeneratingHealth(false); @@ -677,7 +682,7 @@ class npc_gunship : public CreatureScript { if (damage >= me->GetHealth()) { - JustDied(NULL); + JustDied(nullptr); damage = me->GetHealth() - 1; return; } @@ -833,7 +838,7 @@ class npc_gunship : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { if (!creature->GetTransport()) - return NULL; + return nullptr; return GetIcecrownCitadelAI(creature); } @@ -853,7 +858,7 @@ class npc_high_overlord_saurfang_igb : public CreatureScript _controller.SetTransport(creature->GetTransport()); me->setRegeneratingHealth(false); me->m_CombatDistance = 70.0f; - _firstMageCooldown = time(NULL) + 60; + _firstMageCooldown = time(nullptr) + 60; _axethrowersYellCooldown = time_t(0); _rocketeersYellCooldown = time_t(0); } @@ -863,7 +868,7 @@ class npc_high_overlord_saurfang_igb : public CreatureScript ScriptedAI::InitializeAI(); _events.Reset(); - _firstMageCooldown = time(NULL) + 60; + _firstMageCooldown = time(nullptr) + 60; _axethrowersYellCooldown = time_t(0); _rocketeersYellCooldown = time_t(0); } @@ -915,7 +920,7 @@ class npc_high_overlord_saurfang_igb : public CreatureScript } else if (action == ACTION_SPAWN_MAGE) { - time_t now = time(NULL); + time_t now = time(nullptr); if (_firstMageCooldown > now) _events.ScheduleEvent(EVENT_SUMMON_MAGE, (_firstMageCooldown - now) * IN_MILLISECONDS); else @@ -1034,10 +1039,10 @@ class npc_high_overlord_saurfang_igb : public CreatureScript _controller.SummonCreatures(SLOT_MARINE_1, Is25ManRaid() ? SLOT_MARINE_4 : SLOT_MARINE_2); _controller.SummonCreatures(SLOT_SERGEANT_1, Is25ManRaid() ? SLOT_SERGEANT_2 : SLOT_SERGEANT_1); if (Transport* orgrimsHammer = me->GetTransport()) - orgrimsHammer->SummonPassenger(NPC_TELEPORT_PORTAL, OrgrimsHammerTeleportPortal, TEMPSUMMON_TIMED_DESPAWN, NULL, 21000); + orgrimsHammer->SummonPassenger(NPC_TELEPORT_PORTAL, OrgrimsHammerTeleportPortal, TEMPSUMMON_TIMED_DESPAWN, nullptr, 21000); if (Transport* skybreaker = HashMapHolder::Find(_instance->GetGuidData(DATA_ICECROWN_GUNSHIP_BATTLE))) - skybreaker->SummonPassenger(NPC_TELEPORT_EXIT, SkybreakerTeleportExit, TEMPSUMMON_TIMED_DESPAWN, NULL, 23000); + skybreaker->SummonPassenger(NPC_TELEPORT_EXIT, SkybreakerTeleportExit, TEMPSUMMON_TIMED_DESPAWN, nullptr, 23000); _events.ScheduleEvent(EVENT_ADDS_BOARD_YELL, 6000); _events.ScheduleEvent(EVENT_ADDS, 60000); @@ -1049,10 +1054,10 @@ class npc_high_overlord_saurfang_igb : public CreatureScript case EVENT_CHECK_RIFLEMAN: if (_controller.SummonCreatures(SLOT_RIFLEMAN_1, Is25ManRaid() ? SLOT_RIFLEMAN_8 : SLOT_RIFLEMAN_4)) { - if (_axethrowersYellCooldown < time(NULL)) + if (_axethrowersYellCooldown < time(nullptr)) { Talk(SAY_SAURFANG_AXETHROWERS); - _axethrowersYellCooldown = time(NULL) + 5; + _axethrowersYellCooldown = time(nullptr) + 5; } } _events.ScheduleEvent(EVENT_CHECK_RIFLEMAN, 1000); @@ -1060,10 +1065,10 @@ class npc_high_overlord_saurfang_igb : public CreatureScript case EVENT_CHECK_MORTAR: if (_controller.SummonCreatures(SLOT_MORTAR_1, Is25ManRaid() ? SLOT_MORTAR_4 : SLOT_MORTAR_2)) { - if (_rocketeersYellCooldown < time(NULL)) + if (_rocketeersYellCooldown < time(nullptr)) { Talk(SAY_SAURFANG_ROCKETEERS); - _rocketeersYellCooldown = time(NULL) + 5; + _rocketeersYellCooldown = time(nullptr) + 5; } } _events.ScheduleEvent(EVENT_CHECK_MORTAR, 1000); @@ -1122,7 +1127,7 @@ class npc_muradin_bronzebeard_igb : public CreatureScript _controller.SetTransport(creature->GetTransport()); me->setRegeneratingHealth(false); me->m_CombatDistance = 70.0f; - _firstMageCooldown = time(NULL) + 60; + _firstMageCooldown = time(nullptr) + 60; _riflemanYellCooldown = time_t(0); _mortarYellCooldown = time_t(0); } @@ -1132,7 +1137,7 @@ class npc_muradin_bronzebeard_igb : public CreatureScript ScriptedAI::InitializeAI(); _events.Reset(); - _firstMageCooldown = time(NULL) + 60; + _firstMageCooldown = time(nullptr) + 60; _riflemanYellCooldown = time_t(0); _mortarYellCooldown = time_t(0); } @@ -1184,7 +1189,7 @@ class npc_muradin_bronzebeard_igb : public CreatureScript } else if (action == ACTION_SPAWN_MAGE) { - time_t now = time(NULL); + time_t now = time(nullptr); if (_firstMageCooldown > now) _events.ScheduleEvent(EVENT_SUMMON_MAGE, (_firstMageCooldown - now) * IN_MILLISECONDS); else @@ -1307,10 +1312,10 @@ class npc_muradin_bronzebeard_igb : public CreatureScript _controller.SummonCreatures(SLOT_MARINE_1, Is25ManRaid() ? SLOT_MARINE_4 : SLOT_MARINE_2); _controller.SummonCreatures(SLOT_SERGEANT_1, Is25ManRaid() ? SLOT_SERGEANT_2 : SLOT_SERGEANT_1); if (Transport* skybreaker = me->GetTransport()) - skybreaker->SummonPassenger(NPC_TELEPORT_PORTAL, SkybreakerTeleportPortal, TEMPSUMMON_TIMED_DESPAWN, NULL, 21000); + skybreaker->SummonPassenger(NPC_TELEPORT_PORTAL, SkybreakerTeleportPortal, TEMPSUMMON_TIMED_DESPAWN, nullptr, 21000); if (Transport* orgrimsHammer = HashMapHolder::Find(_instance->GetGuidData(DATA_ICECROWN_GUNSHIP_BATTLE))) - orgrimsHammer->SummonPassenger(NPC_TELEPORT_EXIT, OrgrimsHammerTeleportExit, TEMPSUMMON_TIMED_DESPAWN, NULL, 23000); + orgrimsHammer->SummonPassenger(NPC_TELEPORT_EXIT, OrgrimsHammerTeleportExit, TEMPSUMMON_TIMED_DESPAWN, nullptr, 23000); _events.ScheduleEvent(EVENT_ADDS_BOARD_YELL, 6000); _events.ScheduleEvent(EVENT_ADDS, 60000); @@ -1322,10 +1327,10 @@ class npc_muradin_bronzebeard_igb : public CreatureScript case EVENT_CHECK_RIFLEMAN: if (_controller.SummonCreatures(SLOT_RIFLEMAN_1, Is25ManRaid() ? SLOT_RIFLEMAN_8 : SLOT_RIFLEMAN_4)) { - if (_riflemanYellCooldown < time(NULL)) + if (_riflemanYellCooldown < time(nullptr)) { Talk(SAY_MURADIN_RIFLEMAN); - _riflemanYellCooldown = time(NULL) + 5; + _riflemanYellCooldown = time(nullptr) + 5; } } _events.ScheduleEvent(EVENT_CHECK_RIFLEMAN, 1000); @@ -1333,10 +1338,10 @@ class npc_muradin_bronzebeard_igb : public CreatureScript case EVENT_CHECK_MORTAR: if (_controller.SummonCreatures(SLOT_MORTAR_1, Is25ManRaid() ? SLOT_MORTAR_4 : SLOT_MORTAR_2)) { - if (_mortarYellCooldown < time(NULL)) + if (_mortarYellCooldown < time(nullptr)) { Talk(SAY_MURADIN_MORTAR); - _mortarYellCooldown = time(NULL) + 5; + _mortarYellCooldown = time(nullptr) + 5; } } _events.ScheduleEvent(EVENT_CHECK_MORTAR, 1000); @@ -1829,11 +1834,7 @@ class spell_igb_rocket_pack : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROCKET_PACK_DAMAGE) || - !sSpellMgr->GetSpellInfo(SPELL_ROCKET_BURST)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_ROCKET_PACK_DAMAGE, SPELL_ROCKET_BURST }); } void HandlePeriodic(AuraEffect const* /*aurEff*/) @@ -1920,13 +1921,6 @@ class spell_igb_on_gunship_deck : public SpellScriptLoader { PrepareAuraScript(spell_igb_on_gunship_deck_AuraScript); - public: - spell_igb_on_gunship_deck_AuraScript() - { - _teamInInstance = 0; - } - - private: bool Load() override { if (InstanceScript* instance = GetOwner()->GetInstanceScript()) @@ -1954,7 +1948,7 @@ class spell_igb_on_gunship_deck : public SpellScriptLoader AfterEffectApply += AuraEffectApplyFn(spell_igb_on_gunship_deck_AuraScript::HandleApply, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); } - uint32 _teamInInstance; + uint32 _teamInInstance = 0; }; AuraScript* GetAuraScript() const override @@ -2036,13 +2030,6 @@ class spell_igb_incinerating_blast : public SpellScriptLoader { PrepareSpellScript(spell_igb_incinerating_blast_SpellScript); - public: - spell_igb_incinerating_blast_SpellScript() - { - _energyLeft = 0; - } - - private: void StoreEnergy() { _energyLeft = GetCaster()->GetPower(POWER_ENERGY) - 10; @@ -2065,7 +2052,7 @@ class spell_igb_incinerating_blast : public SpellScriptLoader OnEffectLaunchTarget += SpellEffectFn(spell_igb_incinerating_blast_SpellScript::CalculateDamage, EFFECT_1, SPELL_EFFECT_SCHOOL_DAMAGE); } - uint32 _energyLeft; + uint32 _energyLeft = 0; }; SpellScript* GetSpellScript() const override @@ -2101,7 +2088,7 @@ class spell_igb_overheat : public SpellScriptLoader WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, GetUnitOwner()->GetPackGUID().size() + 1); data << GetUnitOwner()->GetPackGUID(); data << uint8(value); - player->GetSession()->SendPacket(&data); + player->SendDirectMessage(&data); } } } @@ -2251,7 +2238,7 @@ class spell_igb_burning_pitch : public SpellScriptLoader void HandleDummy(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); - GetCaster()->CastCustomSpell(uint32(GetEffectValue()), SPELLVALUE_BASE_POINT0, 8000, NULL, TRIGGERED_FULL_MASK); + GetCaster()->CastCustomSpell(uint32(GetEffectValue()), SPELLVALUE_BASE_POINT0, 8000, nullptr, TRIGGERED_FULL_MASK); GetHitUnit()->CastSpell(GetHitUnit(), SPELL_BURNING_PITCH, TRIGGERED_FULL_MASK); } @@ -2317,7 +2304,7 @@ class spell_igb_rocket_artillery_explosion : public SpellScriptLoader void DamageGunship(SpellEffIndex /*effIndex*/) { if (InstanceScript* instance = GetCaster()->GetInstanceScript()) - GetCaster()->CastCustomSpell(instance->GetData(DATA_TEAM_IN_INSTANCE) == HORDE ? SPELL_BURNING_PITCH_DAMAGE_A : SPELL_BURNING_PITCH_DAMAGE_H, SPELLVALUE_BASE_POINT0, 5000, NULL, TRIGGERED_FULL_MASK); + GetCaster()->CastCustomSpell(instance->GetData(DATA_TEAM_IN_INSTANCE) == HORDE ? SPELL_BURNING_PITCH_DAMAGE_A : SPELL_BURNING_PITCH_DAMAGE_H, SPELLVALUE_BASE_POINT0, 5000, nullptr, TRIGGERED_FULL_MASK); } void Register() override @@ -2382,13 +2369,6 @@ class spell_igb_check_for_players : public SpellScriptLoader { PrepareSpellScript(spell_igb_check_for_players_SpellScript); - public: - spell_igb_check_for_players_SpellScript() - { - _playerCount = 0; - } - - private: bool Load() override { return GetCaster()->GetTypeId() == TYPEID_UNIT; @@ -2402,7 +2382,7 @@ class spell_igb_check_for_players : public SpellScriptLoader void TriggerWipe() { if (!_playerCount) - GetCaster()->ToCreature()->AI()->JustDied(NULL); + GetCaster()->ToCreature()->AI()->JustDied(nullptr); } void TeleportPlayer(SpellEffIndex /*effIndex*/) @@ -2418,7 +2398,7 @@ class spell_igb_check_for_players : public SpellScriptLoader OnEffectHitTarget += SpellEffectFn(spell_igb_check_for_players_SpellScript::TeleportPlayer, EFFECT_0, SPELL_EFFECT_DUMMY); } - uint32 _playerCount; + uint32 _playerCount = 0; }; SpellScript* GetSpellScript() const override diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_lady_deathwhisper.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_lady_deathwhisper.cpp index b2a058469cd..8db1e13cb47 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_lady_deathwhisper.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_lady_deathwhisper.cpp @@ -15,14 +15,18 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "PoolMgr.h" #include "Group.h" #include "icecrown_citadel.h" -#include "SpellInfo.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "PoolMgr.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum ScriptTexts { @@ -176,10 +180,10 @@ Position const SummonPositions[7] = {-524.2480f, 2211.920f, 62.90960f, 3.141592f}, // 7 Upper (Random Cultist) }; -class DaranavanMoveEvent : public BasicEvent +class DarnavanMoveEvent : public BasicEvent { public: - DaranavanMoveEvent(Creature& darnavan) : _darnavan(darnavan) { } + DarnavanMoveEvent(Creature& darnavan) : _darnavan(darnavan) { } bool Execute(uint64 /*time*/, uint32 /*diff*/) override { @@ -361,11 +365,11 @@ class boss_lady_deathwhisper : public CreatureScript darnavan->CombatStop(true); darnavan->GetMotionMaster()->MoveIdle(); darnavan->SetReactState(REACT_PASSIVE); - darnavan->m_Events.AddEvent(new DaranavanMoveEvent(*darnavan), darnavan->m_Events.CalculateTime(10000)); + darnavan->m_Events.AddEvent(new DarnavanMoveEvent(*darnavan), darnavan->m_Events.CalculateTime(10000)); darnavan->AI()->Talk(SAY_DARNAVAN_RESCUED); - if (!killer) - return; + if (!killer) + return; if (Player* owner = killer->GetCharmerOrOwnerPlayerOrPlayerItself()) { @@ -453,7 +457,7 @@ class boss_lady_deathwhisper : public CreatureScript } } - void SpellHitTarget(Unit* target, const SpellInfo* spell) override + void SpellHitTarget(Unit* target, SpellInfo const* spell) override { if (spell->Id == SPELL_SUMMON_SPIRITS) _nextVengefulShadeTargetGUID.push_back(target->GetGUID()); @@ -888,8 +892,8 @@ class npc_darnavan : public CreatureScript { _events.Reset(); - if (!killer) - return; + if (!killer) + return; if (Player* owner = killer->GetCharmerOrOwnerPlayerOrPlayerItself()) { @@ -1047,9 +1051,7 @@ class spell_deathwhisper_dominated_mind : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DOMINATE_MIND_SCALE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DOMINATE_MIND_SCALE }); } void HandleApply(AuraEffect const* /*eff*/, AuraEffectHandleModes /*mode*/) @@ -1081,9 +1083,7 @@ class spell_deathwhisper_summon_spirits : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_SHADE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_SHADE }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_lord_marrowgar.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_lord_marrowgar.cpp index 66b3cc3a12a..3bbec36a1ca 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_lord_marrowgar.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_lord_marrowgar.cpp @@ -15,13 +15,18 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" +#include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "MoveSplineInit.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "SpellAuras.h" -#include "MoveSplineInit.h" -#include "Player.h" -#include "icecrown_citadel.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum ScriptTexts { @@ -98,7 +103,7 @@ enum Actions ACTION_TALK_ENTER_ZONE = 2 }; -class BoneSpikeTargetSelector : public std::unary_function +class BoneSpikeTargetSelector { public: BoneSpikeTargetSelector(UnitAI* ai) : _ai(ai) { } @@ -611,11 +616,7 @@ class spell_marrowgar_bone_spike_graveyard : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - for (uint32 i = 0; i < 3; ++i) - if (!sSpellMgr->GetSpellInfo(BoneSpikeSummonId[i])) - return false; - - return true; + return ValidateSpellInfo(BoneSpikeSummonId); } bool Load() override diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_professor_putricide.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_professor_putricide.cpp index 736eb5201ca..56ecb09d778 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_professor_putricide.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_professor_putricide.cpp @@ -15,15 +15,21 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" +#include "DBCStores.h" +#include "GameObject.h" +#include "GridNotifiers.h" +#include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellAuraEffects.h" -#include "Group.h" -#include "Spell.h" -#include "icecrown_citadel.h" +#include "SpellMgr.h" +#include "SpellScript.h" +#include "TemporarySummon.h" #include "Vehicle.h" -#include "GridNotifiers.h" enum Say { @@ -373,7 +379,7 @@ class boss_professor_putricide : public CreatureScript 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()); + festergut->CastSpell(festergut, SPELL_GASEOUS_BLIGHT_LARGE, false, nullptr, nullptr, festergut->GetGUID()); break; case POINT_ROTFACE: instance->SetBossState(DATA_ROTFACE, IN_PROGRESS); // needed here for delayed gate close @@ -470,7 +476,7 @@ class boss_professor_putricide : public CreatureScript case ACTION_ROTFACE_OOZE: Talk(SAY_ROTFACE_OOZE_FLOOD); if (Creature* dummy = ObjectAccessor::GetCreature(*me, _oozeFloodDummyGUIDs[_oozeFloodStage])) - dummy->CastSpell(dummy, oozeFloodSpells[_oozeFloodStage], true, NULL, NULL, me->GetGUID()); // cast from self for LoS (with prof's GUID for logs) + dummy->CastSpell(dummy, oozeFloodSpells[_oozeFloodStage], true, nullptr, nullptr, me->GetGUID()); // cast from self for LoS (with prof's GUID for logs) if (++_oozeFloodStage == 4) _oozeFloodStage = 0; break; @@ -580,7 +586,7 @@ class boss_professor_putricide : public CreatureScript EnterEvadeMode(); break; case EVENT_FESTERGUT_GOO: - me->CastCustomSpell(SPELL_MALLEABLE_GOO_SUMMON, SPELLVALUE_MAX_TARGETS, 1, NULL, true); + me->CastCustomSpell(SPELL_MALLEABLE_GOO_SUMMON, SPELLVALUE_MAX_TARGETS, 1, nullptr, true); events.ScheduleEvent(EVENT_FESTERGUT_GOO, (Is25ManRaid() ? 10000 : 30000) + urand(0, 5000), 0, PHASE_FESTERGUT); break; case EVENT_ROTFACE_DIES: @@ -881,20 +887,9 @@ class spell_putricide_ooze_channel : public SpellScriptLoader { PrepareSpellScript(spell_putricide_ooze_channel_SpellScript); - public: - spell_putricide_ooze_channel_SpellScript() - { - _target = nullptr; - } - - private: bool Validate(SpellInfo const* spell) override { - if (!spell->ExcludeTargetAuraSpell) - return false; - if (!sSpellMgr->GetSpellInfo(spell->ExcludeTargetAuraSpell)) - return false; - return true; + return ValidateSpellInfo({ spell->ExcludeTargetAuraSpell }); } // set up initial variables and check if caster is creature @@ -942,7 +937,7 @@ class spell_putricide_ooze_channel : public SpellScriptLoader AfterHit += SpellHitFn(spell_putricide_ooze_channel_SpellScript::StartAttack); } - WorldObject* _target; + WorldObject* _target = nullptr; }; SpellScript* GetSpellScript() const override @@ -1041,7 +1036,7 @@ class spell_putricide_unstable_experiment : public SpellScriptLoader uint32 stage = creature->AI()->GetData(DATA_EXPERIMENT_STAGE); creature->AI()->SetData(DATA_EXPERIMENT_STAGE, stage ^ true); - Creature* target = NULL; + Creature* target = nullptr; std::list creList; GetCreatureListWithEntryInGrid(creList, GetCaster(), NPC_ABOMINATION_WING_MAD_SCIENTIST_STALKER, 200.0f); // 2 of them are spawned at green place - weird trick blizz @@ -1112,10 +1107,7 @@ class spell_putricide_ooze_tank_protection : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].TriggerSpell) || - !sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_1].TriggerSpell)) - return false; - return true; + return ValidateSpellInfo({ spellInfo->Effects[EFFECT_0].TriggerSpell, spellInfo->Effects[EFFECT_1].TriggerSpell }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1157,7 +1149,7 @@ class spell_putricide_choking_gas_bomb : public SpellScriptLoader continue; uint32 spellId = uint32(GetSpellInfo()->Effects[i].CalcValue()); - GetCaster()->CastSpell(GetCaster(), spellId, true, NULL, NULL, GetCaster()->GetGUID()); + GetCaster()->CastSpell(GetCaster(), spellId, true, nullptr, nullptr, GetCaster()->GetGUID()); } } @@ -1184,11 +1176,7 @@ class spell_putricide_unbound_plague : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_UNBOUND_PLAGUE)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_UNBOUND_PLAGUE_SEARCHER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_UNBOUND_PLAGUE, SPELL_UNBOUND_PLAGUE_SEARCHER }); } void FilterTargets(std::list& targets) @@ -1202,7 +1190,6 @@ class spell_putricide_unbound_plague : public SpellScriptLoader } } - targets.remove_if(Trinity::UnitAuraCheck(true, sSpellMgr->GetSpellIdForDifficulty(SPELL_UNBOUND_PLAGUE, GetCaster()))); Trinity::Containers::RandomResize(targets, 1); } @@ -1217,7 +1204,6 @@ class spell_putricide_unbound_plague : public SpellScriptLoader return; uint32 plagueId = sSpellMgr->GetSpellIdForDifficulty(SPELL_UNBOUND_PLAGUE, GetCaster()); - if (!GetHitUnit()->HasAura(plagueId)) { if (Creature* professor = ObjectAccessor::GetCreature(*GetCaster(), instance->GetGuidData(DATA_PROFESSOR_PUTRICIDE))) @@ -1332,7 +1318,7 @@ class spell_putricide_mutated_plague : public SpellScriptLoader damage *= int32(pow(multiplier, GetStackAmount())); damage = int32(damage * 1.5f); - GetTarget()->CastCustomSpell(triggerSpell, SPELLVALUE_BASE_POINT0, damage, GetTarget(), true, NULL, aurEff, GetCasterGUID()); + GetTarget()->CastCustomSpell(triggerSpell, SPELLVALUE_BASE_POINT0, damage, GetTarget(), true, nullptr, aurEff, GetCasterGUID()); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1344,7 +1330,7 @@ class spell_putricide_mutated_plague : public SpellScriptLoader return; int32 heal = healSpellInfo->Effects[0].CalcValue() * GetStackAmount(); - GetTarget()->CastCustomSpell(healSpell, SPELLVALUE_BASE_POINT0, heal, GetTarget(), true, NULL, NULL, GetCasterGUID()); + GetTarget()->CastCustomSpell(healSpell, SPELLVALUE_BASE_POINT0, heal, GetTarget(), true, nullptr, nullptr, GetCasterGUID()); } void Register() override diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_rotface.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_rotface.cpp index 66d434b7704..b71a862b4ec 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_rotface.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_rotface.cpp @@ -15,12 +15,16 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellAuraEffects.h" #include "GridNotifiers.h" #include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "SpellAuras.h" +#include "SpellScript.h" +#include "TemporarySummon.h" // KNOWN BUGS: // ~ No Slime Spray animation directly at target spot @@ -469,7 +473,7 @@ class spell_rotface_ooze_flood : public SpellScriptLoader return; triggers.sort(Trinity::ObjectDistanceOrderPred(GetHitUnit())); - GetHitUnit()->CastSpell(triggers.back(), uint32(GetEffectValue()), false, NULL, NULL, GetOriginalCaster() ? GetOriginalCaster()->GetGUID() : ObjectGuid::Empty); + GetHitUnit()->CastSpell(triggers.back(), uint32(GetEffectValue()), false, nullptr, nullptr, GetOriginalCaster() ? GetOriginalCaster()->GetGUID() : ObjectGuid::Empty); } void FilterTargets(std::list& targets) @@ -540,9 +544,7 @@ class spell_rotface_mutated_infection : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(uint32(spellInfo->Effects[EFFECT_2].CalcValue()))) - return false; - return true; + return ValidateSpellInfo({ uint32(spellInfo->Effects[EFFECT_2].CalcValue()) }); } void HandleEffectRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -676,7 +678,7 @@ class spell_rotface_large_ooze_buff_combine : public SpellScriptLoader if (Creature* cre = GetCaster()->ToCreature()) cre->AI()->DoAction(EVENT_STICKY_OOZE); - GetCaster()->CastSpell(GetCaster(), SPELL_UNSTABLE_OOZE_EXPLOSION, false, NULL, NULL, GetCaster()->GetGUID()); + GetCaster()->CastSpell(GetCaster(), SPELL_UNSTABLE_OOZE_EXPLOSION, false, nullptr, nullptr, GetCaster()->GetGUID()); if (InstanceScript* instance = GetCaster()->GetInstanceScript()) instance->SetData(DATA_OOZE_DANCE_ACHIEVEMENT, uint32(false)); } @@ -708,9 +710,7 @@ class spell_rotface_unstable_ooze_explosion_init : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_UNSTABLE_OOZE_EXPLOSION_TRIGGER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_UNSTABLE_OOZE_EXPLOSION_TRIGGER }); } void HandleCast(SpellEffIndex effIndex) @@ -759,7 +759,7 @@ class spell_rotface_unstable_ooze_explosion : public SpellScriptLoader // let Rotface handle the cast - caster dies before this executes if (InstanceScript* script = GetCaster()->GetInstanceScript()) if (Creature* rotface = script->instance->GetCreature(script->GetGuidData(DATA_ROTFACE))) - rotface->CastSpell(x, y, z, triggered_spell_id, true, NULL, NULL, GetCaster()->GetGUID()); + rotface->CastSpell(x, y, z, triggered_spell_id, true, nullptr, nullptr, GetCaster()->GetGUID()); } void Register() override diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_sindragosa.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_sindragosa.cpp index e97f447c7e4..7d02971daf2 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_sindragosa.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_sindragosa.cpp @@ -15,12 +15,19 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellAuraEffects.h" #include "GridNotifiers.h" #include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellMgr.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum Texts { @@ -187,7 +194,7 @@ class FrostBombExplosion : public BasicEvent bool Execute(uint64 /*eventTime*/, uint32 /*updateTime*/) override { - _owner->CastSpell((Unit*)NULL, SPELL_FROST_BOMB, false, NULL, NULL, _sindragosaGUID); + _owner->CastSpell((Unit*)nullptr, SPELL_FROST_BOMB, false, nullptr, nullptr, _sindragosaGUID); _owner->RemoveAurasDueToSpell(SPELL_FROST_BOMB_VISUAL); return true; } @@ -305,7 +312,6 @@ class boss_sindragosa : public CreatureScript { if (action == ACTION_START_FROSTWYRM) { - instance->SetData(DATA_SINDRAGOSA_INTRO, 0); if (TempSummon* summon = me->ToTempSummon()) summon->SetTempSummonType(TEMPSUMMON_DEAD_DESPAWN); @@ -364,7 +370,7 @@ class boss_sindragosa : public CreatureScript events.ScheduleEvent(EVENT_AIR_MOVEMENT, 1); break; case POINT_AIR_PHASE: - me->CastCustomSpell(SPELL_ICE_TOMB_TARGET, SPELLVALUE_MAX_TARGETS, RAID_MODE(2, 5, 2, 6), NULL, TRIGGERED_FULL_MASK); + me->CastCustomSpell(SPELL_ICE_TOMB_TARGET, SPELLVALUE_MAX_TARGETS, RAID_MODE(2, 5, 2, 6), nullptr, TRIGGERED_FULL_MASK); me->SetFacingTo(float(M_PI), true); events.ScheduleEvent(EVENT_AIR_MOVEMENT_FAR, 1); events.ScheduleEvent(EVENT_FROST_BOMB, 9000); @@ -1067,12 +1073,7 @@ class spell_sindragosa_s_fury : public SpellScriptLoader bool Load() override { // This script should execute only in Icecrown Citadel - if (InstanceMap* instance = GetCaster()->GetMap()->ToInstanceMap()) - if (instance->GetInstanceScript()) - if (instance->GetScriptId() == sObjectMgr->GetScriptId(ICCScriptName)) - return true; - - return false; + return InstanceHasScript(GetCaster(), ICCScriptName); } void SelectDest() @@ -1241,15 +1242,13 @@ class spell_sindragosa_instability : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BACKLASH)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BACKLASH }); } void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { if (GetTargetApplication()->GetRemoveMode() == AURA_REMOVE_BY_EXPIRE) - GetTarget()->CastCustomSpell(SPELL_BACKLASH, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), GetTarget(), true, NULL, aurEff, GetCasterGUID()); + GetTarget()->CastCustomSpell(SPELL_BACKLASH, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), GetTarget(), true, nullptr, aurEff, GetCasterGUID()); } void Register() override @@ -1275,9 +1274,7 @@ class spell_sindragosa_frost_beacon : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ICE_TOMB_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ICE_TOMB_DAMAGE }); } void PeriodicTick(AuraEffect const* /*aurEff*/) @@ -1331,7 +1328,7 @@ class spell_sindragosa_ice_tomb : public SpellScriptLoader { 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)) + if (GameObject* go = summon->SummonGameObject(GO_ICE_BLOCK, pos, QuaternionData(), 0)) { go->SetSpellId(SPELL_ICE_TOMB_DAMAGE); summon->AddGameObject(go); @@ -1370,9 +1367,7 @@ class spell_sindragosa_icy_grip : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ICY_GRIP_JUMP)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ICY_GRIP_JUMP }); } void HandleScript(SpellEffIndex effIndex) @@ -1444,9 +1439,7 @@ class spell_rimefang_icy_blast : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ICY_BLAST_AREA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ICY_BLAST_AREA }); } void HandleTriggerMissile(SpellEffIndex effIndex) @@ -1496,9 +1489,7 @@ class spell_frostwarden_handler_order_whelp : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FOCUS_FIRE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FOCUS_FIRE }); } void FilterTargets(std::list& targets) 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 f6e6967b41e..c2910eb36ef 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_the_lich_king.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_the_lich_king.cpp @@ -15,19 +15,22 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "Spell.h" -#include "Vehicle.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" #include "CreatureTextMgr.h" +#include "GridNotifiersImpl.h" #include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "ScriptedCreature.h" +#include "Spell.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "Vehicle.h" +#include "Weather.h" enum Texts { @@ -362,7 +365,7 @@ enum Misc DATA_VILE = 45814622 }; -class NecroticPlagueTargetCheck : public std::unary_function +class NecroticPlagueTargetCheck { public: NecroticPlagueTargetCheck(Unit const* obj, uint32 notAura1 = 0, uint32 notAura2 = 0) @@ -420,10 +423,7 @@ class FrozenThroneResetWorker class StartMovementEvent : public BasicEvent { public: - StartMovementEvent(Creature* summoner, Creature* owner) - : _summonerGuid(summoner->GetGUID()), _owner(owner) - { - } + StartMovementEvent(Creature* summoner, Creature* owner) : _summonerGuid(summoner->GetGUID()), _owner(owner) { } bool Execute(uint64 /*time*/, uint32 /*diff*/) override { @@ -451,7 +451,7 @@ class VileSpiritActivateEvent : public BasicEvent { _owner->SetReactState(REACT_AGGRESSIVE); _owner->CastSpell(_owner, SPELL_VILE_SPIRIT_MOVE_SEARCH, true); - _owner->CastSpell((Unit*)NULL, SPELL_VILE_SPIRIT_DAMAGE_SEARCH, true); + _owner->CastSpell((Unit*)nullptr, SPELL_VILE_SPIRIT_DAMAGE_SEARCH, true); return true; } @@ -469,7 +469,7 @@ class TriggerWickedSpirit : public BasicEvent bool Execute(uint64 /*time*/, uint32 /*diff*/) override { - _owner->CastCustomSpell(SPELL_TRIGGER_VILE_SPIRIT_HEROIC, SPELLVALUE_MAX_TARGETS, 1, NULL, true); + _owner->CastCustomSpell(SPELL_TRIGGER_VILE_SPIRIT_HEROIC, SPELLVALUE_MAX_TARGETS, 1, nullptr, true); if (--_counter) { @@ -605,8 +605,8 @@ class boss_the_lich_king : public CreatureScript me->GetMap()->SetZoneOverrideLight(AREA_ICECROWN_CITADEL, 0, 5000); break; case ACTION_BREAK_FROSTMOURNE: - me->CastSpell((Unit*)NULL, SPELL_SUMMON_BROKEN_FROSTMOURNE, TRIGGERED_IGNORE_CAST_IN_PROGRESS); - me->CastSpell((Unit*)NULL, SPELL_SUMMON_BROKEN_FROSTMOURNE_2, TRIGGERED_IGNORE_CAST_IN_PROGRESS); + me->CastSpell((Unit*)nullptr, SPELL_SUMMON_BROKEN_FROSTMOURNE, TRIGGERED_IGNORE_CAST_IN_PROGRESS); + me->CastSpell((Unit*)nullptr, SPELL_SUMMON_BROKEN_FROSTMOURNE_2, TRIGGERED_IGNORE_CAST_IN_PROGRESS); SetEquipmentSlots(false, EQUIP_BROKEN_FROSTMOURNE); events.ScheduleEvent(EVENT_OUTRO_TALK_6, 2500, 0, PHASE_OUTRO); break; @@ -688,7 +688,7 @@ class boss_the_lich_king : public CreatureScript summons.DespawnAll(); me->GetMap()->SetZoneMusic(AREA_ICECROWN_CITADEL, MUSIC_FURY_OF_FROSTMOURNE); me->InterruptNonMeleeSpells(true); - me->CastSpell((Unit*)NULL, SPELL_FURY_OF_FROSTMOURNE, TRIGGERED_NONE); + me->CastSpell((Unit*)nullptr, SPELL_FURY_OF_FROSTMOURNE, TRIGGERED_NONE); me->SetWalk(true); events.ScheduleEvent(EVENT_OUTRO_TALK_1, 2600, 0, PHASE_OUTRO); events.ScheduleEvent(EVENT_OUTRO_EMOTE_TALK, 6600, 0, PHASE_OUTRO); @@ -735,7 +735,7 @@ class boss_the_lich_king : public CreatureScript break; case NPC_FROSTMOURNE_TRIGGER: { - summon->CastSpell((Unit*)NULL, SPELL_BROKEN_FROSTMOURNE, true); + summon->CastSpell((Unit*)nullptr, SPELL_BROKEN_FROSTMOURNE, true); me->GetMap()->SetZoneOverrideLight(AREA_ICECROWN_CITADEL, LIGHT_SOULSTORM, 10000); me->GetMap()->SetZoneWeather(AREA_ICECROWN_CITADEL, WEATHER_STATE_BLACKSNOW, 0.5f); @@ -1043,7 +1043,7 @@ class boss_the_lich_king : public CreatureScript } break; case EVENT_FROSTMOURNE_HEROIC: - if (TempSummon* terenas = me->GetMap()->SummonCreature(NPC_TERENAS_MENETHIL_FROSTMOURNE_H, TerenasSpawnHeroic, NULL, 50000)) + if (TempSummon* terenas = me->GetMap()->SummonCreature(NPC_TERENAS_MENETHIL_FROSTMOURNE_H, TerenasSpawnHeroic, nullptr, 50000)) { terenas->AI()->DoAction(ACTION_FROSTMOURNE_INTRO); std::list triggers; @@ -1097,11 +1097,11 @@ class boss_the_lich_king : public CreatureScript Talk(SAY_LK_OUTRO_6); if (Creature* tirion = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_HIGHLORD_TIRION_FORDRING))) tirion->SetFacingToObject(me); - me->CastSpell((Unit*)NULL, SPELL_SUMMON_BROKEN_FROSTMOURNE_3, TRIGGERED_IGNORE_CAST_IN_PROGRESS); + me->CastSpell((Unit*)nullptr, SPELL_SUMMON_BROKEN_FROSTMOURNE_3, TRIGGERED_IGNORE_CAST_IN_PROGRESS); SetEquipmentSlots(false, EQUIP_UNEQUIP); break; case EVENT_OUTRO_SOUL_BARRAGE: - me->CastSpell((Unit*)NULL, SPELL_SOUL_BARRAGE, TRIGGERED_IGNORE_CAST_IN_PROGRESS); + me->CastSpell((Unit*)nullptr, SPELL_SOUL_BARRAGE, TRIGGERED_IGNORE_CAST_IN_PROGRESS); sCreatureTextMgr->SendSound(me, SOUND_PAIN, CHAT_MSG_MONSTER_YELL, 0, TEXT_RANGE_NORMAL, TEAM_OTHER, false); // set flight me->SetDisableGravity(true); @@ -1671,7 +1671,7 @@ class npc_strangulate_vehicle : public CreatureScript { if (Unit* summoner = summ->GetSummoner()) { - summoner->CastSpell((Unit*)NULL, SPELL_HARVEST_SOUL_VISUAL, true); + summoner->CastSpell((Unit*)nullptr, SPELL_HARVEST_SOUL_VISUAL, true); summoner->ExitVehicle(summoner); if (!IsHeroic()) summoner->CastSpell(summoner, SPELL_HARVEST_SOUL_TELEPORT, true); @@ -1754,7 +1754,7 @@ class npc_terenas_menethil : public CreatureScript } break; case ACTION_TELEPORT_BACK: - me->CastSpell((Unit*)NULL, SPELL_RESTORE_SOUL, TRIGGERED_NONE); + me->CastSpell((Unit*)nullptr, SPELL_RESTORE_SOUL, TRIGGERED_NONE); me->DespawnOrUnsummon(3000); break; default: @@ -1784,7 +1784,7 @@ class npc_terenas_menethil : public CreatureScript _events.ScheduleEvent(EVENT_TELEPORT_BACK, 1000); if (Creature* warden = me->FindNearestCreature(NPC_SPIRIT_WARDEN, 20.0f)) { - warden->CastSpell((Unit*)NULL, SPELL_DESTROY_SOUL, TRIGGERED_NONE); + warden->CastSpell((Unit*)nullptr, SPELL_DESTROY_SOUL, TRIGGERED_NONE); warden->DespawnOrUnsummon(2000); } @@ -1842,7 +1842,7 @@ class npc_terenas_menethil : public CreatureScript case EVENT_DESTROY_SOUL: me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); if (Creature* warden = me->FindNearestCreature(NPC_SPIRIT_WARDEN, 20.0f)) - warden->CastSpell((Unit*)NULL, SPELL_DESTROY_SOUL, TRIGGERED_NONE); + warden->CastSpell((Unit*)nullptr, SPELL_DESTROY_SOUL, TRIGGERED_NONE); DoCast(SPELL_TERENAS_LOSES_INSIDE); _events.ScheduleEvent(EVENT_TELEPORT_BACK, 1000); break; @@ -2103,9 +2103,7 @@ class spell_the_lich_king_necrotic_plague : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_NECROTIC_PLAGUE_JUMP)) - return false; - return true; + return ValidateSpellInfo({ SPELL_NECROTIC_PLAGUE_JUMP }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2123,7 +2121,7 @@ class spell_the_lich_king_necrotic_plague : public SpellScriptLoader CustomSpellValues values; //values.AddSpellMod(SPELLVALUE_AURA_STACK, 2); values.AddSpellMod(SPELLVALUE_MAX_TARGETS, 1); - GetTarget()->CastCustomSpell(SPELL_NECROTIC_PLAGUE_JUMP, values, NULL, TRIGGERED_FULL_MASK, NULL, NULL, GetCasterGUID()); + GetTarget()->CastCustomSpell(SPELL_NECROTIC_PLAGUE_JUMP, values, nullptr, TRIGGERED_FULL_MASK, nullptr, nullptr, GetCasterGUID()); if (Unit* caster = GetCaster()) caster->CastSpell(caster, SPELL_PLAGUE_SIPHON, true); } @@ -2219,7 +2217,7 @@ class spell_the_lich_king_necrotic_plague_jump : public SpellScriptLoader CustomSpellValues values; values.AddSpellMod(SPELLVALUE_AURA_STACK, GetStackAmount()); - GetTarget()->CastCustomSpell(SPELL_NECROTIC_PLAGUE_JUMP, values, NULL, TRIGGERED_FULL_MASK, NULL, NULL, GetCasterGUID()); + GetTarget()->CastCustomSpell(SPELL_NECROTIC_PLAGUE_JUMP, values, nullptr, TRIGGERED_FULL_MASK, nullptr, nullptr, GetCasterGUID()); if (Unit* caster = GetCaster()) caster->CastSpell(caster, SPELL_PLAGUE_SIPHON, true); } @@ -2238,7 +2236,7 @@ class spell_the_lich_king_necrotic_plague_jump : public SpellScriptLoader CustomSpellValues values; values.AddSpellMod(SPELLVALUE_AURA_STACK, GetStackAmount()); values.AddSpellMod(SPELLVALUE_BASE_POINT1, AURA_REMOVE_BY_ENEMY_SPELL); // add as marker (spell has no effect 1) - GetTarget()->CastCustomSpell(SPELL_NECROTIC_PLAGUE_JUMP, values, NULL, TRIGGERED_FULL_MASK, NULL, NULL, GetCasterGUID()); + GetTarget()->CastCustomSpell(SPELL_NECROTIC_PLAGUE_JUMP, values, nullptr, TRIGGERED_FULL_MASK, nullptr, nullptr, GetCasterGUID()); if (Unit* caster = GetCaster()) caster->CastSpell(caster, SPELL_PLAGUE_SIPHON, true); @@ -2308,7 +2306,7 @@ class spell_the_lich_king_shadow_trap_periodic : public SpellScriptLoader if (targets.empty()) return; - GetCaster()->CastSpell((Unit*)NULL, SPELL_SHADOW_TRAP_KNOCKBACK, true); + GetCaster()->CastSpell((Unit*)nullptr, SPELL_SHADOW_TRAP_KNOCKBACK, true); } void Register() override @@ -2334,7 +2332,7 @@ class spell_the_lich_king_quake : public SpellScriptLoader bool Load() override { - return GetCaster()->GetInstanceScript() != NULL; + return GetCaster()->GetInstanceScript() != nullptr; } void FilterTargets(std::list& targets) @@ -2373,9 +2371,7 @@ class spell_the_lich_king_ice_burst_target_search : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ICE_BURST)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ICE_BURST }); } void CheckTargetCount(std::list& unitList) @@ -2532,9 +2528,7 @@ class spell_the_lich_king_soul_reaper : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SOUL_REAPER_BUFF)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SOUL_REAPER_BUFF }); } void OnPeriodic(AuraEffect const* /*aurEff*/) @@ -2564,18 +2558,9 @@ class spell_the_lich_king_valkyr_target_search : public SpellScriptLoader { PrepareSpellScript(spell_the_lich_king_valkyr_target_search_SpellScript); - public: - spell_the_lich_king_valkyr_target_search_SpellScript() - { - _target = nullptr; - } - - private: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CHARGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CHARGE }); } void SelectTarget(std::list& targets) @@ -2613,7 +2598,7 @@ class spell_the_lich_king_valkyr_target_search : public SpellScriptLoader OnEffectHitTarget += SpellEffectFn(spell_the_lich_king_valkyr_target_search_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } - WorldObject* _target; + WorldObject* _target = nullptr; }; SpellScript* GetSpellScript() const override @@ -2659,9 +2644,7 @@ class spell_the_lich_king_life_siphon : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_LIFE_SIPHON_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_LIFE_SIPHON_HEAL }); } void TriggerHeal() @@ -2706,7 +2689,7 @@ class spell_the_lich_king_vile_spirits : public SpellScriptLoader void OnPeriodic(AuraEffect const* aurEff) { if (_is25Man || ((aurEff->GetTickNumber() - 1) % 5)) - GetTarget()->CastSpell((Unit*)NULL, GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell, true, NULL, aurEff, GetCasterGUID()); + GetTarget()->CastSpell((Unit*)nullptr, GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell, true, nullptr, aurEff, GetCasterGUID()); } void Register() override @@ -2829,7 +2812,7 @@ class spell_the_lich_king_vile_spirit_damage_target_search : public SpellScriptL if (TempSummon* summon = GetCaster()->ToTempSummon()) if (Unit* summoner = summon->GetSummoner()) summoner->GetAI()->SetData(DATA_VILE, 1); - GetCaster()->CastSpell((Unit*)NULL, SPELL_SPIRIT_BURST, true); + GetCaster()->CastSpell((Unit*)nullptr, SPELL_SPIRIT_BURST, true); GetCaster()->ToCreature()->DespawnOrUnsummon(3000); GetCaster()->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); } @@ -2857,14 +2840,14 @@ class spell_the_lich_king_harvest_soul : public SpellScriptLoader bool Load() override { - return GetOwner()->GetInstanceScript() != NULL; + return GetOwner()->GetInstanceScript() != nullptr; } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { // m_originalCaster to allow stacking from different casters, meh if (GetTargetApplication()->GetRemoveMode() == AURA_REMOVE_BY_DEATH) - GetTarget()->CastSpell((Unit*)NULL, SPELL_HARVESTED_SOUL, true, NULL, NULL, GetTarget()->GetInstanceScript()->GetGuidData(DATA_THE_LICH_KING)); + GetTarget()->CastSpell((Unit*)nullptr, SPELL_HARVESTED_SOUL, true, nullptr, nullptr, GetTarget()->GetInstanceScript()->GetGuidData(DATA_THE_LICH_KING)); } void Register() override @@ -2930,7 +2913,7 @@ class spell_the_lich_king_soul_rip : public SpellScriptLoader PreventDefaultAction(); // shouldn't be needed, this is channeled if (Unit* caster = GetCaster()) - caster->CastCustomSpell(SPELL_SOUL_RIP_DAMAGE, SPELLVALUE_BASE_POINT0, 5000 * aurEff->GetTickNumber(), GetTarget(), true, NULL, aurEff, GetCasterGUID()); + caster->CastCustomSpell(SPELL_SOUL_RIP_DAMAGE, SPELLVALUE_BASE_POINT0, 5000 * aurEff->GetTickNumber(), GetTarget(), true, nullptr, aurEff, GetCasterGUID()); } void Register() override @@ -2964,7 +2947,7 @@ class spell_the_lich_king_restore_soul : public SpellScriptLoader bool Load() override { _instance = GetCaster()->GetInstanceScript(); - return _instance != NULL; + return _instance != nullptr; } void HandleScript(SpellEffIndex /*effIndex*/) @@ -3016,9 +2999,7 @@ class spell_the_lich_king_dark_hunger : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DARK_HUNGER_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DARK_HUNGER_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -3055,14 +3036,14 @@ class spell_the_lich_king_in_frostmourne_room : public SpellScriptLoader bool Load() override { - return GetOwner()->GetInstanceScript() != NULL; + return GetOwner()->GetInstanceScript() != nullptr; } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { // m_originalCaster to allow stacking from different casters, meh if (GetTargetApplication()->GetRemoveMode() == AURA_REMOVE_BY_DEATH) - GetTarget()->CastSpell((Unit*)NULL, SPELL_HARVESTED_SOUL, true, NULL, NULL, GetTarget()->GetInstanceScript()->GetGuidData(DATA_THE_LICH_KING)); + GetTarget()->CastSpell((Unit*)nullptr, SPELL_HARVESTED_SOUL, true, nullptr, nullptr, GetTarget()->GetInstanceScript()->GetGuidData(DATA_THE_LICH_KING)); } void Register() override @@ -3089,7 +3070,7 @@ class spell_the_lich_king_summon_spirit_bomb : public SpellScriptLoader void HandleScript(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); - GetHitUnit()->CastSpell((Unit*)NULL, uint32(GetEffectValue()), true); + GetHitUnit()->CastSpell((Unit*)nullptr, uint32(GetEffectValue()), true); } void Register() override @@ -3147,7 +3128,7 @@ class spell_the_lich_king_jump : public SpellScriptLoader { PreventHitDefaultEffect(effIndex); GetHitUnit()->RemoveAurasDueToSpell(SPELL_RAISE_DEAD); - GetHitUnit()->CastSpell((Unit*)NULL, SPELL_JUMP_2, true); + GetHitUnit()->CastSpell((Unit*)nullptr, SPELL_JUMP_2, true); if (Creature* creature = GetHitCreature()) creature->AI()->DoAction(ACTION_BREAK_FROSTMOURNE); } diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_valithria_dreamwalker.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_valithria_dreamwalker.cpp index 04f016e2fbb..4bc49f7f74a 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_valithria_dreamwalker.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_valithria_dreamwalker.cpp @@ -15,16 +15,18 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" +#include "CellImpl.h" +#include "GridNotifiersImpl.h" +#include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "PhasingHandler.h" #include "ScriptedCreature.h" #include "SpellAuraEffects.h" -#include "Cell.h" -#include "CellImpl.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "icecrown_citadel.h" +#include "SpellScript.h" enum Texts { @@ -162,16 +164,16 @@ class RisenArchmageCheck } }; -struct ManaVoidSelector : public std::unary_function +struct ManaVoidSelector { - explicit ManaVoidSelector(WorldObject const* source) : _source(source) { } + explicit ManaVoidSelector(WorldObject const* source) : _source(source) { } - bool operator()(Unit* unit) const - { - return unit->getPowerType() == POWER_MANA && _source->GetDistance(unit) > 15.0f; - } + bool operator()(Unit* unit) const + { + return unit->getPowerType() == POWER_MANA && _source->GetDistance(unit) > 15.0f; + } - WorldObject const* _source; + WorldObject const* _source; }; class DelayedCastEvent : public BasicEvent @@ -199,9 +201,7 @@ class DelayedCastEvent : public BasicEvent class AuraRemoveEvent : public BasicEvent { public: - AuraRemoveEvent(Creature* trigger, uint32 spellId) : _trigger(trigger), _spellId(spellId) - { - } + AuraRemoveEvent(Creature* trigger, uint32 spellId) : _trigger(trigger), _spellId(spellId) { } bool Execute(uint64 /*time*/, uint32 /*diff*/) override { @@ -217,9 +217,7 @@ class AuraRemoveEvent : public BasicEvent class ValithriaDespawner : public BasicEvent { public: - explicit ValithriaDespawner(Creature* creature) : _creature(creature) - { - } + explicit ValithriaDespawner(Creature* creature) : _creature(creature) { } bool Execute(uint64 /*currTime*/, uint32 /*diff*/) override { @@ -685,7 +683,7 @@ class npc_the_lich_king_controller : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetIcecrownCitadelAI(creature); } }; @@ -1170,13 +1168,6 @@ class spell_dreamwalker_decay_periodic_timer : public SpellScriptLoader { PrepareAuraScript(spell_dreamwalker_decay_periodic_timer_AuraScript); - public: - spell_dreamwalker_decay_periodic_timer_AuraScript() - { - _decayRate = 0; - } - - private: bool Load() override { _decayRate = GetId() != SPELL_TIMER_BLAZING_SKELETON ? 1000 : 5000; @@ -1197,7 +1188,7 @@ class spell_dreamwalker_decay_periodic_timer : public SpellScriptLoader OnEffectUpdatePeriodic += AuraEffectUpdatePeriodicFn(spell_dreamwalker_decay_periodic_timer_AuraScript::DecayPeriodicTimer, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL); } - int32 _decayRate; + int32 _decayRate = 0; }; AuraScript* GetAuraScript() const override @@ -1266,9 +1257,7 @@ class spell_dreamwalker_summon_suppresser : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_SUPPRESSER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_SUPPRESSER }); } void PeriodicTick(AuraEffect const* /*aurEff*/) @@ -1418,13 +1407,6 @@ class spell_dreamwalker_nightmare_cloud : public SpellScriptLoader { PrepareAuraScript(spell_dreamwalker_nightmare_cloud_AuraScript); - public: - spell_dreamwalker_nightmare_cloud_AuraScript() - { - _instance = nullptr; - } - - private: bool Load() override { _instance = GetOwner()->GetInstanceScript(); @@ -1442,7 +1424,7 @@ class spell_dreamwalker_nightmare_cloud : public SpellScriptLoader OnEffectPeriodic += AuraEffectPeriodicFn(spell_dreamwalker_nightmare_cloud_AuraScript::PeriodicTick, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL); } - InstanceScript* _instance; + InstanceScript* _instance = nullptr; }; AuraScript* GetAuraScript() const override diff --git a/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel.cpp b/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel.cpp index 35b8aa0ad5a..f11077011d3 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel.cpp @@ -15,18 +15,19 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" -#include "PassiveAI.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" -#include "SpellAuraEffects.h" -#include "SmartAI.h" #include "icecrown_citadel.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "PassiveAI.h" +#include "ScriptedEscortAI.h" +#include "SmartAI.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "VehicleDefines.h" // Weekly quest support // * Deprogramming (DONE) @@ -738,7 +739,7 @@ class npc_alchemist_adrianna : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_alchemist_adriannaAI(creature); + return GetIcecrownCitadelAI(creature); } }; @@ -1133,7 +1134,7 @@ class npc_crok_scourgebane : public CreatureScript if (!_wipeCheckTimer) { _wipeCheckTimer = 1000; - Player* player = NULL; + Player* player = nullptr; Trinity::AnyPlayerInObjectRangeCheck check(me, 60.0f); Trinity::PlayerSearcher searcher(me, player, check); Cell::VisitWorldObjects(me, searcher, 60.0f); @@ -1448,7 +1449,7 @@ class npc_captain_arnath : public CreatureScript private: Creature* FindFriendlyCreature() const { - Creature* target = NULL; + Creature* target = nullptr; Trinity::MostHPMissingInRange u_check(me, 60.0f, 0); Trinity::CreatureLastSearcher searcher(me, target, u_check); Cell::VisitGridObjects(me, searcher, 60.0f); @@ -1676,9 +1677,7 @@ class npc_frostwing_vrykul : public CreatureScript struct npc_frostwing_vrykulAI : public SmartAI { - npc_frostwing_vrykulAI(Creature* creature) : SmartAI(creature) - { - } + npc_frostwing_vrykulAI(Creature* creature) : SmartAI(creature) { } bool CanAIAttack(Unit const* target) const override { @@ -1689,7 +1688,7 @@ class npc_frostwing_vrykul : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_frostwing_vrykulAI(creature); + return GetIcecrownCitadelAI(creature); } }; @@ -1733,7 +1732,7 @@ class npc_impaling_spear : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_impaling_spearAI(creature); + return GetIcecrownCitadelAI(creature); } }; @@ -1744,9 +1743,7 @@ class npc_arthas_teleport_visual : public CreatureScript struct npc_arthas_teleport_visualAI : public NullCreatureAI { - npc_arthas_teleport_visualAI(Creature* creature) : NullCreatureAI(creature), _instance(creature->GetInstanceScript()) - { - } + npc_arthas_teleport_visualAI(Creature* creature) : NullCreatureAI(creature), _instance(creature->GetInstanceScript()) { } void Reset() override { @@ -1783,7 +1780,7 @@ class npc_arthas_teleport_visual : public CreatureScript return GetIcecrownCitadelAI(creature); // Default to no script - return NULL; + return nullptr; } }; @@ -1923,13 +1920,6 @@ class spell_frost_giant_death_plague : public SpellScriptLoader { PrepareSpellScript(spell_frost_giant_death_plague_SpellScript); - public: - spell_frost_giant_death_plague_SpellScript() - { - _failed = false; - } - - private: // First effect void CountTargets(std::list& targets) { @@ -1968,7 +1958,7 @@ class spell_frost_giant_death_plague : public SpellScriptLoader OnEffectHitTarget += SpellEffectFn(spell_frost_giant_death_plague_SpellScript::HandleScript, EFFECT_1, SPELL_EFFECT_SCRIPT_EFFECT); } - bool _failed; + bool _failed = false; }; SpellScript* GetSpellScript() const override @@ -2122,6 +2112,49 @@ class spell_icc_soul_missile : public SpellScriptLoader } }; +class spell_trigger_spell_from_caster_SpellScript : public SpellScript +{ + PrepareSpellScript(spell_trigger_spell_from_caster_SpellScript); + + public: + spell_trigger_spell_from_caster_SpellScript(uint32 triggerId, TriggerCastFlags triggerFlags) + : SpellScript(), _triggerId(triggerId), _triggerFlags(triggerFlags) { } + + private: + bool Validate(SpellInfo const* /*spell*/) override + { + return ValidateSpellInfo({ _triggerId }); + } + + void HandleTrigger() + { + GetCaster()->CastSpell(GetHitUnit(), _triggerId, _triggerFlags); + } + + void Register() override + { + AfterHit += SpellHitFn(spell_trigger_spell_from_caster_SpellScript::HandleTrigger); + } + + uint32 _triggerId; + TriggerCastFlags _triggerFlags; +}; + +spell_trigger_spell_from_caster::spell_trigger_spell_from_caster(char const* scriptName, uint32 triggerId) + : SpellScriptLoader(scriptName), _triggerId(triggerId), _triggerFlags(TRIGGERED_FULL_MASK) +{ +} + +spell_trigger_spell_from_caster::spell_trigger_spell_from_caster(char const* scriptName, uint32 triggerId, TriggerCastFlags triggerFlags) + : SpellScriptLoader(scriptName), _triggerId(triggerId), _triggerFlags(triggerFlags) +{ +} + +SpellScript* spell_trigger_spell_from_caster::GetSpellScript() const +{ + return new spell_trigger_spell_from_caster_SpellScript(_triggerId, _triggerFlags); +} + class at_icc_saurfang_portal : public AreaTriggerScript { public: diff --git a/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel.h b/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel.h index ed723bbfe9d..176c6de01b8 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel.h +++ b/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel.h @@ -18,7 +18,11 @@ #ifndef ICECROWN_CITADEL_H_ #define ICECROWN_CITADEL_H_ -#include "SpellScript.h" +#include "CreatureAIImpl.h" +#include "ScriptMgr.h" + +struct Position; +enum TriggerCastFlags : uint32; #define ICCScriptName "instance_icecrown_citadel" #define DataHeader "IC" @@ -529,49 +533,16 @@ enum ICAreaIds class spell_trigger_spell_from_caster : public SpellScriptLoader { public: - spell_trigger_spell_from_caster(char const* scriptName, uint32 triggerId, TriggerCastFlags triggerFlags = TRIGGERED_FULL_MASK) - : SpellScriptLoader(scriptName), _triggerId(triggerId), _triggerFlags(triggerFlags) { } - - class spell_trigger_spell_from_caster_SpellScript : public SpellScript - { - PrepareSpellScript(spell_trigger_spell_from_caster_SpellScript); - - public: - spell_trigger_spell_from_caster_SpellScript(uint32 triggerId, TriggerCastFlags triggerFlags) - : SpellScript(), _triggerId(triggerId), _triggerFlags(triggerFlags) { } - - bool Validate(SpellInfo const* /*spell*/) override - { - if (!sSpellMgr->GetSpellInfo(_triggerId)) - return false; - return true; - } - - void HandleTrigger() - { - GetCaster()->CastSpell(GetHitUnit(), _triggerId, _triggerFlags); - } - - void Register() override - { - AfterHit += SpellHitFn(spell_trigger_spell_from_caster_SpellScript::HandleTrigger); - } - - uint32 _triggerId; - TriggerCastFlags _triggerFlags; - }; - - SpellScript* GetSpellScript() const override - { - return new spell_trigger_spell_from_caster_SpellScript(_triggerId, _triggerFlags); - } + spell_trigger_spell_from_caster(char const* scriptName, uint32 triggerId, TriggerCastFlags triggerFlags); + spell_trigger_spell_from_caster(char const* scriptName, uint32 triggerId); + SpellScript* GetSpellScript() const override; private: uint32 _triggerId; TriggerCastFlags _triggerFlags; }; -template +template inline AI* GetIcecrownCitadelAI(T* obj) { return GetInstanceAI(obj, ICCScriptName); diff --git a/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel_teleport.cpp b/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel_teleport.cpp index aa73f9b95a8..994f072577b 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel_teleport.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/icecrown_citadel_teleport.cpp @@ -15,13 +15,15 @@ * with this program. If not, see . */ +#include "ScriptMgr.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "icecrown_citadel.h" #include "InstanceScript.h" #include "Player.h" #include "ScriptedGossip.h" -#include "ScriptMgr.h" #include "Spell.h" -#include "icecrown_citadel.h" +#include "SpellMgr.h" static std::vector const TeleportSpells = { @@ -43,9 +45,7 @@ class icecrown_citadel_teleport : public GameObjectScript struct icecrown_citadel_teleportAI : public GameObjectAI { - icecrown_citadel_teleportAI(GameObject* go) : GameObjectAI(go) - { - } + icecrown_citadel_teleportAI(GameObject* go) : GameObjectAI(go) { } bool GossipSelect(Player* player, uint32 /*menuId*/, uint32 gossipListId) override { diff --git a/src/server/scripts/Northrend/IcecrownCitadel/instance_icecrown_citadel.cpp b/src/server/scripts/Northrend/IcecrownCitadel/instance_icecrown_citadel.cpp index 919a4ad4d21..766bd158886 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/instance_icecrown_citadel.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/instance_icecrown_citadel.cpp @@ -15,17 +15,20 @@ * with this program. If not, see . */ -#include "AccountMgr.h" +#include "ScriptMgr.h" +#include "AreaBoundary.h" +#include "CreatureAI.h" +#include "GameObject.h" +#include "icecrown_citadel.h" #include "InstanceScript.h" +#include "Map.h" #include "ObjectMgr.h" #include "Player.h" #include "PoolMgr.h" -#include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "TemporarySummon.h" #include "Transport.h" #include "TransportMgr.h" #include "WorldPacket.h" -#include "icecrown_citadel.h" enum EventIds { @@ -186,7 +189,7 @@ class instance_icecrown_citadel : public InstanceMapScript { if (!TeamInInstance) { - Map::PlayerList const &players = instance->GetPlayers(); + Map::PlayerList const& players = instance->GetPlayers(); if (!players.isEmpty()) if (Player* player = players.begin()->GetSource()) TeamInInstance = player->GetTeam(); @@ -1304,12 +1307,12 @@ class instance_icecrown_citadel : public InstanceMapScript teleporter->SetGoState(GO_STATE_ACTIVE); std::list stalkers; - GetCreatureListWithEntryInGrid(stalkers, teleporter, NPC_INVISIBLE_STALKER, 100.0f); + teleporter->GetCreatureListWithEntryInGrid(stalkers, NPC_INVISIBLE_STALKER, 100.0f); if (stalkers.empty()) return; stalkers.sort(Trinity::ObjectDistanceOrderPred(teleporter)); - stalkers.front()->CastSpell((Unit*)NULL, SPELL_ARTHAS_TELEPORTER_CEREMONY, false); + stalkers.front()->CastSpell((Unit*)nullptr, SPELL_ARTHAS_TELEPORTER_CEREMONY, false); stalkers.pop_front(); for (std::list::iterator itr = stalkers.begin(); itr != stalkers.end(); ++itr) (*itr)->AI()->Reset(); @@ -1446,11 +1449,11 @@ class instance_icecrown_citadel : public InstanceMapScript } break; case EVENT_TELEPORT_TO_FROSTMOURNE: // Harvest Soul (normal mode) - if (Creature* terenas = instance->SummonCreature(NPC_TERENAS_MENETHIL_FROSTMOURNE, TerenasSpawn, NULL, 63000)) + if (Creature* terenas = instance->SummonCreature(NPC_TERENAS_MENETHIL_FROSTMOURNE, TerenasSpawn, nullptr, 63000)) { terenas->AI()->DoAction(ACTION_FROSTMOURNE_INTRO); std::list triggers; - GetCreatureListWithEntryInGrid(triggers, terenas, NPC_WORLD_TRIGGER_INFINITE_AOI, 100.0f); + terenas->GetCreatureListWithEntryInGrid(triggers, NPC_WORLD_TRIGGER_INFINITE_AOI, 100.0f); if (!triggers.empty()) { triggers.sort(Trinity::ObjectDistanceOrderPred(terenas, false)); @@ -1458,7 +1461,7 @@ class instance_icecrown_citadel : public InstanceMapScript visual->CastSpell(visual, SPELL_FROSTMOURNE_TELEPORT_VISUAL, true); } - if (Creature* warden = instance->SummonCreature(NPC_SPIRIT_WARDEN, SpiritWardenSpawn, NULL, 63000)) + if (Creature* warden = instance->SummonCreature(NPC_SPIRIT_WARDEN, SpiritWardenSpawn, nullptr, 63000)) { terenas->AI()->AttackStart(warden); warden->AddThreat(terenas, 300000.0f); diff --git a/src/server/scripts/Northrend/IsleOfConquest/isle_of_conquest.cpp b/src/server/scripts/Northrend/IsleOfConquest/isle_of_conquest.cpp index 44890768246..efbc7c074f7 100644 --- a/src/server/scripts/Northrend/IsleOfConquest/isle_of_conquest.cpp +++ b/src/server/scripts/Northrend/IsleOfConquest/isle_of_conquest.cpp @@ -16,13 +16,17 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "PassiveAI.h" #include "BattlegroundIC.h" +#include "GameObject.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "PassiveAI.h" #include "Player.h" -#include "Vehicle.h" -#include "SpellScript.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" +#include "SpellScript.h" +#include "Vehicle.h" // TO-DO: This should be done with SmartAI, but yet it does not correctly support vehicles's AIs. // Even adding ReactState Passive we still have issues using SmartAI. @@ -206,9 +210,7 @@ class spell_ioc_parachute_ic : public SpellScriptLoader class StartLaunchEvent : public BasicEvent { public: - StartLaunchEvent(Position const& pos, ObjectGuid::LowType lowGuid) : _pos(pos), _lowGuid(lowGuid) - { - } + StartLaunchEvent(Position const& pos, ObjectGuid::LowType lowGuid) : _pos(pos), _lowGuid(lowGuid) { } bool Execute(uint64 /*time*/, uint32 /*diff*/) override { @@ -278,9 +280,7 @@ class spell_ioc_seaforium_blast_credit : public SpellScriptLoader 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; + return ValidateSpellInfo({ SPELL_A_BOMB_INABLE_CREDIT, SPELL_A_BOMB_INATION_CREDIT }); } void HandleAchievementCredit(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/Naxxramas/boss_anubrekhan.cpp b/src/server/scripts/Northrend/Naxxramas/boss_anubrekhan.cpp index 4a373102b70..a73512a9bd9 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_anubrekhan.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_anubrekhan.cpp @@ -16,9 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "Player.h" +#include "InstanceScript.h" #include "naxxramas.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" enum AnubSays { @@ -77,11 +79,6 @@ class boss_anubrekhan : public CreatureScript public: boss_anubrekhan() : CreatureScript("boss_anubrekhan") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_anubrekhanAI : public BossAI { boss_anubrekhanAI(Creature* creature) : BossAI(creature, BOSS_ANUBREKHAN) { } @@ -235,6 +232,10 @@ public: GuidSet guardCorpses; }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetNaxxramasAI(creature); + } }; class at_anubrekhan_entrance : public OnlyOnceAreaTriggerScript diff --git a/src/server/scripts/Northrend/Naxxramas/boss_faerlina.cpp b/src/server/scripts/Northrend/Naxxramas/boss_faerlina.cpp index 5b3a7d53c84..ca76190ad27 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_faerlina.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_faerlina.cpp @@ -16,9 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "naxxramas.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" #include "SpellAuras.h" #include "SpellInfo.h" @@ -190,7 +192,7 @@ class boss_faerlina : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_faerlinaAI(creature); + return GetNaxxramasAI(creature); } }; @@ -244,7 +246,7 @@ class npc_faerlina_add : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; diff --git a/src/server/scripts/Northrend/Naxxramas/boss_four_horsemen.cpp b/src/server/scripts/Northrend/Naxxramas/boss_four_horsemen.cpp index 89d0542eafb..9170fbe4600 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_four_horsemen.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_four_horsemen.cpp @@ -15,13 +15,18 @@ * with this program. If not, see . */ -#include "Player.h" -#include "GameTime.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "GameTime.h" +#include "InstanceScript.h" +#include "Log.h" +#include "Map.h" +#include "MotionMaster.h" #include "naxxramas.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Horseman { @@ -210,7 +215,7 @@ struct boss_four_horsemen_baseAI : public BossAI return; } instance->SetBossState(BOSS_HORSEMEN, IN_PROGRESS); - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + Map::PlayerList const& players = me->GetMap()->GetPlayers(); if (players.isEmpty()) // sanity check ResetEncounter(); @@ -456,7 +461,7 @@ class boss_four_horsemen_baron : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -538,7 +543,7 @@ class boss_four_horsemen_thane : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -608,7 +613,7 @@ class boss_four_horsemen_lady : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -690,7 +695,7 @@ class boss_four_horsemen_sir : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; diff --git a/src/server/scripts/Northrend/Naxxramas/boss_gluth.cpp b/src/server/scripts/Northrend/Naxxramas/boss_gluth.cpp index 4039cbc6345..400a956f6c4 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_gluth.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_gluth.cpp @@ -16,10 +16,12 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "naxxramas.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" #include "SpellScript.h" -#include enum Texts { @@ -87,11 +89,6 @@ class boss_gluth : public CreatureScript public: boss_gluth() : CreatureScript("boss_gluth") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_gluthAI : public BossAI { @@ -190,7 +187,7 @@ public: Creature* zombie = nullptr; for (SummonList::const_iterator itr = summons.begin(); !zombie && itr != summons.end(); ++itr) { - zombie=ObjectAccessor::GetCreature(*me, *itr); + zombie = ObjectAccessor::GetCreature(*me, *itr); if (zombie == nullptr || !zombie->IsAlive() || !zombie->IsWithinDistInMap(me, 10.0)) zombie = nullptr; } @@ -293,6 +290,10 @@ public: uint8 state; }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetNaxxramasAI(creature); + } }; // spell 28374 (10man) / 54426 (25man) - Decimate @@ -324,10 +325,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (sSpellMgr->GetSpellInfo(SPELL_DECIMATE_DMG)) - return true; - else - return false; + return ValidateSpellInfo({ SPELL_DECIMATE_DMG }); } void Register() override @@ -387,7 +385,6 @@ public: class npc_zombie_chow : public CreatureScript { public: - npc_zombie_chow() : CreatureScript("npc_zombie_chow") { } struct npc_zombie_chowAI : public ScriptedAI @@ -474,7 +471,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; diff --git a/src/server/scripts/Northrend/Naxxramas/boss_gothik.cpp b/src/server/scripts/Northrend/Naxxramas/boss_gothik.cpp index e6a919fc97f..2cd43cb8865 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_gothik.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_gothik.cpp @@ -16,12 +16,15 @@ */ #include "ScriptMgr.h" +#include "AreaBoundary.h" +#include "GridNotifiers.h" +#include "InstanceScript.h" +#include "Log.h" +#include "Map.h" +#include "naxxramas.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "GridNotifiers.h" -#include "CombatAI.h" -#include "AreaBoundary.h" -#include "naxxramas.h" /* Constants */ enum Yells @@ -127,15 +130,15 @@ enum Actions /* Room side checking logic */ -static AreaBoundary* const livingSide = new RectangleBoundary(2633.84f, 2750.49f, -3434.0f, -3360.78f); -static AreaBoundary* const deadSide = new RectangleBoundary(2633.84f, 2750.49f, -3360.78f, -3285.0f); +AreaBoundary* const livingSide = new RectangleBoundary(2633.84f, 2750.49f, -3434.0f, -3360.78f); +AreaBoundary* const deadSide = new RectangleBoundary(2633.84f, 2750.49f, -3360.78f, -3285.0f); enum Side { SIDE_NONE = 0, SIDE_LIVING, SIDE_DEAD }; -inline static Side GetSide(Position const* who) +inline Side GetSide(Position const* who) { if (livingSide->IsWithinBoundary(who)) return SIDE_LIVING; @@ -143,11 +146,11 @@ inline static Side GetSide(Position const* who) return SIDE_DEAD; return SIDE_NONE; } -inline static bool IsOnSameSide(Position const* who, Position const* other) +inline bool IsOnSameSide(Position const* who, Position const* other) { return (GetSide(who) == GetSide(other)); } -static Player* FindEligibleTarget(Creature const* me, bool isGateOpen) +inline Player* FindEligibleTarget(Creature const* me, bool isGateOpen) { Map::PlayerList const& players = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator it = players.begin(); it != players.end(); ++it) @@ -558,7 +561,7 @@ class boss_gothik : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -665,7 +668,7 @@ class npc_gothik_minion_livingtrainee : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -694,7 +697,7 @@ class npc_gothik_minion_livingknight : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -724,7 +727,7 @@ class npc_gothik_minion_livingrider : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -753,7 +756,7 @@ class npc_gothik_minion_spectraltrainee : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -782,7 +785,7 @@ class npc_gothik_minion_spectralknight : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -847,7 +850,7 @@ class npc_gothik_minion_spectralrider : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -876,7 +879,7 @@ class npc_gothik_minion_spectralhorse : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -885,11 +888,6 @@ class npc_gothik_trigger : public CreatureScript public: npc_gothik_trigger() : CreatureScript("npc_gothik_trigger") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_gothik_triggerAI : public ScriptedAI { npc_gothik_triggerAI(Creature* creature) : ScriptedAI(creature) { creature->SetDisableGravity(true); } @@ -963,6 +961,11 @@ public: gothik->AI()->SummonedCreatureDespawn(summon); } }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetNaxxramasAI(creature); + } }; class spell_gothik_shadow_bolt_volley : public SpellScriptLoader diff --git a/src/server/scripts/Northrend/Naxxramas/boss_grobbulus.cpp b/src/server/scripts/Northrend/Naxxramas/boss_grobbulus.cpp index 87c6051a661..bf658f143bd 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_grobbulus.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_grobbulus.cpp @@ -16,10 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" #include "naxxramas.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Spells { @@ -107,7 +107,7 @@ class boss_grobbulus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_grobbulusAI(creature); + return GetNaxxramasAI(creature); } }; @@ -135,7 +135,7 @@ class npc_grobbulus_poison_cloud : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_grobbulus_poison_cloudAI(creature); + return GetNaxxramasAI(creature); } }; @@ -151,10 +151,7 @@ class spell_grobbulus_mutating_injection : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MUTATING_EXPLOSION) - || !sSpellMgr->GetSpellInfo(SPELL_POISON_CLOUD)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MUTATING_EXPLOSION, SPELL_POISON_CLOUD }); } void HandleRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -166,7 +163,7 @@ class spell_grobbulus_mutating_injection : public SpellScriptLoader if (Unit* caster = GetCaster()) { caster->CastSpell(GetTarget(), SPELL_MUTATING_EXPLOSION, true); - GetTarget()->CastSpell(GetTarget(), SPELL_POISON_CLOUD, true, NULL, aurEff, GetCasterGUID()); + GetTarget()->CastSpell(GetTarget(), SPELL_POISON_CLOUD, true, nullptr, aurEff, GetCasterGUID()); } } @@ -194,9 +191,7 @@ class spell_grobbulus_poison_cloud : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].TriggerSpell)) - return false; - return true; + return ValidateSpellInfo({ spellInfo->Effects[EFFECT_0].TriggerSpell }); } void PeriodicTick(AuraEffect const* aurEff) @@ -205,7 +200,7 @@ class spell_grobbulus_poison_cloud : public SpellScriptLoader uint32 triggerSpell = GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell; int32 mod = int32(((float(aurEff->GetTickNumber()) / aurEff->GetTotalTicks()) * 0.9f + 0.1f) * 10000 * 2 / 3); - GetTarget()->CastCustomSpell(triggerSpell, SPELLVALUE_RADIUS_MOD, mod, (Unit*)NULL, TRIGGERED_FULL_MASK, NULL, aurEff); + GetTarget()->CastCustomSpell(triggerSpell, SPELLVALUE_RADIUS_MOD, mod, (Unit*)nullptr, TRIGGERED_FULL_MASK, nullptr, aurEff); } void Register() override diff --git a/src/server/scripts/Northrend/Naxxramas/boss_heigan.cpp b/src/server/scripts/Northrend/Naxxramas/boss_heigan.cpp index 9da47b40cbd..0b136408fc3 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_heigan.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_heigan.cpp @@ -16,10 +16,15 @@ */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "IteratorPair.h" +#include "Map.h" +#include "naxxramas.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "naxxramas.h" -#include "Player.h" enum Spells { @@ -61,25 +66,23 @@ 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 +uint32 const firstEruptionDBGUID = 84980; + +// count of sequential GO DBGUIDs in the respective section of the room +uint8 const numEruptions[] = +{ 15, 25, 23, 13 }; +uint8 const numSections = std::extent::value; class boss_heigan : public CreatureScript { public: boss_heigan() : CreatureScript("boss_heigan") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_heiganAI : public BossAI { boss_heiganAI(Creature* creature) : BossAI(creature, BOSS_HEIGAN), _safeSection(0), _danceDirection(false), _safetyDance(false) { } @@ -131,9 +134,9 @@ public: _eruptTiles[section].clear(); for (uint8 i = 0; i < numEruptions[section]; ++i) { - std::pair::const_iterator, std::unordered_multimap::const_iterator> tileIt = mapGOs.equal_range(spawnId++); - for (std::unordered_multimap::const_iterator it = tileIt.first; it != tileIt.second; ++it) - _eruptTiles[section].push_back(it->second->GetGUID()); + auto tileBounds = Trinity::Containers::MapEqualRange(mapGOs, spawnId++); + for (auto const& spawnPair : tileBounds) + _eruptTiles[section].push_back(spawnPair.second->GetGUID()); } } } @@ -216,6 +219,10 @@ public: bool _safetyDance; // is achievement still possible? (= no player deaths yet) }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetNaxxramasAI(creature); + } }; class spell_heigan_eruption : public SpellScriptLoader diff --git a/src/server/scripts/Northrend/Naxxramas/boss_kelthuzad.cpp b/src/server/scripts/Northrend/Naxxramas/boss_kelthuzad.cpp index 3b2b3a6f505..245a1fbdf31 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_kelthuzad.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_kelthuzad.cpp @@ -16,11 +16,17 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "naxxramas.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "PlayerAI.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum Texts { @@ -161,7 +167,7 @@ class KelThuzadCharmedPlayerAI : public SimpleCharmedPlayerAI public: KelThuzadCharmedPlayerAI(Player* player) : SimpleCharmedPlayerAI(player) { } - struct CharmedPlayerTargetSelectPred : public std::unary_function + struct CharmedPlayerTargetSelectPred { bool operator()(Unit const* target) const { @@ -190,7 +196,7 @@ class KelThuzadCharmedPlayerAI : public SimpleCharmedPlayerAI } }; -struct ManaUserTargetSelector : public std::unary_function +struct ManaUserTargetSelector { bool operator()(Unit const* target) const { @@ -568,11 +574,11 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; -static const float MINION_AGGRO_DISTANCE = 20.0f; +float const MINION_AGGRO_DISTANCE = 20.0f; // @hack the entire _movementTimer logic only exists because RandomMovementGenerator gets really confused due to the unique map geography of KT's room (it's placed on top of a copy of Winterspring). // As of the time of writing, RMG sometimes selects positions on the "floor" below the room, causing Abominations to path wildly through the room. // This custom movement code prevents this by simply ignoring z coord calculation (the floor of the minion coves is flat anyway). @@ -699,7 +705,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -725,7 +731,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -768,7 +774,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -862,7 +868,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; @@ -915,9 +921,7 @@ public: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MANA_DETONATION_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MANA_DETONATION_DAMAGE }); } void HandleScript(AuraEffect const* aurEff) @@ -928,7 +932,7 @@ public: if (int32 mana = int32(target->GetMaxPower(POWER_MANA) / 10)) { mana = target->ModifyPower(POWER_MANA, -mana); - target->CastCustomSpell(SPELL_MANA_DETONATION_DAMAGE, SPELLVALUE_BASE_POINT0, -mana * 10, target, true, NULL, aurEff); + target->CastCustomSpell(SPELL_MANA_DETONATION_DAMAGE, SPELLVALUE_BASE_POINT0, -mana * 10, target, true, nullptr, aurEff); } } @@ -963,7 +967,6 @@ public: return true; kelThuzad->AI()->DoAction(ACTION_BEGIN_ENCOUNTER); - return true; } }; diff --git a/src/server/scripts/Northrend/Naxxramas/boss_loatheb.cpp b/src/server/scripts/Northrend/Naxxramas/boss_loatheb.cpp index de9a47d8b58..8bcbc833a41 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_loatheb.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_loatheb.cpp @@ -16,10 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "InstanceScript.h" #include "naxxramas.h" +#include "ScriptedCreature.h" +#include "SpellAuras.h" +#include "SpellScript.h" enum Spells { @@ -172,9 +173,7 @@ class spell_loatheb_deathbloom : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DEATHBLOOM_FINAL_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DEATHBLOOM_FINAL_DAMAGE }); } void AfterRemove(AuraEffect const* eff, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Northrend/Naxxramas/boss_maexxna.cpp b/src/server/scripts/Northrend/Naxxramas/boss_maexxna.cpp index 42f04344e07..4d5b298b641 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_maexxna.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_maexxna.cpp @@ -16,10 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "PassiveAI.h" -#include "SpellScript.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "naxxramas.h" +#include "ObjectAccessor.h" +#include "PassiveAI.h" +#include "ScriptedCreature.h" +#include "SpellMgr.h" +#include "SpellScript.h" enum Spells { @@ -45,7 +49,7 @@ enum Creatures }; #define MAX_WRAP_POSITION 7 -const Position WrapPositions[MAX_WRAP_POSITION] = +Position const WrapPositions[MAX_WRAP_POSITION] = { {3453.818f, -3854.651f, 308.7581f, 4.362833f}, {3535.042f, -3842.383f, 300.795f, 3.179324f}, @@ -66,9 +70,9 @@ enum Events EVENT_SUMMON, }; -const float WEB_WRAP_MOVE_SPEED = 20.0f; +float const WEB_WRAP_MOVE_SPEED = 20.0f; -struct WebTargetSelector : public std::unary_function +struct WebTargetSelector { WebTargetSelector(Unit* maexxna) : _maexxna(maexxna) {} bool operator()(Unit const* target) const @@ -83,7 +87,7 @@ struct WebTargetSelector : public std::unary_function } private: - const Unit* _maexxna; + Unit const* _maexxna; }; class boss_maexxna : public CreatureScript @@ -91,11 +95,6 @@ class boss_maexxna : public CreatureScript public: boss_maexxna() : CreatureScript("boss_maexxna") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new boss_maexxnaAI(creature); - } - struct boss_maexxnaAI : public BossAI { boss_maexxnaAI(Creature* creature) : BossAI(creature, BOSS_MAEXXNA) { } @@ -185,6 +184,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetNaxxramasAI(creature); + } }; class npc_webwrap : public CreatureScript @@ -192,11 +195,6 @@ class npc_webwrap : public CreatureScript public: npc_webwrap() : CreatureScript("npc_webwrap") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new npc_webwrapAI(creature); - } - struct npc_webwrapAI : public NullCreatureAI { npc_webwrapAI(Creature* creature) : NullCreatureAI(creature), visibleTimer(0) { } @@ -217,7 +215,7 @@ public: if (Unit* victim = ObjectAccessor::GetUnit(*me, victimGUID)) { visibleTimer = (me->GetDistance2d(victim)/WEB_WRAP_MOVE_SPEED + 0.5f) * IN_MILLISECONDS; - victim->CastSpell(victim, SPELL_WEB_WRAP, true, NULL, NULL, me->GetGUID()); + victim->CastSpell(victim, SPELL_WEB_WRAP, true, nullptr, nullptr, me->GetGUID()); } } @@ -245,6 +243,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetNaxxramasAI(creature); + } }; void AddSC_boss_maexxna() diff --git a/src/server/scripts/Northrend/Naxxramas/boss_noth.cpp b/src/server/scripts/Northrend/Naxxramas/boss_noth.cpp index 2dd4cf54506..0a82cc95ced 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_noth.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_noth.cpp @@ -16,8 +16,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "MotionMaster.h" #include "naxxramas.h" +#include "ScriptedCreature.h" enum Phases { @@ -66,9 +67,9 @@ enum Adds N_CHAMPION_SPELLS = 6, N_GUARDIAN_SPELLS = 3 }; -const uint32 SummonWarriorSpells[N_WARRIOR_SPELLS] = { 29247, 29248, 29249 }; -const uint32 SummonChampionSpells[N_CHAMPION_SPELLS] = { 29238, 29255, 29257, 29258, 29262, 29267 }; -const uint32 SummonGuardianSpells[N_GUARDIAN_SPELLS] = { 29239, 29256, 29268 }; +uint32 const SummonWarriorSpells[N_WARRIOR_SPELLS] = { 29247, 29248, 29249 }; +uint32 const SummonChampionSpells[N_CHAMPION_SPELLS] = { 29238, 29255, 29257, 29258, 29262, 29267 }; +uint32 const SummonGuardianSpells[N_GUARDIAN_SPELLS] = { 29239, 29256, 29268 }; #define SPELL_BLINK RAND(29208, 29209, 29210, 29211) @@ -335,7 +336,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; diff --git a/src/server/scripts/Northrend/Naxxramas/boss_patchwerk.cpp b/src/server/scripts/Northrend/Naxxramas/boss_patchwerk.cpp index e26edfdce1f..0b7aace75b6 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_patchwerk.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_patchwerk.cpp @@ -16,8 +16,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "naxxramas.h" +#include "ScriptedCreature.h" enum Spells { @@ -59,11 +60,6 @@ class boss_patchwerk : public CreatureScript public: boss_patchwerk() : CreatureScript("boss_patchwerk") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_patchwerkAI : public BossAI { boss_patchwerkAI(Creature* creature) : BossAI(creature, BOSS_PATCHWERK) @@ -119,8 +115,8 @@ public: // Hateful Strike targets the highest non-MT threat in melee range on 10man // and the higher HP target out of the two highest non-MT threats in melee range on 25man float MostThreat = 0.0f; - Unit* secondThreatTarget = NULL; - Unit* thirdThreatTarget = NULL; + Unit* secondThreatTarget = nullptr; + Unit* thirdThreatTarget = nullptr; std::list::const_iterator i = me->getThreatManager().getThreatList().begin(); for (; i != me->getThreatManager().getThreatList().end(); ++i) @@ -148,7 +144,7 @@ public: } } - Unit* pHatefulTarget = NULL; + Unit* pHatefulTarget = nullptr; if (!thirdThreatTarget) pHatefulTarget = secondThreatTarget; else if (secondThreatTarget) @@ -193,6 +189,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetNaxxramasAI(creature); + } }; void AddSC_boss_patchwerk() diff --git a/src/server/scripts/Northrend/Naxxramas/boss_razuvious.cpp b/src/server/scripts/Northrend/Naxxramas/boss_razuvious.cpp index 067d548828a..4737b4a2676 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_razuvious.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_razuvious.cpp @@ -16,9 +16,12 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "naxxramas.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellInfo.h" -#include "naxxramas.h" enum Yells { @@ -58,11 +61,6 @@ class boss_razuvious : public CreatureScript public: boss_razuvious() : CreatureScript("boss_razuvious") { } - CreatureAI* GetAI(Creature* creature) const override - { - return new boss_razuviousAI(creature); - } - struct boss_razuviousAI : public BossAI { boss_razuviousAI(Creature* creature) : BossAI(creature, BOSS_RAZUVIOUS) { } @@ -168,6 +166,10 @@ public: } }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetNaxxramasAI(creature); + } }; class npc_dk_understudy : public CreatureScript @@ -240,7 +242,7 @@ class npc_dk_understudy : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNaxxramasAI(creature); } }; diff --git a/src/server/scripts/Northrend/Naxxramas/boss_sapphiron.cpp b/src/server/scripts/Northrend/Naxxramas/boss_sapphiron.cpp index 586eb7b2751..72027239e6c 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_sapphiron.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_sapphiron.cpp @@ -16,12 +16,17 @@ */ #include "ScriptMgr.h" +#include "GameObject.h" #include "GameObjectAI.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "Player.h" -#include "SpellInfo.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "naxxramas.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum Yells { @@ -413,7 +418,7 @@ class boss_sapphiron : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_sapphironAI(creature); + return GetNaxxramasAI(creature); } }; @@ -484,7 +489,7 @@ class go_sapphiron_birth : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return GetInstanceAI(go); + return GetNaxxramasAI(go); } }; @@ -559,7 +564,7 @@ class spell_sapphiron_icebolt : public SpellScriptLoader 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)) + if (GameObject* block = GetTarget()->SummonGameObject(GO_ICEBLOCK, x, y, z, 0.f, QuaternionData(), 25)) _block = block->GetGUID(); } @@ -590,7 +595,7 @@ class spell_sapphiron_summon_blizzard : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - return !!sSpellMgr->GetSpellInfo(SPELL_SUMMON_BLIZZARD); + return ValidateSpellInfo({ SPELL_SUMMON_BLIZZARD }); } void HandleDummy(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/Naxxramas/boss_thaddius.cpp b/src/server/scripts/Northrend/Naxxramas/boss_thaddius.cpp index dc50bf69b00..6a55b557b41 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_thaddius.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_thaddius.cpp @@ -16,12 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "Player.h" -#include "ObjectGuid.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" #include "naxxramas.h" - +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellScript.h" enum Phases { @@ -162,11 +165,6 @@ class boss_thaddius : public CreatureScript public: boss_thaddius() : CreatureScript("boss_thaddius") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct boss_thaddiusAI : public BossAI { public: @@ -486,6 +484,10 @@ public: bool shockingEligibility; }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetNaxxramasAI(creature); + } }; class npc_stalagg : public CreatureScript @@ -493,11 +495,6 @@ class npc_stalagg : public CreatureScript public: npc_stalagg() : CreatureScript("npc_stalagg") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_stalaggAI : public ScriptedAI { public: @@ -755,6 +752,10 @@ public: bool isFeignDeath; }; + CreatureAI* GetAI(Creature* creature) const override + { + return GetNaxxramasAI(creature); + } }; class npc_feugen : public CreatureScript @@ -762,11 +763,6 @@ class npc_feugen : public CreatureScript public: npc_feugen() : CreatureScript("npc_feugen") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_feugenAI : public ScriptedAI { public: @@ -1027,6 +1023,11 @@ public: bool refreshBeam; bool isFeignDeath; }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetNaxxramasAI(creature); + } }; class npc_tesla : public CreatureScript @@ -1034,11 +1035,6 @@ class npc_tesla : public CreatureScript public: npc_tesla() : CreatureScript("npc_tesla") { } - CreatureAI* GetAI(Creature* creature) const override - { - return GetInstanceAI(creature); - } - struct npc_teslaAI : public ScriptedAI { npc_teslaAI(Creature* creature) : ScriptedAI(creature) { } @@ -1048,6 +1044,11 @@ public: void JustEngagedWith(Unit* /*who*/) override { } void DamageTaken(Unit* /*who*/, uint32& damage) override { damage = 0; } // no, you can't kill it }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetNaxxramasAI(creature); + } }; class spell_thaddius_polarity_charge : public SpellScriptLoader @@ -1061,15 +1062,16 @@ class spell_thaddius_polarity_charge : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - return ( - sSpellMgr->GetSpellInfo(SPELL_POLARITY_SHIFT) && - sSpellMgr->GetSpellInfo(SPELL_POSITIVE_CHARGE_APPLY) && - sSpellMgr->GetSpellInfo(SPELL_POSITIVE_CHARGE_TICK) && - sSpellMgr->GetSpellInfo(SPELL_POSITIVE_CHARGE_AMP) && - sSpellMgr->GetSpellInfo(SPELL_NEGATIVE_CHARGE_APPLY) && - sSpellMgr->GetSpellInfo(SPELL_NEGATIVE_CHARGE_TICK) && - sSpellMgr->GetSpellInfo(SPELL_NEGATIVE_CHARGE_AMP) - ); + return ValidateSpellInfo( + { + SPELL_POLARITY_SHIFT, + SPELL_POSITIVE_CHARGE_APPLY, + SPELL_POSITIVE_CHARGE_TICK, + SPELL_POSITIVE_CHARGE_AMP, + SPELL_NEGATIVE_CHARGE_APPLY, + SPELL_NEGATIVE_CHARGE_TICK, + SPELL_NEGATIVE_CHARGE_AMP + }); } void HandleTargets(std::list& targetList) @@ -1160,15 +1162,16 @@ class spell_thaddius_polarity_shift : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - return ( - sSpellMgr->GetSpellInfo(SPELL_POLARITY_SHIFT) && - sSpellMgr->GetSpellInfo(SPELL_POSITIVE_CHARGE_APPLY) && - sSpellMgr->GetSpellInfo(SPELL_POSITIVE_CHARGE_TICK) && - sSpellMgr->GetSpellInfo(SPELL_POSITIVE_CHARGE_AMP) && - sSpellMgr->GetSpellInfo(SPELL_NEGATIVE_CHARGE_APPLY) && - sSpellMgr->GetSpellInfo(SPELL_NEGATIVE_CHARGE_TICK) && - sSpellMgr->GetSpellInfo(SPELL_NEGATIVE_CHARGE_AMP) - ); + return ValidateSpellInfo( + { + SPELL_POLARITY_SHIFT, + SPELL_POSITIVE_CHARGE_APPLY, + SPELL_POSITIVE_CHARGE_TICK, + SPELL_POSITIVE_CHARGE_AMP, + SPELL_NEGATIVE_CHARGE_APPLY, + SPELL_NEGATIVE_CHARGE_TICK, + SPELL_NEGATIVE_CHARGE_AMP + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1212,7 +1215,7 @@ class spell_thaddius_magnetic_pull : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - return sSpellMgr->GetSpellInfo(SPELL_MAGNETIC_PULL) ? true : false; + return ValidateSpellInfo({ SPELL_MAGNETIC_PULL }); } void HandleCast() // only feugen ever casts this according to wowhead data diff --git a/src/server/scripts/Northrend/Naxxramas/instance_naxxramas.cpp b/src/server/scripts/Northrend/Naxxramas/instance_naxxramas.cpp index 2d46e7403ab..4e91a9108aa 100644 --- a/src/server/scripts/Northrend/Naxxramas/instance_naxxramas.cpp +++ b/src/server/scripts/Northrend/Naxxramas/instance_naxxramas.cpp @@ -16,9 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "AreaBoundary.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" #include "naxxramas.h" +#include "TemporarySummon.h" BossBoundaryData const boundaries = { @@ -528,7 +534,7 @@ class instance_naxxramas : public InstanceMapScript return true; } - bool CheckAchievementCriteriaMeet(uint32 criteria_id, Player const* /*source*/, Unit const* /*target = NULL*/, uint32 /*miscvalue1 = 0*/) override + bool CheckAchievementCriteriaMeet(uint32 criteria_id, Player const* /*source*/, Unit const* /*target = nullptr*/, uint32 /*miscvalue1 = 0*/) override { switch (criteria_id) { diff --git a/src/server/scripts/Northrend/Nexus/EyeOfEternity/boss_malygos.cpp b/src/server/scripts/Northrend/Nexus/EyeOfEternity/boss_malygos.cpp index fc56b5b90ff..1e3af5a2bed 100644 --- a/src/server/scripts/Northrend/Nexus/EyeOfEternity/boss_malygos.cpp +++ b/src/server/scripts/Northrend/Nexus/EyeOfEternity/boss_malygos.cpp @@ -20,16 +20,22 @@ SDName: Boss Malygos Script Data End */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "eye_of_eternity.h" -#include "Player.h" -#include "Vehicle.h" #include "CombatAI.h" -#include "GameObjectAI.h" #include "CreatureTextMgr.h" -#include "MoveSplineInit.h" +#include "eye_of_eternity.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "GridNotifiers.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "Vehicle.h" enum Events { @@ -998,7 +1004,7 @@ public: _JustDied(); Talk(SAY_DEATH); if (Creature* alexstraszaGiftBoxBunny = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_GIFT_BOX_BUNNY_GUID))) - alexstraszaGiftBoxBunny->SummonGameObject(RAID_MODE(GO_HEART_OF_MAGIC_10, GO_HEART_OF_MAGIC_25), HeartOfMagicSpawnPos, G3D::Quat(), 0); + alexstraszaGiftBoxBunny->SummonGameObject(RAID_MODE(GO_HEART_OF_MAGIC_10, GO_HEART_OF_MAGIC_25), HeartOfMagicSpawnPos, QuaternionData(), 0); me->SummonCreature(NPC_ALEXSTRASZA, AlexstraszaSpawnPos, TEMPSUMMON_MANUAL_DESPAWN); me->DespawnOrUnsummon(5*IN_MILLISECONDS); @@ -1027,7 +1033,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetEyeOfEternityAI(creature); } }; @@ -1077,7 +1083,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetEyeOfEternityAI(creature); } }; @@ -1138,7 +1144,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetEyeOfEternityAI(creature); } }; @@ -1249,7 +1255,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetEyeOfEternityAI(creature); } }; @@ -1312,7 +1318,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetEyeOfEternityAI(creature); } }; @@ -1388,7 +1394,7 @@ class npc_nexus_lord : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetEyeOfEternityAI(creature); } }; @@ -1455,7 +1461,7 @@ class npc_scion_of_eternity : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetEyeOfEternityAI(creature); } }; @@ -1509,7 +1515,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetEyeOfEternityAI(creature); } }; @@ -1574,7 +1580,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_wyrmrest_skytalonAI(creature); + return GetEyeOfEternityAI(creature); } }; @@ -1600,7 +1606,7 @@ class npc_static_field : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_static_fieldAI(creature); + return GetEyeOfEternityAI(creature); } }; @@ -1620,10 +1626,7 @@ class spell_malygos_portal_beam : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PORTAL_OPENED)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_PORTAL_OPENED }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1723,10 +1726,7 @@ class spell_malygos_arcane_storm : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ARCANE_STORM_EXTRA_VISUAL)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_ARCANE_STORM_EXTRA_VISUAL }); } void FilterTargets(std::list& targets) @@ -1820,10 +1820,7 @@ class spell_malygos_vortex_visual : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_VORTEX_1) || !sSpellMgr->GetSpellInfo(SPELL_VORTEX_6)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_VORTEX_1, SPELL_VORTEX_6 }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1842,7 +1839,7 @@ class spell_malygos_vortex_visual : public SpellScriptLoader if (InstanceScript* instance = caster->GetInstanceScript()) { // Teleport spell - I'm not sure but might be it must be cast by each vehicle when it's passenger leaves it. - if (Creature* trigger = caster->GetMap()->GetCreature(instance->GetGuidData(DATA_TRIGGER))) + if (Creature* trigger = ObjectAccessor::GetCreature(*caster, instance->GetGuidData(DATA_TRIGGER))) trigger->CastSpell(targetPlayer, SPELL_VORTEX_6, true); } } @@ -1978,7 +1975,7 @@ class spell_scion_of_eternity_arcane_barrage : public SpellScriptLoader bool Load() override { - return GetCaster()->GetTypeId() == TYPEID_UNIT && GetCaster()->GetInstanceScript() != NULL; + return GetCaster()->GetTypeId() == TYPEID_UNIT && GetCaster()->GetInstanceScript() != nullptr; } void FilterMeleeHoverDiskPassangers(std::list& targets) @@ -2063,10 +2060,7 @@ class spell_malygos_destroy_platform_channel : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DESTROY_PLATFORM_BOOM_VISUAL)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_DESTROY_PLATFORM_BOOM_VISUAL }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2105,10 +2099,7 @@ class spell_alexstrasza_bunny_destroy_platform_boom_visual : public SpellScriptL bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DESTROY_PLATFORM_EVENT)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_DESTROY_PLATFORM_EVENT }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2153,7 +2144,7 @@ class spell_alexstrasza_bunny_destroy_platform_event : public SpellScriptLoader void HandleScript(SpellEffIndex /*effIndex*/) { - GetCaster()->CastSpell((Unit*)NULL, SPELL_SUMMON_RED_DRAGON_BUDDY_F_CAST); + GetCaster()->CastSpell((Unit*)nullptr, SPELL_SUMMON_RED_DRAGON_BUDDY_F_CAST); } void Register() override @@ -2251,10 +2242,7 @@ class spell_malygos_surge_of_power_warning_selector_25 : public SpellScriptLoade bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SURGE_OF_POWER_PHASE_3_25)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_SURGE_OF_POWER_PHASE_3_25 }); } void SendThreeTargets(std::list& targets) @@ -2285,7 +2273,7 @@ class spell_malygos_surge_of_power_warning_selector_25 : public SpellScriptLoade void ExecuteMainSpell() { - GetCaster()->ToCreature()->CastSpell((Unit*)NULL, SPELL_SURGE_OF_POWER_PHASE_3_25); + GetCaster()->ToCreature()->CastSpell((Unit*)nullptr, SPELL_SURGE_OF_POWER_PHASE_3_25); } void Register() override @@ -2368,10 +2356,7 @@ class spell_alexstrasza_gift_beam : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ALEXSTRASZAS_GIFT_BEAM_VISUAL)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_ALEXSTRASZAS_GIFT_BEAM_VISUAL }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2425,9 +2410,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, G3D::Quat(), 0); + _alexstraszaGift = target->SummonGameObject(GO_ALEXSTRASZA_S_GIFT_10, *target, QuaternionData(), 0); else if (target->GetMap()->GetDifficulty() == RAID_DIFFICULTY_25MAN_NORMAL) - _alexstraszaGift = target->SummonGameObject(GO_ALEXSTRASZA_S_GIFT_25, *target, G3D::Quat(), 0); + _alexstraszaGift = target->SummonGameObject(GO_ALEXSTRASZA_S_GIFT_25, *target, QuaternionData(), 0); } } diff --git a/src/server/scripts/Northrend/Nexus/EyeOfEternity/eye_of_eternity.h b/src/server/scripts/Northrend/Nexus/EyeOfEternity/eye_of_eternity.h index c0c86663441..25d304388a8 100644 --- a/src/server/scripts/Northrend/Nexus/EyeOfEternity/eye_of_eternity.h +++ b/src/server/scripts/Northrend/Nexus/EyeOfEternity/eye_of_eternity.h @@ -18,9 +18,12 @@ #ifndef DEF_EYE_OF_ETERNITY_H #define DEF_EYE_OF_ETERNITY_H +#include "CreatureAIImpl.h" + +#define EoEScriptName "instance_eye_of_eternity" #define DataHeader "EOE" -enum InstanceData +enum EOEInstanceData { DATA_MALYGOS_EVENT, MAX_ENCOUNTER, @@ -30,7 +33,7 @@ enum InstanceData DATA_RESPAWN_IRIS }; -enum InstanceData64 +enum EOEInstanceData64 { DATA_TRIGGER, DATA_MALYGOS, @@ -41,7 +44,7 @@ enum InstanceData64 DATA_GIFT_BOX_BUNNY_GUID }; -enum InstanceNpcs +enum EOEInstanceNpcs { NPC_MALYGOS = 28859, NPC_VORTEX_TRIGGER = 30090, @@ -57,7 +60,7 @@ enum InstanceNpcs NPC_SURGE_OF_POWER = 30334 }; -enum InstanceGameObjects +enum EOEInstanceGameObjects { GO_NEXUS_RAID_PLATFORM = 193070, GO_EXIT_PORTAL = 193908, @@ -69,12 +72,12 @@ enum InstanceGameObjects GO_HEART_OF_MAGIC_25 = 194159 }; -enum InstanceEvents +enum EOEInstanceEvents { EVENT_FOCUSING_IRIS = 20711 }; -enum InstanceSpells +enum EOEInstanceSpells { SPELL_VORTEX_4 = 55853, // damage | used to enter to the vehicle SPELL_VORTEX_5 = 56263, // damage | used to enter to the vehicle @@ -84,4 +87,10 @@ enum InstanceSpells SPELL_SUMMOM_RED_DRAGON_BUDDY = 56070 }; +template +inline AI* GetEyeOfEternityAI(T* obj) +{ + return GetInstanceAI(obj, EoEScriptName); +} + #endif 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 96e76dc4867..d12092d254e 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 @@ -16,9 +16,13 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "InstanceScript.h" +#include "AreaBoundary.h" +#include "Creature.h" +#include "CreatureAI.h" #include "eye_of_eternity.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" #include "Player.h" BossBoundaryData const boundaries = @@ -29,7 +33,7 @@ BossBoundaryData const boundaries = class instance_eye_of_eternity : public InstanceMapScript { public: - instance_eye_of_eternity() : InstanceMapScript("instance_eye_of_eternity", 616) { } + instance_eye_of_eternity() : InstanceMapScript(EoEScriptName, 616) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { @@ -86,11 +90,12 @@ public: void SpawnGameObject(uint32 entry, Position const& pos) { GameObject* go = new GameObject(); - if (!go->Create(instance->GenerateLowGuid(), entry, instance, PHASEMASK_NORMAL, pos, G3D::Quat(), 255, GO_STATE_READY)) + if (!go->Create(instance->GenerateLowGuid(), entry, instance, PHASEMASK_NORMAL, pos, QuaternionData(), 255, GO_STATE_READY)) { delete go; return; } + instance->AddToMap(go); } diff --git a/src/server/scripts/Northrend/Nexus/Nexus/boss_anomalus.cpp b/src/server/scripts/Northrend/Nexus/Nexus/boss_anomalus.cpp index 394f46b160c..2f8639df2ad 100644 --- a/src/server/scripts/Northrend/Nexus/Nexus/boss_anomalus.cpp +++ b/src/server/scripts/Northrend/Nexus/Nexus/boss_anomalus.cpp @@ -17,8 +17,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "nexus.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Spells { @@ -189,7 +192,7 @@ class boss_anomalus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNexusAI(creature); } }; @@ -263,7 +266,7 @@ class npc_chaotic_rift : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNexusAI(creature); } }; diff --git a/src/server/scripts/Northrend/Nexus/Nexus/boss_keristrasza.cpp b/src/server/scripts/Northrend/Nexus/Nexus/boss_keristrasza.cpp index 476a98806ca..993fdf7116f 100644 --- a/src/server/scripts/Northrend/Nexus/Nexus/boss_keristrasza.cpp +++ b/src/server/scripts/Northrend/Nexus/Nexus/boss_keristrasza.cpp @@ -16,12 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "Player.h" -#include "nexus.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "InstanceScript.h" +#include "nexus.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Spells { @@ -114,9 +117,9 @@ class boss_keristrasza : public CreatureScript bool CheckContainmentSpheres(bool remove_prison = false) { - ContainmentSphereGUIDs[0] = instance->GetGuidData(ANOMALUS_CONTAINMET_SPHERE); - ContainmentSphereGUIDs[1] = instance->GetGuidData(ORMOROKS_CONTAINMET_SPHERE); - ContainmentSphereGUIDs[2] = instance->GetGuidData(TELESTRAS_CONTAINMET_SPHERE); + ContainmentSphereGUIDs[0] = instance->GetGuidData(ANOMALUS_CONTAINMENT_SPHERE); + ContainmentSphereGUIDs[1] = instance->GetGuidData(ORMOROKS_CONTAINMENT_SPHERE); + ContainmentSphereGUIDs[2] = instance->GetGuidData(TELESTRAS_CONTAINMENT_SPHERE); for (uint8 i = 0; i < DATA_CONTAINMENT_SPHERES; ++i) { @@ -216,7 +219,7 @@ class boss_keristrasza : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNexusAI(creature); } }; @@ -227,20 +230,20 @@ public: struct containment_sphereAI : public GameObjectAI { - containment_sphereAI(GameObject* go) : GameObjectAI(go) { } + containment_sphereAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* /*player*/) override { - InstanceScript* instance = me->GetInstanceScript(); - - Creature* pKeristrasza = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_KERISTRASZA)); - if (pKeristrasza && pKeristrasza->IsAlive()) + Creature* keristrasza = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_KERISTRASZA)); + if (keristrasza && keristrasza->IsAlive()) { // maybe these are hacks :( me->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); me->SetGoState(GO_STATE_ACTIVE); - ENSURE_AI(boss_keristrasza::boss_keristraszaAI, pKeristrasza->AI())->CheckContainmentSpheres(true); + ENSURE_AI(boss_keristrasza::boss_keristraszaAI, keristrasza->AI())->CheckContainmentSpheres(true); } return true; } @@ -248,7 +251,7 @@ public: GameObjectAI* GetAI(GameObject* go) const override { - return new containment_sphereAI(go); + return GetNexusAI(go); } }; diff --git a/src/server/scripts/Northrend/Nexus/Nexus/boss_magus_telestra.cpp b/src/server/scripts/Northrend/Nexus/Nexus/boss_magus_telestra.cpp index a0d3e876f23..166ddd983dd 100644 --- a/src/server/scripts/Northrend/Nexus/Nexus/boss_magus_telestra.cpp +++ b/src/server/scripts/Northrend/Nexus/Nexus/boss_magus_telestra.cpp @@ -16,11 +16,14 @@ * with this program. If not, see . */ +#include "ScriptMgr.h" #include "GameEventMgr.h" #include "GameTime.h" -#include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "nexus.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Spells { @@ -71,7 +74,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNexusAI(creature); } struct boss_magus_telestraAI : public ScriptedAI diff --git a/src/server/scripts/Northrend/Nexus/Nexus/boss_nexus_commanders.cpp b/src/server/scripts/Northrend/Nexus/Nexus/boss_nexus_commanders.cpp index 81a5bb1cb5c..e4adfdefb35 100644 --- a/src/server/scripts/Northrend/Nexus/Nexus/boss_nexus_commanders.cpp +++ b/src/server/scripts/Northrend/Nexus/Nexus/boss_nexus_commanders.cpp @@ -16,8 +16,8 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "nexus.h" +#include "ScriptedCreature.h" enum Spells { @@ -100,7 +100,7 @@ class boss_nexus_commanders : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNexusAI(creature); } }; diff --git a/src/server/scripts/Northrend/Nexus/Nexus/boss_ormorok.cpp b/src/server/scripts/Northrend/Nexus/Nexus/boss_ormorok.cpp index 3fba12c3f4b..1cce1b3cdae 100644 --- a/src/server/scripts/Northrend/Nexus/Nexus/boss_ormorok.cpp +++ b/src/server/scripts/Northrend/Nexus/Nexus/boss_ormorok.cpp @@ -17,8 +17,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" #include "nexus.h" +#include "ScriptedCreature.h" #include "SpellScript.h" enum Spells @@ -170,7 +171,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetNexusAI(creature); } }; @@ -258,7 +259,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_crystal_spike_triggerAI(creature); + return GetNexusAI(creature); } }; diff --git a/src/server/scripts/Northrend/Nexus/Nexus/instance_nexus.cpp b/src/server/scripts/Northrend/Nexus/Nexus/instance_nexus.cpp index 434aa33b83f..43a0130e342 100644 --- a/src/server/scripts/Northrend/Nexus/Nexus/instance_nexus.cpp +++ b/src/server/scripts/Northrend/Nexus/Nexus/instance_nexus.cpp @@ -17,9 +17,12 @@ */ #include "ScriptMgr.h" +#include "Creature.h" +#include "GameObject.h" #include "InstanceScript.h" -#include "Player.h" +#include "Map.h" #include "nexus.h" +#include "Player.h" class instance_nexus : public InstanceMapScript { @@ -91,17 +94,17 @@ class instance_nexus : public InstanceMapScript { switch (go->GetEntry()) { - case GO_ANOMALUS_CONTAINMET_SPHERE: + case GO_ANOMALUS_CONTAINMENT_SPHERE: AnomalusContainmentSphere = go->GetGUID(); if (GetBossState(DATA_ANOMALUS) == DONE) go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); break; - case GO_ORMOROKS_CONTAINMET_SPHERE: + case GO_ORMOROKS_CONTAINMENT_SPHERE: OrmoroksContainmentSphere = go->GetGUID(); if (GetBossState(DATA_ORMOROK) == DONE) go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); break; - case GO_TELESTRAS_CONTAINMET_SPHERE: + case GO_TELESTRAS_CONTAINMENT_SPHERE: TelestrasContainmentSphere = go->GetGUID(); if (GetBossState(DATA_MAGUS_TELESTRA) == DONE) go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); @@ -154,11 +157,11 @@ class instance_nexus : public InstanceMapScript return AnomalusGUID; case DATA_KERISTRASZA: return KeristraszaGUID; - case ANOMALUS_CONTAINMET_SPHERE: + case ANOMALUS_CONTAINMENT_SPHERE: return AnomalusContainmentSphere; - case ORMOROKS_CONTAINMET_SPHERE: + case ORMOROKS_CONTAINMENT_SPHERE: return OrmoroksContainmentSphere; - case TELESTRAS_CONTAINMET_SPHERE: + case TELESTRAS_CONTAINMENT_SPHERE: return TelestrasContainmentSphere; default: break; diff --git a/src/server/scripts/Northrend/Nexus/Nexus/nexus.h b/src/server/scripts/Northrend/Nexus/Nexus/nexus.h index acaaeae95f1..3be0ca89181 100644 --- a/src/server/scripts/Northrend/Nexus/Nexus/nexus.h +++ b/src/server/scripts/Northrend/Nexus/Nexus/nexus.h @@ -18,6 +18,8 @@ #ifndef DEF_NEXUS_H #define DEF_NEXUS_H +#include "CreatureAIImpl.h" + #define NexusScriptName "instance_nexus" #define DataHeader "NEX" @@ -31,9 +33,9 @@ enum NEXDataTypes DATA_ORMOROK = 3, DATA_KERISTRASZA = 4, - ANOMALUS_CONTAINMET_SPHERE = 5, - ORMOROKS_CONTAINMET_SPHERE = 6, - TELESTRAS_CONTAINMET_SPHERE = 7 + ANOMALUS_CONTAINMENT_SPHERE = 5, + ORMOROKS_CONTAINMENT_SPHERE = 6, + TELESTRAS_CONTAINMENT_SPHERE = 7 }; enum NEXCreatureIds @@ -58,9 +60,15 @@ enum NEXCreatureIds enum NEXGameObjectIds { - GO_ANOMALUS_CONTAINMET_SPHERE = 188527, - GO_ORMOROKS_CONTAINMET_SPHERE = 188528, - GO_TELESTRAS_CONTAINMET_SPHERE = 188526 + GO_ANOMALUS_CONTAINMENT_SPHERE = 188527, + GO_ORMOROKS_CONTAINMENT_SPHERE = 188528, + GO_TELESTRAS_CONTAINMENT_SPHERE = 188526 }; +template +inline AI* GetNexusAI(T* obj) +{ + return GetInstanceAI(obj, NexusScriptName); +} + #endif diff --git a/src/server/scripts/Northrend/Nexus/Oculus/boss_drakos.cpp b/src/server/scripts/Northrend/Nexus/Oculus/boss_drakos.cpp index 5cdd04f4967..9aafde5f576 100644 --- a/src/server/scripts/Northrend/Nexus/Oculus/boss_drakos.cpp +++ b/src/server/scripts/Northrend/Nexus/Oculus/boss_drakos.cpp @@ -16,8 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "oculus.h" +#include "ScriptedCreature.h" enum Spells { @@ -201,7 +203,7 @@ class npc_unstable_sphere : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_unstable_sphereAI(creature); + return GetOculusAI(creature); } }; diff --git a/src/server/scripts/Northrend/Nexus/Oculus/boss_eregos.cpp b/src/server/scripts/Northrend/Nexus/Oculus/boss_eregos.cpp index b4d76e076c5..ddeb1a44936 100644 --- a/src/server/scripts/Northrend/Nexus/Oculus/boss_eregos.cpp +++ b/src/server/scripts/Northrend/Nexus/Oculus/boss_eregos.cpp @@ -16,10 +16,10 @@ */ #include "ScriptMgr.h" +#include "MotionMaster.h" +#include "oculus.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "oculus.h" // Types of drake mounts: Ruby (Tank), Amber (DPS), Emerald (Healer) // Two Repeating phases @@ -258,7 +258,7 @@ class boss_eregos : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_eregosAI(creature); + return GetOculusAI(creature); } }; diff --git a/src/server/scripts/Northrend/Nexus/Oculus/boss_urom.cpp b/src/server/scripts/Northrend/Nexus/Oculus/boss_urom.cpp index ca994d71e51..a89b0208ab6 100644 --- a/src/server/scripts/Northrend/Nexus/Oculus/boss_urom.cpp +++ b/src/server/scripts/Northrend/Nexus/Oculus/boss_urom.cpp @@ -23,8 +23,9 @@ SDCategory: Instance Script EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "MotionMaster.h" #include "oculus.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" enum Spells diff --git a/src/server/scripts/Northrend/Nexus/Oculus/boss_varos.cpp b/src/server/scripts/Northrend/Nexus/Oculus/boss_varos.cpp index 292ddd80042..e570464ec69 100644 --- a/src/server/scripts/Northrend/Nexus/Oculus/boss_varos.cpp +++ b/src/server/scripts/Northrend/Nexus/Oculus/boss_varos.cpp @@ -16,10 +16,13 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "oculus.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellScript.h" enum Says { @@ -233,7 +236,7 @@ class npc_azure_ring_captain : public CreatureScript { switch (action) { - case ACTION_CALL_DRAGON_EVENT: + case ACTION_CALL_DRAGON_EVENT: if (Creature* varos = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_VAROS))) { if (Unit* victim = varos->AI()->SelectTarget(SELECT_TARGET_RANDOM, 0)) @@ -255,7 +258,7 @@ class npc_azure_ring_captain : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetOculusAI(creature); } }; @@ -271,7 +274,7 @@ class spell_varos_centrifuge_shield : public SpellScriptLoader bool Load() override { Unit* caster = GetCaster(); - return (caster && caster->ToCreature()); + return caster && caster->GetTypeId() == TYPEID_UNIT; } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Northrend/Nexus/Oculus/instance_oculus.cpp b/src/server/scripts/Northrend/Nexus/Oculus/instance_oculus.cpp index 366f1fddb63..f5db5ea7e25 100644 --- a/src/server/scripts/Northrend/Nexus/Oculus/instance_oculus.cpp +++ b/src/server/scripts/Northrend/Nexus/Oculus/instance_oculus.cpp @@ -16,10 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "GameObject.h" #include "InstanceScript.h" -#include "WorldPacket.h" +#include "Map.h" +#include "MotionMaster.h" #include "oculus.h" +#include "TemporarySummon.h" +#include "WorldPacket.h" DoorData const doorData[] = { @@ -57,7 +62,7 @@ class instance_oculus : public InstanceMapScript case NPC_VAROS: VarosGUID = creature->GetGUID(); if (GetBossState(DATA_DRAKOS) == DONE) - creature->SetPhaseMask(1, true); + creature->SetPhaseMask(1, true); break; case NPC_UROM: UromGUID = creature->GetGUID(); @@ -111,11 +116,10 @@ class instance_oculus : public InstanceMapScript void OnGameObjectCreate(GameObject* go) override { + InstanceScript::OnGameObjectCreate(go); + switch (go->GetEntry()) { - case GO_DRAGON_CAGE_DOOR: - AddDoor(go, true); - break; case GO_EREGOS_CACHE_N: case GO_EREGOS_CACHE_H: EregosCacheGUID = go->GetGUID(); @@ -125,18 +129,6 @@ class instance_oculus : public InstanceMapScript } } - void OnGameObjectRemove(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_DRAGON_CAGE_DOOR: - AddDoor(go, false); - break; - default: - break; - } - } - void OnUnitDeath(Unit* unit) override { Creature* creature = unit->ToCreature(); diff --git a/src/server/scripts/Northrend/Nexus/Oculus/oculus.cpp b/src/server/scripts/Northrend/Nexus/Oculus/oculus.cpp index 9f9fd33fe97..befd9bcefdf 100644 --- a/src/server/scripts/Northrend/Nexus/Oculus/oculus.cpp +++ b/src/server/scripts/Northrend/Nexus/Oculus/oculus.cpp @@ -16,15 +16,18 @@ */ #include "ScriptMgr.h" +#include "CombatAI.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "oculus.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "SpellScript.h" +#include "Spell.h" #include "SpellAuraEffects.h" -#include "SpellInfo.h" -#include "CombatAI.h" -#include "Player.h" +#include "SpellScript.h" #include "Vehicle.h" -#include "oculus.h" enum GossipNPCs { @@ -156,6 +159,7 @@ class npc_verdisa_beglaristrasz_eternos : public CreatureScript StoreEssence(player, ITEM_EMERALD_ESSENCE); break; } + return false; case GOSSIP_MENU_ETERNOS: if (gossipListId >= 1 && gossipListId <= 3) { @@ -167,6 +171,7 @@ class npc_verdisa_beglaristrasz_eternos : public CreatureScript StoreEssence(player, ITEM_AMBER_ESSENCE); break; } + return false; case GOSSIP_MENU_BELGARISTRASZ: if (gossipListId <= 2) { @@ -178,8 +183,9 @@ class npc_verdisa_beglaristrasz_eternos : public CreatureScript StoreEssence(player, ITEM_RUBY_ESSENCE); break; } + return false; default: - break; + return false; } player->PlayerTalkClass->SendCloseGossip(); return false; @@ -260,7 +266,7 @@ class npc_ruby_emerald_amber_drake : public CreatureScript Initialize(); } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (Unit* creator = ObjectAccessor::GetUnit(*me, me->GetCreatorGUID())) if (spell->Id == SPELL_GPS) @@ -475,9 +481,7 @@ class spell_oculus_evasive_maneuvers : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RUBY_EVASIVE_CHARGES)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RUBY_EVASIVE_CHARGES }); } void HandleProc(AuraEffect const* /*aurEff*/, ProcEventInfo& /*eventInfo*/) @@ -512,27 +516,27 @@ class spell_oculus_shock_lance : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_AMBER_SHOCK_CHARGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_AMBER_SHOCK_CHARGE }); } - void CalcDamage() + void CalcDamage(SpellEffIndex /*effIndex*/) { - int32 damage = GetHitDamage(); + int32 damage = GetEffectValue(); if (Unit* target = GetHitUnit()) + { if (AuraEffect const* shockCharges = target->GetAuraEffect(SPELL_AMBER_SHOCK_CHARGE, EFFECT_0, GetCaster()->GetGUID())) { damage += shockCharges->GetAmount(); - shockCharges->GetBase()->Remove(); + shockCharges->GetBase()->Remove(AURA_REMOVE_BY_ENEMY_SPELL); } + } - SetHitDamage(damage); + SetEffectValue(damage); } void Register() override { - OnHit += SpellHitFn(spell_oculus_shock_lance_SpellScript::CalcDamage); + OnEffectLaunchTarget += SpellEffectFn(spell_oculus_shock_lance_SpellScript::CalcDamage, EFFECT_0, SPELL_EFFECT_SCHOOL_DAMAGE); } }; @@ -554,9 +558,7 @@ class spell_oculus_stop_time : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_AMBER_SHOCK_CHARGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_AMBER_SHOCK_CHARGE }); } void Apply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -594,9 +596,7 @@ class spell_oculus_temporal_rift : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_AMBER_SHOCK_CHARGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_AMBER_SHOCK_CHARGE }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) diff --git a/src/server/scripts/Northrend/Nexus/Oculus/oculus.h b/src/server/scripts/Northrend/Nexus/Oculus/oculus.h index 1eab4132f22..277194a4db8 100644 --- a/src/server/scripts/Northrend/Nexus/Oculus/oculus.h +++ b/src/server/scripts/Northrend/Nexus/Oculus/oculus.h @@ -18,6 +18,8 @@ #ifndef OCULUS_H_ #define OCULUS_H_ +#include "CreatureAIImpl.h" + #define OculusScriptName "instance_oculus" #define DataHeader "OC" @@ -69,13 +71,13 @@ enum OCCreatureActions ACTION_CALL_DRAGON_EVENT = 1 }; -enum OCWorldStates +enum OCOculusWorldStates { WORLD_STATE_CENTRIFUGE_CONSTRUCT_SHOW = 3524, WORLD_STATE_CENTRIFUGE_CONSTRUCT_AMOUNT = 3486 }; -enum OCSpells +enum OCOculusSpells { SPELL_CENTRIFUGE_SHIELD = 50053, SPELL_DEATH_SPELL = 50415 @@ -105,10 +107,10 @@ enum OCMisc POINT_MOVE_OUT = 1 }; -template -AI* GetOculusAI(Creature* creature) +template +inline AI* GetOculusAI(T* obj) { - return GetInstanceAI(creature, OculusScriptName); + return GetInstanceAI(obj, OculusScriptName); } #endif // OCULUS_H_ diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_bjarngrim.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_bjarngrim.cpp index 025c16af442..68238e75de4 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_bjarngrim.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_bjarngrim.cpp @@ -24,8 +24,10 @@ SDCategory: Halls of Lightning EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "halls_of_lightning.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Yells { @@ -99,7 +101,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHallsOfLightningAI(creature); } struct boss_bjarngrimAI : public ScriptedAI @@ -392,7 +394,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHallsOfLightningAI(creature); } struct npc_stormforged_lieutenantAI : public ScriptedAI diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_ionar.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_ionar.cpp index 88ed842d2b0..0765f9b6827 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_ionar.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_ionar.cpp @@ -21,8 +21,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "halls_of_lightning.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" enum Spells @@ -69,7 +72,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHallsOfLightningAI(creature); } struct boss_ionarAI : public ScriptedAI @@ -144,7 +147,7 @@ public: Talk(SAY_SLAY); } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_DISPERSE) { @@ -376,7 +379,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHallsOfLightningAI(creature); } }; diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_loken.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_loken.cpp index 96fd48cc4c4..73508df9562 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_loken.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_loken.cpp @@ -24,9 +24,11 @@ SDCategory: Halls of Lightning EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" #include "halls_of_lightning.h" +#include "InstanceScript.h" +#include "ScriptedCreature.h" +#include "SpellMgr.h" +#include "SpellScript.h" enum Texts { @@ -205,7 +207,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHallsOfLightningAI(creature); } }; diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_volkhan.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_volkhan.cpp index 4d98f87c116..4aa3e7e453c 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_volkhan.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/boss_volkhan.cpp @@ -24,10 +24,12 @@ SDCategory: Halls of Lightning EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "halls_of_lightning.h" -#include "Player.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" +#include "SpellMgr.h" enum Texts { @@ -200,7 +202,7 @@ public: summoned->GetMotionMaster()->MoveFollow(target, 0.0f, 0.0f); // Why healing when just summoned? - summoned->CastSpell(summoned, SPELL_HEAT, false, NULL, NULL, me->GetGUID()); + summoned->CastSpell(summoned, SPELL_HEAT, false, nullptr, nullptr, me->GetGUID()); } } @@ -365,9 +367,8 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHallsOfLightningAI(creature); } - }; /*###### @@ -381,7 +382,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_molten_golemAI(creature); + return GetHallsOfLightningAI(creature); } struct npc_molten_golemAI : public ScriptedAI @@ -437,7 +438,7 @@ public: } } - void SpellHit(Unit* /*pCaster*/, const SpellInfo* pSpell) override + void SpellHit(Unit* /*pCaster*/, SpellInfo const* pSpell) override { // This is the dummy effect of the spells if (pSpell->Id == sSpellMgr->GetSpellIdForDifficulty(SPELL_SHATTER, me)) diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/halls_of_lightning.h b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/halls_of_lightning.h index 22df062831e..3f155d200de 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/halls_of_lightning.h +++ b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/halls_of_lightning.h @@ -18,6 +18,8 @@ #ifndef HALLS_OF_LIGHTNING_H_ #define HALLS_OF_LIGHTNING_H_ +#include "CreatureAIImpl.h" + #define HoLScriptName "instance_halls_of_lightning" #define DataHeader "HOL" @@ -49,10 +51,10 @@ enum HOLGameObjectIds GO_LOKEN_THRONE = 192654 }; -template -AI* GetHallsOfLightningAI(Creature* creature) +template +inline AI* GetHallsOfLightningAI(T* obj) { - return GetInstanceAI(creature, HoLScriptName); + return GetInstanceAI(obj, HoLScriptName); } #endif // HALLS_OF_LIGHTNING_H_ diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/instance_halls_of_lightning.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/instance_halls_of_lightning.cpp index 937f2372e1e..0e345ccb319 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfLightning/instance_halls_of_lightning.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfLightning/instance_halls_of_lightning.cpp @@ -16,15 +16,18 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" +#include "Creature.h" +#include "GameObject.h" #include "halls_of_lightning.h" +#include "InstanceScript.h" +#include "Map.h" DoorData const doorData[] = { { GO_VOLKHAN_DOOR, DATA_VOLKHAN, DOOR_TYPE_PASSAGE }, { GO_IONAR_DOOR, DATA_IONAR, DOOR_TYPE_PASSAGE }, { GO_LOKEN_DOOR, DATA_LOKEN, DOOR_TYPE_PASSAGE }, - { 0, 0, DOOR_TYPE_ROOM } // END + { 0, 0, DOOR_TYPE_ROOM } // END }; class instance_halls_of_lightning : public InstanceMapScript @@ -64,13 +67,10 @@ class instance_halls_of_lightning : public InstanceMapScript void OnGameObjectCreate(GameObject* go) override { + InstanceScript::OnGameObjectCreate(go); + switch (go->GetEntry()) { - case GO_VOLKHAN_DOOR: - case GO_IONAR_DOOR: - case GO_LOKEN_DOOR: - AddDoor(go, true); - break; case GO_LOKEN_THRONE: LokenGlobeGUID = go->GetGUID(); break; @@ -79,20 +79,6 @@ class instance_halls_of_lightning : public InstanceMapScript } } - void OnGameObjectRemove(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_VOLKHAN_DOOR: - case GO_IONAR_DOOR: - case GO_LOKEN_DOOR: - AddDoor(go, false); - break; - default: - break; - } - } - bool SetBossState(uint32 type, EncounterState state) override { if (!InstanceScript::SetBossState(type, state)) diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_krystallus.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_krystallus.cpp index ae664ceae1b..dfdd9d8c65d 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_krystallus.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_krystallus.cpp @@ -16,9 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" #include "halls_of_stone.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellScript.h" enum Spells { @@ -155,7 +156,7 @@ class spell_krystallus_shatter : public SpellScriptLoader if (Unit* target = GetHitUnit()) { target->RemoveAurasDueToSpell(SPELL_STONED); - target->CastSpell((Unit*)NULL, SPELL_SHATTER_EFFECT, true); + target->CastSpell((Unit*)nullptr, SPELL_SHATTER_EFFECT, true); } } diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_maiden_of_grief.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_maiden_of_grief.cpp index f29ab70962e..ed1d4947117 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_maiden_of_grief.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_maiden_of_grief.cpp @@ -16,8 +16,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "halls_of_stone.h" +#include "InstanceScript.h" +#include "ScriptedCreature.h" enum Yells { diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_sjonnir.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_sjonnir.cpp index e3fae84a7ea..fef87f3cd7a 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_sjonnir.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfStone/boss_sjonnir.cpp @@ -16,8 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "halls_of_stone.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Spells { diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfStone/halls_of_stone.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfStone/halls_of_stone.cpp index 1e772f9d626..00cf78085d5 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfStone/halls_of_stone.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfStone/halls_of_stone.cpp @@ -16,11 +16,13 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" #include "halls_of_stone.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "TemporarySummon.h" enum Texts { @@ -577,7 +579,7 @@ public: me->SetStandState(UNIT_STAND_STATE_STAND); instance->HandleGameObject(instance->GetGuidData(DATA_GO_SKY_FLOOR), true); if (Creature* temp = ObjectAccessor::GetCreature(*me, uiControllerGUID)) - temp->DealDamage(temp, temp->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + temp->DealDamage(temp, temp->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); bIsBattle = true; SetEscortPaused(false); JumpToNextStep(6500); diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfStone/halls_of_stone.h b/src/server/scripts/Northrend/Ulduar/HallsOfStone/halls_of_stone.h index 3665ef44475..9f211a1f9d2 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfStone/halls_of_stone.h +++ b/src/server/scripts/Northrend/Ulduar/HallsOfStone/halls_of_stone.h @@ -18,6 +18,8 @@ #ifndef HALLS_OF_STONE_H_ #define HALLS_OF_STONE_H_ +#include "CreatureAIImpl.h" + #define HoSScriptName "instance_halls_of_stone" #define DataHeader "HOS" @@ -67,10 +69,10 @@ enum HOSGameObjectIds GO_TRIBUNAL_SKY_FLOOR = 191527 }; -template -AI* GetHallsOfStoneAI(Creature* creature) +template +inline AI* GetHallsOfStoneAI(T* obj) { - return GetInstanceAI(creature, HoSScriptName); + return GetInstanceAI(obj, HoSScriptName); } #endif // HALLS_OF_STONE_H_ diff --git a/src/server/scripts/Northrend/Ulduar/HallsOfStone/instance_halls_of_stone.cpp b/src/server/scripts/Northrend/Ulduar/HallsOfStone/instance_halls_of_stone.cpp index 4e3c66a09ca..6d36c352970 100644 --- a/src/server/scripts/Northrend/Ulduar/HallsOfStone/instance_halls_of_stone.cpp +++ b/src/server/scripts/Northrend/Ulduar/HallsOfStone/instance_halls_of_stone.cpp @@ -15,10 +15,13 @@ * with this program. If not, see . */ -#include "InstanceScript.h" -#include "Player.h" #include "ScriptMgr.h" +#include "Creature.h" +#include "GameObject.h" #include "halls_of_stone.h" +#include "InstanceScript.h" +#include "Map.h" +#include "Player.h" DoorData const doorData[] = { @@ -72,6 +75,8 @@ class instance_halls_of_stone : public InstanceMapScript void OnGameObjectCreate(GameObject* go) override { + InstanceScript::OnGameObjectCreate(go); + switch (go->GetEntry()) { case GO_ABEDNEUM: @@ -95,21 +100,6 @@ class instance_halls_of_stone : public InstanceMapScript case GO_TRIBUNAL_SKY_FLOOR: TribunalSkyFloorGUID = go->GetGUID(); break; - case GO_SJONNIR_DOOR: - AddDoor(go, true); - break; - default: - break; - } - } - - void OnGameObjectRemove(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_SJONNIR_DOOR: - AddDoor(go, false); - break; default: break; } 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 2d395eab00f..e9074eddb6f 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 @@ -15,16 +15,23 @@ * with this program. If not, see . */ -#include "ObjectMgr.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "PassiveAI.h" +#include "DBCStores.h" +#include "GameObject.h" #include "GameObjectAI.h" -#include "MapManager.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" #include "MoveSplineInit.h" -#include "ulduar.h" +#include "ObjectAccessor.h" +#include "PassiveAI.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "Spell.h" +#include "SpellInfo.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "ulduar.h" enum Texts { @@ -247,7 +254,7 @@ class ActivateLivingConstellation : public BasicEvent if (!_instance || _instance->GetBossState(BOSS_ALGALON) != IN_PROGRESS) return true; // delete event - _owner->CastSpell((Unit*)NULL, SPELL_TRIGGER_3_ADDS, TRIGGERED_FULL_MASK); + _owner->CastSpell((Unit*)nullptr, SPELL_TRIGGER_3_ADDS, TRIGGERED_FULL_MASK); _owner->m_Events.AddEvent(this, execTime + urand(45000, 50000)); return false; } @@ -266,7 +273,7 @@ class CosmicSmashDamageEvent : public BasicEvent bool Execute(uint64 /*execTime*/, uint32 /*diff*/) override { - _caster->CastSpell((Unit*)NULL, SPELL_COSMIC_SMASH_TRIGGERED, TRIGGERED_FULL_MASK); + _caster->CastSpell((Unit*)nullptr, SPELL_COSMIC_SMASH_TRIGGERED, TRIGGERED_FULL_MASK); return true; } @@ -283,7 +290,7 @@ class SummonUnleashedDarkMatter : public BasicEvent bool Execute(uint64 execTime, uint32 /*diff*/) override { - _caster->CastSpell((Unit*)NULL, SPELL_SUMMON_UNLEASHED_DARK_MATTER, TRIGGERED_FULL_MASK); + _caster->CastSpell((Unit*)nullptr, SPELL_SUMMON_UNLEASHED_DARK_MATTER, TRIGGERED_FULL_MASK); _caster->m_Events.AddEvent(this, execTime + 30000); return false; } @@ -466,9 +473,9 @@ class boss_algalon_the_observer : public CreatureScript break; case NPC_BLACK_HOLE: summon->SetReactState(REACT_PASSIVE); - summon->CastSpell((Unit*)NULL, SPELL_BLACK_HOLE_TRIGGER, TRIGGERED_FULL_MASK); + summon->CastSpell((Unit*)nullptr, SPELL_BLACK_HOLE_TRIGGER, TRIGGERED_FULL_MASK); summon->CastSpell(summon, SPELL_CONSTELLATION_PHASE_TRIGGER, TRIGGERED_FULL_MASK); - summon->CastSpell((Unit*)NULL, SPELL_BLACK_HOLE_EXPLOSION); + summon->CastSpell((Unit*)nullptr, SPELL_BLACK_HOLE_EXPLOSION); summon->CastSpell(summon, SPELL_SUMMON_VOID_ZONE_VISUAL, TRIGGERED_FULL_MASK); break; case NPC_ALGALON_VOID_ZONE_VISUAL_STALKER: @@ -778,7 +785,7 @@ class npc_living_constellation : public CreatureScript me->DespawnOrUnsummon(1); if (InstanceScript* instance = me->GetInstanceScript()) instance->DoStartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, EVENT_ID_SUPERMASSIVE_START); - caster->CastSpell((Unit*)NULL, SPELL_BLACK_HOLE_CREDIT, TRIGGERED_FULL_MASK); + caster->CastSpell((Unit*)nullptr, SPELL_BLACK_HOLE_CREDIT, TRIGGERED_FULL_MASK); caster->ToCreature()->DespawnOrUnsummon(1); } @@ -910,7 +917,8 @@ class npc_brann_bronzebeard_algalon : public CreatureScript { case 2: delay = 8000; - me->SetWalk(true); break; + me->SetWalk(true); + break; case 5: me->SetWalk(false); Talk(SAY_BRANN_ALGALON_INTRO_1); @@ -976,9 +984,9 @@ class go_celestial_planetarium_access : public GameObjectScript struct go_celestial_planetarium_accessAI : public GameObjectAI { - go_celestial_planetarium_accessAI(GameObject* go) : GameObjectAI(go) - { - } + go_celestial_planetarium_accessAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool OnReportUse(Player* player) override { @@ -1011,15 +1019,12 @@ class go_celestial_planetarium_access : public GameObjectScript if (Creature* brann = me->SummonCreature(NPC_BRANN_BRONZBEARD_ALG, BrannIntroSpawnPos)) brann->AI()->DoAction(ACTION_START_INTRO); - if (InstanceScript* instance = me->GetInstanceScript()) - { - instance->SetData(DATA_ALGALON_SUMMON_STATE, 1); - if (GameObject* sigil = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(DATA_SIGILDOOR_01))) - sigil->SetGoState(GO_STATE_ACTIVE); + instance->SetData(DATA_ALGALON_SUMMON_STATE, 1); + if (GameObject* sigil = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(DATA_SIGILDOOR_01))) + sigil->SetGoState(GO_STATE_ACTIVE); - if (GameObject* sigil = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(DATA_SIGILDOOR_02))) - sigil->SetGoState(GO_STATE_ACTIVE); - } + if (GameObject* sigil = ObjectAccessor::GetGameObject(*me, instance->GetGuidData(DATA_SIGILDOOR_02))) + sigil->SetGoState(GO_STATE_ACTIVE); return false; } @@ -1189,7 +1194,7 @@ class spell_algalon_collapse : public SpellScriptLoader void HandlePeriodic(AuraEffect const* /*aurEff*/) { PreventDefaultAction(); - GetTarget()->DealDamage(GetTarget(), GetTarget()->CountPctFromMaxHealth(1), NULL, NODAMAGE); + GetTarget()->DealDamage(GetTarget(), GetTarget()->CountPctFromMaxHealth(1), nullptr, NODAMAGE); } void Register() override diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_assembly_of_iron.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_assembly_of_iron.cpp index 307e5e4e806..453658cd9d1 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_assembly_of_iron.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_assembly_of_iron.cpp @@ -23,9 +23,14 @@ SDCategory: Ulduar - Ulduar EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "SpellAuras.h" +#include "SpellMgr.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "TemporarySummon.h" #include "ulduar.h" enum AssemblySpells @@ -206,7 +211,7 @@ class boss_steelbreaker : public CreatureScript } else { - me->SetLootRecipient(NULL); + me->SetLootRecipient(nullptr); Talk(SAY_STEELBREAKER_DEATH); //DoCastAOE(SPELL_SUPERCHARGE, true); @@ -354,7 +359,7 @@ class boss_runemaster_molgeim : public CreatureScript } else { - me->SetLootRecipient(NULL); + me->SetLootRecipient(nullptr); Talk(SAY_MOLGEIM_DEATH); //DoCastAOE(SPELL_SUPERCHARGE, true); @@ -530,7 +535,7 @@ class boss_stormcaller_brundir : public CreatureScript } else { - me->SetLootRecipient(NULL); + me->SetLootRecipient(nullptr); Talk(SAY_BRUNDIR_DEATH); //DoCastAOE(SPELL_SUPERCHARGE, true); @@ -725,15 +730,13 @@ class spell_assembly_rune_of_summoning : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RUNE_OF_SUMMONING_SUMMON)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RUNE_OF_SUMMONING_SUMMON }); } void HandlePeriodic(AuraEffect const* aurEff) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_RUNE_OF_SUMMONING_SUMMON, true, NULL, aurEff, GetTarget()->IsSummon() ? GetTarget()->ToTempSummon()->GetSummonerGUID() : ObjectGuid::Empty); + GetTarget()->CastSpell(GetTarget(), SPELL_RUNE_OF_SUMMONING_SUMMON, true, nullptr, aurEff, GetTarget()->IsSummon() ? GetTarget()->ToTempSummon()->GetSummonerGUID() : ObjectGuid::Empty); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_auriaya.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_auriaya.cpp index 8d965924d78..e2c3ea05be0 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_auriaya.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_auriaya.cpp @@ -16,6 +16,8 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellScript.h" #include "ulduar.h" 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 1b6a8c26b3a..f3a4c0627f6 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_flame_leviathan.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_flame_leviathan.cpp @@ -23,23 +23,21 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" #include "CombatAI.h" +#include "GameObjectAI.h" +#include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "PassiveAI.h" -#include "ObjectMgr.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "Spell.h" #include "SpellInfo.h" #include "SpellScript.h" -#include "Vehicle.h" -#include "VehicleDefines.h" #include "ulduar.h" -#include "Spell.h" -#include "GameObjectAI.h" +#include "Vehicle.h" enum Spells { @@ -1007,7 +1005,7 @@ public: npc_escortAI::UpdateAI(diff); if (!HasEscortState(STATE_ESCORT_ESCORTING)) - Start(false, true, ObjectGuid::Empty, NULL, false, true); + Start(false, true, ObjectGuid::Empty, nullptr, false, true); else { if (infernoTimer <= diff) @@ -1284,14 +1282,12 @@ class go_ulduar_tower : public GameObjectScript struct go_ulduar_towerAI : public GameObjectAI { - go_ulduar_towerAI(GameObject* go) : GameObjectAI(go) { } + go_ulduar_towerAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; void Destroyed(Player* /*player*/, uint32 /*eventId*/) override { - InstanceScript* instance = me->GetInstanceScript(); - if (!instance) - return; - switch (me->GetEntry()) { case GO_TOWER_OF_STORMS: @@ -1315,7 +1311,7 @@ class go_ulduar_tower : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return new go_ulduar_towerAI(go); + return GetUlduarAI(go); } }; @@ -1754,11 +1750,11 @@ class spell_vehicle_throw_passenger : public SpellScriptLoader { // use 99 because it is 3d search std::list targetList; - Trinity::WorldObjectSpellAreaTargetCheck check(99, GetExplTargetDest(), GetCaster(), GetCaster(), GetSpellInfo(), TARGET_CHECK_DEFAULT, NULL); + Trinity::WorldObjectSpellAreaTargetCheck check(99, GetExplTargetDest(), GetCaster(), GetCaster(), GetSpellInfo(), TARGET_CHECK_DEFAULT, nullptr); Trinity::WorldObjectListSearcher searcher(GetCaster(), targetList, check); Cell::VisitAllObjects(GetCaster(), searcher, 99.0f); float minDist = 99 * 99; - Unit* target = NULL; + Unit* target = nullptr; for (std::list::iterator itr = targetList.begin(); itr != targetList.end(); ++itr) { if (Unit* unit = (*itr)->ToUnit()) diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_freya.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_freya.cpp index 5d1a3fb8543..c941e185de3 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_freya.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_freya.cpp @@ -16,12 +16,14 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" +#include "SpellAuras.h" #include "SpellScript.h" -#include "Cell.h" -#include "CellImpl.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" +#include "TemporarySummon.h" #include "ulduar.h" enum FreyaYells @@ -609,7 +611,7 @@ class boss_freya : public CreatureScript /* 25N */ {62955, 62956, 62957, 62958} }; - me->CastSpell((Unit*)NULL, summonSpell[me->GetMap()->GetDifficulty()][elderCount], true); + me->CastSpell((Unit*)nullptr, summonSpell[me->GetMap()->GetDifficulty()][elderCount], true); Talk(SAY_DEATH); @@ -839,7 +841,7 @@ class boss_elder_stonebark : public CreatureScript if (me->HasAura(SPELL_PETRIFIED_BARK)) { int32 reflect = damage; - who->CastCustomSpell(who, SPELL_PETRIFIED_BARK_DMG, &reflect, NULL, NULL, true); + who->CastCustomSpell(who, SPELL_PETRIFIED_BARK_DMG, &reflect, nullptr, nullptr, true); damage = 0; } } 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 4670e062ab5..8bf4e8af20f 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_general_vezax.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_general_vezax.cpp @@ -16,11 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "ulduar.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "ulduar.h" enum VezaxYells { @@ -275,7 +278,7 @@ class boss_general_vezax : public CreatureScript /* Player Range Check Purpose: If there are playersMin people within rangeMin, rangeMax: return a random players in that range. - If not, return NULL and allow other target selection + If not, return nullptr and allow other target selection */ Unit* CheckPlayersInRange(uint8 playersMin, float rangeMin, float rangeMax) { @@ -294,11 +297,11 @@ class boss_general_vezax : public CreatureScript } if (PlayerList.empty()) - return NULL; + return nullptr; size_t size = PlayerList.size(); if (size < playersMin) - return NULL; + return nullptr; return Trinity::Containers::SelectRandomContainerElement(PlayerList); } @@ -371,7 +374,7 @@ class boss_saronite_animus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetUlduarAI(creature); } }; @@ -441,7 +444,7 @@ class npc_saronite_vapors : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetUlduarAI(creature); } }; @@ -456,9 +459,7 @@ class spell_general_vezax_mark_of_the_faceless : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MARK_OF_THE_FACELESS_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MARK_OF_THE_FACELESS_DAMAGE }); } void HandleEffectPeriodic(AuraEffect const* aurEff) @@ -519,9 +520,7 @@ class spell_general_vezax_saronite_vapors : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SARONITE_VAPORS_ENERGIZE) || !sSpellMgr->GetSpellInfo(SPELL_SARONITE_VAPORS_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SARONITE_VAPORS_ENERGIZE, SPELL_SARONITE_VAPORS_DAMAGE }); } void HandleEffectApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -530,8 +529,8 @@ class spell_general_vezax_saronite_vapors : public SpellScriptLoader { int32 mana = int32(aurEff->GetAmount() * std::pow(2.0f, GetStackAmount())); // mana restore - bp * 2^stackamount int32 damage = mana * 2; - caster->CastCustomSpell(GetTarget(), SPELL_SARONITE_VAPORS_ENERGIZE, &mana, NULL, NULL, true); - caster->CastCustomSpell(GetTarget(), SPELL_SARONITE_VAPORS_DAMAGE, &damage, NULL, NULL, true); + caster->CastCustomSpell(GetTarget(), SPELL_SARONITE_VAPORS_ENERGIZE, &mana, nullptr, nullptr, true); + caster->CastCustomSpell(GetTarget(), SPELL_SARONITE_VAPORS_DAMAGE, &damage, nullptr, nullptr, true); } } diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_hodir.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_hodir.cpp index feef62901b2..136a7f0c4e9 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_hodir.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_hodir.cpp @@ -16,13 +16,14 @@ */ #include "ScriptMgr.h" +#include "CellImpl.h" +#include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "Cell.h" -#include "CellImpl.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" +#include "TemporarySummon.h" #include "ulduar.h" /* @todo Achievements @@ -959,7 +960,7 @@ class npc_toasty_fire : public CreatureScript DoCast(me, SPELL_SINGED, true); } - void SpellHit(Unit* /*who*/, const SpellInfo* spell) override + void SpellHit(Unit* /*who*/, SpellInfo const* spell) override { if (spell->Id == SPELL_BLOCK_OF_ICE || spell->Id == SPELL_ICE_SHARD || spell->Id == SPELL_ICE_SHARD_HIT) { @@ -1048,7 +1049,7 @@ public: return; int32 damage = int32(200 * std::pow(2.0f, GetStackAmount())); - caster->CastCustomSpell(caster, SPELL_BITING_COLD_DAMAGE, &damage, NULL, NULL, true); + caster->CastCustomSpell(caster, SPELL_BITING_COLD_DAMAGE, &damage, nullptr, nullptr, true); if (caster->isMoving()) caster->RemoveAuraFromStack(SPELL_BITING_COLD_TRIGGERED); diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp index 664fdec748d..c19b2dde126 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_ignis.cpp @@ -15,11 +15,13 @@ * with this program. If not, see . */ -#include "GameTime.h" #include "ScriptMgr.h" +#include "GameTime.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "SpellAuras.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" #include "ulduar.h" #include "Vehicle.h" @@ -252,7 +254,7 @@ class boss_ignis : public CreatureScript if (Unit* slagPotTarget = ObjectAccessor::GetUnit(*me, _slagPotGUID)) { slagPotTarget->ExitVehicle(); - slagPotTarget = NULL; + slagPotTarget = nullptr; _slagPotGUID.Clear(); events.CancelEvent(EVENT_END_POT); } @@ -454,10 +456,7 @@ class spell_ignis_slag_pot : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SLAG_POT_DAMAGE) - || !sSpellMgr->GetSpellInfo(SPELL_SLAG_IMBUED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SLAG_POT_DAMAGE, SPELL_SLAG_IMBUED }); } void HandleEffectPeriodic(AuraEffect const* /*aurEff*/) diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_kologarn.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_kologarn.cpp index 660b52d9b6f..b41dd4a374d 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_kologarn.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_kologarn.cpp @@ -16,12 +16,16 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" +#include "SpellScript.h" #include "ulduar.h" #include "Vehicle.h" -#include "Player.h" /* ScriptData SDName: boss_kologarn @@ -340,7 +344,7 @@ class spell_ulduar_rubble_summon : public SpellScriptLoader ObjectGuid originalCaster = caster->GetInstanceScript() ? caster->GetInstanceScript()->GetGuidData(BOSS_KOLOGARN) : ObjectGuid::Empty; uint32 spellId = GetEffectValue(); for (uint8 i = 0; i < 5; ++i) - caster->CastSpell(caster, spellId, true, NULL, NULL, originalCaster); + caster->CastSpell(caster, spellId, true, nullptr, nullptr, originalCaster); } void Register() override @@ -356,7 +360,7 @@ class spell_ulduar_rubble_summon : public SpellScriptLoader }; // predicate function to select non main tank target -class StoneGripTargetSelector : public std::unary_function +class StoneGripTargetSelector { public: StoneGripTargetSelector(Creature* me, Unit const* victim) : _me(me), _victim(victim) { } @@ -372,6 +376,7 @@ class StoneGripTargetSelector : public std::unary_function return false; } + private: Creature* _me; Unit const* _victim; }; diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_mimiron.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_mimiron.cpp index c1e0cd8d7b0..f7542d29d1d 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_mimiron.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_mimiron.cpp @@ -15,17 +15,19 @@ * with this program. If not, see . */ -#include "Cell.h" -#include "CellImpl.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" #include "ScriptMgr.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "GridNotifiers.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "TemporarySummon.h" #include "ulduar.h" #include "Vehicle.h" -#include "GameObjectAI.h" enum Yells { @@ -348,7 +350,7 @@ Position const VehicleRelocation[] = }; Position const VX001SummonPos = { 2744.431f, 2569.385f, 364.3968f, 3.141593f }; -Position const ACUSummonPos = { 2744.650f, 2569.460f, 380.0000f, 0.0f }; +Position const ACUSummonPos = { 2744.650f, 2569.460f, 380.0000f, 3.141593f }; static bool IsEncounterFinished(Unit* who) { @@ -493,7 +495,7 @@ class boss_mimiron : public CreatureScript { case EVENT_SUMMON_FLAMES: if (Creature* worldtrigger = instance->GetCreature(DATA_MIMIRON_WORLD_TRIGGER)) - worldtrigger->CastCustomSpell(SPELL_SCRIPT_EFFECT_SUMMON_FLAMES_INITIAL, SPELLVALUE_MAX_TARGETS, 3, NULL, true, NULL, NULL, me->GetGUID()); + worldtrigger->CastCustomSpell(SPELL_SCRIPT_EFFECT_SUMMON_FLAMES_INITIAL, SPELLVALUE_MAX_TARGETS, 3, nullptr, true, nullptr, nullptr, me->GetGUID()); events.RescheduleEvent(EVENT_SUMMON_FLAMES, 28000); break; case EVENT_INTRO_1: @@ -645,10 +647,10 @@ class boss_mimiron : public CreatureScript { if (Creature* computer = instance->GetCreature(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, G3D::Quat(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, QuaternionData(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, G3D::Quat(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, QuaternionData(0.f, 0.f, 0.9999619f, 0.008734641f), 604800); events.ScheduleEvent(EVENT_OUTTRO_3, 11000); break; case EVENT_OUTTRO_3: @@ -1229,15 +1231,15 @@ class boss_aerial_command_unit : public CreatureScript switch (eventId) { case EVENT_SUMMON_FIRE_BOTS: - me->CastCustomSpell(SPELL_SUMMON_FIRE_BOT_TRIGGER, SPELLVALUE_MAX_TARGETS, 3, NULL, true); + me->CastCustomSpell(SPELL_SUMMON_FIRE_BOT_TRIGGER, SPELLVALUE_MAX_TARGETS, 3, nullptr, true); events.RescheduleEvent(EVENT_SUMMON_FIRE_BOTS, 45000, 0, PHASE_AERIAL_COMMAND_UNIT); break; case EVENT_SUMMON_JUNK_BOT: - me->CastCustomSpell(SPELL_SUMMON_JUNK_BOT_TRIGGER, SPELLVALUE_MAX_TARGETS, 1, NULL, true); + me->CastCustomSpell(SPELL_SUMMON_JUNK_BOT_TRIGGER, SPELLVALUE_MAX_TARGETS, 1, nullptr, true); events.RescheduleEvent(EVENT_SUMMON_JUNK_BOT, urand(11000, 12000), 0, PHASE_AERIAL_COMMAND_UNIT); break; case EVENT_SUMMON_ASSAULT_BOT: - me->CastCustomSpell(SPELL_SUMMON_ASSAULT_BOT_TRIGGER, SPELLVALUE_MAX_TARGETS, 1, NULL, true); + me->CastCustomSpell(SPELL_SUMMON_ASSAULT_BOT_TRIGGER, SPELLVALUE_MAX_TARGETS, 1, nullptr, true); events.RescheduleEvent(EVENT_SUMMON_ASSAULT_BOT, 30000, 0, PHASE_AERIAL_COMMAND_UNIT); break; case EVENT_SUMMON_BOMB_BOT: @@ -1648,19 +1650,18 @@ class go_mimiron_hardmode_button : public GameObjectScript struct go_mimiron_hardmode_buttonAI : public GameObjectAI { - go_mimiron_hardmode_buttonAI(GameObject* go) : GameObjectAI(go) { } + go_mimiron_hardmode_buttonAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* /*player*/) override { if (me->HasFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE)) return true; - InstanceScript* instance = me->GetInstanceScript(); - if (!instance) - return false; - if (Creature* computer = instance->GetCreature(DATA_COMPUTER)) computer->AI()->DoAction(DO_ACTIVATE_COMPUTER); + me->SetGoState(GO_STATE_ACTIVE); me->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); return true; @@ -1669,7 +1670,7 @@ class go_mimiron_hardmode_button : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return new go_mimiron_hardmode_buttonAI(go); + return GetUlduarAI(go); } }; @@ -1788,9 +1789,7 @@ class spell_mimiron_fire_search : public SpellScriptLoader private: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WATER_SPRAY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WATER_SPRAY }); } void FilterTargets(std::list& targets) @@ -1879,9 +1878,7 @@ class spell_mimiron_magnetic_core : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGNETIC_CORE_VISUAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGNETIC_CORE_VISUAL }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1934,9 +1931,7 @@ class spell_mimiron_napalm_shell : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_NAPALM_SHELL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_NAPALM_SHELL }); } void FilterTargets(std::list& targets) @@ -2012,9 +2007,7 @@ class spell_mimiron_plasma_blast : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PLASMA_BLAST)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PLASMA_BLAST }); } bool Load() override @@ -2088,9 +2081,7 @@ class spell_mimiron_proximity_mines : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_PROXIMITY_MINE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_PROXIMITY_MINE }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -2123,9 +2114,7 @@ class spell_mimiron_proximity_trigger : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PROXIMITY_MINE_EXPLOSION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PROXIMITY_MINE_EXPLOSION }); } void FilterTargets(std::list& targets) @@ -2138,7 +2127,7 @@ class spell_mimiron_proximity_trigger : public SpellScriptLoader void HandleDummy(SpellEffIndex /*effIndex*/) { - GetCaster()->CastSpell((Unit*)NULL, SPELL_PROXIMITY_MINE_EXPLOSION, true); + GetCaster()->CastSpell((Unit*)nullptr, SPELL_PROXIMITY_MINE_EXPLOSION, true); } void Register() override @@ -2166,9 +2155,7 @@ class spell_mimiron_rapid_burst : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RAPID_BURST_LEFT) || !sSpellMgr->GetSpellInfo(SPELL_RAPID_BURST_RIGHT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RAPID_BURST_LEFT, SPELL_RAPID_BURST_RIGHT }); } void AfterRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2180,7 +2167,7 @@ class spell_mimiron_rapid_burst : public SpellScriptLoader void HandleDummyTick(AuraEffect const* aurEff) { if (GetCaster()) - GetCaster()->CastSpell(GetTarget(), aurEff->GetTickNumber() % 2 == 0 ? SPELL_RAPID_BURST_RIGHT : SPELL_RAPID_BURST_LEFT, true, NULL, aurEff); + GetCaster()->CastSpell(GetTarget(), aurEff->GetTickNumber() % 2 == 0 ? SPELL_RAPID_BURST_RIGHT : SPELL_RAPID_BURST_LEFT, true, nullptr, aurEff); } void Register() override @@ -2208,9 +2195,7 @@ class spell_mimiron_rocket_strike : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SCRIPT_EFFECT_ROCKET_STRIKE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SCRIPT_EFFECT_ROCKET_STRIKE }); } void FilterTargets(std::list& targets) @@ -2228,7 +2213,7 @@ class spell_mimiron_rocket_strike : public SpellScriptLoader void HandleDummy(SpellEffIndex /*effIndex*/) { - GetHitUnit()->CastSpell((Unit*)NULL, SPELL_SCRIPT_EFFECT_ROCKET_STRIKE, true, NULL, NULL, GetCaster()->GetGUID()); + GetHitUnit()->CastSpell((Unit*)nullptr, SPELL_SCRIPT_EFFECT_ROCKET_STRIKE, true, nullptr, nullptr, GetCaster()->GetGUID()); } void Register() override @@ -2256,9 +2241,7 @@ class spell_mimiron_rocket_strike_damage : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_NOT_SO_FRIENDLY_FIRE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_NOT_SO_FRIENDLY_FIRE }); } void HandleAfterCast() @@ -2277,7 +2260,7 @@ class spell_mimiron_rocket_strike_damage : public SpellScriptLoader void HandleFriendlyFire(SpellEffIndex /*effIndex*/) { - GetHitUnit()->CastSpell((Unit*)NULL, SPELL_NOT_SO_FRIENDLY_FIRE, true); + GetHitUnit()->CastSpell((Unit*)nullptr, SPELL_NOT_SO_FRIENDLY_FIRE, true); } void Register() override @@ -2306,9 +2289,7 @@ class spell_mimiron_rocket_strike_target_select : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_ROCKET_STRIKE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_ROCKET_STRIKE }); } void FilterTargets(std::list& targets) @@ -2330,7 +2311,7 @@ class spell_mimiron_rocket_strike_target_select : public SpellScriptLoader void HandleScript(SpellEffIndex /*effIndex*/) { if (InstanceScript* instance = GetCaster()->GetInstanceScript()) - GetCaster()->CastSpell(GetHitUnit(), SPELL_SUMMON_ROCKET_STRIKE, true, NULL, NULL, instance->GetGuidData(DATA_VX_001)); + GetCaster()->CastSpell(GetHitUnit(), SPELL_SUMMON_ROCKET_STRIKE, true, nullptr, nullptr, instance->GetGuidData(DATA_VX_001)); GetCaster()->SetDisplayId(11686); } @@ -2416,9 +2397,7 @@ class spell_mimiron_summon_assault_bot : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_ASSAULT_BOT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_ASSAULT_BOT }); } void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -2426,7 +2405,7 @@ class spell_mimiron_summon_assault_bot : public SpellScriptLoader if (Unit* caster = GetCaster()) if (InstanceScript* instance = caster->GetInstanceScript()) if (instance->GetBossState(BOSS_MIMIRON) == IN_PROGRESS) - caster->CastSpell(caster, SPELL_SUMMON_ASSAULT_BOT, false, NULL, aurEff, instance->GetGuidData(DATA_AERIAL_COMMAND_UNIT)); + caster->CastSpell(caster, SPELL_SUMMON_ASSAULT_BOT, false, nullptr, aurEff, instance->GetGuidData(DATA_AERIAL_COMMAND_UNIT)); } void Register() override @@ -2453,9 +2432,7 @@ class spell_mimiron_summon_assault_bot_target : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_ASSAULT_BOT_DUMMY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_ASSAULT_BOT_DUMMY }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2487,10 +2464,7 @@ class spell_mimiron_summon_fire_bot : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_FIRE_BOT)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_SUMMON_FIRE_BOT }); } void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -2498,7 +2472,7 @@ class spell_mimiron_summon_fire_bot : public SpellScriptLoader if (Unit* caster = GetCaster()) if (InstanceScript* instance = caster->GetInstanceScript()) if (instance->GetBossState(BOSS_MIMIRON) == IN_PROGRESS) - caster->CastSpell(caster, SPELL_SUMMON_FIRE_BOT, false, NULL, aurEff, instance->GetGuidData(DATA_AERIAL_COMMAND_UNIT)); + caster->CastSpell(caster, SPELL_SUMMON_FIRE_BOT, false, nullptr, aurEff, instance->GetGuidData(DATA_AERIAL_COMMAND_UNIT)); } void Register() override @@ -2525,9 +2499,7 @@ class spell_mimiron_summon_fire_bot_target : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_FIRE_BOT_DUMMY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_FIRE_BOT_DUMMY }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2596,9 +2568,7 @@ class spell_mimiron_summon_flames_spread : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_FLAMES_SPREAD)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_FLAMES_SPREAD }); } void HandleTick(AuraEffect const* /*aurEff*/) @@ -2633,9 +2603,7 @@ class spell_mimiron_summon_frost_bomb_target : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_FROST_BOMB)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_FROST_BOMB }); } void FilterTargets(std::list& targets) @@ -2684,9 +2652,7 @@ class spell_mimiron_summon_junk_bot : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_JUNK_BOT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_JUNK_BOT }); } void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -2694,7 +2660,7 @@ class spell_mimiron_summon_junk_bot : public SpellScriptLoader if (Unit* caster = GetCaster()) if (InstanceScript* instance = caster->GetInstanceScript()) if (instance->GetBossState(BOSS_MIMIRON) == IN_PROGRESS) - caster->CastSpell(caster, SPELL_SUMMON_JUNK_BOT, false, NULL, aurEff, instance->GetGuidData(DATA_AERIAL_COMMAND_UNIT)); + caster->CastSpell(caster, SPELL_SUMMON_JUNK_BOT, false, nullptr, aurEff, instance->GetGuidData(DATA_AERIAL_COMMAND_UNIT)); } void Register() override @@ -2721,9 +2687,7 @@ class spell_mimiron_summon_junk_bot_target : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_JUNK_BOT_DUMMY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_JUNK_BOT_DUMMY }); } void HandleDummy(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_razorscale.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_razorscale.cpp index d877752b200..ddd1c3dbb00 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_razorscale.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_razorscale.cpp @@ -18,13 +18,19 @@ /// @todo Harpoon chain from 62505 should not get removed when other chain is applied #include "ScriptMgr.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "SpellScript.h" -#include "ulduar.h" #include "SpellInfo.h" -#include "Player.h" -#include "GameObjectAI.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "ulduar.h" enum Says { @@ -250,7 +256,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, G3D::Quat(), 180); + me->SummonGameObject(GO_RAZOR_BROKEN_HARPOON, PosHarpoon[n].GetPositionX(), PosHarpoon[n].GetPositionY(), PosHarpoon[n].GetPositionZ(), 2.286f, QuaternionData(), 180); break; } } @@ -265,7 +271,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, G3D::Quat(), uint32(me->GetRespawnTime()))) + if (GameObject* harpoon = me->SummonGameObject(GO_RAZOR_HARPOON_1, PosHarpoon[0].GetPositionX(), PosHarpoon[0].GetPositionY(), PosHarpoon[0].GetPositionZ(), 4.790f, QuaternionData(), uint32(me->GetRespawnTime()))) { if (GameObject* brokenHarpoon = harpoon->FindNearestGameObject(GO_RAZOR_BROKEN_HARPOON, 5.0f)) //only nearest broken harpoon brokenHarpoon->RemoveFromWorld(); @@ -275,7 +281,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, G3D::Quat(), uint32(me->GetRespawnTime()))) + if (GameObject* harpoon = me->SummonGameObject(GO_RAZOR_HARPOON_2, PosHarpoon[1].GetPositionX(), PosHarpoon[1].GetPositionY(), PosHarpoon[1].GetPositionZ(), 4.659f, QuaternionData(), uint32(me->GetRespawnTime()))) { if (GameObject* brokenHarpoon = harpoon->FindNearestGameObject(GO_RAZOR_BROKEN_HARPOON, 5.0f)) brokenHarpoon->RemoveFromWorld(); @@ -284,7 +290,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, G3D::Quat(), uint32(me->GetRespawnTime()))) + if (GameObject* harpoon = me->SummonGameObject(GO_RAZOR_HARPOON_3, PosHarpoon[2].GetPositionX(), PosHarpoon[2].GetPositionY(), PosHarpoon[2].GetPositionZ(), 5.382f, QuaternionData(), uint32(me->GetRespawnTime()))) { if (GameObject* brokenHarpoon = harpoon->FindNearestGameObject(GO_RAZOR_BROKEN_HARPOON, 5.0f)) brokenHarpoon->RemoveFromWorld(); @@ -294,7 +300,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, G3D::Quat(), uint32(me->GetRespawnTime()))) + if (GameObject* harpoon = me->SummonGameObject(GO_RAZOR_HARPOON_4, PosHarpoon[3].GetPositionX(), PosHarpoon[3].GetPositionY(), PosHarpoon[3].GetPositionZ(), 4.266f, QuaternionData(), uint32(me->GetRespawnTime()))) { if (GameObject* brokenHarpoon = harpoon->FindNearestGameObject(GO_RAZOR_BROKEN_HARPOON, 5.0f)) brokenHarpoon->RemoveFromWorld(); @@ -319,20 +325,21 @@ class go_razorscale_harpoon : public GameObjectScript struct go_razorscale_harpoonAI : public GameObjectAI { - go_razorscale_harpoonAI(GameObject* go) : GameObjectAI(go) { } + go_razorscale_harpoonAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* /*player*/) override { - if (InstanceScript* instance = me->GetInstanceScript()) - if (instance->GetCreature(BOSS_RAZORSCALE)) - me->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); + if (instance->GetCreature(BOSS_RAZORSCALE)) + me->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); return true; } }; GameObjectAI* GetAI(GameObject* go) const override { - return new go_razorscale_harpoonAI(go); + return GetUlduarAI(go); } }; diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_thorim.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_thorim.cpp index ca07a8b117b..3eb9861b544 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_thorim.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_thorim.cpp @@ -15,16 +15,22 @@ * with this program. If not, see . */ -#include "MoveSplineInit.h" -#include "Player.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "TypeContainerVisitor.h" +#include "AreaBoundary.h" #include "CellImpl.h" #include "GridNotifiersImpl.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "MoveSplineInit.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellMgr.h" +#include "SpellScript.h" +#include "TypeContainerVisitor.h" #include "ulduar.h" +#include enum Spells { @@ -317,8 +323,7 @@ enum DisplayIds THORIM_WEAPON_DISPLAY_ID = 45900 }; -uint32 const LightningOrbPathSize = 8; -G3D::Vector3 const LightningOrbPath[LightningOrbPathSize] = +Position const LightningOrbPath[] = { { 2134.889893f, -298.632996f, 438.247467f }, { 2134.570068f, -440.317993f, 438.247467f }, @@ -329,6 +334,7 @@ G3D::Vector3 const LightningOrbPath[LightningOrbPathSize] = { 2202.208008f, -262.939270f, 412.168976f }, { 2182.310059f, -263.233093f, 414.739410f } }; +std::size_t const LightningOrbPathSize = std::extent::value; // used for trash jump calculation Position const ArenaCenter = { 2134.77f, -262.307f }; @@ -352,7 +358,7 @@ class HeightPositionCheck bool operator()(Position const* pos) const { - return pos->GetPositionZ() > THORIM_BALCONY_Z_CHECK == _ret; + return (pos->GetPositionZ() > THORIM_BALCONY_Z_CHECK) == _ret; } private: @@ -647,7 +653,12 @@ class boss_thorim : public CreatureScript summon->GetMotionMaster()->MovePoint(EVENT_CHARGE_PREPATH, LightningOrbPath[LightningOrbPathSize - 1], false); - Movement::PointsArray path(LightningOrbPath, LightningOrbPath + LightningOrbPathSize); + Movement::PointsArray path; + path.reserve(LightningOrbPathSize); + std::transform(std::begin(LightningOrbPath), std::end(LightningOrbPath), std::back_inserter(path), [](Position const& pos) + { + return G3D::Vector3(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ()); + }); Movement::MoveSplineInit init(summon); init.MovebyPath(path); @@ -1750,9 +1761,7 @@ class spell_thorim_charge_orb : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_LIGHTNING_PILLAR_1)) - return false; - return true; + return ValidateSpellInfo({ SPELL_LIGHTNING_PILLAR_1 }); } void FilterTargets(std::list& targets) @@ -1798,9 +1807,7 @@ class spell_thorim_lightning_charge : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_LIGHTNING_CHARGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_LIGHTNING_CHARGE }); } void HandleFocus() @@ -1881,10 +1888,7 @@ class spell_thorim_stormhammer : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_STORMHAMMER_BOOMERANG) - || !sSpellMgr->GetSpellInfo(SPELL_DEAFENING_THUNDER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_STORMHAMMER_BOOMERANG, SPELL_DEAFENING_THUNDER }); } void FilterTargets(std::list& targets) @@ -1942,10 +1946,7 @@ class spell_thorim_stormhammer_sif : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_STORMHAMMER_BOOMERANG) - || !sSpellMgr->GetSpellInfo(SPELL_SIF_TRANSFORM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_STORMHAMMER_BOOMERANG, SPELL_SIF_TRANSFORM }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -2015,9 +2016,7 @@ class spell_thorim_runic_smash : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RUNIC_SMASH)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RUNIC_SMASH }); } void HandleScript(SpellEffIndex effIndex) diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_xt002.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_xt002.cpp index 8e078e2419b..406c0ff53eb 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_xt002.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_xt002.cpp @@ -22,15 +22,18 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "ulduar.h" -#include "Vehicle.h" -#include "Player.h" -#include "WorldPacket.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Opcodes.h" #include "PassiveAI.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "ulduar.h" +#include "Vehicle.h" +#include "WorldPacket.h" enum Spells { @@ -736,7 +739,7 @@ class npc_life_spark : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_life_sparkAI(creature); + return GetUlduarAI(creature); } struct npc_life_sparkAI : public ScriptedAI @@ -807,7 +810,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_xt_void_zoneAI(creature); + return GetUlduarAI(creature); } }; @@ -823,9 +826,7 @@ class spell_xt002_searing_light_spawn_life_spark : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_LIFE_SPARK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_LIFE_SPARK }); } void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -859,9 +860,7 @@ class spell_xt002_gravity_bomb_aura : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_VOID_ZONE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_VOID_ZONE }); } void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -943,19 +942,7 @@ class spell_xt002_heart_overload_periodic : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ENERGY_ORB)) - return false; - - if (!sSpellMgr->GetSpellInfo(SPELL_RECHARGE_BOOMBOT)) - return false; - - if (!sSpellMgr->GetSpellInfo(SPELL_RECHARGE_PUMMELER)) - return false; - - if (!sSpellMgr->GetSpellInfo(SPELL_RECHARGE_SCRAPBOT)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_ENERGY_ORB, SPELL_RECHARGE_BOOMBOT, SPELL_RECHARGE_PUMMELER, SPELL_RECHARGE_SCRAPBOT }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -1074,9 +1061,7 @@ class spell_xt002_321_boombot_aura : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ACHIEVEMENT_CREDIT_NERF_SCRAPBOTS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ACHIEVEMENT_CREDIT_NERF_SCRAPBOTS }); } bool CheckProc(ProcEventInfo& eventInfo) 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 8f7f6492c4c..b81991947c4 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/boss_yogg_saron.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/boss_yogg_saron.cpp @@ -460,7 +460,6 @@ class boss_voice_of_yogg_saron : public CreatureScript } void MoveInLineOfSight(Unit* who) override - { // TODO: MoveInLineOfSight doesn't work for such a big distance if (who->GetTypeId() == TYPEID_PLAYER && me->GetDistance2d(who) < 99.0f && !me->IsInCombat()) @@ -559,7 +558,7 @@ class boss_voice_of_yogg_saron : public CreatureScript if (Creature* yogg = instance->GetCreature(BOSS_YOGG_SARON)) { yogg->AI()->Talk(EMOTE_YOGG_SARON_EXTINGUISH_ALL_LIFE, me); - yogg->CastSpell((Unit*)NULL, SPELL_EXTINGUISH_ALL_LIFE, true); + yogg->CastSpell((Unit*)nullptr, SPELL_EXTINGUISH_ALL_LIFE, true); } events.ScheduleEvent(EVENT_EXTINGUISH_ALL_LIFE, 10000); // cast it again after a short while, players can survive break; @@ -1102,7 +1101,7 @@ class boss_brain_of_yogg_saron : public CreatureScript uint8 illusion = _instance->GetData(DATA_ILLUSION); if (++_tentaclesKilled >= (illusion == ICECROWN_ILLUSION ? 9 : 8)) { - sCreatureTextMgr->SendChat(me, EMOTE_BRAIN_ILLUSION_SHATTERED, NULL, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_AREA); + sCreatureTextMgr->SendChat(me, EMOTE_BRAIN_ILLUSION_SHATTERED, nullptr, CHAT_MSG_ADDON, LANG_ADDON, TEXT_RANGE_AREA); _summons.DespawnAll(); DoCastAOE(SPELL_SHATTERED_ILLUSION, true); _instance->HandleGameObject(_instance->GetGuidData(GO_BRAIN_ROOM_DOOR_1 + illusion), true); @@ -2070,9 +2069,7 @@ class spell_yogg_saron_malady_of_the_mind : public SpellScriptLoader // 63830 bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MALADY_OF_THE_MIND_JUMP)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MALADY_OF_THE_MIND_JUMP }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2142,11 +2139,7 @@ class spell_yogg_saron_brain_link : public SpellScriptLoader // 63802 bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BRAIN_LINK_DAMAGE)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_BRAIN_LINK_NO_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BRAIN_LINK_DAMAGE, SPELL_BRAIN_LINK_NO_DAMAGE }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2240,9 +2233,7 @@ class spell_yogg_saron_boil_ominously : public SpellScriptLoader // 63030 bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_GUARDIAN_1)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_GUARDIAN_1 }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2341,15 +2332,13 @@ class spell_yogg_saron_empowering_shadows_missile : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_EMPOWERING_SHADOWS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_EMPOWERING_SHADOWS }); } void HandleScript(SpellEffIndex /*effIndex*/) { if (Unit* target = GetHitUnit()) - target->CastSpell((Unit*)NULL, SPELL_EMPOWERING_SHADOWS, true); + target->CastSpell((Unit*)nullptr, SPELL_EMPOWERING_SHADOWS, true); } void Register() override @@ -2376,9 +2365,7 @@ class spell_yogg_saron_constrictor_tentacle : public SpellScriptLoader // 64 bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CONSTRICTOR_TENTACLE_SUMMON)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CONSTRICTOR_TENTACLE_SUMMON }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2409,9 +2396,7 @@ class spell_yogg_saron_lunge : public SpellScriptLoader // 64131 bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SQUEEZE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SQUEEZE }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -2504,11 +2489,7 @@ class spell_yogg_saron_empowered : public SpellScriptLoader // 64161 bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_EMPOWERED_BUFF)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_WEAKENED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_EMPOWERED_BUFF, SPELL_WEAKENED }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2609,11 +2590,7 @@ class spell_yogg_saron_death_ray_warning_visual : public SpellScriptLoader / bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DEATH_RAY_PERIODIC)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_DEATH_RAY_DAMAGE_VISUAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DEATH_RAY_PERIODIC, SPELL_DEATH_RAY_DAMAGE_VISUAL }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2621,7 +2598,7 @@ class spell_yogg_saron_death_ray_warning_visual : public SpellScriptLoader / if (Unit* caster = GetCaster()) { caster->CastSpell(caster, SPELL_DEATH_RAY_PERIODIC, true); - caster->CastSpell((Unit*)NULL, SPELL_DEATH_RAY_DAMAGE_VISUAL, true); + caster->CastSpell((Unit*)nullptr, SPELL_DEATH_RAY_DAMAGE_VISUAL, true); // TODO: set better movement caster->GetMotionMaster()->MoveConfused(); } @@ -2650,9 +2627,7 @@ class spell_yogg_saron_cancel_illusion_room_aura : public SpellScriptLoader / bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TELEPORT_BACK_TO_MAIN_ROOM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TELEPORT_BACK_TO_MAIN_ROOM }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -2713,11 +2688,7 @@ class spell_yogg_saron_revealed_tentacle : public SpellScriptLoader // 64012 bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TENTACLE_VOID_ZONE)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_GRIM_REPRISAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TENTACLE_VOID_ZONE, SPELL_GRIM_REPRISAL }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -2753,9 +2724,7 @@ class spell_yogg_saron_grim_reprisal : public SpellScriptLoader // 63305 bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GRIM_REPRISAL_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_GRIM_REPRISAL_DAMAGE }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2792,11 +2761,7 @@ class spell_yogg_saron_induce_madness : public SpellScriptLoader // 64059 bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TELEPORT_BACK_TO_MAIN_ROOM)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_SHATTERED_ILLUSION_REMOVE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TELEPORT_BACK_TO_MAIN_ROOM, SPELL_SHATTERED_ILLUSION_REMOVE }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -2811,7 +2776,7 @@ class spell_yogg_saron_induce_madness : public SpellScriptLoader // 64059 void ClearShatteredIllusion() { - GetCaster()->CastSpell((Unit*)NULL, SPELL_SHATTERED_ILLUSION_REMOVE); + GetCaster()->CastSpell((Unit*)nullptr, SPELL_SHATTERED_ILLUSION_REMOVE); if (InstanceScript* instance = GetCaster()->GetInstanceScript()) if (Creature* voice = instance->GetCreature(DATA_VOICE_OF_YOGG_SARON)) @@ -2859,11 +2824,7 @@ class spell_yogg_saron_sanity : public SpellScriptLoader // 63050 bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_LOW_SANITY_SCREEN_EFFECT)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_INSANE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_LOW_SANITY_SCREEN_EFFECT, SPELL_INSANE }); } void DummyTick(AuraEffect const* /*aurEff*/) @@ -2918,9 +2879,7 @@ class spell_yogg_saron_insane : public SpellScriptLoader // 63120 bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_INSANE_VISUAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_INSANE_VISUAL }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -3160,9 +3119,7 @@ class spell_yogg_saron_hodirs_protective_gaze : public SpellScriptLoader // bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FLASH_FREEZE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FLASH_FREEZE }); } bool CanApply(Unit* target) diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/instance_ulduar.cpp b/src/server/scripts/Northrend/Ulduar/Ulduar/instance_ulduar.cpp index 2280a176d97..5d1e43a7289 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/instance_ulduar.cpp +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/instance_ulduar.cpp @@ -15,14 +15,20 @@ * with this program. If not, see . */ -#include "InstanceScript.h" -#include "Vehicle.h" -#include "Player.h" -#include "ScriptedCreature.h" #include "ScriptMgr.h" +#include "AreaBoundary.h" +#include "CreatureAI.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Item.h" +#include "Map.h" +#include "Player.h" +#include "Spell.h" #include "SpellScript.h" -#include "WorldPacket.h" +#include "TemporarySummon.h" #include "ulduar.h" +#include "Vehicle.h" +#include "WorldPacket.h" static BossBoundaryData const boundaries = { @@ -885,7 +891,7 @@ class instance_ulduar : public InstanceMapScript return 0; } - bool CheckAchievementCriteriaMeet(uint32 criteriaId, Player const*, Unit const* /* = NULL */, uint32 /* = 0 */) override + bool CheckAchievementCriteriaMeet(uint32 criteriaId, Player const*, Unit const* /* = nullptr */, uint32 /* = 0 */) override { switch (criteriaId) { diff --git a/src/server/scripts/Northrend/Ulduar/Ulduar/ulduar.h b/src/server/scripts/Northrend/Ulduar/Ulduar/ulduar.h index ad8197e5df0..f9a68f81d52 100644 --- a/src/server/scripts/Northrend/Ulduar/Ulduar/ulduar.h +++ b/src/server/scripts/Northrend/Ulduar/Ulduar/ulduar.h @@ -18,6 +18,8 @@ #ifndef DEF_ULDUAR_H #define DEF_ULDUAR_H +#include "CreatureAIImpl.h" + #define UlduarScriptName "instance_ulduar" #define DataHeader "UU" @@ -490,8 +492,8 @@ enum YoggSaronIllusions STORMWIND_ILLUSION = 2, }; -template -AI* GetUlduarAI(T* obj) +template +inline AI* GetUlduarAI(T* obj) { return GetInstanceAI(obj, UlduarScriptName); } diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_ingvar_the_plunderer.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_ingvar_the_plunderer.cpp index b5822a294e2..6ce42de7f1f 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_ingvar_the_plunderer.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_ingvar_the_plunderer.cpp @@ -23,9 +23,12 @@ SDCategory: Utgarde Keep EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "Spell.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" #include "utgarde_keep.h" enum Yells @@ -406,7 +409,7 @@ class npc_ingvar_throw_dummy : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_ingvar_throw_dummyAI(creature); + return GetUtgardeKeepAI(creature); } }; @@ -449,9 +452,7 @@ class spell_ingvar_woe_strike : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WOE_STRIKE_EFFECT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WOE_STRIKE_EFFECT }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -466,7 +467,7 @@ class spell_ingvar_woe_strike : public SpellScriptLoader void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); - GetTarget()->CastSpell(eventInfo.GetActor(), SPELL_WOE_STRIKE_EFFECT, true, NULL, aurEff); + GetTarget()->CastSpell(eventInfo.GetActor(), SPELL_WOE_STRIKE_EFFECT, true, nullptr, aurEff); } void Register() override diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_keleseth.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_keleseth.cpp index 373a6d8eaa1..64b70c802ed 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_keleseth.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_keleseth.cpp @@ -23,9 +23,12 @@ SDCategory: Utgarde Keep EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "SpellAuras.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" #include "utgarde_keep.h" enum KelsethEncounter diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_skarvald_dalronn.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_skarvald_dalronn.cpp index 487f2893815..0a7b2594f23 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_skarvald_dalronn.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/boss_skarvald_dalronn.cpp @@ -23,6 +23,8 @@ SDCategory: Utgarde Keep EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "utgarde_keep.h" diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/instance_utgarde_keep.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/instance_utgarde_keep.cpp index 6097521b0b9..ae4b11fdb42 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/instance_utgarde_keep.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/instance_utgarde_keep.cpp @@ -16,7 +16,10 @@ */ #include "ScriptMgr.h" +#include "Creature.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" #include "utgarde_keep.h" DoorData const doorData[] = @@ -85,6 +88,8 @@ class instance_utgarde_keep : public InstanceMapScript void OnGameObjectCreate(GameObject* go) override { + InstanceScript::OnGameObjectCreate(go); + switch (go->GetEntry()) { case GO_BELLOW_1: @@ -123,23 +128,6 @@ class instance_utgarde_keep : public InstanceMapScript Forges[2].AnvilGUID = go->GetGUID(); HandleGameObject(ObjectGuid::Empty, Forges[2].Event != NOT_STARTED, go); break; - case GO_GIANT_PORTCULLIS_1: - case GO_GIANT_PORTCULLIS_2: - AddDoor(go, true); - break; - default: - break; - } - } - - void OnGameObjectRemove(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_GIANT_PORTCULLIS_1: - case GO_GIANT_PORTCULLIS_2: - AddDoor(go, false); - break; default: break; } diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/utgarde_keep.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/utgarde_keep.cpp index d175b13ffbc..a257f212a61 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/utgarde_keep.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/utgarde_keep.cpp @@ -16,15 +16,13 @@ */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "ScriptedCreature.h" -#include "utgarde_keep.h" +#include "SpellInfo.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" - -enum Spells -{ - SPELL_UK_SECOUND_WIND_TRIGGER = 42771 -}; +#include "utgarde_keep.h" uint32 ForgeSearch[3] = { @@ -135,9 +133,7 @@ class spell_ticking_time_bomb : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TICKING_TIME_BOMB_EXPLODE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TICKING_TIME_BOMB_EXPLODE }); } void HandleOnEffectRemove(AuraEffect const* /* aurEff */, AuraEffectHandleModes /* mode */) @@ -174,9 +170,7 @@ class spell_fixate : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FIXATE_TRIGGER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FIXATE_TRIGGER }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -213,9 +207,7 @@ class spell_uk_second_wind : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SECOND_WIND_TRIGGER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SECOND_WIND_TRIGGER }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -347,7 +339,7 @@ class npc_enslaved_proto_drake : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_enslaved_proto_drakeAI(creature); + return GetUtgardeKeepAI(creature); } }; diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/utgarde_keep.h b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/utgarde_keep.h index 2fc8b6e8940..2b7a5470d68 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/utgarde_keep.h +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/utgarde_keep.h @@ -18,6 +18,8 @@ #ifndef UTGARDE_KEEP_H_ #define UTGARDE_KEEP_H_ +#include "CreatureAIImpl.h" + #define UKScriptName "instance_utgarde_keep" #define DataHeader "UK" @@ -85,10 +87,10 @@ struct ForgeInfo uint32 Event; }; -template -AI* GetUtgardeKeepAI(Creature* creature) +template +inline AI* GetUtgardeKeepAI(T* obj) { - return GetInstanceAI(creature, UKScriptName); + return GetInstanceAI(obj, UKScriptName); } #endif // UTGARDE_KEEP_H_ diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_palehoof.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_palehoof.cpp index b2b5364e087..74f9ec29462 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_palehoof.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_palehoof.cpp @@ -16,11 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "utgarde_pinnacle.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "InstanceScript.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "utgarde_pinnacle.h" enum Spells { @@ -558,19 +562,20 @@ public: struct go_palehoof_sphereAI : public GameObjectAI { - go_palehoof_sphereAI(GameObject* go) : GameObjectAI(go) { } + go_palehoof_sphereAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* /*player*/) override { - if (InstanceScript* instance = me->GetInstanceScript()) + if (Creature* palehoof = instance->GetCreature(DATA_GORTOK_PALEHOOF)) { - if (Creature* palehoof = instance->GetCreature(DATA_GORTOK_PALEHOOF)) - if (palehoof->IsAlive() && instance->GetBossState(DATA_GORTOK_PALEHOOF) != DONE) - { - me->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); - me->SetGoState(GO_STATE_ACTIVE); - palehoof->AI()->DoAction(ACTION_START_ENCOUNTER); - } + if (palehoof->IsAlive() && instance->GetBossState(DATA_GORTOK_PALEHOOF) != DONE) + { + me->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); + me->SetGoState(GO_STATE_ACTIVE); + palehoof->AI()->DoAction(ACTION_START_ENCOUNTER); + } } return true; } @@ -578,7 +583,7 @@ public: GameObjectAI* GetAI(GameObject* go) const override { - return new go_palehoof_sphereAI(go); + return GetUtgardePinnacleAI(go); } }; @@ -619,9 +624,7 @@ class spell_palehoof_crazed_effect : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CRAZED_TAUNT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CRAZED_TAUNT }); } void HandleScriptEffect(SpellEffIndex /* effIndex */) @@ -653,9 +656,7 @@ class spell_palehoof_awaken_subboss : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ORB_CHANNEL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ORB_CHANNEL }); } void HandleScript(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_skadi.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_skadi.cpp index 9af1b2044b5..50c33ba78b3 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_skadi.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_skadi.cpp @@ -16,13 +16,16 @@ */ #include "ScriptMgr.h" +#include "GridNotifiers.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "MoveSplineInit.h" +#include "Player.h" #include "ScriptedCreature.h" #include "SpellAuras.h" #include "SpellScript.h" +#include "TemporarySummon.h" #include "utgarde_pinnacle.h" -#include "GridNotifiers.h" -#include "Player.h" -#include "MoveSplineInit.h" enum Spells { @@ -322,7 +325,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetUtgardePinnacleAI(creature); } }; @@ -437,7 +440,7 @@ public: } } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_LAUNCH_HARPOON) if (Creature* skadi = _instance->GetCreature(DATA_SKADI_THE_RUTHLESS)) @@ -456,7 +459,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetUtgardePinnacleAI(creature); } }; @@ -552,7 +555,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetUtgardePinnacleAI(creature); } }; @@ -583,7 +586,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetUtgardePinnacleAI(creature); } }; @@ -620,7 +623,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetUtgardePinnacleAI(creature); } }; @@ -635,9 +638,7 @@ class spell_freezing_cloud_area_right : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FREEZING_CLOUD)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FREEZING_CLOUD }); } void FilterTargets(std::list& targets) @@ -674,9 +675,7 @@ class spell_freezing_cloud_area_left : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FREEZING_CLOUD)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FREEZING_CLOUD }); } void FilterTargets(std::list& targets) @@ -822,9 +821,7 @@ class spell_skadi_poisoned_spear : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_POISONED_SPEAR_PERIODIC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_POISONED_SPEAR_PERIODIC }); } void HandleScript(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_svala.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_svala.cpp index 3c4b3330193..f6a04dcbb2e 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_svala.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_svala.cpp @@ -16,9 +16,14 @@ */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "SpellInfo.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "TemporarySummon.h" #include "utgarde_pinnacle.h" enum Spells diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_ymiron.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_ymiron.cpp index a4e4f8249c4..3f6a4bd4496 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_ymiron.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/boss_ymiron.cpp @@ -16,10 +16,13 @@ */ #include "ScriptMgr.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "utgarde_pinnacle.h" #include "SpellInfo.h" #include "SpellScript.h" +#include "TemporarySummon.h" +#include "utgarde_pinnacle.h" enum Spells { 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 b92f6ddf108..38917fda932 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/instance_utgarde_pinnacle.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/instance_utgarde_pinnacle.cpp @@ -16,7 +16,10 @@ */ #include "ScriptMgr.h" +#include "AreaBoundary.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" #include "utgarde_pinnacle.h" BossBoundaryData const boundaries = diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/utgarde_pinnacle.h b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/utgarde_pinnacle.h index b4731a87650..7b0a927a63a 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/utgarde_pinnacle.h +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/utgarde_pinnacle.h @@ -18,6 +18,8 @@ #ifndef UTGARDE_PINNACLE_H_ #define UTGARDE_PINNACLE_H_ +#include "CreatureAIImpl.h" + #define UPScriptName "instance_utgarde_pinnacle" #define DataHeader "UP" @@ -95,10 +97,10 @@ enum UPGameObjectIds GO_KING_YMIRON_DOOR = 192174 }; -template -AI* GetUtgardePinnacleAI(Creature* creature) +template +inline AI* GetUtgardePinnacleAI(T* obj) { - return GetInstanceAI(creature, UPScriptName); + return GetInstanceAI(obj, UPScriptName); } #endif // UTGARDE_PINNACLE_H_ diff --git a/src/server/scripts/Northrend/VaultOfArchavon/boss_archavon.cpp b/src/server/scripts/Northrend/VaultOfArchavon/boss_archavon.cpp index 59c9bc7d3dc..8ea14ab909c 100644 --- a/src/server/scripts/Northrend/VaultOfArchavon/boss_archavon.cpp +++ b/src/server/scripts/Northrend/VaultOfArchavon/boss_archavon.cpp @@ -138,7 +138,7 @@ class boss_archavon : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_archavonAI(creature); + return GetVaultOfArchavonAI(creature); } }; @@ -212,7 +212,7 @@ class npc_archavon_warder : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_archavon_warderAI(creature); + return GetVaultOfArchavonAI(creature); } }; @@ -228,12 +228,13 @@ class spell_archavon_rock_shards : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROCK_SHARDS_VISUAL_L) - || !sSpellMgr->GetSpellInfo(SPELL_ROCK_SHARDS_VISUAL_R) - || !sSpellMgr->GetSpellInfo(SPELL_ROCK_SHARDS_DAMAGE_L) - || !sSpellMgr->GetSpellInfo(SPELL_ROCK_SHARDS_DAMAGE_R)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_ROCK_SHARDS_VISUAL_L, + SPELL_ROCK_SHARDS_VISUAL_R, + SPELL_ROCK_SHARDS_DAMAGE_L, + SPELL_ROCK_SHARDS_DAMAGE_R + }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -242,12 +243,12 @@ class spell_archavon_rock_shards : public SpellScriptLoader for (uint8 i = 0; i < 3; ++i) { - caster->CastSpell((Unit*)NULL, SPELL_ROCK_SHARDS_VISUAL_L, true); - caster->CastSpell((Unit*)NULL, SPELL_ROCK_SHARDS_VISUAL_R, true); + caster->CastSpell((Unit*)nullptr, SPELL_ROCK_SHARDS_VISUAL_L, true); + caster->CastSpell((Unit*)nullptr, SPELL_ROCK_SHARDS_VISUAL_R, true); } - caster->CastSpell((Unit*)NULL, SPELL_ROCK_SHARDS_DAMAGE_L, true); - caster->CastSpell((Unit*)NULL, SPELL_ROCK_SHARDS_DAMAGE_R, true); + caster->CastSpell((Unit*)nullptr, SPELL_ROCK_SHARDS_DAMAGE_L, true); + caster->CastSpell((Unit*)nullptr, SPELL_ROCK_SHARDS_DAMAGE_R, true); } void Register() override diff --git a/src/server/scripts/Northrend/VaultOfArchavon/boss_emalon.cpp b/src/server/scripts/Northrend/VaultOfArchavon/boss_emalon.cpp index 042a473f0e0..f2270f4fb05 100644 --- a/src/server/scripts/Northrend/VaultOfArchavon/boss_emalon.cpp +++ b/src/server/scripts/Northrend/VaultOfArchavon/boss_emalon.cpp @@ -16,6 +16,8 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellAuras.h" #include "vault_of_archavon.h" @@ -92,7 +94,7 @@ class boss_emalon : public CreatureScript { BossAI::JustSummoned(summoned); - // AttackStart has NULL-check for victim + // AttackStart has nullptr-check for victim if (summoned->AI()) summoned->AI()->AttackStart(me->GetVictim()); } @@ -171,7 +173,7 @@ class boss_emalon : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_emalonAI(creature); + return GetVaultOfArchavonAI(creature); } }; @@ -277,7 +279,7 @@ class npc_tempest_minion : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetVaultOfArchavonAI(creature); } }; diff --git a/src/server/scripts/Northrend/VaultOfArchavon/boss_koralon.cpp b/src/server/scripts/Northrend/VaultOfArchavon/boss_koralon.cpp index 0ef5645b2c6..c04e390bca0 100644 --- a/src/server/scripts/Northrend/VaultOfArchavon/boss_koralon.cpp +++ b/src/server/scripts/Northrend/VaultOfArchavon/boss_koralon.cpp @@ -17,7 +17,6 @@ #include "ScriptMgr.h" #include "ScriptedCreature.h" -#include "SpellAuraEffects.h" #include "SpellScript.h" #include "vault_of_archavon.h" @@ -117,7 +116,7 @@ class boss_koralon : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_koralonAI(creature); + return GetVaultOfArchavonAI(creature); } }; @@ -181,7 +180,7 @@ class npc_flame_warder : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_flame_warderAI(creature); + return GetVaultOfArchavonAI(creature); } }; @@ -196,15 +195,13 @@ class spell_koralon_meteor_fists : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_METEOR_FISTS_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_METEOR_FISTS_DAMAGE }); } void TriggerFists(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); - GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_METEOR_FISTS_DAMAGE, true, NULL, aurEff); + GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_METEOR_FISTS_DAMAGE, true, nullptr, aurEff); } void Register() override @@ -273,15 +270,13 @@ class spell_flame_warder_meteor_fists : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FW_METEOR_FISTS_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FW_METEOR_FISTS_DAMAGE }); } void TriggerFists(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); - GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_FW_METEOR_FISTS_DAMAGE, true, NULL, aurEff); + GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_FW_METEOR_FISTS_DAMAGE, true, nullptr, aurEff); } void Register() override diff --git a/src/server/scripts/Northrend/VaultOfArchavon/boss_toravon.cpp b/src/server/scripts/Northrend/VaultOfArchavon/boss_toravon.cpp index ede24ae8f53..2ff14155505 100644 --- a/src/server/scripts/Northrend/VaultOfArchavon/boss_toravon.cpp +++ b/src/server/scripts/Northrend/VaultOfArchavon/boss_toravon.cpp @@ -16,6 +16,8 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "vault_of_archavon.h" @@ -117,7 +119,7 @@ class boss_toravon : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_toravonAI(creature); + return GetVaultOfArchavonAI(creature); } }; @@ -172,7 +174,7 @@ class npc_frost_warder : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_frost_warderAI(creature); + return GetVaultOfArchavonAI(creature); } }; @@ -233,7 +235,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_frozen_orbAI(creature); + return GetVaultOfArchavonAI(creature); } }; @@ -287,7 +289,7 @@ class npc_frozen_orb_stalker : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetVaultOfArchavonAI(creature); } }; diff --git a/src/server/scripts/Northrend/VaultOfArchavon/instance_vault_of_archavon.cpp b/src/server/scripts/Northrend/VaultOfArchavon/instance_vault_of_archavon.cpp index 16e972a5ef7..309d9c61683 100644 --- a/src/server/scripts/Northrend/VaultOfArchavon/instance_vault_of_archavon.cpp +++ b/src/server/scripts/Northrend/VaultOfArchavon/instance_vault_of_archavon.cpp @@ -16,7 +16,9 @@ */ #include "ScriptMgr.h" +#include "GameTime.h" #include "InstanceScript.h" +#include "Map.h" #include "vault_of_archavon.h" /* Vault of Archavon encounters: @@ -26,10 +28,19 @@ 4 - Toravon the Ice Watcher event */ +ObjectData const creatureData[] = +{ + { NPC_ARCHAVON, DATA_ARCHAVON }, + { NPC_EMALON, DATA_EMALON }, + { NPC_KORALON, DATA_KORALON }, + { NPC_TORAVON, DATA_TORAVON }, + { 0, 0, } +}; + class instance_vault_of_archavon : public InstanceMapScript { public: - instance_vault_of_archavon() : InstanceMapScript("instance_vault_of_archavon", 624) { } + instance_vault_of_archavon() : InstanceMapScript(VoAScriptName, 624) { } struct instance_vault_of_archavon_InstanceMapScript : public InstanceScript { @@ -37,42 +48,13 @@ class instance_vault_of_archavon : public InstanceMapScript { SetHeaders(DataHeader); SetBossNumber(EncounterCount); + LoadObjectData(creatureData, nullptr); ArchavonDeath = 0; EmalonDeath = 0; KoralonDeath = 0; } - void OnCreatureCreate(Creature* creature) override - { - switch (creature->GetEntry()) - { - case NPC_EMALON: - EmalonGUID = creature->GetGUID(); - break; - case NPC_TORAVON: - ToravonGUID = creature->GetGUID(); - break; - default: - break; - } - } - - ObjectGuid GetGuidData(uint32 identifier) const override - { - switch (identifier) - { - case DATA_EMALON: - return EmalonGUID; - case DATA_TORAVON: - return ToravonGUID; - default: - break; - } - - return ObjectGuid::Empty; - } - bool SetBossState(uint32 type, EncounterState state) override { if (!InstanceScript::SetBossState(type, state)) @@ -84,13 +66,13 @@ class instance_vault_of_archavon : public InstanceMapScript switch (type) { case DATA_ARCHAVON: - ArchavonDeath = time(NULL); + ArchavonDeath = GameTime::GetGameTime(); break; case DATA_EMALON: - EmalonDeath = time(NULL); + EmalonDeath = GameTime::GetGameTime(); break; case DATA_KORALON: - KoralonDeath = time(NULL); + KoralonDeath = GameTime::GetGameTime(); break; default: return true; @@ -125,8 +107,6 @@ class instance_vault_of_archavon : public InstanceMapScript } private: - ObjectGuid EmalonGUID; - ObjectGuid ToravonGUID; time_t ArchavonDeath; time_t EmalonDeath; time_t KoralonDeath; diff --git a/src/server/scripts/Northrend/VaultOfArchavon/vault_of_archavon.h b/src/server/scripts/Northrend/VaultOfArchavon/vault_of_archavon.h index 750e7c4649e..65e55e104c3 100644 --- a/src/server/scripts/Northrend/VaultOfArchavon/vault_of_archavon.h +++ b/src/server/scripts/Northrend/VaultOfArchavon/vault_of_archavon.h @@ -18,6 +18,9 @@ #ifndef DEF_ARCHAVON_H #define DEF_ARCHAVON_H +#include "CreatureAIImpl.h" + +#define VoAScriptName "instance_vault_of_archavon" #define DataHeader "VA" uint32 const EncounterCount = 4; @@ -27,7 +30,7 @@ enum VAData DATA_ARCHAVON = 0, DATA_EMALON = 1, DATA_KORALON = 2, - DATA_TORAVON = 3, + DATA_TORAVON = 3 }; enum VACreatureIds @@ -41,12 +44,18 @@ enum VACreatureIds enum VAAchievementCriteriaIds { CRITERIA_EARTH_WIND_FIRE_10 = 12018, - CRITERIA_EARTH_WIND_FIRE_25 = 12019, + CRITERIA_EARTH_WIND_FIRE_25 = 12019 }; enum VAAchievementSpells { - SPELL_EARTH_WIND_FIRE_ACHIEVEMENT_CHECK = 68308, + SPELL_EARTH_WIND_FIRE_ACHIEVEMENT_CHECK = 68308 }; +template +inline AI* GetVaultOfArchavonAI(T* obj) +{ + return GetInstanceAI(obj, VoAScriptName); +} + #endif diff --git a/src/server/scripts/Northrend/VioletHold/boss_cyanigosa.cpp b/src/server/scripts/Northrend/VioletHold/boss_cyanigosa.cpp index 49139c9c2b5..fab3265b7d1 100644 --- a/src/server/scripts/Northrend/VioletHold/boss_cyanigosa.cpp +++ b/src/server/scripts/Northrend/VioletHold/boss_cyanigosa.cpp @@ -16,6 +16,7 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "SpellScript.h" #include "ScriptedCreature.h" #include "violet_hold.h" @@ -154,9 +155,7 @@ class spell_cyanigosa_arcane_vacuum : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_PLAYER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_PLAYER }); } void HandleScript(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/VioletHold/boss_erekem.cpp b/src/server/scripts/Northrend/VioletHold/boss_erekem.cpp index 453e947fa8f..1ac10fe4e1f 100644 --- a/src/server/scripts/Northrend/VioletHold/boss_erekem.cpp +++ b/src/server/scripts/Northrend/VioletHold/boss_erekem.cpp @@ -16,6 +16,9 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "violet_hold.h" diff --git a/src/server/scripts/Northrend/VioletHold/boss_ichoron.cpp b/src/server/scripts/Northrend/VioletHold/boss_ichoron.cpp index 4788524ba5a..ed6be37b23a 100644 --- a/src/server/scripts/Northrend/VioletHold/boss_ichoron.cpp +++ b/src/server/scripts/Northrend/VioletHold/boss_ichoron.cpp @@ -16,8 +16,10 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "ScriptedCreature.h" -#include "SpellAuraEffects.h" +#include "SpellAuras.h" #include "SpellScript.h" #include "violet_hold.h" @@ -351,9 +353,7 @@ class spell_ichoron_merge : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHRINK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHRINK }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -426,14 +426,15 @@ class spell_ichoron_splatter : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WATER_GLOBULE_SUMMON_1) - || !sSpellMgr->GetSpellInfo(SPELL_WATER_GLOBULE_SUMMON_2) - || !sSpellMgr->GetSpellInfo(SPELL_WATER_GLOBULE_SUMMON_3) - || !sSpellMgr->GetSpellInfo(SPELL_WATER_GLOBULE_SUMMON_4) - || !sSpellMgr->GetSpellInfo(SPELL_WATER_GLOBULE_SUMMON_5) - || !sSpellMgr->GetSpellInfo(SPELL_SHRINK)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_WATER_GLOBULE_SUMMON_1, + SPELL_WATER_GLOBULE_SUMMON_2, + SPELL_WATER_GLOBULE_SUMMON_3, + SPELL_WATER_GLOBULE_SUMMON_4, + SPELL_WATER_GLOBULE_SUMMON_5, + SPELL_SHRINK + }); } void PeriodicTick(AuraEffect const* /*aurEff*/) diff --git a/src/server/scripts/Northrend/VioletHold/boss_lavanthor.cpp b/src/server/scripts/Northrend/VioletHold/boss_lavanthor.cpp index 2a2bf143308..f616eec7b17 100644 --- a/src/server/scripts/Northrend/VioletHold/boss_lavanthor.cpp +++ b/src/server/scripts/Northrend/VioletHold/boss_lavanthor.cpp @@ -16,6 +16,7 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "violet_hold.h" diff --git a/src/server/scripts/Northrend/VioletHold/boss_moragg.cpp b/src/server/scripts/Northrend/VioletHold/boss_moragg.cpp index 45ac551d94c..df108c4b348 100644 --- a/src/server/scripts/Northrend/VioletHold/boss_moragg.cpp +++ b/src/server/scripts/Northrend/VioletHold/boss_moragg.cpp @@ -16,9 +16,10 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" +#include "SpellScript.h" #include "violet_hold.h" enum Spells diff --git a/src/server/scripts/Northrend/VioletHold/boss_xevozz.cpp b/src/server/scripts/Northrend/VioletHold/boss_xevozz.cpp index 7d08c7127c8..9802ff1bb44 100644 --- a/src/server/scripts/Northrend/VioletHold/boss_xevozz.cpp +++ b/src/server/scripts/Northrend/VioletHold/boss_xevozz.cpp @@ -16,10 +16,12 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "Player.h" #include "ScriptedCreature.h" #include "SpellInfo.h" #include "SpellScript.h" -#include "Player.h" #include "violet_hold.h" /* @@ -261,9 +263,7 @@ class spell_xevozz_summon_players : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGIC_PULL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGIC_PULL }); } void HandleScript(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/VioletHold/boss_zuramat.cpp b/src/server/scripts/Northrend/VioletHold/boss_zuramat.cpp index 3bb87569812..066787e9af4 100644 --- a/src/server/scripts/Northrend/VioletHold/boss_zuramat.cpp +++ b/src/server/scripts/Northrend/VioletHold/boss_zuramat.cpp @@ -16,6 +16,7 @@ */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" #include "violet_hold.h" diff --git a/src/server/scripts/Northrend/VioletHold/instance_violet_hold.cpp b/src/server/scripts/Northrend/VioletHold/instance_violet_hold.cpp index 64178c66a3a..0e75ac08002 100644 --- a/src/server/scripts/Northrend/VioletHold/instance_violet_hold.cpp +++ b/src/server/scripts/Northrend/VioletHold/instance_violet_hold.cpp @@ -16,11 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" #include "InstanceScript.h" -#include "WorldPacket.h" -#include "violet_hold.h" +#include "Map.h" +#include "MotionMaster.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" +#include "violet_hold.h" +#include "WorldPacket.h" /* * TODO: @@ -65,7 +69,7 @@ Position const PortalIntroPositions[PortalIntroPositionsSize] = // sniff uint32 const EncouterPortalsCount = PortalPositionsSize + PortalElitePositionsSize; uint32 const MoraggPathSize = 3; -G3D::Vector3 const MoraggPath[MoraggPathSize] = // sniff +Position const MoraggPath[MoraggPathSize] = // sniff { { 1893.895f, 728.1261f, 47.75016f }, { 1892.997f, 738.4987f, 47.66684f }, @@ -73,7 +77,7 @@ G3D::Vector3 const MoraggPath[MoraggPathSize] = // sniff }; uint32 const ErekemPathSize = 3; -G3D::Vector3 const ErekemPath[ErekemPathSize] = // sniff +Position const ErekemPath[ErekemPathSize] = // sniff { { 1871.456f, 871.0361f, 43.41524f }, { 1874.948f, 859.5452f, 43.33349f }, @@ -81,7 +85,7 @@ G3D::Vector3 const ErekemPath[ErekemPathSize] = // sniff }; uint32 const ErekemGuardLeftPathSize = 3; -G3D::Vector3 const ErekemGuardLeftPath[ErekemGuardLeftPathSize] = // sniff +Position const ErekemGuardLeftPath[ErekemGuardLeftPathSize] = // sniff { { 1853.752f, 862.4528f, 43.41614f }, { 1866.931f, 854.577f, 43.3335f }, @@ -89,7 +93,7 @@ G3D::Vector3 const ErekemGuardLeftPath[ErekemGuardLeftPathSize] = // sniff }; uint32 const ErekemGuardRightPathSize = 3; -G3D::Vector3 const ErekemGuardRightPath[ErekemGuardRightPathSize] = // sniff +Position const ErekemGuardRightPath[ErekemGuardRightPathSize] = // sniff { { 1892.418f, 872.2831f, 43.41563f }, { 1885.639f, 859.0245f, 43.3335f }, @@ -97,7 +101,7 @@ G3D::Vector3 const ErekemGuardRightPath[ErekemGuardRightPathSize] = // sniff }; uint32 const IchoronPathSize = 5; -G3D::Vector3 const IchoronPath[IchoronPathSize] = // sniff +Position const IchoronPath[IchoronPathSize] = // sniff { { 1942.041f, 749.5228f, 30.95229f }, { 1930.571f, 762.9065f, 31.98814f }, @@ -107,7 +111,7 @@ G3D::Vector3 const IchoronPath[IchoronPathSize] = // sniff }; uint32 const LavanthorPathSize = 3; -G3D::Vector3 const LavanthorPath[LavanthorPathSize] = // sniff +Position const LavanthorPath[LavanthorPathSize] = // sniff { { 1844.557f, 748.7083f, 38.74205f }, { 1854.618f, 761.5295f, 38.65631f }, @@ -115,7 +119,7 @@ G3D::Vector3 const LavanthorPath[LavanthorPathSize] = // sniff }; uint32 const XevozzPathSize = 3; -G3D::Vector3 const XevozzPath[XevozzPathSize] = // sniff +Position const XevozzPath[XevozzPathSize] = // sniff { { 1908.417f, 845.8502f, 38.71947f }, { 1905.557f, 841.3157f, 38.65529f }, @@ -123,7 +127,7 @@ G3D::Vector3 const XevozzPath[XevozzPathSize] = // sniff }; uint32 const ZuramatPathSize = 3; -G3D::Vector3 const ZuramatPath[ZuramatPathSize] = // sniff +Position const ZuramatPath[ZuramatPathSize] = // sniff { { 1934.151f, 860.9463f, 47.29499f }, { 1927.085f, 852.1342f, 47.19214f }, @@ -330,11 +334,11 @@ class instance_violet_hold : public InstanceMapScript { case DATA_1ST_BOSS: if (state == DONE) - UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, NPC_EREKEM, nullptr); + UpdateEncounterStateForKilledCreature(NPC_EREKEM, nullptr); break; case DATA_2ND_BOSS: if (state == DONE) - UpdateEncounterState(ENCOUNTER_CREDIT_KILL_CREATURE, NPC_MORAGG, nullptr); + UpdateEncounterStateForKilledCreature(NPC_MORAGG, nullptr); break; case DATA_CYANIGOSA: if (state == DONE) diff --git a/src/server/scripts/Northrend/VioletHold/violet_hold.cpp b/src/server/scripts/Northrend/VioletHold/violet_hold.cpp index 2affe94ef2d..54573cf91c9 100644 --- a/src/server/scripts/Northrend/VioletHold/violet_hold.cpp +++ b/src/server/scripts/Northrend/VioletHold/violet_hold.cpp @@ -15,15 +15,19 @@ * with this program. If not, see . */ -#include "Player.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "Player.h" #include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" #include "SpellAuraEffects.h" #include "SpellScript.h" +#include "TemporarySummon.h" #include "violet_hold.h" -#include "GameObjectAI.h" /* * TODO: @@ -156,7 +160,7 @@ enum Sinclari SAY_SINCLARI_PORTAL_KEEPER = 2 }; -G3D::Vector3 const FirstPortalWPs[6] = +Position const FirstPortalWPs[] = { {1877.670288f, 842.280273f, 43.333591f}, {1877.338867f, 834.615356f, 38.762287f}, @@ -167,7 +171,7 @@ G3D::Vector3 const FirstPortalWPs[6] = //{1825.736084f, 807.305847f, 44.363785f} }; -G3D::Vector3 const SecondPortalFirstWPs[9] = +Position const SecondPortalFirstWPs[] = { {1902.561401f, 853.334656f, 47.106117f}, {1895.486084f, 855.376404f, 44.334591f}, @@ -181,7 +185,7 @@ G3D::Vector3 const SecondPortalFirstWPs[9] = //{1825.736084f, 807.305847f, 44.363785f} }; -G3D::Vector3 const SecondPortalSecondWPs[8] = +Position const SecondPortalSecondWPs[] = { {1929.392212f, 837.614990f, 47.136166f}, {1928.290649f, 824.750427f, 45.474411f}, @@ -194,7 +198,7 @@ G3D::Vector3 const SecondPortalSecondWPs[8] = //{1825.736084f, 807.305847f, 44.363785f} }; -G3D::Vector3 const ThirdPortalWPs[8] = +Position const ThirdPortalWPs[] = { {1934.049438f, 815.778503f, 52.408699f}, {1928.290649f, 824.750427f, 45.474411f}, @@ -207,7 +211,7 @@ G3D::Vector3 const ThirdPortalWPs[8] = //{1825.736084f, 807.305847f, 44.363785f} }; -G3D::Vector3 const FourthPortalWPs[9] = +Position const FourthPortalWPs[] = { {1921.658447f, 761.657043f, 50.866741f}, {1910.559814f, 755.780457f, 47.701447f}, @@ -221,7 +225,7 @@ G3D::Vector3 const FourthPortalWPs[9] = //{1827.100342f, 801.605957f, 44.363358f} }; -G3D::Vector3 const FifthPortalWPs[6] = +Position const FifthPortalWPs[] = { {1887.398804f, 763.633240f, 47.666851f}, {1879.020386f, 775.396973f, 38.705990f}, @@ -232,7 +236,7 @@ G3D::Vector3 const FifthPortalWPs[6] = //{1827.100342f, 801.605957f, 44.363358f} }; -G3D::Vector3 const SixthPoralWPs[4] = +Position const SixthPortalWPs[] = { {1888.861084f, 805.074768f, 38.375790f}, {1869.793823f, 804.135804f, 38.647018f}, @@ -241,13 +245,12 @@ G3D::Vector3 const SixthPoralWPs[4] = //{1826.889648f, 803.929993f, 44.363239f} }; -G3D::Vector3 const DefaultPortalWPs[1] = +Position const DefaultPortalWPs[] = { { 1843.567017f, 804.288208f, 44.139091f } }; -uint32 const SaboteurMoraggPathSize = 5; -G3D::Vector3 const SaboteurMoraggPath[SaboteurMoraggPathSize] = // sniff +Position const SaboteurMoraggPath[] = // sniff { { 1886.251f, 803.0743f, 38.42326f }, { 1885.71f, 799.8929f, 38.37241f }, @@ -256,8 +259,7 @@ G3D::Vector3 const SaboteurMoraggPath[SaboteurMoraggPathSize] = // sniff { 1894.603f, 739.9231f, 47.66684f }, }; -uint32 const SaboteurErekemPathSize = 5; -G3D::Vector3 const SaboteurErekemPath[SaboteurErekemPathSize] = // sniff +Position const SaboteurErekemPath[] = // sniff { { 1886.251f, 803.0743f, 38.42326f }, { 1881.047f, 829.6866f, 38.64856f }, @@ -266,24 +268,21 @@ G3D::Vector3 const SaboteurErekemPath[SaboteurErekemPathSize] = // sniff { 1873.747f, 864.1373f, 43.33349f } }; -uint32 const SaboteurIchoronPathSize = 3; -G3D::Vector3 const SaboteurIchoronPath[SaboteurIchoronPathSize] = // sniff +Position const SaboteurIchoronPath[] = // sniff { { 1886.251f, 803.0743f, 38.42326f }, { 1888.672f, 801.2348f, 38.42305f }, { 1901.987f, 793.3254f, 38.65126f } }; -uint32 const SaboteurLavanthorPathSize = 3; -G3D::Vector3 const SaboteurLavanthorPath[SaboteurLavanthorPathSize] = // sniff +Position const SaboteurLavanthorPath[] = // sniff { { 1886.251f, 803.0743f, 38.42326f }, { 1867.925f, 778.8035f, 38.64702f }, { 1853.304f, 759.0161f, 38.65761f } }; -uint32 const SaboteurXevozzPathSize = 4; -G3D::Vector3 const SaboteurXevozzPath[SaboteurXevozzPathSize] = // sniff +Position const SaboteurXevozzPath[] = // sniff { { 1886.251f, 803.0743f, 38.42326f }, { 1889.096f, 810.0487f, 38.43871f }, @@ -291,8 +290,7 @@ G3D::Vector3 const SaboteurXevozzPath[SaboteurXevozzPathSize] = // sniff { 1906.666f, 842.3111f, 38.63351f } }; -uint32 const SaboteurZuramatPathSize = 7; -G3D::Vector3 const SaboteurZuramatPath[SaboteurZuramatPathSize] = // sniff +Position const SaboteurZuramatPath[] = // sniff { { 1886.251f, 803.0743f, 38.42326f }, { 1889.69f, 807.0032f, 38.39914f }, @@ -349,21 +347,18 @@ class npc_sinclari_vh : public CreatureScript bool GossipHello(Player* player) override { // override default gossip - if (InstanceScript* instance = me->GetInstanceScript()) + switch (_instance->GetData(DATA_MAIN_EVENT_STATE)) { - switch (instance->GetData(DATA_MAIN_EVENT_STATE)) - { - case IN_PROGRESS: - player->PrepareGossipMenu(me, GOSSIP_MENU_SEND_ME_IN, true); - player->SendPreparedGossip(me); - return true; - case DONE: - return true; // NYI - case NOT_STARTED: - case FAIL: - default: - break; - } + case IN_PROGRESS: + player->PrepareGossipMenu(me, GOSSIP_MENU_SEND_ME_IN, true); + player->SendPreparedGossip(me); + return true; + case DONE: + return true; // NYI + case NOT_STARTED: + case FAIL: + default: + break; } // load default gossip @@ -546,41 +541,35 @@ class npc_azure_saboteur : public CreatureScript _bossId = _instance->GetData(DATA_2ND_BOSS); } + template + void StartSmoothPath(Position const (&path)[N]) + { + me->GetMotionMaster()->MoveSmoothPath(POINT_INTRO, &path[0], N, false); + } + void StartMovement() { - uint32 pathSize = 0; - G3D::Vector3 const* path = nullptr; - switch (_bossId) { case DATA_MORAGG: - pathSize = SaboteurMoraggPathSize; - path = SaboteurMoraggPath; + StartSmoothPath(SaboteurMoraggPath); break; case DATA_EREKEM: - pathSize = SaboteurErekemPathSize; - path = SaboteurErekemPath; + StartSmoothPath(SaboteurErekemPath); break; case DATA_ICHORON: - pathSize = SaboteurIchoronPathSize; - path = SaboteurIchoronPath; + StartSmoothPath(SaboteurIchoronPath); break; case DATA_LAVANTHOR: - pathSize = SaboteurLavanthorPathSize; - path = SaboteurLavanthorPath; + StartSmoothPath(SaboteurLavanthorPath); break; case DATA_XEVOZZ: - pathSize = SaboteurXevozzPathSize; - path = SaboteurXevozzPath; + StartSmoothPath(SaboteurXevozzPath); break; case DATA_ZURAMAT: - pathSize = SaboteurZuramatPathSize; - path = SaboteurZuramatPath; + StartSmoothPath(SaboteurZuramatPath); break; } - - if (path) - me->GetMotionMaster()->MoveSmoothPath(POINT_INTRO, path, pathSize, false); } void Reset() override @@ -852,58 +841,57 @@ struct violet_hold_trashAI : public npc_escortAI _scheduler.CancelAll(); } + template + Position const* GetPathAndInitLastWaypointFrom(Position const (&path)[N]) + { + _lastWaypointId = N - 1; + return &path[0]; + } + void SetData(uint32 type, uint32 data) override { if (type == DATA_PORTAL_LOCATION) { - G3D::Vector3 const* path = nullptr; + Position const* path = nullptr; switch (data) { case 0: - _lastWaypointId = 5; - path = FirstPortalWPs; + path = GetPathAndInitLastWaypointFrom(FirstPortalWPs); break; case 7: switch (urand(0, 1)) { case 0: - _lastWaypointId = 8; - path = SecondPortalFirstWPs; + path = GetPathAndInitLastWaypointFrom(SecondPortalFirstWPs); break; case 1: - _lastWaypointId = 7; - path = SecondPortalSecondWPs; + path = GetPathAndInitLastWaypointFrom(SecondPortalSecondWPs); break; } break; case 2: - _lastWaypointId = 7; - path = ThirdPortalWPs; + path = GetPathAndInitLastWaypointFrom(ThirdPortalWPs); break; case 6: - _lastWaypointId = 8; - path = FourthPortalWPs; + path = GetPathAndInitLastWaypointFrom(FourthPortalWPs); break; case 1: - _lastWaypointId = 5; - path = FifthPortalWPs; + path = GetPathAndInitLastWaypointFrom(FifthPortalWPs); break; case 5: - _lastWaypointId = 3; - path = SixthPoralWPs; + path = GetPathAndInitLastWaypointFrom(SixthPortalWPs); break; default: - _lastWaypointId = 0; - path = DefaultPortalWPs; + path = GetPathAndInitLastWaypointFrom(DefaultPortalWPs); break; } if (path) { for (uint32 i = 0; i <= _lastWaypointId; i++) - AddWaypoint(i, path[i].x + irand(-1, 1), path[i].y + irand(-1, 1), path[i].z, 0); - me->SetHomePosition(path[_lastWaypointId].x, path[_lastWaypointId].y, path[_lastWaypointId].z, float(M_PI)); + AddWaypoint(i, path[i].GetPositionX() + irand(-1, 1), path[i].GetPositionY() + irand(-1, 1), path[i].GetPositionZ(), 0); + me->SetHomePosition(path[_lastWaypointId].GetPositionX(), path[_lastWaypointId].GetPositionY(), path[_lastWaypointId].GetPositionZ(), float(M_PI)); } Start(true, true); @@ -1302,7 +1290,7 @@ class npc_violet_hold_defense_system : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_violet_hold_defense_systemAI(creature); + return GetVioletHoldAI(creature); } }; @@ -1311,9 +1299,9 @@ class go_activation_crystal : public GameObjectScript public: go_activation_crystal() : GameObjectScript("go_activation_crystal") { } - struct go_blackfathom_altarAI : public GameObjectAI + struct go_activation_crystalAI : public GameObjectAI { - go_blackfathom_altarAI(GameObject* go) : GameObjectAI(go) { } + go_activation_crystalAI(GameObject* go) : GameObjectAI(go) { } bool GossipHello(Player* player) override { @@ -1324,7 +1312,7 @@ class go_activation_crystal : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return new go_blackfathom_altarAI(go); + return GetVioletHoldAI(go); } }; @@ -1407,9 +1395,7 @@ class spell_violet_hold_teleport_player : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TELEPORT_PLAYER_EFFECT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TELEPORT_PLAYER_EFFECT }); } void HandleScript(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Northrend/VioletHold/violet_hold.h b/src/server/scripts/Northrend/VioletHold/violet_hold.h index 17ab4da834e..580e45f8348 100644 --- a/src/server/scripts/Northrend/VioletHold/violet_hold.h +++ b/src/server/scripts/Northrend/VioletHold/violet_hold.h @@ -18,6 +18,8 @@ #ifndef VIOLET_HOLD_H_ #define VIOLET_HOLD_H_ +#include "CreatureAIImpl.h" + #define VioletHoldScriptName "instance_violet_hold" #define DataHeader "VH" @@ -151,10 +153,10 @@ enum VHInstanceMisc POINT_INTRO = 1 }; -template -inline AI* GetVioletHoldAI(Creature* creature) +template +inline AI* GetVioletHoldAI(T* obj) { - return GetInstanceAI(creature, VioletHoldScriptName); + return GetInstanceAI(obj, VioletHoldScriptName); } #endif // VIOLET_HOLD_H_ diff --git a/src/server/scripts/Northrend/zone_borean_tundra.cpp b/src/server/scripts/Northrend/zone_borean_tundra.cpp index 5a4a0bd9d08..33800bb6b2d 100644 --- a/src/server/scripts/Northrend/zone_borean_tundra.cpp +++ b/src/server/scripts/Northrend/zone_borean_tundra.cpp @@ -34,16 +34,20 @@ npc_lurgglbr EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" -#include "ScriptedFollowerAI.h" +#include "GameObject.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "PhasingHandler.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedFollowerAI.h" +#include "ScriptedGossip.h" +#include "SpellAuras.h" #include "SpellInfo.h" -#include "WorldSession.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "TemporarySummon.h" +#include "WorldSession.h" /*###### ## npc_sinkhole_kill_credit @@ -88,7 +92,7 @@ public: Initialize(); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (phase || spell->Id != SPELL_SET_CART) return; @@ -465,7 +469,7 @@ public: void JustDied(Unit* /*killer*/) override { - if (GameObject* go_caribou = me->GetMap()->GetGameObject(go_caribouGUID)) + if (GameObject* go_caribou = ObjectAccessor::GetGameObject(*me, go_caribouGUID)) go_caribou->SetLootState(GO_JUST_DEACTIVATED); if (TempSummon* summon = me->ToTempSummon()) @@ -474,7 +478,7 @@ public: if (Player* player = temp->ToPlayer()) player->KilledMonsterCredit(me->GetEntry()); - if (GameObject* go_caribou = me->GetMap()->GetGameObject(go_caribouGUID)) + if (GameObject* go_caribou = ObjectAccessor::GetGameObject(*me, go_caribouGUID)) go_caribou->SetGoState(GO_STATE_READY); } @@ -518,7 +522,7 @@ public: break; case 7: { - GameObject* go_caribou = NULL; + GameObject* go_caribou = nullptr; for (uint8 i = 0; i < CaribouTrapsNum; ++i) { go_caribou = me->FindNearestGameObject(CaribouTraps[i], 5.0f); @@ -1458,7 +1462,7 @@ public: AttackStart(who); } - void SpellHit(Unit* pCaster, const SpellInfo* pSpell) override + void SpellHit(Unit* pCaster, SpellInfo const* pSpell) override { if (pSpell->Id == SPELL_ARCANE_CHAINS && pCaster->GetTypeId() == TYPEID_PLAYER && !HealthAbovePct(50) && !bEnslaved) { @@ -1568,7 +1572,7 @@ public: { } - void SpellHit(Unit* unit, const SpellInfo* spell) override + void SpellHit(Unit* unit, SpellInfo const* spell) override { if (spell->Id == SPELL_NEURAL_NEEDLE && unit->GetTypeId() == TYPEID_PLAYER) if (Player* player = unit->ToPlayer()) @@ -1861,7 +1865,7 @@ public: { Initialize(); - GameObject* pTrap = NULL; + GameObject* pTrap = nullptr; for (uint8 i = 0; i < MammothTrapsNum; ++i) { pTrap = me->FindNearestGameObject(MammothTraps[i], 11.0f); @@ -1900,7 +1904,7 @@ public: me->DisappearAndDie(); - GameObject* pTrap = NULL; + GameObject* pTrap = nullptr; for (uint8 i = 0; i < MammothTrapsNum; ++i) { pTrap = me->FindNearestGameObject(MammothTraps[i], 11.0f); @@ -1943,9 +1947,9 @@ public: void JustDied(Unit* killer) override { - if (!killer || killer->GetTypeId() != TYPEID_PLAYER) - return; - + if (!killer || killer->GetTypeId() != TYPEID_PLAYER) + return; + Player* player = killer->ToPlayer(); if (player->GetQuestStatus(QUEST_YOU_RE_NOT_SO_BIG_NOW) == QUEST_STATUS_INCOMPLETE && @@ -2162,9 +2166,9 @@ enum HiddenCultist SAY_HIDDEN_CULTIST_4 = 3 }; -const char* GOSSIP_ITEM_TOM_HEGGER = "What do you know about the Cult of the Damned?"; -const char* GOSSIP_ITEM_GUARD_MITCHELLS = "How long have you worked for the Cult of the Damned?"; -const char* GOSSIP_ITEM_SALTY_JOHN_THORPE = "I have a reason to believe you're involved in the cultist activity"; +char const* GOSSIP_ITEM_TOM_HEGGER = "What do you know about the Cult of the Damned?"; +char const* GOSSIP_ITEM_GUARD_MITCHELLS = "How long have you worked for the Cult of the Damned?"; +char const* GOSSIP_ITEM_SALTY_JOHN_THORPE = "I have a reason to believe you're involved in the cultist activity"; class npc_hidden_cultist : public CreatureScript { @@ -2297,7 +2301,7 @@ public: bool GossipHello(Player* player) override { uint32 uiGossipText = 0; - const char* charGossipItem; + char const* charGossipItem; switch (me->GetEntry()) { diff --git a/src/server/scripts/Northrend/zone_crystalsong_forest.cpp b/src/server/scripts/Northrend/zone_crystalsong_forest.cpp index 5794eb7f758..e78306ff652 100644 --- a/src/server/scripts/Northrend/zone_crystalsong_forest.cpp +++ b/src/server/scripts/Northrend/zone_crystalsong_forest.cpp @@ -24,8 +24,9 @@ SDCategory: CrystalsongForest Script Data End */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" /******************************************************* * npc_warmage_violetstand diff --git a/src/server/scripts/Northrend/zone_dalaran.cpp b/src/server/scripts/Northrend/zone_dalaran.cpp index eb4a6d7c614..b681e1a3fce 100644 --- a/src/server/scripts/Northrend/zone_dalaran.cpp +++ b/src/server/scripts/Northrend/zone_dalaran.cpp @@ -24,10 +24,13 @@ SDCategory: Dalaran Script Data End */ #include "ScriptMgr.h" +#include "DatabaseEnv.h" +#include "Mail.h" +#include "Map.h" +#include "MotionMaster.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "Player.h" -#include "WorldSession.h" /******************************************************* * npc_mageguard_dalaran @@ -165,17 +168,16 @@ class npc_minigob_manabonk : public CreatureScript Player* SelectTargetInDalaran() { - std::list PlayerInDalaranList; - PlayerInDalaranList.clear(); + std::vector PlayerInDalaranList; - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + Map::PlayerList const& players = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) if (Player* player = itr->GetSource()->ToPlayer()) if (player->GetZoneId() == ZONE_DALARAN && !player->IsFlying() && !player->IsMounted() && !player->IsGameMaster()) PlayerInDalaranList.push_back(player); if (PlayerInDalaranList.empty()) - return NULL; + return nullptr; return Trinity::Containers::SelectRandomContainerElement(PlayerInDalaranList); } diff --git a/src/server/scripts/Northrend/zone_dragonblight.cpp b/src/server/scripts/Northrend/zone_dragonblight.cpp index f771c587e25..856cf224eef 100644 --- a/src/server/scripts/Northrend/zone_dragonblight.cpp +++ b/src/server/scripts/Northrend/zone_dragonblight.cpp @@ -28,14 +28,15 @@ npc_alexstrasza_wr_gate EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "ScriptedEscortAI.h" -#include "Vehicle.h" #include "CombatAI.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "SpellInfo.h" +#include "SpellScript.h" /*##### # npc_commander_eligor_dawnbringer @@ -640,7 +641,7 @@ class npc_torturer_lecraft : public CreatureScript Talk (SAY_AGGRO, player); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (spell->Id != SPELL_HIGH_EXECUTORS_BRANDING_IRON) return; diff --git a/src/server/scripts/Northrend/zone_grizzly_hills.cpp b/src/server/scripts/Northrend/zone_grizzly_hills.cpp index a17f52d7bde..36a12c31de9 100644 --- a/src/server/scripts/Northrend/zone_grizzly_hills.cpp +++ b/src/server/scripts/Northrend/zone_grizzly_hills.cpp @@ -17,12 +17,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" -#include "Player.h" -#include "SpellScript.h" -#include "CreatureTextMgr.h" #include "CombatAI.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedEscortAI.h" +#include "SpellInfo.h" +#include "SpellScript.h" +#include "TemporarySummon.h" /*###### ## Quest 12027: Mr. Floppy's Perilous Adventure @@ -297,7 +299,7 @@ public: _gender = Data; } - void SpellHit(Unit* Caster, const SpellInfo* Spell) override + void SpellHit(Unit* Caster, SpellInfo const* Spell) override { if (Spell->Id == SPELL_OUTHOUSE_GROANS) { @@ -492,7 +494,7 @@ public: me->DespawnOrUnsummon(_despawnTimer); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (spell->Id == SPELL_RENEW_SKIRMISHER && caster->GetTypeId() == TYPEID_PLAYER && caster->ToPlayer()->GetQuestStatus(QUEST_OVERWHELMED) == QUEST_STATUS_INCOMPLETE) @@ -954,9 +956,7 @@ public: 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; + return ValidateSpellInfo({ SPELL_WARHEAD_Z_CHECK, SPELL_WARHEAD_SEEKING_LUMBERSHIP, SPELL_WARHEAD_FUSE }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -998,9 +998,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PARACHUTE) || !sSpellMgr->GetSpellInfo(SPELL_TORPEDO_EXPLOSION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PARACHUTE, SPELL_TORPEDO_EXPLOSION }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1044,12 +1042,6 @@ public: { PrepareAuraScript(spell_z_check_AuraScript); - public: - spell_z_check_AuraScript() - { - _posZ = 0.0f; - } - void HandleEffectApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { _posZ = GetTarget()->GetPositionZ(); @@ -1064,8 +1056,7 @@ public: target->AI()->DoAction(0); } - private: - float _posZ; + float _posZ = 0.0f; void Register() override { diff --git a/src/server/scripts/Northrend/zone_howling_fjord.cpp b/src/server/scripts/Northrend/zone_howling_fjord.cpp index b9f409f6e05..bad7146461b 100644 --- a/src/server/scripts/Northrend/zone_howling_fjord.cpp +++ b/src/server/scripts/Northrend/zone_howling_fjord.cpp @@ -28,12 +28,13 @@ npc_apothecary_hanes EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" -#include "SpellInfo.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" #include "SpellScript.h" +#include "TemporarySummon.h" /*###### ## npc_apothecary_hanes @@ -558,9 +559,7 @@ class spell_mindless_abomination_explosion_fx_master : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RANDOM_CIRCUMFERENCE_POINT_POISON) || !sSpellMgr->GetSpellInfo(SPELL_COSMETIC_BLOOD_EXPLOSION_GREEN_LARGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RANDOM_CIRCUMFERENCE_POINT_POISON, SPELL_COSMETIC_BLOOD_EXPLOSION_GREEN_LARGE }); } void HandleScript(SpellEffIndex /*eff*/) diff --git a/src/server/scripts/Northrend/zone_icecrown.cpp b/src/server/scripts/Northrend/zone_icecrown.cpp index 6cd5d23bfd9..28719967245 100644 --- a/src/server/scripts/Northrend/zone_icecrown.cpp +++ b/src/server/scripts/Northrend/zone_icecrown.cpp @@ -17,12 +17,15 @@ */ #include "ScriptMgr.h" +#include "CombatAI.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" #include "SpellAuras.h" -#include "Player.h" +#include "SpellInfo.h" #include "TemporarySummon.h" -#include "CombatAI.h" /*###### ## npc_argent_valiant diff --git a/src/server/scripts/Northrend/zone_sholazar_basin.cpp b/src/server/scripts/Northrend/zone_sholazar_basin.cpp index a871f044bf9..ee1cd5df807 100644 --- a/src/server/scripts/Northrend/zone_sholazar_basin.cpp +++ b/src/server/scripts/Northrend/zone_sholazar_basin.cpp @@ -33,13 +33,16 @@ spell_shango_tracks EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedEscortAI.h" -#include "SpellScript.h" -#include "SpellAuras.h" -#include "Vehicle.h" #include "CombatAI.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "SpellAuras.h" +#include "SpellScript.h" +#include "Vehicle.h" /*###### ## npc_engineer_helice @@ -95,7 +98,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, G3D::Quat(), TEMPSUMMON_MANUAL_DESPAWN); //approx 3 to 4 seconds + me->SummonGameObject(184743, 5918.33f, 5372.91f, -98.770f, 0, QuaternionData(), TEMPSUMMON_MANUAL_DESPAWN); //approx 3 to 4 seconds me->HandleEmoteCommand(EMOTE_ONESHOT_LAUGH); break; case 2: @@ -106,7 +109,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, G3D::Quat(), TEMPSUMMON_MANUAL_DESPAWN); //approx 3 to 4 seconds + me->SummonGameObject(184743, 5887.37f, 5379.39f, -91.289f, 0, QuaternionData(), TEMPSUMMON_MANUAL_DESPAWN); //approx 3 to 4 seconds me->HandleEmoteCommand(EMOTE_ONESHOT_LAUGH); break; case 9: diff --git a/src/server/scripts/Northrend/zone_storm_peaks.cpp b/src/server/scripts/Northrend/zone_storm_peaks.cpp index e03d74856de..85b82e330e3 100644 --- a/src/server/scripts/Northrend/zone_storm_peaks.cpp +++ b/src/server/scripts/Northrend/zone_storm_peaks.cpp @@ -16,15 +16,17 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" -#include "SpellHistory.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "Vehicle.h" #include "CombatAI.h" +#include "GameObject.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "TemporarySummon.h" +#include "Vehicle.h" #include "WorldSession.h" ///////////////////// @@ -222,7 +224,7 @@ public: me->DespawnOrUnsummon(); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (spell->Id != SPELL_ICE_LANCE) return; @@ -528,7 +530,7 @@ class npc_brann_bronzebeard_keystone : public CreatureScript 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, G3D::Quat(0.f, 0.f, -0.737277f, 0.6755905f), 0)) + if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_1, 7860.273f, -1383.622f, 1538.302f, -1.658062f, QuaternionData(0.f, 0.f, -0.737277f, 0.6755905f), 0)) objectGUID[objectCounter++] = go->GetGUID(); events.ScheduleEvent(EVENT_SCRIPT_5, 6000); break; @@ -536,7 +538,7 @@ class npc_brann_bronzebeard_keystone : public CreatureScript 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, G3D::Quat(0.f, 0.f, -0.9271832f, 0.3746083f), 0)) + if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_2, 7875.67f, -1387.266f, 1538.323f, -2.373644f, QuaternionData(0.f, 0.f, -0.9271832f, 0.3746083f), 0)) objectGUID[objectCounter++] = go->GetGUID(); events.ScheduleEvent(EVENT_SCRIPT_6, 6000); break; @@ -544,7 +546,7 @@ class npc_brann_bronzebeard_keystone : public CreatureScript 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, G3D::Quat(0.f, 0.f, 0.9961939f, 0.08716504f), 0)) + if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_3, 7879.212f, -1401.175f, 1538.279f, 2.967041f, QuaternionData(0.f, 0.f, 0.9961939f, 0.08716504f), 0)) objectGUID[objectCounter++] = go->GetGUID(); events.ScheduleEvent(EVENT_SCRIPT_7, 6000); break; @@ -552,7 +554,7 @@ class npc_brann_bronzebeard_keystone : public CreatureScript 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, G3D::Quat(0.f, 0.f, 0.8703556f, 0.4924237f), 0)) + if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_4, 7868.944f, -1411.18f, 1538.213f, 2.111848f, QuaternionData(0.f, 0.f, 0.8703556f, 0.4924237f), 0)) objectGUID[objectCounter++] = go->GetGUID(); events.ScheduleEvent(EVENT_SCRIPT_8, 6000); break; @@ -560,7 +562,7 @@ class npc_brann_bronzebeard_keystone : public CreatureScript 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, G3D::Quat(0.f, 0.f, 0.5446386f, 0.8386708f), 0)) + if (GameObject* go = me->SummonGameObject(OBJECT_TOL_SIGNAL_5, 7855.11f, -1406.839f, 1538.42f, 1.151916f, QuaternionData(0.f, 0.f, 0.5446386f, 0.8386708f), 0)) objectGUID[objectCounter] = go->GetGUID(); events.ScheduleEvent(EVENT_SCRIPT_9, 6000); break; @@ -968,9 +970,7 @@ class spell_jokkum_scriptcast : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_JOKKUM_SUMMON)) - return false; - return true; + return ValidateSpellInfo({ SPELL_JOKKUM_SUMMON }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1001,9 +1001,7 @@ class spell_veranus_summon : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_VERANUS_AND_THORIM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_VERANUS_AND_THORIM }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1038,22 +1036,15 @@ class spell_close_rift : public SpellScriptLoader { PrepareAuraScript(spell_close_rift_AuraScript); - public: - spell_close_rift_AuraScript() - { - _counter = 0; - } - - private: bool Validate(SpellInfo const* /*spell*/) override { - return sSpellMgr->GetSpellInfo(SPELL_DESPAWN_RIFT) != nullptr; + return ValidateSpellInfo({ SPELL_DESPAWN_RIFT }); } void HandlePeriodic(AuraEffect const* /* aurEff */) { if (++_counter == 5) - GetTarget()->CastSpell((Unit*)NULL, SPELL_DESPAWN_RIFT, true); + GetTarget()->CastSpell((Unit*)nullptr, SPELL_DESPAWN_RIFT, true); } void Register() override @@ -1061,8 +1052,7 @@ class spell_close_rift : public SpellScriptLoader OnEffectPeriodic += AuraEffectPeriodicFn(spell_close_rift_AuraScript::HandlePeriodic, EFFECT_0, SPELL_AURA_PERIODIC_TRIGGER_SPELL); } - private: - uint8 _counter; + uint8 _counter = 0; }; @@ -1084,9 +1074,7 @@ class spell_eject_passenger_wild_wyrm : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FIGHT_WYRM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FIGHT_WYRM }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -1246,9 +1234,7 @@ class spell_low_health_trigger : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].CalcValue())) - return false; - return true; + return ValidateSpellInfo({ uint32(spellInfo->Effects[EFFECT_0].CalcValue()) }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -1352,9 +1338,7 @@ class spell_fatal_strike : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FATAL_STRIKE_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FATAL_STRIKE_DAMAGE }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1431,9 +1415,7 @@ class spell_player_mount_wyrm : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FIGHT_WYRM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FIGHT_WYRM }); } void HandleDummy(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Northrend/zone_wintergrasp.cpp b/src/server/scripts/Northrend/zone_wintergrasp.cpp index c057b08fca1..a7205edd9f8 100644 --- a/src/server/scripts/Northrend/zone_wintergrasp.cpp +++ b/src/server/scripts/Northrend/zone_wintergrasp.cpp @@ -14,18 +14,20 @@ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ +#include "ScriptMgr.h" +#include "Battlefield.h" #include "BattlefieldMgr.h" #include "BattlefieldWG.h" -#include "Battlefield.h" -#include "ScriptSystem.h" -#include "WorldSession.h" -#include "ObjectMgr.h" -#include "Vehicle.h" +#include "DBCStores.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" +#include "ScriptSystem.h" #include "SpellScript.h" -#include "Player.h" +#include "Vehicle.h" +#include "WorldSession.h" #define GOSSIP_HELLO_DEMO1 "Build catapult." #define GOSSIP_HELLO_DEMO2 "Build demolisher." @@ -304,7 +306,7 @@ class npc_wg_queue : public CreatureScript else { uint32 timer = wintergrasp->GetTimer() / 1000; - player->SendUpdateWorldState(4354, time(NULL) + timer); + player->SendUpdateWorldState(4354, time(nullptr) + timer); if (timer < 15 * MINUTE) { AddGossipItemFor(player, GOSSIP_ICON_CHAT, player->GetSession()->GetTrinityString(WG_NPCQUEUE_TEXTOPTION_JOIN), GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF); @@ -433,12 +435,13 @@ class spell_wintergrasp_force_building : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BUILD_CATAPULT_FORCE) - || !sSpellMgr->GetSpellInfo(SPELL_BUILD_DEMOLISHER_FORCE) - || !sSpellMgr->GetSpellInfo(SPELL_BUILD_SIEGE_VEHICLE_FORCE_HORDE) - || !sSpellMgr->GetSpellInfo(SPELL_BUILD_SIEGE_VEHICLE_FORCE_ALLIANCE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_BUILD_CATAPULT_FORCE, + SPELL_BUILD_DEMOLISHER_FORCE, + SPELL_BUILD_SIEGE_VEHICLE_FORCE_HORDE, + SPELL_BUILD_SIEGE_VEHICLE_FORCE_ALLIANCE + }); } void HandleScript(SpellEffIndex effIndex) diff --git a/src/server/scripts/Northrend/zone_zuldrak.cpp b/src/server/scripts/Northrend/zone_zuldrak.cpp index 43f7747ee3c..c5cc6d0ba72 100644 --- a/src/server/scripts/Northrend/zone_zuldrak.cpp +++ b/src/server/scripts/Northrend/zone_zuldrak.cpp @@ -16,16 +16,18 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "SpellAuras.h" #include "SpellInfo.h" #include "SpellScript.h" -#include "SpellAuras.h" -#include "SpellAuraEffects.h" +#include "TemporarySummon.h" #include "Vehicle.h" -#include "GameObjectAI.h" /*#### ## npc_drakuru_shackles @@ -86,7 +88,7 @@ public: me->setDeathState(DEAD); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (spell->Id == SPELL_UNLOCK_SHACKLE) { @@ -142,7 +144,7 @@ public: void MoveInLineOfSight(Unit* /*who*/) override { } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_FREE_RAGECLAW) { @@ -647,9 +649,12 @@ class spell_random_ingredient_aura : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RANDOM_INGREDIENT_EASY) || !sSpellMgr->GetSpellInfo(SPELL_RANDOM_INGREDIENT_MEDIUM) || !sSpellMgr->GetSpellInfo(SPELL_RANDOM_INGREDIENT_HARD)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_RANDOM_INGREDIENT_EASY, + SPELL_RANDOM_INGREDIENT_MEDIUM, + SPELL_RANDOM_INGREDIENT_HARD + }); } void PeriodicTick(AuraEffect const* /*aurEff*/) @@ -686,7 +691,8 @@ class spell_random_ingredient_aura : public SpellScriptLoader class spell_random_ingredient : public SpellScriptLoader { - public: spell_random_ingredient() : SpellScriptLoader("spell_random_ingredient") { } + public: + spell_random_ingredient() : SpellScriptLoader("spell_random_ingredient") { } class spell_random_ingredient_SpellScript : public SpellScript { @@ -694,15 +700,30 @@ class spell_random_ingredient : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FETCH_KNOTROOT) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_PICKLED_EAGLE_EGG) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_SPECKLED_GUANO) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_WITHERED_BATWING) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_SEASONED_SLIDER_CIDER) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_PULVERIZED_GARGOYLE_TEETH) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_MUDDY_MIRE_MAGGOT) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_SPIKY_SPIDER_EGG) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_HAIRY_HERRING_HEAD) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_PUTRID_PIRATE_PERSPIRATION) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_ICECROWN_BOTTLED_WATER) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_WASPS_WINGS) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_PRISMATIC_MOJO) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_RAPTOR_CLAW) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_AMBERSEED) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_SHRUNKEN_DRAGONS_CLAW) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_CHILLED_SERPENT_MUCUS) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_CRYSTALLIZED_HOGSNOT) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_CRUSHED_BASILISK_CRYSTALS) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_TROLLBANE) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_FROZEN_SPIDER_ICHOR)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_FETCH_KNOTROOT, SPELL_HAVE_KNOTROOT, + SPELL_FETCH_PICKLED_EAGLE_EGG, SPELL_HAVE_PICKLED_EAGLE_EGG, + SPELL_FETCH_SPECKLED_GUANO, SPELL_HAVE_SPECKLED_GUANO, + SPELL_FETCH_WITHERED_BATWING, SPELL_HAVE_WITHERED_BATWING, + SPELL_FETCH_SEASONED_SLIDER_CIDER, SPELL_HAVE_SEASONED_SLIDER_CIDER, + SPELL_FETCH_PULVERIZED_GARGOYLE_TEETH, SPELL_HAVE_PULVERIZED_GARGOYLE_TEETH, + SPELL_FETCH_MUDDY_MIRE_MAGGOT, SPELL_HAVE_MUDDY_MIRE_MAGGOT, + SPELL_FETCH_SPIKY_SPIDER_EGG, SPELL_HAVE_SPIKY_SPIDER_EGG, + SPELL_FETCH_HAIRY_HERRING_HEAD, SPELL_HAVE_HAIRY_HERRING_HEAD, + SPELL_FETCH_PUTRID_PIRATE_PERSPIRATION, SPELL_HAVE_PUTRID_PIRATE_PERSPIRATION, + SPELL_FETCH_ICECROWN_BOTTLED_WATER, SPELL_HAVE_ICECROWN_BOTTLED_WATER, + SPELL_FETCH_WASPS_WINGS, SPELL_HAVE_WASPS_WINGS, + SPELL_FETCH_PRISMATIC_MOJO, SPELL_HAVE_PRISMATIC_MOJO, + SPELL_FETCH_RAPTOR_CLAW, SPELL_HAVE_RAPTOR_CLAW, + SPELL_FETCH_AMBERSEED, SPELL_HAVE_AMBERSEED, + SPELL_FETCH_SHRUNKEN_DRAGONS_CLAW, SPELL_HAVE_SHRUNKEN_DRAGONS_CLAW, + SPELL_FETCH_CHILLED_SERPENT_MUCUS, SPELL_HAVE_CHILLED_SERPENT_MUCUS, + SPELL_FETCH_CRYSTALLIZED_HOGSNOT, SPELL_HAVE_CRYSTALLIZED_HOGSNOT, + SPELL_FETCH_CRUSHED_BASILISK_CRYSTALS, SPELL_HAVE_CRUSHED_BASILISK_CRYSTALS, + SPELL_FETCH_TROLLBANE, SPELL_HAVE_TROLLBANE, + SPELL_FETCH_FROZEN_SPIDER_ICHOR, SPELL_HAVE_FROZEN_SPIDER_ICHOR, + }); } void HandleScriptEffect(SpellEffIndex /* effIndex */) @@ -726,7 +747,7 @@ class spell_random_ingredient : public SpellScriptLoader if (Creature* finklestein = GetClosestCreatureWithEntry(player, NPC_FINKLESTEIN, 25.0f)) { - finklestein->CastSpell(player, FetchIngredients[ingredient][0], true, NULL); + finklestein->CastSpell(player, FetchIngredients[ingredient][0], true, nullptr); finklestein->AI()->Talk(FetchIngredients[ingredient][3], player); } } @@ -736,7 +757,7 @@ class spell_random_ingredient : public SpellScriptLoader { OnEffectHitTarget += SpellEffectFn(spell_random_ingredient_SpellScript::HandleScriptEffect, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); } - }; + }; SpellScript* GetSpellScript() const override { @@ -750,7 +771,8 @@ class spell_random_ingredient : public SpellScriptLoader class spell_pot_check : public SpellScriptLoader { - public: spell_pot_check() : SpellScriptLoader("spell_pot_check") { } + public: + spell_pot_check() : SpellScriptLoader("spell_pot_check") { } class spell_pot_check_SpellScript : public SpellScript { @@ -758,78 +780,86 @@ class spell_pot_check : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FETCH_KNOTROOT) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_PICKLED_EAGLE_EGG) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_SPECKLED_GUANO) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_WITHERED_BATWING) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_SEASONED_SLIDER_CIDER) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_PULVERIZED_GARGOYLE_TEETH) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_MUDDY_MIRE_MAGGOT) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_SPIKY_SPIDER_EGG) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_HAIRY_HERRING_HEAD) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_PUTRID_PIRATE_PERSPIRATION) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_ICECROWN_BOTTLED_WATER) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_WASPS_WINGS) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_PRISMATIC_MOJO) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_RAPTOR_CLAW) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_AMBERSEED) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_SHRUNKEN_DRAGONS_CLAW) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_CHILLED_SERPENT_MUCUS) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_CRYSTALLIZED_HOGSNOT) || - !sSpellMgr->GetSpellInfo(SPELL_FETCH_CRUSHED_BASILISK_CRYSTALS) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_TROLLBANE) || !sSpellMgr->GetSpellInfo(SPELL_FETCH_FROZEN_SPIDER_ICHOR) || - !sSpellMgr->GetSpellInfo(SPELL_HAVE_KNOTROOT) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_PICKLED_EAGLE_EGG) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_SPECKLED_GUANO) || - !sSpellMgr->GetSpellInfo(SPELL_HAVE_WITHERED_BATWING) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_SEASONED_SLIDER_CIDER) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_PULVERIZED_GARGOYLE_TEETH) || - !sSpellMgr->GetSpellInfo(SPELL_HAVE_MUDDY_MIRE_MAGGOT) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_SPIKY_SPIDER_EGG) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_HAIRY_HERRING_HEAD) || - !sSpellMgr->GetSpellInfo(SPELL_HAVE_PUTRID_PIRATE_PERSPIRATION) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_ICECROWN_BOTTLED_WATER) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_WASPS_WINGS) || - !sSpellMgr->GetSpellInfo(SPELL_HAVE_PRISMATIC_MOJO) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_RAPTOR_CLAW) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_AMBERSEED) || - !sSpellMgr->GetSpellInfo(SPELL_HAVE_SHRUNKEN_DRAGONS_CLAW) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_CHILLED_SERPENT_MUCUS) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_CRYSTALLIZED_HOGSNOT) || - !sSpellMgr->GetSpellInfo(SPELL_HAVE_CRUSHED_BASILISK_CRYSTALS) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_TROLLBANE) || !sSpellMgr->GetSpellInfo(SPELL_HAVE_FROZEN_SPIDER_ICHOR)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_FETCH_KNOTROOT, SPELL_HAVE_KNOTROOT, + SPELL_FETCH_PICKLED_EAGLE_EGG, SPELL_HAVE_PICKLED_EAGLE_EGG, + SPELL_FETCH_SPECKLED_GUANO, SPELL_HAVE_SPECKLED_GUANO, + SPELL_FETCH_WITHERED_BATWING, SPELL_HAVE_WITHERED_BATWING, + SPELL_FETCH_SEASONED_SLIDER_CIDER, SPELL_HAVE_SEASONED_SLIDER_CIDER, + SPELL_FETCH_PULVERIZED_GARGOYLE_TEETH, SPELL_HAVE_PULVERIZED_GARGOYLE_TEETH, + SPELL_FETCH_MUDDY_MIRE_MAGGOT, SPELL_HAVE_MUDDY_MIRE_MAGGOT, + SPELL_FETCH_SPIKY_SPIDER_EGG, SPELL_HAVE_SPIKY_SPIDER_EGG, + SPELL_FETCH_HAIRY_HERRING_HEAD, SPELL_HAVE_HAIRY_HERRING_HEAD, + SPELL_FETCH_PUTRID_PIRATE_PERSPIRATION, SPELL_HAVE_PUTRID_PIRATE_PERSPIRATION, + SPELL_FETCH_ICECROWN_BOTTLED_WATER, SPELL_HAVE_ICECROWN_BOTTLED_WATER, + SPELL_FETCH_WASPS_WINGS, SPELL_HAVE_WASPS_WINGS, + SPELL_FETCH_PRISMATIC_MOJO, SPELL_HAVE_PRISMATIC_MOJO, + SPELL_FETCH_RAPTOR_CLAW, SPELL_HAVE_RAPTOR_CLAW, + SPELL_FETCH_AMBERSEED, SPELL_HAVE_AMBERSEED, + SPELL_FETCH_SHRUNKEN_DRAGONS_CLAW, SPELL_HAVE_SHRUNKEN_DRAGONS_CLAW, + SPELL_FETCH_CHILLED_SERPENT_MUCUS, SPELL_HAVE_CHILLED_SERPENT_MUCUS, + SPELL_FETCH_CRYSTALLIZED_HOGSNOT, SPELL_HAVE_CRYSTALLIZED_HOGSNOT, + SPELL_FETCH_CRUSHED_BASILISK_CRYSTALS, SPELL_HAVE_CRUSHED_BASILISK_CRYSTALS, + SPELL_FETCH_TROLLBANE, SPELL_HAVE_TROLLBANE, + SPELL_FETCH_FROZEN_SPIDER_ICHOR, SPELL_HAVE_FROZEN_SPIDER_ICHOR, + }); } - void HandleScriptEffect(SpellEffIndex /* effIndex */) - { - if (Player* player = GetHitPlayer()) + void HandleScriptEffect(SpellEffIndex /* effIndex */) { - for (uint8 i = 0; i < 21; ++i) + if (Player* player = GetHitPlayer()) { - if (player->HasAura(FetchIngredients[i][0])) + for (uint8 i = 0; i < 21; ++i) { - player->CastSpell(player, SPELL_THROW_INGREDIENT); - player->RemoveAura(FetchIngredients[i][0]); - if (player->HasAura(FetchIngredients[i][1])) + if (player->HasAura(FetchIngredients[i][0])) { - player->RemoveAura(FetchIngredients[i][1]); - player->DestroyItemCount(FetchIngredients[i][2], 1, true); - if (i < 15) + player->CastSpell(player, SPELL_THROW_INGREDIENT); + player->RemoveAura(FetchIngredients[i][0]); + if (player->HasAura(FetchIngredients[i][1])) { - if (Creature* finklestein = GetClosestCreatureWithEntry(player, NPC_FINKLESTEIN, 25.0f)) - finklestein->AI()->SetData(1, 1); - return; + player->RemoveAura(FetchIngredients[i][1]); + player->DestroyItemCount(FetchIngredients[i][2], 1, true); + if (i < 15) + { + if (Creature* finklestein = GetClosestCreatureWithEntry(player, NPC_FINKLESTEIN, 25.0f)) + finklestein->AI()->SetData(1, 1); + return; + } + else + { + if (player->GetQuestStatus(QUEST_THE_ALCHEMIST_APPRENTICE_DAILY) == QUEST_STATUS_INCOMPLETE) + { + player->RemoveAura(SPELL_ALCHEMIST_APPRENTICE_INVISBUFF); + player->CastSpell(player, SPELL_KILL_CREDIT); + } + } } else { - if (player->GetQuestStatus(QUEST_THE_ALCHEMIST_APPRENTICE_DAILY) == QUEST_STATUS_INCOMPLETE) - { - player->RemoveAura(SPELL_ALCHEMIST_APPRENTICE_INVISBUFF); - player->CastSpell(player, SPELL_KILL_CREDIT); - } + RemoveItems(player); + player->RemoveAura(SPELL_ALCHEMIST_APPRENTICE_INVISBUFF); + if (Creature* finklestein = GetClosestCreatureWithEntry(player, NPC_FINKLESTEIN, 25.0f)) + finklestein->AI()->Talk(SAY_RUINED, player); + return; } } - else - { - RemoveItems(player); - player->RemoveAura(SPELL_ALCHEMIST_APPRENTICE_INVISBUFF); - if (Creature* finklestein = GetClosestCreatureWithEntry(player, NPC_FINKLESTEIN, 25.0f)) - finklestein->AI()->Talk(SAY_RUINED, player); - return; - } } - } - } - } + } + } - void RemoveItems(Player* player) - { - for (uint8 i = 0; i < 21; ++i) - if (player->HasItemCount(FetchIngredients[i][2], 1, true)) - player->DestroyItemCount(FetchIngredients[i][2], 1, true); - } + void RemoveItems(Player* player) + { + for (uint8 i = 0; i < 21; ++i) + if (player->HasItemCount(FetchIngredients[i][2], 1, true)) + player->DestroyItemCount(FetchIngredients[i][2], 1, true); + } - void Register() override - { - OnEffectHitTarget += SpellEffectFn(spell_pot_check_SpellScript::HandleScriptEffect, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); - } - }; + void Register() override + { + OnEffectHitTarget += SpellEffectFn(spell_pot_check_SpellScript::HandleScriptEffect, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); + } + }; SpellScript* GetSpellScript() const override { @@ -901,7 +931,7 @@ public: Reset(); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (spell->Id != GYMERS_GRAB) return; diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPHP.cpp b/src/server/scripts/OutdoorPvP/OutdoorPvPHP.cpp index 7de320fee4b..2d2b51b8750 100644 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPHP.cpp +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPHP.cpp @@ -15,13 +15,13 @@ * with this program. If not, see . */ -#include "MapManager.h" #include "ScriptMgr.h" -#include "OutdoorPvPHP.h" +#include "GameObject.h" +#include "MapManager.h" #include "OutdoorPvP.h" +#include "OutdoorPvPHP.h" #include "OutdoorPvPMgr.h" #include "Player.h" -#include "ObjectMgr.h" #include "WorldPacket.h" uint32 const OutdoorPvPHPBuffZonesNum = 6; diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPNA.cpp b/src/server/scripts/OutdoorPvP/OutdoorPvPNA.cpp index 1de3497d875..c50a0e7aa67 100644 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPNA.cpp +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPNA.cpp @@ -15,12 +15,14 @@ * with this program. If not, see . */ -#include "MapManager.h" #include "ScriptMgr.h" -#include "OutdoorPvPNA.h" -#include "Player.h" +#include "Creature.h" +#include "GameObject.h" +#include "MapManager.h" #include "ObjectMgr.h" #include "OutdoorPvPMgr.h" +#include "OutdoorPvPNA.h" +#include "Player.h" #include "WorldPacket.h" // kill credit for pks @@ -132,7 +134,7 @@ creature_type const AllianceControlNPCs[NA_CONTROL_NPC_NUM] = OutdoorPvPNA::OutdoorPvPNA() { m_TypeId = OUTDOOR_PVP_NA; - m_obj = NULL; + m_obj = nullptr; } void OutdoorPvPNA::HandleKillImpl(Player* player, Unit* killed) @@ -241,11 +243,11 @@ void OPvPCapturePointNA::DeSpawnGOs() void OPvPCapturePointNA::FactionTakeOver(uint32 team) { if (m_ControllingFaction) - sObjectMgr->RemoveGraveYardLink(NA_HALAA_GRAVEYARD, NA_HALAA_GRAVEYARD_ZONE, m_ControllingFaction, false); + sObjectMgr->RemoveGraveyardLink(NA_HALAA_GRAVEYARD, NA_HALAA_GRAVEYARD_ZONE, m_ControllingFaction, false); m_ControllingFaction = team; if (m_ControllingFaction) - sObjectMgr->AddGraveYardLink(NA_HALAA_GRAVEYARD, NA_HALAA_GRAVEYARD_ZONE, m_ControllingFaction, false); + sObjectMgr->AddGraveyardLink(NA_HALAA_GRAVEYARD, NA_HALAA_GRAVEYARD_ZONE, m_ControllingFaction, false); DeSpawnGOs(); DeSpawnNPCs(); SpawnGOsForTeam(team); @@ -487,7 +489,7 @@ int32 OPvPCapturePointNA::HandleOpenGo(Player* player, GameObject* go) int32 retval = OPvPCapturePoint::HandleOpenGo(player, go); if (retval >= 0) { - const go_type * gos = NULL; + const go_type * gos = nullptr; if (m_ControllingFaction == ALLIANCE) gos=AllianceControlGOs; else if (m_ControllingFaction == HORDE) diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPSI.cpp b/src/server/scripts/OutdoorPvP/OutdoorPvPSI.cpp index 6ea3fabb84a..af6b12f3b30 100644 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPSI.cpp +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPSI.cpp @@ -16,17 +16,18 @@ */ #include "ScriptMgr.h" -#include "OutdoorPvPSI.h" -#include "WorldPacket.h" -#include "PhasingHandler.h" -#include "Player.h" +#include "DBCStores.h" #include "GameObject.h" +#include "Language.h" #include "MapManager.h" #include "ObjectMgr.h" #include "OutdoorPvPMgr.h" +#include "OutdoorPvPSI.h" +#include "PhasingHandler.h" +#include "Player.h" #include "ReputationMgr.h" -#include "Language.h" #include "World.h" +#include "WorldPacket.h" uint32 const SI_MAX_RESOURCES = 200; @@ -121,7 +122,7 @@ bool OutdoorPvPSI::HandleAreaTrigger(Player* player, uint32 trigger) // reward player player->CastSpell(player, SI_TRACES_OF_SILITHYST, true); // add 19 honor - player->RewardHonor(NULL, 1, 19); + player->RewardHonor(nullptr, 1, 19); // add 20 cenarion circle repu player->GetReputationMgr().ModifyReputation(sFactionStore.LookupEntry(609), 20); // complete quest @@ -147,7 +148,7 @@ bool OutdoorPvPSI::HandleAreaTrigger(Player* player, uint32 trigger) // reward player player->CastSpell(player, SI_TRACES_OF_SILITHYST, true); // add 19 honor - player->RewardHonor(NULL, 1, 19); + player->RewardHonor(nullptr, 1, 19); // add 20 cenarion circle repu player->GetReputationMgr().ModifyReputation(sFactionStore.LookupEntry(609), 20); // complete quest @@ -177,7 +178,7 @@ bool OutdoorPvPSI::HandleDropFlag(Player* player, uint32 spellId) GameObject* go = new GameObject; Map* map = player->GetMap(); - if (!go->Create(map->GenerateLowGuid(), SI_SILITHYST_MOUND, map, player->GetPhaseMask(), *player, G3D::Quat(), 255, GO_STATE_READY)) + if (!go->Create(map->GenerateLowGuid(), SI_SILITHYST_MOUND, map, player->GetPhaseMask(), *player, QuaternionData(), 255, GO_STATE_READY)) { delete go; return true; @@ -207,7 +208,7 @@ bool OutdoorPvPSI::HandleDropFlag(Player* player, uint32 spellId) GameObject* go = new GameObject; Map* map = player->GetMap(); - if (!go->Create(map->GenerateLowGuid(), SI_SILITHYST_MOUND, map, player->GetPhaseMask(), *player, G3D::Quat(), 255, GO_STATE_READY)) + if (!go->Create(map->GenerateLowGuid(), SI_SILITHYST_MOUND, map, player->GetPhaseMask(), *player, QuaternionData(), 255, GO_STATE_READY)) { delete go; return true; diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPTF.cpp b/src/server/scripts/OutdoorPvP/OutdoorPvPTF.cpp index 759e496d2c7..ed1f6e1b7ed 100644 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPTF.cpp +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPTF.cpp @@ -15,14 +15,15 @@ * with this program. If not, see . */ -#include "MapManager.h" #include "ScriptMgr.h" -#include "OutdoorPvPTF.h" -#include "OutdoorPvPMgr.h" +#include "GameObject.h" +#include "MapManager.h" +#include "ObjectAccessor.h" #include "OutdoorPvP.h" -#include "WorldPacket.h" +#include "OutdoorPvPMgr.h" +#include "OutdoorPvPTF.h" #include "Player.h" -#include "ObjectMgr.h" +#include "WorldPacket.h" uint8 const OutdoorPvPTFBuffZonesNum = 5; uint32 const OutdoorPvPTFBuffZones[OutdoorPvPTFBuffZonesNum] = diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPZM.cpp b/src/server/scripts/OutdoorPvP/OutdoorPvPZM.cpp index 9ea5be34d04..b8a4c17064a 100644 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPZM.cpp +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPZM.cpp @@ -164,11 +164,11 @@ bool OutdoorPvPZM::Update(uint32 diff) if (changed) { if (m_AllianceTowersControlled == ZM_NUM_BEACONS) - m_GraveYard->SetBeaconState(ALLIANCE); + m_Graveyard->SetBeaconState(ALLIANCE); else if (m_HordeTowersControlled == ZM_NUM_BEACONS) - m_GraveYard->SetBeaconState(HORDE); + m_Graveyard->SetBeaconState(HORDE); else - m_GraveYard->SetBeaconState(0); + m_Graveyard->SetBeaconState(0); } return changed; } @@ -177,12 +177,12 @@ void OutdoorPvPZM::HandlePlayerEnterZone(Player* player, uint32 zone) { if (player->GetTeam() == ALLIANCE) { - if (m_GraveYard->GetGraveYardState() & ZM_GRAVEYARD_A) + if (m_Graveyard->GetGraveyardState() & ZM_GRAVEYARD_A) player->CastSpell(player, ZM_CAPTURE_BUFF, true); } else { - if (m_GraveYard->GetGraveYardState() & ZM_GRAVEYARD_H) + if (m_Graveyard->GetGraveyardState() & ZM_GRAVEYARD_H) player->CastSpell(player, ZM_CAPTURE_BUFF, true); } OutdoorPvP::HandlePlayerEnterZone(player, zone); @@ -201,7 +201,7 @@ void OutdoorPvPZM::HandlePlayerLeaveZone(Player* player, uint32 zone) OutdoorPvPZM::OutdoorPvPZM() { m_TypeId = OUTDOOR_PVP_ZM; - m_GraveYard = NULL; + m_Graveyard = nullptr; m_AllianceTowersControlled = 0; m_HordeTowersControlled = 0; } @@ -219,8 +219,8 @@ bool OutdoorPvPZM::SetupOutdoorPvP() AddCapturePoint(new OPvPCapturePointZM_Beacon(this, ZM_BEACON_WEST)); AddCapturePoint(new OPvPCapturePointZM_Beacon(this, ZM_BEACON_EAST)); - m_GraveYard = new OPvPCapturePointZM_GraveYard(this); - AddCapturePoint(m_GraveYard); // though the update function isn't used, the handleusego is! + m_Graveyard = new OPvPCapturePointZM_Graveyard(this); + AddCapturePoint(m_Graveyard); // though the update function isn't used, the handleusego is! return true; } @@ -236,36 +236,36 @@ void OutdoorPvPZM::HandleKillImpl(Player* player, Unit* killed) player->CastSpell(player, ZM_HordePlayerKillReward, true); } -bool OPvPCapturePointZM_GraveYard::Update(uint32 /*diff*/) +bool OPvPCapturePointZM_Graveyard::Update(uint32 /*diff*/) { bool retval = m_State != m_OldState; m_State = m_OldState; return retval; } -int32 OPvPCapturePointZM_GraveYard::HandleOpenGo(Player* player, GameObject* go) +int32 OPvPCapturePointZM_Graveyard::HandleOpenGo(Player* player, GameObject* go) { int32 retval = OPvPCapturePoint::HandleOpenGo(player, go); if (retval >= 0) { - if (player->HasAura(ZM_BATTLE_STANDARD_A) && m_GraveYardState != ZM_GRAVEYARD_A) + if (player->HasAura(ZM_BATTLE_STANDARD_A) && m_GraveyardState != ZM_GRAVEYARD_A) { - m_GraveYardState = ZM_GRAVEYARD_A; + m_GraveyardState = ZM_GRAVEYARD_A; DelObject(0); // only one gotype is used in the whole outdoor pvp, no need to call it a constant AddObject(0, ZM_Banner_A.entry, ZM_Banner_A.map, ZM_Banner_A.pos, ZM_Banner_A.rot); - sObjectMgr->RemoveGraveYardLink(ZM_GRAVEYARD_ID, ZM_GRAVEYARD_ZONE, HORDE); // rem gy - sObjectMgr->AddGraveYardLink(ZM_GRAVEYARD_ID, ZM_GRAVEYARD_ZONE, ALLIANCE, false); // add gy + sObjectMgr->RemoveGraveyardLink(ZM_GRAVEYARD_ID, ZM_GRAVEYARD_ZONE, HORDE); // rem gy + sObjectMgr->AddGraveyardLink(ZM_GRAVEYARD_ID, ZM_GRAVEYARD_ZONE, ALLIANCE, false); // add gy m_PvP->TeamApplyBuff(TEAM_ALLIANCE, ZM_CAPTURE_BUFF); player->RemoveAurasDueToSpell(ZM_BATTLE_STANDARD_A); m_PvP->SendDefenseMessage(ZM_GRAVEYARD_ZONE, TEXT_TWIN_SPIRE_RUINS_TAKEN_ALLIANCE); } - else if (player->HasAura(ZM_BATTLE_STANDARD_H) && m_GraveYardState != ZM_GRAVEYARD_H) + else if (player->HasAura(ZM_BATTLE_STANDARD_H) && m_GraveyardState != ZM_GRAVEYARD_H) { - m_GraveYardState = ZM_GRAVEYARD_H; + m_GraveyardState = ZM_GRAVEYARD_H; DelObject(0); // only one gotype is used in the whole outdoor pvp, no need to call it a constant AddObject(0, ZM_Banner_H.entry, ZM_Banner_H.map, ZM_Banner_H.pos, ZM_Banner_H.rot); - sObjectMgr->RemoveGraveYardLink(ZM_GRAVEYARD_ID, ZM_GRAVEYARD_ZONE, ALLIANCE); // rem gy - sObjectMgr->AddGraveYardLink(ZM_GRAVEYARD_ID, ZM_GRAVEYARD_ZONE, HORDE, false); // add gy + sObjectMgr->RemoveGraveyardLink(ZM_GRAVEYARD_ID, ZM_GRAVEYARD_ZONE, ALLIANCE); // rem gy + sObjectMgr->AddGraveyardLink(ZM_GRAVEYARD_ID, ZM_GRAVEYARD_ZONE, HORDE, false); // add gy m_PvP->TeamApplyBuff(TEAM_HORDE, ZM_CAPTURE_BUFF); player->RemoveAurasDueToSpell(ZM_BATTLE_STANDARD_H); m_PvP->SendDefenseMessage(ZM_GRAVEYARD_ZONE, TEXT_TWIN_SPIRE_RUINS_TAKEN_HORDE); @@ -275,11 +275,11 @@ int32 OPvPCapturePointZM_GraveYard::HandleOpenGo(Player* player, GameObject* go) return retval; } -OPvPCapturePointZM_GraveYard::OPvPCapturePointZM_GraveYard(OutdoorPvP* pvp) +OPvPCapturePointZM_Graveyard::OPvPCapturePointZM_Graveyard(OutdoorPvP* pvp) : OPvPCapturePoint(pvp) { m_BothControllingFaction = 0; - m_GraveYardState = ZM_GRAVEYARD_N; + m_GraveyardState = ZM_GRAVEYARD_N; m_FlagCarrierGUID.Clear(); // add field scouts here AddCreature(ZM_ALLIANCE_FIELD_SCOUT, ZM_AllianceFieldScout.entry, ZM_AllianceFieldScout.map, ZM_AllianceFieldScout.pos); @@ -288,11 +288,11 @@ OPvPCapturePointZM_GraveYard::OPvPCapturePointZM_GraveYard(OutdoorPvP* pvp) AddObject(0, ZM_Banner_N.entry, ZM_Banner_N.map, ZM_Banner_N.pos, ZM_Banner_N.rot); } -void OPvPCapturePointZM_GraveYard::UpdateTowerState() +void OPvPCapturePointZM_Graveyard::UpdateTowerState() { - m_PvP->SendUpdateWorldState(ZM_MAP_GRAVEYARD_N, uint32((m_GraveYardState & ZM_GRAVEYARD_N) != 0)); - m_PvP->SendUpdateWorldState(ZM_MAP_GRAVEYARD_H, uint32((m_GraveYardState & ZM_GRAVEYARD_H) != 0)); - m_PvP->SendUpdateWorldState(ZM_MAP_GRAVEYARD_A, uint32((m_GraveYardState & ZM_GRAVEYARD_A) != 0)); + m_PvP->SendUpdateWorldState(ZM_MAP_GRAVEYARD_N, uint32((m_GraveyardState & ZM_GRAVEYARD_N) != 0)); + m_PvP->SendUpdateWorldState(ZM_MAP_GRAVEYARD_H, uint32((m_GraveyardState & ZM_GRAVEYARD_H) != 0)); + m_PvP->SendUpdateWorldState(ZM_MAP_GRAVEYARD_A, uint32((m_GraveyardState & ZM_GRAVEYARD_A) != 0)); m_PvP->SendUpdateWorldState(ZM_MAP_ALLIANCE_FLAG_READY, uint32(m_BothControllingFaction == ALLIANCE)); m_PvP->SendUpdateWorldState(ZM_MAP_ALLIANCE_FLAG_NOT_READY, uint32(m_BothControllingFaction != ALLIANCE)); @@ -300,11 +300,11 @@ void OPvPCapturePointZM_GraveYard::UpdateTowerState() m_PvP->SendUpdateWorldState(ZM_MAP_HORDE_FLAG_NOT_READY, uint32(m_BothControllingFaction != HORDE)); } -void OPvPCapturePointZM_GraveYard::FillInitialWorldStates(WorldPacket &data) +void OPvPCapturePointZM_Graveyard::FillInitialWorldStates(WorldPacket &data) { - data << ZM_MAP_GRAVEYARD_N << uint32((m_GraveYardState & ZM_GRAVEYARD_N) != 0); - data << ZM_MAP_GRAVEYARD_H << uint32((m_GraveYardState & ZM_GRAVEYARD_H) != 0); - data << ZM_MAP_GRAVEYARD_A << uint32((m_GraveYardState & ZM_GRAVEYARD_A) != 0); + data << ZM_MAP_GRAVEYARD_N << uint32((m_GraveyardState & ZM_GRAVEYARD_N) != 0); + data << ZM_MAP_GRAVEYARD_H << uint32((m_GraveyardState & ZM_GRAVEYARD_H) != 0); + data << ZM_MAP_GRAVEYARD_A << uint32((m_GraveyardState & ZM_GRAVEYARD_A) != 0); data << ZM_MAP_ALLIANCE_FLAG_READY << uint32(m_BothControllingFaction == ALLIANCE); data << ZM_MAP_ALLIANCE_FLAG_NOT_READY << uint32(m_BothControllingFaction != ALLIANCE); @@ -312,7 +312,7 @@ void OPvPCapturePointZM_GraveYard::FillInitialWorldStates(WorldPacket &data) data << ZM_MAP_HORDE_FLAG_NOT_READY << uint32(m_BothControllingFaction != HORDE); } -void OPvPCapturePointZM_GraveYard::SetBeaconState(uint32 controlling_faction) +void OPvPCapturePointZM_Graveyard::SetBeaconState(uint32 controlling_faction) { // nothing to do here if (m_BothControllingFaction == controlling_faction) @@ -323,20 +323,20 @@ void OPvPCapturePointZM_GraveYard::SetBeaconState(uint32 controlling_faction) { case ALLIANCE: // if ally already controls the gy and taken back both beacons, return, nothing to do for us - if (m_GraveYardState & ZM_GRAVEYARD_A) + if (m_GraveyardState & ZM_GRAVEYARD_A) return; // ally doesn't control the gy, but controls the side beacons -> add gossip option, add neutral banner break; case HORDE: // if horde already controls the gy and taken back both beacons, return, nothing to do for us - if (m_GraveYardState & ZM_GRAVEYARD_H) + if (m_GraveyardState & ZM_GRAVEYARD_H) return; // horde doesn't control the gy, but controls the side beacons -> add gossip option, add neutral banner break; default: // if the graveyard is not neutral, then leave it that way // if the graveyard is neutral, then we have to dispel the buff from the flag carrier - if (m_GraveYardState & ZM_GRAVEYARD_N) + if (m_GraveyardState & ZM_GRAVEYARD_N) { // gy was neutral, thus neutral banner was spawned, it is possible that someone was taking the flag to the gy if (m_FlagCarrierGUID) @@ -357,20 +357,20 @@ void OPvPCapturePointZM_GraveYard::SetBeaconState(uint32 controlling_faction) UpdateTowerState(); } -bool OPvPCapturePointZM_GraveYard::CanTalkTo(Player* player, Creature* c, GossipMenuItems const& /*gso*/) +bool OPvPCapturePointZM_Graveyard::CanTalkTo(Player* player, Creature* c, GossipMenuItems const& /*gso*/) { std::map::iterator itr = m_CreatureTypes.find(c->GetSpawnId()); if (itr != m_CreatureTypes.end()) { - if (itr->second == ZM_ALLIANCE_FIELD_SCOUT && player->GetTeam() == ALLIANCE && m_BothControllingFaction == ALLIANCE && !m_FlagCarrierGUID && m_GraveYardState != ZM_GRAVEYARD_A) + if (itr->second == ZM_ALLIANCE_FIELD_SCOUT && player->GetTeam() == ALLIANCE && m_BothControllingFaction == ALLIANCE && !m_FlagCarrierGUID && m_GraveyardState != ZM_GRAVEYARD_A) return true; - else if (itr->second == ZM_HORDE_FIELD_SCOUT && player->GetTeam() == HORDE && m_BothControllingFaction == HORDE && !m_FlagCarrierGUID && m_GraveYardState != ZM_GRAVEYARD_H) + else if (itr->second == ZM_HORDE_FIELD_SCOUT && player->GetTeam() == HORDE && m_BothControllingFaction == HORDE && !m_FlagCarrierGUID && m_GraveyardState != ZM_GRAVEYARD_H) return true; } return false; } -bool OPvPCapturePointZM_GraveYard::HandleGossipOption(Player* player, Creature* creature, uint32 /*gossipid*/) +bool OPvPCapturePointZM_Graveyard::HandleGossipOption(Player* player, Creature* creature, uint32 /*gossipid*/) { std::map::iterator itr = m_CreatureTypes.find(creature->GetSpawnId()); @@ -396,7 +396,7 @@ bool OPvPCapturePointZM_GraveYard::HandleGossipOption(Player* player, Creature* return false; } -bool OPvPCapturePointZM_GraveYard::HandleDropFlag(Player* /*player*/, uint32 spellId) +bool OPvPCapturePointZM_Graveyard::HandleDropFlag(Player* /*player*/, uint32 spellId) { switch (spellId) { @@ -410,9 +410,9 @@ bool OPvPCapturePointZM_GraveYard::HandleDropFlag(Player* /*player*/, uint32 spe return false; } -uint32 OPvPCapturePointZM_GraveYard::GetGraveYardState() const +uint32 OPvPCapturePointZM_Graveyard::GetGraveyardState() const { - return m_GraveYardState; + return m_GraveyardState; } uint32 OutdoorPvPZM::GetAllianceTowersControlled() const diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPZM.h b/src/server/scripts/OutdoorPvP/OutdoorPvPZM.h index afb0ce8aea8..c1c7583340e 100644 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPZM.h +++ b/src/server/scripts/OutdoorPvP/OutdoorPvPZM.h @@ -114,17 +114,17 @@ class OPvPCapturePointZM_Beacon : public OPvPCapturePoint uint32 m_TowerState; }; -enum ZM_GraveYardState +enum ZM_GraveyardState { ZM_GRAVEYARD_N = 1, ZM_GRAVEYARD_A = 2, ZM_GRAVEYARD_H = 4 }; -class OPvPCapturePointZM_GraveYard : public OPvPCapturePoint +class OPvPCapturePointZM_Graveyard : public OPvPCapturePoint { public: - OPvPCapturePointZM_GraveYard(OutdoorPvP* pvp); + OPvPCapturePointZM_Graveyard(OutdoorPvP* pvp); bool Update(uint32 diff) override; @@ -144,10 +144,10 @@ class OPvPCapturePointZM_GraveYard : public OPvPCapturePoint bool CanTalkTo(Player* player, Creature* creature, GossipMenuItems const& gso) override; - uint32 GetGraveYardState() const; + uint32 GetGraveyardState() const; private: - uint32 m_GraveYardState; + uint32 m_GraveyardState; protected: uint32 m_BothControllingFaction; @@ -180,7 +180,7 @@ class OutdoorPvPZM : public OutdoorPvP void SetHordeTowersControlled(uint32 count); private: - OPvPCapturePointZM_GraveYard * m_GraveYard; + OPvPCapturePointZM_Graveyard * m_Graveyard; uint32 m_AllianceTowersControlled; uint32 m_HordeTowersControlled; diff --git a/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/auchenai_crypts.h b/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/auchenai_crypts.h index fcca8088ac6..2e561f398f4 100644 --- a/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/auchenai_crypts.h +++ b/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/auchenai_crypts.h @@ -18,6 +18,8 @@ #ifndef AUCHENAI_CRYPTS_H_ #define AUCHENAI_CRYPTS_H_ +#include "CreatureAIImpl.h" + #define ACScriptName "instance_auchenai_crypts" #define DataHeader "AC" @@ -30,10 +32,10 @@ enum ACDataTypes DATA_EXARCH_MALADAAR = 1 }; -template -AI* GetAuchenaiCryptsAI(Creature* creature) +template +inline AI* GetAuchenaiCryptsAI(T* obj) { - return GetInstanceAI(creature, ACScriptName); + return GetInstanceAI(obj, ACScriptName); } #endif // AUCHENAI_CRYPTS_H_ diff --git a/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/boss_exarch_maladaar.cpp b/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/boss_exarch_maladaar.cpp index b7867fce8bf..d35c5d2053d 100644 --- a/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/boss_exarch_maladaar.cpp +++ b/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/boss_exarch_maladaar.cpp @@ -30,6 +30,8 @@ npc_avatar_of_martyred EndContentData */ #include "ScriptMgr.h" +#include "auchenai_crypts.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" enum Spells @@ -56,7 +58,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_stolen_soulAI(creature); + return GetAuchenaiCryptsAI(creature); } struct npc_stolen_soulAI : public ScriptedAI @@ -163,7 +165,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_exarch_maladaarAI(creature); + return GetAuchenaiCryptsAI(creature); } struct boss_exarch_maladaarAI : public ScriptedAI @@ -319,7 +321,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_avatar_of_martyredAI(creature); + return GetAuchenaiCryptsAI(creature); } struct npc_avatar_of_martyredAI : public ScriptedAI diff --git a/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/boss_shirrak_the_dead_watcher.cpp b/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/boss_shirrak_the_dead_watcher.cpp index 5a9e8c9f658..8e26b537b61 100644 --- a/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/boss_shirrak_the_dead_watcher.cpp +++ b/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/boss_shirrak_the_dead_watcher.cpp @@ -24,8 +24,11 @@ Category: Auchindoun, Auchenai Crypts EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "auchenai_crypts.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" enum Spells { @@ -55,7 +58,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_shirrak_the_dead_watcherAI(creature); + return GetAuchenaiCryptsAI(creature); } struct boss_shirrak_the_dead_watcherAI : public ScriptedAI @@ -109,7 +112,7 @@ public: if (Inhibitmagic_Timer <= diff) { float dist; - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player* i_pl = i->GetSource()) if (i_pl->IsAlive() && (dist = i_pl->GetDistance(me)) < 45) @@ -172,7 +175,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_focus_fireAI(creature); + return GetAuchenaiCryptsAI(creature); } struct npc_focus_fireAI : public ScriptedAI diff --git a/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/instance_auchenai_crypts.cpp b/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/instance_auchenai_crypts.cpp index 1da7e599be1..5989799b252 100644 --- a/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/instance_auchenai_crypts.cpp +++ b/src/server/scripts/Outland/Auchindoun/AuchenaiCrypts/instance_auchenai_crypts.cpp @@ -16,8 +16,9 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" #include "auchenai_crypts.h" +#include "InstanceScript.h" +#include "Map.h" class instance_auchenai_crypts : public InstanceMapScript { diff --git a/src/server/scripts/Outland/Auchindoun/ManaTombs/boss_nexusprince_shaffar.cpp b/src/server/scripts/Outland/Auchindoun/ManaTombs/boss_nexusprince_shaffar.cpp index 1ef2c87433e..0b4c45472d6 100644 --- a/src/server/scripts/Outland/Auchindoun/ManaTombs/boss_nexusprince_shaffar.cpp +++ b/src/server/scripts/Outland/Auchindoun/ManaTombs/boss_nexusprince_shaffar.cpp @@ -23,8 +23,9 @@ SDCategory: Auchindoun, Mana Tombs EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "mana_tombs.h" +#include "MotionMaster.h" +#include "ScriptedCreature.h" enum Yells { @@ -259,7 +260,7 @@ class npc_ethereal_beacon : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_ethereal_beaconAI(creature); + return GetManaTombsAI(creature); } }; @@ -324,7 +325,7 @@ class npc_ethereal_apprentice : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_ethereal_apprenticeAI(creature); + return GetManaTombsAI(creature); } }; @@ -380,7 +381,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_yorAI(creature); + return GetManaTombsAI(creature); } }; diff --git a/src/server/scripts/Outland/Auchindoun/ManaTombs/instance_mana_tombs.cpp b/src/server/scripts/Outland/Auchindoun/ManaTombs/instance_mana_tombs.cpp index 9731b8edd1c..bb54632b94c 100644 --- a/src/server/scripts/Outland/Auchindoun/ManaTombs/instance_mana_tombs.cpp +++ b/src/server/scripts/Outland/Auchindoun/ManaTombs/instance_mana_tombs.cpp @@ -18,6 +18,7 @@ #include "ScriptMgr.h" #include "InstanceScript.h" #include "mana_tombs.h" +#include "Map.h" class instance_mana_tombs : public InstanceMapScript { diff --git a/src/server/scripts/Outland/Auchindoun/ManaTombs/mana_tombs.h b/src/server/scripts/Outland/Auchindoun/ManaTombs/mana_tombs.h index 1807e4bd32c..6e5ace8ac61 100644 --- a/src/server/scripts/Outland/Auchindoun/ManaTombs/mana_tombs.h +++ b/src/server/scripts/Outland/Auchindoun/ManaTombs/mana_tombs.h @@ -18,6 +18,8 @@ #ifndef MANA_TOMBS_H_ #define MANA_TOMBS_H_ +#include "CreatureAIImpl.h" + #define MTScriptName "instance_mana_tombs" #define DataHeader "MT" @@ -32,10 +34,10 @@ enum MTDataTypes DATA_YOR = 3 }; -template -AI* GetManaTombsAI(Creature* creature) +template +inline AI* GetManaTombsAI(T* obj) { - return GetInstanceAI(creature, MTScriptName); + return GetInstanceAI(obj, MTScriptName); } #endif // MANA_TOMBS_H_ diff --git a/src/server/scripts/Outland/Auchindoun/SethekkHalls/boss_darkweaver_syth.cpp b/src/server/scripts/Outland/Auchindoun/SethekkHalls/boss_darkweaver_syth.cpp index cceac337777..114f48a909f 100644 --- a/src/server/scripts/Outland/Auchindoun/SethekkHalls/boss_darkweaver_syth.cpp +++ b/src/server/scripts/Outland/Auchindoun/SethekkHalls/boss_darkweaver_syth.cpp @@ -257,7 +257,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_syth_fireAI(creature); + return GetSethekkHallsAI(creature); } }; @@ -316,7 +316,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_syth_arcaneAI(creature); + return GetSethekkHallsAI(creature); } }; @@ -375,7 +375,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_syth_frostAI(creature); + return GetSethekkHallsAI(creature); } }; @@ -434,7 +434,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_syth_shadowAI(creature); + return GetSethekkHallsAI(creature); } }; diff --git a/src/server/scripts/Outland/Auchindoun/SethekkHalls/boss_talon_king_ikiss.cpp b/src/server/scripts/Outland/Auchindoun/SethekkHalls/boss_talon_king_ikiss.cpp index 14c27fe0be2..db2cafe21c4 100644 --- a/src/server/scripts/Outland/Auchindoun/SethekkHalls/boss_talon_king_ikiss.cpp +++ b/src/server/scripts/Outland/Auchindoun/SethekkHalls/boss_talon_king_ikiss.cpp @@ -173,9 +173,7 @@ class spell_talon_king_ikiss_blink : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BLINK_TELEPORT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BLINK_TELEPORT }); } void FilterTargets(std::list& targets) diff --git a/src/server/scripts/Outland/Auchindoun/SethekkHalls/instance_sethekk_halls.cpp b/src/server/scripts/Outland/Auchindoun/SethekkHalls/instance_sethekk_halls.cpp index 28be6c07c16..6506f33e61b 100644 --- a/src/server/scripts/Outland/Auchindoun/SethekkHalls/instance_sethekk_halls.cpp +++ b/src/server/scripts/Outland/Auchindoun/SethekkHalls/instance_sethekk_halls.cpp @@ -16,13 +16,16 @@ */ #include "ScriptMgr.h" +#include "Creature.h" +#include "GameObject.h" #include "InstanceScript.h" +#include "Map.h" #include "sethekk_halls.h" DoorData const doorData[] = { { GO_IKISS_DOOR, DATA_TALON_KING_IKISS, DOOR_TYPE_PASSAGE }, - { 0, 0, DOOR_TYPE_ROOM } // END + { 0, 0, DOOR_TYPE_ROOM } // END }; ObjectData const gameObjectData[] = diff --git a/src/server/scripts/Outland/Auchindoun/SethekkHalls/sethekk_halls.h b/src/server/scripts/Outland/Auchindoun/SethekkHalls/sethekk_halls.h index f904b5b35fa..03d3f69b672 100644 --- a/src/server/scripts/Outland/Auchindoun/SethekkHalls/sethekk_halls.h +++ b/src/server/scripts/Outland/Auchindoun/SethekkHalls/sethekk_halls.h @@ -18,6 +18,8 @@ #ifndef SETHEKK_HALLS_H_ #define SETHEKK_HALLS_H_ +#include "CreatureAIImpl.h" + #define SHScriptName "instance_sethekk_halls" #define DataHeader "SH" @@ -46,10 +48,10 @@ enum SHGameObjectIds GO_TALON_KING_COFFER = 187372 }; -template -AI* GetSethekkHallsAI(Creature* creature) +template +inline AI* GetSethekkHallsAI(T* obj) { - return GetInstanceAI(creature, SHScriptName); + return GetInstanceAI(obj, SHScriptName); } #endif // SETHEKK_HALLS_H_ diff --git a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_ambassador_hellmaw.cpp b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_ambassador_hellmaw.cpp index 5cb33701997..b82ba9d3889 100644 --- a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_ambassador_hellmaw.cpp +++ b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_ambassador_hellmaw.cpp @@ -24,7 +24,7 @@ SDCategory: Auchindoun, Shadow Labyrinth EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "ScriptedEscortAI.h" #include "shadow_labyrinth.h" @@ -115,7 +115,7 @@ class boss_ambassador_hellmaw : public CreatureScript me->RemoveAurasDueToSpell(SPELL_BANISH); Talk(SAY_INTRO); - Start(true, false, ObjectGuid::Empty, NULL, false, true); + Start(true, false, ObjectGuid::Empty, nullptr, false, true); } void JustEngagedWith(Unit* /*who*/) override diff --git a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_blackheart_the_inciter.cpp b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_blackheart_the_inciter.cpp index 8466b374bea..c7b3d879f11 100644 --- a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_blackheart_the_inciter.cpp +++ b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_blackheart_the_inciter.cpp @@ -24,6 +24,7 @@ Category: Auchindoun, Shadow Labyrinth */ #include "ScriptMgr.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "shadow_labyrinth.h" diff --git a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_grandmaster_vorpil.cpp b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_grandmaster_vorpil.cpp index 4ceac92e44c..32aebe73665 100644 --- a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_grandmaster_vorpil.cpp +++ b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_grandmaster_vorpil.cpp @@ -23,9 +23,14 @@ Category: Auchindoun, Shadow Labyrinth */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "shadow_labyrinth.h" -#include "Player.h" +#include "TemporarySummon.h" enum GrandmasterVorpil { @@ -182,7 +187,7 @@ class boss_grandmaster_vorpil : public CreatureScript break; case EVENT_DRAW_SHADOWS: { - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) if (Player* i_pl = i->GetSource()) if (i_pl->IsAlive() && !i_pl->HasAura(SPELL_BANISH)) diff --git a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_murmur.cpp b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_murmur.cpp index e9ac7637936..d4340898b5f 100644 --- a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_murmur.cpp +++ b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/boss_murmur.cpp @@ -24,9 +24,10 @@ SDCategory: Auchindoun, Shadow Labyrinth EndScriptData */ #include "ScriptMgr.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "shadow_labyrinth.h" +#include "SpellScript.h" enum Murmur { @@ -188,14 +189,12 @@ class spell_murmur_sonic_boom : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SONIC_BOOM_EFFECT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SONIC_BOOM_EFFECT }); } void HandleEffect(SpellEffIndex /*effIndex*/) { - GetCaster()->CastSpell((Unit*)NULL, SPELL_SONIC_BOOM_EFFECT, true); + GetCaster()->CastSpell((Unit*)nullptr, SPELL_SONIC_BOOM_EFFECT, true); } void Register() override diff --git a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/instance_shadow_labyrinth.cpp b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/instance_shadow_labyrinth.cpp index 1a720970bbc..e6b172418f1 100644 --- a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/instance_shadow_labyrinth.cpp +++ b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/instance_shadow_labyrinth.cpp @@ -17,6 +17,7 @@ #include "ScriptMgr.h" #include "InstanceScript.h" +#include "Map.h" #include "ScriptedCreature.h" #include "shadow_labyrinth.h" @@ -66,32 +67,6 @@ class instance_shadow_labyrinth : public InstanceMapScript } } - void OnGameObjectCreate(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_REFECTORY_DOOR: - case GO_SCREAMING_HALL_DOOR: - AddDoor(go, true); - break; - default: - break; - } - } - - void OnGameObjectRemove(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_REFECTORY_DOOR: - case GO_SCREAMING_HALL_DOOR: - AddDoor(go, false); - break; - default: - break; - } - } - void OnUnitDeath(Unit* unit) override { Creature* creature = unit->ToCreature(); diff --git a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/shadow_labyrinth.cpp b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/shadow_labyrinth.cpp index 2d906c26514..7eb4b6bea62 100644 --- a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/shadow_labyrinth.cpp +++ b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/shadow_labyrinth.cpp @@ -19,6 +19,7 @@ #include "SpellMgr.h" #include "SpellScript.h" #include "SpellAuraEffects.h" +#include "Unit.h" enum Spells { @@ -36,9 +37,7 @@ class spell_mark_of_malice : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MARK_OF_MALICE_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MARK_OF_MALICE_TRIGGERED }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) diff --git a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/shadow_labyrinth.h b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/shadow_labyrinth.h index a62755aa033..14ac971cade 100644 --- a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/shadow_labyrinth.h +++ b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/shadow_labyrinth.h @@ -18,6 +18,8 @@ #ifndef SHADOW_LABYRINTH_H_ #define SHADOW_LABYRINTH_H_ +#include "CreatureAIImpl.h" + #define SLScriptName "instance_shadow_labyrinth" #define DataHeader "SL" @@ -54,10 +56,10 @@ enum SLMisc ACTION_AMBASSADOR_HELLMAW_BANISH = 2, }; -template -AI* GetShadowLabyrinthAI(Creature* creature) +template +inline AI* GetShadowLabyrinthAI(T* obj) { - return GetInstanceAI(creature, SLScriptName); + return GetInstanceAI(obj, SLScriptName); } #endif // SHADOW_LABYRINTH_H_ diff --git a/src/server/scripts/Outland/BlackTemple/black_temple.cpp b/src/server/scripts/Outland/BlackTemple/black_temple.cpp index 7fa89edb232..e73dede49f8 100644 --- a/src/server/scripts/Outland/BlackTemple/black_temple.cpp +++ b/src/server/scripts/Outland/BlackTemple/black_temple.cpp @@ -16,10 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "black_temple.h" -#include "SpellScript.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" #include "SpellAuraEffects.h" +#include "SpellScript.h" enum Spells { @@ -137,11 +138,11 @@ public: { for (ObjectGuid guid : _bloodmageList) if (Creature* bloodmage = ObjectAccessor::GetCreature(*me, guid)) - bloodmage->CastSpell((Unit*)NULL, SPELL_SUMMON_CHANNEL); + bloodmage->CastSpell((Unit*)nullptr, SPELL_SUMMON_CHANNEL); for (ObjectGuid guid : _deathshaperList) if (Creature* deathshaper = ObjectAccessor::GetCreature(*me, guid)) - deathshaper->CastSpell((Unit*)NULL, SPELL_SUMMON_CHANNEL); + deathshaper->CastSpell((Unit*)nullptr, SPELL_SUMMON_CHANNEL); _events.ScheduleEvent(EVENT_SET_CHANNELERS, 12000); @@ -298,9 +299,7 @@ class spell_illidari_nightlord_shadow_inferno : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHADOW_INFERNO_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHADOW_INFERNO_DAMAGE }); } void OnPeriodic(AuraEffect const* aurEffect) diff --git a/src/server/scripts/Outland/BlackTemple/black_temple.h b/src/server/scripts/Outland/BlackTemple/black_temple.h index b16b38801ab..8742002628c 100644 --- a/src/server/scripts/Outland/BlackTemple/black_temple.h +++ b/src/server/scripts/Outland/BlackTemple/black_temple.h @@ -18,6 +18,8 @@ #ifndef BLACK_TEMPLE_H_ #define BLACK_TEMPLE_H_ +#include "CreatureAIImpl.h" + #define BTScriptName "instance_black_temple" #define DataHeader "BT" @@ -135,10 +137,10 @@ enum BlackTempleMisc ACTION_OPEN_DOOR = 4 }; -template -AI* GetBlackTempleAI(Creature* creature) +template +inline AI* GetBlackTempleAI(T* obj) { - return GetInstanceAI(creature, BTScriptName); + return GetInstanceAI(obj, BTScriptName); } #endif // BLACK_TEMPLE_H_ diff --git a/src/server/scripts/Outland/BlackTemple/boss_gurtogg_bloodboil.cpp b/src/server/scripts/Outland/BlackTemple/boss_gurtogg_bloodboil.cpp index 2fa63fa5ff9..7999241014d 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_gurtogg_bloodboil.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_gurtogg_bloodboil.cpp @@ -16,12 +16,12 @@ */ #include "ScriptMgr.h" +#include "black_temple.h" +#include "GridNotifiers.h" +#include "ObjectAccessor.h" +#include "PassiveAI.h" #include "ScriptedCreature.h" #include "SpellScript.h" -#include "PassiveAI.h" -#include "GridNotifiers.h" - -#include "black_temple.h" enum Says { @@ -381,9 +381,7 @@ public: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FEL_RAGE_TARGET)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FEL_RAGE_TARGET }); } void FilterTargets(std::list& targets) diff --git a/src/server/scripts/Outland/BlackTemple/boss_illidan.cpp b/src/server/scripts/Outland/BlackTemple/boss_illidan.cpp index ff8da59fe0c..b40fbe1d1d5 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_illidan.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_illidan.cpp @@ -16,15 +16,19 @@ */ #include "ScriptMgr.h" +#include "black_temple.h" +#include "GridNotifiers.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "PassiveAI.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "PassiveAI.h" -#include "black_temple.h" -#include "Player.h" -#include "SpellInfo.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" -#include "GridNotifiersImpl.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum IllidanSay { @@ -427,18 +431,18 @@ private: Unit* _owner; }; -class ChargeTargetSelector : public std::unary_function +class ChargeTargetSelector { -public: - ChargeTargetSelector(Unit const* unit) : _me(unit) { } + public: + ChargeTargetSelector(Unit const* unit) : _me(unit) { } - bool operator()(Unit* unit) const - { - return unit->GetTypeId() == TYPEID_PLAYER && _me->GetDistance2d(unit) > 25.0f; - } + bool operator()(Unit* unit) const + { + return unit->GetTypeId() == TYPEID_PLAYER && _me->GetDistance2d(unit) > 25.0f; + } -private: - Unit const* _me; + private: + Unit const* _me; }; class boss_illidan_stormrage : public CreatureScript @@ -676,7 +680,7 @@ public: void EnterEvadeModeIfNeeded() { - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + 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)) @@ -1887,9 +1891,7 @@ class spell_illidan_akama_door_channel : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ARCANE_EXPLOSION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ARCANE_EXPLOSION }); } void OnRemoveDummy(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1926,9 +1928,7 @@ class spell_illidan_draw_soul : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRAW_SOUL_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRAW_SOUL_HEAL }); } void HandleScriptEffect(SpellEffIndex effIndex) @@ -1962,9 +1962,7 @@ class spell_illidan_parasitic_shadowfiend : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_PARASITIC_SHADOWFIENDS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_PARASITIC_SHADOWFIENDS }); } void HandleEffectRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2026,9 +2024,7 @@ class spell_illidan_tear_of_azzinoth_channel : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_UNCAGED_WRATH)) - return false; - return true; + return ValidateSpellInfo({ SPELL_UNCAGED_WRATH }); } void OnPeriodic(AuraEffect const* /*aurEff*/) @@ -2069,9 +2065,7 @@ class spell_illidan_flame_blast : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BLAZE_SUMMON)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BLAZE_SUMMON }); } void HandleBlaze(SpellEffIndex /*effIndex*/) @@ -2133,9 +2127,7 @@ class spell_illidan_agonizing_flames : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_AGONIZING_FLAMES)) - return false; - return true; + return ValidateSpellInfo({ SPELL_AGONIZING_FLAMES }); } void FilterTargets(std::list& targets) @@ -2178,9 +2170,7 @@ class spell_illidan_demon_transform1 : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DEMON_TRANSFORM_2)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DEMON_TRANSFORM_2 }); } void OnPeriodic(AuraEffect const* /*aurEff*/) @@ -2214,10 +2204,7 @@ class spell_illidan_demon_transform2 : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DEMON_FORM) - || !sSpellMgr->GetSpellInfo(SPELL_DEMON_TRANSFORM_3)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DEMON_FORM, SPELL_DEMON_TRANSFORM_3 }); } void OnPeriodic(AuraEffect const* aurEff) @@ -2265,9 +2252,7 @@ class spell_illidan_flame_burst : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FLAME_BURST_EFFECT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FLAME_BURST_EFFECT }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -2299,9 +2284,7 @@ class spell_illidan_find_target : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PARALYZE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PARALYZE }); } void FilterTargets(std::list& targets) @@ -2418,9 +2401,7 @@ class spell_illidan_caged : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CAGED_DEBUFF)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CAGED_DEBUFF }); } void OnPeriodic(AuraEffect const* /*aurEff*/) diff --git a/src/server/scripts/Outland/BlackTemple/boss_illidari_council.cpp b/src/server/scripts/Outland/BlackTemple/boss_illidari_council.cpp index 85f2efca148..c049546b1b9 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_illidari_council.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_illidari_council.cpp @@ -16,14 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" #include "black_temple.h" -#include "Cell.h" #include "CellImpl.h" #include "GridNotifiers.h" +#include "InstanceScript.h" #include "PassiveAI.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Says { @@ -303,18 +303,18 @@ private: uint32 _bossId; }; -class HammerTargetSelector : public std::unary_function +class HammerTargetSelector { -public: - HammerTargetSelector(Unit const* unit) : _me(unit) { } + public: + HammerTargetSelector(Unit const* unit) : _me(unit) { } - bool operator()(Unit* unit) const - { - return _me->IsInRange(unit, 10.0f, 40.0f); - } + bool operator()(Unit* unit) const + { + return _me->IsInRange(unit, 10.0f, 40.0f); + } -private: - Unit const* _me; + private: + Unit const* _me; }; class boss_gathios_the_shatterer : public CreatureScript @@ -630,9 +630,7 @@ class spell_illidari_council_empyreal_balance : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BALANCE_OF_POWER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BALANCE_OF_POWER }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -697,9 +695,7 @@ class spell_illidari_council_balance_of_power : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHARED_RULE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHARED_RULE }); } void Absorb(AuraEffect* aurEff, DamageInfo& dmgInfo, uint32& /*absorbAmount*/) @@ -733,9 +729,7 @@ class spell_illidari_council_deadly_strike : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DEADLY_POISON)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DEADLY_POISON }); } void OnTrigger(AuraEffect const* aurEff) @@ -770,9 +764,7 @@ class spell_illidari_council_deadly_poison : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ENVENOM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ENVENOM }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -805,9 +797,7 @@ class spell_illidari_council_reflective_shield : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_REFLECTIVE_SHIELD_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_REFLECTIVE_SHIELD_DAMAGE }); } void OnAbsorb(AuraEffect* aurEff, DamageInfo & dmgInfo, uint32 & absorbAmount) @@ -844,11 +834,7 @@ class spell_illidari_council_judgement : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_JUDGEMENT_OF_BLOOD) - || !sSpellMgr->GetSpellInfo(SPELL_JUDGEMENT_OF_COMMAND) - || !sSpellMgr->GetSpellInfo(SPELL_JUDGEMENT_PRIMER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_JUDGEMENT_OF_BLOOD, SPELL_JUDGEMENT_OF_COMMAND, SPELL_JUDGEMENT_PRIMER }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -892,10 +878,7 @@ class spell_illidari_council_seal : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SEAL_OF_COMMAND) - || !sSpellMgr->GetSpellInfo(SPELL_SEAL_OF_BLOOD)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SEAL_OF_COMMAND, SPELL_SEAL_OF_BLOOD }); } void OnRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Outland/BlackTemple/boss_mother_shahraz.cpp b/src/server/scripts/Outland/BlackTemple/boss_mother_shahraz.cpp index 3c35fd63aae..cd56e216bf5 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_mother_shahraz.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_mother_shahraz.cpp @@ -17,11 +17,11 @@ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "black_temple.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" #include "GridNotifiers.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Texts { @@ -218,10 +218,7 @@ class spell_mother_shahraz_fatal_attraction : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SABER_LASH_IMMUNITY) - || !sSpellMgr->GetSpellInfo(SPELL_FATAL_ATTRACTION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SABER_LASH_IMMUNITY, SPELL_FATAL_ATTRACTION }); } void FilterTargets(std::list& targets) @@ -265,9 +262,7 @@ class spell_mother_shahraz_fatal_attraction_link : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FATAL_ATTRACTION_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FATAL_ATTRACTION_DAMAGE }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -299,9 +294,7 @@ class spell_mother_shahraz_saber_lash : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_1].TriggerSpell)) - return false; - return true; + return ValidateSpellInfo({ spellInfo->Effects[EFFECT_1].TriggerSpell }); } void OnTrigger(AuraEffect const* aurEff) @@ -340,9 +333,7 @@ class spell_mother_shahraz_generic_periodic : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].TriggerSpell)) - return false; - return true; + return ValidateSpellInfo({ spellInfo->Effects[EFFECT_0].TriggerSpell }); } void OnTrigger(AuraEffect const* aurEff) @@ -378,10 +369,7 @@ class spell_mother_shahraz_random_periodic : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - for (uint32 spellId : RandomBeam) - if (!sSpellMgr->GetSpellInfo(spellId)) - return false; - return true; + return ValidateSpellInfo(RandomBeam); } void OnPeriodic(AuraEffect const* /*aurEffect*/) 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 252270eeaaa..e743580b440 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_reliquary_of_souls.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_reliquary_of_souls.cpp @@ -16,12 +16,13 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "black_temple.h" -#include "Spell.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" +#include "InstanceScript.h" +#include "MotionMaster.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Says { @@ -727,9 +728,7 @@ class spell_reliquary_of_souls_aura_of_desire : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_AURA_OF_DESIRE_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_AURA_OF_DESIRE_DAMAGE }); } void OnProcSpell(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -809,9 +808,7 @@ class spell_reliquary_of_souls_spite : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SPITE_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SPITE_DAMAGE }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) 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 344097aec1e..4b806e3fda8 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_shade_of_akama.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_shade_of_akama.cpp @@ -15,15 +15,19 @@ * with this program. If not, see . */ -#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 "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "PassiveAI.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" #include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum Says { @@ -286,7 +290,7 @@ public: void EnterEvadeModeIfNeeded() { - Map::PlayerList const &players = me->GetMap()->GetPlayers(); + 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)) @@ -1200,9 +1204,7 @@ public: bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHADE_SOUL_CHANNEL_2)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHADE_SOUL_CHANNEL_2 }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Outland/BlackTemple/boss_supremus.cpp b/src/server/scripts/Outland/BlackTemple/boss_supremus.cpp index 093cce5f485..9eb5c432428 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_supremus.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_supremus.cpp @@ -16,9 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "PassiveAI.h" #include "black_temple.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "PassiveAI.h" +#include "ScriptedCreature.h" enum Texts { diff --git a/src/server/scripts/Outland/BlackTemple/boss_teron_gorefiend.cpp b/src/server/scripts/Outland/BlackTemple/boss_teron_gorefiend.cpp index 4a40496fec0..15f78234b75 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_teron_gorefiend.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_teron_gorefiend.cpp @@ -16,12 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "black_temple.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "PassiveAI.h" #include "Player.h" -#include "SpellScript.h" +#include "ScriptedCreature.h" #include "SpellAuraEffects.h" +#include "SpellScript.h" enum Says { @@ -231,6 +234,7 @@ class npc_doom_blossom : public CreatureScript { public: npc_doom_blossom() : CreatureScript("npc_doom_blossom") { } + struct npc_doom_blossomAI : public NullCreatureAI { npc_doom_blossomAI(Creature* creature) : NullCreatureAI(creature), _instance(me->GetInstanceScript()) { } @@ -391,15 +395,16 @@ class spell_teron_gorefiend_shadow_of_death : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_SPIRIT) - || !sSpellMgr->GetSpellInfo(SPELL_POSSESS_SPIRIT_IMMUNE) - || !sSpellMgr->GetSpellInfo(SPELL_SPIRITUAL_VENGEANCE) - || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_SKELETRON_1) - || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_SKELETRON_2) - || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_SKELETRON_3) - || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_SKELETRON_4)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SUMMON_SPIRIT, + SPELL_POSSESS_SPIRIT_IMMUNE, + SPELL_SPIRITUAL_VENGEANCE, + SPELL_SUMMON_SKELETRON_1, + SPELL_SUMMON_SKELETRON_2, + SPELL_SUMMON_SKELETRON_3, + SPELL_SUMMON_SKELETRON_4 + }); } void Absorb(AuraEffect* /*aurEff*/, DamageInfo& /*dmgInfo*/, uint32& /*absorbAmount*/) @@ -475,9 +480,7 @@ class spell_teron_gorefiend_shadow_of_death_remove : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHADOW_OF_DEATH) - || !sSpellMgr->GetSpellInfo(SPELL_POSSESS_SPIRIT_IMMUNE) - || !sSpellMgr->GetSpellInfo(SPELL_SPIRITUAL_VENGEANCE)) + return ValidateSpellInfo({ SPELL_SHADOW_OF_DEATH, SPELL_POSSESS_SPIRIT_IMMUNE, SPELL_SPIRITUAL_VENGEANCE }); return false; return true; } diff --git a/src/server/scripts/Outland/BlackTemple/boss_warlord_najentus.cpp b/src/server/scripts/Outland/BlackTemple/boss_warlord_najentus.cpp index f0b490a1ae4..cb25f32e99b 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_warlord_najentus.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_warlord_najentus.cpp @@ -16,13 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "black_temple.h" +#include "GameObjectAI.h" +#include "GridNotifiers.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" #include "SpellScript.h" -#include "GridNotifiers.h" -#include "GameObjectAI.h" enum Texts { @@ -88,7 +90,7 @@ public: Talk(SAY_DEATH); } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_HURL_SPINE && me->HasAura(SPELL_TIDAL_SHIELD)) { @@ -140,7 +142,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, G3D::Quat(), 30); + target->SummonGameObject(GO_NAJENTUS_SPINE, *target, QuaternionData(), 30); Talk(SAY_NEEDLE); } events.Repeat(Seconds(20), Seconds(25)); @@ -175,24 +177,27 @@ class go_najentus_spine : public GameObjectScript struct go_najentus_spineAI : public GameObjectAI { - go_najentus_spineAI(GameObject* go) : GameObjectAI(go) { } + go_najentus_spineAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* player) override { - if (InstanceScript* instance = me->GetInstanceScript()) - if (Creature* najentus = instance->GetCreature(DATA_HIGH_WARLORD_NAJENTUS)) - if (ENSURE_AI(boss_najentus::boss_najentusAI, najentus->AI())->RemoveImpalingSpine()) - { - me->CastSpell(player, SPELL_CREATE_NAJENTUS_SPINE, true); - me->Delete(); - } + if (Creature* najentus = instance->GetCreature(DATA_HIGH_WARLORD_NAJENTUS)) + { + if (ENSURE_AI(boss_najentus::boss_najentusAI, najentus->AI())->RemoveImpalingSpine()) + { + me->CastSpell(player, SPELL_CREATE_NAJENTUS_SPINE, true); + me->Delete(); + } + } return true; } }; GameObjectAI* GetAI(GameObject* go) const override { - return new go_najentus_spineAI(go); + return GetBlackTempleAI(go); } }; @@ -208,9 +213,7 @@ class spell_najentus_needle_spine : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_NEEDLE_SPINE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_NEEDLE_SPINE }); } void FilterTargets(std::list& targets) diff --git a/src/server/scripts/Outland/BlackTemple/instance_black_temple.cpp b/src/server/scripts/Outland/BlackTemple/instance_black_temple.cpp index a4d3c3f923a..08265ecc208 100644 --- a/src/server/scripts/Outland/BlackTemple/instance_black_temple.cpp +++ b/src/server/scripts/Outland/BlackTemple/instance_black_temple.cpp @@ -16,8 +16,13 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" +#include "AreaBoundary.h" #include "black_temple.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" DoorData const doorData[] = { diff --git a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_fathomlord_karathress.cpp b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_fathomlord_karathress.cpp index f6dc16e837a..c297cb14460 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_fathomlord_karathress.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_fathomlord_karathress.cpp @@ -24,9 +24,12 @@ SDCategory: Coilfang Resevoir, Serpent Shrine Cavern EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "serpent_shrine.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedEscortAI.h" +#include "serpent_shrine.h" +#include "TemporarySummon.h" enum FathomlordKarathress { @@ -104,7 +107,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct boss_fathomlord_karathressAI : public ScriptedAI @@ -303,7 +306,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct boss_fathomguard_sharkkisAI : public ScriptedAI @@ -341,7 +344,7 @@ public: Creature* Pet = ObjectAccessor::GetCreature(*me, SummonedPet); if (Pet && Pet->IsAlive()) - Pet->DealDamage(Pet, Pet->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + Pet->DealDamage(Pet, Pet->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); SummonedPet.Clear(); @@ -447,7 +450,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct boss_fathomguard_tidalvessAI : public ScriptedAI @@ -569,7 +572,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct boss_fathomguard_caribdisAI : public ScriptedAI @@ -674,9 +677,9 @@ public: if (Heal_Timer <= diff) { // It can be cast on any of the mobs - Unit* unit = NULL; + Unit* unit = nullptr; - while (unit == NULL || !unit->IsAlive()) + while (unit == nullptr || !unit->IsAlive()) unit = selectAdvisorUnit(); if (unit && unit->IsAlive()) @@ -691,7 +694,7 @@ public: Unit* selectAdvisorUnit() { - Unit* unit = NULL; + Unit* unit = nullptr; switch (rand32() % 4) { case 0: diff --git a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_hydross_the_unstable.cpp b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_hydross_the_unstable.cpp index 33771cc7091..7697ce32972 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_hydross_the_unstable.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_hydross_the_unstable.cpp @@ -24,8 +24,11 @@ SDCategory: Coilfang Resevoir, Serpent Shrine Cavern EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "serpent_shrine.h" +#include "TemporarySummon.h" enum HydrossTheUnstable { @@ -86,7 +89,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct boss_hydross_the_unstableAI : public ScriptedAI @@ -220,7 +223,7 @@ public: if (!beam) { SummonBeams(); - beam=true; + beam = true; } //Return since we have no target if (!UpdateVictim()) 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 4e94cd1edbc..44b631dec5a 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lady_vashj.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lady_vashj.cpp @@ -24,10 +24,16 @@ SDCategory: Coilfang Resevoir, Serpent Shrine Cavern EndScriptData */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "serpent_shrine.h" #include "Spell.h" -#include "Player.h" +#include "TemporarySummon.h" #include "WorldSession.h" enum LadyVashj @@ -140,7 +146,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct boss_lady_vashjAI : public ScriptedAI @@ -257,7 +263,7 @@ public: void JustEngagedWith(Unit* who) override { // remove old tainted cores to prevent cheating in phase 2 - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) if (Player* player = itr->GetSource()) player->DestroyItemCount(31088, 1, true); @@ -327,7 +333,7 @@ public: } else { - AggroTimer-=diff; + AggroTimer -= diff; return; } } @@ -555,7 +561,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct npc_enchanted_elementalAI : public ScriptedAI @@ -650,7 +656,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct npc_tainted_elementalAI : public ScriptedAI @@ -724,7 +730,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct npc_toxic_sporebatAI : public ScriptedAI @@ -826,7 +832,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct npc_shield_generator_channelAI : public ScriptedAI 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 710e4c56f47..64f1f000d6b 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 @@ -24,9 +24,14 @@ SDCategory: Coilfang Resevoir, Serpent Shrine Cavern EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "ScriptedCreature.h" #include "serpent_shrine.h" -#include "Player.h" +#include "TemporarySummon.h" enum LeotherasTheBlind { @@ -76,7 +81,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_inner_demonAI(creature); + return GetSerpentshrineCavernAI(creature); } struct npc_inner_demonAI : public ScriptedAI @@ -153,7 +158,7 @@ public: AttackStart(owner); } else if (owner && owner->isDead()) { - 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; } } @@ -186,7 +191,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct boss_leotheras_the_blindAI : public ScriptedAI @@ -512,7 +517,7 @@ public: { //DoCastVictim(SPELL_CHAOS_BLAST, true); int damage = 100; - me->CastCustomSpell(me->GetVictim(), SPELL_CHAOS_BLAST, &damage, NULL, NULL, false, NULL, NULL, me->GetGUID()); + me->CastCustomSpell(me->GetVictim(), SPELL_CHAOS_BLAST, &damage, nullptr, nullptr, false, nullptr, nullptr, me->GetGUID()); } ChaosBlast_Timer = 3000; } else ChaosBlast_Timer -= diff; @@ -604,7 +609,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_leotheras_the_blind_demonformAI(creature); + return GetSerpentshrineCavernAI(creature); } struct boss_leotheras_the_blind_demonformAI : public ScriptedAI @@ -668,7 +673,7 @@ public: { //DoCastVictim(SPELL_CHAOS_BLAST, true); int damage = 100; - me->CastCustomSpell(me->GetVictim(), SPELL_CHAOS_BLAST, &damage, NULL, NULL, false, NULL, NULL, me->GetGUID()); + me->CastCustomSpell(me->GetVictim(), SPELL_CHAOS_BLAST, &damage, nullptr, nullptr, false, nullptr, nullptr, me->GetGUID()); ChaosBlast_Timer = 3000; } } else ChaosBlast_Timer -= diff; @@ -685,7 +690,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct npc_greyheart_spellbinderAI : public ScriptedAI @@ -780,7 +785,7 @@ public: if (Earthshock_Timer <= diff) { - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator itr = PlayerList.begin(); itr != PlayerList.end(); ++itr) { if (Player* i_pl = itr->GetSource()) diff --git a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lurker_below.cpp b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lurker_below.cpp index 54eb1414755..ab0f5531409 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lurker_below.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lurker_below.cpp @@ -24,11 +24,16 @@ SDCategory: The Lurker Below EndScriptData */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "InstanceScript.h" +#include "Map.h" +#include "MotionMaster.h" +#include "Player.h" #include "ScriptedCreature.h" #include "serpent_shrine.h" #include "Spell.h" -#include "Player.h" -#include "GameObjectAI.h" +#include "TemporarySummon.h" enum Spells { @@ -84,7 +89,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct boss_the_lurker_belowAI : public ScriptedAI @@ -170,7 +175,6 @@ public: } void MoveInLineOfSight(Unit* who) override - { if (!CanStartEvent) // boss is invisible, don't attack return; @@ -200,8 +204,7 @@ public: Submerged = false; WaitTimer2 = 500; } - - if (!Submerged && WaitTimer2 <= diff) // wait 500ms before emerge anim + else if (WaitTimer2 <= diff) // wait 500ms before emerge anim { me->RemoveAllAuras(); me->SetUInt32Value(UNIT_NPC_EMOTESTATE, 0); @@ -239,7 +242,9 @@ public: DoCast(me, SPELL_SUBMERGE); PhaseTimer = 60000; // 60secs submerged Submerged = true; - } else PhaseTimer-=diff; + } + else + PhaseTimer -= diff; if (SpoutTimer <= diff) { @@ -250,19 +255,23 @@ public: WhirlTimer = 20000; // whirl directly after spout RotTimer = 20000; return; - } else SpoutTimer -= diff; + } + else + SpoutTimer -= diff; // Whirl directly after a Spout and at random times if (WhirlTimer <= diff) { WhirlTimer = 18000; DoCast(me, SPELL_WHIRL); - } else WhirlTimer -= diff; + } + else + WhirlTimer -= diff; if (CheckTimer <= diff)//check if there are players in melee range { InRange = false; - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); if (!PlayerList.isEmpty()) { for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -272,11 +281,13 @@ public: } } CheckTimer = 2000; - } else CheckTimer -= diff; + } + else + CheckTimer -= diff; if (RotTimer) { - Map::PlayerList const &PlayerList = me->GetMap()->GetPlayers(); + Map::PlayerList const& PlayerList = me->GetMap()->GetPlayers(); for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) { if (i->GetSource() && i->GetSource()->IsAlive() && me->HasInArc(diff/20000.f*float(M_PI)*2.f, i->GetSource()) && me->IsWithinDist(i->GetSource(), SPOUT_DIST) && !i->GetSource()->IsInWater()) @@ -292,7 +303,9 @@ public: if (RotTimer <= diff) { RotTimer = 0; - } else RotTimer -= diff; + } + else + RotTimer -= diff; return; } @@ -304,7 +317,9 @@ public: if (target) DoCast(target, SPELL_GEYSER, true); GeyserTimer = rand32() % 5000 + 15000; - } else GeyserTimer -= diff; + } + else + GeyserTimer -= diff; if (!InRange) // if on players in melee range cast Waterbolt { @@ -316,7 +331,9 @@ public: if (target) DoCast(target, SPELL_WATERBOLT, true); WaterboltTimer = 3000; - } else WaterboltTimer -= diff; + } + else + WaterboltTimer -= diff; } if (!UpdateVictim()) @@ -339,7 +356,9 @@ public: SpoutTimer = 3000; // directly cast Spout after emerging! PhaseTimer = 120000; return; - } else PhaseTimer-=diff; + } + else + PhaseTimer -= diff; if (me->getThreatManager().getThreatList().empty()) // check if should evade { @@ -371,7 +390,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_coilfang_ambusherAI(creature); + return GetSerpentshrineCavernAI(creature); } struct npc_coilfang_ambusherAI : public ScriptedAI @@ -421,7 +440,7 @@ public: { int bp0 = 1100; if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) - me->CastCustomSpell(target, SPELL_SHOOT, &bp0, NULL, NULL, true); + me->CastCustomSpell(target, SPELL_SHOOT, &bp0, nullptr, nullptr, true); ShootBowTimer = 4000 + rand32() % 5000; MultiShotTimer += 1500; // add global cooldown } else ShootBowTimer -= diff; @@ -437,21 +456,22 @@ class go_strange_pool : public GameObjectScript struct go_strange_poolAI : public GameObjectAI { - go_strange_poolAI(GameObject* go) : GameObjectAI(go) { } + go_strange_poolAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* player) override { // 25% - if (InstanceScript* instanceScript = me->GetInstanceScript()) - if (!urand(0, 3)) + if (!urand(0, 3)) + { + if (instance->GetData(DATA_STRANGE_POOL) == NOT_STARTED) { - if (instanceScript->GetData(DATA_STRANGE_POOL) == NOT_STARTED) - { - me->CastSpell(player, 54587); - instanceScript->SetData(DATA_STRANGE_POOL, IN_PROGRESS); - } - return true; + me->CastSpell(player, 54587); + instance->SetData(DATA_STRANGE_POOL, IN_PROGRESS); } + return true; + } return false; } @@ -459,7 +479,7 @@ class go_strange_pool : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return new go_strange_poolAI(go); + return GetSerpentshrineCavernAI(go); } }; diff --git a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_morogrim_tidewalker.cpp b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_morogrim_tidewalker.cpp index 9543e4e10ea..544cd536447 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_morogrim_tidewalker.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_morogrim_tidewalker.cpp @@ -24,8 +24,11 @@ SDCategory: Coilfang Resevoir, Serpent Shrine Cavern EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "Map.h" #include "ScriptedCreature.h" #include "serpent_shrine.h" +#include "TemporarySummon.h" enum Yells { @@ -91,7 +94,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSerpentshrineCavernAI(creature); } struct boss_morogrim_tidewalkerAI : public ScriptedAI @@ -296,7 +299,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_water_globuleAI(creature); + return GetSerpentshrineCavernAI(creature); } struct npc_water_globuleAI : public ScriptedAI diff --git a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/instance_serpent_shrine.cpp b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/instance_serpent_shrine.cpp index 71810ff2a5e..f59768ef65f 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/instance_serpent_shrine.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/instance_serpent_shrine.cpp @@ -24,11 +24,14 @@ SDCategory: Coilfang Resevoir, Serpent Shrine Cavern EndScriptData */ #include "ScriptMgr.h" -#include "InstanceScript.h" -#include "serpent_shrine.h" -#include "Player.h" -#include "TemporarySummon.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "InstanceScript.h" +#include "Log.h" +#include "Map.h" +#include "Player.h" +#include "serpent_shrine.h" +#include "TemporarySummon.h" #define MAX_ENCOUNTER 6 @@ -67,32 +70,28 @@ class go_bridge_console : public GameObjectScript struct go_bridge_consoleAI : public GameObjectAI { - go_bridge_consoleAI(GameObject* go) : GameObjectAI(go) { } + go_bridge_consoleAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* /*player*/) override { - InstanceScript* instance = me->GetInstanceScript(); - - if (!instance) - return false; - if (instance) instance->SetData(DATA_CONTROL_CONSOLE, DONE); - return true; } }; GameObjectAI* GetAI(GameObject* go) const override { - return new go_bridge_consoleAI(go); + return GetSerpentshrineCavernAI(go); } }; class instance_serpent_shrine : public InstanceMapScript { public: - instance_serpent_shrine() : InstanceMapScript("instance_serpent_shrine", 548) { } + instance_serpent_shrine() : InstanceMapScript(SSCScriptName, 548) { } struct instance_serpentshrine_cavern_InstanceMapScript : public InstanceScript { @@ -134,7 +133,7 @@ class instance_serpent_shrine : public InstanceMapScript else Water = WATERSTATE_FRENZY; - Map::PlayerList const &PlayerList = instance->GetPlayers(); + Map::PlayerList const& PlayerList = instance->GetPlayers(); if (PlayerList.isEmpty()) return; for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) @@ -145,12 +144,11 @@ class instance_serpent_shrine : public InstanceMapScript { if (Water == WATERSTATE_SCALDING) { - if (!player->HasAura(SPELL_SCALDINGWATER)) - { player->CastSpell(player, SPELL_SCALDINGWATER, true); - } - } else + + } + else { //spawn frenzy if (DoSpawnFrenzy) @@ -398,7 +396,7 @@ class instance_serpent_shrine : public InstanceMapScript return stream.str(); } - void Load(const char* in) override + void Load(char const* in) override { if (!in) { diff --git a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/serpent_shrine.h b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/serpent_shrine.h index 3d2a4ea45ce..488d9fbc95d 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/serpent_shrine.h +++ b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/serpent_shrine.h @@ -19,6 +19,9 @@ #ifndef DEF_SERPENT_SHRINE_H #define DEF_SERPENT_SHRINE_H +#include "CreatureAIImpl.h" + +#define SSCScriptName "instance_serpent_shrine" #define DataHeader "SS" enum SSWaterEventState @@ -57,4 +60,10 @@ enum SSDataTypes DATA_TRASH = 25, }; +template +inline AI* GetSerpentshrineCavernAI(T* obj) +{ + return GetInstanceAI(obj, SSCScriptName); +} + #endif diff --git a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_hydromancer_thespia.cpp b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_hydromancer_thespia.cpp index 48857041337..cee8aad089f 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_hydromancer_thespia.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_hydromancer_thespia.cpp @@ -114,7 +114,7 @@ class boss_hydromancer_thespia : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSteamVaultAI(creature); } }; @@ -175,7 +175,7 @@ class npc_coilfang_waterelemental : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_coilfang_waterelementalAI(creature); + return GetSteamVaultAI(creature); } }; diff --git a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_mekgineer_steamrigger.cpp b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_mekgineer_steamrigger.cpp index 390d861730f..8cc0e9ac5c9 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_mekgineer_steamrigger.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_mekgineer_steamrigger.cpp @@ -23,6 +23,8 @@ SDCategory: Coilfang Resevoir, The Steamvault EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "steam_vault.h" @@ -57,7 +59,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSteamVaultAI(creature); } struct boss_mekgineer_steamriggerAI : public ScriptedAI @@ -200,7 +202,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSteamVaultAI(creature); } struct npc_steamrigger_mechanicAI : public ScriptedAI diff --git a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_warlord_kalithresh.cpp b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_warlord_kalithresh.cpp index 0c3dd765e11..46a02b2400f 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_warlord_kalithresh.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/boss_warlord_kalithresh.cpp @@ -23,9 +23,10 @@ SDCategory: Coilfang Resevoir, The Steamvault EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" #include "ScriptedCreature.h" -#include "steam_vault.h" #include "SpellInfo.h" +#include "steam_vault.h" enum NagaDistiller { @@ -50,7 +51,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSteamVaultAI(creature); } struct npc_naga_distillerAI : public ScriptedAI @@ -103,7 +104,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSteamVaultAI(creature); } struct boss_warlord_kalithreshAI : public ScriptedAI @@ -148,7 +149,7 @@ public: Talk(SAY_SLAY); } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { //hack :( if (spell->Id == SPELL_WARLORDS_RAGE_PROC) diff --git a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/instance_steam_vault.cpp b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/instance_steam_vault.cpp index 73ad79d47b1..89aad194086 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/instance_steam_vault.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/instance_steam_vault.cpp @@ -16,9 +16,13 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" -#include "steam_vault.h" +#include "Creature.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "InstanceScript.h" +#include "Log.h" +#include "Map.h" +#include "steam_vault.h" class go_main_chambers_access_panel : public GameObjectScript { @@ -27,14 +31,12 @@ class go_main_chambers_access_panel : public GameObjectScript struct go_main_chambers_access_panelAI : public GameObjectAI { - go_main_chambers_access_panelAI(GameObject* go) : GameObjectAI(go) { } + go_main_chambers_access_panelAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* /*player*/) override { - InstanceScript* instance = me->GetInstanceScript(); - if (!instance) - return false; - if (me->GetEntry() == GO_ACCESS_PANEL_HYDRO && (instance->GetBossState(DATA_HYDROMANCER_THESPIA) == DONE || instance->GetBossState(DATA_HYDROMANCER_THESPIA) == SPECIAL)) instance->SetBossState(DATA_HYDROMANCER_THESPIA, SPECIAL); @@ -43,14 +45,13 @@ class go_main_chambers_access_panel : public GameObjectScript me->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE); me->SetGoState(GO_STATE_ACTIVE); - return true; } }; GameObjectAI* GetAI(GameObject* go) const override { - return new go_main_chambers_access_panelAI(go); + return GetSteamVaultAI(go); } }; diff --git a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/steam_vault.h b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/steam_vault.h index 9d80f1a6a86..be4c4635ee1 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/steam_vault.h +++ b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/steam_vault.h @@ -18,6 +18,8 @@ #ifndef DEF_STEAM_VAULT_H #define DEF_STEAM_VAULT_H +#include "CreatureAIImpl.h" + #define SteamVaultScriptName "instance_steam_vault" #define DataHeader "SV" @@ -49,10 +51,10 @@ enum SVGameObjectIds GO_ACCESS_PANEL_MEK = 184126 }; -template -AI* GetSteamVaultAI(Creature* creature) +template +inline AI* GetSteamVaultAI(T* obj) { - return GetInstanceAI(creature, SteamVaultScriptName); + return GetInstanceAI(obj, SteamVaultScriptName); } #endif diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_ahune.cpp b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_ahune.cpp index aceee192b45..904310869c6 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_ahune.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_ahune.cpp @@ -15,15 +15,23 @@ * with this program. If not, see . */ -#include "CreatureTextMgr.h" -#include "LFGMgr.h" -#include "ScriptedGossip.h" -#include "ScriptedCreature.h" #include "ScriptMgr.h" +#include "CreatureTextMgr.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "Group.h" +#include "InstanceScript.h" +#include "LFGMgr.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "ScriptedGossip.h" #include "SpellAuraEffects.h" #include "SpellScript.h" +#include "TemporarySummon.h" #include "the_slave_pens.h" -#include "GameObjectAI.h" enum Spells { @@ -280,7 +288,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSlavePensAI(creature); } }; @@ -358,7 +366,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSlavePensAI(creature); } }; @@ -396,7 +404,7 @@ public: _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); + me->SummonGameObject(GO_ICE_STONE, -69.90455f, -162.2449f, -2.366563f, 2.426008f, QuaternionData(0.0f, 0.0f, 0.9366722f, 0.3502074f), 0); } void DoAction(int32 action) override @@ -510,7 +518,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSlavePensAI(creature); } }; @@ -638,7 +646,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetSlavePensAI(creature); } }; @@ -649,14 +657,12 @@ public: struct go_ahune_ice_stoneAI : public GameObjectAI { - go_ahune_ice_stoneAI(GameObject* go) : GameObjectAI(go) { } + go_ahune_ice_stoneAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipSelect(Player* player, uint32 /*menuId*/, uint32 /*gossipListId*/) override { - InstanceScript* instance = me->GetInstanceScript(); - if (!instance) - return false; - ClearGossipMenuFor(player); if (Creature* ahuneBunny = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_AHUNE_BUNNY))) @@ -674,7 +680,7 @@ public: GameObjectAI* GetAI(GameObject* go) const override { - return new go_ahune_ice_stoneAI(go); + return GetSlavePensAI(go); } }; @@ -690,9 +696,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SYNCH_HEALTH)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SYNCH_HEALTH }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -726,9 +730,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FORCE_WHISP_FLIGHT) || !sSpellMgr->GetSpellInfo(SPELL_SUMMONING_RHYME_BONFIRE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FORCE_WHISP_FLIGHT, SPELL_SUMMONING_RHYME_BONFIRE }); } void PeriodicTick(AuraEffect const* aurEff) @@ -744,14 +746,14 @@ public: 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); + sCreatureTextMgr->SendChat(caster, SAY_PLAYER_TEXT_1, nullptr, 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); + sCreatureTextMgr->SendChat(caster, SAY_PLAYER_TEXT_2, nullptr, 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); + sCreatureTextMgr->SendChat(caster, SAY_PLAYER_TEXT_3, nullptr, CHAT_MSG_SAY, LANG_UNIVERSAL, TEXT_RANGE_NORMAL, 0, TEAM_OTHER, false, player); Remove(); break; } @@ -781,9 +783,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_ICE_SPEAR_GO) || !sSpellMgr->GetSpellInfo(SPELL_ICE_SPEAR_KNOCKBACK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_ICE_SPEAR_GO, SPELL_ICE_SPEAR_KNOCKBACK }); } void PeriodicTick(AuraEffect const* aurEff) @@ -834,9 +834,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ICE_SPEAR_TARGET_PICKER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ICE_SPEAR_TARGET_PICKER }); } void PeriodicTick(AuraEffect const* /*aurEff*/) @@ -869,9 +867,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_ICE_SPEAR_BUNNY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_ICE_SPEAR_BUNNY }); } void FilterTargets(std::list& targets) @@ -914,9 +910,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SLIPPERY_FLOOR_SLIP)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SLIPPERY_FLOOR_SLIP }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -953,9 +947,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_COLD_SLAP)) - return false; - return true; + return ValidateSpellInfo({ SPELL_COLD_SLAP }); } void HandleProc(AuraEffect const* /*aurEff*/, ProcEventInfo& eventInfo) @@ -1015,9 +1007,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ICE_BOMBARDMENT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ICE_BOMBARDMENT }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_mennu_the_betrayer.cpp b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_mennu_the_betrayer.cpp index 0144d817071..c8dbc4e1068 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_mennu_the_betrayer.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_mennu_the_betrayer.cpp @@ -134,7 +134,7 @@ class boss_mennu_the_betrayer : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_mennu_the_betrayerAI(creature); + return GetSlavePensAI(creature); } }; diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_quagmirran.cpp b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_quagmirran.cpp index dd75e1e4b42..aecdef0c945 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_quagmirran.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_quagmirran.cpp @@ -117,7 +117,7 @@ class boss_quagmirran : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_quagmirranAI(creature); + return GetSlavePensAI(creature); } }; diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_rokmar_the_crackler.cpp b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_rokmar_the_crackler.cpp index 91d1edf025c..15d6a08e32a 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_rokmar_the_crackler.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/boss_rokmar_the_crackler.cpp @@ -128,7 +128,7 @@ class boss_rokmar_the_crackler : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_rokmar_the_cracklerAI(creature); + return GetSlavePensAI(creature); } }; 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 1038604f2a2..23f09fdfd6f 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 @@ -23,7 +23,9 @@ gets instead the deserter debuff. */ #include "ScriptMgr.h" +#include "Creature.h" #include "InstanceScript.h" +#include "Map.h" #include "the_slave_pens.h" class instance_the_slave_pens : public InstanceMapScript 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 044f68a3aaa..2ea69ce5453 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/the_slave_pens.h +++ b/src/server/scripts/Outland/CoilfangReservoir/TheSlavePens/the_slave_pens.h @@ -18,6 +18,8 @@ #ifndef SLAVE_PENS_H #define SLAVE_PENS_H +#include "CreatureAIImpl.h" + uint32 const EncounterCount = 3; #define SPScriptName "instance_the_slave_pens" @@ -66,4 +68,10 @@ enum SPGameObjectIds GO_ICE_STONE = 187882 }; +template +inline AI* GetSlavePensAI(T* obj) +{ + return GetInstanceAI(obj, SPScriptName); +} + #endif // SLAVE_PENS_H diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/boss_hungarfen.cpp b/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/boss_hungarfen.cpp index 0172340670b..4a3ea22703b 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/boss_hungarfen.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/boss_hungarfen.cpp @@ -25,6 +25,7 @@ EndScriptData */ #include "ScriptMgr.h" #include "ScriptedCreature.h" +#include "the_underbog.h" enum Spells { @@ -43,7 +44,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_hungarfenAI(creature); + return GetTheUnderbogAI(creature); } struct boss_hungarfenAI : public ScriptedAI @@ -117,7 +118,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_underbog_mushroomAI(creature); + return GetTheUnderbogAI(creature); } struct npc_underbog_mushroomAI : public ScriptedAI diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/boss_the_black_stalker.cpp b/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/boss_the_black_stalker.cpp index 1940b5b8374..7f15ddbbe70 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/boss_the_black_stalker.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/boss_the_black_stalker.cpp @@ -24,7 +24,9 @@ SDCategory: Coilfang Resevoir, Underbog EndScriptData */ #include "ScriptMgr.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "the_underbog.h" enum Spells { @@ -49,7 +51,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new boss_the_black_stalkerAI(creature); + return GetTheUnderbogAI(creature); } struct boss_the_black_stalkerAI : public ScriptedAI diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/instance_the_underbog.cpp b/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/instance_the_underbog.cpp index 4037386998f..e7983372da7 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/instance_the_underbog.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/instance_the_underbog.cpp @@ -24,11 +24,13 @@ gets instead the deserter debuff. #include "ScriptMgr.h" #include "InstanceScript.h" +#include "Map.h" +#include "the_underbog.h" class instance_the_underbog : public InstanceMapScript { public: - instance_the_underbog() : InstanceMapScript("instance_the_underbog", 546) { } + instance_the_underbog() : InstanceMapScript(TheUndebogScriptName, 546) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { diff --git a/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/the_underbog.h b/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/the_underbog.h new file mode 100644 index 00000000000..92a236091b9 --- /dev/null +++ b/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/the_underbog.h @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#ifndef the_underbog_h__ +#define the_underbog_h__ + +#include "CreatureAIImpl.h" + +#define TheUndebogScriptName "instance_the_underbog" + +template +inline AI* GetTheUnderbogAI(T* obj) +{ + return GetInstanceAI(obj, TheUndebogScriptName); +} + +#endif // the_underbog_h__ diff --git a/src/server/scripts/Outland/GruulsLair/boss_gruul.cpp b/src/server/scripts/Outland/GruulsLair/boss_gruul.cpp index cf5c9f53c8e..07225517163 100644 --- a/src/server/scripts/Outland/GruulsLair/boss_gruul.cpp +++ b/src/server/scripts/Outland/GruulsLair/boss_gruul.cpp @@ -24,9 +24,11 @@ SDCategory: Gruul's Lair EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" #include "gruuls_lair.h" +#include "MotionMaster.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellScript.h" enum Yells { @@ -121,7 +123,7 @@ class boss_gruul : public CreatureScript Talk(SAY_DEATH); } - void SpellHitTarget(Unit* target, const SpellInfo* pSpell) override + void SpellHitTarget(Unit* target, SpellInfo const* pSpell) override { //This to emulate effect1 (77) of SPELL_GROUND_SLAM, knock back to any direction //It's initially wrong, since this will cause fall damage, which is by comments, not intended. @@ -132,11 +134,11 @@ class boss_gruul : public CreatureScript switch (urand(0, 1)) { case 0: - target->CastSpell(target, SPELL_MAGNETIC_PULL, true, NULL, NULL, me->GetGUID()); + target->CastSpell(target, SPELL_MAGNETIC_PULL, true, nullptr, nullptr, me->GetGUID()); break; case 1: - target->CastSpell(target, SPELL_KNOCK_BACK, true, NULL, NULL, me->GetGUID()); + target->CastSpell(target, SPELL_KNOCK_BACK, true, nullptr, nullptr, me->GetGUID()); break; } } @@ -234,7 +236,7 @@ class boss_gruul : public CreatureScript if (m_uiCaveIn_StaticTimer >= 4000) m_uiCaveIn_StaticTimer -= 2000; - m_uiCaveIn_Timer = m_uiCaveIn_StaticTimer; + m_uiCaveIn_Timer = m_uiCaveIn_StaticTimer; } else m_uiCaveIn_Timer -= diff; @@ -275,11 +277,7 @@ class spell_gruul_shatter : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_STONED)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_SHATTER_EFFECT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_STONED, SPELL_SHATTER_EFFECT }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -287,7 +285,7 @@ class spell_gruul_shatter : public SpellScriptLoader if (Unit* target = GetHitUnit()) { target->RemoveAurasDueToSpell(SPELL_STONED); - target->CastSpell((Unit*)NULL, SPELL_SHATTER_EFFECT, true); + target->CastSpell((Unit*)nullptr, SPELL_SHATTER_EFFECT, true); } } diff --git a/src/server/scripts/Outland/GruulsLair/boss_high_king_maulgar.cpp b/src/server/scripts/Outland/GruulsLair/boss_high_king_maulgar.cpp index a3ed0d74ada..d8ff384990f 100644 --- a/src/server/scripts/Outland/GruulsLair/boss_high_king_maulgar.cpp +++ b/src/server/scripts/Outland/GruulsLair/boss_high_king_maulgar.cpp @@ -24,8 +24,11 @@ SDCategory: Gruul's Lair EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "gruuls_lair.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum HighKingMaulgar { @@ -551,7 +554,7 @@ public: //BlastWave_Timer if (BlastWave_Timer <= diff) { - Unit* target = NULL; + Unit* target = nullptr; std::list t_list = me->getThreatManager().getThreatList(); std::vector target_list; for (std::list::const_iterator itr = t_list.begin(); itr!= t_list.end(); ++itr) @@ -560,7 +563,7 @@ public: //15 yard radius minimum if (target && target->IsWithinDist(me, 15, false)) target_list.push_back(target); - target = NULL; + target = nullptr; } if (!target_list.empty()) target = *(target_list.begin() + rand32() % target_list.size()); diff --git a/src/server/scripts/Outland/GruulsLair/gruuls_lair.h b/src/server/scripts/Outland/GruulsLair/gruuls_lair.h index 86d53002a71..b7381dbfb05 100644 --- a/src/server/scripts/Outland/GruulsLair/gruuls_lair.h +++ b/src/server/scripts/Outland/GruulsLair/gruuls_lair.h @@ -18,6 +18,8 @@ #ifndef GRUULS_LAIR_H_ #define GRUULS_LAIR_H_ +#include "CreatureAIImpl.h" + #define GLScriptName "instance_gruuls_lair" #define DataHeader "GL" @@ -45,10 +47,10 @@ enum GLGameObjectIds GO_GRUUL_DOOR = 184662 }; -template -AI* GetGruulsLairAI(Creature* creature) +template +inline AI* GetGruulsLairAI(T* obj) { - return GetInstanceAI(creature, GLScriptName); + return GetInstanceAI(obj, GLScriptName); } #endif // GRUULS_LAIR_H_ diff --git a/src/server/scripts/Outland/GruulsLair/instance_gruuls_lair.cpp b/src/server/scripts/Outland/GruulsLair/instance_gruuls_lair.cpp index 626ba4b8421..b08c14f7f2f 100644 --- a/src/server/scripts/Outland/GruulsLair/instance_gruuls_lair.cpp +++ b/src/server/scripts/Outland/GruulsLair/instance_gruuls_lair.cpp @@ -16,8 +16,10 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" +#include "Creature.h" #include "gruuls_lair.h" +#include "InstanceScript.h" +#include "Map.h" DoorData const doorData[] = { @@ -52,58 +54,12 @@ class instance_gruuls_lair : public InstanceMapScript void OnCreatureCreate(Creature* creature) override { + InstanceScript::OnCreatureCreate(creature); + switch (creature->GetEntry()) { case NPC_MAULGAR: MaulgarGUID = creature->GetGUID(); - // no break; - case NPC_KROSH_FIREHAND: - case NPC_OLM_THE_SUMMONER: - case NPC_KIGGLER_THE_CRAZED: - case NPC_BLINDEYE_THE_SEER: - AddMinion(creature, true); - break; - default: - break; - } - } - - void OnCreatureRemove(Creature* creature) override - { - switch (creature->GetEntry()) - { - case NPC_MAULGAR: - case NPC_KROSH_FIREHAND: - case NPC_OLM_THE_SUMMONER: - case NPC_KIGGLER_THE_CRAZED: - case NPC_BLINDEYE_THE_SEER: - AddMinion(creature, false); - break; - default: - break; - } - } - - void OnGameObjectCreate(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_MAULGAR_DOOR: - case GO_GRUUL_DOOR: - AddDoor(go, true); - break; - default: - break; - } - } - - void OnGameObjectRemove(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_MAULGAR_DOOR: - case GO_GRUUL_DOOR: - AddDoor(go, false); break; default: break; diff --git a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/blood_furnace.h b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/blood_furnace.h index ba879cd5832..fbda57f4b1d 100644 --- a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/blood_furnace.h +++ b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/blood_furnace.h @@ -18,6 +18,8 @@ #ifndef BLOOD_FURNACE_H_ #define BLOOD_FURNACE_H_ +#include "CreatureAIImpl.h" + #define BFScriptName "instance_blood_furnace" #define DataHeader "BF" @@ -80,10 +82,10 @@ enum BFActionIds ACTION_PREPARE_BROGGOK = 3 }; -template -AI* GetBloodFurnaceAI(Creature* creature) +template +inline AI* GetBloodFurnaceAI(T* obj) { - return GetInstanceAI(creature, BFScriptName); + return GetInstanceAI(obj, BFScriptName); } #endif // BLOOD_FURNACE_H_ diff --git a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_broggok.cpp b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_broggok.cpp index ab9ac593bb5..7c5f5a1b506 100644 --- a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_broggok.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_broggok.cpp @@ -16,11 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" #include "blood_furnace.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" enum Yells { @@ -130,17 +133,18 @@ class go_broggok_lever : public GameObjectScript struct go_broggok_leverAI : public GameObjectAI { - go_broggok_leverAI(GameObject* go) : GameObjectAI(go) { } + go_broggok_leverAI(GameObject* go) : GameObjectAI(go), instance(go->GetInstanceScript()) { } + + InstanceScript* instance; bool GossipHello(Player* /*player*/) override { - if (InstanceScript* instance = me->GetInstanceScript()) - if (instance->GetBossState(DATA_BROGGOK) != DONE && instance->GetBossState(DATA_BROGGOK) != IN_PROGRESS) - { - instance->SetBossState(DATA_BROGGOK, IN_PROGRESS); - if (Creature* broggok = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_BROGGOK))) - broggok->AI()->DoAction(ACTION_PREPARE_BROGGOK); - } + if (instance->GetBossState(DATA_BROGGOK) != DONE && instance->GetBossState(DATA_BROGGOK) != IN_PROGRESS) + { + instance->SetBossState(DATA_BROGGOK, IN_PROGRESS); + if (Creature* broggok = ObjectAccessor::GetCreature(*me, instance->GetGuidData(DATA_BROGGOK))) + broggok->AI()->DoAction(ACTION_PREPARE_BROGGOK); + } me->UseDoorOrButton(); return false; @@ -149,7 +153,7 @@ class go_broggok_lever : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return new go_broggok_leverAI(go); + return GetBloodFurnaceAI(go); } }; @@ -165,18 +169,18 @@ class spell_broggok_poison_cloud : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].TriggerSpell)) - return false; - return true; + return ValidateSpellInfo({ spellInfo->Effects[EFFECT_0].TriggerSpell }); } void PeriodicTick(AuraEffect const* aurEff) { PreventDefaultAction(); + if (!aurEff->GetTotalTicks()) + return; uint32 triggerSpell = GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell; int32 mod = int32(((float(aurEff->GetTickNumber()) / aurEff->GetTotalTicks()) * 0.9f + 0.1f) * 10000 * 2 / 3); - GetTarget()->CastCustomSpell(triggerSpell, SPELLVALUE_RADIUS_MOD, mod, (Unit*)NULL, TRIGGERED_FULL_MASK, NULL, aurEff); + GetTarget()->CastCustomSpell(triggerSpell, SPELLVALUE_RADIUS_MOD, mod, (Unit*)nullptr, TRIGGERED_FULL_MASK, nullptr, aurEff); } void Register() override diff --git a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_kelidan_the_breaker.cpp b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_kelidan_the_breaker.cpp index 97501805255..f32868b550f 100644 --- a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_kelidan_the_breaker.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_kelidan_the_breaker.cpp @@ -17,9 +17,11 @@ */ #include "ScriptMgr.h" +#include "blood_furnace.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellAuras.h" -#include "blood_furnace.h" +#include "TemporarySummon.h" enum Kelidan { diff --git a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/instance_blood_furnace.cpp b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/instance_blood_furnace.cpp index d87f3eb1937..d12dadb1cd5 100644 --- a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/instance_blood_furnace.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/instance_blood_furnace.cpp @@ -16,9 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "InstanceScript.h" #include "blood_furnace.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" +#include "ScriptedCreature.h" DoorData const doorData[] = { @@ -79,17 +81,12 @@ class instance_blood_furnace : public InstanceMapScript void OnGameObjectCreate(GameObject* go) override { + InstanceScript::OnGameObjectCreate(go); + switch (go->GetEntry()) { case GO_PRISON_DOOR_04: PrisonDoor4GUID = go->GetGUID(); - // no break - case GO_PRISON_DOOR_01: - case GO_PRISON_DOOR_02: - case GO_PRISON_DOOR_03: - case GO_PRISON_DOOR_05: - case GO_SUMMON_DOOR: - AddDoor(go, true); break; case GO_BROGGOK_LEVER: BroggokLeverGUID = go->GetGUID(); @@ -123,23 +120,6 @@ class instance_blood_furnace : public InstanceMapScript } } - void OnGameObjectRemove(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_PRISON_DOOR_01: - case GO_PRISON_DOOR_02: - case GO_PRISON_DOOR_03: - case GO_PRISON_DOOR_04: - case GO_PRISON_DOOR_05: - case GO_SUMMON_DOOR: - AddDoor(go, false); - break; - default: - break; - } - } - ObjectGuid GetGuidData(uint32 type) const override { switch (type) diff --git a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_omor_the_unscarred.cpp b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_omor_the_unscarred.cpp index 773905382ac..a92f835554e 100644 --- a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_omor_the_unscarred.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_omor_the_unscarred.cpp @@ -24,9 +24,10 @@ SDCategory: Hellfire Citadel, Hellfire Ramparts EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "Player.h" #include "hellfire_ramparts.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedCreature.h" enum Says { @@ -157,7 +158,7 @@ class boss_omor_the_unscarred : public CreatureScript else if (OrbitalStrike_Timer <= diff) { - Unit* temp = NULL; + Unit* temp = nullptr; if (me->IsWithinMeleeRange(me->GetVictim())) temp = me->GetVictim(); else temp = SelectTarget(SELECT_TARGET_RANDOM, 0); @@ -230,7 +231,7 @@ class boss_omor_the_unscarred : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetHellfireRampartsAI(creature); } }; 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 5f77ffe9c60..c202e50405f 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 @@ -24,9 +24,12 @@ Category: Hellfire Citadel, Hellfire Ramparts EndScriptData */ #include "ScriptMgr.h" +#include "hellfire_ramparts.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "SpellInfo.h" -#include "hellfire_ramparts.h" +#include "TemporarySummon.h" enum Says { @@ -108,7 +111,7 @@ class boss_nazan : public CreatureScript } } - void SpellHitTarget(Unit* target, const SpellInfo* entry) override + void SpellHitTarget(Unit* target, SpellInfo const* entry) override { if (target && entry->Id == uint32(SPELL_FIREBALL)) me->SummonCreature(NPC_LIQUID_FIRE, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), target->GetOrientation(), TEMPSUMMON_TIMED_DESPAWN, 30000); @@ -196,7 +199,7 @@ class boss_nazan : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_nazanAI(creature); + return GetHellfireRampartsAI(creature); } }; @@ -282,7 +285,7 @@ class boss_vazruden : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_vazrudenAI(creature); + return GetHellfireRampartsAI(creature); } }; @@ -454,7 +457,7 @@ class boss_vazruden_the_herald : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_vazruden_the_heraldAI(creature); + return GetHellfireRampartsAI(creature); } }; @@ -514,7 +517,7 @@ class npc_hellfire_sentry : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_hellfire_sentryAI(creature); + return GetHellfireRampartsAI(creature); } }; void AddSC_boss_vazruden_the_herald() diff --git a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_watchkeeper_gargolmar.cpp b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_watchkeeper_gargolmar.cpp index 899ca964548..b9f3feb7bf3 100644 --- a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_watchkeeper_gargolmar.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/boss_watchkeeper_gargolmar.cpp @@ -24,8 +24,8 @@ SDCategory: Hellfire Citadel, Hellfire Ramparts EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "hellfire_ramparts.h" +#include "ScriptedCreature.h" enum Says { @@ -175,7 +175,7 @@ class boss_watchkeeper_gargolmar : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_watchkeeper_gargolmarAI(creature); + return GetHellfireRampartsAI(creature); } }; diff --git a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/hellfire_ramparts.h b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/hellfire_ramparts.h index e7661d488f7..688e78874a7 100644 --- a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/hellfire_ramparts.h +++ b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/hellfire_ramparts.h @@ -19,6 +19,9 @@ #ifndef DEF_RAMPARTS_H #define DEF_RAMPARTS_H +#include "CreatureAIImpl.h" + +#define HRScriptName "instance_ramparts" #define DataHeader "HR" uint32 const EncounterCount = 4; @@ -46,4 +49,10 @@ enum HRGameobjectIds GO_FEL_IRON_CHEST_HEROIC = 185169 }; +template +inline AI* GetHellfireRampartsAI(T* obj) +{ + return GetInstanceAI(obj, HRScriptName); +} + #endif diff --git a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/instance_hellfire_ramparts.cpp b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/instance_hellfire_ramparts.cpp index d8995407305..496da536c82 100644 --- a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/instance_hellfire_ramparts.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/instance_hellfire_ramparts.cpp @@ -24,13 +24,15 @@ SDCategory: Hellfire Ramparts EndScriptData */ #include "ScriptMgr.h" -#include "InstanceScript.h" +#include "GameObject.h" #include "hellfire_ramparts.h" +#include "InstanceScript.h" +#include "Map.h" class instance_ramparts : public InstanceMapScript { public: - instance_ramparts() : InstanceMapScript("instance_ramparts", 543) { } + instance_ramparts() : InstanceMapScript(HRScriptName, 543) { } struct instance_ramparts_InstanceMapScript : public InstanceScript { diff --git a/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/boss_magtheridon.cpp b/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/boss_magtheridon.cpp index f4dd961f190..281bff24494 100644 --- a/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/boss_magtheridon.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/boss_magtheridon.cpp @@ -16,14 +16,15 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "GameObject.h" +#include "GameObjectAI.h" +#include "InstanceScript.h" #include "magtheridons_lair.h" +#include "PassiveAI.h" #include "Player.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "PassiveAI.h" -#include "GameObjectAI.h" enum Yells { @@ -304,7 +305,7 @@ class boss_magtheridon : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMagtheridonsLairAI(creature); } }; @@ -422,7 +423,7 @@ class npc_hellfire_channeler : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMagtheridonsLairAI(creature); } }; @@ -455,7 +456,7 @@ public: CreatureAI* GetAI(Creature* creature) const override { - return new npc_magtheridon_roomAI(creature); + return GetMagtheridonsLairAI(creature); } }; @@ -483,7 +484,7 @@ class go_manticron_cube : public GameObjectScript GameObjectAI* GetAI(GameObject* go) const override { - return new go_manticron_cubeAI(go); + return GetMagtheridonsLairAI(go); } }; @@ -499,9 +500,7 @@ class spell_magtheridon_blaze_target : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BLAZE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_BLAZE }); } void HandleAura() @@ -534,9 +533,7 @@ class spell_magtheridon_shadow_grasp : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MIND_EXHAUSTION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MIND_EXHAUSTION }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -570,10 +567,7 @@ class spell_magtheridon_shadow_grasp_visual : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHADOW_CAGE) - || !sSpellMgr->GetSpellInfo(SPELL_SHADOW_GRASP_VISUAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHADOW_CAGE, SPELL_SHADOW_GRASP_VISUAL }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/instance_magtheridons_lair.cpp b/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/instance_magtheridons_lair.cpp index 2b4f6cd37f6..c1741fd20cb 100644 --- a/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/instance_magtheridons_lair.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/instance_magtheridons_lair.cpp @@ -16,9 +16,12 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "AreaBoundary.h" +#include "Creature.h" +#include "GameObject.h" #include "InstanceScript.h" #include "magtheridons_lair.h" +#include "Map.h" BossBoundaryData const boundaries = { @@ -64,7 +67,7 @@ static MLDataTypes const collapseObjectDatas[] = class instance_magtheridons_lair : public InstanceMapScript { public: - instance_magtheridons_lair() : InstanceMapScript("instance_magtheridons_lair", 544) { } + instance_magtheridons_lair() : InstanceMapScript(MLScriptName, 544) { } struct instance_magtheridons_lair_InstanceMapScript : public InstanceScript { diff --git a/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/magtheridons_lair.h b/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/magtheridons_lair.h index fe93061e858..43178e49bfe 100644 --- a/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/magtheridons_lair.h +++ b/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/magtheridons_lair.h @@ -18,8 +18,10 @@ #ifndef DEF_MAGTHERIDONS_LAIR_H #define DEF_MAGTHERIDONS_LAIR_H -#define DataHeader "ML" +#include "CreatureAIImpl.h" +#define MLScriptName "instance_magtheridons_lair" +#define DataHeader "ML" uint32 const EncounterCount = 1; @@ -40,13 +42,13 @@ enum MLDataTypes DATA_CALL_WARDERS = 12 }; -enum Actions +enum MLActions { ACTION_ENABLE = 1, ACTION_DISABLE = 2 }; -enum CreatureIds +enum MLCreatureIds { NPC_MAGTHERIDON = 17257, NPC_ABYSSAL = 17454, @@ -59,7 +61,7 @@ enum CreatureIds NPC_HELLFIRE_WARDER = 18829 }; -enum GameObjectIds +enum MLGameObjectIds { GO_MAGTHERIDON_DOOR = 183847, GO_MANTICRON_CUBE = 181713, @@ -72,4 +74,10 @@ enum GameObjectIds GO_MAGTHERIDON_COLUMN_5 = 184637 }; +template +inline AI* GetMagtheridonsLairAI(T* obj) +{ + return GetInstanceAI(obj, MLScriptName); +} + #endif diff --git a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_nethekurse.cpp b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_nethekurse.cpp index b97b15a66db..d582d7c18aa 100644 --- a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_nethekurse.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_nethekurse.cpp @@ -30,6 +30,8 @@ npc_lesser_shadow_fissure EndContentData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "shattered_halls.h" @@ -299,7 +301,7 @@ class boss_grand_warlock_nethekurse : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShatteredHallsAI(creature); } }; @@ -367,7 +369,7 @@ class npc_fel_orc_convert : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShatteredHallsAI(creature); } }; @@ -392,7 +394,7 @@ class npc_lesser_shadow_fissure : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_lesser_shadow_fissureAI(creature); + return GetShatteredHallsAI(creature); } }; diff --git a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_warbringer_omrogg.cpp b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_warbringer_omrogg.cpp index 476e0ed9b42..63dffc49561 100644 --- a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_warbringer_omrogg.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/boss_warbringer_omrogg.cpp @@ -29,6 +29,8 @@ boss_warbringer_omrogg EndContentData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "shattered_halls.h" @@ -393,7 +395,7 @@ class boss_warbringer_omrogg : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShatteredHallsAI(creature); } }; @@ -443,7 +445,7 @@ class npc_omrogg_heads : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShatteredHallsAI(creature); } }; 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 fda0124c364..aff14a40bdb 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 @@ -28,6 +28,9 @@ boss_warchief_kargath_bladefist EndContentData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "shattered_halls.h" @@ -178,7 +181,7 @@ class boss_warchief_kargath_bladefist : public CreatureScript if (creature && creature->IsAlive()) { creature->GetMotionMaster()->Clear(true); - me->DealDamage(creature, creature->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + me->DealDamage(creature, creature->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); creature->RemoveCorpse(); } } @@ -190,7 +193,7 @@ class boss_warchief_kargath_bladefist : public CreatureScript if (creature && creature->IsAlive()) { creature->GetMotionMaster()->Clear(true); - me->DealDamage(creature, creature->GetHealth(), NULL, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false); + me->DealDamage(creature, creature->GetHealth(), nullptr, DIRECT_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); creature->RemoveCorpse(); } } @@ -339,7 +342,7 @@ class boss_warchief_kargath_bladefist : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShatteredHallsAI(creature); } }; diff --git a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/instance_shattered_halls.cpp b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/instance_shattered_halls.cpp index ded16752951..0b57902066f 100644 --- a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/instance_shattered_halls.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/instance_shattered_halls.cpp @@ -24,13 +24,15 @@ SDCategory: Hellfire Citadel, Shattered Halls EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" #include "InstanceScript.h" +#include "Map.h" #include "Player.h" -#include "SpellAuras.h" +#include "ScriptedCreature.h" #include "shattered_halls.h" +#include "SpellAuraEffects.h" +#include "SpellAuras.h" +#include "SpellScript.h" +#include "TemporarySummon.h" DoorData const doorData[] = { @@ -42,7 +44,7 @@ DoorData const doorData[] = class instance_shattered_halls : public InstanceMapScript { public: - instance_shattered_halls() : InstanceMapScript("instance_shattered_halls", 540) { } + instance_shattered_halls() : InstanceMapScript(SHScriptName, 540) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { @@ -92,35 +94,11 @@ class instance_shattered_halls : public InstanceMapScript ex->SetDuration(executionTimer); } - void OnGameObjectCreate(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_GRAND_WARLOCK_CHAMBER_DOOR_1: - case GO_GRAND_WARLOCK_CHAMBER_DOOR_2: - AddDoor(go, true); - default: - break; - } - } - - void OnGameObjectRemove(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_GRAND_WARLOCK_CHAMBER_DOOR_1: - case GO_GRAND_WARLOCK_CHAMBER_DOOR_2: - AddDoor(go, false); - default: - break; - } - } - void OnCreatureCreate(Creature* creature) override { if (!_team) { - Map::PlayerList const &players = instance->GetPlayers(); + Map::PlayerList const& players = instance->GetPlayers(); if (!players.isEmpty()) if (Player* player = players.begin()->GetSource()) _team = player->GetTeam(); diff --git a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/shattered_halls.cpp b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/shattered_halls.cpp index a4f508f0da3..b58a7e9449b 100644 --- a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/shattered_halls.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/shattered_halls.cpp @@ -16,13 +16,14 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" #include "InstanceScript.h" +#include "Map.h" +#include "ObjectAccessor.h" #include "Player.h" -#include "SpellAuras.h" +#include "ScriptedCreature.h" #include "shattered_halls.h" +#include "SpellScript.h" +#include "TemporarySummon.h" class at_nethekurse_exit : public AreaTriggerScript { @@ -109,7 +110,7 @@ class boss_shattered_executioner : public CreatureScript if (instance->GetData(DATA_PRISONERS_EXECUTED) > 0) return; - Map::PlayerList const &players = instance->instance->GetPlayers(); + Map::PlayerList const& players = instance->instance->GetPlayers(); for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) { Player* pl = itr->GetSource(); @@ -128,7 +129,7 @@ class boss_shattered_executioner : public CreatureScript if (data == 1) { - Map::PlayerList const &players = instance->instance->GetPlayers(); + Map::PlayerList const& players = instance->instance->GetPlayers(); for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) { Player* pl = itr->GetSource(); @@ -173,7 +174,7 @@ class boss_shattered_executioner : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetShatteredHallsAI(creature); } }; diff --git a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/shattered_halls.h b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/shattered_halls.h index 886dfea62aa..d351e8fc81b 100644 --- a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/shattered_halls.h +++ b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/shattered_halls.h @@ -19,6 +19,9 @@ #ifndef DEF_SHATTERED_H #define DEF_SHATTERED_H +#include "CreatureAIImpl.h" + +#define SHScriptName "instance_shattered_halls" #define DataHeader "SH" uint32 const EncounterCount = 4; @@ -88,27 +91,32 @@ enum SHActions ACTION_EXECUTIONER_TAUNT = 1 }; -const Position Executioner = { 152.8524f, -83.63912f, 2.021005f, 0.06981317f }; +Position const Executioner = { 152.8524f, -83.63912f, 2.021005f, 0.06981317f }; struct FactionSpawnerHelper { - FactionSpawnerHelper(uint32 allianceEntry, uint32 hordeEntry, const Position& pos) : _allianceNPC(allianceEntry), _hordeNPC(hordeEntry), _spawnPos(pos) { } + FactionSpawnerHelper(uint32 allianceEntry, uint32 hordeEntry, Position const& pos) : _allianceNPC(allianceEntry), _hordeNPC(hordeEntry), _spawnPos(pos) { } inline uint32 operator()(uint32 teamID) const { return teamID == ALLIANCE ? _allianceNPC : _hordeNPC; } inline Position const& GetPos() const { return _spawnPos; } private: - const uint32 _allianceNPC; - const uint32 _hordeNPC; - const Position _spawnPos; + uint32 const _allianceNPC; + uint32 const _hordeNPC; + Position const _spawnPos; }; -const FactionSpawnerHelper executionerVictims[VictimCount] = +FactionSpawnerHelper const executionerVictims[VictimCount] = { { NPC_CAPTAIN_ALINA, NPC_CAPTAIN_BONESHATTER, { 138.8807f, -84.22707f, 1.992269f, 0.06981317f } }, { NPC_ALLIANCE_VICTIM_1, NPC_HORDE_VICTIM_1, { 151.2411f, -91.02930f, 2.019741f, 1.57079600f } }, { NPC_ALLIANCE_VICTIM_2, NPC_HORDE_VICTIM_2, { 151.0459f, -77.51981f, 2.021008f, 4.74729500f } } }; +template +inline AI* GetShatteredHallsAI(T* obj) +{ + return GetInstanceAI(obj, SHScriptName); +} #endif diff --git a/src/server/scripts/Outland/TempestKeep/Eye/boss_alar.cpp b/src/server/scripts/Outland/TempestKeep/Eye/boss_alar.cpp index eb286ca4f9f..19e9e1a222b 100644 --- a/src/server/scripts/Outland/TempestKeep/Eye/boss_alar.cpp +++ b/src/server/scripts/Outland/TempestKeep/Eye/boss_alar.cpp @@ -24,9 +24,13 @@ SDCategory: Tempest Keep, The Eye EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "MotionMaster.h" #include "ScriptedCreature.h" -#include "the_eye.h" #include "SpellInfo.h" +#include "TemporarySummon.h" +#include "the_eye.h" enum Spells { @@ -185,13 +189,13 @@ class boss_alar : public CreatureScript } } - void SpellHit(Unit*, const SpellInfo* spell) override + void SpellHit(Unit*, SpellInfo const* spell) override { if (spell->Id == SPELL_DIVE_BOMB_VISUAL) { me->ApplySpellImmune(0, IMMUNITY_SCHOOL, SPELL_SCHOOL_MASK_FIRE, true); me->SetDisplayId(11686); - //me->SendUpdateObjectToAllExcept(NULL); + //me->SendUpdateObjectToAllExcept(nullptr); } } @@ -446,7 +450,7 @@ class boss_alar : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTheEyeAI(creature); } }; @@ -518,7 +522,7 @@ class npc_ember_of_alar : public CreatureScript if (toDie) { - 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->SetVisibility(VISIBILITY_OFF); } @@ -529,7 +533,7 @@ class npc_ember_of_alar : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTheEyeAI(creature); } }; @@ -551,7 +555,7 @@ class npc_flame_patch_alar : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_flame_patch_alarAI(creature); + return GetTheEyeAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/Eye/boss_astromancer.cpp b/src/server/scripts/Outland/TempestKeep/Eye/boss_astromancer.cpp index 14fd77a8c3b..ac0da3bfca0 100644 --- a/src/server/scripts/Outland/TempestKeep/Eye/boss_astromancer.cpp +++ b/src/server/scripts/Outland/TempestKeep/Eye/boss_astromancer.cpp @@ -24,10 +24,13 @@ SDCategory: Tempest Keep, The Eye EndScriptData */ #include "ScriptMgr.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "SpellAuras.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" - +#include "TemporarySummon.h" #include "the_eye.h" enum Yells @@ -306,15 +309,15 @@ class boss_high_astromancer_solarian : public CreatureScript } if ((std::abs(Portals[2][0] - Portals[1][0]) < 7) && (std::abs(Portals[2][1] - Portals[1][1]) < 7)) { - int i=1; + int i = 1; if (std::abs(CENTER_X + 26.0f - Portals[2][0]) < 7) i = -1; - Portals[2][0] = Portals[2][0]+7*i; + Portals[2][0] = Portals[2][0] + 7 * i; Portals[2][1] = Portal_Y(Portals[2][0], LARGE_PORTAL_RADIUS); } - for (int i=0; i <= 2; ++i) + for (int i = 0; i <= 2; ++i) { - if (Creature* Summoned = me->SummonCreature(NPC_ASTROMANCER_SOLARIAN_SPOTLIGHT, Portals[i][0], Portals[i][1], Portals[i][2], CENTER_O, TEMPSUMMON_TIMED_DESPAWN, Phase2_Timer+Phase3_Timer+AppearDelay_Timer+1700)) + if (Creature* Summoned = me->SummonCreature(NPC_ASTROMANCER_SOLARIAN_SPOTLIGHT, Portals[i][0], Portals[i][1], Portals[i][2], CENTER_O, TEMPSUMMON_TIMED_DESPAWN, Phase2_Timer + Phase3_Timer + AppearDelay_Timer + 1700)) { Summoned->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); Summoned->CastSpell(Summoned, SPELL_SPOTLIGHT, false); @@ -323,7 +326,7 @@ class boss_high_astromancer_solarian : public CreatureScript AppearDelay = true; } else - Phase1_Timer-=diff; + Phase1_Timer -= diff; } else if (Phase == 2) { @@ -410,7 +413,7 @@ class boss_high_astromancer_solarian : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTheEyeAI(creature); } }; @@ -455,7 +458,7 @@ class npc_solarium_priest : public CreatureScript if (healTimer <= diff) { - Unit* target = NULL; + Unit* target = nullptr; switch (urand(0, 1)) { case 0: @@ -497,7 +500,7 @@ class npc_solarium_priest : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTheEyeAI(creature); } }; @@ -512,9 +515,7 @@ class spell_astromancer_wrath_of_the_astromancer : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WRATH_OF_THE_ASTROMANCER_DOT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WRATH_OF_THE_ASTROMANCER_DOT }); } void AfterRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Outland/TempestKeep/Eye/boss_kaelthas.cpp b/src/server/scripts/Outland/TempestKeep/Eye/boss_kaelthas.cpp index 3f4aed13e7b..75af3be4f49 100644 --- a/src/server/scripts/Outland/TempestKeep/Eye/boss_kaelthas.cpp +++ b/src/server/scripts/Outland/TempestKeep/Eye/boss_kaelthas.cpp @@ -24,8 +24,13 @@ SDCategory: Tempest Keep, The Eye EndScriptData */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "Spell.h" +#include "SpellInfo.h" #include "SpellScript.h" #include "the_eye.h" @@ -864,7 +869,7 @@ class boss_kaelthas : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTheEyeAI(creature); } }; @@ -969,7 +974,7 @@ class boss_thaladred_the_darkener : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTheEyeAI(creature); } }; @@ -1033,7 +1038,7 @@ class boss_lord_sanguinar : public CreatureScript }; CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTheEyeAI(creature); } }; @@ -1135,7 +1140,7 @@ class boss_grand_astromancer_capernian : public CreatureScript if (ArcaneExplosion_Timer <= diff) { bool InMeleeRange = false; - Unit* target = NULL; + Unit* target = nullptr; ThreatContainer::StorageType const &threatlist = me->getThreatManager().getThreatList(); for (ThreatContainer::StorageType::const_iterator i = threatlist.begin(); i!= threatlist.end(); ++i) { @@ -1163,7 +1168,7 @@ class boss_grand_astromancer_capernian : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTheEyeAI(creature); } }; @@ -1242,7 +1247,7 @@ class boss_master_engineer_telonicus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTheEyeAI(creature); } }; @@ -1312,7 +1317,7 @@ class npc_kael_flamestrike : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_kael_flamestrikeAI(creature); + return GetTheEyeAI(creature); } }; @@ -1371,7 +1376,7 @@ class npc_phoenix_tk : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_phoenix_tkAI(creature); + return GetTheEyeAI(creature); } }; @@ -1437,7 +1442,7 @@ class npc_phoenix_egg_tk : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_phoenix_egg_tkAI(creature); + return GetTheEyeAI(creature); } }; @@ -1459,11 +1464,7 @@ class spell_kael_gravity_lapse : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - for (uint8 i = 0; i < 25; ++i) - if (!sSpellMgr->GetSpellInfo(GravityLapseSpells[i])) - return false; - - return true; + return ValidateSpellInfo(GravityLapseSpells); } void HandleScript(SpellEffIndex /*effIndex*/) 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 5d37fff4cce..5af9aa4c53c 100644 --- a/src/server/scripts/Outland/TempestKeep/Eye/boss_void_reaver.cpp +++ b/src/server/scripts/Outland/TempestKeep/Eye/boss_void_reaver.cpp @@ -16,6 +16,7 @@ */ #include "ScriptMgr.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "the_eye.h" @@ -110,7 +111,7 @@ class boss_void_reaver : public CreatureScript break; case EVENT_ARCANE_ORB: { - Unit* target = NULL; + Unit* target = nullptr; std::list t_list = me->getThreatManager().getThreatList(); std::vector target_list; for (std::list::const_iterator itr = t_list.begin(); itr != t_list.end(); ++itr) @@ -121,7 +122,7 @@ class boss_void_reaver : public CreatureScript // 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; + target = nullptr; } if (!target_list.empty()) @@ -130,7 +131,7 @@ class boss_void_reaver : public CreatureScript target = me->GetVictim(); if (target) - me->CastSpell(target, SPELL_ARCANE_ORB, false, NULL, NULL); + me->CastSpell(target, SPELL_ARCANE_ORB, false, nullptr, nullptr); events.ScheduleEvent(EVENT_ARCANE_ORB, 3000); break; @@ -167,7 +168,7 @@ class boss_void_reaver : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetTheEyeAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/Eye/instance_the_eye.cpp b/src/server/scripts/Outland/TempestKeep/Eye/instance_the_eye.cpp index 28e6c4c187f..48f66f55fe4 100644 --- a/src/server/scripts/Outland/TempestKeep/Eye/instance_the_eye.cpp +++ b/src/server/scripts/Outland/TempestKeep/Eye/instance_the_eye.cpp @@ -24,7 +24,9 @@ SDCategory: Tempest Keep, The Eye EndScriptData */ #include "ScriptMgr.h" +#include "Creature.h" #include "InstanceScript.h" +#include "Map.h" #include "the_eye.h" /* The Eye encounters: @@ -52,7 +54,7 @@ ObjectData const gameObjectData[] = class instance_the_eye : public InstanceMapScript { public: - instance_the_eye() : InstanceMapScript("instance_the_eye", 550) { } + instance_the_eye() : InstanceMapScript(TheEyeScriptName, 550) { } struct instance_the_eye_InstanceMapScript : public InstanceScript { @@ -106,13 +108,13 @@ class instance_the_eye : public InstanceMapScript { switch (identifier) { - case DATA_THALADREDTHEDARKENER: return ThaladredTheDarkener; - case DATA_LORDSANGUINAR: return LordSanguinar; - case DATA_GRANDASTROMANCERCAPERNIAN: return GrandAstromancerCapernian; - case DATA_MASTERENGINEERTELONICUS: return MasterEngineerTelonicus; - case DATA_KAELTHAS: return Kaelthas; - case DATA_HIGH_ASTROMANCER_SOLARIAN: return Astromancer; - case DATA_ALAR: return Alar; + case DATA_THALADREDTHEDARKENER: return ThaladredTheDarkener; + case DATA_LORDSANGUINAR: return LordSanguinar; + case DATA_GRANDASTROMANCERCAPERNIAN: return GrandAstromancerCapernian; + case DATA_MASTERENGINEERTELONICUS: return MasterEngineerTelonicus; + case DATA_KAELTHAS: return Kaelthas; + case DATA_HIGH_ASTROMANCER_SOLARIAN: return Astromancer; + case DATA_ALAR: return Alar; } return ObjectGuid::Empty; } diff --git a/src/server/scripts/Outland/TempestKeep/Eye/the_eye.cpp b/src/server/scripts/Outland/TempestKeep/Eye/the_eye.cpp index 6b85c6376a0..cb9f548b492 100644 --- a/src/server/scripts/Outland/TempestKeep/Eye/the_eye.cpp +++ b/src/server/scripts/Outland/TempestKeep/Eye/the_eye.cpp @@ -110,7 +110,7 @@ class npc_crystalcore_devastator : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_crystalcore_devastatorAI(creature); + return GetTheEyeAI(creature); } }; void AddSC_the_eye() diff --git a/src/server/scripts/Outland/TempestKeep/Eye/the_eye.h b/src/server/scripts/Outland/TempestKeep/Eye/the_eye.h index fc3024c340f..8c76591bcff 100644 --- a/src/server/scripts/Outland/TempestKeep/Eye/the_eye.h +++ b/src/server/scripts/Outland/TempestKeep/Eye/the_eye.h @@ -19,6 +19,9 @@ #ifndef DEF_THE_EYE_H #define DEF_THE_EYE_H +#include "CreatureAIImpl.h" + +#define TheEyeScriptName "instance_the_eye" #define DataHeader "TE" uint32 const EncounterCount = 4; @@ -63,4 +66,10 @@ enum TEGameObjectIds GO_ARCANE_DOOR_RIGHT = 184325 }; +template +inline AI* GetTheEyeAI(T* obj) +{ + return GetInstanceAI(obj, TheEyeScriptName); +} + #endif diff --git a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_gatewatcher_gyrokill.cpp b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_gatewatcher_gyrokill.cpp index 06da0fc4932..3ec963d4131 100644 --- a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_gatewatcher_gyrokill.cpp +++ b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_gatewatcher_gyrokill.cpp @@ -23,8 +23,8 @@ SDCategory: Tempest Keep, The Mechanar EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "mechanar.h" +#include "ScriptedCreature.h" enum Say { @@ -120,7 +120,7 @@ class boss_gatewatcher_gyrokill : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_gatewatcher_gyrokillAI(creature); + return GetMechanarAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_gatewatcher_ironhand.cpp b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_gatewatcher_ironhand.cpp index 57607d0a224..584706c13ba 100644 --- a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_gatewatcher_ironhand.cpp +++ b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_gatewatcher_ironhand.cpp @@ -24,8 +24,8 @@ SDCategory: Tempest Keep, The Mechanar EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "mechanar.h" +#include "ScriptedCreature.h" enum Says { @@ -127,7 +127,7 @@ class boss_gatewatcher_iron_hand : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_gatewatcher_iron_handAI(creature); + return GetMechanarAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_mechano_lord_capacitus.cpp b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_mechano_lord_capacitus.cpp index 8487a151950..d91115eff6a 100644 --- a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_mechano_lord_capacitus.cpp +++ b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_mechano_lord_capacitus.cpp @@ -16,10 +16,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" #include "mechanar.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" +#include "SpellScript.h" enum Spells { @@ -155,7 +156,7 @@ class boss_mechano_lord_capacitus : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_mechano_lord_capacitusAI(creature); + return GetMechanarAI(creature); } }; @@ -170,15 +171,13 @@ class spell_capacitus_polarity_charge : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_POSITIVE_CHARGE)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_POSITIVE_CHARGE_STACK)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_NEGATIVE_CHARGE)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_NEGATIVE_CHARGE_STACK)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_POSITIVE_CHARGE, + SPELL_POSITIVE_CHARGE_STACK, + SPELL_NEGATIVE_CHARGE, + SPELL_NEGATIVE_CHARGE_STACK + }); } void HandleTargets(std::list& targetList) @@ -211,7 +210,7 @@ class spell_capacitus_polarity_charge : public SpellScriptLoader Unit* target = GetHitUnit(); if (target->HasAura(GetTriggeringSpell()->Id)) - SetHitDamage(0); + PreventHitDamage(); } void Register() override @@ -238,9 +237,7 @@ class spell_capacitus_polarity_shift : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_POSITIVE_POLARITY) || !sSpellMgr->GetSpellInfo(SPELL_NEGATIVE_POLARITY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_POSITIVE_POLARITY, SPELL_NEGATIVE_POLARITY }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -248,7 +245,7 @@ class spell_capacitus_polarity_shift : public SpellScriptLoader Unit* target = GetHitUnit(); Unit* caster = GetCaster(); - target->CastSpell(target, roll_chance_i(50) ? SPELL_POSITIVE_POLARITY : SPELL_NEGATIVE_POLARITY, true, NULL, NULL, caster->GetGUID()); + target->CastSpell(target, roll_chance_i(50) ? SPELL_POSITIVE_POLARITY : SPELL_NEGATIVE_POLARITY, true, nullptr, nullptr, caster->GetGUID()); } void Register() 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 4ecca88d93e..d5fcc2e5a90 100644 --- a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_nethermancer_sepethrea.cpp +++ b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_nethermancer_sepethrea.cpp @@ -24,8 +24,10 @@ SDCategory: Tempest Keep, The Mechanar EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "InstanceScript.h" #include "mechanar.h" +#include "MotionMaster.h" +#include "ScriptedCreature.h" enum Says { @@ -141,7 +143,7 @@ class boss_nethermancer_sepethrea : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_nethermancer_sepethreaAI(creature); + return GetMechanarAI(creature); } }; @@ -229,7 +231,7 @@ class npc_ragin_flames : public CreatureScript }; CreatureAI* GetAI(Creature* creature) const override { - return GetInstanceAI(creature); + return GetMechanarAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_pathaleon_the_calculator.cpp b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_pathaleon_the_calculator.cpp index 3c5b6dad9e8..7f5c3bb5e90 100644 --- a/src/server/scripts/Outland/TempestKeep/Mechanar/boss_pathaleon_the_calculator.cpp +++ b/src/server/scripts/Outland/TempestKeep/Mechanar/boss_pathaleon_the_calculator.cpp @@ -24,8 +24,9 @@ SDCategory: Tempest Keep, The Mechanar EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "mechanar.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" enum Says { @@ -163,7 +164,7 @@ class boss_pathaleon_the_calculator : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_pathaleon_the_calculatorAI(creature); + return GetMechanarAI(creature); } }; @@ -243,7 +244,7 @@ class npc_nether_wraith : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_nether_wraithAI(creature); + return GetMechanarAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/Mechanar/instance_mechanar.cpp b/src/server/scripts/Outland/TempestKeep/Mechanar/instance_mechanar.cpp index 4c9e17ae4a8..f9c7bf72c07 100644 --- a/src/server/scripts/Outland/TempestKeep/Mechanar/instance_mechanar.cpp +++ b/src/server/scripts/Outland/TempestKeep/Mechanar/instance_mechanar.cpp @@ -18,20 +18,21 @@ #include "ScriptMgr.h" #include "InstanceScript.h" +#include "Map.h" #include "mechanar.h" static DoorData const doorData[] = { { GO_DOOR_MOARG_1, DATA_GATEWATCHER_IRON_HAND, DOOR_TYPE_PASSAGE }, { GO_DOOR_MOARG_2, DATA_GATEWATCHER_GYROKILL, DOOR_TYPE_PASSAGE }, - { GO_DOOR_NETHERMANCER, DATA_NETHERMANCER_SEPRETHREA, DOOR_TYPE_ROOM }, - { 0, 0, DOOR_TYPE_ROOM } + { GO_DOOR_NETHERMANCER, DATA_NETHERMANCER_SEPRETHREA, DOOR_TYPE_ROOM }, + { 0, 0, DOOR_TYPE_ROOM } }; class instance_mechanar : public InstanceMapScript { public: - instance_mechanar(): InstanceMapScript("instance_mechanar", 554) { } + instance_mechanar(): InstanceMapScript(MechanarScriptName, 554) { } struct instance_mechanar_InstanceMapScript : public InstanceScript { @@ -42,34 +43,6 @@ class instance_mechanar : public InstanceMapScript LoadDoorData(doorData); } - void OnGameObjectCreate(GameObject* gameObject) override - { - switch (gameObject->GetEntry()) - { - case GO_DOOR_MOARG_1: - case GO_DOOR_MOARG_2: - case GO_DOOR_NETHERMANCER: - AddDoor(gameObject, true); - break; - default: - break; - } - } - - void OnGameObjectRemove(GameObject* gameObject) override - { - switch (gameObject->GetEntry()) - { - case GO_DOOR_MOARG_1: - case GO_DOOR_MOARG_2: - case GO_DOOR_NETHERMANCER: - AddDoor(gameObject, false); - break; - default: - break; - } - } - bool SetBossState(uint32 type, EncounterState state) override { if (!InstanceScript::SetBossState(type, state)) diff --git a/src/server/scripts/Outland/TempestKeep/Mechanar/mechanar.h b/src/server/scripts/Outland/TempestKeep/Mechanar/mechanar.h index 482f4c9874e..1dc0c6f9cc3 100644 --- a/src/server/scripts/Outland/TempestKeep/Mechanar/mechanar.h +++ b/src/server/scripts/Outland/TempestKeep/Mechanar/mechanar.h @@ -18,6 +18,9 @@ #ifndef DEF_MECHANAR_H #define DEF_MECHANAR_H +#include "CreatureAIImpl.h" + +#define MechanarScriptName "instance_mechanar" #define DataHeader "MR" uint32 const EncounterCount = 5; @@ -38,4 +41,10 @@ enum MRGameobjectIds GO_DOOR_NETHERMANCER = 184449 }; +template +inline AI* GetMechanarAI(T* obj) +{ + return GetInstanceAI(obj, MechanarScriptName); +} + #endif diff --git a/src/server/scripts/Outland/TempestKeep/arcatraz/arcatraz.cpp b/src/server/scripts/Outland/TempestKeep/arcatraz/arcatraz.cpp index 334b2b4bc4d..ee5994397d5 100644 --- a/src/server/scripts/Outland/TempestKeep/arcatraz/arcatraz.cpp +++ b/src/server/scripts/Outland/TempestKeep/arcatraz/arcatraz.cpp @@ -30,8 +30,10 @@ npc_zerekethvoidzone EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "arcatraz.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ScriptedCreature.h" /*##### # npc_millhouse_manastorm @@ -552,7 +554,7 @@ class npc_zerekethvoidzone : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new npc_zerekethvoidzoneAI(creature); + return GetArcatrazAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/arcatraz/arcatraz.h b/src/server/scripts/Outland/TempestKeep/arcatraz/arcatraz.h index abe629d5630..27b044a691f 100644 --- a/src/server/scripts/Outland/TempestKeep/arcatraz/arcatraz.h +++ b/src/server/scripts/Outland/TempestKeep/arcatraz/arcatraz.h @@ -18,6 +18,8 @@ #ifndef ARCATRAZ_H #define ARCATRAZ_H +#include "CreatureAIImpl.h" + #define ArcatrazScriptName "instance_arcatraz" #define DataHeader "AZ" diff --git a/src/server/scripts/Outland/TempestKeep/arcatraz/boss_dalliah_the_doomsayer.cpp b/src/server/scripts/Outland/TempestKeep/arcatraz/boss_dalliah_the_doomsayer.cpp index 0cd2dd6ef1a..dce22c470b2 100644 --- a/src/server/scripts/Outland/TempestKeep/arcatraz/boss_dalliah_the_doomsayer.cpp +++ b/src/server/scripts/Outland/TempestKeep/arcatraz/boss_dalliah_the_doomsayer.cpp @@ -16,8 +16,10 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "arcatraz.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Say { diff --git a/src/server/scripts/Outland/TempestKeep/arcatraz/boss_harbinger_skyriss.cpp b/src/server/scripts/Outland/TempestKeep/arcatraz/boss_harbinger_skyriss.cpp index 3de1123fef5..df8bcd4fa43 100644 --- a/src/server/scripts/Outland/TempestKeep/arcatraz/boss_harbinger_skyriss.cpp +++ b/src/server/scripts/Outland/TempestKeep/arcatraz/boss_harbinger_skyriss.cpp @@ -29,8 +29,10 @@ boss_harbinger_skyriss_illusion EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "arcatraz.h" +#include "InstanceScript.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Says { @@ -297,7 +299,7 @@ class boss_harbinger_skyriss_illusion : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_harbinger_skyriss_illusionAI(creature); + return GetArcatrazAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/arcatraz/boss_wrath_scryer_soccothrates.cpp b/src/server/scripts/Outland/TempestKeep/arcatraz/boss_wrath_scryer_soccothrates.cpp index 3371cc4775e..812ca3e1132 100644 --- a/src/server/scripts/Outland/TempestKeep/arcatraz/boss_wrath_scryer_soccothrates.cpp +++ b/src/server/scripts/Outland/TempestKeep/arcatraz/boss_wrath_scryer_soccothrates.cpp @@ -23,8 +23,11 @@ SDCategory: Tempest Keep, The Arcatraz EndScriptData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "arcatraz.h" +#include "InstanceScript.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "ScriptedCreature.h" enum Say { diff --git a/src/server/scripts/Outland/TempestKeep/arcatraz/boss_zereketh_the_unbound.cpp b/src/server/scripts/Outland/TempestKeep/arcatraz/boss_zereketh_the_unbound.cpp index d28b595553b..b51224570b8 100644 --- a/src/server/scripts/Outland/TempestKeep/arcatraz/boss_zereketh_the_unbound.cpp +++ b/src/server/scripts/Outland/TempestKeep/arcatraz/boss_zereketh_the_unbound.cpp @@ -118,7 +118,7 @@ class boss_zereketh_the_unbound : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_zereketh_the_unboundAI(creature); + return GetArcatrazAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/arcatraz/instance_arcatraz.cpp b/src/server/scripts/Outland/TempestKeep/arcatraz/instance_arcatraz.cpp index 71f60c731c1..9fb985f45a1 100644 --- a/src/server/scripts/Outland/TempestKeep/arcatraz/instance_arcatraz.cpp +++ b/src/server/scripts/Outland/TempestKeep/arcatraz/instance_arcatraz.cpp @@ -16,8 +16,11 @@ */ #include "ScriptMgr.h" -#include "InstanceScript.h" #include "arcatraz.h" +#include "Creature.h" +#include "GameObject.h" +#include "InstanceScript.h" +#include "Map.h" DoorData const doorData[] = { @@ -69,12 +72,10 @@ class instance_arcatraz : public InstanceMapScript void OnGameObjectCreate(GameObject* go) override { + InstanceScript::OnGameObjectCreate(go); + switch (go->GetEntry()) { - case GO_CONTAINMENT_CORE_SECURITY_FIELD_ALPHA: - case GO_CONTAINMENT_CORE_SECURITY_FIELD_BETA: - AddDoor(go, true); - break; case GO_STASIS_POD_ALPHA: StasisPodGUIDs[0] = go->GetGUID(); break; @@ -98,19 +99,6 @@ class instance_arcatraz : public InstanceMapScript } } - void OnGameObjectRemove(GameObject* go) override - { - switch (go->GetEntry()) - { - case GO_CONTAINMENT_CORE_SECURITY_FIELD_ALPHA: - case GO_CONTAINMENT_CORE_SECURITY_FIELD_BETA: - AddDoor(go, false); - break; - default: - break; - } - } - void SetData(uint32 type, uint32 data) override { switch (type) diff --git a/src/server/scripts/Outland/TempestKeep/botanica/boss_commander_sarannis.cpp b/src/server/scripts/Outland/TempestKeep/botanica/boss_commander_sarannis.cpp index 4719a4e07b4..78a04a7e658 100644 --- a/src/server/scripts/Outland/TempestKeep/botanica/boss_commander_sarannis.cpp +++ b/src/server/scripts/Outland/TempestKeep/botanica/boss_commander_sarannis.cpp @@ -16,9 +16,10 @@ */ #include "ScriptMgr.h" +#include "Map.h" #include "ScriptedCreature.h" -#include "the_botanica.h" #include "SpellScript.h" +#include "the_botanica.h" enum Says { @@ -142,7 +143,7 @@ class boss_commander_sarannis : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_commander_sarannisAI(creature); + return GetBotanicaAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/botanica/boss_high_botanist_freywinn.cpp b/src/server/scripts/Outland/TempestKeep/botanica/boss_high_botanist_freywinn.cpp index d5efd734f03..b12d7c4189a 100644 --- a/src/server/scripts/Outland/TempestKeep/botanica/boss_high_botanist_freywinn.cpp +++ b/src/server/scripts/Outland/TempestKeep/botanica/boss_high_botanist_freywinn.cpp @@ -24,6 +24,8 @@ SDCategory: Tempest Keep, The Botanica EndScriptData */ #include "ScriptMgr.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "the_botanica.h" @@ -210,7 +212,7 @@ class boss_high_botanist_freywinn : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_high_botanist_freywinnAI(creature); + return GetBotanicaAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/botanica/boss_laj.cpp b/src/server/scripts/Outland/TempestKeep/botanica/boss_laj.cpp index fb86404b5e4..5da71757b38 100644 --- a/src/server/scripts/Outland/TempestKeep/botanica/boss_laj.cpp +++ b/src/server/scripts/Outland/TempestKeep/botanica/boss_laj.cpp @@ -223,7 +223,7 @@ class boss_laj : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_lajAI(creature); + return GetBotanicaAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/botanica/boss_thorngrin_the_tender.cpp b/src/server/scripts/Outland/TempestKeep/botanica/boss_thorngrin_the_tender.cpp index 8474654e2ea..5bea3017ffa 100644 --- a/src/server/scripts/Outland/TempestKeep/botanica/boss_thorngrin_the_tender.cpp +++ b/src/server/scripts/Outland/TempestKeep/botanica/boss_thorngrin_the_tender.cpp @@ -152,7 +152,7 @@ class boss_thorngrin_the_tender : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_thorngrin_the_tenderAI(creature); + return GetBotanicaAI(creature); } }; 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 f02cb80d243..e3a145c29c9 100644 --- a/src/server/scripts/Outland/TempestKeep/botanica/boss_warp_splinter.cpp +++ b/src/server/scripts/Outland/TempestKeep/botanica/boss_warp_splinter.cpp @@ -24,7 +24,10 @@ SDCategory: Tempest Keep, The Botanica EndScriptData */ #include "ScriptMgr.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" +#include "TemporarySummon.h" #include "the_botanica.h" enum Says @@ -94,7 +97,6 @@ class npc_warp_splinter_treant : public CreatureScript void MoveInLineOfSight(Unit* /*who*/) override { } - void UpdateAI(uint32 diff) override { if (!UpdateVictim() || !me->GetVictim()) @@ -107,7 +109,7 @@ class npc_warp_splinter_treant : public CreatureScript { int32 CurrentHP_Treant = (int32)me->GetHealth(); Warp->CastCustomSpell(Warp, SPELL_HEAL_FATHER, &CurrentHP_Treant, 0, 0, true, 0, 0, me->GetGUID()); - 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; } me->GetMotionMaster()->MoveFollow(Warp, 0, 0); @@ -125,7 +127,7 @@ class npc_warp_splinter_treant : public CreatureScript }; CreatureAI* GetAI(Creature* creature) const override { - return new npc_warp_splinter_treantAI(creature); + return GetBotanicaAI(creature); } }; @@ -239,7 +241,7 @@ class boss_warp_splinter : public CreatureScript CreatureAI* GetAI(Creature* creature) const override { - return new boss_warp_splinterAI(creature); + return GetBotanicaAI(creature); } }; diff --git a/src/server/scripts/Outland/TempestKeep/botanica/instance_the_botanica.cpp b/src/server/scripts/Outland/TempestKeep/botanica/instance_the_botanica.cpp index 11e2df1b599..f1c8d6c3c0d 100644 --- a/src/server/scripts/Outland/TempestKeep/botanica/instance_the_botanica.cpp +++ b/src/server/scripts/Outland/TempestKeep/botanica/instance_the_botanica.cpp @@ -16,13 +16,15 @@ */ #include "ScriptMgr.h" +#include "Creature.h" #include "InstanceScript.h" +#include "Map.h" #include "the_botanica.h" class instance_the_botanica : public InstanceMapScript { public: - instance_the_botanica() : InstanceMapScript("instance_the_botanica", 553) { } + instance_the_botanica() : InstanceMapScript(BotanicaScriptName, 553) { } struct instance_the_botanica_InstanceMapScript : public InstanceScript { diff --git a/src/server/scripts/Outland/TempestKeep/botanica/the_botanica.h b/src/server/scripts/Outland/TempestKeep/botanica/the_botanica.h index 811c432087b..d6c70c598a6 100644 --- a/src/server/scripts/Outland/TempestKeep/botanica/the_botanica.h +++ b/src/server/scripts/Outland/TempestKeep/botanica/the_botanica.h @@ -19,6 +19,9 @@ #ifndef DEF_THE_BOTANICA_H #define DEF_THE_BOTANICA_H +#include "CreatureAIImpl.h" + +#define BotanicaScriptName "instance_the_botanica" #define DataHeader "BC" uint32 const EncounterCount = 5; @@ -41,4 +44,10 @@ enum BCCreatureIds NPC_WARP_SPLINTER = 17977 }; +template +inline AI* GetBotanicaAI(T* obj) +{ + return GetInstanceAI(obj, BotanicaScriptName); +} + #endif diff --git a/src/server/scripts/Outland/boss_doomlord_kazzak.cpp b/src/server/scripts/Outland/boss_doomlord_kazzak.cpp index f2bd2d6894b..e77767cab06 100644 --- a/src/server/scripts/Outland/boss_doomlord_kazzak.cpp +++ b/src/server/scripts/Outland/boss_doomlord_kazzak.cpp @@ -187,9 +187,7 @@ class spell_mark_of_kazzak : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MARK_OF_KAZZAK_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MARK_OF_KAZZAK_DAMAGE }); } void CalculateAmount(AuraEffect const* /*aurEff*/, int32& amount, bool& /*canBeRecalculated*/) @@ -204,7 +202,7 @@ class spell_mark_of_kazzak : public SpellScriptLoader if (target->GetPower(POWER_MANA) == 0) { - target->CastSpell(target, SPELL_MARK_OF_KAZZAK_DAMAGE, true, NULL, aurEff); + target->CastSpell(target, SPELL_MARK_OF_KAZZAK_DAMAGE, true, nullptr, aurEff); // Remove aura SetDuration(0); } @@ -234,9 +232,7 @@ class spell_twisted_reflection : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TWISTED_REFLECTION_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TWISTED_REFLECTION_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) diff --git a/src/server/scripts/Outland/zone_blades_edge_mountains.cpp b/src/server/scripts/Outland/zone_blades_edge_mountains.cpp index b9455e8130b..9d4a04d3fd5 100644 --- a/src/server/scripts/Outland/zone_blades_edge_mountains.cpp +++ b/src/server/scripts/Outland/zone_blades_edge_mountains.cpp @@ -30,17 +30,17 @@ go_legion_obelisk EndContentData */ #include "ScriptMgr.h" +#include "CellImpl.h" +#include "CreatureAIImpl.h" +#include "GameObjectAI.h" +#include "GridNotifiersImpl.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "Cell.h" -#include "CellImpl.h" #include "SpellInfo.h" #include "SpellScript.h" -#include "SpellAuras.h" -#include "SpellAuraEffects.h" -#include "GameObjectAI.h" +#include "TemporarySummon.h" /*###### ## npc_nether_drake @@ -129,11 +129,11 @@ public: } } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (spell->Id == SPELL_T_PHASE_MODULATOR && caster->GetTypeId() == TYPEID_PLAYER) { - const uint32 entry_list[4] = {ENTRY_PROTO, ENTRY_ADOLE, ENTRY_MATUR, ENTRY_NIHIL}; + uint32 const entry_list[4] = {ENTRY_PROTO, ENTRY_ADOLE, ENTRY_MATUR, ENTRY_NIHIL}; int cid = rand32() % (4 - 1); if (entry_list[cid] == me->GetEntry()) @@ -845,7 +845,7 @@ class npc_simon_bunny : public CreatureScript } } - void SpellHitTarget(Unit* target, const SpellInfo* spell) override + void SpellHitTarget(Unit* target, SpellInfo const* spell) override { // Cast SPELL_BAD_PRESS_DAMAGE with scaled basepoints when the visual hits the target. // Need Fix: When SPELL_BAD_PRESS_TRIGGER hits target it triggers spell SPELL_BAD_PRESS_DAMAGE by itself @@ -853,7 +853,7 @@ class npc_simon_bunny : public CreatureScript if (spell->Id == SPELL_BAD_PRESS_TRIGGER) { int32 bp = (int32)((float)(fails)*0.33f*target->GetMaxHealth()); - target->CastCustomSpell(target, SPELL_BAD_PRESS_DAMAGE, &bp, NULL, NULL, true); + target->CastCustomSpell(target, SPELL_BAD_PRESS_DAMAGE, &bp, nullptr, nullptr, true); } } @@ -990,7 +990,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, G3D::Quat(), 50); + me->SummonGameObject(GO_OSCILLATING_FREQUENCY_SCANNER, *me, QuaternionData(), 50); me->DespawnOrUnsummon(50000); } diff --git a/src/server/scripts/Outland/zone_nagrand.cpp b/src/server/scripts/Outland/zone_nagrand.cpp index 71a81938843..8e4d7cbcc40 100644 --- a/src/server/scripts/Outland/zone_nagrand.cpp +++ b/src/server/scripts/Outland/zone_nagrand.cpp @@ -27,13 +27,16 @@ EndScriptData */ npc_maghar_captive npc_creditmarker_visit_with_ancestors EndContentData */ + #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" -#include "Player.h" -#include "SpellInfo.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "MotionMaster.h" +#include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "SpellInfo.h" +#include "TemporarySummon.h" /*###### ## npc_maghar_captive @@ -161,7 +164,7 @@ public: } - void SpellHitTarget(Unit* /*target*/, const SpellInfo* spell) override + void SpellHitTarget(Unit* /*target*/, SpellInfo const* spell) override { if (spell->Id == SPELL_CHAIN_LIGHTNING) { @@ -533,7 +536,7 @@ public: summoned->AI()->AttackStart(me); } - void SpellHitTarget(Unit* /*target*/, const SpellInfo* spell) override + void SpellHitTarget(Unit* /*target*/, SpellInfo const* spell) override { if (spell->Id == SPELL_KUR_CHAIN_LIGHTNING) { diff --git a/src/server/scripts/Outland/zone_netherstorm.cpp b/src/server/scripts/Outland/zone_netherstorm.cpp index 631871fc2e1..998a9f4b85d 100644 --- a/src/server/scripts/Outland/zone_netherstorm.cpp +++ b/src/server/scripts/Outland/zone_netherstorm.cpp @@ -31,11 +31,13 @@ go_captain_tyralius_prison EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" -#include "Player.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "Log.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" /*###### ## npc_commander_dawnforge @@ -407,7 +409,7 @@ public: PlayerGUID = who->GetGUID(); } - //void SpellHit(Unit* /*caster*/, const SpellInfo* /*spell*/) override + //void SpellHit(Unit* /*caster*/, SpellInfo const* /*spell*/) override //{ // DoCast(me, SPELL_DE_MATERIALIZE); //} diff --git a/src/server/scripts/Outland/zone_shadowmoon_valley.cpp b/src/server/scripts/Outland/zone_shadowmoon_valley.cpp index 73029c4d58b..7e34fc1646b 100644 --- a/src/server/scripts/Outland/zone_shadowmoon_valley.cpp +++ b/src/server/scripts/Outland/zone_shadowmoon_valley.cpp @@ -37,14 +37,18 @@ npc_enraged_spirit EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" -#include "Group.h" -#include "SpellScript.h" -#include "Player.h" -#include "WorldSession.h" +#include "GameObject.h" #include "GameObjectAI.h" +#include "Group.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "SpellInfo.h" +#include "SpellScript.h" +#include "TemporarySummon.h" /*##### # npc_invis_infernal_caster @@ -159,7 +163,7 @@ public: caster->AI()->SetData(TYPE_INFERNAL, DATA_DIED); } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_SUMMON_INFERNAL) { @@ -379,7 +383,7 @@ public: me->SetVisible(true); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (!caster) return; @@ -422,7 +426,7 @@ public: } me->SetVisible(false); me->SetDisableGravity(false); - 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(); } } @@ -510,7 +514,7 @@ public: Initialize(); } - void SpellHit(Unit* caster, const SpellInfo* spell) override + void SpellHit(Unit* caster, SpellInfo const* spell) override { if (!caster) return; @@ -553,7 +557,7 @@ public: player->KilledMonsterCredit(23209); } PoisonTimer = 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); } else PoisonTimer -= diff; } if (!UpdateVictim()) @@ -1563,8 +1567,8 @@ public: } // Spawn Soul on Kill ALWAYS! - Creature* Summoned = NULL; - Unit* totemOspirits = NULL; + Creature* Summoned = nullptr; + Unit* totemOspirits = nullptr; if (entry != 0) Summoned = DoSpawnCreature(entry, 0, 0, 1, 0, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 5000); @@ -1662,7 +1666,7 @@ public: } } - void SpellHit(Unit* /*caster*/, const SpellInfo* spell) override + void SpellHit(Unit* /*caster*/, SpellInfo const* spell) override { if (spell->Id == SPELL_WHISTLE) { diff --git a/src/server/scripts/Outland/zone_terokkar_forest.cpp b/src/server/scripts/Outland/zone_terokkar_forest.cpp index 79a0f92d3b5..67003d80cde 100644 --- a/src/server/scripts/Outland/zone_terokkar_forest.cpp +++ b/src/server/scripts/Outland/zone_terokkar_forest.cpp @@ -33,13 +33,13 @@ npc_slim EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" +#include "GameObject.h" +#include "GameObjectAI.h" #include "Group.h" #include "Player.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" #include "WorldSession.h" -#include "GameObjectAI.h" /*###### ## npc_unkor_the_ruthless @@ -110,7 +110,7 @@ public: { if (Group* group = player->GetGroup()) { - for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + for (GroupReference* itr = group->GetFirstMember(); itr != nullptr; itr = itr->next()) { Player* groupie = itr->GetSource(); if (groupie && groupie->IsInMap(player) && diff --git a/src/server/scripts/Pet/pet_dk.cpp b/src/server/scripts/Pet/pet_dk.cpp index dacca30c514..dddd00c0c4e 100644 --- a/src/server/scripts/Pet/pet_dk.cpp +++ b/src/server/scripts/Pet/pet_dk.cpp @@ -21,12 +21,11 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "CombatAI.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" +#include "MotionMaster.h" +#include "ScriptedCreature.h" enum DeathKnightSpells { diff --git a/src/server/scripts/Pet/pet_generic.cpp b/src/server/scripts/Pet/pet_generic.cpp index d9e12fba562..2d50dbbaba4 100644 --- a/src/server/scripts/Pet/pet_generic.cpp +++ b/src/server/scripts/Pet/pet_generic.cpp @@ -28,9 +28,13 @@ EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "DBCStructure.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "PassiveAI.h" #include "Player.h" +#include "ScriptedCreature.h" enum BabyBlizzardBearMisc { diff --git a/src/server/scripts/Pet/pet_hunter.cpp b/src/server/scripts/Pet/pet_hunter.cpp index 7e19315ec5f..839ab4ab596 100644 --- a/src/server/scripts/Pet/pet_hunter.cpp +++ b/src/server/scripts/Pet/pet_hunter.cpp @@ -21,9 +21,11 @@ */ #include "ScriptMgr.h" +#include "CreatureAIImpl.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "TemporarySummon.h" enum HunterSpells { diff --git a/src/server/scripts/Pet/pet_mage.cpp b/src/server/scripts/Pet/pet_mage.cpp index 1616e8e229b..724094043d6 100644 --- a/src/server/scripts/Pet/pet_mage.cpp +++ b/src/server/scripts/Pet/pet_mage.cpp @@ -21,14 +21,12 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "CombatAI.h" -#include "Pet.h" -#include "PetAI.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" +#include "CombatAI.h" #include "GridNotifiersImpl.h" +#include "MotionMaster.h" +#include "PetAI.h" +#include "ScriptedCreature.h" enum MageSpells { diff --git a/src/server/scripts/ScriptPCH.h b/src/server/scripts/ScriptPCH.h index f5fc547bc54..493a63a8f28 100644 --- a/src/server/scripts/ScriptPCH.h +++ b/src/server/scripts/ScriptPCH.h @@ -1,6 +1,6 @@ /* * Copyright (C) 2008-2018 TrinityCore - * Copyright (C) 2006 - 2009 ScriptDev2 + * Copyright (C) 2006-2009 ScriptDev2 * * 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,31 +16,14 @@ * with this program. If not, see . */ -#ifndef SC_PRECOMPILED_H -#define SC_PRECOMPILED_H - -#include "ScriptMgr.h" -#include "Cell.h" -#include "CellImpl.h" -#include "GameEventMgr.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "Unit.h" -#include "GameObject.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" +#include "CreatureAIImpl.h" #include "InstanceScript.h" -#include "CombatAI.h" -#include "PassiveAI.h" -#include "Chat.h" -#include "DBCStructure.h" -#include "DBCStores.h" -#include "ObjectMgr.h" +#include "Map.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" +#include "Player.h" +#include "ScriptMgr.h" +#include "ScriptedCreature.h" +#include "SpellInfo.h" #include "SpellScript.h" -#include "SpellAuraEffects.h" - -#ifdef _WIN32 -#include -#endif - -#endif +#include "TemporarySummon.h" diff --git a/src/server/scripts/Spells/spell_dk.cpp b/src/server/scripts/Spells/spell_dk.cpp index e00681f3e91..07e3797578c 100644 --- a/src/server/scripts/Spells/spell_dk.cpp +++ b/src/server/scripts/Spells/spell_dk.cpp @@ -21,12 +21,14 @@ * Scriptnames of files in this file should be prefixed with "spell_dk_". */ -#include "Player.h" #include "ScriptMgr.h" -#include "SpellScript.h" +#include "Containers.h" +#include "Creature.h" +#include "Player.h" #include "SpellAuraEffects.h" #include "SpellHistory.h" -#include "Containers.h" +#include "SpellMgr.h" +#include "SpellScript.h" enum DeathKnightSpells { @@ -129,15 +131,9 @@ class spell_dk_anti_magic_shell_self : public SpellScriptLoader { PrepareAuraScript(spell_dk_anti_magic_shell_self_AuraScript); - public: - spell_dk_anti_magic_shell_self_AuraScript() - { - absorbPct = 0; - hpPct = 0; - } + uint32 absorbPct = 0; + uint32 hpPct = 0; - private: - uint32 absorbPct, hpPct; bool Load() override { absorbPct = GetSpellInfo()->Effects[EFFECT_0].CalcValue(GetCaster()); @@ -147,9 +143,7 @@ class spell_dk_anti_magic_shell_self : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_RUNIC_POWER_ENERGIZE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_RUNIC_POWER_ENERGIZE }); } void CalculateAmount(AuraEffect const* /*aurEff*/, int32 & amount, bool & /*canBeRecalculated*/) @@ -167,7 +161,7 @@ class spell_dk_anti_magic_shell_self : public SpellScriptLoader // damage absorbed by Anti-Magic Shell energizes the DK with additional runic power. // This, if I'm not mistaken, shows that we get back ~20% of the absorbed damage as runic power. int32 bp = CalculatePct(absorbAmount, 20); - GetTarget()->CastCustomSpell(SPELL_DK_RUNIC_POWER_ENERGIZE, SPELLVALUE_BASE_POINT0, bp, GetTarget(), true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_DK_RUNIC_POWER_ENERGIZE, SPELLVALUE_BASE_POINT0, bp, GetTarget(), true, nullptr, aurEff); } void Register() override @@ -194,14 +188,7 @@ class spell_dk_anti_magic_zone : public SpellScriptLoader { PrepareAuraScript(spell_dk_anti_magic_zone_AuraScript); - public: - spell_dk_anti_magic_zone_AuraScript() - { - absorbPct = 0; - } - - private: - uint32 absorbPct; + uint32 absorbPct = 0; bool Load() override { @@ -211,9 +198,7 @@ class spell_dk_anti_magic_zone : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_ANTI_MAGIC_SHELL_TALENT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_ANTI_MAGIC_SHELL_TALENT }); } void CalculateAmount(AuraEffect const* /*aurEff*/, int32 & amount, bool & /*canBeRecalculated*/) @@ -261,9 +246,7 @@ class spell_dk_blood_boil : public SpellScriptLoader private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_BLOOD_BOIL_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_BLOOD_BOIL_TRIGGERED }); } bool Load() override @@ -304,18 +287,9 @@ class spell_dk_blood_gorged : public SpellScriptLoader { PrepareAuraScript(spell_dk_blood_gorged_AuraScript); - public: - spell_dk_blood_gorged_AuraScript() - { - _procTarget = nullptr; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_BLOOD_GORGED_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_BLOOD_GORGED_HEAL }); } bool CheckProc(ProcEventInfo& /*eventInfo*/) @@ -327,7 +301,7 @@ class spell_dk_blood_gorged : public SpellScriptLoader void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { int32 heal = int32(CalculatePct(eventInfo.GetDamageInfo()->GetDamage(), 150)); - GetTarget()->CastCustomSpell(SPELL_DK_BLOOD_GORGED_HEAL, SPELLVALUE_BASE_POINT0, heal, _procTarget, true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_DK_BLOOD_GORGED_HEAL, SPELLVALUE_BASE_POINT0, heal, _procTarget, true, nullptr, aurEff); } void Register() override @@ -336,8 +310,7 @@ class spell_dk_blood_gorged : public SpellScriptLoader OnEffectProc += AuraEffectProcFn(spell_dk_blood_gorged_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL); } - private: - Unit* _procTarget; + Unit* _procTarget = nullptr; }; AuraScript* GetAuraScript() const override @@ -358,15 +331,13 @@ class spell_dk_butchery : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_BUTCHERY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_BUTCHERY }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastCustomSpell(SPELL_DK_BUTCHERY, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), GetTarget(), true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_DK_BUTCHERY, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), GetTarget(), true, nullptr, aurEff); } void Register() override @@ -392,15 +363,13 @@ class spell_dk_death_and_decay : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_DEATH_AND_DECAY_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_DEATH_AND_DECAY_DAMAGE }); } void HandleDummyTick(AuraEffect const* aurEff) { if (Unit* caster = GetCaster()) - caster->CastCustomSpell(SPELL_DK_DEATH_AND_DECAY_DAMAGE, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), GetTarget(), true, NULL, aurEff); + caster->CastCustomSpell(SPELL_DK_DEATH_AND_DECAY_DAMAGE, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), GetTarget(), true, nullptr, aurEff); } void Register() override @@ -426,9 +395,7 @@ class spell_dk_death_coil : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_DEATH_COIL_DAMAGE) || !sSpellMgr->GetSpellInfo(SPELL_DK_DEATH_COIL_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_DEATH_COIL_DAMAGE, SPELL_DK_DEATH_COIL_HEAL }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -440,13 +407,13 @@ class spell_dk_death_coil : public SpellScriptLoader if (caster->IsFriendlyTo(target)) { int32 bp = int32(damage * 1.5f); - caster->CastCustomSpell(target, SPELL_DK_DEATH_COIL_HEAL, &bp, NULL, NULL, true); + caster->CastCustomSpell(target, SPELL_DK_DEATH_COIL_HEAL, &bp, nullptr, nullptr, true); } else { if (AuraEffect const* auraEffect = caster->GetAuraEffect(SPELL_DK_ITEM_SIGIL_VENGEFUL_HEART, EFFECT_1)) damage += auraEffect->GetBaseAmount(); - caster->CastCustomSpell(target, SPELL_DK_DEATH_COIL_DAMAGE, &damage, NULL, NULL, true); + caster->CastCustomSpell(target, SPELL_DK_DEATH_COIL_DAMAGE, &damage, nullptr, nullptr, true); } } } @@ -583,7 +550,7 @@ class spell_dk_death_pact : public SpellScriptLoader void FilterTargets(std::list& targetList) { - Unit* target = NULL; + Unit* target = nullptr; for (std::list::iterator itr = targetList.begin(); itr != targetList.end(); ++itr) { if (Unit* unit = (*itr)->ToUnit()) @@ -624,12 +591,13 @@ class spell_dk_death_strike : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_DEATH_STRIKE_ENABLER) || - !sSpellMgr->GetSpellInfo(SPELL_DK_DEATH_STRIKE_HEAL) || - !sSpellMgr->GetSpellInfo(SPELL_DK_BLOOD_SHIELD_MASTERY) || - !sSpellMgr->GetSpellInfo(SPELL_DK_BLOOD_SHIELD_ABSORB)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DK_DEATH_STRIKE_ENABLER, + SPELL_DK_DEATH_STRIKE_HEAL, + SPELL_DK_BLOOD_SHIELD_MASTERY, + SPELL_DK_BLOOD_SHIELD_ABSORB + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -751,9 +719,7 @@ class spell_dk_ghoul_explode : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_CORPSE_EXPLOSION_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_CORPSE_EXPLOSION_TRIGGERED }); } void Suicide(SpellEffIndex /*effIndex*/) @@ -838,19 +804,20 @@ class spell_dk_improved_blood_presence : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_BLOOD_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_FROST_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_UNHOLY_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_BLOOD_PRESENCE_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DK_BLOOD_PRESENCE, + SPELL_DK_FROST_PRESENCE, + SPELL_DK_UNHOLY_PRESENCE, + SPELL_DK_BLOOD_PRESENCE_TRIGGERED + }); } void HandleModDamagePctTaken(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { Unit* target = GetTarget(); if ((target->HasAura(SPELL_DK_FROST_PRESENCE) || target->HasAura(SPELL_DK_UNHOLY_PRESENCE)) && !target->HasAura(SPELL_DK_BLOOD_PRESENCE_TRIGGERED)) - target->CastCustomSpell(SPELL_DK_BLOOD_PRESENCE_TRIGGERED, SPELLVALUE_BASE_POINT0, -aurEff->GetAmount(), target, true, NULL, aurEff); + target->CastCustomSpell(SPELL_DK_BLOOD_PRESENCE_TRIGGERED, SPELLVALUE_BASE_POINT0, -aurEff->GetAmount(), target, true, nullptr, aurEff); } void HandleModAttackerMeleeCritChance(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -900,11 +867,12 @@ class spell_dk_improved_frost_presence : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_BLOOD_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_UNHOLY_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_IMPROVED_FROST_PRESENCE_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DK_BLOOD_PRESENCE, + SPELL_DK_UNHOLY_PRESENCE, + SPELL_DK_IMPROVED_FROST_PRESENCE_TRIGGERED + }); } void HandleEffectApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -949,18 +917,19 @@ class spell_dk_improved_unholy_presence : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_BLOOD_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_FROST_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_IMPROVED_UNHOLY_PRESENCE_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DK_BLOOD_PRESENCE, + SPELL_DK_FROST_PRESENCE, + SPELL_DK_IMPROVED_UNHOLY_PRESENCE_TRIGGERED + }); } void HandleEffectApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { Unit* target = GetTarget(); if ((target->HasAura(SPELL_DK_BLOOD_PRESENCE) || target->HasAura(SPELL_DK_FROST_PRESENCE)) && !target->HasAura(SPELL_DK_IMPROVED_UNHOLY_PRESENCE_TRIGGERED)) - target->CastCustomSpell(SPELL_DK_IMPROVED_UNHOLY_PRESENCE_TRIGGERED, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), target, true, NULL, aurEff); + target->CastCustomSpell(SPELL_DK_IMPROVED_UNHOLY_PRESENCE_TRIGGERED, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), target, true, nullptr, aurEff); } void HandleEffectRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1021,12 +990,13 @@ class spell_dk_pestilence : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_PESTILENCE_REDUCED_DOTS) - || !sSpellMgr->GetSpellInfo(SPELL_DK_PESTILENCE_VISUAL) - || !sSpellMgr->GetSpellInfo(SPELL_DK_BLOOD_PLAGUE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_FROST_FEVER)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DK_PESTILENCE_REDUCED_DOTS, + SPELL_DK_PESTILENCE_VISUAL, + SPELL_DK_BLOOD_PLAGUE, + SPELL_DK_FROST_FEVER + }); } bool Load() override @@ -1135,18 +1105,18 @@ class spell_dk_presence : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_BLOOD_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_FROST_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_UNHOLY_PRESENCE) - || !sSpellMgr->GetSpellInfo(SPELL_DK_IMPROVED_BLOOD_PRESENCE_R1) - || !sSpellMgr->GetSpellInfo(SPELL_DK_IMPROVED_FROST_PRESENCE_R1) - || !sSpellMgr->GetSpellInfo(SPELL_DK_IMPROVED_UNHOLY_PRESENCE_R1) - || !sSpellMgr->GetSpellInfo(SPELL_DK_BLOOD_PRESENCE_TRIGGERED) - || !sSpellMgr->GetSpellInfo(SPELL_DK_IMPROVED_UNHOLY_PRESENCE_TRIGGERED) - || !sSpellMgr->GetSpellInfo(SPELL_DK_IMPROVED_FROST_PRESENCE_TRIGGERED)) - return false; - - return true; + return ValidateSpellInfo( + { + SPELL_DK_BLOOD_PRESENCE, + SPELL_DK_FROST_PRESENCE, + SPELL_DK_UNHOLY_PRESENCE, + SPELL_DK_IMPROVED_BLOOD_PRESENCE_R1, + SPELL_DK_IMPROVED_FROST_PRESENCE_R1, + SPELL_DK_IMPROVED_UNHOLY_PRESENCE_R1, + SPELL_DK_BLOOD_PRESENCE_TRIGGERED, + SPELL_DK_IMPROVED_UNHOLY_PRESENCE_TRIGGERED, + SPELL_DK_IMPROVED_FROST_PRESENCE_TRIGGERED + }); } void HandleImprovedBloodPresence(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -1168,10 +1138,10 @@ class spell_dk_presence : public SpellScriptLoader } if (!target->HasAura(SPELL_DK_BLOOD_PRESENCE_TRIGGERED)) - target->CastCustomSpell(SPELL_DK_BLOOD_PRESENCE_TRIGGERED, val, target, TRIGGERED_FULL_MASK, NULL, aurEff); + target->CastCustomSpell(SPELL_DK_BLOOD_PRESENCE_TRIGGERED, val, target, TRIGGERED_FULL_MASK, nullptr, aurEff); } else if (GetSpellInfo()->Id == SPELL_DK_BLOOD_PRESENCE) - target->CastSpell(target, SPELL_DK_BLOOD_PRESENCE_TRIGGERED, true, NULL, aurEff); + target->CastSpell(target, SPELL_DK_BLOOD_PRESENCE_TRIGGERED, true, nullptr, aurEff); } void HandleImprovedFrostPresence(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -1198,7 +1168,7 @@ class spell_dk_presence : public SpellScriptLoader Unit* target = GetTarget(); if (AuraEffect const* impAurEff = target->GetAuraEffectOfRankedSpell(SPELL_DK_IMPROVED_UNHOLY_PRESENCE_R1, EFFECT_0)) if (!target->HasAura(SPELL_DK_IMPROVED_UNHOLY_PRESENCE_TRIGGERED)) - target->CastCustomSpell(SPELL_DK_IMPROVED_UNHOLY_PRESENCE_TRIGGERED, SPELLVALUE_BASE_POINT0, impAurEff->GetAmount(), target, true, NULL, aurEff); + target->CastCustomSpell(SPELL_DK_IMPROVED_UNHOLY_PRESENCE_TRIGGERED, SPELLVALUE_BASE_POINT0, impAurEff->GetAmount(), target, true, nullptr, aurEff); } void HandleEffectRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1236,11 +1206,12 @@ class spell_dk_raise_dead : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].CalcValue()) - || !sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_1].CalcValue()) - || !sSpellMgr->GetSpellInfo(SPELL_DK_MASTER_OF_GHOULS)) - return false; - return true; + return ValidateSpellInfo( + { + uint32(spellInfo->Effects[EFFECT_0].CalcValue()), + uint32(spellInfo->Effects[EFFECT_1].CalcValue()), + SPELL_DK_MASTER_OF_GHOULS + }); } bool Load() override @@ -1316,15 +1287,13 @@ class spell_dk_scent_of_blood : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_SCENT_OF_BLOOD)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_SCENT_OF_BLOOD }); } void OnProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_DK_SCENT_OF_BLOOD, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_DK_SCENT_OF_BLOOD, true, nullptr, aurEff); GetTarget()->RemoveAuraFromStack(GetId()); } @@ -1350,20 +1319,11 @@ class spell_dk_scourge_strike : public SpellScriptLoader { PrepareSpellScript(spell_dk_scourge_strike_SpellScript); - public: - spell_dk_scourge_strike_SpellScript() - { - multiplier = 1.0f; - } - - private: - float multiplier; + float multiplier = 1.0f; bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_SCOURGE_STRIKE_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_SCOURGE_STRIKE_TRIGGERED }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1388,7 +1348,7 @@ class spell_dk_scourge_strike : public SpellScriptLoader if (AuraEffect* aurEff = caster->GetAuraEffectOfRankedSpell(SPELL_DK_BLACK_ICE_R1, EFFECT_0)) AddPct(bp, aurEff->GetAmount()); - caster->CastCustomSpell(unitTarget, SPELL_DK_SCOURGE_STRIKE_TRIGGERED, &bp, NULL, NULL, true); + caster->CastCustomSpell(unitTarget, SPELL_DK_SCOURGE_STRIKE_TRIGGERED, &bp, nullptr, nullptr, true); } } @@ -1444,9 +1404,7 @@ class spell_dk_will_of_the_necropolis : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DK_WILL_OF_THE_NECROPOLIS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DK_WILL_OF_THE_NECROPOLIS }); } bool CheckProc(ProcEventInfo& eventInfo) diff --git a/src/server/scripts/Spells/spell_druid.cpp b/src/server/scripts/Spells/spell_druid.cpp index e5e44543abd..d3a0e07e3eb 100644 --- a/src/server/scripts/Spells/spell_druid.cpp +++ b/src/server/scripts/Spells/spell_druid.cpp @@ -21,12 +21,13 @@ * Scriptnames of files in this file should be prefixed with "spell_dru_". */ -#include "Player.h" #include "ScriptMgr.h" -#include "SpellScript.h" +#include "Containers.h" +#include "Player.h" #include "SpellAuraEffects.h" #include "SpellHistory.h" -#include "Containers.h" +#include "SpellMgr.h" +#include "SpellScript.h" enum DruidSpells { @@ -60,7 +61,7 @@ enum DruidSpells SPELL_DRUID_NATURES_GRACE_TRIGGER = 16886, SPELL_DRUID_SURVIVAL_INSTINCTS = 50322, SPELL_DRUID_SAVAGE_ROAR = 62071, - SPELL_DRUID_STAMPEDE_BAER_RANK_1 = 81016, + SPELL_DRUID_STAMPEDE_BEAR_RANK_1 = 81016, SPELL_DRUID_STAMPEDE_CAT_RANK_1 = 81021, SPELL_DRUID_STAMPEDE_CAT_STATE = 109881, SPELL_DRUID_TIGER_S_FURY_ENERGIZE = 51178 @@ -108,10 +109,7 @@ class spell_dru_eclipse : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_NATURES_GRACE) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_NATURES_GRACE_TRIGGER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_NATURES_GRACE, SPELL_DRUID_NATURES_GRACE_TRIGGER }); } bool Load() override @@ -263,12 +261,13 @@ class spell_dru_enrage : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_KING_OF_THE_JUNGLE) - || !sSpellMgr->GetSpellInfo(SPELL_DRUID_ENRAGE_MOD_DAMAGE) - || !sSpellMgr->GetSpellInfo(SPELL_DRUID_ENRAGED_DEFENSE) - || !sSpellMgr->GetSpellInfo(SPELL_DRUID_ITEM_T10_FERAL_4P_BONUS)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DRUID_KING_OF_THE_JUNGLE, + SPELL_DRUID_ENRAGE_MOD_DAMAGE, + SPELL_DRUID_ENRAGED_DEFENSE, + SPELL_DRUID_ITEM_T10_FERAL_4P_BONUS + }); } void RecalculateBaseArmor() @@ -332,9 +331,7 @@ class spell_dru_glyph_of_innervate : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_GLYPH_OF_INNERVATE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_GLYPH_OF_INNERVATE }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -346,7 +343,7 @@ class spell_dru_glyph_of_innervate : public SpellScriptLoader void HandleEffectProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_DRUID_GLYPH_OF_INNERVATE, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_DRUID_GLYPH_OF_INNERVATE, true, nullptr, aurEff); } void Register() override @@ -374,9 +371,7 @@ class spell_dru_glyph_of_starfire : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_INCREASED_MOONFIRE_DURATION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_INCREASED_MOONFIRE_DURATION }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -424,15 +419,13 @@ class spell_dru_glyph_of_starfire_proc : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_GLYPH_OF_STARFIRE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_GLYPH_OF_STARFIRE }); } void HandleEffectProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); - GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_DRUID_GLYPH_OF_STARFIRE, true, NULL, aurEff); + GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_DRUID_GLYPH_OF_STARFIRE, true, nullptr, aurEff); } void Register() override @@ -554,11 +547,7 @@ class spell_dru_lifebloom : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_LIFEBLOOM_FINAL_HEAL)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_LIFEBLOOM_ENERGIZE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_LIFEBLOOM_FINAL_HEAL, SPELL_DRUID_LIFEBLOOM_ENERGIZE }); } void AfterRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -575,15 +564,15 @@ class spell_dru_lifebloom : public SpellScriptLoader healAmount = caster->SpellHealingBonusDone(GetTarget(), GetSpellInfo(), healAmount, HEAL, stack); healAmount = GetTarget()->SpellHealingBonusTaken(caster, GetSpellInfo(), healAmount, HEAL, stack); - GetTarget()->CastCustomSpell(GetTarget(), SPELL_DRUID_LIFEBLOOM_FINAL_HEAL, &healAmount, NULL, NULL, true, NULL, aurEff, GetCasterGUID()); + GetTarget()->CastCustomSpell(GetTarget(), SPELL_DRUID_LIFEBLOOM_FINAL_HEAL, &healAmount, nullptr, nullptr, true, nullptr, aurEff, GetCasterGUID()); // restore mana int32 returnMana = CalculatePct(caster->GetCreateMana(), GetSpellInfo()->ManaCostPercentage) * stack / 2; - caster->CastCustomSpell(caster, SPELL_DRUID_LIFEBLOOM_ENERGIZE, &returnMana, NULL, NULL, true, NULL, aurEff, GetCasterGUID()); + caster->CastCustomSpell(caster, SPELL_DRUID_LIFEBLOOM_ENERGIZE, &returnMana, nullptr, nullptr, true, nullptr, aurEff, GetCasterGUID()); return; } - GetTarget()->CastCustomSpell(GetTarget(), SPELL_DRUID_LIFEBLOOM_FINAL_HEAL, &healAmount, NULL, NULL, true, NULL, aurEff, GetCasterGUID()); + GetTarget()->CastCustomSpell(GetTarget(), SPELL_DRUID_LIFEBLOOM_FINAL_HEAL, &healAmount, nullptr, nullptr, true, nullptr, aurEff, GetCasterGUID()); } void HandleDispel(DispelInfo* dispelInfo) @@ -598,15 +587,15 @@ class spell_dru_lifebloom : public SpellScriptLoader { healAmount = caster->SpellHealingBonusDone(target, GetSpellInfo(), healAmount, HEAL, dispelInfo->GetRemovedCharges()); healAmount = target->SpellHealingBonusTaken(caster, GetSpellInfo(), healAmount, HEAL, dispelInfo->GetRemovedCharges()); - target->CastCustomSpell(target, SPELL_DRUID_LIFEBLOOM_FINAL_HEAL, &healAmount, NULL, NULL, true, NULL, NULL, GetCasterGUID()); + target->CastCustomSpell(target, SPELL_DRUID_LIFEBLOOM_FINAL_HEAL, &healAmount, nullptr, nullptr, true, nullptr, nullptr, GetCasterGUID()); // restore mana int32 returnMana = CalculatePct(caster->GetCreateMana(), GetSpellInfo()->ManaCostPercentage) * dispelInfo->GetRemovedCharges() / 2; - caster->CastCustomSpell(caster, SPELL_DRUID_LIFEBLOOM_ENERGIZE, &returnMana, NULL, NULL, true, NULL, NULL, GetCasterGUID()); + caster->CastCustomSpell(caster, SPELL_DRUID_LIFEBLOOM_ENERGIZE, &returnMana, nullptr, nullptr, true, nullptr, nullptr, GetCasterGUID()); return; } - target->CastCustomSpell(target, SPELL_DRUID_LIFEBLOOM_FINAL_HEAL, &healAmount, NULL, NULL, true, NULL, NULL, GetCasterGUID()); + target->CastCustomSpell(target, SPELL_DRUID_LIFEBLOOM_FINAL_HEAL, &healAmount, nullptr, nullptr, true, nullptr, nullptr, GetCasterGUID()); } } } @@ -636,16 +625,14 @@ class spell_dru_living_seed : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_LIVING_SEED_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_LIVING_SEED_PROC }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); int32 amount = CalculatePct(eventInfo.GetHealInfo()->GetHeal(), aurEff->GetAmount()); - GetTarget()->CastCustomSpell(SPELL_DRUID_LIVING_SEED_PROC, SPELLVALUE_BASE_POINT0, amount, eventInfo.GetProcTarget(), true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_DRUID_LIVING_SEED_PROC, SPELLVALUE_BASE_POINT0, amount, eventInfo.GetProcTarget(), true, nullptr, aurEff); } void Register() override @@ -672,15 +659,13 @@ class spell_dru_living_seed_proc : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_LIVING_SEED_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_LIVING_SEED_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastCustomSpell(SPELL_DRUID_LIVING_SEED_HEAL, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), GetTarget(), true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_DRUID_LIVING_SEED_HEAL, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), GetTarget(), true, nullptr, aurEff); } void Register() override @@ -853,15 +838,13 @@ class spell_dru_savage_roar : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_SAVAGE_ROAR)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_SAVAGE_ROAR }); } void AfterApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { Unit* target = GetTarget(); - target->CastSpell(target, SPELL_DRUID_SAVAGE_ROAR, true, NULL, aurEff, GetCasterGUID()); + target->CastSpell(target, SPELL_DRUID_SAVAGE_ROAR, true, nullptr, aurEff, GetCasterGUID()); } void AfterRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -945,13 +928,14 @@ class spell_dru_stampede : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_STAMPEDE_BAER_RANK_1) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_STAMPEDE_CAT_RANK_1) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_STAMPEDE_CAT_STATE) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_FERAL_CHARGE_CAT) || - !sSpellMgr->GetSpellInfo(SPELL_DRUID_FERAL_CHARGE_BEAR)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DRUID_STAMPEDE_BEAR_RANK_1, + SPELL_DRUID_STAMPEDE_CAT_RANK_1, + SPELL_DRUID_STAMPEDE_CAT_STATE, + SPELL_DRUID_FERAL_CHARGE_CAT, + SPELL_DRUID_FERAL_CHARGE_BEAR + }); } void HandleEffectCatProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -960,8 +944,8 @@ class spell_dru_stampede : public SpellScriptLoader if (GetTarget()->GetShapeshiftForm() != FORM_CAT || eventInfo.GetDamageInfo()->GetSpellInfo()->Id != SPELL_DRUID_FERAL_CHARGE_CAT) return; - GetTarget()->CastSpell(GetTarget(), sSpellMgr->GetSpellWithRank(SPELL_DRUID_STAMPEDE_CAT_RANK_1, GetSpellInfo()->GetRank()), true, NULL, aurEff); - GetTarget()->CastSpell(GetTarget(), SPELL_DRUID_STAMPEDE_CAT_STATE, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), sSpellMgr->GetSpellWithRank(SPELL_DRUID_STAMPEDE_CAT_RANK_1, GetSpellInfo()->GetRank()), true, nullptr, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_DRUID_STAMPEDE_CAT_STATE, true, nullptr, aurEff); } void HandleEffectBearProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -970,7 +954,7 @@ class spell_dru_stampede : public SpellScriptLoader if (GetTarget()->GetShapeshiftForm() != FORM_BEAR || eventInfo.GetDamageInfo()->GetSpellInfo()->Id != SPELL_DRUID_FERAL_CHARGE_BEAR) return; - GetTarget()->CastSpell(GetTarget(), sSpellMgr->GetSpellWithRank(SPELL_DRUID_STAMPEDE_BAER_RANK_1, GetSpellInfo()->GetRank()), true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), sSpellMgr->GetSpellWithRank(SPELL_DRUID_STAMPEDE_BEAR_RANK_1, GetSpellInfo()->GetRank()), true, nullptr, aurEff); } void Register() override @@ -1017,16 +1001,14 @@ class spell_dru_survival_instincts : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DRUID_SURVIVAL_INSTINCTS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DRUID_SURVIVAL_INSTINCTS }); } void AfterApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { Unit* target = GetTarget(); int32 bp0 = target->CountPctFromMaxHealth(aurEff->GetAmount()); - target->CastCustomSpell(target, SPELL_DRUID_SURVIVAL_INSTINCTS, &bp0, NULL, NULL, true); + target->CastCustomSpell(target, SPELL_DRUID_SURVIVAL_INSTINCTS, &bp0, nullptr, nullptr, true); } void AfterRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) diff --git a/src/server/scripts/Spells/spell_generic.cpp b/src/server/scripts/Spells/spell_generic.cpp index 0189d95339b..5c7b6976aa5 100644 --- a/src/server/scripts/Spells/spell_generic.cpp +++ b/src/server/scripts/Spells/spell_generic.cpp @@ -23,21 +23,23 @@ */ #include "ScriptMgr.h" -#include "GameTime.h" #include "Battleground.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" +#include "DBCStores.h" +#include "GameTime.h" #include "GridNotifiersImpl.h" #include "Group.h" #include "InstanceScript.h" +#include "Item.h" #include "LFGMgr.h" +#include "Log.h" #include "Pet.h" #include "ReputationMgr.h" #include "SkillDiscovery.h" -#include "SpellHistory.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" +#include "SpellHistory.h" +#include "SpellMgr.h" +#include "SpellScript.h" #include "Vehicle.h" class spell_gen_absorb0_hitlimit1 : public SpellScriptLoader @@ -103,13 +105,14 @@ class spell_gen_adaptive_warding : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GEN_ADAPTIVE_WARDING_FIRE) || - !sSpellMgr->GetSpellInfo(SPELL_GEN_ADAPTIVE_WARDING_NATURE) || - !sSpellMgr->GetSpellInfo(SPELL_GEN_ADAPTIVE_WARDING_FROST) || - !sSpellMgr->GetSpellInfo(SPELL_GEN_ADAPTIVE_WARDING_SHADOW) || - !sSpellMgr->GetSpellInfo(SPELL_GEN_ADAPTIVE_WARDING_ARCANE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_GEN_ADAPTIVE_WARDING_FIRE, + SPELL_GEN_ADAPTIVE_WARDING_NATURE, + SPELL_GEN_ADAPTIVE_WARDING_FROST, + SPELL_GEN_ADAPTIVE_WARDING_SHADOW, + SPELL_GEN_ADAPTIVE_WARDING_ARCANE + }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -176,8 +179,8 @@ class spell_gen_adaptive_warding : public SpellScriptLoader enum AlchemistStone { - ALECHEMIST_STONE_HEAL = 21399, - ALECHEMIST_STONE_MANA = 21400, + ALCHEMIST_STONE_HEAL = 21399, + ALCHEMIST_STONE_MANA = 21400, }; // 17619 - Alchemist Stone @@ -192,10 +195,7 @@ class spell_gen_alchemist_stone : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(ALECHEMIST_STONE_HEAL) || - !sSpellMgr->GetSpellInfo(ALECHEMIST_STONE_MANA)) - return false; - return true; + return ValidateSpellInfo({ ALCHEMIST_STONE_HEAL, ALCHEMIST_STONE_MANA }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -211,14 +211,14 @@ class spell_gen_alchemist_stone : public SpellScriptLoader int32 bp = int32(eventInfo.GetDamageInfo()->GetDamage() * 0.4f); if (eventInfo.GetDamageInfo()->GetSpellInfo()->HasEffect(SPELL_EFFECT_HEAL)) - spellId = ALECHEMIST_STONE_HEAL; + spellId = ALCHEMIST_STONE_HEAL; else if (eventInfo.GetDamageInfo()->GetSpellInfo()->HasEffect(SPELL_EFFECT_ENERGIZE)) - spellId = ALECHEMIST_STONE_MANA; + spellId = ALCHEMIST_STONE_MANA; if (!spellId) return; - GetTarget()->CastCustomSpell(spellId, SPELLVALUE_BASE_POINT0, bp, GetTarget(), true, NULL, aurEff); + GetTarget()->CastCustomSpell(spellId, SPELLVALUE_BASE_POINT0, bp, GetTarget(), true, nullptr, aurEff); } @@ -280,9 +280,7 @@ class spell_gen_animal_blood : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SPAWN_BLOOD_POOL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SPAWN_BLOOD_POOL }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -362,9 +360,7 @@ class spell_gen_aura_service_uniform : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SERVICE_UNIFORM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SERVICE_UNIFORM }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -459,9 +455,7 @@ class spell_gen_bandage : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RECENTLY_BANDAGED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RECENTLY_BANDAGED }); } SpellCastResult CheckCast() @@ -511,9 +505,7 @@ class spell_gen_blood_reserve : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GEN_BLOOD_RESERVE_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_GEN_BLOOD_RESERVE_HEAL }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -679,7 +671,7 @@ enum BreakShieldSpells class spell_gen_break_shield: public SpellScriptLoader { public: - spell_gen_break_shield(const char* name) : SpellScriptLoader(name) { } + spell_gen_break_shield(char const* name) : SpellScriptLoader(name) { } class spell_gen_break_shield_SpellScript : public SpellScript { @@ -792,9 +784,7 @@ class spell_gen_burning_depths_necrolyte_image : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(uint32(spellInfo->Effects[EFFECT_2].CalcValue()))) - return false; - return true; + return ValidateSpellInfo({ uint32(spellInfo->Effects[EFFECT_2].CalcValue()) }); } void HandleApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -837,16 +827,14 @@ class spell_gen_cannibalize : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CANNIBALIZE_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CANNIBALIZE_TRIGGERED }); } SpellCastResult CheckIfCorpseNear() { Unit* caster = GetCaster(); float max_range = GetSpellInfo()->GetMaxRange(false); - WorldObject* result = NULL; + WorldObject* result = nullptr; // search for nearby enemy corpse in range Trinity::AnyDeadUnitSpellTargetInRangeCheck check(caster, max_range, GetSpellInfo(), TARGET_CHECK_ENEMY); Trinity::WorldObjectSearcher searcher(caster, result, check); @@ -892,16 +880,14 @@ class spell_gen_chaos_blast : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CHAOS_BLAST)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CHAOS_BLAST }); } void HandleDummy(SpellEffIndex /* effIndex */) { int32 basepoints0 = 100; Unit* caster = GetCaster(); if (Unit* target = GetHitUnit()) - caster->CastCustomSpell(target, SPELL_CHAOS_BLAST, &basepoints0, NULL, NULL, true); + caster->CastCustomSpell(target, SPELL_CHAOS_BLAST, &basepoints0, nullptr, nullptr, true); } void Register() override @@ -1028,23 +1014,17 @@ class spell_gen_clone_weapon_aura : public SpellScriptLoader { PrepareAuraScript(spell_gen_clone_weapon_auraScript); - public: - spell_gen_clone_weapon_auraScript() - { - prevItem = 0; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_COPY_WEAPON_AURA) || - !sSpellMgr->GetSpellInfo(SPELL_COPY_WEAPON_2_AURA) || - !sSpellMgr->GetSpellInfo(SPELL_COPY_WEAPON_3_AURA) || - !sSpellMgr->GetSpellInfo(SPELL_COPY_OFFHAND_AURA) || - !sSpellMgr->GetSpellInfo(SPELL_COPY_OFFHAND_2_AURA) || - !sSpellMgr->GetSpellInfo(SPELL_COPY_RANGED_AURA)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_COPY_WEAPON_AURA, + SPELL_COPY_WEAPON_2_AURA, + SPELL_COPY_WEAPON_3_AURA, + SPELL_COPY_OFFHAND_AURA, + SPELL_COPY_OFFHAND_2_AURA, + SPELL_COPY_RANGED_AURA + }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1132,8 +1112,7 @@ class spell_gen_clone_weapon_aura : public SpellScriptLoader OnEffectRemove += AuraEffectRemoveFn(spell_gen_clone_weapon_auraScript::OnRemove, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY, AURA_EFFECT_HANDLE_REAL_OR_REAPPLY_MASK); } - private: - uint32 prevItem; + uint32 prevItem = 0; }; AuraScript* GetAuraScript() const override @@ -1198,10 +1177,11 @@ class spell_gen_create_lance : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CREATE_LANCE_ALLIANCE) || - !sSpellMgr->GetSpellInfo(SPELL_CREATE_LANCE_HORDE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_CREATE_LANCE_ALLIANCE, + SPELL_CREATE_LANCE_HORDE + }); } void HandleScript(SpellEffIndex effIndex) @@ -1282,28 +1262,33 @@ enum DalaranDisguiseSpells class spell_gen_dalaran_disguise : public SpellScriptLoader { public: - spell_gen_dalaran_disguise(const char* name) : SpellScriptLoader(name) { } + spell_gen_dalaran_disguise(char const* name) : SpellScriptLoader(name) { } class spell_gen_dalaran_disguise_SpellScript : public SpellScript { PrepareSpellScript(spell_gen_dalaran_disguise_SpellScript); - bool Validate(SpellInfo const* spellInfo) override + bool Validate(SpellInfo const* spellInfo) override { switch (spellInfo->Id) { case SPELL_SUNREAVER_DISGUISE_TRIGGER: - if (!sSpellMgr->GetSpellInfo(SPELL_SUNREAVER_DISGUISE_FEMALE) || - !sSpellMgr->GetSpellInfo(SPELL_SUNREAVER_DISGUISE_MALE)) - return false; - break; + return ValidateSpellInfo( + { + SPELL_SUNREAVER_DISGUISE_FEMALE, + SPELL_SUNREAVER_DISGUISE_MALE + }); case SPELL_SILVER_COVENANT_DISGUISE_TRIGGER: - if (!sSpellMgr->GetSpellInfo(SPELL_SILVER_COVENANT_DISGUISE_FEMALE) || - !sSpellMgr->GetSpellInfo(SPELL_SILVER_COVENANT_DISGUISE_MALE)) - return false; + return ValidateSpellInfo( + { + SPELL_SILVER_COVENANT_DISGUISE_FEMALE, + SPELL_SILVER_COVENANT_DISGUISE_MALE + }); + default: break; } - return true; + + return false; } void HandleScript(SpellEffIndex /*effIndex*/) @@ -1472,13 +1457,12 @@ class spell_gen_defend : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_VISUAL_SHIELD_1)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_VISUAL_SHIELD_2)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_VISUAL_SHIELD_3)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_VISUAL_SHIELD_1, + SPELL_VISUAL_SHIELD_2, + SPELL_VISUAL_SHIELD_3 + }); } void RefreshVisualShields(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -1490,7 +1474,7 @@ class spell_gen_defend : public SpellScriptLoader for (uint8 i = 0; i < GetSpellInfo()->StackAmount; ++i) target->RemoveAurasDueToSpell(SPELL_VISUAL_SHIELD_1 + i); - target->CastSpell(target, SPELL_VISUAL_SHIELD_1 + GetAura()->GetStackAmount() - 1, true, NULL, aurEff); + target->CastSpell(target, SPELL_VISUAL_SHIELD_1 + GetAura()->GetStackAmount() - 1, true, nullptr, aurEff); } else GetTarget()->RemoveAurasDueToSpell(GetId()); @@ -1594,9 +1578,7 @@ class spell_gen_divine_storm_cd_reset : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DIVINE_STORM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DIVINE_STORM }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -1664,13 +1646,6 @@ class spell_gen_dungeon_credit : public SpellScriptLoader { PrepareSpellScript(spell_gen_dungeon_credit_SpellScript); - public: - spell_gen_dungeon_credit_SpellScript() - { - _handled = false; - } - - private: bool Load() override { return GetCaster()->GetTypeId() == TYPEID_UNIT; @@ -1685,7 +1660,7 @@ class spell_gen_dungeon_credit : public SpellScriptLoader _handled = true; Unit* caster = GetCaster(); if (InstanceScript* instance = caster->GetInstanceScript()) - instance->UpdateEncounterState(ENCOUNTER_CREDIT_CAST_SPELL, GetSpellInfo()->Id, caster); + instance->UpdateEncounterStateForSpellCast(GetSpellInfo()->Id, caster); } void Register() override @@ -1693,8 +1668,7 @@ class spell_gen_dungeon_credit : public SpellScriptLoader AfterHit += SpellHitFn(spell_gen_dungeon_credit_SpellScript::CreditEncounter); } - private: - bool _handled; + bool _handled = false; }; SpellScript* GetSpellScript() const override @@ -1727,13 +1701,14 @@ class spell_gen_elune_candle : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ELUNE_CANDLE_OMEN_HEAD) || - !sSpellMgr->GetSpellInfo(SPELL_ELUNE_CANDLE_OMEN_CHEST) || - !sSpellMgr->GetSpellInfo(SPELL_ELUNE_CANDLE_OMEN_HAND_R) || - !sSpellMgr->GetSpellInfo(SPELL_ELUNE_CANDLE_OMEN_HAND_L) || - !sSpellMgr->GetSpellInfo(SPELL_ELUNE_CANDLE_NORMAL)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_ELUNE_CANDLE_OMEN_HEAD, + SPELL_ELUNE_CANDLE_OMEN_CHEST, + SPELL_ELUNE_CANDLE_OMEN_HAND_R, + SPELL_ELUNE_CANDLE_OMEN_HAND_L, + SPELL_ELUNE_CANDLE_NORMAL + }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -1761,7 +1736,7 @@ class spell_gen_elune_candle : public SpellScriptLoader else spellId = SPELL_ELUNE_CANDLE_NORMAL; - GetCaster()->CastSpell(GetHitUnit(), spellId, true, NULL); + GetCaster()->CastSpell(GetHitUnit(), spellId, true, nullptr); } void Register() override @@ -1794,11 +1769,12 @@ class spell_gen_gadgetzan_transporter_backfire : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TRANSPORTER_MALFUNCTION_POLYMORPH) || - !sSpellMgr->GetSpellInfo(SPELL_TRANSPORTER_EVIL_TWIN) || - !sSpellMgr->GetSpellInfo(SPELL_TRANSPORTER_MALFUNCTION_MISS)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_TRANSPORTER_MALFUNCTION_POLYMORPH, + SPELL_TRANSPORTER_EVIL_TWIN, + SPELL_TRANSPORTER_MALFUNCTION_MISS + }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -1895,10 +1871,11 @@ class spell_gen_gnomish_transporter : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TRANSPORTER_SUCCESS) || - !sSpellMgr->GetSpellInfo(SPELL_TRANSPORTER_FAILURE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_TRANSPORTER_SUCCESS, + SPELL_TRANSPORTER_FAILURE + }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -1937,15 +1914,13 @@ class spell_gen_interrupt : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GEN_THROW_INTERRUPT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_GEN_THROW_INTERRUPT }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); - GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_GEN_THROW_INTERRUPT, true, NULL, aurEff); + GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_GEN_THROW_INTERRUPT, true, nullptr, aurEff); } void Register() override @@ -2001,7 +1976,7 @@ enum GenericLifebloom class spell_gen_lifebloom : public SpellScriptLoader { public: - spell_gen_lifebloom(const char* name, uint32 spellId) : SpellScriptLoader(name), _spellId(spellId) { } + spell_gen_lifebloom(char const* name, uint32 spellId) : SpellScriptLoader(name), _spellId(spellId) { } class spell_gen_lifebloom_AuraScript : public AuraScript { @@ -2012,9 +1987,7 @@ class spell_gen_lifebloom : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(_spellId)) - return false; - return true; + return ValidateSpellInfo({ _spellId }); } void AfterRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -2024,7 +1997,7 @@ class spell_gen_lifebloom : public SpellScriptLoader return; // final heal - GetTarget()->CastSpell(GetTarget(), _spellId, true, NULL, aurEff, GetCasterGUID()); + GetTarget()->CastSpell(GetTarget(), _spellId, true, nullptr, aurEff, GetCasterGUID()); } void Register() override @@ -2224,9 +2197,7 @@ class spell_gen_moss_covered_feet : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FALL_DOWN)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FALL_DOWN }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2247,7 +2218,7 @@ class spell_gen_moss_covered_feet : public SpellScriptLoader } }; -enum Netherbloom +enum Netherbloom : uint32 { SPELL_NETHERBLOOM_POLLEN_1 = 28703 }; @@ -2265,8 +2236,9 @@ class spell_gen_netherbloom : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { for (uint8 i = 0; i < 5; ++i) - if (!sSpellMgr->GetSpellInfo(SPELL_NETHERBLOOM_POLLEN_1 + i)) + if (!ValidateSpellInfo({ SPELL_NETHERBLOOM_POLLEN_1 + i })) return false; + return true; } @@ -2322,9 +2294,7 @@ class spell_gen_nightmare_vine : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_NIGHTMARE_POLLEN)) - return false; - return true; + return ValidateSpellInfo({ SPELL_NIGHTMARE_POLLEN }); } void HandleScript(SpellEffIndex effIndex) @@ -2373,14 +2343,15 @@ class spell_gen_obsidian_armor : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GEN_OBSIDIAN_ARMOR_HOLY) || - !sSpellMgr->GetSpellInfo(SPELL_GEN_OBSIDIAN_ARMOR_FIRE) || - !sSpellMgr->GetSpellInfo(SPELL_GEN_OBSIDIAN_ARMOR_NATURE) || - !sSpellMgr->GetSpellInfo(SPELL_GEN_OBSIDIAN_ARMOR_FROST) || - !sSpellMgr->GetSpellInfo(SPELL_GEN_OBSIDIAN_ARMOR_SHADOW) || - !sSpellMgr->GetSpellInfo(SPELL_GEN_OBSIDIAN_ARMOR_ARCANE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_GEN_OBSIDIAN_ARMOR_HOLY, + SPELL_GEN_OBSIDIAN_ARMOR_FIRE, + SPELL_GEN_OBSIDIAN_ARMOR_NATURE, + SPELL_GEN_OBSIDIAN_ARMOR_FROST, + SPELL_GEN_OBSIDIAN_ARMOR_SHADOW, + SPELL_GEN_OBSIDIAN_ARMOR_ARCANE + }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -2423,7 +2394,7 @@ class spell_gen_obsidian_armor : public SpellScriptLoader default: return; } - GetTarget()->CastSpell(GetTarget(), spellId, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), spellId, true, nullptr, aurEff); } void Register() override @@ -2501,11 +2472,12 @@ class spell_gen_orc_disguise : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ORC_DISGUISE_TRIGGER) || - !sSpellMgr->GetSpellInfo(SPELL_ORC_DISGUISE_MALE) || - !sSpellMgr->GetSpellInfo(SPELL_ORC_DISGUISE_FEMALE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_ORC_DISGUISE_TRIGGER, + SPELL_ORC_DISGUISE_MALE, + SPELL_ORC_DISGUISE_FEMALE + }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -2550,9 +2522,7 @@ class spell_gen_paralytic_poison : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PARALYSIS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PARALYSIS }); } void HandleStun(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -2578,7 +2548,7 @@ class spell_gen_paralytic_poison : public SpellScriptLoader class spell_gen_proc_below_pct_damaged : public SpellScriptLoader { public: - spell_gen_proc_below_pct_damaged(const char* name) : SpellScriptLoader(name) { } + spell_gen_proc_below_pct_damaged(char const* name) : SpellScriptLoader(name) { } class spell_gen_proc_below_pct_damaged_AuraScript : public AuraScript { @@ -2654,10 +2624,11 @@ class spell_gen_parachute : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PARACHUTE) || - !sSpellMgr->GetSpellInfo(SPELL_PARACHUTE_BUFF)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PARACHUTE, + SPELL_PARACHUTE_BUFF + }); } void HandleEffectPeriodic(AuraEffect const* /*aurEff*/) @@ -2974,9 +2945,7 @@ class spell_gen_running_wild : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ALTERED_FORM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ALTERED_FORM }); } bool Load() override @@ -3094,9 +3063,7 @@ class spell_gen_seaforium_blast : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PLANT_CHARGES_CREDIT_ACHIEVEMENT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PLANT_CHARGES_CREDIT_ACHIEVEMENT }); } bool Load() override @@ -3107,7 +3074,7 @@ class spell_gen_seaforium_blast : public SpellScriptLoader void AchievementCredit(SpellEffIndex /*effIndex*/) { - // but in effect handling OriginalCaster can become NULL + // but in effect handling OriginalCaster can become nullptr if (Unit* originalCaster = GetOriginalCaster()) if (GameObject* go = GetHitGObj()) if (go->GetGOInfo()->type == GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING) @@ -3182,7 +3149,7 @@ class spell_gen_spirit_healer_res : public SpellScriptLoader { WorldPacket data(SMSG_SPIRIT_HEALER_CONFIRM, 8); data << uint64(target->GetGUID()); - originalCaster->GetSession()->SendPacket(&data); + originalCaster->SendDirectMessage(&data); } } @@ -3207,7 +3174,7 @@ enum SummonElemental class spell_gen_summon_elemental : public SpellScriptLoader { public: - spell_gen_summon_elemental(const char* name, uint32 spellId) : SpellScriptLoader(name), _spellId(spellId) { } + spell_gen_summon_elemental(char const* name, uint32 spellId) : SpellScriptLoader(name), _spellId(spellId) { } class spell_gen_summon_elemental_AuraScript : public AuraScript { @@ -3218,9 +3185,7 @@ class spell_gen_summon_elemental : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(_spellId)) - return false; - return true; + return ValidateSpellInfo({ _spellId }); } void AfterApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -3235,7 +3200,7 @@ class spell_gen_summon_elemental : public SpellScriptLoader if (GetCaster()) if (Unit* owner = GetCaster()->GetOwner()) if (owner->GetTypeId() == TYPEID_PLAYER) /// @todo this check is maybe wrong - owner->ToPlayer()->RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true); + owner->ToPlayer()->RemovePet(nullptr, PET_SAVE_NOT_IN_SLOT, true); } void Register() override @@ -3273,9 +3238,7 @@ class spell_gen_summon_tournament_mount : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_LANCE_EQUIPPED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_LANCE_EQUIPPED }); } SpellCastResult CheckIfLanceEquiped() @@ -3349,10 +3312,11 @@ class spell_gen_tournament_duel : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ON_TOURNAMENT_MOUNT) || - !sSpellMgr->GetSpellInfo(SPELL_MOUNTED_DUEL)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_ON_TOURNAMENT_MOUNT, + SPELL_MOUNTED_DUEL + }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -3436,9 +3400,7 @@ class spell_pvp_trinket_wotf_shared_cd : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(Triggered)) - return false; - return true; + return ValidateSpellInfo({ Triggered }); } void HandleScript() @@ -3500,7 +3462,7 @@ class spell_gen_turkey_marker : public SpellScriptLoader // on stack 15 cast the achievement crediting spell if (GetStackAmount() >= 15) - target->CastSpell(target, SPELL_TURKEY_VENGEANCE, true, NULL, aurEff, GetCasterGUID()); + target->CastSpell(target, SPELL_TURKEY_VENGEANCE, true, nullptr, aurEff, GetCasterGUID()); } void OnPeriodic(AuraEffect const* /*aurEff*/) @@ -3592,9 +3554,7 @@ class spell_gen_vampiric_touch : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_VAMPIRIC_TOUCH_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_VAMPIRIC_TOUCH_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -3759,15 +3719,13 @@ class spell_gen_whisper_gulch_yogg_saron_whisper : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_YOGG_SARON_WHISPER_DUMMY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_YOGG_SARON_WHISPER_DUMMY }); } void HandleEffectPeriodic(AuraEffect const* /*aurEff*/) { PreventDefaultAction(); - GetTarget()->CastSpell((Unit*)NULL, SPELL_YOGG_SARON_WHISPER_DUMMY, true); + GetTarget()->CastSpell((Unit*)nullptr, SPELL_YOGG_SARON_WHISPER_DUMMY, true); } void Register() override @@ -3862,9 +3820,7 @@ class spell_gen_gm_freeze : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GM_FREEZE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_GM_FREEZE }); } void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -4047,18 +4003,9 @@ public: { PrepareAuraScript(spell_gen_mixology_bonus_AuraScript); - public: - spell_gen_mixology_bonus_AuraScript() - { - bonus = 0; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MIXOLOGY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MIXOLOGY }); } bool Load() override @@ -4244,7 +4191,7 @@ public: } } - int32 bonus; + int32 bonus = 0; void Register() override { diff --git a/src/server/scripts/Spells/spell_holiday.cpp b/src/server/scripts/Spells/spell_holiday.cpp index 90e658690c4..5da2139e999 100644 --- a/src/server/scripts/Spells/spell_holiday.cpp +++ b/src/server/scripts/Spells/spell_holiday.cpp @@ -21,15 +21,16 @@ * Scriptnames in this file should be prefixed with "spell_#holidayname_". */ -#include "Player.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" #include "CellImpl.h" +#include "CreatureAIImpl.h" +#include "GridNotifiersImpl.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" #include "Vehicle.h" +#include "World.h" // 45102 Romantic Picnic enum SpellsPicnic @@ -135,10 +136,7 @@ class spell_hallow_end_candy : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - for (uint32 spellId : spells) - if (!sSpellMgr->GetSpellInfo(spellId)) - return false; - return true; + return ValidateSpellInfo(spells); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -181,10 +179,11 @@ class spell_hallow_end_candy_pirate : public SpellScriptLoader 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; + return ValidateSpellInfo( + { + SPELL_HALLOWS_END_CANDY_FEMALE_DEFIAS_PIRATE, + SPELL_HALLOWS_END_CANDY_MALE_DEFIAS_PIRATE + }); } void HandleApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -238,11 +237,19 @@ class spell_hallow_end_trick : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PIRATE_COSTUME_MALE) || !sSpellMgr->GetSpellInfo(SPELL_PIRATE_COSTUME_FEMALE) || !sSpellMgr->GetSpellInfo(SPELL_NINJA_COSTUME_MALE) - || !sSpellMgr->GetSpellInfo(SPELL_NINJA_COSTUME_FEMALE) || !sSpellMgr->GetSpellInfo(SPELL_LEPER_GNOME_COSTUME_MALE) || !sSpellMgr->GetSpellInfo(SPELL_LEPER_GNOME_COSTUME_FEMALE) - || !sSpellMgr->GetSpellInfo(SPELL_SKELETON_COSTUME) || !sSpellMgr->GetSpellInfo(SPELL_GHOST_COSTUME_MALE) || !sSpellMgr->GetSpellInfo(SPELL_GHOST_COSTUME_FEMALE) || !sSpellMgr->GetSpellInfo(SPELL_TRICK_BUFF)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PIRATE_COSTUME_MALE, + SPELL_PIRATE_COSTUME_FEMALE, + SPELL_NINJA_COSTUME_MALE, + SPELL_NINJA_COSTUME_FEMALE, + SPELL_LEPER_GNOME_COSTUME_MALE, + SPELL_LEPER_GNOME_COSTUME_FEMALE, + SPELL_SKELETON_COSTUME, + SPELL_GHOST_COSTUME_MALE, + SPELL_GHOST_COSTUME_FEMALE, + SPELL_TRICK_BUFF + }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -311,9 +318,7 @@ class spell_hallow_end_trick_or_treat : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TRICK) || !sSpellMgr->GetSpellInfo(SPELL_TREAT) || !sSpellMgr->GetSpellInfo(SPELL_TRICKED_OR_TREATED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TRICK, SPELL_TREAT, SPELL_TRICKED_OR_TREATED }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -349,13 +354,12 @@ class spell_hallow_end_tricky_treat : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TRICKY_TREAT_SPEED)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_TRICKY_TREAT_TRIGGER)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_UPSET_TUMMY)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_TRICKY_TREAT_SPEED, + SPELL_TRICKY_TREAT_TRIGGER, + SPELL_UPSET_TUMMY + }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -402,16 +406,17 @@ public: bool Validate(SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PIRATE_COSTUME_MALE) || - !sSpellMgr->GetSpellInfo(SPELL_PIRATE_COSTUME_FEMALE) || - !sSpellMgr->GetSpellInfo(SPELL_NINJA_COSTUME_MALE) || - !sSpellMgr->GetSpellInfo(SPELL_NINJA_COSTUME_FEMALE) || - !sSpellMgr->GetSpellInfo(SPELL_LEPER_GNOME_COSTUME_MALE) || - !sSpellMgr->GetSpellInfo(SPELL_LEPER_GNOME_COSTUME_FEMALE) || - !sSpellMgr->GetSpellInfo(SPELL_GHOST_COSTUME_MALE) || - !sSpellMgr->GetSpellInfo(SPELL_GHOST_COSTUME_FEMALE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PIRATE_COSTUME_MALE, + SPELL_PIRATE_COSTUME_FEMALE, + SPELL_NINJA_COSTUME_MALE, + SPELL_NINJA_COSTUME_FEMALE, + SPELL_LEPER_GNOME_COSTUME_MALE, + SPELL_LEPER_GNOME_COSTUME_FEMALE, + SPELL_GHOST_COSTUME_MALE, + SPELL_GHOST_COSTUME_FEMALE + }); } void HandleScriptEffect() @@ -472,7 +477,7 @@ class spell_pilgrims_bounty_buff_food : public SpellScriptLoader private: uint32 const _triggeredSpellId; public: - spell_pilgrims_bounty_buff_food(const char* name, uint32 triggeredSpellId) : SpellScriptLoader(name), _triggeredSpellId(triggeredSpellId) { } + spell_pilgrims_bounty_buff_food(char const* name, uint32 triggeredSpellId) : SpellScriptLoader(name), _triggeredSpellId(triggeredSpellId) { } class spell_pilgrims_bounty_buff_food_AuraScript : public AuraScript { @@ -565,7 +570,7 @@ class spell_pilgrims_bounty_feast_on : public SpellScriptLoader if (Player* player = target->ToPlayer()) { player->CastSpell(player, SPELL_ON_PLATE_EAT_VISUAL, true); - caster->CastSpell(player, _spellId, true, NULL, NULL, player->GetGUID()); + caster->CastSpell(player, _spellId, true, nullptr, nullptr, player->GetGUID()); } if (Aura* aura = caster->GetAura(GetEffectValue())) @@ -609,9 +614,7 @@ class spell_pilgrims_bounty_turkey_tracker : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_KILL_COUNTER_VISUAL) || !sSpellMgr->GetSpellInfo(SPELL_KILL_COUNTER_VISUAL_MAX)) - return false; - return true; + return ValidateSpellInfo({ SPELL_KILL_COUNTER_VISUAL, SPELL_KILL_COUNTER_VISUAL_MAX }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -673,59 +676,58 @@ class spell_pilgrims_bounty_well_fed : public SpellScriptLoader uint32 _triggeredSpellId; public: - spell_pilgrims_bounty_well_fed(const char* name, uint32 triggeredSpellId) : SpellScriptLoader(name), _triggeredSpellId(triggeredSpellId) { } + spell_pilgrims_bounty_well_fed(char const* 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) { } - public: - spell_pilgrims_bounty_well_fed_SpellScript(uint32 triggeredSpellId) : SpellScript(), _triggeredSpellId(triggeredSpellId) { } + private: + PrepareSpellScript(spell_pilgrims_bounty_well_fed_SpellScript); - bool Validate(SpellInfo const* /*spell*/) override - { - if (!sSpellMgr->GetSpellInfo(_triggeredSpellId)) - return false; - return true; - } + uint32 _triggeredSpellId; - void HandleScript(SpellEffIndex effIndex) - { - PreventHitDefaultEffect(effIndex); - Player* target = GetHitPlayer(); - if (!target) - return; - - if (Aura const* aura = target->GetAura(GetSpellInfo()->Id)) + bool Validate(SpellInfo const* /*spell*/) override { - if (aura->GetStackAmount() == 5) - target->CastSpell(target, _triggeredSpellId, true); + return ValidateSpellInfo({ _triggeredSpellId }); } - 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)) + void HandleScript(SpellEffIndex effIndex) { - 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); - } - } + PreventHitDefaultEffect(effIndex); + Player* target = GetHitPlayer(); + if (!target) + return; - void Register() override - { - OnEffectHitTarget += SpellEffectFn(spell_pilgrims_bounty_well_fed_SpellScript::HandleScript, EFFECT_1, SPELL_EFFECT_SCRIPT_EFFECT); - } + 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 @@ -780,107 +782,113 @@ class spell_pilgrims_bounty_on_plate : public SpellScriptLoader uint32 _triggeredSpellId4; public: - spell_pilgrims_bounty_on_plate(const char* name, uint32 triggeredSpellId1, uint32 triggeredSpellId2, uint32 triggeredSpellId3, uint32 triggeredSpellId4) : SpellScriptLoader(name), - _triggeredSpellId1(triggeredSpellId1), _triggeredSpellId2(triggeredSpellId2), _triggeredSpellId3(triggeredSpellId3), _triggeredSpellId4(triggeredSpellId4) { } + spell_pilgrims_bounty_on_plate(char const* name, uint32 triggeredSpellId1, uint32 triggeredSpellId2, uint32 triggeredSpellId3, uint32 triggeredSpellId4) : SpellScriptLoader(name), + _triggeredSpellId1(triggeredSpellId1), _triggeredSpellId2(triggeredSpellId2), _triggeredSpellId3(triggeredSpellId3), _triggeredSpellId4(triggeredSpellId4) + { + } class spell_pilgrims_bounty_on_plate_SpellScript : public SpellScript { - PrepareSpellScript(spell_pilgrims_bounty_on_plate_SpellScript); - private: - uint32 _triggeredSpellId1; - uint32 _triggeredSpellId2; - uint32 _triggeredSpellId3; - uint32 _triggeredSpellId4; - - public: - spell_pilgrims_bounty_on_plate_SpellScript(uint32 triggeredSpellId1, uint32 triggeredSpellId2, uint32 triggeredSpellId3, uint32 triggeredSpellId4) : SpellScript(), - _triggeredSpellId1(triggeredSpellId1), _triggeredSpellId2(triggeredSpellId2), _triggeredSpellId3(triggeredSpellId3), _triggeredSpellId4(triggeredSpellId4) { } - - bool Validate(SpellInfo const* /*spell*/) override - { - if (!sSpellMgr->GetSpellInfo(_triggeredSpellId1) - || !sSpellMgr->GetSpellInfo(_triggeredSpellId2) - || !sSpellMgr->GetSpellInfo(_triggeredSpellId3) - || !sSpellMgr->GetSpellInfo(_triggeredSpellId4)) - return false; - return true; - } - - Vehicle* GetTable(Unit* target) - { - if (target->GetTypeId() == TYPEID_PLAYER) + public: + spell_pilgrims_bounty_on_plate_SpellScript(uint32 triggeredSpellId1, uint32 triggeredSpellId2, uint32 triggeredSpellId3, uint32 triggeredSpellId4) : SpellScript(), + _triggeredSpellId1(triggeredSpellId1), _triggeredSpellId2(triggeredSpellId2), _triggeredSpellId3(triggeredSpellId3), _triggeredSpellId4(triggeredSpellId4) { - if (Unit* vehBase = target->GetVehicleBase()) - if (Vehicle* table = vehBase->GetVehicle()) - if (table->GetCreatureEntry() == NPC_BOUNTIFUL_TABLE) - return table; } - else if (Vehicle* veh = target->GetVehicle()) - if (veh->GetCreatureEntry() == NPC_BOUNTIFUL_TABLE) - return veh; - return nullptr; - } + private: + uint32 _triggeredSpellId1; + uint32 _triggeredSpellId2; + uint32 _triggeredSpellId3; + uint32 _triggeredSpellId4; - Unit* GetPlateInSeat(Vehicle* table, uint8 seat) - { - if (Unit* holderUnit = table->GetPassenger(SEAT_PLATE_HOLDER)) - if (Vehicle* holder = holderUnit->GetVehicleKit()) - if (Unit* plate = holder->GetPassenger(seat)) - return plate; + PrepareSpellScript(spell_pilgrims_bounty_on_plate_SpellScript); - return nullptr; - } - - void HandleDummy(SpellEffIndex /*effIndex*/) - { - Unit* caster = GetCaster(); - Unit* target = GetHitUnit(); - if (!target || caster == target) - return; - - Vehicle* table = GetTable(caster); - if (!table || table != GetTable(target)) - return; - - if (Vehicle* casterChair = caster->GetVehicleKit()) - if (Unit* casterPlr = casterChair->GetPassenger(SEAT_PLAYER)) + bool Validate(SpellInfo const* /*spell*/) override + { + return ValidateSpellInfo( { - if (casterPlr == target) - return; + _triggeredSpellId1, + _triggeredSpellId2, + _triggeredSpellId3, + _triggeredSpellId4 + }); + } - casterPlr->CastSpell(casterPlr, _triggeredSpellId2, true); //Credit for Sharing is Caring(always) + Vehicle* GetTable(Unit* target) + { + if (target->GetTypeId() == TYPEID_PLAYER) + { + if (Unit* vehBase = target->GetVehicleBase()) + if (Vehicle* table = vehBase->GetVehicle()) + if (table->GetCreatureEntry() == NPC_BOUNTIFUL_TABLE) + return table; + } + else if (Vehicle* veh = target->GetVehicle()) + if (veh->GetCreatureEntry() == NPC_BOUNTIFUL_TABLE) + return veh; - uint8 seat = target->GetTransSeat(); - if (target->GetTypeId() == TYPEID_PLAYER && target->GetVehicleBase()) - seat = target->GetVehicleBase()->GetTransSeat(); + return nullptr; + } - if (Unit* plate = GetPlateInSeat(table, seat)) + Unit* GetPlateInSeat(Vehicle* table, uint8 seat) + { + if (Unit* holderUnit = table->GetPassenger(SEAT_PLATE_HOLDER)) + if (Vehicle* holder = holderUnit->GetVehicleKit()) + if (Unit* plate = holder->GetPassenger(seat)) + return plate; + + return nullptr; + } + + void HandleDummy(SpellEffIndex /*effIndex*/) + { + Unit* caster = GetCaster(); + Unit* target = GetHitUnit(); + if (!target || caster == target) + return; + + Vehicle* table = GetTable(caster); + if (!table || table != GetTable(target)) + return; + + if (Vehicle* casterChair = caster->GetVehicleKit()) + if (Unit* casterPlr = casterChair->GetPassenger(SEAT_PLAYER)) { - if (target->GetTypeId() == TYPEID_PLAYER) //Food Fight case + if (casterPlr == target) + return; + + casterPlr->CastSpell(casterPlr, _triggeredSpellId2, true); //Credit for Sharing is Caring(always) + + uint8 seat = target->GetTransSeat(); + if (target->GetTypeId() == TYPEID_PLAYER && target->GetVehicleBase()) + seat = target->GetVehicleBase()->GetTransSeat(); + + if (Unit* plate = GetPlateInSeat(table, seat)) { - casterPlr->CastSpell(target, _triggeredSpellId1, true); - caster->CastSpell(target->GetVehicleBase(), _triggeredSpellId4, true); //CanEat-chair(always) - } - else - { - casterPlr->CastSpell(plate, _triggeredSpellId3, true); //Food Visual on plate - caster->CastSpell(target, _triggeredSpellId4, true); //CanEat-chair(always) + if (target->GetTypeId() == TYPEID_PLAYER) //Food Fight case + { + casterPlr->CastSpell(target, _triggeredSpellId1, true); + caster->CastSpell(target->GetVehicleBase(), _triggeredSpellId4, true); //CanEat-chair(always) + } + else + { + casterPlr->CastSpell(plate, _triggeredSpellId3, true); //Food Visual on plate + caster->CastSpell(target, _triggeredSpellId4, true); //CanEat-chair(always) + } } } - } - } + } - void Register() override - { - OnEffectHitTarget += SpellEffectFn(spell_pilgrims_bounty_on_plate_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); - } + void Register() override + { + OnEffectHitTarget += SpellEffectFn(spell_pilgrims_bounty_on_plate_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); + } }; - SpellScript* GetSpellScript() const override - { - return new spell_pilgrims_bounty_on_plate_SpellScript(_triggeredSpellId1, _triggeredSpellId2, _triggeredSpellId3, _triggeredSpellId4); - } + SpellScript* GetSpellScript() const override + { + return new spell_pilgrims_bounty_on_plate_SpellScript(_triggeredSpellId1, _triggeredSpellId2, _triggeredSpellId3, _triggeredSpellId4); + } }; /* 61804 - A Serving of Cranberries @@ -898,7 +906,7 @@ class spell_pilgrims_bounty_a_serving_of : public SpellScriptLoader private: uint32 _triggeredSpellId; public: - spell_pilgrims_bounty_a_serving_of(const char* name, uint32 triggeredSpellId) : SpellScriptLoader(name), _triggeredSpellId(triggeredSpellId) { } + spell_pilgrims_bounty_a_serving_of(char const* name, uint32 triggeredSpellId) : SpellScriptLoader(name), _triggeredSpellId(triggeredSpellId) { } class spell_pilgrims_bounty_a_serving_of_AuraScript : public AuraScript { @@ -912,9 +920,7 @@ class spell_pilgrims_bounty_a_serving_of : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(_triggeredSpellId)) - return false; - return true; + return ValidateSpellInfo({ _triggeredSpellId }); } void OnApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -976,11 +982,12 @@ class spell_winter_veil_mistletoe : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CREATE_MISTLETOE) || - !sSpellMgr->GetSpellInfo(SPELL_CREATE_HOLLY) || - !sSpellMgr->GetSpellInfo(SPELL_CREATE_SNOWFLAKES)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_CREATE_MISTLETOE, + SPELL_CREATE_HOLLY, + SPELL_CREATE_SNOWFLAKES + }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -1013,6 +1020,14 @@ enum PX238WinterWondervolt SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_4 = 26274 }; +uint32 const WonderboltTransformSpells[] = +{ + SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_1, + SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_2, + SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_3, + SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_4 +}; + class spell_winter_veil_px_238_winter_wondervolt : public SpellScriptLoader { public: @@ -1024,33 +1039,20 @@ class spell_winter_veil_px_238_winter_wondervolt : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_1) || - !sSpellMgr->GetSpellInfo(SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_2) || - !sSpellMgr->GetSpellInfo(SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_3) || - !sSpellMgr->GetSpellInfo(SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_4)) - return false; - return true; + return ValidateSpellInfo(WonderboltTransformSpells); } void HandleScript(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); - uint32 const spells[4] = - { - SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_1, - SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_2, - SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_3, - SPELL_PX_238_WINTER_WONDERVOLT_TRANSFORM_4 - }; - if (Unit* target = GetHitUnit()) { - for (uint8 i = 0; i < 4; ++i) - if (target->HasAura(spells[i])) + for (uint32 spell : WonderboltTransformSpells) + if (target->HasAura(spell)) return; - target->CastSpell(target, spells[urand(0, 3)], true); + target->CastSpell(target, Trinity::Containers::SelectRandomContainerElement(WonderboltTransformSpells), true); } } @@ -1321,7 +1323,7 @@ class spell_brewfest_relay_race_intro_force_player_to_throw : public SpellScript PreventHitDefaultEffect(effIndex); // All this spells trigger a spell that requires reagents; if the // triggered spell is cast as "triggered", reagents are not consumed - GetHitUnit()->CastSpell((Unit*)NULL, GetSpellInfo()->Effects[effIndex].TriggerSpell, TriggerCastFlags(TRIGGERED_FULL_MASK & ~TRIGGERED_IGNORE_POWER_AND_REAGENT_COST)); + GetHitUnit()->CastSpell((Unit*)nullptr, GetSpellInfo()->Effects[effIndex].TriggerSpell, TriggerCastFlags(TRIGGERED_FULL_MASK & ~TRIGGERED_IGNORE_POWER_AND_REAGENT_COST)); } void Register() override @@ -1507,9 +1509,13 @@ class spell_midsummer_braziers_hit : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TORCH_TOSSING_TRAINING) || !sSpellMgr->GetSpellInfo(SPELL_TORCH_TOSSING_PRACTICE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_TORCH_TOSSING_TRAINING, + SPELL_TORCH_TOSSING_PRACTICE, + SPELL_TORCH_TOSSING_TRAINING_SUCCESS_ALLIANCE, + SPELL_TORCH_TOSSING_TRAINING_SUCCESS_HORDE + }); } void HandleEffectApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1560,11 +1566,13 @@ class spell_gen_ribbon_pole_dancer_check : public SpellScriptLoader 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; + return ValidateSpellInfo( + { + SPELL_RIBBON_DANCE_COSMETIC, + SPELL_BURNING_HOT_POLE_DANCE, + SPELL_HAS_FULL_MIDSUMMER_SET, + SPELL_RIBBON_DANCE + }); } void PeriodicTick(AuraEffect const* /*aurEff*/) diff --git a/src/server/scripts/Spells/spell_hunter.cpp b/src/server/scripts/Spells/spell_hunter.cpp index 7e3332c2992..2a0a4caccaa 100644 --- a/src/server/scripts/Spells/spell_hunter.cpp +++ b/src/server/scripts/Spells/spell_hunter.cpp @@ -21,15 +21,14 @@ * Scriptnames of files in this file should be prefixed with "spell_hun_". */ -#include "Pet.h" #include "ScriptMgr.h" -#include "Cell.h" #include "CellImpl.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" -#include "SpellHistory.h" -#include "SpellScript.h" +#include "Pet.h" #include "SpellAuraEffects.h" +#include "SpellHistory.h" +#include "SpellMgr.h" +#include "SpellScript.h" enum HunterSpells { @@ -85,12 +84,13 @@ class spell_hun_ancient_hysteria : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_INSANITY) - || !sSpellMgr->GetSpellInfo(SPELL_MAGE_TEMPORAL_DISPLACEMENT) - || !sSpellMgr->GetSpellInfo(SPELL_SHAMAN_EXHAUSTION) - || !sSpellMgr->GetSpellInfo(SPELL_SHAMAN_SATED)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_HUNTER_INSANITY, + SPELL_MAGE_TEMPORAL_DISPLACEMENT, + SPELL_SHAMAN_EXHAUSTION, + SPELL_SHAMAN_SATED + }); } void RemoveInvalidTargets(std::list& targets) @@ -132,10 +132,7 @@ class spell_hun_chimera_shot : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_CHIMERA_SHOT_HEAL) || - !sSpellMgr->GetSpellInfo(SPELL_HUNTER_SERPENT_STING)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_CHIMERA_SHOT_HEAL, SPELL_HUNTER_SERPENT_STING }); } bool Load() override @@ -175,10 +172,7 @@ class spell_hun_cobra_shot : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_GENERIC_ENERGIZE_FOCUS) || - !sSpellMgr->GetSpellInfo(SPELL_HUNTER_SERPENT_STING)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_GENERIC_ENERGIZE_FOCUS, SPELL_HUNTER_SERPENT_STING }); } bool Load() override @@ -288,9 +282,7 @@ class spell_hun_improved_mend_pet : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_IMPROVED_MEND_PET)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_IMPROVED_MEND_PET }); } bool CheckProc(ProcEventInfo& /*eventInfo*/) @@ -301,7 +293,7 @@ class spell_hun_improved_mend_pet : public SpellScriptLoader void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_HUNTER_IMPROVED_MEND_PET, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_HUNTER_IMPROVED_MEND_PET, true, nullptr, aurEff); } void Register() override @@ -365,9 +357,7 @@ class spell_hun_invigoration : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_INVIGORATION_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_INVIGORATION_TRIGGERED }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -402,16 +392,14 @@ class spell_hun_last_stand_pet : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_PET_LAST_STAND_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_PET_LAST_STAND_TRIGGERED }); } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); int32 healthModSpellBasePoints0 = int32(caster->CountPctFromMaxHealth(30)); - caster->CastCustomSpell(caster, SPELL_HUNTER_PET_LAST_STAND_TRIGGERED, &healthModSpellBasePoints0, NULL, NULL, true, NULL); + caster->CastCustomSpell(caster, SPELL_HUNTER_PET_LAST_STAND_TRIGGERED, &healthModSpellBasePoints0, nullptr, nullptr, true, nullptr); } void Register() override @@ -438,10 +426,7 @@ class spell_hun_lock_and_load : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_LOCK_AND_LOAD_TRIGGER) || - !sSpellMgr->GetSpellInfo(SPELL_LOCK_AND_LOAD_MARKER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_LOCK_AND_LOAD_TRIGGER, SPELL_LOCK_AND_LOAD_MARKER }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -501,10 +486,7 @@ class spell_hun_masters_call : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_MASTERS_CALL_TRIGGERED) || - !sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].CalcValue())) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_MASTERS_CALL_TRIGGERED, uint32(spellInfo->Effects[EFFECT_0].CalcValue()) }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -553,9 +535,7 @@ class spell_hun_misdirection : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_MISDIRECTION_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_MISDIRECTION_PROC }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -572,7 +552,7 @@ class spell_hun_misdirection : public SpellScriptLoader void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_HUNTER_MISDIRECTION_PROC, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_HUNTER_MISDIRECTION_PROC, true, nullptr, aurEff); } void Register() override @@ -635,16 +615,14 @@ class spell_hun_pet_carrion_feeder : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_PET_CARRION_FEEDER_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_PET_CARRION_FEEDER_TRIGGERED }); } SpellCastResult CheckIfCorpseNear() { Unit* caster = GetCaster(); float max_range = GetSpellInfo()->GetMaxRange(false); - WorldObject* result = NULL; + WorldObject* result = nullptr; // search for nearby enemy corpse in range Trinity::AnyDeadUnitSpellTargetInRangeCheck check(caster, max_range, GetSpellInfo(), TARGET_CHECK_ENEMY); Trinity::WorldObjectSearcher searcher(caster, result, check); @@ -694,9 +672,7 @@ class spell_hun_pet_heart_of_the_phoenix : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_TRIGGERED) || !sSpellMgr->GetSpellInfo(SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_DEBUFF)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_TRIGGERED, SPELL_HUNTER_PET_HEART_OF_THE_PHOENIX_DEBUFF }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -734,9 +710,7 @@ class spell_hun_rapid_recuperation : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_RAPID_RECUPERATION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_RAPID_RECUPERATION }); } void HandleAbilityCast(AuraEffect const* /*aurEff*/, ProcEventInfo& eventInfo) @@ -754,7 +728,7 @@ class spell_hun_rapid_recuperation : public SpellScriptLoader return; int32 focus = aurEff->GetAmount(); - GetTarget()->CastCustomSpell(SPELL_HUNTER_RAPID_RECUPERATION, SPELLVALUE_BASE_POINT0, focus, GetTarget(), true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_HUNTER_RAPID_RECUPERATION, SPELLVALUE_BASE_POINT0, focus, GetTarget(), true, nullptr, aurEff); } void Register() override @@ -827,16 +801,14 @@ class spell_hun_ready_set_aim : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_FIRE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_FIRE }); } void OnApply(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { if (GetStackAmount() == 5) { - GetTarget()->CastSpell(GetTarget(), SPELL_HUNTER_FIRE, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_HUNTER_FIRE, true, nullptr, aurEff); GetTarget()->RemoveAura(GetId()); } } @@ -901,10 +873,7 @@ class spell_hun_sniper_training : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_SNIPER_TRAINING_R1) || - !sSpellMgr->GetSpellInfo(SPELL_HUNTER_SNIPER_TRAINING_BUFF_R1)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_SNIPER_TRAINING_R1, SPELL_HUNTER_SNIPER_TRAINING_BUFF_R1 }); } void HandlePeriodic(AuraEffect const* aurEff) @@ -962,9 +931,7 @@ class spell_hun_steady_shot : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_STEADY_SHOT_FOCUS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_STEADY_SHOT_FOCUS }); } bool Load() override @@ -990,7 +957,6 @@ class spell_hun_steady_shot : public SpellScriptLoader }; // 53221 - 53221 - 53224 - Improved Steady Shot - class spell_hun_improved_steady_shot : public SpellScriptLoader { public: @@ -1008,12 +974,7 @@ class spell_hun_improved_steady_shot : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_STEADY_SHOT)) - return false; - - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_IMPROVED_STEADY_SHOT_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_STEADY_SHOT, SPELL_HUNTER_IMPROVED_STEADY_SHOT_TRIGGERED }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1141,9 +1102,7 @@ class spell_hun_thrill_of_the_hunt : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_THRILL_OF_THE_HUNT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_THRILL_OF_THE_HUNT }); } void HandleEffectProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1152,7 +1111,7 @@ class spell_hun_thrill_of_the_hunt : public SpellScriptLoader int32 focus = eventInfo.GetDamageInfo()->GetSpellInfo()->CalcPowerCost(GetTarget(), SpellSchoolMask(eventInfo.GetDamageInfo()->GetSchoolMask())); focus = CalculatePct(focus, aurEff->GetAmount()); - GetTarget()->CastCustomSpell(GetTarget(), SPELL_HUNTER_THRILL_OF_THE_HUNT, &focus, NULL, NULL, true, NULL, aurEff); + GetTarget()->CastCustomSpell(GetTarget(), SPELL_HUNTER_THRILL_OF_THE_HUNT, &focus, nullptr, nullptr, true, nullptr, aurEff); } void Register() override @@ -1179,9 +1138,7 @@ class spell_hun_tnt : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HUNTER_LOCK_AND_LOAD)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HUNTER_LOCK_AND_LOAD }); } bool CheckProc(ProcEventInfo& /*eventInfo*/) @@ -1192,7 +1149,7 @@ class spell_hun_tnt : public SpellScriptLoader void HandleEffectProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_HUNTER_LOCK_AND_LOAD, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_HUNTER_LOCK_AND_LOAD, true, nullptr, aurEff); } void Register() override diff --git a/src/server/scripts/Spells/spell_item.cpp b/src/server/scripts/Spells/spell_item.cpp index 02511885d6b..e3f3a068732 100644 --- a/src/server/scripts/Spells/spell_item.cpp +++ b/src/server/scripts/Spells/spell_item.cpp @@ -21,15 +21,19 @@ * Scriptnames of files in this file should be prefixed with "spell_item_". */ -#include "Player.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "SpellHistory.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "SkillDiscovery.h" #include "Battleground.h" +#include "CreatureAIImpl.h" #include "DBCStores.h" +#include "Map.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "ScriptedCreature.h" +#include "SkillDiscovery.h" +#include "SpellAuraEffects.h" +#include "SpellHistory.h" +#include "SpellMgr.h" +#include "SpellScript.h" // Generic script for handling item dummy effects which trigger another spell. class spell_item_trigger_spell : public SpellScriptLoader @@ -38,7 +42,7 @@ class spell_item_trigger_spell : public SpellScriptLoader uint32 _triggeredSpellId; public: - spell_item_trigger_spell(const char* name, uint32 triggeredSpellId) : SpellScriptLoader(name), _triggeredSpellId(triggeredSpellId) { } + spell_item_trigger_spell(char const* name, uint32 triggeredSpellId) : SpellScriptLoader(name), _triggeredSpellId(triggeredSpellId) { } class spell_item_trigger_spell_SpellScript : public SpellScript { @@ -51,9 +55,7 @@ class spell_item_trigger_spell : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(_triggeredSpellId)) - return false; - return true; + return ValidateSpellInfo({ _triggeredSpellId }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -92,15 +94,13 @@ class spell_item_aegis_of_preservation : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_AEGIS_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_AEGIS_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_AEGIS_HEAL, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_AEGIS_HEAL, true, nullptr, aurEff); } void Register() override @@ -142,10 +142,11 @@ class spell_item_alchemists_stone : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ALCHEMISTS_STONE_EXTRA_HEAL) || - !sSpellMgr->GetSpellInfo(SPELL_ALCHEMISTS_STONE_EXTRA_MANA)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_ALCHEMISTS_STONE_EXTRA_HEAL, + SPELL_ALCHEMISTS_STONE_EXTRA_MANA + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -213,11 +214,12 @@ class spell_item_anger_capacitor : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MOTE_OF_ANGER) || - !sSpellMgr->GetSpellInfo(SPELL_MANIFEST_ANGER_MAIN_HAND) || - !sSpellMgr->GetSpellInfo(SPELL_MANIFEST_ANGER_OFF_HAND)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_MOTE_OF_ANGER, + SPELL_MANIFEST_ANGER_MAIN_HAND, + SPELL_MANIFEST_ANGER_OFF_HAND + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -312,18 +314,18 @@ class spell_item_aura_of_madness : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SOCIOPATH) || - !sSpellMgr->GetSpellInfo(SPELL_DELUSIONAL) || - !sSpellMgr->GetSpellInfo(SPELL_KLEPTOMANIA) || - !sSpellMgr->GetSpellInfo(SPELL_MEGALOMANIA) || - !sSpellMgr->GetSpellInfo(SPELL_PARANOIA) || - !sSpellMgr->GetSpellInfo(SPELL_MANIC) || - !sSpellMgr->GetSpellInfo(SPELL_NARCISSISM) || - !sSpellMgr->GetSpellInfo(SPELL_MARTYR_COMPLEX) || - !sSpellMgr->GetSpellInfo(SPELL_DEMENTIA) || - !sObjectMgr->GetBroadcastText(SAY_MADNESS)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SOCIOPATH, + SPELL_DELUSIONAL, + SPELL_KLEPTOMANIA, + SPELL_MEGALOMANIA, + SPELL_PARANOIA, + SPELL_MANIC, + SPELL_NARCISSISM, + SPELL_MARTYR_COMPLEX, + SPELL_DEMENTIA + }) && sObjectMgr->GetBroadcastText(SAY_MADNESS); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -389,10 +391,11 @@ class spell_item_dementia : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DEMENTIA_POS) || - !sSpellMgr->GetSpellInfo(SPELL_DEMENTIA_NEG)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_DEMENTIA_POS, + SPELL_DEMENTIA_NEG + }); } void HandlePeriodicDummy(AuraEffect const* aurEff) @@ -430,9 +433,7 @@ class spell_item_blessing_of_ancient_kings : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PROTECTION_OF_ANCIENT_KINGS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PROTECTION_OF_ANCIENT_KINGS }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -535,9 +536,7 @@ class spell_item_deadly_precision_dummy : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DEADLY_PRECISION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DEADLY_PRECISION }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -591,13 +590,14 @@ class spell_item_deathbringers_will : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(Strength) || - !sSpellMgr->GetSpellInfo(Agility) || - !sSpellMgr->GetSpellInfo(AttackPower) || - !sSpellMgr->GetSpellInfo(Critical) || - !sSpellMgr->GetSpellInfo(Haste)) - return false; - return true; + return ValidateSpellInfo( + { + Strength, + Agility, + AttackPower, + Critical, + Haste + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -724,9 +724,7 @@ class spell_item_defibrillate : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (_failSpell && !sSpellMgr->GetSpellInfo(_failSpell)) - return false; - return true; + return !_failSpell || ValidateSpellInfo({ _failSpell }); } void HandleScript(SpellEffIndex effIndex) @@ -776,15 +774,13 @@ class spell_item_desperate_defense : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DESPERATE_RAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DESPERATE_RAGE }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_DESPERATE_RAGE, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_DESPERATE_RAGE, true, nullptr, aurEff); } void Register() override @@ -826,17 +822,14 @@ class spell_item_deviate_fish : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - for (uint32 spellId = SPELL_SLEEPY; spellId <= SPELL_HEALTHY_SPIRIT; ++spellId) - if (!sSpellMgr->GetSpellInfo(spellId)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SLEEPY, SPELL_INVIGORATE, SPELL_SHRINK, SPELL_PARTY_TIME, SPELL_HEALTHY_SPIRIT }); } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); uint32 spellId = urand(SPELL_SLEEPY, SPELL_HEALTHY_SPIRIT); - caster->CastSpell(caster, spellId, true, NULL); + caster->CastSpell(caster, spellId, true, nullptr); } void Register() override @@ -868,9 +861,7 @@ class spell_item_discerning_eye_beast_dummy : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_DISCERNING_EYE_BEAST)) - return false; - return true; + return ValidateSpellInfo({ SPELL_DISCERNING_EYE_BEAST }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -942,9 +933,7 @@ class spell_item_fate_rune_of_unsurpassed_vigor : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_UNSURPASSED_VIGOR)) - return false; - return true; + return ValidateSpellInfo({ SPELL_UNSURPASSED_VIGOR }); } void HandleProc(AuraEffect const* /*aurEff*/, ProcEventInfo& /*eventInfo*/) @@ -985,9 +974,7 @@ class spell_item_flask_of_the_north : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_THE_NORTH_SP) || !sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_THE_NORTH_AP) || !sSpellMgr->GetSpellInfo(SPELL_FLASK_OF_THE_NORTH_STR)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FLASK_OF_THE_NORTH_SP, SPELL_FLASK_OF_THE_NORTH_AP, SPELL_FLASK_OF_THE_NORTH_STR }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1020,7 +1007,7 @@ class spell_item_flask_of_the_north : public SpellScriptLoader break; } - caster->CastSpell(caster, possibleSpells[urand(0, (possibleSpells.size() - 1))], true, NULL); + caster->CastSpell(caster, possibleSpells[urand(0, (possibleSpells.size() - 1))], true, nullptr); } void Register() override @@ -1053,9 +1040,7 @@ class spell_item_frozen_shadoweave : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHADOWMEND)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHADOWMEND }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1101,9 +1086,7 @@ class spell_item_gnomish_death_ray : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GNOMISH_DEATH_RAY_SELF) || !sSpellMgr->GetSpellInfo(SPELL_GNOMISH_DEATH_RAY_TARGET)) - return false; - return true; + return ValidateSpellInfo({ SPELL_GNOMISH_DEATH_RAY_SELF, SPELL_GNOMISH_DEATH_RAY_TARGET }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1148,9 +1131,7 @@ class spell_item_harm_prevention_belt : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FORCEFIELD_COLLAPSE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FORCEFIELD_COLLAPSE }); } void HandleProc(ProcEventInfo& /*eventInfo*/) @@ -1188,9 +1169,7 @@ class spell_item_healing_touch_refund : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HEALING_TOUCH_MANA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HEALING_TOUCH_MANA }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1242,12 +1221,13 @@ class spell_item_heartpierce : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(Energy) || - !sSpellMgr->GetSpellInfo(Mana) || - !sSpellMgr->GetSpellInfo(Rage) || - !sSpellMgr->GetSpellInfo(RunicPower)) - return false; - return true; + return ValidateSpellInfo( + { + Energy, + Mana, + Rage, + RunicPower + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1350,9 +1330,14 @@ class spell_item_make_a_wish : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MR_PINCHYS_BLESSING) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_MIGHTY_MR_PINCHY) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_FURIOUS_MR_PINCHY) || !sSpellMgr->GetSpellInfo(SPELL_TINY_MAGICAL_CRAWDAD) || !sSpellMgr->GetSpellInfo(SPELL_MR_PINCHYS_GIFT)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_MR_PINCHYS_BLESSING, + SPELL_SUMMON_MIGHTY_MR_PINCHY, + SPELL_SUMMON_FURIOUS_MR_PINCHY, + SPELL_TINY_MAGICAL_CRAWDAD, + SPELL_MR_PINCHYS_GIFT + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1366,7 +1351,7 @@ class spell_item_make_a_wish : public SpellScriptLoader case 3: spellId = SPELL_SUMMON_FURIOUS_MR_PINCHY; break; case 4: spellId = SPELL_TINY_MAGICAL_CRAWDAD; break; } - caster->CastSpell(caster, spellId, true, NULL); + caster->CastSpell(caster, spellId, true, nullptr); } void Register() override @@ -1400,9 +1385,7 @@ class spell_item_mark_of_conquest : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MARK_OF_CONQUEST_ENERGIZE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MARK_OF_CONQUEST_ENERGIZE }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1501,9 +1484,7 @@ class spell_item_necrotic_touch : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ITEM_NECROTIC_TOUCH_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ITEM_NECROTIC_TOUCH_PROC }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1555,9 +1536,12 @@ class spell_item_net_o_matic : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_NET_O_MATIC_TRIGGERED1) || !sSpellMgr->GetSpellInfo(SPELL_NET_O_MATIC_TRIGGERED2) || !sSpellMgr->GetSpellInfo(SPELL_NET_O_MATIC_TRIGGERED3)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_NET_O_MATIC_TRIGGERED1, + SPELL_NET_O_MATIC_TRIGGERED2, + SPELL_NET_O_MATIC_TRIGGERED3 + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1612,9 +1596,12 @@ class spell_item_noggenfogger_elixir : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED1) || !sSpellMgr->GetSpellInfo(SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED2) || !sSpellMgr->GetSpellInfo(SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED3)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED1, + SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED2, + SPELL_NOGGENFOGGER_ELIXIR_TRIGGERED3 + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1689,9 +1676,7 @@ class spell_item_persistent_shield : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PERSISTENT_SHIELD_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PERSISTENT_SHIELD_TRIGGERED }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1745,9 +1730,7 @@ class spell_item_pet_healing : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_HEALTH_LINK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_HEALTH_LINK }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1870,10 +1853,13 @@ class spell_item_savory_deviate_delight : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - for (uint32 spellId = SPELL_FLIP_OUT_MALE; spellId <= SPELL_YAAARRRR_FEMALE; ++spellId) - if (!sSpellMgr->GetSpellInfo(spellId)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_FLIP_OUT_MALE, + SPELL_FLIP_OUT_FEMALE, + SPELL_YAAARRRR_MALE, + SPELL_YAAARRRR_FEMALE + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1887,7 +1873,7 @@ class spell_item_savory_deviate_delight : public SpellScriptLoader // Yaaarrrr - pirate case 2: spellId = (caster->getGender() == GENDER_MALE ? SPELL_YAAARRRR_MALE : SPELL_YAAARRRR_FEMALE); break; } - caster->CastSpell(caster, spellId, true, NULL); + caster->CastSpell(caster, spellId, true, nullptr); } void Register() override @@ -2070,13 +2056,12 @@ class spell_item_shadowmourne : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_CHAOS_BANE_DAMAGE)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_SOUL_FRAGMENT)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SHADOWMOURNE_CHAOS_BANE_DAMAGE, + SPELL_SHADOWMOURNE_SOUL_FRAGMENT, + SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF + }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -2089,14 +2074,14 @@ class spell_item_shadowmourne : public SpellScriptLoader void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_SHADOWMOURNE_SOUL_FRAGMENT, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_SHADOWMOURNE_SOUL_FRAGMENT, true, nullptr, aurEff); // this can't be handled in AuraScript of SoulFragments because we need to know victim if (Aura* soulFragments = GetTarget()->GetAura(SPELL_SHADOWMOURNE_SOUL_FRAGMENT)) { if (soulFragments->GetStackAmount() >= 10) { - GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_SHADOWMOURNE_CHAOS_BANE_DAMAGE, true, NULL, aurEff); + GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_SHADOWMOURNE_CHAOS_BANE_DAMAGE, true, nullptr, aurEff); soulFragments->Remove(); } } @@ -2127,9 +2112,12 @@ class spell_item_shadowmourne_soul_fragment : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_VISUAL_LOW) || !sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_VISUAL_HIGH) || !sSpellMgr->GetSpellInfo(SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SHADOWMOURNE_VISUAL_LOW, + SPELL_SHADOWMOURNE_VISUAL_HIGH, + SPELL_SHADOWMOURNE_CHAOS_BANE_BUFF + }); } void OnStackChange(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2196,9 +2184,15 @@ class spell_item_six_demon_bag : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FROSTBOLT) || !sSpellMgr->GetSpellInfo(SPELL_POLYMORPH) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_FELHOUND_MINION) || !sSpellMgr->GetSpellInfo(SPELL_FIREBALL) || !sSpellMgr->GetSpellInfo(SPELL_CHAIN_LIGHTNING) || !sSpellMgr->GetSpellInfo(SPELL_ENVELOPING_WINDS)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_FROSTBOLT, + SPELL_POLYMORPH, + SPELL_SUMMON_FELHOUND_MINION, + SPELL_FIREBALL, + SPELL_CHAIN_LIGHTNING, + SPELL_ENVELOPING_WINDS + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2261,9 +2255,7 @@ class spell_item_swift_hand_justice_dummy : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SWIFT_HAND_OF_JUSTICE_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SWIFT_HAND_OF_JUSTICE_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2305,9 +2297,7 @@ class spell_item_totem_of_flowing_water : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_LESSER_HEALING_WAVE_MANA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_LESSER_HEALING_WAVE_MANA }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -2382,9 +2372,12 @@ class spell_item_underbelly_elixir : public SpellScriptLoader } bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_UNDERBELLY_ELIXIR_TRIGGERED1) || !sSpellMgr->GetSpellInfo(SPELL_UNDERBELLY_ELIXIR_TRIGGERED2) || !sSpellMgr->GetSpellInfo(SPELL_UNDERBELLY_ELIXIR_TRIGGERED3)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_UNDERBELLY_ELIXIR_TRIGGERED1, + SPELL_UNDERBELLY_ELIXIR_TRIGGERED2, + SPELL_UNDERBELLY_ELIXIR_TRIGGERED3 + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2396,7 +2389,7 @@ class spell_item_underbelly_elixir : public SpellScriptLoader case 1: spellId = SPELL_UNDERBELLY_ELIXIR_TRIGGERED1; break; case 2: spellId = SPELL_UNDERBELLY_ELIXIR_TRIGGERED2; break; } - caster->CastSpell(caster, spellId, true, NULL); + caster->CastSpell(caster, spellId, true, nullptr); } void Register() override @@ -2480,9 +2473,12 @@ class spell_item_red_rider_air_rifle : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_AIR_RIFLE_HOLD_VISUAL) || !sSpellMgr->GetSpellInfo(SPELL_AIR_RIFLE_SHOOT) || !sSpellMgr->GetSpellInfo(SPELL_AIR_RIFLE_SHOOT_SELF)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_AIR_RIFLE_HOLD_VISUAL, + SPELL_AIR_RIFLE_SHOOT, + SPELL_AIR_RIFLE_SHOOT_SELF + }); } void HandleScript(SpellEffIndex effIndex) @@ -2711,9 +2707,12 @@ class spell_item_vanquished_clutches : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CRUSHER) || !sSpellMgr->GetSpellInfo(SPELL_CONSTRICTOR) || !sSpellMgr->GetSpellInfo(SPELL_CORRUPTOR)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_CRUSHER, + SPELL_CONSTRICTOR, + SPELL_CORRUPTOR + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2897,15 +2896,17 @@ class spell_item_purify_helboar_meat : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_PURIFIED_HELBOAR_MEAT) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_TOXIC_HELBOAR_MEAT)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SUMMON_PURIFIED_HELBOAR_MEAT, + SPELL_SUMMON_TOXIC_HELBOAR_MEAT + }); } void HandleDummy(SpellEffIndex /* effIndex */) { Unit* caster = GetCaster(); - caster->CastSpell(caster, roll_chance_i(50) ? SPELL_SUMMON_PURIFIED_HELBOAR_MEAT : SPELL_SUMMON_TOXIC_HELBOAR_MEAT, true, NULL); + caster->CastSpell(caster, roll_chance_i(50) ? SPELL_SUMMON_PURIFIED_HELBOAR_MEAT : SPELL_SUMMON_TOXIC_HELBOAR_MEAT, true, nullptr); } void Register() override @@ -2946,7 +2947,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, G3D::Quat(), uint32(target->GetRespawnTime()-time(NULL))); + GetCaster()->SummonGameObject(OBJECT_IMPRISONED_DOOMGUARD, *target, QuaternionData(), uint32(target->GetRespawnTime()-time(nullptr))); target->DespawnOrUnsummon(); } } @@ -2983,11 +2984,14 @@ class spell_item_reindeer_transformation : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FLYING_REINDEER_310) || !sSpellMgr->GetSpellInfo(SPELL_FLYING_REINDEER_280) - || !sSpellMgr->GetSpellInfo(SPELL_FLYING_REINDEER_60) || !sSpellMgr->GetSpellInfo(SPELL_REINDEER_100) - || !sSpellMgr->GetSpellInfo(SPELL_REINDEER_60)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_FLYING_REINDEER_310, + SPELL_FLYING_REINDEER_280, + SPELL_FLYING_REINDEER_60, + SPELL_REINDEER_100, + SPELL_REINDEER_60 + }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3048,9 +3052,7 @@ class spell_item_nigh_invulnerability : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_NIGH_INVULNERABILITY) || !sSpellMgr->GetSpellInfo(SPELL_COMPLETE_VULNERABILITY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_NIGH_INVULNERABILITY, SPELL_COMPLETE_VULNERABILITY }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3094,9 +3096,7 @@ class spell_item_poultryizer : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_POULTRYIZER_SUCCESS) || !sSpellMgr->GetSpellInfo(SPELL_POULTRYIZER_BACKFIRE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_POULTRYIZER_SUCCESS, SPELL_POULTRYIZER_BACKFIRE }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3138,9 +3138,7 @@ class spell_item_socrethars_stone : public SpellScriptLoader } bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SOCRETHAR_TO_SEAT) || !sSpellMgr->GetSpellInfo(SPELL_SOCRETHAR_FROM_SEAT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SOCRETHAR_TO_SEAT, SPELL_SOCRETHAR_FROM_SEAT }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3189,9 +3187,9 @@ class spell_item_demon_broiled_surprise : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CREATE_DEMON_BROILED_SURPRISE) || !sObjectMgr->GetCreatureTemplate(NPC_ABYSSAL_FLAMEBRINGER) || !sObjectMgr->GetQuestTemplate(QUEST_SUPER_HOT_STEW)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CREATE_DEMON_BROILED_SURPRISE }) && + sObjectMgr->GetCreatureTemplate(NPC_ABYSSAL_FLAMEBRINGER) && + sObjectMgr->GetQuestTemplate(QUEST_SUPER_HOT_STEW); } bool Load() override @@ -3246,9 +3244,7 @@ class spell_item_complete_raptor_capture : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RAPTOR_CAPTURE_CREDIT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RAPTOR_CAPTURE_CREDIT }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3259,7 +3255,7 @@ class spell_item_complete_raptor_capture : public SpellScriptLoader GetHitCreature()->DespawnOrUnsummon(); //cast spell Raptor Capture Credit - caster->CastSpell(caster, SPELL_RAPTOR_CAPTURE_CREDIT, true, NULL); + caster->CastSpell(caster, SPELL_RAPTOR_CAPTURE_CREDIT, true, nullptr); } } @@ -3340,9 +3336,13 @@ class spell_item_brewfest_mount_transformation : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MOUNT_RAM_100) || !sSpellMgr->GetSpellInfo(SPELL_MOUNT_RAM_60) || !sSpellMgr->GetSpellInfo(SPELL_MOUNT_KODO_100) || !sSpellMgr->GetSpellInfo(SPELL_MOUNT_KODO_60)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_MOUNT_RAM_100, + SPELL_MOUNT_RAM_60, + SPELL_MOUNT_KODO_100, + SPELL_MOUNT_KODO_60 + }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3411,9 +3411,7 @@ class spell_item_nitro_boosts : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_NITRO_BOOSTS_SUCCESS) || !sSpellMgr->GetSpellInfo(SPELL_NITRO_BOOSTS_BACKFIRE )) - return false; - return true; + return ValidateSpellInfo({ SPELL_NITRO_BOOSTS_SUCCESS, SPELL_NITRO_BOOSTS_BACKFIRE }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3508,9 +3506,7 @@ class spell_item_teach_language : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_LEARN_GNOMISH_BINARY) || !sSpellMgr->GetSpellInfo(SPELL_LEARN_GOBLIN_BINARY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_LEARN_GNOMISH_BINARY, SPELL_LEARN_GOBLIN_BINARY }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3554,9 +3550,7 @@ class spell_item_rocket_boots : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROCKET_BOOTS_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROCKET_BOOTS_PROC }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3566,7 +3560,7 @@ class spell_item_rocket_boots : public SpellScriptLoader bg->EventPlayerDroppedFlag(caster); caster->GetSpellHistory()->ResetCooldown(SPELL_ROCKET_BOOTS_PROC); - caster->CastSpell(caster, SPELL_ROCKET_BOOTS_PROC, true, NULL); + caster->CastSpell(caster, SPELL_ROCKET_BOOTS_PROC, true, nullptr); } SpellCastResult CheckCast() @@ -3606,9 +3600,7 @@ class spell_item_pygmy_oil : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PYGMY_OIL_PYGMY_AURA) || !sSpellMgr->GetSpellInfo(SPELL_PYGMY_OIL_SMALLER_AURA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PYGMY_OIL_PYGMY_AURA, SPELL_PYGMY_OIL_SMALLER_AURA }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3692,9 +3684,9 @@ class spell_item_chicken_cover : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CHICKEN_NET) || !sSpellMgr->GetSpellInfo(SPELL_CAPTURE_CHICKEN_ESCAPE) || !sObjectMgr->GetQuestTemplate(QUEST_CHICKEN_PARTY) || !sObjectMgr->GetQuestTemplate(QUEST_FLOWN_THE_COOP)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CHICKEN_NET, SPELL_CAPTURE_CHICKEN_ESCAPE }) && + sObjectMgr->GetQuestTemplate(QUEST_CHICKEN_PARTY) && + sObjectMgr->GetQuestTemplate(QUEST_FLOWN_THE_COOP); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -3808,10 +3800,11 @@ class spell_item_shard_of_the_scale : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(HealProc) || - !sSpellMgr->GetSpellInfo(DamageProc)) - return false; - return true; + return ValidateSpellInfo( + { + HealProc, + DamageProc + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -3858,12 +3851,13 @@ public: 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; + return ValidateSpellInfo( + { + SPELL_SOUL_PRESERVER_DRUID, + SPELL_SOUL_PRESERVER_PALADIN, + SPELL_SOUL_PRESERVER_PRIEST, + SPELL_SOUL_PRESERVER_SHAMAN + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -3945,12 +3939,9 @@ class spell_item_sunwell_neck : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sFactionStore.LookupEntry(FACTION_ALDOR) || - !sFactionStore.LookupEntry(FACTION_SCRYERS) || - !sSpellMgr->GetSpellInfo(Aldors) || - !sSpellMgr->GetSpellInfo(Scryers)) - return false; - return true; + return ValidateSpellInfo({ Aldors, Scryers }) && + sFactionStore.LookupEntry(FACTION_ALDOR) && + sFactionStore.LookupEntry(FACTION_SCRYERS); } bool CheckProc(ProcEventInfo& eventInfo) @@ -4043,11 +4034,8 @@ class spell_item_taunt_flag_targeting : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TAUNT_FLAG)) - return false; - if (!sObjectMgr->GetBroadcastText(EMOTE_PLANTS_FLAG)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TAUNT_FLAG }) && + sObjectMgr->GetBroadcastText(EMOTE_PLANTS_FLAG); } void FilterTargets(std::list& targets) @@ -4116,9 +4104,7 @@ class spell_item_mind_control_cap : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GNOMISH_MIND_CONTROL_CAP) || !sSpellMgr->GetSpellInfo(SPELL_DULLARD)) - return false; - return true; + return ValidateSpellInfo({ SPELL_GNOMISH_MIND_CONTROL_CAP, SPELL_DULLARD }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -4171,9 +4157,7 @@ class spell_item_universal_remote : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CONTROL_MACHINE) || !sSpellMgr->GetSpellInfo(SPELL_MOBILITY_MALFUNCTION) || !sSpellMgr->GetSpellInfo(SPELL_TARGET_LOCK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CONTROL_MACHINE, SPELL_MOBILITY_MALFUNCTION, SPELL_TARGET_LOCK }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -4227,9 +4211,7 @@ class spell_item_zandalarian_charm : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(_spellId)) - return false; - return true; + return ValidateSpellInfo({ _spellId }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -4421,12 +4403,13 @@ public: 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; + return ValidateSpellInfo( + { + SPELL_DEATH_CHOICE_NORMAL_STRENGTH, + SPELL_DEATH_CHOICE_NORMAL_AGILITY, + SPELL_DEATH_CHOICE_HEROIC_STRENGTH, + SPELL_DEATH_CHOICE_HEROIC_AGILITY + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -4507,9 +4490,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(_stackSpell) || !sSpellMgr->GetSpellInfo(_triggerSpell)) - return false; - return true; + return ValidateSpellInfo({ _stackSpell, _triggerSpell }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -4555,7 +4536,7 @@ private: // 57345 - Darkmoon Card: Greatness enum DarkmoonCardSpells { - SPELL_DARKMOON_CARD_STRENGHT = 60229, + SPELL_DARKMOON_CARD_STRENGTH = 60229, SPELL_DARKMOON_CARD_AGILITY = 60233, SPELL_DARKMOON_CARD_INTELLECT = 60234, SPELL_DARKMOON_CARD_SPIRIT = 60235, @@ -4572,12 +4553,13 @@ public: 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; + return ValidateSpellInfo( + { + SPELL_DARKMOON_CARD_STRENGTH, + SPELL_DARKMOON_CARD_AGILITY, + SPELL_DARKMOON_CARD_INTELLECT, + SPELL_DARKMOON_CARD_SPIRIT + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -4591,11 +4573,11 @@ public: float spi = caster->GetStat(STAT_SPIRIT); float stat = 0.0f; - uint32 spellTrigger = SPELL_DARKMOON_CARD_STRENGHT; + uint32 spellTrigger = SPELL_DARKMOON_CARD_STRENGTH; if (str > stat) { - spellTrigger = SPELL_DARKMOON_CARD_STRENGHT; + spellTrigger = SPELL_DARKMOON_CARD_STRENGTH; stat = str; } @@ -4649,9 +4631,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CHARM_WITCH_DOCTOR_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CHARM_WITCH_DOCTOR_PROC }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -4698,10 +4678,11 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MANA_DRAIN_ENERGIZE) - || !sSpellMgr->GetSpellInfo(SPELL_MANA_DRAIN_LEECH)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_MANA_DRAIN_ENERGIZE, + SPELL_MANA_DRAIN_LEECH + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) diff --git a/src/server/scripts/Spells/spell_mage.cpp b/src/server/scripts/Spells/spell_mage.cpp index 0ac73c90ffd..b6cd8a0f4bb 100644 --- a/src/server/scripts/Spells/spell_mage.cpp +++ b/src/server/scripts/Spells/spell_mage.cpp @@ -21,20 +21,21 @@ * Scriptnames of files in this file should be prefixed with "spell_mage_". */ -#include "Player.h" #include "ScriptMgr.h" -#include "SpellHistory.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "Pet.h" #include "GridNotifiers.h" +#include "Pet.h" +#include "Player.h" +#include "SpellAuraEffects.h" +#include "SpellHistory.h" +#include "SpellMgr.h" +#include "SpellScript.h" enum MageSpells { - SPELL_ARCANCE_POTENCY_RANK_1 = 31571, - SPELL_ARCANCE_POTENCY_RANK_2 = 31572, - SPELL_ARCANCE_POTENCY_TRIGGER_RANK_1 = 57529, - SPELL_ARCANCE_POTENCY_TRIGGER_RANK_2 = 57531, + SPELL_MAGE_ARCANE_POTENCY_RANK_1 = 31571, + SPELL_MAGE_ARCANE_POTENCY_RANK_2 = 31572, + SPELL_MAGE_ARCANE_POTENCY_TRIGGER_RANK_1 = 57529, + SPELL_MAGE_ARCANE_POTENCY_TRIGGER_RANK_2 = 57531, SPELL_MAGE_ARCANE_BLAST = 30451, SPELL_MAGE_ARCANE_MISSILES = 5143, @@ -131,12 +132,13 @@ class spell_mage_arcane_potency : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ARCANCE_POTENCY_RANK_1) || - !sSpellMgr->GetSpellInfo(SPELL_ARCANCE_POTENCY_RANK_2) || - !sSpellMgr->GetSpellInfo(SPELL_ARCANCE_POTENCY_TRIGGER_RANK_1) || - !sSpellMgr->GetSpellInfo(SPELL_ARCANCE_POTENCY_TRIGGER_RANK_2)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_MAGE_ARCANE_POTENCY_RANK_1, + SPELL_MAGE_ARCANE_POTENCY_RANK_2, + SPELL_MAGE_ARCANE_POTENCY_TRIGGER_RANK_1, + SPELL_MAGE_ARCANE_POTENCY_TRIGGER_RANK_2 + }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) @@ -144,14 +146,14 @@ class spell_mage_arcane_potency : public SpellScriptLoader PreventDefaultAction(); uint32 spellId = 0; - if (GetSpellInfo()->Id == SPELL_ARCANCE_POTENCY_RANK_1) - spellId = SPELL_ARCANCE_POTENCY_TRIGGER_RANK_1; - else if (GetSpellInfo()->Id == SPELL_ARCANCE_POTENCY_RANK_2) - spellId = SPELL_ARCANCE_POTENCY_TRIGGER_RANK_2; + if (GetSpellInfo()->Id == SPELL_MAGE_ARCANE_POTENCY_RANK_1) + spellId = SPELL_MAGE_ARCANE_POTENCY_TRIGGER_RANK_1; + else if (GetSpellInfo()->Id == SPELL_MAGE_ARCANE_POTENCY_RANK_2) + spellId = SPELL_MAGE_ARCANE_POTENCY_TRIGGER_RANK_2; if (!spellId) return; - GetTarget()->CastSpell(GetTarget(), spellId, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), spellId, true, nullptr, aurEff); } @@ -184,9 +186,7 @@ class spell_mage_blast_wave : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_FLAMESTRIKE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_FLAMESTRIKE }); } void CountTargets(std::list& targetList) @@ -216,8 +216,7 @@ class spell_mage_blast_wave : public SpellScriptLoader AfterCast += SpellCastFn(spell_mage_blast_wave_SpellScript::HandleImprovedFlamestrike); } - private: - uint32 _targetCount =0; + uint32 _targetCount = 0; }; SpellScript* GetSpellScript() const override @@ -238,15 +237,13 @@ class spell_mage_blazing_speed : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_BLAZING_SPEED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_BLAZING_SPEED }); } void OnProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_MAGE_BLAZING_SPEED, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_MAGE_BLAZING_SPEED, true, nullptr, aurEff); } void Register() override @@ -274,11 +271,11 @@ class spell_mage_blizzard : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_CHILLED_R1)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_CHILLED_R2)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_MAGE_CHILLED_R1, + SPELL_MAGE_CHILLED_R2 + }); } void AddChillEffect(SpellEffIndex /*effIndex*/) @@ -386,8 +383,7 @@ struct ConjureRefreshmentData uint32 spellId; }; -uint8 const MAX_CONJURE_REFRESHMENT_SPELLS = 7; -ConjureRefreshmentData const _conjureData[MAX_CONJURE_REFRESHMENT_SPELLS] = +ConjureRefreshmentData const _conjureData[] = { { 33, 43, 92739 }, { 44, 53, 92799 }, @@ -397,6 +393,7 @@ ConjureRefreshmentData const _conjureData[MAX_CONJURE_REFRESHMENT_SPELLS] = { 80, 84, 92822 }, { 85, 85, 92727 } }; +uint8 const MAX_CONJURE_REFRESHMENT_SPELLS = std::extent::value; // 42955 - Conjure Refreshment class spell_mage_conjure_refreshment : public SpellScriptLoader @@ -411,7 +408,7 @@ class spell_mage_conjure_refreshment : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { for (uint8 i = 0; i < MAX_CONJURE_REFRESHMENT_SPELLS; ++i) - if (!sSpellMgr->GetSpellInfo(_conjureData[i].spellId)) + if (!ValidateSpellInfo({ _conjureData[i].spellId })) return false; return true; } @@ -480,10 +477,7 @@ class spell_mage_fire_frost_ward : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_FROST_WARDING_TRIGGERED) || - !sSpellMgr->GetSpellInfo(SPELL_MAGE_FROST_WARDING_R1)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_FROST_WARDING_TRIGGERED, SPELL_MAGE_FROST_WARDING_R1 }); } void CalculateAmount(AuraEffect const* /*aurEff*/, int32& amount, bool& canBeRecalculated) @@ -511,7 +505,7 @@ class spell_mage_fire_frost_ward : public SpellScriptLoader { int32 bp = dmgInfo.GetDamage(); dmgInfo.AbsorbDamage(bp); - target->CastCustomSpell(target, SPELL_MAGE_FROST_WARDING_TRIGGERED, &bp, NULL, NULL, true, NULL, aurEff); + target->CastCustomSpell(target, SPELL_MAGE_FROST_WARDING_TRIGGERED, &bp, nullptr, nullptr, true, nullptr, aurEff); absorbAmount = 0; PreventDefaultAction(); } @@ -541,18 +535,9 @@ class spell_mage_focus_magic : public SpellScriptLoader { PrepareAuraScript(spell_mage_focus_magic_AuraScript); - public: - spell_mage_focus_magic_AuraScript() - { - _procTarget = nullptr; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_FOCUS_MAGIC_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_FOCUS_MAGIC_PROC }); } bool CheckProc(ProcEventInfo& /*eventInfo*/) @@ -564,7 +549,7 @@ class spell_mage_focus_magic : public SpellScriptLoader void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(_procTarget, SPELL_MAGE_FOCUS_MAGIC_PROC, true, NULL, aurEff); + GetTarget()->CastSpell(_procTarget, SPELL_MAGE_FOCUS_MAGIC_PROC, true, nullptr, aurEff); } void Register() override @@ -573,8 +558,7 @@ class spell_mage_focus_magic : public SpellScriptLoader OnEffectProc += AuraEffectProcFn(spell_mage_focus_magic_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_MOD_SPELL_CRIT_CHANCE); } - private: - Unit* _procTarget; + Unit* _procTarget = nullptr; }; AuraScript* GetAuraScript() const override @@ -663,9 +647,7 @@ class spell_mage_glyph_of_ice_block : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_FROST_NOVA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_FROST_NOVA }); } bool CheckProc(ProcEventInfo& /*eventInfo*/) @@ -735,9 +717,7 @@ class spell_mage_glyph_of_polymorph : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_SHADOW_WORD_DEATH)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_SHADOW_WORD_DEATH }); } void HandleEffectProc(AuraEffect const* /*aurEff*/, ProcEventInfo& eventInfo) @@ -774,9 +754,7 @@ class spell_mage_living_bomb : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(uint32(spellInfo->Effects[EFFECT_1].CalcValue()))) - return false; - return true; + return ValidateSpellInfo({ uint32(spellInfo->Effects[EFFECT_1].CalcValue()) }); } void AfterRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -786,7 +764,7 @@ class spell_mage_living_bomb : public SpellScriptLoader return; if (Unit* caster = GetCaster()) - caster->CastSpell(GetTarget(), uint32(aurEff->GetAmount()), true, NULL, aurEff); + caster->CastSpell(GetTarget(), uint32(aurEff->GetAmount()), true, nullptr, aurEff); } void Register() override @@ -856,9 +834,7 @@ class spell_mage_ignite : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_IGNITE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_IGNITE }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -875,7 +851,7 @@ class spell_mage_ignite : public SpellScriptLoader int32 amount = int32(CalculatePct(eventInfo.GetDamageInfo()->GetDamage(), pct) / igniteDot->GetMaxTicks()); amount += eventInfo.GetProcTarget()->GetRemainingPeriodicAmount(eventInfo.GetActor()->GetGUID(), SPELL_MAGE_IGNITE, SPELL_AURA_PERIODIC_DAMAGE); - GetTarget()->CastCustomSpell(SPELL_MAGE_IGNITE, SPELLVALUE_BASE_POINT0, amount, eventInfo.GetProcTarget(), true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_MAGE_IGNITE, SPELLVALUE_BASE_POINT0, amount, eventInfo.GetProcTarget(), true, nullptr, aurEff); } void Register() override @@ -918,7 +894,7 @@ class spell_mage_mage_ward : public SpellScriptLoader if (AuraEffect* aurEff = GetTarget()->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_GENERIC, ICON_MAGE_INCANTER_S_ABSORPTION, EFFECT_0)) { int32 bp = CalculatePct(absorbAmount, aurEff->GetAmount()); - GetTarget()->CastCustomSpell(GetTarget(), SPELL_MAGE_INCANTERS_ABSORBTION_TRIGGERED, &bp, NULL, NULL, true); + GetTarget()->CastCustomSpell(GetTarget(), SPELL_MAGE_INCANTERS_ABSORBTION_TRIGGERED, &bp, nullptr, nullptr, true); } } @@ -971,7 +947,7 @@ class spell_mage_mana_shield : public SpellScriptLoader if (AuraEffect* aurEff = GetTarget()->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_GENERIC, ICON_MAGE_INCANTER_S_ABSORPTION, EFFECT_0)) { int32 bp = CalculatePct(absorbAmount, aurEff->GetAmount()); - GetTarget()->CastCustomSpell(GetTarget(), SPELL_MAGE_INCANTERS_ABSORBTION_TRIGGERED, &bp, NULL, NULL, true); + GetTarget()->CastCustomSpell(GetTarget(), SPELL_MAGE_INCANTERS_ABSORBTION_TRIGGERED, &bp, nullptr, nullptr, true); } } @@ -1008,9 +984,7 @@ class spell_mage_master_of_elements : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_MASTER_OF_ELEMENTS_ENERGIZE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_MASTER_OF_ELEMENTS_ENERGIZE }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1026,7 +1000,7 @@ class spell_mage_master_of_elements : public SpellScriptLoader mana = CalculatePct(mana, aurEff->GetAmount()); if (mana > 0) - GetTarget()->CastCustomSpell(SPELL_MAGE_MASTER_OF_ELEMENTS_ENERGIZE, SPELLVALUE_BASE_POINT0, mana, GetTarget(), true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_MAGE_MASTER_OF_ELEMENTS_ENERGIZE, SPELLVALUE_BASE_POINT0, mana, GetTarget(), true, nullptr, aurEff); } void Register() override @@ -1076,7 +1050,7 @@ class spell_mage_nether_vortex : public SpellScriptLoader void HandleEffectProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); - GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_MAGE_SLOW, true, NULL, aurEff); + GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_MAGE_SLOW, true, nullptr, aurEff); } void Register() override @@ -1104,9 +1078,7 @@ class spell_mage_permafrost : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_PERMAFROST)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_PERMAFROST }); } bool DoCheck(ProcEventInfo& eventInfo) @@ -1119,7 +1091,7 @@ class spell_mage_permafrost : public SpellScriptLoader PreventDefaultAction(); int32 heal = int32(CalculatePct(eventInfo.GetDamageInfo()->GetDamage(), aurEff->GetAmount())); - GetTarget()->CastCustomSpell(SPELL_MAGE_PERMAFROST, SPELLVALUE_BASE_POINT0, heal, (Unit*)NULL, true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_MAGE_PERMAFROST, SPELLVALUE_BASE_POINT0, heal, (Unit*)nullptr, true, nullptr, aurEff); } void Register() override @@ -1147,16 +1119,17 @@ class spell_mage_polymorph : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_IMPROVED_POLYMORPH_RANK_1) || - !sSpellMgr->GetSpellInfo(SPELL_MAGE_IMPROVED_POLYMORPH_STUN_RANK_1) || - !sSpellMgr->GetSpellInfo(SPELL_MAGE_IMPROVED_POLYMORPH_MARKER)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_MAGE_IMPROVED_POLYMORPH_RANK_1, + SPELL_MAGE_IMPROVED_POLYMORPH_STUN_RANK_1, + SPELL_MAGE_IMPROVED_POLYMORPH_MARKER + }); } bool Load() override { - _caster = NULL; + _caster = nullptr; return true; } @@ -1175,8 +1148,8 @@ class spell_mage_polymorph : public SpellScriptLoader if (_caster->HasAura(SPELL_MAGE_IMPROVED_POLYMORPH_MARKER)) return; - GetTarget()->CastSpell(GetTarget(), sSpellMgr->GetSpellWithRank(SPELL_MAGE_IMPROVED_POLYMORPH_STUN_RANK_1, improvedPolymorph->GetSpellInfo()->GetRank()), true, NULL, aurEff); - _caster->CastSpell(_caster, SPELL_MAGE_IMPROVED_POLYMORPH_MARKER, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), sSpellMgr->GetSpellWithRank(SPELL_MAGE_IMPROVED_POLYMORPH_STUN_RANK_1, improvedPolymorph->GetSpellInfo()->GetRank()), true, nullptr, aurEff); + _caster->CastSpell(_caster, SPELL_MAGE_IMPROVED_POLYMORPH_MARKER, true, nullptr, aurEff); } } @@ -1217,10 +1190,7 @@ class spell_mage_polymorph_cast_visual : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { // check if spell ids exist in dbc - for (uint32 i = 0; i < 6; i++) - if (!sSpellMgr->GetSpellInfo(PolymorhForms[i])) - return false; - return true; + return ValidateSpellInfo(PolymorhForms); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1266,9 +1236,7 @@ class spell_mage_replenish_mana : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_IMPROVED_MANA_GEM_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_IMPROVED_MANA_GEM_TRIGGERED }); } void HandleImprovedManaGem() @@ -1276,7 +1244,7 @@ class spell_mage_replenish_mana : public SpellScriptLoader if (AuraEffect* aurEff = GetCaster()->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_MAGE, ICON_MAGE_IMPROVED_MANA_GEM, EFFECT_0)) { int32 bp = CalculatePct(GetCaster()->GetMaxPower(POWER_MANA), aurEff->GetAmount()); - GetCaster()->CastCustomSpell(GetCaster(), SPELL_MAGE_IMPROVED_MANA_GEM_TRIGGERED, &bp, &bp, NULL, true); + GetCaster()->CastCustomSpell(GetCaster(), SPELL_MAGE_IMPROVED_MANA_GEM_TRIGGERED, &bp, &bp, nullptr, true); } } @@ -1305,18 +1273,17 @@ class spell_mage_ring_of_frost : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_RING_OF_FROST_SUMMON)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_RING_OF_FROST_FREEZE)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_RING_OF_FROST_DUMMY)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_MAGE_RING_OF_FROST_SUMMON, + SPELL_MAGE_RING_OF_FROST_FREEZE, + SPELL_MAGE_RING_OF_FROST_DUMMY + }); } bool Load() override { - ringOfFrost = NULL; + ringOfFrost = nullptr; return true; } @@ -1380,11 +1347,7 @@ class spell_mage_ring_of_frost_freeze : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_RING_OF_FROST_SUMMON)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_RING_OF_FROST_FREEZE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_RING_OF_FROST_SUMMON, SPELL_MAGE_RING_OF_FROST_FREEZE }); } void FilterTargets(std::list& targets) @@ -1415,9 +1378,7 @@ class spell_mage_ring_of_frost_freeze : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_RING_OF_FROST_DUMMY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_RING_OF_FROST_DUMMY }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1451,12 +1412,13 @@ class spell_mage_time_warp : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_TEMPORAL_DISPLACEMENT) - || !sSpellMgr->GetSpellInfo(SPELL_HUNTER_INSANITY) - || !sSpellMgr->GetSpellInfo(SPELL_SHAMAN_EXHAUSTION) - || !sSpellMgr->GetSpellInfo(SPELL_SHAMAN_SATED)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_MAGE_TEMPORAL_DISPLACEMENT, + SPELL_HUNTER_INSANITY, + SPELL_SHAMAN_EXHAUSTION, + SPELL_SHAMAN_SATED + }); } void RemoveInvalidTargets(std::list& targets) @@ -1499,9 +1461,7 @@ class spell_mage_water_elemental_freeze : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_FINGERS_OF_FROST)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_FINGERS_OF_FROST }); } void CountTargets(std::list& targetList) @@ -1558,9 +1518,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_ARCANE_MISSILES_AURASTATE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MAGE_ARCANE_MISSILES_AURASTATE }); } void HandleProc(AuraEffect const* /*aurEff*/, ProcEventInfo& /*eventInfo*/) @@ -1609,16 +1567,13 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_ARCANE_MISSILES)) - return false; - - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_ARCANE_MISSILES_DAMAGE)) - return false; - - if (!sSpellMgr->GetSpellInfo(SPELL_MAGE_ARCANE_BLAST)) - return false; - - return true; + return ValidateSpellInfo( + { + SPELL_MAGE_ARCANE_MISSILES, + SPELL_MAGE_ARCANE_MISSILES_DAMAGE, + SPELL_MAGE_ARCANE_BLAST + }); + } bool CheckProc(ProcEventInfo& eventInfo) @@ -1677,7 +1632,7 @@ public: void AfterRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) { if (Unit* caster = GetCaster()) - caster->CastSpell(caster, SPELL_MAGE_EARLY_FROST_VISUAL , true, NULL, aurEff); + caster->CastSpell(caster, SPELL_MAGE_EARLY_FROST_VISUAL , true, nullptr, aurEff); } void Register() override diff --git a/src/server/scripts/Spells/spell_paladin.cpp b/src/server/scripts/Spells/spell_paladin.cpp index 5914059b60c..566ce800683 100644 --- a/src/server/scripts/Spells/spell_paladin.cpp +++ b/src/server/scripts/Spells/spell_paladin.cpp @@ -21,12 +21,13 @@ * Scriptnames of files in this file should be prefixed with "spell_pal_". */ -#include "Player.h" #include "ScriptMgr.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "SpellHistory.h" #include "Group.h" +#include "Player.h" +#include "SpellAuraEffects.h" +#include "SpellScript.h" +#include "SpellHistory.h" +#include "SpellMgr.h" enum PaladinSpells { @@ -141,7 +142,7 @@ class spell_pal_ardent_defender : public SpellScriptLoader : float(defenseSkillValue) / float(reqDefForMaxHeal); int32 healAmount = int32(victim->CountPctFromMaxHealth(uint32(healPct * pctFromDefense))); - victim->CastCustomSpell(victim, PAL_SPELL_ARDENT_DEFENDER_HEAL, &healAmount, NULL, NULL, true, NULL, aurEff); + victim->CastCustomSpell(victim, PAL_SPELL_ARDENT_DEFENDER_HEAL, &healAmount, nullptr, nullptr, true, nullptr, aurEff); victim->GetSpellHistory()->AddCooldown(PAL_SPELL_ARDENT_DEFENDER_HEAL, 0, std::chrono::minutes(2)); } else if (remainingHealth < int32(allowedHealth)) @@ -180,9 +181,7 @@ class spell_pal_aura_mastery : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_AURA_MASTERY_IMMUNE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_AURA_MASTERY_IMMUNE }); } void HandleEffectApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -220,9 +219,7 @@ class spell_pal_aura_mastery_immune : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_CONCENTRACTION_AURA)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_CONCENTRACTION_AURA }); } bool CheckAreaTarget(Unit* target) @@ -254,10 +251,7 @@ class spell_pal_avenging_wrath : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_SANCTIFIED_WRATH) - || !sSpellMgr->GetSpellInfo(SPELL_PALADIN_SANCTIFIED_WRATH_TALENT_R1)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_SANCTIFIED_WRATH, SPELL_PALADIN_SANCTIFIED_WRATH_TALENT_R1 }); } void HandleApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -266,7 +260,7 @@ class spell_pal_avenging_wrath : public SpellScriptLoader if (AuraEffect const* aurEff = target->GetAuraEffectOfRankedSpell(SPELL_PALADIN_SANCTIFIED_WRATH_TALENT_R1, EFFECT_2)) { int32 basepoints = aurEff->GetAmount(); - target->CastCustomSpell(target, SPELL_PALADIN_SANCTIFIED_WRATH, &basepoints, &basepoints, NULL, true, NULL, aurEff); + target->CastCustomSpell(target, SPELL_PALADIN_SANCTIFIED_WRATH, &basepoints, &basepoints, nullptr, true, nullptr, aurEff); } } @@ -300,9 +294,13 @@ class spell_pal_blessing_of_faith : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_BLESSING_OF_LOWER_CITY_DRUID) || !sSpellMgr->GetSpellInfo(SPELL_PALADIN_BLESSING_OF_LOWER_CITY_PALADIN) || !sSpellMgr->GetSpellInfo(SPELL_PALADIN_BLESSING_OF_LOWER_CITY_PRIEST) || !sSpellMgr->GetSpellInfo(SPELL_PALADIN_BLESSING_OF_LOWER_CITY_SHAMAN)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PALADIN_BLESSING_OF_LOWER_CITY_DRUID, + SPELL_PALADIN_BLESSING_OF_LOWER_CITY_PALADIN, + SPELL_PALADIN_BLESSING_OF_LOWER_CITY_PRIEST, + SPELL_PALADIN_BLESSING_OF_LOWER_CITY_SHAMAN + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -410,20 +408,11 @@ class spell_pal_divine_storm : public SpellScriptLoader { PrepareSpellScript(spell_pal_divine_storm_SpellScript); - public: - spell_pal_divine_storm_SpellScript() - { - healPct = 0; - } - - private: - uint32 healPct; + uint32 healPct = 0; bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_DIVINE_STORM_DUMMY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_DIVINE_STORM_DUMMY }); } bool Load() override @@ -460,18 +449,9 @@ class spell_pal_divine_storm_dummy : public SpellScriptLoader { PrepareSpellScript(spell_pal_divine_storm_dummy_SpellScript); - public: - spell_pal_divine_storm_dummy_SpellScript() - { - _targetCount = 0; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_DIVINE_STORM_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_DIVINE_STORM_HEAL }); } void CountTargets(std::list& targetList) @@ -485,10 +465,10 @@ class spell_pal_divine_storm_dummy : public SpellScriptLoader return; int32 heal = GetEffectValue() / _targetCount; - GetCaster()->CastCustomSpell(GetHitUnit(), SPELL_PALADIN_DIVINE_STORM_HEAL, &heal, NULL, NULL, true); + GetCaster()->CastCustomSpell(GetHitUnit(), SPELL_PALADIN_DIVINE_STORM_HEAL, &heal, nullptr, nullptr, true); } - private: - uint32 _targetCount; + + uint32 _targetCount = 0; void Register() override { @@ -551,16 +531,14 @@ class spell_pal_eye_for_an_eye : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_EYE_FOR_AN_EYE_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_EYE_FOR_AN_EYE_DAMAGE }); } void HandleEffectProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); int32 damage = CalculatePct(eventInfo.GetDamageInfo()->GetDamage(), aurEff->GetAmount()); - GetTarget()->CastCustomSpell(SPELL_PALADIN_EYE_FOR_AN_EYE_DAMAGE, SPELLVALUE_BASE_POINT0, damage, eventInfo.GetProcTarget(), true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_PALADIN_EYE_FOR_AN_EYE_DAMAGE, SPELLVALUE_BASE_POINT0, damage, eventInfo.GetProcTarget(), true, nullptr, aurEff); } void Register() override @@ -587,9 +565,7 @@ class spell_pal_grand_crusader : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_AVENGERS_SHIELD)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_AVENGERS_SHIELD }); } bool CheckProc(ProcEventInfo& /*eventInfo*/) @@ -825,15 +801,13 @@ class spell_pal_item_healing_discount : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_ITEM_HEALING_TRANCE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_ITEM_HEALING_TRANCE }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_PALADIN_ITEM_HEALING_TRANCE, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_PALADIN_ITEM_HEALING_TRANCE, true, nullptr, aurEff); } void Register() override @@ -861,9 +835,7 @@ class spell_pal_judgement : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_JUDGEMENT_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_JUDGEMENT_DAMAGE }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -909,10 +881,7 @@ class spell_pal_lay_on_hands : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_FORBEARANCE) || - !sSpellMgr->GetSpellInfo(SPELL_PALADIN_IMMUNE_SHIELD_MARKER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_FORBEARANCE, SPELL_PALADIN_IMMUNE_SHIELD_MARKER }); } SpellCastResult CheckCast() @@ -964,11 +933,7 @@ class spell_pal_light_s_beacon : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_BEACON_OF_LIGHT) - || !sSpellMgr->GetSpellInfo(SPELL_PALADIN_BEACON_OF_LIGHT_HEAL) - || !sSpellMgr->GetSpellInfo(SPELL_PALADIN_HOLY_LIGHT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_BEACON_OF_LIGHT, SPELL_PALADIN_BEACON_OF_LIGHT_HEAL, SPELL_PALADIN_HOLY_LIGHT }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1026,9 +991,7 @@ class spell_pal_righteous_defense : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_RIGHTEOUS_DEFENSE_TAUNT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_RIGHTEOUS_DEFENSE_TAUNT }); } SpellCastResult CheckCast() @@ -1174,10 +1137,7 @@ class spell_pal_templar_s_verdict : public SpellScriptLoader bool Validate (SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_DIVINE_PURPOSE_PROC)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_PALADIN_DIVINE_PURPOSE_PROC }); } bool Load() override @@ -1241,9 +1201,7 @@ class spell_pal_seal_of_righteousness : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PALADIN_SEAL_OF_RIGHTEOUSNESS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PALADIN_SEAL_OF_RIGHTEOUSNESS }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1259,7 +1217,7 @@ class spell_pal_seal_of_righteousness : public SpellScriptLoader int32 holy = GetTarget()->SpellBaseDamageBonusDone(SPELL_SCHOOL_MASK_HOLY); holy += eventInfo.GetProcTarget()->SpellBaseDamageBonusTaken(SPELL_SCHOOL_MASK_HOLY); int32 bp = int32((ap * 0.022f + 0.044f * holy) * GetTarget()->GetAttackTime(BASE_ATTACK) / 1000); - GetTarget()->CastCustomSpell(SPELL_PALADIN_SEAL_OF_RIGHTEOUSNESS, SPELLVALUE_BASE_POINT0, bp, eventInfo.GetProcTarget(), true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_PALADIN_SEAL_OF_RIGHTEOUSNESS, SPELLVALUE_BASE_POINT0, bp, eventInfo.GetProcTarget(), true, nullptr, aurEff); } void Register() override @@ -1337,12 +1295,11 @@ class spell_pal_hand_of_light : public SpellScriptLoader bool CheckProc(ProcEventInfo& eventInfo) { - if (eventInfo.GetProcSpell()->GetSpellInfo()->Id == SPELL_PALADIN_TEMPLARS_VERDICT || - eventInfo.GetProcSpell()->GetSpellInfo()->Id == SPELL_PALADIN_CRUSADER_STRIKE || - eventInfo.GetProcSpell()->GetSpellInfo()->Id == SPELL_PALADIN_DIVINE_STORM) - return true; - - return false; + SpellInfo const* spellInfo = eventInfo.GetSpellInfo(); + return spellInfo && + (spellInfo->Id == SPELL_PALADIN_TEMPLARS_VERDICT || + spellInfo->Id == SPELL_PALADIN_CRUSADER_STRIKE || + spellInfo->Id == SPELL_PALADIN_DIVINE_STORM); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1353,7 +1310,7 @@ class spell_pal_hand_of_light : public SpellScriptLoader if (Unit* target = eventInfo.GetProcTarget()) { uint32 damageAmount = CalculatePct(eventInfo.GetDamageInfo()->GetDamage(), aurEff->GetAmount()); - caster->CastCustomSpell(SPELL_PALADIN_HAND_OF_LIGHT, SPELLVALUE_BASE_POINT0, damageAmount, target, true, NULL, aurEff); + caster->CastCustomSpell(SPELL_PALADIN_HAND_OF_LIGHT, SPELLVALUE_BASE_POINT0, damageAmount, target, true, nullptr, aurEff); } } } diff --git a/src/server/scripts/Spells/spell_pet.cpp b/src/server/scripts/Spells/spell_pet.cpp index a7b515fd791..a08d7c4422c 100644 --- a/src/server/scripts/Spells/spell_pet.cpp +++ b/src/server/scripts/Spells/spell_pet.cpp @@ -22,11 +22,13 @@ */ #include "ScriptMgr.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" -#include "Unit.h" -#include "Player.h" +#include "ObjectMgr.h" #include "Pet.h" +#include "Player.h" +#include "SpellAuraEffects.h" +#include "SpellMgr.h" +#include "SpellScript.h" +#include "Unit.h" enum HunterPetCalculate { @@ -892,13 +894,6 @@ public: { PrepareAuraScript(spell_hun_pet_scaling_01_AuraScript); - public: - spell_hun_pet_scaling_01_AuraScript() - { - _tempHealth = 0; - } - - private: void CalculateStaminaAmount(AuraEffect const* /* aurEff */, int32& amount, bool& /*canBeRecalculated*/) { if (Unit* pet = GetUnitOwner()) @@ -1006,8 +1001,7 @@ public: DoEffectCalcAmount += AuraEffectCalcAmountFn(spell_hun_pet_scaling_01_AuraScript::CalculateDamageDoneAmount, EFFECT_2, SPELL_AURA_MOD_DAMAGE_DONE); } - private: - uint32 _tempHealth; + uint32 _tempHealth = 0; }; AuraScript* GetAuraScript() const override @@ -1542,7 +1536,7 @@ public: float mod = 0.7f; // Ravenous Dead - AuraEffect const* aurEff = NULL; + AuraEffect const* aurEff = nullptr; // Check just if owner has Ravenous Dead since it's effect is not an aura aurEff = owner->GetAuraEffect(SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE, SPELLFAMILY_DEATHKNIGHT, 3010, 0); if (aurEff) diff --git a/src/server/scripts/Spells/spell_priest.cpp b/src/server/scripts/Spells/spell_priest.cpp index 0a5b3277d5d..7be2cf0edb3 100644 --- a/src/server/scripts/Spells/spell_priest.cpp +++ b/src/server/scripts/Spells/spell_priest.cpp @@ -21,11 +21,12 @@ * Scriptnames of files in this file should be prefixed with "spell_pri_". */ -#include "Player.h" #include "ScriptMgr.h" -#include "SpellScript.h" -#include "SpellAuraEffects.h" #include "GridNotifiers.h" +#include "Player.h" +#include "SpellAuraEffects.h" +#include "SpellMgr.h" +#include "SpellScript.h" enum PriestSpells { @@ -123,10 +124,7 @@ class spell_pri_body_and_soul : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_CURE_DISEASE) || - !sSpellMgr->GetSpellInfo(SPELL_PRIEST_BODY_AND_SOUL_DISPEL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_CURE_DISEASE, SPELL_PRIEST_BODY_AND_SOUL_DISPEL }); } void HandleEffectSpeedProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -136,7 +134,7 @@ class spell_pri_body_and_soul : public SpellScriptLoader if (!(eventInfo.GetDamageInfo()->GetSpellInfo()->SpellFamilyFlags[0] & 0x1 || eventInfo.GetDamageInfo()->GetSpellInfo()->SpellFamilyFlags[2] & 0x80000)) return; - GetTarget()->CastCustomSpell(SPELL_PRIEST_BODY_AND_SOUL_SPEED, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), eventInfo.GetProcTarget(), true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_PRIEST_BODY_AND_SOUL_SPEED, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), eventInfo.GetProcTarget(), true, nullptr, aurEff); } void HandleEffectDispelProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -147,7 +145,7 @@ class spell_pri_body_and_soul : public SpellScriptLoader return; if (roll_chance_i(aurEff->GetAmount())) - GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_PRIEST_BODY_AND_SOUL_DISPEL, true, NULL, aurEff); + GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_PRIEST_BODY_AND_SOUL_DISPEL, true, nullptr, aurEff); } void Register() override @@ -175,9 +173,7 @@ class spell_pri_circle_of_healing : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_GLYPH_OF_CIRCLE_OF_HEALING)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_GLYPH_OF_CIRCLE_OF_HEALING }); } void FilterTargets(std::list& targets) @@ -217,13 +213,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_ABSOLUTION)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_GLYPH_OF_DISPEL_MAGIC_HEAL)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_GLYPH_OF_DISPEL_MAGIC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_ABSOLUTION, SPELL_PRIEST_GLYPH_OF_DISPEL_MAGIC_HEAL, SPELL_PRIEST_GLYPH_OF_DISPEL_MAGIC }); } SpellCastResult CheckCast() @@ -276,9 +266,7 @@ class spell_pri_divine_aegis : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_DIVINE_AEGIS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_DIVINE_AEGIS }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -298,7 +286,7 @@ class spell_pri_divine_aegis : public SpellScriptLoader absorb = std::min(absorb, eventInfo.GetProcTarget()->getLevel() * 125); - GetTarget()->CastCustomSpell(SPELL_PRIEST_DIVINE_AEGIS, SPELLVALUE_BASE_POINT0, absorb, eventInfo.GetProcTarget(), true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_PRIEST_DIVINE_AEGIS, SPELLVALUE_BASE_POINT0, absorb, eventInfo.GetProcTarget(), true, nullptr, aurEff); } void Register() override @@ -361,9 +349,7 @@ class spell_pri_glyph_of_prayer_of_healing : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_GLYPH_OF_PRAYER_OF_HEALING_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_GLYPH_OF_PRAYER_OF_HEALING_HEAL }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -372,7 +358,7 @@ class spell_pri_glyph_of_prayer_of_healing : public SpellScriptLoader 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); + GetTarget()->CastCustomSpell(SPELL_PRIEST_GLYPH_OF_PRAYER_OF_HEALING_HEAL, SPELLVALUE_BASE_POINT0, heal, eventInfo.GetProcTarget(), true, nullptr, aurEff); } void Register() override @@ -434,15 +420,13 @@ class spell_pri_item_greater_heal_refund : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_ITEM_EFFICIENCY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_ITEM_EFFICIENCY }); } void OnProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_PRIEST_ITEM_EFFICIENCY, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_PRIEST_ITEM_EFFICIENCY, true, nullptr, aurEff); } void Register() override @@ -478,9 +462,7 @@ class spell_pri_guardian_spirit : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_GUARDIAN_SPIRIT_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_GUARDIAN_SPIRIT_HEAL }); } bool Load() override @@ -504,7 +486,7 @@ class spell_pri_guardian_spirit : public SpellScriptLoader int32 healAmount = int32(target->CountPctFromMaxHealth(healPct)); // remove the aura now, we don't want 40% healing bonus Remove(AURA_REMOVE_BY_ENEMY_SPELL); - target->CastCustomSpell(target, SPELL_PRIEST_GUARDIAN_SPIRIT_HEAL, &healAmount, NULL, NULL, true); + target->CastCustomSpell(target, SPELL_PRIEST_GUARDIAN_SPIRIT_HEAL, &healAmount, nullptr, nullptr, true); absorbAmount = dmgInfo.GetDamage(); } @@ -569,9 +551,7 @@ class spell_pri_leap_of_faith_effect_trigger : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_LEAP_OF_FAITH_EFFECT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_LEAP_OF_FAITH_EFFECT }); } void HandleEffectDummy(SpellEffIndex /*effIndex*/) @@ -581,7 +561,7 @@ class spell_pri_leap_of_faith_effect_trigger : public SpellScriptLoader SpellCastTargets targets; targets.SetDst(destPos); targets.SetUnitTarget(GetCaster()); - GetHitUnit()->CastSpell(targets, sSpellMgr->GetSpellInfo(GetEffectValue()), NULL); + GetHitUnit()->CastSpell(targets, sSpellMgr->GetSpellInfo(GetEffectValue()), nullptr); } void Register() override @@ -638,18 +618,9 @@ class spell_pri_mana_leech : public SpellScriptLoader { PrepareAuraScript(spell_pri_mana_leech_AuraScript); - public: - spell_pri_mana_leech_AuraScript() - { - _procTarget = nullptr; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_MANA_LEECH_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_MANA_LEECH_PROC }); } bool CheckProc(ProcEventInfo& /*eventInfo*/) @@ -661,7 +632,7 @@ class spell_pri_mana_leech : public SpellScriptLoader void HandleProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(_procTarget, SPELL_PRIEST_MANA_LEECH_PROC, true, NULL, aurEff); + GetTarget()->CastSpell(_procTarget, SPELL_PRIEST_MANA_LEECH_PROC, true, nullptr, aurEff); } void Register() override @@ -670,8 +641,7 @@ class spell_pri_mana_leech : public SpellScriptLoader OnEffectProc += AuraEffectProcFn(spell_pri_mana_leech_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_DUMMY); } - private: - Unit* _procTarget; + Unit* _procTarget = nullptr; }; AuraScript* GetAuraScript() const override @@ -868,11 +838,11 @@ class spell_pri_power_word_shield : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_REFLECTIVE_SHIELD_TRIGGERED)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_REFLECTIVE_SHIELD_R1)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PRIEST_REFLECTIVE_SHIELD_TRIGGERED, + SPELL_PRIEST_REFLECTIVE_SHIELD_R1 + }); } void CalculateAmount(AuraEffect const* aurEff, int32& amount, bool& canBeRecalculated) @@ -917,7 +887,7 @@ class spell_pri_power_word_shield : public SpellScriptLoader if (AuraEffect const* talentAurEff = target->GetAuraEffectOfRankedSpell(SPELL_PRIEST_REFLECTIVE_SHIELD_R1, EFFECT_0)) { int32 bp = CalculatePct(absorbAmount, talentAurEff->GetAmount()); - target->CastCustomSpell(dmgInfo.GetAttacker(), SPELL_PRIEST_REFLECTIVE_SHIELD_TRIGGERED, &bp, NULL, NULL, true, NULL, aurEff); + target->CastCustomSpell(dmgInfo.GetAttacker(), SPELL_PRIEST_REFLECTIVE_SHIELD_TRIGGERED, &bp, nullptr, nullptr, true, nullptr, aurEff); } } @@ -981,9 +951,7 @@ class spell_pri_renew : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_DIVINE_TOUCH)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_DIVINE_TOUCH }); } bool Load() override @@ -1001,7 +969,7 @@ class spell_pri_renew : public SpellScriptLoader uint32 heal = caster->SpellHealingBonusDone(GetTarget(), GetSpellInfo(), aurEff->GetAmount(), DOT); heal = GetTarget()->SpellHealingBonusTaken(caster, GetSpellInfo(), heal, DOT); int32 basepoints0 = CalculatePct(int32(heal) * aurEff->GetTotalTicks(), empoweredRenewAurEff->GetAmount()); - caster->CastCustomSpell(GetTarget(), SPELL_PRIEST_DIVINE_TOUCH, &basepoints0, NULL, NULL, true, NULL, aurEff); + caster->CastCustomSpell(GetTarget(), SPELL_PRIEST_DIVINE_TOUCH, &basepoints0, nullptr, nullptr, true, nullptr, aurEff); } } } @@ -1063,10 +1031,11 @@ class spell_pri_shadowform : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_SHADOWFORM_VISUAL_WITHOUT_GLYPH) || - !sSpellMgr->GetSpellInfo(SPELL_PRIEST_SHADOWFORM_VISUAL_WITH_GLYPH)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_PRIEST_SHADOWFORM_VISUAL_WITHOUT_GLYPH, + SPELL_PRIEST_SHADOWFORM_VISUAL_WITH_GLYPH + }); } void HandleEffectApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1105,9 +1074,7 @@ class spell_pri_vampiric_embrace : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_VAMPIRIC_EMBRACE_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_VAMPIRIC_EMBRACE_HEAL }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1122,7 +1089,7 @@ class spell_pri_vampiric_embrace : public SpellScriptLoader int32 self = int32(CalculatePct(eventInfo.GetDamageInfo()->GetDamage(), aurEff->GetAmount())); int32 team = int32(CalculatePct(eventInfo.GetDamageInfo()->GetDamage(), aurEff->GetAmount() / 2)); - GetTarget()->CastCustomSpell((Unit*)NULL, SPELL_PRIEST_VAMPIRIC_EMBRACE_HEAL, &team, &self, NULL, true, NULL, aurEff); + GetTarget()->CastCustomSpell((Unit*)nullptr, SPELL_PRIEST_VAMPIRIC_EMBRACE_HEAL, &team, &self, nullptr, true, nullptr, aurEff); } void Register() override @@ -1177,10 +1144,7 @@ class spell_pri_vampiric_touch : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_PRIEST_VAMPIRIC_TOUCH_DISPEL) || - !sSpellMgr->GetSpellInfo(SPELL_GEN_REPLENISHMENT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_PRIEST_VAMPIRIC_TOUCH_DISPEL, SPELL_GEN_REPLENISHMENT }); } void HandleDispel(DispelInfo* /*dispelInfo*/) @@ -1191,7 +1155,7 @@ class spell_pri_vampiric_touch : public SpellScriptLoader { int32 damage = aurEff->GetAmount() * 8; // backfire damage - caster->CastCustomSpell(target, SPELL_PRIEST_VAMPIRIC_TOUCH_DISPEL, &damage, NULL, NULL, true, NULL, aurEff); + caster->CastCustomSpell(target, SPELL_PRIEST_VAMPIRIC_TOUCH_DISPEL, &damage, nullptr, nullptr, true, nullptr, aurEff); } } @@ -1202,7 +1166,7 @@ class spell_pri_vampiric_touch : public SpellScriptLoader void HandleEffectProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { - eventInfo.GetProcTarget()->CastSpell((Unit*)NULL, SPELL_GEN_REPLENISHMENT, true, NULL, aurEff); + eventInfo.GetProcTarget()->CastSpell((Unit*)nullptr, SPELL_GEN_REPLENISHMENT, true, nullptr, aurEff); } void Register() override @@ -1243,7 +1207,7 @@ class spell_pri_echo_of_light : public SpellScriptLoader uint32 healAmount = CalculatePct(eventInfo.GetHealInfo()->GetHeal(), aurEff->GetAmount()); uint8 tickNumber = sSpellMgr->GetSpellInfo(SPELL_PRIEST_ECHO_OF_LIGHT)->GetMaxTicks(); if (healAmount && tickNumber) - caster->CastCustomSpell(SPELL_PRIEST_ECHO_OF_LIGHT, SPELLVALUE_BASE_POINT0, healAmount / tickNumber, target, true, NULL, aurEff); + caster->CastCustomSpell(SPELL_PRIEST_ECHO_OF_LIGHT, SPELLVALUE_BASE_POINT0, healAmount / tickNumber, target, true, nullptr, aurEff); } } } diff --git a/src/server/scripts/Spells/spell_quest.cpp b/src/server/scripts/Spells/spell_quest.cpp index 3445fac226d..19f209c3341 100644 --- a/src/server/scripts/Spells/spell_quest.cpp +++ b/src/server/scripts/Spells/spell_quest.cpp @@ -21,15 +21,15 @@ * Scriptnames of files in this file should be prefixed with "spell_q#questID_". */ +#include "ScriptMgr.h" #include "CellImpl.h" +#include "CreatureAIImpl.h" #include "CreatureTextMgr.h" -#include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "Player.h" -#include "ScriptMgr.h" #include "ScriptedCreature.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" +#include "SpellScript.h" #include "Vehicle.h" class spell_generic_quest_update_entry_SpellScript : public SpellScript @@ -104,9 +104,7 @@ class spell_q2203_thaumaturgy_channel : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_THAUMATURGY_CHANNEL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_THAUMATURGY_CHANNEL }); } void HandleEffectPeriodic(AuraEffect const* /*aurEff*/) @@ -152,16 +150,14 @@ class spell_q5206_test_fetid_skull : public SpellScriptLoader bool Validate(SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_CREATE_RESONATING_SKULL) || !sSpellMgr->GetSpellInfo(SPELL_CREATE_BONE_DUST)) - return false; - return true; + return ValidateSpellInfo({ SPELL_CREATE_RESONATING_SKULL, SPELL_CREATE_BONE_DUST }); } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); uint32 spellId = roll_chance_i(50) ? SPELL_CREATE_RESONATING_SKULL : SPELL_CREATE_BONE_DUST; - caster->CastSpell(caster, spellId, true, NULL); + caster->CastSpell(caster, spellId, true, nullptr); } void Register() override @@ -316,9 +312,7 @@ class spell_q11396_11399_scourging_crystal_controller : public SpellScriptLoader bool Validate(SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FORCE_SHIELD_ARCANE_PURPLE_X3) || !sSpellMgr->GetSpellInfo(SPELL_SCOURGING_CRYSTAL_CONTROLLER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FORCE_SHIELD_ARCANE_PURPLE_X3, SPELL_SCOURGING_CRYSTAL_CONTROLLER }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -354,9 +348,7 @@ class spell_q11396_11399_scourging_crystal_controller_dummy : public SpellScript bool Validate(SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FORCE_SHIELD_ARCANE_PURPLE_X3)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FORCE_SHIELD_ARCANE_PURPLE_X3 }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -417,9 +409,7 @@ class spell_q11587_arcane_prisoner_rescue : public SpellScriptLoader bool Validate(SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_ARCANE_PRISONER_MALE) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_ARCANE_PRISONER_FEMALE) || !sSpellMgr->GetSpellInfo(SPELL_ARCANE_PRISONER_KILL_CREDIT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_ARCANE_PRISONER_MALE, SPELL_SUMMON_ARCANE_PRISONER_FEMALE, SPELL_ARCANE_PRISONER_KILL_CREDIT }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -480,9 +470,15 @@ class spell_q11730_ultrasonic_screwdriver : public SpellScriptLoader bool Validate(SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_SCAVENGEBOT_004A8) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_SENTRYBOT_57K) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_DEFENDOTANK_66D) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_SCAVENGEBOT_005B6) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_55D_COLLECTATRON) || !sSpellMgr->GetSpellInfo(SPELL_ROBOT_KILL_CREDIT)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SUMMON_SCAVENGEBOT_004A8, + SPELL_SUMMON_SENTRYBOT_57K, + SPELL_SUMMON_DEFENDOTANK_66D, + SPELL_SUMMON_SCAVENGEBOT_005B6, + SPELL_SUMMON_55D_COLLECTATRON, + SPELL_ROBOT_KILL_CREDIT + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -592,9 +588,13 @@ class spell_q12634_despawn_fruit_tosser : public SpellScriptLoader bool Validate(SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BANANAS_FALL_TO_GROUND) || !sSpellMgr->GetSpellInfo(SPELL_ORANGE_FALLS_TO_GROUND) || !sSpellMgr->GetSpellInfo(SPELL_PAPAYA_FALLS_TO_GROUND) || !sSpellMgr->GetSpellInfo(SPELL_SUMMON_ADVENTUROUS_DWARF)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_BANANAS_FALL_TO_GROUND, + SPELL_ORANGE_FALLS_TO_GROUND, + SPELL_PAPAYA_FALLS_TO_GROUND, + SPELL_SUMMON_ADVENTUROUS_DWARF + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -608,7 +608,7 @@ class spell_q12634_despawn_fruit_tosser : public SpellScriptLoader // sometimes, if you're lucky, you get a dwarf if (roll_chance_i(5)) spellId = SPELL_SUMMON_ADVENTUROUS_DWARF; - GetCaster()->CastSpell(GetCaster(), spellId, true, NULL); + GetCaster()->CastSpell(GetCaster(), spellId, true, nullptr); } void Register() override @@ -642,7 +642,7 @@ class spell_q12683_take_sputum_sample : public SpellScriptLoader if (caster->HasAuraEffect(reqAuraId, 0)) { uint32 spellId = GetSpellInfo()->Effects[EFFECT_0].CalcValue(); - caster->CastSpell(caster, spellId, true, NULL); + caster->CastSpell(caster, spellId, true, nullptr); } } @@ -744,9 +744,7 @@ class spell_q12937_relief_for_the_fallen : public SpellScriptLoader bool Validate(SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TRIGGER_AID_OF_THE_EARTHEN)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TRIGGER_AID_OF_THE_EARTHEN }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -754,7 +752,7 @@ class spell_q12937_relief_for_the_fallen : public SpellScriptLoader Player* caster = GetCaster()->ToPlayer(); if (Creature* target = GetHitCreature()) { - caster->CastSpell(caster, SPELL_TRIGGER_AID_OF_THE_EARTHEN, true, NULL); + caster->CastSpell(caster, SPELL_TRIGGER_AID_OF_THE_EARTHEN, true, nullptr); caster->KilledMonsterCredit(NPC_FALLEN_EARTHEN_DEFENDER); target->DespawnOrUnsummon(); } @@ -790,9 +788,7 @@ class spell_q10041_q10040_who_are_they : public SpellScriptLoader bool Validate(SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MALE_DISGUISE) || !sSpellMgr->GetSpellInfo(SPELL_FEMALE_DISGUISE) || !sSpellMgr->GetSpellInfo(SPELL_GENERIC_DISGUISE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_MALE_DISGUISE, SPELL_FEMALE_DISGUISE, SPELL_GENERIC_DISGUISE }); } void HandleScript(SpellEffIndex effIndex) @@ -1072,9 +1068,7 @@ class spell_q14112_14145_chum_the_water: public SpellScriptLoader bool Validate(SpellInfo const* /*spellEntry*/) override { - if (!sSpellMgr->GetSpellInfo(SUMMON_ANGRY_KVALDIR) || !sSpellMgr->GetSpellInfo(SUMMON_NORTH_SEA_MAKO) || !sSpellMgr->GetSpellInfo(SUMMON_NORTH_SEA_THRESHER) || !sSpellMgr->GetSpellInfo(SUMMON_NORTH_SEA_BLUE_SHARK)) - return false; - return true; + return ValidateSpellInfo({ SUMMON_ANGRY_KVALDIR, SUMMON_NORTH_SEA_MAKO, SUMMON_NORTH_SEA_THRESHER, SUMMON_NORTH_SEA_BLUE_SHARK }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -1684,16 +1678,14 @@ class spell_q12527_zuldrak_rat : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_GORGED_LURKING_BASILISK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_GORGED_LURKING_BASILISK }); } void HandleScriptEffect(SpellEffIndex /* effIndex */) { if (GetHitAura() && GetHitAura()->GetStackAmount() >= GetSpellInfo()->StackAmount) { - GetHitUnit()->CastSpell((Unit*) NULL, SPELL_SUMMON_GORGED_LURKING_BASILISK, true); + GetHitUnit()->CastSpell((Unit*) nullptr, SPELL_SUMMON_GORGED_LURKING_BASILISK, true); if (Creature* basilisk = GetHitUnit()->ToCreature()) basilisk->DespawnOrUnsummon(); } @@ -1756,9 +1748,7 @@ class spell_q12730_quenching_mist : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FLICKERING_FLAMES)) - return false; - return true; + return ValidateSpellInfo({ SPELL_FLICKERING_FLAMES }); } void HandleEffectPeriodic(AuraEffect const* /*aurEff*/) @@ -1799,10 +1789,7 @@ class spell_q13291_q13292_q13239_q13261_frostbrood_skytalon_grab_decoy : public bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RIDE)) - return false; - - return true; + return ValidateSpellInfo({ SPELL_RIDE }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1902,10 +1889,11 @@ class spell_q13011_bear_flank_master : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BEAR_FLANK_MASTER) || - !sSpellMgr->GetSpellInfo(SPELL_CREATE_BEAR_FLANK)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_CREATE_BEAR_FLANK, + SPELL_BEAR_FLANK_FAIL + }); } bool Load() override @@ -1951,9 +1939,7 @@ class spell_q13086_cannons_target : public SpellScriptLoader bool Validate(SpellInfo const* spellInfo) override { - if (!sSpellMgr->GetSpellInfo(spellInfo->Effects[EFFECT_0].CalcValue())) - return false; - return true; + return ValidateSpellInfo({ static_cast(spellInfo->Effects[EFFECT_0].CalcValue()) }); } void HandleEffectDummy(SpellEffIndex /*effIndex*/) @@ -2088,14 +2074,15 @@ class spell_q12690_burst_at_the_seams : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_BURST_AT_THE_SEAMS) - || !sSpellMgr->GetSpellInfo(SPELL_BURST_AT_THE_SEAMS_DMG) - || !sSpellMgr->GetSpellInfo(SPELL_BURST_AT_THE_SEAMS_DMG_2) - || !sSpellMgr->GetSpellInfo(SPELL_BURST_AT_THE_SEAMS_BONE) - || !sSpellMgr->GetSpellInfo(SPELL_BURST_AT_THE_SEAMS_MEAT) - || !sSpellMgr->GetSpellInfo(SPELL_BURST_AT_THE_SEAMS_BMEAT)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_BURST_AT_THE_SEAMS, + SPELL_BURST_AT_THE_SEAMS_DMG, + SPELL_BURST_AT_THE_SEAMS_DMG_2, + SPELL_BURST_AT_THE_SEAMS_BONE, + SPELL_BURST_AT_THE_SEAMS_MEAT, + SPELL_BURST_AT_THE_SEAMS_BMEAT + }); } bool Load() override @@ -2164,9 +2151,7 @@ class spell_q12308_escape_from_silverbrook : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_WORGEN)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_WORGEN }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2242,12 +2227,13 @@ class spell_q12641_death_comes_from_on_high : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_FORGE_CREDIT) || - !sSpellMgr->GetSpellInfo(SPELL_TOWN_HALL_CREDIT) || - !sSpellMgr->GetSpellInfo(SPELL_SCARLET_HOLD_CREDIT) || - !sSpellMgr->GetSpellInfo(SPELL_CHAPEL_CREDIT)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_FORGE_CREDIT, + SPELL_TOWN_HALL_CREDIT, + SPELL_SCARLET_HOLD_CREDIT, + SPELL_CHAPEL_CREDIT + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2272,7 +2258,7 @@ class spell_q12641_death_comes_from_on_high : public SpellScriptLoader return; } - GetCaster()->CastSpell((Unit*)NULL, spellId, true); + GetCaster()->CastSpell((Unit*)nullptr, spellId, true); } void Register() override @@ -2338,7 +2324,7 @@ class spell_q12619_emblazon_runeblade : public SpellScriptLoader { PreventDefaultAction(); if (Unit* caster = GetCaster()) - caster->CastSpell(caster, GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell, true, NULL, aurEff); + caster->CastSpell(caster, GetSpellInfo()->Effects[aurEff->GetEffIndex()].TriggerSpell, true, nullptr, aurEff); } void Register() override @@ -2397,9 +2383,7 @@ class spell_q12919_gymers_grab : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RIDE_GYMER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RIDE_GYMER }); } void HandleScript(SpellEffIndex /*effIndex*/) @@ -2476,9 +2460,7 @@ class spell_q13400_illidan_kill_master : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ILLIDAN_KILL_CREDIT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ILLIDAN_KILL_CREDIT }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -2518,9 +2500,7 @@ class spell_q14100_q14111_make_player_destroy_totems : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_TOTEM_OF_THE_EARTHEN_RING)) - return false; - return true; + return ValidateSpellInfo({ SPELL_TOTEM_OF_THE_EARTHEN_RING }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -2559,11 +2539,7 @@ class spell_q10929_fumping : SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_SAND_GNOME)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_SUMMON_BONE_SLICER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SUMMON_SAND_GNOME, SPELL_SUMMON_BONE_SLICER }); } void HandleEffectRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -2605,9 +2581,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_RENEWED_LIFE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_RENEWED_LIFE }); } void HandleDummyEffect() diff --git a/src/server/scripts/Spells/spell_rogue.cpp b/src/server/scripts/Spells/spell_rogue.cpp index 25edcf0eccc..4e8166d8518 100644 --- a/src/server/scripts/Spells/spell_rogue.cpp +++ b/src/server/scripts/Spells/spell_rogue.cpp @@ -21,12 +21,17 @@ * Scriptnames of files in this file should be prefixed with "spell_rog_". */ -#include "Player.h" #include "ScriptMgr.h" -#include "SpellScript.h" +#include "Containers.h" +#include "DBCStores.h" +#include "Item.h" +#include "Log.h" +#include "ObjectAccessor.h" +#include "Player.h" #include "SpellAuraEffects.h" #include "SpellHistory.h" -#include "Containers.h" +#include "SpellMgr.h" +#include "SpellScript.h" enum RogueSpells { @@ -70,18 +75,9 @@ class spell_rog_blade_flurry : public SpellScriptLoader { PrepareAuraScript(spell_rog_blade_flurry_AuraScript); - public: - spell_rog_blade_flurry_AuraScript() - { - _procTarget = nullptr; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_BLADE_FLURRY_EXTRA_ATTACK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROGUE_BLADE_FLURRY_EXTRA_ATTACK }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -93,11 +89,7 @@ class spell_rog_blade_flurry : public SpellScriptLoader void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); - - TC_LOG_ERROR("misc", "damage: %u procSpell: %u", - eventInfo.GetDamageInfo()->GetDamage(), eventInfo.GetDamageInfo()->GetSpellInfo() ? eventInfo.GetDamageInfo()->GetSpellInfo()->Id : 0); - - GetTarget()->CastCustomSpell(SPELL_ROGUE_BLADE_FLURRY_EXTRA_ATTACK, SPELLVALUE_BASE_POINT0, eventInfo.GetDamageInfo()->GetDamage(), _procTarget, true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_ROGUE_BLADE_FLURRY_EXTRA_ATTACK, SPELLVALUE_BASE_POINT0, eventInfo.GetDamageInfo()->GetDamage(), _procTarget, true, nullptr, aurEff); } void Register() override @@ -109,8 +101,7 @@ class spell_rog_blade_flurry : public SpellScriptLoader OnEffectProc += AuraEffectProcFn(spell_rog_blade_flurry_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_MOD_MELEE_HASTE); } - private: - Unit* _procTarget; + Unit* _procTarget = nullptr; }; AuraScript* GetAuraScript() const override @@ -129,20 +120,11 @@ class spell_rog_cheat_death : public SpellScriptLoader { PrepareAuraScript(spell_rog_cheat_death_AuraScript); - public: - spell_rog_cheat_death_AuraScript() - { - absorbChance = 0; - } - - private: - uint32 absorbChance; + uint32 absorbChance = 0; bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_CHEAT_DEATH_COOLDOWN)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROGUE_CHEAT_DEATH_COOLDOWN }); } bool Load() override @@ -201,15 +183,13 @@ class spell_rog_crippling_poison : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_CRIPPLING_POISON)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROGUE_CRIPPLING_POISON }); } void OnProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); - GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_ROGUE_CRIPPLING_POISON, true, NULL, aurEff); + GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_ROGUE_CRIPPLING_POISON, true, nullptr, aurEff); } void Register() override @@ -263,13 +243,6 @@ class spell_rog_deadly_poison : public SpellScriptLoader { PrepareSpellScript(spell_rog_deadly_poison_SpellScript); - public: - spell_rog_deadly_poison_SpellScript() - { - _stackAmount = 0; - } - - private: bool Load() override { // at this point CastItem must already be initialized @@ -347,7 +320,7 @@ class spell_rog_deadly_poison : public SpellScriptLoader AfterHit += SpellHitFn(spell_rog_deadly_poison_SpellScript::HandleAfterHit); } - uint8 _stackAmount; + uint8 _stackAmount = 0; }; SpellScript* GetSpellScript() const override @@ -357,11 +330,12 @@ class spell_rog_deadly_poison : public SpellScriptLoader }; // 51690 - Killing Spree -#define KillingSpreeScriptName "spell_rog_killing_spree" class spell_rog_killing_spree : public SpellScriptLoader { public: - spell_rog_killing_spree() : SpellScriptLoader(KillingSpreeScriptName) { } + static char constexpr const ScriptName[] = "spell_rog_killing_spree"; + + spell_rog_killing_spree() : SpellScriptLoader(ScriptName) { } class spell_rog_killing_spree_SpellScript : public SpellScript { @@ -376,10 +350,8 @@ class spell_rog_killing_spree : public SpellScriptLoader void HandleDummy(SpellEffIndex /*effIndex*/) { if (Aura* aura = GetCaster()->GetAura(SPELL_ROGUE_KILLING_SPREE)) - { - if (spell_rog_killing_spree_AuraScript* script = dynamic_cast(aura->GetScriptByName(KillingSpreeScriptName))) + if (spell_rog_killing_spree_AuraScript* script = aura->GetScript(ScriptName)) script->AddTarget(GetHitUnit()); - } } void Register() override @@ -400,11 +372,12 @@ class spell_rog_killing_spree : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_KILLING_SPREE_TELEPORT) - || !sSpellMgr->GetSpellInfo(SPELL_ROGUE_KILLING_SPREE_WEAPON_DMG) - || !sSpellMgr->GetSpellInfo(SPELL_ROGUE_KILLING_SPREE_DMG_BUFF)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_ROGUE_KILLING_SPREE_TELEPORT, + SPELL_ROGUE_KILLING_SPREE_WEAPON_DMG, + SPELL_ROGUE_KILLING_SPREE_DMG_BUFF + }); } void HandleApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -455,6 +428,7 @@ class spell_rog_killing_spree : public SpellScriptLoader return new spell_rog_killing_spree_AuraScript(); } }; +char constexpr const spell_rog_killing_spree::ScriptName[]; // 31666 - Master of Subtlety class spell_rog_master_of_subtlety : public SpellScriptLoader @@ -468,9 +442,7 @@ class spell_rog_master_of_subtlety : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_MASTER_OF_SUBTLETY_DAMAGE_PERCENT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROGUE_MASTER_OF_SUBTLETY_DAMAGE_PERCENT }); } void HandleEffectPeriodic(AuraEffect const* /*aurEff*/) @@ -556,9 +528,7 @@ class spell_rog_overkill : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_OVERKILL_POWER_REGEN)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROGUE_OVERKILL_POWER_REGEN }); } void HandleEffectPeriodic(AuraEffect const* /*aurEff*/) @@ -598,9 +568,7 @@ class spell_rog_preparation : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_GLYPH_OF_PREPARATION)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROGUE_GLYPH_OF_PREPARATION }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -644,9 +612,7 @@ class spell_rog_prey_on_the_weak : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_PREY_ON_THE_WEAK)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROGUE_PREY_ON_THE_WEAK }); } void HandleEffectPeriodic(AuraEffect const* /*aurEff*/) @@ -727,11 +693,12 @@ class spell_rog_recuperate : public SpellScriptLoader }; // -1943 - Rupture -#define RuptureScriptName "spell_rog_rupture" class spell_rog_rupture : public SpellScriptLoader { public: - spell_rog_rupture() : SpellScriptLoader(RuptureScriptName) { } + static char constexpr const ScriptName[] = "spell_rog_rupture"; + + spell_rog_rupture() : SpellScriptLoader(ScriptName) { } class spell_rog_rupture_AuraScript : public AuraScript { @@ -789,6 +756,7 @@ class spell_rog_rupture : public SpellScriptLoader return new spell_rog_rupture_AuraScript(); } }; +char constexpr const spell_rog_rupture::ScriptName[]; // 63975 - Glyph of Backstab (triggered - serverside) class spell_rog_glyph_of_backstab_triggered : public SpellScriptLoader @@ -810,7 +778,7 @@ class spell_rog_glyph_of_backstab_triggered : public SpellScriptLoader // search our Rupture aura on target if (AuraEffect* aurEff = GetHitUnit()->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_ROGUE, 0x00100000, 0, 0, caster->GetGUID())) { - RuptureAuraScript* ruptureAuraScript = dynamic_cast(aurEff->GetBase()->GetScriptByName(RuptureScriptName)); + RuptureAuraScript* ruptureAuraScript = aurEff->GetBase()->GetScript(spell_rog_rupture::ScriptName); if (!ruptureAuraScript) return; @@ -863,9 +831,7 @@ class spell_rog_shiv : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_SHIV_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROGUE_SHIV_TRIGGERED }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -899,14 +865,15 @@ class spell_rog_stealth : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_MASTER_OF_SUBTLETY_PASSIVE) || - !sSpellMgr->GetSpellInfo(SPELL_ROGUE_MASTER_OF_SUBTLETY_DAMAGE_PERCENT) || - !sSpellMgr->GetSpellInfo(SPELL_ROGUE_MASTER_OF_SUBTLETY_PERIODIC) || - !sSpellMgr->GetSpellInfo(SPELL_ROGUE_OVERKILL_TALENT) || - !sSpellMgr->GetSpellInfo(SPELL_ROGUE_OVERKILL_POWER_REGEN) || - !sSpellMgr->GetSpellInfo(SPELL_ROGUE_OVERKILL_PERIODIC)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_ROGUE_MASTER_OF_SUBTLETY_PASSIVE, + SPELL_ROGUE_MASTER_OF_SUBTLETY_DAMAGE_PERCENT, + SPELL_ROGUE_MASTER_OF_SUBTLETY_PERIODIC, + SPELL_ROGUE_OVERKILL_TALENT, + SPELL_ROGUE_OVERKILL_POWER_REGEN, + SPELL_ROGUE_OVERKILL_PERIODIC + }); } void HandleEffectApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -917,7 +884,7 @@ class spell_rog_stealth : public SpellScriptLoader if (AuraEffect const* aurEff = target->GetAuraEffect(SPELL_ROGUE_MASTER_OF_SUBTLETY_PASSIVE, EFFECT_0)) { int32 basepoints0 = aurEff->GetAmount(); - target->CastCustomSpell(target, SPELL_ROGUE_MASTER_OF_SUBTLETY_DAMAGE_PERCENT, &basepoints0, NULL, NULL, true); + target->CastCustomSpell(target, SPELL_ROGUE_MASTER_OF_SUBTLETY_DAMAGE_PERCENT, &basepoints0, nullptr, nullptr, true); } // Overkill @@ -961,20 +928,9 @@ class spell_rog_tricks_of_the_trade : public SpellScriptLoader { PrepareAuraScript(spell_rog_tricks_of_the_trade_AuraScript); - public: - spell_rog_tricks_of_the_trade_AuraScript() - { - _redirectTarget = nullptr; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_TRICKS_OF_THE_TRADE_DMG_BOOST)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_TRICKS_OF_THE_TRADE_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROGUE_TRICKS_OF_THE_TRADE_DMG_BOOST, SPELL_ROGUE_TRICKS_OF_THE_TRADE_PROC }); } void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1006,8 +962,7 @@ class spell_rog_tricks_of_the_trade : public SpellScriptLoader OnEffectProc += AuraEffectProcFn(spell_rog_tricks_of_the_trade_AuraScript::HandleProc, EFFECT_1, SPELL_AURA_DUMMY); } - private: - Unit* _redirectTarget; + Unit* _redirectTarget = nullptr; }; AuraScript* GetAuraScript() const override @@ -1089,9 +1044,7 @@ class spell_rog_honor_among_thieves : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_ROGUE_HONOR_AMONG_THIEVES_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_ROGUE_HONOR_AMONG_THIEVES_TRIGGERED }); } bool CheckProc(ProcEventInfo& /*eventInfo*/) diff --git a/src/server/scripts/Spells/spell_shaman.cpp b/src/server/scripts/Spells/spell_shaman.cpp index 582ddad0c03..72fc100c9be 100644 --- a/src/server/scripts/Spells/spell_shaman.cpp +++ b/src/server/scripts/Spells/spell_shaman.cpp @@ -21,13 +21,13 @@ * Scriptnames of files in this file should be prefixed with "spell_sha_". */ -#include "Player.h" #include "ScriptMgr.h" +#include "Player.h" #include "GridNotifiers.h" -#include "Unit.h" -#include "SpellHistory.h" -#include "SpellScript.h" #include "SpellAuraEffects.h" +#include "SpellHistory.h" +#include "SpellMgr.h" +#include "SpellScript.h" enum ShamanSpells { @@ -94,9 +94,7 @@ class spell_sha_ancestral_awakening : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_TIDAL_WAVES)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_TIDAL_WAVES }); } void HandleEffectProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -104,7 +102,7 @@ class spell_sha_ancestral_awakening : public SpellScriptLoader PreventDefaultAction(); int32 heal = int32(CalculatePct(eventInfo.GetHealInfo()->GetHeal(), aurEff->GetAmount())); - GetTarget()->CastCustomSpell(SPELL_SHAMAN_ANCESTRAL_AWAKENING, SPELLVALUE_BASE_POINT0, heal, (Unit*)NULL, true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_SHAMAN_ANCESTRAL_AWAKENING, SPELLVALUE_BASE_POINT0, heal, (Unit*)nullptr, true, nullptr, aurEff); } void Register() override @@ -132,9 +130,7 @@ class spell_sha_ancestral_awakening_proc : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_ANCESTRAL_AWAKENING_PROC)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_ANCESTRAL_AWAKENING_PROC }); } void FilterTargets(std::list& targets) @@ -180,11 +176,12 @@ class spell_sha_bloodlust : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_SATED) - || !sSpellMgr->GetSpellInfo(SPELL_HUNTER_INSANITY) - || !sSpellMgr->GetSpellInfo(SPELL_MAGE_TEMPORAL_DISPLACEMENT)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SHAMAN_SATED, + SPELL_HUNTER_INSANITY, + SPELL_MAGE_TEMPORAL_DISPLACEMENT + }); } void RemoveInvalidTargets(std::list& targets) @@ -285,10 +282,7 @@ class spell_sha_earth_shield : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_EARTH_SHIELD_HEAL) || - !sSpellMgr->GetSpellInfo(SPELL_SHAMAN_GLYPH_OF_EARTH_SHIELD)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_EARTH_SHIELD_HEAL, SPELL_SHAMAN_GLYPH_OF_EARTH_SHIELD }); } void CalculateAmount(AuraEffect const* /*aurEff*/, int32& amount, bool & /*canBeRecalculated*/) @@ -326,7 +320,7 @@ class spell_sha_earth_shield : public SpellScriptLoader { PreventDefaultAction(); - GetTarget()->CastCustomSpell(SPELL_SHAMAN_EARTH_SHIELD_HEAL, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), GetTarget(), true, NULL, aurEff, GetCasterGUID()); + GetTarget()->CastCustomSpell(SPELL_SHAMAN_EARTH_SHIELD_HEAL, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), GetTarget(), true, nullptr, aurEff, GetCasterGUID()); /// @hack: due to currenct proc system implementation if (Player* player = GetTarget()->ToPlayer()) @@ -360,10 +354,7 @@ class spell_sha_earthbind_totem : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_TOTEM_EARTHBIND_TOTEM) || - !sSpellMgr->GetSpellInfo(SPELL_SHAMAN_TOTEM_EARTHEN_POWER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_TOTEM_EARTHBIND_TOTEM, SPELL_SHAMAN_TOTEM_EARTHEN_POWER }); } void HandleEffectPeriodic(AuraEffect const* /*aurEff*/) @@ -373,7 +364,7 @@ class spell_sha_earthbind_totem : public SpellScriptLoader if (Player* owner = GetCaster()->GetCharmerOrOwnerPlayerOrPlayerItself()) if (AuraEffect* aur = owner->GetDummyAuraEffect(SPELLFAMILY_SHAMAN, 2289, 0)) if (roll_chance_i(aur->GetBaseAmount())) - GetTarget()->CastSpell((Unit*)NULL, SPELL_SHAMAN_TOTEM_EARTHEN_POWER, true); + GetTarget()->CastSpell((Unit*)nullptr, SPELL_SHAMAN_TOTEM_EARTHEN_POWER, true); } void Apply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -460,9 +451,7 @@ class spell_sha_feedback : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_ELEMENTAL_MASTERY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_ELEMENTAL_MASTERY }); } void HandleEffectProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) @@ -533,10 +522,7 @@ class spell_sha_flame_shock : public SpellScriptLoader bool Validate(SpellInfo const* /*spell*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_LAVA_FLOWS_R1) || - !sSpellMgr->GetSpellInfo(SPELL_SHAMAN_LAVA_FLOWS_TRIGGERED_R1)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_LAVA_FLOWS_R1, SPELL_SHAMAN_LAVA_FLOWS_TRIGGERED_R1 }); } void HandleDispel(DispelInfo* /*dispelInfo*/) @@ -551,7 +537,7 @@ class spell_sha_flame_shock : public SpellScriptLoader return; int32 basepoints = aurEff->GetAmount(); - caster->CastCustomSpell(caster, SPELL_SHAMAN_LAVA_FLOWS_TRIGGERED_R1, &basepoints, NULL, NULL, true); + caster->CastCustomSpell(caster, SPELL_SHAMAN_LAVA_FLOWS_TRIGGERED_R1, &basepoints, nullptr, nullptr, true); } } } @@ -580,9 +566,7 @@ class spell_sha_focused_insight : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_FOCUSED_INSIGHT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_FOCUSED_INSIGHT }); } void HandleEffectProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) @@ -591,7 +575,7 @@ class spell_sha_focused_insight : public SpellScriptLoader int32 basePoints0 = aurEff->GetAmount(); int32 basePoints1 = aurEff->GetSpellInfo()->Effects[EFFECT_1].CalcValue(); - GetTarget()->CastCustomSpell(GetTarget(), SPELL_SHAMAN_FOCUSED_INSIGHT, &basePoints0, &basePoints1, &basePoints1, true, NULL, aurEff); + GetTarget()->CastCustomSpell(GetTarget(), SPELL_SHAMAN_FOCUSED_INSIGHT, &basePoints0, &basePoints1, &basePoints1, true, nullptr, aurEff); } void Register() override @@ -618,9 +602,7 @@ class spell_sha_glyph_of_healing_wave : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_GLYPH_OF_HEALING_WAVE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_GLYPH_OF_HEALING_WAVE }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -634,7 +616,7 @@ class spell_sha_glyph_of_healing_wave : public SpellScriptLoader PreventDefaultAction(); int32 heal = CalculatePct(int32(eventInfo.GetHealInfo()->GetHeal()), aurEff->GetAmount()); - GetTarget()->CastCustomSpell(SPELL_SHAMAN_GLYPH_OF_HEALING_WAVE, SPELLVALUE_BASE_POINT0, heal, (Unit*)NULL, true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_SHAMAN_GLYPH_OF_HEALING_WAVE, SPELLVALUE_BASE_POINT0, heal, (Unit*)nullptr, true, nullptr, aurEff); } void Register() override @@ -663,7 +645,7 @@ class spell_sha_healing_stream_totem : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - return sSpellMgr->GetSpellInfo(SPELL_SHAMAN_TOTEM_HEALING_STREAM_HEAL) != nullptr; + return ValidateSpellInfo({ SPELL_SHAMAN_TOTEM_HEALING_STREAM_HEAL }); } void HandleDummy(SpellEffIndex /* effIndex */) @@ -713,11 +695,12 @@ class spell_sha_heroism : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_EXHAUSTION) - || !sSpellMgr->GetSpellInfo(SPELL_HUNTER_INSANITY) - || !sSpellMgr->GetSpellInfo(SPELL_MAGE_TEMPORAL_DISPLACEMENT)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_SHAMAN_EXHAUSTION, + SPELL_HUNTER_INSANITY, + SPELL_MAGE_TEMPORAL_DISPLACEMENT + }); } void RemoveInvalidTargets(std::list& targets) @@ -760,15 +743,13 @@ class spell_sha_item_lightning_shield : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_ITEM_LIGHTNING_SHIELD)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_ITEM_LIGHTNING_SHIELD }); } void OnProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); - GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_SHAMAN_ITEM_LIGHTNING_SHIELD, true, NULL, aurEff); + GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_SHAMAN_ITEM_LIGHTNING_SHIELD, true, nullptr, aurEff); } void Register() override @@ -795,15 +776,13 @@ class spell_sha_item_lightning_shield_trigger : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_ITEM_MANA_SURGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_ITEM_MANA_SURGE }); } void OnProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_SHAMAN_ITEM_LIGHTNING_SHIELD_DAMAGE, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_SHAMAN_ITEM_LIGHTNING_SHIELD_DAMAGE, true, nullptr, aurEff); } void Register() override @@ -830,9 +809,7 @@ class spell_sha_item_mana_surge : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_ITEM_LIGHTNING_SHIELD_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_ITEM_LIGHTNING_SHIELD_DAMAGE }); } void OnProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -841,7 +818,7 @@ class spell_sha_item_mana_surge : public SpellScriptLoader int32 mana = eventInfo.GetDamageInfo()->GetSpellInfo()->CalcPowerCost(GetTarget(), SpellSchoolMask(eventInfo.GetDamageInfo()->GetSchoolMask())); mana = int32(CalculatePct(mana, 35)); - GetTarget()->CastCustomSpell(SPELL_SHAMAN_ITEM_MANA_SURGE, SPELLVALUE_BASE_POINT0, mana, GetTarget(), true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_SHAMAN_ITEM_MANA_SURGE, SPELLVALUE_BASE_POINT0, mana, GetTarget(), true, nullptr, aurEff); } void Register() override @@ -868,9 +845,7 @@ class spell_sha_item_t10_elemental_2p_bonus : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_ELEMENTAL_MASTERY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_ELEMENTAL_MASTERY }); } void HandleEffectProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) @@ -948,9 +923,7 @@ class spell_sha_lava_surge : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_LAVA_SURGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_LAVA_SURGE }); } void HandleEffectProc(AuraEffect const* /*aurEff*/, ProcEventInfo& /*eventInfo*/) @@ -982,9 +955,7 @@ class spell_sha_lava_surge_proc : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_LAVA_BURST)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_LAVA_BURST }); } bool Load() override @@ -1053,9 +1024,7 @@ class spell_sha_nature_guardian : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_NATURE_GUARDIAN)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_NATURE_GUARDIAN }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -1073,7 +1042,7 @@ class spell_sha_nature_guardian : public SpellScriptLoader PreventDefaultAction(); int32 basePoints0 = GetTarget()->CountPctFromMaxHealth(aurEff->GetAmount()); - GetTarget()->CastCustomSpell(GetTarget(), SPELL_SHAMAN_NATURE_GUARDIAN, &basePoints0, NULL, NULL, true); + GetTarget()->CastCustomSpell(GetTarget(), SPELL_SHAMAN_NATURE_GUARDIAN, &basePoints0, nullptr, nullptr, true); if (eventInfo.GetProcTarget() && eventInfo.GetProcTarget()->IsAlive()) eventInfo.GetProcTarget()->getThreatManager().modifyThreatPercent(GetTarget(), -10); @@ -1107,9 +1076,7 @@ class spell_sha_rolling_thunder : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_LIGHTNING_SHIELD)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_LIGHTNING_SHIELD }); } void HandleEffectProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) @@ -1145,9 +1112,7 @@ class spell_sha_telluric_currents : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_TELLURIC_CURRENTS)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_TELLURIC_CURRENTS }); } void HandleEffectProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -1155,7 +1120,7 @@ class spell_sha_telluric_currents : public SpellScriptLoader PreventDefaultAction(); int32 basePoints0 = CalculatePct(eventInfo.GetDamageInfo()->GetDamage(), aurEff->GetAmount()); - GetTarget()->CastCustomSpell(GetTarget(), SPELL_SHAMAN_TELLURIC_CURRENTS, &basePoints0, NULL, NULL, true); + GetTarget()->CastCustomSpell(GetTarget(), SPELL_SHAMAN_TELLURIC_CURRENTS, &basePoints0, nullptr, nullptr, true); } void Register() override @@ -1211,9 +1176,7 @@ class spell_sha_tidal_waves : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_TIDAL_WAVES)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_TIDAL_WAVES }); } void HandleEffectProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) @@ -1222,7 +1185,7 @@ class spell_sha_tidal_waves : public SpellScriptLoader int32 basePoints0 = -aurEff->GetAmount(); int32 basePoints1 = aurEff->GetAmount(); - GetTarget()->CastCustomSpell(GetTarget(), SPELL_SHAMAN_TIDAL_WAVES, &basePoints0, &basePoints1, NULL, true, NULL, aurEff); + GetTarget()->CastCustomSpell(GetTarget(), SPELL_SHAMAN_TIDAL_WAVES, &basePoints0, &basePoints1, nullptr, true, nullptr, aurEff); } void Register() override @@ -1249,9 +1212,7 @@ public: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_SHAMAN_TOTEMIC_MASTERY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_SHAMAN_TOTEMIC_MASTERY }); } void HandleDummy(AuraEffect const* /*aurEff*/) diff --git a/src/server/scripts/Spells/spell_warlock.cpp b/src/server/scripts/Spells/spell_warlock.cpp index bc26f2e37d5..fe69cbdb96e 100644 --- a/src/server/scripts/Spells/spell_warlock.cpp +++ b/src/server/scripts/Spells/spell_warlock.cpp @@ -21,11 +21,16 @@ * Scriptnames of files in this file should be prefixed with "spell_warl_". */ -#include "Player.h" #include "ScriptMgr.h" -#include "SpellScript.h" +#include "Creature.h" +#include "GameObject.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "Random.h" #include "SpellAuraEffects.h" #include "SpellAuras.h" +#include "SpellMgr.h" +#include "SpellScript.h" enum WarlockSpells { @@ -101,9 +106,7 @@ class spell_warl_aftermath : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_AFTERMATH_STUN)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_AFTERMATH_STUN }); } void HandleProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) @@ -113,7 +116,7 @@ class spell_warl_aftermath : public SpellScriptLoader PreventDefaultAction(); if (eventInfo.GetProcTarget() && roll_chance_i(aurEff->GetAmount())) - GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_WARLOCK_AFTERMATH_STUN, true, NULL, aurEff); + GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_WARLOCK_AFTERMATH_STUN, true, nullptr, aurEff); } } @@ -196,9 +199,7 @@ class spell_warl_conflagrate : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_IMMOLATE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_IMMOLATE }); } void HandleHit(SpellEffIndex /*effIndex*/) @@ -231,9 +232,7 @@ class spell_warl_create_healthstone : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_CREATE_HEALTHSTONE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_CREATE_HEALTHSTONE }); } bool Load() override @@ -271,9 +270,7 @@ class spell_warl_bane_of_doom : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_BANE_OF_DOOM_EFFECT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_BANE_OF_DOOM_EFFECT }); } bool Load() override @@ -291,7 +288,7 @@ class spell_warl_bane_of_doom : public SpellScriptLoader return; if (GetCaster()->ToPlayer()->isHonorOrXPTarget(GetTarget())) - GetCaster()->CastSpell(GetTarget(), SPELL_WARLOCK_BANE_OF_DOOM_EFFECT, true, NULL, aurEff); + GetCaster()->CastSpell(GetTarget(), SPELL_WARLOCK_BANE_OF_DOOM_EFFECT, true, nullptr, aurEff); } void Register() override @@ -406,17 +403,14 @@ class spell_warl_demon_soul : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_DEMON_SOUL_IMP)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_DEMON_SOUL_FELHUNTER)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_DEMON_SOUL_FELGUARD)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_DEMON_SOUL_SUCCUBUS)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_DEMON_SOUL_VOIDWALKER)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_WARLOCK_DEMON_SOUL_IMP, + SPELL_WARLOCK_DEMON_SOUL_FELHUNTER, + SPELL_WARLOCK_DEMON_SOUL_FELGUARD, + SPELL_WARLOCK_DEMON_SOUL_SUCCUBUS, + SPELL_WARLOCK_DEMON_SOUL_VOIDWALKER + }); } void OnHitTarget(SpellEffIndex /*effIndex*/) @@ -476,9 +470,14 @@ class spell_warl_demonic_empowerment : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_DEMONIC_EMPOWERMENT_SUCCUBUS) || !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_DEMONIC_EMPOWERMENT_VOIDWALKER) || !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_DEMONIC_EMPOWERMENT_FELGUARD) || !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_DEMONIC_EMPOWERMENT_FELHUNTER) || !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_DEMONIC_EMPOWERMENT_IMP)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_WARLOCK_DEMONIC_EMPOWERMENT_SUCCUBUS, + SPELL_WARLOCK_DEMONIC_EMPOWERMENT_VOIDWALKER, + SPELL_WARLOCK_DEMONIC_EMPOWERMENT_FELGUARD, + SPELL_WARLOCK_DEMONIC_EMPOWERMENT_FELHUNTER, + SPELL_WARLOCK_DEMONIC_EMPOWERMENT_IMP + }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -498,7 +497,7 @@ class spell_warl_demonic_empowerment : public SpellScriptLoader { 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); + targetCreature->CastCustomSpell(targetCreature, SPELL_WARLOCK_DEMONIC_EMPOWERMENT_VOIDWALKER, &hp, nullptr, nullptr, true); break; } case CREATURE_FAMILY_FELGUARD: @@ -616,9 +615,7 @@ class spell_warl_fel_synergy : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_FEL_SYNERGY_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_FEL_SYNERGY_HEAL }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -631,7 +628,7 @@ class spell_warl_fel_synergy : public SpellScriptLoader PreventDefaultAction(); int32 heal = CalculatePct(int32(eventInfo.GetDamageInfo()->GetDamage()), aurEff->GetAmount()); - GetTarget()->CastCustomSpell(SPELL_WARLOCK_FEL_SYNERGY_HEAL, SPELLVALUE_BASE_POINT0, heal, (Unit*)NULL, true, NULL, aurEff); // TARGET_UNIT_PET + GetTarget()->CastCustomSpell(SPELL_WARLOCK_FEL_SYNERGY_HEAL, SPELLVALUE_BASE_POINT0, heal, (Unit*)nullptr, true, nullptr, aurEff); // TARGET_UNIT_PET } void Register() override @@ -659,15 +656,13 @@ class spell_warl_glyph_of_shadowflame : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_GLYPH_OF_SHADOWFLAME)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_GLYPH_OF_SHADOWFLAME }); } void OnProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); - GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_WARLOCK_GLYPH_OF_SHADOWFLAME, true, NULL, aurEff); + GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_WARLOCK_GLYPH_OF_SHADOWFLAME, true, nullptr, aurEff); } void Register() override @@ -712,9 +707,7 @@ class spell_warl_haunt : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_HAUNT_HEAL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_HAUNT_HEAL }); } void HandleRemove(AuraEffect const* aurEff, AuraEffectHandleModes /*mode*/) @@ -722,7 +715,7 @@ class spell_warl_haunt : public SpellScriptLoader if (Unit* caster = GetCaster()) { int32 amount = aurEff->GetAmount(); - GetTarget()->CastCustomSpell(caster, SPELL_WARLOCK_HAUNT_HEAL, &amount, NULL, NULL, true, NULL, aurEff, GetCasterGUID()); + GetTarget()->CastCustomSpell(caster, SPELL_WARLOCK_HAUNT_HEAL, &amount, nullptr, nullptr, true, nullptr, aurEff, GetCasterGUID()); } } @@ -783,7 +776,7 @@ class spell_warl_health_funnel : public SpellScriptLoader uint32 damage = caster->CountPctFromMaxHealth(aurEff->GetBaseAmount()); if (Player* modOwner = caster->GetSpellModOwner()) - modOwner->ApplySpellMod(GetId(), damage); + modOwner->ApplySpellMod(GetId(), SPELLMOD_COST, damage); SpellNonMeleeDamage damageInfo(caster, caster, GetSpellInfo()->Id, GetSpellInfo()->SchoolMask); damageInfo.damage = damage; @@ -845,17 +838,14 @@ class spell_warl_improved_soul_fire : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_IMPROVED_SOUL_FIRE_PCT) || - !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_IMPROVED_SOUL_FIRE_STATE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_IMPROVED_SOUL_FIRE_PCT, SPELL_WARLOCK_IMPROVED_SOUL_FIRE_STATE }); } void OnProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastCustomSpell(SPELL_WARLOCK_IMPROVED_SOUL_FIRE_PCT, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), GetTarget(), true, NULL, aurEff); - GetTarget()->CastSpell(GetTarget(), SPELL_WARLOCK_IMPROVED_SOUL_FIRE_STATE, true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_WARLOCK_IMPROVED_SOUL_FIRE_PCT, SPELLVALUE_BASE_POINT0, aurEff->GetAmount(), GetTarget(), true, nullptr, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_WARLOCK_IMPROVED_SOUL_FIRE_STATE, true, nullptr, aurEff); } void Register() override @@ -886,12 +876,9 @@ class spell_warl_life_tap : public SpellScriptLoader return GetCaster()->GetTypeId() == TYPEID_PLAYER; } - bool Validate(SpellInfo const* /*spellInfo*/) override + bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_LIFE_TAP_ENERGIZE) || - !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_LIFE_TAP_ENERGIZE_2)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_LIFE_TAP_ENERGIZE, SPELL_WARLOCK_LIFE_TAP_ENERGIZE_2 }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -909,14 +896,14 @@ class spell_warl_life_tap : public SpellScriptLoader if (AuraEffect const* aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_WARLOCK, WARLOCK_ICON_ID_IMPROVED_LIFE_TAP, 0)) AddPct(mana, aurEff->GetAmount()); - caster->CastCustomSpell(target, SPELL_WARLOCK_LIFE_TAP_ENERGIZE, &mana, NULL, NULL, false); + caster->CastCustomSpell(target, SPELL_WARLOCK_LIFE_TAP_ENERGIZE, &mana, nullptr, nullptr, false); // Mana Feed if (AuraEffect const* aurEff = caster->GetAuraEffect(SPELL_AURA_ADD_FLAT_MODIFIER, SPELLFAMILY_WARLOCK, WARLOCK_ICON_ID_MANA_FEED, 0)) { int32 manaFeedVal = aurEff->GetAmount(); ApplyPct(manaFeedVal, mana); - caster->CastCustomSpell(caster, SPELL_WARLOCK_LIFE_TAP_ENERGIZE_2, &manaFeedVal, NULL, NULL, true, NULL); + caster->CastCustomSpell(caster, SPELL_WARLOCK_LIFE_TAP_ENERGIZE_2, &manaFeedVal, nullptr, nullptr, true, nullptr); } } } @@ -954,11 +941,12 @@ class spell_warl_nether_ward_overrride : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_NETHER_TALENT) || - !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_NETHER_WARD) || - !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_SHADOW_WARD)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_WARLOCK_NETHER_TALENT, + SPELL_WARLOCK_NETHER_WARD, + SPELL_WARLOCK_SHADOW_WARD + }); } void CalculateAmount(AuraEffect const* /*aurEff*/, int32& amount, bool& /*canBeRecalculated*/) @@ -993,10 +981,7 @@ class spell_warl_seduction : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_GLYPH_OF_SUCCUBUS) || - !sSpellMgr->GetSpellInfo(SPELL_PRIEST_SHADOW_WORD_DEATH)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_GLYPH_OF_SUCCUBUS, SPELL_PRIEST_SHADOW_WORD_DEATH }); } void HandleScriptEffect(SpellEffIndex /*effIndex*/) @@ -1067,15 +1052,13 @@ class spell_warl_shadow_trance_proc : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_SHADOW_TRANCE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_SHADOW_TRANCE }); } void OnProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { PreventDefaultAction(); - GetTarget()->CastSpell(GetTarget(), SPELL_WARLOCK_SHADOW_TRANCE, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), SPELL_WARLOCK_SHADOW_TRANCE, true, nullptr, aurEff); } void Register() override @@ -1138,14 +1121,12 @@ class spell_warl_soul_leech : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_GEN_REPLENISHMENT)) - return false; - return true; + return ValidateSpellInfo({ SPELL_GEN_REPLENISHMENT }); } void OnProc(AuraEffect const* aurEff, ProcEventInfo& /*eventInfo*/) { - GetTarget()->CastSpell((Unit*)NULL, SPELL_GEN_REPLENISHMENT, true, NULL, aurEff); + GetTarget()->CastSpell((Unit*)nullptr, SPELL_GEN_REPLENISHMENT, true, nullptr, aurEff); } void Register() override @@ -1172,11 +1153,12 @@ class spell_warl_soul_swap : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_GLYPH_OF_SOUL_SWAP) || - !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_SOUL_SWAP_CD_MARKER) || - !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_SOUL_SWAP_OVERRIDE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_WARLOCK_GLYPH_OF_SOUL_SWAP, + SPELL_WARLOCK_SOUL_SWAP_CD_MARKER, + SPELL_WARLOCK_SOUL_SWAP_OVERRIDE + }); } void HandleHit(SpellEffIndex /*effIndex*/) @@ -1201,7 +1183,9 @@ class spell_warl_soul_swap : public SpellScriptLoader class spell_warl_soul_swap_override : public SpellScriptLoader { public: - spell_warl_soul_swap_override() : SpellScriptLoader("spell_warl_soul_swap_override") { } + static char constexpr const ScriptName[] = "spell_warl_soul_swap_override"; + + spell_warl_soul_swap_override() : SpellScriptLoader(ScriptName) { } class spell_warl_soul_swap_override_AuraScript : public AuraScript { @@ -1209,7 +1193,7 @@ class spell_warl_soul_swap_override : public SpellScriptLoader bool Load() override { - _swapCaster = NULL; + _swapCaster = nullptr; return true; } @@ -1232,8 +1216,7 @@ class spell_warl_soul_swap_override : public SpellScriptLoader return new spell_warl_soul_swap_override_AuraScript(); } }; - -typedef spell_warl_soul_swap_override::spell_warl_soul_swap_override_AuraScript SoulSwapOverrideAuraScript; +char constexpr const spell_warl_soul_swap_override::ScriptName[]; //! Soul Swap Copy Spells - 92795 - Simply copies spell IDs. class spell_warl_soul_swap_dot_marker : public SpellScriptLoader @@ -1245,6 +1228,8 @@ class spell_warl_soul_swap_dot_marker : public SpellScriptLoader { PrepareSpellScript(spell_warl_soul_swap_dot_marker_SpellScript); + typedef spell_warl_soul_swap_override::spell_warl_soul_swap_override_AuraScript SoulSwapOverrideAuraScript; + void HandleHit(SpellEffIndex effIndex) { Unit* swapVictim = GetCaster(); @@ -1255,11 +1240,11 @@ class spell_warl_soul_swap_dot_marker : public SpellScriptLoader flag96 classMask = GetSpellInfo()->Effects[effIndex].SpellClassMask; Unit::AuraApplicationMap const& appliedAuras = swapVictim->GetAppliedAuras(); - SoulSwapOverrideAuraScript* swapSpellScript = NULL; + SoulSwapOverrideAuraScript* swapSpellScript = nullptr; if (Aura* swapOverrideAura = warlock->GetAura(SPELL_WARLOCK_SOUL_SWAP_OVERRIDE)) - swapSpellScript = dynamic_cast(swapOverrideAura->GetScriptByName("spell_warl_soul_swap_override")); + swapSpellScript = swapOverrideAura->GetScript(spell_warl_soul_swap_override::ScriptName); - if (swapSpellScript == NULL) + if (swapSpellScript == nullptr) return; for (Unit::AuraApplicationMap::const_iterator itr = appliedAuras.begin(); itr != appliedAuras.end(); ++itr) @@ -1295,20 +1280,23 @@ public: { PrepareSpellScript(spell_warl_soul_swap_exhale_SpellScript); + typedef spell_warl_soul_swap_override::spell_warl_soul_swap_override_AuraScript SoulSwapOverrideAuraScript; + bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_SOUL_SWAP_MOD_COST) || - !sSpellMgr->GetSpellInfo(SPELL_WARLOCK_SOUL_SWAP_OVERRIDE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_WARLOCK_SOUL_SWAP_MOD_COST, + SPELL_WARLOCK_SOUL_SWAP_OVERRIDE + }); } SpellCastResult CheckCast() { Unit* currentTarget = GetExplTargetUnit(); - Unit* swapTarget = NULL; + Unit* swapTarget = nullptr; if (Aura const* swapOverride = GetCaster()->GetAura(SPELL_WARLOCK_SOUL_SWAP_OVERRIDE)) - if (SoulSwapOverrideAuraScript* swapScript = dynamic_cast(swapOverride->GetScriptByName("spell_warl_soul_swap_override"))) + if (SoulSwapOverrideAuraScript* swapScript = swapOverride->GetScript(spell_warl_soul_swap_override::ScriptName)) swapTarget = swapScript->GetOriginalSwapSource(); // Soul Swap Exhale can't be cast on the same target than Soul Swap @@ -1324,10 +1312,10 @@ public: bool hasGlyph = GetCaster()->HasAura(SPELL_WARLOCK_GLYPH_OF_SOUL_SWAP); std::list dotList; - Unit* swapSource = NULL; + Unit* swapSource = nullptr; if (Aura const* swapOverride = GetCaster()->GetAura(SPELL_WARLOCK_SOUL_SWAP_OVERRIDE)) { - SoulSwapOverrideAuraScript* swapScript = dynamic_cast(swapOverride->GetScriptByName("spell_warl_soul_swap_override")); + SoulSwapOverrideAuraScript* swapScript = swapOverride->GetScript(spell_warl_soul_swap_override::ScriptName); if (!swapScript) return; dotList = swapScript->GetDotList(); @@ -1377,9 +1365,7 @@ class spell_warl_soulshatter : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_SOULSHATTER)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_SOULSHATTER }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -1415,9 +1401,7 @@ class spell_warl_unstable_affliction : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARLOCK_UNSTABLE_AFFLICTION_DISPEL)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARLOCK_UNSTABLE_AFFLICTION_DISPEL }); } void HandleDispel(DispelInfo* dispelInfo) @@ -1427,7 +1411,7 @@ class spell_warl_unstable_affliction : public SpellScriptLoader { int32 damage = aurEff->GetAmount() * 9; // backfire damage and silence - caster->CastCustomSpell(dispelInfo->GetDispeller(), SPELL_WARLOCK_UNSTABLE_AFFLICTION_DISPEL, &damage, NULL, NULL, true, NULL, aurEff); + caster->CastCustomSpell(dispelInfo->GetDispeller(), SPELL_WARLOCK_UNSTABLE_AFFLICTION_DISPEL, &damage, nullptr, nullptr, true, nullptr, aurEff); } } diff --git a/src/server/scripts/Spells/spell_warrior.cpp b/src/server/scripts/Spells/spell_warrior.cpp index 226906c426d..de6efd2a9a7 100644 --- a/src/server/scripts/Spells/spell_warrior.cpp +++ b/src/server/scripts/Spells/spell_warrior.cpp @@ -21,11 +21,13 @@ * Scriptnames of files in this file should be prefixed with "spell_warr_". */ -#include "Player.h" #include "ScriptMgr.h" -#include "SpellHistory.h" -#include "SpellScript.h" +#include "Player.h" +#include "Random.h" #include "SpellAuraEffects.h" +#include "SpellHistory.h" +#include "SpellMgr.h" +#include "SpellScript.h" enum WarriorSpells { @@ -48,10 +50,10 @@ enum WarriorSpells SPELL_WARRIOR_RALLYING_CRY = 97463, SPELL_WARRIOR_REND = 94009, SPELL_WARRIOR_RETALIATION_DAMAGE = 22858, - SPELL_WARRIOR_SECOUND_WIND_PROC_RANK_1 = 29834, - SPELL_WARRIOR_SECOUND_WIND_PROC_RANK_2 = 29838, - SPELL_WARRIOR_SECOUND_WIND_TRIGGER_RANK_1 = 29841, - SPELL_WARRIOR_SECOUND_WIND_TRIGGER_RANK_2 = 29842, + SPELL_WARRIOR_SECOND_WIND_PROC_RANK_1 = 29834, + SPELL_WARRIOR_SECOND_WIND_PROC_RANK_2 = 29838, + SPELL_WARRIOR_SECOND_WIND_TRIGGER_RANK_1 = 29841, + SPELL_WARRIOR_SECOND_WIND_TRIGGER_RANK_2 = 29842, SPELL_WARRIOR_SHIELD_SLAM = 23922, SPELL_WARRIOR_SLAM = 50782, SPELL_WARRIOR_SUNDER_ARMOR = 58567, @@ -105,7 +107,7 @@ class spell_warr_bloodthirst : public SpellScriptLoader void HandleDummy(SpellEffIndex /*effIndex*/) { int32 damage = GetEffectValue(); - GetCaster()->CastCustomSpell(GetCaster(), SPELL_WARRIOR_BLOODTHIRST, &damage, NULL, NULL, true, NULL); + GetCaster()->CastCustomSpell(GetCaster(), SPELL_WARRIOR_BLOODTHIRST, &damage, nullptr, nullptr, true, nullptr); } void Register() override @@ -131,10 +133,15 @@ class spell_warr_bloodthirst_heal : public SpellScriptLoader { PrepareSpellScript(spell_warr_bloodthirst_heal_SpellScript); + bool Validate(SpellInfo const* /*spellInfo*/) override + { + return ValidateSpellInfo({ SPELL_WARRIOR_BLOODTHIRST_DAMAGE }); + } + void HandleHeal(SpellEffIndex /*effIndex*/) { - if (SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(SPELL_WARRIOR_BLOODTHIRST_DAMAGE)) - SetHitHeal(GetCaster()->CountPctFromMaxHealth(spellInfo->Effects[EFFECT_1].CalcValue(GetCaster())) / 100); + SpellInfo const* spellInfo = sSpellMgr->AssertSpellInfo(SPELL_WARRIOR_BLOODTHIRST_DAMAGE); + SetHitHeal(GetCaster()->CountPctFromMaxHealth(spellInfo->Effects[EFFECT_1].CalcValue(GetCaster())) / 100); } void Register() override @@ -161,18 +168,19 @@ class spell_warr_charge : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_JUGGERNAUT_CRIT_BONUS_TALENT) || - !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_JUGGERNAUT_CRIT_BONUS_BUFF) || - !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_CHARGE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_WARRIOR_JUGGERNAUT_CRIT_BONUS_TALENT, + SPELL_WARRIOR_JUGGERNAUT_CRIT_BONUS_BUFF, + SPELL_WARRIOR_CHARGE + }); } void HandleDummy(SpellEffIndex /*effIndex*/) { int32 chargeBasePoints0 = GetEffectValue(); Unit* caster = GetCaster(); - caster->CastCustomSpell(caster, SPELL_WARRIOR_CHARGE, &chargeBasePoints0, NULL, NULL, true); + caster->CastCustomSpell(caster, SPELL_WARRIOR_CHARGE, &chargeBasePoints0, nullptr, nullptr, true); // Juggernaut crit bonus if (caster->HasAura(SPELL_WARRIOR_JUGGERNAUT_CRIT_BONUS_TALENT)) @@ -230,12 +238,13 @@ class spell_warr_deep_wounds : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_DEEP_WOUNDS_RANK_1) || - !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_DEEP_WOUNDS_RANK_2) || - !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_DEEP_WOUNDS_RANK_3) || - !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_DEEP_WOUNDS_PERIODIC)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_WARRIOR_DEEP_WOUNDS_RANK_1, + SPELL_WARRIOR_DEEP_WOUNDS_RANK_2, + SPELL_WARRIOR_DEEP_WOUNDS_RANK_3, + SPELL_WARRIOR_DEEP_WOUNDS_PERIODIC + }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -255,7 +264,7 @@ class spell_warr_deep_wounds : public SpellScriptLoader damage /= int32(ticks); - caster->CastCustomSpell(target, SPELL_WARRIOR_DEEP_WOUNDS_PERIODIC, &damage, NULL, NULL, true); + caster->CastCustomSpell(target, SPELL_WARRIOR_DEEP_WOUNDS_PERIODIC, &damage, nullptr, nullptr, true); } } @@ -423,10 +432,7 @@ class spell_warr_lambs_to_the_slaughter : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_MORTAL_STRIKE) || - !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_REND)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARRIOR_MORTAL_STRIKE, SPELL_WARRIOR_REND }); } void OnProc(AuraEffect const* /*aurEff*/, ProcEventInfo& eventInfo) @@ -461,16 +467,14 @@ class spell_warr_last_stand : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_LAST_STAND_TRIGGERED)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARRIOR_LAST_STAND_TRIGGERED }); } void HandleDummy(SpellEffIndex /*effIndex*/) { Unit* caster = GetCaster(); int32 healthModSpellBasePoints0 = int32(caster->CountPctFromMaxHealth(GetEffectValue())); - caster->CastCustomSpell(caster, SPELL_WARRIOR_LAST_STAND_TRIGGERED, &healthModSpellBasePoints0, NULL, NULL, true, NULL); + caster->CastCustomSpell(caster, SPELL_WARRIOR_LAST_STAND_TRIGGERED, &healthModSpellBasePoints0, nullptr, nullptr, true, nullptr); } void Register() override @@ -536,9 +540,7 @@ class spell_warr_rallying_cry : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_RALLYING_CRY)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARRIOR_RALLYING_CRY }); } bool Load() override @@ -550,7 +552,7 @@ class spell_warr_rallying_cry : public SpellScriptLoader { int32 basePoints0 = int32(GetHitUnit()->CountPctFromMaxHealth(GetEffectValue())); - GetCaster()->CastCustomSpell(GetHitUnit(), SPELL_WARRIOR_RALLYING_CRY, &basePoints0, NULL, NULL, true); + GetCaster()->CastCustomSpell(GetHitUnit(), SPELL_WARRIOR_RALLYING_CRY, &basePoints0, nullptr, nullptr, true); } void Register() override @@ -615,9 +617,7 @@ class spell_warr_retaliation : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_RETALIATION_DAMAGE)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARRIOR_RETALIATION_DAMAGE }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -629,7 +629,7 @@ class spell_warr_retaliation : public SpellScriptLoader void HandleEffectProc(AuraEffect const* aurEff, ProcEventInfo& eventInfo) { PreventDefaultAction(); - GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_WARRIOR_RETALIATION_DAMAGE, true, NULL, aurEff); + GetTarget()->CastSpell(eventInfo.GetProcTarget(), SPELL_WARRIOR_RETALIATION_DAMAGE, true, nullptr, aurEff); } void Register() override @@ -688,9 +688,7 @@ class spell_warr_slam : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_SLAM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARRIOR_SLAM }); } void HandleDummy(SpellEffIndex /*effIndex*/) @@ -722,12 +720,13 @@ class spell_warr_second_wind_proc : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_SECOUND_WIND_PROC_RANK_1) || - !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_SECOUND_WIND_PROC_RANK_2) || - !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_SECOUND_WIND_TRIGGER_RANK_1) || - !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_SECOUND_WIND_TRIGGER_RANK_2)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_WARRIOR_SECOND_WIND_PROC_RANK_1, + SPELL_WARRIOR_SECOND_WIND_PROC_RANK_2, + SPELL_WARRIOR_SECOND_WIND_TRIGGER_RANK_1, + SPELL_WARRIOR_SECOND_WIND_TRIGGER_RANK_2 + }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -744,14 +743,14 @@ class spell_warr_second_wind_proc : public SpellScriptLoader PreventDefaultAction(); uint32 spellId = 0; - if (GetSpellInfo()->Id == SPELL_WARRIOR_SECOUND_WIND_PROC_RANK_1) - spellId = SPELL_WARRIOR_SECOUND_WIND_TRIGGER_RANK_1; - else if (GetSpellInfo()->Id == SPELL_WARRIOR_SECOUND_WIND_PROC_RANK_2) - spellId = SPELL_WARRIOR_SECOUND_WIND_TRIGGER_RANK_2; + if (GetSpellInfo()->Id == SPELL_WARRIOR_SECOND_WIND_PROC_RANK_1) + spellId = SPELL_WARRIOR_SECOND_WIND_TRIGGER_RANK_1; + else if (GetSpellInfo()->Id == SPELL_WARRIOR_SECOND_WIND_PROC_RANK_2) + spellId = SPELL_WARRIOR_SECOND_WIND_TRIGGER_RANK_2; if (!spellId) return; - GetTarget()->CastSpell(GetTarget(), spellId, true, NULL, aurEff); + GetTarget()->CastSpell(GetTarget(), spellId, true, nullptr, aurEff); } @@ -807,9 +806,7 @@ class spell_warr_sudden_death : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_COLOSSUS_SMASH)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARRIOR_COLOSSUS_SMASH }); } void HandleApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -841,18 +838,9 @@ class spell_warr_sweeping_strikes : public SpellScriptLoader { PrepareAuraScript(spell_warr_sweeping_strikes_AuraScript); - public: - spell_warr_sweeping_strikes_AuraScript() - { - _procTarget = nullptr; - } - - private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_SWEEPING_STRIKES_EXTRA_ATTACK_1) || !sSpellMgr->GetSpellInfo(SPELL_WARRIOR_SWEEPING_STRIKES_EXTRA_ATTACK_2)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARRIOR_SWEEPING_STRIKES_EXTRA_ATTACK_1, SPELL_WARRIOR_SWEEPING_STRIKES_EXTRA_ATTACK_2 }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -870,12 +858,12 @@ class spell_warr_sweeping_strikes : public SpellScriptLoader if (spellInfo && (spellInfo->Id == SPELL_WARRIOR_BLADESTORM_PERIODIC_WHIRLWIND || (spellInfo->Id == SPELL_WARRIOR_EXECUTE && !_procTarget->HasAuraState(AURA_STATE_HEALTHLESS_20_PERCENT)))) { // If triggered by Execute (while target is not under 20% hp) or Bladestorm deals normalized weapon damage - GetTarget()->CastSpell(_procTarget, SPELL_WARRIOR_SWEEPING_STRIKES_EXTRA_ATTACK_2, true, NULL, aurEff); + GetTarget()->CastSpell(_procTarget, SPELL_WARRIOR_SWEEPING_STRIKES_EXTRA_ATTACK_2, true, nullptr, aurEff); } else { int32 damage = eventInfo.GetDamageInfo()->GetDamage(); - GetTarget()->CastCustomSpell(SPELL_WARRIOR_SWEEPING_STRIKES_EXTRA_ATTACK_1, SPELLVALUE_BASE_POINT0, damage, _procTarget, true, NULL, aurEff); + GetTarget()->CastCustomSpell(SPELL_WARRIOR_SWEEPING_STRIKES_EXTRA_ATTACK_1, SPELLVALUE_BASE_POINT0, damage, _procTarget, true, nullptr, aurEff); } } } @@ -886,8 +874,7 @@ class spell_warr_sweeping_strikes : public SpellScriptLoader OnEffectProc += AuraEffectProcFn(spell_warr_sweeping_strikes_AuraScript::HandleProc, EFFECT_0, SPELL_AURA_DUMMY); } - private: - Unit* _procTarget; + Unit* _procTarget = nullptr; }; AuraScript* GetAuraScript() const override @@ -909,9 +896,7 @@ class spell_warr_sword_and_board : public SpellScriptLoader private: bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_SHIELD_SLAM)) - return false; - return true; + return ValidateSpellInfo({ SPELL_WARRIOR_SHIELD_SLAM }); } void OnProc(AuraEffect const* /*aurEff*/, ProcEventInfo& /*eventInfo*/) @@ -974,15 +959,7 @@ class spell_warr_vigilance : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_WARRIOR_VENGEANCE)) - return false; - return true; - } - - bool Load() override - { - _procTarget = NULL; - return true; + return ValidateSpellInfo({ SPELL_WARRIOR_VENGEANCE }); } bool CheckProc(ProcEventInfo& eventInfo) @@ -996,8 +973,8 @@ class spell_warr_vigilance : public SpellScriptLoader PreventDefaultAction(); int32 damage = int32(CalculatePct(eventInfo.GetDamageInfo()->GetDamage(), aurEff->GetSpellInfo()->Effects[EFFECT_1].CalcValue())); - GetTarget()->CastSpell(_procTarget, SPELL_WARRIOR_VIGILANCE_PROC, true, NULL, aurEff); - _procTarget->CastCustomSpell(_procTarget, SPELL_WARRIOR_VENGEANCE, &damage, &damage, &damage, true, NULL, aurEff); + GetTarget()->CastSpell(_procTarget, SPELL_WARRIOR_VIGILANCE_PROC, true, nullptr, aurEff); + _procTarget->CastCustomSpell(_procTarget, SPELL_WARRIOR_VENGEANCE, &damage, &damage, &damage, true, nullptr, aurEff); } void HandleRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) @@ -1016,8 +993,7 @@ class spell_warr_vigilance : public SpellScriptLoader OnEffectRemove += AuraEffectRemoveFn(spell_warr_vigilance_AuraScript::HandleRemove, EFFECT_0, SPELL_AURA_PROC_TRIGGER_SPELL, AURA_EFFECT_HANDLE_REAL); } - private: - Unit* _procTarget; + Unit* _procTarget = nullptr; }; AuraScript* GetAuraScript() const override diff --git a/src/server/scripts/World/action_ip_logger.cpp b/src/server/scripts/World/action_ip_logger.cpp index 85cae1216cf..5e6d0708b15 100644 --- a/src/server/scripts/World/action_ip_logger.cpp +++ b/src/server/scripts/World/action_ip_logger.cpp @@ -16,9 +16,9 @@ */ #include "ScriptMgr.h" -#include "Channel.h" -#include "Guild.h" -#include "Group.h" +#include "DatabaseEnv.h" +#include "Player.h" +#include "WorldSession.h" enum IPLoggingTypes { @@ -124,7 +124,7 @@ class AccountActionIpLogger : public AccountScript /*case ACCOUNT_LOGOUT: systemNote = "Logged on AccountLogout"; //Can not be logged break;*/ - // Neither should happen. Ever. Period. If it does, call Ghostbusters and all your local software defences to investigate. + // Neither should happen. Ever. Period. If it does, call Ghostbusters and all your local software defenses to investigate. case UNKNOWN_ACTION: default: systemNote = "ERROR! Unknown action!"; diff --git a/src/server/scripts/World/areatrigger_scripts.cpp b/src/server/scripts/World/areatrigger_scripts.cpp index 2708a59d520..9c33dcf382a 100644 --- a/src/server/scripts/World/areatrigger_scripts.cpp +++ b/src/server/scripts/World/areatrigger_scripts.cpp @@ -35,10 +35,15 @@ at_brewfest at_area_52_entrance EndContentData */ -#include "GameTime.h" #include "ScriptMgr.h" -#include "ScriptedCreature.h" +#include "DBCStructure.h" +#include "GameObject.h" +#include "GameTime.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" +#include "TemporarySummon.h" /*###### ## at_coilfang_waterfall diff --git a/src/server/scripts/World/boss_emerald_dragons.cpp b/src/server/scripts/World/boss_emerald_dragons.cpp index d80435ece56..e3e88b714e5 100644 --- a/src/server/scripts/World/boss_emerald_dragons.cpp +++ b/src/server/scripts/World/boss_emerald_dragons.cpp @@ -17,12 +17,13 @@ */ #include "ObjectMgr.h" -#include "ScriptMgr.h" +#include "MotionMaster.h" +#include "PassiveAI.h" #include "ScriptedCreature.h" -#include "SpellScript.h" +#include "ScriptMgr.h" #include "Spell.h" #include "SpellAuraEffects.h" -#include "PassiveAI.h" +#include "SpellScript.h" // // Emerald Dragon NPCs and IDs (kept here for reference) @@ -397,7 +398,7 @@ class boss_lethon : public CreatureScript switch (eventId) { case EVENT_SHADOW_BOLT_WHIRL: - me->CastSpell((Unit*)NULL, SPELL_SHADOW_BOLT_WHIRL, false); + me->CastSpell((Unit*)nullptr, SPELL_SHADOW_BOLT_WHIRL, false); events.ScheduleEvent(EVENT_SHADOW_BOLT_WHIRL, urand(15000, 30000)); break; default: @@ -437,7 +438,7 @@ class npc_spirit_shade : public CreatureScript { if (moveType == FOLLOW_MOTION_TYPE && data == _summonerGuid.GetCounter()) { - me->CastSpell((Unit*)NULL, SPELL_DARK_OFFERING, false); + me->CastSpell((Unit*)nullptr, SPELL_DARK_OFFERING, false); me->DespawnOrUnsummon(1000); } } @@ -770,11 +771,11 @@ class spell_mark_of_nature : public SpellScriptLoader bool Validate(SpellInfo const* /*spellInfo*/) override { - if (!sSpellMgr->GetSpellInfo(SPELL_MARK_OF_NATURE)) - return false; - if (!sSpellMgr->GetSpellInfo(SPELL_AURA_OF_NATURE)) - return false; - return true; + return ValidateSpellInfo( + { + SPELL_MARK_OF_NATURE, + SPELL_AURA_OF_NATURE + }); } void FilterTargets(std::list& targets) diff --git a/src/server/scripts/World/chat_log.cpp b/src/server/scripts/World/chat_log.cpp index 972791e8a22..b791a7fb4a9 100644 --- a/src/server/scripts/World/chat_log.cpp +++ b/src/server/scripts/World/chat_log.cpp @@ -17,8 +17,10 @@ #include "ScriptMgr.h" #include "Channel.h" -#include "Guild.h" #include "Group.h" +#include "Guild.h" +#include "Log.h" +#include "Player.h" class ChatLogScript : public PlayerScript { diff --git a/src/server/scripts/World/duel_reset.cpp b/src/server/scripts/World/duel_reset.cpp index 00ff46aba81..56dfe7a2336 100644 --- a/src/server/scripts/World/duel_reset.cpp +++ b/src/server/scripts/World/duel_reset.cpp @@ -15,11 +15,14 @@ * with this program. If not, see . */ -#include "GameTime.h" #include "ScriptMgr.h" -#include "Player.h" +#include "GameTime.h" #include "Pet.h" +#include "Player.h" +#include "SpelLHistory.h" #include "SpellInfo.h" +#include "SpellMgr.h" +#include "World.h" class DuelResetScript : public PlayerScript { diff --git a/src/server/scripts/World/go_scripts.cpp b/src/server/scripts/World/go_scripts.cpp index 5f4635717c3..5c6ee7a0a00 100644 --- a/src/server/scripts/World/go_scripts.cpp +++ b/src/server/scripts/World/go_scripts.cpp @@ -45,14 +45,20 @@ go_bells EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "GameObjectAI.h" -#include "Spell.h" -#include "Player.h" -#include "WorldSession.h" +#include "Creature.h" +#include "CreatureAI.h" +#include "DBCStructure.h" #include "GameEventMgr.h" +#include "GameObject.h" +#include "GameObjectAI.h" #include "GameTime.h" +#include "Log.h" +#include "MotionMaster.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "ScriptedGossip.h" +#include "TemporarySummon.h" +#include "WorldSession.h" /*###### ## go_cat_figurine @@ -562,7 +568,6 @@ class go_tele_to_dalaran_crystal : public GameObjectScript return false; player->GetSession()->SendNotification(GO_TELE_TO_DALARAN_CRYSTAL_FAILED); - return true; } }; @@ -1207,7 +1212,7 @@ class go_amberpine_outhouse : public GameObjectScript if (action == GOSSIP_ACTION_INFO_DEF + 1) { CloseGossipMenuFor(player); - Creature* target = GetClosestCreatureWithEntry(player, NPC_OUTHOUSE_BUNNY, 3.0f); + Creature* target = player->FindNearestCreature(NPC_OUTHOUSE_BUNNY, 3.0f); if (target) { target->AI()->SetData(1, player->getGender()); @@ -1315,15 +1320,15 @@ class go_veil_skith_cage : public GameObjectScript me->UseDoorOrButton(); if (player->GetQuestStatus(QUEST_MISSING_FRIENDS) == QUEST_STATUS_INCOMPLETE) { - std::list childrenList; - GetCreatureListWithEntryInGrid(childrenList, me, NPC_CAPTIVE_CHILD, INTERACTION_DISTANCE); - for (std::list::const_iterator itr = childrenList.begin(); itr != childrenList.end(); ++itr) + std::vector childrenList; + me->GetCreatureListWithEntryInGrid(childrenList, NPC_CAPTIVE_CHILD, INTERACTION_DISTANCE); + for (Creature* children : childrenList) { - player->KilledMonsterCredit(NPC_CAPTIVE_CHILD, (*itr)->GetGUID()); - (*itr)->DespawnOrUnsummon(5000); - (*itr)->GetMotionMaster()->MovePoint(1, me->GetPositionX() + 5, me->GetPositionY(), me->GetPositionZ()); - (*itr)->AI()->Talk(SAY_FREE_0); - (*itr)->GetMotionMaster()->Clear(); + player->KilledMonsterCredit(NPC_CAPTIVE_CHILD, children->GetGUID()); + children->DespawnOrUnsummon(5000); + children->GetMotionMaster()->MovePoint(1, me->GetPositionX() + 5, me->GetPositionY(), me->GetPositionZ()); + children->AI()->Talk(SAY_FREE_0); + children->GetMotionMaster()->Clear(); } } return false; @@ -1655,7 +1660,7 @@ public: break; std::vector playersNearby; - me->GetPlayerListInGrid(playersNearby, me->GetMap()->GetVisibilityRange()); + me->GetPlayerListInGrid(playersNearby, me->GetVisibilityRange()); for (Player* player : playersNearby) { if (player->GetTeamId() == TEAM_HORDE) diff --git a/src/server/scripts/World/guards.cpp b/src/server/scripts/World/guards.cpp index 1dbb55831d9..5b164058bea 100644 --- a/src/server/scripts/World/guards.cpp +++ b/src/server/scripts/World/guards.cpp @@ -30,9 +30,11 @@ guard_shattrath_scryer EndContentData */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "GuardAI.h" +#include "MotionMaster.h" +#include "ObjectAccessor.h" #include "Player.h" +#include "ScriptedCreature.h" #include "SpellInfo.h" enum GuardGeneric @@ -120,7 +122,7 @@ public: if (me->IsWithinMeleeRange(me->GetVictim())) { bool healing = false; - SpellInfo const* info = NULL; + SpellInfo const* info = nullptr; //Select a healing spell if less than 30% hp if (me->HealthBelowPct(30)) @@ -156,7 +158,7 @@ public: if (!me->IsNonMeleeSpellCast(false)) { bool healing = false; - SpellInfo const* info = NULL; + SpellInfo const* info = nullptr; //Select a healing spell if less than 30% hp ONLY 33% of the time if (me->HealthBelowPct(30) && 33 > urand(0, 99)) diff --git a/src/server/scripts/World/item_scripts.cpp b/src/server/scripts/World/item_scripts.cpp index b1e1986e443..9da73e7be1b 100644 --- a/src/server/scripts/World/item_scripts.cpp +++ b/src/server/scripts/World/item_scripts.cpp @@ -31,9 +31,13 @@ item_only_for_flight Items which should only useable while flying EndContentData */ #include "ScriptMgr.h" +#include "GameObject.h" +#include "Item.h" +#include "Player.h" #include "ScriptedCreature.h" #include "Spell.h" -#include "Player.h" +#include "SpellMgr.h" +#include "TemporarySummon.h" /*##### # item_only_for_flight @@ -76,7 +80,7 @@ public: return false; // error - player->SendEquipError(EQUIP_ERR_CLIENT_LOCKED_OUT, item, NULL); + player->SendEquipError(EQUIP_ERR_CLIENT_LOCKED_OUT, item, nullptr); return true; } }; @@ -119,7 +123,7 @@ public: targets.GetUnitTarget()->GetEntry() == 20748 && !targets.GetUnitTarget()->HasAura(32578)) return false; - player->SendEquipError(EQUIP_ERR_CLIENT_LOCKED_OUT, item, NULL); + player->SendEquipError(EQUIP_ERR_CLIENT_LOCKED_OUT, item, nullptr); return true; } }; @@ -139,7 +143,7 @@ public: return false; else { - player->SendEquipError(EQUIP_ERR_OUT_OF_RANGE, item, NULL); + player->SendEquipError(EQUIP_ERR_OUT_OF_RANGE, item, nullptr); return true; } } @@ -159,7 +163,7 @@ public: ItemPosCountVec dest; uint8 msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, 39883, 1); // Cracked Egg if (msg == EQUIP_ERR_OK) - player->StoreNewItem(dest, 39883, true, Item::GenerateItemRandomPropertyId(39883)); + player->StoreNewItem(dest, 39883, true, GenerateItemRandomPropertyId(39883)); return true; } @@ -179,7 +183,7 @@ public: ItemPosCountVec dest; uint8 msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, 44718, 1); // Ripe Disgusting Jar if (msg == EQUIP_ERR_OK) - player->StoreNewItem(dest, 44718, true, Item::GenerateItemRandomPropertyId(44718)); + player->StoreNewItem(dest, 44718, true, GenerateItemRandomPropertyId(44718)); return true; } @@ -225,7 +229,7 @@ public: bool OnUse(Player* player, Item* /*item*/, SpellCastTargets const & /*targets*/) override { - GameObject* go = NULL; + GameObject* go = nullptr; for (uint8 i = 0; i < CaribouTrapsNum; ++i) { go = player->FindNearestGameObject(CaribouTraps[i], 5.0f); @@ -241,7 +245,7 @@ public: float x, y, z; go->GetClosePoint(x, y, z, go->GetObjectSize() / 3, 7.0f); - go->SummonGameObject(GO_HIGH_QUALITY_FUR, *go, G3D::Quat(), 1); + go->SummonGameObject(GO_HIGH_QUALITY_FUR, *go, QuaternionData(), 1); if (TempSummon* summon = player->SummonCreature(NPC_NESINGWARY_TRAPPER, x, y, z, go->GetOrientation(), TEMPSUMMON_DEAD_DESPAWN, 1000)) { summon->SetVisible(false); @@ -275,7 +279,7 @@ public: if (!player->GetTransport() || player->GetAreaId() != AREA_ID_SHATTERED_STRAITS) { - if (const SpellInfo* spellInfo = sSpellMgr->GetSpellInfo(SPELL_PETROV_BOMB)) + if (SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(SPELL_PETROV_BOMB)) Spell::SendCastResult(player, spellInfo, 1, SPELL_FAILED_NOT_HERE); return true; @@ -341,7 +345,7 @@ public: if (!pMammoth) return false; - GameObject* pTrap = NULL; + GameObject* pTrap = nullptr; for (uint8 i = 0; i < MammothTrapsNum; ++i) { pTrap = player->FindNearestGameObject(MammothTraps[i], 11.0f); @@ -375,10 +379,10 @@ public: if (player->FindNearestCreature(NPC_VANIRAS_SENTRY_TOTEM, 10.0f)) return false; else - player->SendEquipError(EQUIP_ERR_OUT_OF_RANGE, item, NULL); + player->SendEquipError(EQUIP_ERR_OUT_OF_RANGE, item, nullptr); } else - player->SendEquipError(EQUIP_ERR_CLIENT_LOCKED_OUT, item, NULL); + player->SendEquipError(EQUIP_ERR_CLIENT_LOCKED_OUT, item, nullptr); return true; } }; diff --git a/src/server/scripts/World/mob_generic_creature.cpp b/src/server/scripts/World/mob_generic_creature.cpp index 3bb43efcac8..e5acc43a7f3 100644 --- a/src/server/scripts/World/mob_generic_creature.cpp +++ b/src/server/scripts/World/mob_generic_creature.cpp @@ -17,8 +17,9 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" #include "PassiveAI.h" +#include "ScriptedCreature.h" +#include "SpellMgr.h" class trigger_periodic : public CreatureScript { @@ -29,13 +30,13 @@ public: { trigger_periodicAI(Creature* creature) : NullCreatureAI(creature) { - spell = me->m_spells[0] ? sSpellMgr->GetSpellInfo(me->m_spells[0]) : NULL; + spell = me->m_spells[0] ? sSpellMgr->GetSpellInfo(me->m_spells[0]) : nullptr; interval = me->GetAttackTime(BASE_ATTACK); timer = interval; } uint32 timer, interval; - const SpellInfo* spell; + SpellInfo const* spell; void UpdateAI(uint32 diff) override { diff --git a/src/server/scripts/World/npc_innkeeper.cpp b/src/server/scripts/World/npc_innkeeper.cpp index 5bd5e310075..f2b2a1291a5 100644 --- a/src/server/scripts/World/npc_innkeeper.cpp +++ b/src/server/scripts/World/npc_innkeeper.cpp @@ -38,18 +38,18 @@ enum Spells #define LOCALE_TRICK_OR_TREAT_0 "Trick or Treat!" #define LOCALE_TRICK_OR_TREAT_2 "Des bonbons ou des blagues!" -#define LOCALE_TRICK_OR_TREAT_3 "Süßes oder Saures!" -#define LOCALE_TRICK_OR_TREAT_6 "¡Truco o trato!" +#define LOCALE_TRICK_OR_TREAT_3 "Süßes oder Saures!" +#define LOCALE_TRICK_OR_TREAT_6 "¡Truco o trato!" #define LOCALE_INNKEEPER_0 "Make this inn my home." #define LOCALE_INNKEEPER_2 "Faites de cette auberge votre foyer." -#define LOCALE_INNKEEPER_3 "Ich möchte dieses Gasthaus zu meinem Heimatort machen." +#define LOCALE_INNKEEPER_3 "Ich möchte dieses Gasthaus zu meinem Heimatort machen." #define LOCALE_INNKEEPER_6 "Fija tu hogar en esta taberna." #define LOCALE_VENDOR_0 "I want to browse your goods." #define LOCALE_VENDOR_2 "Je voudrais regarder vos articles." #define LOCALE_VENDOR_3 "Ich sehe mich nur mal um." -#define LOCALE_VENDOR_6 "Quiero ver tus mercancías." +#define LOCALE_VENDOR_6 "Quiero ver tus mercancías." class npc_innkeeper : public CreatureScript { @@ -64,7 +64,7 @@ class npc_innkeeper : public CreatureScript { if (IsHolidayActive(HOLIDAY_HALLOWS_END) && !player->HasAura(SPELL_TRICK_OR_TREATED)) { - const char* localizedEntry; + char const* localizedEntry; switch (player->GetSession()->GetSessionDbcLocale()) { case LOCALE_frFR: localizedEntry = LOCALE_TRICK_OR_TREAT_2; break; @@ -94,7 +94,7 @@ class npc_innkeeper : public CreatureScript if (me->IsInnkeeper()) { - const char* localizedEntry; + char const* localizedEntry; switch (player->GetSession()->GetSessionDbcLocale()) { case LOCALE_frFR: localizedEntry = LOCALE_INNKEEPER_2; break; diff --git a/src/server/scripts/World/npc_professions.cpp b/src/server/scripts/World/npc_professions.cpp index 2a574d0ff36..8a8f9668d28 100644 --- a/src/server/scripts/World/npc_professions.cpp +++ b/src/server/scripts/World/npc_professions.cpp @@ -24,10 +24,13 @@ SDCategory: NPCs/GOBs EndScriptData */ #include "ScriptMgr.h" +#include "Item.h" +#include "Log.h" +#include "Player.h" #include "ScriptedCreature.h" #include "ScriptedGossip.h" -#include "Player.h" #include "SpellInfo.h" +#include "SpellMgr.h" #include "WorldSession.h" /* @@ -244,7 +247,7 @@ bool EquippedOk(Player* player, uint32 spellId) if (!reqSpell) continue; - Item* item = NULL; + Item* item = nullptr; for (uint8 j = EQUIPMENT_SLOT_START; j < EQUIPMENT_SLOT_END; ++j) { item = player->GetItemByPos(INVENTORY_SLOT_BAG_0, j); @@ -368,7 +371,7 @@ void ProcessUnlearnAction(Player* player, Creature* creature, uint32 spellId, ui player->SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, creature, 0, 0); } else - player->SendEquipError(EQUIP_ERR_CLIENT_LOCKED_OUT, NULL, NULL); + player->SendEquipError(EQUIP_ERR_CLIENT_LOCKED_OUT, nullptr, nullptr); CloseGossipMenuFor(player); } diff --git a/src/server/scripts/World/npcs_special.cpp b/src/server/scripts/World/npcs_special.cpp index 8ef373bbd70..acb082a42fa 100644 --- a/src/server/scripts/World/npcs_special.cpp +++ b/src/server/scripts/World/npcs_special.cpp @@ -17,26 +17,27 @@ */ #include "ScriptMgr.h" -#include "ScriptedCreature.h" -#include "ScriptedGossip.h" -#include "ScriptedEscortAI.h" -#include "ObjectMgr.h" -#include "ScriptMgr.h" -#include "World.h" -#include "PassiveAI.h" -#include "GameEventMgr.h" -#include "GridNotifiers.h" -#include "GridNotifiersImpl.h" -#include "Cell.h" #include "CellImpl.h" -#include "SpellHistory.h" -#include "SpellAuras.h" -#include "Pet.h" -#include "CreatureTextMgr.h" #include "CombatAI.h" -#include "SmartAI.h" -#include "Vehicle.h" +#include "CreatureTextMgr.h" +#include "GameEventMgr.h" +#include "GridNotifiersImpl.h" +#include "Log.h" +#include "MotionMaster.h" #include "MoveSplineInit.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "PassiveAI.h" +#include "Pet.h" +#include "ScriptedEscortAI.h" +#include "ScriptedGossip.h" +#include "ScriptMgr.h" +#include "SmartAI.h" +#include "SpellAuras.h" +#include "SpellHistory.h" +#include "SpellMgr.h" +#include "Vehicle.h" +#include "World.h" /*######## # npc_air_force_bots @@ -104,7 +105,7 @@ public: { npc_air_force_botsAI(Creature* creature) : ScriptedAI(creature) { - SpawnAssoc = NULL; + SpawnAssoc = nullptr; SpawnedGUID.Clear(); // find the correct spawnhandling @@ -128,7 +129,7 @@ public: if (!spawnedTemplate) { TC_LOG_ERROR("sql.sql", "TCSR: Creature template entry %u does not exist in DB, which is required by npc_air_force_bots", SpawnAssoc->spawnedCreatureEntry); - SpawnAssoc = NULL; + SpawnAssoc = nullptr; return; } } @@ -148,7 +149,7 @@ public: else { TC_LOG_ERROR("sql.sql", "TCSR: npc_air_force_bots: wasn't able to spawn Creature %u", SpawnAssoc->spawnedCreatureEntry); - SpawnAssoc = NULL; + SpawnAssoc = nullptr; } return summoned; @@ -157,11 +158,10 @@ public: Creature* GetSummonedGuard() { Creature* creature = ObjectAccessor::GetCreature(*me, SpawnedGUID); - if (creature && creature->IsAlive()) return creature; - return NULL; + return nullptr; } void MoveInLineOfSight(Unit* who) override @@ -177,7 +177,7 @@ public: if (!playerTarget) return; - Creature* lastSpawnedGuard = SpawnedGUID.IsEmpty() ? NULL : GetSummonedGuard(); + Creature* lastSpawnedGuard = SpawnedGUID.IsEmpty() ? nullptr : GetSummonedGuard(); // prevent calling Unit::GetUnit at next MoveInLineOfSight call - speedup if (!lastSpawnedGuard) @@ -840,7 +840,7 @@ public: void Initialize() { DoctorGUID.Clear(); - Coord = NULL; + Coord = nullptr; } ObjectGuid DoctorGUID; @@ -1815,7 +1815,7 @@ public: void DamageTaken(Unit* doneBy, uint32& damage) override { me->AddThreat(doneBy, float(damage)); // just to create threat reference - _damageTimes[doneBy->GetGUID()] = time(NULL); + _damageTimes[doneBy->GetGUID()] = time(nullptr); damage = 0; } @@ -1854,7 +1854,7 @@ public: { case EVENT_TD_CHECK_COMBAT: { - time_t now = time(NULL); + time_t now = time(nullptr); for (std::unordered_map::iterator itr = _damageTimes.begin(); itr != _damageTimes.end();) { // If unit has not dealt damage to training dummy for 5 seconds, remove him from combat @@ -2211,7 +2211,7 @@ public: GameObject* FindNearestLauncher() { - GameObject* launcher = NULL; + GameObject* launcher = nullptr; if (isCluster()) { @@ -2326,8 +2326,7 @@ public: break; } - const SpellInfo* spellInfo = sSpellMgr->GetSpellInfo(spellId); - + SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spellId); if (spellInfo && spellInfo->Effects[0].Effect == SPELL_EFFECT_SUMMON_OBJECT_WILD) return spellInfo->Effects[0].MiscValue; @@ -2371,7 +2370,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(), G3D::Quat(), 1); + me->SummonGameObject(GetFireworkGameObjectId(), me->GetPositionX() + (i % 2 == 0 ? displacement : -displacement), me->GetPositionY() + (i > 1 ? displacement : -displacement), me->GetPositionZ() + 4.0f, me->GetOrientation(), QuaternionData(), 1); } else //me->CastSpell(me, GetFireworkSpell(me->GetEntry()), true); diff --git a/src/server/shared/CMakeLists.txt b/src/server/shared/CMakeLists.txt index ffa0bee4adc..904f178ff85 100644 --- a/src/server/shared/CMakeLists.txt +++ b/src/server/shared/CMakeLists.txt @@ -20,7 +20,6 @@ CollectSourceFiles( if (USE_COREPCH) set(PRIVATE_PCH_HEADER PrecompiledHeaders/sharedPCH.h) - set(PRIVATE_PCH_SOURCE PrecompiledHeaders/sharedPCH.cpp) endif() GroupSources(${CMAKE_CURRENT_SOURCE_DIR}) @@ -45,6 +44,8 @@ target_include_directories(shared ${CMAKE_CURRENT_BINARY_DIR}) target_link_libraries(shared + PRIVATE + trinity-core-interface PUBLIC database) @@ -67,5 +68,5 @@ endif() # Generate precompiled header if (USE_COREPCH) - add_cxx_pch(shared ${PRIVATE_PCH_HEADER} ${PRIVATE_PCH_SOURCE}) + add_cxx_pch(shared ${PRIVATE_PCH_HEADER}) endif () diff --git a/src/server/shared/DataStores/DB2FileLoader.cpp b/src/server/shared/DataStores/DB2FileLoader.cpp index dacb14674c2..8499890a215 100644 --- a/src/server/shared/DataStores/DB2FileLoader.cpp +++ b/src/server/shared/DataStores/DB2FileLoader.cpp @@ -39,16 +39,16 @@ DB2FileLoader::DB2FileLoader() locale = 0; unk5 = 0; - data = NULL; - fieldsOffset = NULL; + data = nullptr; + fieldsOffset = nullptr; } -bool DB2FileLoader::Load(const char *filename, const char *fmt) +bool DB2FileLoader::Load(char const* filename, char const* fmt) { if (data) { delete [] data; - data = NULL; + data = nullptr; } FILE* f = fopen(filename, "rb"); @@ -202,7 +202,7 @@ DB2FileLoader::Record DB2FileLoader::getRecord(size_t id) return Record(*this, data + id*recordSize); } -uint32 DB2FileLoader::GetFormatRecordSize(const char * format, int32* index_pos) +uint32 DB2FileLoader::GetFormatRecordSize(char const* format, int32* index_pos) { uint32 recordsize = 0; int32 i = -1; @@ -236,7 +236,7 @@ uint32 DB2FileLoader::GetFormatRecordSize(const char * format, int32* index_pos) return recordsize; } -uint32 DB2FileLoader::GetFormatStringsFields(const char * format) +uint32 DB2FileLoader::GetFormatStringsFields(char const* format) { uint32 stringfields = 0; for (uint32 x=0; format[x]; ++x) @@ -246,12 +246,11 @@ uint32 DB2FileLoader::GetFormatStringsFields(const char * format) return stringfields; } -char* DB2FileLoader::AutoProduceData(const char* format, uint32& records, char**& indexTable) +char* DB2FileLoader::AutoProduceData(char const* format, uint32& records, char**& indexTable) { - typedef char * ptr; if (strlen(format) != fieldCount) - return NULL; + return nullptr; //get struct size and index pos int32 i; @@ -310,7 +309,7 @@ char* DB2FileLoader::AutoProduceData(const char* format, uint32& records, char** offset += 1; break; case FT_STRING: - *((char**)(&dataTable[offset])) = NULL; // will be replaces non-empty or "" strings in AutoProduceStrings + *((char**)(&dataTable[offset])) = nullptr; // will be replaces non-empty or "" strings in AutoProduceStrings offset += sizeof(char*); break; } @@ -322,10 +321,10 @@ char* DB2FileLoader::AutoProduceData(const char* format, uint32& records, char** static char const* const nullStr = ""; -char* DB2FileLoader::AutoProduceStringsArrayHolders(const char* format, char* dataTable) +char* DB2FileLoader::AutoProduceStringsArrayHolders(char const* format, char* dataTable) { if (strlen(format) != fieldCount) - return NULL; + return nullptr; // we store flat holders pool as single memory block size_t stringFields = GetFormatStringsFields(format); @@ -380,10 +379,10 @@ char* DB2FileLoader::AutoProduceStringsArrayHolders(const char* format, char* da return stringHoldersPool; } -char* DB2FileLoader::AutoProduceStrings(const char* format, char* dataTable, uint32 locale) +char* DB2FileLoader::AutoProduceStrings(char const* format, char* dataTable, uint32 locale) { if (strlen(format) != fieldCount) - return NULL; + return nullptr; char* stringPool= new char[stringSize]; memcpy(stringPool, stringTable, stringSize); @@ -410,7 +409,7 @@ char* DB2FileLoader::AutoProduceStrings(const char* format, char* dataTable, uin if (db2str->Str[locale] == nullStr) { const char * st = getRecord(y).getString(x); - db2str->Str[locale] = stringPool + (st - (const char*)stringTable); + db2str->Str[locale] = stringPool + (st - (char const*)stringTable); } offset += sizeof(char*); diff --git a/src/server/shared/DataStores/DB2FileLoader.h b/src/server/shared/DataStores/DB2FileLoader.h index 2895fc2c3f3..ab70c907b48 100644 --- a/src/server/shared/DataStores/DB2FileLoader.h +++ b/src/server/shared/DataStores/DB2FileLoader.h @@ -62,9 +62,9 @@ class TC_SHARED_API DB2FileLoader } private: - Record(DB2FileLoader &file_, unsigned char *offset_): offset(offset_), file(file_) {} + Record(DB2FileLoader& file_, unsigned char* offset_): offset(offset_), file(file_) {} unsigned char *offset; - DB2FileLoader &file; + DB2FileLoader& file; friend class DB2FileLoader; }; @@ -75,14 +75,14 @@ class TC_SHARED_API DB2FileLoader uint32 GetNumRows() const { return recordCount;} uint32 GetCols() const { return fieldCount; } - uint32 GetOffset(size_t id) const { return (fieldsOffset != NULL && id < fieldCount) ? fieldsOffset[id] : 0; } + uint32 GetOffset(size_t id) const { return (fieldsOffset != nullptr && id < fieldCount) ? fieldsOffset[id] : 0; } uint32 GetHash() const { return tableHash; } - bool IsLoaded() const { return (data != NULL); } - char* AutoProduceData(const char* fmt, uint32& count, char**& indexTable); - char* AutoProduceStringsArrayHolders(const char* fmt, char* dataTable); - char* AutoProduceStrings(const char* fmt, char* dataTable, uint32 locale); - static uint32 GetFormatRecordSize(const char * format, int32 * index_pos = NULL); - static uint32 GetFormatStringsFields(const char * format); + bool IsLoaded() const { return (data != nullptr); } + char* AutoProduceData(char const* fmt, uint32& count, char**& indexTable); + char* AutoProduceStringsArrayHolders(char const* fmt, char* dataTable); + char* AutoProduceStrings(char const* fmt, char* dataTable, uint32 locale); + static uint32 GetFormatRecordSize(char const* format, int32* index_pos = nullptr); + static uint32 GetFormatStringsFields(char const* format); private: uint32 recordSize; diff --git a/src/server/shared/DataStores/DB2Store.h b/src/server/shared/DataStores/DB2Store.h index b1dc322e949..95151da8ef5 100644 --- a/src/server/shared/DataStores/DB2Store.h +++ b/src/server/shared/DataStores/DB2Store.h @@ -18,8 +18,9 @@ #ifndef DB2STORE_H #define DB2STORE_H -#include "DB2FileLoader.h" #include "Common.h" +#include "DB2FileLoader.h" +#include "Errors.h" #include "ByteBuffer.h" #include @@ -45,7 +46,7 @@ class DB2Storage; template bool DB2StorageHasEntry(DB2Storage const& store, uint32 id) { - return store.LookupEntry(id) != NULL; + return store.LookupEntry(id) != nullptr; } template @@ -100,15 +101,15 @@ void WriteDB2RecordToPacket(DB2Storage const& store, uint32 id, uint32 locale template class DB2Storage : public DB2StorageBase { - typedef std::list StringPoolList; + typedef std::vector StringPoolList; typedef std::vector DataTableEx; typedef bool(*EntryChecker)(DB2Storage const&, uint32); typedef void(*PacketWriter)(DB2Storage const&, uint32, LocaleConstant, ByteBuffer&); public: - DB2Storage(char const* f, EntryChecker checkEntry = NULL, PacketWriter writePacket = NULL) : - nCount(0), fieldCount(0), fmt(f), m_dataTable(NULL) + DB2Storage(char const* f, EntryChecker checkEntry = nullptr, PacketWriter writePacket = nullptr) : + nCount(0), fieldCount(0), fmt(f), m_dataTable(nullptr) { - indexTable.asT = NULL; + indexTable.asT = nullptr; CheckEntry = checkEntry ? checkEntry : (EntryChecker)&DB2StorageHasEntry; WritePacket = writePacket ? writePacket : (PacketWriter)&WriteDB2RecordToPacket; } @@ -116,7 +117,7 @@ public: ~DB2Storage() { Clear(); } bool HasRecord(uint32 id) const { return CheckEntry(*this, id); } - T const* LookupEntry(uint32 id) const { return (id >= nCount) ? NULL : indexTable.asT[id]; } + T const* LookupEntry(uint32 id) const { return (id >= nCount) ? nullptr : indexTable.asT[id]; } uint32 GetNumRows() const { return nCount; } char const* GetFormat() const { return fmt; } uint32 GetFieldCount() const { return fieldCount; } @@ -128,7 +129,7 @@ public: T* CreateEntry(uint32 id, bool evenIfExists = false) { if (evenIfExists && LookupEntry(id)) - return NULL; + return nullptr; if (id >= nCount) { @@ -147,7 +148,7 @@ public: return entryDst; } - void EraseEntry(uint32 id) { indexTable.asT[id] = NULL; } + void EraseEntry(uint32 id) { indexTable.asT[id] = nullptr; } bool Load(char const* fn, LocaleConstant localeConstant) { @@ -168,8 +169,8 @@ public: // load strings from dbc data m_stringPoolList.push_back(db2.AutoProduceStrings(fmt, (char*)m_dataTable, localeConstant)); - // error in dbc file at loading if NULL - return indexTable.asT != NULL; + // error in dbc file at loading if nullptr + return indexTable.asT != nullptr; } bool LoadStringsFrom(char const* fn, uint32 locale) @@ -195,20 +196,18 @@ public: return; delete[] reinterpret_cast(indexTable.asT); - indexTable.asT = NULL; + indexTable.asT = nullptr; delete[] reinterpret_cast(m_dataTable); - m_dataTable = NULL; + m_dataTable = nullptr; for (typename DataTableEx::iterator itr = m_dataTableEx.begin(); itr != m_dataTableEx.end(); ++itr) delete *itr; m_dataTableEx.clear(); - while (!m_stringPoolList.empty()) - { - delete[] m_stringPoolList.front(); - m_stringPoolList.pop_front(); - } + for (char* strings : m_stringPoolList) + delete[] strings; + m_stringPoolList.clear(); nCount = 0; } diff --git a/src/server/shared/DataStores/DBCDatabaseLoader.cpp b/src/server/shared/DataStores/DBCDatabaseLoader.cpp new file mode 100644 index 00000000000..3ef3e8f64c0 --- /dev/null +++ b/src/server/shared/DataStores/DBCDatabaseLoader.cpp @@ -0,0 +1,193 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * 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 . + */ + +#include "DBCDatabaseLoader.h" +#include "Common.h" +#include "DatabaseEnv.h" +#include "Errors.h" +#include "Log.h" +#include + +DBCDatabaseLoader::DBCDatabaseLoader(std::string const& storageName, std::string const& dbFormatString, std::string const& primaryKey, char const* dbcFormatString) + : _formatString(dbFormatString), _indexName(primaryKey), _sqlTableName(storageName), _dbcFormat(dbcFormatString), _sqlIndexPos(0), _recordSize(0) +{ + // Convert dbc file name to sql table name + std::transform(_sqlTableName.begin(), _sqlTableName.end(), _sqlTableName.begin(), ::tolower); + for (char& c : _sqlTableName) + if (c == '.') + c = '_'; + + // Get sql index position + int32 indexPos = -1; + _recordSize = DBCFileLoader::GetFormatRecordSize(_dbcFormat, &indexPos); + ASSERT(indexPos >= 0); + ASSERT(_recordSize); + + uint32 uindexPos = uint32(indexPos); + for (uint32 x = 0; x < _formatString.size(); ++x) + { + // Count only fields present in sql + if (_formatString[x] == FT_SQL_PRESENT) + { + if (x == uindexPos) + break; + ++_sqlIndexPos; + } + } +} + +static char const* nullStr = ""; + +char* DBCDatabaseLoader::Load(uint32& records, char**& indexTable) +{ + std::ostringstream queryBuilder; + queryBuilder << "SELECT * FROM " << _sqlTableName + << " ORDER BY " << _indexName << " DESC;"; + + // no error if empty set + QueryResult result = WorldDatabase.Query(queryBuilder.str().c_str()); + if (!result) + return nullptr; + + // Check if sql index pos is valid + if (int32(result->GetFieldCount() - 1) < _sqlIndexPos) + { + ASSERT(false, "Invalid index pos for dbc:'%s'", _sqlTableName.c_str()); + return nullptr; + } + + // Resize index table + // database query *MUST* contain ORDER BY `index_field` DESC clause + uint32 indexTableSize = std::max(records, (*result)[_sqlIndexPos].GetUInt32() + 1); + if (indexTableSize > records) + { + char** tmpIdxTable = new char*[indexTableSize]; + memset(tmpIdxTable, 0, indexTableSize * sizeof(char*)); + memcpy(tmpIdxTable, indexTable, records * sizeof(char*)); + delete[] indexTable; + indexTable = tmpIdxTable; + } + + std::unique_ptr dataTable = Trinity::make_unique(result->GetRowCount() * _recordSize); + std::unique_ptr newIndexes = Trinity::make_unique(result->GetRowCount()); + uint32 newRecords = 0; + + // Insert sql data into the data array + do + { + Field* fields = result->Fetch(); + uint32 offset = 0; + + uint32 indexValue = fields[_sqlIndexPos].GetUInt32(); + + char* dataValue = indexTable[indexValue]; + if (!dataValue) + { + newIndexes[newRecords] = indexValue; + dataValue = &dataTable[newRecords++ * _recordSize]; + } + else + { + // Attempt to overwrite existing data + ASSERT(false, "Index %d already exists in dbc:'%s'", indexValue, _sqlTableName.c_str()); + return nullptr; + } + + uint32 columnNumber = 0; + uint32 sqlColumnNumber = 0; + + for (; columnNumber < _formatString.size(); ++columnNumber) + { + if (_formatString[columnNumber] == FT_SQL_ABSENT) + { + switch (_dbcFormat[columnNumber]) + { + case FT_FLOAT: + *reinterpret_cast(&dataValue[offset]) = 0.0f; + offset += 4; + break; + case FT_IND: + case FT_INT: + *reinterpret_cast(&dataValue[offset]) = uint32(0); + offset += 4; + break; + case FT_BYTE: + *reinterpret_cast(&dataValue[offset]) = uint8(0); + offset += 1; + break; + case FT_STRING: + *reinterpret_cast(&dataValue[offset]) = const_cast(nullStr); + offset += sizeof(char*); + break; + } + } + else if (_formatString[columnNumber] == FT_SQL_PRESENT) + { + bool validSqlColumn = true; + switch (_dbcFormat[columnNumber]) + { + case FT_FLOAT: + *reinterpret_cast(&dataValue[offset]) = fields[sqlColumnNumber].GetFloat(); + offset += 4; + break; + case FT_IND: + case FT_INT: + *reinterpret_cast(&dataValue[offset]) = fields[sqlColumnNumber].GetUInt32(); + offset += 4; + break; + case FT_BYTE: + *reinterpret_cast(&dataValue[offset]) = fields[sqlColumnNumber].GetUInt8(); + offset += 1; + break; + case FT_STRING: + ASSERT(false, "Unsupported data type in table '%s' at char %d", _sqlTableName.c_str(), columnNumber); + return nullptr; + case FT_SORT: + break; + default: + validSqlColumn = false; + break; + } + if (validSqlColumn && (columnNumber != (_formatString.size() - 1))) + sqlColumnNumber++; + } + else + { + ASSERT(false, "Incorrect sql format string '%s' at char %d", _sqlTableName.c_str(), columnNumber); + break; + } + } + + if (sqlColumnNumber != (result->GetFieldCount() - 1)) + { + ASSERT(false, "SQL and DBC format strings are not matching for table: '%s'", _sqlTableName.c_str()); + return nullptr; + } + + ASSERT(offset == _recordSize); + } while (result->NextRow()); + + ASSERT(newRecords == result->GetRowCount()); + + // insert new records to index table + for (uint32 i = 0; i < newRecords; ++i) + indexTable[newIndexes[i]] = &dataTable[i * _recordSize]; + + records = indexTableSize; + + return dataTable.release(); +} diff --git a/src/server/shared/DataStores/DBCDatabaseLoader.h b/src/server/shared/DataStores/DBCDatabaseLoader.h new file mode 100644 index 00000000000..153a0eb4dcb --- /dev/null +++ b/src/server/shared/DataStores/DBCDatabaseLoader.h @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * 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 . + */ + +#ifndef DBCDatabaseLoader_h__ +#define DBCDatabaseLoader_h__ + +#include "DBCFileLoader.h" +#include +#include + +struct TC_SHARED_API DBCDatabaseLoader +{ + DBCDatabaseLoader(std::string const& storageName, std::string const& dbFormatString, std::string const& primaryKey, char const* dbcFormatString); + + char* Load(uint32& records, char**& indexTable); + +private: + std::string const& _formatString; + std::string const& _indexName; + std::string _sqlTableName; + char const* _dbcFormat; + int32 _sqlIndexPos; + uint32 _recordSize; + + DBCDatabaseLoader(DBCDatabaseLoader const& right) = delete; + DBCDatabaseLoader& operator=(DBCDatabaseLoader const& right) = delete; +}; + +#endif // DBCDatabaseLoader_h__ diff --git a/src/server/shared/DataStores/DBCStore.cpp b/src/server/shared/DataStores/DBCStore.cpp new file mode 100644 index 00000000000..3bd1492fa2c --- /dev/null +++ b/src/server/shared/DataStores/DBCStore.cpp @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + +#include "DBCStore.h" +#include "DBCDatabaseLoader.h" + +DBCStorageBase::DBCStorageBase(char const* fmt) : _fieldCount(0), _fileFormat(fmt), _dataTable(nullptr), _dataTableEx(nullptr), _indexTableSize(0) +{ +} + +DBCStorageBase::~DBCStorageBase() +{ + delete[] _dataTable; + delete[] _dataTableEx; + for (char* strings : _stringPool) + delete[] strings; +} + +bool DBCStorageBase::Load(std::string const& path, char**& indexTable) +{ + indexTable = nullptr; + + DBCFileLoader dbc; + // Check if load was sucessful, only then continue + if (!dbc.Load(path.c_str(), _fileFormat)) + return false; + + _fieldCount = dbc.GetCols(); + + // load raw non-string data + _dataTable = dbc.AutoProduceData(_fileFormat, _indexTableSize, indexTable); + + // load strings from dbc data + if (char* stringBlock = dbc.AutoProduceStrings(_fileFormat, _dataTable)) + _stringPool.push_back(stringBlock); + + // error in dbc file at loading if NULL + return indexTable != nullptr; +} + +bool DBCStorageBase::LoadStringsFrom(std::string const& path, char**& indexTable) +{ + // DBC must be already loaded using Load + if (!indexTable) + return false; + + DBCFileLoader dbc; + // Check if load was successful, only then continue + if (!dbc.Load(path.c_str(), _fileFormat)) + return false; + + // load strings from another locale dbc data + if (char* stringBlock = dbc.AutoProduceStrings(_fileFormat, _dataTable)) + _stringPool.push_back(stringBlock); + + return true; +} + +void DBCStorageBase::LoadFromDB(std::string const& path, std::string const& dbFormat, std::string const& primaryKey, char**& indexTable) +{ + _dataTableEx = DBCDatabaseLoader(path, dbFormat, primaryKey, _fileFormat).Load(_indexTableSize, indexTable); +} diff --git a/src/server/shared/DataStores/DBCStore.h b/src/server/shared/DataStores/DBCStore.h index 48714fa7665..c6803b9143b 100644 --- a/src/server/shared/DataStores/DBCStore.h +++ b/src/server/shared/DataStores/DBCStore.h @@ -19,304 +19,83 @@ #ifndef DBCSTORE_H #define DBCSTORE_H -#include "DBCFileLoader.h" +#include "Common.h" #include "DBStorageIterator.h" -#include "Log.h" -#include "Field.h" -#include "DatabaseWorkerPool.h" -#include "Implementation/WorldDatabase.h" -#include "DatabaseEnv.h" +#include -struct SqlDbc + /// Interface class for common access +class TC_SHARED_API DBCStorageBase { - std::string const* formatString; - std::string const* indexName; - std::string sqlTableName; - int32 indexPos; - int32 sqlIndexPos; - SqlDbc(std::string const* _filename, std::string const* _format, std::string const* _idname, char const* fmt) - : formatString(_format), indexName (_idname), sqlIndexPos(0) - { - // Convert dbc file name to sql table name - sqlTableName = *_filename; - for (uint32 i = 0; i< sqlTableName.size(); ++i) - { - if (isalpha(sqlTableName[i])) - sqlTableName[i] = char(tolower(sqlTableName[i])); - else if (sqlTableName[i] == '.') - sqlTableName[i] = '_'; - } + public: + DBCStorageBase(char const* fmt); + virtual ~DBCStorageBase(); - // Get sql index position - DBCFileLoader::GetFormatRecordSize(fmt, &indexPos); - if (indexPos >= 0) - { - uint32 uindexPos = uint32(indexPos); - for (uint32 x = 0; x < formatString->size(); ++x) - { - // Count only fields present in sql - if ((*formatString)[x] == FT_SQL_PRESENT) - { - if (x == uindexPos) - break; - ++sqlIndexPos; - } - } - } - } + char const* GetFormat() const { return _fileFormat; } + uint32 GetFieldCount() const { return _fieldCount; } -private: - SqlDbc(SqlDbc const& right) = delete; - SqlDbc& operator=(SqlDbc const& right) = delete; + virtual bool Load(std::string const& path) = 0; + virtual bool LoadStringsFrom(std::string const& path) = 0; + virtual void LoadFromDB(std::string const& path, std::string const& dbFormat, std::string const& primaryKey) = 0; + + protected: + bool Load(std::string const& path, char**& indexTable); + bool LoadStringsFrom(std::string const& path, char**& indexTable); + void LoadFromDB(std::string const& path, std::string const& dbFormat, std::string const& primaryKey, char**& indexTable); + + uint32 _fieldCount; + char const* _fileFormat; + char* _dataTable; + char* _dataTableEx; + std::vector _stringPool; + uint32 _indexTableSize; }; -template -class DBCStorage +template +class DBCStorage : public DBCStorageBase { - typedef std::list StringPoolList; - public: typedef DBStorageIterator iterator; - explicit DBCStorage(char const* f) - : fmt(f), nCount(0), fieldCount(0), dataTable(NULL) + explicit DBCStorage(char const* fmt) : DBCStorageBase(fmt) { - indexTable.asT = NULL; + _indexTable.AsT = nullptr; } - ~DBCStorage() { Clear(); } - - T const* LookupEntry(uint32 id) const + ~DBCStorage() { - return (id >= nCount) ? NULL : indexTable.asT[id]; + delete[] reinterpret_cast(_indexTable.AsT); } - T const* AssertEntry(uint32 id) const + T const* LookupEntry(uint32 id) const { return (id >= _indexTableSize) ? nullptr : _indexTable.AsT[id]; } + T const* AssertEntry(uint32 id) const { return ASSERT_NOTNULL(LookupEntry(id)); } + + uint32 GetNumRows() const { return _indexTableSize; } + + bool Load(std::string const& path) override { - T const* entry = LookupEntry(id); - ASSERT(entry); - return entry; + return DBCStorageBase::Load(path, _indexTable.AsChar); } - uint32 GetNumRows() const { return nCount; } - char const* GetFormat() const { return fmt; } - uint32 GetFieldCount() const { return fieldCount; } - - bool Load(char const* fn, SqlDbc* sql) + bool LoadStringsFrom(std::string const& path) override { - DBCFileLoader dbc; - // Check if load was sucessful, only then continue - if (!dbc.Load(fn, fmt)) - return false; - - uint32 sqlRecordCount = 0; - uint32 sqlHighestIndex = 0; - Field* fields = NULL; - QueryResult result = QueryResult(NULL); - // Load data from sql - if (sql) - { - std::string query = "SELECT * FROM " + sql->sqlTableName; - if (sql->indexPos >= 0) - query +=" ORDER BY " + *sql->indexName + " DESC"; - query += ';'; - - - result = WorldDatabase.Query(query.c_str()); - if (result) - { - sqlRecordCount = uint32(result->GetRowCount()); - if (sql->indexPos >= 0) - { - fields = result->Fetch(); - sqlHighestIndex = fields[sql->sqlIndexPos].GetUInt32(); - } - - // Check if sql index pos is valid - if (int32(result->GetFieldCount() - 1) < sql->sqlIndexPos) - { - TC_LOG_ERROR("server.loading", "Invalid index pos for dbc:'%s'", sql->sqlTableName.c_str()); - return false; - } - } - } - - char* sqlDataTable = NULL; - fieldCount = dbc.GetCols(); - - dataTable = reinterpret_cast(dbc.AutoProduceData(fmt, nCount, indexTable.asChar, - sqlRecordCount, sqlHighestIndex, sqlDataTable)); - - stringPoolList.push_back(dbc.AutoProduceStrings(fmt, reinterpret_cast(dataTable))); - - // Insert sql data into arrays - if (result) - { - if (indexTable.asT) - { - uint32 offset = 0; - uint32 rowIndex = dbc.GetNumRows(); - do - { - if (!fields) - fields = result->Fetch(); - - if (sql->indexPos >= 0) - { - uint32 id = fields[sql->sqlIndexPos].GetUInt32(); - if (indexTable.asT[id]) - { - TC_LOG_ERROR("server.loading", "Index %d already exists in dbc:'%s'", id, sql->sqlTableName.c_str()); - return false; - } - - indexTable.asT[id] = reinterpret_cast(&sqlDataTable[offset]); - } - else - indexTable.asT[rowIndex]= reinterpret_cast(&sqlDataTable[offset]); - - uint32 columnNumber = 0; - uint32 sqlColumnNumber = 0; - - for (; columnNumber < sql->formatString->size(); ++columnNumber) - { - if ((*sql->formatString)[columnNumber] == FT_SQL_ABSENT) - { - switch (fmt[columnNumber]) - { - case FT_FLOAT: - *reinterpret_cast(&sqlDataTable[offset]) = 0.0f; - offset += 4; - break; - case FT_IND: - case FT_INT: - *reinterpret_cast(&sqlDataTable[offset]) = uint32(0); - offset += 4; - break; - case FT_BYTE: - *reinterpret_cast(&sqlDataTable[offset]) = uint8(0); - offset += 1; - break; - case FT_LONG: - *reinterpret_cast(&sqlDataTable[offset]) = uint64(0); - offset += 8; - break; - case FT_STRING: - // Beginning of the pool - empty string - *reinterpret_cast(&sqlDataTable[offset]) = stringPoolList.back(); - offset += sizeof(char*); - break; - } - } - else if ((*sql->formatString)[columnNumber] == FT_SQL_PRESENT) - { - bool validSqlColumn = true; - switch (fmt[columnNumber]) - { - case FT_FLOAT: - *reinterpret_cast(&sqlDataTable[offset]) = fields[sqlColumnNumber].GetFloat(); - offset += 4; - break; - case FT_IND: - case FT_INT: - *reinterpret_cast(&sqlDataTable[offset]) = fields[sqlColumnNumber].GetUInt32(); - offset += 4; - break; - case FT_BYTE: - *reinterpret_cast(&sqlDataTable[offset]) = fields[sqlColumnNumber].GetUInt8(); - offset += 1; - break; - case FT_LONG: - *reinterpret_cast(&sqlDataTable[offset]) = fields[sqlColumnNumber].GetUInt64(); - offset += 8; - break; - case FT_STRING: - TC_LOG_ERROR("server.loading", "Unsupported data type in table '%s' at char %d", sql->sqlTableName.c_str(), columnNumber); - return false; - case FT_SORT: - break; - default: - validSqlColumn = false; - break; - } - if (validSqlColumn && (columnNumber != (sql->formatString->size()-1))) - sqlColumnNumber++; - } - else - { - TC_LOG_ERROR("server.loading", "Incorrect sql format string '%s' at char %d", sql->sqlTableName.c_str(), columnNumber); - return false; - } - } - - if (sqlColumnNumber != (result->GetFieldCount() - 1)) - { - TC_LOG_ERROR("server.loading", "SQL and DBC format strings are not matching for table: '%s'", sql->sqlTableName.c_str()); - return false; - } - - fields = NULL; - ++rowIndex; - } while (result->NextRow()); - } - } - - // error in dbc file at loading if NULL - return indexTable.asT != NULL; + return DBCStorageBase::LoadStringsFrom(path, _indexTable.AsChar); } - bool LoadStringsFrom(char const* fn) + void LoadFromDB(std::string const& path, std::string const& dbFormat, std::string const& primaryKey) override { - // DBC must be already loaded using Load - if (!indexTable.asT) - return false; - - DBCFileLoader dbc; - // Check if load was successful, only then continue - if (!dbc.Load(fn, fmt)) - return false; - - stringPoolList.push_back(dbc.AutoProduceStrings(fmt, reinterpret_cast(dataTable))); - - return true; + DBCStorageBase::LoadFromDB(path, dbFormat, primaryKey, _indexTable.AsChar); } - void Clear() - { - if (!indexTable.asT) - return; - - delete[] reinterpret_cast(indexTable.asT); - indexTable.asT = NULL; - delete[] reinterpret_cast(dataTable); - dataTable = NULL; - - while (!stringPoolList.empty()) - { - delete[] stringPoolList.front(); - stringPoolList.pop_front(); - } - - nCount = 0; - } - - iterator begin() { return iterator(indexTable.asT, nCount); } - iterator end() { return iterator(indexTable.asT, nCount, nCount); } + iterator begin() { return iterator(_indexTable.AsT, _indexTableSize); } + iterator end() { return iterator(_indexTable.AsT, _indexTableSize, _indexTableSize); } private: - char const* fmt; - uint32 nCount; - uint32 fieldCount; - union { - T** asT; - char** asChar; + T** AsT; + char** AsChar; } - indexTable; - - T* dataTable; - StringPoolList stringPoolList; + _indexTable; DBCStorage(DBCStorage const& right) = delete; DBCStorage& operator=(DBCStorage const& right) = delete; diff --git a/src/server/shared/Dynamic/LinkedReference/Reference.h b/src/server/shared/Dynamic/LinkedReference/Reference.h index 9f9805d71fe..71c6451a788 100644 --- a/src/server/shared/Dynamic/LinkedReference/Reference.h +++ b/src/server/shared/Dynamic/LinkedReference/Reference.h @@ -40,16 +40,16 @@ template class Reference : public LinkedListElement // Tell our refFrom (source) object, that the link is cut (Target destroyed) virtual void sourceObjectDestroyLink() = 0; public: - Reference() { iRefTo = NULL; iRefFrom = NULL; } + Reference() { iRefTo = nullptr; iRefFrom = nullptr; } virtual ~Reference() { } // Create new link void link(TO* toObj, FROM* fromObj) { - ASSERT(fromObj); // fromObj MUST not be NULL + ASSERT(fromObj); // fromObj MUST not be nullptr if (isValid()) unlink(); - if (toObj != NULL) + if (toObj != nullptr) { iRefTo = toObj; iRefFrom = fromObj; @@ -63,8 +63,8 @@ template class Reference : public LinkedListElement { targetObjectDestroyLink(); delink(); - iRefTo = NULL; - iRefFrom = NULL; + iRefTo = nullptr; + iRefFrom = nullptr; } // Link is invalid due to destruction of referenced target object. Call comes from the refTo object @@ -73,12 +73,12 @@ template class Reference : public LinkedListElement { sourceObjectDestroyLink(); delink(); - iRefTo = NULL; + iRefTo = nullptr; } bool isValid() const // Only check the iRefTo { - return iRefTo != NULL; + return iRefTo != nullptr; } Reference * next() { return((Reference *) LinkedListElement::next()); } diff --git a/src/server/shared/Dynamic/TypeContainer.h b/src/server/shared/Dynamic/TypeContainer.h index bea05adf59f..bac45eab6e2 100644 --- a/src/server/shared/Dynamic/TypeContainer.h +++ b/src/server/shared/Dynamic/TypeContainer.h @@ -86,14 +86,14 @@ template class TypeMapContainer { public: - template size_t Count() const { return Trinity::Count(i_elements, (SPECIFIC_TYPE*)NULL); } + template size_t Count() const { return Trinity::Count(i_elements, (SPECIFIC_TYPE*)nullptr); } /// inserts a specific object into the container template bool insert(SPECIFIC_TYPE *obj) { SPECIFIC_TYPE* t = Trinity::Insert(i_elements, obj); - return (t != NULL); + return (t != nullptr); } /// Removes the object from the container, and returns the removed object @@ -101,7 +101,7 @@ class TypeMapContainer //bool remove(SPECIFIC_TYPE* obj) //{ // SPECIFIC_TYPE* t = Trinity::Remove(i_elements, obj); - // return (t != NULL); + // return (t != nullptr); //} ContainerMapList & GetElements(void) { return i_elements; } diff --git a/src/server/shared/Networking/AsyncAcceptor.h b/src/server/shared/Networking/AsyncAcceptor.h index 4251a0868b3..e903f4297e3 100644 --- a/src/server/shared/Networking/AsyncAcceptor.h +++ b/src/server/shared/Networking/AsyncAcceptor.h @@ -18,21 +18,29 @@ #ifndef __ASYNCACCEPT_H_ #define __ASYNCACCEPT_H_ +#include "IoContext.h" +#include "IpAddress.h" #include "Log.h" -#include +#include #include #include using boost::asio::ip::tcp; +#if BOOST_VERSION >= 106600 +#define TRINITY_MAX_LISTEN_CONNECTIONS boost::asio::socket_base::max_listen_connections +#else +#define TRINITY_MAX_LISTEN_CONNECTIONS boost::asio::socket_base::max_connections +#endif + class AsyncAcceptor { public: typedef void(*AcceptCallback)(tcp::socket&& newSocket, uint32 threadIndex); - AsyncAcceptor(boost::asio::io_service& ioService, std::string const& bindIp, uint16 port) : - _acceptor(ioService), _endpoint(boost::asio::ip::address::from_string(bindIp), port), - _socket(ioService), _closed(false), _socketFactory(std::bind(&AsyncAcceptor::DefeaultSocketFactory, this)) + AsyncAcceptor(Trinity::Asio::IoContext& ioContext, std::string const& bindIp, uint16 port) : + _acceptor(ioContext), _endpoint(Trinity::Net::make_address(bindIp), port), + _socket(ioContext), _closed(false), _socketFactory(std::bind(&AsyncAcceptor::DefeaultSocketFactory, this)) { } @@ -82,7 +90,7 @@ public: return false; } - _acceptor.listen(boost::asio::socket_base::max_connections, errorCode); + _acceptor.listen(TRINITY_MAX_LISTEN_CONNECTIONS, errorCode); if (errorCode) { TC_LOG_INFO("network", "Failed to start listening on %s:%u %s", _endpoint.address().to_string().c_str(), _endpoint.port(), errorCode.message().c_str()); diff --git a/src/server/shared/Networking/NetworkThread.h b/src/server/shared/Networking/NetworkThread.h index e384e1515ae..2f032a20247 100644 --- a/src/server/shared/Networking/NetworkThread.h +++ b/src/server/shared/Networking/NetworkThread.h @@ -20,6 +20,7 @@ #include "Define.h" #include "Errors.h" +#include "IoContext.h" #include "Log.h" #include "Timer.h" #include @@ -37,8 +38,8 @@ template class NetworkThread { public: - NetworkThread() : _connections(0), _stopped(false), _thread(nullptr), _io_service(1), - _acceptSocket(_io_service), _updateTimer(_io_service) + NetworkThread() : _connections(0), _stopped(false), _thread(nullptr), _ioContext(1), + _acceptSocket(_ioContext), _updateTimer(_ioContext) { } @@ -55,7 +56,7 @@ public: void Stop() { _stopped = true; - _io_service.stop(); + _ioContext.stop(); } bool Start() @@ -123,7 +124,7 @@ protected: _updateTimer.expires_from_now(boost::posix_time::milliseconds(10)); _updateTimer.async_wait(std::bind(&NetworkThread::Update, this)); - _io_service.run(); + _ioContext.run(); TC_LOG_DEBUG("misc", "Network Thread exits"); _newSockets.clear(); @@ -170,7 +171,7 @@ private: std::mutex _newSocketsLock; SocketContainer _newSockets; - boost::asio::io_service _io_service; + Trinity::Asio::IoContext _ioContext; tcp::socket _acceptSocket; boost::asio::deadline_timer _updateTimer; }; diff --git a/src/server/shared/Networking/SocketMgr.h b/src/server/shared/Networking/SocketMgr.h index e0ae87d908e..0795ede3394 100644 --- a/src/server/shared/Networking/SocketMgr.h +++ b/src/server/shared/Networking/SocketMgr.h @@ -35,14 +35,14 @@ public: 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, int threadCount) + virtual bool StartNetwork(Trinity::Asio::IoContext& ioContext, std::string const& bindIp, uint16 port, int threadCount) { ASSERT(threadCount > 0); AsyncAcceptor* acceptor = nullptr; try { - acceptor = new AsyncAcceptor(service, bindIp, port); + acceptor = new AsyncAcceptor(ioContext, bindIp, port); } catch (boost::system::system_error const& err) { diff --git a/src/server/shared/Packets/ByteBuffer.cpp b/src/server/shared/Packets/ByteBuffer.cpp index 99a5df18b0a..9f9f06704dc 100644 --- a/src/server/shared/Packets/ByteBuffer.cpp +++ b/src/server/shared/Packets/ByteBuffer.cpp @@ -17,10 +17,13 @@ */ #include "ByteBuffer.h" +#include "Errors.h" #include "MessageBuffer.h" #include "Common.h" #include "Log.h" +#include "Util.h" #include +#include ByteBuffer::ByteBuffer(MessageBuffer&& buffer) : _rpos(0), _wpos(0), _bitpos(InitialBitPos), _curbitval(0), _storage(buffer.Move()) { @@ -44,12 +47,86 @@ ByteBufferSourceException::ByteBufferSourceException(size_t pos, size_t size, std::ostringstream ss; ss << "Attempted to put a " - << (valueSize > 0 ? "NULL-pointer" : "zero-sized value") + << (valueSize > 0 ? "nullptr-pointer" : "zero-sized value") << " in ByteBuffer (pos: " << pos << " size: " << size << ")"; message().assign(ss.str()); } +ByteBuffer& ByteBuffer::operator>>(float& value) +{ + value = read(); + if (!std::isfinite(value)) + throw ByteBufferException(); + return *this; +} + +ByteBuffer& ByteBuffer::operator>>(double& value) +{ + value = read(); + if (!std::isfinite(value)) + throw ByteBufferException(); + return *this; +} + +uint32 ByteBuffer::ReadPackedTime() +{ + uint32 packedDate = read(); + tm lt = tm(); + + lt.tm_min = packedDate & 0x3F; + lt.tm_hour = (packedDate >> 6) & 0x1F; + //lt.tm_wday = (packedDate >> 11) & 7; + lt.tm_mday = ((packedDate >> 14) & 0x3F) + 1; + lt.tm_mon = (packedDate >> 20) & 0xF; + lt.tm_year = ((packedDate >> 24) & 0x1F) + 100; + + return uint32(mktime(<)); +} + +void ByteBuffer::append(uint8 const* src, size_t cnt) +{ + ASSERT(src, "Attempted to put a NULL-pointer in ByteBuffer (pos: " SZFMTD " size: " SZFMTD ")", _wpos, size()); + ASSERT(cnt, "Attempted to put a zero-sized value in ByteBuffer (pos: " SZFMTD " size: " SZFMTD ")", _wpos, size()); + ASSERT(size() < 10000000); + + FlushBits(); + + size_t const newSize = _wpos + cnt; + if (_storage.capacity() < newSize) // custom memory allocation rules + { + if (newSize < 100) + _storage.reserve(300); + else if (newSize < 750) + _storage.reserve(2500); + else if (newSize < 6000) + _storage.reserve(10000); + else + _storage.reserve(400000); + } + + if (_storage.size() < newSize) + _storage.resize(newSize); + std::memcpy(&_storage[_wpos], src, cnt); + _wpos = newSize; +} + +void ByteBuffer::AppendPackedTime(time_t time) +{ + tm lt; + localtime_r(&time, <); + append((lt.tm_year - 100) << 24 | lt.tm_mon << 20 | (lt.tm_mday - 1) << 14 | lt.tm_wday << 11 | lt.tm_hour << 6 | lt.tm_min); +} + +void ByteBuffer::put(size_t pos, uint8 const* src, size_t cnt) +{ + ASSERT(pos + cnt <= size(), "Attempted to put value with size: " SZFMTD " in ByteBuffer (pos: " SZFMTD " size: " SZFMTD ")", cnt, pos, size()); + ASSERT(src, "Attempted to put a NULL-pointer in ByteBuffer (pos: " SZFMTD " size: " SZFMTD ")", pos, size()); + ASSERT(cnt, "Attempted to put a zero-sized value in ByteBuffer (pos: " SZFMTD " size: " SZFMTD ")", pos, size()); + + std::memcpy(&_storage[pos], src, cnt); +} + void ByteBuffer::print_storage() const { if (!sLog->ShouldLog("network", LOG_LEVEL_TRACE)) // optimize disabled trace output diff --git a/src/server/shared/Packets/ByteBuffer.h b/src/server/shared/Packets/ByteBuffer.h index da10cb9199f..a4e8e14eef1 100644 --- a/src/server/shared/Packets/ByteBuffer.h +++ b/src/server/shared/Packets/ByteBuffer.h @@ -20,10 +20,9 @@ #define _BYTEBUFFER_H #include "Define.h" -#include "Errors.h" #include "ByteConverter.h" -#include "Util.h" - +#include +#include #include class MessageBuffer; @@ -181,7 +180,8 @@ class TC_SHARED_API ByteBuffer append(b ^ 1); } - template void put(size_t pos, T value) + template + void put(std::size_t pos, T value) { static_assert(std::is_fundamental::value, "append(compound)"); EndianConvert(value); @@ -352,21 +352,8 @@ class TC_SHARED_API ByteBuffer return *this; } - ByteBuffer &operator>>(float &value) - { - value = read(); - if (!std::isfinite(value)) - throw ByteBufferException(); - return *this; - } - - ByteBuffer &operator>>(double &value) - { - value = read(); - if (!std::isfinite(value)) - throw ByteBufferException(); - return *this; - } + ByteBuffer& operator>>(float& value); + ByteBuffer& operator>>(double& value); ByteBuffer &operator>>(std::string& value) { @@ -503,20 +490,7 @@ class TC_SHARED_API ByteBuffer append(str.c_str(), len); } - uint32 ReadPackedTime() - { - uint32 packedDate = read(); - tm lt = tm(); - - lt.tm_min = packedDate & 0x3F; - lt.tm_hour = (packedDate >> 6) & 0x1F; - //lt.tm_wday = (packedDate >> 11) & 7; - lt.tm_mday = ((packedDate >> 14) & 0x3F) + 1; - lt.tm_mon = (packedDate >> 20) & 0xF; - lt.tm_year = ((packedDate >> 24) & 0x1F) + 100; - - return uint32(mktime(<)); - } + uint32 ReadPackedTime(); ByteBuffer& ReadPackedTime(uint32& time) { @@ -564,36 +538,7 @@ class TC_SHARED_API ByteBuffer return append((const uint8 *)src, cnt * sizeof(T)); } - void append(const uint8 *src, size_t cnt) - { - if (!cnt) - throw ByteBufferSourceException(_wpos, size(), cnt); - - if (!src) - throw ByteBufferSourceException(_wpos, size(), cnt); - - ASSERT(size() < 10000000); - - FlushBits(); - - size_t const newSize = _wpos + cnt; - if (_storage.capacity() < newSize) // custom memory allocation rules - { - if (newSize < 100) - _storage.reserve(300); - else if (newSize < 750) - _storage.reserve(2500); - else if (newSize < 6000) - _storage.reserve(10000); - else - _storage.reserve(400000); - } - - if (_storage.size() < newSize) - _storage.resize(newSize); - std::memcpy(&_storage[_wpos], src, cnt); - _wpos = newSize; - } + void append(uint8 const* src, size_t cnt); void append(const ByteBuffer& buffer) { @@ -630,23 +575,9 @@ class TC_SHARED_API ByteBuffer append(packGUID, size); } - void AppendPackedTime(time_t time) - { - tm lt; - localtime_r(&time, <); - append((lt.tm_year - 100) << 24 | lt.tm_mon << 20 | (lt.tm_mday - 1) << 14 | lt.tm_wday << 11 | lt.tm_hour << 6 | lt.tm_min); - } + void AppendPackedTime(time_t time); - void put(size_t pos, const uint8 *src, size_t cnt) - { - if (pos + cnt > size()) - throw ByteBufferPositionException(true, pos, cnt, size()); - - if (!src) - throw ByteBufferSourceException(_wpos, size(), cnt); - - std::memcpy(&_storage[pos], src, cnt); - } + void put(size_t pos, uint8 const* src, size_t cnt); void print_storage() const; @@ -660,85 +591,6 @@ class TC_SHARED_API ByteBuffer std::vector _storage; }; -template -inline ByteBuffer &operator<<(ByteBuffer &b, std::vector v) -{ - b << (uint32)v.size(); - for (typename std::vector::iterator i = v.begin(); i != v.end(); ++i) - { - b << *i; - } - return b; -} - -template -inline ByteBuffer &operator>>(ByteBuffer &b, std::vector &v) -{ - uint32 vsize; - b >> vsize; - v.clear(); - while (vsize--) - { - T t; - b >> t; - v.push_back(t); - } - return b; -} - -template -inline ByteBuffer &operator<<(ByteBuffer &b, std::list v) -{ - b << (uint32)v.size(); - for (typename std::list::iterator i = v.begin(); i != v.end(); ++i) - { - b << *i; - } - return b; -} - -template -inline ByteBuffer &operator>>(ByteBuffer &b, std::list &v) -{ - uint32 vsize; - b >> vsize; - v.clear(); - while (vsize--) - { - T t; - b >> t; - v.push_back(t); - } - return b; -} - -template -inline ByteBuffer &operator<<(ByteBuffer &b, std::map &m) -{ - b << (uint32)m.size(); - for (typename std::map::iterator i = m.begin(); i != m.end(); ++i) - { - b << i->first << i->second; - } - return b; -} - -template -inline ByteBuffer &operator>>(ByteBuffer &b, std::map &m) -{ - uint32 msize; - b >> msize; - m.clear(); - while (msize--) - { - K k; - V v; - b >> k >> v; - m.insert(make_pair(k, v)); - } - return b; -} - /// @todo Make a ByteBuffer.cpp and move all this inlining to it. template<> inline std::string ByteBuffer::read() { diff --git a/src/server/shared/PrecompiledHeaders/sharedPCH.cpp b/src/server/shared/PrecompiledHeaders/sharedPCH.cpp deleted file mode 100644 index 36eb3a877f0..00000000000 --- a/src/server/shared/PrecompiledHeaders/sharedPCH.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "sharedPCH.h" diff --git a/src/server/shared/PrecompiledHeaders/sharedPCH.h b/src/server/shared/PrecompiledHeaders/sharedPCH.h index f864674d5ad..10bdd371ed9 100644 --- a/src/server/shared/PrecompiledHeaders/sharedPCH.h +++ b/src/server/shared/PrecompiledHeaders/sharedPCH.h @@ -1,4 +1,28 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + //add here most rarely modified headers to speed up debug build compilation -#include "TypeList.h" -#include "GitRevision.h" +#include "Common.h" +#include "Define.h" +#include "Errors.h" +#include "Log.h" +#include +#include +#include +#include +#include diff --git a/src/server/shared/Realm/Realm.cpp b/src/server/shared/Realm/Realm.cpp index 7c1fe1fcb61..766e4b5328e 100644 --- a/src/server/shared/Realm/Realm.cpp +++ b/src/server/shared/Realm/Realm.cpp @@ -16,7 +16,11 @@ */ #include "Realm.h" -boost::asio::ip::tcp::endpoint Realm::GetAddressForClient(boost::asio::ip::address const& clientAddr) const +#include "IpAddress.h" +#include "IpNetwork.h" +#include + +boost::asio::ip::tcp_endpoint Realm::GetAddressForClient(boost::asio::ip::address const& clientAddr) const { boost::asio::ip::address realmIp; @@ -24,31 +28,25 @@ boost::asio::ip::tcp::endpoint Realm::GetAddressForClient(boost::asio::ip::addre if (clientAddr.is_loopback()) { // Try guessing if realm is also connected locally - if (LocalAddress.is_loopback() || ExternalAddress.is_loopback()) + 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; + 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; - } + if (clientAddr.is_v4() && Trinity::Net::IsInNetwork(LocalAddress->to_v4(), LocalSubnetMask->to_v4(), clientAddr.to_v4())) + realmIp = *LocalAddress; else - realmIp = ExternalAddress; + realmIp = *ExternalAddress; } - boost::asio::ip::tcp::endpoint endpoint(realmIp, Port); - // Return external IP - return endpoint; + return boost::asio::ip::tcp_endpoint(realmIp, Port); } uint32 Realm::GetConfigId() const diff --git a/src/server/shared/Realm/Realm.h b/src/server/shared/Realm/Realm.h index 2605474ac5b..35a71c00151 100644 --- a/src/server/shared/Realm/Realm.h +++ b/src/server/shared/Realm/Realm.h @@ -19,8 +19,7 @@ #define Realm_h__ #include "Common.h" -#include -#include +#include "AsioHacksFwd.h" enum RealmFlags { @@ -80,9 +79,9 @@ struct TC_SHARED_API Realm { Battlenet::RealmHandle Id; uint32 Build; - boost::asio::ip::address ExternalAddress; - boost::asio::ip::address LocalAddress; - boost::asio::ip::address LocalSubnetMask; + std::unique_ptr ExternalAddress; + std::unique_ptr LocalAddress; + std::unique_ptr LocalSubnetMask; uint16 Port; std::string Name; uint8 Type; @@ -93,7 +92,7 @@ struct TC_SHARED_API Realm bool Updated; bool Keep; - boost::asio::ip::tcp::endpoint GetAddressForClient(boost::asio::ip::address const& clientAddr) const; + boost::asio::ip::tcp_endpoint GetAddressForClient(boost::asio::ip::address const& clientAddr) const; uint32 GetConfigId() const; static uint32 const ConfigIdByType[MAX_CLIENT_REALM_TYPE]; diff --git a/src/server/shared/Realm/RealmList.h b/src/server/shared/Realm/RealmList.h deleted file mode 100644 index d55be284d60..00000000000 --- a/src/server/shared/Realm/RealmList.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2008-2018 TrinityCore - * Copyright (C) 2005-2009 MaNGOS - * - * 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 . - */ - -#ifndef _REALMLIST_H -#define _REALMLIST_H - -#include "Common.h" -#include "Realm/Realm.h" -#include -#include -#include -#include - -/// Storage object for the list of realms on the server -class TC_SHARED_API RealmList -{ -public: - typedef std::map 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(Battlenet::RealmHandle const& id) const; - -private: - RealmList(); - - void UpdateRealms(boost::system::error_code const& error); - void UpdateRealm(Battlenet::RealmHandle const& id, uint32 build, const std::string& name, boost::asio::ip::address const& address, boost::asio::ip::address const& localAddr, - boost::asio::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 15aa1efc1f2..bbfaa21f5ab 100644 --- a/src/server/worldserver/CMakeLists.txt +++ b/src/server/worldserver/CMakeLists.txt @@ -23,10 +23,6 @@ endif() if (USE_COREPCH) set(PRIVATE_PCH_HEADER PrecompiledHeaders/worldPCH.h) - set(PRIVATE_PCH_SOURCE PrecompiledHeaders/worldPCH.cpp) - if (MSVC) - list(INSERT PRIVATE_SOURCES 0 PrecompiledHeaders/worldPCH.cpp) - endif (MSVC) endif() GroupSources(${CMAKE_CURRENT_SOURCE_DIR}) @@ -48,6 +44,8 @@ endif() set_target_properties(worldserver PROPERTIES LINK_FLAGS "${worldserver_LINK_FLAGS}") target_link_libraries(worldserver + PRIVATE + trinity-core-interface PUBLIC scripts game @@ -104,5 +102,5 @@ endif() # Generate precompiled header if( USE_COREPCH ) - add_cxx_pch(worldserver ${PRIVATE_PCH_HEADER} ${PRIVATE_PCH_SOURCE}) + add_cxx_pch(worldserver ${PRIVATE_PCH_HEADER}) endif() diff --git a/src/server/worldserver/CommandLine/CliRunnable.cpp b/src/server/worldserver/CommandLine/CliRunnable.cpp index 4e6f52616c0..840fcfcb63e 100644 --- a/src/server/worldserver/CommandLine/CliRunnable.cpp +++ b/src/server/worldserver/CommandLine/CliRunnable.cpp @@ -34,10 +34,10 @@ #include #include "Chat.h" -char* command_finder(const char* text, int state) +char* command_finder(char const* text, int state) { static size_t idx, len; - const char* ret; + char const* ret; std::vector const& cmd = ChatHandler::getCommandTable(); if (!state) @@ -61,12 +61,12 @@ char* command_finder(const char* text, int state) return strdup(ret); } - return ((char*)NULL); + return ((char*)nullptr); } -char** cli_completion(const char* text, int start, int /*end*/) +char** cli_completion(char const* text, int start, int /*end*/) { - char** matches = NULL; + char** matches = nullptr; if (start) rl_bind_key('\t', rl_abort); @@ -84,7 +84,7 @@ int cli_hook_func() #endif -void utf8print(void* /*arg*/, const char* str) +void utf8print(void* /*arg*/, char const* str) { #if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS wchar_t wtemp_buf[6000]; @@ -119,7 +119,7 @@ int kb_hit_return() tv.tv_usec = 0; FD_ZERO(&fds); FD_SET(STDIN_FILENO, &fds); - select(STDIN_FILENO+1, &fds, NULL, NULL, &tv); + select(STDIN_FILENO+1, &fds, nullptr, nullptr, &tv); return FD_ISSET(STDIN_FILENO, &fds); } #endif @@ -156,7 +156,7 @@ void CliThread() rl_bind_key('\t', rl_complete); #endif - if (command_str != NULL) + if (command_str != nullptr) { for (int x=0; command_str[x]; ++x) if (command_str[x] == '\r' || command_str[x] == '\n') @@ -187,7 +187,7 @@ void CliThread() } fflush(stdout); - sWorld->QueueCliCommand(new CliCommandHolder(NULL, command.c_str(), &utf8print, &commandFinished)); + sWorld->QueueCliCommand(new CliCommandHolder(nullptr, command.c_str(), &utf8print, &commandFinished)); #if TRINITY_PLATFORM != TRINITY_PLATFORM_WINDOWS add_history(command.c_str()); free(command_str); diff --git a/src/server/worldserver/Main.cpp b/src/server/worldserver/Main.cpp index fa4ab6a4631..99d074bd6f9 100644 --- a/src/server/worldserver/Main.cpp +++ b/src/server/worldserver/Main.cpp @@ -21,39 +21,48 @@ /// \file #include "Common.h" -#include "Commands.h" -#include "ZmqContext.h" -#include "DatabaseEnv.h" +#include "AppenderDB.h" #include "AsyncAcceptor.h" -#include "RASession.h" -#include "Configuration/Config.h" -#include "OpenSSLCrypto.h" -#include "ProcessPriority.h" +#include "Banner.h" +#include "BattlegroundMgr.h" +#include "BattlenetServerManager.h" #include "BigNumber.h" -#include "World.h" -#include "MapManager.h" +#include "CliRunnable.h" +#include "Configuration/Config.h" +#include "DatabaseEnv.h" +#include "DatabaseLoader.h" +#include "GitRevision.h" #include "InstanceSaveMgr.h" +#include "IoContext.h" +#include "MapManager.h" +#include "Metric.h" +#include "MySQLThreading.h" #include "ObjectAccessor.h" +#include "OpenSSLCrypto.h" +#include "OutdoorPvP/OutdoorPvPMgr.h" +#include "ProcessPriority.h" +#include "RASession.h" +#include "Resolver.h" +#include "ScriptLoader.h" #include "ScriptMgr.h" #include "ScriptReloadMgr.h" -#include "ScriptLoader.h" -#include "OutdoorPvP/OutdoorPvPMgr.h" -#include "BattlegroundMgr.h" #include "TCSoap.h" -#include "CliRunnable.h" -#include "GitRevision.h" +#include "World.h" #include "WorldSocket.h" #include "WorldSocketMgr.h" -#include "BattlenetServerManager.h" -#include "DatabaseLoader.h" -#include "AppenderDB.h" -#include "Metric.h" +#include "ZmqContext.h" #include #include -#include #include -#include +#include +#include #include +#include +#include + +#ifdef _WIN32 // ugly as hell +#pragma comment(lib, "iphlpapi.lib") +#endif using namespace boost::program_options; namespace fs = boost::filesystem; @@ -81,8 +90,8 @@ int m_ServiceStatus = -1; class FreezeDetector { public: - FreezeDetector(boost::asio::io_service& ioService, uint32 maxCoreStuckTime) - : _timer(ioService), _worldLoopCounter(0), _lastChangeMsTime(0), _maxCoreStuckTimeInMs(maxCoreStuckTime) { } + FreezeDetector(Trinity::Asio::IoContext& ioContext, uint32 maxCoreStuckTime) + : _timer(ioContext), _worldLoopCounter(0), _lastChangeMsTime(0), _maxCoreStuckTimeInMs(maxCoreStuckTime) { } static void Start(std::shared_ptr const& freezeDetector) { @@ -101,13 +110,13 @@ class FreezeDetector void SignalHandler(boost::system::error_code const& error, int signalNumber); -AsyncAcceptor* StartRaSocketAcceptor(boost::asio::io_service& ioService); +AsyncAcceptor* StartRaSocketAcceptor(Trinity::Asio::IoContext& ioContext); bool StartDB(); void StopDB(); void WorldUpdateLoop(); void ClearOnlineAccounts(); void ShutdownCLIThread(std::thread* cliThread); -bool LoadRealmInfo(boost::asio::io_service& ioService); +bool LoadRealmInfo(Trinity::Asio::IoContext& ioContext); variables_map GetConsoleArguments(int argc, char** argv, fs::path& configFile, std::string& cfg_service); /// Launch the Trinity server @@ -141,26 +150,24 @@ extern int main(int argc, char** argv) return 1; } - std::shared_ptr ioService = std::make_shared(); + std::shared_ptr ioContext = std::make_shared(); sLog->RegisterAppender(); - // If logs are supposed to be handled async then we need to pass the io_service into the Log singleton - sLog->Initialize(sConfigMgr->GetBoolDefault("Log.Async.Enable", false) ? ioService.get() : nullptr); + // If logs are supposed to be handled async then we need to pass the IoContext into the Log singleton + sLog->Initialize(sConfigMgr->GetBoolDefault("Log.Async.Enable", false) ? ioContext.get() : nullptr); - TC_LOG_INFO("server.worldserver", "%s (worldserver-daemon)", GitRevision::GetFullVersion()); - TC_LOG_INFO("server.worldserver", " to stop.\n"); - TC_LOG_INFO("server.worldserver", " ______ __"); - TC_LOG_INFO("server.worldserver", "/\\__ _\\ __ __/\\ \\__"); - TC_LOG_INFO("server.worldserver", "\\/_/\\ \\/ _ __ /\\_\\ ___ /\\_\\ \\, _\\ __ __"); - TC_LOG_INFO("server.worldserver", " \\ \\ \\/\\`'__\\/\\ \\ /' _ `\\/\\ \\ \\ \\/ /\\ \\/\\ \\"); - TC_LOG_INFO("server.worldserver", " \\ \\ \\ \\ \\/ \\ \\ \\/\\ \\/\\ \\ \\ \\ \\ \\_\\ \\ \\_\\ \\"); - TC_LOG_INFO("server.worldserver", " \\ \\_\\ \\_\\ \\ \\_\\ \\_\\ \\_\\ \\_\\ \\__\\\\/`____ \\"); - 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.", 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); + Trinity::Banner::Show("worldserver-daemon", + [](char const* text) + { + TC_LOG_INFO("server.worldserver", "%s", text); + }, + []() + { + 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); + } + ); OpenSSLCrypto::threadsSetup(); @@ -184,8 +191,8 @@ extern int main(int argc, char** argv) } } - // Set signal handlers (this must be done before starting io_service threads, because otherwise they would unblock and exit) - boost::asio::signal_set signals(*ioService, SIGINT, SIGTERM); + // Set signal handlers (this must be done before starting IoContext threads, because otherwise they would unblock and exit) + boost::asio::signal_set signals(*ioContext, SIGINT, SIGTERM); #if TRINITY_PLATFORM == TRINITY_PLATFORM_WINDOWS signals.add(SIGBREAK); #endif @@ -193,9 +200,9 @@ extern int main(int argc, char** argv) // Start the Boost based thread pool int numThreads = sConfigMgr->GetIntDefault("ThreadPool", 1); - std::shared_ptr> threadPool(new std::vector(), [ioService](std::vector* del) + std::shared_ptr> threadPool(new std::vector(), [ioContext](std::vector* del) { - ioService->stop(); + ioContext->stop(); for (std::thread& thr : *del) thr.join(); @@ -206,10 +213,10 @@ extern int main(int argc, char** argv) numThreads = 1; for (int i = 0; i < numThreads; ++i) - threadPool->push_back(std::thread([ioService]() { ioService->run(); })); + threadPool->push_back(std::thread([ioContext]() { ioContext->run(); })); // Set process priority according to configuration settings - SetProcessPriority("server.worldserver"); + SetProcessPriority("server.worldserver", sConfigMgr->GetIntDefault(CONFIG_PROCESSOR_AFFINITY, 0), sConfigMgr->GetBoolDefault(CONFIG_HIGH_PRIORITY, false)); // Start the databases if (!StartDB()) @@ -220,9 +227,9 @@ extern int main(int argc, char** argv) // Set server offline (not connectable) LoginDatabase.DirectPExecute("UPDATE realmlist SET flag = flag | %u WHERE id = '%d'", REALM_FLAG_OFFLINE, realm.Id.Realm); - LoadRealmInfo(*ioService); + LoadRealmInfo(*ioContext); - sMetric->Initialize(realm.Name, *ioService, []() + sMetric->Initialize(realm.Name, *ioContext, []() { TC_METRIC_VALUE("online_players", sWorld->GetPlayerCount()); }); @@ -258,7 +265,7 @@ extern int main(int argc, char** argv) // Start the Remote Access port (acceptor) if enabled std::unique_ptr raAcceptor; if (sConfigMgr->GetBoolDefault("Ra.Enable", false)) - raAcceptor.reset(StartRaSocketAcceptor(*ioService)); + raAcceptor.reset(StartRaSocketAcceptor(*ioContext)); // Start soap serving thread if enabled std::shared_ptr soapThread; @@ -284,7 +291,7 @@ extern int main(int argc, char** argv) return 1; } - if (!sWorldSocketMgr.StartNetwork(*ioService, worldListener, worldPort, networkThreads)) + if (!sWorldSocketMgr.StartWorldNetwork(*ioContext, worldListener, worldPort, networkThreads)) { TC_LOG_ERROR("server.worldserver", "Failed to initialize network"); return 1; @@ -321,7 +328,7 @@ extern int main(int argc, char** argv) std::shared_ptr freezeDetector; if (int coreStuckTime = sConfigMgr->GetIntDefault("MaxCoreStuckTime", 0)) { - freezeDetector = std::make_shared(*ioService, coreStuckTime * 1000); + freezeDetector = std::make_shared(*ioContext, coreStuckTime * 1000); FreezeDetector::Start(freezeDetector); TC_LOG_INFO("server.worldserver", "Starting up anti-freeze thread (%u seconds max stuck time)...", coreStuckTime); } @@ -485,12 +492,12 @@ void FreezeDetector::Handler(std::weak_ptr freezeDetectorRef, bo } } -AsyncAcceptor* StartRaSocketAcceptor(boost::asio::io_service& ioService) +AsyncAcceptor* StartRaSocketAcceptor(Trinity::Asio::IoContext& ioContext) { uint16 raPort = uint16(sConfigMgr->GetIntDefault("Ra.Port", 3443)); std::string raListener = sConfigMgr->GetStringDefault("Ra.IP", "0.0.0.0"); - AsyncAcceptor* acceptor = new AsyncAcceptor(ioService, raListener, raPort); + AsyncAcceptor* acceptor = new AsyncAcceptor(ioContext, raListener, raPort); if (!acceptor->Bind()) { TC_LOG_ERROR("server.worldserver", "Failed to bind RA socket acceptor"); @@ -502,48 +509,42 @@ AsyncAcceptor* StartRaSocketAcceptor(boost::asio::io_service& ioService) return acceptor; } -bool LoadRealmInfo(boost::asio::io_service& ioService) +bool LoadRealmInfo(Trinity::Asio::IoContext& ioContext) { - 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; + boost::asio::ip::tcp::resolver resolver(ioContext); + Field* fields = result->Fetch(); realm.Name = fields[1].GetString(); - boost::asio::ip::tcp::resolver::query externalAddressQuery(boost::asio::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) + Optional externalAddress = Trinity::Net::Resolve(resolver, boost::asio::ip::tcp::v4(), fields[2].GetString(), ""); + if (!externalAddress) { TC_LOG_ERROR("server.worldserver", "Could not resolve address %s", fields[2].GetString().c_str()); return false; } - realm.ExternalAddress = (*endPoint).endpoint().address(); + realm.ExternalAddress = Trinity::make_unique(externalAddress->address()); - boost::asio::ip::tcp::resolver::query localAddressQuery(boost::asio::ip::tcp::v4(), fields[3].GetString(), ""); - endPoint = resolver.resolve(localAddressQuery, ec); - if (endPoint == end || ec) + Optional localAddress = Trinity::Net::Resolve(resolver, boost::asio::ip::tcp::v4(), fields[3].GetString(), ""); + if (!localAddress) { TC_LOG_ERROR("server.worldserver", "Could not resolve address %s", fields[3].GetString().c_str()); return false; } - realm.LocalAddress = (*endPoint).endpoint().address(); + realm.LocalAddress = Trinity::make_unique(localAddress->address()); - boost::asio::ip::tcp::resolver::query localSubmaskQuery(boost::asio::ip::tcp::v4(), fields[4].GetString(), ""); - endPoint = resolver.resolve(localSubmaskQuery, ec); - if (endPoint == end || ec) + Optional localSubmask = Trinity::Net::Resolve(resolver, boost::asio::ip::tcp::v4(), fields[4].GetString(), ""); + if (!localSubmask) { TC_LOG_ERROR("server.worldserver", "Could not resolve address %s", fields[4].GetString().c_str()); return false; } - realm.LocalSubnetMask = (*endPoint).endpoint().address(); + realm.LocalSubnetMask = Trinity::make_unique(localSubmask->address()); realm.Port = fields[5].GetUInt16(); realm.Type = fields[6].GetUInt8(); diff --git a/src/server/worldserver/PrecompiledHeaders/worldPCH.cpp b/src/server/worldserver/PrecompiledHeaders/worldPCH.cpp deleted file mode 100644 index 99c2400eccf..00000000000 --- a/src/server/worldserver/PrecompiledHeaders/worldPCH.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "worldPCH.h" diff --git a/src/server/worldserver/PrecompiledHeaders/worldPCH.h b/src/server/worldserver/PrecompiledHeaders/worldPCH.h index 6407485f70b..b4cdca9f3cf 100644 --- a/src/server/worldserver/PrecompiledHeaders/worldPCH.h +++ b/src/server/worldserver/PrecompiledHeaders/worldPCH.h @@ -1,3 +1,20 @@ +/* + * Copyright (C) 2008-2018 TrinityCore + * + * 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 . + */ + #include "Common.h" #include "World.h" #include "Log.h" diff --git a/src/server/worldserver/RemoteAccess/RASession.cpp b/src/server/worldserver/RemoteAccess/RASession.cpp index 09a1d1a8622..a7881a0b490 100644 --- a/src/server/worldserver/RemoteAccess/RASession.cpp +++ b/src/server/worldserver/RemoteAccess/RASession.cpp @@ -16,16 +16,16 @@ * with this program. If not, see . */ -#include -#include -#include -#include #include "RASession.h" #include "AccountMgr.h" -#include "Log.h" -#include "DatabaseEnv.h" -#include "World.h" #include "Config.h" +#include "DatabaseEnv.h" +#include "Log.h" +#include "Util.h" +#include "World.h" +#include +#include +#include using boost::asio::ip::tcp; @@ -39,7 +39,7 @@ void RASession::Start() if (_socket.available() > 0) { // Handle subnegotiation - boost::array buf; + char buf[1024] = { }; _socket.read_some(boost::asio::buffer(buf)); // Send the end-of-negotiation packet @@ -88,7 +88,7 @@ void RASession::Start() _socket.close(); } -int RASession::Send(const char* data) +int RASession::Send(char const* data) { std::ostream os(&_writeBuffer); os << data; @@ -202,7 +202,7 @@ bool RASession::ProcessCommand(std::string& command) return false; } -void RASession::CommandPrint(void* callbackArg, const char* text) +void RASession::CommandPrint(void* callbackArg, char const* text) { if (!text || !*text) return; diff --git a/src/server/worldserver/RemoteAccess/RASession.h b/src/server/worldserver/RemoteAccess/RASession.h index aa77fd08427..66fa19b4f6b 100644 --- a/src/server/worldserver/RemoteAccess/RASession.h +++ b/src/server/worldserver/RemoteAccess/RASession.h @@ -43,13 +43,13 @@ public: unsigned short GetRemotePort() const { return _socket.remote_endpoint().port(); } private: - int Send(const char* data); + int Send(char const* data); std::string ReadString(); bool CheckAccessLevel(const std::string& user); bool CheckPassword(const std::string& user, const std::string& pass); bool ProcessCommand(std::string& command); - static void CommandPrint(void* callbackArg, const char* text); + static void CommandPrint(void* callbackArg, char const* text); static void CommandFinished(void* callbackArg, bool); tcp::socket _socket; diff --git a/src/server/worldserver/TCSoap/TCSoap.cpp b/src/server/worldserver/TCSoap/TCSoap.cpp index d39d26ec8b5..e91ec4892e6 100644 --- a/src/server/worldserver/TCSoap/TCSoap.cpp +++ b/src/server/worldserver/TCSoap/TCSoap.cpp @@ -137,10 +137,10 @@ void SOAPCommand::commandFinished(void* soapconnection, bool success) //////////////////////////////////////////////////////////////////////////////// struct Namespace namespaces[] = -{ { "SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/", NULL, NULL }, // must be first - { "SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/", NULL, NULL }, // must be second - { "xsi", "http://www.w3.org/1999/XMLSchema-instance", "http://www.w3.org/*/XMLSchema-instance", NULL }, - { "xsd", "http://www.w3.org/1999/XMLSchema", "http://www.w3.org/*/XMLSchema", NULL }, - { "ns1", "urn:TC", NULL, NULL }, // "ns1" namespace prefix - { NULL, NULL, NULL, NULL } +{ { "SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/", nullptr, nullptr }, // must be first + { "SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/", nullptr, nullptr }, // must be second + { "xsi", "http://www.w3.org/1999/XMLSchema-instance", "http://www.w3.org/*/XMLSchema-instance", nullptr }, + { "xsd", "http://www.w3.org/1999/XMLSchema", "http://www.w3.org/*/XMLSchema", nullptr }, + { "ns1", "urn:TC", nullptr, nullptr }, // "ns1" namespace prefix + { nullptr, nullptr, nullptr, nullptr } }; diff --git a/src/server/worldserver/TCSoap/TCSoap.h b/src/server/worldserver/TCSoap/TCSoap.h index c3aade6f7d8..913b841e422 100644 --- a/src/server/worldserver/TCSoap/TCSoap.h +++ b/src/server/worldserver/TCSoap/TCSoap.h @@ -38,7 +38,7 @@ class SOAPCommand { } - void appendToPrintBuffer(const char* msg) + void appendToPrintBuffer(char const* msg) { m_printBuffer += msg; } @@ -54,7 +54,7 @@ class SOAPCommand return m_success; } - static void print(void* callbackArg, const char* msg) + static void print(void* callbackArg, char const* msg) { ((SOAPCommand*)callbackArg)->appendToPrintBuffer(msg); } diff --git a/src/tools/map_extractor/CMakeLists.txt b/src/tools/map_extractor/CMakeLists.txt index abee2a22484..eb2360ba286 100644 --- a/src/tools/map_extractor/CMakeLists.txt +++ b/src/tools/map_extractor/CMakeLists.txt @@ -9,37 +9,41 @@ # 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) - -include_directories ( - ${CMAKE_SOURCE_DIR} - ${CMAKE_SOURCE_DIR}/src/server/shared - ${CMAKE_SOURCE_DIR}/dep/fmt - ${CMAKE_SOURCE_DIR}/dep/StormLib/src - ${CMAKE_SOURCE_DIR}/dep/g3dlite/include - ${CMAKE_SOURCE_DIR}/src/common - ${CMAKE_SOURCE_DIR}/src/common/Utilities - ${CMAKE_SOURCE_DIR}/src/server/shared - ${CMAKE_CURRENT_SOURCE_DIR}/loadlib +CollectSourceFiles( + ${CMAKE_CURRENT_SOURCE_DIR} + PRIVATE_SOURCES ) -include_directories(${include_Dirs}) +if (WIN32) + list(APPEND PRIVATE_SOURCES ${sources_windows}) +endif() add_executable(mapextractor - ${mapextractor_SRCS} + ${PRIVATE_SOURCES} ) target_link_libraries(mapextractor - common - fmt - g3dlib - ${BZIP2_LIBRARIES} - ${ZLIB_LIBRARIES} - ${Boost_LIBRARIES} - storm + PRIVATE + trinity-core-interface + PUBLIC + common + storm) + +CollectIncludeDirectories( + ${CMAKE_CURRENT_SOURCE_DIR} + PUBLIC_INCLUDES ) -add_dependencies(mapextractor storm) +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 ba5a4a1e63b..0f5d6da29af 100644 --- a/src/tools/map_extractor/System.cpp +++ b/src/tools/map_extractor/System.cpp @@ -16,8 +16,6 @@ * with this program. If not, see . */ -#define _CRT_SECURE_NO_DEPRECATE - #include #include #include @@ -35,6 +33,7 @@ #include "StormLib.h" #include "dbcfile.h" +#include "Banner.h" #include "adt.h" #include "wdt.h" @@ -56,8 +55,8 @@ #define OPEN_FLAGS (O_RDONLY | O_BINARY) #endif -HANDLE WorldMpq = NULL; -HANDLE LocaleMpq = NULL; +HANDLE WorldMpq = nullptr; +HANDLE LocaleMpq = nullptr; typedef struct { @@ -248,7 +247,7 @@ uint32 ReadBuild(int locale) char buff[512]; DWORD readBytes = 0; - SFileReadFile(dbcFile, buff, 512, &readBytes, NULL); + SFileReadFile(dbcFile, buff, 512, &readBytes, nullptr); if (!readBytes) { printf("Fatal error: Not found %s file!\n", filename.c_str()); @@ -630,12 +629,12 @@ bool ConvertADT(char *filename, char *filename2, int /*cell_y*/, int /*cell_x*/, float diff = maxHeight - minHeight; if (diff < CONF_float_to_int8_limit) // As uint8 (max accuracy = CONF_float_to_int8_limit/256) { - heightHeader.flags|=MAP_HEIGHT_AS_INT8; + heightHeader.flags |= MAP_HEIGHT_AS_INT8; step = selectUInt8StepStore(diff); } else if (diff 0) { - SFileReadFile(fileInArchive, buffer, sizeof(buffer), &readBytes, NULL); + SFileReadFile(fileInArchive, buffer, sizeof(buffer), &readBytes, nullptr); if (readBytes > 0) fwrite(buffer, 1, readBytes, output); } @@ -1045,8 +1044,8 @@ void ExtractDBCFiles(int l, bool basicLocale) SFILE_FIND_DATA foundFile; memset(&foundFile, 0, sizeof(foundFile)); - HANDLE listFile = SFileFindFirstFile(LocaleMpq, "DBFilesClient\\*dbc", &foundFile, NULL); - HANDLE dbcFile = NULL; + HANDLE listFile = SFileFindFirstFile(LocaleMpq, "DBFilesClient\\*dbc", &foundFile, nullptr); + HANDLE dbcFile = nullptr; uint32 count = 0; if (listFile) { @@ -1095,8 +1094,8 @@ void ExtractDB2Files(int l, bool basicLocale) SFILE_FIND_DATA foundFile; memset(&foundFile, 0, sizeof(foundFile)); - HANDLE listFile = SFileFindFirstFile(LocaleMpq, "DBFilesClient\\*db2", &foundFile, NULL); - HANDLE dbcFile = NULL; + HANDLE listFile = SFileFindFirstFile(LocaleMpq, "DBFilesClient\\*db2", &foundFile, nullptr); + HANDLE dbcFile = nullptr; uint32 count = 0; if (listFile) { @@ -1179,7 +1178,7 @@ void ExtractCameraFiles(int locale, bool basicLocale) for (std::string thisFile : camerafiles) { std::string filename = path; - HANDLE dbcFile = NULL; + HANDLE dbcFile = nullptr; filename += (thisFile.c_str() + strlen("Cameras\\")); if (FileExists(filename.c_str())) @@ -1215,7 +1214,7 @@ bool LoadLocaleMPQFile(int locale) } _tprintf(_T("\nLoading %s locale MPQs\n"), LocalesT[locale]); - char const* prefix = NULL; + char const* prefix = nullptr; for (int i = 0; Builds[i] && Builds[i] <= CONF_TargetBuild; ++i) { // Do not attempt to read older MPQ patch archives past this build, they were merged with base @@ -1280,7 +1279,7 @@ void LoadCommonMPQFiles(uint32 build) } - char const* prefix = NULL; + char const* prefix = nullptr; for (int i = 0; Builds[i] && Builds[i] <= CONF_TargetBuild; ++i) { // Do not attempt to read older MPQ patch archives past this build, they were merged with base @@ -1317,8 +1316,7 @@ void LoadCommonMPQFiles(uint32 build) int main(int argc, char * arg[]) { - printf("Map & DBC Extractor\n"); - printf("===================\n"); + Trinity::Banner::Show("Map & DBC Extractor", [](char const* text) { printf("%s\n", text); }, nullptr); HandleArgs(argc, arg); diff --git a/src/tools/map_extractor/adt.h b/src/tools/map_extractor/adt.h index 68b84f73527..2e42d9a58d2 100644 --- a/src/tools/map_extractor/adt.h +++ b/src/tools/map_extractor/adt.h @@ -294,8 +294,8 @@ public: uint32 data4; uint32 data5; bool prepareLoadedData(); - adt_MCIN* getMCIN() { return offsMCIN ? (adt_MCIN *)((uint8 *)&flags+offsMCIN) : NULL; } - adt_MH2O* getMH2O() { return offsMH2O ? (adt_MH2O *)((uint8 *)&flags+offsMH2O) : NULL; } + adt_MCIN* getMCIN() { return offsMCIN ? (adt_MCIN *)((uint8 *)&flags+offsMCIN) : nullptr; } + adt_MH2O* getMH2O() { return offsMH2O ? (adt_MH2O *)((uint8 *)&flags+offsMH2O) : nullptr; } }; class ADT_file : public FileLoader{ diff --git a/src/tools/map_extractor/dbcfile.cpp b/src/tools/map_extractor/dbcfile.cpp index 0c584e7d054..e127b0b5894 100644 --- a/src/tools/map_extractor/dbcfile.cpp +++ b/src/tools/map_extractor/dbcfile.cpp @@ -21,7 +21,7 @@ #include "dbcfile.h" DBCFile::DBCFile(HANDLE file) : - _file(file), _data(NULL), _stringTable(NULL) + _file(file), _data(nullptr), _stringTable(nullptr) { } @@ -31,26 +31,26 @@ bool DBCFile::open() unsigned int na, nb, es, ss; DWORD readBytes = 0; - SFileReadFile(_file, header, 4, &readBytes, NULL); + SFileReadFile(_file, header, 4, &readBytes, nullptr); if (readBytes != 4) // Number of records return false; if (header[0] != 'W' || header[1] != 'D' || header[2] != 'B' || header[3] != 'C') return false; - SFileReadFile(_file, &na, 4, &readBytes, NULL); + SFileReadFile(_file, &na, 4, &readBytes, nullptr); if (readBytes != 4) // Number of records return false; - SFileReadFile(_file, &nb, 4, &readBytes, NULL); + SFileReadFile(_file, &nb, 4, &readBytes, nullptr); if (readBytes != 4) // Number of fields return false; - SFileReadFile(_file, &es, 4, &readBytes, NULL); + SFileReadFile(_file, &es, 4, &readBytes, nullptr); if (readBytes != 4) // Size of a record return false; - SFileReadFile(_file, &ss, 4, &readBytes, NULL); + SFileReadFile(_file, &ss, 4, &readBytes, nullptr); if (readBytes != 4) // String size return false; @@ -65,7 +65,7 @@ bool DBCFile::open() _stringTable = _data + _recordSize*_recordCount; size_t data_size = _recordSize * _recordCount + _stringSize; - SFileReadFile(_file, _data, data_size, &readBytes, NULL); + SFileReadFile(_file, _data, data_size, &readBytes, nullptr); if (readBytes != data_size) return false; diff --git a/src/tools/map_extractor/loadlib.cpp b/src/tools/map_extractor/loadlib.cpp index 74051d402dd..9978c76e798 100644 --- a/src/tools/map_extractor/loadlib.cpp +++ b/src/tools/map_extractor/loadlib.cpp @@ -46,9 +46,9 @@ bool FileLoader::loadFile(HANDLE mpq, char* filename, bool log) return false; } - data_size = SFileGetFileSize(file, NULL); + data_size = SFileGetFileSize(file, nullptr); data = new uint8[data_size]; - SFileReadFile(file, data, data_size, NULL/*bytesRead*/, NULL); + SFileReadFile(file, data, data_size, nullptr/*bytesRead*/, nullptr); if (prepareLoadedData()) { SFileCloseFile(file); diff --git a/src/tools/map_extractor/loadlib/loadlib.h b/src/tools/map_extractor/loadlib/loadlib.h index 0a8ef2f8dee..c855739d598 100644 --- a/src/tools/map_extractor/loadlib/loadlib.h +++ b/src/tools/map_extractor/loadlib/loadlib.h @@ -20,32 +20,7 @@ #define LOAD_LIB_H #include "StormLib.h" - -#ifdef _WIN32 -typedef __int64 int64; -typedef __int32 int32; -typedef __int16 int16; -typedef __int8 int8; -typedef unsigned __int64 uint64; -typedef unsigned __int32 uint32; -typedef unsigned __int16 uint16; -typedef unsigned __int8 uint8; -#else -#include -#ifndef uint64_t -#ifdef __linux__ -#include -#endif -#endif -typedef int64_t int64; -typedef int32_t int32; -typedef int16_t int16; -typedef int8_t int8; -typedef uint64_t uint64; -typedef uint32_t uint32; -typedef uint16_t uint16; -typedef uint8_t uint8; -#endif +#include "Define.h" #define FILE_FORMAT_VERSION 18 diff --git a/src/tools/map_extractor/wdt.cpp b/src/tools/map_extractor/wdt.cpp index 1da5954c0ff..d3826e505a7 100644 --- a/src/tools/map_extractor/wdt.cpp +++ b/src/tools/map_extractor/wdt.cpp @@ -79,6 +79,6 @@ bool WDT_file::prepareLoadedData() return false; wmo = (wdt_MWMO *)((uint8*)main+ main->size+8); if (!wmo->prepareLoadedData()) - wmo = NULL; // optional as of cataclysm + wmo = nullptr; // optional as of cataclysm return true; } diff --git a/src/tools/mmaps_generator/CMakeLists.txt b/src/tools/mmaps_generator/CMakeLists.txt index 4bd2812f33a..de1fea8da0f 100644 --- a/src/tools/mmaps_generator/CMakeLists.txt +++ b/src/tools/mmaps_generator/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright (C) 2008-2018 TrinityCore +# Copyright (C) 2008-2018 TrinityCore # # This file is free software; as a special exception the author gives # unlimited permission to copy and/or distribute it, with or without @@ -8,44 +8,39 @@ # 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/fmt - ${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/common - ${CMAKE_SOURCE_DIR}/src/common/Utilities - ${CMAKE_SOURCE_DIR}/src/common/Threading - ${CMAKE_SOURCE_DIR}/src/server/game/Conditions - ${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/DataStores -) +if (WIN32) + list(APPEND PRIVATE_SOURCES ${sources_windows}) +endif() -include_directories(${mmap_gen_Includes}) - -add_executable(mmaps_generator ${mmap_gen_sources}) +add_executable(mmaps_generator ${PRIVATE_SOURCES}) target_link_libraries(mmaps_generator - common - g3dlib - Recast - Detour - fmt - ${BZIP2_LIBRARIES} - ${ZLIB_LIBRARIES} - ${CMAKE_THREAD_LIBS_INIT} - ${Boost_LIBRARIES} -) + PRIVATE + trinity-core-interface + PUBLIC + common + Recast + Detour + storm) + +CollectIncludeDirectories( + ${CMAKE_CURRENT_SOURCE_DIR} + PUBLIC_INCLUDES) + +target_include_directories(mmaps_generator + PUBLIC + ${PUBLIC_INCLUDES} + PRIVATE + ${CMAKE_CURRENT_BINARY_DIR}) + +set_target_properties(mmaps_generator + PROPERTIES + FOLDER + "tools") if( UNIX ) install(TARGETS mmaps_generator DESTINATION bin) diff --git a/src/tools/mmaps_generator/IntermediateValues.cpp b/src/tools/mmaps_generator/IntermediateValues.cpp index 397702a4989..7d20ab0c3a6 100644 --- a/src/tools/mmaps_generator/IntermediateValues.cpp +++ b/src/tools/mmaps_generator/IntermediateValues.cpp @@ -69,7 +69,7 @@ namespace MMAP #undef DEBUG_WRITE } - void IntermediateValues::debugWrite(FILE* file, const rcHeightfield* mesh) + void IntermediateValues::debugWrite(FILE* file, rcHeightfield const* mesh) { if (!file || !mesh) return; @@ -107,7 +107,7 @@ namespace MMAP } } - void IntermediateValues::debugWrite(FILE* file, const rcCompactHeightfield* chf) + void IntermediateValues::debugWrite(FILE* file, rcCompactHeightfield const* chf) { if (!file | !chf) return; @@ -146,7 +146,7 @@ namespace MMAP fwrite(chf->areas, sizeof(unsigned char), chf->spanCount, file); } - void IntermediateValues::debugWrite(FILE* file, const rcContourSet* cs) + void IntermediateValues::debugWrite(FILE* file, rcContourSet const* cs) { if (!file || !cs) return; @@ -167,7 +167,7 @@ namespace MMAP } } - void IntermediateValues::debugWrite(FILE* file, const rcPolyMesh* mesh) + void IntermediateValues::debugWrite(FILE* file, rcPolyMesh const* mesh) { if (!file || !mesh) return; @@ -186,7 +186,7 @@ namespace MMAP fwrite(mesh->regs, sizeof(unsigned short), mesh->npolys, file); } - void IntermediateValues::debugWrite(FILE* file, const rcPolyMeshDetail* mesh) + void IntermediateValues::debugWrite(FILE* file, rcPolyMeshDetail const* mesh) { if (!file || !mesh) return; @@ -199,7 +199,7 @@ namespace MMAP fwrite(mesh->meshes, sizeof(int), mesh->nmeshes*4, file); } - void IntermediateValues::generateObjFile(uint32 mapID, uint32 tileX, uint32 tileY, MeshData &meshData) + void IntermediateValues::generateObjFile(uint32 mapID, uint32 tileX, uint32 tileY, MeshData& meshData) { char objFileName[255]; sprintf(objFileName, "meshes/map%03u%02u%02u.obj", mapID, tileY, tileX); diff --git a/src/tools/mmaps_generator/IntermediateValues.h b/src/tools/mmaps_generator/IntermediateValues.h index 44f5669b9d4..aa365026998 100644 --- a/src/tools/mmaps_generator/IntermediateValues.h +++ b/src/tools/mmaps_generator/IntermediateValues.h @@ -34,19 +34,19 @@ namespace MMAP rcPolyMesh* polyMesh; rcPolyMeshDetail* polyMeshDetail; - IntermediateValues() : heightfield(NULL), compactHeightfield(NULL), - contours(NULL), polyMesh(NULL), polyMeshDetail(NULL) {} + IntermediateValues() : heightfield(nullptr), compactHeightfield(nullptr), + contours(nullptr), polyMesh(nullptr), polyMeshDetail(nullptr) {} ~IntermediateValues(); void writeIV(uint32 mapID, uint32 tileX, uint32 tileY); - void debugWrite(FILE* file, const rcHeightfield* mesh); - void debugWrite(FILE* file, const rcCompactHeightfield* chf); - void debugWrite(FILE* file, const rcContourSet* cs); - void debugWrite(FILE* file, const rcPolyMesh* mesh); - void debugWrite(FILE* file, const rcPolyMeshDetail* mesh); + void debugWrite(FILE* file, rcHeightfield const* mesh); + void debugWrite(FILE* file, rcCompactHeightfield const* chf); + void debugWrite(FILE* file, rcContourSet const* cs); + void debugWrite(FILE* file, rcPolyMesh const* mesh); + void debugWrite(FILE* file, rcPolyMeshDetail const* mesh); - void generateObjFile(uint32 mapID, uint32 tileX, uint32 tileY, MeshData &meshData); + void generateObjFile(uint32 mapID, uint32 tileX, uint32 tileY, MeshData& meshData); }; } #endif diff --git a/src/tools/mmaps_generator/PathCommon.h b/src/tools/mmaps_generator/PathCommon.h index b14e2906853..7129ac1080d 100644 --- a/src/tools/mmaps_generator/PathCommon.h +++ b/src/tools/mmaps_generator/PathCommon.h @@ -48,7 +48,7 @@ enum NavTerrain namespace MMAP { - inline bool matchWildcardFilter(const char* filter, const char* str) + inline bool matchWildcardFilter(char const* filter, char const* str) { if (!filter || !str) return false; @@ -116,7 +116,7 @@ namespace MMAP while (dirp) { errno = 0; - if ((dp = readdir(dirp)) != NULL) + if ((dp = readdir(dirp)) != nullptr) { if (matchWildcardFilter(filter.c_str(), dp->d_name)) fileList.push_back(std::string(dp->d_name)); diff --git a/src/tools/mmaps_generator/PathGenerator.cpp b/src/tools/mmaps_generator/PathGenerator.cpp index e6e48d9894d..a3503ad08ce 100644 --- a/src/tools/mmaps_generator/PathGenerator.cpp +++ b/src/tools/mmaps_generator/PathGenerator.cpp @@ -16,15 +16,15 @@ * with this program. If not, see . */ -#include "MapBuilder.h" #include "PathCommon.h" +#include "Banner.h" +#include "DBCFileLoader.h" +#include "MapBuilder.h" #include "Timer.h" #include "VMapFactory.h" #include "VMapManager2.h" -#include "DBCFileLoader.h" #include #include -#include using namespace MMAP; @@ -94,7 +94,7 @@ bool handleArgs(int argc, char** argv, char* &file, unsigned int& threads) { - char* param = NULL; + char* param = nullptr; for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "--maxAngle") == 0) @@ -130,7 +130,7 @@ bool handleArgs(int argc, char** argv, return false; char* stileX = strtok(param, ","); - char* stileY = strtok(NULL, ","); + char* stileY = strtok(nullptr, ","); int tilex = atoi(stileX); int tiley = atoi(stileY); @@ -251,7 +251,7 @@ bool handleArgs(int argc, char** argv, return true; } -int finish(const char* message, int returnValue) +int finish(char const* message, int returnValue) { printf("%s", message); getchar(); // Wait for user input @@ -260,6 +260,8 @@ int finish(const char* message, int returnValue) int main(int argc, char** argv) { + Trinity::Banner::Show("MMAP generator", [](char const* text) { printf("%s\n", text); }, nullptr); + unsigned int threads = std::thread::hardware_concurrency(); int mapnum = -1; float maxAngle = 70.0f; @@ -271,8 +273,8 @@ int main(int argc, char** argv) debugOutput = false, silent = false, bigBaseUnit = false; - char* offMeshInputPath = NULL; - char* file = NULL; + char* offMeshInputPath = nullptr; + char* file = nullptr; bool validParam = handleArgs(argc, argv, mapnum, tileX, tileY, maxAngle, diff --git a/src/tools/mmaps_generator/TerrainBuilder.cpp b/src/tools/mmaps_generator/TerrainBuilder.cpp index b2e47022fe0..e2aa8fe7f8a 100644 --- a/src/tools/mmaps_generator/TerrainBuilder.cpp +++ b/src/tools/mmaps_generator/TerrainBuilder.cpp @@ -22,6 +22,7 @@ #include "ModelInstance.h" #include "VMapFactory.h" #include "VMapManager2.h" +#include // ****************************************** // Map file format defines @@ -289,7 +290,7 @@ namespace MMAP printf("TerrainBuilder::loadMap: Failed to read some data expected 1, read 0\n"); - float* liquid_map = NULL; + float* liquid_map = nullptr; if (!(lheader.flags & MAP_LIQUID_NO_TYPE)) if (fread(liquid_type, sizeof(liquid_type), 1, mapFile) != 1) @@ -382,7 +383,7 @@ namespace MMAP // make a copy of liquid vertices // used to pad right-bottom frame due to lost vertex data at extraction - float* lverts_copy = NULL; + float* lverts_copy = nullptr; if (meshData.liquidVerts.size()) { lverts_copy = new float[meshData.liquidVerts.size()]; @@ -654,7 +655,7 @@ namespace MMAP if (!instanceTrees[mapID]) break; - ModelInstance* models = NULL; + ModelInstance* models = nullptr; uint32 count = 0; instanceTrees[mapID]->getModelInstances(models, count); @@ -691,7 +692,7 @@ namespace MMAP std::vector tempVertices; std::vector transformedVertices; std::vector tempTriangles; - WmoLiquid* liquid = NULL; + WmoLiquid* liquid = nullptr; it->getMeshData(tempVertices, tempTriangles, liquid); @@ -890,10 +891,10 @@ namespace MMAP } /**************************************************************************/ - void TerrainBuilder::loadOffMeshConnections(uint32 mapID, uint32 tileX, uint32 tileY, MeshData &meshData, const char* offMeshFilePath) + void TerrainBuilder::loadOffMeshConnections(uint32 mapID, uint32 tileX, uint32 tileY, MeshData &meshData, char const* offMeshFilePath) { // no meshfile input given? - if (offMeshFilePath == NULL) + if (offMeshFilePath == nullptr) return; FILE* fp = fopen(offMeshFilePath, "rb"); diff --git a/src/tools/mmaps_generator/TerrainBuilder.h b/src/tools/mmaps_generator/TerrainBuilder.h index 979753131ed..71bccd8e946 100644 --- a/src/tools/mmaps_generator/TerrainBuilder.h +++ b/src/tools/mmaps_generator/TerrainBuilder.h @@ -85,7 +85,7 @@ namespace MMAP void loadMap(uint32 mapID, uint32 tileX, uint32 tileY, MeshData &meshData); bool loadVMap(uint32 mapID, uint32 tileX, uint32 tileY, MeshData &meshData); - void loadOffMeshConnections(uint32 mapID, uint32 tileX, uint32 tileY, MeshData &meshData, const char* offMeshFilePath); + void loadOffMeshConnections(uint32 mapID, uint32 tileX, uint32 tileY, MeshData &meshData, char const* offMeshFilePath); bool usesLiquids() const { return !m_skipLiquid; } diff --git a/src/tools/vmap4_assembler/CMakeLists.txt b/src/tools/vmap4_assembler/CMakeLists.txt index 14066daf90b..2f75bc883b2 100644 --- a/src/tools/vmap4_assembler/CMakeLists.txt +++ b/src/tools/vmap4_assembler/CMakeLists.txt @@ -1,5 +1,5 @@ # Copyright (C) 2005-2009 MaNGOS project -# Copyright (C) 2008-2018 TrinityCore +# Copyright (C) 2008-2018 TrinityCore # # This file is free software; as a special exception the author gives # unlimited permission to copy and/or distribute it, with or without @@ -9,25 +9,29 @@ # 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} -) +set(PRIVATE_SOURCES VMapAssembler.cpp) -add_executable(vmap4assembler VMapAssembler.cpp) -add_dependencies(vmap4assembler storm) +if (WIN32) + list(APPEND PRIVATE_SOURCES ${sources_windows}) +endif() + +add_executable(vmap4assembler ${PRIVATE_SOURCES}) + +if(CMAKE_SYSTEM_NAME MATCHES "Darwin") + set_target_properties(vmap4assembler PROPERTIES LINK_FLAGS "-framework Carbon") +endif() target_link_libraries(vmap4assembler - common - g3dlib - ${ZLIB_LIBRARIES} -) + PRIVATE + trinity-core-interface + PUBLIC + common + zlib) + +set_target_properties(vmap4assembler + PROPERTIES + FOLDER + "tools") if( UNIX ) install(TARGETS vmap4assembler DESTINATION bin) diff --git a/src/tools/vmap4_assembler/VMapAssembler.cpp b/src/tools/vmap4_assembler/VMapAssembler.cpp index 9a4cbe95b2b..082e0f57b4a 100644 --- a/src/tools/vmap4_assembler/VMapAssembler.cpp +++ b/src/tools/vmap4_assembler/VMapAssembler.cpp @@ -20,9 +20,12 @@ #include #include "TileAssembler.h" +#include "Banner.h" int main(int argc, char* argv[]) { + Trinity::Banner::Show("VMAP assembler", [](char const* text) { std::cout << text << std::endl; }, nullptr); + std::string src = "Buildings"; std::string dest = "vmaps"; diff --git a/src/tools/vmap4_extractor/CMakeLists.txt b/src/tools/vmap4_extractor/CMakeLists.txt index 83ac9f5c556..76d8d36f8be 100644 --- a/src/tools/vmap4_extractor/CMakeLists.txt +++ b/src/tools/vmap4_extractor/CMakeLists.txt @@ -1,5 +1,5 @@ # Copyright (C) 2005-2009 MaNGOS project -# Copyright (C) 2008-2018 TrinityCore +# Copyright (C) 2008-2018 TrinityCore # # This file is free software; as a special exception the author gives # unlimited permission to copy and/or distribute it, with or without @@ -9,31 +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 sources *.cpp *.h) +CollectSourceFiles( + ${CMAKE_CURRENT_SOURCE_DIR} + PRIVATE_SOURCES) -# uncomment next line to disable debug mode -add_definitions("-DIOMAP_DEBUG") - -# build setup currently only supports libmpq 0.4.x -if( NOT MSVC ) - add_definitions("-Wall") - add_definitions("-ggdb") - add_definitions("-O3") +if (WIN32) + list(APPEND PRIVATE_SOURCES ${sources_windows}) endif() -include_directories( - ${CMAKE_SOURCE_DIR}/dep/StormLib/src -) - -add_executable(vmap4extractor ${sources}) +add_executable(vmap4extractor ${PRIVATE_SOURCES}) target_link_libraries(vmap4extractor - ${BZIP2_LIBRARIES} - ${ZLIB_LIBRARIES} - storm + PRIVATE + trinity-core-interface + PUBLIC + common + storm) + +CollectIncludeDirectories( + ${CMAKE_CURRENT_SOURCE_DIR} + PUBLIC_INCLUDES ) -add_dependencies(vmap4extractor storm) +target_include_directories(vmap4extractor + PUBLIC + ${PUBLIC_INCLUDES} + PRIVATE + ${CMAKE_CURRENT_BINARY_DIR}) + +set_target_properties(vmap4extractor + PROPERTIES + FOLDER + "tools") if( UNIX ) install(TARGETS vmap4extractor DESTINATION bin) diff --git a/src/tools/vmap4_extractor/adtfile.cpp b/src/tools/vmap4_extractor/adtfile.cpp index 516fcf3a86b..e01e79a9e49 100644 --- a/src/tools/vmap4_extractor/adtfile.cpp +++ b/src/tools/vmap4_extractor/adtfile.cpp @@ -30,7 +30,7 @@ char const* GetPlainName(char const* FileName) { const char * szTemp; - if ((szTemp = strrchr(FileName, '\\')) != NULL) + if ((szTemp = strrchr(FileName, '\\')) != nullptr) FileName = szTemp + 1; return FileName; } @@ -39,7 +39,7 @@ char* GetPlainName(char* FileName) { char * szTemp; - if ((szTemp = strrchr(FileName, '\\')) != NULL) + if ((szTemp = strrchr(FileName, '\\')) != nullptr) FileName = szTemp + 1; return FileName; } @@ -74,7 +74,7 @@ char* GetExtension(char* FileName) { if (char* szTemp = strrchr(FileName, '.')) return szTemp; - return NULL; + return nullptr; } extern HANDLE WorldMpq; @@ -199,7 +199,7 @@ bool ADTFile::init(uint32 map_num, uint32 tileX, uint32 tileY, uint32 originalMa ModelInstance inst(ADT, ModelInstanceNames[id].c_str(), map_num, tileX, tileY, originalMapId, dirfile, dirfileCache); } delete[] ModelInstanceNames; - ModelInstanceNames = NULL; + ModelInstanceNames = nullptr; } } else if (!strcmp(fourcc,"MODF")) @@ -215,7 +215,7 @@ bool ADTFile::init(uint32 map_num, uint32 tileX, uint32 tileY, uint32 originalMa } delete[] WmoInstanceNames; - WmoInstanceNames = NULL; + WmoInstanceNames = nullptr; } } diff --git a/src/tools/vmap4_extractor/dbcfile.cpp b/src/tools/vmap4_extractor/dbcfile.cpp index 7e37511e530..7733b3acae2 100644 --- a/src/tools/vmap4_extractor/dbcfile.cpp +++ b/src/tools/vmap4_extractor/dbcfile.cpp @@ -20,8 +20,8 @@ #include "dbcfile.h" -DBCFile::DBCFile(HANDLE mpq, const char* filename) : - _mpq(mpq), _filename(filename), _file(NULL), _data(NULL), _stringTable(NULL) +DBCFile::DBCFile(HANDLE mpq, char const* filename) : + _mpq(mpq), _filename(filename), _file(nullptr), _data(nullptr), _stringTable(nullptr) { } @@ -34,7 +34,7 @@ bool DBCFile::open() unsigned int na, nb, es, ss; DWORD readBytes = 0; - SFileReadFile(_file, header, 4, &readBytes, NULL); + SFileReadFile(_file, header, 4, &readBytes, nullptr); if (readBytes != 4) // Number of records return false; @@ -42,22 +42,22 @@ bool DBCFile::open() return false; readBytes = 0; - SFileReadFile(_file, &na, 4, &readBytes, NULL); + SFileReadFile(_file, &na, 4, &readBytes, nullptr); if (readBytes != 4) // Number of records return false; readBytes = 0; - SFileReadFile(_file, &nb, 4, &readBytes, NULL); + SFileReadFile(_file, &nb, 4, &readBytes, nullptr); if (readBytes != 4) // Number of fields return false; readBytes = 0; - SFileReadFile(_file, &es, 4, &readBytes, NULL); + SFileReadFile(_file, &es, 4, &readBytes, nullptr); if (readBytes != 4) // Size of a record return false; readBytes = 0; - SFileReadFile(_file, &ss, 4, &readBytes, NULL); + SFileReadFile(_file, &ss, 4, &readBytes, nullptr); if (readBytes != 4) // String size return false; @@ -73,7 +73,7 @@ bool DBCFile::open() size_t data_size = _recordSize * _recordCount + _stringSize; readBytes = 0; - SFileReadFile(_file, _data, data_size, &readBytes, NULL); + SFileReadFile(_file, _data, data_size, &readBytes, nullptr); if (readBytes != data_size) return false; @@ -83,7 +83,7 @@ bool DBCFile::open() DBCFile::~DBCFile() { delete [] _data; - if (_file != NULL) + if (_file != nullptr) SFileCloseFile(_file); } diff --git a/src/tools/vmap4_extractor/dbcfile.h b/src/tools/vmap4_extractor/dbcfile.h index 9a56bed30b5..9d82d8b8b86 100644 --- a/src/tools/vmap4_extractor/dbcfile.h +++ b/src/tools/vmap4_extractor/dbcfile.h @@ -25,7 +25,7 @@ class DBCFile { public: - DBCFile(HANDLE mpq, const char* filename); + DBCFile(HANDLE mpq, char const* filename); ~DBCFile(); // Open database. It must be openened before it can be used. @@ -148,7 +148,7 @@ class DBCFile private: HANDLE _mpq; - const char* _filename; + char const* _filename; HANDLE _file; size_t _recordSize; size_t _recordCount; diff --git a/src/tools/vmap4_extractor/model.h b/src/tools/vmap4_extractor/model.h index 283279ea54a..8376a50e036 100644 --- a/src/tools/vmap4_extractor/model.h +++ b/src/tools/vmap4_extractor/model.h @@ -35,8 +35,8 @@ private: { delete[] vertices; delete[] indices; - vertices = NULL; - indices = NULL; + vertices = nullptr; + indices = nullptr; } std::string filename; public: diff --git a/src/tools/vmap4_extractor/mpqfile.cpp b/src/tools/vmap4_extractor/mpqfile.cpp index 4e690aabee3..8a7af1bbca8 100644 --- a/src/tools/vmap4_extractor/mpqfile.cpp +++ b/src/tools/vmap4_extractor/mpqfile.cpp @@ -3,7 +3,7 @@ #include #include "StormLib.h" -MPQFile::MPQFile(HANDLE mpq, const char* filename, bool warnNoExist /*= true*/) : +MPQFile::MPQFile(HANDLE mpq, char const* filename, bool warnNoExist /*= true*/) : eof(false), buffer(0), pointer(0), diff --git a/src/tools/vmap4_extractor/mpqfile.h b/src/tools/vmap4_extractor/mpqfile.h index e7379c4f7a0..71f0d3843c4 100644 --- a/src/tools/vmap4_extractor/mpqfile.h +++ b/src/tools/vmap4_extractor/mpqfile.h @@ -12,32 +12,10 @@ #include #include #include "StormLib.h" +#include "Define.h" #ifdef _WIN32 #include // mainly only HANDLE definition is required -typedef __int64 int64; -typedef __int32 int32; -typedef __int16 int16; -typedef __int8 int8; -typedef unsigned __int64 uint64; -typedef unsigned __int32 uint32; -typedef unsigned __int16 uint16; -typedef unsigned __int8 uint8; -#else -#include -#ifndef uint64_t -#ifdef __linux__ -#include -#endif -#endif -typedef int64_t int64; -typedef int32_t int32; -typedef int16_t int16; -typedef int8_t int8; -typedef uint64_t uint64; -typedef uint32_t uint32; -typedef uint16_t uint16; -typedef uint8_t uint8; #endif using namespace std; @@ -50,11 +28,11 @@ class MPQFile size_t pointer,size; // disable copying - MPQFile(const MPQFile &f); - void operator=(const MPQFile &f); + MPQFile(MPQFile const& f) = delete; + void operator=(MPQFile const& f) = delete; public: - MPQFile(HANDLE mpq, const char* filename, bool warnNoExist = true); // filenames are not case sensitive + MPQFile(HANDLE mpq, char const* filename, bool warnNoExist = true); // filenames are not case sensitive ~MPQFile() { close(); } size_t read(void* dest, size_t bytes); size_t getSize() { return size; } diff --git a/src/tools/vmap4_extractor/vmapexport.cpp b/src/tools/vmap4_extractor/vmapexport.cpp index fbf6dff3230..fabf9b3e4cb 100644 --- a/src/tools/vmap4_extractor/vmapexport.cpp +++ b/src/tools/vmap4_extractor/vmapexport.cpp @@ -16,41 +16,30 @@ * with this program. If not, see . */ -#define _CRT_SECURE_NO_DEPRECATE -#include -#include -#include -#include -#include -#include -#include - -#ifdef _WIN32 - #include - #include - #include - #define mkdir _mkdir -#else - #include - #define ERROR_PATH_NOT_FOUND ERROR_FILE_NOT_FOUND -#endif - -#undef min -#undef max - -//#pragma warning(disable : 4505) -//#pragma comment(lib, "Winmm.lib") - -#include - -//From Extractor #include "adtfile.h" #include "wdtfile.h" #include "dbcfile.h" #include "wmo.h" #include "mpqfile.h" - #include "vmapexport.h" +#include "Banner.h" +#include + +#ifdef _WIN32 + #include + #define mkdir _mkdir +#endif + +#undef min +#undef max + +#include +#include +#include +#include +#include +#include +#include //------------------------------------------------------------------------------ // Defines @@ -59,8 +48,8 @@ //----------------------------------------------------------------------------- -HANDLE WorldMpq = NULL; -HANDLE LocaleMpq = NULL; +HANDLE WorldMpq = nullptr; +HANDLE LocaleMpq = nullptr; uint32 CONF_TargetBuild = 15595; // 4.3.4.15595 @@ -121,8 +110,8 @@ bool preciseVectorData = false; // Constants //static const char * szWorkDirMaps = ".\\Maps"; -const char* szWorkDirWmo = "./Buildings"; -const char* szRawVMAPMagic = "VMAP045"; +char const* szWorkDirWmo = "./Buildings"; +char const* szRawVMAPMagic = "VMAP045"; bool LoadLocaleMPQFile(int locale) { @@ -140,7 +129,7 @@ bool LoadLocaleMPQFile(int locale) } _tprintf(_T("Loading %s locale MPQs\n"), LocalesT[locale]); - char const* prefix = NULL; + char const* prefix = nullptr; for (int i = 0; Builds[i] && Builds[i] <= CONF_TargetBuild; ++i) { // Do not attempt to read older MPQ patch archives past this build, they were merged with base @@ -202,7 +191,7 @@ void LoadCommonMPQFiles(uint32 build) _tprintf(_T("Loaded %s\n"), filename); } - char const* prefix = NULL; + char const* prefix = nullptr; for (int i = 0; Builds[i] && Builds[i] <= CONF_TargetBuild; ++i) { // Do not attempt to read older MPQ patch archives past this build, they were merged with base @@ -240,7 +229,7 @@ void LoadCommonMPQFiles(uint32 build) // Local testing functions -bool FileExists(const char* file) +bool FileExists(char const* file) { if (FILE* n = fopen(file, "rb")) { @@ -286,11 +275,11 @@ bool ExtractWmo() { bool success = false; - //const char* ParsArchiveNames[] = {"patch-2.MPQ", "patch.MPQ", "common.MPQ", "expansion.MPQ"}; + //char const* ParsArchiveNames[] = {"patch-2.MPQ", "patch.MPQ", "common.MPQ", "expansion.MPQ"}; SFILE_FIND_DATA data; - HANDLE find = SFileFindFirstFile(WorldMpq, "*.wmo", &data, NULL); - if (find != NULL) + HANDLE find = SFileFindFirstFile(WorldMpq, "*.wmo", &data, nullptr); + if (find != nullptr) { do { @@ -323,7 +312,7 @@ bool ExtractSingleWmo(std::string& fname) int p = 0; // Select root wmo files char const* rchr = strrchr(plain_name, '_'); - if (rchr != NULL) + if (rchr != nullptr) { char cpy[4]; memcpy(cpy, rchr, 4); @@ -531,7 +520,9 @@ bool processArgv(int argc, char ** argv, const char *versionString) int main(int argc, char ** argv) { - bool success=true; + Trinity::Banner::Show("VMAP data extractor", [](char const* text) { printf("%s\n", text); }, nullptr); + + bool success = true; const char *versionString = "V4.05 2018_03"; // Use command line arguments, when some @@ -553,7 +544,7 @@ int main(int argc, char ** argv) } } - printf("Extract %s. Beginning work ....\n\n",versionString); + printf("Extract %s. Beginning work ....\n\n", versionString); //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx // Create the working directory if (mkdir(szWorkDirWmo @@ -601,7 +592,7 @@ int main(int argc, char ** argv) { map_info& m = map_ids[dbc->getRecord(x).getUInt(0)]; - const char* map_name = dbc->getRecord(x).getString(1); + char const* map_name = dbc->getRecord(x).getString(1); size_t max_map_name_length = sizeof(m.name); if (strlen(map_name) >= max_map_name_length) { @@ -628,11 +619,11 @@ int main(int argc, char ** argv) printf("\n"); if (!success) { - printf("ERROR: Extract %s. Work NOT complete.\n Precise vector data=%d.\nPress any key.\n",versionString, preciseVectorData); + printf("ERROR: Extract %s. Work NOT complete.\n Precise vector data=%d.\nPress any key.\n", versionString, preciseVectorData); getchar(); } - printf("Extract %s. Work complete. No errors.\n",versionString); + printf("Extract %s. Work complete. No errors.\n", versionString); delete [] LiqType; return 0; } diff --git a/src/tools/vmap4_extractor/wdtfile.cpp b/src/tools/vmap4_extractor/wdtfile.cpp index e5856d9aafa..86e4bcef46d 100644 --- a/src/tools/vmap4_extractor/wdtfile.cpp +++ b/src/tools/vmap4_extractor/wdtfile.cpp @@ -26,7 +26,7 @@ char * wdtGetPlainName(char * FileName) { char * szTemp; - if ((szTemp = strrchr(FileName, '\\')) != NULL) + if ((szTemp = strrchr(FileName, '\\')) != nullptr) FileName = szTemp + 1; return FileName; } diff --git a/src/tools/vmap4_extractor/wmo.cpp b/src/tools/vmap4_extractor/wmo.cpp index dbfe3a9c8f5..6e5fc2c80d8 100644 --- a/src/tools/vmap4_extractor/wmo.cpp +++ b/src/tools/vmap4_extractor/wmo.cpp @@ -487,7 +487,7 @@ WMOGroup::~WMOGroup() } WMOInstance::WMOInstance(MPQFile& f, char const* WmoInstName, uint32 mapID, uint32 tileX, uint32 tileY, uint32 originalMapId, FILE* pDirfile, std::vector* dirfileCache) - : currx(0), curry(0), wmo(NULL), doodadset(0), pos(), indx(0), id(0) + : currx(0), curry(0), wmo(nullptr), doodadset(0), pos(), indx(0), id(0) { float ff[3]; f.read(&id, 4);