diff options
248 files changed, 4383 insertions, 17678 deletions
diff --git a/contrib/conf_merge/README b/contrib/conf_merge/README index 3d027b7ad42..974c1063064 100644 --- a/contrib/conf_merge/README +++ b/contrib/conf_merge/README @@ -1,6 +1,13 @@ -This is a PHP script for merging a new .dist file with your existing .conf file (trinitycore and trinityrealm) +==== PHP merger (index.php + merge.php) ==== + +This is a PHP script for merging a new .dist file with your existing .conf file (worldserver.conf.dist and authserver.conf.dist) It should also work with mangos dist/conf files as well. It uses sessions so it is multi user safe, it adds any options that are removed to the bottom of the file, commented out, just in case it removes something it shouldn't, and, if you add all of your custom patch configs below "# Custom" they will be copied exactly as they are. + +==== Perl merger (tc-conf-merger.pl) ==== + +Perl based command line merger script. This script feeds a .conf.dist file with variables that exist in an old .conf file, +comments and custom options are ignored. diff --git a/contrib/conf_merge/tc-conf-merger.pl b/contrib/conf_merge/tc-conf-merger.pl new file mode 100644 index 00000000000..a6589b5c674 --- /dev/null +++ b/contrib/conf_merge/tc-conf-merger.pl @@ -0,0 +1,43 @@ +#!/usr/bin/perl -w + +# Copyright (C) 2008-2010 TrinityCore <http://www.trinitycore.org/> +# Author: leak +# Date: 2010-12-06 +# Note: Based on conf file format of rev 10507 + +use strict; + +if (@ARGV != 3) +{ + print("Usage:\ntc-conf-merger.pl <path to new .conf.dist> <path to old .conf> <path to output .conf>\n"); + exit(1); +} + +if (! -e $ARGV[0]) +{ + print("No file found at: ".$ARGV[0]); + exit(1); +} +elsif (! -e $ARGV[1]) +{ + print("No file found at: ".$ARGV[1]); + exit(1); +} + +open CONFDIST, "<", $ARGV[0] or die "Error: Could not open ".$ARGV[0]."\n"; +my $confdist = join "", <CONFDIST>; +close CONFDIST; + +open CONFOLD, "<", $ARGV[1] or die "Error: Could not open ".$ARGV[1]."\n"; +my $confold = join "", <CONFOLD>; +close CONFOLD; + +while ($confold =~ m/^(?!#)(.*?)\s+?=\s+?(.*?)$/mg) { + my $key = $1, my $value = $2; + $confdist =~ s/^(\Q$key\E)(\s+?=\s+?)(.*)/$1$2$value/mg; +} + +open OUTPUT, ">", $ARGV[2] or die "Error: Could not open ".$ARGV[2]."\n"; +binmode(OUTPUT); +print OUTPUT $confdist; +close OUTPUT; diff --git a/dep/CMakeLists.txt b/dep/CMakeLists.txt index 4b11eda2fdd..8332d1b1546 100644 --- a/dep/CMakeLists.txt +++ b/dep/CMakeLists.txt @@ -35,7 +35,6 @@ endif() add_subdirectory(g3dlite) if(SERVERS) - add_subdirectory(sockets) add_subdirectory(gsoap) endif() diff --git a/dep/sockets/Base64.cpp b/dep/sockets/Base64.cpp deleted file mode 100644 index f7f12f5edff..00000000000 --- a/dep/sockets/Base64.cpp +++ /dev/null @@ -1,262 +0,0 @@ -/** \file Base64.cpp - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include "Base64.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -const char *Base64::bstr = - "ABCDEFGHIJKLMNOPQ" - "RSTUVWXYZabcdefgh" - "ijklmnopqrstuvwxy" - "z0123456789+/"; - -const char Base64::rstr[] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63, - 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0, - 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, - 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, - 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0}; - -Base64::Base64() -{ -} - -void Base64::encode(FILE *fil, std::string& output, bool add_crlf) -{ - size_t remain; - size_t i = 0; - size_t o = 0; - char input[4]; - - output = ""; - remain = fread(input,1,3,fil); - while (remain > 0) - { - if (add_crlf && o && o % 76 == 0) - output += "\n"; - switch (remain) - { - case 1: - output += bstr[ ((input[i] >> 2) & 0x3f) ]; - output += bstr[ ((input[i] << 4) & 0x30) ]; - output += "=="; - break; - case 2: - output += bstr[ ((input[i] >> 2) & 0x3f) ]; - output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ]; - output += bstr[ ((input[i + 1] << 2) & 0x3c) ]; - output += "="; - break; - default: - output += bstr[ ((input[i] >> 2) & 0x3f) ]; - output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ]; - output += bstr[ ((input[i + 1] << 2) & 0x3c) + ((input[i + 2] >> 6) & 0x03) ]; - output += bstr[ (input[i + 2] & 0x3f) ]; - } - o += 4; - // - remain = fread(input,1,3,fil); - } -} - -void Base64::encode(const std::string& str_in, std::string& str_out, bool add_crlf) -{ - encode(str_in.c_str(), str_in.size(), str_out, add_crlf); -} - -void Base64::encode(const char* input,size_t l,std::string& output, bool add_crlf) -{ - size_t i = 0; - size_t o = 0; - - output = ""; - while (i < l) - { - size_t remain = l - i; - if (add_crlf && o && o % 76 == 0) - output += "\n"; - switch (remain) - { - case 1: - output += bstr[ ((input[i] >> 2) & 0x3f) ]; - output += bstr[ ((input[i] << 4) & 0x30) ]; - output += "=="; - break; - case 2: - output += bstr[ ((input[i] >> 2) & 0x3f) ]; - output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ]; - output += bstr[ ((input[i + 1] << 2) & 0x3c) ]; - output += "="; - break; - default: - output += bstr[ ((input[i] >> 2) & 0x3f) ]; - output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ]; - output += bstr[ ((input[i + 1] << 2) & 0x3c) + ((input[i + 2] >> 6) & 0x03) ]; - output += bstr[ (input[i + 2] & 0x3f) ]; - } - o += 4; - i += 3; - } -} - -void Base64::encode(const unsigned char* input,size_t l,std::string& output,bool add_crlf) -{ - size_t i = 0; - size_t o = 0; - - output = ""; - while (i < l) - { - size_t remain = l - i; - if (add_crlf && o && o % 76 == 0) - output += "\n"; - switch (remain) - { - case 1: - output += bstr[ ((input[i] >> 2) & 0x3f) ]; - output += bstr[ ((input[i] << 4) & 0x30) ]; - output += "=="; - break; - case 2: - output += bstr[ ((input[i] >> 2) & 0x3f) ]; - output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ]; - output += bstr[ ((input[i + 1] << 2) & 0x3c) ]; - output += "="; - break; - default: - output += bstr[ ((input[i] >> 2) & 0x3f) ]; - output += bstr[ ((input[i] << 4) & 0x30) + ((input[i + 1] >> 4) & 0x0f) ]; - output += bstr[ ((input[i + 1] << 2) & 0x3c) + ((input[i + 2] >> 6) & 0x03) ]; - output += bstr[ (input[i + 2] & 0x3f) ]; - } - o += 4; - i += 3; - } -} - -void Base64::decode(const std::string& input,std::string& output) -{ - size_t i = 0; - size_t l = input.size(); - - output = ""; - while (i < l) - { - while (i < l && (input[i] == 13 || input[i] == 10)) - i++; - if (i < l) - { - char b1 = (char)((rstr[(int)input[i]] << 2 & 0xfc) + - (rstr[(int)input[i + 1]] >> 4 & 0x03)); - output += b1; - if (input[i + 2] != '=') - { - char b2 = (char)((rstr[(int)input[i + 1]] << 4 & 0xf0) + - (rstr[(int)input[i + 2]] >> 2 & 0x0f)); - output += b2; - } - if (input[i + 3] != '=') - { - char b3 = (char)((rstr[(int)input[i + 2]] << 6 & 0xc0) + - rstr[(int)input[i + 3]]); - output += b3; - } - i += 4; - } - } -} - -void Base64::decode(const std::string& input, unsigned char *output, size_t& sz) -{ - size_t i = 0; - size_t l = input.size(); - size_t j = 0; - - while (i < l) - { - while (i < l && (input[i] == 13 || input[i] == 10)) - i++; - if (i < l) - { - unsigned char b1 = (unsigned char)((rstr[(int)input[i]] << 2 & 0xfc) + - (rstr[(int)input[i + 1]] >> 4 & 0x03)); - if (output) - { - output[j] = b1; - } - j++; - if (input[i + 2] != '=') - { - unsigned char b2 = (unsigned char)((rstr[(int)input[i + 1]] << 4 & 0xf0) + - (rstr[(int)input[i + 2]] >> 2 & 0x0f)); - if (output) - { - output[j] = b2; - } - j++; - } - if (input[i + 3] != '=') - { - unsigned char b3 = (unsigned char)((rstr[(int)input[i + 2]] << 6 & 0xc0) + - rstr[(int)input[i + 3]]); - if (output) - { - output[j] = b3; - } - j++; - } - i += 4; - } - } - sz = j; -} - -size_t Base64::decode_length(const std::string& str64) -{ - if (str64.empty() || str64.size() % 4) - return 0; - size_t l = 3 * (str64.size() / 4 - 1) + 1; - if (str64[str64.size() - 2] != '=') - l++; - if (str64[str64.size() - 1] != '=') - l++; - return l; -} - -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/dep/sockets/CMakeLists.txt b/dep/sockets/CMakeLists.txt deleted file mode 100644 index a1756773c08..00000000000 --- a/dep/sockets/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright (C) 2008-2010 Trinity <http://www.trinitycore.org/> -# -# This file is free software; as a special exception the author gives -# unlimited permission to copy and/or distribute it, with or without -# modifications, as long as this notice is preserved. -# -# This program is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the -# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -file(GLOB sources *.cpp) - -set(trinitysockets_STAT_SRCS - ${sources} -) - -include_directories( - ${CMAKE_CURRENT_SOURCE_DIR}/include -) - -add_library(trinitysockets STATIC ${trinitysockets_STAT_SRCS}) diff --git a/dep/sockets/Exception.cpp b/dep/sockets/Exception.cpp deleted file mode 100644 index 4d79aeef813..00000000000 --- a/dep/sockets/Exception.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/** - ** \file Exception.cpp - ** \date 2007-09-28 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2007 Anders Hedstrom - -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, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifdef _MSC_VER -#pragma warning(disable:4786) -#endif -#include "Exception.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -Exception::Exception(const std::string& description) : m_description(description) -{ -} - -const std::string Exception::ToString() const -{ - return m_description; -} - -#ifdef SOCKETS_NAMESPACE -} // namespace SOCKETS_NAMESPACE { -#endif - - diff --git a/dep/sockets/Ipv4Address.cpp b/dep/sockets/Ipv4Address.cpp deleted file mode 100644 index 03935038951..00000000000 --- a/dep/sockets/Ipv4Address.cpp +++ /dev/null @@ -1,192 +0,0 @@ -/** - ** \file Ipv4Address.cpp - ** \date 2006-09-21 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2007 Anders Hedstrom - -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, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include "Ipv4Address.h" -#include "Utility.h" -#include "Parse.h" -#ifndef _WIN32 -#include <netdb.h> -#endif - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -Ipv4Address::Ipv4Address(port_t port) : m_valid(true) -{ - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons( port ); -} - -Ipv4Address::Ipv4Address(ipaddr_t a,port_t port) : m_valid(true) -{ - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons( port ); - memcpy(&m_addr.sin_addr, &a, sizeof(struct in_addr)); -} - -Ipv4Address::Ipv4Address(struct in_addr& a,port_t port) : m_valid(true) -{ - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons( port ); - m_addr.sin_addr = a; -} - -Ipv4Address::Ipv4Address(const std::string& host,port_t port) : m_valid(false) -{ - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin_family = AF_INET; - m_addr.sin_port = htons( port ); - { - ipaddr_t a; - if (Utility::u2ip(host, a)) - { - memcpy(&m_addr.sin_addr, &a, sizeof(struct in_addr)); - m_valid = true; - } - } -} - -Ipv4Address::Ipv4Address(struct sockaddr_in& sa) -{ - m_addr = sa; - m_valid = sa.sin_family == AF_INET; -} - -Ipv4Address::~Ipv4Address() -{ -} - -Ipv4Address::operator struct sockaddr *() -{ - return (struct sockaddr *)&m_addr; -} - -Ipv4Address::operator socklen_t() -{ - return sizeof(struct sockaddr_in); -} - -void Ipv4Address::SetPort(port_t port) -{ - m_addr.sin_port = htons( port ); -} - -port_t Ipv4Address::GetPort() -{ - return ntohs( m_addr.sin_port ); -} - -bool Ipv4Address::Resolve(const std::string& hostname,struct in_addr& a) -{ - struct sockaddr_in sa; - memset(&a, 0, sizeof(a)); - if (Utility::isipv4(hostname)) - { - if (!Utility::u2ip(hostname, sa, AI_NUMERICHOST)) - return false; - a = sa.sin_addr; - return true; - } - if (!Utility::u2ip(hostname, sa)) - return false; - a = sa.sin_addr; - return true; -} - -bool Ipv4Address::Reverse(struct in_addr& a,std::string& name) -{ - struct sockaddr_in sa; - memset(&sa, 0, sizeof(sa)); - sa.sin_family = AF_INET; - sa.sin_addr = a; - return Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name); -} - -std::string Ipv4Address::Convert(bool include_port) -{ - if (include_port) - return Convert(m_addr.sin_addr) + ":" + Utility::l2string(GetPort()); - return Convert(m_addr.sin_addr); -} - -std::string Ipv4Address::Convert(struct in_addr& a) -{ - struct sockaddr_in sa; - memset(&sa, 0, sizeof(sa)); - sa.sin_family = AF_INET; - sa.sin_addr = a; - std::string name; - Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name, NI_NUMERICHOST); - return name; -} - -void Ipv4Address::SetAddress(struct sockaddr *sa) -{ - memcpy(&m_addr, sa, sizeof(struct sockaddr_in)); -} - -int Ipv4Address::GetFamily() -{ - return m_addr.sin_family; -} - -bool Ipv4Address::IsValid() -{ - return m_valid; -} - -bool Ipv4Address::operator==(SocketAddress& a) -{ - if (a.GetFamily() != GetFamily()) - return false; - if ((socklen_t)a != sizeof(m_addr)) - return false; - struct sockaddr *sa = a; - struct sockaddr_in *p = (struct sockaddr_in *)sa; - if (p -> sin_port != m_addr.sin_port) - return false; - if (memcmp(&p -> sin_addr, &m_addr.sin_addr, 4)) - return false; - return true; -} - -std::auto_ptr<SocketAddress> Ipv4Address::GetCopy() -{ - return std::auto_ptr<SocketAddress>(new Ipv4Address(m_addr)); -} - -std::string Ipv4Address::Reverse() -{ - std::string tmp; - Reverse(m_addr.sin_addr, tmp); - return tmp; -} - -#ifdef SOCKETS_NAMESPACE -} // namespace SOCKETS_NAMESPACE { -#endif - - diff --git a/dep/sockets/Ipv6Address.cpp b/dep/sockets/Ipv6Address.cpp deleted file mode 100644 index 3208b5098fa..00000000000 --- a/dep/sockets/Ipv6Address.cpp +++ /dev/null @@ -1,247 +0,0 @@ -/** - ** \file Ipv6Address.cpp - ** \date 2006-09-21 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2007 Anders Hedstrom - -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, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include "Ipv6Address.h" -#ifdef ENABLE_IPV6 - -#include "Utility.h" -#include "Parse.h" -#ifndef _WIN32 -#include <netdb.h> -#endif -#ifdef IPPROTO_IPV6 - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -Ipv6Address::Ipv6Address(port_t port) : m_valid(true) -{ - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin6_family = AF_INET6; - m_addr.sin6_port = htons( port ); -} - -Ipv6Address::Ipv6Address(struct in6_addr& a,port_t port) : m_valid(true) -{ - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin6_family = AF_INET6; - m_addr.sin6_port = htons( port ); - m_addr.sin6_addr = a; -} - -Ipv6Address::Ipv6Address(const std::string& host,port_t port) : m_valid(false) -{ - memset(&m_addr, 0, sizeof(m_addr)); - m_addr.sin6_family = AF_INET6; - m_addr.sin6_port = htons( port ); - { - struct in6_addr a; - if (Utility::u2ip(host, a)) - { - m_addr.sin6_addr = a; - m_valid = true; - } - } -} - -Ipv6Address::Ipv6Address(struct sockaddr_in6& sa) -{ - m_addr = sa; - m_valid = sa.sin6_family == AF_INET6; -} - -Ipv6Address::~Ipv6Address() -{ -} - -Ipv6Address::operator struct sockaddr *() -{ - return (struct sockaddr *)&m_addr; -} - -Ipv6Address::operator socklen_t() -{ - return sizeof(struct sockaddr_in6); -} - -void Ipv6Address::SetPort(port_t port) -{ - m_addr.sin6_port = htons( port ); -} - -port_t Ipv6Address::GetPort() -{ - return ntohs( m_addr.sin6_port ); -} - -bool Ipv6Address::Resolve(const std::string& hostname,struct in6_addr& a) -{ - struct sockaddr_in6 sa; - memset(&a, 0, sizeof(a)); - if (Utility::isipv6(hostname)) - { - if (!Utility::u2ip(hostname, sa, AI_NUMERICHOST)) - return false; - a = sa.sin6_addr; - return true; - } - if (!Utility::u2ip(hostname, sa)) - return false; - a = sa.sin6_addr; - return true; -} - -bool Ipv6Address::Reverse(struct in6_addr& a,std::string& name) -{ - struct sockaddr_in6 sa; - memset(&sa, 0, sizeof(sa)); - sa.sin6_family = AF_INET6; - sa.sin6_addr = a; - return Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name); -} - -std::string Ipv6Address::Convert(bool include_port) -{ - if (include_port) - return Convert(m_addr.sin6_addr) + ":" + Utility::l2string(GetPort()); - return Convert(m_addr.sin6_addr); -} - -std::string Ipv6Address::Convert(struct in6_addr& a,bool mixed) -{ - char slask[100]; // l2ip temporary - *slask = 0; - unsigned int prev = 0; - bool skipped = false; - bool ok_to_skip = true; - if (mixed) - { - unsigned short x; - unsigned short addr16[8]; - memcpy(addr16, &a, sizeof(addr16)); - for (size_t i = 0; i < 6; i++) - { - x = ntohs(addr16[i]); - if (*slask && (x || !ok_to_skip || prev)) - strcat(slask,":"); - if (x || !ok_to_skip) - { - sprintf(slask + strlen(slask),"%x", x); - if (x && skipped) - ok_to_skip = false; - } - else - { - skipped = true; - } - prev = x; - } - x = ntohs(addr16[6]); - sprintf(slask + strlen(slask),":%u.%u",x / 256,x & 255); - x = ntohs(addr16[7]); - sprintf(slask + strlen(slask),".%u.%u",x / 256,x & 255); - } - else - { - struct sockaddr_in6 sa; - memset(&sa, 0, sizeof(sa)); - sa.sin6_family = AF_INET6; - sa.sin6_addr = a; - std::string name; - Utility::reverse((struct sockaddr *)&sa, sizeof(sa), name, NI_NUMERICHOST); - return name; - } - return slask; -} - -void Ipv6Address::SetAddress(struct sockaddr *sa) -{ - memcpy(&m_addr, sa, sizeof(struct sockaddr_in6)); -} - -int Ipv6Address::GetFamily() -{ - return m_addr.sin6_family; -} - -void Ipv6Address::SetFlowinfo(uint32_t x) -{ - m_addr.sin6_flowinfo = x; -} - -uint32_t Ipv6Address::GetFlowinfo() -{ - return m_addr.sin6_flowinfo; -} - -#ifndef _WIN32 -void Ipv6Address::SetScopeId(uint32_t x) -{ - m_addr.sin6_scope_id = x; -} - -uint32_t Ipv6Address::GetScopeId() -{ - return m_addr.sin6_scope_id; -} -#endif - -bool Ipv6Address::IsValid() -{ - return m_valid; -} - -bool Ipv6Address::operator==(SocketAddress& a) -{ - if (a.GetFamily() != GetFamily()) - return false; - if ((socklen_t)a != sizeof(m_addr)) - return false; - struct sockaddr *sa = a; - struct sockaddr_in6 *p = (struct sockaddr_in6 *)sa; - if (p -> sin6_port != m_addr.sin6_port) - return false; - if (memcmp(&p -> sin6_addr, &m_addr.sin6_addr, sizeof(struct in6_addr))) - return false; - return true; -} - -std::auto_ptr<SocketAddress> Ipv6Address::GetCopy() -{ - return std::auto_ptr<SocketAddress>(new Ipv6Address(m_addr)); -} - -std::string Ipv6Address::Reverse() -{ - std::string tmp; - Reverse(m_addr.sin6_addr, tmp); - return tmp; -} - -#ifdef SOCKETS_NAMESPACE -} // namespace SOCKETS_NAMESPACE { -#endif -#endif // IPPROTO_IPV6 -#endif // ENABLE_IPV6 - - diff --git a/dep/sockets/Lock.cpp b/dep/sockets/Lock.cpp deleted file mode 100644 index b75664cfbdc..00000000000 --- a/dep/sockets/Lock.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/** \file Lock.cpp - ** \date 2005-08-22 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2005,2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include "Mutex.h" -#include "Lock.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -Lock::Lock(Mutex& m) : m_mutex(m) -{ - m_mutex.Lock(); -} - -Lock::~Lock() -{ - m_mutex.Unlock(); -} - - -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/dep/sockets/Makefile b/dep/sockets/Makefile deleted file mode 100644 index 88b6199788c..00000000000 --- a/dep/sockets/Makefile +++ /dev/null @@ -1,136 +0,0 @@ -# CMAKE generated file: DO NOT EDIT! -# Generated by "Unix Makefiles" Generator, CMake Version 2.6 - -# Default target executed when no arguments are given to make. -default_target: all -.PHONY : default_target - -#============================================================================= -# Special targets provided by cmake. - -# Disable implicit rules so canoncical targets will work. -.SUFFIXES: - -# Remove some rules from gmake that .SUFFIXES does not remove. -SUFFIXES = - -.SUFFIXES: .hpux_make_needs_suffix_list - -# Suppress display of executed commands. -$(VERBOSE).SILENT: - -# A target that is always out of date. -cmake_force: -.PHONY : cmake_force - -#============================================================================= -# Set environment variables for the build. - -# The shell in which to execute make rules. -SHELL = /bin/sh - -# The CMake executable. -CMAKE_COMMAND = /usr/bin/cmake - -# The command to remove a file. -RM = /usr/bin/cmake -E remove -f - -# The program to use to edit the cache. -CMAKE_EDIT_COMMAND = /usr/bin/ccmake - -# The top-level source directory on which CMake was run. -CMAKE_SOURCE_DIR = /home/trinity/dev/trinitycore/dep/sockets - -# The top-level build directory on which CMake was run. -CMAKE_BINARY_DIR = /home/trinity/dev/trinitycore/dep/sockets - -#============================================================================= -# Targets provided globally by CMake. - -# Special rule for the target edit_cache -edit_cache: - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake cache editor..." - /usr/bin/ccmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) -.PHONY : edit_cache - -# Special rule for the target edit_cache -edit_cache/fast: edit_cache -.PHONY : edit_cache/fast - -# Special rule for the target rebuild_cache -rebuild_cache: - @$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..." - /usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) -.PHONY : rebuild_cache - -# Special rule for the target rebuild_cache -rebuild_cache/fast: rebuild_cache -.PHONY : rebuild_cache/fast - -# The main all target -all: cmake_check_build_system - $(CMAKE_COMMAND) -E cmake_progress_start /home/trinity/dev/trinitycore/dep/sockets/CMakeFiles /home/trinity/dev/trinitycore/dep/sockets/CMakeFiles/progress.make - $(MAKE) -f CMakeFiles/Makefile2 all - $(CMAKE_COMMAND) -E cmake_progress_start /home/trinity/dev/trinitycore/dep/sockets/CMakeFiles 0 -.PHONY : all - -# The main clean target -clean: - $(MAKE) -f CMakeFiles/Makefile2 clean -.PHONY : clean - -# The main clean target -clean/fast: clean -.PHONY : clean/fast - -# Prepare targets for installation. -preinstall: all - $(MAKE) -f CMakeFiles/Makefile2 preinstall -.PHONY : preinstall - -# Prepare targets for installation. -preinstall/fast: - $(MAKE) -f CMakeFiles/Makefile2 preinstall -.PHONY : preinstall/fast - -# clear depends -depend: - $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1 -.PHONY : depend - -#============================================================================= -# Target rules for targets named trinitysockets - -# Build rule for target. -trinitysockets: cmake_check_build_system - $(MAKE) -f CMakeFiles/Makefile2 trinitysockets -.PHONY : trinitysockets - -# fast build rule for target. -trinitysockets/fast: - $(MAKE) -f CMakeFiles/trinitysockets.dir/build.make CMakeFiles/trinitysockets.dir/build -.PHONY : trinitysockets/fast - -# Help Target -help: - @echo "The following are some of the valid targets for this Makefile:" - @echo "... all (the default if no target is provided)" - @echo "... clean" - @echo "... depend" - @echo "... edit_cache" - @echo "... rebuild_cache" - @echo "... trinitysockets" -.PHONY : help - - - -#============================================================================= -# Special targets to cleanup operation of make. - -# Special rule to run CMake to check the build system integrity. -# No rule that depends on this can have commands that come from listfiles -# because they might be regenerated. -cmake_check_build_system: - $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0 -.PHONY : cmake_check_build_system - diff --git a/dep/sockets/Mutex.cpp b/dep/sockets/Mutex.cpp deleted file mode 100644 index 681e85cee5b..00000000000 --- a/dep/sockets/Mutex.cpp +++ /dev/null @@ -1,77 +0,0 @@ -/** \file Mutex.cpp - ** \date 2004-10-30 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include "Mutex.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -Mutex::Mutex() -{ -#ifdef _WIN32 - m_mutex = ::CreateMutex(NULL, FALSE, NULL); -#else - pthread_mutex_init(&m_mutex, NULL); -#endif -} - -Mutex::~Mutex() -{ -#ifdef _WIN32 - ::CloseHandle(m_mutex); -#else - pthread_mutex_destroy(&m_mutex); -#endif -} - -void Mutex::Lock() -{ -#ifdef _WIN32 - /*DWORD d =*/ WaitForSingleObject(m_mutex, INFINITE); - /// \todo check 'd' for result -#else - pthread_mutex_lock(&m_mutex); -#endif -} - -void Mutex::Unlock() -{ -#ifdef _WIN32 - ::ReleaseMutex(m_mutex); -#else - pthread_mutex_unlock(&m_mutex); -#endif -} - -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/dep/sockets/Parse.cpp b/dep/sockets/Parse.cpp deleted file mode 100644 index 2967859f23d..00000000000 --- a/dep/sockets/Parse.cpp +++ /dev/null @@ -1,318 +0,0 @@ -/** \file Parse.cpp - parse a string - ** - ** Written: 1999-Feb-10 grymse@alhem.net - **/ - -/* -Copyright (C) 1999-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include <stdlib.h> -#include <string.h> - -#include "Parse.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/* implementation of class Parse */ - -Parse::Parse() -:pa_the_str("") -,pa_splits("") -,pa_ord("") -,pa_the_ptr(0) -,pa_breakchar(0) -,pa_enable(0) -,pa_disable(0) -,pa_nospace(0) -,pa_quote(false) -{ -} - -Parse::Parse(const std::string&s) -:pa_the_str(s) -,pa_splits("") -,pa_ord("") -,pa_the_ptr(0) -,pa_breakchar(0) -,pa_enable(0) -,pa_disable(0) -,pa_nospace(0) -,pa_quote(false) -{ -} - -Parse::Parse(const std::string&s,const std::string&sp) -:pa_the_str(s) -,pa_splits(sp) -,pa_ord("") -,pa_the_ptr(0) -,pa_breakchar(0) -,pa_enable(0) -,pa_disable(0) -,pa_nospace(0) -,pa_quote(false) -{ -} - -Parse::Parse(const std::string&s,const std::string&sp,short /*nospace*/) -:pa_the_str(s) -,pa_splits(sp) -,pa_ord("") -,pa_the_ptr(0) -,pa_breakchar(0) -,pa_enable(0) -,pa_disable(0) -,pa_nospace(1) -,pa_quote(false) -{ -} - -Parse::~Parse() -{ -} - -#define C ((pa_the_ptr<pa_the_str.size()) ? pa_the_str[pa_the_ptr] : 0) - -short Parse::issplit(const char c) -{ - for (size_t i = 0; i < pa_splits.size(); i++) - if (pa_splits[i] == c) - return 1; - return 0; -} - -void Parse::getsplit() -{ - size_t x; - - if (C == '=') - { - x = pa_the_ptr++; - } else - { - while (C && (issplit(C))) - pa_the_ptr++; - x = pa_the_ptr; - while (C && !issplit(C) && C != '=') - pa_the_ptr++; - } - if (x == pa_the_ptr && C == '=') - pa_the_ptr++; - pa_ord = (x < pa_the_str.size()) ? pa_the_str.substr(x,pa_the_ptr - x) : ""; -} - -std::string Parse::getword() -{ - size_t x; - int disabled = 0; - int quote = 0; - int rem = 0; - - if (pa_nospace) - { - while (C && issplit(C)) - pa_the_ptr++; - x = pa_the_ptr; - while (C && !issplit(C) && (C != pa_breakchar || !pa_breakchar || disabled)) - { - if (pa_breakchar && C == pa_disable) - disabled = 1; - if (pa_breakchar && C == pa_enable) - disabled = 0; - if (pa_quote && C == '"') - quote = 1; - pa_the_ptr++; - while (quote && C && C != '"') - { - pa_the_ptr++; - } - if (pa_quote && C == '"') - { - pa_the_ptr++; - } - quote = 0; - } - } else - { - if (C == pa_breakchar && pa_breakchar) - { - x = pa_the_ptr++; - rem = 1; - } else - { - while (C && (C == ' ' || C == 9 || C == 13 || C == 10 || issplit(C))) - pa_the_ptr++; - x = pa_the_ptr; - while (C && C != ' ' && C != 9 && C != 13 && C != 10 && !issplit(C) && - (C != pa_breakchar || !pa_breakchar || disabled)) - { - if (pa_breakchar && C == pa_disable) - disabled = 1; - if (pa_breakchar && C == pa_enable) - disabled = 0; - if (pa_quote && C == '"') - { - quote = 1; - pa_the_ptr++; - while (quote && C && C != '"') - { - pa_the_ptr++; - } - if (pa_quote && C == '"') - { - pa_the_ptr++; - } - } - else - pa_the_ptr++; - quote = 0; - } - pa_the_ptr++; - rem = 1; - } - if (x == pa_the_ptr && C == pa_breakchar && pa_breakchar) - pa_the_ptr++; - } - if (x < pa_the_str.size()) - { - pa_ord = pa_the_str.substr(x,pa_the_ptr - x - rem); - } - else - { - pa_ord = ""; - } - return pa_ord; -} - -void Parse::getword(std::string&s) -{ - s = Parse::getword(); -} - -void Parse::getsplit(std::string&s) -{ - Parse::getsplit(); - s = pa_ord; -} - -void Parse::getword(std::string&s,std::string&fill,int l) -{ - Parse::getword(); - s = ""; - while (s.size() + pa_ord.size() < (size_t)l) - s += fill; - s += pa_ord; -} - -std::string Parse::getrest() -{ - std::string s; - while (C && (C == ' ' || C == 9 || issplit(C))) - pa_the_ptr++; - s = (pa_the_ptr < pa_the_str.size()) ? pa_the_str.substr(pa_the_ptr) : ""; - return s; -} - -void Parse::getrest(std::string&s) -{ - while (C && (C == ' ' || C == 9 || issplit(C))) - pa_the_ptr++; - s = (pa_the_ptr < pa_the_str.size()) ? pa_the_str.substr(pa_the_ptr) : ""; -} - -long Parse::getvalue() -{ - Parse::getword(); - return atol(pa_ord.c_str()); -} - -void Parse::setbreak(const char c) -{ - pa_breakchar = c; -} - -int Parse::getwordlen() -{ - size_t x,y = pa_the_ptr,len; - - if (C == pa_breakchar && pa_breakchar) - { - x = pa_the_ptr++; - } else - { - while (C && (C == ' ' || C == 9 || C == 13 || C == 10 || issplit(C))) - pa_the_ptr++; - x = pa_the_ptr; - while (C && C != ' ' && C != 9 && C != 13 && C != 10 && !issplit(C) && (C != pa_breakchar || !pa_breakchar)) - pa_the_ptr++; - } - if (x == pa_the_ptr && C == pa_breakchar && pa_breakchar) - pa_the_ptr++; - len = pa_the_ptr - x; - pa_the_ptr = y; - return (int)len; -} - -int Parse::getrestlen() -{ - size_t y = pa_the_ptr; - size_t len; - - while (C && (C == ' ' || C == 9 || issplit(C))) - pa_the_ptr++; - len = strlen(pa_the_str.c_str() + pa_the_ptr); - pa_the_ptr = y; - return (int)len; -} - -void Parse::getline() -{ - size_t x; - - x = pa_the_ptr; - while (C && C != 13 && C != 10) - pa_the_ptr++; - pa_ord = (x < pa_the_str.size()) ? pa_the_str.substr(x,pa_the_ptr - x) : ""; - if (C == 13) - pa_the_ptr++; - if (C == 10) - pa_the_ptr++; -} - -void Parse::getline(std::string&s) -{ - getline(); - s = pa_ord; -} - -/* end of implementation of class Parse */ -/***************************************************/ -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/dep/sockets/ResolvServer.cpp b/dep/sockets/ResolvServer.cpp deleted file mode 100644 index 3c8a7de6bc0..00000000000 --- a/dep/sockets/ResolvServer.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/** \file ResolvServer.cpp - ** \date 2005-03-24 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifdef _MSC_VER -#pragma warning(disable:4786) -#endif -#include "ResolvServer.h" -#ifdef ENABLE_RESOLVER -#include "StdoutLog.h" -#include "ListenSocket.h" -#include "ResolvSocket.h" -#include "SocketHandler.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -ResolvServer::ResolvServer(port_t port) -:Thread() -,m_quit(false) -,m_port(port) -,m_ready(false) -{ -} - -ResolvServer::~ResolvServer() -{ -} - -void ResolvServer::Run() -{ -// StdoutLog log; - SocketHandler h; - ListenSocket<ResolvSocket> l(h); - - if (l.Bind("127.0.0.1", m_port)) - { - return; - } - h.Add(&l); - - m_ready = true; - while (!m_quit && IsRunning() ) - { - h.Select(0, 500000); - } - SetRunning(false); -} - -void ResolvServer::Quit() -{ - m_quit = true; -} - -bool ResolvServer::Ready() -{ - return m_ready; -} - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // ENABLE_RESOLVER - - diff --git a/dep/sockets/ResolvSocket.cpp b/dep/sockets/ResolvSocket.cpp deleted file mode 100644 index 636de276426..00000000000 --- a/dep/sockets/ResolvSocket.cpp +++ /dev/null @@ -1,426 +0,0 @@ -/** \file ResolvSocket.cpp - ** \date 2005-03-24 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifdef _WIN32 -#ifdef _MSC_VER -#pragma warning(disable:4786) -#pragma warning(disable:4503) -#endif -#else -#include <netdb.h> -#endif -#include "ResolvSocket.h" -#ifdef ENABLE_RESOLVER -#include "Utility.h" -#include "Parse.h" -#include "ISocketHandler.h" -#include "Lock.h" -#include "Mutex.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -//#ifdef _DEBUG -//#define DEB(x) x -//#else -#define DEB(x) -//#endif - -// static -ResolvSocket::cache_t ResolvSocket::m_cache; -ResolvSocket::timeout_t ResolvSocket::m_cache_to; -Mutex ResolvSocket::m_cache_mutex; - -ResolvSocket::ResolvSocket(ISocketHandler& h) -:TcpSocket(h) -,m_bServer(false) -,m_parent(NULL) -#ifdef ENABLE_IPV6 -,m_resolve_ipv6(false) -#endif -,m_cached(false) -{ - SetLineProtocol(); -} - -ResolvSocket::ResolvSocket(ISocketHandler& h, Socket *parent, const std::string& host, port_t port, bool ipv6) -:TcpSocket(h) -,m_bServer(false) -,m_parent(parent) -,m_resolv_host(host) -,m_resolv_port(port) -#ifdef ENABLE_IPV6 -,m_resolve_ipv6(ipv6) -#endif -,m_cached(false) -{ - SetLineProtocol(); -} - -ResolvSocket::ResolvSocket(ISocketHandler& h, Socket *parent, ipaddr_t a) -:TcpSocket(h) -,m_bServer(false) -,m_parent(parent) -,m_resolv_port(0) -,m_resolv_address(a) -#ifdef ENABLE_IPV6 -,m_resolve_ipv6(false) -#endif -,m_cached(false) -{ - SetLineProtocol(); -} - -#ifdef ENABLE_IPV6 -ResolvSocket::ResolvSocket(ISocketHandler& h, Socket *parent, in6_addr& a) -:TcpSocket(h) -,m_bServer(false) -,m_parent(parent) -,m_resolv_port(0) -,m_resolve_ipv6(true) -,m_resolv_address6(a) -,m_cached(false) -{ - SetLineProtocol(); -} -#endif - -ResolvSocket::~ResolvSocket() -{ -} - -void ResolvSocket::OnLine(const std::string& line) -{ - Parse pa(line, ":"); - if (m_bServer) - { - m_query = pa.getword(); - m_data = pa.getrest(); -DEB( fprintf(stderr, " *** ResolvSocket server; query=%s, data=%s\n", m_query.c_str(), m_data.c_str());) - // %! check cache - { - Lock lock(m_cache_mutex); - if (m_cache[m_query].find(m_data) != m_cache[m_query].end()) - { - if (time(NULL) - m_cache_to[m_query][m_data] < 3600) // ttl - { - std::string result = m_cache[m_query][m_data]; -DEB(fprintf(stderr, " *** Returning cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), result.c_str());) - Send("Cached\n"); - if (!result.size()) /* failed */ - { - Send("Failed\n\n"); - SetCloseAndDelete(); - return; - } - else - if (m_query == "gethostbyname") - { - Send("A: " + result + "\n\n"); - SetCloseAndDelete(); - return; - } - else -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (m_query == "gethostbyname2") - { - Send("AAAA: " + result + "\n\n"); - SetCloseAndDelete(); - return; - } - else -#endif -#endif - if (m_query == "gethostbyaddr") - { - Send("Name: " + result + "\n\n"); - SetCloseAndDelete(); - return; - } - } - } - } - if (!Detach()) // detach failed? - { - SetCloseAndDelete(); - } - return; - } - std::string key = pa.getword(); - std::string value = pa.getrest(); -DEB( fprintf(stderr, " *** ResolvSocket response; %s: %s\n", key.c_str(), value.c_str());) - - if (key == "Cached") - { - m_cached = true; - } - else - if (key == "Failed" && m_parent) - { -DEB( fprintf(stderr, " ************ Resolve failed\n");) - if (Handler().Resolving(m_parent) || Handler().Valid(m_parent)) - { - m_parent -> OnResolveFailed(m_resolv_id); - } - // update cache - if (!m_cached) - { - Lock lock(m_cache_mutex); -DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), value.c_str());) - m_cache[m_query][m_data] = value; - m_cache_to[m_query][m_data] = time(NULL); - } - m_parent = NULL; - } - else - if (key == "Name" && !m_resolv_host.size() && m_parent) - { - if (Handler().Resolving(m_parent) || Handler().Valid(m_parent)) - { - m_parent -> OnReverseResolved(m_resolv_id, value); - } - // update cache - if (!m_cached) - { - Lock lock(m_cache_mutex); -DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), value.c_str());) - m_cache[m_query][m_data] = value; - m_cache_to[m_query][m_data] = time(NULL); - } - m_parent = NULL; - } - else - if (key == "A" && m_parent) - { - if (Handler().Resolving(m_parent) || Handler().Valid(m_parent)) - { - ipaddr_t l; - Utility::u2ip(value, l); // ip2ipaddr_t - m_parent -> OnResolved(m_resolv_id, l, m_resolv_port); - } - // update cache - if (!m_cached) - { - Lock lock(m_cache_mutex); -DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), value.c_str());) - m_cache[m_query][m_data] = value; - m_cache_to[m_query][m_data] = time(NULL); - } - m_parent = NULL; // always use first ip in case there are several - } -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - else - if (key == "AAAA" && m_parent) - { - if (Handler().Resolving(m_parent) || Handler().Valid(m_parent)) - { - in6_addr a; - Utility::u2ip(value, a); - m_parent -> OnResolved(m_resolv_id, a, m_resolv_port); - } - // update cache - if (!m_cached) - { - Lock lock(m_cache_mutex); -DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), value.c_str());) - m_cache[m_query][m_data] = value; - m_cache_to[m_query][m_data] = time(NULL); - } - m_parent = NULL; - } -#endif -#endif -} - -void ResolvSocket::OnDetached() -{ -DEB( fprintf(stderr, " *** ResolvSocket::OnDetached(); query=%s, data=%s\n", m_query.c_str(), m_data.c_str());) - if (m_query == "gethostbyname") - { - struct sockaddr_in sa; - if (Utility::u2ip(m_data, sa)) - { - std::string ip; - Utility::l2ip(sa.sin_addr, ip); - Send("A: " + ip + "\n"); - } - else - { - Send("Failed\n"); - } - Send("\n"); - } - else -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (m_query == "gethostbyname2") - { - struct sockaddr_in6 sa; - if (Utility::u2ip(m_data, sa)) - { - std::string ip; - Utility::l2ip(sa.sin6_addr, ip); - Send("AAAA: " + ip + "\n"); - } - else - { - Send("Failed\n"); - } - Send("\n"); - } - else -#endif -#endif - if (m_query == "gethostbyaddr") - { - if (Utility::isipv4( m_data )) - { - struct sockaddr_in sa; - if (!Utility::u2ip(m_data, sa, AI_NUMERICHOST)) - { - Send("Failed: convert to sockaddr_in failed\n"); - } - else - { - std::string name; - if (!Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), name)) - { - Send("Failed: ipv4 reverse lookup of " + m_data + "\n"); - } - else - { - Send("Name: " + name + "\n"); - } - } - } - else -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (Utility::isipv6( m_data )) - { - struct sockaddr_in6 sa; - if (!Utility::u2ip(m_data, sa, AI_NUMERICHOST)) - { - Send("Failed: convert to sockaddr_in6 failed\n"); - } - else - { - std::string name; - if (!Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), name)) - { - Send("Failed: ipv6 reverse lookup of " + m_data + "\n"); - } - else - { - Send("Name: " + name + "\n"); - } - } - } - else -#endif -#endif - { - Send("Failed: malformed address\n"); - } - Send("\n"); - } - else - { - std::string msg = "Unknown query type: " + m_query; - Handler().LogError(this, "OnDetached", 0, msg); - Send("Unknown\n\n"); - } - SetCloseAndDelete(); -} - -void ResolvSocket::OnConnect() -{ - if (!m_resolv_host.empty()) - { -#ifdef ENABLE_IPV6 - std::string msg = (m_resolve_ipv6 ? "gethostbyname2 " : "gethostbyname ") + m_resolv_host + "\n"; - m_query = m_resolve_ipv6 ? "gethostbyname2" : "gethostbyname"; -#else - std::string msg = "gethostbyname " + m_resolv_host + "\n"; - m_query = "gethostbyname"; -#endif - m_data = m_resolv_host; - Send( msg ); - return; - } -#ifdef ENABLE_IPV6 - if (m_resolve_ipv6) - { - std::string tmp; - Utility::l2ip(m_resolv_address6, tmp); - m_query = "gethostbyaddr"; - m_data = tmp; - std::string msg = "gethostbyaddr " + tmp + "\n"; - Send( msg ); - } -#endif - std::string tmp; - Utility::l2ip(m_resolv_address, tmp); - m_query = "gethostbyaddr"; - m_data = tmp; - std::string msg = "gethostbyaddr " + tmp + "\n"; - Send( msg ); -} - -void ResolvSocket::OnDelete() -{ - if (m_parent) - { - if (Handler().Resolving(m_parent) || Handler().Valid(m_parent)) - { - m_parent -> OnResolveFailed(m_resolv_id); - } - // update cache - if (!m_cached) - { - Lock lock(m_cache_mutex); - std::string value; -DEB(fprintf(stderr, " *** Update cache for [%s][%s] = '%s'\n", m_query.c_str(), m_data.c_str(), value.c_str());) - m_cache[m_query][m_data] = value; - m_cache_to[m_query][m_data] = time(NULL); - } - m_parent = NULL; - } -} - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // ENABLE_RESOLVER - - diff --git a/dep/sockets/Socket.cpp b/dep/sockets/Socket.cpp deleted file mode 100644 index f53cd27621e..00000000000 --- a/dep/sockets/Socket.cpp +++ /dev/null @@ -1,1726 +0,0 @@ -/** \file Socket.cpp - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include "Socket.h" -#ifdef _WIN32 -#ifdef _MSC_VER -#pragma warning(disable:4786) -#endif -#include <stdlib.h> -#else -#include <errno.h> -#include <netdb.h> -#endif -#include <ctype.h> -#include <fcntl.h> - -#include "ISocketHandler.h" -#include "Utility.h" - -#include "SocketAddress.h" -#include "SocketHandler.h" -#ifdef ENABLE_EXCEPTIONS -#include "Exception.h" -#endif -#include "Ipv4Address.h" - -//#ifdef _DEBUG -//#define DEB(x) x; fflush(stderr); -//#else -#define DEB(x) -//#endif - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -// statics -#ifdef _WIN32 -WSAInitializer Socket::m_winsock_init; -#endif - -Socket::Socket(ISocketHandler& h) -//:m_flags(0) -:m_handler(h) -,m_socket( INVALID_SOCKET ) -,m_bDel(false) -,m_bClose(false) -,m_tCreate(time(NULL)) -,m_parent(NULL) -,m_b_disable_read(false) -,m_connected(false) -,m_b_erased_by_handler(false) -,m_tClose(0) -,m_client_remote_address(NULL) -,m_remote_address(NULL) -,m_traffic_monitor(NULL) -,m_bLost(false) -#ifdef HAVE_OPENSSL -,m_b_enable_ssl(false) -,m_b_ssl(false) -,m_b_ssl_server(false) -#endif -#ifdef ENABLE_IPV6 -,m_ipv6(false) -#endif -#ifdef ENABLE_POOL -,m_socket_type(0) -,m_bClient(false) -,m_bRetain(false) -#endif -#ifdef ENABLE_SOCKS4 -,m_bSocks4(false) -,m_socks4_host(h.GetSocks4Host()) -,m_socks4_port(h.GetSocks4Port()) -,m_socks4_userid(h.GetSocks4Userid()) -#endif -#ifdef ENABLE_DETACH -,m_detach(false) -,m_detached(false) -,m_pThread(NULL) -,m_slave_handler(NULL) -#endif -{ -} - -Socket::~Socket() -{ - Handler().Remove(this); - if (m_socket != INVALID_SOCKET -#ifdef ENABLE_POOL - && !m_bRetain -#endif - ) - { - Close(); - } -} - -void Socket::Init() -{ -} - -void Socket::OnRead() -{ -} - -void Socket::OnWrite() -{ -} - -void Socket::OnException() -{ - // %! exception doesn't always mean something bad happened, this code should be reworked - // errno valid here? - int err = SoError(); - Handler().LogError(this, "exception on select", err, StrError(err), LOG_LEVEL_FATAL); - SetCloseAndDelete(); -} - -void Socket::OnDelete() -{ -} - -void Socket::OnConnect() -{ -} - -void Socket::OnAccept() -{ -} - -int Socket::Close() -{ - if (m_socket == INVALID_SOCKET) // this could happen - { - Handler().LogError(this, "Socket::Close", 0, "file descriptor invalid", LOG_LEVEL_WARNING); - return 0; - } - int n; - if ((n = closesocket(m_socket)) == -1) - { - // failed... - Handler().LogError(this, "close", Errno, StrError(Errno), LOG_LEVEL_ERROR); - } - Handler().Set(m_socket, false, false, false); // remove from fd_set's - Handler().AddList(m_socket, LIST_CALLONCONNECT, false); -#ifdef ENABLE_DETACH - Handler().AddList(m_socket, LIST_DETACH, false); -#endif - Handler().AddList(m_socket, LIST_TIMEOUT, false); - Handler().AddList(m_socket, LIST_RETRY, false); - Handler().AddList(m_socket, LIST_CLOSE, false); - m_socket = INVALID_SOCKET; - return n; -} - -SOCKET Socket::CreateSocket(int af,int type, const std::string& protocol) -{ - struct protoent *p = NULL; - SOCKET s; - -#ifdef ENABLE_POOL - m_socket_type = type; - m_socket_protocol = protocol; -#endif - if (!protocol.empty()) - { - p = getprotobyname( protocol.c_str() ); - if (!p) - { - Handler().LogError(this, "getprotobyname", Errno, StrError(Errno), LOG_LEVEL_FATAL); - SetCloseAndDelete(); -#ifdef ENABLE_EXCEPTIONS - throw Exception(std::string("getprotobyname() failed: ") + StrError(Errno)); -#endif - return INVALID_SOCKET; - } - } - int protno = p ? p -> p_proto : 0; - - s = socket(af, type, protno); - if (s == INVALID_SOCKET) - { - Handler().LogError(this, "socket", Errno, StrError(Errno), LOG_LEVEL_FATAL); - SetCloseAndDelete(); -#ifdef ENABLE_EXCEPTIONS - throw Exception(std::string("socket() failed: ") + StrError(Errno)); -#endif - return INVALID_SOCKET; - } - Attach(s); - OnOptions(af, type, protno, s); - Attach(INVALID_SOCKET); - return s; -} - -void Socket::Attach(SOCKET s) -{ - m_socket = s; -} - -SOCKET Socket::GetSocket() -{ - return m_socket; -} - -void Socket::SetDeleteByHandler(bool x) -{ - m_bDel = x; -} - -bool Socket::DeleteByHandler() -{ - return m_bDel; -} - -void Socket::SetCloseAndDelete(bool x) -{ - if (x != m_bClose) - { - Handler().AddList(m_socket, LIST_CLOSE, x); - m_bClose = x; - if (x) - { - m_tClose = time(NULL); - } - } -} - -bool Socket::CloseAndDelete() -{ - return m_bClose; -} - -void Socket::SetRemoteAddress(SocketAddress& ad) //struct sockaddr* sa, socklen_t l) -{ - m_remote_address = ad.GetCopy(); -} - -std::auto_ptr<SocketAddress> Socket::GetRemoteSocketAddress() -{ - return m_remote_address -> GetCopy(); -} - -ISocketHandler& Socket::Handler() const -{ -#ifdef ENABLE_DETACH - if (IsDetached()) - return *m_slave_handler; -#endif - return m_handler; -} - -ISocketHandler& Socket::MasterHandler() const -{ - return m_handler; -} - -ipaddr_t Socket::GetRemoteIP4() -{ - ipaddr_t l = 0; -#ifdef ENABLE_IPV6 - if (m_ipv6) - { - Handler().LogError(this, "GetRemoteIP4", 0, "get ipv4 address for ipv6 socket", LOG_LEVEL_WARNING); - } -#endif - if (m_remote_address.get() != NULL) - { - struct sockaddr *p = *m_remote_address; - struct sockaddr_in *sa = (struct sockaddr_in *)p; - memcpy(&l, &sa -> sin_addr, sizeof(struct in_addr)); - } - return l; -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -struct in6_addr Socket::GetRemoteIP6() -{ - if (!m_ipv6) - { - Handler().LogError(this, "GetRemoteIP6", 0, "get ipv6 address for ipv4 socket", LOG_LEVEL_WARNING); - } - struct sockaddr_in6 fail; - if (m_remote_address.get() != NULL) - { - struct sockaddr *p = *m_remote_address; - memcpy(&fail, p, sizeof(struct sockaddr_in6)); - } - else - { - memset(&fail, 0, sizeof(struct sockaddr_in6)); - } - return fail.sin6_addr; -} -#endif -#endif - -port_t Socket::GetRemotePort() -{ - if (!m_remote_address.get()) - { - return 0; - } - return m_remote_address -> GetPort(); -} - -std::string Socket::GetRemoteAddress() -{ - if (!m_remote_address.get()) - { - return ""; - } - return m_remote_address -> Convert(false); -} - -std::string Socket::GetRemoteHostname() -{ - if (!m_remote_address.get()) - { - return ""; - } - return m_remote_address -> Reverse(); -} - -bool Socket::SetNonblocking(bool bNb) -{ -#ifdef _WIN32 - unsigned long l = bNb ? 1 : 0; - int n = ioctlsocket(m_socket, FIONBIO, &l); - if (n != 0) - { - Handler().LogError(this, "ioctlsocket(FIONBIO)", Errno, ""); - return false; - } - return true; -#else - if (bNb) - { - if (fcntl(m_socket, F_SETFL, O_NONBLOCK) == -1) - { - Handler().LogError(this, "fcntl(F_SETFL, O_NONBLOCK)", Errno, StrError(Errno), LOG_LEVEL_ERROR); - return false; - } - } - else - { - if (fcntl(m_socket, F_SETFL, 0) == -1) - { - Handler().LogError(this, "fcntl(F_SETFL, 0)", Errno, StrError(Errno), LOG_LEVEL_ERROR); - return false; - } - } - return true; -#endif -} - -bool Socket::SetNonblocking(bool bNb, SOCKET s) -{ -#ifdef _WIN32 - unsigned long l = bNb ? 1 : 0; - int n = ioctlsocket(s, FIONBIO, &l); - if (n != 0) - { - Handler().LogError(this, "ioctlsocket(FIONBIO)", Errno, ""); - return false; - } - return true; -#else - if (bNb) - { - if (fcntl(s, F_SETFL, O_NONBLOCK) == -1) - { - Handler().LogError(this, "fcntl(F_SETFL, O_NONBLOCK)", Errno, StrError(Errno), LOG_LEVEL_ERROR); - return false; - } - } - else - { - if (fcntl(s, F_SETFL, 0) == -1) - { - Handler().LogError(this, "fcntl(F_SETFL, 0)", Errno, StrError(Errno), LOG_LEVEL_ERROR); - return false; - } - } - return true; -#endif -} - -void Socket::Set(bool bRead, bool bWrite, bool bException) -{ - Handler().Set(m_socket, bRead, bWrite, bException); -} - -bool Socket::Ready() -{ - if (m_socket != INVALID_SOCKET && !CloseAndDelete()) - return true; - return false; -} - -void Socket::OnLine(const std::string& ) -{ -} - -void Socket::OnConnectFailed() -{ -} - -Socket *Socket::GetParent() -{ - return m_parent; -} - -void Socket::SetParent(Socket *x) -{ - m_parent = x; -} - -port_t Socket::GetPort() -{ - Handler().LogError(this, "GetPort", 0, "GetPort only implemented for ListenSocket", LOG_LEVEL_WARNING); - return 0; -} - -bool Socket::OnConnectRetry() -{ - return true; -} - -#ifdef ENABLE_RECONNECT -void Socket::OnReconnect() -{ -} -#endif - -time_t Socket::Uptime() -{ - return time(NULL) - m_tCreate; -} - -#ifdef ENABLE_IPV6 -void Socket::SetIpv6(bool x) -{ - m_ipv6 = x; -} - -bool Socket::IsIpv6() -{ - return m_ipv6; -} -#endif - -void Socket::DisableRead(bool x) -{ - m_b_disable_read = x; -} - -bool Socket::IsDisableRead() -{ - return m_b_disable_read; -} - -void Socket::SendBuf(const char *,size_t,int) -{ -} - -void Socket::Send(const std::string&,int) -{ -} - -void Socket::SetConnected(bool x) -{ - m_connected = x; -} - -bool Socket::IsConnected() -{ - return m_connected; -} - -void Socket::OnDisconnect() -{ -} - -void Socket::SetLost() -{ - m_bLost = true; -} - -bool Socket::Lost() -{ - return m_bLost; -} - -void Socket::SetErasedByHandler(bool x) -{ - m_b_erased_by_handler = x; -} - -bool Socket::ErasedByHandler() -{ - return m_b_erased_by_handler; -} - -time_t Socket::TimeSinceClose() -{ - return time(NULL) - m_tClose; -} - -void Socket::SetClientRemoteAddress(SocketAddress& ad) -{ - if (!ad.IsValid()) - { - Handler().LogError(this, "SetClientRemoteAddress", 0, "remote address not valid", LOG_LEVEL_ERROR); - } - m_client_remote_address = ad.GetCopy(); -} - -std::auto_ptr<SocketAddress> Socket::GetClientRemoteAddress() -{ - if (!m_client_remote_address.get()) - { - Handler().LogError(this, "GetClientRemoteAddress", 0, "remote address not yet set", LOG_LEVEL_ERROR); - } - return m_client_remote_address -> GetCopy(); -} - -uint64_t Socket::GetBytesSent(bool) -{ - return 0; -} - -uint64_t Socket::GetBytesReceived(bool) -{ - return 0; -} - -#ifdef HAVE_OPENSSL -void Socket::OnSSLConnect() -{ -} - -void Socket::OnSSLAccept() -{ -} - -bool Socket::SSLNegotiate() -{ - return false; -} - -bool Socket::IsSSL() -{ - return m_b_enable_ssl; -} - -void Socket::EnableSSL(bool x) -{ - m_b_enable_ssl = x; -} - -bool Socket::IsSSLNegotiate() -{ - return m_b_ssl; -} - -void Socket::SetSSLNegotiate(bool x) -{ - m_b_ssl = x; -} - -bool Socket::IsSSLServer() -{ - return m_b_ssl_server; -} - -void Socket::SetSSLServer(bool x) -{ - m_b_ssl_server = x; -} - -void Socket::OnSSLConnectFailed() -{ -} - -void Socket::OnSSLAcceptFailed() -{ -} -#endif // HAVE_OPENSSL - -#ifdef ENABLE_POOL -void Socket::CopyConnection(Socket *sock) -{ - Attach( sock -> GetSocket() ); -#ifdef ENABLE_IPV6 - SetIpv6( sock -> IsIpv6() ); -#endif - SetSocketType( sock -> GetSocketType() ); - SetSocketProtocol( sock -> GetSocketProtocol() ); - - SetClientRemoteAddress( *sock -> GetClientRemoteAddress() ); - SetRemoteAddress( *sock -> GetRemoteSocketAddress() ); -} - -void Socket::SetIsClient() -{ - m_bClient = true; -} - -void Socket::SetSocketType(int x) -{ - m_socket_type = x; -} - -int Socket::GetSocketType() -{ - return m_socket_type; -} - -void Socket::SetSocketProtocol(const std::string& x) -{ - m_socket_protocol = x; -} - -const std::string& Socket::GetSocketProtocol() -{ - return m_socket_protocol; -} - -void Socket::SetRetain() -{ - if (m_bClient) m_bRetain = true; -} - -bool Socket::Retain() -{ - return m_bRetain; -} - -#endif // ENABLE_POOL - -#ifdef ENABLE_SOCKS4 -void Socket::OnSocks4Connect() -{ - Handler().LogError(this, "OnSocks4Connect", 0, "Use with TcpSocket only"); -} - -void Socket::OnSocks4ConnectFailed() -{ - Handler().LogError(this, "OnSocks4ConnectFailed", 0, "Use with TcpSocket only"); -} - -bool Socket::OnSocks4Read() -{ - Handler().LogError(this, "OnSocks4Read", 0, "Use with TcpSocket only"); - return true; -} - -void Socket::SetSocks4Host(const std::string& host) -{ - Utility::u2ip(host, m_socks4_host); -} - -bool Socket::Socks4() -{ - return m_bSocks4; -} - -void Socket::SetSocks4(bool x) -{ - m_bSocks4 = x; -} - -void Socket::SetSocks4Host(ipaddr_t a) -{ - m_socks4_host = a; -} - -void Socket::SetSocks4Port(port_t p) -{ - m_socks4_port = p; -} - -void Socket::SetSocks4Userid(const std::string& x) -{ - m_socks4_userid = x; -} - -ipaddr_t Socket::GetSocks4Host() -{ - return m_socks4_host; -} - -port_t Socket::GetSocks4Port() -{ - return m_socks4_port; -} - -const std::string& Socket::GetSocks4Userid() -{ - return m_socks4_userid; -} -#endif // ENABLE_SOCKS4 - -#ifdef ENABLE_DETACH -bool Socket::Detach() -{ - if (!DeleteByHandler()) - return false; - if (m_pThread) - return false; - if (m_detached) - return false; - SetDetach(); - return true; -} - -void Socket::DetachSocket() -{ - SetDetached(); - m_pThread = new SocketThread(this); - m_pThread -> SetRelease(true); -} - -void Socket::OnDetached() -{ -} - -void Socket::SetDetach(bool x) -{ - Handler().AddList(m_socket, LIST_DETACH, x); - m_detach = x; -} - -bool Socket::IsDetach() -{ - return m_detach; -} - -void Socket::SetDetached(bool x) -{ - m_detached = x; -} - -const bool Socket::IsDetached() const -{ - return m_detached; -} - -void Socket::SetSlaveHandler(ISocketHandler *p) -{ - m_slave_handler = p; -} - -Socket::SocketThread::SocketThread(Socket *p) -:Thread(false) -,m_socket(p) -{ - // Creator will release -} - -Socket::SocketThread::~SocketThread() -{ - if (IsRunning()) - { - SetRelease(true); - SetRunning(false); -#ifdef _WIN32 - Sleep(1000); -#else - sleep(1); -#endif - } -} - -void Socket::SocketThread::Run() -{ - SocketHandler h; - h.SetSlave(); - h.Add(m_socket); - m_socket -> SetSlaveHandler(&h); - m_socket -> OnDetached(); - while (h.GetCount() && IsRunning()) - { - h.Select(0, 500000); - } - // m_socket now deleted oops - // yeah oops m_socket delete its socket thread, that means this - // so Socket will no longer delete its socket thread, instead we do this: - SetDeleteOnExit(); -} -#endif // ENABLE_DETACH - -#ifdef ENABLE_RESOLVER -int Socket::Resolve(const std::string& host,port_t port) -{ - return Handler().Resolve(this, host, port); -} - -#ifdef ENABLE_IPV6 -int Socket::Resolve6(const std::string& host,port_t port) -{ - return Handler().Resolve6(this, host, port); -} -#endif - -int Socket::Resolve(ipaddr_t a) -{ - return Handler().Resolve(this, a); -} - -#ifdef ENABLE_IPV6 -int Socket::Resolve(in6_addr& a) -{ - return Handler().Resolve(this, a); -} -#endif - -void Socket::OnResolved(int,ipaddr_t,port_t) -{ -} - -#ifdef ENABLE_IPV6 -void Socket::OnResolved(int,in6_addr&,port_t) -{ -} -#endif - -void Socket::OnReverseResolved(int,const std::string&) -{ -} - -void Socket::OnResolveFailed(int) -{ -} -#endif // ENABLE_RESOLVER - -/* IP options */ - -bool Socket::SetIpOptions(const void *p, socklen_t len) -{ -#ifdef IP_OPTIONS - if (setsockopt(GetSocket(), IPPROTO_IP, IP_OPTIONS, (char *)p, len) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_OPTIONS)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "ip option not available", 0, "IP_OPTIONS", LOG_LEVEL_INFO); - return false; -#endif -} - -#ifdef IP_PKTINFO -bool Socket::SetIpPktinfo(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IP, IP_PKTINFO, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_PKTINFO)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -#ifdef IP_RECVTOS -bool Socket::SetIpRecvTOS(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IP, IP_RECVTOS, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RECVTOS)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -#ifdef IP_RECVTTL -bool Socket::SetIpRecvTTL(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IP, IP_RECVTTL, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RECVTTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -#ifdef IP_RECVOPTS -bool Socket::SetIpRecvopts(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IP, IP_RECVOPTS, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RECVOPTS)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -#ifdef IP_RETOPTS -bool Socket::SetIpRetopts(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IP, IP_RETOPTS, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RETOPTS)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -bool Socket::SetIpTOS(unsigned char tos) -{ -#ifdef IP_TOS - if (setsockopt(GetSocket(), IPPROTO_IP, IP_TOS, (char *)&tos, sizeof(tos)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_TOS)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "ip option not available", 0, "IP_TOS", LOG_LEVEL_INFO); - return false; -#endif -} - -unsigned char Socket::IpTOS() -{ - unsigned char tos = 0; -#ifdef IP_TOS - socklen_t len = sizeof(tos); - if (getsockopt(GetSocket(), IPPROTO_IP, IP_TOS, (char *)&tos, &len) == -1) - { - Handler().LogError(this, "getsockopt(IPPROTO_IP, IP_TOS)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - } -#else - Handler().LogError(this, "ip option not available", 0, "IP_TOS", LOG_LEVEL_INFO); -#endif - return tos; -} - -bool Socket::SetIpTTL(int ttl) -{ -#ifdef IP_TTL - if (setsockopt(GetSocket(), IPPROTO_IP, IP_TTL, (char *)&ttl, sizeof(ttl)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_TTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "ip option not available", 0, "IP_TTL", LOG_LEVEL_INFO); - return false; -#endif -} - -int Socket::IpTTL() -{ - int ttl = 0; -#ifdef IP_TTL - socklen_t len = sizeof(ttl); - if (getsockopt(GetSocket(), IPPROTO_IP, IP_TTL, (char *)&ttl, &len) == -1) - { - Handler().LogError(this, "getsockopt(IPPROTO_IP, IP_TTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - } -#else - Handler().LogError(this, "ip option not available", 0, "IP_TTL", LOG_LEVEL_INFO); -#endif - return ttl; -} - -bool Socket::SetIpHdrincl(bool x) -{ -#ifdef IP_HDRINCL - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IP, IP_HDRINCL, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_HDRINCL)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "ip option not available", 0, "IP_HDRINCL", LOG_LEVEL_INFO); - return false; -#endif -} - -#ifdef IP_RECVERR -bool Socket::SetIpRecverr(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IP, IP_RECVERR, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_RECVERR)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -#ifdef IP_MTU_DISCOVER -bool Socket::SetIpMtudiscover(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IP, IP_MTU_DISCOVER, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_MTU_DISCOVER)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -#ifdef IP_MTU -int Socket::IpMtu() -{ - int mtu = 0; - socklen_t len = sizeof(mtu); - if (getsockopt(GetSocket(), IPPROTO_IP, IP_MTU, (char *)&mtu, &len) == -1) - { - Handler().LogError(this, "getsockopt(IPPROTO_IP, IP_MTU)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - } - return mtu; -} -#endif - -#ifdef IP_ROUTER_ALERT -bool Socket::SetIpRouterAlert(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IP, IP_ROUTER_ALERT, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_ROUTER_ALERT)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -bool Socket::SetIpMulticastTTL(int ttl) -{ -#ifdef IP_MULTICAST_TTL - if (setsockopt(GetSocket(), IPPROTO_IP, IP_MULTICAST_TTL, (char *)&ttl, sizeof(ttl)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_MULTICAST_TTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "ip option not available", 0, "IP_MULTICAST_TTL", LOG_LEVEL_INFO); - return false; -#endif -} - -int Socket::IpMulticastTTL() -{ - int ttl = 0; -#ifdef IP_MULTICAST_TTL - socklen_t len = sizeof(ttl); - if (getsockopt(GetSocket(), IPPROTO_IP, IP_MULTICAST_TTL, (char *)&ttl, &len) == -1) - { - Handler().LogError(this, "getsockopt(IPPROTO_IP, IP_MULTICAST_TTL)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - } -#else - Handler().LogError(this, "ip option not available", 0, "IP_MULTICAST_TTL", LOG_LEVEL_INFO); -#endif - return ttl; -} - -bool Socket::SetMulticastLoop(bool x) -{ -#ifdef IP_MULTICAST_LOOP - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IP, IP_MULTICAST_LOOP, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_MULTICAST_LOOP)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "ip option not available", 0, "IP_MULTICAST_LOOP", LOG_LEVEL_INFO); - return false; -#endif -} - -#ifdef LINUX -bool Socket::IpAddMembership(struct ip_mreqn& ref) -{ -#ifdef IP_ADD_MEMBERSHIP - if (setsockopt(GetSocket(), IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&ref, sizeof(struct ip_mreqn)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "ip option not available", 0, "IP_ADD_MEMBERSHIP", LOG_LEVEL_INFO); - return false; -#endif -} -#endif - -bool Socket::IpAddMembership(struct ip_mreq& ref) -{ -#ifdef IP_ADD_MEMBERSHIP - if (setsockopt(GetSocket(), IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&ref, sizeof(struct ip_mreq)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "ip option not available", 0, "IP_ADD_MEMBERSHIP", LOG_LEVEL_INFO); - return false; -#endif -} - -#ifdef LINUX -bool Socket::IpDropMembership(struct ip_mreqn& ref) -{ -#ifdef IP_DROP_MEMBERSHIP - if (setsockopt(GetSocket(), IPPROTO_IP, IP_DROP_MEMBERSHIP, (char *)&ref, sizeof(struct ip_mreqn)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_DROP_MEMBERSHIP)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "ip option not available", 0, "IP_DROP_MEMBERSHIP", LOG_LEVEL_INFO); - return false; -#endif -} -#endif - -bool Socket::IpDropMembership(struct ip_mreq& ref) -{ -#ifdef IP_DROP_MEMBERSHIP - if (setsockopt(GetSocket(), IPPROTO_IP, IP_DROP_MEMBERSHIP, (char *)&ref, sizeof(struct ip_mreq)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_IP, IP_DROP_MEMBERSHIP)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "ip option not available", 0, "IP_DROP_MEMBERSHIP", LOG_LEVEL_INFO); - return false; -#endif -} - -/* SOCKET options */ - -bool Socket::SetSoReuseaddr(bool x) -{ -#ifdef SO_REUSEADDR - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_REUSEADDR, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_REUSEADDR)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_REUSEADDR", LOG_LEVEL_INFO); - return false; -#endif -} - -bool Socket::SetSoKeepalive(bool x) -{ -#ifdef SO_KEEPALIVE - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_KEEPALIVE, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_KEEPALIVE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_KEEPALIVE", LOG_LEVEL_INFO); - return false; -#endif -} - -#ifdef SO_NOSIGPIPE -bool Socket::SetSoNosigpipe(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_NOSIGPIPE, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_NOSIGPIPE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -bool Socket::SoAcceptconn() -{ - int value = 0; -#ifdef SO_ACCEPTCONN - socklen_t len = sizeof(value); - if (getsockopt(GetSocket(), SOL_SOCKET, SO_ACCEPTCONN, (char *)&value, &len) == -1) - { - Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_ACCEPTCONN)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - } -#else - Handler().LogError(this, "socket option not available", 0, "SO_ACCEPTCONN", LOG_LEVEL_INFO); -#endif - return value ? true : false; -} - -#ifdef SO_BSDCOMPAT -bool Socket::SetSoBsdcompat(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_BSDCOMPAT, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_BSDCOMPAT)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -#ifdef SO_BINDTODEVICE -bool Socket::SetSoBindtodevice(const std::string& intf) -{ - if (setsockopt(GetSocket(), SOL_SOCKET, SO_BINDTODEVICE, (char *)intf.c_str(), intf.size()) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_BINDTODEVICE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -bool Socket::SetSoBroadcast(bool x) -{ -#ifdef SO_BROADCAST - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_BROADCAST)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_BROADCAST", LOG_LEVEL_INFO); - return false; -#endif -} - -bool Socket::SetSoDebug(bool x) -{ -#ifdef SO_DEBUG - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_DEBUG, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_DEBUG)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_DEBUG", LOG_LEVEL_INFO); - return false; -#endif -} - -int Socket::SoError() -{ - int value = 0; -#ifdef SO_ERROR - socklen_t len = sizeof(value); - if (getsockopt(GetSocket(), SOL_SOCKET, SO_ERROR, (char *)&value, &len) == -1) - { - Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_ERROR)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - } -#else - Handler().LogError(this, "socket option not available", 0, "SO_ERROR", LOG_LEVEL_INFO); -#endif - return value; -} - -bool Socket::SetSoDontroute(bool x) -{ -#ifdef SO_DONTROUTE - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_DONTROUTE, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_DONTROUTE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_DONTROUTE", LOG_LEVEL_INFO); - return false; -#endif -} - -bool Socket::SetSoLinger(int onoff, int linger) -{ -#ifdef SO_LINGER - struct linger stl; - stl.l_onoff = onoff; - stl.l_linger = linger; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_LINGER, (char *)&stl, sizeof(stl)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_LINGER)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_LINGER", LOG_LEVEL_INFO); - return false; -#endif -} - -bool Socket::SetSoOobinline(bool x) -{ -#ifdef SO_OOBINLINE - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_OOBINLINE, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_OOBINLINE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_OOBINLINE", LOG_LEVEL_INFO); - return false; -#endif -} - -#ifdef SO_PASSCRED -bool Socket::SetSoPasscred(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_PASSCRED, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_PASSCRED)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -#ifdef SO_PEERCRED -bool Socket::SoPeercred(struct ucred& ucr) -{ - if (setsockopt(GetSocket(), SOL_SOCKET, SO_PEERCRED, (char *)&ucr, sizeof(ucr)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_PEERCRED)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -#ifdef SO_PRIORITY -bool Socket::SetSoPriority(int x) -{ - if (setsockopt(GetSocket(), SOL_SOCKET, SO_PRIORITY, (char *)&x, sizeof(x)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_PRIORITY)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -bool Socket::SetSoRcvlowat(int x) -{ -#ifdef SO_RCVLOWAT - if (setsockopt(GetSocket(), SOL_SOCKET, SO_RCVLOWAT, (char *)&x, sizeof(x)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_RCVLOWAT)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_RCVLOWAT", LOG_LEVEL_INFO); - return false; -#endif -} - -bool Socket::SetSoSndlowat(int x) -{ -#ifdef SO_SNDLOWAT - if (setsockopt(GetSocket(), SOL_SOCKET, SO_SNDLOWAT, (char *)&x, sizeof(x)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_SNDLOWAT)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_SNDLOWAT", LOG_LEVEL_INFO); - return false; -#endif -} - -bool Socket::SetSoRcvtimeo(struct timeval& tv) -{ -#ifdef SO_RCVTIMEO - if (setsockopt(GetSocket(), SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_RCVTIMEO)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_RCVTIMEO", LOG_LEVEL_INFO); - return false; -#endif -} - -bool Socket::SetSoSndtimeo(struct timeval& tv) -{ -#ifdef SO_SNDTIMEO - if (setsockopt(GetSocket(), SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_SNDTIMEO)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_SNDTIMEO", LOG_LEVEL_INFO); - return false; -#endif -} - -bool Socket::SetSoRcvbuf(int x) -{ -#ifdef SO_RCVBUF - if (setsockopt(GetSocket(), SOL_SOCKET, SO_RCVBUF, (char *)&x, sizeof(x)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_RCVBUF)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_RCVBUF", LOG_LEVEL_INFO); - return false; -#endif -} - -int Socket::SoRcvbuf() -{ - int value = 0; -#ifdef SO_RCVBUF - socklen_t len = sizeof(value); - if (getsockopt(GetSocket(), SOL_SOCKET, SO_RCVBUF, (char *)&value, &len) == -1) - { - Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_RCVBUF)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - } -#else - Handler().LogError(this, "socket option not available", 0, "SO_RCVBUF", LOG_LEVEL_INFO); -#endif - return value; -} - -#ifdef SO_RCVBUFFORCE -bool Socket::SetSoRcvbufforce(int x) -{ - if (setsockopt(GetSocket(), SOL_SOCKET, SO_RCVBUFFORCE, (char *)&x, sizeof(x)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_RCVBUFFORCE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -bool Socket::SetSoSndbuf(int x) -{ -#ifdef SO_SNDBUF - if (setsockopt(GetSocket(), SOL_SOCKET, SO_SNDBUF, (char *)&x, sizeof(x)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_SNDBUF)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "SO_SNDBUF", LOG_LEVEL_INFO); - return false; -#endif -} - -int Socket::SoSndbuf() -{ - int value = 0; -#ifdef SO_SNDBUF - socklen_t len = sizeof(value); - if (getsockopt(GetSocket(), SOL_SOCKET, SO_SNDBUF, (char *)&value, &len) == -1) - { - Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_SNDBUF)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - } -#else - Handler().LogError(this, "socket option not available", 0, "SO_SNDBUF", LOG_LEVEL_INFO); -#endif - return value; -} - -#ifdef SO_SNDBUFFORCE -bool Socket::SetSoSndbufforce(int x) -{ - if (setsockopt(GetSocket(), SOL_SOCKET, SO_SNDBUFFORCE, (char *)&x, sizeof(x)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_SNDBUFFORCE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -#ifdef SO_TIMESTAMP -bool Socket::SetSoTimestamp(bool x) -{ - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_SOCKET, SO_TIMESTAMP, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(SOL_SOCKET, SO_TIMESTAMP)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -} -#endif - -int Socket::SoType() -{ - int value = 0; -#ifdef SO_TYPE - socklen_t len = sizeof(value); - if (getsockopt(GetSocket(), SOL_SOCKET, SO_TYPE, (char *)&value, &len) == -1) - { - Handler().LogError(this, "getsockopt(SOL_SOCKET, SO_TYPE)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - } -#else - Handler().LogError(this, "socket option not available", 0, "SO_TYPE", LOG_LEVEL_INFO); -#endif - return value; -} - -#ifdef ENABLE_TRIGGERS -void Socket::Subscribe(int id) -{ - Handler().Subscribe(id, this); -} - -void Socket::Unsubscribe(int id) -{ - Handler().Unsubscribe(id, this); -} - -void Socket::OnTrigger(int, const TriggerData&) -{ -} - -void Socket::OnCancelled(int) -{ -} -#endif - -void Socket::SetTimeout(time_t secs) -{ - if (!secs) - { - Handler().AddList(m_socket, LIST_TIMEOUT, false); - return; - } - Handler().AddList(m_socket, LIST_TIMEOUT, true); - m_timeout_start = time(NULL); - m_timeout_limit = secs; -} - -void Socket::OnTimeout() -{ -} - -void Socket::OnConnectTimeout() -{ -} - -bool Socket::Timeout(time_t tnow) -{ - if (tnow - m_timeout_start > m_timeout_limit) - return true; - return false; -} - -/** Returns local port number for bound socket file descriptor. */ -port_t Socket::GetSockPort() -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - struct sockaddr_in6 sa; - socklen_t sockaddr_length = sizeof(struct sockaddr_in6); - if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1) - memset(&sa, 0, sizeof(sa)); - return ntohs(sa.sin6_port); - } -#endif -#endif - struct sockaddr_in sa; - socklen_t sockaddr_length = sizeof(struct sockaddr_in); - if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1) - memset(&sa, 0, sizeof(sa)); - return ntohs(sa.sin_port); -} - -/** Returns local ipv4 address for bound socket file descriptor. */ -ipaddr_t Socket::GetSockIP4() -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - return 0; - } -#endif -#endif - struct sockaddr_in sa; - socklen_t sockaddr_length = sizeof(struct sockaddr_in); - if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1) - memset(&sa, 0, sizeof(sa)); - ipaddr_t a; - memcpy(&a, &sa.sin_addr, 4); - return a; -} - -/** Returns local ipv4 address as text for bound socket file descriptor. */ -std::string Socket::GetSockAddress() -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - return ""; - } -#endif -#endif - struct sockaddr_in sa; - socklen_t sockaddr_length = sizeof(struct sockaddr_in); - if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1) - memset(&sa, 0, sizeof(sa)); - Ipv4Address addr( sa ); - return addr.Convert(); -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -/** Returns local ipv6 address for bound socket file descriptor. */ -struct in6_addr Socket::GetSockIP6() -{ - if (IsIpv6()) - { - struct sockaddr_in6 sa; - socklen_t sockaddr_length = sizeof(struct sockaddr_in6); - if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1) - memset(&sa, 0, sizeof(sa)); - return sa.sin6_addr; - } - struct in6_addr a; - memset(&a, 0, sizeof(a)); - return a; -} - -/** Returns local ipv6 address as text for bound socket file descriptor. */ -std::string Socket::GetSockAddress6() -{ - if (IsIpv6()) - { - struct sockaddr_in6 sa; - socklen_t sockaddr_length = sizeof(struct sockaddr_in6); - if (getsockname(GetSocket(), (struct sockaddr *)&sa, (socklen_t*)&sockaddr_length) == -1) - memset(&sa, 0, sizeof(sa)); - Ipv6Address addr( sa ); - return addr.Convert(); - } - return ""; -} -#endif -#endif - -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/dep/sockets/SocketHandler.cpp b/dep/sockets/SocketHandler.cpp deleted file mode 100644 index acf71fb2efa..00000000000 --- a/dep/sockets/SocketHandler.cpp +++ /dev/null @@ -1,1377 +0,0 @@ -/** \file SocketHandler.cpp - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifdef _WIN32 -#ifdef _MSC_VER -#pragma warning(disable:4786) -#endif -#endif -#include <stdlib.h> -#include <stdio.h> -#include <errno.h> -#include <cstdio> - -#include "SocketHandler.h" -#include "UdpSocket.h" -#include "ResolvSocket.h" -#include "ResolvServer.h" -#include "TcpSocket.h" -#include "Mutex.h" -#include "Utility.h" -#include "SocketAddress.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -//#ifdef _DEBUG -//#define DEB(x) x; fflush(stderr); -//#else -#define DEB(x) -//#endif - -SocketHandler::SocketHandler(StdLog *p) -:m_stdlog(p) -,m_mutex(m_mutex) -,m_b_use_mutex(false) -,m_maxsock(0) -,m_preverror(-1) -,m_errcnt(0) -,m_tlast(0) -#ifdef ENABLE_SOCKS4 -,m_socks4_host(0) -,m_socks4_port(0) -,m_bTryDirect(false) -#endif -#ifdef ENABLE_RESOLVER -,m_resolv_id(0) -,m_resolver(NULL) -#endif -#ifdef ENABLE_POOL -,m_b_enable_pool(false) -#endif -#ifdef ENABLE_TRIGGERS -,m_next_trigger_id(0) -#endif -#ifdef ENABLE_DETACH -,m_slave(false) -#endif -{ - FD_ZERO(&m_rfds); - FD_ZERO(&m_wfds); - FD_ZERO(&m_efds); -} - -SocketHandler::SocketHandler(Mutex& mutex,StdLog *p) -:m_stdlog(p) -,m_mutex(mutex) -,m_b_use_mutex(true) -,m_maxsock(0) -,m_preverror(-1) -,m_errcnt(0) -,m_tlast(0) -#ifdef ENABLE_SOCKS4 -,m_socks4_host(0) -,m_socks4_port(0) -,m_bTryDirect(false) -#endif -#ifdef ENABLE_RESOLVER -,m_resolv_id(0) -,m_resolver(NULL) -#endif -#ifdef ENABLE_POOL -,m_b_enable_pool(false) -#endif -#ifdef ENABLE_TRIGGERS -,m_next_trigger_id(0) -#endif -#ifdef ENABLE_DETACH -,m_slave(false) -#endif -{ - m_mutex.Lock(); - FD_ZERO(&m_rfds); - FD_ZERO(&m_wfds); - FD_ZERO(&m_efds); -} - -SocketHandler::~SocketHandler() -{ -#ifdef ENABLE_RESOLVER - if (m_resolver) - { - m_resolver -> Quit(); - } -#endif - { - while (m_sockets.size()) - { -DEB( fprintf(stderr, "Emptying sockets list in SocketHandler destructor, %d instances\n", (int)m_sockets.size());) - socket_m::iterator it = m_sockets.begin(); - Socket *p = it -> second; - if (p) - { -DEB( fprintf(stderr, " fd %d\n", p -> GetSocket());) - p -> Close(); -DEB( fprintf(stderr, " fd closed %d\n", p -> GetSocket());) -// p -> OnDelete(); // hey, I turn this back on. what's the worst that could happen??!! - // MinionSocket breaks, calling MinderHandler methods in OnDelete - - // MinderHandler is already gone when that happens... - - // only delete socket when controlled - // ie master sockethandler can delete non-detached sockets - // and a slave sockethandler can only delete a detach socket - if (p -> DeleteByHandler() -#ifdef ENABLE_DETACH - && !(m_slave ^ p -> IsDetached()) -#endif - ) - { - p -> SetErasedByHandler(); - delete p; - } - m_sockets.erase(it); - } - else - { - m_sockets.erase(it); - } -DEB( fprintf(stderr, "next\n");) - } -DEB( fprintf(stderr, "/Emptying sockets list in SocketHandler destructor, %d instances\n", (int)m_sockets.size());) - } -#ifdef ENABLE_RESOLVER - if (m_resolver) - { - delete m_resolver; - } -#endif - if (m_b_use_mutex) - { - m_mutex.Unlock(); - } -} - -Mutex& SocketHandler::GetMutex() const -{ - return m_mutex; -} - -#ifdef ENABLE_DETACH -void SocketHandler::SetSlave(bool x) -{ - m_slave = x; -} - -bool SocketHandler::IsSlave() -{ - return m_slave; -} -#endif - -void SocketHandler::RegStdLog(StdLog *log) -{ - m_stdlog = log; -} - -void SocketHandler::LogError(Socket *p,const std::string& user_text,int err,const std::string& sys_err,loglevel_t t) -{ - if (m_stdlog) - { - m_stdlog -> error(this, p, user_text, err, sys_err, t); - } -} - -void SocketHandler::Add(Socket *p) -{ - if (p -> GetSocket() == INVALID_SOCKET) - { - LogError(p, "Add", -1, "Invalid socket", LOG_LEVEL_WARNING); - if (p -> CloseAndDelete()) - { - m_delete.push_back(p); - } - return; - } - if (m_add.find(p -> GetSocket()) != m_add.end()) - { - LogError(p, "Add", (int)p -> GetSocket(), "Attempt to add socket already in add queue", LOG_LEVEL_FATAL); - m_delete.push_back(p); - return; - } - m_add[p -> GetSocket()] = p; -} - -void SocketHandler::Get(SOCKET s,bool& r,bool& w,bool& e) -{ - if (s >= 0) - { - r = FD_ISSET(s, &m_rfds) ? true : false; - w = FD_ISSET(s, &m_wfds) ? true : false; - e = FD_ISSET(s, &m_efds) ? true : false; - } -} - -void SocketHandler::Set(SOCKET s,bool bRead,bool bWrite,bool bException) -{ -DEB( fprintf(stderr, "Set(%d, %s, %s, %s)\n", s, bRead ? "true" : "false", bWrite ? "true" : "false", bException ? "true" : "false");) - if (s >= 0) - { - if (bRead) - { - if (!FD_ISSET(s, &m_rfds)) - { - FD_SET(s, &m_rfds); - } - } - else - { - FD_CLR(s, &m_rfds); - } - if (bWrite) - { - if (!FD_ISSET(s, &m_wfds)) - { - FD_SET(s, &m_wfds); - } - } - else - { - FD_CLR(s, &m_wfds); - } - if (bException) - { - if (!FD_ISSET(s, &m_efds)) - { - FD_SET(s, &m_efds); - } - } - else - { - FD_CLR(s, &m_efds); - } - } -} - -int SocketHandler::Select(long sec,long usec) -{ - struct timeval tv; - tv.tv_sec = sec; - tv.tv_usec = usec; - return Select(&tv); -} - -int SocketHandler::Select() -{ - if (!m_fds_callonconnect.empty() || -#ifdef ENABLE_DETACH - (!m_slave && !m_fds_detach.empty()) || -#endif - !m_fds_timeout.empty() || - !m_fds_retry.empty() || - !m_fds_close.empty() || - !m_fds_erase.empty()) - { - return Select(0, 200000); - } - return Select(NULL); -} - -int SocketHandler::Select(struct timeval *tsel) -{ - size_t ignore = 0; - while (m_add.size() > ignore) - { - if (m_sockets.size() >= FD_SETSIZE) - { - LogError(NULL, "Select", (int)m_sockets.size(), "FD_SETSIZE reached", LOG_LEVEL_WARNING); - break; - } - socket_m::iterator it = m_add.begin(); - SOCKET s = it -> first; - Socket *p = it -> second; -DEB( fprintf(stderr, "Trying to add fd %d, m_add.size() %d, ignore %d\n", (int)s, (int)m_add.size(), (int)ignore);) - // - if (m_sockets.find(p -> GetSocket()) != m_sockets.end()) - { - LogError(p, "Add", (int)p -> GetSocket(), "Attempt to add socket already in controlled queue", LOG_LEVEL_FATAL); - // %! it's a dup, don't add to delete queue, just ignore it - m_delete.push_back(p); - m_add.erase(it); -// ignore++; - continue; - } - if (!p -> CloseAndDelete()) - { - StreamSocket *scp = dynamic_cast<StreamSocket *>(p); - if (scp && scp -> Connecting()) // 'Open' called before adding socket - { - Set(s,false,true); - } - else - { - TcpSocket *tcp = dynamic_cast<TcpSocket *>(p); - bool bWrite = tcp ? tcp -> GetOutputLength() != 0 : false; - if (p -> IsDisableRead()) - { - Set(s, false, bWrite); - } - else - { - Set(s, true, bWrite); - } - } - m_maxsock = (s > m_maxsock) ? s : m_maxsock; - } - else - { - LogError(p, "Add", (int)p -> GetSocket(), "Trying to add socket with SetCloseAndDelete() true", LOG_LEVEL_WARNING); - } - // only add to m_fds (process fd_set events) if - // slave handler and detached/detaching socket - // master handler and non-detached socket -#ifdef ENABLE_DETACH - if (!(m_slave ^ p -> IsDetach())) -#endif - { - m_fds.push_back(s); - } - m_sockets[s] = p; - // - m_add.erase(it); - } -#ifdef MACOSX - fd_set rfds; - fd_set wfds; - fd_set efds; - FD_COPY(&m_rfds, &rfds); - FD_COPY(&m_wfds, &wfds); - FD_COPY(&m_efds, &efds); -#else - fd_set rfds = m_rfds; - fd_set wfds = m_wfds; - fd_set efds = m_efds; -#endif - int n; - if (m_b_use_mutex) - { - m_mutex.Unlock(); - n = select( (int)(m_maxsock + 1),&rfds,&wfds,&efds,tsel); - m_mutex.Lock(); - } - else - { - n = select( (int)(m_maxsock + 1),&rfds,&wfds,&efds,tsel); - } - if (n == -1) - { - /* - EBADF An invalid file descriptor was given in one of the sets. - EINTR A non blocked signal was caught. - EINVAL n is negative. Or struct timeval contains bad time values (<0). - ENOMEM select was unable to allocate memory for internal tables. - */ - if (Errno != m_preverror || m_errcnt++ % 10000 == 0) - { - LogError(NULL, "select", Errno, StrError(Errno)); -DEB( fprintf(stderr, "m_maxsock: %d\n", m_maxsock); - fprintf(stderr, "%s\n", Errno == EINVAL ? "EINVAL" : - Errno == EINTR ? "EINTR" : - Errno == EBADF ? "EBADF" : - Errno == ENOMEM ? "ENOMEM" : "<another>"); - // test bad fd - for (SOCKET i = 0; i <= m_maxsock; i++) - { - bool t = false; - FD_ZERO(&rfds); - FD_ZERO(&wfds); - FD_ZERO(&efds); - if (FD_ISSET(i, &m_rfds)) - { - FD_SET(i, &rfds); - t = true; - } - if (FD_ISSET(i, &m_wfds)) - { - FD_SET(i, &wfds); - t = true; - } - if (FD_ISSET(i, &m_efds)) - { - FD_SET(i, &efds); - t = true; - } - if (t && m_sockets.find(i) == m_sockets.end()) - { - fprintf(stderr, "Bad fd in fd_set: %d\n", i); - } - } -) // DEB - m_preverror = Errno; - } - /// \todo rebuild fd_set's from active sockets list (m_sockets) here - } - else - if (!n) - { - m_preverror = -1; - } - else - if (n > 0) - { - for (socket_v::iterator it2 = m_fds.begin(); it2 != m_fds.end() && n; it2++) - { - SOCKET i = *it2; - if (FD_ISSET(i, &rfds)) - { - socket_m::iterator itmp = m_sockets.find(i); - if (itmp != m_sockets.end()) // found - { - Socket *p = itmp -> second; - // new SSL negotiate method -#ifdef HAVE_OPENSSL - if (p -> IsSSLNegotiate()) - { - p -> SSLNegotiate(); - } - else -#endif - { - p -> OnRead(); - } - } - else - { - LogError(NULL, "GetSocket/handler/1", (int)i, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); - } - n--; - } - if (FD_ISSET(i, &wfds)) - { - socket_m::iterator itmp = m_sockets.find(i); - if (itmp != m_sockets.end()) // found - { - Socket *p = itmp -> second; - // new SSL negotiate method -#ifdef HAVE_OPENSSL - if (p -> IsSSLNegotiate()) - { - p -> SSLNegotiate(); - } - else -#endif - { - p -> OnWrite(); - } - } - else - { - LogError(NULL, "GetSocket/handler/2", (int)i, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); - } - n--; - } - if (FD_ISSET(i, &efds)) - { - socket_m::iterator itmp = m_sockets.find(i); - if (itmp != m_sockets.end()) // found - { - Socket *p = itmp -> second; - p -> OnException(); - } - else - { - LogError(NULL, "GetSocket/handler/3", (int)i, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); - } - n--; - } - } // m_fds loop - m_preverror = -1; - } // if (n > 0) - - // check CallOnConnect - EVENT - if (!m_fds_callonconnect.empty()) - { - socket_v tmp = m_fds_callonconnect; - for (socket_v::iterator it = tmp.begin(); it != tmp.end(); it++) - { - Socket *p = NULL; - { - socket_m::iterator itmp = m_sockets.find(*it); - if (itmp != m_sockets.end()) // found - { - p = itmp -> second; - } - else - { - LogError(NULL, "GetSocket/handler/4", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); - } - } - if (p) - { -// if (p -> CallOnConnect() && p -> Ready() ) - { - p -> SetConnected(); // moved here from inside if (tcp) check below -#ifdef HAVE_OPENSSL - if (p -> IsSSL()) // SSL Enabled socket - p -> OnSSLConnect(); - else -#endif -#ifdef ENABLE_SOCKS4 - if (p -> Socks4()) - p -> OnSocks4Connect(); - else -#endif - { - TcpSocket *tcp = dynamic_cast<TcpSocket *>(p); - if (tcp) - { - if (tcp -> GetOutputLength()) - { - p -> OnWrite(); - } - } -#ifdef ENABLE_RECONNECT - if (tcp && tcp -> IsReconnect()) - p -> OnReconnect(); - else -#endif - { -// LogError(p, "Calling OnConnect", 0, "Because CallOnConnect", LOG_LEVEL_INFO); - p -> OnConnect(); - } - } -// p -> SetCallOnConnect( false ); - AddList(p -> GetSocket(), LIST_CALLONCONNECT, false); - } - } - } - } -#ifdef ENABLE_DETACH - // check detach of socket if master handler - EVENT - if (!m_slave && !m_fds_detach.empty()) - { - // %! why not using tmp list here??!? - for (socket_v::iterator it = m_fds_detach.begin(); it != m_fds_detach.end(); it++) - { - Socket *p = NULL; - { - socket_m::iterator itmp = m_sockets.find(*it); - if (itmp != m_sockets.end()) // found - { - p = itmp -> second; - } - else - { - LogError(NULL, "GetSocket/handler/5", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); - } - } - if (p) - { -// if (p -> IsDetach()) - { - Set(p -> GetSocket(), false, false, false); - // After DetachSocket(), all calls to Handler() will return a reference - // to the new slave SocketHandler running in the new thread. - p -> DetachSocket(); - // Adding the file descriptor to m_fds_erase will now also remove the - // socket from the detach queue - tnx knightmad - m_fds_erase.push_back(p -> GetSocket()); - } - } - } - } -#endif - // check Connecting - connection timeout - conditional event - if (m_fds_timeout.size()) - { - time_t tnow = time(NULL); - if (tnow != m_tlast) - { - socket_v tmp = m_fds_timeout; -DEB( fprintf(stderr, "Checking %d socket(s) for timeout\n", tmp.size());) - for (socket_v::iterator it = tmp.begin(); it != tmp.end(); it++) - { - Socket *p = NULL; - { - socket_m::iterator itmp = m_sockets.find(*it); - if (itmp != m_sockets.end()) // found - { - p = itmp -> second; - } - else - { - itmp = m_add.find(*it); - if (itmp != m_add.end()) - { - p = itmp -> second; - } - else - { - LogError(NULL, "GetSocket/handler/6", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); - } - } - } - if (p) - { - if (p -> Timeout(tnow)) - { - StreamSocket *scp = dynamic_cast<StreamSocket *>(p); - if (scp && scp -> Connecting()) - p -> OnConnectTimeout(); - else - p -> OnTimeout(); - p -> SetTimeout(0); - } - } - } - m_tlast = tnow; - } // tnow != tlast - } - // check retry client connect - EVENT - if (!m_fds_retry.empty()) - { - socket_v tmp = m_fds_retry; - for (socket_v::iterator it = tmp.begin(); it != tmp.end(); it++) - { - Socket *p = NULL; - { - socket_m::iterator itmp = m_sockets.find(*it); - if (itmp != m_sockets.end()) // found - { - p = itmp -> second; - } - else - { - LogError(NULL, "GetSocket/handler/7", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); - } - } - if (p) - { -// if (p -> RetryClientConnect()) - { - TcpSocket *tcp = dynamic_cast<TcpSocket *>(p); - SOCKET nn = *it; //(*it3).first; - tcp -> SetRetryClientConnect(false); -DEB( fprintf(stderr, "Close() before retry client connect\n");) - p -> Close(); // removes from m_fds_retry - std::auto_ptr<SocketAddress> ad = p -> GetClientRemoteAddress(); - if (ad.get()) - { - tcp -> Open(*ad); - } - else - { - LogError(p, "RetryClientConnect", 0, "no address", LOG_LEVEL_ERROR); - } - Add(p); - m_fds_erase.push_back(nn); - } - } - } - } - // check close and delete - conditional event - if (!m_fds_close.empty()) - { - socket_v tmp = m_fds_close; -DEB( fprintf(stderr, "m_fds_close.size() == %d\n", (int)m_fds_close.size());) - for (socket_v::iterator it = tmp.begin(); it != tmp.end(); it++) - { - Socket *p = NULL; - { - socket_m::iterator itmp = m_sockets.find(*it); - if (itmp != m_sockets.end()) // found - { - p = itmp -> second; - } - else - { - itmp = m_add.find(*it); - if (itmp != m_add.end()) - { - p = itmp -> second; - } - else - { - LogError(NULL, "GetSocket/handler/8", (int)*it, "Did not find expected socket using file descriptor", LOG_LEVEL_WARNING); - } - } - } - if (p) - { -// if (p -> CloseAndDelete() ) - { - TcpSocket *tcp = dynamic_cast<TcpSocket *>(p); - // new graceful tcp - flush and close timeout 5s - if (tcp && p -> IsConnected() && tcp -> GetFlushBeforeClose() && -#ifdef HAVE_OPENSSL - !tcp -> IsSSL() && -#endif - p -> TimeSinceClose() < 5) - { -DEB( fprintf(stderr, " close(1)\n");) - if (tcp -> GetOutputLength()) - { - LogError(p, "Closing", (int)tcp -> GetOutputLength(), "Sending all data before closing", LOG_LEVEL_INFO); - } - else // shutdown write when output buffer is empty - if (!(tcp -> GetShutdown() & SHUT_WR)) - { - SOCKET nn = *it; - if (nn != INVALID_SOCKET && shutdown(nn, SHUT_WR) == -1) - { - LogError(p, "graceful shutdown", Errno, StrError(Errno), LOG_LEVEL_ERROR); - } - tcp -> SetShutdown(SHUT_WR); - } - } - else -#ifdef ENABLE_RECONNECT - if (tcp && p -> IsConnected() && tcp -> Reconnect()) - { - SOCKET nn = *it; //(*it3).first; -DEB( fprintf(stderr, " close(2) fd %d\n", nn);) - p -> SetCloseAndDelete(false); - tcp -> SetIsReconnect(); - p -> SetConnected(false); -DEB( fprintf(stderr, "Close() before reconnect\n");) - p -> Close(); // dispose of old file descriptor (Open creates a new) - p -> OnDisconnect(); - std::auto_ptr<SocketAddress> ad = p -> GetClientRemoteAddress(); - if (ad.get()) - { - tcp -> Open(*ad); - } - else - { - LogError(p, "Reconnect", 0, "no address", LOG_LEVEL_ERROR); - } - tcp -> ResetConnectionRetries(); - Add(p); - m_fds_erase.push_back(nn); - } - else -#endif - { - SOCKET nn = *it; //(*it3).first; -DEB( fprintf(stderr, " close(3) fd %d GetSocket() %d\n", nn, p -> GetSocket());) - if (tcp && p -> IsConnected() && tcp -> GetOutputLength()) - { - LogError(p, "Closing", (int)tcp -> GetOutputLength(), "Closing socket while data still left to send", LOG_LEVEL_WARNING); - } -#ifdef ENABLE_POOL - if (p -> Retain() && !p -> Lost()) - { - PoolSocket *p2 = new PoolSocket(*this, p); - p2 -> SetDeleteByHandler(); - Add(p2); - // - p -> SetCloseAndDelete(false); // added - remove from m_fds_close - } - else -#endif // ENABLE_POOL - { - Set(p -> GetSocket(),false,false,false); -DEB( fprintf(stderr, "Close() before OnDelete\n");) - p -> Close(); - } - p -> OnDelete(); - if (p -> DeleteByHandler()) - { - p -> SetErasedByHandler(); - } - m_fds_erase.push_back(nn); - } - } - } - } - } - - // check erased sockets - bool check_max_fd = false; - while (!m_fds_erase.empty()) - { - socket_v::iterator it = m_fds_erase.begin(); - SOCKET nn = *it; -#ifdef ENABLE_DETACH - { - for (socket_v::iterator it = m_fds_detach.begin(); it != m_fds_detach.end(); it++) - { - if (*it == nn) - { - m_fds_detach.erase(it); - break; - } - } - } -#endif - { - for (socket_v::iterator it = m_fds.begin(); it != m_fds.end(); it++) - { - if (*it == nn) - { - m_fds.erase(it); - break; - } - } - } - { - socket_m::iterator it = m_sockets.find(nn); - if (it != m_sockets.end()) - { - Socket *p = it -> second; - /* Sometimes a SocketThread class can finish its run before the master - sockethandler gets here. In that case, the SocketThread has set the - 'ErasedByHandler' flag on the socket which will make us end up with a - double delete on the socket instance. - The fix is to make sure that the master sockethandler only can delete - non-detached sockets, and a slave sockethandler only can delete - detach sockets. */ - if (p -> ErasedByHandler() -#ifdef ENABLE_DETACH - && !(m_slave ^ p -> IsDetached()) -#endif - ) - { -#ifdef ENABLE_TRIGGERS - bool again = false; - do - { - again = false; - for (std::map<int, Socket *>::iterator it = m_trigger_src.begin(); it != m_trigger_src.end(); it++) - { - int id = it -> first; - Socket *src = it -> second; - if (src == p) - { - for (std::map<Socket *, bool>::iterator it = m_trigger_dst[id].begin(); it != m_trigger_dst[id].end(); it++) - { - Socket *dst = it -> first; - if (Valid(dst)) - { - dst -> OnCancelled(id); - } - } - m_trigger_src.erase(m_trigger_src.find(id)); - m_trigger_dst.erase(m_trigger_dst.find(id)); - again = true; - break; - } - } - } while (again); -#endif - delete p; - } - m_sockets.erase(it); - } - } - m_fds_erase.erase(it); - check_max_fd = true; - } - // calculate max file descriptor for select() call - if (check_max_fd) - { - m_maxsock = 0; - for (socket_v::iterator it = m_fds.begin(); it != m_fds.end(); it++) - { - SOCKET s = *it; - m_maxsock = s > m_maxsock ? s : m_maxsock; - } - } - // remove Add's that fizzed - while (!m_delete.empty()) - { - std::list<Socket *>::iterator it = m_delete.begin(); - Socket *p = *it; - p -> OnDelete(); - m_delete.erase(it); - if (p -> DeleteByHandler() -#ifdef ENABLE_DETACH - && !(m_slave ^ p -> IsDetached()) -#endif - ) - { - p -> SetErasedByHandler(); -#ifdef ENABLE_TRIGGERS - bool again = false; - do - { - again = false; - for (std::map<int, Socket *>::iterator it = m_trigger_src.begin(); it != m_trigger_src.end(); it++) - { - int id = it -> first; - Socket *src = it -> second; - if (src == p) - { - for (std::map<Socket *, bool>::iterator it = m_trigger_dst[id].begin(); it != m_trigger_dst[id].end(); it++) - { - Socket *dst = it -> first; - if (Valid(dst)) - { - dst -> OnCancelled(id); - } - } - m_trigger_src.erase(m_trigger_src.find(id)); - m_trigger_dst.erase(m_trigger_dst.find(id)); - again = true; - break; - } - } - } while (again); -#endif - delete p; - } - } - return n; -} - -#ifdef ENABLE_RESOLVER -bool SocketHandler::Resolving(Socket *p0) -{ - std::map<Socket *, bool>::iterator it = m_resolve_q.find(p0); - return it != m_resolve_q.end(); -} -#endif - -bool SocketHandler::Valid(Socket *p0) -{ - for (socket_m::iterator it = m_sockets.begin(); it != m_sockets.end(); it++) - { - Socket *p = it -> second; - if (p0 == p) - return true; - } - return false; -} - -bool SocketHandler::OkToAccept(Socket *) -{ - return true; -} - -size_t SocketHandler::GetCount() -{ -/* -printf(" m_sockets : %d\n", m_sockets.size()); -printf(" m_add : %d\n", m_add.size()); -printf(" m_delete : %d\n", m_delete.size()); -*/ - return m_sockets.size() + m_add.size() + m_delete.size(); -} - -#ifdef ENABLE_SOCKS4 -void SocketHandler::SetSocks4Host(ipaddr_t a) -{ - m_socks4_host = a; -} - -void SocketHandler::SetSocks4Host(const std::string& host) -{ - Utility::u2ip(host, m_socks4_host); -} - -void SocketHandler::SetSocks4Port(port_t port) -{ - m_socks4_port = port; -} - -void SocketHandler::SetSocks4Userid(const std::string& id) -{ - m_socks4_userid = id; -} -#endif - -#ifdef ENABLE_RESOLVER -int SocketHandler::Resolve(Socket *p,const std::string& host,port_t port) -{ - // check cache - ResolvSocket *resolv = new ResolvSocket(*this, p, host, port); - resolv -> SetId(++m_resolv_id); - resolv -> SetDeleteByHandler(); - ipaddr_t local; - Utility::u2ip("127.0.0.1", local); - if (!resolv -> Open(local, m_resolver_port)) - { - LogError(resolv, "Resolve", -1, "Can't connect to local resolve server", LOG_LEVEL_FATAL); - } - Add(resolv); - m_resolve_q[p] = true; -DEB( fprintf(stderr, " *** Resolve '%s:%d' id#%d m_resolve_q size: %d p: %p\n", host.c_str(), port, resolv -> GetId(), m_resolve_q.size(), p);) - return resolv -> GetId(); -} - -#ifdef ENABLE_IPV6 -int SocketHandler::Resolve6(Socket *p,const std::string& host,port_t port) -{ - // check cache - ResolvSocket *resolv = new ResolvSocket(*this, p, host, port, true); - resolv -> SetId(++m_resolv_id); - resolv -> SetDeleteByHandler(); - ipaddr_t local; - Utility::u2ip("127.0.0.1", local); - if (!resolv -> Open(local, m_resolver_port)) - { - LogError(resolv, "Resolve", -1, "Can't connect to local resolve server", LOG_LEVEL_FATAL); - } - Add(resolv); - m_resolve_q[p] = true; - return resolv -> GetId(); -} -#endif - -int SocketHandler::Resolve(Socket *p,ipaddr_t a) -{ - // check cache - ResolvSocket *resolv = new ResolvSocket(*this, p, a); - resolv -> SetId(++m_resolv_id); - resolv -> SetDeleteByHandler(); - ipaddr_t local; - Utility::u2ip("127.0.0.1", local); - if (!resolv -> Open(local, m_resolver_port)) - { - LogError(resolv, "Resolve", -1, "Can't connect to local resolve server", LOG_LEVEL_FATAL); - } - Add(resolv); - m_resolve_q[p] = true; - return resolv -> GetId(); -} - -#ifdef ENABLE_IPV6 -int SocketHandler::Resolve(Socket *p,in6_addr& a) -{ - // check cache - ResolvSocket *resolv = new ResolvSocket(*this, p, a); - resolv -> SetId(++m_resolv_id); - resolv -> SetDeleteByHandler(); - ipaddr_t local; - Utility::u2ip("127.0.0.1", local); - if (!resolv -> Open(local, m_resolver_port)) - { - LogError(resolv, "Resolve", -1, "Can't connect to local resolve server", LOG_LEVEL_FATAL); - } - Add(resolv); - m_resolve_q[p] = true; - return resolv -> GetId(); -} -#endif - -void SocketHandler::EnableResolver(port_t port) -{ - if (!m_resolver) - { - m_resolver_port = port; - m_resolver = new ResolvServer(port); - } -} - -bool SocketHandler::ResolverReady() -{ - return m_resolver ? m_resolver -> Ready() : false; -} -#endif // ENABLE_RESOLVER - -#ifdef ENABLE_SOCKS4 -void SocketHandler::SetSocks4TryDirect(bool x) -{ - m_bTryDirect = x; -} - -ipaddr_t SocketHandler::GetSocks4Host() -{ - return m_socks4_host; -} - -port_t SocketHandler::GetSocks4Port() -{ - return m_socks4_port; -} - -const std::string& SocketHandler::GetSocks4Userid() -{ - return m_socks4_userid; -} - -bool SocketHandler::Socks4TryDirect() -{ - return m_bTryDirect; -} -#endif - -#ifdef ENABLE_RESOLVER -bool SocketHandler::ResolverEnabled() -{ - return m_resolver ? true : false; -} - -port_t SocketHandler::GetResolverPort() -{ - return m_resolver_port; -} -#endif // ENABLE_RESOLVER - -#ifdef ENABLE_POOL -ISocketHandler::PoolSocket *SocketHandler::FindConnection(int type,const std::string& protocol,SocketAddress& ad) -{ - for (socket_m::iterator it = m_sockets.begin(); it != m_sockets.end() && !m_sockets.empty(); it++) - { - PoolSocket *pools = dynamic_cast<PoolSocket *>(it -> second); - if (pools) - { - if (pools -> GetSocketType() == type && - pools -> GetSocketProtocol() == protocol && -// %! pools -> GetClientRemoteAddress() && - *pools -> GetClientRemoteAddress() == ad) - { - m_sockets.erase(it); - pools -> SetRetain(); // avoid Close in Socket destructor - return pools; // Caller is responsible that this socket is deleted - } - } - } - return NULL; -} - -void SocketHandler::EnablePool(bool x) -{ - m_b_enable_pool = x; -} - -bool SocketHandler::PoolEnabled() -{ - return m_b_enable_pool; -} -#endif - -void SocketHandler::Remove(Socket *p) -{ -#ifdef ENABLE_RESOLVER - std::map<Socket *, bool>::iterator it4 = m_resolve_q.find(p); - if (it4 != m_resolve_q.end()) - m_resolve_q.erase(it4); -#endif - if (p -> ErasedByHandler()) - { - return; - } - for (socket_m::iterator it = m_sockets.begin(); it != m_sockets.end(); it++) - { - if (it -> second == p) - { - LogError(p, "Remove", -1, "Socket destructor called while still in use", LOG_LEVEL_WARNING); - m_sockets.erase(it); - return; - } - } - for (socket_m::iterator it2 = m_add.begin(); it2 != m_add.end(); it2++) - { - if ((*it2).second == p) - { - LogError(p, "Remove", -2, "Socket destructor called while still in use", LOG_LEVEL_WARNING); - m_add.erase(it2); - return; - } - } - for (std::list<Socket *>::iterator it3 = m_delete.begin(); it3 != m_delete.end(); it3++) - { - if (*it3 == p) - { - LogError(p, "Remove", -3, "Socket destructor called while still in use", LOG_LEVEL_WARNING); - m_delete.erase(it3); - return; - } - } -} - -void SocketHandler::CheckSanity() -{ - CheckList(m_fds, "active sockets"); // active sockets - CheckList(m_fds_erase, "sockets to be erased"); // should always be empty anyway - CheckList(m_fds_callonconnect, "checklist CallOnConnect"); -#ifdef ENABLE_DETACH - CheckList(m_fds_detach, "checklist Detach"); -#endif - CheckList(m_fds_timeout, "checklist Timeout"); - CheckList(m_fds_retry, "checklist retry client connect"); - CheckList(m_fds_close, "checklist close and delete"); -} - -void SocketHandler::CheckList(socket_v& ref,const std::string& listname) -{ - for (socket_v::iterator it = ref.begin(); it != ref.end(); it++) - { - SOCKET s = *it; - if (m_sockets.find(s) != m_sockets.end()) - continue; - if (m_add.find(s) != m_add.end()) - continue; - bool found = false; - for (std::list<Socket *>::iterator it = m_delete.begin(); it != m_delete.end(); it++) - { - Socket *p = *it; - if (p -> GetSocket() == s) - { - found = true; - break; - } - } - if (!found) - { - fprintf(stderr, "CheckList failed for \"%s\": fd %d\n", listname.c_str(), s); - } - } -} - -void SocketHandler::AddList(SOCKET s,list_t which_one,bool add) -{ - if (s == INVALID_SOCKET) - { -DEB( fprintf(stderr, "AddList: invalid_socket\n");) - return; - } - socket_v& ref = - (which_one == LIST_CALLONCONNECT) ? m_fds_callonconnect : -#ifdef ENABLE_DETACH - (which_one == LIST_DETACH) ? m_fds_detach : -#endif - (which_one == LIST_TIMEOUT) ? m_fds_timeout : - (which_one == LIST_RETRY) ? m_fds_retry : - (which_one == LIST_CLOSE) ? m_fds_close : m_fds_close; - if (add) - { -#ifdef ENABLE_DETACH -DEB( fprintf(stderr, "AddList; %5d: %s: %s\n", s, (which_one == LIST_CALLONCONNECT) ? "CallOnConnect" : - (which_one == LIST_DETACH) ? "Detach" : - (which_one == LIST_TIMEOUT) ? "Timeout" : - (which_one == LIST_RETRY) ? "Retry" : - (which_one == LIST_CLOSE) ? "Close" : "<undef>", - add ? "Add" : "Remove");) -#else -DEB( fprintf(stderr, "AddList; %5d: %s: %s\n", s, (which_one == LIST_CALLONCONNECT) ? "CallOnConnect" : - (which_one == LIST_TIMEOUT) ? "Timeout" : - (which_one == LIST_RETRY) ? "Retry" : - (which_one == LIST_CLOSE) ? "Close" : "<undef>", - add ? "Add" : "Remove");) -#endif - } - if (add) - { - for (socket_v::iterator it = ref.begin(); it != ref.end(); it++) - { - if (*it == s) // already there - { - return; - } - } - ref.push_back(s); - return; - } - // remove - for (socket_v::iterator it = ref.begin(); it != ref.end(); it++) - { - if (*it == s) - { - ref.erase(it); - break; - } - } -//DEB( fprintf(stderr, "/AddList\n");) -} - -#ifdef ENABLE_TRIGGERS -int SocketHandler::TriggerID(Socket *src) -{ - int id = m_next_trigger_id++; - m_trigger_src[id] = src; - return id; -} - -bool SocketHandler::Subscribe(int id, Socket *dst) -{ - if (m_trigger_src.find(id) != m_trigger_src.end()) - { - std::map<Socket *, bool>::iterator it = m_trigger_dst[id].find(dst); - if (it != m_trigger_dst[id].end()) - { - m_trigger_dst[id][dst] = true; - return true; - } - LogError(dst, "Subscribe", id, "Already subscribed", LOG_LEVEL_INFO); - return false; - } - LogError(dst, "Subscribe", id, "Trigger id not found", LOG_LEVEL_INFO); - return false; -} - -bool SocketHandler::Unsubscribe(int id, Socket *dst) -{ - if (m_trigger_src.find(id) != m_trigger_src.end()) - { - std::map<Socket *, bool>::iterator it = m_trigger_dst[id].find(dst); - if (it != m_trigger_dst[id].end()) - { - m_trigger_dst[id].erase(it); - return true; - } - LogError(dst, "Unsubscribe", id, "Not subscribed", LOG_LEVEL_INFO); - return false; - } - LogError(dst, "Unsubscribe", id, "Trigger id not found", LOG_LEVEL_INFO); - return false; -} - -void SocketHandler::Trigger(int id, Socket::TriggerData& data, bool erase) -{ - if (m_trigger_src.find(id) != m_trigger_src.end()) - { - data.SetSource( m_trigger_src[id] ); - for (std::map<Socket *, bool>::iterator it = m_trigger_dst[id].begin(); it != m_trigger_dst[id].end(); it++) - { - Socket *dst = it -> first; - if (Valid(dst)) - { - dst -> OnTrigger(id, data); - } - } - if (erase) - { - m_trigger_src.erase(m_trigger_src.find(id)); - m_trigger_dst.erase(m_trigger_dst.find(id)); - } - } - else - { - LogError(NULL, "Trigger", id, "Trigger id not found", LOG_LEVEL_INFO); - } -} -#endif // ENABLE_TRIGGERS - -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/dep/sockets/StdoutLog.cpp b/dep/sockets/StdoutLog.cpp deleted file mode 100644 index e745a6d3358..00000000000 --- a/dep/sockets/StdoutLog.cpp +++ /dev/null @@ -1,98 +0,0 @@ -/** \file StdoutLog.cpp - ** \date 2004-06-01 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include <stdio.h> - -#ifdef _MSC_VER -#pragma warning(disable:4786) -#endif - -#include <cstdio> - -#include "ISocketHandler.h" -#include "Socket.h" -#include "StdoutLog.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - - -void StdoutLog::error(ISocketHandler *,Socket *sock,const std::string& call,int err,const std::string& sys_err,loglevel_t lvl) -{ - time_t t = time(NULL); - struct tm tp; -#ifdef _WIN32 - memcpy(&tp, localtime(&t), sizeof(tp)); -#else - localtime_r(&t, &tp); -#endif - std::string level; - - switch (lvl) - { - case LOG_LEVEL_WARNING: - level = "Warning"; - break; - case LOG_LEVEL_ERROR: - level = "Error"; - break; - case LOG_LEVEL_FATAL: - level = "Fatal"; - break; - case LOG_LEVEL_INFO: - level = "Info"; - break; - } - if (sock) - { - printf("%d-%02d-%02d %02d:%02d:%02d :: fd %d :: %s: %d %s (%s)\n", - tp.tm_year + 1900, - tp.tm_mon + 1, - tp.tm_mday, - tp.tm_hour,tp.tm_min,tp.tm_sec, - sock -> GetSocket(), - call.c_str(),err,sys_err.c_str(),level.c_str()); - } - else - { - printf("%d-%02d-%02d %02d:%02d:%02d :: %s: %d %s (%s)\n", - tp.tm_year + 1900, - tp.tm_mon + 1, - tp.tm_mday, - tp.tm_hour,tp.tm_min,tp.tm_sec, - call.c_str(),err,sys_err.c_str(),level.c_str()); - } -} - -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/dep/sockets/StreamSocket.cpp b/dep/sockets/StreamSocket.cpp deleted file mode 100644 index 009abadad8f..00000000000 --- a/dep/sockets/StreamSocket.cpp +++ /dev/null @@ -1,145 +0,0 @@ -#include "StreamSocket.h" -#include "ISocketHandler.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -StreamSocket::StreamSocket(ISocketHandler& h) : Socket(h) -,m_bConnecting(false) -,m_connect_timeout(5) -,m_flush_before_close(true) -,m_connection_retry(0) -,m_retries(0) -,m_call_on_connect(false) -,m_b_retry_connect(false) -,m_line_protocol(false) -,m_shutdown(0) -{ -} - -StreamSocket::~StreamSocket() -{ -} - -void StreamSocket::SetConnecting(bool x) -{ - if (x != m_bConnecting) - { - m_bConnecting = x; - if (x) - { - SetTimeout( GetConnectTimeout() ); - } - else - { - SetTimeout( 0 ); - } - } -} - -bool StreamSocket::Connecting() -{ - return m_bConnecting; -} - -bool StreamSocket::Ready() -{ - if (GetSocket() != INVALID_SOCKET && !Connecting() && !CloseAndDelete()) - return true; - return false; -} - -void StreamSocket::SetConnectTimeout(int x) -{ - m_connect_timeout = x; -} - -int StreamSocket::GetConnectTimeout() -{ - return m_connect_timeout; -} - -void StreamSocket::SetFlushBeforeClose(bool x) -{ - m_flush_before_close = x; -} - -bool StreamSocket::GetFlushBeforeClose() -{ - return m_flush_before_close; -} - -int StreamSocket::GetConnectionRetry() -{ - return m_connection_retry; -} - -void StreamSocket::SetConnectionRetry(int x) -{ - m_connection_retry = x; -} - -int StreamSocket::GetConnectionRetries() -{ - return m_retries; -} - -void StreamSocket::IncreaseConnectionRetries() -{ - m_retries++; -} - -void StreamSocket::ResetConnectionRetries() -{ - m_retries = 0; -} - -void StreamSocket::SetCallOnConnect(bool x) -{ - Handler().AddList(GetSocket(), LIST_CALLONCONNECT, x); - m_call_on_connect = x; -} - -bool StreamSocket::CallOnConnect() -{ - return m_call_on_connect; -} - -void StreamSocket::SetRetryClientConnect(bool x) -{ - Handler().AddList(GetSocket(), LIST_RETRY, x); - m_b_retry_connect = x; -} - -bool StreamSocket::RetryClientConnect() -{ - return m_b_retry_connect; -} - -void StreamSocket::SetLineProtocol(bool x) -{ - m_line_protocol = x; -} - -bool StreamSocket::LineProtocol() -{ - return m_line_protocol; -} - -void StreamSocket::SetShutdown(int x) -{ - m_shutdown = x; -} - -int StreamSocket::GetShutdown() -{ - return m_shutdown; -} - - -#ifdef SOCKETS_NAMESPACE -} // namespace SOCKETS_NAMESPACE { -#endif - - diff --git a/dep/sockets/TcpSocket.cpp b/dep/sockets/TcpSocket.cpp deleted file mode 100644 index 5f067b53124..00000000000 --- a/dep/sockets/TcpSocket.cpp +++ /dev/null @@ -1,1681 +0,0 @@ -/** \file TcpSocket.cpp - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifdef _WIN32 -#ifdef _MSC_VER -#pragma warning(disable:4786) -#endif -#include <stdlib.h> -#else -#include <errno.h> -#endif -#include "ISocketHandler.h" -#include <fcntl.h> -#include <assert.h> -#include <stdarg.h> -#include <stdio.h> -#ifdef HAVE_OPENSSL -#include <openssl/rand.h> -#include <openssl/err.h> -#endif -#include <map> -#include <cstdio> - -#include "TcpSocket.h" -#include "Utility.h" -#include "Ipv4Address.h" -#include "Ipv6Address.h" -#include "Mutex.h" -#include "IFile.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -//#ifdef _DEBUG -//#define DEB(x) x -//#else -#define DEB(x) -//#endif - -// statics -#ifdef HAVE_OPENSSL -SSLInitializer TcpSocket::m_ssl_init; -#endif - -// thanks, q -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif -TcpSocket::TcpSocket(ISocketHandler& h) : StreamSocket(h) -,ibuf(TCP_BUFSIZE_READ) -,m_b_input_buffer_disabled(false) -,m_bytes_sent(0) -,m_bytes_received(0) -,m_skip_c(false) -#ifdef SOCKETS_DYNAMIC_TEMP -,m_buf(new char[TCP_BUFSIZE_READ + 1]) -#endif -,m_obuf_top(NULL) -,m_transfer_limit(0) -,m_output_length(0) -#ifdef HAVE_OPENSSL -,m_ssl_ctx(NULL) -,m_ssl(NULL) -,m_sbio(NULL) -#endif -#ifdef ENABLE_SOCKS4 -,m_socks4_state(0) -#endif -#ifdef ENABLE_RESOLVER -,m_resolver_id(0) -#endif -#ifdef ENABLE_RECONNECT -,m_b_reconnect(false) -,m_b_is_reconnect(false) -#endif -{ -} -#ifdef _MSC_VER -#pragma warning(default:4355) -#endif - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif -TcpSocket::TcpSocket(ISocketHandler& h,size_t isize,size_t osize) : StreamSocket(h) -,ibuf(isize) -,m_b_input_buffer_disabled(false) -,m_bytes_sent(0) -,m_bytes_received(0) -,m_skip_c(false) -#ifdef SOCKETS_DYNAMIC_TEMP -,m_buf(new char[TCP_BUFSIZE_READ + 1]) -#endif -,m_obuf_top(NULL) -,m_transfer_limit(0) -,m_output_length(0) -#ifdef HAVE_OPENSSL -,m_ssl_ctx(NULL) -,m_ssl(NULL) -,m_sbio(NULL) -#endif -#ifdef ENABLE_SOCKS4 -,m_socks4_state(0) -#endif -#ifdef ENABLE_RESOLVER -,m_resolver_id(0) -#endif -#ifdef ENABLE_RECONNECT -,m_b_reconnect(false) -,m_b_is_reconnect(false) -#endif -{ -} -#ifdef _MSC_VER -#pragma warning(default:4355) -#endif - -TcpSocket::~TcpSocket() -{ -#ifdef SOCKETS_DYNAMIC_TEMP - delete[] m_buf; -#endif - // %! empty m_obuf - while (m_obuf.size()) - { - output_l::iterator it = m_obuf.begin(); - OUTPUT *p = *it; - delete p; - m_obuf.erase(it); - } -#ifdef HAVE_OPENSSL - if (m_ssl) - { - SSL_free(m_ssl); - } -#endif -} - -bool TcpSocket::Open(ipaddr_t ip,port_t port,bool skip_socks) -{ - Ipv4Address ad(ip, port); - Ipv4Address local; - return Open(ad, local, skip_socks); -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -bool TcpSocket::Open(in6_addr ip,port_t port,bool skip_socks) -{ - Ipv6Address ad(ip, port); - return Open(ad, skip_socks); -} -#endif -#endif - -bool TcpSocket::Open(SocketAddress& ad,bool skip_socks) -{ - Ipv4Address bind_ad("0.0.0.0", 0); - return Open(ad, bind_ad, skip_socks); -} - -bool TcpSocket::Open(SocketAddress& ad,SocketAddress& bind_ad,bool skip_socks) -{ - if (!ad.IsValid()) - { - Handler().LogError(this, "Open", 0, "Invalid SocketAddress", LOG_LEVEL_FATAL); - SetCloseAndDelete(); - return false; - } - if (Handler().GetCount() >= FD_SETSIZE) - { - Handler().LogError(this, "Open", 0, "no space left in fd_set", LOG_LEVEL_FATAL); - SetCloseAndDelete(); - return false; - } - SetConnecting(false); -#ifdef ENABLE_SOCKS4 - SetSocks4(false); -#endif - // check for pooling -#ifdef ENABLE_POOL - if (Handler().PoolEnabled()) - { - ISocketHandler::PoolSocket *pools = Handler().FindConnection(SOCK_STREAM, "tcp", ad); - if (pools) - { - CopyConnection( pools ); - delete pools; - - SetIsClient(); - SetCallOnConnect(); // ISocketHandler must call OnConnect - Handler().LogError(this, "SetCallOnConnect", 0, "Found pooled connection", LOG_LEVEL_INFO); - return true; - } - } -#endif - // if not, create new connection - SOCKET s = CreateSocket(ad.GetFamily(), SOCK_STREAM, "tcp"); - if (s == INVALID_SOCKET) - { - return false; - } - // socket must be nonblocking for async connect - if (!SetNonblocking(true, s)) - { - SetCloseAndDelete(); - closesocket(s); - return false; - } -#ifdef ENABLE_POOL - SetIsClient(); // client because we connect -#endif - SetClientRemoteAddress(ad); - int n = 0; - if (bind_ad.GetPort() != 0) - { - bind(s, bind_ad, bind_ad); - } -#ifdef ENABLE_SOCKS4 - if (!skip_socks && GetSocks4Host() && GetSocks4Port()) - { - Ipv4Address sa(GetSocks4Host(), GetSocks4Port()); - { - std::string sockshost; - Utility::l2ip(GetSocks4Host(), sockshost); - Handler().LogError(this, "Open", 0, "Connecting to socks4 server @ " + sockshost + ":" + - Utility::l2string(GetSocks4Port()), LOG_LEVEL_INFO); - } - SetSocks4(); - n = connect(s, sa, sa); - SetRemoteAddress(sa); - } - else -#endif - { - n = connect(s, ad, ad); - SetRemoteAddress(ad); - } - if (n == -1) - { - // check error code that means a connect is in progress -#ifdef _WIN32 - if (Errno == WSAEWOULDBLOCK) -#else - if (Errno == EINPROGRESS) -#endif - { - Attach(s); - SetConnecting( true ); // this flag will control fd_set's - } - else -#ifdef ENABLE_SOCKS4 - if (Socks4() && Handler().Socks4TryDirect() ) // retry - { - closesocket(s); - return Open(ad, true); - } - else -#endif -#ifdef ENABLE_RECONNECT - if (Reconnect()) - { - Handler().LogError(this, "connect: failed, reconnect pending", Errno, StrError(Errno), LOG_LEVEL_INFO); - Attach(s); - SetConnecting( true ); // this flag will control fd_set's - } - else -#endif - { - Handler().LogError(this, "connect: failed", Errno, StrError(Errno), LOG_LEVEL_FATAL); - SetCloseAndDelete(); - closesocket(s); - return false; - } - } - else - { - Attach(s); - SetCallOnConnect(); // ISocketHandler must call OnConnect - } - - // 'true' means connected or connecting(not yet connected) - // 'false' means something failed - return true; //!Connecting(); -} - -bool TcpSocket::Open(const std::string &host,port_t port) -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { -#ifdef ENABLE_RESOLVER - if (!Handler().ResolverEnabled() || Utility::isipv6(host) ) - { -#endif - in6_addr a; - if (!Utility::u2ip(host, a)) - { - SetCloseAndDelete(); - return false; - } - Ipv6Address ad(a, port); - Ipv6Address local; - return Open(ad, local); -#ifdef ENABLE_RESOLVER - } - m_resolver_id = Resolve6(host, port); - return true; -#endif - } -#endif -#endif -#ifdef ENABLE_RESOLVER - if (!Handler().ResolverEnabled() || Utility::isipv4(host) ) - { -#endif - ipaddr_t l; - if (!Utility::u2ip(host,l)) - { - SetCloseAndDelete(); - return false; - } - Ipv4Address ad(l, port); - Ipv4Address local; - return Open(ad, local); -#ifdef ENABLE_RESOLVER - } - // resolve using async resolver thread - m_resolver_id = Resolve(host, port); - return true; -#endif -} - -#ifdef ENABLE_RESOLVER -void TcpSocket::OnResolved(int id,ipaddr_t a,port_t port) -{ -DEB( fprintf(stderr, "TcpSocket::OnResolved id %d addr %x port %d\n", id, a, port);) - if (id == m_resolver_id) - { - if (a && port) - { - Ipv4Address ad(a, port); - Ipv4Address local; - if (Open(ad, local)) - { - if (!Handler().Valid(this)) - { - Handler().Add(this); - } - } - } - else - { - Handler().LogError(this, "OnResolved", 0, "Resolver failed", LOG_LEVEL_FATAL); - SetCloseAndDelete(); - } - } - else - { - Handler().LogError(this, "OnResolved", id, "Resolver returned wrong job id", LOG_LEVEL_FATAL); - SetCloseAndDelete(); - } -} - -#ifdef ENABLE_IPV6 -void TcpSocket::OnResolved(int id,in6_addr& a,port_t port) -{ - if (id == m_resolver_id) - { - Ipv6Address ad(a, port); - if (ad.IsValid()) - { - Ipv6Address local; - if (Open(ad, local)) - { - if (!Handler().Valid(this)) - { - Handler().Add(this); - } - } - } - } - else - { - Handler().LogError(this, "OnResolved", id, "Resolver returned wrong job id", LOG_LEVEL_FATAL); - SetCloseAndDelete(); - } -} -#endif -#endif - -void TcpSocket::OnRead() -{ - int n = 0; -#ifdef SOCKETS_DYNAMIC_TEMP - char *buf = m_buf; -#else - char buf[TCP_BUFSIZE_READ]; -#endif -#ifdef HAVE_OPENSSL - if (IsSSL()) - { - if (!Ready()) - return; - n = SSL_read(m_ssl, buf, TCP_BUFSIZE_READ); - if (n == -1) - { - n = SSL_get_error(m_ssl, n); - switch (n) - { - case SSL_ERROR_NONE: - case SSL_ERROR_WANT_READ: - case SSL_ERROR_WANT_WRITE: - break; - case SSL_ERROR_ZERO_RETURN: -DEB( fprintf(stderr, "SSL_read() returns zero - closing socket\n");) - OnDisconnect(); - SetCloseAndDelete(true); - SetFlushBeforeClose(false); - SetLost(); - break; - default: -DEB( fprintf(stderr, "SSL read problem, errcode = %d\n",n);) - OnDisconnect(); - SetCloseAndDelete(true); - SetFlushBeforeClose(false); - SetLost(); - } - return; - } - else - if (!n) - { - OnDisconnect(); - SetCloseAndDelete(true); - SetFlushBeforeClose(false); - SetLost(); - SetShutdown(SHUT_WR); - return; - } - else - if (n > 0 && n <= TCP_BUFSIZE_READ) - { - m_bytes_received += n; - if (GetTrafficMonitor()) - { - GetTrafficMonitor() -> fwrite(buf, 1, n); - } - if (!m_b_input_buffer_disabled && !ibuf.Write(buf,n)) - { - Handler().LogError(this, "OnRead(ssl)", 0, "ibuf overflow", LOG_LEVEL_WARNING); - } - } - else - { - Handler().LogError(this, "OnRead(ssl)", n, "abnormal value from SSL_read", LOG_LEVEL_ERROR); - } - } - else -#endif // HAVE_OPENSSL - { - n = recv(GetSocket(), buf, TCP_BUFSIZE_READ, MSG_NOSIGNAL); - if (n == -1) - { - Handler().LogError(this, "read", Errno, StrError(Errno), LOG_LEVEL_FATAL); - OnDisconnect(); - SetCloseAndDelete(true); - SetFlushBeforeClose(false); - SetLost(); - return; - } - else - if (!n) - { - OnDisconnect(); - SetCloseAndDelete(true); - SetFlushBeforeClose(false); - SetLost(); - SetShutdown(SHUT_WR); - return; - } - else - if (n > 0 && n <= TCP_BUFSIZE_READ) - { - m_bytes_received += n; - if (GetTrafficMonitor()) - { - GetTrafficMonitor() -> fwrite(buf, 1, n); - } - if (!m_b_input_buffer_disabled && !ibuf.Write(buf,n)) - { - Handler().LogError(this, "OnRead", 0, "ibuf overflow", LOG_LEVEL_WARNING); - } - } - else - { - Handler().LogError(this, "OnRead", n, "abnormal value from recv", LOG_LEVEL_ERROR); - } - } - // - OnRead( buf, n ); -} - -void TcpSocket::OnRead( char *buf, size_t n ) -{ - // unbuffered - if (n > 0 && n <= TCP_BUFSIZE_READ) - { - if (LineProtocol()) - { - buf[n] = 0; - size_t i = 0; - if (m_skip_c && (buf[i] == 13 || buf[i] == 10) && buf[i] != m_c) - { - m_skip_c = false; - i++; - } - size_t x = i; - for (; i < n && LineProtocol(); i++) - { - while ((buf[i] == 13 || buf[i] == 10) && LineProtocol()) - { - char c = buf[i]; - buf[i] = 0; - if (buf[x]) - { - m_line += (buf + x); - } - OnLine( m_line ); - i++; - m_skip_c = true; - m_c = c; - if (i < n && (buf[i] == 13 || buf[i] == 10) && buf[i] != c) - { - m_skip_c = false; - i++; - } - x = i; - m_line = ""; - } - if (!LineProtocol()) - { - break; - } - } - if (!LineProtocol()) - { - if (i < n) - { - OnRawData(buf + i, n - i); - } - } - else - if (buf[x]) - { - m_line += (buf + x); - } - } - else - { - OnRawData(buf, n); - } - } - if (m_b_input_buffer_disabled) - { - return; - } - // further processing: socks4 -#ifdef ENABLE_SOCKS4 - if (Socks4()) - { - bool need_more = false; - while (GetInputLength() && !need_more && !CloseAndDelete()) - { - need_more = OnSocks4Read(); - } - } -#endif -} - -void TcpSocket::OnWriteComplete() -{ -} - -void TcpSocket::OnWrite() -{ - if (Connecting()) - { - int err = SoError(); - - // don't reset connecting flag on error here, we want the OnConnectFailed timeout later on - if (!err) // ok - { - Set(!IsDisableRead(), false); - SetConnecting(false); - SetCallOnConnect(); - return; - } - Handler().LogError(this, "tcp: connect failed", err, StrError(err), LOG_LEVEL_FATAL); - Set(false, false); // no more monitoring because connection failed - - // failed -#ifdef ENABLE_SOCKS4 - if (Socks4()) - { - // %! leave 'Connecting' flag set? - OnSocks4ConnectFailed(); - return; - } -#endif - if (GetConnectionRetry() == -1 || - (GetConnectionRetry() && GetConnectionRetries() < GetConnectionRetry()) ) - { - // even though the connection failed at once, only retry after - // the connection timeout. - // should we even try to connect again, when CheckConnect returns - // false it's because of a connection error - not a timeout... - return; - } - SetConnecting(false); - SetCloseAndDelete( true ); - /// \todo state reason why connect failed - OnConnectFailed(); - return; - } - // try send next block in buffer - // if full block is sent, repeat - // if all blocks are sent, reset m_wfds - - bool repeat = false; - size_t sz = m_transfer_limit ? GetOutputLength() : 0; - do - { - output_l::iterator it = m_obuf.begin(); - OUTPUT *p = *it; - repeat = false; - int n = TryWrite(p -> Buf(), p -> Len()); - if (n > 0) - { - size_t left = p -> Remove(n); - m_output_length -= n; - if (!left) - { - delete p; - m_obuf.erase(it); - if (!m_obuf.size()) - { - m_obuf_top = NULL; - OnWriteComplete(); - } - else - { - repeat = true; - } - } - } - } while (repeat); - - if (m_transfer_limit && sz > m_transfer_limit && GetOutputLength() < m_transfer_limit) - { - OnTransferLimit(); - } - - // check output buffer set, set/reset m_wfds accordingly - { - bool br; - bool bw; - bool bx; - Handler().Get(GetSocket(), br, bw, bx); - if (m_obuf.size()) - Set(br, true); - else - Set(br, false); - } -} - -int TcpSocket::TryWrite(const char *buf, size_t len) -{ - int n = 0; -#ifdef HAVE_OPENSSL - if (IsSSL()) - { - n = SSL_write(m_ssl, buf, (int)len); - if (n == -1) - { - int errnr = SSL_get_error(m_ssl, n); - if ( errnr != SSL_ERROR_WANT_READ && errnr != SSL_ERROR_WANT_WRITE ) - { - OnDisconnect(); - SetCloseAndDelete(true); - SetFlushBeforeClose(false); - SetLost(); - const char *errbuf = ERR_error_string(errnr, NULL); - Handler().LogError(this, "OnWrite/SSL_write", errnr, errbuf, LOG_LEVEL_FATAL); - } - return 0; - } - else - if (!n) - { - OnDisconnect(); - SetCloseAndDelete(true); - SetFlushBeforeClose(false); - SetLost(); -DEB( int errnr = SSL_get_error(m_ssl, n); - const char *errbuf = ERR_error_string(errnr, NULL); - fprintf(stderr, "SSL_write() returns 0: %d : %s\n",errnr, errbuf);) - } - } - else -#endif // HAVE_OPENSSL - { - n = send(GetSocket(), buf, (int)len, MSG_NOSIGNAL); - if (n == -1) - { - // normal error codes: - // WSAEWOULDBLOCK - // EAGAIN or EWOULDBLOCK -#ifdef _WIN32 - if (Errno != WSAEWOULDBLOCK) -#else - if (Errno != EWOULDBLOCK) -#endif - { - Handler().LogError(this, "send", Errno, StrError(Errno), LOG_LEVEL_FATAL); - OnDisconnect(); - SetCloseAndDelete(true); - SetFlushBeforeClose(false); - SetLost(); - } - return 0; - } - } - if (n > 0) - { - m_bytes_sent += n; - if (GetTrafficMonitor()) - { - GetTrafficMonitor() -> fwrite(buf, 1, n); - } - } - return n; -} - -void TcpSocket::Buffer(const char *buf, size_t len) -{ - size_t ptr = 0; - m_output_length += len; - while (ptr < len) - { - // buf/len => pbuf/sz - size_t space = 0; - if (m_obuf_top && (space = m_obuf_top -> Space()) > 0) - { - const char *pbuf = buf + ptr; - size_t sz = len - ptr; - if (space >= sz) - { - m_obuf_top -> Add(pbuf, sz); - ptr += sz; - } - else - { - m_obuf_top -> Add(pbuf, space); - ptr += space; - } - } - else - { - m_obuf_top = new OUTPUT; - m_obuf.push_back( m_obuf_top ); - } - } -} - -void TcpSocket::Send(const std::string &str,int i) -{ - SendBuf(str.c_str(),str.size(),i); -} - -void TcpSocket::SendBuf(const char *buf,size_t len,int) -{ - if (!Ready() && !Connecting()) - { - Handler().LogError(this, "SendBuf", -1, "Attempt to write to a non-ready socket" ); // warning - if (GetSocket() == INVALID_SOCKET) - Handler().LogError(this, "SendBuf", 0, " * GetSocket() == INVALID_SOCKET", LOG_LEVEL_INFO); - if (Connecting()) - Handler().LogError(this, "SendBuf", 0, " * Connecting()", LOG_LEVEL_INFO); - if (CloseAndDelete()) - Handler().LogError(this, "SendBuf", 0, " * CloseAndDelete()", LOG_LEVEL_INFO); - return; - } - if (!IsConnected()) - { - Handler().LogError(this, "SendBuf", -1, "Attempt to write to a non-connected socket, will be sent on connect" ); // warning - Buffer(buf, len); - return; - } - if (m_obuf_top) - { - Buffer(buf, len); - return; - } - int n = TryWrite(buf, len); - if (n >= 0 && n < (int)len) - { - Buffer(buf + n, len - n); - } - // if ( data in buffer || !IsConnected ) - // { - // add to buffer - // } - // else - // try_send - // if any data is unsent, buffer it and set m_wfds - - // check output buffer set, set/reset m_wfds accordingly - { - bool br; - bool bw; - bool bx; - Handler().Get(GetSocket(), br, bw, bx); - if (m_obuf.size()) - Set(br, true); - else - Set(br, false); - } -} - -void TcpSocket::OnLine(const std::string& ) -{ -} - -#ifdef _MSC_VER -#pragma warning(disable:4355) -#endif -TcpSocket::TcpSocket(const TcpSocket& s) -:StreamSocket(s) -,ibuf(0) -{ -} -#ifdef _MSC_VER -#pragma warning(default:4355) -#endif - -#ifdef ENABLE_SOCKS4 -void TcpSocket::OnSocks4Connect() -{ - char request[1000]; - memset(request, 0, sizeof(request)); - request[0] = 4; // socks v4 - request[1] = 1; // command code: CONNECT - { - std::auto_ptr<SocketAddress> ad = GetClientRemoteAddress(); - if (ad.get()) - { - struct sockaddr *p0 = (struct sockaddr *)*ad; - struct sockaddr_in *p = (struct sockaddr_in *)p0; - if (p -> sin_family == AF_INET) - { - memcpy(request + 2, &p -> sin_port, 2); // nwbo is ok here - memcpy(request + 4, &p -> sin_addr, sizeof(struct in_addr)); - } - else - { - /// \todo warn - } - } - else - { - /// \todo warn - } - } - strcpy(request + 8, GetSocks4Userid().c_str()); - size_t length = GetSocks4Userid().size() + 8 + 1; - SendBuf(request, length); - m_socks4_state = 0; -} - -void TcpSocket::OnSocks4ConnectFailed() -{ - Handler().LogError(this,"OnSocks4ConnectFailed",0,"connection to socks4 server failed, trying direct connection",LOG_LEVEL_WARNING); - if (!Handler().Socks4TryDirect()) - { - SetConnecting(false); - SetCloseAndDelete(); - OnConnectFailed(); // just in case - } - else - { - SetRetryClientConnect(); - } -} - -bool TcpSocket::OnSocks4Read() -{ - switch (m_socks4_state) - { - case 0: - ibuf.Read(&m_socks4_vn, 1); - m_socks4_state = 1; - break; - case 1: - ibuf.Read(&m_socks4_cd, 1); - m_socks4_state = 2; - break; - case 2: - if (GetInputLength() > 1) - { - ibuf.Read( (char *)&m_socks4_dstport, 2); - m_socks4_state = 3; - } - else - { - return true; - } - break; - case 3: - if (GetInputLength() > 3) - { - ibuf.Read( (char *)&m_socks4_dstip, 4); - SetSocks4(false); - - switch (m_socks4_cd) - { - case 90: - OnConnect(); - Handler().LogError(this, "OnSocks4Read", 0, "Connection established", LOG_LEVEL_INFO); - break; - case 91: - case 92: - case 93: - Handler().LogError(this,"OnSocks4Read",m_socks4_cd,"socks4 server reports connect failed",LOG_LEVEL_FATAL); - SetConnecting(false); - SetCloseAndDelete(); - OnConnectFailed(); - break; - default: - Handler().LogError(this,"OnSocks4Read",m_socks4_cd,"socks4 server unrecognized response",LOG_LEVEL_FATAL); - SetCloseAndDelete(); - break; - } - } - else - { - return true; - } - break; - } - return false; -} -#endif - -void TcpSocket::Sendf(const char *format, ...) -{ - va_list ap; - va_start(ap, format); - char slask[5000]; // vsprintf / vsnprintf temporary -#ifdef _WIN32 - vsprintf(slask, format, ap); -#else - vsnprintf(slask, 5000, format, ap); -#endif - va_end(ap); - Send( slask ); -} - -#ifdef HAVE_OPENSSL -void TcpSocket::OnSSLConnect() -{ - SetNonblocking(true); - { - if (m_ssl_ctx) - { -DEB( fprintf(stderr, "SSL Context already initialized - closing socket\n");) - SetCloseAndDelete(true); - return; - } - InitSSLClient(); - } - if (m_ssl_ctx) - { - /* Connect the SSL socket */ - m_ssl = SSL_new(m_ssl_ctx); - if (!m_ssl) - { -DEB( fprintf(stderr, " m_ssl is NULL\n");) - SetCloseAndDelete(true); - return; - } - SSL_set_mode(m_ssl, SSL_MODE_AUTO_RETRY); - m_sbio = BIO_new_socket((int)GetSocket(), BIO_NOCLOSE); - if (!m_sbio) - { -DEB( fprintf(stderr, " m_sbio is NULL\n");) - SetCloseAndDelete(true); - return; - } - SSL_set_bio(m_ssl, m_sbio, m_sbio); - if (!SSLNegotiate()) - { - SetSSLNegotiate(); - } - } - else - { - SetCloseAndDelete(); - } -} - -void TcpSocket::OnSSLAccept() -{ - SetNonblocking(true); - { - if (m_ssl_ctx) - { -DEB( fprintf(stderr, "SSL Context already initialized - closing socket\n");) - SetCloseAndDelete(true); - return; - } - InitSSLServer(); - SetSSLServer(); - } - if (m_ssl_ctx) - { - m_ssl = SSL_new(m_ssl_ctx); - if (!m_ssl) - { -DEB( fprintf(stderr, " m_ssl is NULL\n");) - SetCloseAndDelete(true); - return; - } - SSL_set_mode(m_ssl, SSL_MODE_AUTO_RETRY); - m_sbio = BIO_new_socket((int)GetSocket(), BIO_NOCLOSE); - if (!m_sbio) - { -DEB( fprintf(stderr, " m_sbio is NULL\n");) - SetCloseAndDelete(true); - return; - } - SSL_set_bio(m_ssl, m_sbio, m_sbio); -// if (!SSLNegotiate()) - { - SetSSLNegotiate(); - } - } -} - -bool TcpSocket::SSLNegotiate() -{ - if (!IsSSLServer()) // client - { - int r = SSL_connect(m_ssl); - if (r > 0) - { - SetSSLNegotiate(false); - /// \todo: resurrect certificate check... client -// CheckCertificateChain( "");//ServerHOST); - SetNonblocking(false); - // - { - SetConnected(); - if (GetOutputLength()) - { - OnWrite(); - } - } -#ifdef ENABLE_RECONNECT - if (IsReconnect()) - OnReconnect(); - else -#endif - { - OnConnect(); - } - Handler().LogError(this, "SSLNegotiate/SSL_connect", 0, "Connection established", LOG_LEVEL_INFO); - return true; - } - else - if (!r) - { - Handler().LogError(this, "SSLNegotiate/SSL_connect", 0, "Connection failed", LOG_LEVEL_INFO); - SetSSLNegotiate(false); - SetCloseAndDelete(); - OnSSLConnectFailed(); - } - else - { - r = SSL_get_error(m_ssl, r); - if (r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE) - { - Handler().LogError(this, "SSLNegotiate/SSL_connect", -1, "Connection failed", LOG_LEVEL_INFO); -DEB( fprintf(stderr, "SSL_connect() failed - closing socket, return code: %d\n",r);) - SetSSLNegotiate(false); - SetCloseAndDelete(true); - OnSSLConnectFailed(); - } - } - } - else // server - { - int r = SSL_accept(m_ssl); - if (r > 0) - { - SetSSLNegotiate(false); - /// \todo: resurrect certificate check... server -// CheckCertificateChain( "");//ClientHOST); - SetNonblocking(false); - // - { - SetConnected(); - if (GetOutputLength()) - { - OnWrite(); - } - } - OnAccept(); - Handler().LogError(this, "SSLNegotiate/SSL_accept", 0, "Connection established", LOG_LEVEL_INFO); - return true; - } - else - if (!r) - { - Handler().LogError(this, "SSLNegotiate/SSL_accept", 0, "Connection failed", LOG_LEVEL_INFO); - SetSSLNegotiate(false); - SetCloseAndDelete(); - OnSSLAcceptFailed(); - } - else - { - r = SSL_get_error(m_ssl, r); - if (r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE) - { - Handler().LogError(this, "SSLNegotiate/SSL_accept", -1, "Connection failed", LOG_LEVEL_INFO); -DEB( fprintf(stderr, "SSL_accept() failed - closing socket, return code: %d\n",r);) - SetSSLNegotiate(false); - SetCloseAndDelete(true); - OnSSLAcceptFailed(); - } - } - } - return false; -} - -void TcpSocket::InitSSLClient() -{ - InitializeContext("", SSLv23_method()); -} - -void TcpSocket::InitSSLServer() -{ - Handler().LogError(this, "InitSSLServer", 0, "You MUST implement your own InitSSLServer method", LOG_LEVEL_FATAL); - SetCloseAndDelete(); -} - -void TcpSocket::InitializeContext(const std::string& context, SSL_METHOD *meth_in) -{ - /* Create our context*/ - static std::map<std::string, SSL_CTX *> client_contexts; - if (client_contexts.find(context) == client_contexts.end()) - { - SSL_METHOD *meth = meth_in ? meth_in : SSLv3_method(); - m_ssl_ctx = client_contexts[context] = SSL_CTX_new(meth); - SSL_CTX_set_mode(m_ssl_ctx, SSL_MODE_AUTO_RETRY); - } - else - { - m_ssl_ctx = client_contexts[context]; - } -} - -void TcpSocket::InitializeContext(const std::string& context,const std::string& keyfile,const std::string& password,SSL_METHOD *meth_in) -{ - /* Create our context*/ - static std::map<std::string, SSL_CTX *> server_contexts; - if (server_contexts.find(context) == server_contexts.end()) - { - SSL_METHOD *meth = meth_in ? meth_in : SSLv3_method(); - m_ssl_ctx = server_contexts[context] = SSL_CTX_new(meth); - SSL_CTX_set_mode(m_ssl_ctx, SSL_MODE_AUTO_RETRY); - // session id - if (!context.empty()) - SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)context.c_str(), (unsigned int)context.size()); - else - SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)"--empty--", 9); - } - else - { - m_ssl_ctx = server_contexts[context]; - } - - /* Load our keys and certificates*/ - if (!(SSL_CTX_use_certificate_file(m_ssl_ctx, keyfile.c_str(), SSL_FILETYPE_PEM))) - { - Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read certificate file " + keyfile, LOG_LEVEL_FATAL); - } - - m_password = password; - SSL_CTX_set_default_passwd_cb(m_ssl_ctx, SSL_password_cb); - SSL_CTX_set_default_passwd_cb_userdata(m_ssl_ctx, this); - if (!(SSL_CTX_use_PrivateKey_file(m_ssl_ctx, keyfile.c_str(), SSL_FILETYPE_PEM))) - { - Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read private key file " + keyfile, LOG_LEVEL_FATAL); - } -} - -void TcpSocket::InitializeContext(const std::string& context,const std::string& certfile,const std::string& keyfile,const std::string& password,SSL_METHOD *meth_in) -{ - /* Create our context*/ - static std::map<std::string, SSL_CTX *> server_contexts; - if (server_contexts.find(context) == server_contexts.end()) - { - SSL_METHOD *meth = meth_in ? meth_in : SSLv3_method(); - m_ssl_ctx = server_contexts[context] = SSL_CTX_new(meth); - SSL_CTX_set_mode(m_ssl_ctx, SSL_MODE_AUTO_RETRY); - // session id - if (context.size()) - SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)context.c_str(), (unsigned int)context.size()); - else - SSL_CTX_set_session_id_context(m_ssl_ctx, (const unsigned char *)"--empty--", 9); - } - else - { - m_ssl_ctx = server_contexts[context]; - } - - /* Load our keys and certificates*/ - if (!(SSL_CTX_use_certificate_file(m_ssl_ctx, certfile.c_str(), SSL_FILETYPE_PEM))) - { - Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read certificate file " + keyfile, LOG_LEVEL_FATAL); - } - - m_password = password; - SSL_CTX_set_default_passwd_cb(m_ssl_ctx, SSL_password_cb); - SSL_CTX_set_default_passwd_cb_userdata(m_ssl_ctx, this); - if (!(SSL_CTX_use_PrivateKey_file(m_ssl_ctx, keyfile.c_str(), SSL_FILETYPE_PEM))) - { - Handler().LogError(this, "TcpSocket InitializeContext", 0, "Couldn't read private key file " + keyfile, LOG_LEVEL_FATAL); - } -} - -int TcpSocket::SSL_password_cb(char *buf,int num,int rwflag,void *userdata) -{ - Socket *p0 = static_cast<Socket *>(userdata); - TcpSocket *p = dynamic_cast<TcpSocket *>(p0); - std::string pw = p ? p -> GetPassword() : ""; - if ( (size_t)num < pw.size() + 1) - { - return 0; - } - strcpy(buf,pw.c_str()); - return (int)pw.size(); -} -#endif // HAVE_OPENSSL - -int TcpSocket::Close() -{ - if (GetSocket() == INVALID_SOCKET) // this could happen - { - Handler().LogError(this, "Socket::Close", 0, "file descriptor invalid", LOG_LEVEL_WARNING); - return 0; - } - int n; - SetNonblocking(true); - if (!Lost() && IsConnected() && !(GetShutdown() & SHUT_WR)) - { - if (shutdown(GetSocket(), SHUT_WR) == -1) - { - // failed... - Handler().LogError(this, "shutdown", Errno, StrError(Errno), LOG_LEVEL_ERROR); - } - } - // - char tmp[1000]; - if (!Lost() && (n = recv(GetSocket(),tmp,1000,0)) >= 0) - { - if (n) - { - Handler().LogError(this, "read() after shutdown", n, "bytes read", LOG_LEVEL_WARNING); - } - } -#ifdef HAVE_OPENSSL - if (IsSSL() && m_ssl) - SSL_shutdown(m_ssl); - if (m_ssl) - { - SSL_free(m_ssl); - m_ssl = NULL; - } -#endif - return Socket::Close(); -} - -#ifdef HAVE_OPENSSL -SSL_CTX *TcpSocket::GetSslContext() -{ - if (!m_ssl_ctx) - Handler().LogError(this, "GetSslContext", 0, "SSL Context is NULL; check InitSSLServer/InitSSLClient", LOG_LEVEL_WARNING); - return m_ssl_ctx; -} - -SSL *TcpSocket::GetSsl() -{ - if (!m_ssl) - Handler().LogError(this, "GetSsl", 0, "SSL is NULL; check InitSSLServer/InitSSLClient", LOG_LEVEL_WARNING); - return m_ssl; -} -#endif - -#ifdef ENABLE_RECONNECT -void TcpSocket::SetReconnect(bool x) -{ - m_b_reconnect = x; -} -#endif - -void TcpSocket::OnRawData(const char *buf_in,size_t len) -{ -} - -size_t TcpSocket::GetInputLength() -{ - return ibuf.GetLength(); -} - -size_t TcpSocket::GetOutputLength() -{ - return m_output_length; -} - -uint64_t TcpSocket::GetBytesReceived(bool clear) -{ - uint64_t z = m_bytes_received; - if (clear) - m_bytes_received = 0; - return z; -} - -uint64_t TcpSocket::GetBytesSent(bool clear) -{ - uint64_t z = m_bytes_sent; - if (clear) - m_bytes_sent = 0; - return z; -} - -#ifdef ENABLE_RECONNECT -bool TcpSocket::Reconnect() -{ - return m_b_reconnect; -} - -void TcpSocket::SetIsReconnect(bool x) -{ - m_b_is_reconnect = x; -} - -bool TcpSocket::IsReconnect() -{ - return m_b_is_reconnect; -} -#endif - -#ifdef HAVE_OPENSSL -const std::string& TcpSocket::GetPassword() -{ - return m_password; -} -#endif - -void TcpSocket::DisableInputBuffer(bool x) -{ - m_b_input_buffer_disabled = x; -} - -void TcpSocket::OnOptions(int family,int type,int protocol,SOCKET s) -{ -DEB( fprintf(stderr, "Socket::OnOptions()\n");) -#ifdef SO_NOSIGPIPE - SetSoNosigpipe(true); -#endif - SetSoReuseaddr(true); - SetSoKeepalive(true); -} - -void TcpSocket::SetLineProtocol(bool x) -{ - StreamSocket::SetLineProtocol(x); - DisableInputBuffer(x); -} - -bool TcpSocket::SetTcpNodelay(bool x) -{ -#ifdef TCP_NODELAY - int optval = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_TCP, TCP_NODELAY, (char *)&optval, sizeof(optval)) == -1) - { - Handler().LogError(this, "setsockopt(IPPROTO_TCP, TCP_NODELAY)", Errno, StrError(Errno), LOG_LEVEL_FATAL); - return false; - } - return true; -#else - Handler().LogError(this, "socket option not available", 0, "TCP_NODELAY", LOG_LEVEL_INFO); - return false; -#endif -} - -TcpSocket::CircularBuffer::CircularBuffer(size_t size) -:buf(new char[2 * size]) -,m_max(size) -,m_q(0) -,m_b(0) -,m_t(0) -,m_count(0) -{ -} - -TcpSocket::CircularBuffer::~CircularBuffer() -{ - delete[] buf; -} - -bool TcpSocket::CircularBuffer::Write(const char *s,size_t l) -{ - if (m_q + l > m_max) - { - return false; // overflow - } - m_count += (unsigned long)l; - if (m_t + l > m_max) // block crosses circular border - { - size_t l1 = m_max - m_t; // size left until circular border crossing - // always copy full block to buffer(buf) + top pointer(m_t) - // because we have doubled the buffer size for performance reasons - memcpy(buf + m_t, s, l); - memcpy(buf, s + l1, l - l1); - m_t = l - l1; - m_q += l; - } - else - { - memcpy(buf + m_t, s, l); - memcpy(buf + m_max + m_t, s, l); - m_t += l; - if (m_t >= m_max) - m_t -= m_max; - m_q += l; - } - return true; -} - -bool TcpSocket::CircularBuffer::Read(char *s,size_t l) -{ - if (l > m_q) - { - return false; // not enough chars - } - if (m_b + l > m_max) // block crosses circular border - { - size_t l1 = m_max - m_b; - if (s) - { - memcpy(s, buf + m_b, l1); - memcpy(s + l1, buf, l - l1); - } - m_b = l - l1; - m_q -= l; - } - else - { - if (s) - { - memcpy(s, buf + m_b, l); - } - m_b += l; - if (m_b >= m_max) - m_b -= m_max; - m_q -= l; - } - if (!m_q) - { - m_b = m_t = 0; - } - return true; -} - -bool TcpSocket::CircularBuffer::SoftRead(char *s, size_t l) -{ - if (l > m_q) - { - return false; - } - if (m_b + l > m_max) // block crosses circular border - { - size_t l1 = m_max - m_b; - if (s) - { - memcpy(s, buf + m_b, l1); - memcpy(s + l1, buf, l - l1); - } - } - else - { - if (s) - { - memcpy(s, buf + m_b, l); - } - } - return true; -} - -bool TcpSocket::CircularBuffer::Remove(size_t l) -{ - return Read(NULL, l); -} - -size_t TcpSocket::CircularBuffer::GetLength() -{ - return m_q; -} - -const char *TcpSocket::CircularBuffer::GetStart() -{ - return buf + m_b; -} - -size_t TcpSocket::CircularBuffer::GetL() -{ - return (m_b + m_q > m_max) ? m_max - m_b : m_q; -} - -size_t TcpSocket::CircularBuffer::Space() -{ - return m_max - m_q; -} - -unsigned long TcpSocket::CircularBuffer::ByteCounter(bool clear) -{ - if (clear) - { - unsigned long x = m_count; - m_count = 0; - return x; - } - return m_count; -} - -std::string TcpSocket::CircularBuffer::ReadString(size_t l) -{ - char *sz = new char[l + 1]; - if (!Read(sz, l)) // failed, debug printout in Read() method - { - delete[] sz; - return ""; - } - sz[l] = 0; - std::string tmp = sz; - delete[] sz; - return tmp; -} - -void TcpSocket::OnConnectTimeout() -{ - Handler().LogError(this, "connect", -1, "connect timeout", LOG_LEVEL_FATAL); -#ifdef ENABLE_SOCKS4 - if (Socks4()) - { - OnSocks4ConnectFailed(); - // retry direct connection - } - else -#endif - if (GetConnectionRetry() == -1 || - (GetConnectionRetry() && GetConnectionRetries() < GetConnectionRetry()) ) - { - IncreaseConnectionRetries(); - // ask socket via OnConnectRetry callback if we should continue trying - if (OnConnectRetry()) - { - SetRetryClientConnect(); - } - else - { - SetCloseAndDelete( true ); - /// \todo state reason why connect failed - OnConnectFailed(); - } - } - else - { - SetCloseAndDelete(true); - /// \todo state reason why connect failed - OnConnectFailed(); - } - // - SetConnecting(false); -} - -#ifdef _WIN32 -void TcpSocket::OnException() -{ - if (Connecting()) - { -#ifdef ENABLE_SOCKS4 - if (Socks4()) - OnSocks4ConnectFailed(); - else -#endif - if (GetConnectionRetry() == -1 || - (GetConnectionRetry() && - GetConnectionRetries() < GetConnectionRetry() )) - { - // even though the connection failed at once, only retry after - // the connection timeout - // should we even try to connect again, when CheckConnect returns - // false it's because of a connection error - not a timeout... - } - else - { - SetConnecting(false); // tnx snibbe - SetCloseAndDelete(); - OnConnectFailed(); - } - return; - } - // %! exception doesn't always mean something bad happened, this code should be reworked - // errno valid here? - int err = SoError(); - Handler().LogError(this, "exception on select", err, StrError(err), LOG_LEVEL_FATAL); - SetCloseAndDelete(); -} -#endif // _WIN32 - -int TcpSocket::Protocol() -{ - return IPPROTO_TCP; -} - -void TcpSocket::SetTransferLimit(size_t sz) -{ - m_transfer_limit = sz; -} - -void TcpSocket::OnTransferLimit() -{ -} - -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/dep/sockets/Thread.cpp b/dep/sockets/Thread.cpp deleted file mode 100644 index 773e9f214fa..00000000000 --- a/dep/sockets/Thread.cpp +++ /dev/null @@ -1,154 +0,0 @@ -/** \file Thread.cpp - ** \date 2004-10-30 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include <stdio.h> -#ifdef _WIN32 -#include <process.h> -#include "socket_include.h" -#else -#include <unistd.h> -#endif - -#include "Thread.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -Thread::Thread(bool release) -:m_thread(0) -,m_running(true) -,m_release(false) -,m_b_delete_on_exit(false) -,m_b_destructor(false) -{ -#ifdef _WIN32 -// m_thread = ::CreateThread(NULL, 0, StartThread, this, 0, &m_dwThreadId); - m_thread = (HANDLE)_beginthreadex(NULL, 0, &StartThread, this, 0, &m_dwThreadId); -#else - pthread_attr_t attr; - - pthread_attr_init(&attr); - pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); - if (pthread_create(&m_thread,&attr, StartThread,this) == -1) - { - perror("Thread: create failed"); - SetRunning(false); - } -// pthread_attr_destroy(&attr); -#endif - m_release = release; -} - -Thread::~Thread() -{ - m_b_destructor = true; - if (m_running) - { - SetRelease(true); - SetRunning(false); -#ifdef _WIN32 - Sleep(1000); -#else - sleep(1); -#endif - } -#ifdef _WIN32 - if (m_thread) - ::CloseHandle(m_thread); -#endif -} - -threadfunc_t STDPREFIX Thread::StartThread(threadparam_t zz) -{ - Thread *p = (Thread *)zz; - - while (p -> m_running && !p -> m_release) - { -#ifdef _WIN32 - Sleep(1000); -#else - sleep(1); -#endif - } - if (p -> m_running) - { - p -> Run(); - } - p -> SetRunning(false); // if return - if (p -> DeleteOnExit() && !p -> IsDestructor()) - { - delete p; - } -#ifdef _WIN32 - _endthreadex(0); -#endif - return (threadfunc_t)NULL; -} - -bool Thread::IsRunning() -{ - return m_running; -} - -void Thread::SetRunning(bool x) -{ - m_running = x; -} - -bool Thread::IsReleased() -{ - return m_release; -} - -void Thread::SetRelease(bool x) -{ - m_release = x; -} - -bool Thread::DeleteOnExit() -{ - return m_b_delete_on_exit; -} - -void Thread::SetDeleteOnExit(bool x) -{ - m_b_delete_on_exit = x; -} - -bool Thread::IsDestructor() -{ - return m_b_destructor; -} - -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/dep/sockets/UdpSocket.cpp b/dep/sockets/UdpSocket.cpp deleted file mode 100644 index a3d393c00e2..00000000000 --- a/dep/sockets/UdpSocket.cpp +++ /dev/null @@ -1,810 +0,0 @@ -/** \file UdpSocket.cpp - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifdef _WIN32 -#ifdef _MSC_VER -#pragma warning(disable:4786) -#endif -#include <stdlib.h> -#else -#include <errno.h> -#endif - -#include "ISocketHandler.h" -#include "UdpSocket.h" -#include "Utility.h" -#include "Ipv4Address.h" -#include "Ipv6Address.h" -#ifdef ENABLE_EXCEPTIONS -#include "Exception.h" -#endif -// include this to see strange sights -//#include <linux/in6.h> - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -UdpSocket::UdpSocket(ISocketHandler& h, int ibufsz, bool ipv6, int retries) : Socket(h) -, m_ibuf(new char[ibufsz]) -, m_ibufsz(ibufsz) -, m_bind_ok(false) -, m_port(0) -, m_last_size_written(-1) -, m_retries(retries) -, m_b_read_ts(false) -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - SetIpv6(ipv6); -#endif -#endif -} - -UdpSocket::~UdpSocket() -{ - Close(); - delete[] m_ibuf; -} - -int UdpSocket::Bind(port_t &port, int range) -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - Ipv6Address ad(port); - return Bind(ad, range); - } -#endif -#endif - Ipv4Address ad(port); - return Bind(ad, range); -} - -int UdpSocket::Bind(const std::string& intf, port_t &port, int range) -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - Ipv6Address ad(intf, port); - if (ad.IsValid()) - { - return Bind(ad, range); - } - SetCloseAndDelete(); - return -1; - } -#endif -#endif - Ipv4Address ad(intf, port); - if (ad.IsValid()) - { - return Bind(ad, range); - } - SetCloseAndDelete(); - return -1; -} - -int UdpSocket::Bind(ipaddr_t a, port_t &port, int range) -{ - Ipv4Address ad(a, port); - return Bind(ad, range); -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -int UdpSocket::Bind(in6_addr a, port_t &port, int range) -{ - Ipv6Address ad(a, port); - return Bind(ad, range); -} -#endif -#endif - -int UdpSocket::Bind(SocketAddress& ad, int range) -{ - if (GetSocket() == INVALID_SOCKET) - { - Attach(CreateSocket(ad.GetFamily(), SOCK_DGRAM, "udp")); - } - if (GetSocket() != INVALID_SOCKET) - { - SetNonblocking(true); - int n = bind(GetSocket(), ad, ad); - int tries = range; - while (n == -1 && tries--) - { - ad.SetPort(ad.GetPort() + 1); - n = bind(GetSocket(), ad, ad); - } - if (n == -1) - { - Handler().LogError(this, "bind", Errno, StrError(Errno), LOG_LEVEL_FATAL); - SetCloseAndDelete(); -#ifdef ENABLE_EXCEPTIONS - throw Exception("bind() failed for UdpSocket, port:range: " + Utility::l2string(ad.GetPort()) + ":" + Utility::l2string(range)); -#endif - return -1; - } - m_bind_ok = true; - m_port = ad.GetPort(); - return 0; - } - return -1; -} - -/** if you wish to use Send, first Open a connection */ -bool UdpSocket::Open(ipaddr_t l, port_t port) -{ - Ipv4Address ad(l, port); - return Open(ad); -} - -bool UdpSocket::Open(const std::string& host, port_t port) -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - Ipv6Address ad(host, port); - if (ad.IsValid()) - { - return Open(ad); - } - return false; - } -#endif -#endif - Ipv4Address ad(host, port); - if (ad.IsValid()) - { - return Open(ad); - } - return false; -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -bool UdpSocket::Open(struct in6_addr& a, port_t port) -{ - Ipv6Address ad(a, port); - return Open(ad); -} -#endif -#endif - -bool UdpSocket::Open(SocketAddress& ad) -{ - if (GetSocket() == INVALID_SOCKET) - { - Attach(CreateSocket(ad.GetFamily(), SOCK_DGRAM, "udp")); - } - if (GetSocket() != INVALID_SOCKET) - { - SetNonblocking(true); - if (connect(GetSocket(), ad, ad) == -1) - { - Handler().LogError(this, "connect", Errno, StrError(Errno), LOG_LEVEL_FATAL); - SetCloseAndDelete(); - return false; - } - SetConnected(); - return true; - } - return false; -} - -void UdpSocket::CreateConnection() -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - if (GetSocket() == INVALID_SOCKET) - { - SOCKET s = CreateSocket(AF_INET6, SOCK_DGRAM, "udp"); - if (s == INVALID_SOCKET) - { - return; - } - SetNonblocking(true, s); - Attach(s); - } - return; - } -#endif -#endif - if (GetSocket() == INVALID_SOCKET) - { - SOCKET s = CreateSocket(AF_INET, SOCK_DGRAM, "udp"); - if (s == INVALID_SOCKET) - { - return; - } - SetNonblocking(true, s); - Attach(s); - } -} - -/** send to specified address */ -void UdpSocket::SendToBuf(const std::string& h, port_t p, const char *data, int len, int flags) -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - Ipv6Address ad(h, p); - if (ad.IsValid()) - { - SendToBuf(ad, data, len, flags); - } - return; - } -#endif -#endif - Ipv4Address ad(h, p); - if (ad.IsValid()) - { - SendToBuf(ad, data, len, flags); - } -} - -/** send to specified address */ -void UdpSocket::SendToBuf(ipaddr_t a, port_t p, const char *data, int len, int flags) -{ - Ipv4Address ad(a, p); - SendToBuf(ad, data, len, flags); -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -void UdpSocket::SendToBuf(in6_addr a, port_t p, const char *data, int len, int flags) -{ - Ipv6Address ad(a, p); - SendToBuf(ad, data, len, flags); -} -#endif -#endif - -void UdpSocket::SendToBuf(SocketAddress& ad, const char *data, int len, int flags) -{ - if (GetSocket() == INVALID_SOCKET) - { - Attach(CreateSocket(ad.GetFamily(), SOCK_DGRAM, "udp")); - } - if (GetSocket() != INVALID_SOCKET) - { - SetNonblocking(true); - if ((m_last_size_written = sendto(GetSocket(), data, len, flags, ad, ad)) == -1) - { - Handler().LogError(this, "sendto", Errno, StrError(Errno), LOG_LEVEL_ERROR); - } - } -} - -void UdpSocket::SendTo(const std::string& a, port_t p, const std::string& str, int flags) -{ - SendToBuf(a, p, str.c_str(), (int)str.size(), flags); -} - -void UdpSocket::SendTo(ipaddr_t a, port_t p, const std::string& str, int flags) -{ - SendToBuf(a, p, str.c_str(), (int)str.size(), flags); -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -void UdpSocket::SendTo(in6_addr a, port_t p, const std::string& str, int flags) -{ - SendToBuf(a, p, str.c_str(), (int)str.size(), flags); -} -#endif -#endif - -void UdpSocket::SendTo(SocketAddress& ad, const std::string& str, int flags) -{ - SendToBuf(ad, str.c_str(), (int)str.size(), flags); -} - -/** send to connected address */ -void UdpSocket::SendBuf(const char *data, size_t len, int flags) -{ - if (!IsConnected()) - { - Handler().LogError(this, "SendBuf", 0, "not connected", LOG_LEVEL_ERROR); - return; - } - if ((m_last_size_written = send(GetSocket(), data, (int)len, flags)) == -1) - { - Handler().LogError(this, "send", Errno, StrError(Errno), LOG_LEVEL_ERROR); - } -} - -void UdpSocket::Send(const std::string& str, int flags) -{ - SendBuf(str.c_str(), (int)str.size(), flags); -} - -#if defined(LINUX) || defined(MACOSX) -int UdpSocket::ReadTS(char *ioBuf, int inBufSize, struct sockaddr *from, socklen_t fromlen, struct timeval *ts) -{ - struct msghdr msg; - struct iovec vec[1]; - union { - struct cmsghdr cm; -#ifdef MACOSX -#ifdef __DARWIN_UNIX03 -#define ALIGNBYTES __DARWIN_ALIGNBYTES -#endif -#define myALIGN(p) (((unsigned int)(p) + ALIGNBYTES) &~ ALIGNBYTES) -#define myCMSG_SPACE(l) (myALIGN(sizeof(struct cmsghdr)) + myALIGN(l)) - char data[ myCMSG_SPACE(sizeof(struct timeval)) ]; -#else - char data[ CMSG_SPACE(sizeof(struct timeval)) ]; -#endif - } cmsg_un; - struct cmsghdr *cmsg; - struct timeval *tv; - - vec[0].iov_base = ioBuf; - vec[0].iov_len = inBufSize; - - memset(&msg, 0, sizeof(msg)); - memset(from, 0, fromlen); - memset(ioBuf, 0, inBufSize); - memset(&cmsg_un, 0, sizeof(cmsg_un)); - - msg.msg_name = (caddr_t)from; - msg.msg_namelen = fromlen; - msg.msg_iov = vec; - msg.msg_iovlen = 1; - msg.msg_control = cmsg_un.data; - msg.msg_controllen = sizeof(cmsg_un.data); - msg.msg_flags = 0; - - // Original version - for reference only - //int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); - - int n = recvmsg(GetSocket(), &msg, MSG_DONTWAIT); - - // now ioBuf will contain the data, as if we used recvfrom - - // Now get the time - if(n != -1 && msg.msg_controllen >= sizeof(struct cmsghdr) && !(msg.msg_flags & MSG_CTRUNC)) - { - tv = 0; - for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; cmsg = CMSG_NXTHDR(&msg, cmsg)) - { - if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_TIMESTAMP) - { - tv = (struct timeval *)CMSG_DATA(cmsg); - } - } - if (tv) - { - memcpy(ts, tv, sizeof(struct timeval)); - } - } - // The address is in network order, but that's OK right now - return n; -} -#endif - -void UdpSocket::OnRead() -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - struct sockaddr_in6 sa; - socklen_t sa_len = sizeof(sa); - if (m_b_read_ts) - { - struct timeval ts; - Utility::GetTime(&ts); -#if !defined(LINUX) && !defined(MACOSX) - int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); -#else - int n = ReadTS(m_ibuf, m_ibufsz, (struct sockaddr *)&sa, sa_len, &ts); -#endif - if (n > 0) - { - this -> OnRawData(m_ibuf, n, (struct sockaddr *)&sa, sa_len, &ts); - } - else - if (n == -1) - { -#ifdef _WIN32 - if (Errno != WSAEWOULDBLOCK) -#else - if (Errno != EWOULDBLOCK) -#endif - Handler().LogError(this, "recvfrom", Errno, StrError(Errno), LOG_LEVEL_ERROR); - } - return; - } - int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); - int q = m_retries; // receive max 10 at one cycle - while (n > 0) - { - if (sa_len != sizeof(sa)) - { - Handler().LogError(this, "recvfrom", 0, "unexpected address struct size", LOG_LEVEL_WARNING); - } - this -> OnRawData(m_ibuf, n, (struct sockaddr *)&sa, sa_len); - if (!q--) - break; - // - n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); - } - if (n == -1) - { -#ifdef _WIN32 - if (Errno != WSAEWOULDBLOCK) -#else - if (Errno != EWOULDBLOCK) -#endif - Handler().LogError(this, "recvfrom", Errno, StrError(Errno), LOG_LEVEL_ERROR); - } - return; - } -#endif -#endif - struct sockaddr_in sa; - socklen_t sa_len = sizeof(sa); - if (m_b_read_ts) - { - struct timeval ts; - Utility::GetTime(&ts); -#if !defined(LINUX) && !defined(MACOSX) - int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); -#else - int n = ReadTS(m_ibuf, m_ibufsz, (struct sockaddr *)&sa, sa_len, &ts); -#endif - if (n > 0) - { - this -> OnRawData(m_ibuf, n, (struct sockaddr *)&sa, sa_len, &ts); - } - else - if (n == -1) - { -#ifdef _WIN32 - if (Errno != WSAEWOULDBLOCK) -#else - if (Errno != EWOULDBLOCK) -#endif - Handler().LogError(this, "recvfrom", Errno, StrError(Errno), LOG_LEVEL_ERROR); - } - return; - } - int n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); - int q = m_retries; - while (n > 0) - { - if (sa_len != sizeof(sa)) - { - Handler().LogError(this, "recvfrom", 0, "unexpected address struct size", LOG_LEVEL_WARNING); - } - this -> OnRawData(m_ibuf, n, (struct sockaddr *)&sa, sa_len); - if (!q--) - break; - // - n = recvfrom(GetSocket(), m_ibuf, m_ibufsz, 0, (struct sockaddr *)&sa, &sa_len); - } - if (n == -1) - { -#ifdef _WIN32 - if (Errno != WSAEWOULDBLOCK) -#else - if (Errno != EWOULDBLOCK) -#endif - Handler().LogError(this, "recvfrom", Errno, StrError(Errno), LOG_LEVEL_ERROR); - } -} - -void UdpSocket::SetBroadcast(bool b) -{ - int one = 1; - int zero = 0; - - if (GetSocket() == INVALID_SOCKET) - { - CreateConnection(); - } - if (b) - { - if (setsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *) &one, sizeof(one)) == -1) - { - Handler().LogError(this, "SetBroadcast", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - } - else - { - if (setsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *) &zero, sizeof(zero)) == -1) - { - Handler().LogError(this, "SetBroadcast", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - } -} - -bool UdpSocket::IsBroadcast() -{ - int is_broadcast = 0; - socklen_t size; - - if (GetSocket() == INVALID_SOCKET) - { - CreateConnection(); - } - if (getsockopt(GetSocket(), SOL_SOCKET, SO_BROADCAST, (char *)&is_broadcast, &size) == -1) - { - Handler().LogError(this, "IsBroadcast", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - return is_broadcast != 0; -} - -void UdpSocket::SetMulticastTTL(int ttl) -{ - if (GetSocket() == INVALID_SOCKET) - { - CreateConnection(); - } - if (setsockopt(GetSocket(), SOL_IP, IP_MULTICAST_TTL, (char *)&ttl, sizeof(int)) == -1) - { - Handler().LogError(this, "SetMulticastTTL", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } -} - -int UdpSocket::GetMulticastTTL() -{ - int ttl = 0; - socklen_t size = sizeof(int); - - if (GetSocket() == INVALID_SOCKET) - { - CreateConnection(); - } - if (getsockopt(GetSocket(), SOL_IP, IP_MULTICAST_TTL, (char *)&ttl, &size) == -1) - { - Handler().LogError(this, "GetMulticastTTL", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - return ttl; -} - -void UdpSocket::SetMulticastLoop(bool x) -{ - if (GetSocket() == INVALID_SOCKET) - { - CreateConnection(); - } -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - int val = x ? 1 : 0; - if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (char *)&val, sizeof(int)) == -1) - { - Handler().LogError(this, "SetMulticastLoop", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - return; - } -#endif -#endif - int val = x ? 1 : 0; - if (setsockopt(GetSocket(), SOL_IP, IP_MULTICAST_LOOP, (char *)&val, sizeof(int)) == -1) - { - Handler().LogError(this, "SetMulticastLoop", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } -} - -bool UdpSocket::IsMulticastLoop() -{ - if (GetSocket() == INVALID_SOCKET) - { - CreateConnection(); - } -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - int is_loop = 0; - socklen_t size = sizeof(int); - if (getsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_LOOP, (char *)&is_loop, &size) == -1) - { - Handler().LogError(this, "IsMulticastLoop", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - return is_loop ? true : false; - } -#endif -#endif - int is_loop = 0; - socklen_t size = sizeof(int); - if (getsockopt(GetSocket(), SOL_IP, IP_MULTICAST_LOOP, (char *)&is_loop, &size) == -1) - { - Handler().LogError(this, "IsMulticastLoop", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - return is_loop ? true : false; -} - -void UdpSocket::AddMulticastMembership(const std::string& group, const std::string& local_if, int if_index) -{ - if (GetSocket() == INVALID_SOCKET) - { - CreateConnection(); - } -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - struct ipv6_mreq x; - struct in6_addr addr; - if (Utility::u2ip( group, addr )) - { - x.ipv6mr_multiaddr = addr; - x.ipv6mr_interface = if_index; - if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, (char *)&x, sizeof(struct ipv6_mreq)) == -1) - { - Handler().LogError(this, "AddMulticastMembership", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - } - return; - } -#endif -#endif - struct ip_mreq x; // ip_mreqn - ipaddr_t addr; - if (Utility::u2ip( group, addr )) - { - memcpy(&x.imr_multiaddr.s_addr, &addr, sizeof(addr)); - Utility::u2ip( local_if, addr); - memcpy(&x.imr_interface.s_addr, &addr, sizeof(addr)); -// x.imr_ifindex = if_index; - if (setsockopt(GetSocket(), SOL_IP, IP_ADD_MEMBERSHIP, (char *)&x, sizeof(struct ip_mreq)) == -1) - { - Handler().LogError(this, "AddMulticastMembership", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - } -} - -void UdpSocket::DropMulticastMembership(const std::string& group, const std::string& local_if, int if_index) -{ - if (GetSocket() == INVALID_SOCKET) - { - CreateConnection(); - } -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - struct ipv6_mreq x; - struct in6_addr addr; - if (Utility::u2ip( group, addr )) - { - x.ipv6mr_multiaddr = addr; - x.ipv6mr_interface = if_index; - if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, (char *)&x, sizeof(struct ipv6_mreq)) == -1) - { - Handler().LogError(this, "DropMulticastMembership", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - } - return; - } -#endif -#endif - struct ip_mreq x; // ip_mreqn - ipaddr_t addr; - if (Utility::u2ip( group, addr )) - { - memcpy(&x.imr_multiaddr.s_addr, &addr, sizeof(addr)); - Utility::u2ip( local_if, addr); - memcpy(&x.imr_interface.s_addr, &addr, sizeof(addr)); -// x.imr_ifindex = if_index; - if (setsockopt(GetSocket(), SOL_IP, IP_DROP_MEMBERSHIP, (char *)&x, sizeof(struct ip_mreq)) == -1) - { - Handler().LogError(this, "DropMulticastMembership", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - } -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -void UdpSocket::SetMulticastHops(int hops) -{ - if (GetSocket() == INVALID_SOCKET) - { - CreateConnection(); - } - if (!IsIpv6()) - { - Handler().LogError(this, "SetMulticastHops", 0, "Ipv6 only", LOG_LEVEL_ERROR); - return; - } - if (setsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (char *)&hops, sizeof(int)) == -1) - { - Handler().LogError(this, "SetMulticastHops", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } -} - -int UdpSocket::GetMulticastHops() -{ - if (GetSocket() == INVALID_SOCKET) - { - CreateConnection(); - } - if (!IsIpv6()) - { - Handler().LogError(this, "SetMulticastHops", 0, "Ipv6 only", LOG_LEVEL_ERROR); - return -1; - } - int hops = 0; - socklen_t size = sizeof(int); - if (getsockopt(GetSocket(), IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (char *)&hops, &size) == -1) - { - Handler().LogError(this, "GetMulticastHops", Errno, StrError(Errno), LOG_LEVEL_WARNING); - } - return hops; -} -#endif // IPPROTO_IPV6 -#endif - -bool UdpSocket::IsBound() -{ - return m_bind_ok; -} - -void UdpSocket::OnRawData(const char *buf, size_t len, struct sockaddr *sa, socklen_t sa_len) -{ -} - -void UdpSocket::OnRawData(const char *buf, size_t len, struct sockaddr *sa, socklen_t sa_len, struct timeval *ts) -{ -} - -port_t UdpSocket::GetPort() -{ - return m_port; -} - -int UdpSocket::GetLastSizeWritten() -{ - return m_last_size_written; -} - -void UdpSocket::SetTimestamp(bool x) -{ - m_b_read_ts = x; -} - -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/dep/sockets/Utility.cpp b/dep/sockets/Utility.cpp deleted file mode 100644 index 7c093fc0832..00000000000 --- a/dep/sockets/Utility.cpp +++ /dev/null @@ -1,960 +0,0 @@ -/** \file Utility.cpp - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include "Utility.h" -#include "Parse.h" -#include "Ipv4Address.h" -#include "Ipv6Address.h" -#include "Base64.h" -#include <vector> -#ifdef _WIN32 -#include <time.h> -#else -#include <netdb.h> -#include <pthread.h> -#endif -#include <map> - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -// defines for the random number generator -#define TWIST_IA 397 -#define TWIST_IB (TWIST_LEN - TWIST_IA) -#define UMASK 0x80000000 -#define LMASK 0x7FFFFFFF -#define MATRIX_A 0x9908B0DF -#define TWIST(b,i,j) ((b)[i] & UMASK) | ((b)[j] & LMASK) -#define MAGIC_TWIST(s) (((s) & 1) * MATRIX_A) - -// statics -std::string Utility::m_host; -bool Utility::m_local_resolved = false; -ipaddr_t Utility::m_ip = 0; -std::string Utility::m_addr; -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -struct in6_addr Utility::m_local_ip6; -std::string Utility::m_local_addr6; -#endif -#endif - -std::string Utility::base64(const std::string& str_in) -{ - std::string str; - Base64 m_b; - m_b.encode(str_in, str, false); // , false == do not add cr/lf - return str; -} - -std::string Utility::base64d(const std::string& str_in) -{ - std::string str; - Base64 m_b; - m_b.decode(str_in, str); - return str; -} - -std::string Utility::l2string(long l) -{ - std::string str; - char tmp[100]; - sprintf(tmp,"%ld",l); - str = tmp; - return str; -} - -std::string Utility::bigint2string(uint64_t l) -{ - std::string str; - uint64_t tmp = l; - while (tmp) - { - uint64_t a = tmp % 10; - str = (char)(a + 48) + str; - tmp /= 10; - } - if (str.empty()) - { - str = "0"; - } - return str; -} - -uint64_t Utility::atoi64(const std::string& str) -{ - uint64_t l = 0; - for (size_t i = 0; i < str.size(); i++) - { - l = l * 10 + str[i] - 48; - } - return l; -} - -unsigned int Utility::hex2unsigned(const std::string& str) -{ - unsigned int r = 0; - for (size_t i = 0; i < str.size(); i++) - { - r = r * 16 + str[i] - 48 - ((str[i] >= 'A') ? 7 : 0) - ((str[i] >= 'a') ? 32 : 0); - } - return r; -} - -/* -* Encode string per RFC1738 URL encoding rules -* tnx rstaveley -*/ -std::string Utility::rfc1738_encode(const std::string& src) -{ -static char hex[] = "0123456789ABCDEF"; - std::string dst; - for (size_t i = 0; i < src.size(); i++) - { - if (isalnum(src[i])) - { - dst += src[i]; - } - else - if (src[i] == ' ') - { - dst += '+'; - } - else - { - unsigned char c = static_cast<unsigned char>(src[i]); - dst += '%'; - dst += hex[c / 16]; - dst += hex[c % 16]; - } - } - return dst; -} // rfc1738_encode - -/* -* Decode string per RFC1738 URL encoding rules -* tnx rstaveley -*/ -std::string Utility::rfc1738_decode(const std::string& src) -{ - std::string dst; - for (size_t i = 0; i < src.size(); i++) - { - if (src[i] == '%' && isxdigit(src[i + 1]) && isxdigit(src[i + 2])) - { - char c1 = src[++i]; - char c2 = src[++i]; - c1 = c1 - 48 - ((c1 >= 'A') ? 7 : 0) - ((c1 >= 'a') ? 32 : 0); - c2 = c2 - 48 - ((c2 >= 'A') ? 7 : 0) - ((c2 >= 'a') ? 32 : 0); - dst += (char)(c1 * 16 + c2); - } - else - if (src[i] == '+') - { - dst += ' '; - } - else - { - dst += src[i]; - } - } - return dst; -} // rfc1738_decode - -bool Utility::isipv4(const std::string& str) -{ - int dots = 0; - // %! ignore :port? - for (size_t i = 0; i < str.size(); i++) - { - if (str[i] == '.') - dots++; - else - if (!isdigit(str[i])) - return false; - } - if (dots != 3) - return false; - return true; -} - -bool Utility::isipv6(const std::string& str) -{ - size_t qc = 0; - size_t qd = 0; - for (size_t i = 0; i < str.size(); i++) - { - qc += (str[i] == ':') ? 1 : 0; - qd += (str[i] == '.') ? 1 : 0; - } - if (qc > 7) - { - return false; - } - if (qd && qd != 3) - { - return false; - } - Parse pa(str,":."); - std::string tmp = pa.getword(); - while (!tmp.empty()) - { - if (tmp.size() > 4) - { - return false; - } - for (size_t i = 0; i < tmp.size(); i++) - { - if (tmp[i] < '0' || (tmp[i] > '9' && tmp[i] < 'A') || - (tmp[i] > 'F' && tmp[i] < 'a') || tmp[i] > 'f') - { - return false; - } - } - // - tmp = pa.getword(); - } - return true; -} - -bool Utility::u2ip(const std::string& str, ipaddr_t& l) -{ - struct sockaddr_in sa; - bool r = Utility::u2ip(str, sa); - memcpy(&l, &sa.sin_addr, sizeof(l)); - return r; -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -bool Utility::u2ip(const std::string& str, struct in6_addr& l) -{ - struct sockaddr_in6 sa; - bool r = Utility::u2ip(str, sa); - l = sa.sin6_addr; - return r; -} -#endif -#endif - -void Utility::l2ip(const ipaddr_t ip, std::string& str) -{ - struct sockaddr_in sa; - memset(&sa, 0, sizeof(sa)); - sa.sin_family = AF_INET; - memcpy(&sa.sin_addr, &ip, sizeof(sa.sin_addr)); - Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), str, NI_NUMERICHOST); -} - -void Utility::l2ip(const in_addr& ip, std::string& str) -{ - struct sockaddr_in sa; - memset(&sa, 0, sizeof(sa)); - sa.sin_family = AF_INET; - sa.sin_addr = ip; - Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), str, NI_NUMERICHOST); -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -void Utility::l2ip(const struct in6_addr& ip, std::string& str,bool mixed) -{ - char slask[100]; // l2ip temporary - *slask = 0; - unsigned int prev = 0; - bool skipped = false; - bool ok_to_skip = true; - if (mixed) - { - unsigned short x; - unsigned short addr16[8]; - memcpy(addr16, &ip, sizeof(addr16)); - for (size_t i = 0; i < 6; i++) - { - x = ntohs(addr16[i]); - if (*slask && (x || !ok_to_skip || prev)) - strcat(slask,":"); - if (x || !ok_to_skip) - { - sprintf(slask + strlen(slask),"%x", x); - if (x && skipped) - ok_to_skip = false; - } - else - { - skipped = true; - } - prev = x; - } - x = ntohs(addr16[6]); - sprintf(slask + strlen(slask),":%u.%u",x / 256,x & 255); - x = ntohs(addr16[7]); - sprintf(slask + strlen(slask),".%u.%u",x / 256,x & 255); - } - else - { - struct sockaddr_in6 sa; - memset(&sa, 0, sizeof(sa)); - sa.sin6_family = AF_INET6; - sa.sin6_addr = ip; - Utility::reverse( (struct sockaddr *)&sa, sizeof(sa), str, NI_NUMERICHOST); - return; - } - str = slask; -} - -int Utility::in6_addr_compare(in6_addr a,in6_addr b) -{ - for (size_t i = 0; i < 16; i++) - { - if (a.s6_addr[i] < b.s6_addr[i]) - return -1; - if (a.s6_addr[i] > b.s6_addr[i]) - return 1; - } - return 0; -} -#endif -#endif - -void Utility::ResolveLocal() -{ - char h[256]; - - // get local hostname and translate into ip-address - *h = 0; - gethostname(h,255); - { - if (Utility::u2ip(h, m_ip)) - { - Utility::l2ip(m_ip, m_addr); - } - } -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - memset(&m_local_ip6, 0, sizeof(m_local_ip6)); - { - if (Utility::u2ip(h, m_local_ip6)) - { - Utility::l2ip(m_local_ip6, m_local_addr6); - } - } -#endif -#endif - m_host = h; - m_local_resolved = true; -} - -const std::string& Utility::GetLocalHostname() -{ - if (!m_local_resolved) - { - ResolveLocal(); - } - return m_host; -} - -ipaddr_t Utility::GetLocalIP() -{ - if (!m_local_resolved) - { - ResolveLocal(); - } - return m_ip; -} - -const std::string& Utility::GetLocalAddress() -{ - if (!m_local_resolved) - { - ResolveLocal(); - } - return m_addr; -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -const struct in6_addr& Utility::GetLocalIP6() -{ - if (!m_local_resolved) - { - ResolveLocal(); - } - return m_local_ip6; -} - -const std::string& Utility::GetLocalAddress6() -{ - if (!m_local_resolved) - { - ResolveLocal(); - } - return m_local_addr6; -} -#endif -#endif - -void Utility::SetEnv(const std::string& var,const std::string& value) -{ -#if (defined(SOLARIS8) || defined(SOLARIS)) - { - static std::map<std::string, char *> vmap; - if (vmap.find(var) != vmap.end()) - { - delete[] vmap[var]; - } - vmap[var] = new char[var.size() + 1 + value.size() + 1]; - sprintf(vmap[var], "%s=%s", var.c_str(), value.c_str()); - putenv( vmap[var] ); - } -#elif defined _WIN32 - { - std::string slask = var + "=" + value; - _putenv( (char *)slask.c_str()); - } -#else - setenv(var.c_str(), value.c_str(), 1); -#endif -} - -std::string Utility::Sa2String(struct sockaddr *sa) -{ -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (sa -> sa_family == AF_INET6) - { - struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)sa; - std::string tmp; - Utility::l2ip(sa6 -> sin6_addr, tmp); - return tmp + ":" + Utility::l2string(ntohs(sa6 -> sin6_port)); - } -#endif -#endif - if (sa -> sa_family == AF_INET) - { - struct sockaddr_in *sa4 = (struct sockaddr_in *)sa; - ipaddr_t a; - memcpy(&a, &sa4 -> sin_addr, 4); - std::string tmp; - Utility::l2ip(a, tmp); - return tmp + ":" + Utility::l2string(ntohs(sa4 -> sin_port)); - } - return ""; -} - -void Utility::GetTime(struct timeval *p) -{ -#ifdef _WIN32 - FILETIME ft; // Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC). - GetSystemTimeAsFileTime(&ft); - uint64_t tt; - memcpy(&tt, &ft, sizeof(tt)); - tt /= 10; // make it usecs - p->tv_sec = (long)tt / 1000000; - p->tv_usec = (long)tt % 1000000; -#else - gettimeofday(p, NULL); -#endif -} - -std::auto_ptr<SocketAddress> Utility::CreateAddress(struct sockaddr *sa,socklen_t sa_len) -{ - switch (sa -> sa_family) - { - case AF_INET: - if (sa_len == sizeof(struct sockaddr_in)) - { - struct sockaddr_in *p = (struct sockaddr_in *)sa; - return std::auto_ptr<SocketAddress>(new Ipv4Address(*p)); - } - break; -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - case AF_INET6: - if (sa_len == sizeof(struct sockaddr_in6)) - { - struct sockaddr_in6 *p = (struct sockaddr_in6 *)sa; - return std::auto_ptr<SocketAddress>(new Ipv6Address(*p)); - } - break; -#endif -#endif - } - return std::auto_ptr<SocketAddress>(NULL); -} - -bool Utility::u2ip(const std::string& host, struct sockaddr_in& sa, int ai_flags) -{ - memset(&sa, 0, sizeof(sa)); - sa.sin_family = AF_INET; -#ifdef NO_GETADDRINFO - if ((ai_flags & AI_NUMERICHOST) != 0 || isipv4(host)) - { - Parse pa((char *)host.c_str(), "."); - union { - struct { - unsigned char b1; - unsigned char b2; - unsigned char b3; - unsigned char b4; - } a; - ipaddr_t l; - } u; - u.a.b1 = static_cast<unsigned char>(pa.getvalue()); - u.a.b2 = static_cast<unsigned char>(pa.getvalue()); - u.a.b3 = static_cast<unsigned char>(pa.getvalue()); - u.a.b4 = static_cast<unsigned char>(pa.getvalue()); - memcpy(&sa.sin_addr, &u.l, sizeof(sa.sin_addr)); - return true; - } -#ifndef LINUX - struct hostent *he = gethostbyname( host.c_str() ); - if (!he) - { - return false; - } - memcpy(&sa.sin_addr, he -> h_addr, sizeof(sa.sin_addr)); -#else - struct hostent he; - struct hostent *result = NULL; - int myerrno = 0; - char buf[2000]; - int n = gethostbyname_r(host.c_str(), &he, buf, sizeof(buf), &result, &myerrno); - if (n || !result) - { - return false; - } - if (he.h_addr_list && he.h_addr_list[0]) - memcpy(&sa.sin_addr, he.h_addr, 4); - else - return false; -#endif - return true; -#else - struct addrinfo hints; - memset(&hints, 0, sizeof(hints)); - // AI_NUMERICHOST - // AI_CANONNAME - // AI_PASSIVE - server - // AI_ADDRCONFIG - // AI_V4MAPPED - // AI_ALL - // AI_NUMERICSERV - hints.ai_flags = ai_flags; - hints.ai_family = AF_INET; - hints.ai_socktype = 0; - hints.ai_protocol = 0; - struct addrinfo *res; - if (Utility::isipv4(host)) - hints.ai_flags |= AI_NUMERICHOST; - int n = getaddrinfo(host.c_str(), NULL, &hints, &res); - if (!n) - { - std::vector<struct addrinfo *> vec; - struct addrinfo *ai = res; - while (ai) - { - if (ai -> ai_addrlen == sizeof(sa)) - vec.push_back( ai ); - ai = ai -> ai_next; - } - if (vec.empty()) - return false; - ai = vec[Utility::Rnd() % vec.size()]; - { - memcpy(&sa, ai -> ai_addr, ai -> ai_addrlen); - } - freeaddrinfo(res); - return true; - } - std::string error = "Error: "; -#ifndef __CYGWIN__ - error += gai_strerror(n); -#endif - return false; -#endif // NO_GETADDRINFO -} - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 -bool Utility::u2ip(const std::string& host, struct sockaddr_in6& sa, int ai_flags) -{ - memset(&sa, 0, sizeof(sa)); - sa.sin6_family = AF_INET6; -#ifdef NO_GETADDRINFO - if ((ai_flags & AI_NUMERICHOST) != 0 || isipv6(host)) - { - std::list<std::string> vec; - size_t x = 0; - for (size_t i = 0; i <= host.size(); i++) - { - if (i == host.size() || host[i] == ':') - { - std::string s = host.substr(x, i - x); - // - if (strstr(s.c_str(),".")) // x.x.x.x - { - Parse pa(s,"."); - char slask[100]; // u2ip temporary hex2string conversion - unsigned long b0 = static_cast<unsigned long>(pa.getvalue()); - unsigned long b1 = static_cast<unsigned long>(pa.getvalue()); - unsigned long b2 = static_cast<unsigned long>(pa.getvalue()); - unsigned long b3 = static_cast<unsigned long>(pa.getvalue()); - sprintf(slask,"%lx",b0 * 256 + b1); - vec.push_back(slask); - sprintf(slask,"%lx",b2 * 256 + b3); - vec.push_back(slask); - } - else - { - vec.push_back(s); - } - // - x = i + 1; - } - } - size_t sz = vec.size(); // number of byte pairs - size_t i = 0; // index in in6_addr.in6_u.u6_addr16[] ( 0 .. 7 ) - unsigned short addr16[8]; - for (std::list<std::string>::iterator it = vec.begin(); it != vec.end(); it++) - { - std::string bytepair = *it; - if (!bytepair.empty()) - { - addr16[i++] = htons(Utility::hex2unsigned(bytepair)); - } - else - { - addr16[i++] = 0; - while (sz++ < 8) - { - addr16[i++] = 0; - } - } - } - memcpy(&sa.sin6_addr, addr16, sizeof(addr16)); - return true; - } -#ifdef SOLARIS - int errnum = 0; - struct hostent *he = getipnodebyname( host.c_str(), AF_INET6, 0, &errnum ); -#else - struct hostent *he = gethostbyname2( host.c_str(), AF_INET6 ); -#endif - if (!he) - { - return false; - } - memcpy(&sa.sin6_addr,he -> h_addr_list[0],he -> h_length); -#ifdef SOLARIS - free(he); -#endif - return true; -#else - struct addrinfo hints; - memset(&hints, 0, sizeof(hints)); - hints.ai_flags = ai_flags; - hints.ai_family = AF_INET6; - hints.ai_socktype = 0; - hints.ai_protocol = 0; - struct addrinfo *res; - if (Utility::isipv6(host)) - hints.ai_flags |= AI_NUMERICHOST; - int n = getaddrinfo(host.c_str(), NULL, &hints, &res); - if (!n) - { - std::vector<struct addrinfo *> vec; - struct addrinfo *ai = res; - while (ai) - { - if (ai -> ai_addrlen == sizeof(sa)) - vec.push_back( ai ); - ai = ai -> ai_next; - } - if (vec.empty()) - return false; - ai = vec[Utility::Rnd() % vec.size()]; - { - memcpy(&sa, ai -> ai_addr, ai -> ai_addrlen); - } - freeaddrinfo(res); - return true; - } - std::string error = "Error: "; -#ifndef __CYGWIN__ - error += gai_strerror(n); -#endif - return false; -#endif // NO_GETADDRINFO -} -#endif // IPPROTO_IPV6 -#endif // ENABLE_IPV6 - -bool Utility::reverse(struct sockaddr *sa, socklen_t sa_len, std::string& hostname, int flags) -{ - std::string service; - return Utility::reverse(sa, sa_len, hostname, service, flags); -} - -bool Utility::reverse(struct sockaddr *sa, socklen_t sa_len, std::string& hostname, std::string& service, int flags) -{ - hostname = ""; - service = ""; -#ifdef NO_GETADDRINFO - switch (sa -> sa_family) - { - case AF_INET: - if (flags & NI_NUMERICHOST) - { - union { - struct { - unsigned char b1; - unsigned char b2; - unsigned char b3; - unsigned char b4; - } a; - ipaddr_t l; - } u; - struct sockaddr_in *sa_in = (struct sockaddr_in *)sa; - memcpy(&u.l, &sa_in -> sin_addr, sizeof(u.l)); - char tmp[100]; - sprintf(tmp, "%u.%u.%u.%u", u.a.b1, u.a.b2, u.a.b3, u.a.b4); - hostname = tmp; - return true; - } - else - { - struct sockaddr_in *sa_in = (struct sockaddr_in *)sa; - struct hostent *h = gethostbyaddr( (const char *)&sa_in -> sin_addr, sizeof(sa_in -> sin_addr), AF_INET); - if (h) - { - hostname = h -> h_name; - return true; - } - } - break; -#ifdef ENABLE_IPV6 - case AF_INET6: - if (flags & NI_NUMERICHOST) - { - char slask[100]; // l2ip temporary - *slask = 0; - unsigned int prev = 0; - bool skipped = false; - bool ok_to_skip = true; - { - unsigned short addr16[8]; - struct sockaddr_in6 *sa_in6 = (struct sockaddr_in6 *)sa; - memcpy(addr16, &sa_in6 -> sin6_addr, sizeof(addr16)); - for (size_t i = 0; i < 8; i++) - { - unsigned short x = ntohs(addr16[i]); - if (*slask && (x || !ok_to_skip || prev)) - strcat(slask,":"); - if (x || !ok_to_skip) - { - sprintf(slask + strlen(slask),"%x", x); - if (x && skipped) - ok_to_skip = false; - } - else - { - skipped = true; - } - prev = x; - } - } - if (!*slask) - strcpy(slask, "::"); - hostname = slask; - return true; - } - else - { - // %! TODO: ipv6 reverse lookup - struct sockaddr_in6 *sa_in = (struct sockaddr_in6 *)sa; - struct hostent *h = gethostbyaddr( (const char *)&sa_in -> sin6_addr, sizeof(sa_in -> sin6_addr), AF_INET6); - if (h) - { - hostname = h -> h_name; - return true; - } - } - break; -#endif - } - return false; -#else - char host[NI_MAXHOST]; - char serv[NI_MAXSERV]; - // NI_NOFQDN - // NI_NUMERICHOST - // NI_NAMEREQD - // NI_NUMERICSERV - // NI_DGRAM - int n = getnameinfo(sa, sa_len, host, sizeof(host), serv, sizeof(serv), flags); - if (n) - { - // EAI_AGAIN - // EAI_BADFLAGS - // EAI_FAIL - // EAI_FAMILY - // EAI_MEMORY - // EAI_NONAME - // EAI_OVERFLOW - // EAI_SYSTEM - return false; - } - hostname = host; - service = serv; - return true; -#endif // NO_GETADDRINFO -} - -bool Utility::u2service(const std::string& name, int& service, int ai_flags) -{ -#ifdef NO_GETADDRINFO - // %! - return false; -#else - struct addrinfo hints; - service = 0; - memset(&hints, 0, sizeof(hints)); - // AI_NUMERICHOST - // AI_CANONNAME - // AI_PASSIVE - server - // AI_ADDRCONFIG - // AI_V4MAPPED - // AI_ALL - // AI_NUMERICSERV - hints.ai_flags = ai_flags; - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = 0; - hints.ai_protocol = 0; - struct addrinfo *res; - int n = getaddrinfo(NULL, name.c_str(), &hints, &res); - if (!n) - { - service = res -> ai_protocol; - freeaddrinfo(res); - return true; - } - return false; -#endif // NO_GETADDRINFO -} - -unsigned long Utility::ThreadID() -{ -#ifdef _WIN32 - return GetCurrentThreadId(); -#else - return (unsigned long)pthread_self(); -#endif -} - -std::string Utility::ToLower(const std::string& str) -{ - std::string r; - for (size_t i = 0; i < str.size(); i++) - { - if (str[i] >= 'A' && str[i] <= 'Z') - r += str[i] | 32; - else - r += str[i]; - } - return r; -} - -std::string Utility::ToUpper(const std::string& str) -{ - std::string r; - for (size_t i = 0; i < str.size(); i++) - { - if (str[i] >= 'a' && str[i] <= 'z') - r += (char)(str[i] - 32); - else - r += str[i]; - } - return r; -} - -std::string Utility::ToString(double d) -{ - char tmp[100]; - sprintf(tmp, "%f", d); - return tmp; -} - -unsigned long Utility::Rnd() -{ -static Utility::Rng generator( (unsigned long)time(NULL) ); - return generator.Get(); -} - -Utility::Rng::Rng(unsigned long seed) : m_value( 0 ) -{ - m_tmp[0]= seed & 0xffffffffUL; - for (int i = 1; i < TWIST_LEN; i++) - { - m_tmp[i] = (1812433253UL * (m_tmp[i - 1] ^ (m_tmp[i - 1] >> 30)) + i); - } -} - -unsigned long Utility::Rng::Get() -{ - unsigned long val = m_tmp[m_value]; - ++m_value; - if (m_value == TWIST_LEN) - { - for (int i = 0; i < TWIST_IB; ++i) - { - unsigned long s = TWIST(m_tmp, i, i + 1); - m_tmp[i] = m_tmp[i + TWIST_IA] ^ (s >> 1) ^ MAGIC_TWIST(s); - } - { - for (int i = 0; i < TWIST_LEN - 1; ++i) - { - unsigned long s = TWIST(m_tmp, i, i + 1); - m_tmp[i] = m_tmp[i - TWIST_IB] ^ (s >> 1) ^ MAGIC_TWIST(s); - } - } - unsigned long s = TWIST(m_tmp, TWIST_LEN - 1, 0); - m_tmp[TWIST_LEN - 1] = m_tmp[TWIST_IA - 1] ^ (s >> 1) ^ MAGIC_TWIST(s); - - m_value = 0; - } - return val; -} - -#ifdef SOCKETS_NAMESPACE -} -#endif - - diff --git a/dep/sockets/include/Base64.h b/dep/sockets/include/Base64.h deleted file mode 100644 index d4323aaa019..00000000000 --- a/dep/sockets/include/Base64.h +++ /dev/null @@ -1,77 +0,0 @@ -/** \file Base64.h - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_Base64_H -#define _SOCKETS_Base64_H - -#include "sockets-config.h" -#ifdef _MSC_VER -#pragma warning(disable:4514) -#endif - -#include <stdio.h> -#include <string> - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** \defgroup util Utilities */ - -/** Base64 encode/decode. - \ingroup util */ -class Base64 -{ -public: - Base64(); - - void encode(FILE *, std::string& , bool add_crlf = true); - void encode(const std::string&, std::string& , bool add_crlf = true); - void encode(const char *, size_t, std::string& , bool add_crlf = true); - void encode(const unsigned char *, size_t, std::string& , bool add_crlf = true); - - void decode(const std::string&, std::string& ); - void decode(const std::string&, unsigned char *, size_t&); - - size_t decode_length(const std::string& ); - -private: - Base64(const Base64& ) {} - Base64& operator=(const Base64& ) { return *this; } -static const char *bstr; -static const char rstr[128]; -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_Base64_H - - diff --git a/dep/sockets/include/Exception.h b/dep/sockets/include/Exception.h deleted file mode 100644 index bb881b2d74f..00000000000 --- a/dep/sockets/include/Exception.h +++ /dev/null @@ -1,55 +0,0 @@ -/** - ** \file Exception.h - ** \date 2007-09-28 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2007 Anders Hedstrom - -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, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _Sockets_Exception_H -#define _Sockets_Exception_H - -#include <string> - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -class Exception -{ -public: - Exception(const std::string& description); - virtual ~Exception() {} - - virtual const std::string ToString() const; - - Exception(const Exception& ) {} // copy constructor - - Exception& operator=(const Exception& ) { return *this; } // assignment operator - -private: - std::string m_description; - -}; - -#ifdef SOCKETS_NAMESPACE -} // namespace SOCKETS_NAMESPACE { -#endif - -#endif // _Sockets_Exception_H - - diff --git a/dep/sockets/include/File.h b/dep/sockets/include/File.h deleted file mode 100644 index ed322efa2d8..00000000000 --- a/dep/sockets/include/File.h +++ /dev/null @@ -1,82 +0,0 @@ -/** \file File.h - ** \date 2005-04-25 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_File_H -#define _SOCKETS_File_H - -#include "sockets-config.h" -#include "IFile.h" -#include <stdio.h> - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** IFile implementation of a disk file. - \ingroup file */ -class File : public IFile -{ -public: - File(); - ~File(); - - bool fopen(const std::string&, const std::string&); - void fclose(); - - size_t fread(char *, size_t, size_t) const; - size_t fwrite(const char *, size_t, size_t); - - char *fgets(char *, int) const; - void fprintf(const char *format, ...); - - off_t size() const; - bool eof() const; - - void reset_read() const; - void reset_write(); - -private: - File(const File& ) {} // copy constructor - File& operator=(const File& ) { return *this; } // assignment operator - - std::string m_path; - std::string m_mode; - FILE *m_fil; - mutable long m_rptr; - long m_wptr; -}; - - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_File_H - - diff --git a/dep/sockets/include/IFile.h b/dep/sockets/include/IFile.h deleted file mode 100644 index 657c8a4b1d9..00000000000 --- a/dep/sockets/include/IFile.h +++ /dev/null @@ -1,71 +0,0 @@ -/** \file IFile.h - ** \date 2005-04-25 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_IFile_H -#define _SOCKETS_IFile_H - -#include "sockets-config.h" -#include <string> - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** \defgroup file File handling */ -/** Pure virtual file I/O interface. - \ingroup file */ -class IFile -{ -public: - virtual ~IFile() {} - - virtual bool fopen(const std::string&, const std::string&) = 0; - virtual void fclose() = 0; - - virtual size_t fread(char *, size_t, size_t) const = 0; - virtual size_t fwrite(const char *, size_t, size_t) = 0; - - virtual char *fgets(char *, int) const = 0; - virtual void fprintf(const char *format, ...) = 0; - - virtual off_t size() const = 0; - virtual bool eof() const = 0; - - virtual void reset_read() const = 0; - virtual void reset_write() = 0; - -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_IFile_H - - diff --git a/dep/sockets/include/ISocketHandler.h b/dep/sockets/include/ISocketHandler.h deleted file mode 100644 index 940783c104b..00000000000 --- a/dep/sockets/include/ISocketHandler.h +++ /dev/null @@ -1,231 +0,0 @@ -/** \file ISocketHandler.h - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_ISocketHandler_H -#define _SOCKETS_ISocketHandler_H -#include "sockets-config.h" - -#include <list> - -#include "socket_include.h" -#include "Socket.h" -#include "StdLog.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -typedef enum { - LIST_CALLONCONNECT = 0, -#ifdef ENABLE_DETACH - LIST_DETACH, -#endif - LIST_TIMEOUT, - LIST_RETRY, - LIST_CLOSE -} list_t; - -class SocketAddress; -class Mutex; - -/** Socket container class, event generator. - \ingroup basic */ -class ISocketHandler -{ - friend class Socket; - -public: - /** Connection pool class for internal use by the ISocketHandler. - \ingroup internal */ -#ifdef ENABLE_POOL - class PoolSocket : public Socket - { - public: - PoolSocket(ISocketHandler& h,Socket *src) : Socket(h) { - CopyConnection( src ); - SetIsClient(); - } - - void OnRead() { - Handler().LogError(this, "OnRead", 0, "data on hibernating socket", LOG_LEVEL_FATAL); - SetCloseAndDelete(); - } - void OnOptions(int,int,int,SOCKET) {} - - }; -#endif - -public: - virtual ~ISocketHandler() {} - - /** Get mutex reference for threadsafe operations. */ - virtual Mutex& GetMutex() const = 0; - - /** Register StdLog object for error callback. - \param log Pointer to log class */ - virtual void RegStdLog(StdLog *log) = 0; - - /** Log error to log class for print out / storage. */ - virtual void LogError(Socket *p,const std::string& user_text,int err,const std::string& sys_err,loglevel_t t = LOG_LEVEL_WARNING) = 0; - - // ------------------------------------------------------------------------- - // Socket stuff - // ------------------------------------------------------------------------- - /** Add socket instance to socket map. Removal is always automatic. */ - virtual void Add(Socket *) = 0; -private: - /** Remove socket from socket map, used by Socket class. */ - virtual void Remove(Socket *) = 0; -public: - /** Get status of read/write/exception file descriptor set for a socket. */ - virtual void Get(SOCKET s,bool& r,bool& w,bool& e) = 0; - /** Set read/write/exception file descriptor sets (fd_set). */ - virtual void Set(SOCKET s,bool bRead,bool bWrite,bool bException = true) = 0; - - /** Wait for events, generate callbacks. */ - virtual int Select(long sec,long usec) = 0; - /** This method will not return until an event has been detected. */ - virtual int Select() = 0; - /** Wait for events, generate callbacks. */ - virtual int Select(struct timeval *tsel) = 0; - - /** Check that a socket really is handled by this socket handler. */ - virtual bool Valid(Socket *) = 0; - /** Return number of sockets handled by this handler. */ - virtual size_t GetCount() = 0; - - /** Override and return false to deny all incoming connections. - \param p ListenSocket class pointer (use GetPort to identify which one) */ - virtual bool OkToAccept(Socket *p) = 0; - - /** Called by Socket when a socket changes state. */ - virtual void AddList(SOCKET s,list_t which_one,bool add) = 0; - - // ------------------------------------------------------------------------- - // Connection pool - // ------------------------------------------------------------------------- -#ifdef ENABLE_POOL - /** Find available open connection (used by connection pool). */ - virtual ISocketHandler::PoolSocket *FindConnection(int type,const std::string& protocol,SocketAddress&) = 0; - /** Enable connection pool (by default disabled). */ - virtual void EnablePool(bool = true) = 0; - /** Check pool status. - \return true if connection pool is enabled */ - virtual bool PoolEnabled() = 0; -#endif // ENABLE_POOL - - // ------------------------------------------------------------------------- - // Socks4 - // ------------------------------------------------------------------------- -#ifdef ENABLE_SOCKS4 - /** Set socks4 server ip that all new tcp sockets should use. */ - virtual void SetSocks4Host(ipaddr_t) = 0; - /** Set socks4 server hostname that all new tcp sockets should use. */ - virtual void SetSocks4Host(const std::string& ) = 0; - /** Set socks4 server port number that all new tcp sockets should use. */ - virtual void SetSocks4Port(port_t) = 0; - /** Set optional socks4 userid. */ - virtual void SetSocks4Userid(const std::string& ) = 0; - /** If connection to socks4 server fails, immediately try direct connection to final host. */ - virtual void SetSocks4TryDirect(bool = true) = 0; - /** Get socks4 server ip. - \return socks4 server ip */ - virtual ipaddr_t GetSocks4Host() = 0; - /** Get socks4 port number. - \return socks4 port number */ - virtual port_t GetSocks4Port() = 0; - /** Get socks4 userid (optional). - \return socks4 userid */ - virtual const std::string& GetSocks4Userid() = 0; - /** Check status of socks4 try direct flag. - \return true if direct connection should be tried if connection to socks4 server fails */ - virtual bool Socks4TryDirect() = 0; -#endif // ENABLE_SOCKS4 - - // ------------------------------------------------------------------------- - // DNS resolve server - // ------------------------------------------------------------------------- -#ifdef ENABLE_RESOLVER - /** Enable asynchronous DNS. - \param port Listen port of asynchronous dns server */ - virtual void EnableResolver(port_t = 16667) = 0; - /** Check resolver status. - \return true if resolver is enabled */ - virtual bool ResolverEnabled() = 0; - /** Queue a dns request. - \param host Hostname to be resolved - \param port Port number will be echoed in Socket::OnResolved callback */ - virtual int Resolve(Socket *,const std::string& host,port_t port) = 0; -#ifdef ENABLE_IPV6 - virtual int Resolve6(Socket *,const std::string& host,port_t port) = 0; -#endif - /** Do a reverse dns lookup. */ - virtual int Resolve(Socket *,ipaddr_t a) = 0; -#ifdef ENABLE_IPV6 - virtual int Resolve(Socket *,in6_addr& a) = 0; -#endif - /** Get listen port of asynchronous dns server. */ - virtual port_t GetResolverPort() = 0; - /** Resolver thread ready for queries. */ - virtual bool ResolverReady() = 0; - /** Returns true if socket waiting for a resolve event. */ - virtual bool Resolving(Socket *) = 0; -#endif // ENABLE_RESOLVER - -#ifdef ENABLE_TRIGGERS - /** Fetch unique trigger id. */ - virtual int TriggerID(Socket *src) = 0; - /** Subscribe socket to trigger id. */ - virtual bool Subscribe(int id, Socket *dst) = 0; - /** Unsubscribe socket from trigger id. */ - virtual bool Unsubscribe(int id, Socket *dst) = 0; - /** Execute OnTrigger for subscribed sockets. - \param id Trigger ID - \param data Data passed from source to destination - \param erase Empty trigger id source and destination maps if 'true', - Leave them in place if 'false' - if a trigger should be called many times */ - virtual void Trigger(int id, Socket::TriggerData& data, bool erase = true) = 0; -#endif // ENABLE_TRIGGERS - -#ifdef ENABLE_DETACH - /** Indicates that the handler runs under SocketThread. */ - virtual void SetSlave(bool x = true) = 0; - /** Indicates that the handler runs under SocketThread. */ - virtual bool IsSlave() = 0; -#endif // ENABLE_DETACH - -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_ISocketHandler_H - - diff --git a/dep/sockets/include/Ipv4Address.h b/dep/sockets/include/Ipv4Address.h deleted file mode 100644 index 71d925254e9..00000000000 --- a/dep/sockets/include/Ipv4Address.h +++ /dev/null @@ -1,95 +0,0 @@ -/** - ** \file Ipv4Address.h - ** \date 2006-09-21 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2007 Anders Hedstrom - -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, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_Ipv4Address_H -#define _SOCKETS_Ipv4Address_H - -#include "sockets-config.h" -#include "SocketAddress.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/* Ipv4 address implementation. - \ingroup basic */ -class Ipv4Address : public SocketAddress -{ -public: - /** Create empty Ipv4 address structure. - \param port Port number */ - Ipv4Address(port_t port = 0); - /** Create Ipv4 address structure. - \param a Socket address in network byte order (as returned by Utility::u2ip) - \param port Port number in host byte order */ - Ipv4Address(ipaddr_t a,port_t port); - /** Create Ipv4 address structure. - \param a Socket address in network byte order - \param port Port number in host byte order */ - Ipv4Address(struct in_addr& a,port_t port); - /** Create Ipv4 address structure. - \param host Hostname to be resolved - \param port Port number in host byte order */ - Ipv4Address(const std::string& host,port_t port); - Ipv4Address(struct sockaddr_in&); - ~Ipv4Address(); - - // SocketAddress implementation - - operator struct sockaddr *(); - operator socklen_t(); - bool operator==(SocketAddress&); - - void SetPort(port_t port); - port_t GetPort(); - - void SetAddress(struct sockaddr *sa); - int GetFamily(); - - bool IsValid(); - std::auto_ptr<SocketAddress> GetCopy(); - - /** Convert address struct to text. */ - std::string Convert(bool include_port = false); - std::string Reverse(); - - /** Resolve hostname. */ -static bool Resolve(const std::string& hostname,struct in_addr& a); - /** Reverse resolve (IP to hostname). */ -static bool Reverse(struct in_addr& a,std::string& name); - /** Convert address struct to text. */ -static std::string Convert(struct in_addr& a); - -private: - Ipv4Address(const Ipv4Address& ) {} // copy constructor - Ipv4Address& operator=(const Ipv4Address& ) { return *this; } // assignment operator - struct sockaddr_in m_addr; - bool m_valid; -}; - - -#ifdef SOCKETS_NAMESPACE -} // namespace SOCKETS_NAMESPACE { -#endif -#endif // _SOCKETS_Ipv4Address_H - - diff --git a/dep/sockets/include/Ipv6Address.h b/dep/sockets/include/Ipv6Address.h deleted file mode 100644 index 20c68d8c92d..00000000000 --- a/dep/sockets/include/Ipv6Address.h +++ /dev/null @@ -1,105 +0,0 @@ -/** - ** \file Ipv6Address.h - ** \date 2006-09-21 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2007 Anders Hedstrom - -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, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_Ipv6Address_H -#define _SOCKETS_Ipv6Address_H -#include "sockets-config.h" -#ifdef ENABLE_IPV6 - -#include "SocketAddress.h" -#ifdef IPPROTO_IPV6 -#if defined( _WIN32) && !defined(__CYGWIN__) -typedef unsigned __int32 uint32_t; -#endif - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** Ipv6 address implementation. - \ingroup basic */ -class Ipv6Address : public SocketAddress -{ -public: - /** Create empty Ipv6 address structure. - \param port Port number */ - Ipv6Address(port_t port = 0); - /** Create Ipv6 address structure. - \param a Socket address in network byte order - \param port Port number in host byte order */ - Ipv6Address(struct in6_addr& a,port_t port); - /** Create Ipv6 address structure. - \param host Hostname to be resolved - \param port Port number in host byte order */ - Ipv6Address(const std::string& host,port_t port); - Ipv6Address(struct sockaddr_in6&); - ~Ipv6Address(); - - // SocketAddress implementation - - operator struct sockaddr *(); - operator socklen_t(); - bool operator==(SocketAddress&); - - void SetPort(port_t port); - port_t GetPort(); - - void SetAddress(struct sockaddr *sa); - int GetFamily(); - - bool IsValid(); - std::auto_ptr<SocketAddress> GetCopy(); - - /** Convert address struct to text. */ - std::string Convert(bool include_port = false); - std::string Reverse(); - - /** Resolve hostname. */ -static bool Resolve(const std::string& hostname,struct in6_addr& a); - /** Reverse resolve (IP to hostname). */ -static bool Reverse(struct in6_addr& a,std::string& name); - /** Convert address struct to text. */ -static std::string Convert(struct in6_addr& a,bool mixed = false); - - void SetFlowinfo(uint32_t); - uint32_t GetFlowinfo(); -#ifndef _WIN32 - void SetScopeId(uint32_t); - uint32_t GetScopeId(); -#endif - -private: - Ipv6Address(const Ipv6Address& ) {} // copy constructor - Ipv6Address& operator=(const Ipv6Address& ) { return *this; } // assignment operator - struct sockaddr_in6 m_addr; - bool m_valid; -}; - - -#ifdef SOCKETS_NAMESPACE -} // namespace SOCKETS_NAMESPACE { -#endif -#endif // IPPROTO_IPV6 -#endif // ENABLE_IPV6 -#endif // _SOCKETS_Ipv6Address_H - - diff --git a/dep/sockets/include/ListenSocket.h b/dep/sockets/include/ListenSocket.h deleted file mode 100644 index 8934a809d0e..00000000000 --- a/dep/sockets/include/ListenSocket.h +++ /dev/null @@ -1,418 +0,0 @@ -/** \file ListenSocket.h - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_ListenSocket_H -#define _SOCKETS_ListenSocket_H -#include "sockets-config.h" - -#ifdef _WIN32 -#include <stdlib.h> -#else -#include <errno.h> -#endif - -#include "ISocketHandler.h" -#include "Socket.h" -#include "Utility.h" -#include "SctpSocket.h" -#include "Ipv4Address.h" -#include "Ipv6Address.h" -#ifdef ENABLE_EXCEPTIONS -#include "Exception.h" -#endif - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** Binds incoming port number to new Socket class X. - \ingroup basic */ -template <class X> -class ListenSocket : public Socket -{ -public: - /** Constructor. - \param h ISocketHandler reference - \param use_creator Optional use of creator (default true) */ - ListenSocket(ISocketHandler& h,bool use_creator = true) : Socket(h), m_depth(0), m_creator(NULL) - ,m_bHasCreate(false) - { - if (use_creator) - { - m_creator = new X(h); - Socket *tmp = m_creator -> Create(); - if (tmp && dynamic_cast<X *>(tmp)) - { - m_bHasCreate = true; - } - if (tmp) - { - delete tmp; - } - } - } - ~ListenSocket() { - if (m_creator) - { - delete m_creator; - } - } - - /** Close file descriptor. */ - int Close() { - if (GetSocket() != INVALID_SOCKET) - { - closesocket(GetSocket()); - } - return 0; - } - - /** Bind and listen to any interface. - \param port Port (0 is random) - \param depth Listen queue depth */ - int Bind(port_t port,int depth = 20) { -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - Ipv6Address ad(port); - return Bind(ad, depth); - } - else -#endif -#endif - { - Ipv4Address ad(port); - return Bind(ad, depth); - } - } - - int Bind(SocketAddress& ad,int depth) { -#ifdef USE_SCTP - if (dynamic_cast<SctpSocket *>(m_creator)) - { - return Bind(ad, "sctp", depth); - } -#endif - return Bind(ad, "tcp", depth); - } - - /** Bind and listen to any interface, with optional protocol. - \param port Port (0 is random) - \param protocol Network protocol - \param depth Listen queue depth */ - int Bind(port_t port,const std::string& protocol,int depth = 20) { -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - Ipv6Address ad(port); - return Bind(ad, protocol, depth); - } - else -#endif -#endif - { - Ipv4Address ad(port); - return Bind(ad, protocol, depth); - } - } - - /** Bind and listen to specific interface. - \param intf Interface hostname - \param port Port (0 is random) - \param depth Listen queue depth */ - int Bind(const std::string& intf,port_t port,int depth = 20) { -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - Ipv6Address ad(intf, port); - if (ad.IsValid()) - { - return Bind(ad, depth); - } - Handler().LogError(this, "Bind", 0, "name resolution of interface name failed", LOG_LEVEL_FATAL); - return -1; - } - else -#endif -#endif - { - Ipv4Address ad(intf, port); - if (ad.IsValid()) - { - return Bind(ad, depth); - } - Handler().LogError(this, "Bind", 0, "name resolution of interface name failed", LOG_LEVEL_FATAL); - return -1; - } - } - - /** Bind and listen to specific interface. - \param intf Interface hostname - \param port Port (0 is random) - \param protocol Network protocol - \param depth Listen queue depth */ - int Bind(const std::string& intf,port_t port,const std::string& protocol,int depth = 20) { -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (IsIpv6()) - { - Ipv6Address ad(intf, port); - if (ad.IsValid()) - { - return Bind(ad, protocol, depth); - } - Handler().LogError(this, "Bind", 0, "name resolution of interface name failed", LOG_LEVEL_FATAL); - return -1; - } - else -#endif -#endif - { - Ipv4Address ad(intf, port); - if (ad.IsValid()) - { - return Bind(ad, protocol, depth); - } - Handler().LogError(this, "Bind", 0, "name resolution of interface name failed", LOG_LEVEL_FATAL); - return -1; - } - } - - /** Bind and listen to ipv4 interface. - \param a Ipv4 interface address - \param port Port (0 is random) - \param depth Listen queue depth */ - int Bind(ipaddr_t a,port_t port,int depth = 20) { - Ipv4Address ad(a, port); -#ifdef USE_SCTP - if (dynamic_cast<SctpSocket *>(m_creator)) - { - return Bind(ad, "sctp", depth); - } -#endif - return Bind(ad, "tcp", depth); - } - /** Bind and listen to ipv4 interface. - \param a Ipv4 interface address - \param port Port (0 is random) - \param protocol Network protocol - \param depth Listen queue depth */ - int Bind(ipaddr_t a,port_t port,const std::string& protocol,int depth) { - Ipv4Address ad(a, port); - return Bind(ad, protocol, depth); - } - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** Bind and listen to ipv6 interface. - \param a Ipv6 interface address - \param port Port (0 is random) - \param depth Listen queue depth */ - int Bind(in6_addr a,port_t port,int depth = 20) { - Ipv6Address ad(a, port); -#ifdef USE_SCTP - if (dynamic_cast<SctpSocket *>(m_creator)) - { - return Bind(ad, "sctp", depth); - } -#endif - return Bind(ad, "tcp", depth); - } - /** Bind and listen to ipv6 interface. - \param a Ipv6 interface address - \param port Port (0 is random) - \param protocol Network protocol - \param depth Listen queue depth */ - int Bind(in6_addr a,port_t port,const std::string& protocol,int depth) { - Ipv6Address ad(a, port); - return Bind(ad, protocol, depth); - } -#endif -#endif - - /** Bind and listen to network interface. - \param ad Interface address - \param protocol Network protocol - \param depth Listen queue depth */ - int Bind(SocketAddress& ad,const std::string& protocol,int depth) { - SOCKET s; - if ( (s = CreateSocket(ad.GetFamily(), SOCK_STREAM, protocol)) == INVALID_SOCKET) - { - return -1; - } - if (bind(s, ad, ad) == -1) - { - Handler().LogError(this, "bind", Errno, StrError(Errno), LOG_LEVEL_FATAL); - closesocket(s); -#ifdef ENABLE_EXCEPTIONS - throw Exception("bind() failed for port " + Utility::l2string(ad.GetPort()) + ": " + StrError(Errno)); -#endif - return -1; - } - if (listen(s, depth) == -1) - { - Handler().LogError(this, "listen", Errno, StrError(Errno), LOG_LEVEL_FATAL); - closesocket(s); -#ifdef ENABLE_EXCEPTIONS - throw Exception("listen() failed for port " + Utility::l2string(ad.GetPort()) + ": " + StrError(Errno)); -#endif - return -1; - } - m_depth = depth; - Attach(s); - return 0; - } - - /** Return assigned port number. */ - port_t GetPort() - { - return GetSockPort(); - } - - /** Return listen queue depth. */ - int GetDepth() - { - return m_depth; - } - - /** OnRead on a ListenSocket receives an incoming connection. */ - void OnRead() - { - struct sockaddr sa; - socklen_t sa_len = sizeof(struct sockaddr); - SOCKET a_s = accept(GetSocket(), &sa, &sa_len); - - if (a_s == INVALID_SOCKET) - { - Handler().LogError(this, "accept", Errno, StrError(Errno), LOG_LEVEL_ERROR); - return; - } - if (!Handler().OkToAccept(this)) - { - Handler().LogError(this, "accept", -1, "Not OK to accept", LOG_LEVEL_WARNING); - closesocket(a_s); - return; - } - if (Handler().GetCount() >= FD_SETSIZE) - { - Handler().LogError(this, "accept", (int)Handler().GetCount(), "ISocketHandler fd_set limit reached", LOG_LEVEL_FATAL); - closesocket(a_s); - return; - } - Socket *tmp = m_bHasCreate ? m_creator -> Create() : new X(Handler()); -#ifdef ENABLE_IPV6 - tmp -> SetIpv6( IsIpv6() ); -#endif - tmp -> SetParent(this); - tmp -> Attach(a_s); - tmp -> SetNonblocking(true); - { -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - if (sa_len == sizeof(struct sockaddr_in6)) - { - struct sockaddr_in6 *p = (struct sockaddr_in6 *)&sa; - if (p -> sin6_family == AF_INET6) - { - Ipv6Address ad(p -> sin6_addr,ntohs(p -> sin6_port)); - ad.SetFlowinfo(p -> sin6_flowinfo); -#ifndef _WIN32 - ad.SetScopeId(p -> sin6_scope_id); -#endif - tmp -> SetRemoteAddress(ad); - } - } -#endif -#endif - if (sa_len == sizeof(struct sockaddr_in)) - { - struct sockaddr_in *p = (struct sockaddr_in *)&sa; - if (p -> sin_family == AF_INET) - { - Ipv4Address ad(p -> sin_addr,ntohs(p -> sin_port)); - tmp -> SetRemoteAddress(ad); - } - } - } - tmp -> SetConnected(true); - tmp -> Init(); - tmp -> SetDeleteByHandler(true); - Handler().Add(tmp); -#ifdef HAVE_OPENSSL - if (tmp -> IsSSL()) // SSL Enabled socket - { - // %! OnSSLAccept calls SSLNegotiate that can finish in this one call. - // %! If that happens and negotiation fails, the 'tmp' instance is - // %! still added to the list of active sockets in the sockethandler. - // %! See bugfix for this in SocketHandler::Select - don't Set rwx - // %! flags if CloseAndDelete() flag is true. - // %! An even better fugbix (see TcpSocket::OnSSLAccept) now avoids - // %! the Add problem altogether, so ignore the above. - // %! (OnSSLAccept does no longer call SSLNegotiate().) - tmp -> OnSSLAccept(); - } - else -#endif - { - tmp -> OnAccept(); - } - } - - /** Please don't use this method. - "accept()" is handled automatically in the OnRead() method. */ - virtual SOCKET Accept(SOCKET socket, struct sockaddr *saptr, socklen_t *lenptr) - { - return accept(socket, saptr, lenptr); - } - - bool HasCreator() { return m_bHasCreate; } - - void OnOptions(int,int,int,SOCKET) { - SetSoReuseaddr(true); - } - -protected: - ListenSocket(const ListenSocket& s) : Socket(s) {} -private: - ListenSocket& operator=(const ListenSocket& ) { return *this; } - int m_depth; - X *m_creator; - bool m_bHasCreate; -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_ListenSocket_H - - diff --git a/dep/sockets/include/Lock.h b/dep/sockets/include/Lock.h deleted file mode 100644 index f3bb9273920..00000000000 --- a/dep/sockets/include/Lock.h +++ /dev/null @@ -1,58 +0,0 @@ -/** \file Lock.h - ** \date 2005-08-22 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2005,2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_Lock_H -#define _SOCKETS_Lock_H - -#include "sockets-config.h" -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -class Mutex; - -/** Mutex encapsulation class. - \ingroup threading */ -class Lock -{ -public: - Lock(Mutex&); - ~Lock(); - -private: - Mutex& m_mutex; -}; - - -#ifdef SOCKETS_NAMESPACE -} -#endif -#endif // _SOCKETS_Lock_H - - diff --git a/dep/sockets/include/Mutex.h b/dep/sockets/include/Mutex.h deleted file mode 100644 index e42a57c3262..00000000000 --- a/dep/sockets/include/Mutex.h +++ /dev/null @@ -1,68 +0,0 @@ -/** \file Mutex.h - ** \date 2004-10-30 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_Mutex_H -#define _SOCKETS_Mutex_H - -#include "sockets-config.h" -#ifndef _WIN32 -#include <pthread.h> -#else -#include <windows.h> -#endif - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** Mutex container class, used by Lock. - \ingroup threading */ -class Mutex -{ - friend class Lock; -public: - Mutex(); - ~Mutex(); - - void Lock(); - void Unlock(); -private: -#ifdef _WIN32 - HANDLE m_mutex; -#else - pthread_mutex_t m_mutex; -#endif -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif -#endif // _SOCKETS_Mutex_H - - diff --git a/dep/sockets/include/Parse.h b/dep/sockets/include/Parse.h deleted file mode 100644 index 52bd9327e28..00000000000 --- a/dep/sockets/include/Parse.h +++ /dev/null @@ -1,100 +0,0 @@ -/** \file Parse.h - parse a string - ** - ** Written: 1999-Feb-10 grymse@alhem.net - **/ - -/* -Copyright (C) 1999-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ - -#ifndef _SOCKETS_Parse_H -#define _SOCKETS_Parse_H - -#include "sockets-config.h" -#ifdef _MSC_VER -#pragma warning(disable:4514) -#endif - -#include <string> - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/***************************************************/ -/* interface of class Parse */ - -/** Splits a string whatever way you want. - \ingroup util */ -class Parse -{ -public: - Parse(); - Parse(const std::string&); - Parse(const std::string&,const std::string&); - Parse(const std::string&,const std::string&,short); - ~Parse(); - short issplit(const char); - void getsplit(); - void getsplit(std::string&); - std::string getword(); - void getword(std::string&); - void getword(std::string&,std::string&,int); - std::string getrest(); - void getrest(std::string&); - long getvalue(); - void setbreak(const char); - int getwordlen(); - int getrestlen(); - void enablebreak(const char c) { - pa_enable = c; - } - void disablebreak(const char c) { - pa_disable = c; - } - void getline(); - void getline(std::string&); - size_t getptr() { return pa_the_ptr; } - void EnableQuote(bool b) { pa_quote = b; } - -private: - std::string pa_the_str; - std::string pa_splits; - std::string pa_ord; - size_t pa_the_ptr; - char pa_breakchar; - char pa_enable; - char pa_disable; - short pa_nospace; - bool pa_quote; -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_Parse_H - - diff --git a/dep/sockets/include/ResolvServer.h b/dep/sockets/include/ResolvServer.h deleted file mode 100644 index 409c9b7a619..00000000000 --- a/dep/sockets/include/ResolvServer.h +++ /dev/null @@ -1,72 +0,0 @@ -/** \file ResolvServer.h - ** \date 2005-03-24 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_ResolvServer_H -#define _SOCKETS_ResolvServer_H -#include "sockets-config.h" -#ifdef ENABLE_RESOLVER -#include "socket_include.h" -#include "Thread.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** \defgroup async Asynchronous DNS */ -/** Async DNS resolver thread. - \ingroup async */ -class ResolvServer : public Thread -{ -public: - ResolvServer(port_t); - ~ResolvServer(); - - void Run(); - void Quit(); - - bool Ready(); - -private: - ResolvServer(const ResolvServer& ) {} // copy constructor - ResolvServer& operator=(const ResolvServer& ) { return *this; } // assignment operator - - bool m_quit; - port_t m_port; - bool m_ready; -}; - - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // ENABLE_RESOLVER -#endif // _SOCKETS_ResolvServer_H - - diff --git a/dep/sockets/include/ResolvSocket.h b/dep/sockets/include/ResolvSocket.h deleted file mode 100644 index 60743736e08..00000000000 --- a/dep/sockets/include/ResolvSocket.h +++ /dev/null @@ -1,105 +0,0 @@ -/** \file ResolvSocket.h - ** \date 2005-03-24 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_ResolvSocket_H -#define _SOCKETS_ResolvSocket_H -#include "sockets-config.h" -#ifdef ENABLE_RESOLVER -#include "TcpSocket.h" -#include <map> - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -class Mutex; - -/** Async DNS resolver socket. - \ingroup async */ -class ResolvSocket : public TcpSocket -{ - typedef std::map<std::string, /* type */ - std::map<std::string, std::string> > cache_t; /* host, result */ - typedef std::map<std::string, /* type */ - std::map<std::string, time_t> > timeout_t; /* host, time */ - -public: - ResolvSocket(ISocketHandler&); - ResolvSocket(ISocketHandler&, Socket *parent, const std::string& host, port_t port, bool ipv6 = false); - ResolvSocket(ISocketHandler&, Socket *parent, ipaddr_t); -#ifdef ENABLE_IPV6 - ResolvSocket(ISocketHandler&, Socket *parent, in6_addr&); -#endif - ~ResolvSocket(); - - void OnAccept() { m_bServer = true; } - void OnLine(const std::string& line); - void OnDetached(); - void OnDelete(); - - void SetId(int x) { m_resolv_id = x; } - int GetId() { return m_resolv_id; } - - void OnConnect(); - -#ifdef ENABLE_IPV6 - void SetResolveIpv6(bool x = true) { m_resolve_ipv6 = x; } -#endif - -private: - ResolvSocket(const ResolvSocket& s) : TcpSocket(s) {} // copy constructor - ResolvSocket& operator=(const ResolvSocket& ) { return *this; } // assignment operator - - std::string m_query; - std::string m_data; - bool m_bServer; - Socket *m_parent; - int m_resolv_id; - std::string m_resolv_host; - port_t m_resolv_port; - ipaddr_t m_resolv_address; -#ifdef ENABLE_IPV6 - bool m_resolve_ipv6; - in6_addr m_resolv_address6; -#endif - static cache_t m_cache; - static timeout_t m_cache_to; - static Mutex m_cache_mutex; - bool m_cached; -}; - - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // ENABLE_RESOLVER -#endif // _SOCKETS_ResolvSocket_H - - diff --git a/dep/sockets/include/SctpSocket.h b/dep/sockets/include/SctpSocket.h deleted file mode 100644 index ed507fb1880..00000000000 --- a/dep/sockets/include/SctpSocket.h +++ /dev/null @@ -1,108 +0,0 @@ -/** - ** \file SctpSocket.h - ** \date 2006-09-04 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2007 Anders Hedstrom - -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, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_SctpSocket_H -#define _SOCKETS_SctpSocket_H -#include "sockets-config.h" - -#include "StreamSocket.h" -#ifdef USE_SCTP -#include <netinet/sctp.h> - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -#define SCTP_BUFSIZE_READ 16400 - -class SocketAddress; - -class SctpSocket : public StreamSocket -{ -public: - /** SctpSocket constructor. - \param h Owner - \param type SCTP_STREAM or SCTP_SEQPACKET */ - SctpSocket(ISocketHandler& h,int type); - ~SctpSocket(); - - /** bind() */ - int Bind(const std::string&,port_t); - int Bind(SocketAddress&); - /** sctp_bindx() */ - int AddAddress(const std::string&,port_t); - int AddAddress(SocketAddress&); - /** sctp_bindx() */ - int RemoveAddress(const std::string&,port_t); - int RemoveAddress(SocketAddress&); - - /** connect() */ - int Open(const std::string&,port_t); - int Open(SocketAddress&); - - /** Connect timeout callback. */ - void OnConnectTimeout(); -#ifdef _WIN32 - /** Connection failed reported as exception on win32 */ - void OnException(); -#endif - -#ifndef SOLARIS - /** sctp_connectx() */ - int AddConnection(const std::string&,port_t); - int AddConnection(SocketAddress&); -#endif - - /** Get peer addresses of an association. */ - int getpaddrs(sctp_assoc_t id,std::list<std::string>&); - /** Get all bound addresses of an association. */ - int getladdrs(sctp_assoc_t id,std::list<std::string>&); - - /** sctp_peeloff */ - int PeelOff(sctp_assoc_t id); - - /** recvmsg callback */ - virtual void OnReceiveMessage(const char *buf,size_t sz,struct sockaddr *sa,socklen_t sa_len,struct sctp_sndrcvinfo *sinfo,int msg_flags) = 0; - - void OnOptions(int,int,int,SOCKET) {} - - virtual int Protocol(); - -protected: - SctpSocket(const SctpSocket& s) : StreamSocket(s) {} - void OnRead(); - void OnWrite(); - -private: - SctpSocket& operator=(const SctpSocket& s) { return *this; } - int m_type; ///< SCTP_STREAM or SCTP_SEQPACKET - char *m_buf; ///< Temporary receive buffer -}; - -#ifdef SOCKETS_NAMESPACE -} // namespace SOCKETS_NAMESPACE -#endif - -#endif // USE_SCTP -#endif // _SOCKETS_SctpSocket_H - - diff --git a/dep/sockets/include/Socket.h b/dep/sockets/include/Socket.h deleted file mode 100644 index 23a806b5ea1..00000000000 --- a/dep/sockets/include/Socket.h +++ /dev/null @@ -1,735 +0,0 @@ -/** \file Socket.h - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This software is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_Socket_H -#define _SOCKETS_Socket_H -#include "sockets-config.h" - -#include <string> -#include <vector> -#include <list> -#ifdef HAVE_OPENSSL -#include <openssl/ssl.h> -#endif - -#include "socket_include.h" -#include <time.h> -#include "SocketAddress.h" -#include "Thread.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -class ISocketHandler; -class SocketAddress; -class IFile; - -/** \defgroup basic Basic sockets */ -/** Socket base class. - \ingroup basic */ -class Socket -{ - friend class ISocketHandler; -#ifdef ENABLE_DETACH - /** Detached socket run thread. - \ingroup internal */ - class SocketThread : public Thread - { - public: - SocketThread(Socket *p); - ~SocketThread(); - - void Run(); - - private: - Socket *GetSocket() const { return m_socket; } - SocketThread(const SocketThread& s) : m_socket(s.GetSocket()) {} - SocketThread& operator=(const SocketThread& ) { return *this; } - Socket *m_socket; - }; -#endif // ENABLE_DETACH - -#ifdef ENABLE_TRIGGERS -public: - /** Data pass class from source to destination. */ - class TriggerData - { - public: - TriggerData() : m_src(NULL) {} - virtual ~TriggerData() {} - - Socket *GetSource() const { return m_src; } - void SetSource(Socket *x) { m_src = x; } - - private: - Socket *m_src; - }; -#endif // ENABLE_TRIGGERS - - /** Socket mode flags. */ -/* - enum { - // Socket - SOCK_DEL = 0x01, ///< Delete by handler flag - SOCK_CLOSE = 0x02, ///< Close and delete flag - SOCK_DISABLE_READ = 0x04, ///< Disable checking for read events - SOCK_CONNECTED = 0x08, ///< Socket is connected (tcp/udp) - - SOCK_ERASED_BY_HANDLER = 0x10, ///< Set by handler before delete - // HAVE_OPENSSL - SOCK_ENABLE_SSL = 0x20, ///< Enable SSL for this TcpSocket - SOCK_SSL = 0x40, ///< ssl negotiation mode (TcpSocket) - SOCK_SSL_SERVER = 0x80, ///< True if this is an incoming ssl TcpSocket connection - - // ENABLE_IPV6 - SOCK_IPV6 = 0x0100, ///< This is an ipv6 socket if this one is true - // ENABLE_POOL - SOCK_CLIENT = 0x0200, ///< only client connections are pooled - SOCK_RETAIN = 0x0400, ///< keep connection on close - SOCK_LOST = 0x0800, ///< connection lost - - // ENABLE_SOCKS4 - SOCK_SOCKS4 = 0x1000, ///< socks4 negotiation mode (TcpSocket) - // ENABLE_DETACH - SOCK_DETACH = 0x2000, ///< Socket ordered to detach flag - SOCK_DETACHED = 0x4000, ///< Socket has been detached - // StreamSocket - STREAMSOCK_CONNECTING = 0x8000, ///< Flag indicating connection in progress - - STREAMSOCK_FLUSH_BEFORE_CLOSE = 0x010000L, ///< Send all data before closing (default true) - STREAMSOCK_CALL_ON_CONNECT = 0x020000L, ///< OnConnect will be called next ISocketHandler cycle if true - STREAMSOCK_RETRY_CONNECT = 0x040000L, ///< Try another connection attempt next ISocketHandler cycle - STREAMSOCK_LINE_PROTOCOL = 0x080000L, ///< Line protocol mode flag - - }; -*/ - -public: - /** "Default" constructor */ - Socket(ISocketHandler&); - - virtual ~Socket(); - - /** Socket class instantiation method. Used when a "non-standard" constructor - * needs to be used for the socket class. Note: the socket class still needs - * the "default" constructor with one ISocketHandler& as input parameter. - */ - virtual Socket *Create() { return NULL; } - - /** Returns reference to sockethandler that owns the socket. - If the socket is detached, this is a reference to the slave sockethandler. - */ - ISocketHandler& Handler() const; - - /** Returns reference to sockethandler that owns the socket. - This one always returns the reference to the original sockethandler, - even if the socket is detached. - */ - ISocketHandler& MasterHandler() const; - - /** Called by ListenSocket after accept but before socket is added to handler. - * CTcpSocket uses this to create its ICrypt member variable. - * The ICrypt member variable is created by a virtual method, therefore - * it can't be called directly from the CTcpSocket constructor. - * Also used to determine if incoming HTTP connection is normal (port 80) - * or ssl (port 443). - */ - virtual void Init(); - - /** Create a socket file descriptor. - \param af Address family AF_INET / AF_INET6 / ... - \param type SOCK_STREAM / SOCK_DGRAM / ... - \param protocol "tcp" / "udp" / ... */ - SOCKET CreateSocket(int af,int type,const std::string& protocol = ""); - - /** Assign this socket a file descriptor created - by a call to socket() or otherwise. */ - void Attach(SOCKET s); - - /** Return file descriptor assigned to this socket. */ - SOCKET GetSocket(); - - /** Close connection immediately - internal use. - \sa SetCloseAndDelete */ - virtual int Close(); - - /** Add file descriptor to sockethandler fd_set's. */ - void Set(bool bRead,bool bWrite,bool bException = true); - - /** Returns true when socket file descriptor is valid - and socket is not about to be closed. */ - virtual bool Ready(); - - /** Returns pointer to ListenSocket that created this instance - * on an incoming connection. */ - Socket *GetParent(); - - /** Used by ListenSocket to set parent pointer of newly created - * socket instance. */ - void SetParent(Socket *); - - /** Get listening port from ListenSocket<>. */ - virtual port_t GetPort(); - - /** Set socket non-block operation. */ - bool SetNonblocking(bool); - - /** Set socket non-block operation. */ - bool SetNonblocking(bool, SOCKET); - - /** Total lifetime of instance. */ - time_t Uptime(); - - /** Set address/port of last connect() call. */ - void SetClientRemoteAddress(SocketAddress&); - - /** Get address/port of last connect() call. */ - std::auto_ptr<SocketAddress> GetClientRemoteAddress(); - - /** Common interface for SendBuf used by Tcp and Udp sockets. */ - virtual void SendBuf(const char *,size_t,int = 0); - - /** Common interface for Send used by Tcp and Udp sockets. */ - virtual void Send(const std::string&,int = 0); - - /** Outgoing traffic counter. */ - virtual uint64_t GetBytesSent(bool clear = false); - - /** Incoming traffic counter. */ - virtual uint64_t GetBytesReceived(bool clear = false); - - // LIST_TIMEOUT - - /** Enable timeout control. 0=disable timeout check. */ - void SetTimeout(time_t secs); - - /** Check timeout. \return true if time limit reached */ - bool Timeout(time_t tnow); - - /** Used by ListenSocket. ipv4 and ipv6 */ - void SetRemoteAddress(SocketAddress&); - - /** \name Event callbacks */ - //@{ - - /** Called when there is something to be read from the file descriptor. */ - virtual void OnRead(); - /** Called when there is room for another write on the file descriptor. */ - virtual void OnWrite(); - /** Called on socket exception. */ - virtual void OnException(); - /** Called before a socket class is deleted by the ISocketHandler. */ - virtual void OnDelete(); - /** Called when a connection has completed. */ - virtual void OnConnect(); - /** Called when an incoming connection has been completed. */ - virtual void OnAccept(); - /** Called when a complete line has been read and the socket is in - * line protocol mode. */ - virtual void OnLine(const std::string& ); - /** Called on connect timeout (5s). */ - virtual void OnConnectFailed(); - /** Called when a client socket is created, to set socket options. - \param family AF_INET, AF_INET6, etc - \param type SOCK_STREAM, SOCK_DGRAM, etc - \param protocol Protocol number (tcp, udp, sctp, etc) - \param s Socket file descriptor - */ - virtual void OnOptions(int family,int type,int protocol,SOCKET s) = 0; - /** Connection retry callback - return false to abort connection attempts */ - virtual bool OnConnectRetry(); -#ifdef ENABLE_RECONNECT - /** a reconnect has been made */ - virtual void OnReconnect(); -#endif - /** TcpSocket: When a disconnect has been detected (recv/SSL_read returns 0 bytes). */ - virtual void OnDisconnect(); - /** Timeout callback. */ - virtual void OnTimeout(); - /** Connection timeout. */ - virtual void OnConnectTimeout(); - //@} - - /** \name Socket mode flags, set/reset */ - //@{ - /** Set delete by handler true when you want the sockethandler to - delete the socket instance after use. */ - void SetDeleteByHandler(bool = true); - /** Check delete by handler flag. - \return true if this instance should be deleted by the sockethandler */ - bool DeleteByHandler(); - - // LIST_CLOSE - conditional event queue - - /** Set close and delete to terminate the connection. */ - void SetCloseAndDelete(bool = true); - /** Check close and delete flag. - \return true if this socket should be closed and the instance removed */ - bool CloseAndDelete(); - - /** Return number of seconds since socket was ordered to close. \sa SetCloseAndDelete */ - time_t TimeSinceClose(); - - /** Ignore read events for an output only socket. */ - void DisableRead(bool x = true); - /** Check ignore read events flag. - \return true if read events should be ignored */ - bool IsDisableRead(); - - /** Set connected status. */ - void SetConnected(bool = true); - /** Check connected status. - \return true if connected */ - bool IsConnected(); - - /** Connection lost - error while reading/writing from a socket - TcpSocket only. */ - void SetLost(); - /** Check connection lost status flag, used by TcpSocket only. - \return true if there was an error while r/w causing the socket to close */ - bool Lost(); - - /** Set flag indicating the socket is being actively deleted by the sockethandler. */ - void SetErasedByHandler(bool x = true); - /** Get value of flag indicating socket is deleted by sockethandler. */ - bool ErasedByHandler(); - - //@} - - /** \name Information about remote connection */ - //@{ - /** Returns address of remote end. */ - std::auto_ptr<SocketAddress> GetRemoteSocketAddress(); - /** Returns address of remote end: ipv4. */ - ipaddr_t GetRemoteIP4(); -#ifdef ENABLE_IPV6 - /** Returns address of remote end: ipv6. */ -#ifdef IPPROTO_IPV6 - struct in6_addr GetRemoteIP6(); -#endif -#endif - /** Returns remote port number: ipv4 and ipv6. */ - port_t GetRemotePort(); - /** Returns remote ip as string? ipv4 and ipv6. */ - std::string GetRemoteAddress(); - /** ipv4 and ipv6(not implemented) */ - std::string GetRemoteHostname(); - //@} - - /** Returns local port number for bound socket file descriptor. */ - port_t GetSockPort(); - /** Returns local ipv4 address for bound socket file descriptor. */ - ipaddr_t GetSockIP4(); - /** Returns local ipv4 address as text for bound socket file descriptor. */ - std::string GetSockAddress(); -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** Returns local ipv6 address for bound socket file descriptor. */ - struct in6_addr GetSockIP6(); - /** Returns local ipv6 address as text for bound socket file descriptor. */ - std::string GetSockAddress6(); -#endif -#endif - // -------------------------------------------------------------------------- - /** @name IP options - When an ip or socket option is available on all of the operating systems - I'm testing on (linux 2.4.x, _win32, macosx, solaris9 intel) they are not - checked with an #ifdef below. - This might cause a compile error on other operating systems. */ - // -------------------------------------------------------------------------- - - // IP options - //@{ - - bool SetIpOptions(const void *p, socklen_t len); - bool SetIpTOS(unsigned char tos); - unsigned char IpTOS(); - bool SetIpTTL(int ttl); - int IpTTL(); - bool SetIpHdrincl(bool x = true); - bool SetIpMulticastTTL(int); - int IpMulticastTTL(); - bool SetMulticastLoop(bool x = true); - bool IpAddMembership(struct ip_mreq&); - bool IpDropMembership(struct ip_mreq&); - -#ifdef IP_PKTINFO - bool SetIpPktinfo(bool x = true); -#endif -#ifdef IP_RECVTOS - bool SetIpRecvTOS(bool x = true); -#endif -#ifdef IP_RECVTTL - bool SetIpRecvTTL(bool x = true); -#endif -#ifdef IP_RECVOPTS - bool SetIpRecvopts(bool x = true); -#endif -#ifdef IP_RETOPTS - bool SetIpRetopts(bool x = true); -#endif -#ifdef IP_RECVERR - bool SetIpRecverr(bool x = true); -#endif -#ifdef IP_MTU_DISCOVER - bool SetIpMtudiscover(bool x = true); -#endif -#ifdef IP_MTU - int IpMtu(); -#endif -#ifdef IP_ROUTER_ALERT - bool SetIpRouterAlert(bool x = true); -#endif -#ifdef LINUX - bool IpAddMembership(struct ip_mreqn&); -#endif -#ifdef LINUX - bool IpDropMembership(struct ip_mreqn&); -#endif - //@} - - // SOCKET options - /** @name Socket Options */ - //@{ - - bool SoAcceptconn(); - bool SetSoBroadcast(bool x = true); - bool SetSoDebug(bool x = true); - int SoError(); - bool SetSoDontroute(bool x = true); - bool SetSoLinger(int onoff, int linger); - bool SetSoOobinline(bool x = true); - bool SetSoRcvlowat(int); - bool SetSoSndlowat(int); - bool SetSoRcvtimeo(struct timeval&); - bool SetSoSndtimeo(struct timeval&); - bool SetSoRcvbuf(int); - int SoRcvbuf(); - bool SetSoSndbuf(int); - int SoSndbuf(); - int SoType(); - bool SetSoReuseaddr(bool x = true); - bool SetSoKeepalive(bool x = true); - -#ifdef SO_BSDCOMPAT - bool SetSoBsdcompat(bool x = true); -#endif -#ifdef SO_BINDTODEVICE - bool SetSoBindtodevice(const std::string& intf); -#endif -#ifdef SO_PASSCRED - bool SetSoPasscred(bool x = true); -#endif -#ifdef SO_PEERCRED - bool SoPeercred(struct ucred& ); -#endif -#ifdef SO_PRIORITY - bool SetSoPriority(int); -#endif -#ifdef SO_RCVBUFFORCE - bool SetSoRcvbufforce(int); -#endif -#ifdef SO_SNDBUFFORCE - bool SetSoSndbufforce(int); -#endif -#ifdef SO_TIMESTAMP - bool SetSoTimestamp(bool x = true); -#endif -#ifdef SO_NOSIGPIPE - bool SetSoNosigpipe(bool x = true); -#endif - //@} - - // TCP options in TcpSocket.h/TcpSocket.cpp - -#ifdef HAVE_OPENSSL - /** @name SSL Support */ - //@{ - /** SSL client/server support - internal use. \sa TcpSocket */ - virtual void OnSSLConnect(); - /** SSL client/server support - internal use. \sa TcpSocket */ - virtual void OnSSLAccept(); - /** SSL negotiation failed for client connect. */ - virtual void OnSSLConnectFailed(); - /** SSL negotiation failed for server accept. */ - virtual void OnSSLAcceptFailed(); - /** new SSL support */ - virtual bool SSLNegotiate(); - /** Check if SSL is Enabled for this TcpSocket. - \return true if this is a TcpSocket with SSL enabled */ - bool IsSSL(); - /** Enable SSL operation for a TcpSocket. */ - void EnableSSL(bool x = true); - /** Still negotiating ssl connection. - \return true if ssl negotiating is still in progress */ - bool IsSSLNegotiate(); - /** Set flag indicating ssl handshaking still in progress. */ - void SetSSLNegotiate(bool x = true); - /** OnAccept called with SSL Enabled. - \return true if this is a TcpSocket with an incoming SSL connection */ - bool IsSSLServer(); - /** Set flag indicating that this is a TcpSocket with incoming SSL connection. */ - void SetSSLServer(bool x = true); - /** SSL; Get pointer to ssl context structure. */ - virtual SSL_CTX *GetSslContext() { return NULL; } - /** SSL; Get pointer to ssl structure. */ - virtual SSL *GetSsl() { return NULL; } - //@} -#endif // HAVE_OPENSSL - -#ifdef ENABLE_IPV6 - /** Enable ipv6 for this socket. */ - void SetIpv6(bool x = true); - /** Check ipv6 socket. - \return true if this is an ipv6 socket */ - bool IsIpv6(); -#endif - -#ifdef ENABLE_POOL - /** @name Connection Pool */ - //@{ - /** Client = connecting TcpSocket. */ - void SetIsClient(); - /** Socket type from socket() call. */ - void SetSocketType(int x); - /** Socket type from socket() call. */ - int GetSocketType(); - /** Protocol type from socket() call. */ - void SetSocketProtocol(const std::string& x); - /** Protocol type from socket() call. */ - const std::string& GetSocketProtocol(); - /** Instruct a client socket to stay open in the connection pool after use. - If you have connected to a server using tcp, you can call SetRetain - to leave the connection open after your socket instance has been deleted. - The next connection you make to the same server will reuse the already - opened connection, if it is still available. - */ - void SetRetain(); - /** Check retain flag. - \return true if the socket should be moved to connection pool after use */ - bool Retain(); - /** Copy connection parameters from sock. */ - void CopyConnection(Socket *sock); - //@} -#endif // ENABLE_POOL - -#ifdef ENABLE_SOCKS4 - /** \name Socks4 support */ - //@{ - /** Socks4 client support internal use. \sa TcpSocket */ - virtual void OnSocks4Connect(); - /** Socks4 client support internal use. \sa TcpSocket */ - virtual void OnSocks4ConnectFailed(); - /** Socks4 client support internal use. \sa TcpSocket */ - virtual bool OnSocks4Read(); - /** Called when the last write caused the tcp output buffer to - * become empty. */ - /** socket still in socks4 negotiation mode */ - bool Socks4(); - /** Set flag indicating Socks4 handshaking in progress */ - void SetSocks4(bool x = true); - - /** Set socks4 server host address to use */ - void SetSocks4Host(ipaddr_t a); - /** Set socks4 server hostname to use. */ - void SetSocks4Host(const std::string& ); - /** Socks4 server port to use. */ - void SetSocks4Port(port_t p); - /** Provide a socks4 userid if required by the socks4 server. */ - void SetSocks4Userid(const std::string& x); - /** Get the ip address of socks4 server to use. - \return socks4 server host address */ - ipaddr_t GetSocks4Host(); - /** Get the socks4 server port to use. - \return socks4 server port */ - port_t GetSocks4Port(); - /** Get socks4 userid. - \return Socks4 userid */ - const std::string& GetSocks4Userid(); - //@} -#endif // ENABLE_SOCKS4 - -#ifdef ENABLE_RESOLVER - /** \name Asynchronous Resolver */ - //@{ - /** Request an asynchronous dns resolution. - \param host hostname to be resolved - \param port port number passed along for the ride - \return Resolve ID */ - int Resolve(const std::string& host,port_t port = 0); -#ifdef ENABLE_IPV6 - int Resolve6(const std::string& host, port_t port = 0); -#endif - /** Callback returning a resolved address. - \param id Resolve ID from Resolve call - \param a resolved ip address - \param port port number passed to Resolve */ - virtual void OnResolved(int id,ipaddr_t a,port_t port); -#ifdef ENABLE_IPV6 - virtual void OnResolved(int id,in6_addr& a,port_t port); -#endif - /** Request asynchronous reverse dns lookup. - \param a in_addr to be translated */ - int Resolve(ipaddr_t a); -#ifdef ENABLE_IPV6 - int Resolve(in6_addr& a); -#endif - /** Callback returning reverse resolve results. - \param id Resolve ID - \param name Resolved hostname */ - virtual void OnReverseResolved(int id,const std::string& name); - /** Callback indicating failed dns lookup. - \param id Resolve ID */ - virtual void OnResolveFailed(int id); - //@} -#endif // ENABLE_RESOLVER - -#ifdef ENABLE_DETACH - /** \name Thread Support */ - //@{ - /** Callback fires when a new socket thread has started and this - socket is ready for operation again. - \sa ResolvSocket */ - virtual void OnDetached(); - - // LIST_DETACH - - /** Internal use. */ - void SetDetach(bool x = true); - /** Check detach flag. - \return true if the socket should detach to its own thread */ - bool IsDetach(); - - /** Internal use. */ - void SetDetached(bool x = true); - /** Check detached flag. - \return true if the socket runs in its own thread. */ - const bool IsDetached() const; - /** Order this socket to start its own thread and call OnDetached - when ready for operation. */ - bool Detach(); - /** Store the slave sockethandler pointer. */ - void SetSlaveHandler(ISocketHandler *); - /** Create new thread for this socket to run detached in. */ - void DetachSocket(); - //@} -#endif // ENABLE_DETACH - - /** Write traffic to an IFile. Socket will not delete this object. */ - void SetTrafficMonitor(IFile *p) { m_traffic_monitor = p; } - -#ifdef ENABLE_TRIGGERS - /** \name Triggers */ - //@{ - /** Subscribe to trigger id. */ - void Subscribe(int id); - /** Unsubscribe from trigger id. */ - void Unsubscribe(int id); - /** Trigger callback, with data passed from source to destination. */ - virtual void OnTrigger(int id, const TriggerData& data); - /** Trigger cancelled because source has been deleted (as in delete). */ - virtual void OnCancelled(int id); - //@} -#endif - -protected: - /** default constructor not available */ - Socket() : m_handler(m_handler) {} - /** copy constructor not available */ - Socket(const Socket& s) : m_handler(s.m_handler) {} - - /** assignment operator not available. */ - Socket& operator=(const Socket& ) { return *this; } - - /** All traffic will be written to this IFile, if set. */ - IFile *GetTrafficMonitor() { return m_traffic_monitor; } - -// unsigned long m_flags; ///< boolean flags, replacing old 'bool' members - -private: - ISocketHandler& m_handler; ///< Reference of ISocketHandler in control of this socket - SOCKET m_socket; ///< File descriptor - bool m_bDel; ///< Delete by handler flag - bool m_bClose; ///< Close and delete flag - time_t m_tCreate; ///< Time in seconds when this socket was created - Socket *m_parent; ///< Pointer to ListenSocket class, valid for incoming sockets - bool m_b_disable_read; ///< Disable checking for read events - bool m_connected; ///< Socket is connected (tcp/udp) - bool m_b_erased_by_handler; ///< Set by handler before delete - time_t m_tClose; ///< Time in seconds when ordered to close - std::auto_ptr<SocketAddress> m_client_remote_address; ///< Address of last connect() - std::auto_ptr<SocketAddress> m_remote_address; ///< Remote end address - IFile *m_traffic_monitor; - time_t m_timeout_start; ///< Set by SetTimeout - time_t m_timeout_limit; ///< Defined by SetTimeout - bool m_bLost; ///< connection lost - -#ifdef _WIN32 -static WSAInitializer m_winsock_init; ///< Winsock initialization singleton class -#endif - -#ifdef HAVE_OPENSSL - bool m_b_enable_ssl; ///< Enable SSL for this TcpSocket - bool m_b_ssl; ///< ssl negotiation mode (TcpSocket) - bool m_b_ssl_server; ///< True if this is an incoming ssl TcpSocket connection -#endif - -#ifdef ENABLE_IPV6 - bool m_ipv6; ///< This is an ipv6 socket if this one is true -#endif - -#ifdef ENABLE_POOL - int m_socket_type; ///< Type of socket, from socket() call - std::string m_socket_protocol; ///< Protocol, from socket() call - bool m_bClient; ///< only client connections are pooled - bool m_bRetain; ///< keep connection on close -#endif - -#ifdef ENABLE_SOCKS4 - bool m_bSocks4; ///< socks4 negotiation mode (TcpSocket) - ipaddr_t m_socks4_host; ///< socks4 server address - port_t m_socks4_port; ///< socks4 server port number - std::string m_socks4_userid; ///< socks4 server usedid -#endif - -#ifdef ENABLE_DETACH - bool m_detach; ///< Socket ordered to detach flag - bool m_detached; ///< Socket has been detached - SocketThread *m_pThread; ///< Detach socket thread class pointer - ISocketHandler *m_slave_handler; ///< Actual sockethandler while detached -#endif -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_Socket_H - - diff --git a/dep/sockets/include/SocketAddress.h b/dep/sockets/include/SocketAddress.h deleted file mode 100644 index abdbbfd2cf6..00000000000 --- a/dep/sockets/include/SocketAddress.h +++ /dev/null @@ -1,93 +0,0 @@ -/** - ** \file SocketAddress.h - ** \date 2006-09-21 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2007 Anders Hedstrom - -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, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_SocketAddress_H -#define _SOCKETS_SocketAddress_H - -#include "sockets-config.h" -#include <string> -#include <memory> -#include "socket_include.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** - This class and its subclasses is intended to be used as replacement - for the internal data type 'ipaddr_t' and various implementations of - IPv6 addressing found throughout the library. - 'ipaddr_t' is an IPv4 address in network byte order. - 'port_t' is the portnumber in host byte order. - 'struct in6_addr' is an IPv6 address. - 'struct in_addr' is an IPv4 address. - \ingroup basic -*/ -class SocketAddress -{ -public: - virtual ~SocketAddress() {} - - /** Get a pointer to the address struct. */ - virtual operator struct sockaddr *() = 0; - - /** Get length of address struct. */ - virtual operator socklen_t() = 0; - - /** Compare two addresses. */ - virtual bool operator==(SocketAddress&) = 0; - - /** Set port number. - \param port Port number in host byte order */ - virtual void SetPort(port_t port) = 0; - - /** Get port number. - \return Port number in host byte order. */ - virtual port_t GetPort() = 0; - - /** Set socket address. - \param sa Pointer to either 'struct sockaddr_in' or 'struct sockaddr_in6'. */ - virtual void SetAddress(struct sockaddr *sa) = 0; - - /** Convert address to text. */ - virtual std::string Convert(bool include_port) = 0; - - /** Reverse lookup of address. */ - virtual std::string Reverse() = 0; - - /** Get address family. */ - virtual int GetFamily() = 0; - - /** Address structure is valid. */ - virtual bool IsValid() = 0; - - /** Get a copy of this SocketAddress object. */ - virtual std::auto_ptr<SocketAddress> GetCopy() = 0; -}; - - -#ifdef SOCKETS_NAMESPACE -} // namespace SOCKETS_NAMESPACE { -#endif -#endif // _SOCKETS_SocketAddress_H - - diff --git a/dep/sockets/include/SocketHandler.h b/dep/sockets/include/SocketHandler.h deleted file mode 100644 index 5598ec4249b..00000000000 --- a/dep/sockets/include/SocketHandler.h +++ /dev/null @@ -1,265 +0,0 @@ -/** \file SocketHandler.h - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_SocketHandler_H -#define _SOCKETS_SocketHandler_H - -#include "sockets-config.h" -#include <map> -#include <list> - -#include "socket_include.h" -#include "ISocketHandler.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -class Socket; -#ifdef ENABLE_RESOLVER -class ResolvServer; -#endif -class Mutex; - -/** Socket container class, event generator. - \ingroup basic */ -class SocketHandler : public ISocketHandler -{ -protected: - /** Map type for holding file descriptors/socket object pointers. */ - typedef std::map<SOCKET,Socket *> socket_m; - -public: - /** SocketHandler constructor. - \param log Optional log class pointer */ - SocketHandler(StdLog *log = NULL); - - /** SocketHandler threadsafe constructor. - \param mutex Externally declared mutex variable - \param log Optional log class pointer */ - SocketHandler(Mutex& mutex,StdLog *log = NULL); - - ~SocketHandler(); - - /** Get mutex reference for threadsafe operations. */ - Mutex& GetMutex() const; - - /** Register StdLog object for error callback. - \param log Pointer to log class */ - void RegStdLog(StdLog *log); - - /** Log error to log class for print out / storage. */ - void LogError(Socket *p,const std::string& user_text,int err,const std::string& sys_err,loglevel_t t = LOG_LEVEL_WARNING); - - /** Add socket instance to socket map. Removal is always automatic. */ - void Add(Socket *); - - /** Get status of read/write/exception file descriptor set for a socket. */ - void Get(SOCKET s,bool& r,bool& w,bool& e); - - /** Set read/write/exception file descriptor sets (fd_set). */ - void Set(SOCKET s,bool bRead,bool bWrite,bool bException = true); - - /** Wait for events, generate callbacks. */ - int Select(long sec,long usec); - - /** This method will not return until an event has been detected. */ - int Select(); - - /** Wait for events, generate callbacks. */ - int Select(struct timeval *tsel); - - /** Check that a socket really is handled by this socket handler. */ - bool Valid(Socket *); - - /** Return number of sockets handled by this handler. */ - size_t GetCount(); - - /** Override and return false to deny all incoming connections. - \param p ListenSocket class pointer (use GetPort to identify which one) */ - bool OkToAccept(Socket *p); - - /** Called by Socket when a socket changes state. */ - void AddList(SOCKET s,list_t which_one,bool add); - - // Connection pool -#ifdef ENABLE_POOL - /** Find available open connection (used by connection pool). */ - ISocketHandler::PoolSocket *FindConnection(int type,const std::string& protocol,SocketAddress&); - /** Enable connection pool (by default disabled). */ - void EnablePool(bool x = true); - /** Check pool status. - \return true if connection pool is enabled */ - bool PoolEnabled(); -#endif // ENABLE_POOL - - // Socks4 -#ifdef ENABLE_SOCKS4 - /** Set socks4 server ip that all new tcp sockets should use. */ - void SetSocks4Host(ipaddr_t); - /** Set socks4 server hostname that all new tcp sockets should use. */ - void SetSocks4Host(const std::string& ); - /** Set socks4 server port number that all new tcp sockets should use. */ - void SetSocks4Port(port_t); - /** Set optional socks4 userid. */ - void SetSocks4Userid(const std::string& ); - /** If connection to socks4 server fails, immediately try direct connection to final host. */ - void SetSocks4TryDirect(bool x = true); - /** Get socks4 server ip. - \return socks4 server ip */ - ipaddr_t GetSocks4Host(); - /** Get socks4 port number. - \return socks4 port number */ - port_t GetSocks4Port(); - /** Get socks4 userid (optional). - \return socks4 userid */ - const std::string& GetSocks4Userid(); - /** Check status of socks4 try direct flag. - \return true if direct connection should be tried if connection to socks4 server fails */ - bool Socks4TryDirect(); -#endif // ENABLE_SOCKS4 - - // DNS resolve server -#ifdef ENABLE_RESOLVER - /** Enable asynchronous DNS. - \param port Listen port of asynchronous dns server */ - void EnableResolver(port_t port = 16667); - /** Check resolver status. - \return true if resolver is enabled */ - bool ResolverEnabled(); - /** Queue a dns request. - \param host Hostname to be resolved - \param port Port number will be echoed in Socket::OnResolved callback */ - int Resolve(Socket *,const std::string& host,port_t port); -#ifdef ENABLE_IPV6 - int Resolve6(Socket *,const std::string& host,port_t port); -#endif - /** Do a reverse dns lookup. */ - int Resolve(Socket *,ipaddr_t a); -#ifdef ENABLE_IPV6 - int Resolve(Socket *,in6_addr& a); -#endif - /** Get listen port of asynchronous dns server. */ - port_t GetResolverPort(); - /** Resolver thread ready for queries. */ - bool ResolverReady(); - /** Returns true if the socket is waiting for a resolve event. */ - bool Resolving(Socket *); -#endif // ENABLE_RESOLVER - -#ifdef ENABLE_TRIGGERS - /** Fetch unique trigger id. */ - int TriggerID(Socket *src); - /** Subscribe socket to trigger id. */ - bool Subscribe(int id, Socket *dst); - /** Unsubscribe socket from trigger id. */ - bool Unsubscribe(int id, Socket *dst); - /** Execute OnTrigger for subscribed sockets. - \param id Trigger ID - \param data Data passed from source to destination - \param erase Empty trigger id source and destination maps if 'true', - Leave them in place if 'false' - if a trigger should be called many times */ - void Trigger(int id, Socket::TriggerData& data, bool erase = true); -#endif // ENABLE_TRIGGERS - -#ifdef ENABLE_DETACH - /** Indicates that the handler runs under SocketThread. */ - void SetSlave(bool x = true); - /** Indicates that the handler runs under SocketThread. */ - bool IsSlave(); -#endif - - /** Sanity check of those accursed lists. */ - void CheckSanity(); - -protected: - socket_m m_sockets; ///< Active sockets map - socket_m m_add; ///< Sockets to be added to sockets map - std::list<Socket *> m_delete; ///< Sockets to be deleted (failed when Add) - -protected: - StdLog *m_stdlog; ///< Registered log class, or NULL - Mutex& m_mutex; ///< Thread safety mutex - bool m_b_use_mutex; ///< Mutex correctly initialized - -private: - void CheckList(socket_v&,const std::string&); ///< Used by CheckSanity - /** Remove socket from socket map, used by Socket class. */ - void Remove(Socket *); - SOCKET m_maxsock; ///< Highest file descriptor + 1 in active sockets list - fd_set m_rfds; ///< file descriptor set monitored for read events - fd_set m_wfds; ///< file descriptor set monitored for write events - fd_set m_efds; ///< file descriptor set monitored for exceptions - int m_preverror; ///< debug select() error - int m_errcnt; ///< debug select() error - time_t m_tlast; ///< timeout control - - // state lists - socket_v m_fds; ///< Active file descriptor list - socket_v m_fds_erase; ///< File descriptors that are to be erased from m_sockets - socket_v m_fds_callonconnect; ///< checklist CallOnConnect -#ifdef ENABLE_DETACH - socket_v m_fds_detach; ///< checklist Detach -#endif - socket_v m_fds_timeout; ///< checklist timeout - socket_v m_fds_retry; ///< checklist retry client connect - socket_v m_fds_close; ///< checklist close and delete - -#ifdef ENABLE_SOCKS4 - ipaddr_t m_socks4_host; ///< Socks4 server host ip - port_t m_socks4_port; ///< Socks4 server port number - std::string m_socks4_userid; ///< Socks4 userid - bool m_bTryDirect; ///< Try direct connection if socks4 server fails -#endif -#ifdef ENABLE_RESOLVER - int m_resolv_id; ///< Resolver id counter - ResolvServer *m_resolver; ///< Resolver thread pointer - port_t m_resolver_port; ///< Resolver listen port - std::map<Socket *, bool> m_resolve_q; ///< resolve queue -#endif -#ifdef ENABLE_POOL - bool m_b_enable_pool; ///< Connection pool enabled if true -#endif -#ifdef ENABLE_TRIGGERS - int m_next_trigger_id; ///< Unique trigger id counter - std::map<int, Socket *> m_trigger_src; ///< mapping trigger id to source socket - std::map<int, std::map<Socket *, bool> > m_trigger_dst; ///< mapping trigger id to destination sockets -#endif -#ifdef ENABLE_DETACH - bool m_slave; ///< Indicates that this is a ISocketHandler run in SocketThread -#endif -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_SocketHandler_H - - diff --git a/dep/sockets/include/StdLog.h b/dep/sockets/include/StdLog.h deleted file mode 100644 index 3ff68d6e9ea..00000000000 --- a/dep/sockets/include/StdLog.h +++ /dev/null @@ -1,73 +0,0 @@ -/** \file StdLog.h - ** \date 2004-06-01 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_StdLog_H -#define _SOCKETS_StdLog_H - -#include "sockets-config.h" -#include <string> - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** error level enum. */ -typedef enum -{ - LOG_LEVEL_WARNING = 0, - LOG_LEVEL_ERROR, - LOG_LEVEL_FATAL, - LOG_LEVEL_INFO -} loglevel_t; - -class ISocketHandler; -class Socket; - -/** \defgroup logging Log help classes */ -/** Log class interface. - \ingroup logging */ -class StdLog -{ -public: - virtual ~StdLog() {} - - virtual void error(ISocketHandler *,Socket *, - const std::string& user_text, - int err, - const std::string& sys_err, - loglevel_t = LOG_LEVEL_WARNING) = 0; -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_StdLog_H - - diff --git a/dep/sockets/include/StdoutLog.h b/dep/sockets/include/StdoutLog.h deleted file mode 100644 index aeb25b3e6e6..00000000000 --- a/dep/sockets/include/StdoutLog.h +++ /dev/null @@ -1,55 +0,0 @@ -/** \file StdoutLog.h - ** \date 2004-06-01 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_StdoutLog_H -#define _SOCKETS_StdoutLog_H - -#include "sockets-config.h" -#include "StdLog.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** StdLog implementation, logs to stdout. - \ingroup logging */ -class StdoutLog : public StdLog -{ -public: - void error(ISocketHandler *,Socket *,const std::string& call,int err,const std::string& sys_err,loglevel_t); -}; - - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_StdoutLog_H - - diff --git a/dep/sockets/include/StreamSocket.h b/dep/sockets/include/StreamSocket.h deleted file mode 100644 index bcce10ffbc5..00000000000 --- a/dep/sockets/include/StreamSocket.h +++ /dev/null @@ -1,124 +0,0 @@ -#ifndef _StreamSocket_H -#define _StreamSocket_H - -#include "Socket.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** SOCK_STREAM Socket base class. - \ingroup basic */ -class StreamSocket : public Socket -{ -public: - StreamSocket(ISocketHandler& ); - ~StreamSocket(); - - /** Socket should Check Connect on next write event from select(). */ - void SetConnecting(bool = true); - - /** Check connecting flag. - \return true if the socket is still trying to connect */ - bool Connecting(); - - /** Returns true when socket file descriptor is valid, - socket connection is established, and socket is not about to - be closed. */ - bool Ready(); - - /** Set timeout to use for connection attempt. - \param x Timeout in seconds */ - void SetConnectTimeout(int x); - - /** Return number of seconds to wait for a connection. - \return Connection timeout (seconds) */ - int GetConnectTimeout(); - - /** Set flush before close to make a tcp socket completely empty its - output buffer before closing the connection. */ - void SetFlushBeforeClose(bool = true); - - /** Check flush before status. - \return true if the socket should send all data before closing */ - bool GetFlushBeforeClose(); - - /** Define number of connection retries (tcp only). - n = 0 - no retry - n > 0 - number of retries - n = -1 - unlimited retries */ - void SetConnectionRetry(int n); - - /** Get number of maximum connection retries (tcp only). */ - int GetConnectionRetry(); - - /** Increase number of actual connection retries (tcp only). */ - void IncreaseConnectionRetries(); - - /** Get number of actual connection retries (tcp only). */ - int GetConnectionRetries(); - - /** Reset actual connection retries (tcp only). */ - void ResetConnectionRetries(); - - // LIST_CALLONCONNECT - - /** Instruct socket to call OnConnect callback next sockethandler cycle. */ - void SetCallOnConnect(bool x = true); - - /** Check call on connect flag. - \return true if OnConnect() should be called a.s.a.p */ - bool CallOnConnect(); - - // LIST_RETRY - - /** Set flag to initiate a connection attempt after a connection timeout. */ - void SetRetryClientConnect(bool x = true); - - /** Check if a connection attempt should be made. - \return true when another attempt should be made */ - bool RetryClientConnect(); - - /** Called after OnRead if socket is in line protocol mode. - \sa SetLineProtocol */ - /** Enable the OnLine callback. Do not create your own OnRead - * callback when using this. */ - virtual void SetLineProtocol(bool = true); - - /** Check line protocol mode. - \return true if socket is in line protocol mode */ - bool LineProtocol(); - - /** Set shutdown status. */ - void SetShutdown(int); - - /** Get shutdown status. */ - int GetShutdown(); - - /** Returns IPPROTO_TCP or IPPROTO_SCTP */ - virtual int Protocol() = 0; - -protected: - StreamSocket(const StreamSocket& ) {} // copy constructor - -private: - StreamSocket& operator=(const StreamSocket& ) { return *this; } // assignment operator - - bool m_bConnecting; ///< Flag indicating connection in progress - int m_connect_timeout; ///< Connection timeout (seconds) - bool m_flush_before_close; ///< Send all data before closing (default true) - int m_connection_retry; ///< Maximum connection retries (tcp) - int m_retries; ///< Actual number of connection retries (tcp) - bool m_call_on_connect; ///< OnConnect will be called next ISocketHandler cycle if true - bool m_b_retry_connect; ///< Try another connection attempt next ISocketHandler cycle - bool m_line_protocol; ///< Line protocol mode flag - int m_shutdown; ///< Shutdown status -}; - -#ifdef SOCKETS_NAMESPACE -} // namespace SOCKETS_NAMESPACE { -#endif - -#endif // _StreamSocket_H - - diff --git a/dep/sockets/include/TcpSocket.h b/dep/sockets/include/TcpSocket.h deleted file mode 100644 index de1be8bd8b9..00000000000 --- a/dep/sockets/include/TcpSocket.h +++ /dev/null @@ -1,356 +0,0 @@ -/** \file TcpSocket.h - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_TcpSocket_H -#define _SOCKETS_TcpSocket_H -#include "sockets-config.h" -#include "StreamSocket.h" -#ifdef HAVE_OPENSSL -#include <openssl/ssl.h> -#include "SSLInitializer.h" -#endif - -#include <string.h> - -#define TCP_BUFSIZE_READ 16400 -#define TCP_OUTPUT_CAPACITY 1024000 - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -class SocketAddress; - -/** Socket implementation for TCP. - \ingroup basic */ -class TcpSocket : public StreamSocket -{ - /** \defgroup internal Internal utility */ -protected: - /** Buffer class containing one read/write circular buffer. - \ingroup internal */ - class CircularBuffer - { - public: - CircularBuffer(size_t size); - ~CircularBuffer(); - - /** append l bytes from p to buffer */ - bool Write(const char *p,size_t l); - /** copy l bytes from buffer to dest */ - bool Read(char *dest,size_t l); - /** copy l bytes from buffer to dest, dont touch buffer pointers */ - bool SoftRead(char *dest, size_t l); - /** skip l bytes from buffer */ - bool Remove(size_t l); - /** read l bytes from buffer, returns as string. */ - std::string ReadString(size_t l); - - /** total buffer length */ - size_t GetLength(); - /** pointer to circular buffer beginning */ - const char *GetStart(); - /** return number of bytes from circular buffer beginning to buffer physical end */ - size_t GetL(); - /** return free space in buffer, number of bytes until buffer overrun */ - size_t Space(); - - /** return total number of bytes written to this buffer, ever */ - unsigned long ByteCounter(bool clear = false); - - private: - CircularBuffer(const CircularBuffer& /*s*/) {} - CircularBuffer& operator=(const CircularBuffer& ) { return *this; } - char *buf; - size_t m_max; - size_t m_q; - size_t m_b; - size_t m_t; - unsigned long m_count; - }; - /** Output buffer struct. - \ingroup internal */ - struct OUTPUT { - OUTPUT() : _b(0), _t(0), _q(0) {} - OUTPUT(const char *buf, size_t len) : _b(0), _t(len), _q(len) { - memcpy(_buf, buf, len); - } - size_t Space() { - return TCP_OUTPUT_CAPACITY - _t; - } - void Add(const char *buf, size_t len) { - memcpy(_buf + _t, buf, len); - _t += len; - _q += len; - } - size_t Remove(size_t len) { - _b += len; - _q -= len; - return _q; - } - const char *Buf() { - return _buf + _b; - } - size_t Len() { - return _q; - } - size_t _b; - size_t _t; - size_t _q; - char _buf[TCP_OUTPUT_CAPACITY]; - }; - typedef std::list<OUTPUT *> output_l; - -public: - /** Constructor with standard values on input/output buffers. */ - TcpSocket(ISocketHandler& ); - /** Constructor with custom values for i/o buffer. - \param h ISocketHandler reference - \param isize Input buffer size - \param osize Output buffer size */ - TcpSocket(ISocketHandler& h,size_t isize,size_t osize); - ~TcpSocket(); - - /** Open a connection to a remote server. - If you want your socket to connect to a server, - always call Open before Add'ing a socket to the sockethandler. - If not, the connection attempt will not be monitored by the - socket handler... - \param ip IP address - \param port Port number - \param skip_socks Do not use socks4 even if configured */ - bool Open(ipaddr_t ip,port_t port,bool skip_socks = false); -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** Open connection. - \param ip Ipv6 address - \param port Port number - \param skip_socks Do not use socks4 even if configured */ - bool Open(in6_addr ip,port_t port,bool skip_socks = false); -#endif -#endif - bool Open(SocketAddress&,bool skip_socks = false); - bool Open(SocketAddress&,SocketAddress& bind_address,bool skip_socks = false); - /** Open connection. - \param host Hostname - \param port Port number */ - bool Open(const std::string &host,port_t port); - - /** Connect timeout callback. */ - void OnConnectTimeout(); -#ifdef _WIN32 - /** Connection failed reported as exception on win32 */ - void OnException(); -#endif - - /** Close file descriptor - internal use only. - \sa SetCloseAndDelete */ - int Close(); - - /** Send a string. - \param s String to send - \param f Dummy flags -- not used */ - void Send(const std::string &s,int f = 0); - /** Send string using printf formatting. */ - void Sendf(const char *format, ...); - /** Send buffer of bytes. - \param buf Buffer pointer - \param len Length of data - \param f Dummy flags -- not used */ - void SendBuf(const char *buf,size_t len,int f = 0); - /** This callback is executed after a successful read from the socket. - \param buf Pointer to the data - \param len Length of the data */ - virtual void OnRawData(const char *buf,size_t len); - - /** Called when output buffer has been sent. - Note: Will only be called IF the output buffer has been used. - Send's that was successful without needing the output buffer - will not generate a call to this method. */ - virtual void OnWriteComplete(); - /** Number of bytes in input buffer. */ - size_t GetInputLength(); - /** Number of bytes in output buffer. */ - size_t GetOutputLength(); - - /** Callback fires when a socket in line protocol has read one full line. - \param line Line read */ - void OnLine(const std::string& line); - /** Get counter of number of bytes received. */ - uint64_t GetBytesReceived(bool clear = false); - /** Get counter of number of bytes sent. */ - uint64_t GetBytesSent(bool clear = false); - - /** Socks4 specific callback. */ - void OnSocks4Connect(); - /** Socks4 specific callback. */ - void OnSocks4ConnectFailed(); - /** Socks4 specific callback. - \return 'need_more' */ - bool OnSocks4Read(); - -#ifdef ENABLE_RESOLVER - /** Callback executed when resolver thread has finished a resolve request. */ - void OnResolved(int id,ipaddr_t a,port_t port); -#ifdef ENABLE_IPV6 - void OnResolved(int id,in6_addr& a,port_t port); -#endif -#endif -#ifdef HAVE_OPENSSL - /** Callback for 'New' ssl support - replaces SSLSocket. Internal use. */ - void OnSSLConnect(); - /** Callback for 'New' ssl support - replaces SSLSocket. Internal use. */ - void OnSSLAccept(); - /** This method must be implemented to initialize - the ssl context for an outgoing connection. */ - virtual void InitSSLClient(); - /** This method must be implemented to initialize - the ssl context for an incoming connection. */ - virtual void InitSSLServer(); -#endif - -#ifdef ENABLE_RECONNECT - /** Flag that says a broken connection will try to reconnect. */ - void SetReconnect(bool = true); - /** Check reconnect on lost connection flag status. */ - bool Reconnect(); - /** Flag to determine if a reconnect is in progress. */ - void SetIsReconnect(bool x = true); - /** Socket is reconnecting. */ - bool IsReconnect(); -#endif - - void DisableInputBuffer(bool = true); - - void OnOptions(int,int,int,SOCKET); - - void SetLineProtocol(bool = true); - - // TCP options - bool SetTcpNodelay(bool = true); - - virtual int Protocol(); - - /** Trigger limit for callback OnTransferLimit. */ - void SetTransferLimit(size_t sz); - /** This callback fires when the output buffer drops below the value - set by SetTransferLimit. Default: 0 (disabled). */ - virtual void OnTransferLimit(); - -protected: - TcpSocket(const TcpSocket& ); - void OnRead(); - void OnRead( char *buf, size_t n ); - void OnWrite(); -#ifdef HAVE_OPENSSL - /** SSL; Initialize ssl context for a client socket. - \param meth_in SSL method */ - void InitializeContext(const std::string& context, SSL_METHOD *meth_in = NULL); - /** SSL; Initialize ssl context for a server socket. - \param keyfile Combined private key/certificate file - \param password Password for private key - \param meth_in SSL method */ - void InitializeContext(const std::string& context, const std::string& keyfile, const std::string& password, SSL_METHOD *meth_in = NULL); - /** SSL; Initialize ssl context for a server socket. - \param certfile Separate certificate file - \param keyfile Combined private key/certificate file - \param password Password for private key - \param meth_in SSL method */ - void InitializeContext(const std::string& context, const std::string& certfile, const std::string& keyfile, const std::string& password, SSL_METHOD *meth_in = NULL); - /** SSL; Password callback method. */ -static int SSL_password_cb(char *buf,int num,int rwflag,void *userdata); - /** SSL; Get pointer to ssl context structure. */ - virtual SSL_CTX *GetSslContext(); - /** SSL; Get pointer to ssl structure. */ - virtual SSL *GetSsl(); - /** ssl; still negotiating connection. */ - bool SSLNegotiate(); - /** SSL; Get ssl password. */ - const std::string& GetPassword(); -#endif - - CircularBuffer ibuf; ///< Circular input buffer - -private: - TcpSocket& operator=(const TcpSocket& ) { return *this; } - - /** the actual send() */ - int TryWrite(const char *buf, size_t len); - /** add data to output buffer top */ - void Buffer(const char *buf, size_t len); - - // - bool m_b_input_buffer_disabled; - uint64_t m_bytes_sent; - uint64_t m_bytes_received; - bool m_skip_c; ///< Skip second char of CRLF or LFCR sequence in OnRead - char m_c; ///< First char in CRLF or LFCR sequence - std::string m_line; ///< Current line in line protocol mode -#ifdef SOCKETS_DYNAMIC_TEMP - char *m_buf; ///< temporary read buffer -#endif - output_l m_obuf; ///< output buffer - OUTPUT *m_obuf_top; ///< output buffer on top - size_t m_transfer_limit; - size_t m_output_length; - -#ifdef HAVE_OPENSSL -static SSLInitializer m_ssl_init; - SSL_CTX *m_ssl_ctx; ///< ssl context - SSL *m_ssl; ///< ssl 'socket' - BIO *m_sbio; ///< ssl bio - std::string m_password; ///< ssl password -#endif - -#ifdef ENABLE_SOCKS4 - int m_socks4_state; ///< socks4 support - char m_socks4_vn; ///< socks4 support, temporary variable - char m_socks4_cd; ///< socks4 support, temporary variable - unsigned short m_socks4_dstport; ///< socks4 support - unsigned long m_socks4_dstip; ///< socks4 support -#endif - -#ifdef ENABLE_RESOLVER - int m_resolver_id; ///< Resolver id (if any) for current Open call -#endif - -#ifdef ENABLE_RECONNECT - bool m_b_reconnect; ///< Reconnect on lost connection flag - bool m_b_is_reconnect; ///< Trying to reconnect -#endif - -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_TcpSocket_H - - diff --git a/dep/sockets/include/Thread.h b/dep/sockets/include/Thread.h deleted file mode 100644 index efb766e9ee6..00000000000 --- a/dep/sockets/include/Thread.h +++ /dev/null @@ -1,100 +0,0 @@ -/** \file Thread.h - ** \date 2004-10-30 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_Thread_H -#define _SOCKETS_Thread_H - -#include "sockets-config.h" -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -#ifdef _WIN32 -// to be -//typedef DWORD threadfunc_t; -//typedef LPVOID threadparam_t; -//#define STDPREFIX WINAPI -typedef unsigned threadfunc_t; -typedef void * threadparam_t; -#define STDPREFIX __stdcall -#else -#include <pthread.h> - -typedef void * threadfunc_t; -typedef void * threadparam_t; -#define STDPREFIX -#endif - -/** \defgroup threading Threading */ -/** Thread base class. -The Thread class is used by the resolver (ResolvServer) and running a detached socket (SocketThread). -When you know some processing will take a long time and will freeze up a socket, there is always the -possibility to call Detach() on that socket before starting the processing. -When the OnDetached() callback is later called the processing can continue, now in its own thread. - \ingroup threading */ -class Thread -{ -public: - Thread(bool release = true); - virtual ~Thread(); - - static threadfunc_t STDPREFIX StartThread(threadparam_t); - - virtual void Run() = 0; - - bool IsRunning(); - void SetRunning(bool x); - bool IsReleased(); - void SetRelease(bool x); - bool DeleteOnExit(); - void SetDeleteOnExit(bool x = true); - bool IsDestructor(); - -private: - Thread(const Thread& ) {} - Thread& operator=(const Thread& ) { return *this; } -#ifdef _WIN32 - HANDLE m_thread; - unsigned m_dwThreadId; -#else - pthread_t m_thread; -#endif - bool m_running; - bool m_release; - bool m_b_delete_on_exit; - bool m_b_destructor; -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_Thread_H - - diff --git a/dep/sockets/include/UdpSocket.h b/dep/sockets/include/UdpSocket.h deleted file mode 100644 index 3b06c6955bd..00000000000 --- a/dep/sockets/include/UdpSocket.h +++ /dev/null @@ -1,215 +0,0 @@ -/** \file UdpSocket.h - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_UdpSocket_H -#define _SOCKETS_UdpSocket_H - -#include "sockets-config.h" -#include "Socket.h" - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -/** Socket implementation for UDP. - \ingroup basic */ -class UdpSocket : public Socket -{ -public: - /** Constructor. - \param h ISocketHandler reference - \param ibufsz Maximum size of receive message (extra bytes will be truncated) - \param ipv6 'true' if this is an ipv6 socket */ - UdpSocket(ISocketHandler& h,int ibufsz = 16384,bool ipv6 = false, int retries = 0); - ~UdpSocket(); - - /** Called when incoming data has been received. - \param buf Pointer to data - \param len Length of data - \param sa Pointer to sockaddr struct of sender - \param sa_len Length of sockaddr struct */ - virtual void OnRawData(const char *buf,size_t len,struct sockaddr *sa,socklen_t sa_len); - - /** Called when incoming data has been received and read timestamp is enabled. - \param buf Pointer to data - \param len Length of data - \param sa Pointer to sockaddr struct of sender - \param sa_len Length of sockaddr struct - \param ts Timestamp from message */ - virtual void OnRawData(const char *buf,size_t len,struct sockaddr *sa,socklen_t sa_len,struct timeval *ts); - - /** To receive incoming data, call Bind to setup an incoming port. - \param port Incoming port number - \param range Port range to try if ports already in use - \return 0 if bind succeeded */ - int Bind(port_t& port,int range = 1); - /** To receive data on a specific interface:port, use this. - \param intf Interface ip/hostname - \param port Port number - \param range Port range - \return 0 if bind succeeded */ - int Bind(const std::string& intf,port_t& port,int range = 1); - /** To receive data on a specific interface:port, use this. - \param a Ip address - \param port Port number - \param range Port range - \return 0 if bind succeeded */ - int Bind(ipaddr_t a,port_t& port,int range = 1); -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** To receive data on a specific interface:port, use this. - \param a Ipv6 address - \param port Port number - \param range Port range - \return 0 if bind succeeded */ - int Bind(in6_addr a,port_t& port,int range = 1); -#endif -#endif - /** To receive data on a specific interface:port, use this. - \param ad Socket address - \param range Port range - \return 0 if bind succeeded */ - int Bind(SocketAddress& ad,int range = 1); - - /** Define remote host. - \param l Address of remote host - \param port Port of remote host - \return true if successful */ - bool Open(ipaddr_t l,port_t port); - /** Define remote host. - \param host Hostname - \param port Port number - \return true if successful */ - bool Open(const std::string& host,port_t port); -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** Define remote host. - \param a Address of remote host, ipv6 - \param port Port of remote host - \return true if successful */ - bool Open(struct in6_addr& a,port_t port); -#endif -#endif - /** Define remote host. - \param ad Socket address - \return true if successful */ - bool Open(SocketAddress& ad); - - /** Send to specified host */ - void SendToBuf(const std::string& ,port_t,const char *data,int len,int flags = 0); - /** Send to specified address */ - void SendToBuf(ipaddr_t,port_t,const char *data,int len,int flags = 0); -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** Send to specified ipv6 address */ - void SendToBuf(in6_addr,port_t,const char *data,int len,int flags = 0); -#endif -#endif - /** Send to specified socket address */ - void SendToBuf(SocketAddress& ad,const char *data,int len,int flags = 0); - - /** Send string to specified host */ - void SendTo(const std::string&,port_t,const std::string&,int flags = 0); - /** Send string to specified address */ - void SendTo(ipaddr_t,port_t,const std::string&,int flags = 0); -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** Send string to specified ipv6 address */ - void SendTo(in6_addr,port_t,const std::string&,int flags = 0); -#endif -#endif - /** Send string to specified socket address */ - void SendTo(SocketAddress& ad,const std::string&,int flags = 0); - - /** Send to connected address */ - void SendBuf(const char *data,size_t,int flags = 0); - /** Send string to connected address. */ - void Send(const std::string& ,int flags = 0); - - /** Set broadcast */ - void SetBroadcast(bool b = true); - /** Check broadcast flag. - \return true broadcast is enabled. */ - bool IsBroadcast(); - - /** multicast */ - void SetMulticastTTL(int ttl = 1); - int GetMulticastTTL(); - void SetMulticastLoop(bool = true); - bool IsMulticastLoop(); - void AddMulticastMembership(const std::string& group,const std::string& intf = "0.0.0.0",int if_index = 0); - void DropMulticastMembership(const std::string& group,const std::string& intf = "0.0.0.0",int if_index = 0); -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** multicast, ipv6 only */ - void SetMulticastHops(int = -1); - /** multicast, ipv6 only */ - int GetMulticastHops(); -#endif -#endif - /** Returns true if Bind succeeded. */ - bool IsBound(); - /** Return Bind port number */ - port_t GetPort(); - - void OnOptions(int,int,int,SOCKET) {} - - int GetLastSizeWritten(); - - /** Also read timestamp information from incoming message */ - void SetTimestamp(bool = true); - -protected: - UdpSocket(const UdpSocket& s) : Socket(s) {} - void OnRead(); -#if defined(LINUX) || defined(MACOSX) - /** This method emulates socket recvfrom, but uses messages so we can get the timestamp */ - int ReadTS(char *ioBuf, int inBufSize, struct sockaddr *from, socklen_t fromlen, struct timeval *ts); -#endif - -private: - UdpSocket& operator=(const UdpSocket& ) { return *this; } - /** create before using sendto methods */ - void CreateConnection(); - char *m_ibuf; ///< Input buffer - int m_ibufsz; ///< Size of input buffer - bool m_bind_ok; ///< Bind completed successfully - port_t m_port; ///< Bind port number - int m_last_size_written; - int m_retries; - bool m_b_read_ts; -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_UdpSocket_H - - diff --git a/dep/sockets/include/Utility.h b/dep/sockets/include/Utility.h deleted file mode 100644 index 724a94e4b32..00000000000 --- a/dep/sockets/include/Utility.h +++ /dev/null @@ -1,186 +0,0 @@ -/** \file Utility.h - ** \date 2004-02-13 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_Utility_H -#define _SOCKETS_Utility_H - -#include "sockets-config.h" -#include <ctype.h> -#include <string.h> -#include <memory> -#include "socket_include.h" -#include <map> -#include <string> - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -#define TWIST_LEN 624 - -class SocketAddress; - -/** Conversion utilities. - \ingroup util */ -class Utility -{ - /** - The Mersenne Twister - http://www.math.keio.ac.jp/~matumoto/emt.html - */ - class Rng { - public: - Rng(unsigned long seed); - - unsigned long Get(); - - private: - int m_value; - unsigned long m_tmp[TWIST_LEN]; - }; - class ncmap_compare { - public: - bool operator()(const std::string& x, const std::string& y) const { - return strcasecmp(x.c_str(), y.c_str()) < 0; - } - }; -public: - template<typename Y> class ncmap : public std::map<std::string, Y, ncmap_compare> { - public: - ncmap() {} - }; -public: - static std::string base64(const std::string& str_in); - static std::string base64d(const std::string& str_in); - static std::string l2string(long l); - static std::string bigint2string(uint64_t l); - static uint64_t atoi64(const std::string& str); - static unsigned int hex2unsigned(const std::string& str); - static std::string rfc1738_encode(const std::string& src); - static std::string rfc1738_decode(const std::string& src); - - /** Checks whether a string is a valid ipv4/ipv6 ip number. */ - static bool isipv4(const std::string&); - /** Checks whether a string is a valid ipv4/ipv6 ip number. */ - static bool isipv6(const std::string&); - - /** Hostname to ip resolution ipv4, not asynchronous. */ - static bool u2ip(const std::string&, ipaddr_t&); - static bool u2ip(const std::string&, struct sockaddr_in& sa, int ai_flags = 0); - -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** Hostname to ip resolution ipv6, not asynchronous. */ - static bool u2ip(const std::string&, struct in6_addr&); - static bool u2ip(const std::string&, struct sockaddr_in6& sa, int ai_flags = 0); -#endif -#endif - - /** Reverse lookup of address to hostname */ - static bool reverse(struct sockaddr *sa, socklen_t sa_len, std::string&, int flags = 0); - static bool reverse(struct sockaddr *sa, socklen_t sa_len, std::string& hostname, std::string& service, int flags = 0); - - static bool u2service(const std::string& name, int& service, int ai_flags = 0); - - /** Convert binary ip address to string: ipv4. */ - static void l2ip(const ipaddr_t,std::string& ); - static void l2ip(const in_addr&,std::string& ); -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** Convert binary ip address to string: ipv6. */ - static void l2ip(const struct in6_addr&,std::string& ,bool mixed = false); - - /** ipv6 address compare. */ - static int in6_addr_compare(in6_addr,in6_addr); -#endif -#endif - /** ResolveLocal (hostname) - call once before calling any GetLocal method. */ - static void ResolveLocal(); - /** Returns local hostname, ResolveLocal must be called once before using. - \sa ResolveLocal */ - static const std::string& GetLocalHostname(); - /** Returns local ip, ResolveLocal must be called once before using. - \sa ResolveLocal */ - static ipaddr_t GetLocalIP(); - /** Returns local ip number as string. - \sa ResolveLocal */ - static const std::string& GetLocalAddress(); -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - /** Returns local ipv6 ip. - \sa ResolveLocal */ - static const struct in6_addr& GetLocalIP6(); - /** Returns local ipv6 address. - \sa ResolveLocal */ - static const std::string& GetLocalAddress6(); -#endif -#endif - /** Set environment variable. - \param var Name of variable to set - \param value Value */ - static void SetEnv(const std::string& var,const std::string& value); - /** Convert sockaddr struct to human readable string. - \param sa Ptr to sockaddr struct */ - static std::string Sa2String(struct sockaddr *sa); - - /** Get current time in sec/microseconds. */ - static void GetTime(struct timeval *); - - static std::auto_ptr<SocketAddress> CreateAddress(struct sockaddr *,socklen_t); - - static unsigned long ThreadID(); - - static std::string ToLower(const std::string& str); - static std::string ToUpper(const std::string& str); - - static std::string ToString(double d); - - /** Returns a random 32-bit integer */ - static unsigned long Rnd(); - -private: - static std::string m_host; ///< local hostname - static ipaddr_t m_ip; ///< local ip address - static std::string m_addr; ///< local ip address in string format -#ifdef ENABLE_IPV6 -#ifdef IPPROTO_IPV6 - static struct in6_addr m_local_ip6; ///< local ipv6 address -#endif - static std::string m_local_addr6; ///< local ipv6 address in string format -#endif - static bool m_local_resolved; ///< ResolveLocal has been called if true -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // _SOCKETS_Utility_H - - diff --git a/dep/sockets/include/socket_include.h b/dep/sockets/include/socket_include.h deleted file mode 100644 index 89855a54108..00000000000 --- a/dep/sockets/include/socket_include.h +++ /dev/null @@ -1,290 +0,0 @@ -/** \file socket_include.h - ** \date 2005-04-12 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_socket_include_H -#define _SOCKETS_socket_include_H -#include "sockets-config.h" - -#ifdef _MSC_VER -#pragma warning(disable:4514) -#endif - -// common defines affecting library and applications using library - -/* Define SOCKETS_DYNAMIC_TEMP to use dynamically allocated buffers - in read operations - helps on ECOS */ -#define SOCKETS_DYNAMIC_TEMP - -// platform specific stuff -#if (defined(__unix__) || defined(unix)) && !defined(USG) -#include <sys/param.h> -#endif -#include <list> - -// int64 -#ifdef _WIN32 -typedef unsigned __int64 uint64_t; -#else -#include <stdlib.h> -#ifdef SOLARIS -# include <sys/types.h> -#else -# include <stdint.h> -#endif -#endif - -#ifndef _WIN32 -// ---------------------------------------- -// common unix includes / defines -#include <unistd.h> -#include <sys/time.h> -#include <sys/types.h> -#include <sys/socket.h> -#include <netinet/in.h> -#include <arpa/inet.h> -//#include <netdb.h> - -// all typedefs in this file will be declared outside the sockets namespace, -// because some os's will already have one or more of the type defined. -typedef int SOCKET; -#define Errno errno -#define StrError strerror - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -// WIN32 adapt -#define closesocket close -#define INVALID_SOCKET -1 -#define SOCKET_ERROR -1 - -#ifndef INADDR_NONE -#define INADDR_NONE ((unsigned long) -1) -#endif // INADDR_NONE - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif // !_WIN32 - -// ---------------------------------------- -// Generic -#ifndef SOL_IP -#define SOL_IP IPPROTO_IP -#endif - -// ---------------------------------------- -// OS specific adaptions - -#ifdef SOLARIS -// ---------------------------------------- -// Solaris -typedef unsigned short port_t; -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif -// no defs - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#define s6_addr16 _S6_un._S6_u8 -#define MSG_NOSIGNAL 0 - -#elif defined __FreeBSD__ -// ---------------------------------------- -// FreeBSD -# if __FreeBSD_version >= 400014 -# define s6_addr16 __u6_addr.__u6_addr16 -# if !defined(MSG_NOSIGNAL) -# define MSG_NOSIGNAL 0 -# endif -# include <netinet/in.h> -typedef in_addr_t ipaddr_t; -typedef in_port_t port_t; -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif -// no defs - -#ifdef SOCKETS_NAMESPACE -} -#endif - -# define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP -# define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP -# else -# error FreeBSD versions prior to 400014 does not support ipv6 -# endif - -#elif defined (__NetBSD__) || defined (__OpenBSD__) -# if !defined(MSG_NOSIGNAL) -# define MSG_NOSIGNAL 0 -# endif -# include <netinet/in.h> -typedef in_addr_t ipaddr_t; -typedef in_port_t port_t; -#elif defined MACOSX -// ---------------------------------------- -// Mac OS X -#include <string.h> -#ifdef __DARWIN_UNIX03 -typedef unsigned short port_t; -#else -#include <mach/port.h> -#endif // __DARWIN_UNIX03 -typedef unsigned long ipaddr_t; -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif -// no defs - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#define s6_addr16 __u6_addr.__u6_addr16 -#define MSG_NOSIGNAL 0 // oops - thanks Derek -#define IPV6_ADD_MEMBERSHIP IPV6_JOIN_GROUP -#define IPV6_DROP_MEMBERSHIP IPV6_LEAVE_GROUP - -#elif defined _WIN32 -// ---------------------------------------- -// Win32 -#ifdef _MSC_VER -#pragma comment(lib, "wsock32.lib") -#endif -#define strcasecmp _stricmp - -typedef unsigned long ipaddr_t; -typedef unsigned short port_t; -typedef int socklen_t; -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif -// no defs - -#ifdef SOCKETS_NAMESPACE -} -#endif - -// 1.8.6: define FD_SETSIZE to something bigger than 64 if there are a lot of -// simultaneous connections (must be done before including winsock.h) -#define FD_SETSIZE 1024 - -// windows 2000 with ipv6 preview installed: -// http://msdn.microsoft.com/downloads/sdks/platform/tpipv6.asp -// see the FAQ on how to install -#define WIN32_LEAN_AND_MEAN -#include <winsock2.h> -#include <ws2tcpip.h> -#if _MSC_VER < 1200 -#ifndef __CYGWIN__ -#ifdef ENABLE_IPV6 -#include <tpipv6.h> // For IPv6 Tech Preview. -#endif -#endif -#endif // _MSC_VER < 1200 - -#define MSG_NOSIGNAL 0 -//#define SHUT_RDWR 2 -#define SHUT_WR 1 - -#define Errno WSAGetLastError() -const char *StrError(int x); - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - -// class WSAInitializer is a part of the Socket class (on win32) -// as a static instance - so whenever an application uses a Socket, -// winsock is initialized -class WSAInitializer // Winsock Initializer -{ -public: - WSAInitializer() { - if (WSAStartup(0x101,&m_wsadata)) - { - exit(-1); - } - } - ~WSAInitializer() { - WSACleanup(); - } -private: - WSADATA m_wsadata; -}; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#else -// ---------------------------------------- -// LINUX -typedef unsigned long ipaddr_t; -typedef unsigned short port_t; -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif -// no defs - -#ifdef SOCKETS_NAMESPACE -} -#endif - -#endif - -#ifdef SOCKETS_NAMESPACE -namespace SOCKETS_NAMESPACE { -#endif - /** List type containing file descriptors. */ - typedef std::list<SOCKET> socket_v; - -#ifdef SOCKETS_NAMESPACE -} -#endif - -// getaddrinfo / getnameinfo replacements -#ifdef NO_GETADDRINFO -#ifndef AI_NUMERICHOST -#define AI_NUMERICHOST 1 -#endif -#ifndef NI_NUMERICHOST -#define NI_NUMERICHOST 1 -#endif -#endif - -#endif // _SOCKETS_socket_include_H - - diff --git a/dep/sockets/include/sockets-config.h b/dep/sockets/include/sockets-config.h deleted file mode 100644 index 1c8dc439092..00000000000 --- a/dep/sockets/include/sockets-config.h +++ /dev/null @@ -1,90 +0,0 @@ -/** - ** \file sockets-config.h - ** \date 2007-04-14 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2007 Anders Hedstrom - -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, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#ifndef _SOCKETS_CONFIG_H -#define _SOCKETS_CONFIG_H - -#ifndef _RUN_DP -/* First undefine symbols if already defined. */ -#undef HAVE_OPENSSL -#undef ENABLE_IPV6 -#undef USE_SCTP -#undef NO_GETADDRINFO -#undef ENABLE_POOL -#undef ENABLE_SOCKS4 -#undef ENABLE_RESOLVER -#undef ENABLE_RECONNECT -#undef ENABLE_DETACH -#undef ENABLE_TRIGGERS -#undef ENABLE_EXCEPTIONS -#endif // _RUN_DP - -// define MACOSX for internal socket library checks -#if defined(__APPLE__) && defined(__MACH__) && !defined(MACOSX) -#define MACOSX -#endif - -/* OpenSSL support. */ -//#define HAVE_OPENSSL - -/* Ipv6 support. */ -//#define ENABLE_IPV6 - -/* SCTP support. */ -//#define USE_SCTP - -/* Define NO_GETADDRINFO if your operating system does not support - the "getaddrinfo" and "getnameinfo" function calls. */ -#define NO_GETADDRINFO - -/* Connection pool support. */ -#define ENABLE_POOL - -/* Socks4 client support. */ -//#define ENABLE_SOCKS4 - -/* Asynchronous resolver. */ -#define ENABLE_RESOLVER - -/* Enable TCP reconnect on lost connection. - Socket::OnReconnect - Socket::OnDisconnect -*/ -#define ENABLE_RECONNECT - -/* Enable socket thread detach functionality. */ -#define ENABLE_DETACH - -/* Enable socket to socket triggers. Not yet in use. */ -//#define ENABLE_TRIGGERS - -/* Enabled exceptions. */ -//#define ENABLE_EXCEPTIONS - -/* Resolver uses the detach function so either enable both or disable both. */ -#ifndef ENABLE_DETACH -#undef ENABLE_RESOLVER -#endif - -#endif // _SOCKETS_CONFIG_H - - diff --git a/dep/sockets/network_kist.txt b/dep/sockets/network_kist.txt deleted file mode 100644 index f6597bf9c77..00000000000 --- a/dep/sockets/network_kist.txt +++ /dev/null @@ -1,20 +0,0 @@ -The following are the only .cpp files used from the new network library (v2.2.8) This file is just for future reference. - -Base64.cpp -Exception.cpp -Ipv4Address.cpp -Ipv6Address.cpp -Lock.cpp -Mutex.cpp -Parse.cpp -ResolvServer.cpp -ResolvSocket.cpp -Socket.cpp -SocketHandler.cpp -socket_include.cpp -StdoutLog.cpp -StreamSocket.cpp -TcpSocket.cpp -Thread.cpp -UdpSocket.cpp -Utility.cpp diff --git a/dep/sockets/socket_include.cpp b/dep/sockets/socket_include.cpp deleted file mode 100644 index 290602c1b52..00000000000 --- a/dep/sockets/socket_include.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/** \file socket_include.cpp - ** \date 2004-11-28 - ** \author grymse@alhem.net -**/ -/* -Copyright (C) 2004-2007 Anders Hedstrom - -This library is made available under the terms of the GNU GPL. - -If you would like to use this library in a closed-source application, -a separate license agreement is available. For information about -the closed-source license agreement for the C++ sockets library, -please visit http://www.alhem.net/Sockets/license.html and/or -email license@alhem.net. - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -#include <stdio.h> - -// only to be included in win32 projects -const char *StrError(int x) -{ -static char tmp[100]; - switch (x) - { - case 10004: return "Interrupted function call."; - case 10013: return "Permission denied."; - case 10014: return "Bad address."; - case 10022: return "Invalid argument."; - case 10024: return "Too many open files."; - case 10035: return "Resource temporarily unavailable."; - case 10036: return "Operation now in progress."; - case 10037: return "Operation already in progress."; - case 10038: return "Socket operation on nonsocket."; - case 10039: return "Destination address required."; - case 10040: return "Message too long."; - case 10041: return "Protocol wrong type for socket."; - case 10042: return "Bad protocol option."; - case 10043: return "Protocol not supported."; - case 10044: return "Socket type not supported."; - case 10045: return "Operation not supported."; - case 10046: return "Protocol family not supported."; - case 10047: return "Address family not supported by protocol family."; - case 10048: return "Address already in use."; - case 10049: return "Cannot assign requested address."; - case 10050: return "Network is down."; - case 10051: return "Network is unreachable."; - case 10052: return "Network dropped connection on reset."; - case 10053: return "Software caused connection abort."; - case 10054: return "Connection reset by peer."; - case 10055: return "No buffer space available."; - case 10056: return "Socket is already connected."; - case 10057: return "Socket is not connected."; - case 10058: return "Cannot send after socket shutdown."; - case 10060: return "Connection timed out."; - case 10061: return "Connection refused."; - case 10064: return "Host is down."; - case 10065: return "No route to host."; - case 10067: return "Too many processes."; - case 10091: return "Network subsystem is unavailable."; - case 10092: return "Winsock.dll version out of range."; - case 10093: return "Successful WSAStartup not yet performed."; - case 10101: return "Graceful shutdown in progress."; - case 10109: return "Class type not found."; - case 11001: return "Host not found."; - case 11002: return "Nonauthoritative host not found."; - case 11003: return "This is a nonrecoverable error."; - case 11004: return "Valid name, no data record of requested type."; - - default: - break; - } - sprintf(tmp, "Winsock error code: %d", x); - return tmp; -} - - diff --git a/sql/base/world_database.sql b/sql/base/world_database.sql index 4265dc0434b..cfcd30f5359 100644 --- a/sql/base/world_database.sql +++ b/sql/base/world_database.sql @@ -16887,6 +16887,7 @@ INSERT INTO `spell_bonus_data` (`entry`,`direct_bonus`,`dot_bonus`,`ap_bonus`,`a (26573, -1, 0.04, -1, 0.04, 'Paladin - Consecration'), (879, 0.15, -1, 0.15, -1, 'Paladin - Exorcism'), (19750, 1, -1, -1, -1, 'Paladin - Flash of Light'), +(66922, 0, 0, 0, 0, 'Paladin - Flash of Light'), (53595, 0, 0, 0, 0, 'Paladin - Hammer of the Righteous'), (24275, 0.15, -1, 0.15, -1, 'Paladin - Hammer of Wrath'), (62124, 0.085, -1, -1, -1, 'Paladin - Hand of Reckoning'), @@ -18305,7 +18306,6 @@ INSERT INTO `spell_proc_event` (`entry`,`SchoolMask`,`SpellFamilyName`,`SpellFam ( 11185, 0x00, 3, 0x00000080, 0x00000000, 0x00000000, 0x00050000, 0x00000000, 0, 0, 0), -- Improved Blizzard (Rank 1) ( 11255, 0x00, 3, 0x00004000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0, 0, 0), -- Improved Counterspell (Rank 1) ( 12169, 0x00, 0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000040, 0, 0, 0), -- Shield Block -( 12281, 0x00, 0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0, 0, 6), -- Sword Specialization (Rank 1) ( 12289, 0x00, 4, 0x00000002, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0, 0, 0), -- Improved Hamstring (Rank 1) ( 12298, 0x00, 0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000070, 0, 0, 0), -- Shield Specialization (Rank 1) ( 12311, 0x00, 4, 0x00000800, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0, 0, 0), -- Gag Order (Rank 1) @@ -18321,10 +18321,11 @@ INSERT INTO `spell_proc_event` (`entry`,`SchoolMask`,`SpellFamilyName`,`SpellFam ( 12727, 0x00, 0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000070, 0, 0, 0), -- Shield Specialization (Rank 5) ( 12797, 0x00, 4, 0x00000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0, 0, 0), -- Improved Revenge (Rank 1) ( 12799, 0x00, 4, 0x00000400, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0, 0, 0), -- Improved Revenge (Rank 2) -( 12812, 0x00, 0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0, 0, 6), -- Sword Specialization (Rank 2) -( 12813, 0x00, 0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0, 0, 6), -- Sword Specialization (Rank 3) -( 12814, 0x00, 0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0, 0, 6), -- Sword Specialization (Rank 4) -( 12815, 0x00, 0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0, 0, 6), -- Sword Specialization (Rank 5) +( 12281, 0x00, 4, 0xAA600444, 0x00400105, 0x00000000, 0x00000000, 0x00000000, 0, 0, 6), -- Sword Specialization (Rank 1) +( 12812, 0x00, 4, 0xAA600444, 0x00400105, 0x00000000, 0x00000000, 0x00000000, 0, 0, 6), -- Sword Specialization (Rank 2) +( 12813, 0x00, 4, 0xAA600444, 0x00400105, 0x00000000, 0x00000000, 0x00000000, 0, 0, 6), -- Sword Specialization (Rank 3) +( 12814, 0x00, 4, 0xAA600444, 0x00400105, 0x00000000, 0x00000000, 0x00000000, 0, 0, 6), -- Sword Specialization (Rank 4) +( 12815, 0x00, 4, 0xAA600444, 0x00400105, 0x00000000, 0x00000000, 0x00000000, 0, 0, 6), -- Sword Specialization (Rank 5) ( 12834, 0x00, 0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000002, 0, 0, 0), -- Deep Wounds (Rank 1) ( 12846, 0x04, 3, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000002, 0, 0, 0), -- Ignite (Rank 3) ( 12847, 0x04, 3, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000002, 0, 0, 0), -- Ignite (Rank 4) @@ -19330,12 +19331,7 @@ INSERT INTO `spell_proc_event` (`entry`,`SchoolMask`,`SpellFamilyName`,`SpellFam ( 75474, 0x00, 0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0, 0, 45), -- Charred Twilight Scale (Heroic) ( 75465, 0x00, 0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0, 0, 45), -- Charred Twilight Scale ( 75457, 0x00, 0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0, 0, 45), -- Sharpened Twilight Scale (Heroic) -( 75455, 0x00, 0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0, 0, 45), -- Sharpened Twilight Scale -( 12281, 0x00, 4, 0xAA600444, 0x00400105, 0x00000000, 0x00000000, 0x00000000, 0, 0, 6), -- Sword Specialization (Rank 1) -( 12812, 0x00, 4, 0xAA600444, 0x00400105, 0x00000000, 0x00000000, 0x00000000, 0, 0, 6), -- Sword Specialization (Rank 2) -( 12813, 0x00, 4, 0xAA600444, 0x00400105, 0x00000000, 0x00000000, 0x00000000, 0, 0, 6), -- Sword Specialization (Rank 3) -( 12814, 0x00, 4, 0xAA600444, 0x00400105, 0x00000000, 0x00000000, 0x00000000, 0, 0, 6), -- Sword Specialization (Rank 4) -( 12815, 0x00, 4, 0xAA600444, 0x00400105, 0x00000000, 0x00000000, 0x00000000, 0, 0, 6); -- Sword Specialization (Rank 5) +( 75455, 0x00, 0, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0, 0, 45); -- Sharpened Twilight Scale /*!40000 ALTER TABLE `spell_proc_event` ENABLE KEYS */; UNLOCK TABLES; @@ -26875,6 +26871,9 @@ INSERT INTO `spell_script_names` (`spell_id`,`ScriptName`) VALUES ( 17271, 'spell_q5206_test_fetid_skull'), ( 19512, 'spell_q6124_6129_apply_salve'), ( 34665, 'spell_q10255_administer_antidote'), +( 43874, 'spell_q11396_11399_force_shield_arcane_purple_x3'), +( 43882, 'spell_q11396_11399_scourging_crystal_controller_dummy'), +( 50133, 'spell_q11396_11399_scourging_crystal_controller'), ( 44936, 'spell_q11515_fel_siphon_dummy'), ( 45449, 'spell_q11587_arcane_prisoner_rescue'), ( 46023, 'spell_q11730_ultrasonic_screwdriver'), @@ -27778,8 +27777,8 @@ INSERT INTO `trinity_string` (`entry`,`content_default`,`content_loc1`,`content_ (5019, '[Mountable]', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL), (5020, 'Phasemask: %u', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL), (5021, 'Armor: %u', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL), -(5022, 'Granting ownership to first person that joins the channel \"%s\": Enabled.'), -(5023, 'Granting ownership to first person that joins the channel \"%s\": Disabled.'), +(5022, 'Granting ownership to first person that joins the channel \"%s\": Enabled.', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL), +(5023, 'Granting ownership to first person that joins the channel \"%s\": Disabled.', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL), (5024, 'Entry: %u', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL), (5025, 'Type: %u', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL), (5026, 'DisplayID: %u', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL), diff --git a/sql/updates/10619_world_spell_script_names.sql b/sql/updates/10619_world_spell_script_names.sql new file mode 100644 index 00000000000..23f06a72125 --- /dev/null +++ b/sql/updates/10619_world_spell_script_names.sql @@ -0,0 +1,7 @@ +DELETE FROM `spell_script_names` WHERE `spell_id`=43874 AND `ScriptName`='spell_q11396_11399_force_shield_arcane_purple_x3'; +DELETE FROM `spell_script_names` WHERE `spell_id`=50133 AND `ScriptName`='spell_q11396_11399_scourging_crystal_controller'; +DELETE FROM `spell_script_names` WHERE `spell_id`=43882 AND `ScriptName`='spell_q11396_11399_scourging_crystal_controller_dummy'; +INSERT INTO `spell_script_names` (`spell_id`,`ScriptName`) VALUES +(43874, 'spell_q11396_11399_force_shield_arcane_purple_x3'), +(43882, 'spell_q11396_11399_scourging_crystal_controller_dummy'), +(50133, 'spell_q11396_11399_scourging_crystal_controller'); diff --git a/sql/updates/10623_world_spell_bonus_data.sql b/sql/updates/10623_world_spell_bonus_data.sql new file mode 100644 index 00000000000..7db48d5bd92 --- /dev/null +++ b/sql/updates/10623_world_spell_bonus_data.sql @@ -0,0 +1,3 @@ +DELETE FROM `spell_bonus_data` WHERE `entry` IN (66922); +INSERT INTO `spell_bonus_data` (`entry`, `direct_bonus`, `dot_bonus`, `ap_bonus`, `ap_dot_bonus`, `comments`) VALUES +(66922, 0, 0, 0, 0, 'Paladin - Flash of Light'); diff --git a/src/server/authserver/authserver.conf.dist b/src/server/authserver/authserver.conf.dist index 9c14178a0a0..6bd1185305c 100644 --- a/src/server/authserver/authserver.conf.dist +++ b/src/server/authserver/authserver.conf.dist @@ -40,10 +40,10 @@ LogsDir = "" # # MaxPingTime -# Description: Time (in seconds) between database pings. -# Default: 1800 - (30 minutes) +# Description: Time (in minutes) between database pings. +# Default: 30 -MaxPingTime = 1800 +MaxPingTime = 30 # # RealmServerPort @@ -225,10 +225,9 @@ LoginDatabaseInfo = "127.0.0.1;3306;trinity;trinity;auth" # LoginDatabase.WorkerThreads # Description: The amount of worker threads spawned to handle asynchronous (delayed) MySQL # statements. Each worker thread is mirrored with its own connection to the -# MySQL server and their own thread on the MySQL server. -# Default: 1 - (LoginDatabase.WorkerThreads) +# Default: 1 -LoginDatabase.WorkerThreads = 1 +LoginDatabase.WorkerThreads = 1 # ################################################################################################### diff --git a/src/server/collision/Maps/TileAssembler.cpp b/src/server/collision/Maps/TileAssembler.cpp index 22982fe86f5..ac451b8913f 100644 --- a/src/server/collision/Maps/TileAssembler.cpp +++ b/src/server/collision/Maps/TileAssembler.cpp @@ -264,6 +264,9 @@ namespace VMAP // temporary use defines to simplify read/check code (close file and return at fail) #define READ_OR_RETURN(V,S) if(fread((V), (S), 1, rf) != 1) { \ fclose(rf); printf("readfail, op = %i\n", readOperation); return(false); }readOperation++; + #define READ_OR_RETURN_WITH_DELETE(V,S) if(fread((V), (S), 1, rf) != 1) { \ + fclose(rf); printf("readfail, op = %i\n", readOperation); delete V; return(false); }readOperation++; + #define CMP_OR_RETURN(V,S) if(strcmp((V),(S)) != 0) { \ fclose(rf); printf("cmpfail, %s!=%s\n", V, S);return(false); } @@ -309,11 +312,12 @@ namespace VMAP if (nvectors >0) { vectorarray = new float[nvectors*3]; - READ_OR_RETURN(vectorarray, nvectors*sizeof(float)*3); + READ_OR_RETURN_WITH_DELETE(vectorarray, nvectors*sizeof(float)*3); } else { std::cout << "error: model '" << spawn.name << "' has no geometry!" << std::endl; + fclose(rf); return false; } @@ -370,6 +374,8 @@ namespace VMAP // temporary use defines to simplify read/check code (close file and return at fail) #define READ_OR_RETURN(V,S) if(fread((V), (S), 1, rf) != 1) { \ fclose(rf); printf("readfail, op = %i\n", readOperation); return(false); }readOperation++; + #define READ_OR_RETURN_WITH_DELETE(V,S) if(fread((V), (S), 1, rf) != 1) { \ + fclose(rf); printf("readfail, op = %i\n", readOperation); delete V; return(false); }readOperation++; #define CMP_OR_RETURN(V,S) if(strcmp((V),(S)) != 0) { \ fclose(rf); printf("cmpfail, %s!=%s\n", V, S);return(false); } @@ -429,7 +435,7 @@ namespace VMAP if (nindexes >0) { uint16 *indexarray = new uint16[nindexes]; - READ_OR_RETURN(indexarray, nindexes*sizeof(uint16)); + READ_OR_RETURN_WITH_DELETE(indexarray, nindexes*sizeof(uint16)); for (uint32 i=0; i<nindexes; i+=3) { triangles.push_back(MeshTriangle(indexarray[i], indexarray[i+1], indexarray[i+2])); @@ -447,7 +453,7 @@ namespace VMAP if (nvectors >0) { float *vectorarray = new float[nvectors*3]; - READ_OR_RETURN(vectorarray, nvectors*sizeof(float)*3); + READ_OR_RETURN_WITH_DELETE(vectorarray, nvectors*sizeof(float)*3); for (uint32 i=0; i<nvectors; ++i) { vertexArray.push_back( Vector3(vectorarray + 3*i) ); diff --git a/src/server/collision/Maps/TileAssembler.h b/src/server/collision/Maps/TileAssembler.h index fa52ef3a3fc..600ae879160 100755 --- a/src/server/collision/Maps/TileAssembler.h +++ b/src/server/collision/Maps/TileAssembler.h @@ -82,7 +82,6 @@ namespace VMAP bool convertRawFile(const std::string& pModelFilename); void setModelNameFilterMethod(bool (*pFilterMethod)(char *pName)) { iFilterMethod = pFilterMethod; } std::string getDirEntryNameFromModName(unsigned int pMapId, const std::string& pModPosName); - unsigned int getUniqueNameId(const std::string pName); }; } // VMAP diff --git a/src/server/game/AI/CoreAI/GameObjectAI.h b/src/server/game/AI/CoreAI/GameObjectAI.h index ec3802ced37..e0f657b2868 100644 --- a/src/server/game/AI/CoreAI/GameObjectAI.h +++ b/src/server/game/AI/CoreAI/GameObjectAI.h @@ -46,7 +46,7 @@ class GameObjectAI virtual bool GossipSelectCode(Player* /*player*/, uint32 /*sender*/, uint32 /*action*/, const char* /*code*/) {return false;} virtual bool QuestAccept(Player* /*player*/, Quest const* /*quest*/) {return false;} virtual bool QuestReward(Player* /*player*/, Quest const* /*quest*/, uint32 /*opt*/) {return false;} - uint32 GetDialogStatus(Player* /*player*/) {return 100;} + virtual uint32 GetDialogStatus(Player* /*player*/) {return 100;} virtual void Destroyed(Player* /*player*/, uint32 /*eventId*/) {} virtual void SetData(uint32 /*id*/, uint32 /*value*/) {} }; diff --git a/src/server/game/AI/CreatureAI.h b/src/server/game/AI/CreatureAI.h index e1067dadd88..98e0e448195 100755 --- a/src/server/game/AI/CreatureAI.h +++ b/src/server/game/AI/CreatureAI.h @@ -70,7 +70,6 @@ class CreatureAI : public UnitAI bool UpdateVictim(); bool UpdateVictimWithGaze(); - bool UpdateCombatState(); void SetGazeOn(Unit *target); diff --git a/src/server/game/AI/CreatureAIImpl.h b/src/server/game/AI/CreatureAIImpl.h index cab8c54d471..ae989fdb987 100755 --- a/src/server/game/AI/CreatureAIImpl.h +++ b/src/server/game/AI/CreatureAIImpl.h @@ -524,26 +524,6 @@ inline bool CreatureAI::UpdateVictimWithGaze() return me->getVictim(); } -inline bool CreatureAI::UpdateCombatState() -{ - if (!me->isInCombat()) - return false; - - if (!me->HasReactState(REACT_PASSIVE)) - { - if (Unit *victim = me->SelectVictim()) - AttackStart(victim); - return me->getVictim(); - } - else if (me->getThreatManager().isThreatListEmpty()) - { - EnterEvadeMode(); - return false; - } - - return true; -} - inline bool CreatureAI::UpdateVictim() { if (!me->isInCombat()) diff --git a/src/server/game/AI/ScriptedAI/ScriptedCreature.h b/src/server/game/AI/ScriptedAI/ScriptedCreature.h index 84e02ae169e..36f31c52e8e 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedCreature.h +++ b/src/server/game/AI/ScriptedAI/ScriptedCreature.h @@ -269,7 +269,7 @@ struct BossAI : public ScriptedAI void Reset() { _Reset(); } void EnterCombat(Unit * /*who*/) { _EnterCombat(); } void JustDied(Unit * /*killer*/) { _JustDied(); } - void JustReachedHome() { me->setActive(false); } + void JustReachedHome() { _JustReachedHome(); } protected: void _Reset(); diff --git a/src/server/game/AI/SmartScripts/SmartAI.cpp b/src/server/game/AI/SmartScripts/SmartAI.cpp index 7509fa4e329..f5bf2b975e3 100644 --- a/src/server/game/AI/SmartScripts/SmartAI.cpp +++ b/src/server/game/AI/SmartScripts/SmartAI.cpp @@ -789,6 +789,13 @@ void SmartAI::SetFollow(Unit* target, float dist, float angle, uint32 credit, ui me->GetMotionMaster()->MoveFollow(target, dist, angle); mFollowCreditType = creditType; } + +void SmartAI::SetScript9(SmartScriptHolder &e, uint32 entry, Unit* invoker) +{ + if (invoker) + GetScript()->mLastInvoker = invoker; + GetScript()->SetScript9(e, entry); +} /* SMART_EVENT_UPDATE_OOC SMART_EVENT_SPELLHIT @@ -884,6 +891,13 @@ void SmartGameObjectAI::SetData(uint32 id, uint32 value) GetScript()->ProcessEventsFor(SMART_EVENT_DATA_SET, NULL, id, value); } +void SmartGameObjectAI::SetScript9(SmartScriptHolder &e, uint32 entry, Unit* invoker) +{ + if (invoker) + GetScript()->mLastInvoker = invoker; + GetScript()->SetScript9(e, entry); +} + class SmartTrigger : public AreaTriggerScript { public: diff --git a/src/server/game/AI/SmartScripts/SmartAI.h b/src/server/game/AI/SmartScripts/SmartAI.h index b664ded1ddd..30aeef323a6 100644 --- a/src/server/game/AI/SmartScripts/SmartAI.h +++ b/src/server/game/AI/SmartScripts/SmartAI.h @@ -65,6 +65,7 @@ class SmartAI : public CreatureAI void SetCombatMove(bool on); void SetFollow(Unit* target, float dist = 0.0f, float angle = 0.0f, uint32 credit = 0, uint32 end = 0, uint32 creditType = 0); + void SetScript9(SmartScriptHolder &e, uint32 entry, Unit* invoker); SmartScript* GetScript() { return &mScript; } bool IsEscortInvokerInRange(); @@ -247,6 +248,7 @@ public: uint32 GetDialogStatus(Player* /*player*/); void Destroyed(Player* player, uint32 eventId); void SetData(uint32 id, uint32 value); + void SetScript9(SmartScriptHolder &e, uint32 entry, Unit* invoker); protected: GameObject * const go; diff --git a/src/server/game/AI/SmartScripts/SmartScript.cpp b/src/server/game/AI/SmartScripts/SmartScript.cpp index 21499d0b8a9..f75bc60cbaf 100644 --- a/src/server/game/AI/SmartScripts/SmartScript.cpp +++ b/src/server/game/AI/SmartScripts/SmartScript.cpp @@ -460,13 +460,13 @@ void SmartScript::ProcessAction(SmartScriptHolder &e, Unit* unit, uint32 var0, u } case SMART_ACTION_CALL_CASTEDCREATUREORGO: { - if (!me) return; + if (!GetBaseObject()) return; ObjectList* targets = GetTargets(e, unit); if (!targets) return; for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); itr++) { if (IsPlayer((*itr))) - (*itr)->ToPlayer()->CastedCreatureOrGO(e.action.castedCreatureOrGO.creature, me->GetGUID(), e.action.castedCreatureOrGO.spell); + (*itr)->ToPlayer()->CastedCreatureOrGO(e.action.castedCreatureOrGO.creature, GetBaseObject()->GetGUID(), e.action.castedCreatureOrGO.spell); } break; } @@ -566,7 +566,8 @@ void SmartScript::ProcessAction(SmartScriptHolder &e, Unit* unit, uint32 var0, u WorldObject* obj = GetBaseObject(); if (!obj) obj = unit; - if (obj) return; + if (!obj) + return; InstanceScript* pInst = (InstanceScript*)obj->GetInstanceScript(); if (!pInst) { @@ -1062,7 +1063,27 @@ void SmartScript::ProcessAction(SmartScriptHolder &e, Unit* unit, uint32 var0, u } case SMART_ACTION_CALL_TIMED_ACTIONLIST: { - SetScript9(e, e.action.timedActionList.id); + if (e.GetTargetType() == SMART_TARGET_NONE) + { + sLog.outErrorDb("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()); + return; + } + 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)) + CAST_AI(SmartAI, target->AI())->SetScript9(e, e.action.timedActionList.id, mLastInvoker); + } else if (GameObject* target = (*itr)->ToGameObject()) + { + if (IsSmartGO(target)) + CAST_AI(SmartGameObjectAI, target->AI())->SetScript9(e, e.action.timedActionList.id, mLastInvoker); + } + } + } break; } case SMART_ACTION_SET_NPC_FLAG: @@ -1134,12 +1155,54 @@ void SmartScript::ProcessAction(SmartScriptHolder &e, Unit* unit, uint32 var0, u count++; } } - SetScript9(e, temp[urand(0, count)]); + uint32 id = temp[urand(0, count)]; + if (e.GetTargetType() == SMART_TARGET_NONE) + { + sLog.outErrorDb("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()); + return; + } + 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)) + CAST_AI(SmartAI, target->AI())->SetScript9(e, id, mLastInvoker); + } else if (GameObject* target = (*itr)->ToGameObject()) + { + if (IsSmartGO(target)) + CAST_AI(SmartGameObjectAI, target->AI())->SetScript9(e, id, mLastInvoker); + } + } + } break; } case SMART_ACTION_CALL_RANDOM_RANGE_TIMED_ACTIONLIST: { - SetScript9(e, urand(e.action.randTimedActionList.entry1, e.action.randTimedActionList.entry2)); + uint32 id = urand(e.action.randTimedActionList.entry1, e.action.randTimedActionList.entry2); + if (e.GetTargetType() == SMART_TARGET_NONE) + { + sLog.outErrorDb("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()); + return; + } + 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)) + CAST_AI(SmartAI, target->AI())->SetScript9(e, id, mLastInvoker); + } else if (GameObject* target = (*itr)->ToGameObject()) + { + if (IsSmartGO(target)) + CAST_AI(SmartGameObjectAI, target->AI())->SetScript9(e, id, mLastInvoker); + } + } + } break; } case SMART_ACTION_ACTIVATE_TAXI: diff --git a/src/server/game/AI/SmartScripts/SmartScript.h b/src/server/game/AI/SmartScripts/SmartScript.h index 74b3a4f4d33..7c43abba155 100644 --- a/src/server/game/AI/SmartScripts/SmartScript.h +++ b/src/server/game/AI/SmartScripts/SmartScript.h @@ -53,7 +53,7 @@ class SmartScript SmartScriptHolder CreateEvent(SMART_EVENT e, uint32 event_flags, uint32 event_param1, uint32 event_param2, uint32 event_param3, uint32 event_param4, 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, 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() { return mPathId; } + uint32 GetPathId() const { return mPathId; } WorldObject* GetBaseObject() { WorldObject* obj = NULL; @@ -111,7 +111,16 @@ class SmartScript if (c && c->GetAIName() != "SmartAI") smart = false; if (!me || me->GetAIName() != "SmartAI") smart = false; if (!smart) - sLog.outErrorDb("SmartScript: Action target creature(entry: %u) is not using SmartAI, action skipped to prevent crash.", c?c->GetEntry():(me?me->GetEntry():0)); + sLog.outErrorDb("SmartScript: Action target Creature(entry: %u) is not using SmartAI, action skipped to prevent crash.", c?c->GetEntry():(me?me->GetEntry():0)); + return smart; + } + bool IsSmartGO(GameObject* g = NULL) + { + bool smart = true; + if (g && g->GetAIName() != "SmartGameObjectAI") smart = false; + if (!go || go->GetAIName() != "SmartGameObjectAI") smart = false; + if (!smart) + sLog.outErrorDb("SmartScript: Action target GameObject(entry: %u) is not using SmartGameObjectAI, action skipped to prevent crash.", g?g->GetEntry():(go?go->GetEntry():0)); return smart; } ObjectList* GetTargetList(uint32 id) @@ -180,6 +189,10 @@ class SmartScript meOrigGUID = 0; } + //TIMED_ACTIONLIST (script type 9 aka script9) + void SetScript9(SmartScriptHolder &e, uint32 entry); + Unit* mLastInvoker; + private: void IncPhase(int32 p = 1) { if(p >= 0) @@ -188,7 +201,7 @@ class SmartScript DecPhase(abs(p)); } void DecPhase(int32 p = 1) { mEventPhase -= (mEventPhase < (uint32)p ? (uint32)p - mEventPhase : (uint32)p); } - bool IsInPhase(uint32 p) { return mEventPhase & p; } + bool IsInPhase(uint32 p) const { return mEventPhase & p; } void SetPhase(uint32 p = 0) { mEventPhase = p; } SmartAIEventList mEvents; @@ -214,7 +227,6 @@ class SmartScript uint64 mTextGUID; Creature* talker; bool mUseTextTimer; - Unit* mLastInvoker; SMARTAI_TEMPLATE mTemplate; void InstallEvents(); @@ -250,8 +262,6 @@ class SmartScript SmartScriptHolder s; return s; } - //TIMED_ACTIONLIST (script type 9 aka script9) - void SetScript9(SmartScriptHolder &e, uint32 entry); }; #endif diff --git a/src/server/game/AI/SmartScripts/SmartScriptMgr.h b/src/server/game/AI/SmartScripts/SmartScriptMgr.h index 55332117770..46de5bf1ac8 100644 --- a/src/server/game/AI/SmartScripts/SmartScriptMgr.h +++ b/src/server/game/AI/SmartScripts/SmartScriptMgr.h @@ -1121,10 +1121,10 @@ struct SmartScriptHolder SmartTarget target; public: - uint32 GetScriptType() { return (uint32)source_type; } - uint32 GetEventType() { return (uint32)event.type; } - uint32 GetActionType() { return (uint32)action.type; } - uint32 GetTargetType() { return (uint32)target.type; } + uint32 GetScriptType() const { return (uint32)source_type; } + uint32 GetEventType() const { return (uint32)event.type; } + uint32 GetActionType() const { return (uint32)action.type; } + uint32 GetTargetType() const { return (uint32)target.type; } uint32 timer; bool active; diff --git a/src/server/game/AuctionHouse/AuctionHouseMgr.cpp b/src/server/game/AuctionHouse/AuctionHouseMgr.cpp index 88d42368215..b305421feb9 100644 --- a/src/server/game/AuctionHouse/AuctionHouseMgr.cpp +++ b/src/server/game/AuctionHouse/AuctionHouseMgr.cpp @@ -75,9 +75,9 @@ uint32 AuctionHouseMgr::GetAuctionDeposit(AuctionHouseEntry const* entry, uint32 if (MSV <= 0) return AH_MINIMUM_DEPOSIT; - uint32 timeHr = (((time / 60) / 60) /12); - float multiplier = (float)(entry->depositPercent * 3) / 100.0f; - uint32 deposit = ((uint32)((float)MSV * multiplier * (float)count)/3) * 3 * timeHr; + float multiplier = CalculatePctN(float(entry->depositPercent), 3); + uint32 timeHr = (((time / 60) / 60) / 12); + uint32 deposit = uint32(multiplier * MSV * count / 3) * timeHr * 3; sLog.outDebug("MSV: %u", MSV); sLog.outDebug("Items: %u", count); @@ -98,12 +98,12 @@ void AuctionHouseMgr::SendAuctionWonMail(AuctionEntry *auction, SQLTransaction& return; uint32 bidder_accId = 0; - uint32 bidder_security = 0; uint64 bidder_guid = MAKE_NEW_GUID(auction->bidder, 0, HIGHGUID_PLAYER); Player *bidder = sObjectMgr.GetPlayer(bidder_guid); // data for gm.log if (sWorld.getBoolConfig(CONFIG_GM_LOG_TRADE)) { + uint32 bidder_security = 0; std::string bidder_name; if (bidder) { @@ -500,7 +500,7 @@ AuctionHouseEntry const* AuctionHouseMgr::GetAuctionHouseEntry(uint32 factionTem //FIXME: found way for proper auctionhouse selection by another way // AuctionHouse.dbc have faction field with _player_ factions associated with auction house races. // but no easy way convert creature faction to player race faction for specific city - switch(factionTemplateId) + switch (factionTemplateId) { case 12: houseid = 1; break; // human case 29: houseid = 6; break; // orc, and generic for horde @@ -762,27 +762,22 @@ bool AuctionEntry::BuildAuctionInfo(WorldPacket & data) const //minimal outbid data << uint32(buyout); //auction->buyout data << uint32((expire_time-time(NULL))*IN_MILLISECONDS);//time left - data << uint64(bidder) ; //auction->bidder current + data << uint64(bidder); //auction->bidder current data << uint32(bid); //current bid return true; } uint32 AuctionEntry::GetAuctionCut() const { - int32 cut = int32(((double)auctionHouseEntry->cutPercent / 100.0f) * (double)sWorld.getRate(RATE_AUCTION_CUT)) * bid; - if (cut > 0) - return cut; - else - return 0; + int32 cut = int32(CalculatePctU(sWorld.getRate(RATE_AUCTION_CUT), auctionHouseEntry->cutPercent)) * bid; + return std::max(cut, 0); } /// the sum of outbid is (1% from current bid)*5, if bid is very small, it is 1c uint32 AuctionEntry::GetAuctionOutBid() const { - uint32 outbid = (uint32)((double)bid / 100.0f) * 5; - if (!outbid) - outbid = 1; - return outbid; + uint32 outbid = CalculatePctN(bid, 5); + return outbid ? outbid : 1; } void AuctionEntry::DeleteFromDB(SQLTransaction& trans) const diff --git a/src/server/game/Battlegrounds/Battleground.cpp b/src/server/game/Battlegrounds/Battleground.cpp index 6dd2bd9fe5d..797e615dede 100755 --- a/src/server/game/Battlegrounds/Battleground.cpp +++ b/src/server/game/Battlegrounds/Battleground.cpp @@ -896,8 +896,8 @@ void Battleground::EndBattleground(uint32 winner) uint32 Battleground::GetBonusHonorFromKill(uint32 kills) const { //variable kills means how many honorable kills you scored (so we need kills * honor_for_one_kill) - uint32 maxLevel = (GetMaxLevel() < 80) ? GetMaxLevel() : 80; - return Trinity::Honor::hk_honor_at_level(maxLevel, kills); + uint32 maxLevel = std::min(GetMaxLevel(), 80U); + return Trinity::Honor::hk_honor_at_level(maxLevel, float(kills)); } uint32 Battleground::GetBattlemasterEntry() const @@ -1803,7 +1803,7 @@ void Battleground::HandleKillPlayer(Player *player, Player *killer) // return the player's team based on battlegroundplayer info // used in same faction arena matches mainly -uint32 Battleground::GetPlayerTeam(uint64 guid) +uint32 Battleground::GetPlayerTeam(uint64 guid) const { BattlegroundPlayerMap::const_iterator itr = m_Players.find(guid); if (itr != m_Players.end()) @@ -1811,12 +1811,12 @@ uint32 Battleground::GetPlayerTeam(uint64 guid) return 0; } -uint32 Battleground::GetOtherTeam(uint32 teamId) +uint32 Battleground::GetOtherTeam(uint32 teamId) const { return (teamId) ? ((teamId == ALLIANCE) ? HORDE : ALLIANCE) : 0; } -bool Battleground::IsPlayerInBattleground(uint64 guid) +bool Battleground::IsPlayerInBattleground(uint64 guid) const { BattlegroundPlayerMap::const_iterator itr = m_Players.find(guid); if (itr != m_Players.end()) @@ -1935,13 +1935,13 @@ void Battleground::RewardXPAtKill(Player* plr, Player* victim) return; uint32 xp = 0; - uint32 count = 0; - uint32 sum_level = 0; Player* member_with_max_level = NULL; Player* not_gray_member_with_max_level = NULL; if (Group *pGroup = plr->GetGroup())//should be always in a raid group while in any bg { + uint32 count = 0; + uint32 sum_level = 0; for (GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next()) { Player* member = itr->getSource(); @@ -1985,16 +1985,16 @@ void Battleground::RewardXPAtKill(Player* plr, Player* victim) // XP updated only for alive group member if (pGroupGuy->isAlive() && not_gray_member_with_max_level && pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel()) { - uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1); + uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp * rate) : uint32((xp * rate / 2) + 1); // handle SPELL_AURA_MOD_XP_PCT auras Unit::AuraEffectList const& ModXPPctAuras = plr->GetAuraEffectsByType(SPELL_AURA_MOD_XP_PCT); for (Unit::AuraEffectList::const_iterator i = ModXPPctAuras.begin(); i != ModXPPctAuras.end(); ++i) - itr_xp = uint32(itr_xp*(1.0f + (*i)->GetAmount() / 100.0f)); + AddPctN(itr_xp, (*i)->GetAmount()); pGroupGuy->GiveXP(itr_xp, victim); if (Pet* pet = pGroupGuy->GetPet()) - pet->GivePetXP(itr_xp/2); + pet->GivePetXP(itr_xp / 2); } } } @@ -2009,7 +2009,7 @@ void Battleground::RewardXPAtKill(Player* plr, Player* victim) // handle SPELL_AURA_MOD_XP_PCT auras Unit::AuraEffectList const& ModXPPctAuras = plr->GetAuraEffectsByType(SPELL_AURA_MOD_XP_PCT); for (Unit::AuraEffectList::const_iterator i = ModXPPctAuras.begin(); i != ModXPPctAuras.end(); ++i) - xp = uint32(xp*(1.0f + (*i)->GetAmount() / 100.0f)); + AddPctN(xp, (*i)->GetAmount()); plr->GiveXP(xp, victim); diff --git a/src/server/game/Battlegrounds/Battleground.h b/src/server/game/Battlegrounds/Battleground.h index 81540b43f6a..e8d5f032850 100755 --- a/src/server/game/Battlegrounds/Battleground.h +++ b/src/server/game/Battlegrounds/Battleground.h @@ -373,7 +373,7 @@ class Battleground uint32 GetScriptId() const { return ScriptId; } uint32 GetBattlemasterEntry() const; uint32 GetBonusHonorFromKill(uint32 kills) const; - bool IsRandom() { return m_IsRandom; } + bool IsRandom() const { return m_IsRandom; } // Set methods: void SetName(char const* Name) { m_Name = Name; } @@ -569,9 +569,9 @@ class Battleground virtual bool HandlePlayerUnderMap(Player * /*plr*/) { return false; } // since arenas can be AvA or Hvh, we have to get the "temporary" team of a player - uint32 GetPlayerTeam(uint64 guid); - uint32 GetOtherTeam(uint32 teamId); - bool IsPlayerInBattleground(uint64 guid); + uint32 GetPlayerTeam(uint64 guid) const; + uint32 GetOtherTeam(uint32 teamId) const; + bool IsPlayerInBattleground(uint64 guid) const; void SetDeleteThis() {m_SetDeleteThis = true;} diff --git a/src/server/game/Battlegrounds/BattlegroundMgr.cpp b/src/server/game/Battlegrounds/BattlegroundMgr.cpp index d286a1220cd..6103aabf694 100755 --- a/src/server/game/Battlegrounds/BattlegroundMgr.cpp +++ b/src/server/game/Battlegrounds/BattlegroundMgr.cpp @@ -865,8 +865,8 @@ void BattlegroundMgr::BuildBattlegroundListPacket(WorldPacket *data, const uint6 uint32 winner_arena = plr->GetRandomWinner() ? BG_REWARD_WINNER_ARENA_LAST : BG_REWARD_WINNER_ARENA_FIRST; uint32 loser_kills = plr->GetRandomWinner() ? BG_REWARD_LOSER_HONOR_LAST : BG_REWARD_LOSER_HONOR_FIRST; - winner_kills = Trinity::Honor::hk_honor_at_level(plr->getLevel(), winner_kills); - loser_kills = Trinity::Honor::hk_honor_at_level(plr->getLevel(), loser_kills); + winner_kills = Trinity::Honor::hk_honor_at_level(plr->getLevel(), float(winner_kills)); + loser_kills = Trinity::Honor::hk_honor_at_level(plr->getLevel(), float(loser_kills)); data->Initialize(SMSG_BATTLEFIELD_LIST); *data << uint64(guid); // battlemaster guid @@ -900,7 +900,6 @@ void BattlegroundMgr::BuildBattlegroundListPacket(WorldPacket *data, const uint6 else // battleground { size_t count_pos = data->wpos(); - uint32 count = 0; *data << uint32(0); // number of bg instances if (Battleground* bgTemplate = sBattlegroundMgr.GetBattlegroundTemplate(bgTypeId)) @@ -908,6 +907,7 @@ void BattlegroundMgr::BuildBattlegroundListPacket(WorldPacket *data, const uint6 // expected bracket entry if (PvPDifficultyEntry const* bracketEntry = GetBattlegroundBracketByLevel(bgTemplate->GetMapId(),plr->getLevel())) { + uint32 count = 0; BattlegroundBracketId bracketId = bracketEntry->GetBracketId(); for (std::set<uint32>::iterator itr = m_ClientBattlegroundIds[bgTypeId][bracketId].begin(); itr != m_ClientBattlegroundIds[bgTypeId][bracketId].end();++itr) { diff --git a/src/server/game/Battlegrounds/BattlegroundQueue.cpp b/src/server/game/Battlegrounds/BattlegroundQueue.cpp index ef664b24b8b..8078db8956b 100755 --- a/src/server/game/Battlegrounds/BattlegroundQueue.cpp +++ b/src/server/game/Battlegrounds/BattlegroundQueue.cpp @@ -258,7 +258,7 @@ void BattlegroundQueue::PlayerInvitedToBGUpdateAverageWaitTime(GroupQueueInfo* g (*lastPlayerAddedPointer) %= COUNT_OF_PLAYERS_TO_AVERAGE_WAIT_TIME; } -uint32 BattlegroundQueue::GetAverageQueueWaitTime(GroupQueueInfo* ginfo, BattlegroundBracketId bracket_id) +uint32 BattlegroundQueue::GetAverageQueueWaitTime(GroupQueueInfo* ginfo, BattlegroundBracketId bracket_id) const { uint8 team_index = BG_TEAM_ALLIANCE; //default set to BG_TEAM_ALLIANCE - or non rated arenas! if (!ginfo->ArenaType) diff --git a/src/server/game/Battlegrounds/BattlegroundQueue.h b/src/server/game/Battlegrounds/BattlegroundQueue.h index 5618746fcc5..bad3692d942 100755 --- a/src/server/game/Battlegrounds/BattlegroundQueue.h +++ b/src/server/game/Battlegrounds/BattlegroundQueue.h @@ -80,7 +80,7 @@ class BattlegroundQueue bool IsPlayerInvited(const uint64& pl_guid, const uint32 bgInstanceGuid, const uint32 removeTime); bool GetPlayerGroupInfoData(const uint64& guid, GroupQueueInfo* ginfo); void PlayerInvitedToBGUpdateAverageWaitTime(GroupQueueInfo* ginfo, BattlegroundBracketId bracket_id); - uint32 GetAverageQueueWaitTime(GroupQueueInfo* ginfo, BattlegroundBracketId bracket_id); + uint32 GetAverageQueueWaitTime(GroupQueueInfo* ginfo, BattlegroundBracketId bracket_id) const; typedef std::map<uint64, PlayerQueueInfo> QueuedPlayersMap; QueuedPlayersMap m_QueuedPlayers; diff --git a/src/server/game/Chat/Channels/Channel.cpp b/src/server/game/Chat/Channels/Channel.cpp index 30f9f95adfc..316d4e5ac99 100755 --- a/src/server/game/Chat/Channels/Channel.cpp +++ b/src/server/game/Chat/Channels/Channel.cpp @@ -624,10 +624,7 @@ void Channel::Say(uint64 p, const char *what, uint32 lang) if (sWorld.getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL)) lang = LANG_UNIVERSAL; - uint32 sec = 0; Player *plr = sObjectMgr.GetPlayer(p); - if (plr) - sec = plr->GetSession()->GetSecurity(); if (!IsOn(p)) { diff --git a/src/server/game/Chat/Channels/Channel.h b/src/server/game/Chat/Channels/Channel.h index 63f8fa6b502..5bbb8997ae8 100755 --- a/src/server/game/Chat/Channels/Channel.h +++ b/src/server/game/Chat/Channels/Channel.h @@ -123,21 +123,21 @@ class Channel uint64 player; uint8 flags; - bool HasFlag(uint8 flag) { return flags & flag; } + bool HasFlag(uint8 flag) const { return flags & flag; } void SetFlag(uint8 flag) { if (!HasFlag(flag)) flags |= flag; } - bool IsOwner() { return flags & MEMBER_FLAG_OWNER; } + bool IsOwner() const { return flags & MEMBER_FLAG_OWNER; } void SetOwner(bool state) { if (state) flags |= MEMBER_FLAG_OWNER; else flags &= ~MEMBER_FLAG_OWNER; } - bool IsModerator() { return flags & MEMBER_FLAG_MODERATOR; } + bool IsModerator() const { return flags & MEMBER_FLAG_MODERATOR; } void SetModerator(bool state) { if (state) flags |= MEMBER_FLAG_MODERATOR; else flags &= ~MEMBER_FLAG_MODERATOR; } - bool IsMuted() { return flags & MEMBER_FLAG_MUTED; } + bool IsMuted() const { return flags & MEMBER_FLAG_MUTED; } void SetMuted(bool state) { if (state) flags |= MEMBER_FLAG_MUTED; @@ -255,7 +255,7 @@ class Channel void SetAnnounce(bool nannounce) { m_announce = nannounce; } uint32 GetNumPlayers() const { return players.size(); } uint8 GetFlags() const { return m_flags; } - bool HasFlag(uint8 flag) { return m_flags & flag; } + bool HasFlag(uint8 flag) const { return m_flags & flag; } void Join(uint64 p, const char *pass); void Leave(uint64 p, bool send = true); diff --git a/src/server/game/Chat/Commands/Level2.cpp b/src/server/game/Chat/Commands/Level2.cpp index f1bc40d77bf..4124b54a7e8 100755 --- a/src/server/game/Chat/Commands/Level2.cpp +++ b/src/server/game/Chat/Commands/Level2.cpp @@ -205,7 +205,6 @@ bool ChatHandler::HandleDeMorphCommand(const char* /*args*/) //kick player bool ChatHandler::HandleKickPlayerCommand(const char *args) { - const char* kickName = strtok((char*)args, " "); Player* target = NULL; std::string playerName; if (!extractPlayerTarget((char*)args, &target, NULL, &playerName)) diff --git a/src/server/game/Chat/Commands/Level3.cpp b/src/server/game/Chat/Commands/Level3.cpp index 20b4ae7fc7a..5c321be6e08 100755 --- a/src/server/game/Chat/Commands/Level3.cpp +++ b/src/server/game/Chat/Commands/Level3.cpp @@ -57,7 +57,6 @@ #include "Transport.h" #include "WeatherMgr.h" #include "ScriptMgr.h" -#include "LFGMgr.h" #include "CreatureTextMgr.h" #include "SmartAI.h" #include "Group.h" @@ -2505,7 +2504,7 @@ static bool HandleResetStatsOrLevelHelper(Player* player) // reset m_form if no aura if (!player->HasAuraType(SPELL_AURA_MOD_SHAPESHIFT)) - player->m_form = FORM_NONE; + player->SetShapeshiftForm(FORM_NONE); player->SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE); player->SetFloatValue(UNIT_FIELD_COMBATREACH, DEFAULT_COMBAT_REACH); @@ -2515,11 +2514,10 @@ static bool HandleResetStatsOrLevelHelper(Player* player) player->SetUInt32Value(UNIT_FIELD_BYTES_0, ((player->getRace()) | (player->getClass() << 8) | (player->getGender() << 16) | (powertype << 24))); // reset only if player not in some form; - if (player->m_form == FORM_NONE) + if (player->GetShapeshiftForm() == FORM_NONE) player->InitDisplayIds(); player->SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP); - player->SetByteValue(UNIT_FIELD_BYTES_2, 3, player->m_form); player->SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE); diff --git a/src/server/game/Combat/ThreatManager.h b/src/server/game/Combat/ThreatManager.h index d93e3151eec..8e2ed7fe7d3 100755 --- a/src/server/game/Combat/ThreatManager.h +++ b/src/server/game/Combat/ThreatManager.h @@ -58,8 +58,8 @@ class HostileReference : public Reference<Unit, ThreatManager> void addThreatPercent(int32 pPercent) { float tmpThreat = iThreat; - tmpThreat = tmpThreat * (pPercent+100.0f) / 100.0f; - addThreat(tmpThreat-iThreat); + AddPctN(tmpThreat, pPercent); + addThreat(tmpThreat - iThreat); } float getThreat() const { return iThreat; } @@ -170,9 +170,9 @@ class ThreatContainer void setDirty(bool pDirty) { iDirty = pDirty; } - bool isDirty() { return iDirty; } + bool isDirty() const { return iDirty; } - bool empty() { return(iThreatList.empty()); } + bool empty() const { return(iThreatList.empty()); } HostileReference* getMostHated() { return iThreatList.empty() ? NULL : iThreatList.front(); } diff --git a/src/server/game/Conditions/ConditionMgr.h b/src/server/game/Conditions/ConditionMgr.h index d245483a6d7..538b4e92f1b 100755 --- a/src/server/game/Conditions/ConditionMgr.h +++ b/src/server/game/Conditions/ConditionMgr.h @@ -128,7 +128,7 @@ struct Condition } bool Meets(Player * player, Unit* invoker = NULL); - bool isLoaded() { return mConditionType > CONDITION_NONE || mReferenceId; } + bool isLoaded() const { return mConditionType > CONDITION_NONE || mReferenceId; } }; typedef std::list<Condition*> ConditionList; @@ -168,7 +168,7 @@ class ConditionMgr bool addToGossipMenuItems(Condition* cond); bool IsPlayerMeetToConditionList(Player* player,const ConditionList& conditions, Unit* invoker = NULL); - bool isGroupable(ConditionSourceType sourceType) + bool isGroupable(ConditionSourceType sourceType) const { return (sourceType == CONDITION_SOURCE_TYPE_CREATURE_LOOT_TEMPLATE || sourceType == CONDITION_SOURCE_TYPE_DISENCHANT_LOOT_TEMPLATE || diff --git a/src/server/game/DungeonFinding/LFG.h b/src/server/game/DungeonFinding/LFG.h index cf49f57aac9..5823970f795 100755 --- a/src/server/game/DungeonFinding/LFG.h +++ b/src/server/game/DungeonFinding/LFG.h @@ -18,6 +18,9 @@ #ifndef _LFG_H #define _LFG_H +#include "Common.h" +#include "SharedDefines.h" + enum LfgRoles { ROLE_NONE = 0x00, @@ -27,13 +30,6 @@ enum LfgRoles ROLE_DAMAGE = 0x08, }; -enum LfgState -{ - LFG_STATE_NONE = 0, // Not using LFG / LFR - LFG_STATE_LFG = 1, // Using Dungeon finder - LFG_STATE_LFR = 2, // Using Raid finder -}; - enum LfgUpdateType { LFG_UPDATETYPE_LEADER = 1, @@ -55,10 +51,10 @@ typedef std::set<uint32> LfgDungeonSet; struct LookingForGroup { - LookingForGroup(): roles(0), update(true), state(LFG_STATE_NONE) {} + LookingForGroup(): roles(0), state(LFG_STATE_NONE), oldState(LFG_STATE_NONE) {} uint8 roles; - bool update; LfgState state; + LfgState oldState; LfgDungeonSet applyDungeons; // Dungeons the player have applied for std::string comment; }; diff --git a/src/server/game/DungeonFinding/LFGMgr.cpp b/src/server/game/DungeonFinding/LFGMgr.cpp index 649d642375c..30cc7c52751 100755 --- a/src/server/game/DungeonFinding/LFGMgr.cpp +++ b/src/server/game/DungeonFinding/LFGMgr.cpp @@ -17,133 +17,60 @@ #include "Common.h" #include "SharedDefines.h" +#include "DBCStores.h" #include "DisableMgr.h" #include "ObjectMgr.h" #include "ProgressBar.h" #include "SocialMgr.h" #include "LFGMgr.h" +#include "LFGScripts.h" #include "Group.h" #include "Player.h" -// --- Temporal functions -// Added to try to find bugs that leaves data inconsistent -void LFGMgr::Cleaner() +LFGMgr::LFGMgr(): m_update(true), m_QueueTimer(0), m_lfgProposalId(1), +m_WaitTimeAvg(-1), m_WaitTimeTank(-1), m_WaitTimeHealer(-1), m_WaitTimeDps(-1), +m_NumWaitTimeAvg(0), m_NumWaitTimeTank(0), m_NumWaitTimeHealer(0), m_NumWaitTimeDps(0) { - LfgQueueInfoMap::iterator itQueue; - LfgGuidList::iterator itGuidListRemove; - LfgGuidList eraseList; - - for (LfgQueueInfoMap::iterator it = m_QueueInfoMap.begin(); it != m_QueueInfoMap.end();) - { - itQueue = it++; - // Remove empty queues - if (!itQueue->second) - { - sLog.outError("LFGMgr::Cleaner: removing [" UI64FMTD "] from QueueInfoMap, data is null", itQueue->first); - m_QueueInfoMap.erase(itQueue); - } - // Remove queue with empty players - else if(!itQueue->second->roles.size()) - { - sLog.outError("LFGMgr::Cleaner: removing [" UI64FMTD "] from QueueInfoMap, no players in queue!", itQueue->first); - m_QueueInfoMap.erase(itQueue); - } - } - - // Remove from NewToQueue those guids that do not exist in queueMap - for (LfgGuidList::iterator it = m_newToQueue.begin(); it != m_newToQueue.end();) + m_update = sWorld.getBoolConfig(CONFIG_DUNGEON_FINDER_ENABLE); + if (m_update) { - itGuidListRemove = it++; - if (m_QueueInfoMap.find(*itGuidListRemove) == m_QueueInfoMap.end()) - { - eraseList.push_back(*itGuidListRemove); - m_newToQueue.erase(itGuidListRemove); - sLog.outError("LFGMgr::Cleaner: removing [" UI64FMTD "] from newToQueue, no queue info with that guid", (*itGuidListRemove)); - } - } + new LFGScripts(); - // Remove from currentQueue those guids that do not exist in queueMap - for (LfgGuidList::iterator it = m_currentQueue.begin(); it != m_currentQueue.end();) - { - itGuidListRemove = it++; - if (m_QueueInfoMap.find(*itGuidListRemove) == m_QueueInfoMap.end()) + // Initialize dungeon cache + for (uint32 i = 0; i < sLFGDungeonStore.GetNumRows(); ++i) { - eraseList.push_back(*itGuidListRemove); - m_newToQueue.erase(itGuidListRemove); - sLog.outError("LFGMgr::Cleaner: removing [" UI64FMTD "] from currentQueue, no queue info with that guid", (*itGuidListRemove)); - } - } - - for (LfgGuidList::iterator it = eraseList.begin(); it != eraseList.end(); ++it) - { - if (IS_GROUP(*it)) - { - if (Group* grp = sObjectMgr.GetGroupByGUID(GUID_LOPART(*it))) - for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) - if (Player* plr = itr->getSource()) - plr->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_REMOVED_FROM_QUEUE); + LFGDungeonEntry const* dungeon = sLFGDungeonStore.LookupEntry(i); + if (dungeon && dungeon->type != LFG_TYPE_ZONE) + { + if (dungeon->type != LFG_TYPE_RANDOM) + m_CachedDungeonMap[dungeon->grouptype].insert(dungeon->ID); + m_CachedDungeonMap[0].insert(dungeon->ID); + } } - else - if (Player* plr = sObjectMgr.GetPlayer(*it)) - plr->GetSession()->SendLfgUpdatePlayer(LFG_UPDATETYPE_REMOVED_FROM_QUEUE); } } -LFGMgr::LFGMgr() -{ - m_QueueTimer = 0; - m_WaitTimeAvg = -1; - m_WaitTimeTank = -1; - m_WaitTimeHealer = -1; - m_WaitTimeDps = -1; - m_NumWaitTimeAvg = 0; - m_NumWaitTimeTank = 0; - m_NumWaitTimeHealer = 0; - m_NumWaitTimeDps = 0; - m_update = true; - m_lfgProposalId = 1; - GetAllDungeons(); -} - LFGMgr::~LFGMgr() { for (LfgRewardMap::iterator itr = m_RewardMap.begin(); itr != m_RewardMap.end(); ++itr) delete itr->second; - m_RewardMap.clear(); - - m_EncountersByAchievement.clear(); for (LfgQueueInfoMap::iterator it = m_QueueInfoMap.begin(); it != m_QueueInfoMap.end(); ++it) delete it->second; - m_QueueInfoMap.clear(); for (LfgProposalMap::iterator it = m_Proposals.begin(); it != m_Proposals.end(); ++it) delete it->second; - m_Proposals.clear(); for (LfgPlayerBootMap::iterator it = m_Boots.begin(); it != m_Boots.end(); ++it) delete it->second; - m_Boots.clear(); for (LfgRoleCheckMap::iterator it = m_RoleChecks.begin(); it != m_RoleChecks.end(); ++it) delete it->second; - m_RoleChecks.clear(); - - for (LfgDungeonMap::iterator it = m_CachedDungeonMap.begin(); it != m_CachedDungeonMap.end(); ++it) - delete it->second; - m_CachedDungeonMap.clear(); - - m_CompatibleMap.clear(); - m_QueueInfoMap.clear(); - m_currentQueue.clear(); - m_newToQueue.clear(); } -/// <summary> /// Load achievement <-> encounter associations -/// </summary> void LFGMgr::LoadDungeonEncounters() { m_EncountersByAchievement.clear(); @@ -199,9 +126,8 @@ void LFGMgr::LoadDungeonEncounters() sLog.outString(">> Loaded %u dungeon encounter lfg associations.", count); } -/// <summary> + /// Load rewards for completing dungeons -/// </summary> void LFGMgr::LoadRewards() { for (LfgRewardMap::iterator itr = m_RewardMap.begin(); itr != m_RewardMap.end(); ++itr) @@ -272,117 +198,108 @@ void LFGMgr::LoadRewards() void LFGMgr::Update(uint32 diff) { - if (!m_update || !sWorld.getBoolConfig(CONFIG_DUNGEON_FINDER_ENABLE)) + if (!m_update) return; m_update = false; time_t currTime = time(NULL); // Remove obsolete role checks - LfgRoleCheckMap::iterator itRoleCheck; - LfgRoleCheck* pRoleCheck; for (LfgRoleCheckMap::iterator it = m_RoleChecks.begin(); it != m_RoleChecks.end();) { - itRoleCheck = it++; - pRoleCheck = itRoleCheck->second; + LfgRoleCheckMap::iterator itRoleCheck = it++; + LfgRoleCheck* pRoleCheck = itRoleCheck->second; if (currTime < pRoleCheck->cancelTime) continue; pRoleCheck->result = LFG_ROLECHECK_MISSING_ROLE; - Player* plr = NULL; for (LfgRolesMap::const_iterator itRoles = pRoleCheck->roles.begin(); itRoles != pRoleCheck->roles.end(); ++itRoles) - { - plr = sObjectMgr.GetPlayerByLowGUID(itRoles->first); - if (!plr) - continue; - plr->GetSession()->SendLfgRoleCheckUpdate(pRoleCheck); - plr->GetLfgDungeons()->clear(); - plr->SetLfgRoles(ROLE_NONE); - if (!plr->GetGroup() || !plr->GetGroup()->isLFGGroup()) - plr->SetLfgState(LFG_STATE_NONE); + if (Player* plr = sObjectMgr.GetPlayerByLowGUID(itRoles->first)) + { + plr->GetSession()->SendLfgRoleCheckUpdate(pRoleCheck); + plr->ClearLfgState(); - if (itRoles->first == pRoleCheck->leader) - plr->GetSession()->SendLfgJoinResult(LFG_JOIN_FAILED, pRoleCheck->result); - } + if (itRoles->first == pRoleCheck->leader) + plr->GetSession()->SendLfgJoinResult(LFG_JOIN_FAILED, pRoleCheck->result); + } delete pRoleCheck; m_RoleChecks.erase(itRoleCheck); } // Remove obsolete proposals - LfgProposalMap::iterator itRemove; for (LfgProposalMap::iterator it = m_Proposals.begin(); it != m_Proposals.end();) { - itRemove = it++; + LfgProposalMap::iterator itRemove = it++; if (itRemove->second->cancelTime < currTime) RemoveProposal(itRemove, LFG_UPDATETYPE_PROPOSAL_FAILED); } // Remove obsolete kicks - LfgPlayerBootMap::iterator itBoot; - LfgPlayerBoot* pBoot; for (LfgPlayerBootMap::iterator it = m_Boots.begin(); it != m_Boots.end();) { - itBoot = it++; - pBoot = itBoot->second; + LfgPlayerBootMap::iterator itBoot = it++; + LfgPlayerBoot* pBoot = itBoot->second; if (pBoot->cancelTime < currTime) { - Group* grp = sObjectMgr.GetGroupByGUID(itBoot->first); pBoot->inProgress = false; for (LfgAnswerMap::const_iterator itVotes = pBoot->votes.begin(); itVotes != pBoot->votes.end(); ++itVotes) if (Player* plrg = sObjectMgr.GetPlayerByLowGUID(itVotes->first)) if (plrg->GetGUIDLow() != pBoot->victimLowGuid) plrg->GetSession()->SendLfgBootPlayer(pBoot); - if (grp) - grp->SetLfgKickActive(false); delete pBoot; m_Boots.erase(itBoot); } } - // Consistency cleaner - Cleaner(); - // Check if a proposal can be formed with the new groups being added - LfgProposal* pProposal = NULL; - LfgGuidList firstNew; - while (!m_newToQueue.empty()) + for (LfgGuidListMap::iterator it = m_newToQueue.begin(); it != m_newToQueue.end(); ++it) { - sLog.outDebug("LFGMgr::Update: checking [" UI64FMTD "] m_newToQueue(%u), m_currentQueue(%u)", m_newToQueue.front(), uint32(m_newToQueue.size()), uint32(m_currentQueue.size())); - firstNew.push_back(m_newToQueue.front()); - pProposal = FindNewGroups(firstNew, m_currentQueue); - if (pProposal) // Group found! + LfgGuidList& newToQueue = it->second; + LfgGuidList& currentQueue = m_currentQueue[it->first]; + LfgGuidList firstNew; + while (!newToQueue.empty()) { - // Remove groups in the proposal from new and current queues (not from queue map) - for (LfgGuidList::const_iterator it = pProposal->queues.begin(); it != pProposal->queues.end(); ++it) + sLog.outDebug("LFGMgr::Update: QueueId %u: checking [" UI64FMTD "] newToQueue(%u), currentQueue(%u)", it->first, newToQueue.front(), uint32(newToQueue.size()), uint32(currentQueue.size())); + firstNew.push_back(newToQueue.front()); + LfgGuidList temporalList = currentQueue; + if (LfgProposal* pProposal = FindNewGroups(firstNew, temporalList)) // Group found! { - m_currentQueue.remove(*it); - m_newToQueue.remove(*it); - } - m_Proposals[++m_lfgProposalId] = pProposal; + // Remove groups in the proposal from new and current queues (not from queue map) + for (LfgGuidList::const_iterator itQueue = pProposal->queues.begin(); itQueue != pProposal->queues.end(); ++itQueue) + { + currentQueue.remove(*itQueue); + newToQueue.remove(*itQueue); + } + m_Proposals[++m_lfgProposalId] = pProposal; - uint32 lowGuid = 0; - for (LfgProposalPlayerMap::const_iterator itPlayers = pProposal->players.begin(); itPlayers != pProposal->players.end(); ++itPlayers) - { - lowGuid = itPlayers->first; - if (Player* plr = sObjectMgr.GetPlayerByLowGUID(itPlayers->first)) + uint32 lowGuid = 0; + for (LfgProposalPlayerMap::const_iterator itPlayers = pProposal->players.begin(); itPlayers != pProposal->players.end(); ++itPlayers) { - if (plr->GetGroup()) - plr->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_PROPOSAL_BEGIN, plr->GetLfgDungeons(), plr->GetLfgComment()); - else - plr->GetSession()->SendLfgUpdatePlayer(LFG_UPDATETYPE_PROPOSAL_BEGIN, plr->GetLfgDungeons(), plr->GetLfgComment()); - plr->GetSession()->SendUpdateProposal(m_lfgProposalId, pProposal); + lowGuid = itPlayers->first; + if (Player* plr = sObjectMgr.GetPlayerByLowGUID(itPlayers->first)) + { + plr->SetLfgState(LFG_STATE_PROPOSAL); + if (plr->GetGroup()) + { + plr->GetGroup()->SetLfgState(LFG_STATE_PROPOSAL); + plr->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_PROPOSAL_BEGIN, plr->GetLfgDungeons(), plr->GetLfgComment()); + } + else + plr->GetSession()->SendLfgUpdatePlayer(LFG_UPDATETYPE_PROPOSAL_BEGIN, plr->GetLfgDungeons(), plr->GetLfgComment()); + plr->GetSession()->SendLfgUpdateProposal(m_lfgProposalId, pProposal); + } } - } - if (pProposal->state == LFG_PROPOSAL_SUCCESS) - UpdateProposal(m_lfgProposalId, lowGuid, true); - } - else - { - m_currentQueue.push_back(m_newToQueue.front()); // Group not found, add this group to the queue. - m_newToQueue.pop_front(); + if (pProposal->state == LFG_PROPOSAL_SUCCESS) + UpdateProposal(m_lfgProposalId, lowGuid, true); + } + else + { + currentQueue.push_back(newToQueue.front());// Group not found, add this group to the queue. + newToQueue.pop_front(); + } + firstNew.clear(); } - firstNew.clear(); } // Update all players status queue info @@ -390,26 +307,22 @@ void LFGMgr::Update(uint32 diff) { m_QueueTimer = 0; time_t currTime = time(NULL); - int32 waitTime; - LfgQueueInfo* queue; - uint32 dungeonId; - uint32 queuedTime; - uint8 role; for (LfgQueueInfoMap::const_iterator itQueue = m_QueueInfoMap.begin(); itQueue != m_QueueInfoMap.end(); ++itQueue) { - queue = itQueue->second; + LfgQueueInfo* queue = itQueue->second; if (!queue) { sLog.outError("LFGMgr::Update: [" UI64FMTD "] queued with null queue info!", itQueue->first); continue; } - dungeonId = (*queue->dungeons.begin()); - queuedTime = uint32(currTime - queue->joinTime); - role = ROLE_NONE; + uint32 dungeonId = (*queue->dungeons.begin()); + uint32 queuedTime = uint32(currTime - queue->joinTime); + uint8 role = ROLE_NONE; for (LfgRolesMap::const_iterator itPlayer = queue->roles.begin(); itPlayer != queue->roles.end(); ++itPlayer) role |= itPlayer->second; role &= ~ROLE_LEADER; + int32 waitTime = -1; switch(role) { case ROLE_NONE: // Should not happen - just in case @@ -439,45 +352,43 @@ void LFGMgr::Update(uint32 diff) m_update = true; } -/// <summary> -/// Add a guid to new queue, checks consistency -/// </summary> -/// <param name="uint64">Player or group guid</param> -void LFGMgr::AddGuidToNewQueue(uint64 guid) -{ - // Consistency check - LfgGuidList::iterator it = std::find(m_newToQueue.begin(), m_newToQueue.end(), guid); +/** + Add a guid to the queue of guids to be added to main queue. It guid its already + in queue does nothing. If this function is called guid is not in the main queue + (No need to check it here) - if (it != m_newToQueue.end()) - { - sLog.outError("LFGMgr::AddGuidToNewQueue: [" UI64FMTD "] being added to queue and it was already added. ignoring", guid); - return; - } + @param[in] guid Player or group guid to add to queue + @param[in] queueId Queue Id to add player/group to +*/ +void LFGMgr::AddToQueue(uint64& guid, uint8 queueId) +{ + if (sWorld.getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP)) + queueId = 0; - it = std::find(m_currentQueue.begin(), m_currentQueue.end(), guid); - if (it != m_currentQueue.end()) + LfgGuidList& list = m_newToQueue[queueId]; + if (std::find(list.begin(), list.end(), guid) != list.end()) + sLog.outDebug("LFGMgr::AddToQueue: [" UI64FMTD "] already in new queue. ignoring", guid); + else { - sLog.outError("LFGMgr::AddGuidToNewQueue: [" UI64FMTD "] being added to queue and already in current queue (removing to readd)", guid); - m_currentQueue.erase(it); + list.push_back(guid); + sLog.outDebug("LFGMgr::AddToQueue: [" UI64FMTD "] added to m_newToQueue (size: %u)", guid, uint32(list.size())); } - - // Add to queue - m_newToQueue.push_back(guid); - sLog.outDebug("LFGMgr::AddGuidToNewQueue: [" UI64FMTD "] added to m_newToQueue (size: %u)", guid, uint32(m_newToQueue.size())); } -/// <summary> -/// Removes the player/group from all queues -/// </summary> -/// <param name="uint64">Player or group guid</param> -/// <returns>bool</returns> -bool LFGMgr::RemoveFromQueue(uint64 guid) +/** + Removes a guid from the main and new queues. + + @param[in] guid Player or group guid to add to queue + @return true if guid was found in main queue. +*/ +bool LFGMgr::RemoveFromQueue(uint64& guid) { - bool ret = false; - uint32 before = m_QueueInfoMap.size(); + for (LfgGuidListMap::iterator it = m_currentQueue.begin(); it != m_currentQueue.end(); ++it) + it->second.remove(guid); + + for (LfgGuidListMap::iterator it = m_newToQueue.begin(); it != m_newToQueue.end(); ++it) + it->second.remove(guid); - m_currentQueue.remove(guid); - m_newToQueue.remove(guid); RemoveFromCompatibles(guid); LfgQueueInfoMap::iterator it = m_QueueInfoMap.find(guid); @@ -485,17 +396,30 @@ bool LFGMgr::RemoveFromQueue(uint64 guid) { delete it->second; m_QueueInfoMap.erase(it); - ret = true; + sLog.outDebug("LFGMgr::RemoveFromQueue: [" UI64FMTD "] removed", guid); + return true; } - sLog.outDebug("LFGMgr::RemoveFromQueue: [" UI64FMTD "] %s - Queue(%u)", guid, - before != m_QueueInfoMap.size() ? "Removed" : "Not in queue", uint32(m_QueueInfoMap.size())); - return ret; + else + { + sLog.outDebug("LFGMgr::RemoveFromQueue: [" UI64FMTD "] not in queue", guid); + return false; + } + } -/// Adds the player/group to lfg queue -void LFGMgr::Join(Player* plr, uint8 roles, LfgDungeonSet* dungeons, std::string comment) +/** + Adds the player/group to lfg queue. If player is in a group then it is the leader + of the group tying to join the group. Join conditions are checked before adding + to the new queue. + + @param[in] plr Player trying to join (or leader of group trying to join) + @param[in] roles Player selected roles + @param[in] dungeons Dungeons the player/group is applying for + @param[in] comment Player selected comment +*/ +void LFGMgr::Join(Player* plr, uint8 roles, LfgDungeonSet& dungeons, std::string& comment) { - if (!plr || !plr->GetSession() || !dungeons || !dungeons->size()) + if (!plr || !plr->GetSession() || !dungeons.size()) return; Group* grp = plr->GetGroup(); @@ -504,13 +428,13 @@ void LFGMgr::Join(Player* plr, uint8 roles, LfgDungeonSet* dungeons, std::string LfgJoinResult result = LFG_JOIN_OK; PlayerSet players; uint32 rDungeonId = 0; - bool isContinue = grp && grp->isLFGGroup() && !grp->isLfgDungeonComplete(); + bool isContinue = grp && grp->isLFGGroup() && grp->GetLfgState() != LFG_STATE_FINISHED_DUNGEON; // Do not allow to change dungeon in the middle of a current dungeon if (isContinue) { - dungeons->clear(); - dungeons->insert(grp->GetLfgDungeonEntry()); + dungeons.clear(); + dungeons.insert(grp->GetLfgDungeonEntry()); } // Already in queue? @@ -519,7 +443,7 @@ void LFGMgr::Join(Player* plr, uint8 roles, LfgDungeonSet* dungeons, std::string { bool sameDungeons = true; for (LfgDungeonSet::const_iterator it = plr->GetLfgDungeons()->begin(); it != plr->GetLfgDungeons()->end() && sameDungeons; ++it) - if (dungeons->find(*it) == dungeons->end()) + if (dungeons.find(*it) == dungeons.end()) sameDungeons = false; if (sameDungeons) // Joining the same dungeons -- Send OK @@ -529,19 +453,16 @@ void LFGMgr::Join(Player* plr, uint8 roles, LfgDungeonSet* dungeons, std::string { for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) if (itr->getSource() && itr->getSource()->GetSession()) - itr->getSource()->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_ADDED_TO_QUEUE, dungeons, comment); + itr->getSource()->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_ADDED_TO_QUEUE, &dungeons, comment); } - dungeons->clear(); - delete dungeons; - return; } else if (!isContinue) // Different dungeons and it's not an offer to continue { // Different dungeons and it's not a LfgGroup in the middle of a dungeon that need more people Leave(plr, grp); Join(plr, roles, dungeons, comment); - return; } + return; } // Check player or group member restrictions @@ -551,7 +472,7 @@ void LFGMgr::Join(Player* plr, uint8 roles, LfgDungeonSet* dungeons, std::string result = LFG_JOIN_DESERTER; else if (plr->HasAura(LFG_SPELL_DUNGEON_COOLDOWN)) result = LFG_JOIN_RANDOM_COOLDOWN; - else if (!dungeons || !dungeons->size()) + else if (!dungeons.size()) result = LFG_JOIN_NOT_MEET_REQS; else if (grp) { @@ -559,12 +480,10 @@ void LFGMgr::Join(Player* plr, uint8 roles, LfgDungeonSet* dungeons, std::string result = LFG_JOIN_TOO_MUCH_MEMBERS; else { - Player* plrg; uint8 memberCount = 0; for (GroupReference* itr = grp->GetFirstMember(); itr != NULL && result == LFG_JOIN_OK; itr = itr->next()) { - plrg = itr->getSource(); - if (plrg) + if (Player* plrg = itr->getSource()) { if (plrg->HasAura(LFG_SPELL_DUNGEON_DESERTER)) result = LFG_JOIN_PARTY_DESERTER; @@ -588,15 +507,15 @@ void LFGMgr::Join(Player* plr, uint8 roles, LfgDungeonSet* dungeons, std::string if (result == LFG_JOIN_OK) { bool isDungeon = false; - for (LfgDungeonSet::const_iterator it = dungeons->begin(); it != dungeons->end() && result == LFG_JOIN_OK; ++it) + for (LfgDungeonSet::const_iterator it = dungeons.begin(); it != dungeons.end() && result == LFG_JOIN_OK; ++it) { switch(GetDungeonType(*it)) { case LFG_TYPE_RANDOM: - if (dungeons->size() > 1) // Only allow 1 random dungeon + if (dungeons.size() > 1) // Only allow 1 random dungeon result = LFG_JOIN_DUNGEON_INVALID; else - rDungeonId = (*dungeons->begin()); + rDungeonId = (*dungeons.begin()); // No break on purpose (Random can only be dungeon or heroic dungeon) case LFG_TYPE_HEROIC: case LFG_TYPE_DUNGEON: @@ -617,14 +536,22 @@ void LFGMgr::Join(Player* plr, uint8 roles, LfgDungeonSet* dungeons, std::string // Expand random dungeons and check restrictions if (rDungeonId) + GetDungeonsByRandom(rDungeonId, dungeons); + + LfgLockStatusMap* lockStatusMap = CheckCompatibleDungeons(dungeons, players); + if (!dungeons.size()) + { + sLog.outDebug("LFGMgr::Join: [" UI64FMTD "] joining with %u members. result: LFG_JOIN_PARTY_NOT_MEET_REQS", guid, uint8(players.size())); + plr->GetSession()->SendLfgJoinResult(LFG_JOIN_PARTY_NOT_MEET_REQS, 0, lockStatusMap); + } + if (lockStatusMap) { - dungeons->clear(); - delete dungeons; - dungeons = GetDungeonsByRandom(rDungeonId); + for (LfgLockStatusMap::iterator it = lockStatusMap->begin(); it != lockStatusMap->end(); ++it) + delete it->second; + delete lockStatusMap; } - CheckCompatibleDungeons(dungeons, &players, false); - if (!dungeons || !dungeons->size()) - result = LFG_JOIN_NOT_MEET_REQS; + if (!dungeons.size()) + return; } // Can't join. Send result @@ -632,10 +559,6 @@ void LFGMgr::Join(Player* plr, uint8 roles, LfgDungeonSet* dungeons, std::string { sLog.outDebug("LFGMgr::Join: [" UI64FMTD "] joining with %u members. result: %u", guid, grp ? grp->GetMembersCount() : 1, result); plr->GetSession()->SendLfgJoinResult(result); - if (dungeons) - dungeons->clear(); - delete dungeons; - dungeons = NULL; return; } @@ -643,74 +566,70 @@ void LFGMgr::Join(Player* plr, uint8 roles, LfgDungeonSet* dungeons, std::string if (isRaid) { sLog.outDebug("LFGMgr::Join: [" UI64FMTD "] trying to join raid browser and it's disabled.", guid); - dungeons->clear(); - delete dungeons; - dungeons = NULL; return; } - // All ok, Update player info - if (!isContinue) - { - plr->GetLfgDungeons()->clear(); - if (rDungeonId) - plr->GetLfgDungeons()->insert(rDungeonId); - else - for (LfgDungeonSet::const_iterator it = dungeons->begin(); it != dungeons->end(); ++it) - plr->GetLfgDungeons()->insert(*it); - } - plr->SetLfgComment(comment); plr->SetLfgRoles(roles); if (grp) // Begin rolecheck { + // Create new rolecheck LfgRoleCheck* pRoleCheck = new LfgRoleCheck(); pRoleCheck->cancelTime = time_t(time(NULL)) + LFG_TIME_ROLECHECK; pRoleCheck->result = LFG_ROLECHECK_INITIALITING; pRoleCheck->leader = plr->GetGUIDLow(); + pRoleCheck->dungeons = dungeons; + pRoleCheck->rDungeonId = rDungeonId; m_RoleChecks[grp->GetLowGUID()] = pRoleCheck; - if (isContinue) - { - dungeons->clear(); - dungeons->insert(grp->GetLfgDungeonEntry()); - } - else if (rDungeonId) + if (rDungeonId) { - dungeons->clear(); - dungeons->insert(rDungeonId); + dungeons.clear(); + dungeons.insert(rDungeonId); } - for (LfgDungeonSet::const_iterator it = dungeons->begin(); it != dungeons->end(); ++it) - pRoleCheck->dungeons.insert(*it); - Player* plrg; + grp->SetLfgState(LFG_STATE_ROLECHECK); + // Send update to player for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) { - plrg = itr->getSource(); - if (!plrg) - continue; - - plrg->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_JOIN_PROPOSAL, dungeons, comment); - plrg->SetLfgState(LFG_STATE_LFG); - if (!isContinue) + if (Player* plrg = itr->getSource()) { - plrg->GetLfgDungeons()->clear(); - for (LfgDungeonSet::const_iterator it = dungeons->begin(); it != dungeons->end(); ++it) - plrg->GetLfgDungeons()->insert(*it); + plrg->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_JOIN_PROPOSAL, &dungeons, comment); + plrg->SetLfgState(LFG_STATE_ROLECHECK); + if (!isContinue) + { + plrg->GetLfgDungeons()->clear(); + for (LfgDungeonSet::const_iterator it = dungeons.begin(); it != dungeons.end(); ++it) + plrg->GetLfgDungeons()->insert(*it); + } + pRoleCheck->roles[plrg->GetGUIDLow()] = 0; } - pRoleCheck->roles[plrg->GetGUIDLow()] = 0; } + // Update leader role UpdateRoleCheck(grp, plr, true); } else // Add player to queue { + // Send update to player plr->GetSession()->SendLfgJoinResult(LFG_JOIN_OK); - plr->GetSession()->SendLfgUpdatePlayer(LFG_UPDATETYPE_JOIN_PROPOSAL, dungeons, comment); - plr->SetLfgState(LFG_STATE_LFG); + plr->GetSession()->SendLfgUpdatePlayer(LFG_UPDATETYPE_JOIN_PROPOSAL, &dungeons, comment); + plr->SetLfgState(LFG_STATE_QUEUED); + if (!isContinue) + { + plr->GetLfgDungeons()->clear(); + if (rDungeonId) + plr->GetLfgDungeons()->insert(rDungeonId); + else + for (LfgDungeonSet::const_iterator it = dungeons.begin(); it != dungeons.end(); ++it) + plr->GetLfgDungeons()->insert(*it); + } + + // Queue player LfgQueueInfo* pqInfo = new LfgQueueInfo(); pqInfo->joinTime = time_t(time(NULL)); pqInfo->roles[plr->GetGUIDLow()] = plr->GetLfgRoles(); + pqInfo->dungeons = dungeons; uint8 roles = plr->GetLfgRoles(); if (roles & ROLE_TANK) --pqInfo->tanks; @@ -718,112 +637,111 @@ void LFGMgr::Join(Player* plr, uint8 roles, LfgDungeonSet* dungeons, std::string --pqInfo->healers; else --pqInfo->dps; - for (LfgDungeonSet::const_iterator it = dungeons->begin(); it != dungeons->end(); ++it) - pqInfo->dungeons.insert(*it); + m_QueueInfoMap[guid] = pqInfo; - AddGuidToNewQueue(guid); + AddToQueue(guid, uint8(plr->GetTeam())); } - std::string dungeonsstr = ConcatenateDungeons(dungeons); - sLog.outDebug("LFGMgr::Join: [" UI64FMTD "] joined with %u members. dungeons: %s", guid, grp ? grp->GetMembersCount() : 1, dungeonsstr.c_str()); - dungeons->clear(); - delete dungeons; - dungeons = NULL; + sLog.outDebug("LFGMgr::Join: [" UI64FMTD "] joined with %u members. dungeons: %u", guid, grp ? grp->GetMembersCount() : 1, uint8(dungeons.size())); } -/// <summary> -/// Leave the lfg queue -/// </summary> -/// <param name="Player*">Player (could be NULL)</param> -/// <param name="Group*">Group (could be NULL)</param> +/** + 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 + + @param[in] plr Player trying to leave (can be NULL) + @param[in] grp Group trying to leave (default NULL) +*/ void LFGMgr::Leave(Player* plr, Group* grp /* = NULL*/) { - if ((plr && (!plr->GetLfgUpdate() || !plr->isUsingLfg())) || !sWorld.getBoolConfig(CONFIG_DUNGEON_FINDER_ENABLE)) + if (!plr && !grp) return; - uint64 guid = grp ? grp->GetGUID() : plr ? plr->GetGUID() : 0; - sLog.outDebug("LFGMgr::Leave: [" UI64FMTD "]", guid); - - if (!guid) - return; + uint64 guid = 0; + LfgState state; - // Remove from Role Checks if (grp) { - grp->SetLfgQueued(false); - LfgRoleCheckMap::const_iterator itRoleCheck = m_RoleChecks.find(GUID_LOPART(guid)); - if (itRoleCheck != m_RoleChecks.end()) - { - UpdateRoleCheck(grp); // No player to update role = LFG_ROLECHECK_ABORTED - return; - } + guid = grp->GetGUID(); + state = grp->GetLfgState(); } - - // Remove from Proposals - bool proposalFound = false; - LfgProposalMap::iterator it = m_Proposals.begin(); - while (it != m_Proposals.end() && !proposalFound) + else { - // Mark the player/leader of group who left as didn't accept the proposal - for (LfgProposalPlayerMap::iterator itPlayer = it->second->players.begin(); itPlayer != it->second->players.end(); ++itPlayer) - { - if ((plr && itPlayer->first == plr->GetGUIDLow()) || (grp && itPlayer->first == GUID_LOPART(grp->GetLeaderGUID()))) - { - itPlayer->second->accept = LFG_ANSWER_DENY; - proposalFound = true; - } - } - if (!proposalFound) - ++it; + guid = plr->GetGUID(); + state = plr->GetLfgState(); } - // Remove from queue - if proposal is found, RemoveProposal will call RemoveFromQueue - if (proposalFound) - RemoveProposal(it, LFG_UPDATETYPE_PROPOSAL_DECLINED); - else - RemoveFromQueue(guid); - - if (grp) + sLog.outDebug("LFGMgr::Leave: [" UI64FMTD "]", guid); + switch(state) { - for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) - if (Player* plrg = itr->getSource()) + case LFG_STATE_QUEUED: + RemoveFromQueue(guid); + if (grp) { - plrg->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_REMOVED_FROM_QUEUE); - plrg->GetLfgDungeons()->clear(); - plrg->SetLfgRoles(ROLE_NONE); - plrg->SetLfgState(LFG_STATE_NONE); + grp->RestoreLfgState(); + for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) + if (Player* plrg = itr->getSource()) + { + plrg->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_REMOVED_FROM_QUEUE); + plrg->ClearLfgState(); + } } - } - else - { - plr->GetSession()->SendLfgUpdatePlayer(LFG_UPDATETYPE_REMOVED_FROM_QUEUE); - plr->GetLfgDungeons()->clear(); - plr->SetLfgRoles(ROLE_NONE); - plr->SetLfgState(LFG_STATE_NONE); - plr->RemoveAurasDueToSpell(LFG_SPELL_LUCK_OF_THE_DRAW); + else + { + plr->GetSession()->SendLfgUpdatePlayer(LFG_UPDATETYPE_REMOVED_FROM_QUEUE); + plr->ClearLfgState(); + } + break; + case LFG_STATE_ROLECHECK: + if (grp) + UpdateRoleCheck(grp); // No player to update role = LFG_ROLECHECK_ABORTED + break; + case LFG_STATE_PROPOSAL: + { + // Remove from Proposals + LfgProposalMap::iterator it = m_Proposals.begin(); + uint32 lowguid = plr ? plr->GetGUIDLow() : GUID_LOPART(grp->GetLeaderGUID()); + while (it != m_Proposals.end()) + { + LfgProposalPlayerMap::iterator itPlayer = it->second->players.find(lowguid); + if (itPlayer != it->second->players.end()) + { + // Mark the player/leader of group who left as didn't accept the proposal + itPlayer->second->accept = LFG_ANSWER_DENY; + break; + } + ++it; + } + + // Remove from queue - if proposal is found, RemoveProposal will call RemoveFromQueue + if (it != m_Proposals.end()) + RemoveProposal(it, LFG_UPDATETYPE_PROPOSAL_DECLINED); + break; + } + default: + break; } } -/// <summary> -/// Given a Lfg group checks if leader needs to be show the popup to select more players -/// </summary> -/// <param name="Group*">Group than needs new players</param> +/** + Sends the leader of a group the offer to continue popup + + @param[in] grp Group to send offer to +*/ void LFGMgr::OfferContinue(Group* grp) { - if (!sWorld.getBoolConfig(CONFIG_DUNGEON_FINDER_ENABLE)) - return; - - ASSERT(grp); - if (Player* leader = sObjectMgr.GetPlayer(grp->GetLeaderGUID())) + Player* leader = grp ? sObjectMgr.GetPlayer(grp->GetLeaderGUID()) : NULL; + if (leader) leader->GetSession()->SendLfgOfferContinue(grp->GetLfgDungeonEntry(false)); } -/// <summary> -/// Check the queue to try to match groups. Returns all the possible matches -/// </summary> -/// <param name="LfgGuidList &">Guids we trying to match with the rest of groups</param> -/// <param name="LfgGuidList">All guids in queue</param> -/// <returns>LfgProposal*</returns> -LfgProposal* LFGMgr::FindNewGroups(LfgGuidList check, LfgGuidList all) +/** + Checks que main queue to try to form a Lfg group. Returns first match found (if any) + + @param[in] check List of guids trying to match with other groups + @param[in] all List of all other guids in main queue to match against + @return Pointer to proposal, if match is found +*/ +LfgProposal* LFGMgr::FindNewGroups(LfgGuidList& check, LfgGuidList& all) { sLog.outDebug("LFGMgr::FindNewGroup: (%s) - all(%s)", ConcatenateGuids(check).c_str(), ConcatenateGuids(all).c_str()); @@ -842,15 +760,16 @@ LfgProposal* LFGMgr::FindNewGroups(LfgGuidList check, LfgGuidList all) return pProposal; } -/// <summary> -/// Check compatibilities between groups. -/// </summary> -/// <param name="LfgGuidList">Guids we checking compatibility</param> -/// <returns>bool</returns> -/// <param name="LfgProposal*&">Proposals found.</param> +/** + Check compatibilities between groups + + @param[in] check List of guids to check compatibilities + @param[out] pProposal Proposal found if groups are compatibles and Match + @return true if group are compatibles +*/ bool LFGMgr::CheckCompatibility(LfgGuidList check, LfgProposal*& pProposal) { - if (pProposal) // Do not check anything if we already have a proposal + if (pProposal) // Do not check anything if we already have a proposal return false; std::string strGuids = ConcatenateGuids(check); @@ -893,22 +812,22 @@ bool LFGMgr::CheckCompatibility(LfgGuidList check, LfgProposal*& pProposal) uint8 numLfgGroups = 0; uint32 groupLowGuid = 0; LfgQueueInfoMap pqInfoMap; - LfgQueueInfoMap::iterator itQueue; for (LfgGuidList::const_iterator it = check.begin(); it != check.end() && numLfgGroups < 2 && numPlayers <= MAXGROUPSIZE; ++it) { - itQueue = m_QueueInfoMap.find(*it); + uint64 guid = (*it); + LfgQueueInfoMap::iterator itQueue = m_QueueInfoMap.find(guid); if (itQueue == m_QueueInfoMap.end()) { sLog.outError("LFGMgr::CheckCompatibility: [" UI64FMTD "] is not queued but listed as queued!", (*it)); - RemoveFromQueue(*it); + RemoveFromQueue(guid); return false; } - pqInfoMap[*it] = itQueue->second; + pqInfoMap[guid] = itQueue->second; numPlayers += itQueue->second->roles.size(); - if (IS_GROUP(*it)) + if (IS_GROUP(guid)) { - uint32 lowGuid = GUID_LOPART(*it); + uint32 lowGuid = GUID_LOPART(guid); if (Group* grp = sObjectMgr.GetGroupByGUID(lowGuid)) if (grp->isLFGGroup()) { @@ -919,16 +838,12 @@ bool LFGMgr::CheckCompatibility(LfgGuidList check, LfgProposal*& pProposal) } } - if (check.size() == 1) - { - if (numPlayers != MAXGROUPSIZE) // Single group with less than MAXGROUPSIZE - Compatibles - return true; - } + if (check.size() == 1 && numPlayers != MAXGROUPSIZE) // Single group with less than MAXGROUPSIZE - Compatibles + return true; // Do not match - groups already in a lfgDungeon or too much players if (numLfgGroups > 1 || numPlayers > MAXGROUPSIZE) { - pqInfoMap.clear(); SetCompatibles(strGuids, false); if (numLfgGroups > 1) sLog.outDebug("LFGMgr::CheckCompatibility: (%s) More than one Lfggroup (%u)", strGuids.c_str(), numLfgGroups); @@ -947,45 +862,18 @@ bool LFGMgr::CheckCompatibility(LfgGuidList check, LfgProposal*& pProposal) // Assign new leader if (itRoles->second & ROLE_LEADER && (!newLeaderLowGuid || urand(0, 1))) newLeaderLowGuid = itRoles->first; - if (rolesMap[itRoles->first]) // Player already added! - { - // Find the other guid - uint64 guid1 = it->first; - uint64 guid2 = 0; - for (LfgQueueInfoMap::const_iterator it2 = pqInfoMap.begin(); it2 != it && !guid2; ++it2) - { - if (it2->second->roles.find(itRoles->first) != it2->second->roles.end()) - guid2 = it2->first; - } - uint64 playerguid; - // store in guid2 the obsolete group - if (pqInfoMap[guid2]->joinTime > it->second->joinTime) - { - playerguid = guid2; - guid2 = guid1; - guid1 = playerguid; - } - playerguid = MAKE_NEW_GUID(itRoles->first, 0, HIGHGUID_PLAYER); - sLog.outError("LFGMgr::CheckCompatibility: check(%s) player [" UI64FMTD "] in queue with [" UI64FMTD "] and OBSOLETE! [" UI64FMTD "]", - strGuids.c_str(), playerguid, guid1, guid2); - } rolesMap[itRoles->first] = itRoles->second; } } - if (rolesMap.size() != numPlayers) - { - pqInfoMap.clear(); - rolesMap.clear(); + if (rolesMap.size() != numPlayers) // Player in multiples queues! return false; - } - Player* plr; PlayerSet players; for (LfgRolesMap::const_iterator it = rolesMap.begin(); it != rolesMap.end(); ++it) { - plr = sObjectMgr.GetPlayerByLowGUID(it->first); + Player* plr = sObjectMgr.GetPlayerByLowGUID(it->first); if (!plr) sLog.outDebug("LFGMgr::CheckCompatibility: (%s) Warning! %u offline! Marking as not compatibles!", strGuids.c_str(), it->first); else @@ -998,12 +886,6 @@ bool LFGMgr::CheckCompatibility(LfgGuidList check, LfgProposal*& pProposal) sLog.outDebug("LFGMgr::CheckCompatibility: (%s) Players [" UI64FMTD "] and [" UI64FMTD "] ignoring", strGuids.c_str(), (*itPlayer)->GetGUID(), plr->GetGUID()); plr = NULL; } - // neither with diferent faction if it's not a mixed faction server - else if (plr->GetTeam() != (*itPlayer)->GetTeam() && !sWorld.getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP)) - { - sLog.outDebug("LFGMgr::CheckCompatibility: (%s) Players [" UI64FMTD "] and [" UI64FMTD "] are from diff sides", strGuids.c_str(), (*itPlayer)->GetGUID(), plr->GetGUID()); - plr = NULL; - } } if (plr) players.insert(plr); @@ -1016,28 +898,29 @@ bool LFGMgr::CheckCompatibility(LfgGuidList check, LfgProposal*& pProposal) { if (players.size() == numPlayers) sLog.outDebug("LFGMgr::CheckCompatibility: (%s) Roles not compatible", strGuids.c_str()); - pqInfoMap.clear(); - rolesMap.clear(); - players.clear(); SetCompatibles(strGuids, false); return false; } // ----- Selected Dungeon checks ----- // Check if there are any compatible dungeon from the selected dungeons - LfgDungeonMap dungeonMap; - for (LfgQueueInfoMap::const_iterator it = pqInfoMap.begin(); it != pqInfoMap.end(); ++it) - dungeonMap[it->first] = &it->second->dungeons; + LfgDungeonSet compatibleDungeons; + + LfgQueueInfoMap::const_iterator itFirst = pqInfoMap.begin(); + for (LfgDungeonSet::const_iterator itDungeon = itFirst->second->dungeons.begin(); itDungeon != itFirst->second->dungeons.end(); ++itDungeon) + { + LfgQueueInfoMap::const_iterator itOther = itFirst; + ++itOther; + while(itOther != pqInfoMap.end() && itOther->second->dungeons.find(*itDungeon) != itOther->second->dungeons.end()) + ++itOther; + + if (itOther == pqInfoMap.end()) + compatibleDungeons.insert(*itDungeon); + } + CheckCompatibleDungeons(compatibleDungeons, players, false); - LfgDungeonSet* compatibleDungeons = CheckCompatibleDungeons(&dungeonMap, &players); - dungeonMap.clear(); - pqInfoMap.clear(); - if (!compatibleDungeons || !compatibleDungeons->size()) + if (!compatibleDungeons.size()) { - if (compatibleDungeons) - delete compatibleDungeons; - players.clear(); - rolesMap.clear(); SetCompatibles(strGuids, false); return false; } @@ -1046,8 +929,6 @@ bool LFGMgr::CheckCompatibility(LfgGuidList check, LfgProposal*& pProposal) // ----- Group is compatible, if we have MAXGROUPSIZE members then match is found if (numPlayers != MAXGROUPSIZE) { - players.clear(); - rolesMap.clear(); sLog.outDebug("LFGMgr::CheckCompatibility: (%s) Compatibles but not match. Players(%u)", strGuids.c_str(), numPlayers); return true; } @@ -1059,26 +940,18 @@ bool LFGMgr::CheckCompatibility(LfgGuidList check, LfgProposal*& pProposal) // Select a random dungeon from the compatible list // TODO - Select the dungeon based on group item Level, not just random - LfgDungeonSet::iterator itDungeon = compatibleDungeons->begin(); - uint32 selectedDungeon = urand(0, compatibleDungeons->size() - 1); - while (selectedDungeon > 0) - { + LfgDungeonSet::const_iterator itDungeon = compatibleDungeons.begin(); + for (uint8 i = 0; i < urand(0, compatibleDungeons.size() - 1); ++i) ++itDungeon; - --selectedDungeon; - } - selectedDungeon = (*itDungeon); - compatibleDungeons->clear(); - delete compatibleDungeons; // Create a new proposal - pProposal = new LfgProposal(selectedDungeon); + pProposal = new LfgProposal(*itDungeon); pProposal->cancelTime = time_t(time(NULL)) + LFG_TIME_PROPOSAL; + pProposal->state = LFG_PROPOSAL_INITIATING; pProposal->queues = check; pProposal->groupLowGuid = groupLowGuid; // Assign new roles to players and assign new leader - LfgProposalPlayer* ppPlayer; - uint32 lowGuid; PlayerSet::const_iterator itPlayers = players.begin(); if (!newLeaderLowGuid) { @@ -1092,13 +965,12 @@ bool LFGMgr::CheckCompatibility(LfgGuidList check, LfgProposal*& pProposal) uint8 numAccept = 0; for (itPlayers = players.begin(); itPlayers != players.end(); ++itPlayers) { - lowGuid = (*itPlayers)->GetGUIDLow(); - ppPlayer = new LfgProposalPlayer(); - Group* grp = (*itPlayers)->GetGroup(); - if (grp) + uint32 lowGuid = (*itPlayers)->GetGUIDLow(); + LfgProposalPlayer* ppPlayer = new LfgProposalPlayer(); + if (Group* grp = (*itPlayers)->GetGroup()) { ppPlayer->groupLowGuid = grp->GetLowGUID(); - if (grp->GetLfgDungeonEntry() == selectedDungeon && ppPlayer->groupLowGuid == pProposal->groupLowGuid) // Player from existing group, autoaccept + if (grp->isLFGGroup()) // Player from existing group, autoaccept { ppPlayer->accept = LFG_ANSWER_AGREE; ++numAccept; @@ -1110,205 +982,155 @@ bool LFGMgr::CheckCompatibility(LfgGuidList check, LfgProposal*& pProposal) if (numAccept == MAXGROUPSIZE) pProposal->state = LFG_PROPOSAL_SUCCESS; - rolesMap.clear(); - players.clear(); return true; } -/// Update the Role check info with the player selected role. +/** + Update the Role check info with the player selected role. + + @param[in] grp Group to update rolecheck + @param[in] plr Player to update role (NULL = Rolecheck Failed) + @param[in] newRoleCheck Determines if its a new rolecheck (Default false) +*/ void LFGMgr::UpdateRoleCheck(Group* grp, Player* plr /* = NULL*/, bool newRoleCheck /* = false */) { if (!grp) return; - LfgRoleCheck* pRoleCheck = NULL; LfgRolesMap check_roles; LfgRoleCheckMap::iterator itRoleCheck = m_RoleChecks.find(grp->GetLowGUID()); if (itRoleCheck == m_RoleChecks.end()) return; - pRoleCheck = itRoleCheck->second; - LfgLockStatusMap* playersLockMap = NULL; - if (plr) + LfgRoleCheck* pRoleCheck = itRoleCheck->second; + if (!plr) + pRoleCheck->result = LFG_ROLECHECK_ABORTED; + else if (plr->GetLfgRoles() < ROLE_TANK) // Player selected no role. + pRoleCheck->result = LFG_ROLECHECK_NO_ROLE; + else { - // Player selected no role. - if (plr->GetLfgRoles() < ROLE_TANK) - pRoleCheck->result = LFG_ROLECHECK_NO_ROLE; - else - { - // Check if all players have selected a role - pRoleCheck->roles[plr->GetGUIDLow()] = plr->GetLfgRoles(); - uint8 size = 0; - for (LfgRolesMap::const_iterator itRoles = pRoleCheck->roles.begin(); itRoles != pRoleCheck->roles.end() && itRoles->second != ROLE_NONE; ++itRoles) - ++size; + pRoleCheck->roles[plr->GetGUIDLow()] = plr->GetLfgRoles(); - if (pRoleCheck->roles.size() == size) - { - // use temporal var to check roles, CheckGroupRoles modifies the roles - check_roles = pRoleCheck->roles; - if (!CheckGroupRoles(check_roles)) // Group is not posible - pRoleCheck->result = LFG_ROLECHECK_WRONG_ROLES; - else - { - // Check if we can find a dungeon for that group - pRoleCheck->result = LFG_ROLECHECK_FINISHED; - if (pRoleCheck->dungeons.size() == 1 && isRandomDungeon(*pRoleCheck->dungeons.begin())) - { - // Random dungeon - select the compatible dungeons - LfgDungeonSet* dungeons = GetDungeonsByRandom(*pRoleCheck->dungeons.begin()); - PlayerSet players; - for (LfgRolesMap::const_iterator it = pRoleCheck->roles.begin(); it != pRoleCheck->roles.end(); ++it) - if (Player* plr = sObjectMgr.GetPlayerByLowGUID(it->first)) - players.insert(plr); - - playersLockMap = CheckCompatibleDungeons(dungeons, &players); - std::string dungeonstr = ConcatenateDungeons(dungeons); - sLog.outDebug("LFGMgr::UpdateRoleCheck: [" UI64FMTD "] done. Dungeons: %s", plr->GetGUID(), dungeonstr.c_str()); - - pRoleCheck->dungeons.clear(); - if (dungeons) - { - if (dungeons->empty()) - delete dungeons; - else - { - for (LfgDungeonSet::const_iterator it = dungeons->begin(); it != dungeons->end(); ++it) - pRoleCheck->dungeons.insert(*it); - if (playersLockMap) - { - for (LfgLockStatusMap::iterator itMap = playersLockMap->begin(); itMap != playersLockMap->end(); ++itMap) - { - itMap->second->clear(); - delete itMap->second; - } - playersLockMap->clear(); - delete playersLockMap; - playersLockMap = NULL; - } - } - } - } - else - playersLockMap = GetPartyLockStatusDungeons(plr, &pRoleCheck->dungeons); - } - } + // Check if all players have selected a role + LfgRolesMap::const_iterator itRoles = pRoleCheck->roles.begin(); + while (itRoles != pRoleCheck->roles.end() && itRoles->second != ROLE_NONE) + ++itRoles; + + if (itRoles == pRoleCheck->roles.end()) + { + // use temporal var to check roles, CheckGroupRoles modifies the roles + check_roles = pRoleCheck->roles; + pRoleCheck->result = CheckGroupRoles(check_roles) ? LFG_ROLECHECK_FINISHED : LFG_ROLECHECK_WRONG_ROLES; } } + + uint8 team = 0; + LfgDungeonSet dungeons; + if (pRoleCheck->rDungeonId) + dungeons.insert(pRoleCheck->rDungeonId); else - pRoleCheck->result = LFG_ROLECHECK_ABORTED; + dungeons = pRoleCheck->dungeons; - WorldSession* session; - Player* plrg = NULL; for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) { - plrg = itr->getSource(); + Player* plrg = itr->getSource(); if (!plrg) continue; - session = plrg->GetSession(); + team = plrg->GetTeam(); + WorldSession* session = plrg->GetSession(); if (!newRoleCheck && plr) session->SendLfgRoleChosen(plr->GetGUID(), plr->GetLfgRoles()); session->SendLfgRoleCheckUpdate(pRoleCheck); switch(pRoleCheck->result) { - case LFG_ROLECHECK_INITIALITING: - continue; - case LFG_ROLECHECK_FINISHED: - if (!playersLockMap) - session->SendLfgUpdateParty(LFG_UPDATETYPE_ADDED_TO_QUEUE, &pRoleCheck->dungeons, plrg->GetLfgComment()); - else - { + case LFG_ROLECHECK_INITIALITING: + continue; + case LFG_ROLECHECK_FINISHED: + plrg->SetLfgState(LFG_STATE_QUEUED); + session->SendLfgUpdateParty(LFG_UPDATETYPE_ADDED_TO_QUEUE, &dungeons, plrg->GetLfgComment()); + break; + default: if (grp->GetLeaderGUID() == plrg->GetGUID()) - session->SendLfgJoinResult(LFG_JOIN_PARTY_NOT_MEET_REQS, 0, playersLockMap); + session->SendLfgJoinResult(LFG_JOIN_FAILED, pRoleCheck->result); session->SendLfgUpdateParty(LFG_UPDATETYPE_ROLECHECK_FAILED); - plrg->GetLfgDungeons()->clear(); - plrg->SetLfgRoles(ROLE_NONE); - if (!grp->isLFGGroup()) - plrg->SetLfgState(LFG_STATE_NONE); - } - break; - default: - if (grp->GetLeaderGUID() == plrg->GetGUID()) - session->SendLfgJoinResult(LFG_JOIN_FAILED, pRoleCheck->result); - session->SendLfgUpdateParty(LFG_UPDATETYPE_ROLECHECK_FAILED); - plrg->GetLfgDungeons()->clear(); - if (grp->isLFGGroup()) - plrg->SetLfgRoles(ROLE_NONE); - plrg->SetLfgState(LFG_STATE_NONE); - break; + plrg->ClearLfgState(); + break; } } - if (pRoleCheck->result == LFG_ROLECHECK_FINISHED && pRoleCheck->dungeons.size()) + if (pRoleCheck->result == LFG_ROLECHECK_FINISHED) { - grp->SetLfgQueued(true); + grp->SetLfgState(LFG_STATE_QUEUED); LfgQueueInfo* pqInfo = new LfgQueueInfo(); pqInfo->joinTime = time_t(time(NULL)); + pqInfo->roles = pRoleCheck->roles; + pqInfo->dungeons = pRoleCheck->dungeons; + + // Set queue roles needed - As we are using check_roles will not have more that 1 tank, 1 healer, 3 dps for (LfgRolesMap::const_iterator it = check_roles.begin(); it != check_roles.end(); ++it) { - if (pqInfo->tanks && it->second & ROLE_TANK) + uint8 roles = it->second; + if (roles & ROLE_TANK) --pqInfo->tanks; - else if (pqInfo->healers && it->second & ROLE_HEALER) + else if (roles & ROLE_HEALER) --pqInfo->healers; else --pqInfo->dps; } - for (LfgRolesMap::const_iterator itRoles = pRoleCheck->roles.begin(); itRoles != pRoleCheck->roles.end(); ++itRoles) - pqInfo->roles[itRoles->first] = itRoles->second; - for (LfgDungeonSet::const_iterator it = pRoleCheck->dungeons.begin(); it != pRoleCheck->dungeons.end(); ++it) - pqInfo->dungeons.insert(*it); - - m_QueueInfoMap[grp->GetGUID()] = pqInfo; - AddGuidToNewQueue(grp->GetGUID()); + uint64 guid = grp->GetGUID(); + m_QueueInfoMap[guid] = pqInfo; + AddToQueue(guid, team); } if (pRoleCheck->result != LFG_ROLECHECK_INITIALITING) { - pRoleCheck->dungeons.clear(); - pRoleCheck->roles.clear(); + if (pRoleCheck->result != LFG_ROLECHECK_FINISHED) + grp->RestoreLfgState(); delete pRoleCheck; m_RoleChecks.erase(itRoleCheck); } } -/// <summary> -/// Remove from cached compatible dungeons any entry that contains the given guid -/// </summary> -/// <param name="uint64">guid to remove from any list</param> +/** + Remove from cached compatible dungeons any entry that contains the given guid + + @param[in] guid Guid to remove from compatible cache +*/ void LFGMgr::RemoveFromCompatibles(uint64 guid) { - LfgGuidList lista; - lista.push_back(guid); - std::string strGuid = ConcatenateGuids(lista); - lista.clear(); + std::stringstream out; + out << guid; + std::string strGuid = out.str(); sLog.outDebug("LFGMgr::RemoveFromCompatibles: Removing [" UI64FMTD "]", guid); - LfgCompatibleMap::iterator it; for (LfgCompatibleMap::iterator itNext = m_CompatibleMap.begin(); itNext != m_CompatibleMap.end();) { - it = itNext++; - if (it->first.find(strGuid) != std::string::npos) // Found, remove it + LfgCompatibleMap::iterator it = itNext++; + if (it->first.find(strGuid) != std::string::npos) // Found, remove it m_CompatibleMap.erase(it); } } -/// <summary> -/// Set the compatibility of a list of guids -/// </summary> -/// <param name="std::string">list of guids concatenated by |</param> -/// <param name="bool">compatibles or not</param> +/** + Stores the compatibility of a list of guids + + @param[in] key String concatenation of guids (| used as separator) + @param[in] compatibles Compatibles or not +*/ void LFGMgr::SetCompatibles(std::string key, bool compatibles) { m_CompatibleMap[key] = LfgAnswer(compatibles); } -/// <summary> -/// Get the compatible dungeons between two groups from cache -/// </summary> -/// <param name="std::string">list of guids concatenated by |</param> -/// <returns>LfgAnswer, +/** + Get the compatibility of a group of guids + + @param[in] key String concatenation of guids (| used as separator) + @return 1 (Compatibles), 0 (Not compatibles), -1 (Not set) +*/ LfgAnswer LFGMgr::GetCompatibles(std::string key) { LfgAnswer answer = LFG_ANSWER_PENDING; @@ -1319,39 +1141,35 @@ LfgAnswer LFGMgr::GetCompatibles(std::string key) return answer; } -/// <summary> -/// Given a list of dungeons remove the dungeons with restrictions. -/// </summary> -/// <param name="LfgDungeonSet*">dungeons to check</param> -/// <param name="PlayerSet*">Players to check restrictions</param> -/// <param name="LfgLockStatusMap*">Used to return the lockStatusMap</param> -/// <param name="boot">Return lockMap or discard it</param> -/// <returns>LfgLockStatusMap*</returns> -LfgLockStatusMap* LFGMgr::CheckCompatibleDungeons(LfgDungeonSet* dungeons, PlayerSet* players, bool returnLockMap /* = true */) +/** + Given a list of dungeons remove the dungeons players have restrictions. + + @param[in,out] dungeons Dungeons to check restrictions + @param[in] players Set of players to check their dungeon restrictions + @param[in] returnLockMap Determines when to return a function value (Default true) + @return Map of players Lock status info of given dungeons +*/ +LfgLockStatusMap* LFGMgr::CheckCompatibleDungeons(LfgDungeonSet& dungeons, PlayerSet& players, bool returnLockMap /* = true */) { - if (!dungeons) + if (!dungeons.size()) return NULL; LfgLockStatusMap* pLockDungeons = GetGroupLockStatusDungeons(players, dungeons, false); if (pLockDungeons) // Found dungeons not compatible, remove them from the set { - for (LfgLockStatusMap::const_iterator itLockMap = pLockDungeons->begin(); itLockMap != pLockDungeons->end() && dungeons->size(); ++itLockMap) + for (LfgLockStatusMap::const_iterator itLockMap = pLockDungeons->begin(); itLockMap != pLockDungeons->end() && dungeons.size(); ++itLockMap) { for(LfgLockStatusSet::const_iterator itLockSet = itLockMap->second->begin(); itLockSet != itLockMap->second->end(); ++itLockSet) { - LfgDungeonSet::iterator itDungeon = dungeons->find((*itLockSet)->dungeon); - if (itDungeon != dungeons->end()) - dungeons->erase(itDungeon); + LfgDungeonSet::iterator itDungeon = dungeons.find((*itLockSet)->dungeon); + if (itDungeon != dungeons.end()) + dungeons.erase(itDungeon); } if (!returnLockMap) - { - itLockMap->second->clear(); delete itLockMap->second; - } } if (!returnLockMap) { - pLockDungeons->clear(); delete pLockDungeons; return NULL; } @@ -1359,53 +1177,14 @@ LfgLockStatusMap* LFGMgr::CheckCompatibleDungeons(LfgDungeonSet* dungeons, Playe return pLockDungeons; } -/// <summary> -/// Given a list of groups checks the compatible dungeons. If players is not null also check restictions -/// </summary> -/// <param name="LfgDungeonMap*">dungeons to check</param> -/// <param name="PlayerSet*">Players to check restrictions</param> -/// <returns>LfgDungeonSet*</returns> -LfgDungeonSet* LFGMgr::CheckCompatibleDungeons(LfgDungeonMap* dungeonsMap, PlayerSet* players) -{ - if (!dungeonsMap || dungeonsMap->empty()) - return NULL; - - LfgDungeonMap::const_iterator itMap = ++dungeonsMap->begin(); - LfgDungeonSet* compatibleDungeons = new LfgDungeonSet(); - - bool compatibleDungeon; - - // Get the first group and compare with the others to select all common dungeons - for (LfgDungeonSet::const_iterator itDungeon = dungeonsMap->begin()->second->begin(); itDungeon != dungeonsMap->begin()->second->end(); ++itDungeon) - { - compatibleDungeon = true; - for (LfgDungeonMap::const_iterator it = itMap; it != dungeonsMap->end() && compatibleDungeon; ++it) - if (it->second->find(*itDungeon) == it->second->end()) - compatibleDungeon = false; - if (compatibleDungeon) - compatibleDungeons->insert(*itDungeon); - } - - // if we have players remove restrictions - if (players && !players->empty()) - CheckCompatibleDungeons(compatibleDungeons, players, false); +/** + Check if a group can be formed with the given group roles - // Any compatible dungeon after checking restrictions? - if (compatibleDungeons && !compatibleDungeons->size()) - { - delete compatibleDungeons; - compatibleDungeons = NULL; - } - return compatibleDungeons; -} - -/// <summary> -/// Check if a group can be formed with the given group -/// </summary> -/// <param name="LfgRolesMap &">Roles to check</param> -/// <param name="bool">Used to remove ROLE_LEADER</param> -/// <returns>bool</returns> -bool LFGMgr::CheckGroupRoles(LfgRolesMap &groles, bool removeLeaderFlag /*= true*/) + @param[in] groles Map of roles to check + @param[in] removeLeaderFlag Determines if we have to remove leader flag (only used first call, Default = true) + @return True if roles are compatible +*/ +bool LFGMgr::CheckGroupRoles(LfgRolesMap& groles, bool removeLeaderFlag /*= true*/) { if (!groles.size()) return false; @@ -1471,12 +1250,13 @@ bool LFGMgr::CheckGroupRoles(LfgRolesMap &groles, bool removeLeaderFlag /*= true return (tank + healer + damage) == uint8(groles.size()); } -/// <summary> -/// Update Proposal info with player answer -/// </summary> -/// <param name="uint32">Id of the proposal</param> -/// <param name="uint32">Player low guid</param> -/// <param name="bool">Player answer</param> +/** + Update Proposal info with player answer + + @param[in] proposalId Proposal id to be updated + @param[in] lowguid Player low guid to update answer + @param[in] accept Player answer +*/ void LFGMgr::UpdateProposal(uint32 proposalId, uint32 lowGuid, bool accept) { // Check if the proposal exists @@ -1501,15 +1281,12 @@ void LFGMgr::UpdateProposal(uint32 proposalId, uint32 lowGuid, bool accept) LfgPlayerList players; LfgPlayerList playersToTeleport; - Player* plr; // check if all have answered and reorder players (leader first) bool allAnswered = true; for (LfgProposalPlayerMap::const_iterator itPlayers = pProposal->players.begin(); itPlayers != pProposal->players.end(); ++itPlayers) { - plr = sObjectMgr.GetPlayerByLowGUID(itPlayers->first); - - if (plr) + if (Player* plr = sObjectMgr.GetPlayerByLowGUID(itPlayers->first)) { if (itPlayers->first == pProposal->leaderLowGuid) players.push_front(plr); @@ -1517,7 +1294,8 @@ void LFGMgr::UpdateProposal(uint32 proposalId, uint32 lowGuid, bool accept) players.push_back(plr); // Only teleport new players - if (!plr->GetGroup() || !plr->GetGroup()->isLFGGroup() || plr->GetGroup()->isLfgDungeonComplete()) + Group* grp = plr->GetGroup(); + if (!grp || !grp->isLFGGroup() || grp->GetLfgState() == LFG_STATE_FINISHED_DUNGEON) playersToTeleport.push_back(plr); } @@ -1528,7 +1306,7 @@ void LFGMgr::UpdateProposal(uint32 proposalId, uint32 lowGuid, bool accept) if (!allAnswered) { for (LfgPlayerList::const_iterator it = players.begin(); it != players.end(); ++it) - (*it)->GetSession()->SendUpdateProposal(proposalId, pProposal); + (*it)->GetSession()->SendLfgUpdateProposal(proposalId, pProposal); } else { @@ -1556,62 +1334,53 @@ void LFGMgr::UpdateProposal(uint32 proposalId, uint32 lowGuid, bool accept) } // Create a new group (if needed) - Group* grp = sObjectMgr.GetGroupByGUID(pProposal->groupLowGuid); + Group* grp = pProposal->groupLowGuid ? sObjectMgr.GetGroupByGUID(pProposal->groupLowGuid) : NULL; for (LfgPlayerList::const_iterator it = players.begin(); it != players.end(); ++it) { - plr = (*it); + Player* plr = (*it); + Group* group = plr->GetGroup(); if (sendUpdate) - plr->GetSession()->SendUpdateProposal(proposalId, pProposal); - if (plr->GetGroup()) + plr->GetSession()->SendLfgUpdateProposal(proposalId, pProposal); + if (group) { plr->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_GROUP_FOUND); - plr->SetLfgUpdate(false); - if (plr->GetGroup() != grp) - { - plr->GetGroup()->SetLfgQueued(false); + if (group != grp) plr->RemoveFromGroup(); - } } else - { plr->GetSession()->SendLfgUpdatePlayer(LFG_UPDATETYPE_GROUP_FOUND); - plr->SetLfgUpdate(false); - } if (!grp) { grp = new Group(); grp->Create(plr->GetGUID(), plr->GetName()); grp->ConvertToLFG(); + grp->SetLfgState(LFG_STATE_PROPOSAL); sObjectMgr.AddGroup(grp); } - else if (plr->GetGroup() != grp) - { - grp->SetLfgQueued(false); + else if (group != grp) grp->AddMember(plr->GetGUID(), plr->GetName()); - } - plr->SetLfgUpdate(true); // Update timers uint8 role = plr->GetLfgRoles(); - if (role & ROLE_TANK) + role &= ~ROLE_LEADER; + switch(role) { - if (role & ROLE_HEALER || role & ROLE_DAMAGE) - m_WaitTimeAvg = int32((m_WaitTimeAvg * m_NumWaitTimeAvg + waitTimesMap[plr->GetGUID()]) / ++m_NumWaitTimeAvg); - else + case ROLE_DAMAGE: + m_WaitTimeDps = int32((m_WaitTimeDps * m_NumWaitTimeDps + waitTimesMap[plr->GetGUID()]) / ++m_NumWaitTimeDps); + break; + case ROLE_HEALER: + m_WaitTimeHealer = int32((m_WaitTimeHealer * m_NumWaitTimeHealer + waitTimesMap[plr->GetGUID()]) / ++m_NumWaitTimeHealer); + break; + case ROLE_TANK: m_WaitTimeTank = int32((m_WaitTimeTank * m_NumWaitTimeTank + waitTimesMap[plr->GetGUID()]) / ++m_NumWaitTimeTank); - } - else if (role & ROLE_HEALER) - { - if (role & ROLE_DAMAGE) + break; + default: m_WaitTimeAvg = int32((m_WaitTimeAvg * m_NumWaitTimeAvg + waitTimesMap[plr->GetGUID()]) / ++m_NumWaitTimeAvg); - else - m_WaitTimeHealer = int32((m_WaitTimeHealer * m_NumWaitTimeHealer + waitTimesMap[plr->GetGUID()]) / ++m_NumWaitTimeHealer); + break; } - else if (role & ROLE_DAMAGE) - m_WaitTimeDps = int32((m_WaitTimeDps * m_NumWaitTimeDps + waitTimesMap[plr->GetGUID()]) / ++m_NumWaitTimeDps); - grp->SetLfgRoles(plr->GetGUID(), pProposal->players[plr->GetGUIDLow()]->role); + plr->SetLfgState(LFG_STATE_DUNGEON); } // Set the dungeon difficulty @@ -1619,11 +1388,14 @@ void LFGMgr::UpdateProposal(uint32 proposalId, uint32 lowGuid, bool accept) ASSERT(dungeon); grp->SetDungeonDifficulty(Difficulty(dungeon->difficulty)); grp->SetLfgDungeonEntry(dungeon->Entry()); - grp->SetLfgStatus(LFG_STATUS_NOT_SAVED); + grp->SetLfgState(LFG_STATE_DUNGEON); // Remove players/groups from Queue for (LfgGuidList::const_iterator it = pProposal->queues.begin(); it != pProposal->queues.end(); ++it) - RemoveFromQueue(*it); + { + uint64 guid = (*it); + RemoveFromQueue(guid); + } // Teleport Player for (LfgPlayerList::const_iterator it = playersToTeleport.begin(); it != playersToTeleport.end(); ++it) @@ -1632,28 +1404,19 @@ void LFGMgr::UpdateProposal(uint32 proposalId, uint32 lowGuid, bool accept) // Update group info grp->SendUpdate(); - for (LfgProposalPlayerMap::const_iterator it = pProposal->players.begin(); it != pProposal->players.end(); ++it) - delete it->second; - pProposal->players.clear(); - pProposal->queues.clear(); delete pProposal; m_Proposals.erase(itProposal); } - players.clear(); - playersToTeleport.clear(); } -/// <summary> -/// Remove a proposal from the pool, remove the group that didn't accept (if needed) and readd the other members to the queue -/// </summary> -/// <param name="LfgProposalMap::iterator">Proposal to remove</param> -/// <param name="LfgUpdateType">Type of removal (LFG_UPDATETYPE_PROPOSAL_FAILED, LFG_UPDATETYPE_PROPOSAL_DECLINED)</param> +/** + Remove a proposal from the pool, remove the group that didn't accept (if needed) and readd the other members to the queue + + @param[in] itProposal Iterator to the proposal to remove + @param[in] type Type of removal (LFG_UPDATETYPE_PROPOSAL_FAILED, LFG_UPDATETYPE_PROPOSAL_DECLINED) +*/ void LFGMgr::RemoveProposal(LfgProposalMap::iterator itProposal, LfgUpdateType type) { - Player* plr; - uint64 guid; - LfgUpdateType updateType; - LfgQueueInfoMap::iterator itQueue; LfgProposal* pProposal = itProposal->second; pProposal->state = LFG_PROPOSAL_FAILED; @@ -1661,26 +1424,43 @@ void LFGMgr::RemoveProposal(LfgProposalMap::iterator itProposal, LfgUpdateType t // Mark all people that didn't answered as no accept if (type == LFG_UPDATETYPE_PROPOSAL_FAILED) for (LfgProposalPlayerMap::const_iterator it = pProposal->players.begin(); it != pProposal->players.end(); ++it) - if (it->second->accept != LFG_ANSWER_AGREE) + if (it->second->accept == LFG_ANSWER_PENDING) it->second->accept = LFG_ANSWER_DENY; - // Remove from queue all players/groups that didn't accept + // Mark players/groups to be removed + LfgGuidSet toRemove; for (LfgProposalPlayerMap::const_iterator it = pProposal->players.begin(); it != pProposal->players.end(); ++it) - if (it->second->accept == LFG_ANSWER_DENY) - RemoveFromQueue(it->second->groupLowGuid ? MAKE_NEW_GUID(it->second->groupLowGuid, 0, HIGHGUID_GROUP) : MAKE_NEW_GUID(it->first, 0, HIGHGUID_PLAYER)); + { + if (it->second->accept == LFG_ANSWER_AGREE) + continue; - // Inform players + uint64 guid = it->second->groupLowGuid ? MAKE_NEW_GUID(it->second->groupLowGuid, 0, HIGHGUID_GROUP) : MAKE_NEW_GUID(it->first, 0, HIGHGUID_PLAYER); + // Player didn't accept or still pending when no secs left + if (it->second->accept == LFG_ANSWER_DENY || type == LFG_UPDATETYPE_PROPOSAL_FAILED) + { + it->second->accept = LFG_ANSWER_DENY; + toRemove.insert(guid); + } + } + + uint8 team = 0; + // Notify players for (LfgProposalPlayerMap::const_iterator it = pProposal->players.begin(); it != pProposal->players.end(); ++it) { - plr = sObjectMgr.GetPlayerByLowGUID(it->first); + Player* plr = sObjectMgr.GetPlayerByLowGUID(it->first); if (!plr) continue; - plr->GetSession()->SendUpdateProposal(itProposal->first, pProposal); - guid = it->second->groupLowGuid ? MAKE_NEW_GUID(it->second->groupLowGuid, 0, HIGHGUID_GROUP) : plr->GetGUID(); - itQueue = m_QueueInfoMap.find(guid); - if (itQueue == m_QueueInfoMap.end()) // Didn't accept or in same group that someone that didn't accept + team = uint8(plr->GetTeam()); + plr->GetSession()->SendLfgUpdateProposal(itProposal->first, pProposal); + + Group* grp = plr->GetGroup(); + uint64 guid = plr->GetGUID(); + uint64 gguid = it->second->groupLowGuid ? MAKE_NEW_GUID(it->second->groupLowGuid, 0, HIGHGUID_GROUP) : guid; + + if (toRemove.find(gguid) != toRemove.end()) // Didn't accept or in same group that someone that didn't accept { + LfgUpdateType updateType; if (it->second->accept == LFG_ANSWER_DENY) { updateType = type; @@ -1691,66 +1471,82 @@ void LFGMgr::RemoveProposal(LfgProposalMap::iterator itProposal, LfgUpdateType t updateType = LFG_UPDATETYPE_REMOVED_FROM_QUEUE; sLog.outDebug("LFGMgr::RemoveProposal: [" UI64FMTD "] in same group that someone that didn't accept. Removing from queue and compatible cache", guid); } - plr->GetLfgDungeons()->clear(); - plr->SetLfgRoles(ROLE_NONE); - if (!plr->GetGroup() || !plr->GetGroup()->isLFGGroup()) - plr->SetLfgState(LFG_STATE_NONE); - - if (plr->GetGroup()) + plr->ClearLfgState(); + if (grp) + { + grp->RestoreLfgState(); plr->GetSession()->SendLfgUpdateParty(updateType); + } else plr->GetSession()->SendLfgUpdatePlayer(updateType); } else { sLog.outDebug("LFGMgr::RemoveProposal: Readding [" UI64FMTD "] to queue.", guid); - itQueue->second->joinTime = time_t(time(NULL)); - AddGuidToNewQueue(guid); - if (plr->GetGroup()) + plr->SetLfgState(LFG_STATE_QUEUED); + if (grp) + { + grp->SetLfgState(LFG_STATE_QUEUED); plr->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_ADDED_TO_QUEUE, plr->GetLfgDungeons(), plr->GetLfgComment()); + } else plr->GetSession()->SendLfgUpdatePlayer(LFG_UPDATETYPE_ADDED_TO_QUEUE, plr->GetLfgDungeons(), plr->GetLfgComment()); } } - for (LfgProposalPlayerMap::const_iterator it = pProposal->players.begin(); it != pProposal->players.end(); ++it) - delete it->second; - pProposal->players.clear(); - pProposal->queues.clear(); + // Remove players/groups from queue + for (LfgGuidSet::const_iterator it = toRemove.begin(); it != toRemove.end(); ++it) + { + uint64 guid = *it; + RemoveFromQueue(guid); + pProposal->queues.remove(guid); + } + + // Readd to queue + for (LfgGuidList::const_iterator it = pProposal->queues.begin(); it != pProposal->queues.end(); ++it) + { + uint64 guid = *it; + AddToQueue(guid, team); + } + delete pProposal; m_Proposals.erase(itProposal); } -/// <summary> -/// Initialize a boot kick vote -/// </summary> -/// <param name="Group*">Group</param> -/// <param name="uint32">Player low guid who inits the vote kick</param> -/// <param name="uint32">Player low guid to be kicked </param> -/// <param name="std::string">kick reason</param> -void LFGMgr::InitBoot(Group* grp, uint32 iLowGuid, uint32 vLowguid, std::string reason) +/** + Initialize a boot kick vote + + @param[in] grp Group the vote kicks belongs to + @param[in] kicker Kicker low guid + @param[in] victim Victim low guid + @param[in] reason Kick reason +*/ +void LFGMgr::InitBoot(Group* grp, uint32 kicker, uint32 victim, std::string reason) { if (!grp) return; + grp->SetLfgState(LFG_STATE_BOOT); + LfgPlayerBoot* pBoot = new LfgPlayerBoot(); pBoot->inProgress = true; pBoot->cancelTime = time_t(time(NULL)) + LFG_TIME_BOOT; pBoot->reason = reason; - pBoot->victimLowGuid = vLowguid; + pBoot->victimLowGuid = victim; pBoot->votedNeeded = GROUP_LFG_KICK_VOTES_NEEDED; PlayerSet players; - uint32 pLowGuid = 0; + // Set votes for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) { if (Player* plrg = itr->getSource()) { - pLowGuid = plrg->GetGUIDLow(); - if (pLowGuid == vLowguid) - pBoot->votes[pLowGuid] = LFG_ANSWER_DENY; // Victim auto vote NO - else if (pLowGuid == iLowGuid) - pBoot->votes[pLowGuid] = LFG_ANSWER_AGREE; // Kicker auto vote YES + plrg->SetLfgState(LFG_STATE_BOOT); + uint32 pLowGuid = plrg->GetGUIDLow(); + if (pLowGuid == victim) + pBoot->votes[pLowGuid] = LFG_ANSWER_DENY; // Victim auto vote NO + else if (pLowGuid == kicker) + pBoot->votes[pLowGuid] = LFG_ANSWER_AGREE; // Kicker auto vote YES else { pBoot->votes[pLowGuid] = LFG_ANSWER_PENDING; // Other members need to vote @@ -1759,18 +1555,19 @@ void LFGMgr::InitBoot(Group* grp, uint32 iLowGuid, uint32 vLowguid, std::string } } + // Notify players for (PlayerSet::const_iterator it = players.begin(); it != players.end(); ++it) (*it)->GetSession()->SendLfgBootPlayer(pBoot); - grp->SetLfgKickActive(true); m_Boots[grp->GetLowGUID()] = pBoot; } -/// <summary> -/// Update Boot info with player answer -/// </summary> -/// <param name="Player*">Player guid</param> -/// <param name="bool">Player answer</param> +/** + Update Boot info with player answer + + @param[in] plr Player who has answered + @param[in] accept player answer +*/ void LFGMgr::UpdateBoot(Player* plr, bool accept) { Group* grp = plr ? plr->GetGroup() : NULL; @@ -1788,7 +1585,7 @@ void LFGMgr::UpdateBoot(Player* plr, bool accept) if (!pBoot) return; - if (pBoot->votes[lowGuid] != LFG_ANSWER_PENDING) // Cheat check: Player can't vote twice + if (pBoot->votes[lowGuid] != LFG_ANSWER_PENDING) // Cheat check: Player can't vote twice return; pBoot->votes[lowGuid] = LfgAnswer(accept); @@ -1805,8 +1602,8 @@ void LFGMgr::UpdateBoot(Player* plr, bool accept) } } - if (agreeNum == pBoot->votedNeeded || // Vote passed - votesNum == pBoot->votes.size() || // All voted but not passed + if (agreeNum == pBoot->votedNeeded || // Vote passed + votesNum == pBoot->votes.size() || // All voted but not passed (pBoot->votes.size() - votesNum + agreeNum) < pBoot->votedNeeded) // Vote didnt passed { // Send update info to all players @@ -1814,28 +1611,36 @@ void LFGMgr::UpdateBoot(Player* plr, bool accept) for (LfgAnswerMap::const_iterator itVotes = pBoot->votes.begin(); itVotes != pBoot->votes.end(); ++itVotes) if (Player* plrg = sObjectMgr.GetPlayerByLowGUID(itVotes->first)) if (plrg->GetGUIDLow() != pBoot->victimLowGuid) + { + plrg->SetLfgState(LFG_STATE_DUNGEON); plrg->GetSession()->SendLfgBootPlayer(pBoot); + } - if (agreeNum == pBoot->votedNeeded) // Vote passed - Kick player + grp->SetLfgState(LFG_STATE_DUNGEON); + if (agreeNum == pBoot->votedNeeded) // Vote passed - Kick player { Player::RemoveFromGroup(grp, MAKE_NEW_GUID(pBoot->victimLowGuid, 0, HIGHGUID_PLAYER)); if (Player* victim = sObjectMgr.GetPlayerByLowGUID(pBoot->victimLowGuid)) + { TeleportPlayer(victim, true, false); + victim->SetLfgState(LFG_STATE_NONE); + } OfferContinue(grp); grp->SetLfgKicks(grp->GetLfgKicks() + 1); + } - grp->SetLfgKickActive(false); delete pBoot; m_Boots.erase(itBoot); } } -/// <summary> -/// Teleports the player in or out the dungeon -/// </summary> -/// <param name="Player*">Player</param> -/// <param name="bool">Teleport out</param> -/// <param name="bool">Automatic or manual teleport</param> +/** + Teleports the player in or out the dungeon + + @param[in] plr Player to teleport + @param[in] out Teleport out (true) or in (false) + @param[in] fromOpcode Function called from opcode handlers? (Default false) +*/ void LFGMgr::TeleportPlayer(Player* plr, bool out, bool fromOpcode /*= false*/) { sLog.outDebug("LFGMgr::TeleportPlayer: [" UI64FMTD "] is being teleported %s", plr->GetGUID(), out ? "out" : "in"); @@ -1850,7 +1655,7 @@ void LFGMgr::TeleportPlayer(Player* plr, bool out, bool fromOpcode /*= false*/) LfgTeleportError error = LFG_TELEPORTERROR_OK; Group* grp = plr->GetGroup(); - if (!grp || !grp->isLFGGroup()) // should never happen, but just in case... + if (!grp || !grp->isLFGGroup()) // should never happen, but just in case... error = LFG_TELEPORTERROR_INVALID_LOCATION; else if (!plr->isAlive()) error = LFG_TELEPORTERROR_PLAYER_DEAD; @@ -1862,7 +1667,7 @@ void LFGMgr::TeleportPlayer(Player* plr, bool out, bool fromOpcode /*= false*/) if (!dungeon) error = LFG_TELEPORTERROR_INVALID_LOCATION; - else if (plr->GetMapId() != uint32(dungeon->map)) // Do not teleport players in dungeon to the entrance + else if (plr->GetMapId() != uint32(dungeon->map)) // Do not teleport players in dungeon to the entrance { uint32 mapid = 0; float x = 0; @@ -1872,11 +1677,11 @@ void LFGMgr::TeleportPlayer(Player* plr, bool out, bool fromOpcode /*= false*/) if (!fromOpcode) { - Player *plrg; + // Select a player inside to be teleported to for (GroupReference* itr = grp->GetFirstMember(); itr != NULL && !mapid; itr = itr->next()) { - plrg = itr->getSource(); + Player* plrg = itr->getSource(); if (plrg && plrg != plr && plrg->GetMapId() == uint32(dungeon->map)) { mapid = plrg->GetMapId(); @@ -1918,6 +1723,7 @@ void LFGMgr::TeleportPlayer(Player* plr, bool out, bool fromOpcode /*= false*/) } if (plr->TeleportTo(mapid, x, y, z, orientation)) + // FIXME - HACK - this should be done by teleport, when teleporting far plr->RemoveAurasByType(SPELL_AURA_MOUNTED); else { @@ -1932,30 +1738,42 @@ void LFGMgr::TeleportPlayer(Player* plr, bool out, bool fromOpcode /*= false*/) plr->GetSession()->SendLfgTeleportError(error); } -/// <summary> -/// Give completion reward to player -/// </summary> -/// <param name="const uint32">dungeonId</param> -/// <param name="Player*">player</param> -void LFGMgr::RewardDungeonDoneFor(const uint32 /*dungeonId*/, Player* player) +/** + Give completion reward to player + + @param[in] dungeonId Dungeonid (Obsolete) + @param[in] plr Player to reward +*/ +void LFGMgr::RewardDungeonDoneFor(const uint32 dungeonId, Player* player) { Group* group = player->GetGroup(); - if (!group || !group->isLFGGroup() || !sWorld.getBoolConfig(CONFIG_DUNGEON_FINDER_ENABLE)) + if (!group || !group->isLFGGroup()) + { + sLog.outDebug("LFGMgr::RewardDungeonDoneFor: [" UI64FMTD "] is not in a group or not a LFGGroup. Ignoring", player->GetGUID()); return; + } + + if (player->GetLfgState() == LFG_STATE_FINISHED_DUNGEON) + { + sLog.outDebug("LFGMgr::RewardDungeonDoneFor: [" UI64FMTD "] Already rewarded player. Ignoring", player->GetGUID()); + return; + } // Mark dungeon as finished - if (!group->isLfgDungeonComplete()) - group->SetLfgStatus(LFG_STATUS_COMPLETE); + group->SetLfgState(LFG_STATE_FINISHED_DUNGEON); // Clear player related lfg stuff uint32 rDungeonId = (*player->GetLfgDungeons()->begin()); - player->GetLfgDungeons()->clear(); - player->SetLfgRoles(ROLE_NONE); + player->ClearLfgState(); + player->SetLfgState(LFG_STATE_FINISHED_DUNGEON); // Give rewards only if its a random dungeon LFGDungeonEntry const* dungeon = sLFGDungeonStore.LookupEntry(rDungeonId); if (!dungeon || dungeon->type != LFG_TYPE_RANDOM) + { + sLog.outDebug("LFGMgr::RewardDungeonDoneFor: [" UI64FMTD "] dungeon %u is not random. Queued for %u dungeons", player->GetGUID(), rDungeonId, uint8(player->GetLfgDungeons()->size())); return; + } // Update achievements if (dungeon->difficulty == DUNGEON_DIFFICULTY_HEROIC) @@ -1984,7 +1802,7 @@ void LFGMgr::RewardDungeonDoneFor(const uint32 /*dungeonId*/, Player* player) } // Give rewards - sLog.outDebug("LFGMgr::RewardDungeonDoneFor: [" UI64FMTD "] done dungeon %u, %s previously done.", player->GetGUID(), rDungeonId, index > 0 ? "" : "not "); + sLog.outDebug("LFGMgr::RewardDungeonDoneFor: [" UI64FMTD "] done dungeon %u,%s previously done.", player->GetGUID(), group->GetLfgDungeonEntry(), index > 0 ? " " : " not"); player->GetSession()->SendLfgPlayerReward(dungeon->Entry(), group->GetLfgDungeonEntry(false), index, reward, qReward); } @@ -1992,97 +1810,91 @@ void LFGMgr::RewardDungeonDoneFor(const uint32 /*dungeonId*/, Player* player) // Auxiliar Functions // --------------------------------------------------------------------------// -/// <summary> -/// Given a group get the dungeons that can't be done and reason -/// </summary> -/// <param name="PlayerSet*">Players to check lock status</param> -/// <param name="LfgDungeonSet*">Dungeons to check</param> -/// <param name="bool">Use dungeon entry (true) or id (false)</param> -/// <returns>LfgLockStatusMap*</returns> -LfgLockStatusMap* LFGMgr::GetGroupLockStatusDungeons(PlayerSet* pPlayers, LfgDungeonSet* dungeons, bool useEntry /* = true */) +/** + Get all Group members list of all dungeons that can't be done and reason + leader excluded as the list given is he list he can do + + @param[in] plr Players to check group lock status + @returns Map of player's group dungeon Lock status +*/ +LfgLockStatusMap* LFGMgr::GetPartyLockStatusDungeons(Player* plr) { - if (!pPlayers || !dungeons) + Group* grp = plr->GetGroup(); + if (!grp) return NULL; - LfgLockStatusSet* dungeonSet = NULL; - LfgLockStatusMap* dungeonMap = new LfgLockStatusMap(); - for (PlayerSet::const_iterator itr = pPlayers->begin(); itr != pPlayers->end(); ++itr) + PlayerSet players; + for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) { - dungeonSet = GetPlayerLockStatusDungeons(*itr, dungeons, useEntry); - if (dungeonSet) - (*dungeonMap)[(*itr)->GetGUIDLow()] = dungeonSet; + Player* plrg = itr->getSource(); + if (plrg && plrg != plr) + players.insert(plrg); } - if (!dungeonMap->size()) - { - delete dungeonMap; - dungeonMap = NULL; - } - return dungeonMap; + LfgDungeonSet allDungeons; + GetDungeonsByRandom(0, allDungeons); + return GetGroupLockStatusDungeons(players, allDungeons, true); } -/// <summary> -/// Get all Group members list of dungeons that can't be done and reason -/// leader excluded as the list given is he list he can do -/// </summary> -/// <param name="Player*">Player to get Party Lock info</param> -/// <param name="LfgDungeonSet*">Dungeons to check</param> -/// <returns>LfgLockStatusMap*</returns> -LfgLockStatusMap* LFGMgr::GetPartyLockStatusDungeons(Player* plr, LfgDungeonSet* dungeons /* = NULL */) +/** + Get list of all dungeons player can't do and reasons + + @param[in] plr Players to check dungeon lock status + @returns Set of player's dungeon Lock status +*/ +LfgLockStatusSet* LFGMgr::GetPlayerLockStatusDungeons(Player* plr) { - if (!plr) - return NULL; + LfgDungeonSet allDungeons; + GetDungeonsByRandom(0, allDungeons); + return GetPlayerLockStatusDungeons(plr, allDungeons, true); +} - if (!dungeons) - dungeons = GetAllDungeons(); +/** + Given a group get the dungeons that can't be done and reason - Group* grp = plr->GetGroup(); - if (!grp) - return NULL; + @param[in] players Players to check lock status + @param[in] dungeons Dungeons to check + @param[in] useEntry Use dungeon entry (true) or id (false) + @returns Map of player's dungeon Lock status +*/ +LfgLockStatusMap* LFGMgr::GetGroupLockStatusDungeons(PlayerSet& players, LfgDungeonSet& dungeons, bool useEntry) +{ + LfgLockStatusMap* dungeonMap = new LfgLockStatusMap(); + for (PlayerSet::const_iterator itr = players.begin(); itr != players.end(); ++itr) + if (LfgLockStatusSet* dungeonSet = GetPlayerLockStatusDungeons(*itr, dungeons, useEntry)) + (*dungeonMap)[(*itr)->GetGUIDLow()] = dungeonSet; - PlayerSet* pPlayers = new PlayerSet(); - Player* plrg; - for (GroupReference* itr = grp->GetFirstMember(); itr != NULL; itr = itr->next()) + if (!dungeonMap->size()) { - plrg = itr->getSource(); - if (plrg && plrg != plr) - pPlayers->insert(plrg); + delete dungeonMap; + dungeonMap = NULL; } - LfgLockStatusMap* dungeonMap = GetGroupLockStatusDungeons(pPlayers, dungeons); - pPlayers->clear(); - delete pPlayers; return dungeonMap; } -/// <summary> -/// Get list of dungeons player can't do and reasons -/// </summary> -/// <param name="Player*">Player to check lock status</param> -/// <param name="LfgDungeonSet*">Dungeons to check</param> -/// <param name="bool">Use dungeon entry (true) or id (false)</param> -/// <returns>LfgLockStatusSet*</returns> -LfgLockStatusSet* LFGMgr::GetPlayerLockStatusDungeons(Player* plr, LfgDungeonSet* dungeons /* = NULL */, bool useEntry /* = true */) +/** + Given a list of dungeon return the list of dungeons player can't do and reasons + + @param[in] plr Players to check dungeon lock status + @param[in] dungeons Dungeons to check (Default = NULL, means check all dungeons) + @param[in] useEntry Use dungeon entry (true) or id (false) + @returns Set of player's dungeon Lock status +*/ +LfgLockStatusSet* LFGMgr::GetPlayerLockStatusDungeons(Player* plr, LfgDungeonSet& dungeons, bool useEntry) { LfgLockStatusSet* list = new LfgLockStatusSet(); - LfgLockStatus* lockstatus = NULL; - LFGDungeonEntry const* dungeon; - LfgLockStatusType locktype; uint8 level = plr->getLevel(); uint8 expansion = plr->GetSession()->Expansion(); - AccessRequirement const* ar; - - if (!dungeons) - dungeons = GetAllDungeons(); - for (LfgDungeonSet::const_iterator it = dungeons->begin(); it != dungeons->end(); ++it) + for (LfgDungeonSet::const_iterator it = dungeons.begin(); it != dungeons.end(); ++it) { - dungeon = sLFGDungeonStore.LookupEntry(*it); + LFGDungeonEntry const* dungeon = sLFGDungeonStore.LookupEntry(*it); if (!dungeon) // should never happen - We provide a list from sLFGDungeonStore continue; - ar = sObjectMgr.GetAccessRequirement(dungeon->map, Difficulty(dungeon->difficulty)); + AccessRequirement const* ar = sObjectMgr.GetAccessRequirement(dungeon->map, Difficulty(dungeon->difficulty)); - locktype = LFG_LOCKSTATUS_OK; + LfgLockStatusType locktype = LFG_LOCKSTATUS_OK; if (dungeon->expansion > expansion) locktype = LFG_LOCKSTATUS_INSUFFICIENT_EXPANSION; else if (sDisableMgr.IsDisabledFor(DISABLE_TYPE_MAP, dungeon->map, plr)) @@ -2120,7 +1932,7 @@ LfgLockStatusSet* LFGMgr::GetPlayerLockStatusDungeons(Player* plr, LfgDungeonSet if (locktype != LFG_LOCKSTATUS_OK) { - lockstatus = new LfgLockStatus(); + LfgLockStatus* lockstatus = new LfgLockStatus(); lockstatus->dungeon = useEntry ? dungeon->Entry(): dungeon->ID; lockstatus->lockstatus = locktype; list->insert(lockstatus); @@ -2134,89 +1946,26 @@ LfgLockStatusSet* LFGMgr::GetPlayerLockStatusDungeons(Player* plr, LfgDungeonSet return list; } -/// <summary> -/// Get the dungeon list that can be done. -/// </summary> -/// <returns>LfgDungeonSet*</returns> -LfgDungeonSet* LFGMgr::GetAllDungeons() -{ - LfgDungeonSet* alldungeons = m_CachedDungeonMap[0]; - - if (alldungeons) - return alldungeons; - - LfgDungeonSet* dungeons; - LFGDungeonEntry const* dungeon; +/** + Get the dungeon list that can be done given a random dungeon entry. - alldungeons = new LfgDungeonSet(); - m_CachedDungeonMap[0] = alldungeons; - for (uint32 i = 0; i < sLFGDungeonStore.GetNumRows(); ++i) - { - dungeon = sLFGDungeonStore.LookupEntry(i); - if (!dungeon || dungeon->type == LFG_TYPE_ZONE) - continue; - dungeons = m_CachedDungeonMap[dungeon->grouptype]; - if (!dungeons) - { - dungeons = new LfgDungeonSet(); - m_CachedDungeonMap[dungeon->grouptype] = dungeons; - } - if (dungeon->type != LFG_TYPE_RANDOM) - dungeons->insert(dungeon->ID); - alldungeons->insert(dungeon->ID); - } - - return alldungeons; -} - -/// <summary> -/// Get the dungeon list that can be done given a random dungeon entry. -/// Special case: randomdungeon == 0 then will return all dungeons -/// </summary> -/// <param name="uint32">Random dungeon entry</param> -/// <returns>LfgDungeonSet*</returns> -LfgDungeonSet* LFGMgr::GetDungeonsByRandom(uint32 randomdungeon) + @param[in] randomdungeon Random dungeon id (if value = 0 will return all dungeons) + @param[out] dungeons Set of dungeons that can be done. +*/ +void LFGMgr::GetDungeonsByRandom(uint32 randomdungeon, LfgDungeonSet& dungeons) { - uint8 groupType = 0; - if (LFGDungeonEntry const* dungeon = sLFGDungeonStore.LookupEntry(randomdungeon)) - groupType = dungeon->grouptype; - - LfgDungeonMap::const_iterator itMap = m_CachedDungeonMap.find(groupType); - if (itMap == m_CachedDungeonMap.end()) - return NULL; - - LfgDungeonSet* dungeons = new LfgDungeonSet(); - for (LfgDungeonSet::const_iterator it = itMap->second->begin(); it != itMap->second->end(); ++it) - dungeons->insert(*it); - return dungeons; + LFGDungeonEntry const* dungeon = sLFGDungeonStore.LookupEntry(randomdungeon); + uint8 groupType = dungeon ? dungeon->grouptype : 0; + dungeons = m_CachedDungeonMap[groupType]; } -/// <summary> -/// Get the random dungeon list that can be done at a certain level and expansion. -/// </summary> -/// <param name="uint8">Player level</param> -/// <param name="uint8">Player account expansion</param> -/// <returns>LfgDungeonSet*</returns> -LfgDungeonSet* LFGMgr::GetRandomDungeons(uint8 level, uint8 expansion) -{ - LfgDungeonSet* list = new LfgDungeonSet(); - LFGDungeonEntry const* dungeon; - for (uint32 i = 0; i < sLFGDungeonStore.GetNumRows(); ++i) - { - dungeon = sLFGDungeonStore.LookupEntry(i); - if (dungeon && dungeon->expansion <= expansion && dungeon->type == LFG_TYPE_RANDOM && - dungeon->minlevel <= level && level <= dungeon->maxlevel) - list->insert(dungeon->Entry()); - } - return list; -} +/** + Get the reward of a given random dungeon at a certain level -/// <summary> -/// Get the reward of a given random dungeon at a certain level -/// </summary> -/// <param name="uint32">random dungeon id</param> -/// <param name="uint8">Player level</param> -/// <returns>LfgReward const*</returns> + @param[in] dungeon dungeon id + @param[in] level Player level + @returns Reward +*/ LfgReward const* LFGMgr::GetRandomDungeonReward(uint32 dungeon, uint8 level) { LfgReward const* rew = NULL; @@ -2232,11 +1981,12 @@ LfgReward const* LFGMgr::GetRandomDungeonReward(uint32 dungeon, uint8 level) return rew; } -/// <summary> -/// Given a Dungeon id returns the dungeon Type -/// </summary> -/// <param name="uint32">Dungeon id</param> -/// <returns>uint8: Type</returns> +/** + Given a Dungeon id returns the dungeon Type + + @param[in] dungeon dungeon id + @returns Dungeon type +*/ LfgType LFGMgr::GetDungeonType(uint32 dungeonId) { LFGDungeonEntry const* dungeon = sLFGDungeonStore.LookupEntry(dungeonId); @@ -2246,25 +1996,12 @@ LfgType LFGMgr::GetDungeonType(uint32 dungeonId) return LfgType(dungeon->type); } -/// <summary> -/// Given a Dungeon id returns if it's random -/// </summary> -/// <param name="uint32">Dungeon id</param> -/// <returns>bool</returns> -bool LFGMgr::isRandomDungeon(uint32 dungeonId) -{ - LFGDungeonEntry const* dungeon = sLFGDungeonStore.LookupEntry(dungeonId); - if (!dungeon) - return false; - - return dungeon->type == LFG_TYPE_RANDOM; -} +/** + Given a Achievement id returns the related dungeon id -/// <summary> -/// Given a Achievement id returns the related dungeon id -/// </summary> -/// <param name="uint32">Achievement id</param> -/// <returns>uint32</returns> + @param[in] achievementId Achievement id + @returns dungeon id +*/ uint32 LFGMgr::GetDungeonIdForAchievement(uint32 achievementId) { std::map<uint32, uint32>::iterator itr = m_EncountersByAchievement.find(achievementId); @@ -2274,48 +2011,21 @@ uint32 LFGMgr::GetDungeonIdForAchievement(uint32 achievementId) return 0; }; -/// <summary> -/// Given a list of guids returns the concatenation using | as delimiter -/// </summary> -/// <param name="LfgGuidList ">list of guids</param> -/// <returns>std::string</returns> +/** + Given a list of guids returns the concatenation using | as delimiter + + @param[in] check list of guids + @returns Concatenated string +*/ std::string LFGMgr::ConcatenateGuids(LfgGuidList check) { if (check.empty()) return ""; - LfgGuidSet guidSet; - while (!check.empty()) - { - guidSet.insert(check.front()); - check.pop_front(); - } - std::ostringstream o; - LfgGuidSet::const_iterator it = guidSet.begin(); + LfgGuidList::const_iterator it = check.begin(); o << (*it); - for (++it; it != guidSet.end(); ++it) + for (++it; it != check.end(); ++it) o << "|" << (*it); - guidSet.clear(); return o.str(); } - -/// <summary> -/// Given a list of dungeonIds returns the concatenation using , as delimiter -/// </summary> -/// <param name="LfgDungeonSet ">list of dungeons</param> -/// <returns>std::string</returns> -std::string LFGMgr::ConcatenateDungeons(LfgDungeonSet* dungeons) -{ - std::string dungeonstr = ""; - if (dungeons && !dungeons->empty()) - { - std::ostringstream o; - LfgDungeonSet::const_iterator it = dungeons->begin(); - o << (*it); - for (++it; it != dungeons->end(); ++it) - o << ", " << (*it); - dungeonstr = o.str(); - } - return dungeonstr; -} diff --git a/src/server/game/DungeonFinding/LFGMgr.h b/src/server/game/DungeonFinding/LFGMgr.h index 02b0694146a..ddfbfc5235b 100755 --- a/src/server/game/DungeonFinding/LFGMgr.h +++ b/src/server/game/DungeonFinding/LFGMgr.h @@ -27,113 +27,145 @@ class Player; enum LFGenum { - LFG_TIME_ROLECHECK = 2*MINUTE, - LFG_TIME_BOOT = 2*MINUTE, - LFG_TIME_PROPOSAL = 2*MINUTE, - LFG_TANKS_NEEDED = 1, - LFG_HEALERS_NEEDED = 1, - LFG_DPS_NEEDED = 3, - LFG_QUEUEUPDATE_INTERVAL = 15*IN_MILLISECONDS, - LFG_SPELL_DUNGEON_COOLDOWN = 71328, - LFG_SPELL_DUNGEON_DESERTER = 71041, - LFG_SPELL_LUCK_OF_THE_DRAW = 72221, + LFG_TIME_ROLECHECK = 2*MINUTE, + LFG_TIME_BOOT = 2*MINUTE, + LFG_TIME_PROPOSAL = 2*MINUTE, + LFG_TANKS_NEEDED = 1, + LFG_HEALERS_NEEDED = 1, + LFG_DPS_NEEDED = 3, + LFG_QUEUEUPDATE_INTERVAL = 15*IN_MILLISECONDS, + LFG_SPELL_DUNGEON_COOLDOWN = 71328, + LFG_SPELL_DUNGEON_DESERTER = 71041, + LFG_SPELL_LUCK_OF_THE_DRAW = 72221, }; +/// Determines the type of instance enum LfgType { - LFG_TYPE_NONE = 0, // Internal use only - LFG_TYPE_DUNGEON = 1, - LFG_TYPE_RAID = 2, - LFG_TYPE_QUEST = 3, - LFG_TYPE_ZONE = 4, - LFG_TYPE_HEROIC = 5, - LFG_TYPE_RANDOM = 6, + LFG_TYPE_NONE = 0, // Internal use only + LFG_TYPE_DUNGEON = 1, + LFG_TYPE_RAID = 2, + LFG_TYPE_QUEST = 3, + LFG_TYPE_ZONE = 4, + LFG_TYPE_HEROIC = 5, + LFG_TYPE_RANDOM = 6, }; +/// Proposal states enum LfgProposalState { - LFG_PROPOSAL_INITIATING = 0, - LFG_PROPOSAL_FAILED = 1, - LFG_PROPOSAL_SUCCESS = 2, + LFG_PROPOSAL_INITIATING = 0, + LFG_PROPOSAL_FAILED = 1, + LFG_PROPOSAL_SUCCESS = 2, }; +/// Instance lock types enum LfgLockStatusType { - LFG_LOCKSTATUS_OK = 0, // Internal use only - LFG_LOCKSTATUS_INSUFFICIENT_EXPANSION = 1, - LFG_LOCKSTATUS_TOO_LOW_LEVEL = 2, - LFG_LOCKSTATUS_TOO_HIGH_LEVEL = 3, - LFG_LOCKSTATUS_TOO_LOW_GEAR_SCORE = 4, - LFG_LOCKSTATUS_TOO_HIGH_GEAR_SCORE = 5, - LFG_LOCKSTATUS_RAID_LOCKED = 6, - LFG_LOCKSTATUS_ATTUNEMENT_TOO_LOW_LEVEL = 1001, - LFG_LOCKSTATUS_ATTUNEMENT_TOO_HIGH_LEVEL = 1002, - LFG_LOCKSTATUS_QUEST_NOT_COMPLETED = 1022, - LFG_LOCKSTATUS_MISSING_ITEM = 1025, - LFG_LOCKSTATUS_NOT_IN_SEASON = 1031, + LFG_LOCKSTATUS_OK = 0, // Internal use only + LFG_LOCKSTATUS_INSUFFICIENT_EXPANSION = 1, + LFG_LOCKSTATUS_TOO_LOW_LEVEL = 2, + LFG_LOCKSTATUS_TOO_HIGH_LEVEL = 3, + LFG_LOCKSTATUS_TOO_LOW_GEAR_SCORE = 4, + LFG_LOCKSTATUS_TOO_HIGH_GEAR_SCORE = 5, + LFG_LOCKSTATUS_RAID_LOCKED = 6, + LFG_LOCKSTATUS_ATTUNEMENT_TOO_LOW_LEVEL = 1001, + LFG_LOCKSTATUS_ATTUNEMENT_TOO_HIGH_LEVEL = 1002, + LFG_LOCKSTATUS_QUEST_NOT_COMPLETED = 1022, + LFG_LOCKSTATUS_MISSING_ITEM = 1025, + LFG_LOCKSTATUS_NOT_IN_SEASON = 1031, }; +/// Teleport errors enum LfgTeleportError { - LFG_TELEPORTERROR_OK = 0, // Internal use - LFG_TELEPORTERROR_PLAYER_DEAD = 1, - LFG_TELEPORTERROR_FALLING = 2, - //LFG_TELEPORTERROR_UNK2 = 3, // You can't do that right now - LFG_TELEPORTERROR_FATIGUE = 4, - //LFG_TELEPORTERROR_UNK3 = 5, // No reaction - LFG_TELEPORTERROR_INVALID_LOCATION = 6, - //LFG_TELEPORTERROR_UNK4 = 7, // You can't do that right now - //LFG_TELEPORTERROR_UNK5 = 8, // You can't do that right now + // 3, 7, 8 = "You can't do that right now" | 5 = No client reaction + LFG_TELEPORTERROR_OK = 0, // Internal use + LFG_TELEPORTERROR_PLAYER_DEAD = 1, + LFG_TELEPORTERROR_FALLING = 2, + LFG_TELEPORTERROR_FATIGUE = 4, + LFG_TELEPORTERROR_INVALID_LOCATION = 6, }; +/// Queue join results enum LfgJoinResult { - LFG_JOIN_OK = 0, // Joined (no client msg) - LFG_JOIN_FAILED = 1, // RoleCheck Failed - LFG_JOIN_GROUPFULL = 2, // Your group is full - //LFG_JOIN_UNK3 = 3, // No client reaction - LFG_JOIN_INTERNAL_ERROR = 4, // Internal LFG Error - LFG_JOIN_NOT_MEET_REQS = 5, // You do not meet the requirements for the chosen dungeons - LFG_JOIN_PARTY_NOT_MEET_REQS = 6, // One or more party members do not meet the requirements for the chosen dungeons - LFG_JOIN_MIXED_RAID_DUNGEON = 7, // You cannot mix dungeons, raids, and random when picking dungeons - LFG_JOIN_MULTI_REALM = 8, // The dungeon you chose does not support players from multiple realms - LFG_JOIN_DISCONNECTED = 9, // One or more party members are pending invites or disconnected - LFG_JOIN_PARTY_INFO_FAILED = 10, // Could not retrieve information about some party members - LFG_JOIN_DUNGEON_INVALID = 11, // One or more dungeons was not valid - LFG_JOIN_DESERTER = 12, // You can not queue for dungeons until your deserter debuff wears off - LFG_JOIN_PARTY_DESERTER = 13, // One or more party members has a deserter debuff - LFG_JOIN_RANDOM_COOLDOWN = 14, // You can not queue for random dungeons while on random dungeon cooldown - LFG_JOIN_PARTY_RANDOM_COOLDOWN = 15, // One or more party members are on random dungeon cooldown - LFG_JOIN_TOO_MUCH_MEMBERS = 16, // You can not enter dungeons with more that 5 party members - LFG_JOIN_USING_BG_SYSTEM = 17, // You can not use the dungeon system while in BG or arenas - //LFG_JOIN_FAILED2 = 18, // RoleCheck Failed + // 3 = No client reaction | 18 = "Rolecheck failed" + LFG_JOIN_OK = 0, // Joined (no client msg) + LFG_JOIN_FAILED = 1, // RoleCheck Failed + LFG_JOIN_GROUPFULL = 2, // Your group is full + LFG_JOIN_INTERNAL_ERROR = 4, // Internal LFG Error + LFG_JOIN_NOT_MEET_REQS = 5, // You do not meet the requirements for the chosen dungeons + LFG_JOIN_PARTY_NOT_MEET_REQS = 6, // One or more party members do not meet the requirements for the chosen dungeons + LFG_JOIN_MIXED_RAID_DUNGEON = 7, // You cannot mix dungeons, raids, and random when picking dungeons + LFG_JOIN_MULTI_REALM = 8, // The dungeon you chose does not support players from multiple realms + LFG_JOIN_DISCONNECTED = 9, // One or more party members are pending invites or disconnected + LFG_JOIN_PARTY_INFO_FAILED = 10, // Could not retrieve information about some party members + LFG_JOIN_DUNGEON_INVALID = 11, // One or more dungeons was not valid + LFG_JOIN_DESERTER = 12, // You can not queue for dungeons until your deserter debuff wears off + LFG_JOIN_PARTY_DESERTER = 13, // One or more party members has a deserter debuff + LFG_JOIN_RANDOM_COOLDOWN = 14, // You can not queue for random dungeons while on random dungeon cooldown + LFG_JOIN_PARTY_RANDOM_COOLDOWN = 15, // One or more party members are on random dungeon cooldown + LFG_JOIN_TOO_MUCH_MEMBERS = 16, // You can not enter dungeons with more that 5 party members + LFG_JOIN_USING_BG_SYSTEM = 17, // You can not use the dungeon system while in BG or arenas }; -enum LfgRoleCheckResult +/// Role check states +enum LfgRoleCheckState { - LFG_ROLECHECK_FINISHED = 1, // Role check finished - LFG_ROLECHECK_INITIALITING = 2, // Role check begins - LFG_ROLECHECK_MISSING_ROLE = 3, // Someone didn't selected a role after 2 mins - LFG_ROLECHECK_WRONG_ROLES = 4, // Can't form a group with that role selection - LFG_ROLECHECK_ABORTED = 5, // Someone leave the group - LFG_ROLECHECK_NO_ROLE = 6, // Someone selected no role + LFG_ROLECHECK_FINISHED = 1, // Role check finished + LFG_ROLECHECK_INITIALITING = 2, // Role check begins + LFG_ROLECHECK_MISSING_ROLE = 3, // Someone didn't selected a role after 2 mins + LFG_ROLECHECK_WRONG_ROLES = 4, // Can't form a group with that role selection + LFG_ROLECHECK_ABORTED = 5, // Someone leave the group + LFG_ROLECHECK_NO_ROLE = 6, // Someone selected no role }; +/// Answer state (Also used to check compatibilites) enum LfgAnswer { - LFG_ANSWER_PENDING = -1, - LFG_ANSWER_DENY = 0, - LFG_ANSWER_AGREE = 1, + LFG_ANSWER_PENDING = -1, + LFG_ANSWER_DENY = 0, + LFG_ANSWER_AGREE = 1, }; -// Dungeon and reason why player can't join + +// Forward declaration (just to have all typedef together) +struct LfgReward; +struct LfgLockStatus; +struct LfgQueueInfo; +struct LfgRoleCheck; +struct LfgProposal; +struct LfgProposalPlayer; +struct LfgPlayerBoot; + +typedef std::set<uint64> LfgGuidSet; +typedef std::list<uint64> LfgGuidList; +typedef std::map<uint8, LfgGuidList> LfgGuidListMap; +typedef std::set<Player*> PlayerSet; +typedef std::list<Player*> LfgPlayerList; +typedef std::multimap<uint32, LfgReward const*> LfgRewardMap; +typedef std::pair<LfgRewardMap::const_iterator, LfgRewardMap::const_iterator> LfgRewardMapBounds; +typedef std::map<std::string, LfgAnswer> LfgCompatibleMap; +typedef std::map<uint64, LfgDungeonSet> LfgDungeonMap; +typedef std::set<LfgLockStatus*> LfgLockStatusSet; +typedef std::map<uint32, LfgLockStatusSet*> LfgLockStatusMap; +typedef std::map<uint32, uint8> LfgRolesMap; +typedef std::map<uint32, LfgAnswer> LfgAnswerMap; +typedef std::map<uint32, LfgRoleCheck*> LfgRoleCheckMap; +typedef std::map<uint64, LfgQueueInfo*> LfgQueueInfoMap; +typedef std::map<uint32, LfgProposal*> LfgProposalMap; +typedef std::map<uint32, LfgProposalPlayer*> LfgProposalPlayerMap; +typedef std::map<uint32, LfgPlayerBoot*> LfgPlayerBootMap; + +/// Dungeon and reason why player can't join struct LfgLockStatus { - uint32 dungeon; - LfgLockStatusType lockstatus; + uint32 dungeon; ///< Dungeon Id + LfgLockStatusType lockstatus; ///< Lock type }; -// Reward info +/// Reward info struct LfgReward { uint32 maxLevel; @@ -156,34 +188,29 @@ struct LfgReward } }; -typedef std::map<uint32, uint8> LfgRolesMap; -typedef std::map<uint32, LfgAnswer> LfgAnswerMap; -typedef std::list<uint64> LfgGuidList; -typedef std::map<uint64, LfgDungeonSet*> LfgDungeonMap; - -// Stores player or group queue info +/// Stores player or group queue info struct LfgQueueInfo { LfgQueueInfo(): tanks(LFG_TANKS_NEEDED), healers(LFG_HEALERS_NEEDED), dps(LFG_DPS_NEEDED) {}; - time_t joinTime; // Player queue join time (to calculate wait times) - uint8 tanks; // Tanks needed - uint8 healers; // Healers needed - uint8 dps; // Dps needed - LfgDungeonSet dungeons; // Selected Player/Group Dungeon/s - LfgRolesMap roles; // Selected Player Role/s + time_t joinTime; ///< Player queue join time (to calculate wait times) + uint8 tanks; ///< Tanks needed + uint8 healers; ///< Healers needed + uint8 dps; ///< Dps needed + LfgDungeonSet dungeons; ///< Selected Player/Group Dungeon/s + LfgRolesMap roles; ///< Selected Player Role/s }; +/// Stores player data related to proposal to join struct LfgProposalPlayer { LfgProposalPlayer(): role(0), accept(LFG_ANSWER_PENDING), groupLowGuid(0) {}; - uint8 role; // Proposed role - LfgAnswer accept; // Accept status (-1 not answer | 0 Not agree | 1 agree) - uint32 groupLowGuid; // Original group guid (Low guid) 0 if no original group + uint8 role; ///< Proposed role + LfgAnswer accept; ///< Accept status (-1 not answer | 0 Not agree | 1 agree) + uint32 groupLowGuid; ///< Original group guid (Low guid) 0 if no original group }; -typedef std::map<uint32, LfgProposalPlayer*> LfgProposalPlayerMap; -// Stores all Dungeon Proposal after matching candidates +/// Stores group data related to proposal to join struct LfgProposal { LfgProposal(uint32 dungeon): dungeonId(dungeon), state(LFG_PROPOSAL_INITIATING), groupLowGuid(0), leaderLowGuid(0) {} @@ -195,125 +222,126 @@ struct LfgProposal players.clear(); queues.clear(); }; - uint32 dungeonId; // Dungeon to join - LfgProposalState state; // State of the proposal - uint32 groupLowGuid; // Proposal group (0 if new) - uint32 leaderLowGuid; // Leader guid. - time_t cancelTime; // Time when we will cancel this proposal - LfgGuidList queues; // Queue Ids to remove/readd - LfgProposalPlayerMap players; // Player current groupId + uint32 dungeonId; ///< Dungeon to join + LfgProposalState state; ///< State of the proposal + uint32 groupLowGuid; ///< Proposal group (0 if new) + uint32 leaderLowGuid; ///< Leader guid. + time_t cancelTime; ///< Time when we will cancel this proposal + LfgGuidList queues; ///< Queue Ids to remove/readd + LfgProposalPlayerMap players; ///< Players data }; -// Stores all rolecheck info of a group that wants to join LFG +/// Stores all rolecheck info of a group that wants to join struct LfgRoleCheck { - time_t cancelTime; - LfgRolesMap roles; - LfgRoleCheckResult result; - LfgDungeonSet dungeons; - uint32 leader; + time_t cancelTime; ///< Time when the rolecheck will fail + LfgRolesMap roles; ///< Player selected roles + LfgRoleCheckState result; ///< State of the rolecheck + LfgDungeonSet dungeons; ///< Dungeons group is applying for (expanded random dungeons) + uint32 rDungeonId; ///< Random Dungeon Id. + uint32 leader; ///< Leader of the group }; -// Stores information of a current vote to kick someone from a group +/// Stores information of a current vote to kick someone from a group struct LfgPlayerBoot { - time_t cancelTime; // Time left to vote - bool inProgress; // Vote in progress - LfgAnswerMap votes; // Player votes (-1 not answer | 0 Not agree | 1 agree) - uint32 victimLowGuid; // Player guid to be kicked (can't vote) - uint8 votedNeeded; // Votes needed to kick the player - std::string reason; // kick reason + time_t cancelTime; ///< Time left to vote + bool inProgress; ///< Vote in progress + LfgAnswerMap votes; ///< Player votes (-1 not answer | 0 Not agree | 1 agree) + uint32 victimLowGuid; ///< Player guid to be kicked (can't vote) + uint8 votedNeeded; ///< Votes needed to kick the player + std::string reason; ///< kick reason }; -typedef std::set<Player*> PlayerSet; -typedef std::set<LfgLockStatus*> LfgLockStatusSet; -typedef std::map<uint32, LfgLockStatusSet*> LfgLockStatusMap; -typedef std::map<uint64, LfgQueueInfo*> LfgQueueInfoMap; -typedef std::map<uint32, LfgRoleCheck*> LfgRoleCheckMap; -typedef std::map<uint32, LfgProposal*> LfgProposalMap; -typedef std::map<uint32, LfgPlayerBoot*> LfgPlayerBootMap; -typedef std::multimap<uint32, LfgReward const*> LfgRewardMap; -typedef std::pair<LfgRewardMap::const_iterator, LfgRewardMap::const_iterator> LfgRewardMapBounds; -typedef std::list<Player*> LfgPlayerList; -typedef std::set<uint64> LfgGuidSet; -typedef std::map<std::string, LfgAnswer> LfgCompatibleMap; - - class LFGMgr { friend class ACE_Singleton<LFGMgr, ACE_Null_Mutex>; public: LFGMgr(); ~LFGMgr(); - - void Join(Player* plr, uint8 roles, LfgDungeonSet* dungeons, std::string comment); - void Leave(Player* plr, Group* grp = NULL); - void OfferContinue(Group* grp); - void TeleportPlayer(Player* plr, bool out, bool fromOpcode = false); - void UpdateProposal(uint32 proposalId, uint32 lowGuid, bool accept); - void UpdateBoot(Player* plr, bool accept); - void UpdateRoleCheck(Group* grp, Player* plr = NULL, bool newRoleCheck = false); void Update(uint32 diff); - bool isRandomDungeon(uint32 dungeonId); - void InitBoot(Group* grp, uint32 plowGuid, uint32 vlowGuid, std::string reason); - + // Reward void LoadDungeonEncounters(); void LoadRewards(); void RewardDungeonDoneFor(const uint32 dungeonId, Player* player); uint32 GetDungeonIdForAchievement(uint32 achievementId); - - LfgLockStatusMap* GetPartyLockStatusDungeons(Player* plr, LfgDungeonSet* dungeons = NULL); - LfgDungeonSet* GetRandomDungeons(uint8 level, uint8 expansion); - LfgLockStatusSet* GetPlayerLockStatusDungeons(Player* plr, LfgDungeonSet* dungeons = NULL, bool useEntry = true); LfgReward const* GetRandomDungeonReward(uint32 dungeon, uint8 level); + // Queue + void Join(Player* plr, uint8 roles, LfgDungeonSet& dungeons, std::string& comment); + void Leave(Player* plr, Group* grp = NULL); + + // Role Check + void UpdateRoleCheck(Group* grp, Player* plr = NULL, bool newRoleCheck = false); + + // Proposals + void UpdateProposal(uint32 proposalId, uint32 lowGuid, bool accept); + + // Teleportation + void TeleportPlayer(Player* plr, bool out, bool fromOpcode = false); + + // Vote kick + void InitBoot(Group* grp, uint32 plowGuid, uint32 vlowGuid, std::string reason); + void UpdateBoot(Player* plr, bool accept); + void OfferContinue(Group* grp); + + // Lock info + LfgLockStatusMap* GetPartyLockStatusDungeons(Player* plr); + LfgLockStatusSet* GetPlayerLockStatusDungeons(Player* plr); + private: - void Cleaner(); - void AddGuidToNewQueue(uint64 guid); + // Queue + void AddToQueue(uint64& guid, uint8 queueId); + bool RemoveFromQueue(uint64& guid); - bool RemoveFromQueue(uint64 guid); + // Proposals void RemoveProposal(LfgProposalMap::iterator itProposal, LfgUpdateType type); - LfgProposal* FindNewGroups(LfgGuidList check, LfgGuidList all); - + // Group Matching + LfgProposal* FindNewGroups(LfgGuidList& check, LfgGuidList& all); bool CheckGroupRoles(LfgRolesMap &groles, bool removeLeaderFlag = true); bool CheckCompatibility(LfgGuidList check, LfgProposal*& pProposal); - LfgDungeonSet* CheckCompatibleDungeons(LfgDungeonMap* dungeonsMap, PlayerSet* players); - LfgLockStatusMap* CheckCompatibleDungeons(LfgDungeonSet* dungeons, PlayerSet* players, bool returnLockMap = true); + LfgLockStatusMap* CheckCompatibleDungeons(LfgDungeonSet& dungeons, PlayerSet& players, bool returnLockMap = true); void SetCompatibles(std::string concatenatedGuids, bool compatibles); LfgAnswer GetCompatibles(std::string concatenatedGuids); void RemoveFromCompatibles(uint64 guid); - std::string ConcatenateGuids(LfgGuidList check); - std::string ConcatenateDungeons(LfgDungeonSet* dungeons); - LfgLockStatusMap* GetGroupLockStatusDungeons(PlayerSet* pPlayers, LfgDungeonSet* dungeons, bool useEntry = true); - LfgDungeonSet* GetDungeonsByRandom(uint32 randomdungeon); - LfgDungeonSet* GetAllDungeons(); + // Lock info + LfgLockStatusMap* GetGroupLockStatusDungeons(PlayerSet& players, LfgDungeonSet& dungeons, bool useEntry); + LfgLockStatusSet* GetPlayerLockStatusDungeons(Player* plr, LfgDungeonSet& dungeons, bool useEntry); + + // Generic + void GetDungeonsByRandom(uint32 randomdungeon, LfgDungeonSet& dungeons); LfgType GetDungeonType(uint32 dungeon); + std::string ConcatenateGuids(LfgGuidList check); - LfgRewardMap m_RewardMap; // Stores rewards for random dungeons - std::map<uint32, uint32> m_EncountersByAchievement; // Stores dungeon ids associated with achievements (for rewards) - LfgDungeonMap m_CachedDungeonMap; // Stores all dungeons by groupType - LfgQueueInfoMap m_QueueInfoMap; // Queued groups - LfgGuidList m_currentQueue; // Ordered list. Used to find groups - LfgGuidList m_newToQueue; // New groups to add to queue - LfgCompatibleMap m_CompatibleMap; // Compatible dungeons - LfgProposalMap m_Proposals; // Current Proposals - LfgPlayerBootMap m_Boots; // Current player kicks - LfgRoleCheckMap m_RoleChecks; // Current Role checks - uint32 m_QueueTimer; // used to check interval of update - uint32 m_lfgProposalId; // used as internal counter for proposals - int32 m_WaitTimeAvg; - int32 m_WaitTimeTank; - int32 m_WaitTimeHealer; - int32 m_WaitTimeDps; - uint32 m_NumWaitTimeAvg; - uint32 m_NumWaitTimeTank; - uint32 m_NumWaitTimeHealer; - uint32 m_NumWaitTimeDps; - bool m_update; + // General variables + bool m_update; ///< Doing an update? + uint32 m_QueueTimer; ///< used to check interval of update + uint32 m_lfgProposalId; ///< used as internal counter for proposals + int32 m_WaitTimeAvg; ///< Average wait time to find a group queuing as multiple roles + int32 m_WaitTimeTank; ///< Average wait time to find a group queuing as tank + int32 m_WaitTimeHealer; ///< Average wait time to find a group queuing as healer + int32 m_WaitTimeDps; ///< Average wait time to find a group queuing as dps + uint32 m_NumWaitTimeAvg; ///< Num of players used to calc avs wait time + uint32 m_NumWaitTimeTank; ///< Num of players used to calc tank wait time + uint32 m_NumWaitTimeHealer; ///< Num of players used to calc healers wait time + uint32 m_NumWaitTimeDps; ///< Num of players used to calc dps wait time + LfgDungeonMap m_CachedDungeonMap; ///< Stores all dungeons by groupType + // Reward System + LfgRewardMap m_RewardMap; ///< Stores rewards for random dungeons + std::map<uint32, uint32> m_EncountersByAchievement;///< Stores dungeon ids associated with achievements (for rewards) + // Queue + LfgQueueInfoMap m_QueueInfoMap; ///< Queued groups + LfgGuidListMap m_currentQueue; ///< Ordered list. Used to find groups + LfgGuidListMap m_newToQueue; ///< New groups to add to queue + LfgCompatibleMap m_CompatibleMap; ///< Compatible dungeons + // Rolecheck - Proposal - Vote Kicks + LfgRoleCheckMap m_RoleChecks; ///< Current Role checks + LfgProposalMap m_Proposals; ///< Current Proposals + LfgPlayerBootMap m_Boots; ///< Current player kicks }; #define sLFGMgr (*ACE_Singleton<LFGMgr, ACE_Null_Mutex>::instance()) diff --git a/src/server/game/DungeonFinding/LFGScripts.cpp b/src/server/game/DungeonFinding/LFGScripts.cpp new file mode 100644 index 00000000000..d9f81435e93 --- /dev/null +++ b/src/server/game/DungeonFinding/LFGScripts.cpp @@ -0,0 +1,148 @@ +/* + * Copyright (C) 2008-2010 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +/* + * Interaction between core and LFGScripts + */ + +#include "Common.h" +#include "SharedDefines.h" +#include "Player.h" +#include "Group.h" +#include "ScriptPCH.h" +#include "LFGScripts.h" +#include "LFGMgr.h" + +LFGScripts::LFGScripts(): GroupScript("LFGScripts"), PlayerScript("LFGScripts") {} + +void LFGScripts::OnAddMember(Group* group, uint64 guid) +{ + uint64 gguid = group->GetGUID(); + if (!gguid) + return; + + sLog.outDebug("LFGScripts::OnAddMember [" UI64FMTD "]: added [" UI64FMTD "]", gguid, guid); + for (GroupReference *itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) + { + if (Player *plrg = itr->getSource()) + { + plrg->GetSession()->SendLfgUpdatePlayer(LFG_UPDATETYPE_CLEAR_LOCK_LIST); + plrg->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_CLEAR_LOCK_LIST); + } + } + + // TODO - if group is queued and new player is added convert to rolecheck without notify the current players queued + if (group->GetLfgState() == LFG_STATE_QUEUED) + sLFGMgr.Leave(NULL, group); + + Player *plr = sObjectMgr.GetPlayer(guid); + if (plr && plr->GetLfgState() == LFG_STATE_QUEUED) + sLFGMgr.Leave(plr); +} + +void LFGScripts::OnRemoveMember(Group* group, uint64 guid, RemoveMethod& method, uint64 kicker, const char* reason) +{ + uint64 gguid = group->GetGUID(); + if (!gguid || method == GROUP_REMOVEMETHOD_DEFAULT) + return; + + sLog.outDebug("LFGScripts::OnRemoveMember [" UI64FMTD "]: remove [" UI64FMTD "] Method: %d Kicker: [" UI64FMTD "] Reason: %s", gguid, guid, method, kicker, (reason ? reason : "")); + if (group->GetLfgState() == LFG_STATE_QUEUED) + { + // TODO - Do not remove, just remove the one leaving and rejoin queue with all other data + sLFGMgr.Leave(NULL, group); + } + + if (!group->isLFGGroup()) + return; + + if (method == GROUP_REMOVEMETHOD_KICK) // Player have been kicked + { + // TODO - Update internal kick cooldown of kicker + std::string str_reason = ""; + if (reason) + str_reason = std::string(reason); + sLFGMgr.InitBoot(group, GUID_LOPART(kicker), GUID_LOPART(guid), str_reason); + return; + } + + if (Player *plr = sObjectMgr.GetPlayer(guid)) + { + /* + if (method == GROUP_REMOVEMETHOD_LEAVE) + // Add deserter flag + else if (group->isLfgKickActive()) + // Update internal kick cooldown of kicked + */ + + plr->ClearLfgState(); + plr->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_LEADER); + if (plr->GetMap()->IsDungeon()) // Teleport player out the dungeon + sLFGMgr.TeleportPlayer(plr, true); + } + + if (group->GetLfgState() != LFG_STATE_FINISHED_DUNGEON)// Need more players to finish the dungeon + sLFGMgr.OfferContinue(group); +} + +void LFGScripts::OnDisband(Group* group) +{ +} + +void LFGScripts::OnChangeLeader(Group* group, uint64 newLeaderGuid, uint64 oldLeaderGuid) +{ + uint64 gguid = group->GetGUID(); + if (!gguid) + return; + + sLog.outDebug("LFGScripts::OnChangeLeader [" UI64FMTD "]: old [" UI64FMTD "] new [" UI64FMTD "]", gguid, newLeaderGuid, oldLeaderGuid); + Player *plr = sObjectMgr.GetPlayer(newLeaderGuid); + if (plr) + plr->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_LEADER); + + plr = sObjectMgr.GetPlayer(oldLeaderGuid); + if (plr) + plr->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_GROUP_DISBAND); +} + +void LFGScripts::OnInviteMember(Group* group, uint64 guid) +{ + uint64 gguid = group->GetGUID(); + if (!gguid) + return; + + sLog.outDebug("LFGScripts::OnInviteMember [" UI64FMTD "]: invite [" UI64FMTD "] leader [" UI64FMTD "]", gguid, guid, group->GetLeaderGUID()); + sLFGMgr.Leave(NULL, group); +} + +void LFGScripts::OnLevelChanged(Player* /*player*/, uint8 /*newLevel*/) +{ + // TODO - Invalidate LockStatus from cache +} + +void LFGScripts::OnLogout(Player* player) +{ + sLFGMgr.Leave(player); + player->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_REMOVED_FROM_QUEUE); + player->GetSession()->SendLfgUpdatePlayer(LFG_UPDATETYPE_REMOVED_FROM_QUEUE); + player->GetSession()->SendLfgUpdateSearch(false); +} + +void LFGScripts::OnLogin(Player* /*player*/) +{ + // TODO - Restore LfgPlayerData and send proper status to player if it was in a group +}
\ No newline at end of file diff --git a/src/server/game/DungeonFinding/LFGScripts.h b/src/server/game/DungeonFinding/LFGScripts.h new file mode 100644 index 00000000000..e6216cf8d8e --- /dev/null +++ b/src/server/game/DungeonFinding/LFGScripts.h @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2008-2010 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +/* + * Interaction between core and LFGScripts + */ + +#include "Common.h" +#include "SharedDefines.h" +#include "ScriptPCH.h" + +class Player; +class Group; + +class LFGScripts: public GroupScript, PlayerScript +{ + public: + LFGScripts(); + + // Group Hooks + void OnAddMember(Group* group, uint64 guid); + void OnRemoveMember(Group* group, uint64 guid, RemoveMethod& method, uint64 kicker, const char* reason); + void OnDisband(Group* group); + void OnChangeLeader(Group* group, uint64 newLeaderGuid, uint64 oldLeaderGuid); + void OnInviteMember(Group* group, uint64 guid); + + // Player Hooks + void OnLevelChanged(Player* player, uint8 newLevel); + void OnLogout(Player* player); + void OnLogin(Player* player); +}; diff --git a/src/server/game/Entities/Creature/Creature.cpp b/src/server/game/Entities/Creature/Creature.cpp index 6c943721b5b..c7b270a344d 100755 --- a/src/server/game/Entities/Creature/Creature.cpp +++ b/src/server/game/Entities/Creature/Creature.cpp @@ -182,7 +182,7 @@ void Creature::AddToWorld() if (!IsInWorld()) { if (m_zoneScript) - m_zoneScript->OnCreatureCreate(this, true); + m_zoneScript->OnCreatureCreate(this); sObjectAccessor.AddObject(this); Unit::AddToWorld(); SearchFormation(); @@ -197,7 +197,7 @@ void Creature::RemoveFromWorld() if (IsInWorld()) { if (m_zoneScript) - m_zoneScript->OnCreatureCreate(this, false); + m_zoneScript->OnCreatureRemove(this); if (m_formation) formation_mgr.RemoveCreatureFromGroup(m_formation, this); Unit::RemoveFromWorld(); @@ -614,17 +614,17 @@ void Creature::RegenerateMana() float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA); float Spirit = GetStat(STAT_SPIRIT); - addvalue = uint32((Spirit/5.0f + 17.0f) * ManaIncreaseRate); + addvalue = uint32((Spirit / 5.0f + 17.0f) * ManaIncreaseRate); } } else - addvalue = maxValue/3; + addvalue = maxValue / 3; // Apply modifiers (if any). AuraEffectList const& ModPowerRegenPCTAuras = GetAuraEffectsByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT); for (AuraEffectList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i) if ((*i)->GetMiscValue() == POWER_MANA) - addvalue = uint32(addvalue * ((*i)->GetAmount() + 100) / 100.0f); + AddPctN(addvalue, (*i)->GetAmount()); addvalue += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_POWER_REGEN, POWER_MANA) * CREATURE_REGEN_INTERVAL / (5 * IN_MILLISECONDS); @@ -661,7 +661,7 @@ void Creature::RegenerateHealth() // Apply modifiers (if any). AuraEffectList const& ModPowerRegenPCTAuras = GetAuraEffectsByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT); for (AuraEffectList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i) - addvalue = uint32(addvalue * ((*i)->GetAmount() + 100) / 100.0f); + AddPctN(addvalue, (*i)->GetAmount()); addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_REGEN) * CREATURE_REGEN_INTERVAL / (5 * IN_MILLISECONDS); diff --git a/src/server/game/Entities/Creature/GossipDef.h b/src/server/game/Entities/Creature/GossipDef.h index b6eba922559..df321683893 100755 --- a/src/server/game/Entities/Creature/GossipDef.h +++ b/src/server/game/Entities/Creature/GossipDef.h @@ -159,7 +159,7 @@ class GossipMenu void AddMenuItem(uint8 Icon, char const* Message, uint32 dtSender, uint32 dtAction, char const* BoxMessage, uint32 BoxMoney, bool Coded = false); void SetMenuId(uint32 menu_id) { m_gMenuId = menu_id; } - uint32 GetMenuId() { return m_gMenuId; } + uint32 GetMenuId() const { return m_gMenuId; } void AddGossipMenuItemData(uint32 action_menu, uint32 action_poi, uint32 action_script); @@ -173,12 +173,12 @@ class GossipMenu return m_gItems.empty(); } - GossipMenuItem const& GetItem(unsigned int Id) + GossipMenuItem const& GetItem(unsigned int Id) const { return m_gItems[ Id ]; } - GossipMenuItemData const& GetItemData(unsigned int indexId) + GossipMenuItemData const& GetItemData(unsigned int indexId) const { return m_gItemsData[indexId]; } @@ -217,7 +217,7 @@ class QuestMenu bool HasItem(uint32 questid); - QuestMenuItem const& GetItem(uint16 Id) + QuestMenuItem const& GetItem(uint16 Id) const { return m_qItems[ Id ]; } diff --git a/src/server/game/Entities/GameObject/GameObject.cpp b/src/server/game/Entities/GameObject/GameObject.cpp index 5cf6240bea6..5a6411491f9 100755 --- a/src/server/game/Entities/GameObject/GameObject.cpp +++ b/src/server/game/Entities/GameObject/GameObject.cpp @@ -125,7 +125,7 @@ void GameObject::AddToWorld() if (!IsInWorld()) { if (m_zoneScript) - m_zoneScript->OnGameObjectCreate(this, true); + m_zoneScript->OnGameObjectCreate(this); sObjectAccessor.AddObject(this); WorldObject::AddToWorld(); @@ -138,7 +138,7 @@ void GameObject::RemoveFromWorld() if (IsInWorld()) { if (m_zoneScript) - m_zoneScript->OnGameObjectCreate(this, false); + m_zoneScript->OnGameObjectRemove(this); // Possible crash at access to deleted GO in Unit::m_gameobj if (uint64 owner_guid = GetOwnerGUID()) @@ -246,8 +246,8 @@ bool GameObject::Create(uint32 guidlow, uint32 name_id, Map *map, uint32 phaseMa SetGoAnimProgress(animprogress); break; } - LastUsedScriptID = GetGOInfo()->ScriptId; + AIM_Initialize(); return true; } diff --git a/src/server/game/Entities/Item/ItemEnchantmentMgr.cpp b/src/server/game/Entities/Item/ItemEnchantmentMgr.cpp index 7ff96662f51..e177e4db485 100755 --- a/src/server/game/Entities/Item/ItemEnchantmentMgr.cpp +++ b/src/server/game/Entities/Item/ItemEnchantmentMgr.cpp @@ -48,15 +48,11 @@ void LoadRandomEnchantmentsTable() { RandomItemEnch.clear(); // for reload case - EnchantmentStore::const_iterator tab; - uint32 entry, ench; - float chance; - uint32 count = 0; - QueryResult result = WorldDatabase.Query("SELECT entry, ench, chance FROM item_enchantment_template"); if (result) { + uint32 count = 0; barGoLink bar(result->GetRowCount()); do @@ -64,9 +60,9 @@ void LoadRandomEnchantmentsTable() Field *fields = result->Fetch(); bar.step(); - entry = fields[0].GetUInt32(); - ench = fields[1].GetUInt32(); - chance = fields[2].GetFloat(); + uint32 entry = fields[0].GetUInt32(); + uint32 ench = fields[1].GetUInt32(); + float chance = fields[2].GetFloat(); if (chance > 0.000001f && chance <= 100.0f) RandomItemEnch[entry].push_back(EnchStoreItem(ench, chance)); diff --git a/src/server/game/Entities/Object/Object.h b/src/server/game/Entities/Object/Object.h index b9dd8ed44c0..08c5f716db8 100755 --- a/src/server/game/Entities/Object/Object.h +++ b/src/server/game/Entities/Object/Object.h @@ -229,8 +229,9 @@ class Object void ApplyPercentModFloatValue(uint16 index, float val, bool apply) { - val = val != -100.0f ? val : -99.9f ; - SetFloatValue(index, GetFloatValue(index) * (apply?(100.0f+val)/100.0f : 100.0f / (100.0f+val))); + float value = GetFloatValue(index); + ApplyPercentModFloatVar(value, val, apply); + SetFloatValue(index, value); } void SetFlag(uint16 index, uint32 newFlag); diff --git a/src/server/game/Entities/Pet/Pet.cpp b/src/server/game/Entities/Pet/Pet.cpp index 2b02020299a..5c53ca3cbb5 100755 --- a/src/server/game/Entities/Pet/Pet.cpp +++ b/src/server/game/Entities/Pet/Pet.cpp @@ -613,11 +613,11 @@ void Creature::Regenerate(Powers power) AuraEffectList const& ModPowerRegenPCTAuras = GetAuraEffectsByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT); for (AuraEffectList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i) if (Powers((*i)->GetMiscValue()) == power) - addvalue *= ((*i)->GetAmount() + 100) / 100.0f; + AddPctN(addvalue, (*i)->GetAmount()); addvalue += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_POWER_REGEN, power) * (isHunterPet()? PET_FOCUS_REGEN_INTERVAL : CREATURE_REGEN_INTERVAL) / (5 * IN_MILLISECONDS); - ModifyPower(power, (int32)addvalue); + ModifyPower(power, int32(addvalue)); } void Pet::LoseHappiness() @@ -1351,8 +1351,6 @@ bool Pet::addSpell(uint32 spell_id,ActiveStates active /*= ACT_DECIDE*/, PetSpel return false; } - uint32 oldspell_id = 0; - PetSpell newspell; newspell.state = state; newspell.type = type; @@ -1402,7 +1400,6 @@ bool Pet::addSpell(uint32 spell_id,ActiveStates active /*= ACT_DECIDE*/, PetSpel if (newspell.active == ACT_ENABLED) ToggleAutocast(itr2->first, false); - oldspell_id = itr2->first; unlearnSpell(itr2->first,false,false); break; } @@ -1943,7 +1940,7 @@ void Pet::CastPetAura(PetAura const* aura) if (auraId == 35696) // Demonic Knowledge { - int32 basePoints = int32(aura->GetDamage() * (GetStat(STAT_STAMINA) + GetStat(STAT_INTELLECT)) / 100); + int32 basePoints = CalculatePctF(aura->GetDamage(), GetStat(STAT_STAMINA) + GetStat(STAT_INTELLECT)); CastCustomSpell(this, auraId, &basePoints, NULL, NULL, true); } else diff --git a/src/server/game/Entities/Player/Player.cpp b/src/server/game/Entities/Player/Player.cpp index cc4ca11f207..0049c9ca702 100755 --- a/src/server/game/Entities/Player/Player.cpp +++ b/src/server/game/Entities/Player/Player.cpp @@ -1045,22 +1045,22 @@ int32 Player::getMaxTimer(MirrorTimerType timer) switch (timer) { case FATIGUE_TIMER: - return MINUTE*IN_MILLISECONDS; + return MINUTE * IN_MILLISECONDS; case BREATH_TIMER: { if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) || GetSession()->GetSecurity() >= AccountTypes(sWorld.getIntConfig(CONFIG_DISABLE_BREATHING))) return DISABLED_MIRROR_TIMER; - int32 UnderWaterTime = 3*MINUTE*IN_MILLISECONDS; + int32 UnderWaterTime = 3 * MINUTE * IN_MILLISECONDS; AuraEffectList const& mModWaterBreathing = GetAuraEffectsByType(SPELL_AURA_MOD_WATER_BREATHING); for (AuraEffectList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i) - UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetAmount()) / 100.0f); + AddPctN(UnderWaterTime, (*i)->GetAmount()); return UnderWaterTime; } case FIRE_TIMER: { if (!isAlive()) return DISABLED_MIRROR_TIMER; - return 1*IN_MILLISECONDS; + return 1 * IN_MILLISECONDS; } default: return 0; @@ -1547,7 +1547,7 @@ void Player::setDeathState(DeathState s) clearResurrectRequestData(); // remove form before other mods to prevent incorrect stats calculation - RemoveAurasDueToSpell(m_ShapeShiftFormSpellId); + RemoveAurasByType(SPELL_AURA_MOD_SHAPESHIFT); //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD) RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true); @@ -2259,7 +2259,7 @@ void Player::Regenerate(Powers power) AuraEffectList const& ModPowerRegenPCTAuras = GetAuraEffectsByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT); for (AuraEffectList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i) if (Powers((*i)->GetMiscValue()) == power) - addvalue *= ((*i)->GetAmount() + 100) / 100.0f; + AddPctN(addvalue, (*i)->GetAmount()); // Butchery requires combat for this effect if (power != POWER_RUNIC_POWER || isInCombat()) @@ -2339,12 +2339,12 @@ void Player::RegenerateHealth() { AuraEffectList const& mModHealthRegenPct = GetAuraEffectsByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT); for (AuraEffectList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i) - addvalue *= (100.0f + (*i)->GetAmount()) / 100.0f; + AddPctN(addvalue, (*i)->GetAmount()); addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_REGEN) * 2 * IN_MILLISECONDS / (5 * IN_MILLISECONDS); } else if (HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT)) - addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f; + ApplyPctN(addvalue, GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT)); if (!IsStandState()) addvalue *= 1.5; @@ -3589,7 +3589,9 @@ bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const { // note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell // talent dependent passives activated at form apply have proper stance data - bool need_cast = (!spellInfo->Stances || (m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))))); + ShapeshiftForm form = GetShapeshiftForm(); + bool need_cast = (!spellInfo->Stances || (form && (spellInfo->Stances & (1 << (form - 1)))) || + (!form && (spellInfo->AttributesEx2 & SPELL_ATTR_EX2_NOT_NEED_SHAPESHIFT))); //Check CasterAuraStates return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState))); @@ -5355,7 +5357,7 @@ void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, floa float val = 1.0f; - switch(modType) + switch (modType) { case FLAT_MOD: m_auraBaseMod[modGroup][modType] += apply ? amount : -amount; @@ -5363,9 +5365,7 @@ void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, floa case PCT_MOD: if (amount <= -100.0f) amount = -200.0f; - - val = (100.0f + amount) / 100.0f; - m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val); + ApplyPercentModFloatVar(m_auraBaseMod[modGroup][modType], amount, apply); break; } @@ -5615,7 +5615,7 @@ void Player::UpdateRating(CombatRating cr) AuraEffectList const& modRatingFromStat = GetAuraEffectsByType(SPELL_AURA_MOD_RATING_FROM_STAT); for (AuraEffectList::const_iterator i = modRatingFromStat.begin(); i != modRatingFromStat.end(); ++i) if ((*i)->GetMiscValue() & (1<<cr)) - amount += int32(GetStat(Stats((*i)->GetMiscValueB())) * (*i)->GetAmount() / 100.0f); + amount += int32(CalculatePctN(GetStat(Stats((*i)->GetMiscValueB())), (*i)->GetAmount())); if (amount < 0) amount = 0; SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount)); @@ -5906,7 +5906,7 @@ void Player::UpdateWeaponSkill (WeaponAttackType attType) if (IsInFeralForm()) return; // always maximized SKILL_FERAL_COMBAT in fact - if (m_form == FORM_TREE) + if (GetShapeshiftForm() == FORM_TREE) return; // use weapon but not skill up if (pVictim && pVictim->GetTypeId() == TYPEID_UNIT && (pVictim->ToCreature()->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_SKILLGAIN)) @@ -6891,7 +6891,7 @@ bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, int32 honor, bool pvpt honor_f /= groupsize; // apply honor multiplier from aura (not stacking-get highest) - honor_f *= (GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN_PCT) + 100) / 100.0f; + AddPctN(honor_f, GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN_PCT)); } honor_f *= sWorld.getRate(RATE_HONOR); @@ -7796,7 +7796,7 @@ void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply if (apply) { // Cannot be used in this stance/form - if (GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK) + if (GetErrorAtShapeshiftedCast(spellInfo, GetShapeshiftForm()) != SPELL_CAST_OK) return; if (form_change) // check aura active state from other form @@ -7816,7 +7816,7 @@ void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply if (form_change) // check aura compatibility { // Cannot be used in this stance/form - if (GetErrorAtShapeshiftedCast(spellInfo, m_form) == SPELL_CAST_OK) + if (GetErrorAtShapeshiftedCast(spellInfo, GetShapeshiftForm()) == SPELL_CAST_OK) return; // and remove only not compatible at form change } @@ -13593,7 +13593,6 @@ void Player::PrepareGossipMenu(WorldObject *pSource, uint32 menuId, bool showQue uint32 npcflags = 0; Creature *pCreature = NULL; - GameObject *pGo = NULL; if (pSource->GetTypeId() == TYPEID_UNIT) { @@ -13602,8 +13601,6 @@ void Player::PrepareGossipMenu(WorldObject *pSource, uint32 menuId, bool showQue if (npcflags & UNIT_NPC_FLAG_QUESTGIVER && showQuests) PrepareQuestMenu(pSource->GetGUID()); } - else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT) - pGo = (GameObject*)pSource; for (GossipMenuItemsMap::const_iterator itr = pMenuItemBounds.first; itr != pMenuItemBounds.second; ++itr) { @@ -14526,7 +14523,7 @@ void Player::RewardQuest(Quest const *pQuest, uint32 reward, Object* questGiver, // handle SPELL_AURA_MOD_XP_QUEST_PCT auras Unit::AuraEffectList const& ModXPPctAuras = GetAuraEffectsByType(SPELL_AURA_MOD_XP_QUEST_PCT); for (Unit::AuraEffectList::const_iterator i = ModXPPctAuras.begin(); i != ModXPPctAuras.end(); ++i) - XP = uint32(XP*(1.0f + (*i)->GetAmount() / 100.0f)); + AddPctN(XP, (*i)->GetAmount()); int32 moneyRew = 0; if (getLevel() < sWorld.getIntConfig(CONFIG_MAX_PLAYER_LEVEL)) @@ -19404,7 +19401,7 @@ bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc return false; } - if (m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW) + if (IsInDisallowedMountForm()) { WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4); data << uint32(ERR_TAXIPLAYERSHAPESHIFTED); @@ -19426,8 +19423,8 @@ bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc { RemoveAurasByType(SPELL_AURA_MOUNTED); - if (m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW) - RemoveAurasDueToSpell(m_ShapeShiftFormSpellId); + if (IsInDisallowedMountForm()) + RemoveAurasByType(SPELL_AURA_MOD_SHAPESHIFT); if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL)) if (spell->m_spellInfo->Id != spellid) @@ -19696,7 +19693,9 @@ void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs) void Player::InitDataForForm(bool reapplyMods) { - SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form); + ShapeshiftForm form = GetShapeshiftForm(); + + SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(form); if (ssEntry && ssEntry->attackSpeed) { SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed); @@ -19706,7 +19705,7 @@ void Player::InitDataForForm(bool reapplyMods) else SetRegularAttackTime(); - switch(m_form) + switch (form) { case FORM_GHOUL: case FORM_CAT: @@ -21859,16 +21858,16 @@ bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim) if (pGroupGuy->isAlive() && not_gray_member_with_max_level && pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel()) { - uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1); + uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp * rate) : uint32((xp * rate / 2) + 1); // handle SPELL_AURA_MOD_XP_PCT auras Unit::AuraEffectList const& ModXPPctAuras = GetAuraEffectsByType(SPELL_AURA_MOD_XP_PCT); for (Unit::AuraEffectList::const_iterator i = ModXPPctAuras.begin(); i != ModXPPctAuras.end(); ++i) - itr_xp = uint32(itr_xp*(1.0f + (*i)->GetAmount() / 100.0f)); + AddPctN(itr_xp, (*i)->GetAmount()); pGroupGuy->GiveXP(itr_xp, pVictim, group_rate); if (Pet* pet = pGroupGuy->GetPet()) - pet->GivePetXP(itr_xp/2); + pet->GivePetXP(itr_xp / 2); } // quest objectives updated only for alive group member or dead but with not released body @@ -21898,7 +21897,7 @@ bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim) // handle SPELL_AURA_MOD_XP_PCT auras Unit::AuraEffectList const& ModXPPctAuras = GetAuraEffectsByType(SPELL_AURA_MOD_XP_PCT); for (Unit::AuraEffectList::const_iterator i = ModXPPctAuras.begin(); i != ModXPPctAuras.end(); ++i) - xp = uint32(xp*(1.0f + (*i)->GetAmount() / 100.0f)); + AddPctN(xp, (*i)->GetAmount()); GiveXP(xp, pVictim); @@ -22190,13 +22189,13 @@ PartyResult Player::CanUninviteFromGroup() const if (grp->GetLfgKicks() == GROUP_MAX_LFG_KICKS) return ERR_PARTY_LFG_BOOT_LIMIT; - if (grp->isLfgKickActive()) + if (GetLfgState() == LFG_STATE_BOOT) return ERR_PARTY_LFG_BOOT_IN_PROGRESS; if (grp->GetMembersCount() <= GROUP_LFG_KICK_VOTES_NEEDED) return ERR_PARTY_LFG_BOOT_TOO_FEW_PLAYERS; - if (grp->isLfgDungeonComplete()) + if (GetLfgState() == LFG_STATE_FINISHED_DUNGEON) return ERR_PARTY_LFG_BOOT_DUNGEON_COMPLETE; if (grp->isRollLootActive()) diff --git a/src/server/game/Entities/Player/Player.h b/src/server/game/Entities/Player/Player.h index e64c7d0807b..0034222f31a 100755 --- a/src/server/game/Entities/Player/Player.h +++ b/src/server/game/Entities/Player/Player.h @@ -445,8 +445,9 @@ enum PlayerFieldByteFlags // used in PLAYER_FIELD_BYTES2 values enum PlayerFieldByte2Flags { - PLAYER_FIELD_BYTE2_NONE = 0x0000, - PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW = 0x4000 + PLAYER_FIELD_BYTE2_NONE = 0x00, + PLAYER_FIELD_BYTE2_STEALTH = 0x20, + PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW = 0x40 }; enum ActivateTaxiReplies @@ -2260,10 +2261,27 @@ class Player : public Unit, public GridObject<Player> void SetLfgComment(std::string _comment) { m_LookingForGroup.comment = _comment; } uint8 GetLfgRoles() { return m_LookingForGroup.roles; } void SetLfgRoles(uint8 _roles) { m_LookingForGroup.roles = _roles; } - bool GetLfgUpdate() { return m_LookingForGroup.update; } - void SetLfgUpdate(bool update) { m_LookingForGroup.update = update; } - LfgState GetLfgState() { return m_LookingForGroup.state; } - void SetLfgState(LfgState state) { m_LookingForGroup.state = state; } + LfgState GetLfgState() const { return m_LookingForGroup.state; } + void SetLfgState(LfgState state) + { + + switch(state) + { + case LFG_STATE_NONE: + case LFG_STATE_DUNGEON: + case LFG_STATE_FINISHED_DUNGEON: + m_LookingForGroup.oldState = state; + // No break on purpose + default: + m_LookingForGroup.state = state; + } + } + void ClearLfgState() + { + m_LookingForGroup.applyDungeons.clear(); + m_LookingForGroup.roles = ROLE_NONE; + m_LookingForGroup.state = m_LookingForGroup.oldState; + } bool isUsingLfg() { return GetLfgState() != LFG_STATE_NONE; } typedef std::set<uint32> DFQuestsDoneList; @@ -2735,7 +2753,7 @@ template <class T> T Player::ApplySpellMod(uint32 spellId, SpellModOp op, T &bas if (mod->op == SPELLMOD_CASTING_TIME && basevalue >= T(10000) && mod->value <= -100) continue; - totalmul *= 1.0f + (float)mod->value / 100.0f; + AddPctN(totalmul, mod->value); } DropModCharge(mod, spell); diff --git a/src/server/game/Entities/Player/SocialMgr.h b/src/server/game/Entities/Player/SocialMgr.h index 1baf668cd8b..e64b82fdfa2 100755 --- a/src/server/game/Entities/Player/SocialMgr.h +++ b/src/server/game/Entities/Player/SocialMgr.h @@ -128,7 +128,7 @@ class PlayerSocial // Misc bool HasFriend(uint32 friend_guid); bool HasIgnore(uint32 ignore_guid); - uint32 GetPlayerGUID() { return m_playerGUID; } + uint32 GetPlayerGUID() const { return m_playerGUID; } void SetPlayerGUID(uint32 guid) { m_playerGUID = guid; } uint32 GetNumberOfSocialsWithFlag(SocialFlag flag); private: diff --git a/src/server/game/Entities/Unit/StatSystem.cpp b/src/server/game/Entities/Unit/StatSystem.cpp index 10e855188fc..20d751546c1 100755 --- a/src/server/game/Entities/Unit/StatSystem.cpp +++ b/src/server/game/Entities/Unit/StatSystem.cpp @@ -213,7 +213,7 @@ void Player::UpdateArmor() for (AuraEffectList::const_iterator i = mResbyIntellect.begin(); i != mResbyIntellect.end(); ++i) { if ((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL) - value += int32(GetStat(Stats((*i)->GetMiscValueB())) * (*i)->GetAmount() / 100.0f); + value += CalculatePctN(GetStat(Stats((*i)->GetMiscValueB())), (*i)->GetAmount()); } value *= GetModifierValue(unitMod, TOTAL_PCT); @@ -296,13 +296,13 @@ void Player::UpdateAttackPowerAndDamage(bool ranged) index_mod = UNIT_FIELD_RANGED_ATTACK_POWER_MODS; index_mult = UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER; - switch(getClass()) + switch (getClass()) { case CLASS_HUNTER: val2 = level * 2.0f + GetStat(STAT_AGILITY) - 10.0f; break; case CLASS_ROGUE: val2 = level + GetStat(STAT_AGILITY) - 10.0f; break; case CLASS_WARRIOR:val2 = level + GetStat(STAT_AGILITY) - 10.0f; break; case CLASS_DRUID: - switch(m_form) + switch (GetShapeshiftForm()) { case FORM_CAT: case FORM_BEAR: @@ -317,19 +317,20 @@ void Player::UpdateAttackPowerAndDamage(bool ranged) } else { - switch(getClass()) + switch (getClass()) { - case CLASS_WARRIOR: val2 = level*3.0f + GetStat(STAT_STRENGTH)*2.0f - 20.0f; break; - case CLASS_PALADIN: val2 = level*3.0f + GetStat(STAT_STRENGTH)*2.0f - 20.0f; break; - case CLASS_DEATH_KNIGHT: val2 = level*3.0f + GetStat(STAT_STRENGTH)*2.0f - 20.0f; break; - case CLASS_ROGUE: val2 = level*2.0f + GetStat(STAT_STRENGTH) + GetStat(STAT_AGILITY) - 20.0f; break; - case CLASS_HUNTER: val2 = level*2.0f + GetStat(STAT_STRENGTH) + GetStat(STAT_AGILITY) - 20.0f; break; - case CLASS_SHAMAN: val2 = level*2.0f + GetStat(STAT_STRENGTH) + GetStat(STAT_AGILITY) - 20.0f; break; + case CLASS_WARRIOR: val2 = level * 3.0f + GetStat(STAT_STRENGTH) * 2.0f - 20.0f; break; + case CLASS_PALADIN: val2 = level * 3.0f + GetStat(STAT_STRENGTH) * 2.0f - 20.0f; break; + case CLASS_DEATH_KNIGHT: val2 = level * 3.0f + GetStat(STAT_STRENGTH) * 2.0f - 20.0f; break; + case CLASS_ROGUE: val2 = level * 2.0f + GetStat(STAT_STRENGTH) + GetStat(STAT_AGILITY) - 20.0f; break; + case CLASS_HUNTER: val2 = level * 2.0f + GetStat(STAT_STRENGTH) + GetStat(STAT_AGILITY) - 20.0f; break; + case CLASS_SHAMAN: val2 = level * 2.0f + GetStat(STAT_STRENGTH) + GetStat(STAT_AGILITY) - 20.0f; break; case CLASS_DRUID: { - //Check if Predatory Strikes is skilled - float mLevelMult = 0.0; - switch(m_form) + ShapeshiftForm form = GetShapeshiftForm(); + // Check if Predatory Strikes is skilled + float mLevelMult = 0.0f; + switch (form) { case FORM_CAT: case FORM_BEAR: @@ -342,7 +343,7 @@ void Player::UpdateAttackPowerAndDamage(bool ranged) // Predatory Strikes (effect 0) if ((*itr)->GetEffIndex() == 0 && (*itr)->GetSpellProto()->SpellIconID == 1563) { - mLevelMult = (*itr)->GetAmount() / 100.0f; + mLevelMult = CalculatePctN(1.0f, (*itr)->GetAmount()); break; } } @@ -351,17 +352,17 @@ void Player::UpdateAttackPowerAndDamage(bool ranged) default: break; } - switch(m_form) + switch (form) { case FORM_CAT: - val2 = getLevel()*(mLevelMult+2.0f) + GetStat(STAT_STRENGTH)*2.0f + GetStat(STAT_AGILITY) - 20.0f + m_baseFeralAP; break; + val2 = getLevel() * (mLevelMult + 2.0f) + GetStat(STAT_STRENGTH) * 2.0f + GetStat(STAT_AGILITY) - 20.0f + m_baseFeralAP; break; case FORM_BEAR: case FORM_DIREBEAR: - val2 = getLevel()*(mLevelMult+3.0f) + GetStat(STAT_STRENGTH)*2.0f - 20.0f + m_baseFeralAP; break; + val2 = getLevel() * (mLevelMult + 3.0f) + GetStat(STAT_STRENGTH) * 2.0f - 20.0f + m_baseFeralAP; break; case FORM_MOONKIN: - val2 = getLevel()*(mLevelMult+1.5f) + GetStat(STAT_STRENGTH)*2.0f - 20.0f + m_baseFeralAP; break; + val2 = getLevel() * (mLevelMult + 1.5f) + GetStat(STAT_STRENGTH) * 2.0f - 20.0f + m_baseFeralAP; break; default: - val2 = GetStat(STAT_STRENGTH)*2.0f - 20.0f; break; + val2 = GetStat(STAT_STRENGTH) * 2.0f - 20.0f; break; } break; } @@ -383,14 +384,14 @@ void Player::UpdateAttackPowerAndDamage(bool ranged) { AuraEffectList const& mRAPbyStat = GetAuraEffectsByType(SPELL_AURA_MOD_RANGED_ATTACK_POWER_OF_STAT_PERCENT); for (AuraEffectList::const_iterator i = mRAPbyStat.begin(); i != mRAPbyStat.end(); ++i) - attPowerMod += int32(GetStat(Stats((*i)->GetMiscValue())) * (*i)->GetAmount() / 100.0f); + attPowerMod += CalculatePctN(GetStat(Stats((*i)->GetMiscValue())), (*i)->GetAmount()); } } else { AuraEffectList const& mAPbyStat = GetAuraEffectsByType(SPELL_AURA_MOD_ATTACK_POWER_OF_STAT_PERCENT); for (AuraEffectList::const_iterator i = mAPbyStat.begin(); i != mAPbyStat.end(); ++i) - attPowerMod += int32(GetStat(Stats((*i)->GetMiscValue())) * (*i)->GetAmount() / 100.0f); + attPowerMod += CalculatePctN(GetStat(Stats((*i)->GetMiscValue())), (*i)->GetAmount()); AuraEffectList const& mAPbyArmor = GetAuraEffectsByType(SPELL_AURA_MOD_ATTACK_POWER_OF_ARMOR); for (AuraEffectList::const_iterator iter = mAPbyArmor.begin(); iter != mAPbyArmor.end(); ++iter) @@ -433,22 +434,18 @@ void Player::UpdateShieldBlockValue() void Player::CalculateMinMaxDamage(WeaponAttackType attType, bool normalized, bool addTotalPct, float& min_damage, float& max_damage) { UnitMods unitMod; - UnitMods attPower; switch(attType) { case BASE_ATTACK: default: unitMod = UNIT_MOD_DAMAGE_MAINHAND; - attPower = UNIT_MOD_ATTACK_POWER; break; case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; - attPower = UNIT_MOD_ATTACK_POWER; break; case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; - attPower = UNIT_MOD_ATTACK_POWER_RANGED; break; } @@ -742,7 +739,7 @@ void Player::UpdateManaRegen() int32 modManaRegenInterrupt = GetTotalAuraModifier(SPELL_AURA_MOD_MANA_REGEN_INTERRUPT); if (modManaRegenInterrupt > 100) modManaRegenInterrupt = 100; - SetStatFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER, power_regen_mp5 + power_regen * modManaRegenInterrupt / 100.0f); + SetStatFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER, power_regen_mp5 + CalculatePctN(power_regen, modManaRegenInterrupt)); SetStatFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER, power_regen_mp5 + power_regen); } @@ -961,13 +958,13 @@ bool Guardian::UpdateStats(Stats stat) aurEff = owner->GetAuraEffect(SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE, SPELLFAMILY_DEATHKNIGHT, 3010, 0); if (aurEff) { - SpellEntry const* sProto = aurEff->GetSpellProto(); // Then get the SpellProto and add the dummy effect value - mod += mod * (SpellMgr::CalculateSpellEffectAmount(sProto, 1) / 100.0f); // Ravenous Dead edits the original scale + SpellEntry const* sProto = aurEff->GetSpellProto(); // Then get the SpellProto and add the dummy effect value + AddPctN(mod, SpellMgr::CalculateSpellEffectAmount(sProto, 1)); // Ravenous Dead edits the original scale } // Glyph of the Ghoul aurEff = owner->GetAuraEffect(58686, 0); if (aurEff) - mod += (aurEff->GetAmount() / 100.0f); // Glyph of the Ghoul adds a flat value to the scale mod + mod += CalculatePctN(1.0f, aurEff->GetAmount()); // Glyph of the Ghoul adds a flat value to the scale mod ownersBonus = float(owner->GetStat(stat)) * mod; value += ownersBonus; } @@ -975,7 +972,7 @@ bool Guardian::UpdateStats(Stats stat) { if (owner->getClass() == CLASS_WARLOCK && isPet()) { - ownersBonus = float(owner->GetStat(STAT_STAMINA)) * 0.75f; + ownersBonus = CalculatePctN(owner->GetStat(STAT_STAMINA), 75); value += ownersBonus; } else @@ -990,7 +987,7 @@ bool Guardian::UpdateStats(Stats stat) if (itr != ToPet()->m_spells.end()) // If pet has Wild Hunt { SpellEntry const* sProto = sSpellStore.LookupEntry(itr->first); // Then get the SpellProto and add the dummy effect value - mod += mod * (SpellMgr::CalculateSpellEffectAmount(sProto, 0) / 100.0f); + AddPctN(mod, SpellMgr::CalculateSpellEffectAmount(sProto, 0)); } } ownersBonus = float(owner->GetStat(stat)) * mod; @@ -1002,7 +999,7 @@ bool Guardian::UpdateStats(Stats stat) { if (owner->getClass() == CLASS_WARLOCK || owner->getClass() == CLASS_MAGE) { - ownersBonus = float(owner->GetStat(stat)) * 0.3f; + ownersBonus = CalculatePctN(owner->GetStat(stat), 30); value += ownersBonus; } } @@ -1054,7 +1051,7 @@ void Guardian::UpdateResistances(uint32 school) // hunter and warlock pets gain 40% of owner's resistance if (isPet()) - value += float(m_owner->GetResistance(SpellSchools(school))) * 0.4f; + value += float(CalculatePctN(m_owner->GetResistance(SpellSchools(school)), 40)); SetResistance(SpellSchools(school), int32(value)); } @@ -1070,7 +1067,7 @@ void Guardian::UpdateArmor() // hunter and warlock pets gain 35% of owner's armor value if (isPet()) - bonus_armor = 0.35f * float(m_owner->GetArmor()); + bonus_armor = float(CalculatePctN(m_owner->GetArmor(), 35)); value = GetModifierValue(unitMod, BASE_VALUE); value *= GetModifierValue(unitMod, BASE_PCT); @@ -1160,7 +1157,7 @@ void Guardian::UpdateAttackPowerAndDamage(bool ranged) if (itr != ToPet()->m_spells.end()) // If pet has Wild Hunt { SpellEntry const* sProto = sSpellStore.LookupEntry(itr->first); // Then get the SpellProto and add the dummy effect value - mod += (SpellMgr::CalculateSpellEffectAmount(sProto, 1) / 100.0f); + mod += CalculatePctN(1.0f, SpellMgr::CalculateSpellEffectAmount(sProto, 1)); } } @@ -1278,8 +1275,8 @@ void Guardian::UpdateDamagePhysical(WeaponAttackType attType) { case 61682: case 61683: - mindamage = mindamage * (100.0f-float((*itr)->GetAmount()))/100.0f; - maxdamage = maxdamage * (100.0f-float((*itr)->GetAmount()))/100.0f; + AddPctN(mindamage, -(*itr)->GetAmount()); + AddPctN(maxdamage, -(*itr)->GetAmount()); break; default: break; diff --git a/src/server/game/Entities/Unit/Unit.cpp b/src/server/game/Entities/Unit/Unit.cpp index ab394fcc91c..317cdfaecfd 100755 --- a/src/server/game/Entities/Unit/Unit.cpp +++ b/src/server/game/Entities/Unit/Unit.cpp @@ -123,7 +123,6 @@ m_vehicleKit(NULL), m_unitTypeMask(UNIT_MASK_NONE), m_HostileRefManager(this) m_rootTimes = 0; m_state = 0; - m_form = FORM_NONE; m_deathState = ALIVE; for (uint8 i = 0; i < CURRENT_MAX_SPELL; ++i) @@ -140,7 +139,6 @@ m_vehicleKit(NULL), m_unitTypeMask(UNIT_MASK_NONE), m_HostileRefManager(this) m_interruptMask = 0; m_transform = 0; - m_ShapeShiftFormSpellId = 0; m_canModifyStats = false; for (uint8 i = 0; i < MAX_SPELL_IMMUNITY; ++i) @@ -568,7 +566,7 @@ uint32 Unit::DealDamage(Unit *pVictim, uint32 damage, CleanDamage const* cleanDa continue; SpellEntry const * spell = (*i)->GetSpellProto(); - uint32 share = uint32(damage * (float((*i)->GetAmount()) / 100.0f)); + uint32 share = CalculatePctN(damage, (*i)->GetAmount()); // TODO: check packets if damage is done by pVictim, or by attacker of pVictim DealDamageMods(shareDamageTarget, share, NULL); @@ -1004,7 +1002,7 @@ void Unit::CalculateSpellDamageTaken(SpellNonMeleeDamage *damageInfo, int32 dama critPctDamageMod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask); if (critPctDamageMod != 0) - damage = int32(damage * float((100.0f + critPctDamageMod)/100.0f)); + AddPctN(damage, critPctDamageMod); } // Spell weapon based damage CAN BE crit & blocked at same time @@ -1044,12 +1042,8 @@ void Unit::CalculateSpellDamageTaken(SpellNonMeleeDamage *damageInfo, int32 dama // Calculate absorb resist if (damage > 0) { - // Chaos Bolt - "Chaos Bolt cannot be resisted, and pierces through all absorption effects." - if (spellInfo->SpellIconID != 3178) - { - CalcAbsorbResist(pVictim, damageSchoolMask, SPELL_DIRECT_DAMAGE, damage, &damageInfo->absorb, &damageInfo->resist, spellInfo); - damage -= damageInfo->absorb + damageInfo->resist; - } + CalcAbsorbResist(pVictim, damageSchoolMask, SPELL_DIRECT_DAMAGE, damage, &damageInfo->absorb, &damageInfo->resist, spellInfo); + damage -= damageInfo->absorb + damageInfo->resist; } else damage = 0; @@ -1210,7 +1204,7 @@ void Unit::CalculateMeleeDamage(Unit *pVictim, uint32 damage, CalcDamageInfo *da // Increase crit damage from SPELL_AURA_MOD_CRIT_PERCENT_VERSUS mod += GetTotalAuraModifierByMiscMask(SPELL_AURA_MOD_CRIT_PERCENT_VERSUS, crTypeMask); if (mod != 0) - damageInfo->damage = int32((damageInfo->damage) * float((100.0f + mod)/100.0f)); + AddPctN(damageInfo->damage, mod); } break; case MELEE_HIT_PARRY: @@ -1472,14 +1466,14 @@ uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage, SpellEnt { if ((*j)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL && (*j)->IsAffectedOnSpell(spellInfo)) - armor = floor(float(armor) * (float(100 - (*j)->GetAmount()) / 100.0f)); + armor = floor(AddPctN(armor, -(*j)->GetAmount())); } AuraEffectList const& ResIgnoreAuras = GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_TARGET_RESIST); for (AuraEffectList::const_iterator j = ResIgnoreAuras.begin(); j != ResIgnoreAuras.end(); ++j) { if ((*j)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL) - armor = floor(float(armor) * (float(100 - (*j)->GetAmount()) / 100.0f)); + armor = floor(AddPctN(armor, -(*j)->GetAmount())); } if (GetTypeId() == TYPEID_PLAYER) @@ -1490,7 +1484,7 @@ uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage, SpellEnt // item neutral spell if ((*itr)->GetSpellProto()->EquippedItemClass == -1) { - armor = floor(float(armor) * (float(100 - (*itr)->GetAmount()) / 100.0f)); + armor = floor(AddPctN(armor, -(*itr)->GetAmount())); continue; } @@ -1501,7 +1495,7 @@ uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage, SpellEnt if (weapon && weapon->IsFitToSpellRequirements((*itr)->GetSpellProto())) { - armor = floor(float(armor) * (float(100 - (*itr)->GetAmount()) / 100.0f)); + armor = floor(AddPctN(armor, -(*itr)->GetAmount())); break; } } @@ -1511,15 +1505,15 @@ uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage, SpellEnt // Apply Player CR_ARMOR_PENETRATION rating if (GetTypeId() == TYPEID_PLAYER) { - float maxArmorPen=0; + float maxArmorPen = 0; if (getLevel() < 60) maxArmorPen = float(400 + 85 * pVictim->getLevel()); else maxArmorPen = 400 + 85 * pVictim->getLevel() + 4.5f * 85 * (pVictim->getLevel() - 59); // Cap armor penetration to this number - maxArmorPen = std::min(((armor+maxArmorPen) / 3),armor); + maxArmorPen = std::min((armor + maxArmorPen) / 3, armor); // Figure out how much armor do we ignore - float armorPen = maxArmorPen * this->ToPlayer()->GetRatingBonusValue(CR_ARMOR_PENETRATION) / 100.0f; + float armorPen = CalculatePctF(maxArmorPen, ToPlayer()->GetRatingBonusValue(CR_ARMOR_PENETRATION)); // Got the value, apply it armor -= armorPen; } @@ -1529,10 +1523,10 @@ uint32 Unit::CalcArmorReducedDamage(Unit* pVictim, const uint32 damage, SpellEnt float levelModifier = getLevel(); if (levelModifier > 59) - levelModifier = levelModifier + (4.5f * (levelModifier-59)); + levelModifier = levelModifier + (4.5f * (levelModifier - 59)); float tmpvalue = 0.1f * armor / (8.5f * levelModifier + 40); - tmpvalue = tmpvalue/(1.0f + tmpvalue); + tmpvalue = tmpvalue / (1.0f + tmpvalue); if (tmpvalue < 0.0f) tmpvalue = 0.0f; @@ -1601,14 +1595,14 @@ void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEff { if ((*j)->GetMiscValue() & schoolMask && (*j)->IsAffectedOnSpell(spellInfo)) - *resist= int32(float(*resist) * (float(100-(*j)->GetAmount())/100.0f)); + AddPctN(*resist, -(*j)->GetAmount()); } AuraEffectList const &ResIgnoreAuras = GetAuraEffectsByType(SPELL_AURA_MOD_IGNORE_TARGET_RESIST); for (AuraEffectList::const_iterator j = ResIgnoreAuras.begin(); j != ResIgnoreAuras.end(); ++j) { if ((*j)->GetMiscValue() & schoolMask) - *resist= int32(float(*resist) * (float(100-(*j)->GetAmount())/100.0f)); + AddPctN(*resist, -(*j)->GetAmount()); } } else @@ -1628,24 +1622,67 @@ void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEff // Incanter's Absorption, for converting to spell power int32 incanterAbsorption = 0; + // Ignore Absorption Auras + int32 auraAbsorbMod = 0; + AuraEffectList const & AbsIgnoreAurasA = GetAuraEffectsByType(SPELL_AURA_MOD_TARGET_ABSORB_SCHOOL); + for (AuraEffectList::const_iterator itr = AbsIgnoreAurasA.begin(); itr != AbsIgnoreAurasA.end(); ++itr) + { + if (!((*itr)->GetMiscValue() & schoolMask)) + continue; + + if ((*itr)->GetAmount() > auraAbsorbMod) + auraAbsorbMod = (*itr)->GetAmount(); + } + + AuraEffectList const & AbsIgnoreAurasB = GetAuraEffectsByType(SPELL_AURA_MOD_TARGET_ABILITY_ABSORB_SCHOOL); + for (AuraEffectList::const_iterator itr = AbsIgnoreAurasB.begin(); itr != AbsIgnoreAurasB.end(); ++itr) + { + if (!((*itr)->GetMiscValue() & schoolMask)) + continue; + + if (((*itr)->GetAmount() > auraAbsorbMod) && (*itr)->IsAffectedOnSpell(spellInfo)) + auraAbsorbMod = (*itr)->GetAmount(); + } + + AuraEffectList vSchoolAbsorb; + pVictim->FillOrderedAbsorbAuras(vSchoolAbsorb); + // absorb without mana cost - AuraEffectList const& vSchoolAbsorb = pVictim->GetAuraEffectsByType(SPELL_AURA_SCHOOL_ABSORB); - for (AuraEffectList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end() && RemainingDamage > 0; ++i) + for (AuraEffectList::const_iterator itr = vSchoolAbsorb.begin(); (itr != vSchoolAbsorb.end()) && (RemainingDamage > 0); ++itr) { - if (!((*i)->GetMiscValue() & schoolMask)) + if (!((*itr)->GetMiscValue() & schoolMask)) continue; - SpellEntry const* spellProto = (*i)->GetSpellProto(); + SpellEntry const * spellProto = (*itr)->GetSpellProto(); - // Max Amount can be absorbed by this aura - int32 currentAbsorb = (*i)->GetAmount(); + // Frost Warding + // Chaos Bolt ignore the absorption but still proc Frost Warding mana return + if ((spellProto->SpellFamilyName == SPELLFAMILY_MAGE) && (spellProto->Category == 56)) + if (AuraEffect * aurEff = pVictim->GetAuraEffect(SPELL_AURA_ADD_PCT_MODIFIER, SPELLFAMILY_MAGE, 501, EFFECT_0)) + { + int32 chance = SpellMgr::CalculateSpellEffectAmount(aurEff->GetSpellProto(), EFFECT_1); + + if (roll_chance_i(chance)) + { + triggeredSpells.push_back(TriggeredSpellInfo(57776, pVictim, pVictim, RemainingDamage, (*itr))); + RemainingDamage = RemainingDamage * auraAbsorbMod / 100; + continue; + } + } + if (auraAbsorbMod >= 100) // Do nothing if 100% absorb ignore + continue; + + // Max Amount can be absorbed by this aura + int32 currentAbsorb = (*itr)->GetAmount(); // Found empty aura (impossible but..) if (currentAbsorb <= 0) { existExpired = true; continue; } + currentAbsorb = (100 - auraAbsorbMod) * currentAbsorb / 100; + // Handle custom absorb auras // TODO: try find better way switch (spellProto->SpellFamilyName) @@ -1656,39 +1693,39 @@ void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEff if (spellProto->SpellIconID == 3066) { //reduces all damage taken while stun, fear or silence - if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED)) - RemainingDamage -= RemainingDamage * currentAbsorb / 100; + if (unitflag & (UNIT_FLAG_STUNNED | UNIT_FLAG_FLEEING | UNIT_FLAG_SILENCED)) + AddPctN(RemainingDamage, -currentAbsorb); continue; } // Nerves of Steel if (spellProto->SpellIconID == 2115) { // while affected by Stun and Fear - if (unitflag&(UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING)) - RemainingDamage -= RemainingDamage * currentAbsorb / 100; + if (unitflag & (UNIT_FLAG_STUNNED | UNIT_FLAG_FLEEING)) + AddPctN(RemainingDamage, -currentAbsorb); continue; } // Spell Deflection if (spellProto->SpellIconID == 3006) { // You have a chance equal to your Parry chance - if (damagetype == DIRECT_DAMAGE && // Only for direct damage - roll_chance_f(pVictim->GetUnitParryChance())) // Roll chance - RemainingDamage -= RemainingDamage * currentAbsorb / 100; + if ((damagetype == DIRECT_DAMAGE) && roll_chance_f(pVictim->GetUnitParryChance())) + AddPctN(RemainingDamage, -currentAbsorb); continue; } // Reflective Shield (Lady Malande boss) if (spellProto->Id == 41475) { - triggeredSpells.push_back(TriggeredSpellInfo(33619, pVictim, this, - std::min(RemainingDamage, currentAbsorb) / 2, *i)); + triggeredSpells.push_back( + TriggeredSpellInfo(33619, pVictim, this, std::min(RemainingDamage, currentAbsorb) / 2, *itr) + ); break; } - if (spellProto->Id == 39228 || // Argussian Compass - spellProto->Id == 60218) // Essence of Gossamer + if ((spellProto->Id == 39228) || // Argussian Compass + (spellProto->Id == 60218)) // Essence of Gossamer { // Max absorb stored in 1 dummy effect - int32 maxAbsorb = SpellMgr::CalculateSpellEffectAmount(spellProto, 1); + int32 maxAbsorb = SpellMgr::CalculateSpellEffectAmount(spellProto, EFFECT_1); if (maxAbsorb < currentAbsorb) currentAbsorb = maxAbsorb; break; @@ -1701,8 +1738,8 @@ void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEff if (spellProto->SpellIconID == 2253) { //reduces all damage taken while Stunned - if (pVictim->m_form == FORM_CAT && (unitflag & UNIT_FLAG_STUNNED)) - RemainingDamage -= RemainingDamage * currentAbsorb / 100; + if ((pVictim->GetShapeshiftForm() == FORM_CAT) && (unitflag & UNIT_FLAG_STUNNED)) + AddPctN(RemainingDamage, -currentAbsorb); continue; } // Savage Defense @@ -1711,7 +1748,7 @@ void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEff if (RemainingDamage < currentAbsorb) currentAbsorb = RemainingDamage; - (*i)->SetAmount(0); // guarantee removal + (*itr)->SetAmount(0); // guarantee removal existExpired = true; // maybe hacky but not crashy RemainingDamage -= currentAbsorb; @@ -1722,7 +1759,7 @@ void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEff { //reduces all damage taken while Stunned if (unitflag & UNIT_FLAG_STUNNED) - RemainingDamage -= RemainingDamage * currentAbsorb / 100; + AddPctN(RemainingDamage, -currentAbsorb); continue; } break; @@ -1732,13 +1769,9 @@ void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEff // Cheat Death (make less prio with Guardian Spirit case) if (spellProto->SpellIconID == 2109) { - if (!preventDeathSpell && - pVictim->GetTypeId() == TYPEID_PLAYER && // Only players - !pVictim->ToPlayer()->HasSpellCooldown(31231) && // Only if no cooldown - roll_chance_i((*i)->GetAmount())) // Only if roll - { - preventDeathSpell = (*i)->GetSpellProto(); - } + if (!preventDeathSpell && pVictim->ToPlayer()) + if (!pVictim->ToPlayer()->HasSpellCooldown(31231) && roll_chance_i((*itr)->GetAmount())) + preventDeathSpell = (*itr)->GetSpellProto(); continue; } break; @@ -1748,42 +1781,45 @@ void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEff // Guardian Spirit if (spellProto->SpellIconID == 2873) { - preventDeathSpell = (*i)->GetSpellProto(); - preventDeathAmount = (*i)->GetAmount(); + preventDeathSpell = (*itr)->GetSpellProto(); + preventDeathAmount = (*itr)->GetAmount(); continue; } - // Power Word: Shield if (spellProto->SpellFamilyFlags.IsEqual(0x1, 0, 0x400)) { if (pVictim == this) break; - Unit* caster = (*i)->GetCaster(); + + Unit * caster = (*itr)->GetCaster(); if (!caster) break; + // Reflective Shield - if (AuraEffect const * aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_PRIEST, 566, 0)) - { + if (AuraEffect const * aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_PRIEST, 566, EFFECT_0)) switch(aurEff->GetMiscValue()) { case 5065: // Rank 1 case 5064: // Rank 2 - triggeredSpells.push_back(TriggeredSpellInfo(33619, pVictim, this, - std::min(RemainingDamage, currentAbsorb) * aurEff->GetAmount() / 100, *i)); + triggeredSpells.push_back( + TriggeredSpellInfo(33619, pVictim, this, CalculatePctN(std::min(RemainingDamage, currentAbsorb), aurEff->GetAmount()), *itr) + ); break; default: sLog.outError("Unit::CalcAbsorbResist: unknown Reflective Shield spell %d", aurEff->GetId()); break; } - } } break; } case SPELLFAMILY_PALADIN: { // Ardent Defender - if (spellProto->SpellIconID == 2135 && pVictim->GetTypeId() == TYPEID_PLAYER) + if (spellProto->SpellIconID == 2135) { + if (!pVictim->ToPlayer()) + continue; + int32 remainingHealth = pVictim->GetHealth() - RemainingDamage; uint32 allowedHealth = pVictim->CountPctFromMaxHealth(35); // If damage kills us @@ -1800,9 +1836,9 @@ void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEff ? 1.0f : float(defenseSkillValue) / float(reqDefForMaxHeal); - int32 healAmount = int32(pVictim->CountPctFromMaxHealth(uint32((*i)->GetAmount() * pctFromDefense))); + int32 healAmount = int32(pVictim->CountPctFromMaxHealth(uint32((*itr)->GetAmount() * pctFromDefense))); pVictim->CastCustomSpell(pVictim, 66235, &healAmount, NULL, NULL, true); - pVictim->ToPlayer()->AddSpellCooldown(66235,0,time(NULL) + 120); + pVictim->ToPlayer()->AddSpellCooldown(66235, 0, time(NULL) + 120); } else if (remainingHealth < int32(allowedHealth)) { @@ -1810,10 +1846,9 @@ void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEff uint32 damageToReduce = (pVictim->GetHealth() < allowedHealth) ? RemainingDamage : allowedHealth - remainingHealth; - RemainingDamage -= damageToReduce * currentAbsorb / 100; + RemainingDamage -= CalculatePctN(damageToReduce, currentAbsorb); } continue; - } break; } @@ -1823,8 +1858,8 @@ void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEff if (spellProto->SpellIconID == 3066) { //reduces all damage taken while stun, fear or silence - if (unitflag & (UNIT_FLAG_STUNNED|UNIT_FLAG_FLEEING|UNIT_FLAG_SILENCED)) - RemainingDamage -= RemainingDamage * currentAbsorb / 100; + if (unitflag & (UNIT_FLAG_STUNNED | UNIT_FLAG_FLEEING | UNIT_FLAG_SILENCED)) + AddPctN(RemainingDamage, -currentAbsorb); continue; } break; @@ -1834,13 +1869,13 @@ void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEff switch (spellProto->Id) { case 51271: // Unbreakable Armor - if (Unit *caster = (*i)->GetCaster()) + if (Unit * caster = (*itr)->GetCaster()) { uint32 absorbed = uint32(currentAbsorb * caster->GetArmor() * 0.01f); // Glyph of Unbreakable Armor - if (AuraEffect *aurEff = caster->GetAuraEffect(58635, 0)) - absorbed += uint32(absorbed * aurEff->GetAmount() / 100); + if (AuraEffect const * aurEff = caster->GetAuraEffect(58635, 0)) + AddPctN(absorbed, aurEff->GetAmount()); RemainingDamage -= absorbed; } @@ -1849,13 +1884,13 @@ void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEff case 52285: case 52286: { - int32 remainingHp = (int32)pVictim->GetHealth() - RemainingDamage; + int32 remainingHp = int32(pVictim->GetHealth() - RemainingDamage); // min pct of hp is stored in effect 0 of talent spell uint32 rank = sSpellMgr.GetSpellRank(spellProto->Id); SpellEntry const * talentProto = sSpellStore.LookupEntry(sSpellMgr.GetSpellWithRank(49189, rank)); - int32 minHp = int32(pVictim->CountPctFromMaxHealth(SpellMgr::CalculateSpellEffectAmount(talentProto, 0, (*i)->GetCaster()))); + int32 minHp = int32(pVictim->CountPctFromMaxHealth(SpellMgr::CalculateSpellEffectAmount(talentProto, EFFECT_0, (*itr)->GetCaster()))); // Damage that would take you below [effect0] health or taken while you are at [effect0] if (remainingHp < minHp) { @@ -1868,18 +1903,18 @@ void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEff { // damage absorbed by Anti-Magic Shell energizes the DK with additional runic power. // This, if I'm not mistaken, shows that we get back ~2% of the absorbed damage as runic power. - int32 absorbed = RemainingDamage * currentAbsorb / 100; + int32 absorbed = CalculatePctN(RemainingDamage, currentAbsorb); RemainingDamage -= absorbed; - triggeredSpells.push_back(TriggeredSpellInfo(49088, pVictim, pVictim, absorbed * 2 / 10, *i)); + triggeredSpells.push_back(TriggeredSpellInfo(49088, pVictim, pVictim, absorbed * 2 / 10, *itr)); continue; } case 50462: // Anti-Magic Shell (on single party/raid member) - RemainingDamage -= RemainingDamage * currentAbsorb / 100; + AddPctN(RemainingDamage, -currentAbsorb); continue; case 50461: // Anti-Magic Zone - if (Unit *caster = (*i)->GetCaster()) + if (Unit * caster = (*itr)->GetCaster()) { - int32 absorbed = RemainingDamage * currentAbsorb / 100; + int32 absorbed = CalculatePctN(RemainingDamage, currentAbsorb); int32 canabsorb = caster->GetHealth(); if (canabsorb < absorbed) absorbed = canabsorb; @@ -1905,18 +1940,17 @@ void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEff // Fire Ward or Frost Ward or Ice Barrier (or Mana Shield) // for Incanter's Absorption converting to spell power - if (spellProto->SpellFamilyName == SPELLFAMILY_MAGE && spellProto->SpellFamilyFlags[2] & 0x000008) + if (spellProto->SpellFamilyName == SPELLFAMILY_MAGE && spellProto->SpellFamilyFlags[EFFECT_2] & 0x8) incanterAbsorption += currentAbsorb; // Reduce shield amount - (*i)->SetAmount((*i)->GetAmount() -currentAbsorb); + (*itr)->SetAmount((*itr)->GetAmount() - currentAbsorb); // Need remove it later - if ((*i)->GetAmount() <= 0) + if ((*itr)->GetAmount() <= 0) existExpired = true; } for (TriggeredSpellInfoVct::const_iterator itr = triggeredSpells.begin(); itr != triggeredSpells.end(); ++itr) - { if (itr->spell) itr->source->CastCustomSpell(itr->spell, SPELLVALUE_BASE_POINT0, itr->amount, itr->target, true, NULL, itr->auraEff); else if (itr->amount > 0) @@ -1925,177 +1959,189 @@ void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEff itr->source->DealDamageMods(itr->target, damage, NULL); itr->source->DealDamage(itr->target, damage, NULL, damagetype, schoolMask, 0, false); } - } // Remove all expired absorb auras if (existExpired) { - for (AuraEffectList::const_iterator i = vSchoolAbsorb.begin(); i != vSchoolAbsorb.end();) + AuraEffectList const & vSchoolAbsorbOri = pVictim->GetAuraEffectsByType(SPELL_AURA_SCHOOL_ABSORB); + + for (AuraEffectList::const_iterator itr = vSchoolAbsorbOri.begin(); itr != vSchoolAbsorbOri.end();) { - AuraEffect * auraEff =(*i); - ++i; + AuraEffect * auraEff = (*itr); + ++itr; + if (auraEff->GetAmount() <= 0) { uint32 removedAuras = pVictim->m_removedAurasCount; auraEff->GetBase()->Remove(AURA_REMOVE_BY_ENEMY_SPELL); - if (removedAuras+1<pVictim->m_removedAurasCount) - i=vSchoolAbsorb.begin(); + if (removedAuras + 1 < pVictim->m_removedAurasCount) + itr = vSchoolAbsorbOri.begin(); } } } - // absorb by mana cost - AuraEffectList const& vManaShield = pVictim->GetAuraEffectsByType(SPELL_AURA_MANA_SHIELD); - for (AuraEffectList::const_iterator i = vManaShield.begin(), next; i != vManaShield.end() && RemainingDamage > 0; i = next) + if (auraAbsorbMod < 100) // Do nothing if 100% absorb ignore { - next = i; ++next; - - // check damage school mask - if (((*i)->GetMiscValue() & schoolMask) == 0) - continue; + existExpired = false; - int32 currentAbsorb; - if (RemainingDamage >= (*i)->GetAmount()) - currentAbsorb = (*i)->GetAmount(); - else - currentAbsorb = RemainingDamage; + // absorb by mana cost + AuraEffectList const & vManaShield = pVictim->GetAuraEffectsByType(SPELL_AURA_MANA_SHIELD); - if (float manaMultiplier = SpellMgr::CalculateSpellEffectValueMultiplier((*i)->GetSpellProto(), (*i)->GetEffIndex(), (*i)->GetCaster())) + for (AuraEffectList::const_iterator itr = vManaShield.begin(); (itr != vManaShield.end()) && (RemainingDamage > 0); ++itr) { - int32 maxAbsorb = int32(pVictim->GetPower(POWER_MANA) / manaMultiplier); - if (currentAbsorb > maxAbsorb) - currentAbsorb = maxAbsorb; + // check damage school mask + if (!((*itr)->GetMiscValue() & schoolMask)) + continue; - int32 manaReduction = int32(currentAbsorb * manaMultiplier); - pVictim->ApplyPowerMod(POWER_MANA, manaReduction, false); - } + int32 currentAbsorb; - // Mana Shield (or Fire Ward or Frost Ward or Ice Barrier) - // for Incanter's Absorption converting to spell power - if ((*i)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_MAGE && (*i)->GetSpellProto()->SpellFamilyFlags[2] & 0x000008) - incanterAbsorption += currentAbsorb; + if (RemainingDamage >= (*itr)->GetAmount()) + currentAbsorb = (*itr)->GetAmount(); + else + currentAbsorb = RemainingDamage; - (*i)->SetAmount((*i)->GetAmount()-currentAbsorb); - if ((*i)->GetAmount() <= 0) - { - (*i)->GetBase()->Remove(AURA_REMOVE_BY_ENEMY_SPELL); - next = vManaShield.begin(); + currentAbsorb = (100 - auraAbsorbMod) * currentAbsorb / 100; + + if (float manaMultiplier = SpellMgr::CalculateSpellEffectValueMultiplier((*itr)->GetSpellProto(), (*itr)->GetEffIndex(), (*itr)->GetCaster())) + { + int32 maxAbsorb = int32(pVictim->GetPower(POWER_MANA) / manaMultiplier); + if (currentAbsorb > maxAbsorb) + currentAbsorb = maxAbsorb; + + int32 manaReduction = int32(currentAbsorb * manaMultiplier); + pVictim->ApplyPowerMod(POWER_MANA, manaReduction, false); + } + + // Mana Shield (or Fire Ward or Frost Ward or Ice Barrier) + // for Incanter's Absorption converting to spell power + if ((*itr)->GetSpellProto()->SpellFamilyName == SPELLFAMILY_MAGE && (*itr)->GetSpellProto()->SpellFamilyFlags[EFFECT_2] & 0x8) + incanterAbsorption += currentAbsorb; + + (*itr)->SetAmount((*itr)->GetAmount() - currentAbsorb); + if (((*itr)->GetAmount() <= 0) || (pVictim->GetPower(POWER_MANA) <= 1)) + existExpired = true; + + RemainingDamage -= currentAbsorb; } - RemainingDamage -= currentAbsorb; + if (existExpired) + for (AuraEffectList::const_iterator itr = vManaShield.begin(); itr != vManaShield.end();) + { + AuraEffect * auraEff = (*itr); + ++itr; + + if ((auraEff->GetAmount() <= 0) || (pVictim->GetPower(POWER_MANA) <= 1)) + { + uint32 removedAuras = pVictim->m_removedAurasCount; + auraEff->GetBase()->Remove(AURA_REMOVE_BY_ENEMY_SPELL); + if (removedAuras + 1 < pVictim->m_removedAurasCount) + itr = vManaShield.begin(); + } + } } // only split damage if not damaging yourself - if (pVictim != this) - { - AuraEffectList const& vSplitDamageFlat = pVictim->GetAuraEffectsByType(SPELL_AURA_SPLIT_DAMAGE_FLAT); - for (AuraEffectList::const_iterator i = vSplitDamageFlat.begin(), next; i != vSplitDamageFlat.end() && RemainingDamage >= 0; i = next) + if (auraAbsorbMod < 100) // Do nothing if 100% absorb ignore + if (pVictim != this) { - next = i; ++next; + AuraEffectList const & vSplitDamageFlat = pVictim->GetAuraEffectsByType(SPELL_AURA_SPLIT_DAMAGE_FLAT); + for (AuraEffectList::const_iterator itr = vSplitDamageFlat.begin(), next; (itr != vSplitDamageFlat.end()) && (RemainingDamage >= 0); itr = next) + { + next = itr; ++next; - // check damage school mask - if (((*i)->GetMiscValue() & schoolMask) == 0) - continue; + // check damage school mask + if (!((*itr)->GetMiscValue() & schoolMask)) + continue; - // Damage can be splitted only if aura has an alive caster - Unit *caster = (*i)->GetCaster(); - if (!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive()) - continue; + // Damage can be splitted only if aura has an alive caster + Unit * caster = (*itr)->GetCaster(); + if (!caster || (caster == pVictim) || !caster->IsInWorld() || !caster->isAlive()) + continue; - int32 currentAbsorb; - if (RemainingDamage >= (*i)->GetAmount()) - currentAbsorb = (*i)->GetAmount(); - else - currentAbsorb = RemainingDamage; + int32 currentAbsorb; + if (RemainingDamage >= (*itr)->GetAmount()) + currentAbsorb = (*itr)->GetAmount(); + else + currentAbsorb = RemainingDamage; + currentAbsorb = (100 - auraAbsorbMod) * currentAbsorb / 100; - RemainingDamage -= currentAbsorb; + RemainingDamage -= currentAbsorb; - uint32 splitted = currentAbsorb; - uint32 splitted_absorb = 0; - DealDamageMods(caster,splitted,&splitted_absorb); + uint32 splitted = currentAbsorb; + uint32 splitted_absorb = 0; + DealDamageMods(caster, splitted, &splitted_absorb); - SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, splitted_absorb, 0, false, 0, false); + SendSpellNonMeleeDamageLog(caster, (*itr)->GetSpellProto()->Id, splitted, schoolMask, splitted_absorb, 0, false, 0, false); - CleanDamage cleanDamage = CleanDamage(splitted, 0, BASE_ATTACK, MELEE_HIT_NORMAL); - DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false); - } + CleanDamage cleanDamage = CleanDamage(splitted, 0, BASE_ATTACK, MELEE_HIT_NORMAL); + DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*itr)->GetSpellProto(), false); + } - AuraEffectList const& vSplitDamagePct = pVictim->GetAuraEffectsByType(SPELL_AURA_SPLIT_DAMAGE_PCT); - for (AuraEffectList::const_iterator i = vSplitDamagePct.begin(), next; i != vSplitDamagePct.end() && RemainingDamage >= 0; i = next) - { - next = i; - ++next; + AuraEffectList const & vSplitDamagePct = pVictim->GetAuraEffectsByType(SPELL_AURA_SPLIT_DAMAGE_PCT); + for (AuraEffectList::const_iterator itr = vSplitDamagePct.begin(), next; (itr != vSplitDamagePct.end()) && (RemainingDamage >= 0); itr = next) + { + next = itr; ++next; - // check damage school mask - if (((*i)->GetMiscValue() & schoolMask) == 0) - continue; + // check damage school mask + if (!((*itr)->GetMiscValue() & schoolMask)) + continue; - // Damage can be splitted only if aura has an alive caster - Unit *caster = (*i)->GetCaster(); - if (!caster || caster == pVictim || !caster->IsInWorld() || !caster->isAlive()) - continue; + // Damage can be splitted only if aura has an alive caster + Unit * caster = (*itr)->GetCaster(); + if (!caster || (caster == pVictim) || !caster->IsInWorld() || !caster->isAlive()) + continue; - uint32 splitted = uint32(RemainingDamage * (*i)->GetAmount() / 100.0f); + uint32 splitted = CalculatePctN(RemainingDamage, (*itr)->GetAmount()); + AddPctN(splitted, -auraAbsorbMod); - RemainingDamage -= int32(splitted); + RemainingDamage -= int32(splitted); - uint32 split_absorb = 0; - DealDamageMods(caster,splitted,&split_absorb); + uint32 split_absorb = 0; + DealDamageMods(caster, splitted, &split_absorb); - SendSpellNonMeleeDamageLog(caster, (*i)->GetSpellProto()->Id, splitted, schoolMask, split_absorb, 0, false, 0, false); + SendSpellNonMeleeDamageLog(caster, (*itr)->GetSpellProto()->Id, splitted, schoolMask, split_absorb, 0, false, 0, false); - CleanDamage cleanDamage = CleanDamage(splitted, 0, BASE_ATTACK, MELEE_HIT_NORMAL); - DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*i)->GetSpellProto(), false); + CleanDamage cleanDamage = CleanDamage(splitted, 0, BASE_ATTACK, MELEE_HIT_NORMAL); + DealDamage(caster, splitted, &cleanDamage, DIRECT_DAMAGE, schoolMask, (*itr)->GetSpellProto(), false); + } } - } TotalAbsorb = (TotalAbsorb - RemainingDamage > 0) ? TotalAbsorb - RemainingDamage : 0; - // TODO: School should be checked for absorbing auras or for attacks? - int32 auraAbsorbMod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_TARGET_ABSORB_SCHOOL); - AuraEffectList const& AbsIgnoreAurasAb = GetAuraEffectsByType(SPELL_AURA_MOD_TARGET_ABILITY_ABSORB_SCHOOL); - for (AuraEffectList::const_iterator i = AbsIgnoreAurasAb.begin(); i != AbsIgnoreAurasAb.end(); ++i) - { - if ((*i)->GetAmount() > auraAbsorbMod - && (*i)->IsAffectedOnSpell(spellInfo)) - auraAbsorbMod = (*i)->GetAmount(); - } - - // Ignore absorb - add reduced amount again to damage - RemainingDamage += auraAbsorbMod * TotalAbsorb / 100; // Apply death prevention spells effects - if (preventDeathSpell && RemainingDamage >= int32(pVictim->GetHealth())) - { - switch(preventDeathSpell->SpellFamilyName) + if (auraAbsorbMod < 100) // Do nothing if 100% absorb ignore + if (preventDeathSpell && (RemainingDamage >= int32(pVictim->GetHealth()))) { - case SPELLFAMILY_ROGUE: + switch(preventDeathSpell->SpellFamilyName) { - // Cheat Death - if (preventDeathSpell->SpellIconID == 2109) + case SPELLFAMILY_ROGUE: { - pVictim->CastSpell(pVictim, 31231, true); - pVictim->ToPlayer()->AddSpellCooldown(31231, 0, time(NULL) + 60); + // Cheat Death + if (preventDeathSpell->SpellIconID == 2109) + { + pVictim->CastSpell(pVictim, 31231, true); + pVictim->ToPlayer()->AddSpellCooldown(31231, 0, time(NULL) + 60); - // with health > 10% lost health until health == 10%, in other case no losses - uint32 health10 = pVictim->CountPctFromMaxHealth(10); - RemainingDamage = pVictim->GetHealth() > health10 ? pVictim->GetHealth() - health10 : 0; + // with health > 10% lost health until health == 10%, in other case no losses + uint32 health10 = pVictim->CountPctFromMaxHealth(10); + RemainingDamage = pVictim->GetHealth() > health10 ? pVictim->GetHealth() - health10 : 0; + } + break; } - break; - } - case SPELLFAMILY_PRIEST: - { - // Guardian Spirit - if (preventDeathSpell->SpellIconID == 2873) + case SPELLFAMILY_PRIEST: { - int32 healAmount = int32(pVictim->CountPctFromMaxHealth(preventDeathAmount)); - pVictim->RemoveAurasDueToSpell(preventDeathSpell->Id); - pVictim->CastCustomSpell(pVictim, 48153, &healAmount, NULL, NULL, true); - RemainingDamage = 0; + // Guardian Spirit + if (preventDeathSpell->SpellIconID == 2873) + { + int32 healAmount = int32(pVictim->CountPctFromMaxHealth(preventDeathAmount)); + pVictim->RemoveAurasDueToSpell(preventDeathSpell->Id); + pVictim->CastCustomSpell(pVictim, 48153, &healAmount, NULL, NULL, true); + RemainingDamage = 0; + } + break; } - break; } } - } *absorb = RemainingDamage > 0 ? (damage - RemainingDamage - *resist) : (damage - *resist); @@ -2104,7 +2150,7 @@ void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEff { // Incanter's Absorption // TODO: move this code to procflag - if (AuraEffect const * aurEff = pVictim->GetDummyAuraEffect(SPELLFAMILY_GENERIC, 2941, 0)) + if (AuraEffect const * aurEff = pVictim->GetDummyAuraEffect(SPELLFAMILY_GENERIC, 2941, EFFECT_0)) { // Get total damage bonus from auras int32 current_dmg = 0; @@ -2113,13 +2159,19 @@ void Unit::CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEff if (AuraEffect const * bonusEff = iter->second->GetBase()->GetEffect(0)) current_dmg += bonusEff->GetAmount(); - int32 new_dmg = (int32)*absorb * aurEff->GetAmount() / 100; + int32 new_dmg = CalculatePctN(int32(*absorb), aurEff->GetAmount()); if (new_dmg > 0) pVictim->CastCustomSpell(pVictim, 44413, &new_dmg, NULL, NULL, true); } } } +void Unit::FillOrderedAbsorbAuras(AuraEffectList & out) const +{ + out = GetAuraEffectsByType(SPELL_AURA_SCHOOL_ABSORB); + out.sort(Trinity::AbsorbAuraOrderPred()); +} + void Unit::CalcHealAbsorb(Unit *pVictim, const SpellEntry *healSpell, uint32 &healAmount, uint32 &absorb) { if (!healAmount) @@ -2477,7 +2529,7 @@ float Unit::CalculateLevelPenalty(SpellEntry const* spellProto) const if (LvlFactor > 1.0f) LvlFactor = 1.0f; - return (100.0f - LvlPenalty) * LvlFactor / 100.0f; + return AddPctF(LvlFactor, -LvlPenalty); } void Unit::SendMeleeAttackStart(Unit* pVictim) @@ -4571,7 +4623,7 @@ float Unit::GetTotalAuraMultiplier(AuraType auratype) const AuraEffectList const& mTotalAuraList = GetAuraEffectsByType(auratype); for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) - multiplier *= (100.0f + (*i)->GetAmount())/100.0f; + AddPctN(multiplier, (*i)->GetAmount()); return multiplier; } @@ -4623,7 +4675,7 @@ float Unit::GetTotalAuraMultiplierByMiscMask(AuraType auratype, uint32 misc_mask for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) { if ((*i)->GetMiscValue()& misc_mask) - multiplier *= (100.0f + (*i)->GetAmount())/100.0f; + AddPctN(multiplier, (*i)->GetAmount()); } return multiplier; } @@ -4677,7 +4729,7 @@ float Unit::GetTotalAuraMultiplierByMiscValue(AuraType auratype, int32 misc_valu for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) { if ((*i)->GetMiscValue() == misc_value) - multiplier *= (100.0f + (*i)->GetAmount())/100.0f; + AddPctN(multiplier, (*i)->GetAmount()); } return multiplier; } @@ -4731,7 +4783,7 @@ float Unit::GetTotalAuraMultiplierByAffectMask(AuraType auratype, SpellEntry con for (AuraEffectList::const_iterator i = mTotalAuraList.begin(); i != mTotalAuraList.end(); ++i) { if ((*i)->IsAffectedOnSpell(affectedSpell)) - multiplier *= (100.0f + (*i)->GetAmount())/100.0f; + AddPctN(multiplier, (*i)->GetAmount()); } return multiplier; } @@ -5274,11 +5326,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger case 25988: { // return damage % to attacker but < 50% own total health - basepoints0 = int32((triggerAmount * damage) /100); - - int32 halfMaxHealth = int32(CountPctFromMaxHealth(50)); - if (basepoints0 > halfMaxHealth) - basepoints0 = halfMaxHealth; + basepoints0 = int32(std::min(CalculatePctN(damage, triggerAmount), CountPctFromMaxHealth(50))); sLog.outDebug("DEBUG LINE: Data about Eye for an Eye ID %u, damage taken %u, unit max health %u, damage done %u", dummySpell->Id, damage, GetMaxHealth(), basepoints0); @@ -5744,8 +5792,34 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger // Shadow's Fate (Shadowmourne questline) case 71169: { - triggered_spell_id = 71203; target = triggeredByAura->GetCaster(); + Player* player = target->ToPlayer(); + if (!player) + return false; + // not checking Infusion auras because its in targetAuraSpell of credit spell + if (player->GetQuestStatus(24749) == QUEST_STATUS_INCOMPLETE) // Unholy Infusion + { + if (GetEntry() != 36678) // Professor Putricide + return false; + CastSpell(target, 71518, true); // Quest Credit + return true; + } + else if (player->GetQuestStatus(24756) == QUEST_STATUS_INCOMPLETE) // Blood Infusion + { + if (GetEntry() != 37955) // Blood-Queen Lana'thel + return false; + CastSpell(target, 72934, true); // Quest Credit + return true; + } + else if (player->GetQuestStatus(24757) == QUEST_STATUS_INCOMPLETE) // Frost Infusion + { + if (GetEntry() != 36853) // Sindragosa + return false; + CastSpell(target, 72289, true); // Quest Credit + return true; + } + else if (player->GetQuestStatus(24547) == QUEST_STATUS_INCOMPLETE) // A Feast of Souls + triggered_spell_id = 71203; break; } // Gaseous Bloat (Professor Putricide add) @@ -5762,7 +5836,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger { target = this; triggered_spell_id = 70872; - basepoints0 = int32(damage) * triggerAmount / 100; + basepoints0 = CalculatePctN(int32(damage), triggerAmount); break; } } @@ -5777,7 +5851,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger return false; // mana reward - basepoints0 = (triggerAmount * GetMaxPower(POWER_MANA) / 100); + basepoints0 = CalculatePctN(int32(GetMaxPower(POWER_MANA)), triggerAmount); target = this; triggered_spell_id = 29442; break; @@ -5789,8 +5863,8 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger return false; // mana cost save - int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100; - basepoints0 = cost * triggerAmount/100; + int32 cost = int32(procSpell->manaCost + CalculatePctU(GetCreateMana(), procSpell->ManaCostPercentage)); + basepoints0 = CalculatePctN(cost, triggerAmount); if (basepoints0 <= 0) return false; @@ -5844,8 +5918,8 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger if (!procSpell) return false; - int32 cost = procSpell->manaCost + procSpell->ManaCostPercentage * GetCreateMana() / 100; - basepoints0 = cost * triggerAmount/100; + int32 cost = int32(procSpell->manaCost + CalculatePctU(GetCreateMana(), procSpell->ManaCostPercentage)); + basepoints0 = CalculatePctN(cost, triggerAmount); if (basepoints0 <= 0) return false; triggered_spell_id = 44450; @@ -5872,7 +5946,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger // Glyph of Icy Veins case 56374: { - RemoveAurasByType(SPELL_AURA_MOD_HASTE, 0, 0, true, false); + RemoveAurasByType(SPELL_AURA_MOD_MELEE_HASTE, 0, 0, true, false); RemoveAurasByType(SPELL_AURA_MOD_DECREASE_SPEED); return true; } @@ -5982,7 +6056,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger { triggered_spell_id = 59653; // % of amount blocked - basepoints0 = GetShieldBlockValue() * triggerAmount / 100; + basepoints0 = CalculatePctN(int32(GetShieldBlockValue()), triggerAmount); break; } // Glyph of Blocking @@ -6059,7 +6133,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger target = GetGuardianPet(); if (!target) return false; - basepoints0 = damage * triggerAmount / 100; + basepoints0 = CalculatePctN(int32(damage), triggerAmount); triggered_spell_id = 54181; break; } @@ -6073,7 +6147,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger triggerAmount += triggerAmount / 4; triggered_spell_id = 63106; target = this; - basepoints0 = int32(damage*triggerAmount/100); + basepoints0 = CalculatePctN(int32(damage), triggerAmount); break; } // Glyph of Shadowflame @@ -6127,7 +6201,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger } } // health - basepoints0 = int32(damage*triggerAmount/100); + basepoints0 = CalculatePctN(int32(damage), triggerAmount); target = this; triggered_spell_id = 30294; break; @@ -6146,7 +6220,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger return false; // heal amount - basepoints0 = damage * triggerAmount/100; + basepoints0 = CalculatePctN(int32(damage), triggerAmount); triggered_spell_id = 37382; break; } @@ -6186,7 +6260,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger if (AuraEffect *aurEff = target->GetAuraEffect(47753, 0)) bonus = aurEff->GetAmount(); - basepoints0 = damage * triggerAmount/100 + bonus; + basepoints0 = CalculatePctN(int32(damage), triggerAmount) + bonus; if (basepoints0 > target->getLevel() * 125) basepoints0 = target->getLevel() * 125; @@ -6203,7 +6277,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger target = this; break; } - switch(dummySpell->Id) + switch (dummySpell->Id) { // Vampiric Embrace case 15286: @@ -6212,9 +6286,10 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger return false; // heal amount - int32 team = triggerAmount*damage/500; - int32 self = triggerAmount*damage/100 - team; - CastCustomSpell(this,15290,&team,&self,NULL,true,castItem,triggeredByAura); + int32 total = CalculatePctN(int32(damage), triggerAmount); + int32 team = total / 5; + int32 self = total - team; + CastCustomSpell(this, 15290, &team, &self, NULL, true, castItem, triggeredByAura); return true; // no hidden cooldown } // Priest Tier 6 Trinket (Ashtongue Talisman of Acumen) @@ -6254,7 +6329,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger if (!tickcount) return false; - basepoints0 = damage * triggerAmount / tickcount / 100; + basepoints0 = CalculatePctN(int32(damage), triggerAmount) / tickcount; break; } // Improved Shadowform @@ -6284,7 +6359,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger case 26169: { // heal amount - basepoints0 = int32(damage * 10/100); + basepoints0 = int32(CalculatePctN(damage, 10)); target = this; triggered_spell_id = 26170; break; @@ -6296,7 +6371,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger return false; // heal amount - basepoints0 = damage * triggerAmount/100; + basepoints0 = CalculatePctN(int32(damage), triggerAmount); target = this; triggered_spell_id = 39373; break; @@ -6316,7 +6391,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger SpellEntry const* blessHealing = sSpellStore.LookupEntry(triggered_spell_id); if (!blessHealing) return false; - basepoints0 = int32(triggerAmount * damage / 100 / (GetSpellMaxDuration(blessHealing) / blessHealing->EffectAmplitude[0])); + basepoints0 = int32(CalculatePctN(damage, triggerAmount) / (GetSpellMaxDuration(blessHealing) / blessHealing->EffectAmplitude[0])); } break; } @@ -6333,7 +6408,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger return false; int32 mana_perc = SpellMgr::CalculateSpellEffectAmount(triggeredByAura->GetSpellProto(), triggeredByAura->GetEffIndex()); - basepoints0 = uint32((GetCreatePowers(POWER_MANA) * mana_perc / 100) / 10); + basepoints0 = int32(CalculatePctN(GetCreatePowers(POWER_MANA), mana_perc) / 10); triggered_spell_id = 54833; target = this; break; @@ -6407,7 +6482,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger case 28719: { // mana back - basepoints0 = int32(procSpell->manaCost * 30 / 100); + basepoints0 = int32(CalculatePctN(procSpell->manaCost, 30)); target = this; triggered_spell_id = 28742; break; @@ -6417,7 +6492,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger { if (!pVictim || !pVictim->HealthBelowPct(uint32(triggerAmount))) return false; - basepoints0 = int32(triggerAmount * damage / 100); + basepoints0 = CalculatePctN(int32(damage), triggerAmount); triggered_spell_id = 54755; break; } @@ -6485,7 +6560,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger SpellEntry const* triggeredSpell = sSpellStore.LookupEntry(triggered_spell_id); if (!triggeredSpell) return false; - basepoints0 = int32(triggerAmount * damage / 100 / (GetSpellMaxDuration(triggeredSpell) / triggeredSpell->EffectAmplitude[0])); + basepoints0 = CalculatePctN(int32(damage), triggerAmount) / (GetSpellMaxDuration(triggeredSpell) / triggeredSpell->EffectAmplitude[0]); } break; } @@ -6512,7 +6587,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger else if (dummySpell->SpellIconID == 2860) { triggered_spell_id = 48504; - basepoints0 = triggerAmount * damage / 100; + basepoints0 = CalculatePctN(int32(damage), triggerAmount); break; } // King of the Jungle @@ -6567,7 +6642,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger { // "refresh your Slice and Dice duration to its 5 combo point maximum" // lookup Slice and Dice - if (AuraEffect const* aur = GetAuraEffect(SPELL_AURA_MOD_HASTE, SPELLFAMILY_ROGUE,0x40000, 0, 0)) + if (AuraEffect const* aur = GetAuraEffect(SPELL_AURA_MOD_MELEE_HASTE, SPELLFAMILY_ROGUE, 0x40000, 0, 0)) { aur->GetBase()->SetDuration(GetSpellMaxDuration(aur->GetSpellProto()), true); return true; @@ -6587,7 +6662,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger return false; // energy cost save - basepoints0 = procSpell->manaCost * triggerAmount/100; + basepoints0 = CalculatePctN(int32(procSpell->manaCost), triggerAmount); if (basepoints0 <= 0) return false; @@ -6688,7 +6763,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger float ap = GetTotalAttackPowerValue(BASE_ATTACK); int32 holy = SpellBaseDamageBonus(SPELL_SCHOOL_MASK_HOLY) + SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_HOLY, pVictim); - basepoints0 = (int32)GetAttackTime(BASE_ATTACK) * int32(ap*0.022f + 0.044f * holy) / 1000; + basepoints0 = (int32)GetAttackTime(BASE_ATTACK) * int32(ap * 0.022f + 0.044f * holy) / 1000; break; } // Light's Beacon - Beacon of Light @@ -6733,23 +6808,27 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger return true; } // Sacred Shield - if (dummySpell->SpellFamilyFlags[1]&0x00080000) + if (dummySpell->SpellFamilyFlags[1] & 0x80000) { if (procFlag & PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_POS) { - if (procSpell->SpellFamilyName == SPELLFAMILY_PALADIN - && (procSpell->SpellFamilyFlags[0] & 0x40000000)) + if ((procSpell->SpellFamilyName == SPELLFAMILY_PALADIN) && (procSpell->SpellFamilyFlags[0] & 0x40000000)) { - basepoints0 = int32(float(damage)/12.0f); - CastCustomSpell(this,66922,&basepoints0,NULL,NULL,true,0,triggeredByAura, pVictim->GetGUID()); + basepoints0 = damage / 12; + + if (basepoints0) + CastCustomSpell(this, 66922, &basepoints0, NULL, NULL, true, 0, triggeredByAura, pVictim->GetGUID()); + return true; } else return false; } - else + else if (damage > 0) + { triggered_spell_id = 58597; - target = this; + target = this; + } break; } // Righteous Vengeance @@ -6799,7 +6878,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger if (pVictim && pVictim->isAlive() && pVictim->getPowerType() == POWER_MANA) { // 2% of base mana - basepoints0 = int32(pVictim->GetCreateMana() * 2 / 100); + basepoints0 = int32(CalculatePctN(pVictim->GetCreateMana(), 2)); pVictim->CastCustomSpell(pVictim, 20268, &basepoints0, NULL, NULL, true, 0, triggeredByAura); } return true; @@ -6908,7 +6987,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger return false; // heal amount - basepoints0 = triggerAmount*(std::min(damage,GetMaxHealth() - GetHealth()))/100; + basepoints0 = int32(CalculatePctN(std::min(damage, GetMaxHealth() - GetHealth()), triggerAmount)); target = this; if (basepoints0) @@ -6960,14 +7039,14 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger case 54936: { triggered_spell_id = 54957; - basepoints0 = triggerAmount*damage/100; + basepoints0 = CalculatePctN(int32(damage), triggerAmount); break; } // Glyph of Holy Light case 54937: { triggered_spell_id = 54968; - basepoints0 = triggerAmount*damage/100; + basepoints0 = CalculatePctN(int32(damage), triggerAmount); break; } case 71406: // Tiny Abomination in a Jar @@ -7194,7 +7273,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger // Not proc from self heals if (this == pVictim) return false; - basepoints0 = triggerAmount * damage / 100; + basepoints0 = CalculatePctN(int32(damage), triggerAmount); target = this; triggered_spell_id = 55533; break; @@ -7206,14 +7285,14 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger target = GetOwner(); if (!target) return false; - basepoints0 = triggerAmount * damage / 100; + basepoints0 = CalculatePctN(int32(damage), triggerAmount); triggered_spell_id = 58879; break; } // Shaman T8 Elemental 4P Bonus case 64928: { - basepoints0 = int32(triggerAmount * damage / 100); + basepoints0 = CalculatePctN(int32(damage), triggerAmount); triggered_spell_id = 64930; // Electrified break; } @@ -7227,7 +7306,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger SpellEntry const* triggeredSpell = sSpellStore.LookupEntry(triggered_spell_id); if (!triggeredSpell) return false; - basepoints0 = int32(triggerAmount * damage / 100 / (GetSpellMaxDuration(triggeredSpell) / triggeredSpell->EffectAmplitude[0])); + basepoints0 = CalculatePctN(int32(damage), triggerAmount) / (GetSpellMaxDuration(triggeredSpell) / triggeredSpell->EffectAmplitude[0]); } break; } @@ -7241,7 +7320,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger SpellEntry const* triggeredSpell = sSpellStore.LookupEntry(triggered_spell_id); if (!triggeredSpell) return false; - basepoints0 = int32(triggerAmount * damage / 100 / (GetSpellMaxDuration(triggeredSpell) / triggeredSpell->EffectAmplitude[0])); + basepoints0 = CalculatePctN(int32(damage), triggerAmount) / (GetSpellMaxDuration(triggeredSpell) / triggeredSpell->EffectAmplitude[0]); } break; } @@ -7293,9 +7372,9 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger if (aurEffA) { int32 bp0 = 0, bp1 = 0; - bp0 = aurEffA->GetAmount() * triggerAmount / 100; + bp0 = CalculatePctN(triggerAmount, aurEffA->GetAmount()); if (AuraEffect * aurEffB = aurEffA->GetBase()->GetEffect(EFFECT_1)) - bp1 = aurEffB->GetAmount() * triggerAmount / 100; + bp1 = CalculatePctN(triggerAmount, aurEffB->GetAmount()); CastCustomSpell(this, 63283, &bp0, &bp1, NULL, true, NULL, triggeredByAura); return true; } @@ -7333,7 +7412,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger if (dummySpell->SpellIconID == 3065) { triggered_spell_id = 52759; - basepoints0 = triggerAmount * damage / 100; + basepoints0 = CalculatePctN(int32(damage), triggerAmount); target = this; break; } @@ -7347,10 +7426,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger // Glyph of Earth Shield if (AuraEffect* aur = GetAuraEffect(63279,0)) - { - int32 aur_mod = aur->GetAmount(); - basepoints0 = int32(basepoints0 * (aur_mod + 100.0f) / 100.0f); - } + AddPctN(basepoints0, aur->GetAmount()); triggered_spell_id = 379; break; } @@ -7360,13 +7436,13 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger if (GetTypeId() != TYPEID_PLAYER || !pVictim || !pVictim->isAlive() || !castItem || !castItem->IsEquipped()) return false; - float fire_onhit = (float)(SpellMgr::CalculateSpellEffectAmount(dummySpell, 0) / 100.0); + float fire_onhit = float(CalculatePctF(SpellMgr::CalculateSpellEffectAmount(dummySpell, 0), 1.0f)); float add_spellpower = (float)(SpellBaseDamageBonus(SPELL_SCHOOL_MASK_FIRE) + SpellBaseDamageBonusForVictim(SPELL_SCHOOL_MASK_FIRE, pVictim)); // 1.3speed = 5%, 2.6speed = 10%, 4.0 speed = 15%, so, 1.0speed = 3.84% - add_spellpower= add_spellpower / 100.0f * 3.84f; + ApplyPctF(add_spellpower, 3.84f); // Enchant on Off-Hand and ready? if (castItem->GetSlot() == EQUIPMENT_SLOT_OFFHAND && isAttackReady(OFF_ATTACK)) @@ -7520,7 +7596,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger { if (GetTypeId() != TYPEID_PLAYER) return false; - basepoints0 = triggerAmount * damage / 100; + basepoints0 = CalculatePctN(int32(damage), triggerAmount); break; } // Butchery @@ -7566,10 +7642,10 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger // Unholy Blight if (dummySpell->Id == 49194) { - basepoints0 = triggerAmount * damage / 100; + basepoints0 = CalculatePctN(int32(damage), triggerAmount); // Glyph of Unholy Blight if (AuraEffect *glyph=GetAuraEffect(63332,0)) - basepoints0 += basepoints0 * glyph->GetAmount() / 100; + AddPctN(basepoints0, glyph->GetAmount()); // Find replaced aura to use it's remaining amount AuraEffectList const& DoTAuras = target->GetAuraEffectsByType(SPELL_AURA_PERIODIC_DAMAGE); for (Unit::AuraEffectList::const_iterator i = DoTAuras.begin(); i != DoTAuras.end(); ++i) @@ -7594,7 +7670,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger // Necrosis if (dummySpell->SpellIconID == 2709) { - basepoints0 = triggerAmount * damage / 100; + basepoints0 = CalculatePctN(int32(damage), triggerAmount); triggered_spell_id = 51460; break; } @@ -7672,7 +7748,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger { if (!roll_chance_f(GetUnitCriticalChance(BASE_ATTACK, pVictim))) return false; - basepoints0 = triggerAmount * damage / 100; + basepoints0 = CalculatePctN(int32(damage), triggerAmount); triggered_spell_id = 50526; break; } @@ -7761,7 +7837,7 @@ bool Unit::HandleDummyAuraProc(Unit *pVictim, uint32 damage, AuraEffect* trigger { triggered_spell_id = 54445; target = this; - float addThreat = SpellMgr::CalculateSpellEffectAmount(procSpell, 0, this) * triggerAmount / 100.0f; + float addThreat = float(CalculatePctN(SpellMgr::CalculateSpellEffectAmount(procSpell, 0, this), triggerAmount)); pVictim->AddThreat(this, addThreat); break; } @@ -7833,7 +7909,7 @@ bool Unit::HandleObsModEnergyAuraProc(Unit *pVictim, uint32 /*damage*/, AuraEffe if (dummySpell->SpellFamilyFlags[1] & 0x40000) { uint32 maxmana = GetMaxPower(POWER_MANA); - basepoints0 = uint32(maxmana* GetAttackTime(RANGED_ATTACK)/1000.0f/100.0f); + basepoints0 = CalculatePctF(maxmana, GetAttackTime(RANGED_ATTACK) / 1000.0f); target = this; triggered_spell_id = 34075; break; @@ -7965,7 +8041,7 @@ bool Unit::HandleAuraProc(Unit * pVictim, uint32 damage, Aura * triggeredByAura, *handled = true; if (pVictim->HasAura(53601)) { - int32 bp0 = (damage/12) * SpellMgr::CalculateSpellEffectAmount(dummySpell, 2)/100; + int32 bp0 = CalculatePctN(int32(damage / 12), SpellMgr::CalculateSpellEffectAmount(dummySpell, 2)); CastCustomSpell(pVictim, 66922, &bp0, NULL, NULL, true); return true; } @@ -8014,7 +8090,7 @@ bool Unit::HandleAuraProc(Unit * pVictim, uint32 damage, Aura * triggeredByAura, if (!spInfo) return false; - int32 bp0 = this->GetCreateMana() * SpellMgr::CalculateSpellEffectAmount(spInfo, 0) / 100; + int32 bp0 = int32(CalculatePctN(GetCreateMana(), SpellMgr::CalculateSpellEffectAmount(spInfo, 0))); this->CastCustomSpell(this, 67545, &bp0, NULL, NULL, true, NULL, triggeredByAura->GetEffect(0), this->GetGUID()); return true; } @@ -8206,7 +8282,7 @@ bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, AuraEffect* trig if ((*i)->GetMiscValue() == SPELLMOD_CHANCE_OF_SUCCESS && (*i)->GetSpellProto()->SpellIconID == 113) { int32 value2 = CalculateSpellDamage(this, (*i)->GetSpellProto(),2); - basepoints0 = value2 * GetMaxPower(POWER_MANA) / 100; + basepoints0 = int32(CalculatePctN(GetMaxPower(POWER_MANA), value2)); // Drain Soul CastCustomSpell(this, 18371, &basepoints0, NULL, NULL, true, castItem, triggeredByAura); break; @@ -8254,7 +8330,7 @@ bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, AuraEffect* trig sLog.outError("Unit::HandleProcTriggerSpell: Spell %u not handled in BR", auraSpellInfo->Id); return false; } - basepoints0 = damage * triggerAmount / 100 / 3; + basepoints0 = CalculatePctN(int32(damage), triggerAmount) / 3; target = this; } break; @@ -8264,7 +8340,7 @@ bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, AuraEffect* trig // Druid Forms Trinket if (auraSpellInfo->Id == 37336) { - switch(m_form) + switch (GetShapeshiftForm()) { case FORM_NONE: trigger_spell_id = 37344;break; case FORM_CAT: trigger_spell_id = 37341;break; @@ -8279,7 +8355,7 @@ bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, AuraEffect* trig // Druid T9 Feral Relic (Lacerate, Swipe, Mangle, and Shred) else if (auraSpellInfo->Id == 67353) { - switch(m_form) + switch (GetShapeshiftForm()) { case FORM_CAT: trigger_spell_id = 67355; break; case FORM_BEAR: @@ -8309,7 +8385,7 @@ bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, AuraEffect* trig if (!TriggerPS) return false; - basepoints0 = int32(damage * triggerAmount / 100 / (GetSpellMaxDuration(TriggerPS) / TriggerPS->EffectAmplitude[0])); + basepoints0 = CalculatePctN(int32(damage), triggerAmount) / (GetSpellMaxDuration(TriggerPS) / TriggerPS->EffectAmplitude[0]); basepoints0 += pVictim->GetRemainingDotDamage(GetGUID(), trigger_spell_id); break; } @@ -8438,8 +8514,8 @@ bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, AuraEffect* trig return false; } // percent stored in effect 1 (class scripts) base points - int32 cost = originalSpell->manaCost + originalSpell->ManaCostPercentage * GetCreateMana() / 100; - basepoints0 = cost*SpellMgr::CalculateSpellEffectAmount(auraSpellInfo, 1)/100; + int32 cost = int32(originalSpell->manaCost + CalculatePctU(GetCreateMana(), originalSpell->ManaCostPercentage)); + basepoints0 = CalculatePctN(cost, SpellMgr::CalculateSpellEffectAmount(auraSpellInfo, 1)); trigger_spell_id = 20272; target = this; } @@ -8469,7 +8545,7 @@ bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, AuraEffect* trig { if (!procSpell) return false; - basepoints0 = procSpell->manaCost * 35 / 100; + basepoints0 = int32(CalculatePctN(procSpell->manaCost, 35)); trigger_spell_id = 23571; target = this; break; @@ -8527,7 +8603,7 @@ bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, AuraEffect* trig return false; trigger_spell_id = 50475; - basepoints0 = damage * triggerAmount / 100; + basepoints0 = CalculatePctN(int32(damage), triggerAmount); } break; } @@ -8557,7 +8633,7 @@ bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, AuraEffect* trig // This spell originally trigger 13567 - Dummy Trigger (vs dummy efect) case 26467: { - basepoints0 = damage * 15 / 100; + basepoints0 = int32(CalculatePctN(damage, 15)); target = pVictim; trigger_spell_id = 26470; break; @@ -8621,7 +8697,7 @@ bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, AuraEffect* trig case 45057: { // reduce you below $s1% health - if (GetHealth() - damage > GetMaxHealth() * triggerAmount / 100) + if ((GetHealth() - damage) > CalculatePctN(GetMaxHealth(), triggerAmount)) return false; break; } @@ -8637,7 +8713,7 @@ bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, AuraEffect* trig // Blessing of Ancient Kings (Val'anyr, Hammer of Ancient Kings) case 64411: { - basepoints0 = damage * 15 / 100; + basepoints0 = int32(CalculatePctN(damage, 15)); target = pVictim; trigger_spell_id = 64413; break; @@ -8741,7 +8817,7 @@ bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, AuraEffect* trig // Shamanistic Rage triggered spell case 30824: { - basepoints0 = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100); + basepoints0 = int32(CalculatePctN(GetTotalAttackPowerValue(BASE_ATTACK), triggerAmount)); break; } // Enlightenment (trigger only from mana cost spells) @@ -8760,8 +8836,8 @@ bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, AuraEffect* trig { if (AuraEffect * aurEff = owner->GetDummyAuraEffect(SPELLFAMILY_WARLOCK, 3220, 0)) { - basepoints0 = int32((aurEff->GetAmount() * owner->SpellBaseDamageBonus(SpellSchoolMask(SPELL_SCHOOL_MASK_MAGIC)) + 100.0f) / 100.0f); - CastCustomSpell(this,trigger_spell_id,&basepoints0,&basepoints0,NULL,true,castItem,triggeredByAura); + basepoints0 = int32((aurEff->GetAmount() * owner->SpellBaseDamageBonus(SpellSchoolMask(SPELL_SCHOOL_MASK_MAGIC)) + 100.0f) / 100.0f); // TODO: Is it right? + CastCustomSpell(this, trigger_spell_id, &basepoints0, &basepoints0, NULL, true, castItem, triggeredByAura); return true; } } @@ -8834,7 +8910,7 @@ bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, AuraEffect* trig // Savage Defense case 62606: { - basepoints0 = int32(GetTotalAttackPowerValue(BASE_ATTACK) * triggerAmount / 100.0f); + basepoints0 = CalculatePctF(triggerAmount, GetTotalAttackPowerValue(BASE_ATTACK)); break; } // Body and Soul @@ -8863,16 +8939,36 @@ bool Unit::HandleProcTriggerSpell(Unit *pVictim, uint32 damage, AuraEffect* trig break; // Shadow's Fate (Shadowmourne questline) case 71169: + { if (GetTypeId() != TYPEID_PLAYER) return false; - if (ToPlayer()->GetQuestStatus(24547) != QUEST_STATUS_INCOMPLETE) // A Feast of Souls + + Player* player = this->ToPlayer(); + if (player->GetQuestStatus(24749) == QUEST_STATUS_INCOMPLETE) // Unholy Infusion + { + if (!player->HasAura(71516) || pVictim->GetEntry() != 36678) // Shadow Infusion && Professor Putricide + return false; + } + else if (player->GetQuestStatus(24756) == QUEST_STATUS_INCOMPLETE) // Blood Infusion + { + if (!player->HasAura(72154) || pVictim->GetEntry() != 37955) // Thirst Quenched && Blood-Queen Lana'thel + return false; + } + else if (player->GetQuestStatus(24757) == QUEST_STATUS_INCOMPLETE) // Frost Infusion + { + if (!player->HasAura(72290) || pVictim->GetEntry() != 36853) // Frost-Imbued Blade && Sindragosa + return false; + } + else if (player->GetQuestStatus(24547) != QUEST_STATUS_INCOMPLETE) // A Feast of Souls return false; + if (pVictim->GetTypeId() != TYPEID_UNIT) return false; // critters are not allowed if (pVictim->GetCreatureType() == CREATURE_TYPE_CRITTER) return false; break; + } } if (cooldown && GetTypeId() == TYPEID_PLAYER && ToPlayer()->HasSpellCooldown(trigger_spell_id)) @@ -10196,7 +10292,7 @@ uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint3 if (((*i)->GetMiscValue() & GetSpellSchoolMask(spellProto)) && (*i)->GetSpellProto()->EquippedItemClass == -1 && // -1 == any item class (not wand) (*i)->GetSpellProto()->EquippedItemInventoryTypeMask == 0) // 0 == any inventory type (not wand) - DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); uint32 creatureTypeMask = pVictim->GetCreatureTypeMask(); // Add flat bonus from spell damage versus @@ -10204,13 +10300,13 @@ uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint3 AuraEffectList const &mDamageDoneVersus = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS); for (AuraEffectList::const_iterator i = mDamageDoneVersus.begin(); i != mDamageDoneVersus.end(); ++i) if (creatureTypeMask & uint32((*i)->GetMiscValue())) - DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); // bonus against aurastate AuraEffectList const &mDamageDoneVersusAurastate = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS_AURASTATE); for (AuraEffectList::const_iterator i = mDamageDoneVersusAurastate.begin(); i != mDamageDoneVersusAurastate.end(); ++i) if (pVictim->HasAuraState(AuraState((*i)->GetMiscValue()))) - DoneTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); // done scripted mod (take it from owner) Unit * owner = GetOwner() ? GetOwner() : this; @@ -10229,7 +10325,7 @@ uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint3 case 6928: { if (pVictim->HasAuraState(AURA_STATE_HEALTHLESS_35_PERCENT, spellProto, this)) - DoneTotalMod *= (100.0f+(*i)->GetAmount())/100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); break; } // Soul Siphon @@ -10256,19 +10352,19 @@ uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint3 break; } } - DoneTotalMod *= (modPercent+100.0f)/100.0f; + AddPctN(DoneTotalMod, modPercent); break; } case 6916: // Death's Embrace case 6925: case 6927: if (HasAuraState(AURA_STATE_HEALTHLESS_20_PERCENT, spellProto, this)) - DoneTotalMod *= (100.0f+(*i)->GetAmount())/100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); break; case 5481: // Starfire Bonus { if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x200002, 0, 0)) - DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); break; } case 4418: // Increased Shock Damage @@ -10291,14 +10387,14 @@ uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint3 if ((*i)->GetSpellProto()->SpellIconID == 2656) { if (!pVictim->HealthAbovePct(35)) - DoneTotalMod *= (100.0f+(*i)->GetAmount())/100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); } // Tundra Stalker else { // Frost Fever (target debuff) if (pVictim->HasAura(55095)) - DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); break; } break; @@ -10309,7 +10405,7 @@ uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint3 if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0,0x02000000,0)) { if (SpellChainNode const *chain = sSpellMgr.GetSpellChainNode((*i)->GetId())) - DoneTotalMod *= (chain->rank * 2.0f + 100.0f)/100.0f; + AddPctF(DoneTotalMod, chain->rank * 2.0f); } break; } @@ -10317,7 +10413,7 @@ uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint3 case 7377: { if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x8000, 0,0, GetGUID())) - DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); break; } // Marked for Death @@ -10328,7 +10424,7 @@ uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint3 case 7602: { if (pVictim->GetAuraEffect(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, 0x400, 0, 0)) - DoneTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); break; } } @@ -10359,7 +10455,7 @@ uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint3 for (AuraEffectList::const_iterator i = mDumyAuras.begin(); i != mDumyAuras.end(); ++i) if ((*i)->GetSpellProto()->SpellIconID == 3263) { - DoneTotalMod *= float((*i)->GetAmount() + 100.f) / 100.f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); break; } } @@ -10371,13 +10467,13 @@ uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint3 if (AuraEffect * aurEff = GetAuraEffect(55687, 0)) // Increase Mind Flay damage if Shadow Word: Pain present on target if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x8000, 0,0, GetGUID())) - DoneTotalMod *= (aurEff->GetAmount() + 100.0f) / 100.f; + AddPctN(DoneTotalMod, aurEff->GetAmount()); // Twisted Faith - Mind Flay part if (AuraEffect * aurEff = GetAuraEffect(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS, SPELLFAMILY_PRIEST, 2848, 1)) // Increase Mind Flay damage if Shadow Word: Pain present on target if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x8000, 0,0, GetGUID())) - DoneTotalMod *= (aurEff->GetAmount() + 100.0f) / 100.f; + AddPctN(DoneTotalMod, aurEff->GetAmount()); } break; case SPELLFAMILY_PALADIN: @@ -10395,7 +10491,7 @@ uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint3 } // + 10% for each application of Holy Vengeance/Blood Corruption on the target if (stacks) - DoneTotalMod *= (10.0f + float(stacks)) / 10.0f; + AddPctU(DoneTotalMod, 10 * stacks); } break; case SPELLFAMILY_WARLOCK: @@ -10407,7 +10503,7 @@ uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint3 for (AuraEffectList::const_iterator i = mDumyAuras.begin(); i != mDumyAuras.end(); ++i) if ((*i)->GetSpellProto()->SpellIconID == 3173) { - DoneTotalMod *= float((*i)->GetAmount() + 100.f) / 100.f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); break; } } @@ -10420,13 +10516,13 @@ uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint3 // Improved Icy Touch if (spellProto->SpellFamilyFlags[0] & 0x2) if (AuraEffect * aurEff = GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 2721, 0)) - DoneTotalMod *= (100.0f + aurEff->GetAmount()) / 100.0f; + AddPctN(DoneTotalMod, aurEff->GetAmount()); // Glacier Rot if (spellProto->SpellFamilyFlags[0] & 0x2 || spellProto->SpellFamilyFlags[1] & 0x6) if (AuraEffect * aurEff = GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 196, 0)) if (pVictim->GetDiseasesByCaster(owner->GetGUID()) > 0) - DoneTotalMod *= (100.0f + aurEff->GetAmount()) / 100.0f; + AddPctN(DoneTotalMod, aurEff->GetAmount()); // Impurity (dummy effect) if (GetTypeId() == TYPEID_PLAYER) @@ -10445,7 +10541,7 @@ uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint3 case 49638: { if (const SpellEntry *proto=sSpellStore.LookupEntry(itr->first)) - ApCoeffMod *= (100.0f + SpellMgr::CalculateSpellEffectAmount(proto, 0)) / 100.0f; + AddPctN(ApCoeffMod, SpellMgr::CalculateSpellEffectAmount(proto, 0)); } break; } @@ -10514,7 +10610,7 @@ uint32 Unit::SpellDamageBonus(Unit *pVictim, SpellEntry const *spellProto, uint3 sumNegativeMod += (*i)->GetAmount(); } - float TakenTotalMod = (sumNegativeMod+maxPositiveMod+100.0f)/100.0f; + float TakenTotalMod = (sumNegativeMod + maxPositiveMod + 100.0f) / 100.0f; // Taken/Done fixed damage bonus auras int32 DoneAdvertisedBenefit = SpellBaseDamageBonus(GetSpellSchoolMask(spellProto)); @@ -10667,14 +10763,14 @@ int32 Unit::SpellBaseDamageBonus(SpellSchoolMask schoolMask) { // stat used stored in miscValueB for this aura Stats usedStat = Stats((*i)->GetMiscValueB()); - DoneAdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetAmount() / 100.0f); + DoneAdvertisedBenefit += int32(CalculatePctN(GetStat(usedStat), (*i)->GetAmount())); } } // ... and attack power AuraEffectList const& mDamageDonebyAP = GetAuraEffectsByType(SPELL_AURA_MOD_SPELL_DAMAGE_OF_ATTACK_POWER); for (AuraEffectList::const_iterator i =mDamageDonebyAP.begin(); i != mDamageDonebyAP.end(); ++i) if ((*i)->GetMiscValue() & schoolMask) - DoneAdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetAmount() / 100.0f); + DoneAdvertisedBenefit += int32(CalculatePctN(GetTotalAttackPowerValue(BASE_ATTACK), (*i)->GetAmount())); } return DoneAdvertisedBenefit > 0 ? DoneAdvertisedBenefit : 0; @@ -10956,7 +11052,7 @@ uint32 Unit::SpellHealingBonus(Unit *pVictim, SpellEntry const *spellProto, uint // Healing done percent AuraEffectList const& mHealingDonePct = GetAuraEffectsByType(SPELL_AURA_MOD_HEALING_DONE_PERCENT); for (AuraEffectList::const_iterator i = mHealingDonePct.begin(); i != mHealingDonePct.end(); ++i) - DoneTotalMod *= (100.0f + (*i)->GetAmount()) / 100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); // done scripted mod (take it from owner) Unit *owner = GetOwner() ? GetOwner() : this; @@ -10970,23 +11066,23 @@ uint32 Unit::SpellHealingBonus(Unit *pVictim, SpellEntry const *spellProto, uint case 4415: // Increased Rejuvenation Healing case 4953: case 3736: // Hateful Totem of the Third Wind / Increased Lesser Healing Wave / LK Arena (4/5/6) Totem of the Third Wind / Savage Totem of the Third Wind - DoneTotal+=(*i)->GetAmount(); + DoneTotal += (*i)->GetAmount(); break; case 7997: // Renewed Hope case 7998: if (pVictim->HasAura(6788)) - DoneTotalMod *=((*i)->GetAmount() + 100.0f)/100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); break; case 21: // Test of Faith case 6935: case 6918: if (pVictim->HealthBelowPct(50)) - DoneTotalMod *=((*i)->GetAmount() + 100.0f)/100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); break; case 7798: // Glyph of Regrowth { if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_HEAL, SPELLFAMILY_DRUID, 0x40, 0, 0)) - DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); break; } case 8477: // Nourish Heal Boost @@ -11005,13 +11101,13 @@ uint32 Unit::SpellHealingBonus(Unit *pVictim, SpellEntry const *spellProto, uint continue; modPercent += stepPercent * aura->GetStackAmount(); } - DoneTotalMod *= (modPercent+100.0f)/100.0f; + AddPctN(DoneTotalMod, modPercent); break; } case 7871: // Glyph of Lesser Healing Wave { if (pVictim->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, 0 , 0x00000400, 0, GetGUID())) - DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); break; } default: @@ -11169,39 +11265,39 @@ uint32 Unit::SpellHealingBonus(Unit *pVictim, SpellEntry const *spellProto, uint { // Search for Healing Way on Victim if (AuraEffect const* HealingWay = pVictim->GetAuraEffect(29203, 0)) - TakenTotalMod *= (HealingWay->GetAmount() + 100.0f) / 100.0f; + AddPctN(TakenTotalMod, HealingWay->GetAmount()); } // Tenacity increase healing % taken if (AuraEffect const* Tenacity = pVictim->GetAuraEffect(58549, 0)) - TakenTotalMod *= (Tenacity->GetAmount() + 100.0f) / 100.0f; + AddPctN(TakenTotalMod, Tenacity->GetAmount()); // Healing taken percent float minval = (float)pVictim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT); if (minval) - TakenTotalMod *= (100.0f + minval) / 100.0f; + AddPctF(TakenTotalMod, minval); float maxval = (float)pVictim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT); if (maxval) - TakenTotalMod *= (100.0f + maxval) / 100.0f; + AddPctF(TakenTotalMod, maxval); if (damagetype == DOT) { // Healing over time taken percent float minval_hot = (float)pVictim->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HOT_PCT); if (minval_hot) - TakenTotalMod *= (100.0f + minval_hot) / 100.0f; + AddPctF(TakenTotalMod, minval_hot); float maxval_hot = (float)pVictim->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HOT_PCT); if (maxval_hot) - TakenTotalMod *= (100.0f + maxval_hot) / 100.0f; + AddPctF(TakenTotalMod, maxval_hot); } AuraEffectList const& mHealingGet= pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_HEALING_RECEIVED); for (AuraEffectList::const_iterator i = mHealingGet.begin(); i != mHealingGet.end(); ++i) if (GetGUID() == (*i)->GetCasterGUID() && (*i)->IsAffectedOnSpell(spellProto)) - TakenTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; + AddPctN(TakenTotalMod, (*i)->GetAmount()); heal = (int32(heal) + TakenTotal) * TakenTotalMod; @@ -11229,14 +11325,14 @@ int32 Unit::SpellBaseHealingBonus(SpellSchoolMask schoolMask) { // stat used dependent from misc value (stat index) Stats usedStat = Stats((*i)->GetSpellProto()->EffectMiscValue[(*i)->GetEffIndex()]); - AdvertisedBenefit += int32(GetStat(usedStat) * (*i)->GetAmount() / 100.0f); + AdvertisedBenefit += int32(CalculatePctN(GetStat(usedStat), (*i)->GetAmount())); } // ... and attack power AuraEffectList const& mHealingDonebyAP = GetAuraEffectsByType(SPELL_AURA_MOD_SPELL_HEALING_OF_ATTACK_POWER); for (AuraEffectList::const_iterator i = mHealingDonebyAP.begin(); i != mHealingDonebyAP.end(); ++i) if ((*i)->GetMiscValue() & schoolMask) - AdvertisedBenefit += int32(GetTotalAttackPowerValue(BASE_ATTACK) * (*i)->GetAmount() / 100.0f); + AdvertisedBenefit += int32(CalculatePctN(GetTotalAttackPowerValue(BASE_ATTACK), (*i)->GetAmount())); } return AdvertisedBenefit; } @@ -11491,19 +11587,19 @@ void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage, WeaponAttackType att AuraEffectList const &mModDamagePercentDone = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE); for (AuraEffectList::const_iterator i = mModDamagePercentDone.begin(); i != mModDamagePercentDone.end(); ++i) if (((*i)->GetMiscValue() & GetSpellSchoolMask(spellProto)) && !((*i)->GetMiscValue() & SPELL_SCHOOL_MASK_NORMAL)) - DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); } AuraEffectList const &mDamageDoneVersus = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS); for (AuraEffectList::const_iterator i = mDamageDoneVersus.begin(); i != mDamageDoneVersus.end(); ++i) if (creatureTypeMask & uint32((*i)->GetMiscValue())) - DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); // bonus against aurastate AuraEffectList const &mDamageDoneVersusAurastate = GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_DONE_VERSUS_AURASTATE); for (AuraEffectList::const_iterator i = mDamageDoneVersusAurastate.begin(); i != mDamageDoneVersusAurastate.end(); ++i) if (pVictim->HasAuraState(AuraState((*i)->GetMiscValue()))) - DoneTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); // done scripted mod (take it from owner) Unit * owner = GetOwner() ? GetOwner() : this; @@ -11523,14 +11619,14 @@ void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage, WeaponAttackType att if ((*i)->GetSpellProto()->SpellIconID == 2656) { if (!pVictim->HealthAbovePct(35)) - DoneTotalMod *= (100.0f+(*i)->GetAmount())/100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); } // Tundra Stalker else { // Frost Fever (target debuff) if (pVictim->HasAura(55095)) - DoneTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); } break; } @@ -11539,7 +11635,7 @@ void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage, WeaponAttackType att { if (pVictim->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0,0x02000000,0)) if (SpellChainNode const *chain = sSpellMgr.GetSpellChainNode((*i)->GetId())) - DoneTotalMod *= (chain->rank * 2.0f + 100.0f)/100.0f; + AddPctF(DoneTotalMod, chain->rank * 2.0f); break; } // Marked for Death @@ -11550,7 +11646,7 @@ void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage, WeaponAttackType att case 7602: { if (pVictim->GetAuraEffect(SPELL_AURA_MOD_STALKED, SPELLFAMILY_HUNTER, 0x400, 0, 0)) - DoneTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; + AddPctN(DoneTotalMod, (*i)->GetAmount()); break; } } @@ -11565,7 +11661,7 @@ void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage, WeaponAttackType att if (spellProto->SpellFamilyFlags[0] & 0x2 || spellProto->SpellFamilyFlags[1] & 0x6) if (AuraEffect * aurEff = GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 196, 0)) if (pVictim->GetDiseasesByCaster(owner->GetGUID()) > 0) - DoneTotalMod *= (100.0f + aurEff->GetAmount()) / 100.0f; + AddPctN(DoneTotalMod, aurEff->GetAmount()); break; } @@ -11573,13 +11669,13 @@ void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage, WeaponAttackType att AuraEffectList const& mModDamagePercentTaken = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN); for (AuraEffectList::const_iterator i = mModDamagePercentTaken.begin(); i != mModDamagePercentTaken.end(); ++i) if ((*i)->GetMiscValue() & GetMeleeDamageSchoolMask()) - TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f; + AddPctN(TakenTotalMod, (*i)->GetAmount()); // From caster spells AuraEffectList const& mOwnerTaken = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_DAMAGE_FROM_CASTER); for (AuraEffectList::const_iterator i = mOwnerTaken.begin(); i != mOwnerTaken.end(); ++i) if ((*i)->GetCasterGUID() == GetGUID() && (*i)->IsAffectedOnSpell(spellProto)) - TakenTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; + AddPctN(TakenTotalMod, (*i)->GetAmount()); // .. taken pct (special attacks) if (spellProto) @@ -11596,7 +11692,7 @@ void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage, WeaponAttackType att AuraEffectList const& mDamageDoneMechanic = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_MECHANIC_DAMAGE_TAKEN_PERCENT); for (AuraEffectList::const_iterator i = mDamageDoneMechanic.begin(); i != mDamageDoneMechanic.end(); ++i) if (mechanicMask & uint32(1<<((*i)->GetMiscValue()))) - TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f; + AddPctN(TakenTotalMod, (*i)->GetAmount()); } } @@ -11613,9 +11709,7 @@ void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage, WeaponAttackType att if (pVictim->GetTypeId() != TYPEID_PLAYER) continue; float mod = pVictim->ToPlayer()->GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*(-8.0f); - if (mod < (*i)->GetAmount()) - mod = (float)(*i)->GetAmount(); - TakenTotalMod *= (mod+100.0f)/100.0f; + AddPctF(TakenTotalMod, std::max(mod, float((*i)->GetAmount()))); } break; // Blessing of Sanctuary @@ -11627,13 +11721,13 @@ void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage, WeaponAttackType att continue; if ((*i)->GetMiscValue() & (spellProto ? GetSpellSchoolMask(spellProto) : 0)) - TakenTotalMod *= ((*i)->GetAmount() + 100.0f) / 100.0f; + AddPctN(TakenTotalMod, (*i)->GetAmount()); break; } // Ebon Plague case 1933: if ((*i)->GetMiscValue() & (spellProto ? GetSpellSchoolMask(spellProto) : 0)) - TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f; + AddPctN(TakenTotalMod, (*i)->GetAmount()); break; } } @@ -11655,7 +11749,7 @@ void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage, WeaponAttackType att } // effect 0 have expected value but in negative state - TakenTotalMod *= (-eff0->GetAmount()+100.0f)/100.0f; + AddPctN(TakenTotalMod, -eff0->GetAmount()); } break; } @@ -11665,13 +11759,13 @@ void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage, WeaponAttackType att { AuraEffectList const& mModMeleeDamageTakenPercent = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_MELEE_DAMAGE_TAKEN_PCT); for (AuraEffectList::const_iterator i = mModMeleeDamageTakenPercent.begin(); i != mModMeleeDamageTakenPercent.end(); ++i) - TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f; + AddPctN(TakenTotalMod, (*i)->GetAmount()); } else { AuraEffectList const& mModRangedDamageTakenPercent = pVictim->GetAuraEffectsByType(SPELL_AURA_MOD_RANGED_DAMAGE_TAKEN_PCT); for (AuraEffectList::const_iterator i = mModRangedDamageTakenPercent.begin(); i != mModRangedDamageTakenPercent.end(); ++i) - TakenTotalMod *= ((*i)->GetAmount()+100.0f)/100.0f; + AddPctN(TakenTotalMod, (*i)->GetAmount()); } float tmpDamage = float(int32(*pdamage) + DoneFlatBenefit) * DoneTotalMod; @@ -11681,7 +11775,7 @@ void Unit::MeleeDamageBonus(Unit *pVictim, uint32 *pdamage, WeaponAttackType att if (Player* modOwner = GetSpellModOwner()) modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_DAMAGE, tmpDamage); - tmpDamage = (tmpDamage + TakenFlatBenefit)*TakenTotalMod; + tmpDamage = (tmpDamage + TakenFlatBenefit) * TakenTotalMod; // bonus result can be negative *pdamage = uint32(std::max(tmpDamage, 0.0f)); @@ -12163,7 +12257,7 @@ void Unit::UpdateSpeed(UnitMoveType mtype, bool forced) float stack_bonus = 1.0f; float non_stack_bonus = 1.0f; - switch(mtype) + switch (mtype) { // Only apply debuffs case MOVE_FLIGHT_BACK: @@ -12178,13 +12272,13 @@ void Unit::UpdateSpeed(UnitMoveType mtype, bool forced) { main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_MOUNTED_SPEED); stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_MOUNTED_SPEED_ALWAYS); - non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK))/100.0f; + non_stack_bonus += GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MOUNTED_SPEED_NOT_STACK) / 100.0f; } else { main_speed_mod = GetMaxPositiveAuraModifier(SPELL_AURA_MOD_INCREASE_SPEED); stack_bonus = GetTotalAuraMultiplier(SPELL_AURA_MOD_SPEED_ALWAYS); - non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK))/100.0f; + non_stack_bonus += GetMaxPositiveAuraModifier(SPELL_AURA_MOD_SPEED_NOT_STACK) / 100.0f; } break; } @@ -12216,7 +12310,7 @@ void Unit::UpdateSpeed(UnitMoveType mtype, bool forced) else // Use not mount (shapeshift for example) auras (should stack) main_speed_mod = GetTotalAuraModifier(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) + GetTotalAuraModifier(SPELL_AURA_MOD_INCREASE_VEHICLE_FLIGHT_SPEED); - non_stack_bonus = (100.0f + GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK))/100.0f; + non_stack_bonus += GetMaxPositiveAuraModifier(SPELL_AURA_MOD_FLIGHT_SPEED_NOT_STACK) / 100.0f; // Update speed for vehicle if available if (GetTypeId() == TYPEID_PLAYER && GetVehicle()) @@ -12228,12 +12322,12 @@ void Unit::UpdateSpeed(UnitMoveType mtype, bool forced) return; } - float bonus = non_stack_bonus > stack_bonus ? non_stack_bonus : stack_bonus; - // now we ready for speed calculation - float speed = main_speed_mod ? bonus*(100.0f + main_speed_mod)/100.0f : bonus; + float speed = std::max(non_stack_bonus, stack_bonus); + if (main_speed_mod) + AddPctN(speed, main_speed_mod); - switch(mtype) + switch (mtype) { case MOVE_RUN: case MOVE_SWIM: @@ -12269,7 +12363,7 @@ void Unit::UpdateSpeed(UnitMoveType mtype, bool forced) int32 slow = GetMaxNegativeAuraModifier(SPELL_AURA_MOD_DECREASE_SPEED); if (slow) { - speed *=(100.0f + slow)/100.0f; + AddPctN(speed, slow); if (float minSpeedMod = (float)GetMaxPositiveAuraModifier(SPELL_AURA_MOD_MINIMUM_SPEED)) { float min_speed = minSpeedMod / 100.0f; @@ -12712,21 +12806,21 @@ Unit* Creature::SelectVictim() //====================================================================== //====================================================================== -int32 Unit::ApplyEffectModifiers(SpellEntry const* spellProto, uint8 effect_index, int32 value) const +float Unit::ApplyEffectModifiers(SpellEntry const* spellProto, uint8 effect_index, float value) const { if (Player* modOwner = GetSpellModOwner()) { - modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_ALL_EFFECTS, value); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_ALL_EFFECTS, value); switch (effect_index) { case 0: - modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT1, value); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT1, value); break; case 1: - modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT2, value); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT2, value); break; case 2: - modOwner->ApplySpellMod(spellProto->Id,SPELLMOD_EFFECT3, value); + modOwner->ApplySpellMod(spellProto->Id, SPELLMOD_EFFECT3, value); break; } } @@ -12793,7 +12887,7 @@ int32 Unit::ModSpellDuration(SpellEntry const* spellProto, Unit const* target, i durationMod = durationMod_always; if (durationMod != 0) - duration = int32(float(duration) * float(100.0f+durationMod) / 100.0f); + AddPctN(duration, durationMod); // there are only negative mods currently durationMod_always = target->GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_AURA_DURATION_BY_DISPEL, spellProto->Dispel); @@ -12806,7 +12900,7 @@ int32 Unit::ModSpellDuration(SpellEntry const* spellProto, Unit const* target, i durationMod += durationMod_always; if (durationMod != 0) - duration = int32(float(duration) * float(100.0f+durationMod) / 100.0f); + AddPctN(duration, durationMod); } else { @@ -12855,7 +12949,7 @@ int32 Unit::ModSpellDuration(SpellEntry const* spellProto, Unit const* target, i break; } } - return duration > 0 ? duration : 0; + return std::max(duration, 0); } void Unit::ModSpellCastTime(SpellEntry const* spellProto, int32 & castTime, Spell * spell) @@ -13045,7 +13139,8 @@ uint32 Unit::GetCreatureType() const { if (GetTypeId() == TYPEID_PLAYER) { - SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form); + ShapeshiftForm form = GetShapeshiftForm(); + SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(form); if (ssEntry && ssEntry->creatureType > 0) return ssEntry->creatureType; else @@ -13879,7 +13974,7 @@ bool InitTriggerAuraData() isTriggerAura[SPELL_AURA_OVERRIDE_CLASS_SCRIPTS] = true; isTriggerAura[SPELL_AURA_MOD_MECHANIC_RESISTANCE] = true; isTriggerAura[SPELL_AURA_RANGED_ATTACK_POWER_ATTACKER_BONUS] = true; - isTriggerAura[SPELL_AURA_MOD_HASTE] = true; + isTriggerAura[SPELL_AURA_MOD_MELEE_HASTE] = true; isTriggerAura[SPELL_AURA_MOD_ATTACKER_MELEE_HIT_CHANCE]=true; isTriggerAura[SPELL_AURA_RAID_PROC_FROM_CHARGE] = true; isTriggerAura[SPELL_AURA_RAID_PROC_FROM_CHARGE_WITH_VALUE] = true; @@ -14136,7 +14231,7 @@ void Unit::ProcDamageAndSpellFor(bool isVictim, Unit * pTarget, uint32 procFlag, if (HandleModDamagePctTakenAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown)) takeCharges = true; break; - case SPELL_AURA_MOD_HASTE: + case SPELL_AURA_MOD_MELEE_HASTE: { sLog.outDebug("ProcDamageAndSpell: casting spell id %u (triggered by %s haste aura of spell %u)", spellInfo->Id,(isVictim?"a victim's":"an attacker's"), triggeredByAura->GetId()); if (HandleHasteAuraProc(pTarget, damage, triggeredByAura, procSpell, procFlag, procExtra, cooldown)) @@ -16188,10 +16283,8 @@ float Unit::GetCombatRatingReduction(CombatRating cr) const uint32 Unit::GetCombatRatingDamageReduction(CombatRating cr, float rate, float cap, uint32 damage) const { - float percent = GetCombatRatingReduction(cr) * rate; - if (percent > cap) - percent = cap; - return uint32 (percent * damage / 100.0f); + float percent = std::min(GetCombatRatingReduction(cr) * rate, cap); + return CalculatePctF(damage, percent); } uint32 Unit::GetModelForForm(ShapeshiftForm form) @@ -16835,22 +16928,22 @@ void Unit::RewardRage(uint32 damage, uint32 weaponSpeedHitFactor, bool attacker) { float addRage; - float rageconversion = ((0.0091107836f * getLevel()*getLevel())+3.225598133f*getLevel())+4.2652911f; + float rageconversion = ((0.0091107836f * getLevel() * getLevel()) + 3.225598133f * getLevel()) + 4.2652911f; // Unknown if correct, but lineary adjust rage conversion above level 70 if (getLevel() > 70) - rageconversion += 13.27f*(getLevel()-70); + rageconversion += 13.27f * (getLevel() - 70); if (attacker) { - addRage = ((damage/rageconversion*7.5f + weaponSpeedHitFactor)/2); + addRage = (damage / rageconversion * 7.5f + weaponSpeedHitFactor) / 2; // talent who gave more rage on attack - addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f; + AddPctN(addRage, GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT)); } else { - addRage = damage/rageconversion*2.5f; + addRage = damage / rageconversion * 2.5f; // Berserker Rage effect if (HasAura(18499)) @@ -16859,7 +16952,7 @@ void Unit::RewardRage(uint32 damage, uint32 weaponSpeedHitFactor, bool attacker) addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME); - ModifyPower(POWER_RAGE, uint32(addRage*10)); + ModifyPower(POWER_RAGE, uint32(addRage * 10)); } void Unit::StopAttackFaction(uint32 faction_id) diff --git a/src/server/game/Entities/Unit/Unit.h b/src/server/game/Entities/Unit/Unit.h index a0014d06bf1..2a5cdb36139 100755 --- a/src/server/game/Entities/Unit/Unit.h +++ b/src/server/game/Entities/Unit/Unit.h @@ -989,8 +989,8 @@ struct CharmInfo void SetPetNumber(uint32 petnumber, bool statwindow); void SetCommandState(CommandStates st) { m_CommandState = st; } - CommandStates GetCommandState() { return m_CommandState; } - bool HasCommandState(CommandStates state) { return (m_CommandState == state); } + CommandStates GetCommandState() const { return m_CommandState; } + bool HasCommandState(CommandStates state) const { return (m_CommandState == state); } //void SetReactState(ReactStates st) { m_reactState = st; } //ReactStates GetReactState() { return m_reactState; } //bool HasReactState(ReactStates state) { return (m_reactState == state); } @@ -1211,8 +1211,8 @@ class Unit : public WorldObject inline bool HealthBelowPct(int32 pct) const { return GetHealth() * (uint64)100 < GetMaxHealth() * (uint64)pct; } inline bool HealthBelowPctDamaged(int32 pct, uint32 damage) const { return (int32(GetHealth()) - damage) * (int64)100 < GetMaxHealth() * (int64)pct; } inline bool HealthAbovePct(int32 pct) const { return GetHealth() * (uint64)100 > GetMaxHealth() * (uint64)pct; } - inline float GetHealthPct() const { return GetMaxHealth() ? 100.f * GetHealth() / GetMaxHealth() : 0.0f; } - inline uint32 CountPctFromMaxHealth(int32 pct) const { return uint32(float(pct) * GetMaxHealth() / 100.0f); } + inline float GetHealthPct() const { return GetMaxHealth() ? 100.f * GetHealth() / GetMaxHealth() : 0.0f; } + inline uint32 CountPctFromMaxHealth(int32 pct) const { return CalculatePctN(GetMaxHealth(), pct); } void SetHealth(uint32 val); void SetMaxHealth(uint32 val); @@ -1713,9 +1713,21 @@ class Unit : public WorldObject uint64 m_SummonSlot[MAX_SUMMON_SLOT]; uint64 m_ObjectSlot[4]; - uint32 m_ShapeShiftFormSpellId; - ShapeshiftForm m_form; - bool IsInFeralForm() const { return m_form == FORM_CAT || m_form == FORM_BEAR || m_form == FORM_DIREBEAR; } + ShapeshiftForm GetShapeshiftForm() const { return ShapeshiftForm(GetByteValue(UNIT_FIELD_BYTES_2, 3)); } + void SetShapeshiftForm(ShapeshiftForm form) { SetByteValue(UNIT_FIELD_BYTES_2, 3, form); } + + inline bool IsInFeralForm() const + { + ShapeshiftForm form = GetShapeshiftForm(); + return form == FORM_CAT || form == FORM_BEAR || form == FORM_DIREBEAR; + } + + inline bool IsInDisallowedMountForm() const + { + ShapeshiftForm form = GetShapeshiftForm(); + return form != FORM_NONE && form != FORM_BATTLESTANCE && form != FORM_BERSERKERSTANCE && form != FORM_DEFENSIVESTANCE && + form != FORM_SHADOW; + } float m_modMeleeHitChance; float m_modRangedHitChance; @@ -1861,6 +1873,7 @@ class Unit : public WorldObject static bool IsDamageReducedByArmor(SpellSchoolMask damageSchoolMask, SpellEntry const *spellInfo = NULL, uint8 effIndex = MAX_SPELL_EFFECTS); uint32 CalcArmorReducedDamage(Unit* pVictim, const uint32 damage, SpellEntry const *spellInfo, WeaponAttackType attackType=MAX_ATTACK); void CalcAbsorbResist(Unit *pVictim, SpellSchoolMask schoolMask, DamageEffectType damagetype, const uint32 damage, uint32 *absorb, uint32 *resist, SpellEntry const *spellInfo = NULL); + void FillOrderedAbsorbAuras(AuraEffectList & out) const; void CalcHealAbsorb(Unit *pVictim, const SpellEntry *spellProto, uint32 &healAmount, uint32 &absorb); void UpdateSpeed(UnitMoveType mtype, bool forced); @@ -1872,7 +1885,7 @@ class Unit : public WorldObject void SetHover(bool on); bool isHover() const { return HasAuraType(SPELL_AURA_HOVER); } - int32 ApplyEffectModifiers(SpellEntry const* spellProto, uint8 effect_index, int32 value) const; + float ApplyEffectModifiers(SpellEntry const* spellProto, uint8 effect_index, float value) const; int32 CalculateSpellDamage(Unit const* target, SpellEntry const* spellProto, uint8 effect_index, int32 const* basePoints = NULL) const; int32 CalcSpellDuration(SpellEntry const* spellProto); int32 ModSpellDuration(SpellEntry const* spellProto, Unit const* target, int32 duration, bool positive); diff --git a/src/server/game/Entities/Vehicle/Vehicle.h b/src/server/game/Entities/Vehicle/Vehicle.h index 4c1f383bc74..f24d24dc697 100755 --- a/src/server/game/Entities/Vehicle/Vehicle.h +++ b/src/server/game/Entities/Vehicle/Vehicle.h @@ -99,7 +99,7 @@ class Vehicle void InstallAllAccessories(uint32 entry); Unit *GetBase() const { return me; } - VehicleEntry const *GetVehicleInfo() { return m_vehicleInfo; } + VehicleEntry const *GetVehicleInfo() const { return m_vehicleInfo; } bool HasEmptySeat(int8 seatId) const; Unit *GetPassenger(int8 seatId) const; diff --git a/src/server/game/Globals/ObjectMgr.cpp b/src/server/game/Globals/ObjectMgr.cpp index af0515e7d78..11739172214 100755 --- a/src/server/game/Globals/ObjectMgr.cpp +++ b/src/server/game/Globals/ObjectMgr.cpp @@ -5858,13 +5858,13 @@ void ObjectMgr::GetTaxiPath(uint32 source, uint32 destination, uint32 &path, uin uint32 ObjectMgr::GetTaxiMountDisplayId(uint32 id, uint32 team, bool allowed_alt_team /* = false */) { - uint32 mount_entry = 0; uint32 mount_id = 0; // select mount creature id TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(id); if (node) { + uint32 mount_entry = 0; if (team == ALLIANCE) mount_entry = node->MountCreatureID[1]; else @@ -9011,7 +9011,7 @@ uint32 ObjectMgr::GetScriptId(const char *name) ScriptNameMap::const_iterator itr = std::lower_bound(m_scriptNames.begin(), m_scriptNames.end(), name); if (itr == m_scriptNames.end() || *itr != name) return 0; - return itr - m_scriptNames.begin(); + return uint32(itr - m_scriptNames.begin()); } void ObjectMgr::CheckScripts(ScriptsType type, std::set<int32>& ids) diff --git a/src/server/game/Grids/ObjectGridLoader.h b/src/server/game/Grids/ObjectGridLoader.h index c9503c8fd5d..e224855827a 100755 --- a/src/server/game/Grids/ObjectGridLoader.h +++ b/src/server/game/Grids/ObjectGridLoader.h @@ -39,9 +39,9 @@ class ObjectGridLoader void Load(GridType &grid); void Visit(GameObjectMapType &m); void Visit(CreatureMapType &m); - void Visit(CorpseMapType &) {} + void Visit(CorpseMapType &) const {} - void Visit(DynamicObjectMapType&) { } + void Visit(DynamicObjectMapType&) const {} void LoadN(void); diff --git a/src/server/game/Groups/Group.cpp b/src/server/game/Groups/Group.cpp index 9244544e91a..bb5b44c9550 100755 --- a/src/server/game/Groups/Group.cpp +++ b/src/server/game/Groups/Group.cpp @@ -53,24 +53,11 @@ Loot* Roll::getLoot() return getTarget(); } -Group::Group() -{ - m_leaderGuid = 0; - m_groupType = GroupType(0); - m_bgGroup = NULL; - m_lootMethod = LootMethod(0); - m_looterGuid = 0; - m_lootThreshold = ITEM_QUALITY_UNCOMMON; - m_subGroupsCounts = NULL; - m_guid = 0; - m_counter = 0; - m_maxEnchantingLevel= 0; - m_LfgQueued = false; - m_LfgStatus = LFG_STATUS_NOT_SAVED; - m_LfgDungeonEntry = 0; - m_Lfgkicks = 0; - m_LfgkicksActive = false; - +Group::Group() : m_leaderGuid(0), m_groupType(GROUPTYPE_NORMAL), m_bgGroup(NULL), +m_lootMethod(FREE_FOR_ALL), m_looterGuid(0), m_lootThreshold(ITEM_QUALITY_UNCOMMON), +m_subGroupsCounts(NULL), m_guid(0), m_counter(0), m_maxEnchantingLevel(0), +m_LfgState(LFG_STATE_NONE), m_LfgOldState(LFG_STATE_NONE), m_LfgDungeonEntry(0), m_Lfgkicks(0) +{ for (uint8 i = 0; i < TARGETICONCOUNT; ++i) m_targetIcons[i] = 0; } @@ -289,14 +276,13 @@ bool Group::AddLeaderInvite(Player *player) return true; } -uint32 Group::RemoveInvite(Player *player) +void Group::RemoveInvite(Player *player) { if (player) { m_invitees.erase(player); player->SetGroupInvite(NULL); } - return GetMembersCount(); } void Group::RemoveAllInvites() @@ -1119,7 +1105,7 @@ void Group::SendUpdate() data << uint8(citr->roles); if (isLFGGroup()) { - data << uint8(m_LfgStatus); + data << uint8(m_LfgState == LFG_STATE_FINISHED_DUNGEON ? 2 : 0); // FIXME - Dungeon save status? 2 = done data << uint32(m_LfgDungeonEntry); } @@ -1936,37 +1922,28 @@ void Group::SetLootThreshold(ItemQualities threshold) m_lootThreshold = threshold; } -void Group::SetLfgQueued(bool queued) +void Group::SetLfgState(LfgState state) { - m_LfgQueued = queued; + m_LfgState = state; } -bool Group::isLfgQueued() +LfgState Group::GetLfgState() const { - return m_LfgQueued; + return m_LfgState; } -void Group::SetLfgStatus(uint8 status) +void Group::RestoreLfgState() { - m_LfgStatus = status; + m_LfgState = m_LfgOldState; } -uint8 Group::GetLfgStatus() -{ - return m_LfgStatus; -} - -bool Group::isLfgDungeonComplete() const -{ - return m_LfgStatus == LFG_STATUS_COMPLETE; -} void Group::SetLfgDungeonEntry(uint32 dungeonEntry) { m_LfgDungeonEntry = dungeonEntry; } -uint32 Group::GetLfgDungeonEntry(bool id /* = true*/) +uint32 Group::GetLfgDungeonEntry(bool id /* = true*/) const { if (id) return (m_LfgDungeonEntry & 0x00FFFFFF); @@ -1974,16 +1951,6 @@ uint32 Group::GetLfgDungeonEntry(bool id /* = true*/) return m_LfgDungeonEntry; } -bool Group::isLfgKickActive() const -{ - return m_LfgkicksActive; -} - -void Group::SetLfgKickActive(bool active) -{ - m_LfgkicksActive = active; -} - uint8 Group::GetLfgKicks() const { return m_Lfgkicks; @@ -2200,7 +2167,7 @@ void Group::LinkMember(GroupReference *pRef) m_memberMgr.insertFirst(pRef); } -void Group::DelinkMember(GroupReference* /*pRef*/) +void Group::DelinkMember(GroupReference* /*pRef*/) const { } diff --git a/src/server/game/Groups/Group.h b/src/server/game/Groups/Group.h index 7d6eea412b6..584c2f3489d 100755 --- a/src/server/game/Groups/Group.h +++ b/src/server/game/Groups/Group.h @@ -55,13 +55,6 @@ enum RollVote NOT_VALID = 5 }; -enum LfgDungeonStatus -{ - LFG_STATUS_SAVED = 0, - LFG_STATUS_NOT_SAVED = 1, - LFG_STATUS_COMPLETE = 2, -}; - enum GroupMemberOnlineStatus { MEMBER_STATUS_OFFLINE = 0x0000, @@ -189,7 +182,7 @@ class Group bool LoadGroupFromDB(const uint32 &guid, QueryResult result, bool loadMembers = true); bool LoadMemberFromDB(uint32 guidLow, uint8 memberFlags, uint8 subgroup, uint8 roles); bool AddInvite(Player *player); - uint32 RemoveInvite(Player *player); + void RemoveInvite(Player *player); void RemoveAllInvites(); bool AddLeaderInvite(Player *player); bool AddMember(const uint64 &guid, const char* name); @@ -202,15 +195,11 @@ class Group void Disband(bool hideDestroy=false); // Dungeon Finder - void SetLfgQueued(bool queued); - bool isLfgQueued(); - void SetLfgStatus(uint8 status); - uint8 GetLfgStatus(); - bool isLfgDungeonComplete() const; + void SetLfgState(LfgState state); + LfgState GetLfgState() const; + void RestoreLfgState(); void SetLfgDungeonEntry(uint32 dungeonEntry); - uint32 GetLfgDungeonEntry(bool id = true); - bool isLfgKickActive() const; - void SetLfgKickActive(bool active); + uint32 GetLfgDungeonEntry(bool id = true) const; uint8 GetLfgKicks() const; void SetLfgKicks(uint8 kicks); void SetLfgRoles(uint64 guid, const uint8 roles); @@ -303,7 +292,7 @@ class Group void ResetMaxEnchantingLevel(); void LinkMember(GroupReference *pRef); - void DelinkMember(GroupReference* /*pRef*/); + void DelinkMember(GroupReference* /*pRef*/) const; InstanceGroupBind* BindToInstance(InstanceSave *save, bool permanent, bool load = false); void UnbindInstance(uint32 mapid, uint8 difficulty, bool unload = false); @@ -357,10 +346,9 @@ class Group uint64 m_guid; uint32 m_counter; // used only in SMSG_GROUP_LIST uint32 m_maxEnchantingLevel; - bool m_LfgQueued; - uint8 m_LfgStatus; + LfgState m_LfgState; + LfgState m_LfgOldState; uint32 m_LfgDungeonEntry; uint8 m_Lfgkicks; - bool m_LfgkicksActive; }; #endif diff --git a/src/server/game/Instances/InstanceSaveMgr.h b/src/server/game/Instances/InstanceSaveMgr.h index 029b46be9f6..aaeefe65c9d 100755 --- a/src/server/game/Instances/InstanceSaveMgr.h +++ b/src/server/game/Instances/InstanceSaveMgr.h @@ -61,8 +61,8 @@ class InstanceSave /* A map corresponding to the InstanceId/MapId does not always exist. InstanceSave objects may be created on player logon but the maps are created and loaded only when a player actually enters the instance. */ - uint32 GetInstanceId() { return m_instanceid; } - uint32 GetMapId() { return m_mapid; } + uint32 GetInstanceId() const { return m_instanceid; } + uint32 GetMapId() const { return m_mapid; } /* Saved when the instance is generated for the first time */ void SaveToDB(); @@ -71,7 +71,7 @@ class InstanceSave /* for normal instances this corresponds to max(creature respawn time) + X hours for raid/heroic instances this caches the global respawn time for the map */ - time_t GetResetTime() { return m_resetTime; } + time_t GetResetTime() const { return m_resetTime; } void SetResetTime(time_t resetTime) { m_resetTime = resetTime; } time_t GetResetTimeForDB(); @@ -89,12 +89,12 @@ class InstanceSave /* instances cannot be reset (except at the global reset time) if there are players permanently bound to it this is cached for the case when those players are offline */ - bool CanReset() { return m_canReset; } + bool CanReset() const { return m_canReset; } void SetCanReset(bool canReset) { m_canReset = canReset; } /* currently it is possible to omit this information from this structure but that would depend on a lot of things that can easily change in future */ - Difficulty GetDifficulty() { return m_difficulty; } + Difficulty GetDifficulty() const { return m_difficulty; } typedef std::list<Player*> PlayerListType; typedef std::list<Group*> GroupListType; diff --git a/src/server/game/Loot/LootMgr.cpp b/src/server/game/Loot/LootMgr.cpp index f25029765c1..904d27d2dd9 100755 --- a/src/server/game/Loot/LootMgr.cpp +++ b/src/server/game/Loot/LootMgr.cpp @@ -94,7 +94,6 @@ void LootStore::Verify() const void LootStore::LoadLootTable() { LootTemplateMap::const_iterator tab; - uint32 count = 0; // Clearing store (for reloading case) Clear(); @@ -106,6 +105,8 @@ void LootStore::LoadLootTable() if (result) { + uint32 count = 0; + barGoLink bar(result->GetRowCount()); do diff --git a/src/server/game/Maps/ZoneScript.h b/src/server/game/Maps/ZoneScript.h index ae38ea4dd24..b7bec3b353f 100755 --- a/src/server/game/Maps/ZoneScript.h +++ b/src/server/game/Maps/ZoneScript.h @@ -33,8 +33,10 @@ class ZoneScript virtual uint32 GetCreatureEntry(uint32 /*guidlow*/, const CreatureData *data) { return data->id; } virtual uint32 GetGameObjectEntry(uint32 /*guidlow*/, uint32 entry) { return entry; } - virtual void OnCreatureCreate(Creature *, bool /*add*/) {} - virtual void OnGameObjectCreate(GameObject * /*go*/, bool /*add*/) {} + virtual void OnCreatureCreate(Creature *) {} + virtual void OnCreatureRemove(Creature *) {} + virtual void OnGameObjectCreate(GameObject *) {} + virtual void OnGameObjectRemove(GameObject *) {} //All-purpose data storage 64 bit virtual uint64 GetData64(uint32 /*DataId*/) { return 0; } diff --git a/src/server/game/Miscellaneous/SharedDefines.h b/src/server/game/Miscellaneous/SharedDefines.h index a08e5a74cfd..c7e82516bdf 100755 --- a/src/server/game/Miscellaneous/SharedDefines.h +++ b/src/server/game/Miscellaneous/SharedDefines.h @@ -2874,4 +2874,16 @@ enum RemoveMethod GROUP_REMOVEMETHOD_LEAVE = 2, }; +enum LfgState +{ + LFG_STATE_NONE, // Not using LFG / LFR + LFG_STATE_ROLECHECK, // Rolecheck active + LFG_STATE_QUEUED, // Queued + LFG_STATE_PROPOSAL, // Proposal active + LFG_STATE_BOOT, // Vote kick active + LFG_STATE_DUNGEON, // In LFG Group, in a Dungeon + LFG_STATE_FINISHED_DUNGEON, // In LFG Group, in a finished Dungeon + LFG_STATE_RAIDBROWSER, // Using Raid finder +}; + #endif diff --git a/src/server/game/Movement/Waypoints/WaypointManager.h b/src/server/game/Movement/Waypoints/WaypointManager.h index 4b57c6ae815..0c7f608d893 100755 --- a/src/server/game/Movement/Waypoints/WaypointManager.h +++ b/src/server/game/Movement/Waypoints/WaypointManager.h @@ -57,7 +57,7 @@ class WaypointStore else return 0; } - inline uint32 GetRecordsCount() { return records; } + inline uint32 GetRecordsCount() const { return records; } }; #define sWaypointMgr WaypointStore::instance() diff --git a/src/server/game/OutdoorPvP/OutdoorPvP.cpp b/src/server/game/OutdoorPvP/OutdoorPvP.cpp index 88b02cb9661..06d3e37f7c2 100755 --- a/src/server/game/OutdoorPvP/OutdoorPvP.cpp +++ b/src/server/game/OutdoorPvP/OutdoorPvP.cpp @@ -135,7 +135,7 @@ bool OPvPCapturePoint::SetCapturePointData(uint32 entry, uint32 map, float x, fl m_maxValue = (float)goinfo->capturePoint.maxTime; m_maxSpeed = m_maxValue / (goinfo->capturePoint.minTime ? goinfo->capturePoint.minTime : 60); m_neutralValuePct = goinfo->capturePoint.neutralPercent; - m_minValue = m_maxValue * goinfo->capturePoint.neutralPercent / 100; + m_minValue = CalculatePctU(m_maxValue, m_neutralValuePct); return true; } @@ -590,11 +590,20 @@ void OutdoorPvP::TeamApplyBuff(TeamId team, uint32 spellId, uint32 spellId2) TeamCastSpell(OTHER_TEAM(team), spellId2 ? -(int32)spellId2 : -(int32)spellId); } -void OutdoorPvP::OnGameObjectCreate(GameObject *go, bool add) +void OutdoorPvP::OnGameObjectCreate(GameObject *go) { if (go->GetGoType() != GAMEOBJECT_TYPE_CAPTURE_POINT) return; if (OPvPCapturePoint *cp = GetCapturePoint(go->GetDBTableGUIDLow())) - cp->m_capturePoint = add ? go : NULL; + cp->m_capturePoint = go; +} + +void OutdoorPvP::OnGameObjectRemove(GameObject *go) +{ + if (go->GetGoType() != GAMEOBJECT_TYPE_CAPTURE_POINT) + return; + + if (OPvPCapturePoint *cp = GetCapturePoint(go->GetDBTableGUIDLow())) + cp->m_capturePoint = NULL; } diff --git a/src/server/game/OutdoorPvP/OutdoorPvP.h b/src/server/game/OutdoorPvP/OutdoorPvP.h index d3ec99034e9..406f5ec9c51 100755 --- a/src/server/game/OutdoorPvP/OutdoorPvP.h +++ b/src/server/game/OutdoorPvP/OutdoorPvP.h @@ -219,8 +219,9 @@ class OutdoorPvP : public ZoneScript // setup stuff virtual bool SetupOutdoorPvP() {return true;} - void OnGameObjectCreate(GameObject *go, bool add); - void OnCreatureCreate(Creature *, bool /*add*/) {} + void OnGameObjectCreate(GameObject *go); + void OnGameObjectRemove(GameObject *go); + void OnCreatureCreate(Creature *) {} // send world state update to all players present void SendUpdateWorldState(uint32 field, uint32 value); diff --git a/src/server/game/Pools/PoolMgr.h b/src/server/game/Pools/PoolMgr.h index 29371f68fe9..369de80e90f 100755 --- a/src/server/game/Pools/PoolMgr.h +++ b/src/server/game/Pools/PoolMgr.h @@ -58,7 +58,7 @@ class ActivePoolData template<typename T> void RemoveObject(uint32 db_guid_or_pool_id, uint32 pool_id); - ActivePoolObjects GetActiveQuests() { return mActiveQuests; } // a copy of the set + ActivePoolObjects GetActiveQuests() const { return mActiveQuests; } // a copy of the set private: ActivePoolObjects mSpawnedCreatures; ActivePoolObjects mSpawnedGameobjects; diff --git a/src/server/game/Reputation/ReputationMgr.cpp b/src/server/game/Reputation/ReputationMgr.cpp index 934c8579edd..cbd469edb69 100755 --- a/src/server/game/Reputation/ReputationMgr.cpp +++ b/src/server/game/Reputation/ReputationMgr.cpp @@ -424,7 +424,7 @@ void ReputationMgr::SetAtWar(RepListID repListID, bool on) SetAtWar(&itr->second,on); } -void ReputationMgr::SetAtWar(FactionState* faction, bool atWar) +void ReputationMgr::SetAtWar(FactionState* faction, bool atWar) const { // not allow declare war to own faction if (atWar && (faction->Flags & FACTION_FLAG_PEACE_FORCED)) @@ -452,7 +452,7 @@ void ReputationMgr::SetInactive(RepListID repListID, bool on) SetInactive(&itr->second,on); } -void ReputationMgr::SetInactive(FactionState* faction, bool inactive) +void ReputationMgr::SetInactive(FactionState* faction, bool inactive) const { // always invisible or hidden faction can't be inactive if (inactive && ((faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN)) || !(faction->Flags & FACTION_FLAG_VISIBLE))) diff --git a/src/server/game/Reputation/ReputationMgr.h b/src/server/game/Reputation/ReputationMgr.h index 2fe3054971e..2d167c9c1dc 100755 --- a/src/server/game/Reputation/ReputationMgr.h +++ b/src/server/game/Reputation/ReputationMgr.h @@ -141,8 +141,8 @@ class ReputationMgr bool SetReputation(FactionEntry const* factionEntry, int32 standing, bool incremental); bool SetOneFactionReputation(FactionEntry const* factionEntry, int32 standing, bool incremental); void SetVisible(FactionState* faction); - void SetAtWar(FactionState* faction, bool atWar); - void SetInactive(FactionState* faction, bool inactive); + void SetAtWar(FactionState* faction, bool atWar) const; + void SetInactive(FactionState* faction, bool inactive) const; void SendVisible(FactionState const* faction) const; void UpdateRankCounters(ReputationRank old_rank, ReputationRank new_rank); private: diff --git a/src/server/game/Scripting/ScriptLoader.cpp b/src/server/game/Scripting/ScriptLoader.cpp index d2b1cfc6bdb..78da1ad549d 100755 --- a/src/server/game/Scripting/ScriptLoader.cpp +++ b/src/server/game/Scripting/ScriptLoader.cpp @@ -76,7 +76,6 @@ void AddSC_npc_innkeeper(); void AddSC_npcs_special(); void AddSC_npc_taxi(); void AddSC_achievement_scripts(); -void AddSC_dungeon_finder(); //eastern kingdoms void AddSC_alterac_valley(); //Alterac Valley @@ -664,7 +663,6 @@ void AddWorldScripts() AddSC_npc_taxi(); AddSC_achievement_scripts(); AddSC_chat_log(); - AddSC_dungeon_finder(); #endif } diff --git a/src/server/game/Server/Protocol/Handlers/CharacterHandler.cpp b/src/server/game/Server/Protocol/Handlers/CharacterHandler.cpp index 3a3a23cc4ec..7be5f7fafbf 100755 --- a/src/server/game/Server/Protocol/Handlers/CharacterHandler.cpp +++ b/src/server/game/Server/Protocol/Handlers/CharacterHandler.cpp @@ -23,7 +23,6 @@ #include "World.h" #include "WorldPacket.h" #include "WorldSession.h" -#include "MD5.h" #include "DatabaseEnv.h" #include "ArenaTeam.h" diff --git a/src/server/game/Server/Protocol/Handlers/ChatHandler.cpp b/src/server/game/Server/Protocol/Handlers/ChatHandler.cpp index 958f26598e4..523809ae4c3 100755 --- a/src/server/game/Server/Protocol/Handlers/ChatHandler.cpp +++ b/src/server/game/Server/Protocol/Handlers/ChatHandler.cpp @@ -183,33 +183,66 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recv_data) return; } - switch(type) + std::string to, channel, msg; + bool ignoreChecks = false; + switch (type) { case CHAT_MSG_SAY: case CHAT_MSG_EMOTE: case CHAT_MSG_YELL: - { - std::string msg; + case CHAT_MSG_PARTY: + case CHAT_MSG_PARTY_LEADER: + case CHAT_MSG_GUILD: + case CHAT_MSG_OFFICER: + case CHAT_MSG_RAID: + case CHAT_MSG_RAID_LEADER: + case CHAT_MSG_RAID_WARNING: + case CHAT_MSG_BATTLEGROUND: + case CHAT_MSG_BATTLEGROUND_LEADER: recv_data >> msg; + break; + case CHAT_MSG_WHISPER: + recv_data >> to; + recv_data >> msg; + break; + case CHAT_MSG_CHANNEL: + recv_data >> channel; + recv_data >> msg; + break; + case CHAT_MSG_AFK: + case CHAT_MSG_DND: + recv_data >> msg; + ignoreChecks = true; + break; + } - if (msg.empty()) - break; + if (!ignoreChecks) + { + if (msg.empty()) + return; - if (ChatHandler(this).ParseCommands(msg.c_str()) > 0) - break; + if (ChatHandler(this).ParseCommands(msg.c_str()) > 0) + return; + + if (!processChatmessageFurtherAfterSecurityChecks(msg, lang)) + return; + if (msg.empty()) + return; + } + + switch (type) + { + case CHAT_MSG_SAY: + case CHAT_MSG_EMOTE: + case CHAT_MSG_YELL: + { if (_player->getLevel() < sWorld.getIntConfig(CONFIG_CHAT_SAY_LEVEL_REQ)) { SendNotification(GetTrinityString(LANG_SAY_REQ), sWorld.getIntConfig(CONFIG_CHAT_SAY_LEVEL_REQ)); return; } - if (!processChatmessageFurtherAfterSecurityChecks(msg, lang)) - return; - - if (msg.empty()) - break; - if (type == CHAT_MSG_SAY) GetPlayer()->Say(msg, lang); else if (type == CHAT_MSG_EMOTE) @@ -217,25 +250,14 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recv_data) else if (type == CHAT_MSG_YELL) GetPlayer()->Yell(msg, lang); } break; - case CHAT_MSG_WHISPER: { - std::string to, msg; - recv_data >> to; - recv_data >> msg; - if (_player->getLevel() < sWorld.getIntConfig(CONFIG_CHAT_WHISPER_LEVEL_REQ)) { SendNotification(GetTrinityString(LANG_WHISPER_REQ), sWorld.getIntConfig(CONFIG_CHAT_WHISPER_LEVEL_REQ)); return; } - if (!processChatmessageFurtherAfterSecurityChecks(msg, lang)) - return; - - if (msg.empty()) - break; - if (!normalizePlayerName(to)) { SendPlayerNotFoundNotice(to); @@ -270,25 +292,9 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recv_data) GetPlayer()->Whisper(msg, lang, player->GetGUID()); } break; - case CHAT_MSG_PARTY: case CHAT_MSG_PARTY_LEADER: { - std::string msg; - recv_data >> msg; - - if (msg.empty()) - break; - - if (ChatHandler(this).ParseCommands(msg.c_str()) > 0) - break; - - if (!processChatmessageFurtherAfterSecurityChecks(msg, lang)) - return; - - if (msg.empty()) - break; - // if player is in battleground, he cannot say to battleground members by /p Group *group = GetPlayer()->GetOriginalGroup(); if (!group) @@ -307,24 +313,8 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recv_data) ChatHandler::FillMessageData(&data, this, type, lang, NULL, 0, msg.c_str(), NULL); group->BroadcastPacket(&data, false, group->GetMemberGroup(GetPlayer()->GetGUID())); } break; - case CHAT_MSG_GUILD: { - std::string msg; - recv_data >> msg; - - if (msg.empty()) - break; - - if (ChatHandler(this).ParseCommands(msg.c_str()) > 0) - break; - - if (!processChatmessageFurtherAfterSecurityChecks(msg, lang)) - return; - - if (msg.empty()) - break; - if (GetPlayer()->GetGuildId()) { if (Guild *guild = sObjectMgr.GetGuildById(GetPlayer()->GetGuildId())) @@ -334,26 +324,9 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recv_data) guild->BroadcastToGuild(this, false, msg, lang == LANG_ADDON ? LANG_ADDON : LANG_UNIVERSAL); } } - - break; - } + } break; case CHAT_MSG_OFFICER: { - std::string msg; - recv_data >> msg; - - if (msg.empty()) - break; - - if (ChatHandler(this).ParseCommands(msg.c_str()) > 0) - break; - - if (!processChatmessageFurtherAfterSecurityChecks(msg, lang)) - return; - - if (msg.empty()) - break; - if (GetPlayer()->GetGuildId()) { if (Guild *guild = sObjectMgr.GetGuildById(GetPlayer()->GetGuildId())) @@ -363,25 +336,9 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recv_data) guild->BroadcastToGuild(this, true, msg, lang == LANG_ADDON ? LANG_ADDON : LANG_UNIVERSAL); } } - break; - } + } break; case CHAT_MSG_RAID: { - std::string msg; - recv_data >> msg; - - if (msg.empty()) - break; - - if (ChatHandler(this).ParseCommands(msg.c_str()) > 0) - break; - - if (!processChatmessageFurtherAfterSecurityChecks(msg, lang)) - return; - - if (msg.empty()) - break; - // if player is in battleground, he cannot say to battleground members by /ra Group *group = GetPlayer()->GetOriginalGroup(); if (!group) @@ -399,21 +356,6 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recv_data) } break; case CHAT_MSG_RAID_LEADER: { - std::string msg; - recv_data >> msg; - - if (msg.empty()) - break; - - if (ChatHandler(this).ParseCommands(msg.c_str()) > 0) - break; - - if (!processChatmessageFurtherAfterSecurityChecks(msg, lang)) - return; - - if (msg.empty()) - break; - // if player is in battleground, he cannot say to battleground members by /ra Group *group = GetPlayer()->GetOriginalGroup(); if (!group) @@ -431,15 +373,6 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recv_data) } break; case CHAT_MSG_RAID_WARNING: { - std::string msg; - recv_data >> msg; - - if (!processChatmessageFurtherAfterSecurityChecks(msg, lang)) - return; - - if (msg.empty()) - break; - Group *group = GetPlayer()->GetGroup(); if (!group || !group->isRaidGroup() || !(group->IsLeader(GetPlayer()->GetGUID()) || group->IsAssistant(GetPlayer()->GetGUID())) || group->isBGGroup()) return; @@ -451,18 +384,8 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recv_data) ChatHandler::FillMessageData(&data, this, CHAT_MSG_RAID_WARNING, lang, "", 0, msg.c_str(), NULL); group->BroadcastPacket(&data, false); } break; - case CHAT_MSG_BATTLEGROUND: { - std::string msg; - recv_data >> msg; - - if (!processChatmessageFurtherAfterSecurityChecks(msg, lang)) - return; - - if (msg.empty()) - break; - //battleground raid is always in Player->GetGroup(), never in GetOriginalGroup() Group *group = GetPlayer()->GetGroup(); if (!group || !group->isBGGroup()) @@ -474,18 +397,8 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recv_data) ChatHandler::FillMessageData(&data, this, CHAT_MSG_BATTLEGROUND, lang, "", 0, msg.c_str(), NULL); group->BroadcastPacket(&data, false); } break; - case CHAT_MSG_BATTLEGROUND_LEADER: { - std::string msg; - recv_data >> msg; - - if (!processChatmessageFurtherAfterSecurityChecks(msg, lang)) - return; - - if (msg.empty()) - break; - // battleground raid is always in Player->GetGroup(), never in GetOriginalGroup() Group *group = GetPlayer()->GetGroup(); if (!group || !group->isBGGroup() || !group->IsLeader(GetPlayer()->GetGUID())) @@ -497,25 +410,14 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recv_data) ChatHandler::FillMessageData(&data, this, CHAT_MSG_BATTLEGROUND_LEADER, lang, "", 0, msg.c_str(), NULL); group->BroadcastPacket(&data, false); } break; - case CHAT_MSG_CHANNEL: { - std::string channel, msg; - recv_data >> channel; - recv_data >> msg; - - if (!processChatmessageFurtherAfterSecurityChecks(msg, lang)) - return; - if (_player->getLevel() < sWorld.getIntConfig(CONFIG_CHAT_CHANNEL_LEVEL_REQ)) { SendNotification(GetTrinityString(LANG_CHANNEL_REQ), sWorld.getIntConfig(CONFIG_CHAT_CHANNEL_LEVEL_REQ)); return; } - if (msg.empty()) - break; - if (ChannelMgr* cMgr = channelMgr(_player->GetTeam())) { @@ -527,12 +429,8 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recv_data) } } } break; - case CHAT_MSG_AFK: { - std::string msg; - recv_data >> msg; - if ((msg.empty() || !_player->isAFK()) && !_player->isInCombat()) { if (!_player->isAFK()) @@ -549,12 +447,8 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recv_data) _player->ToggleDND(); } } break; - case CHAT_MSG_DND: { - std::string msg; - recv_data >> msg; - if (msg.empty() || !_player->isDND()) { if (!_player->isDND()) @@ -571,7 +465,6 @@ void WorldSession::HandleMessagechatOpcode(WorldPacket & recv_data) _player->ToggleAFK(); } } break; - default: sLog.outError("CHAT: unknown message type %u, lang: %u", type, lang); break; diff --git a/src/server/game/Server/Protocol/Handlers/GuildHandler.cpp b/src/server/game/Server/Protocol/Handlers/GuildHandler.cpp index 421275c94be..0ff97ee8fbe 100755 --- a/src/server/game/Server/Protocol/Handlers/GuildHandler.cpp +++ b/src/server/game/Server/Protocol/Handlers/GuildHandler.cpp @@ -465,7 +465,6 @@ void WorldSession::HandleGuildBankSwapItems(WorldPacket & recv_data) uint8 playerBag = NULL_BAG; uint8 playerSlotId = NULL_SLOT; uint8 toChar = 1; - uint32 autoStoreCount = 0; recv_data >> tabId; recv_data >> slotId; @@ -475,7 +474,7 @@ void WorldSession::HandleGuildBankSwapItems(WorldPacket & recv_data) recv_data >> autoStore; if (autoStore) { - recv_data >> autoStoreCount; + recv_data.read_skip<uint32>(); // autoStoreCount recv_data.read_skip<uint8>(); // ToChar (?), always and expected to be 1 (autostore only triggered in Bank -> Char) recv_data.read_skip<uint32>(); // Always 0 } diff --git a/src/server/game/Server/Protocol/Handlers/LFGHandler.cpp b/src/server/game/Server/Protocol/Handlers/LFGHandler.cpp index 45dea6d98ce..7e65b02b1af 100755 --- a/src/server/game/Server/Protocol/Handlers/LFGHandler.cpp +++ b/src/server/game/Server/Protocol/Handlers/LFGHandler.cpp @@ -15,20 +15,23 @@ * with this program. If not, see <http://www.gnu.org/licenses/>. */ -#include "LFGMgr.h" #include "WorldSession.h" #include "WorldPacket.h" +#include "DBCStores.h" #include "Player.h" -#include "ObjectMgr.h" #include "Group.h" +#include "LFGMgr.h" +#include "ObjectMgr.h" + void BuildPlayerLockDungeonBlock(WorldPacket &data, LfgLockStatusSet* lockSet) { - if (!lockSet || !lockSet->size()) + if (!lockSet) { data << uint8(0); return; } + data << uint32(lockSet->size()); // Size of lock dungeons for (LfgLockStatusSet::iterator it = lockSet->begin(); it != lockSet->end(); ++it) { @@ -36,13 +39,13 @@ void BuildPlayerLockDungeonBlock(WorldPacket &data, LfgLockStatusSet* lockSet) data << uint32((*it)->lockstatus); // Lock status delete (*it); } - lockSet->clear(); delete lockSet; + lockSet = NULL; } void BuildPartyLockDungeonBlock(WorldPacket &data, LfgLockStatusMap* lockMap) { - if (!lockMap || !lockMap->size()) + if (!lockMap) { data << uint8(0); return; @@ -54,8 +57,8 @@ void BuildPartyLockDungeonBlock(WorldPacket &data, LfgLockStatusMap* lockMap) data << uint64(MAKE_NEW_GUID(it->first, 0, HIGHGUID_PLAYER)); // Player guid BuildPlayerLockDungeonBlock(data, it->second); } - lockMap->clear(); delete lockMap; + lockMap = NULL; } void WorldSession::HandleLfgJoinOpcode(WorldPacket &recv_data) @@ -70,8 +73,6 @@ void WorldSession::HandleLfgJoinOpcode(WorldPacket &recv_data) uint8 numDungeons; uint32 dungeon; uint32 roles; - std::string comment; - LfgDungeonSet* newDungeons; recv_data >> roles; recv_data.read_skip<uint16>(); // uint8 (always 0) - uint8 (always 0) @@ -83,17 +84,18 @@ void WorldSession::HandleLfgJoinOpcode(WorldPacket &recv_data) return; } - newDungeons = new LfgDungeonSet(); + LfgDungeonSet newDungeons; for (int8 i = 0 ; i < numDungeons; ++i) { recv_data >> dungeon; - newDungeons->insert((dungeon & 0x00FFFFFF)); // remove the type from the dungeon entry + newDungeons.insert((dungeon & 0x00FFFFFF)); // remove the type from the dungeon entry } recv_data.read_skip<uint32>(); // for 0..uint8 (always 3) { uint8 (always 0) } + std::string comment; recv_data >> comment; - sLog.outDebug("CMSG_LFG_JOIN [" UI64FMTD "] roles: %u, Dungeons: %u, Comment: %s", GetPlayer()->GetGUID(), roles, uint8(newDungeons->size()), comment.c_str()); + sLog.outDebug("CMSG_LFG_JOIN [" UI64FMTD "] roles: %u, Dungeons: %u, Comment: %s", GetPlayer()->GetGUID(), roles, uint8(newDungeons.size()), comment.c_str()); sLFGMgr.Join(GetPlayer(), uint8(roles), newDungeons, comment); } @@ -130,14 +132,12 @@ void WorldSession::HandleLfgSetRolesOpcode(WorldPacket &recv_data) sLog.outDebug("CMSG_LFG_SET_ROLES [" UI64FMTD "] Not in group", GetPlayer()->GetGUID()); return; } - else - sLog.outDebug("CMSG_LFG_SET_ROLES [" UI64FMTD "] Roles: %u", GetPlayer()->GetGUID(), roles); - + sLog.outDebug("CMSG_LFG_SET_ROLES [" UI64FMTD "] Roles: %u", GetPlayer()->GetGUID(), roles); GetPlayer()->SetLfgRoles(roles); sLFGMgr.UpdateRoleCheck(grp, GetPlayer()); } -void WorldSession::HandleSetLfgCommentOpcode(WorldPacket & recv_data) +void WorldSession::HandleLfgSetCommentOpcode(WorldPacket & recv_data) { std::string comment; recv_data >> comment; @@ -167,20 +167,26 @@ void WorldSession::HandleLfgTeleportOpcode(WorldPacket &recv_data) void WorldSession::HandleLfgPlayerLockInfoRequestOpcode(WorldPacket &/*recv_data*/) { sLog.outDebug("CMSG_LFD_PLAYER_LOCK_INFO_REQUEST [" UI64FMTD "]", GetPlayer()->GetGUID()); - uint32 rsize = 0; - uint32 lsize = 0; - LfgDungeonSet* randomlist = sLFGMgr.GetRandomDungeons(GetPlayer()->getLevel(), GetPlayer()->GetSession()->Expansion()); - LfgLockStatusSet* lockSet = sLFGMgr.GetPlayerLockStatusDungeons(GetPlayer()); - if (randomlist) - rsize = randomlist->size(); + // FIXME - Should return seasonals (when not disabled) + LfgDungeonSet randomDungeons; + uint8 level = GetPlayer()->getLevel(); + uint8 expansion = GetPlayer()->GetSession()->Expansion(); + for (uint32 i = 0; i < sLFGDungeonStore.GetNumRows(); ++i) + { + LFGDungeonEntry const* dungeon = sLFGDungeonStore.LookupEntry(i); + if (dungeon && dungeon->type == LFG_TYPE_RANDOM && dungeon && dungeon->expansion <= expansion && + dungeon->minlevel <= level && level <= dungeon->maxlevel) + randomDungeons.insert(dungeon->Entry()); + } - if (lockSet) - lsize = lockSet->size(); + LfgLockStatusSet* lockSet = sLFGMgr.GetPlayerLockStatusDungeons(GetPlayer()); + uint32 rsize = uint32(randomDungeons.size()); + uint32 lsize = lockSet ? uint32(lockSet->size()) : 0; sLog.outDebug("SMSG_LFG_PLAYER_INFO [" UI64FMTD "]", GetPlayer()->GetGUID()); WorldPacket data(SMSG_LFG_PLAYER_INFO, 1 + rsize * (4 + 1 + 4 + 4 + 4 + 4 + 1 + 4 + 4 + 4) + 4 + lsize * (1 + 4 + 4 + 4 + 4 + 1 + 4 + 4 + 4)); - if (!randomlist) + if (!randomDungeons.size()) data << uint8(0); else { @@ -188,11 +194,11 @@ void WorldSession::HandleLfgPlayerLockInfoRequestOpcode(WorldPacket &/*recv_data Quest const* qRew = NULL; uint8 done; - data << uint8(randomlist->size()); // Random Dungeon count - for (LfgDungeonSet::iterator it = randomlist->begin(); it != randomlist->end(); ++it) + data << uint8(randomDungeons.size()); // Random Dungeon count + for (LfgDungeonSet::iterator it = randomDungeons.begin(); it != randomDungeons.end(); ++it) { data << uint32(*it); // Entry - reward = sLFGMgr.GetRandomDungeonReward(*it, GetPlayer()->getLevel()); + reward = sLFGMgr.GetRandomDungeonReward(*it, level); qRew = NULL; if (reward) { @@ -239,8 +245,6 @@ void WorldSession::HandleLfgPlayerLockInfoRequestOpcode(WorldPacket &/*recv_data data << uint8(0); } } - randomlist->clear(); - delete randomlist; } BuildPlayerLockDungeonBlock(data, lockSet); SendPacket(&data); @@ -382,51 +386,55 @@ void WorldSession::SendLfgRoleChosen(uint64 guid, uint8 roles) void WorldSession::SendLfgRoleCheckUpdate(LfgRoleCheck* pRoleCheck) { ASSERT(pRoleCheck); + LfgDungeonSet dungeons; + if (pRoleCheck->rDungeonId) + dungeons.insert(pRoleCheck->rDungeonId); + else + dungeons = pRoleCheck->dungeons; sLog.outDebug("SMSG_LFG_ROLE_CHECK_UPDATE [" UI64FMTD "]", GetPlayer()->GetGUID()); - WorldPacket data(SMSG_LFG_ROLE_CHECK_UPDATE, 4 + 1 + 1 + pRoleCheck->dungeons.size() * 4 + 1 + pRoleCheck->roles.size() * (8 + 1 + 4 + 1)); + WorldPacket data(SMSG_LFG_ROLE_CHECK_UPDATE, 4 + 1 + 1 + dungeons.size() * 4 + 1 + pRoleCheck->roles.size() * (8 + 1 + 4 + 1)); Player* plr; uint8 roles; data << uint32(pRoleCheck->result); // Check result data << uint8(pRoleCheck->result == LFG_ROLECHECK_INITIALITING); - data << uint8(pRoleCheck->dungeons.size()); // Number of dungeons - LFGDungeonEntry const* dungeon; - for (LfgDungeonSet::iterator it = pRoleCheck->dungeons.begin(); it != pRoleCheck->dungeons.end(); ++it) + data << uint8(dungeons.size()); // Number of dungeons + if (dungeons.size()) { - dungeon = sLFGDungeonStore.LookupEntry(*it); - if (!dungeon) + for (LfgDungeonSet::iterator it = dungeons.begin(); it != dungeons.end(); ++it) { - sLog.outError("BuildLfgRoleCheck: Dungeon %u does not exist in dbcs", (*it)); - data << uint32(0); + LFGDungeonEntry const* dungeon = sLFGDungeonStore.LookupEntry(*it); + data << uint32(dungeon ? dungeon->Entry() : 0); // Dungeon } - else - data << uint32(dungeon->Entry()); // Dungeon } data << uint8(pRoleCheck->roles.size()); // Players in group - // Leader info MUST be sent 1st :S - roles = pRoleCheck->roles[pRoleCheck->leader]; - uint64 guid = MAKE_NEW_GUID(pRoleCheck->leader, 0, HIGHGUID_PLAYER); - data << uint64(guid); // Guid - data << uint8(roles > 0); // Ready - data << uint32(roles); // Roles - plr = sObjectMgr.GetPlayer(guid); - data << uint8(plr ? plr->getLevel() : 0); // Level - - for (LfgRolesMap::const_iterator itPlayers = pRoleCheck->roles.begin(); itPlayers != pRoleCheck->roles.end(); ++itPlayers) + if (pRoleCheck->roles.size()) { - if (itPlayers->first == pRoleCheck->leader) - continue; - - roles = itPlayers->second; - guid = MAKE_NEW_GUID(itPlayers->first, 0, HIGHGUID_PLAYER); + // Leader info MUST be sent 1st :S + roles = pRoleCheck->roles[pRoleCheck->leader]; + uint64 guid = MAKE_NEW_GUID(pRoleCheck->leader, 0, HIGHGUID_PLAYER); data << uint64(guid); // Guid data << uint8(roles > 0); // Ready data << uint32(roles); // Roles plr = sObjectMgr.GetPlayer(guid); data << uint8(plr ? plr->getLevel() : 0); // Level + + for (LfgRolesMap::const_iterator itPlayers = pRoleCheck->roles.begin(); itPlayers != pRoleCheck->roles.end(); ++itPlayers) + { + if (itPlayers->first == pRoleCheck->leader) + continue; + + roles = itPlayers->second; + guid = MAKE_NEW_GUID(itPlayers->first, 0, HIGHGUID_PLAYER); + data << uint64(guid); // Guid + data << uint8(roles > 0); // Ready + data << uint32(roles); // Roles + plr = sObjectMgr.GetPlayer(guid); + data << uint8(plr ? plr->getLevel() : 0); // Level + } } SendPacket(&data); } @@ -444,8 +452,7 @@ void WorldSession::SendLfgJoinResult(uint8 checkResult, uint8 checkValue /* = 0 WorldPacket data(SMSG_LFG_JOIN_RESULT, 4 + 4 + size); data << uint32(checkResult); // Check Result data << uint32(checkValue); // Check Value - if (playersLockMap) - BuildPartyLockDungeonBlock(data, playersLockMap); + BuildPartyLockDungeonBlock(data, playersLockMap); SendPacket(&data); } @@ -535,7 +542,7 @@ void WorldSession::SendLfgBootPlayer(LfgPlayerBoot* pBoot) SendPacket(&data); } -void WorldSession::SendUpdateProposal(uint32 proposalId, LfgProposal* pProp) +void WorldSession::SendLfgUpdateProposal(uint32 proposalId, LfgProposal* pProp) { if (!pProp) return; @@ -554,7 +561,7 @@ void WorldSession::SendUpdateProposal(uint32 proposalId, LfgProposal* pProp) Group* grp = dLowGuid ? sObjectMgr.GetGroupByGUID(dLowGuid) : NULL; if (grp) { - isContinue = grp->isLFGGroup() && !grp->isLfgDungeonComplete(); + isContinue = grp->isLFGGroup() && grp->GetLfgState() != LFG_STATE_FINISHED_DUNGEON; isSameDungeon = GetPlayer()->GetGroup() == grp && isContinue; } diff --git a/src/server/game/Server/Protocol/Handlers/MiscHandler.cpp b/src/server/game/Server/Protocol/Handlers/MiscHandler.cpp index b782c8ad4ee..9a77a4b7187 100755 --- a/src/server/game/Server/Protocol/Handlers/MiscHandler.cpp +++ b/src/server/game/Server/Protocol/Handlers/MiscHandler.cpp @@ -47,7 +47,6 @@ #include "ScriptMgr.h" #include "MapManager.h" #include "InstanceScript.h" -#include "LFGMgr.h" #include "GameObjectAI.h" #include "Group.h" @@ -948,7 +947,7 @@ void WorldSession::HandleAreaTriggerOpcode(WorldPacket & recv_data) // Check if we are in LfgGroup and trying to get out the dungeon if (GetPlayer()->GetGroup() && GetPlayer()->GetGroup()->isLFGGroup() && GetPlayer()->GetMap()->IsDungeon() && at->target_mapId != GetPlayer()->GetMapId()) - sLFGMgr.TeleportPlayer(GetPlayer(), true); + GetPlayer()->TeleportToBGEntryPoint(); else GetPlayer()->TeleportTo(at->target_mapId,at->target_X,at->target_Y,at->target_Z,at->target_Orientation,TELE_TO_NOT_LEAVE_TRANSPORT); } diff --git a/src/server/game/Server/Protocol/Opcodes.cpp b/src/server/game/Server/Protocol/Opcodes.cpp index 457aeb195e9..4101014b29c 100755 --- a/src/server/game/Server/Protocol/Opcodes.cpp +++ b/src/server/game/Server/Protocol/Opcodes.cpp @@ -896,7 +896,7 @@ OpcodeHandler opcodeTable[NUM_MSG_TYPES] = /*0x363*/ { "SMSG_LFG_ROLE_CHECK_UPDATE", STATUS_NEVER, &WorldSession::Handle_ServerSide }, /*0x364*/ { "SMSG_LFG_JOIN_RESULT", STATUS_NEVER, &WorldSession::Handle_ServerSide }, /*0x365*/ { "SMSG_LFG_QUEUE_STATUS", STATUS_NEVER, &WorldSession::Handle_ServerSide }, - /*0x366*/ { "CMSG_SET_LFG_COMMENT", STATUS_LOGGEDIN, &WorldSession::HandleSetLfgCommentOpcode }, + /*0x366*/ { "CMSG_SET_LFG_COMMENT", STATUS_LOGGEDIN, &WorldSession::HandleLfgSetCommentOpcode }, /*0x367*/ { "SMSG_LFG_UPDATE_PLAYER", STATUS_NEVER, &WorldSession::Handle_ServerSide }, /*0x368*/ { "SMSG_LFG_UPDATE_PARTY", STATUS_NEVER, &WorldSession::Handle_ServerSide }, /*0x369*/ { "SMSG_LFG_UPDATE_LIST", STATUS_NEVER, &WorldSession::Handle_ServerSide }, diff --git a/src/server/game/Server/WorldSession.h b/src/server/game/Server/WorldSession.h index 9c853ef9b2f..083d4c0786d 100755 --- a/src/server/game/Server/WorldSession.h +++ b/src/server/game/Server/WorldSession.h @@ -718,7 +718,7 @@ class WorldSession void HandleHearthAndResurrect(WorldPacket& recv_data); // Looking for Dungeon/Raid - void HandleSetLfgCommentOpcode(WorldPacket & recv_data); + void HandleLfgSetCommentOpcode(WorldPacket & recv_data); void HandleLfgPlayerLockInfoRequestOpcode(WorldPacket& recv_data); void HandleLfgPartyLockInfoRequestOpcode(WorldPacket& recv_data); void HandleLfgJoinOpcode(WorldPacket &recv_data); @@ -739,7 +739,7 @@ class WorldSession void SendLfgQueueStatus(uint32 dungeon, int32 waitTime, int32 avgWaitTime, int32 waitTimeTanks, int32 waitTimeHealer, int32 waitTimeDps, uint32 queuedTime, uint8 tanks, uint8 healers, uint8 dps); void SendLfgPlayerReward(uint32 rdungeonEntry, uint32 sdungeonEntry, uint8 done, const LfgReward *reward, const Quest *qRew); void SendLfgBootPlayer(LfgPlayerBoot *pBoot); - void SendUpdateProposal(uint32 proposalId, LfgProposal *pProp); + void SendLfgUpdateProposal(uint32 proposalId, LfgProposal *pProp); void SendLfgDisabled(); void SendLfgOfferContinue(uint32 dungeonEntry); void SendLfgTeleportError(uint8 err); diff --git a/src/server/game/Server/WorldSocket.cpp b/src/server/game/Server/WorldSocket.cpp index b4e77af2f09..f6df407279a 100755 --- a/src/server/game/Server/WorldSocket.cpp +++ b/src/server/game/Server/WorldSocket.cpp @@ -562,7 +562,7 @@ int WorldSocket::handle_input_missing_data (void) recv_size); if (n <= 0) - return n; + return int(n); message_block.wr_ptr (n); diff --git a/src/server/game/Skills/SkillExtraItems.cpp b/src/server/game/Skills/SkillExtraItems.cpp index 2f5a310d840..5cc86ffbe3c 100755 --- a/src/server/game/Skills/SkillExtraItems.cpp +++ b/src/server/game/Skills/SkillExtraItems.cpp @@ -52,8 +52,6 @@ SkillExtraItemMap SkillExtraItemStore; // loads the extra item creation info from DB void LoadSkillExtraItemTable() { - uint32 count = 0; - SkillExtraItemStore.clear(); // need for reload // 0 1 2 3 @@ -61,6 +59,8 @@ void LoadSkillExtraItemTable() if (result) { + uint32 count = 0; + barGoLink bar(result->GetRowCount()); do diff --git a/src/server/game/Spells/Auras/SpellAuraDefines.h b/src/server/game/Spells/Auras/SpellAuraDefines.h index e23906b355e..019ff85e93d 100755 --- a/src/server/game/Spells/Auras/SpellAuraDefines.h +++ b/src/server/game/Spells/Auras/SpellAuraDefines.h @@ -192,7 +192,7 @@ enum AuraType SPELL_AURA_MOD_HEALING_DONE = 135, SPELL_AURA_MOD_HEALING_DONE_PERCENT = 136, SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE = 137, - SPELL_AURA_MOD_HASTE = 138, + SPELL_AURA_MOD_MELEE_HASTE = 138, SPELL_AURA_FORCE_REACTION = 139, SPELL_AURA_MOD_RANGED_HASTE = 140, SPELL_AURA_MOD_RANGED_AMMO_HASTE = 141, @@ -246,7 +246,7 @@ enum AuraType SPELL_AURA_MOD_RATING = 189, SPELL_AURA_MOD_FACTION_REPUTATION_GAIN = 190, SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED = 191, - SPELL_AURA_HASTE_MELEE = 192, + SPELL_AURA_MOD_MELEE_RANGED_HASTE = 192, SPELL_AURA_MELEE_SLOW = 193, SPELL_AURA_MOD_TARGET_ABSORB_SCHOOL = 194, SPELL_AURA_MOD_TARGET_ABILITY_ABSORB_SCHOOL = 195, diff --git a/src/server/game/Spells/Auras/SpellAuraEffects.cpp b/src/server/game/Spells/Auras/SpellAuraEffects.cpp index 49bb9b4e52b..03780375f00 100755 --- a/src/server/game/Spells/Auras/SpellAuraEffects.cpp +++ b/src/server/game/Spells/Auras/SpellAuraEffects.cpp @@ -190,7 +190,7 @@ pAuraEffectHandler AuraEffectHandler[TOTAL_AURAS]= &AuraEffect::HandleModHealingDone, //135 SPELL_AURA_MOD_HEALING_DONE &AuraEffect::HandleNoImmediateEffect, //136 SPELL_AURA_MOD_HEALING_DONE_PERCENT implemented in Unit::SpellHealingBonus &AuraEffect::HandleModTotalPercentStat, //137 SPELL_AURA_MOD_TOTAL_STAT_PERCENTAGE - &AuraEffect::HandleHaste, //138 SPELL_AURA_MOD_HASTE + &AuraEffect::HandleModMeleeSpeedPct, //138 SPELL_AURA_MOD_MELEE_HASTE &AuraEffect::HandleForceReaction, //139 SPELL_AURA_FORCE_REACTION &AuraEffect::HandleAuraModRangedHaste, //140 SPELL_AURA_MOD_RANGED_HASTE &AuraEffect::HandleRangedAmmoHaste, //141 SPELL_AURA_MOD_RANGED_AMMO_HASTE @@ -244,7 +244,7 @@ pAuraEffectHandler AuraEffectHandler[TOTAL_AURAS]= &AuraEffect::HandleModRating, //189 SPELL_AURA_MOD_RATING &AuraEffect::HandleNoImmediateEffect, //190 SPELL_AURA_MOD_FACTION_REPUTATION_GAIN implemented in Player::CalculateReputationGain &AuraEffect::HandleAuraModUseNormalSpeed, //191 SPELL_AURA_USE_NORMAL_MOVEMENT_SPEED - &AuraEffect::HandleModMeleeRangedSpeedPct, //192 SPELL_AURA_HASTE_MELEE + &AuraEffect::HandleModMeleeRangedSpeedPct, //192 SPELL_AURA_MOD_MELEE_RANGED_HASTE &AuraEffect::HandleModCombatSpeedPct, //193 SPELL_AURA_MELEE_SLOW (in fact combat (any type attack) speed pct) &AuraEffect::HandleNoImmediateEffect, //194 SPELL_AURA_MOD_TARGET_ABSORB_SCHOOL implemented in Unit::CalcAbsorbResist &AuraEffect::HandleNoImmediateEffect, //195 SPELL_AURA_MOD_TARGET_ABILITY_ABSORB_SCHOOL implemented in Unit::CalcAbsorbResist @@ -400,6 +400,17 @@ void AuraEffect::GetTargetList(std::list<Unit *> & targetList) const } } +void AuraEffect::GetApplicationList(std::list<AuraApplication *> & applicationList) const +{ + Aura::ApplicationMap const & targetMap = GetBase()->GetApplicationMap(); + // remove all targets which were not added to new list - they no longer deserve area aura + for (Aura::ApplicationMap::const_iterator appIter = targetMap.begin(); appIter != targetMap.end(); ++appIter) + { + if (appIter->second->HasEffect(GetEffIndex())) + applicationList.push_back(appIter->second); + } +} + int32 AuraEffect::CalculateAmount(Unit * caster) { int32 amount; @@ -461,7 +472,7 @@ int32 AuraEffect::CalculateAmount(Unit * caster) // Glyph of Fear, Glyph of Frost nova and similar auras if ((*itr)->GetMiscValue() == 7801) { - amount += (int32)(amount*(*itr)->GetAmount()/100.0f); + AddPctN(amount, (*itr)->GetAmount()); break; } } @@ -482,7 +493,7 @@ int32 AuraEffect::CalculateAmount(Unit * caster) DoneActualBenefit += caster->SpellBaseDamageBonus(GetSpellSchoolMask(m_spellProto)) * 0.8068f; // Glyph of Ice Barrier: its weird having a SPELLMOD_ALL_EFFECTS here but its blizzards doing :) // Glyph of Ice Barrier is only applied at the spell damage bonus because it was already applied to the base value in CalculateSpellDamage - DoneActualBenefit = caster->ApplyEffectModifiers(GetSpellProto(), m_effIndex, (int32)DoneActualBenefit); + DoneActualBenefit = caster->ApplyEffectModifiers(GetSpellProto(), m_effIndex, DoneActualBenefit); } // Fire Ward else if(GetSpellProto()->SpellFamilyFlags[0] & 0x8 && GetSpellProto()->SpellFamilyFlags[2] & 0x8) @@ -509,27 +520,27 @@ int32 AuraEffect::CalculateAmount(Unit * caster) // Power Word: Shield if (GetSpellProto()->SpellFamilyFlags[0] & 0x1 && GetSpellProto()->SpellFamilyFlags[2] & 0x400) { - //+80.68% from sp bonus + // +80.68% from sp bonus float bonus = 0.8068f; // Borrowed Time if (AuraEffect const* pAurEff = caster->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_PRIEST, 2899, 1)) - bonus += (float)pAurEff->GetAmount() / 100.0f; + bonus += CalculatePctN(1.0f, pAurEff->GetAmount()); DoneActualBenefit += caster->SpellBaseHealingBonus(GetSpellSchoolMask(m_spellProto)) * bonus; // Improved PW: Shield: its weird having a SPELLMOD_ALL_EFFECTS here but its blizzards doing :) // Improved PW: Shield is only applied at the spell healing bonus because it was already applied to the base value in CalculateSpellDamage - DoneActualBenefit = caster->ApplyEffectModifiers(GetSpellProto(), m_effIndex, (int32)DoneActualBenefit); + DoneActualBenefit = caster->ApplyEffectModifiers(GetSpellProto(), m_effIndex, DoneActualBenefit); DoneActualBenefit *= caster->CalculateLevelPenalty(GetSpellProto()); - amount += (int32)DoneActualBenefit; + amount += int32(DoneActualBenefit); // Twin Disciplines if (AuraEffect const* pAurEff = caster->GetAuraEffect(SPELL_AURA_ADD_PCT_MODIFIER, SPELLFAMILY_PRIEST, 0x400000, 0, 0, caster->GetGUID())) - amount *= (100.0f + pAurEff->GetAmount()) / 100.0f; + AddPctN(amount, pAurEff->GetAmount()); // Focused Power - amount *= caster->GetTotalAuraMultiplier(SPELL_AURA_MOD_HEALING_DONE_PERCENT); + amount *= int32(caster->GetTotalAuraMultiplier(SPELL_AURA_MOD_HEALING_DONE_PERCENT)); return amount; } @@ -543,17 +554,17 @@ int32 AuraEffect::CalculateAmount(Unit * caster) DoneActualBenefit += caster->SpellBaseHealingBonus(GetSpellSchoolMask(m_spellProto)) * bonus; // Divine Guardian is only applied at the spell healing bonus because it was already applied to the base value in CalculateSpellDamage - DoneActualBenefit = caster->ApplyEffectModifiers(GetSpellProto(), m_effIndex, (int32)DoneActualBenefit); + DoneActualBenefit = caster->ApplyEffectModifiers(GetSpellProto(), m_effIndex, DoneActualBenefit); DoneActualBenefit *= caster->CalculateLevelPenalty(GetSpellProto()); amount += (int32)DoneActualBenefit; // Arena - Dampening if (AuraEffect const* pAurEff = caster->GetAuraEffect(74410, 0)) - amount *= (100.0f + pAurEff->GetAmount()) / 100.0f; + AddPctN(amount, pAurEff->GetAmount()); // Battleground - Dampening else if (AuraEffect const* pAurEff = caster->GetAuraEffect(74411, 0)) - amount *= (100.0f + pAurEff->GetAmount()) / 100.0f; + AddPctN(amount, pAurEff->GetAmount()); return amount; } @@ -621,24 +632,25 @@ int32 AuraEffect::CalculateAmount(Unit * caster) if (AuraEffect const * aurEff = caster->GetAuraEffect(34241,0)) amount += cp * aurEff->GetAmount(); - amount += int32(caster->GetTotalAttackPowerValue(BASE_ATTACK) * cp / 100); + amount += CalculatePctF(cp, caster->GetTotalAttackPowerValue(BASE_ATTACK)); } // Rend else if (GetSpellProto()->SpellFamilyName == SPELLFAMILY_WARRIOR && GetSpellProto()->SpellFamilyFlags[0] & 0x20) { m_canBeRecalculated = false; - // $0.2*(($MWB+$mwb)/2+$AP/14*$MWS) bonus per tick + // $0.2 * (($MWB + $mwb) / 2 + $AP / 14 * $MWS) bonus per tick float ap = caster->GetTotalAttackPowerValue(BASE_ATTACK); int32 mws = caster->GetAttackTime(BASE_ATTACK); float mwb_min = caster->GetWeaponDamageRange(BASE_ATTACK,MINDAMAGE); float mwb_max = caster->GetWeaponDamageRange(BASE_ATTACK,MAXDAMAGE); - amount+=caster->ApplyEffectModifiers(m_spellProto,m_effIndex,int32(((mwb_min+mwb_max)/2+ap*mws/14000)*0.2f)); + float mwb = ((mwb_min + mwb_max) / 2 + ap * mws / 14000) * 0.2f; + amount += int32(caster->ApplyEffectModifiers(m_spellProto, m_effIndex, mwb)); // "If used while your target is above 75% health, Rend does 35% more damage." // as for 3.1.3 only ranks above 9 (wrong tooltip?) if (sSpellMgr.GetSpellRank(m_spellProto->Id) >= 9) { if (GetBase()->GetUnitOwner()->HasAuraState(AURA_STATE_HEALTH_ABOVE_75_PERCENT, m_spellProto, caster)) - amount += int32(amount * SpellMgr::CalculateSpellEffectAmount(m_spellProto, 2, caster) / 100.0f); + AddPctN(amount, SpellMgr::CalculateSpellEffectAmount(m_spellProto, 2, caster)); } } // Unholy Blight damage over time effect @@ -659,10 +671,10 @@ int32 AuraEffect::CalculateAmount(Unit * caster) } // Innervate else if (m_spellProto->Id == 29166) - amount = int32(GetBase()->GetUnitOwner()->GetCreatePowers(POWER_MANA) * amount / (GetTotalTicks() * 100.0f)); + ApplyPctF(amount, float(GetBase()->GetUnitOwner()->GetCreatePowers(POWER_MANA)) / GetTotalTicks()); // Owlkin Frenzy else if (m_spellProto->Id == 48391) - amount = GetBase()->GetUnitOwner()->GetCreatePowers(POWER_MANA) * amount / 100; + ApplyPctU(amount, GetBase()->GetUnitOwner()->GetCreatePowers(POWER_MANA)); break; case SPELL_AURA_PERIODIC_HEAL: if (!caster) @@ -673,7 +685,7 @@ int32 AuraEffect::CalculateAmount(Unit * caster) if (caster->GetTypeId() == TYPEID_PLAYER) // Bonus from Glyph of Lightwell if (AuraEffect* modHealing = caster->GetAuraEffect(55673, 0)) - amount = int32(amount * (100.0f + modHealing->GetAmount()) / 100.0f); + AddPctN(amount, modHealing->GetAmount()); } break; case SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN: @@ -738,12 +750,12 @@ int32 AuraEffect::CalculateAmount(Unit * caster) case SPELL_AURA_MOD_INCREASE_ENERGY: // Hymn of Hope if (GetId() == 64904) - amount = GetBase()->GetUnitOwner()->GetMaxPower(GetBase()->GetUnitOwner()->getPowerType()) * amount / 100; + ApplyPctU(amount, GetBase()->GetUnitOwner()->GetMaxPower(GetBase()->GetUnitOwner()->getPowerType())); break; case SPELL_AURA_MOD_INCREASE_SPEED: // Dash - do not set speed if not in cat form if (GetSpellProto()->SpellFamilyName == SPELLFAMILY_DRUID && GetSpellProto()->SpellFamilyFlags[2] & 0x00000008) - amount = GetBase()->GetUnitOwner()->m_form == FORM_CAT ? amount : 0; + amount = GetBase()->GetUnitOwner()->GetShapeshiftForm() == FORM_CAT ? amount : 0; break; default: break; @@ -1057,13 +1069,13 @@ void AuraEffect::Update(uint32 diff, Unit * caster) m_periodicTimer += m_amplitude - diff; UpdatePeriodic(caster); - UnitList effectTargets; - GetTargetList(effectTargets); + std::list<AuraApplication*> effectApplications; + GetApplicationList(effectApplications); // tick on targets of effects if (!caster || !caster->hasUnitState(UNIT_STAT_ISOLATED)) { - for (UnitList::iterator targetItr = effectTargets.begin(); targetItr != effectTargets.end(); ++targetItr) - PeriodicTick(*targetItr, caster); + for (std::list<AuraApplication*>::iterator apptItr = effectApplications.begin(); apptItr != effectApplications.end(); ++apptItr) + PeriodicTick(*apptItr, caster); } } } @@ -1224,12 +1236,14 @@ void AuraEffect::SendTickImmune(Unit * target, Unit *caster) const caster->SendSpellDamageImmune(target, m_spellProto->Id); } -void AuraEffect::PeriodicTick(Unit * target, Unit * caster) const +void AuraEffect::PeriodicTick(AuraApplication * aurApp, Unit * caster) const { - bool prevented = GetBase()->CallScriptEffectPeriodicHandlers(const_cast<AuraEffect const *>(this), GetBase()->GetApplicationOfTarget(target->GetGUID())); + bool prevented = GetBase()->CallScriptEffectPeriodicHandlers(const_cast<AuraEffect const *>(this), aurApp); if (prevented) return; + Unit * target = aurApp->GetTarget(); + switch(GetAuraType()) { case SPELL_AURA_PERIODIC_DAMAGE: @@ -1537,27 +1551,27 @@ void AuraEffect::PeriodicTick(Unit * target, Unit * caster) const // Tenacity increase healing % taken if (AuraEffect const* Tenacity = target->GetAuraEffect(58549, 0)) - TakenTotalMod *= (Tenacity->GetAmount() + 100.0f) / 100.0f; + AddPctN(TakenTotalMod, Tenacity->GetAmount()); // Healing taken percent float minval = (float)target->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HEALING_PCT); if (minval) - TakenTotalMod *= (100.0f + minval) / 100.0f; + AddPctF(TakenTotalMod, minval); float maxval = (float)target->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HEALING_PCT); if (maxval) - TakenTotalMod *= (100.0f + maxval) / 100.0f; + AddPctF(TakenTotalMod, maxval); // Healing over time taken percent float minval_hot = (float)target->GetMaxNegativeAuraModifier(SPELL_AURA_MOD_HOT_PCT); if (minval_hot) - TakenTotalMod *= (100.0f + minval_hot) / 100.0f; + AddPctF(TakenTotalMod, minval_hot); float maxval_hot = (float)target->GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HOT_PCT); if (maxval_hot) - TakenTotalMod *= (100.0f + maxval_hot) / 100.0f; + AddPctF(TakenTotalMod, maxval_hot); - TakenTotalMod = TakenTotalMod > 0.0f ? TakenTotalMod : 0.0f; + TakenTotalMod = std::max(TakenTotalMod, 0.0f); damage = uint32(target->CountPctFromMaxHealth(damage)); damage = uint32(damage * TakenTotalMod); @@ -1657,8 +1671,8 @@ void AuraEffect::PeriodicTick(Unit * target, Unit * caster) const if (m_spellProto->ManaCostPercentage) { // max value - uint32 maxmana = caster->GetMaxPower(power) * damage * 2 / 100; - damage = target->GetMaxPower(power) * damage / 100; + uint32 maxmana = CalculatePctF(caster->GetMaxPower(power), damage * 2.0f); + ApplyPctU(damage, target->GetMaxPower(power)); if (damage > maxmana) damage = maxmana; } @@ -1666,7 +1680,7 @@ void AuraEffect::PeriodicTick(Unit * target, Unit * caster) const sLog.outDetail("PeriodicTick: %u (TypeId: %u) power leech of %u (TypeId: %u) for %u dmg inflicted by %u", GUID_LOPART(GetCasterGUID()), GuidHigh2TypeId(GUID_HIPART(GetCasterGUID())), target->GetGUIDLow(), target->GetTypeId(), damage, GetId()); - int32 drain_amount = target->GetPower(power) > damage ? damage : target->GetPower(power); + int32 drain_amount = std::min(target->GetPower(power), damage); // resilience reduce mana draining effect at spell crit damage reduction (added in 2.4) if (power == POWER_MANA) @@ -1686,7 +1700,7 @@ void AuraEffect::PeriodicTick(Unit * target, Unit * caster) const if (gain_amount) { - int32 gain = caster->ModifyPower(power,gain_amount); + int32 gain = caster->ModifyPower(power, gain_amount); target->AddThreat(caster, float(gain) * 0.5f, GetSpellSchoolMask(GetSpellProto()), GetSpellProto()); } @@ -1722,7 +1736,7 @@ void AuraEffect::PeriodicTick(Unit * target, Unit * caster) const // Mana Feed - Drain Mana if (manaFeedVal > 0) { - manaFeedVal = manaFeedVal * gain_amount / 100; + ApplyPctN(manaFeedVal, gain_amount); caster->CastCustomSpell(caster, 32554, &manaFeedVal, NULL, NULL, true, NULL, this); } } @@ -2751,7 +2765,7 @@ void AuraEffect::HandleModInvisibility(AuraApplication const * aurApp, uint8 mod // apply glow vision if (target->GetTypeId() == TYPEID_PLAYER) - target->SetFlag(PLAYER_FIELD_BYTES2,PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW); + target->SetByteFlag(PLAYER_FIELD_BYTES2, 3, PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW); target->m_invisibility.AddFlag(type); target->m_invisibility.AddValue(type, GetAmount()); @@ -2763,7 +2777,7 @@ void AuraEffect::HandleModInvisibility(AuraApplication const * aurApp, uint8 mod // if not have different invisibility auras. // remove glow vision if (target->GetTypeId() == TYPEID_PLAYER) - target->RemoveFlag(PLAYER_FIELD_BYTES2,PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW); + target->RemoveByteFlag(PLAYER_FIELD_BYTES2, 3, PLAYER_FIELD_BYTE2_INVISIBILITY_GLOW); target->m_invisibility.DelFlag(type); } @@ -2819,7 +2833,7 @@ void AuraEffect::HandleModStealth(AuraApplication const * aurApp, uint8 mode, bo target->SetStandFlags(UNIT_STAND_FLAGS_CREEP); if (target->GetTypeId() == TYPEID_PLAYER) - target->SetFlag(PLAYER_FIELD_BYTES2, 0x2000); + target->SetByteFlag(PLAYER_FIELD_BYTES2, 3, PLAYER_FIELD_BYTE2_STEALTH); } else { @@ -2831,7 +2845,7 @@ void AuraEffect::HandleModStealth(AuraApplication const * aurApp, uint8 mode, bo target->RemoveStandFlags(UNIT_STAND_FLAGS_CREEP); if (target->GetTypeId() == TYPEID_PLAYER) - target->RemoveFlag(PLAYER_FIELD_BYTES2, 0x2000); + target->RemoveByteFlag(PLAYER_FIELD_BYTES2, 3, PLAYER_FIELD_BYTE2_STEALTH); } } @@ -3041,10 +3055,7 @@ void AuraEffect::HandleAuraModShapeshift(AuraApplication const * aurApp, uint8 m if (apply) { // remove other shapeshift before applying a new one - if (target->m_ShapeShiftFormSpellId) - target->RemoveAurasDueToSpell(target->m_ShapeShiftFormSpellId); - - target->SetByteValue(UNIT_FIELD_BYTES_2, 3, form); + target->RemoveAurasByType(SPELL_AURA_MOD_SHAPESHIFT, 0, GetBase()); if (modelid > 0) target->SetDisplayId(modelid); @@ -3093,8 +3104,7 @@ void AuraEffect::HandleAuraModShapeshift(AuraApplication const * aurApp, uint8 m } } - target->m_ShapeShiftFormSpellId = GetId(); - target->m_form = form; + target->SetShapeshiftForm(form); } else { @@ -3103,8 +3113,7 @@ void AuraEffect::HandleAuraModShapeshift(AuraApplication const * aurApp, uint8 m target->SetByteValue(UNIT_FIELD_BYTES_2, 3, FORM_NONE); if (target->getClass() == CLASS_DRUID) target->setPowerType(POWER_MANA); - target->m_ShapeShiftFormSpellId = 0; - target->m_form = FORM_NONE; + target->SetShapeshiftForm(FORM_NONE); switch(form) { @@ -5218,7 +5227,7 @@ void AuraEffect::HandleModAttackSpeed(AuraApplication const * aurApp, uint8 mode target->UpdateDamagePhysical(BASE_ATTACK); } -void AuraEffect::HandleHaste(AuraApplication const * aurApp, uint8 mode, bool apply) const +void AuraEffect::HandleModMeleeSpeedPct(AuraApplication const * aurApp, uint8 mode, bool apply) const { if (!(mode & (AURA_EFFECT_HANDLE_CHANGE_AMOUNT_MASK | AURA_EFFECT_HANDLE_STAT))) return; @@ -5227,7 +5236,6 @@ void AuraEffect::HandleHaste(AuraApplication const * aurApp, uint8 mode, bool ap target->ApplyAttackTimePercentMod(BASE_ATTACK, (float)GetAmount(), apply); target->ApplyAttackTimePercentMod(OFF_ATTACK, (float)GetAmount(), apply); - target->ApplyAttackTimePercentMod(RANGED_ATTACK, (float)GetAmount(), apply); } void AuraEffect::HandleAuraModRangedHaste(AuraApplication const * aurApp, uint8 mode, bool apply) const @@ -5563,10 +5571,10 @@ void AuraEffect::HandleModPowerCostPCT(AuraApplication const * aurApp, uint8 mod Unit * target = aurApp->GetTarget(); - float amount = GetAmount() /100.0f; + float amount = CalculatePctN(1.0f, GetAmount()); for (int i = 0; i < MAX_SPELL_SCHOOL; ++i) - if (GetMiscValue() & (1<<i)) - target->ApplyModSignedFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,amount,apply); + if (GetMiscValue() & (1 << i)) + target->ApplyModSignedFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER + i, amount, apply); } void AuraEffect::HandleModPowerCost(AuraApplication const * aurApp, uint8 mode, bool apply) const @@ -5923,7 +5931,7 @@ void AuraEffect::HandleAuraDummy(AuraApplication const * aurApp, uint8 mode, boo // restore mana if (caster) { - int32 returnmana = (GetSpellProto()->ManaCostPercentage * caster->GetCreateMana() / 100) * stack / 2; + int32 returnmana = CalculatePctU(caster->GetCreateMana(), GetSpellProto()->ManaCostPercentage) * stack / 2; caster->CastCustomSpell(caster, 64372, &returnmana, NULL, NULL, true, NULL, this, GetCasterGUID()); } } @@ -6122,7 +6130,7 @@ void AuraEffect::HandleAuraDummy(AuraApplication const * aurApp, uint8 mode, boo uint32 spellId = 62071; if (apply) { - if (target->m_form != FORM_CAT) + if (target->GetShapeshiftForm() != FORM_CAT) break; target->CastSpell(target, spellId, true, NULL, NULL, GetCasterGUID()); @@ -6493,7 +6501,7 @@ void AuraEffect::HandleAuraOverrideSpells(AuraApplication const * aurApp, uint8 if (apply) { - target->SetUInt32Value(PLAYER_FIELD_BYTES2, overrideId); + target->SetUInt16Value(PLAYER_FIELD_BYTES2, 0, overrideId); if (OverrideSpellDataEntry const* overrideSpells = sOverrideSpellDataStore.LookupEntry(overrideId)) for (uint8 i = 0; i < MAX_OVERRIDE_SPELL; ++i) if (uint32 spellId = overrideSpells->spellId[i]) @@ -6501,7 +6509,7 @@ void AuraEffect::HandleAuraOverrideSpells(AuraApplication const * aurApp, uint8 } else { - target->SetUInt32Value(PLAYER_FIELD_BYTES2, 0); + target->SetUInt16Value(PLAYER_FIELD_BYTES2, 0, 0); if (OverrideSpellDataEntry const* overrideSpells = sOverrideSpellDataStore.LookupEntry(overrideId)) for (uint8 i = 0; i < MAX_OVERRIDE_SPELL; ++i) if (uint32 spellId = overrideSpells->spellId[i]) diff --git a/src/server/game/Spells/Auras/SpellAuraEffects.h b/src/server/game/Spells/Auras/SpellAuraEffects.h index 2807e621673..80809c9d0bb 100644 --- a/src/server/game/Spells/Auras/SpellAuraEffects.h +++ b/src/server/game/Spells/Auras/SpellAuraEffects.h @@ -23,6 +23,7 @@ class AuraEffect uint64 GetCasterGUID() const { return GetBase()->GetCasterGUID(); } Aura * GetBase() const { return m_base; } void GetTargetList(std::list<Unit*> & targetList) const; + void GetApplicationList(std::list<AuraApplication*> & applicationList) const; SpellEntry const * GetSpellProto() const { return m_spellProto; } uint32 GetId() const { return m_spellProto->Id; } @@ -63,7 +64,7 @@ class AuraEffect void SendTickImmune(Unit * target, Unit *caster) const; - void PeriodicTick(Unit * target, Unit * caster) const; + void PeriodicTick(AuraApplication * aurApp, Unit * caster) const; void PeriodicDummyTick(Unit * target, Unit * caster) const; Unit* GetTriggerTarget(Unit * target) const; void TriggerSpell(Unit * target, Unit * caster) const; @@ -222,7 +223,7 @@ class AuraEffect void HandleModMeleeRangedSpeedPct(AuraApplication const * aurApp, uint8 mode, bool apply) const; void HandleModCombatSpeedPct(AuraApplication const * aurApp, uint8 mode, bool apply) const; void HandleModAttackSpeed(AuraApplication const * aurApp, uint8 mode, bool apply) const; - void HandleHaste(AuraApplication const * aurApp, uint8 mode, bool apply) const; + void HandleModMeleeSpeedPct(AuraApplication const * aurApp, uint8 mode, bool apply) const; void HandleAuraModRangedHaste(AuraApplication const * aurApp, uint8 mode, bool apply) const; void HandleRangedAmmoHaste(AuraApplication const * aurApp, uint8 mode, bool apply) const; // combat rating @@ -263,4 +264,62 @@ class AuraEffect void HandleAuraModFakeInebriation(AuraApplication const * aurApp, uint8 mode, bool apply) const; }; -#endif
\ No newline at end of file +namespace Trinity +{ + // Binary predicate for sorting the priority of absorption aura effects + class AbsorbAuraOrderPred + { + public: + AbsorbAuraOrderPred() { } + bool operator() (AuraEffect * aurEffA, AuraEffect * aurEffB) const + { + SpellEntry const * spellProtoA = aurEffA->GetSpellProto(); + SpellEntry const * spellProtoB = aurEffB->GetSpellProto(); + + // Wards + if ((spellProtoA->SpellFamilyName == SPELLFAMILY_MAGE) || + (spellProtoA->SpellFamilyName == SPELLFAMILY_WARLOCK)) + if (spellProtoA->Category == 56) + return true; + if ((spellProtoB->SpellFamilyName == SPELLFAMILY_MAGE) || + (spellProtoB->SpellFamilyName == SPELLFAMILY_WARLOCK)) + if (spellProtoB->Category == 56) + return false; + + // Sacred Shield + if (spellProtoA->Id == 58597) + return true; + if (spellProtoB->Id == 58597) + return false; + + // Fel Blossom + if (spellProtoA->Id == 28527) + return true; + if (spellProtoB->Id == 28527) + return false; + + // Divine Aegis + if (spellProtoA->Id == 47753) + return true; + if (spellProtoB->Id == 47753) + return false; + + // Ice Barrier + if (spellProtoA->Category == 471) + return true; + if (spellProtoB->Category == 471) + return false; + + // Sacrifice + if ((spellProtoA->SpellFamilyName == SPELLFAMILY_WARLOCK) && + (spellProtoA->SpellIconID == 693)) + return true; + if ((spellProtoB->SpellFamilyName == SPELLFAMILY_WARLOCK) && + (spellProtoB->SpellIconID == 693)) + return false; + + return false; + } + }; +} +#endif diff --git a/src/server/game/Spells/Auras/SpellAuras.cpp b/src/server/game/Spells/Auras/SpellAuras.cpp index 05e3b937ab0..21cad6bdd3f 100755 --- a/src/server/game/Spells/Auras/SpellAuras.cpp +++ b/src/server/game/Spells/Auras/SpellAuras.cpp @@ -988,10 +988,10 @@ void Aura::HandleAuraSpecificMods(AuraApplication const * aurApp, Unit * caster, case 48020: // Demonic Circle if (target->GetTypeId() == TYPEID_PLAYER) if (GameObject* obj = target->GetGameObject(48018)) - { - target->ToPlayer()->TeleportTo(obj->GetMapId(),obj->GetPositionX(),obj->GetPositionY(),obj->GetPositionZ(),obj->GetOrientation()); - target->ToPlayer()->RemoveMovementImpairingAuras(); - } + { + target->ToPlayer()->TeleportTo(obj->GetMapId(),obj->GetPositionX(),obj->GetPositionY(),obj->GetPositionZ(),obj->GetOrientation()); + target->ToPlayer()->RemoveMovementImpairingAuras(); + } break; } break; @@ -1271,7 +1271,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const * aurApp, Unit * caster, else if (aurEff->GetId() == 47537) multiplier += 0.5f; - int32 basepoints0 = int32(multiplier * caster->GetMaxPower(POWER_MANA) / 100); + int32 basepoints0 = int32(CalculatePctF(caster->GetMaxPower(POWER_MANA), multiplier)); caster->CastCustomSpell(caster, 47755, &basepoints0, NULL, NULL, true); } // effect on aura target @@ -1285,7 +1285,7 @@ void Aura::HandleAuraSpecificMods(AuraApplication const * aurApp, Unit * caster, { case POWER_MANA: { - int32 basepoints0 = 2 * (target->GetMaxPower(POWER_MANA) / 100); + int32 basepoints0 = int32(CalculatePctN(target->GetMaxPower(POWER_MANA), 2)); caster->CastCustomSpell(target, 63654, &basepoints0, NULL, NULL, true); break; } diff --git a/src/server/game/Spells/Spell.cpp b/src/server/game/Spells/Spell.cpp index e105da7ca4d..a0dee3630d1 100755 --- a/src/server/game/Spells/Spell.cpp +++ b/src/server/game/Spells/Spell.cpp @@ -1298,7 +1298,7 @@ void Spell::DoAllEffectOnTarget(TargetInfo *target) if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->SpellFamilyFlags[1] & 0x40000 && m_spellAura && m_spellAura->GetEffect(1)) { AuraEffect * aurEff = m_spellAura->GetEffect(1); - aurEff->SetAmount(aurEff->GetAmount() * damageInfo.damage / 100); + aurEff->SetAmount(CalculatePctU(aurEff->GetAmount(), damageInfo.damage)); } } // Passive spell hits/misses or active spells only misses (only triggers) @@ -2745,19 +2745,6 @@ void Spell::SelectEffectTargets(uint32 i, uint32 cur) unitList.sort(Trinity::PowerPctOrderPred((Powers)power)); unitList.resize(maxSize); } - - // Replenishment: refresh existing auras - if (m_spellInfo->Id == 57669) - for (std::list<Unit *>::iterator itr = unitList.begin(); itr != unitList.end();) - if (AuraEffect *aurEff = (*itr)->GetAuraEffect(SPELL_AURA_PERIODIC_ENERGIZE, SPELLFAMILY_GENERIC, 3184, EFFECT_0)) - { - aurEff->SetAmount((*itr)->GetMaxPower(POWER_MANA) * 25 / 10000); - aurEff->GetBase()->RefreshDuration(); - - itr = unitList.erase(itr); - } - else - ++itr; } } @@ -2778,6 +2765,8 @@ void Spell::SelectEffectTargets(uint32 i, uint32 cur) switch (m_spellInfo->Id) { case 27285: // Seed of Corruption proc spell + case 49821: // Mind Sear proc spell Rank 1 + case 53022: // Mind Sear proc spell Rank 2 unitList.remove(m_targets.getUnitTarget()); break; case 55789: // Improved Icy Talons @@ -4799,7 +4788,7 @@ SpellCastResult Spell::CheckCast(bool strict) if (checkForm) { // Cannot be used in this stance/form - SpellCastResult shapeError = GetErrorAtShapeshiftedCast(m_spellInfo, m_caster->m_form); + SpellCastResult shapeError = GetErrorAtShapeshiftedCast(m_spellInfo, m_caster->GetShapeshiftForm()); if (shapeError != SPELL_CAST_OK) return shapeError; @@ -5578,11 +5567,7 @@ SpellCastResult Spell::CheckCast(bool strict) if (m_caster->GetTypeId() == TYPEID_PLAYER && !AllowMount && !m_IsTriggeredSpell && !m_spellInfo->AreaGroupId) return SPELL_FAILED_NO_MOUNTS_ALLOWED; - ShapeshiftForm form = m_caster->m_form; - if (form == FORM_CAT || form == FORM_TREE || form == FORM_TRAVEL || - form == FORM_AQUA || form == FORM_BEAR || form == FORM_DIREBEAR || - form == FORM_CREATUREBEAR || form == FORM_GHOSTWOLF || form == FORM_FLIGHT || - form == FORM_FLIGHT_EPIC || form == FORM_MOONKIN || form == FORM_METAMORPHOSIS) + if (m_caster->IsInDisallowedMountForm()) return SPELL_FAILED_NOT_SHAPESHIFT; break; @@ -6465,7 +6450,7 @@ void Spell::Delayed() // only called in DealDamage() if (delayReduce >= 100) return; - delaytime = delaytime * (100 - delayReduce) / 100; + AddPctN(delaytime, -delayReduce); if (int32(m_timer) + delaytime > m_casttime) { @@ -6493,14 +6478,14 @@ void Spell::DelayedChannel() return; //check pushback reduce - int32 delaytime = GetSpellDuration(m_spellInfo) * 25 / 100; // channeling delay is normally 25% of its time per hit + int32 delaytime = CalculatePctN(GetSpellDuration(m_spellInfo), 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, SPELLMOD_NOT_LOSE_CASTING_TIME, delayReduce, this); delayReduce += m_caster->GetTotalAuraModifier(SPELL_AURA_REDUCE_PUSHBACK) - 100; if (delayReduce >= 100) return; - delaytime = delaytime * (100 - delayReduce) / 100; + AddPctN(delaytime, -delayReduce); if (int32(m_timer) <= delaytime) { diff --git a/src/server/game/Spells/SpellEffects.cpp b/src/server/game/Spells/SpellEffects.cpp index 5754d247b0e..8f4bf73c1a3 100755 --- a/src/server/game/Spells/SpellEffects.cpp +++ b/src/server/game/Spells/SpellEffects.cpp @@ -460,14 +460,14 @@ void Spell::SpellDamageSchoolDmg(SpellEffIndex effIndex) { // Bloodthirst if (m_spellInfo->SpellFamilyFlags[1] & 0x400) - damage = uint32(damage * (m_caster->GetTotalAttackPowerValue(BASE_ATTACK)) / 100); + ApplyPctF(damage, m_caster->GetTotalAttackPowerValue(BASE_ATTACK)); // Shield Slam else if (m_spellInfo->SpellFamilyFlags[1] & 0x200 && m_spellInfo->Category == 1209) - damage += m_caster->ApplyEffectModifiers(m_spellInfo,effIndex,int32(m_caster->GetShieldBlockValue())); + damage += int32(m_caster->ApplyEffectModifiers(m_spellInfo, effIndex, float(m_caster->GetShieldBlockValue()))); // Victory Rush else if (m_spellInfo->SpellFamilyFlags[1] & 0x100) { - damage = uint32(damage * m_caster->GetTotalAttackPowerValue(BASE_ATTACK) / 100); + ApplyPctF(damage, m_caster->GetTotalAttackPowerValue(BASE_ATTACK)); m_caster->ModifyAuraState(AURA_STATE_WARRIOR_VICTORY_RUSH, false); } // Shockwave @@ -475,7 +475,7 @@ void Spell::SpellDamageSchoolDmg(SpellEffIndex effIndex) { int32 pct = m_caster->CalculateSpellDamage(unitTarget, m_spellInfo, 2); if (pct > 0) - damage+= int32(m_caster->GetTotalAttackPowerValue(BASE_ATTACK) * pct / 100); + damage += int32(CalculatePctN(m_caster->GetTotalAttackPowerValue(BASE_ATTACK), pct)); break; } break; @@ -521,14 +521,14 @@ void Spell::SpellDamageSchoolDmg(SpellEffIndex effIndex) // found Immolate or Shadowflame if (aura) { - uint32 pdamage = aura->GetAmount() > 0 ? aura->GetAmount() : 0; + uint32 pdamage = uint32(std::max(aura->GetAmount(), 0)); pdamage = m_caster->SpellDamageBonus(unitTarget, aura->GetSpellProto(), pdamage, DOT, aura->GetBase()->GetStackAmount()); uint32 pct_dir = m_caster->CalculateSpellDamage(unitTarget, m_spellInfo, (effIndex + 1)); uint8 baseTotalTicks = uint8(m_caster->CalcSpellDuration(aura->GetSpellProto()) / aura->GetSpellProto()->EffectAmplitude[0]); - damage += pdamage * baseTotalTicks * pct_dir / 100; + damage += int32(CalculatePctU(pdamage * baseTotalTicks, pct_dir)); uint32 pct_dot = m_caster->CalculateSpellDamage(unitTarget, m_spellInfo, (effIndex + 2)) / 3; - m_spellValue->EffectBasePoints[1] = SpellMgr::CalculateSpellEffectBaseAmount(pdamage * baseTotalTicks * pct_dot / 100, m_spellInfo, 1); + m_spellValue->EffectBasePoints[1] = SpellMgr::CalculateSpellEffectBaseAmount(int32(CalculatePctU(pdamage * baseTotalTicks, pct_dot)), m_spellInfo, 1); apply_direct_bonus = false; // Glyph of Conflagrate @@ -542,10 +542,8 @@ void Spell::SpellDamageSchoolDmg(SpellEffIndex effIndex) else if (m_spellInfo->SpellFamilyFlags[1] & 0x400000) { if (m_caster->GetTypeId() == TYPEID_UNIT && m_caster->ToCreature()->isPet()) - { // Get DoTs on target by owner (5% increase by dot) - damage += 5 * unitTarget->GetDoTsByCaster(m_caster->GetOwnerGUID()) / 100; - } + damage += int32(CalculatePctN(unitTarget->GetDoTsByCaster(m_caster->GetOwnerGUID()), 5)); } break; } @@ -557,7 +555,7 @@ void Spell::SpellDamageSchoolDmg(SpellEffIndex effIndex) int32 back_damage = m_caster->SpellDamageBonus(unitTarget, m_spellInfo, (uint32)damage, SPELL_DIRECT_DAMAGE); // Pain and Suffering reduces damage if (AuraEffect * aurEff = m_caster->GetDummyAuraEffect(SPELLFAMILY_PRIEST, 2874, 0)) - back_damage -= aurEff->GetAmount() * back_damage / 100; + AddPctN(back_damage, -aurEff->GetAmount()); if (back_damage < int32(unitTarget->GetHealth())) m_caster->CastCustomSpell(m_caster, 32409, &back_damage, 0, 0, true); @@ -566,7 +564,7 @@ void Spell::SpellDamageSchoolDmg(SpellEffIndex effIndex) else if (m_spellInfo->SpellFamilyFlags[2] & 0x00002000) { // We are in Shadow Form - if (m_caster->m_form == FORM_SHADOW) + if (m_caster->GetShapeshiftForm() == FORM_SHADOW) // We have Improved Mind Blast if (AuraEffect * aurEff = m_caster->GetDummyAuraEffect(SPELLFAMILY_PRIEST,95,0)) // Chance has been successfully rolled @@ -579,10 +577,10 @@ void Spell::SpellDamageSchoolDmg(SpellEffIndex effIndex) // Glyph of Smite if (AuraEffect * aurEff = m_caster->GetAuraEffect(55692, 0)) if (unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_PRIEST, 0x100000, 0, 0, m_caster->GetGUID())) - damage += damage * aurEff->GetAmount() / 100; + AddPctN(damage, aurEff->GetAmount()); } // Improved Mind Blast (Mind Blast in shadow form bonus) - else if (m_caster->m_form == FORM_SHADOW && (m_spellInfo->SpellFamilyFlags[0] & 0x00002000)) + else if (m_caster->GetShapeshiftForm() == FORM_SHADOW && (m_spellInfo->SpellFamilyFlags[0] & 0x00002000)) { Unit::AuraEffectList const& ImprMindBlast = m_caster->GetAuraEffectsByType(SPELL_AURA_ADD_FLAT_MODIFIER); for (Unit::AuraEffectList::const_iterator i = ImprMindBlast.begin(); i != ImprMindBlast.end(); ++i) @@ -610,7 +608,7 @@ void Spell::SpellDamageSchoolDmg(SpellEffIndex effIndex) float multiple = ap / 410 + m_spellInfo->EffectDamageMultiplier[effIndex]; int32 energy = -(m_caster->ModifyPower(POWER_ENERGY, -30)); damage += int32(energy * multiple); - damage += int32(m_caster->ToPlayer()->GetComboPoints() * ap * 7 / 100); + damage += int32(CalculatePctN(m_caster->ToPlayer()->GetComboPoints() * ap, 7)); } // Wrath else if (m_spellInfo->SpellFamilyFlags[0] & 0x00000001) @@ -618,7 +616,7 @@ void Spell::SpellDamageSchoolDmg(SpellEffIndex effIndex) // Improved Insect Swarm if (AuraEffect const * aurEff = m_caster->GetDummyAuraEffect(SPELLFAMILY_DRUID, 1771, 0)) if (unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x00200000, 0, 0)) - damage = int32(damage*(100.0f+aurEff->GetAmount())/100.0f); + AddPctN(damage, aurEff->GetAmount()); } break; } @@ -739,7 +737,7 @@ void Spell::SpellDamageSchoolDmg(SpellEffIndex effIndex) // Shield of Righteousness if (m_spellInfo->SpellFamilyFlags[EFFECT_1] & 0x100000) { - damage += m_caster->GetShieldBlockValue() * SpellMgr::CalculateSpellEffectAmount(m_spellInfo, EFFECT_1) / 100; + damage += CalculatePctN(m_caster->GetShieldBlockValue(), SpellMgr::CalculateSpellEffectAmount(m_spellInfo, EFFECT_1)); break; } break; @@ -1255,7 +1253,7 @@ void Spell::EffectDummy(SpellEffIndex effIndex) // Concussion Blow if (m_spellInfo->SpellFamilyFlags[0] & SPELLFAMILYFLAG_WARRIOR_CONCUSSION_BLOW) { - m_damage+= uint32(damage * m_caster->GetTotalAttackPowerValue(BASE_ATTACK) / 100); + m_damage += CalculatePctF(damage, m_caster->GetTotalAttackPowerValue(BASE_ATTACK)); return; } switch(m_spellInfo->Id) @@ -1289,7 +1287,7 @@ void Spell::EffectDummy(SpellEffIndex effIndex) // Improved Life Tap mod if (AuraEffect const * aurEff = m_caster->GetDummyAuraEffect(SPELLFAMILY_WARLOCK, 208, 0)) - mana = (aurEff->GetAmount() + 100)* mana / 100; + AddPctN(mana, aurEff->GetAmount()); m_caster->CastCustomSpell(unitTarget, 31818, &mana, NULL, NULL, true); @@ -1300,7 +1298,7 @@ void Spell::EffectDummy(SpellEffIndex effIndex) if (manaFeedVal > 0) { - manaFeedVal = manaFeedVal * mana / 100; + ApplyPctN(manaFeedVal, mana); m_caster->CastCustomSpell(m_caster, 32553, &manaFeedVal, NULL, NULL, true, NULL); } } @@ -1333,7 +1331,7 @@ void Spell::EffectDummy(SpellEffIndex effIndex) // Divine Storm if (m_spellInfo->SpellFamilyFlags[1] & SPELLFAMILYFLAG1_PALADIN_DIVINESTORM && effIndex == 1) { - int32 dmg = m_damage * damage / 100; + int32 dmg = CalculatePctN(m_damage, damage); if (!unitTarget) unitTarget = m_caster; m_caster->CastCustomSpell(unitTarget, 54171, &dmg, 0, 0, true); @@ -1383,7 +1381,7 @@ void Spell::EffectDummy(SpellEffIndex effIndex) // Restorative Totems if (Unit *owner = m_caster->GetOwner()) if (AuraEffect *dummy = owner->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, 338, 1)) - damage += damage * dummy->GetAmount() / 100; + AddPctN(damage, dummy->GetAmount()); m_caster->CastCustomSpell(unitTarget, 52042, &damage, 0, 0, true, 0, 0, m_originalCasterGUID); return; @@ -1406,7 +1404,7 @@ void Spell::EffectDummy(SpellEffIndex effIndex) { // Damage is increased by 25% if your off-hand weapon is enchanted with Flametongue. if (m_caster->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_SHAMAN, 0x200000, 0, 0)) - m_damage += m_damage * damage / 100; + AddPctN(m_damage, damage); } return; } @@ -1419,7 +1417,7 @@ void Spell::EffectDummy(SpellEffIndex effIndex) int32 bp = int32(count * m_caster->CountPctFromMaxHealth(int32(m_spellInfo->EffectDamageMultiplier[0]))); // Improved Death Strike if (AuraEffect const * aurEff = m_caster->GetAuraEffect(SPELL_AURA_ADD_PCT_MODIFIER, SPELLFAMILY_DEATHKNIGHT, 2751, 0)) - bp = int32(bp * (m_caster->CalculateSpellDamage(m_caster, aurEff->GetSpellProto(), 2) + 100.0f) / 100.0f); + AddPctN(bp, m_caster->CalculateSpellDamage(m_caster, aurEff->GetSpellProto(), 2)); m_caster->CastCustomSpell(m_caster, 45470, &bp, NULL, NULL, false); return; } @@ -2115,8 +2113,8 @@ void Spell::EffectPowerBurn(SpellEffIndex effIndex) // burn x% of target's mana, up to maximum of 2x% of caster's mana (Mana Burn) if (m_spellInfo->ManaCostPercentage) { - int32 maxDamage = m_caster->GetMaxPower(powerType) * damage * 2 / 100; - damage = unitTarget->GetMaxPower(powerType) * damage / 100; + int32 maxDamage = int32(CalculatePctN(m_caster->GetMaxPower(powerType), damage * 2)); + damage = int32(CalculatePctN(unitTarget->GetMaxPower(powerType), damage)); damage = std::min(damage, maxDamage); } @@ -2224,7 +2222,7 @@ void Spell::SpellDamageHeal(SpellEffIndex /*effIndex*/) for (Unit::AuraEffectList::const_iterator i = Periodic.begin(); i != Periodic.end(); ++i) { if (m_caster->GetGUID() == (*i)->GetCasterGUID()) - addhealth += addhealth * aurEff->GetAmount() / 100; + AddPctN(addhealth, aurEff->GetAmount()); } } } @@ -2530,10 +2528,10 @@ void Spell::EffectEnergize(SpellEffIndex effIndex) case 31930: // Judgements of the Wise case 63375: // Improved Stormstrike case 68082: // Glyph of Seal of Command - damage = damage * unitTarget->GetCreateMana() / 100; + damage = int32(CalculatePctN(unitTarget->GetCreateMana(), damage)); break; case 48542: // Revitalize - damage = damage * unitTarget->GetMaxPower(power) / 100; + damage = int32(CalculatePctN(unitTarget->GetMaxPower(power), damage)); break; default: break; @@ -2616,7 +2614,7 @@ void Spell::EffectEnergizePct(SpellEffIndex effIndex) if (maxPower == 0) return; - uint32 gain = damage * maxPower / 100; + uint32 gain = CalculatePctN(maxPower, damage); m_caster->EnergizeBySpell(unitTarget, m_spellInfo->Id, gain, power); } @@ -3350,7 +3348,7 @@ void Spell::EffectAddHonor(SpellEffIndex /*effIndex*/) // do not allow to add too many honor for player (50 * 21) = 1040 at level 70, or (50 * 31) = 1550 at level 80 if (damage <= 50) { - uint32 honor_reward = Trinity::Honor::hk_honor_at_level(unitTarget->getLevel(), damage); + uint32 honor_reward = Trinity::Honor::hk_honor_at_level(unitTarget->getLevel(), float(damage)); unitTarget->ToPlayer()->RewardHonor(NULL, 1, honor_reward); sLog.outDebug("SpellEffect::AddHonor (spell_id %u) rewards %u honor points (scale) to player: %u", m_spellInfo->Id, honor_reward, unitTarget->ToPlayer()->GetGUIDLow()); } @@ -3938,14 +3936,14 @@ void Spell::SpellDamageWeaponDmg(SpellEffIndex effIndex) // Seal of Command - Increase damage by 36% on every swing if (m_spellInfo->SpellFamilyFlags[0] & 0x2000000) { - totalDamagePercentMod *= 1.36f; //136% damage + totalDamagePercentMod *= 1.36f; // 136% damage } // Seal of Command Unleashed else if (m_spellInfo->Id == 20467) { - spell_bonus += int32(0.08f*m_caster->GetTotalAttackPowerValue(BASE_ATTACK)); - spell_bonus += int32(0.13f*m_caster->SpellBaseDamageBonus(GetSpellSchoolMask(m_spellInfo))); + spell_bonus += int32(0.08f * m_caster->GetTotalAttackPowerValue(BASE_ATTACK)); + spell_bonus += int32(0.13f * m_caster->SpellBaseDamageBonus(GetSpellSchoolMask(m_spellInfo))); } break; } @@ -3963,15 +3961,13 @@ void Spell::SpellDamageWeaponDmg(SpellEffIndex effIndex) if (m_spellInfo->SpellFamilyFlags[1] & 0x400) { if (m_caster->GetTypeId() == TYPEID_PLAYER) - m_caster->ToPlayer()->AddComboPoints(unitTarget,1, this); + m_caster->ToPlayer()->AddComboPoints(unitTarget, 1, this); } // Shred, Maul - Rend and Tear else if (m_spellInfo->SpellFamilyFlags[0] & 0x00008800 && unitTarget->HasAuraState(AURA_STATE_BLEEDING)) { if (AuraEffect const* rendAndTear = m_caster->GetDummyAuraEffect(SPELLFAMILY_DRUID, 2859, 0)) - { - totalDamagePercentMod *= float((rendAndTear->GetAmount() + 100.0f) / 100.0f); - } + AddPctN(totalDamagePercentMod, rendAndTear->GetAmount()); } break; } @@ -3979,7 +3975,7 @@ void Spell::SpellDamageWeaponDmg(SpellEffIndex effIndex) { // Kill Shot - bonus damage from Ranged Attack Power if (m_spellInfo->SpellFamilyFlags[1] & 0x800000) - spell_bonus += int32(0.4f*m_caster->GetTotalAttackPowerValue(RANGED_ATTACK)); + spell_bonus += int32(0.4f * m_caster->GetTotalAttackPowerValue(RANGED_ATTACK)); break; } case SPELLFAMILY_DEATHKNIGHT: @@ -3989,18 +3985,18 @@ void Spell::SpellDamageWeaponDmg(SpellEffIndex effIndex) { // Glyph of Plague Strike if (AuraEffect const * aurEff = m_caster->GetAuraEffect(58657, EFFECT_0)) - totalDamagePercentMod *= (aurEff->GetAmount() + 100.0f) / 100.0f; + AddPctN(totalDamagePercentMod, aurEff->GetAmount()); break; } // Blood Strike if (m_spellInfo->SpellFamilyFlags[EFFECT_0] & 0x400000) { - totalDamagePercentMod *= ((SpellMgr::CalculateSpellEffectAmount(m_spellInfo, EFFECT_2) * unitTarget->GetDiseasesByCaster(m_caster->GetGUID()) / 2.0f) + 100.0f) / 100.0f; + AddPctF(totalDamagePercentMod, SpellMgr::CalculateSpellEffectAmount(m_spellInfo, EFFECT_2) * unitTarget->GetDiseasesByCaster(m_caster->GetGUID()) / 2.0f); // Glyph of Blood Strike if (m_caster->GetAuraEffect(59332, EFFECT_0)) if (unitTarget->HasAuraType(SPELL_AURA_MOD_DECREASE_SPEED)) - totalDamagePercentMod *= (20 + 100.0f) / 100.0f; + AddPctN(totalDamagePercentMod, 20); break; } // Death Strike @@ -4009,7 +4005,7 @@ void Spell::SpellDamageWeaponDmg(SpellEffIndex effIndex) // Glyph of Death Strike if (AuraEffect const * aurEff = m_caster->GetAuraEffect(59336, EFFECT_0)) if (uint32 runic = std::min<uint32>(m_caster->GetPower(POWER_RUNIC_POWER), SpellMgr::CalculateSpellEffectAmount(aurEff->GetSpellProto(), EFFECT_1))) - totalDamagePercentMod *= (runic + 100.0f) / 100.0f; + AddPctN(totalDamagePercentMod, runic); break; } // Obliterate (12.5% more damage per disease) @@ -4022,19 +4018,19 @@ void Spell::SpellDamageWeaponDmg(SpellEffIndex effIndex) if (roll_chance_i(aurEff->GetAmount())) consumeDiseases = false; - totalDamagePercentMod *= ((SpellMgr::CalculateSpellEffectAmount(m_spellInfo, EFFECT_2) * unitTarget->GetDiseasesByCaster(m_caster->GetGUID(), consumeDiseases) / 2.0f) + 100.0f) / 100.0f; + AddPctF(totalDamagePercentMod, SpellMgr::CalculateSpellEffectAmount(m_spellInfo, EFFECT_2) * unitTarget->GetDiseasesByCaster(m_caster->GetGUID(), consumeDiseases) / 2.0f); break; } // Blood-Caked Strike - Blood-Caked Blade if (m_spellInfo->SpellIconID == 1736) { - totalDamagePercentMod *= ((unitTarget->GetDiseasesByCaster(m_caster->GetGUID()) * 12.5f) + 100.0f) / 100.0f; + AddPctF(totalDamagePercentMod, unitTarget->GetDiseasesByCaster(m_caster->GetGUID()) * 12.5f); break; } // Heart Strike if (m_spellInfo->SpellFamilyFlags[EFFECT_0] & 0x1000000) { - totalDamagePercentMod *= ((SpellMgr::CalculateSpellEffectAmount(m_spellInfo, EFFECT_2) * unitTarget->GetDiseasesByCaster(m_caster->GetGUID())) + 100.0f) / 100.0f; + AddPctN(totalDamagePercentMod, SpellMgr::CalculateSpellEffectAmount(m_spellInfo, EFFECT_2) * unitTarget->GetDiseasesByCaster(m_caster->GetGUID())); break; } break; @@ -4042,10 +4038,10 @@ void Spell::SpellDamageWeaponDmg(SpellEffIndex effIndex) } bool normalized = false; - float weaponDamagePercentMod = 1.0; + float weaponDamagePercentMod = 1.0f; for (int j = 0; j < MAX_SPELL_EFFECTS; ++j) { - switch(m_spellInfo->Effect[j]) + switch (m_spellInfo->Effect[j]) { case SPELL_EFFECT_WEAPON_DAMAGE: case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL: @@ -4056,7 +4052,7 @@ void Spell::SpellDamageWeaponDmg(SpellEffIndex effIndex) normalized = true; break; case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE: - weaponDamagePercentMod *= float(CalculateDamage(j,unitTarget)) / 100.0f; + ApplyPctN(weaponDamagePercentMod, CalculateDamage(j, unitTarget)); break; default: break; // not weapon damage effect, just skip @@ -4067,7 +4063,7 @@ void Spell::SpellDamageWeaponDmg(SpellEffIndex effIndex) if (fixed_bonus || spell_bonus) { UnitMods unitMod; - switch(m_attackType) + switch (m_attackType) { default: case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break; @@ -4113,11 +4109,11 @@ void Spell::SpellDamageWeaponDmg(SpellEffIndex effIndex) weaponDamage = int32(weaponDamage * totalDamagePercentMod); // prevent negative damage - uint32 eff_damage = uint32(weaponDamage > 0 ? weaponDamage : 0); + uint32 eff_damage(std::max(weaponDamage, 0)); // Add melee damage bonuses (also check for negative) m_caster->MeleeDamageBonus(unitTarget, &eff_damage, m_attackType, m_spellInfo); - m_damage+= eff_damage; + m_damage += eff_damage; } void Spell::EffectThreat(SpellEffIndex /*effIndex*/) @@ -4154,7 +4150,7 @@ void Spell::EffectHealMaxHealth(SpellEffIndex /*effIndex*/) addhealth = unitTarget->GetMaxHealth() - unitTarget->GetHealth(); if (m_originalCaster) - m_healing += m_originalCaster->SpellHealingBonus(unitTarget,m_spellInfo, addhealth, HEAL); + m_healing += m_originalCaster->SpellHealingBonus(unitTarget, m_spellInfo, addhealth, HEAL); } void Spell::EffectInterruptCast(SpellEffIndex effIndex) @@ -5811,7 +5807,7 @@ void Spell::EffectResurrect(SpellEffIndex effIndex) return; uint32 health = pTarget->CountPctFromMaxHealth(damage); - uint32 mana = pTarget->GetMaxPower(POWER_MANA) * damage / 100; + uint32 mana = CalculatePctN(pTarget->GetMaxPower(POWER_MANA), damage); ExecuteLogEffectResurrect(effIndex, pTarget); @@ -5931,7 +5927,7 @@ void Spell::EffectSelfResurrect(SpellEffIndex effIndex) { health = unitTarget->CountPctFromMaxHealth(damage); if (unitTarget->GetMaxPower(POWER_MANA) > 0) - mana = uint32(damage/100.0f*unitTarget->GetMaxPower(POWER_MANA)); + mana = CalculatePctN(unitTarget->GetMaxPower(POWER_MANA), damage); } Player *plr = unitTarget->ToPlayer(); @@ -6206,13 +6202,12 @@ void Spell::EffectDestroyAllTotems(SpellEffIndex /*effIndex*/) if (spellInfo) { mana += spellInfo->manaCost; - mana += spellInfo->ManaCostPercentage * m_caster->GetCreateMana() / 100; + mana += int32(CalculatePctU(m_caster->GetCreateMana(), spellInfo->ManaCostPercentage)); } totem->ToTotem()->UnSummon(); } } - mana = mana * damage / 100; - + ApplyPctN(mana, damage); if (mana) m_caster->CastCustomSpell(m_caster, 39104, &mana, NULL, NULL, true); } @@ -6253,7 +6248,7 @@ void Spell::EffectDurabilityDamagePCT(SpellEffIndex effIndex) // Possibly its mean -1 all player equipped items and -2 all items if (slot < 0) { - unitTarget->ToPlayer()->DurabilityLossAll(double(damage)/100.0f, (slot < -1)); + unitTarget->ToPlayer()->DurabilityLossAll(float(damage) / 100.0f, (slot < -1)); return; } @@ -6265,7 +6260,7 @@ void Spell::EffectDurabilityDamagePCT(SpellEffIndex effIndex) return; if (Item* item = unitTarget->ToPlayer()->GetItemByPos(INVENTORY_SLOT_BAG_0, slot)) - unitTarget->ToPlayer()->DurabilityLoss(item, double(damage)/100.0f); + unitTarget->ToPlayer()->DurabilityLoss(item, float(damage) / 100.0f); } void Spell::EffectModifyThreatPercent(SpellEffIndex /*effIndex*/) diff --git a/src/server/game/Spells/SpellMgr.cpp b/src/server/game/Spells/SpellMgr.cpp index 6c1170463dd..f7b0d92a7e2 100755 --- a/src/server/game/Spells/SpellMgr.cpp +++ b/src/server/game/Spells/SpellMgr.cpp @@ -392,16 +392,16 @@ uint32 CalculatePowerCost(SpellEntry const * spellInfo, Unit const * caster, Spe { // health as power used case POWER_HEALTH: - powerCost += spellInfo->ManaCostPercentage * caster->GetCreateHealth() / 100; + powerCost += int32(CalculatePctU(caster->GetCreateHealth(), spellInfo->ManaCostPercentage)); break; case POWER_MANA: - powerCost += spellInfo->ManaCostPercentage * caster->GetCreateMana() / 100; + powerCost += int32(CalculatePctU(caster->GetCreateMana(), spellInfo->ManaCostPercentage)); break; case POWER_RAGE: case POWER_FOCUS: case POWER_ENERGY: case POWER_HAPPINESS: - powerCost += spellInfo->ManaCostPercentage * caster->GetMaxPower(Powers(spellInfo->powerType)) / 100; + powerCost += int32(CalculatePctU(caster->GetMaxPower(Powers(spellInfo->powerType)), spellInfo->ManaCostPercentage)); break; case POWER_RUNE: case POWER_RUNIC_POWER: @@ -1862,7 +1862,7 @@ int32 SpellMgr::CalculateSpellEffectAmount(SpellEntry const * spellEntry, uint8 break; } - int32 value = basePoints; + float value = float(basePoints); // random damage if (caster) @@ -1871,7 +1871,7 @@ int32 SpellMgr::CalculateSpellEffectAmount(SpellEntry const * spellEntry, uint8 if (caster->m_movedPlayer) if (uint8 comboPoints = caster->m_movedPlayer->GetComboPoints()) if (float comboDamage = spellEntry->EffectPointsPerComboPoint[effIndex]) - value += int32(comboDamage * comboPoints); + value += comboDamage * comboPoints; value = caster->ApplyEffectModifiers(spellEntry, effIndex, value); @@ -1884,11 +1884,11 @@ int32 SpellMgr::CalculateSpellEffectAmount(SpellEntry const * spellEntry, uint8 spellEntry->EffectApplyAuraName[effIndex] != SPELL_AURA_MOD_INCREASE_SPEED && spellEntry->EffectApplyAuraName[effIndex] != SPELL_AURA_MOD_DECREASE_SPEED) //there are many more: slow speed, -healing pct - value = int32(value*0.25f*exp(caster->getLevel()*(70-spellEntry->spellLevel)/1000.0f)); + value *= 0.25f * exp(caster->getLevel() * (70 - spellEntry->spellLevel) / 1000.0f); //value = int32(value * (int32)getLevel() / (int32)(spellProto->spellLevel ? spellProto->spellLevel : 1)); } - return value; + return int32(value); } int32 SpellMgr::CalculateSpellEffectBaseAmount(int32 value, SpellEntry const * spellEntry, uint8 effIndex) @@ -2871,7 +2871,7 @@ DiminishingGroup GetDiminishingReturnsGroupForSpell(SpellEntry const* spellproto else if (spellproto->SpellFamilyFlags[1] & 0x8) return DIMINISHING_FEAR_BLIND; // Seduction - else if (spellproto->SpellFamilyFlags[0] & 0x40000000) + else if (spellproto->SpellFamilyFlags[1] & 0x10000000) return DIMINISHING_FEAR_BLIND; break; } @@ -3157,6 +3157,9 @@ bool SpellMgr::CanAurasStack(SpellEntry const *spellInfo_1, SpellEntry const *sp case SPELL_AURA_OBS_MOD_POWER: case SPELL_AURA_OBS_MOD_HEALTH: case SPELL_AURA_PERIODIC_TRIGGER_SPELL_WITH_VALUE: + // periodic auras which target areas are not allowed to stack this way (replenishment for example) + if (IsAreaOfEffectSpellEffect(spellInfo_1, i) || IsAreaOfEffectSpellEffect(spellInfo_2, i)) + break; return true; default: break; @@ -3885,11 +3888,6 @@ void SpellMgr::LoadSpellCustomAttr() spellInfo->EffectImplicitTargetA[0] = TARGET_DST_DB; count++; break; - // Deathbringer Saurfang achievement (must be cast on players, cannot do that with ENTRY target) - case 72928: - spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_AREA_ENEMY_SRC; - count++; - break; case 63675: // Improved Devouring Plague spellInfo->AttributesEx3 |= SPELL_ATTR_EX3_NO_DONE_BONUS; count++; @@ -3951,6 +3949,12 @@ void SpellMgr::LoadSpellCustomAttr() spellInfo->EffectImplicitTargetB[0] = TARGET_UNIT_TARGET_ENEMY; count++; break; + case 71518: // Unholy Infusion Quest Credit + case 72934: // Blood Infusion Quest Credit + case 72289: // Frost Infusion Quest Credit + spellInfo->EffectRadiusIndex[0] = 28; // another missing radius + count++; + break; case 71708: // Empowered Flare case 72785: // Empowered Flare case 72786: // Empowered Flare diff --git a/src/server/game/Spells/SpellMgr.h b/src/server/game/Spells/SpellMgr.h index df130205943..e16dd2b1c33 100755 --- a/src/server/game/Spells/SpellMgr.h +++ b/src/server/game/Spells/SpellMgr.h @@ -403,6 +403,13 @@ inline bool IsAreaOfEffectSpell(SpellEntry const *spellInfo) return false; } +inline bool IsAreaOfEffectSpellEffect(SpellEntry const *spellInfo, uint8 effIndex) +{ + if (IsAreaEffectTarget[spellInfo->EffectImplicitTargetA[effIndex]] || IsAreaEffectTarget[spellInfo->EffectImplicitTargetB[effIndex]]) + return true; + return false; +} + inline bool IsFarUnitTargetEffect(uint32 effect) { return (effect == SPELL_EFFECT_SUMMON_PLAYER); diff --git a/src/server/game/Spells/SpellScript.cpp b/src/server/game/Spells/SpellScript.cpp index af884e6ebcc..baaeaa3c1fc 100755 --- a/src/server/game/Spells/SpellScript.cpp +++ b/src/server/game/Spells/SpellScript.cpp @@ -567,6 +567,8 @@ bool AuraScript::_IsDefaultActionPrevented() case AURA_SCRIPT_HOOK_EFFECT_PERIODIC: return m_defaultActionPrevented; default: + //TOFIX: probably one hook is called from another hook + //ASSERT(false && "m_defaultActionPrevented has incorrect value, or AuraScript::_IsDefaultActionPrevented is called in a wrong place"); return false; } } diff --git a/src/server/game/Spells/SpellScript.h b/src/server/game/Spells/SpellScript.h index 09ef73c37c0..0a06d5ab091 100755 --- a/src/server/game/Spells/SpellScript.h +++ b/src/server/game/Spells/SpellScript.h @@ -444,7 +444,7 @@ class AuraScript : public _SpellScript Unit* GetCaster() const; // returns object on which aura was casted, target for non-area auras, area aura source for area auras WorldObject * GetOwner() const; - // returns owner if it's unit, NULL otherwise + // returns owner if it's unit or unit derived object, NULL otherwise (only for persistent area auras NULL is returned) Unit * GetUnitOwner() const; // returns owner if it's dynobj, NULL otherwise DynamicObject * GetDynobjOwner() const; diff --git a/src/server/game/Tickets/TicketMgr.h b/src/server/game/Tickets/TicketMgr.h index 2dc99d65e0d..b6b6513eef0 100755 --- a/src/server/game/Tickets/TicketMgr.h +++ b/src/server/game/Tickets/TicketMgr.h @@ -132,7 +132,7 @@ public: uint64 GenerateGMTicketId(); bool GetStatus() const { return status; } void SetStatus(bool newStatus) { status = newStatus; } - uint64 GetOpenTicketCount() { return m_openTickets; } + uint64 GetOpenTicketCount() const { return m_openTickets; } uint64 GetNextSurveyID() { return ++m_GMSurveyID; } void Initialize() @@ -149,7 +149,7 @@ public: return NULL; } - time_t GetLastChange() { return lastChange; } + time_t GetLastChange() const { return lastChange; } void UpdateLastChange() { lastChange = time(NULL); } GmTicketList m_GMTicketList; diff --git a/src/server/game/Tools/PlayerDump.cpp b/src/server/game/Tools/PlayerDump.cpp index dd6a7bb5498..8f0d375596d 100755 --- a/src/server/game/Tools/PlayerDump.cpp +++ b/src/server/game/Tools/PlayerDump.cpp @@ -595,7 +595,8 @@ DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account, s { //store a map of old pet id to new inserted pet id for use by type 5 tables snprintf(currpetid, 20, "%s", getnth(line, 1).c_str()); - if (strlen(lastpetid) == 0) snprintf(lastpetid, 20, "%s", currpetid); + if (*lastpetid == '\0') + snprintf(lastpetid, 20, "%s", currpetid); if (strcmp(lastpetid,currpetid) != 0) { snprintf(newpetid, 20, "%d", sObjectMgr.GeneratePetNumber()); diff --git a/src/server/game/World/World.cpp b/src/server/game/World/World.cpp index 3a73fa295f6..f7466f6c092 100755 --- a/src/server/game/World/World.cpp +++ b/src/server/game/World/World.cpp @@ -221,9 +221,9 @@ World::AddSession_(WorldSession* s) ///- kick already loaded player with same account (if any) and remove session ///- if player is in loading and want to load again, return - if (!RemoveSession (s->GetAccountId ())) + if (!RemoveSession (s->GetAccountId())) { - s->KickPlayer (); + s->KickPlayer(); delete s; // session not added yet in session list, so not listed in queue return; } @@ -234,7 +234,7 @@ World::AddSession_(WorldSession* s) // if session already exist, prepare to it deleting at next world update // NOTE - KickPlayer() should be called on "old" in RemoveSession() { - SessionMap::const_iterator old = m_sessions.find(s->GetAccountId ()); + SessionMap::const_iterator old = m_sessions.find(s->GetAccountId()); if (old != m_sessions.end()) { @@ -246,22 +246,22 @@ World::AddSession_(WorldSession* s) } } - m_sessions[s->GetAccountId ()] = s; + m_sessions[s->GetAccountId()] = s; - uint32 Sessions = GetActiveAndQueuedSessionCount (); - uint32 pLimit = GetPlayerAmountLimit (); - uint32 QueueSize = GetQueueSize (); //number of players in the queue + uint32 Sessions = GetActiveAndQueuedSessionCount(); + uint32 pLimit = GetPlayerAmountLimit(); + uint32 QueueSize = GetQueuedSessionCount(); //number of players in the queue //so we don't count the user trying to //login as a session and queue the socket that we are using if (decrease_session) --Sessions; - if (pLimit > 0 && Sessions >= pLimit && s->GetSecurity () == SEC_PLAYER && !HasRecentlyDisconnected(s)) + if (pLimit > 0 && Sessions >= pLimit && s->GetSecurity() == SEC_PLAYER && !HasRecentlyDisconnected(s)) { AddQueuedPlayer (s); - UpdateMaxSessionCounters (); - sLog.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s->GetAccountId (), ++QueueSize); + UpdateMaxSessionCounters(); + sLog.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s->GetAccountId(), ++QueueSize); return; } @@ -273,7 +273,7 @@ World::AddSession_(WorldSession* s) s->SendTutorialsData(); - UpdateMaxSessionCounters (); + UpdateMaxSessionCounters(); // Updates the population if (pLimit > 0) @@ -1185,7 +1185,7 @@ void World::LoadConfigSettings(bool reload) m_int_configs[CONFIG_AUTOBROADCAST_INTERVAL] = sConfig.GetIntDefault("AutoBroadcast.Timer", 60000); // MySQL ping time interval - m_int_configs[CONFIG_DB_PING_INTERVAL] = sConfig.GetIntDefault("MaxPingTime", 1800); + m_int_configs[CONFIG_DB_PING_INTERVAL] = sConfig.GetIntDefault("MaxPingTime", 30); sScriptMgr.OnConfigLoad(reload); } @@ -1650,7 +1650,7 @@ void World::SetInitialWorldSettings() m_timers[WUPDATE_AUTOBROADCAST].SetInterval(getIntConfig(CONFIG_AUTOBROADCAST_INTERVAL)); m_timers[WUPDATE_DELETECHARS].SetInterval(DAY*IN_MILLISECONDS); // check for chars to delete every day - m_timers[WUPDATE_PINGDB].SetInterval(getIntConfig(CONFIG_DB_PING_INTERVAL)*IN_MILLISECONDS); // Mysql ping time in seconds + m_timers[WUPDATE_PINGDB].SetInterval(getIntConfig(CONFIG_DB_PING_INTERVAL)*MINUTE*IN_MILLISECONDS); // Mysql ping time in minutes //to set mailtimer to return mails every day between 4 and 5 am //mailtimer is increased when updating auctions diff --git a/src/server/game/World/World.h b/src/server/game/World/World.h index 750c7dc7e4a..02c1dbed570 100755 --- a/src/server/game/World/World.h +++ b/src/server/game/World/World.h @@ -572,7 +572,6 @@ class World bool RemoveQueuedPlayer(WorldSession* session); int32 GetQueuePos(WorldSession*); bool HasRecentlyDisconnected(WorldSession*); - uint32 GetQueueSize() const { return m_QueuedPlayer.size(); } /// \todo Actions on m_allowMovement still to be implemented /// Is movement allowed? @@ -725,8 +724,8 @@ class World //used World DB version void LoadDBVersion(); - char const* GetDBVersion() { return m_DBVersion.c_str(); } - char const* GetCreatureEventAIVersion() { return m_CreatureEventAIVersion.c_str(); } + char const* GetDBVersion() const { return m_DBVersion.c_str(); } + char const* GetCreatureEventAIVersion() const { return m_CreatureEventAIVersion.c_str(); } void RecordTimeDiff(const char * text, ...); @@ -736,7 +735,7 @@ class World void ProcessStartEvent(); void ProcessStopEvent(); - bool GetEventKill() { return isEventKillStart; } + bool GetEventKill() const { return isEventKillStart; } bool isEventKillStart; protected: diff --git a/src/server/scripts/EasternKingdoms/BlackrockDepths/instance_blackrock_depths.cpp b/src/server/scripts/EasternKingdoms/BlackrockDepths/instance_blackrock_depths.cpp index 54578462b5e..bbd8be5e8d2 100644 --- a/src/server/scripts/EasternKingdoms/BlackrockDepths/instance_blackrock_depths.cpp +++ b/src/server/scripts/EasternKingdoms/BlackrockDepths/instance_blackrock_depths.cpp @@ -157,58 +157,58 @@ public: TombBossGUIDs[i] = 0; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case NPC_EMPEROR: EmperorGUID = pCreature->GetGUID(); break; - case NPC_PHALANX: PhalanxGUID = pCreature->GetGUID(); break; - case NPC_DOOMREL: TombBossGUIDs[0] = pCreature->GetGUID(); break; - case NPC_DOPEREL: TombBossGUIDs[1] = pCreature->GetGUID(); break; - case NPC_HATEREL: TombBossGUIDs[2] = pCreature->GetGUID(); break; - case NPC_VILEREL: TombBossGUIDs[3] = pCreature->GetGUID(); break; - case NPC_SEETHREL: TombBossGUIDs[4] = pCreature->GetGUID(); break; - case NPC_GLOOMREL: TombBossGUIDs[5] = pCreature->GetGUID(); break; - case NPC_ANGERREL: TombBossGUIDs[6] = pCreature->GetGUID(); break; + case NPC_EMPEROR: EmperorGUID = creature->GetGUID(); break; + case NPC_PHALANX: PhalanxGUID = 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 = pCreature->GetGUID(); - if (!pCreature->isAlive()) + MagmusGUID = creature->GetGUID(); + if (!creature->isAlive()) HandleGameObject(GetData64(DATA_THRONE_DOOR), true); // if Magmus is dead open door to last boss break; } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { - case GO_ARENA1: GoArena1GUID = pGo->GetGUID(); break; - case GO_ARENA2: GoArena2GUID = pGo->GetGUID(); break; - case GO_ARENA3: GoArena3GUID = pGo->GetGUID(); break; - case GO_ARENA4: GoArena4GUID = pGo->GetGUID(); break; - case GO_SHADOW_LOCK: GoShadowLockGUID = pGo->GetGUID(); break; - case GO_SHADOW_MECHANISM: GoShadowMechGUID = pGo->GetGUID(); break; - case GO_SHADOW_GIANT_DOOR: GoShadowGiantGUID = pGo->GetGUID(); break; - case GO_SHADOW_DUMMY: GoShadowDummyGUID = pGo->GetGUID(); break; - case GO_BAR_KEG_SHOT: GoBarKegGUID = pGo->GetGUID(); break; - case GO_BAR_KEG_TRAP: GoBarKegTrapGUID = pGo->GetGUID(); break; - case GO_BAR_DOOR: GoBarDoorGUID = pGo->GetGUID(); break; - case GO_TOMB_ENTER: GoTombEnterGUID = pGo->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 = pGo->GetGUID(); + GoTombExitGUID = go->GetGUID(); if (GhostKillCount >= 7) - HandleGameObject(0, true, pGo); + HandleGameObject(0, true, go); else - HandleGameObject(0, false, pGo); + HandleGameObject(0, false, go); break; - case GO_LYCEUM: GoLyceumGUID = pGo->GetGUID(); break; - case GO_SF_S: GoSFSGUID = pGo->GetGUID(); break; - case GO_SF_N: GoSFNGUID = pGo->GetGUID(); break; - case GO_GOLEM_ROOM_N: GoGolemNGUID = pGo->GetGUID(); break; - case GO_GOLEM_ROOM_S: GoGolemSGUID = pGo->GetGUID(); break; - case GO_THRONE_ROOM: GoThroneGUID = pGo->GetGUID(); break; - case GO_CHEST_SEVEN: GoChestGUID = pGo->GetGUID(); break; - case GO_SPECTRAL_CHALICE: GoSpectralChaliceGUID = pGo->GetGUID(); 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; } } diff --git a/src/server/scripts/EasternKingdoms/Deadmines/instance_deadmines.cpp b/src/server/scripts/EasternKingdoms/Deadmines/instance_deadmines.cpp index 5bf7012f897..d1130059247 100644 --- a/src/server/scripts/EasternKingdoms/Deadmines/instance_deadmines.cpp +++ b/src/server/scripts/EasternKingdoms/Deadmines/instance_deadmines.cpp @@ -87,7 +87,7 @@ class instance_deadmines : public InstanceMapScript if (!IronCladDoorGUID || !DefiasCannonGUID || !DoorLeverGUID) return; - GameObject *pIronCladDoor = instance->GetGameObject(IronCladDoorGUID); + GameObject* pIronCladDoor = instance->GetGameObject(IronCladDoorGUID); if (!pIronCladDoor) return; @@ -126,11 +126,11 @@ class instance_deadmines : public InstanceMapScript void SummonCreatures() { - if (GameObject *pIronCladDoor = instance->GetGameObject(IronCladDoorGUID)) + if (GameObject* pIronCladDoor = instance->GetGameObject(IronCladDoorGUID)) { - Creature *DefiasPirate1 = pIronCladDoor->SummonCreature(657,pIronCladDoor->GetPositionX() - 2,pIronCladDoor->GetPositionY()-7,pIronCladDoor->GetPositionZ(), 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 3000); - Creature *DefiasPirate2 = pIronCladDoor->SummonCreature(657,pIronCladDoor->GetPositionX() + 3,pIronCladDoor->GetPositionY()-6,pIronCladDoor->GetPositionZ(), 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 3000); - Creature *DefiasCompanion = pIronCladDoor->SummonCreature(3450,pIronCladDoor->GetPositionX() + 2,pIronCladDoor->GetPositionY()-6,pIronCladDoor->GetPositionZ(), 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 3000); + Creature* DefiasPirate1 = pIronCladDoor->SummonCreature(657,pIronCladDoor->GetPositionX() - 2,pIronCladDoor->GetPositionY()-7,pIronCladDoor->GetPositionZ(), 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 3000); + Creature* DefiasPirate2 = pIronCladDoor->SummonCreature(657,pIronCladDoor->GetPositionX() + 3,pIronCladDoor->GetPositionY()-6,pIronCladDoor->GetPositionZ(), 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 3000); + Creature* DefiasCompanion = pIronCladDoor->SummonCreature(3450,pIronCladDoor->GetPositionX() + 2,pIronCladDoor->GetPositionY()-6,pIronCladDoor->GetPositionZ(), 0, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 3000); DefiasPirate1GUID = DefiasPirate1->GetGUID(); DefiasPirate2GUID = DefiasPirate2->GetGUID(); @@ -143,9 +143,9 @@ class instance_deadmines : public InstanceMapScript if (!DefiasPirate1GUID || !DefiasPirate2GUID || !DefiasCompanionGUID) return; - Creature *pDefiasPirate1 = instance->GetCreature(DefiasPirate1GUID); - Creature *pDefiasPirate2 = instance->GetCreature(DefiasPirate2GUID); - Creature *pDefiasCompanion = instance->GetCreature(DefiasCompanionGUID); + Creature* pDefiasPirate1 = instance->GetCreature(DefiasPirate1GUID); + Creature* pDefiasPirate2 = instance->GetCreature(DefiasPirate2GUID); + Creature* pDefiasCompanion = instance->GetCreature(DefiasCompanionGUID); if (!pDefiasPirate1 || !pDefiasPirate2 || !pDefiasCompanion) return; @@ -154,15 +154,15 @@ class instance_deadmines : public InstanceMapScript MoveCreatureInside(pDefiasCompanion); } - void MoveCreatureInside(Creature* pCreature) + void MoveCreatureInside(Creature* creature) { - pCreature->RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING); - pCreature->GetMotionMaster()->MovePoint(0, -102.7f,-655.9f, pCreature->GetPositionZ()); + creature->RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING); + creature->GetMotionMaster()->MovePoint(0, -102.7f,-655.9f, creature->GetPositionZ()); } void ShootCannon() { - if (GameObject *pDefiasCannon = instance->GetGameObject(DefiasCannonGUID)) + if (GameObject* pDefiasCannon = instance->GetGameObject(DefiasCannonGUID)) { pDefiasCannon->SetGoState(GO_STATE_ACTIVE); DoPlaySound(pDefiasCannon, SOUND_CANNONFIRE); @@ -171,7 +171,7 @@ class instance_deadmines : public InstanceMapScript void BlastOutDoor() { - if (GameObject *pIronCladDoor = instance->GetGameObject(IronCladDoorGUID)) + if (GameObject* pIronCladDoor = instance->GetGameObject(IronCladDoorGUID)) { pIronCladDoor->SetGoState(GO_STATE_ACTIVE_ALTERNATIVE); DoPlaySound(pIronCladDoor, SOUND_DESTROYDOOR); @@ -180,19 +180,19 @@ class instance_deadmines : public InstanceMapScript void LeverStucked() { - if (GameObject *pDoorLever = instance->GetGameObject(DoorLeverGUID)) + if (GameObject* pDoorLever = instance->GetGameObject(DoorLeverGUID)) pDoorLever->SetUInt32Value(GAMEOBJECT_FLAGS, 4); } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { - case GO_FACTORY_DOOR: FactoryDoorGUID = pGo->GetGUID(); break; - case GO_IRONCLAD_DOOR: IronCladDoorGUID = pGo->GetGUID(); break; - case GO_DEFIAS_CANNON: DefiasCannonGUID = pGo->GetGUID(); break; - case GO_DOOR_LEVER: DoorLeverGUID = pGo->GetGUID(); break; - case GO_MR_SMITE_CHEST: uiSmiteChestGUID = pGo->GetGUID(); break; + case GO_FACTORY_DOOR: FactoryDoorGUID = go->GetGUID(); break; + case GO_IRONCLAD_DOOR: IronCladDoorGUID = go->GetGUID(); break; + case GO_DEFIAS_CANNON: DefiasCannonGUID = go->GetGUID(); break; + case GO_DOOR_LEVER: DoorLeverGUID = go->GetGUID(); break; + case GO_MR_SMITE_CHEST: uiSmiteChestGUID = go->GetGUID(); break; } } @@ -206,8 +206,8 @@ class instance_deadmines : public InstanceMapScript break; case EVENT_RHAHKZOR: if (data == DONE) - if (GameObject* pGo = instance->GetGameObject(FactoryDoorGUID)) - pGo->SetGoState(GO_STATE_ACTIVE); + if (GameObject* go = instance->GetGameObject(FactoryDoorGUID)) + go->SetGoState(GO_STATE_ACTIVE); break; } } diff --git a/src/server/scripts/EasternKingdoms/Gnomeregan/instance_gnomeregan.cpp b/src/server/scripts/EasternKingdoms/Gnomeregan/instance_gnomeregan.cpp index 50f62664c15..b0f30078445 100644 --- a/src/server/scripts/EasternKingdoms/Gnomeregan/instance_gnomeregan.cpp +++ b/src/server/scripts/EasternKingdoms/Gnomeregan/instance_gnomeregan.cpp @@ -76,27 +76,27 @@ public: OUT_LOAD_INST_DATA_COMPLETE; } - void OnCreatureCreate(Creature* pCreature, bool /*bAdd*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case NPC_BLASTMASTER_EMI_SHORTFUSE: uiBastmasterEmiShortfuseGUID = pCreature->GetGUID(); break; + case NPC_BLASTMASTER_EMI_SHORTFUSE: uiBastmasterEmiShortfuseGUID = creature->GetGUID(); break; } } - void OnGameObjectCreate(GameObject* pGo, bool /*bAdd*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case GO_CAVE_IN_LEFT: - uiCaveInLeftGUID = pGo->GetGUID(); + uiCaveInLeftGUID = go->GetGUID(); if (m_auiEncounter[0] == DONE || m_auiEncounter[0] == NOT_STARTED) - HandleGameObject(NULL,false,pGo); + HandleGameObject(NULL,false,go); break; case GO_CAVE_IN_RIGHT: - uiCaveInRightGUID = pGo->GetGUID(); + uiCaveInRightGUID = go->GetGUID(); if (m_auiEncounter[0] == DONE || m_auiEncounter[0] == NOT_STARTED) - HandleGameObject(NULL,false,pGo); + HandleGameObject(NULL,false,go); break; } } diff --git a/src/server/scripts/EasternKingdoms/Karazhan/instance_karazhan.cpp b/src/server/scripts/EasternKingdoms/Karazhan/instance_karazhan.cpp index 3e8038a465b..71673f9d509 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/instance_karazhan.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/instance_karazhan.cpp @@ -116,13 +116,13 @@ public: return false; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch (pCreature->GetEntry()) + switch (creature->GetEntry()) { - case 17229: m_uiKilrekGUID = pCreature->GetGUID(); break; - case 15688: m_uiTerestianGUID = pCreature->GetGUID(); break; - case 15687: m_uiMoroesGUID = pCreature->GetGUID(); break; + case 17229: m_uiKilrekGUID = creature->GetGUID(); break; + case 15688: m_uiTerestianGUID = creature->GetGUID(); break; + case 15687: m_uiMoroesGUID = creature->GetGUID(); break; } } @@ -185,36 +185,36 @@ public: } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { - case 183932: m_uiCurtainGUID = pGo->GetGUID(); break; + case 183932: m_uiCurtainGUID = go->GetGUID(); break; case 184278: - m_uiStageDoorLeftGUID = pGo->GetGUID(); + m_uiStageDoorLeftGUID = go->GetGUID(); if (m_auiEncounter[4] == DONE) - pGo->SetGoState(GO_STATE_ACTIVE); + go->SetGoState(GO_STATE_ACTIVE); break; case 184279: - m_uiStageDoorRightGUID = pGo->GetGUID(); + m_uiStageDoorRightGUID = go->GetGUID(); if (m_auiEncounter[4] == DONE) - pGo->SetGoState(GO_STATE_ACTIVE); + go->SetGoState(GO_STATE_ACTIVE); break; - case 184517: m_uiLibraryDoor = pGo->GetGUID(); break; - case 185521: m_uiMassiveDoor = pGo->GetGUID(); break; - case 184276: m_uiGamesmansDoor = pGo->GetGUID(); break; - case 184277: m_uiGamesmansExitDoor = pGo->GetGUID(); break; - case 185134: m_uiNetherspaceDoor = pGo->GetGUID(); break; - case 184274: MastersTerraceDoor[0] = pGo->GetGUID(); break; - case 184280: MastersTerraceDoor[1] = pGo->GetGUID(); break; + case 184517: m_uiLibraryDoor = go->GetGUID(); break; + case 185521: m_uiMassiveDoor = go->GetGUID(); break; + case 184276: m_uiGamesmansDoor = go->GetGUID(); break; + case 184277: m_uiGamesmansExitDoor = go->GetGUID(); break; + case 185134: m_uiNetherspaceDoor = go->GetGUID(); break; + case 184274: MastersTerraceDoor[0] = go->GetGUID(); break; + case 184280: MastersTerraceDoor[1] = go->GetGUID(); break; case 184275: - m_uiSideEntranceDoor = pGo->GetGUID(); + m_uiSideEntranceDoor = go->GetGUID(); if (m_auiEncounter[4] == DONE) - pGo->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED); + go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED); else - pGo->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED); + go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_LOCKED); break; - case 185119: DustCoveredChest = pGo->GetGUID(); break; + case 185119: DustCoveredChest = go->GetGUID(); break; } switch(m_uiOperaEvent) diff --git a/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_priestess_delrissa.cpp b/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_priestess_delrissa.cpp index 74462736992..e633c748146 100644 --- a/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_priestess_delrissa.cpp +++ b/src/server/scripts/EasternKingdoms/MagistersTerrace/boss_priestess_delrissa.cpp @@ -299,14 +299,11 @@ public: if (DispelTimer <= diff) { Unit *pTarget = NULL; - bool friendly = false; if (urand(0,1)) pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true); else { - friendly = true; - if (urand(0,1)) pTarget = me; else diff --git a/src/server/scripts/EasternKingdoms/MagistersTerrace/instance_magisters_terrace.cpp b/src/server/scripts/EasternKingdoms/MagistersTerrace/instance_magisters_terrace.cpp index 386bb117f11..710ac2b2e43 100644 --- a/src/server/scripts/EasternKingdoms/MagistersTerrace/instance_magisters_terrace.cpp +++ b/src/server/scripts/EasternKingdoms/MagistersTerrace/instance_magisters_terrace.cpp @@ -137,29 +137,29 @@ public: } } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case 24723: SelinGUID = pCreature->GetGUID(); break; - case 24560: DelrissaGUID = pCreature->GetGUID(); break; - case 24722: FelCrystals.push_back(pCreature->GetGUID()); break; + case 24723: SelinGUID = creature->GetGUID(); break; + case 24560: DelrissaGUID = creature->GetGUID(); break; + case 24722: FelCrystals.push_back(creature->GetGUID()); break; } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { - case 187896: VexallusDoorGUID = pGo->GetGUID(); break; + case 187896: VexallusDoorGUID = go->GetGUID(); break; //SunwellRaid Gate 02 - case 187979: SelinDoorGUID = pGo->GetGUID(); break; + case 187979: SelinDoorGUID = go->GetGUID(); break; //Assembly Chamber Door - case 188065: SelinEncounterDoorGUID = pGo->GetGUID(); break; - case 187770: DelrissaDoorGUID = pGo->GetGUID(); break; - case 188064: KaelDoorGUID = pGo->GetGUID(); break; - case 188165: KaelStatue[0] = pGo->GetGUID(); break; - case 188166: KaelStatue[1] = pGo->GetGUID(); break; + case 188065: SelinEncounterDoorGUID = go->GetGUID(); break; + case 187770: DelrissaDoorGUID = go->GetGUID(); break; + case 188064: KaelDoorGUID = go->GetGUID(); break; + case 188165: KaelStatue[0] = go->GetGUID(); break; + case 188166: KaelStatue[1] = go->GetGUID(); break; } } diff --git a/src/server/scripts/EasternKingdoms/MoltenCore/instance_molten_core.cpp b/src/server/scripts/EasternKingdoms/MoltenCore/instance_molten_core.cpp index b6eff7157c9..ec59f004b33 100644 --- a/src/server/scripts/EasternKingdoms/MoltenCore/instance_molten_core.cpp +++ b/src/server/scripts/EasternKingdoms/MoltenCore/instance_molten_core.cpp @@ -105,83 +105,83 @@ public: return false; }; - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case 176951: //Sulfuron - RuneKoro = pGo->GetGUID(); + RuneKoro = go->GetGUID(); break; case 176952: //Geddon - RuneZeth = pGo->GetGUID(); + RuneZeth = go->GetGUID(); break; case 176953: //Shazzrah - RuneMazj = pGo->GetGUID(); + RuneMazj = go->GetGUID(); break; case 176954: //Golemagg - RuneTheri = pGo->GetGUID(); + RuneTheri = go->GetGUID(); break; case 176955: //Garr - RuneBlaz = pGo->GetGUID(); + RuneBlaz = go->GetGUID(); break; case 176956: //Magmadar - RuneKress = pGo->GetGUID(); + RuneKress = go->GetGUID(); break; case 176957: //Gehennas - RuneMohn = pGo->GetGUID(); + RuneMohn = go->GetGUID(); break; case 179703: - m_uiFirelordCacheGUID = pGo->GetGUID(); //when majordomo event == DONE DoRespawnGameObject(m_uiFirelordCacheGUID,); + m_uiFirelordCacheGUID = go->GetGUID(); //when majordomo event == DONE DoRespawnGameObject(m_uiFirelordCacheGUID,); break; } } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch (pCreature->GetEntry()) + switch (creature->GetEntry()) { case ID_LUCIFRON: - Lucifron = pCreature->GetGUID(); + Lucifron = creature->GetGUID(); break; case ID_MAGMADAR: - Magmadar = pCreature->GetGUID(); + Magmadar = creature->GetGUID(); break; case ID_GEHENNAS: - Gehennas = pCreature->GetGUID(); + Gehennas = creature->GetGUID(); break; case ID_GARR: - Garr = pCreature->GetGUID(); + Garr = creature->GetGUID(); break; case ID_GEDDON: - Geddon = pCreature->GetGUID(); + Geddon = creature->GetGUID(); break; case ID_SHAZZRAH: - Shazzrah = pCreature->GetGUID(); + Shazzrah = creature->GetGUID(); break; case ID_SULFURON: - Sulfuron = pCreature->GetGUID(); + Sulfuron = creature->GetGUID(); break; case ID_GOLEMAGG: - Golemagg = pCreature->GetGUID(); + Golemagg = creature->GetGUID(); break; case ID_DOMO: - Domo = pCreature->GetGUID(); + Domo = creature->GetGUID(); break; case ID_RAGNAROS: - Ragnaros = pCreature->GetGUID(); + Ragnaros = creature->GetGUID(); break; case ID_FLAMEWAKERPRIEST: - FlamewakerPriest = pCreature->GetGUID(); + FlamewakerPriest = creature->GetGUID(); break; } } diff --git a/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter5.cpp b/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter5.cpp index 69ea27b46cc..ed990b9684c 100644 --- a/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter5.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletEnclave/chapter5.cpp @@ -229,10 +229,9 @@ enum mograine SPELL_THUNDER = 53630 }; -struct Locations +struct Location { float x, y, z, o; - uint32 id; }; void UpdateWorldState(Map *map, uint32 id, uint32 state) @@ -249,38 +248,38 @@ void UpdateWorldState(Map *map, uint32 id, uint32 state) } } -static Locations LightofDawnLoc[]= +static Location LightofDawnLoc[]= { - {2281.335f, -5300.409f, 85.170f, 0 ,0}, // 0 Tirion Fordring loc - {2283.896f, -5287.914f, 83.066f, 1.55f ,0}, // 1 Tirion Fordring loc2 - {2281.461f, -5263.014f, 81.164f, 0 ,0}, // 2 Tirion charges - {2262.277f, -5293.477f, 82.167f, 0 ,0}, // 3 Tirion run - {2270.286f, -5287.73f, 82.262f, 0 ,0}, // 4 Tirion relocate - {2269.511f, -5288.289f, 82.225f, 0 ,0}, // 5 Tirion forward - {2262.277f, -5293.477f, 82.167f, 0 ,0}, // 6 Tirion runs to Darion - {2270.286f, -5287.73f, 82.262f, 0 ,0}, - {2269.511f, -5288.289f, 82.225f, 0 ,0}, - {2273.205f, -5288.848f, 82.617f, 0 ,0}, // 9 Korfax loc1 - {2274.739f, -5287.926f, 82.684f, 0 ,0}, // 10 Korfax loc2 - {2253.673f, -5318.004f, 81.724f, 0 ,0}, // 11 Korfax kicked - {2287.028f, -5309.644f, 87.253f, 0 ,0}, // 12 Maxwell loc1 - {2286.978f, -5308.025f, 86.83f, 0 ,0}, // 13 Maxwell loc2 - {2248.877f, -5307.586f, 82.166f, 0 ,0}, // 14 maxwell kicked - {2278.58f, -5316.933f, 88.319f, 0 ,0}, // 15 Eligor loc1 - {2278.535f, -5315.479f, 88.08f, 0 ,0}, // 16 Eligor loc2 - {2259.416f, -5304.505f, 82.149f, 0 ,0}, // 17 eligor kicked - {2289.259f, -5280.355f, 82.112f, 0 ,0}, // 18 Koltira loc1 - {2289.02f, -5281.985f, 82.207f, 0 ,0}, // 19 Koltira loc2 - {2273.289f, -5273.675f, 81.701f, 0 ,0}, // 20 Thassarian loc1 - {2273.332f, -5275.544f, 81.849f, 0 ,0}, // 21 Thassarian loc2 - {2281.198f, -5257.397f, 80.224f, 4.66f ,0}, // 22 Alexandros loc1 - {2281.156f, -5259.934f, 80.647f, 0 ,0}, // 23 Alexandros loc2 - {2281.294f, -5281.895f, 82.445f, 1.35f ,0}, // 24 Darion loc1 - {2281.093f, -5263.013f, 81.125f, 0 ,0}, // 25 Darion loc1 - {2281.313f, -5250.282f, 79.322f, 4.69f ,0}, // 26 Lich King spawns - {2281.523f, -5261.058f, 80.877f, 0 ,0}, // 27 Lich king move forwards - {2272.709f, -5255.552f, 78.226f, 0 ,0}, // 28 Lich king kicked - {2273.972f, -5257.676f, 78.862f, 0, 0}, // 29 Lich king moves forward + {2281.335f, -5300.409f, 85.170f, 0}, // 0 Tirion Fordring loc + {2283.896f, -5287.914f, 83.066f, 1.55f}, // 1 Tirion Fordring loc2 + {2281.461f, -5263.014f, 81.164f, 0}, // 2 Tirion charges + {2262.277f, -5293.477f, 82.167f, 0}, // 3 Tirion run + {2270.286f, -5287.73f, 82.262f, 0}, // 4 Tirion relocate + {2269.511f, -5288.289f, 82.225f, 0}, // 5 Tirion forward + {2262.277f, -5293.477f, 82.167f, 0}, // 6 Tirion runs to Darion + {2270.286f, -5287.73f, 82.262f, 0}, + {2269.511f, -5288.289f, 82.225f, 0}, + {2273.205f, -5288.848f, 82.617f, 0}, // 9 Korfax loc1 + {2274.739f, -5287.926f, 82.684f, 0}, // 10 Korfax loc2 + {2253.673f, -5318.004f, 81.724f, 0}, // 11 Korfax kicked + {2287.028f, -5309.644f, 87.253f, 0}, // 12 Maxwell loc1 + {2286.978f, -5308.025f, 86.83f, 0}, // 13 Maxwell loc2 + {2248.877f, -5307.586f, 82.166f, 0}, // 14 maxwell kicked + {2278.58f, -5316.933f, 88.319f, 0}, // 15 Eligor loc1 + {2278.535f, -5315.479f, 88.08f, 0}, // 16 Eligor loc2 + {2259.416f, -5304.505f, 82.149f, 0}, // 17 eligor kicked + {2289.259f, -5280.355f, 82.112f, 0}, // 18 Koltira loc1 + {2289.02f, -5281.985f, 82.207f, 0}, // 19 Koltira loc2 + {2273.289f, -5273.675f, 81.701f, 0}, // 20 Thassarian loc1 + {2273.332f, -5275.544f, 81.849f, 0}, // 21 Thassarian loc2 + {2281.198f, -5257.397f, 80.224f, 4.66f}, // 22 Alexandros loc1 + {2281.156f, -5259.934f, 80.647f, 0}, // 23 Alexandros loc2 + {2281.294f, -5281.895f, 82.445f, 1.35f}, // 24 Darion loc1 + {2281.093f, -5263.013f, 81.125f, 0}, // 25 Darion loc1 + {2281.313f, -5250.282f, 79.322f, 4.69f}, // 26 Lich King spawns + {2281.523f, -5261.058f, 80.877f, 0}, // 27 Lich king move forwards + {2272.709f, -5255.552f, 78.226f, 0}, // 28 Lich king kicked + {2273.972f, -5257.676f, 78.862f, 0}, // 29 Lich king moves forward }; class npc_highlord_darion_mograine : public CreatureScript diff --git a/src/server/scripts/EasternKingdoms/ScarletMonastery/instance_scarlet_monastery.cpp b/src/server/scripts/EasternKingdoms/ScarletMonastery/instance_scarlet_monastery.cpp index 48fac5766a7..255e8bbf64c 100644 --- a/src/server/scripts/EasternKingdoms/ScarletMonastery/instance_scarlet_monastery.cpp +++ b/src/server/scripts/EasternKingdoms/ScarletMonastery/instance_scarlet_monastery.cpp @@ -74,25 +74,25 @@ public: DoorHighInquisitorGUID = 0; } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { - case ENTRY_PUMPKIN_SHRINE: PumpkinShrineGUID = pGo->GetGUID();break; - case 104600: DoorHighInquisitorGUID = pGo->GetGUID(); break; + case ENTRY_PUMPKIN_SHRINE: PumpkinShrineGUID = go->GetGUID();break; + case 104600: DoorHighInquisitorGUID = go->GetGUID(); break; } } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case ENTRY_HORSEMAN: HorsemanGUID = pCreature->GetGUID(); break; - case ENTRY_HEAD: HeadGUID = pCreature->GetGUID(); break; - case ENTRY_PUMPKIN: HorsemanAdds.insert(pCreature->GetGUID());break; - case 3976: MograineGUID = pCreature->GetGUID(); break; - case 3977: WhitemaneGUID = pCreature->GetGUID(); break; - case 3981: VorrelGUID = pCreature->GetGUID(); break; + case ENTRY_HORSEMAN: HorsemanGUID = creature->GetGUID(); break; + case ENTRY_HEAD: HeadGUID = creature->GetGUID(); break; + case ENTRY_PUMPKIN: HorsemanAdds.insert(creature->GetGUID());break; + case 3976: MograineGUID = creature->GetGUID(); break; + case 3977: WhitemaneGUID = creature->GetGUID(); break; + case 3981: VorrelGUID = creature->GetGUID(); break; } } diff --git a/src/server/scripts/EasternKingdoms/Scholomance/instance_scholomance.cpp b/src/server/scripts/EasternKingdoms/Scholomance/instance_scholomance.cpp index 14f7bb3bf7b..1059c3f4d03 100644 --- a/src/server/scripts/EasternKingdoms/Scholomance/instance_scholomance.cpp +++ b/src/server/scripts/EasternKingdoms/Scholomance/instance_scholomance.cpp @@ -81,18 +81,18 @@ public: IsBossDied[i] = false; } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { - case GO_GATE_KIRTONOS: GateKirtonosGUID = pGo->GetGUID(); break; - case GO_GATE_GANDLING: GateGandlingGUID = pGo->GetGUID(); break; - case GO_GATE_MALICIA: GateMiliciaGUID = pGo->GetGUID(); break; - case GO_GATE_THEOLEN: GateTheolenGUID = pGo->GetGUID(); break; - case GO_GATE_POLKELT: GatePolkeltGUID = pGo->GetGUID(); break; - case GO_GATE_RAVENIAN: GateRavenianGUID = pGo->GetGUID(); break; - case GO_GATE_BAROV: GateBarovGUID = pGo->GetGUID(); break; - case GO_GATE_ILLUCIA: GateIlluciaGUID = pGo->GetGUID(); break; + case GO_GATE_KIRTONOS: GateKirtonosGUID = go->GetGUID(); break; + case GO_GATE_GANDLING: GateGandlingGUID = go->GetGUID(); break; + case GO_GATE_MALICIA: GateMiliciaGUID = go->GetGUID(); break; + case GO_GATE_THEOLEN: GateTheolenGUID = go->GetGUID(); break; + case GO_GATE_POLKELT: GatePolkeltGUID = go->GetGUID(); break; + case GO_GATE_RAVENIAN: GateRavenianGUID = go->GetGUID(); break; + case GO_GATE_BAROV: GateBarovGUID = go->GetGUID(); break; + case GO_GATE_ILLUCIA: GateIlluciaGUID = go->GetGUID(); break; } } diff --git a/src/server/scripts/EasternKingdoms/ShadowfangKeep/instance_shadowfang_keep.cpp b/src/server/scripts/EasternKingdoms/ShadowfangKeep/instance_shadowfang_keep.cpp index b2a893971dd..ca7e769d049 100644 --- a/src/server/scripts/EasternKingdoms/ShadowfangKeep/instance_shadowfang_keep.cpp +++ b/src/server/scripts/EasternKingdoms/ShadowfangKeep/instance_shadowfang_keep.cpp @@ -98,34 +98,34 @@ public: uiTimer = 0; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case NPC_ASH: uiAshGUID = pCreature->GetGUID(); break; - case NPC_ADA: uiAdaGUID = pCreature->GetGUID(); break; - case NPC_ARCHMAGE_ARUGAL: uiArchmageArugalGUID = pCreature->GetGUID(); break; + case NPC_ASH: uiAshGUID = creature->GetGUID(); break; + case NPC_ADA: uiAdaGUID = creature->GetGUID(); break; + case NPC_ARCHMAGE_ARUGAL: uiArchmageArugalGUID = creature->GetGUID(); break; } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case GO_COURTYARD_DOOR: - DoorCourtyardGUID = pGo->GetGUID(); + DoorCourtyardGUID = go->GetGUID(); if (m_auiEncounter[0] == DONE) - HandleGameObject(NULL, true, pGo); + HandleGameObject(NULL, true, go); break; case GO_SORCERER_DOOR: - DoorSorcererGUID = pGo->GetGUID(); + DoorSorcererGUID = go->GetGUID(); if (m_auiEncounter[2] == DONE) - HandleGameObject(NULL, true, pGo); + HandleGameObject(NULL, true, go); break; case GO_ARUGAL_DOOR: - DoorArugalGUID = pGo->GetGUID(); + DoorArugalGUID = go->GetGUID(); if (m_auiEncounter[3] == DONE) - HandleGameObject(NULL, true, pGo); + HandleGameObject(NULL, true, go); break; } } diff --git a/src/server/scripts/EasternKingdoms/Stratholme/instance_stratholme.cpp b/src/server/scripts/EasternKingdoms/Stratholme/instance_stratholme.cpp index 6aa5840b109..396e49a925e 100644 --- a/src/server/scripts/EasternKingdoms/Stratholme/instance_stratholme.cpp +++ b/src/server/scripts/EasternKingdoms/Stratholme/instance_stratholme.cpp @@ -134,76 +134,76 @@ public: if (!goGuid) return; - if (GameObject* pGo = instance->GetGameObject(goGuid)) + if (GameObject* go = instance->GetGameObject(goGuid)) { if (withRestoreTime) - pGo->UseDoorOrButton(10); + go->UseDoorOrButton(10); else - pGo->SetGoState((GOState)newState); + go->SetGoState((GOState)newState); } } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case C_BARON: baronGUID = pCreature->GetGUID(); break; - case C_YSIDA_TRIGGER: ysidaTriggerGUID = pCreature->GetGUID(); break; - case C_CRYSTAL: crystalsGUID.insert(pCreature->GetGUID()); break; + case C_BARON: baronGUID = creature->GetGUID(); break; + case C_YSIDA_TRIGGER: ysidaTriggerGUID = creature->GetGUID(); break; + case C_CRYSTAL: crystalsGUID.insert(creature->GetGUID()); break; case C_ABOM_BILE: - case C_ABOM_VENOM: abomnationGUID.insert(pCreature->GetGUID()); break; + case C_ABOM_VENOM: abomnationGUID.insert(creature->GetGUID()); break; } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case GO_SERVICE_ENTRANCE: - serviceEntranceGUID = pGo->GetGUID(); + serviceEntranceGUID = go->GetGUID(); break; case GO_GAUNTLET_GATE1: //weird, but unless flag is set, client will not respond as expected. DB bug? - pGo->SetFlag(GAMEOBJECT_FLAGS,GO_FLAG_LOCKED); - gauntletGate1GUID = pGo->GetGUID(); + go->SetFlag(GAMEOBJECT_FLAGS,GO_FLAG_LOCKED); + gauntletGate1GUID = go->GetGUID(); break; case GO_ZIGGURAT1: - ziggurat1GUID = pGo->GetGUID(); + ziggurat1GUID = go->GetGUID(); if (GetData(TYPE_BARONESS) == IN_PROGRESS) - HandleGameObject(0, true, pGo); + HandleGameObject(0, true, go); break; case GO_ZIGGURAT2: - ziggurat2GUID = pGo->GetGUID(); + ziggurat2GUID = go->GetGUID(); if (GetData(TYPE_NERUB) == IN_PROGRESS) - HandleGameObject(0, true, pGo); + HandleGameObject(0, true, go); break; case GO_ZIGGURAT3: - ziggurat3GUID = pGo->GetGUID(); + ziggurat3GUID = go->GetGUID(); if (GetData(TYPE_PALLID) == IN_PROGRESS) - HandleGameObject(0, true, pGo); + HandleGameObject(0, true, go); break; case GO_ZIGGURAT4: - ziggurat4GUID = pGo->GetGUID(); + ziggurat4GUID = go->GetGUID(); if (GetData(TYPE_BARON) == DONE || GetData(TYPE_RAMSTEIN) == DONE) - HandleGameObject(0, true, pGo); + HandleGameObject(0, true, go); break; case GO_ZIGGURAT5: - ziggurat5GUID = pGo->GetGUID(); + ziggurat5GUID = go->GetGUID(); if (GetData(TYPE_BARON) == DONE || GetData(TYPE_RAMSTEIN) == DONE) - HandleGameObject(0, true, pGo); + HandleGameObject(0, true, go); break; case GO_PORT_GAUNTLET: - portGauntletGUID = pGo->GetGUID(); + portGauntletGUID = go->GetGUID(); if (GetData(TYPE_BARONESS) == IN_PROGRESS && GetData(TYPE_NERUB) == IN_PROGRESS && GetData(TYPE_PALLID) == IN_PROGRESS) - HandleGameObject(0, true, pGo); + HandleGameObject(0, true, go); break; case GO_PORT_SLAUGTHER: - portSlaugtherGUID = pGo->GetGUID(); + portSlaugtherGUID = go->GetGUID(); if (GetData(TYPE_BARONESS) == IN_PROGRESS && GetData(TYPE_NERUB) == IN_PROGRESS && GetData(TYPE_PALLID) == IN_PROGRESS) - HandleGameObject(0, true, pGo); + HandleGameObject(0, true, go); break; case GO_PORT_ELDERS: - portElderGUID = pGo->GetGUID(); + portElderGUID = go->GetGUID(); break; } } diff --git a/src/server/scripts/EasternKingdoms/SunkenTemple/instance_sunken_temple.cpp b/src/server/scripts/EasternKingdoms/SunkenTemple/instance_sunken_temple.cpp index ce441cdee5c..e8f49c06257 100644 --- a/src/server/scripts/EasternKingdoms/SunkenTemple/instance_sunken_temple.cpp +++ b/src/server/scripts/EasternKingdoms/SunkenTemple/instance_sunken_temple.cpp @@ -93,17 +93,17 @@ public: s6 = false; } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { - case GO_ATALAI_STATUE1: GOAtalaiStatue1 = pGo->GetGUID(); break; - case GO_ATALAI_STATUE2: GOAtalaiStatue2 = pGo->GetGUID(); break; - case GO_ATALAI_STATUE3: GOAtalaiStatue3 = pGo->GetGUID(); break; - case GO_ATALAI_STATUE4: GOAtalaiStatue4 = pGo->GetGUID(); break; - case GO_ATALAI_STATUE5: GOAtalaiStatue5 = pGo->GetGUID(); break; - case GO_ATALAI_STATUE6: GOAtalaiStatue6 = pGo->GetGUID(); break; - case GO_ATALAI_IDOL: GOAtalaiIdol = pGo->GetGUID(); break; + case GO_ATALAI_STATUE1: GOAtalaiStatue1 = go->GetGUID(); break; + case GO_ATALAI_STATUE2: GOAtalaiStatue2 = go->GetGUID(); break; + case GO_ATALAI_STATUE3: GOAtalaiStatue3 = go->GetGUID(); break; + case GO_ATALAI_STATUE4: GOAtalaiStatue4 = go->GetGUID(); break; + case GO_ATALAI_STATUE5: GOAtalaiStatue5 = go->GetGUID(); break; + case GO_ATALAI_STATUE6: GOAtalaiStatue6 = go->GetGUID(); break; + case GO_ATALAI_IDOL: GOAtalaiIdol = go->GetGUID(); break; } } @@ -114,7 +114,7 @@ public: case GO_ATALAI_STATUE1: if (!s1 && !s2 && !s3 && !s4 && !s5 && !s6) { - if (GameObject *pAtalaiStatue1 = instance->GetGameObject(GOAtalaiStatue1)) + if (GameObject* pAtalaiStatue1 = instance->GetGameObject(GOAtalaiStatue1)) UseStatue(pAtalaiStatue1); s1 = true; State = 0; @@ -123,7 +123,7 @@ public: case GO_ATALAI_STATUE2: if (s1 && !s2 && !s3 && !s4 && !s5 && !s6) { - if (GameObject *pAtalaiStatue2 = instance->GetGameObject(GOAtalaiStatue2)) + if (GameObject* pAtalaiStatue2 = instance->GetGameObject(GOAtalaiStatue2)) UseStatue(pAtalaiStatue2); s2 = true; State = 0; @@ -132,7 +132,7 @@ public: case GO_ATALAI_STATUE3: if (s1 && s2 && !s3 && !s4 && !s5 && !s6) { - if (GameObject *pAtalaiStatue3 = instance->GetGameObject(GOAtalaiStatue3)) + if (GameObject* pAtalaiStatue3 = instance->GetGameObject(GOAtalaiStatue3)) UseStatue(pAtalaiStatue3); s3 = true; State = 0; @@ -141,7 +141,7 @@ public: case GO_ATALAI_STATUE4: if (s1 && s2 && s3 && !s4 && !s5 && !s6) { - if (GameObject *pAtalaiStatue4 = instance->GetGameObject(GOAtalaiStatue4)) + if (GameObject* pAtalaiStatue4 = instance->GetGameObject(GOAtalaiStatue4)) UseStatue(pAtalaiStatue4); s4 = true; State = 0; @@ -150,7 +150,7 @@ public: case GO_ATALAI_STATUE5: if (s1 && s2 && s3 && s4 && !s5 && !s6) { - if (GameObject *pAtalaiStatue5 = instance->GetGameObject(GOAtalaiStatue5)) + if (GameObject* pAtalaiStatue5 = instance->GetGameObject(GOAtalaiStatue5)) UseStatue(pAtalaiStatue5); s5 = true; State = 0; @@ -159,7 +159,7 @@ public: case GO_ATALAI_STATUE6: if (s1 && s2 && s3 && s4 && s5 && !s6) { - if (GameObject *pAtalaiStatue6 = instance->GetGameObject(GOAtalaiStatue6)) + if (GameObject* pAtalaiStatue6 = instance->GetGameObject(GOAtalaiStatue6)) UseStatue(pAtalaiStatue6); s6 = true; State = 0; @@ -168,14 +168,14 @@ public: } }; - void UseStatue(GameObject* pGo) + void UseStatue(GameObject* go) { - pGo->SummonGameObject(GO_ATALAI_LIGHT1,pGo->GetPositionX(),pGo->GetPositionY(),pGo->GetPositionZ(),0,0,0,0,0,0); - pGo->SetUInt32Value(GAMEOBJECT_FLAGS, 4); + go->SummonGameObject(GO_ATALAI_LIGHT1,go->GetPositionX(),go->GetPositionY(),go->GetPositionZ(),0,0,0,0,0,0); + go->SetUInt32Value(GAMEOBJECT_FLAGS, 4); } /* - void UseLastStatue(GameObject* pGo) + void UseLastStatue(GameObject* go) { AtalaiStatue1->SummonGameObject(GO_ATALAI_LIGHT2,AtalaiStatue1->GetPositionX(),AtalaiStatue1->GetPositionY(),AtalaiStatue1->GetPositionZ(),0,0,0,0,0,100000); AtalaiStatue2->SummonGameObject(GO_ATALAI_LIGHT2,AtalaiStatue2->GetPositionX(),AtalaiStatue2->GetPositionY(),AtalaiStatue2->GetPositionZ(),0,0,0,0,0,100000); @@ -183,7 +183,7 @@ public: AtalaiStatue4->SummonGameObject(GO_ATALAI_LIGHT2,AtalaiStatue4->GetPositionX(),AtalaiStatue4->GetPositionY(),AtalaiStatue4->GetPositionZ(),0,0,0,0,0,100000); AtalaiStatue5->SummonGameObject(GO_ATALAI_LIGHT2,AtalaiStatue5->GetPositionX(),AtalaiStatue5->GetPositionY(),AtalaiStatue5->GetPositionZ(),0,0,0,0,0,100000); AtalaiStatue6->SummonGameObject(GO_ATALAI_LIGHT2,AtalaiStatue6->GetPositionX(),AtalaiStatue6->GetPositionY(),AtalaiStatue6->GetPositionZ(),0,0,0,0,0,100000); - pGo->SummonGameObject(148838,-488.997,96.61,-189.019,-1.52,0,0,0,0,100000); + go->SummonGameObject(148838,-488.997,96.61,-189.019,-1.52,0,0,0,0,100000); } */ diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kiljaeden.cpp b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kiljaeden.cpp index b89824b819b..05fd6881d85 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kiljaeden.cpp +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/boss_kiljaeden.cpp @@ -724,8 +724,9 @@ public: if (Speeches[speechCount].timer < SpeechTimer) { SpeechTimer = 0; - if (Creature* pSpeechCreature = Unit::GetCreature(*me, pInstance->GetData64(Speeches[speechCount].pCreature))) - DoScriptText(Speeches[speechCount].textid, pSpeechCreature); + if (pInstance) + if (Creature* pSpeechCreature = Unit::GetCreature(*me, pInstance->GetData64(Speeches[speechCount].pCreature))) + DoScriptText(Speeches[speechCount].textid, pSpeechCreature); if (speechCount == 12) if (Creature* pAnveena = Unit::GetCreature(*me, pInstance->GetData64(DATA_ANVEENA))) pAnveena->CastSpell(me, SPELL_SACRIFICE_OF_ANVEENA, false); @@ -826,18 +827,19 @@ public: } break; case TIMER_ORBS_EMPOWER: //Phase 3 - if (Creature* pKalec = Unit::GetCreature(*me, pInstance->GetData64(DATA_KALECGOS_KJ))) - { - switch (Phase) + if (pInstance) + if (Creature* pKalec = Unit::GetCreature(*me, pInstance->GetData64(DATA_KALECGOS_KJ))) { + switch (Phase) + { case PHASE_SACRIFICE: CAST_AI(boss_kalecgos_kj::boss_kalecgos_kjAI, pKalec->AI())->EmpowerOrb(true); break; default: CAST_AI(boss_kalecgos_kj::boss_kalecgos_kjAI, pKalec->AI())->EmpowerOrb(false); break; + } } - } OrbActivated = true; TimerIsDeactivated[TIMER_ORBS_EMPOWER] = true; break; diff --git a/src/server/scripts/EasternKingdoms/SunwellPlateau/instance_sunwell_plateau.cpp b/src/server/scripts/EasternKingdoms/SunwellPlateau/instance_sunwell_plateau.cpp index 509ab3a10d8..b1909900067 100644 --- a/src/server/scripts/EasternKingdoms/SunwellPlateau/instance_sunwell_plateau.cpp +++ b/src/server/scripts/EasternKingdoms/SunwellPlateau/instance_sunwell_plateau.cpp @@ -138,43 +138,43 @@ public: return NULL; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case 24850: Kalecgos_Dragon = pCreature->GetGUID(); break; - case 24891: Kalecgos_Human = pCreature->GetGUID(); break; - case 24892: Sathrovarr = pCreature->GetGUID(); break; - case 24882: Brutallus = pCreature->GetGUID(); break; - case 24895: Madrigosa = pCreature->GetGUID(); break; - case 25038: Felmyst = pCreature->GetGUID(); break; - case 25166: Alythess = pCreature->GetGUID(); break; - case 25165: Sacrolash = pCreature->GetGUID(); break; - case 25741: Muru = pCreature->GetGUID(); break; - case 25315: KilJaeden = pCreature->GetGUID(); break; - case 25608: KilJaedenController = pCreature->GetGUID(); break; - case 26046: Anveena = pCreature->GetGUID(); break; - case 25319: KalecgosKJ = pCreature->GetGUID(); break; + case 24850: Kalecgos_Dragon = creature->GetGUID(); break; + case 24891: Kalecgos_Human = creature->GetGUID(); break; + case 24892: Sathrovarr = creature->GetGUID(); break; + case 24882: Brutallus = creature->GetGUID(); break; + case 24895: Madrigosa = creature->GetGUID(); break; + case 25038: Felmyst = creature->GetGUID(); break; + case 25166: Alythess = creature->GetGUID(); break; + case 25165: Sacrolash = creature->GetGUID(); break; + case 25741: Muru = creature->GetGUID(); break; + case 25315: KilJaeden = creature->GetGUID(); break; + case 25608: KilJaedenController = creature->GetGUID(); break; + case 26046: Anveena = creature->GetGUID(); break; + case 25319: KalecgosKJ = creature->GetGUID(); break; } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { - case 188421: ForceField = pGo->GetGUID(); break; - case 188523: KalecgosWall[0] = pGo->GetGUID(); break; - case 188524: KalecgosWall[0] = pGo->GetGUID(); break; + case 188421: ForceField = go->GetGUID(); break; + case 188523: KalecgosWall[0] = go->GetGUID(); break; + case 188524: KalecgosWall[0] = go->GetGUID(); break; case 188075: if (m_auiEncounter[2] == DONE) - HandleGameObject(NULL, true, pGo); - FireBarrier = pGo->GetGUID(); + HandleGameObject(NULL, true, go); + FireBarrier = go->GetGUID(); break; - case 187990: MurusGate[0] = pGo->GetGUID(); break; + case 187990: MurusGate[0] = go->GetGUID(); break; case 188118: if (m_auiEncounter[4] == DONE) - HandleGameObject(NULL, true, pGo); - MurusGate[1]= pGo->GetGUID(); + HandleGameObject(NULL, true, go); + MurusGate[1]= go->GetGUID(); break; } } diff --git a/src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp b/src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp index f518b0b418d..e8820ba5e18 100644 --- a/src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp +++ b/src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp @@ -100,65 +100,65 @@ class instance_uldaman : public InstanceMapScript uint32 m_auiEncounter[MAX_ENCOUNTER]; std::string str_data; - void OnGameObjectCreate(GameObject* pGO, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch (pGO->GetEntry()) + switch (go->GetEntry()) { case GO_ALTAR_OF_THE_KEEPER_TEMPLE_DOOR: // lock the door - uiAltarOfTheKeeperTempleDoor = pGO->GetGUID(); + uiAltarOfTheKeeperTempleDoor = go->GetGUID(); if(m_auiEncounter[0] == DONE) - HandleGameObject(NULL, true, pGO); + HandleGameObject(NULL, true, go); break; case GO_ARCHAEDAS_TEMPLE_DOOR: - uiArchaedasTempleDoor = pGO->GetGUID(); + uiArchaedasTempleDoor = go->GetGUID(); if(m_auiEncounter[0] == DONE) - HandleGameObject(NULL, true, pGO); + HandleGameObject(NULL, true, go); break; case GO_ANCIENT_VAULT_DOOR: - pGO->SetGoState(GO_STATE_READY); - pGO->SetUInt32Value(GAMEOBJECT_FLAGS, 33); - uiAncientVaultDoor = pGO->GetGUID(); + go->SetGoState(GO_STATE_READY); + go->SetUInt32Value(GAMEOBJECT_FLAGS, 33); + uiAncientVaultDoor = go->GetGUID(); if(m_auiEncounter[1] == DONE) - HandleGameObject(NULL, true, pGO); + HandleGameObject(NULL, true, go); break; case GO_IRONAYA_SEAL_DOOR: - uiIronayaSealDoor = pGO->GetGUID(); + uiIronayaSealDoor = go->GetGUID(); if (m_auiEncounter[2] == DONE) - HandleGameObject(NULL, true, pGO); + HandleGameObject(NULL, true, go); break; case GO_KEYSTONE: - uiKeystoneGUID = pGO->GetGUID(); + uiKeystoneGUID = go->GetGUID(); if (m_auiEncounter[2] == DONE) { - HandleGameObject(NULL, true, pGO); - pGO->SetUInt32Value(GAMEOBJECT_FLAGS, GO_FLAG_INTERACT_COND); + HandleGameObject(NULL, true, go); + go->SetUInt32Value(GAMEOBJECT_FLAGS, GO_FLAG_INTERACT_COND); } break; } } - void SetFrozenState(Creature* pCreature) + void SetFrozenState(Creature* creature) { - pCreature->setFaction(35); - pCreature->RemoveAllAuras(); + creature->setFaction(35); + creature->RemoveAllAuras(); //creature->RemoveFlag (UNIT_FIELD_FLAGS,UNIT_FLAG_ANIMATION_FROZEN); - pCreature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - pCreature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); + creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); + creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); } void SetDoor(uint64 guid, bool open) { - GameObject* pGO = instance->GetGameObject(guid); - if (!pGO) + GameObject* go = instance->GetGameObject(guid); + if (!go) return; HandleGameObject(guid, open); @@ -166,18 +166,18 @@ class instance_uldaman : public InstanceMapScript void BlockGO(uint64 guid) { - GameObject *pGO = instance->GetGameObject(guid); - if(!pGO) + GameObject* go = instance->GetGameObject(guid); + if(!go) return; - pGO->SetUInt32Value(GAMEOBJECT_FLAGS, GO_FLAG_INTERACT_COND); + go->SetUInt32Value(GAMEOBJECT_FLAGS, GO_FLAG_INTERACT_COND); } void ActivateStoneKeepers() { for (std::vector<uint64>::const_iterator i = vStoneKeeper.begin(); i != vStoneKeeper.end(); ++i) { - Creature *pTarget = instance->GetCreature(*i); + Creature* pTarget = instance->GetCreature(*i); if (!pTarget || !pTarget->isAlive() || pTarget->getFaction() == 14) continue; pTarget->RemoveFlag(UNIT_FIELD_FLAGS,UNIT_FLAG_DISABLE_MOVE); @@ -192,13 +192,13 @@ class instance_uldaman : public InstanceMapScript void ActivateWallMinions() { - Creature *archaedas = instance->GetCreature(uiArchaedasGUID); + Creature* archaedas = instance->GetCreature(uiArchaedasGUID); if (!archaedas) return; for (std::vector<uint64>::const_iterator i = vArchaedasWallMinions.begin(); i != vArchaedasWallMinions.end(); ++i) { - Creature *pTarget = instance->GetCreature(*i); + Creature* pTarget = instance->GetCreature(*i); if (!pTarget || !pTarget->isAlive() || pTarget->getFaction() == 14) continue; archaedas->CastSpell(pTarget, SPELL_AWAKEN_VAULT_WALKER, true); @@ -213,7 +213,7 @@ class instance_uldaman : public InstanceMapScript // first despawn any aggroed wall minions for (std::vector<uint64>::const_iterator i = vArchaedasWallMinions.begin(); i != vArchaedasWallMinions.end(); ++i) { - Creature *pTarget = instance->GetCreature(*i); + Creature* pTarget = instance->GetCreature(*i); if (!pTarget || pTarget->isDead() || pTarget->getFaction() != 14) continue; pTarget->setDeathState(JUST_DIED); @@ -223,7 +223,7 @@ class instance_uldaman : public InstanceMapScript // Vault Walkers for (std::vector<uint64>::const_iterator i = vVaultWalker.begin(); i != vVaultWalker.end(); ++i) { - Creature *pTarget = instance->GetCreature(*i); + Creature* pTarget = instance->GetCreature(*i); if (!pTarget || pTarget->isDead() || pTarget->getFaction() != 14) continue; pTarget->setDeathState(JUST_DIED); @@ -233,7 +233,7 @@ class instance_uldaman : public InstanceMapScript // Earthen Guardians for (std::vector<uint64>::const_iterator i = vEarthenGuardian.begin(); i != vEarthenGuardian.end(); ++i) { - Creature *pTarget = instance->GetCreature(*i); + Creature* pTarget = instance->GetCreature(*i); if (!pTarget || pTarget->isDead() || pTarget->getFaction() != 14) continue; pTarget->setDeathState(JUST_DIED); @@ -243,7 +243,7 @@ class instance_uldaman : public InstanceMapScript void ActivateArchaedas(uint64 target) { - Creature *archaedas = instance->GetCreature(uiArchaedasGUID); + Creature* archaedas = instance->GetCreature(uiArchaedasGUID); if (!archaedas) return; @@ -256,7 +256,7 @@ class instance_uldaman : public InstanceMapScript void ActivateIronaya() { - Creature *ironaya = instance->GetCreature(uiIronayaGUID); + Creature* ironaya = instance->GetCreature(uiIronayaGUID); if(!ironaya) return; @@ -270,7 +270,7 @@ class instance_uldaman : public InstanceMapScript // first respawn any aggroed wall minions for (std::vector<uint64>::const_iterator i = vArchaedasWallMinions.begin(); i != vArchaedasWallMinions.end(); ++i) { - Creature *pTarget = instance->GetCreature(*i); + Creature* pTarget = instance->GetCreature(*i); if (pTarget && pTarget->isDead()) { pTarget->Respawn(); @@ -282,7 +282,7 @@ class instance_uldaman : public InstanceMapScript // Vault Walkers for (std::vector<uint64>::const_iterator i = vVaultWalker.begin(); i != vVaultWalker.end(); ++i) { - Creature *pTarget = instance->GetCreature(*i); + Creature* pTarget = instance->GetCreature(*i); if (pTarget && pTarget->isDead()) { pTarget->Respawn(); @@ -294,7 +294,7 @@ class instance_uldaman : public InstanceMapScript // Earthen Guardians for (std::vector<uint64>::const_iterator i = vEarthenGuardian.begin(); i != vEarthenGuardian.end(); ++i) { - Creature *pTarget = instance->GetCreature(*i); + Creature* pTarget = instance->GetCreature(*i); if (pTarget && pTarget->isDead()) { pTarget->Respawn(); @@ -425,39 +425,39 @@ class instance_uldaman : public InstanceMapScript OUT_LOAD_INST_DATA_COMPLETE; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch (pCreature->GetEntry()) { + switch (creature->GetEntry()) { case 4857: // Stone Keeper - SetFrozenState (pCreature); - vStoneKeeper.push_back(pCreature->GetGUID()); + SetFrozenState (creature); + vStoneKeeper.push_back(creature->GetGUID()); break; case 7309: // Earthen Custodian - vArchaedasWallMinions.push_back(pCreature->GetGUID()); + vArchaedasWallMinions.push_back(creature->GetGUID()); break; case 7077: // Earthen Hallshaper - vArchaedasWallMinions.push_back(pCreature->GetGUID()); + vArchaedasWallMinions.push_back(creature->GetGUID()); break; case 7076: // Earthen Guardian - vEarthenGuardian.push_back(pCreature->GetGUID()); + vEarthenGuardian.push_back(creature->GetGUID()); break; case 7228: // Ironaya - uiIronayaGUID = pCreature->GetGUID(); + uiIronayaGUID = creature->GetGUID(); if(m_auiEncounter[2] != DONE) - SetFrozenState (pCreature); + SetFrozenState (creature); break; case 10120: // Vault Walker - vVaultWalker.push_back(pCreature->GetGUID()); + vVaultWalker.push_back(creature->GetGUID()); break; case 2748: // Archaedas - uiArchaedasGUID = pCreature->GetGUID(); + uiArchaedasGUID = creature->GetGUID(); break; } // end switch diff --git a/src/server/scripts/EasternKingdoms/ZulAman/boss_hexlord.cpp b/src/server/scripts/EasternKingdoms/ZulAman/boss_hexlord.cpp index 2e7598284d3..eb0cd759bb1 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/boss_hexlord.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/boss_hexlord.cpp @@ -128,7 +128,7 @@ struct PlayerAbilityStruct { uint32 spell; AbilityTarget target; - uint32 cooldown; + uint32 cooldown; //FIXME - it's never used }; static PlayerAbilityStruct PlayerAbility[][3] = diff --git a/src/server/scripts/EasternKingdoms/ZulAman/instance_zulaman.cpp b/src/server/scripts/EasternKingdoms/ZulAman/instance_zulaman.cpp index 9ff1751ffc2..3b14f247792 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/instance_zulaman.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/instance_zulaman.cpp @@ -38,7 +38,7 @@ EndScriptData */ // But we cannot add loots to gameobject, so we have to use the fixed loot_template struct SHostageInfo { - uint32 npc, pGo; + uint32 npc, go; // FIXME go Not used float x, y, z, o; }; @@ -114,9 +114,9 @@ class instance_zulaman : public InstanceMapScript return false; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { case 23578://janalai case 23863://zuljin @@ -127,20 +127,20 @@ class instance_zulaman : public InstanceMapScript } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { - case 186303: HalazziDoorGUID = pGo->GetGUID(); break; - case 186304: ZulJinGateGUID = pGo->GetGUID(); break; - case 186305: HexLordGateGUID = pGo->GetGUID(); break; - case 186858: AkilzonDoorGUID = pGo->GetGUID(); break; - case 186859: ZulJinDoorGUID = pGo->GetGUID(); break; - - case 187021: HarkorsSatchelGUID = pGo->GetGUID(); break; - case 186648: TanzarsTrunkGUID = pGo->GetGUID(); break; - case 186672: AshlisBagGUID = pGo->GetGUID(); break; - case 186667: KrazsPackageGUID = pGo->GetGUID(); break; + case 186303: HalazziDoorGUID = go->GetGUID(); break; + case 186304: ZulJinGateGUID = go->GetGUID(); break; + case 186305: HexLordGateGUID = go->GetGUID(); break; + case 186858: AkilzonDoorGUID = go->GetGUID(); break; + case 186859: ZulJinDoorGUID = go->GetGUID(); break; + + case 187021: HarkorsSatchelGUID = go->GetGUID(); break; + case 186648: TanzarsTrunkGUID = go->GetGUID(); break; + case 186672: AshlisBagGUID = go->GetGUID(); break; + case 186667: KrazsPackageGUID = go->GetGUID(); break; default: break; } diff --git a/src/server/scripts/EasternKingdoms/ZulGurub/instance_zulgurub.cpp b/src/server/scripts/EasternKingdoms/ZulGurub/instance_zulgurub.cpp index 72834d07fb6..e2d66a4bab9 100644 --- a/src/server/scripts/EasternKingdoms/ZulGurub/instance_zulgurub.cpp +++ b/src/server/scripts/EasternKingdoms/ZulGurub/instance_zulgurub.cpp @@ -63,14 +63,14 @@ class instance_zulgurub : public InstanceMapScript return false; } - void OnCreatureCreate(Creature* pCreature) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case 11347: m_uiLorKhanGUID = pCreature->GetGUID(); break; - case 11348: m_uiZathGUID = pCreature->GetGUID(); break; - case 14509: m_uiThekalGUID = pCreature->GetGUID(); break; - case 11380: m_uiJindoGUID = pCreature->GetGUID(); break; + case 11347: m_uiLorKhanGUID = creature->GetGUID(); break; + case 11348: m_uiZathGUID = creature->GetGUID(); break; + case 14509: m_uiThekalGUID = creature->GetGUID(); break; + case 11380: m_uiJindoGUID = creature->GetGUID(); break; } } diff --git a/src/server/scripts/Kalimdor/BlackfathomDeeps/instance_blackfathom_deeps.cpp b/src/server/scripts/Kalimdor/BlackfathomDeeps/instance_blackfathom_deeps.cpp index 80eb83c227a..41644fee53c 100644 --- a/src/server/scripts/Kalimdor/BlackfathomDeeps/instance_blackfathom_deeps.cpp +++ b/src/server/scripts/Kalimdor/BlackfathomDeeps/instance_blackfathom_deeps.cpp @@ -94,49 +94,49 @@ public: uiDeathTimes = 0; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch (pCreature->GetEntry()) + switch (creature->GetEntry()) { case NPC_TWILIGHT_LORD_KELRIS: - m_uiTwilightLordKelrisGUID = pCreature->GetGUID(); + m_uiTwilightLordKelrisGUID = creature->GetGUID(); break; case NPC_LORGUS_JETT: - pCreature->SetHomePosition(LorgusPosition[urand(0,3)]); + creature->SetHomePosition(LorgusPosition[urand(0,3)]); break; } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case GO_FIRE_OF_AKU_MAI_1: - m_uiShrine1GUID = pGo->GetGUID(); + m_uiShrine1GUID = go->GetGUID(); break; case GO_FIRE_OF_AKU_MAI_2: - m_uiShrine2GUID = pGo->GetGUID(); + m_uiShrine2GUID = go->GetGUID(); break; case GO_FIRE_OF_AKU_MAI_3: - m_uiShrine3GUID = pGo->GetGUID(); + m_uiShrine3GUID = go->GetGUID(); break; case GO_FIRE_OF_AKU_MAI_4: - m_uiShrine4GUID = pGo->GetGUID(); + m_uiShrine4GUID = go->GetGUID(); break; case GO_SHRINE_OF_GELIHAST: - m_uiShrineOfGelihastGUID = pGo->GetGUID(); + m_uiShrineOfGelihastGUID = go->GetGUID(); if (m_auiEncounter[0] != DONE) - pGo->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); + go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); break; case GO_ALTAR_OF_THE_DEEPS: - m_uiAltarOfTheDeepsGUID = pGo->GetGUID(); + m_uiAltarOfTheDeepsGUID = go->GetGUID(); if (m_auiEncounter[3] != DONE) - pGo->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); + go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); break; case GO_AKU_MAI_DOOR: if (m_auiEncounter[2] == DONE) - HandleGameObject(NULL,true,pGo); - m_uiMainDoorGUID = pGo->GetGUID(); + HandleGameObject(NULL,true,go); + m_uiMainDoorGUID = go->GetGUID(); break; } } @@ -148,16 +148,16 @@ public: case TYPE_GELIHAST: m_auiEncounter[0] = uiData; if (uiData == DONE) - if (GameObject *pGo = instance->GetGameObject(m_uiShrineOfGelihastGUID)) - pGo->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); + if (GameObject* go = instance->GetGameObject(m_uiShrineOfGelihastGUID)) + go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); break; case TYPE_AKU_MAI: m_auiEncounter[3] = uiData; if (uiData == DONE) - if (GameObject *pGo = instance->GetGameObject(m_uiAltarOfTheDeepsGUID)) + if (GameObject* go = instance->GetGameObject(m_uiAltarOfTheDeepsGUID)) { - pGo->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); - pGo->SummonCreature(NPC_MORRIDUNE,SpawnsLocation[4], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 300000); + go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); + go->SummonCreature(NPC_MORRIDUNE,SpawnsLocation[4], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 300000); } break; case DATA_FIRE: diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/instance_hyjal.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/instance_hyjal.cpp index 0cc3056b648..de73311bd72 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/instance_hyjal.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/instance_hyjal.cpp @@ -115,42 +115,42 @@ public: return false; } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case 182060: - HordeGate = pGo->GetGUID(); + HordeGate = go->GetGUID(); if (allianceRetreat) - HandleGameObject(0, true, pGo); + HandleGameObject(0, true, go); else - HandleGameObject(0, false, pGo); + HandleGameObject(0, false, go); break; case 182061: - ElfGate = pGo->GetGUID(); + ElfGate = go->GetGUID(); if (hordeRetreat) - HandleGameObject(0, true, pGo); + HandleGameObject(0, true, go); else - HandleGameObject(0, false, pGo); + HandleGameObject(0, false, go); break; case GO_ANCIENT_GEM: - m_uiAncientGemGUID.push_back(pGo->GetGUID()); + m_uiAncientGemGUID.push_back(go->GetGUID()); break; } } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case 17767: RageWinterchill = pCreature->GetGUID(); break; - case 17808: Anetheron = pCreature->GetGUID(); break; - case 17888: Kazrogal = pCreature->GetGUID(); break; - case 17842: Azgalor = pCreature->GetGUID(); break; - case 17968: Archimonde = pCreature->GetGUID(); break; - case 17772: JainaProudmoore = pCreature->GetGUID(); break; - case 17852: Thrall = pCreature->GetGUID(); break; - case 17948: TyrandeWhisperwind = pCreature->GetGUID(); break; + case 17767: RageWinterchill = creature->GetGUID(); break; + case 17808: Anetheron = creature->GetGUID(); break; + case 17888: Kazrogal = creature->GetGUID(); break; + case 17842: Azgalor = creature->GetGUID(); break; + case 17968: Archimonde = creature->GetGUID(); break; + case 17772: JainaProudmoore = creature->GetGUID(); break; + case 17852: Thrall = creature->GetGUID(); break; + case 17948: TyrandeWhisperwind = creature->GetGUID(); break; } } @@ -188,12 +188,12 @@ public: if (ArchiYell)break; ArchiYell = true; - Creature* pCreature = instance->GetCreature(Azgalor); - if (pCreature) + Creature* creature = instance->GetCreature(Azgalor); + if (creature) { - Creature* pUnit = pCreature->SummonCreature(21987,pCreature->GetPositionX(),pCreature->GetPositionY(),pCreature->GetPositionZ(),0,TEMPSUMMON_TIMED_DESPAWN,10000); + Creature* pUnit = creature->SummonCreature(21987,creature->GetPositionX(),creature->GetPositionY(),creature->GetPositionZ(),0,TEMPSUMMON_TIMED_DESPAWN,10000); - Map* pMap = pCreature->GetMap(); + Map* pMap = creature->GetMap(); if (pMap->IsDungeon() && pUnit) { pUnit->SetVisible(false); 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 e5714a2bdde..2c14506e102 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 @@ -66,54 +66,54 @@ public: return false; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { case NPC_ARTHAS: - uiArthas = pCreature->GetGUID(); + uiArthas = creature->GetGUID(); break; case NPC_MEATHOOK: - uiMeathook = pCreature->GetGUID(); + uiMeathook = creature->GetGUID(); break; case NPC_SALRAMM: - uiSalramm = pCreature->GetGUID(); + uiSalramm = creature->GetGUID(); break; case NPC_EPOCH: - uiEpoch = pCreature->GetGUID(); + uiEpoch = creature->GetGUID(); break; case NPC_MAL_GANIS: - uiMalGanis = pCreature->GetGUID(); + uiMalGanis = creature->GetGUID(); break; case NPC_INFINITE: - uiInfinite = pCreature->GetGUID(); + uiInfinite = creature->GetGUID(); break; } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case GO_SHKAF_GATE: - uiShkafGate = pGo->GetGUID(); + uiShkafGate = go->GetGUID(); break; case GO_MALGANIS_GATE_1: - uiMalGanisGate1 = pGo->GetGUID(); + uiMalGanisGate1 = go->GetGUID(); break; case GO_MALGANIS_GATE_2: - uiMalGanisGate2 = pGo->GetGUID(); + uiMalGanisGate2 = go->GetGUID(); break; case GO_EXIT_GATE: - uiExitGate = pGo->GetGUID(); + uiExitGate = go->GetGUID(); if (m_auiEncounter[3] == DONE) HandleGameObject(uiExitGate,true); break; case GO_MALGANIS_CHEST_N: case GO_MALGANIS_CHEST_H: - uiMalGanisChest = pGo->GetGUID(); + uiMalGanisChest = go->GetGUID(); if (m_auiEncounter[3] == DONE) - pGo->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_INTERACT_COND); + go->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_INTERACT_COND); break; } } @@ -144,8 +144,8 @@ public: break; case DONE: HandleGameObject(uiExitGate, true); - if (GameObject *pGo = instance->GetGameObject(uiMalGanisChest)) - pGo->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_INTERACT_COND); + if (GameObject* go = instance->GetGameObject(uiMalGanisChest)) + go->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_INTERACT_COND); break; } break; diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/DarkPortal/instance_dark_portal.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/DarkPortal/instance_dark_portal.cpp index 77f82a180db..1b66ec70698 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/DarkPortal/instance_dark_portal.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/DarkPortal/instance_dark_portal.cpp @@ -130,10 +130,10 @@ public: pPlayer->SendUpdateWorldState(WORLD_STATE_BM,0); } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - if (pCreature->GetEntry() == C_MEDIVH) - MedivhGUID = pCreature->GetGUID(); + if (creature->GetEntry() == C_MEDIVH) + MedivhGUID = creature->GetGUID(); } //what other conditions to check? @@ -272,7 +272,7 @@ public: //normalize Z-level if we can, if rift is not at ground level. pos.m_positionZ = std::max(me->GetMap()->GetHeight(pos.m_positionX, pos.m_positionY, MAX_HEIGHT), me->GetMap()->GetWaterLevel(pos.m_positionX, pos.m_positionY)); - if (Creature *summon = me->SummonCreature(entry, pos, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 600000)) + if (Creature* summon = me->SummonCreature(entry, pos, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 600000)) return summon; sLog.outDebug("TSCR: Instance Dark Portal: What just happened there? No boss, no loot, no fun..."); @@ -292,7 +292,7 @@ public: CurrentRiftId = tmp; - Creature *pTemp = pMedivh->SummonCreature(C_TIME_RIFT, + Creature* pTemp = pMedivh->SummonCreature(C_TIME_RIFT, PortalLocation[tmp][0],PortalLocation[tmp][1],PortalLocation[tmp][2],PortalLocation[tmp][3], TEMPSUMMON_CORPSE_DESPAWN,0); if (pTemp) @@ -300,7 +300,7 @@ public: pTemp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); pTemp->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); - if (Creature *pBoss = SummonedPortalBoss(pTemp)) + if (Creature* pBoss = SummonedPortalBoss(pTemp)) { if (pBoss->GetEntry() == C_AEONUS) pBoss->AddThreat(pMedivh,0.0f); 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 a6916fdb2e7..ac1c2508ca8 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/instance_old_hillsbrad.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/EscapeFromDurnholdeKeep/instance_old_hillsbrad.cpp @@ -101,18 +101,18 @@ public: } } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { case THRALL_ENTRY: - ThrallGUID = pCreature->GetGUID(); + ThrallGUID = creature->GetGUID(); break; case TARETHA_ENTRY: - TarethaGUID = pCreature->GetGUID(); + TarethaGUID = creature->GetGUID(); break; case EPOCH_ENTRY: - EpochGUID = pCreature->GetGUID(); + EpochGUID = creature->GetGUID(); break; } } diff --git a/src/server/scripts/Kalimdor/OnyxiasLair/instance_onyxias_lair.cpp b/src/server/scripts/Kalimdor/OnyxiasLair/instance_onyxias_lair.cpp index c5ed6541f2a..a0d4880b5f9 100644 --- a/src/server/scripts/Kalimdor/OnyxiasLair/instance_onyxias_lair.cpp +++ b/src/server/scripts/Kalimdor/OnyxiasLair/instance_onyxias_lair.cpp @@ -67,33 +67,30 @@ public: m_uiEruptTimer = 0; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch (pCreature->GetEntry()) + switch (creature->GetEntry()) { case NPC_ONYXIA: - m_uiOnyxiasGUID = pCreature->GetGUID(); + m_uiOnyxiasGUID = creature->GetGUID(); break; } } - void OnGameObjectCreate(GameObject* pGo, bool add) + void OnGameObjectCreate(GameObject* go) { - if ((pGo->GetGOInfo()->displayId == 4392 || pGo->GetGOInfo()->displayId == 4472) && pGo->GetGOInfo()->trap.spellId == 17731) + if ((go->GetGOInfo()->displayId == 4392 || go->GetGOInfo()->displayId == 4472) && go->GetGOInfo()->trap.spellId == 17731) { - if (add) - FloorEruptionGUID[0].insert(std::make_pair(pGo->GetGUID(),0)); - else - FloorEruptionGUID[0].erase(pGo->GetGUID()); + FloorEruptionGUID[0].insert(std::make_pair(go->GetGUID(),0)); return; } - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case GO_WHELP_SPAWNER: - Position pGoPos; - pGo->GetPosition(&pGoPos); - if (Creature* pTemp = pGo->SummonCreature(NPC_WHELP,pGoPos,TEMPSUMMON_CORPSE_DESPAWN)) + Position goPos; + go->GetPosition(&goPos); + if (Creature* pTemp = go->SummonCreature(NPC_WHELP,goPos,TEMPSUMMON_CORPSE_DESPAWN)) { pTemp->SetInCombatWithZone(); ++m_uiManyWhelpsCounter; @@ -102,9 +99,18 @@ public: } } + void OnGameObjectRemove(GameObject* go) + { + if ((go->GetGOInfo()->displayId == 4392 || go->GetGOInfo()->displayId == 4472) && go->GetGOInfo()->trap.spellId == 17731) + { + FloorEruptionGUID[0].erase(go->GetGUID()); + return; + } + } + void FloorEruption(uint64 floorEruptedGUID) { - if (GameObject *pFloorEruption = instance->GetGameObject(floorEruptedGUID)) + if (GameObject* pFloorEruption = instance->GetGameObject(floorEruptedGUID)) { //THIS GOB IS A TRAP - What shall i do? =( //Cast it spell? Copyed Heigan method diff --git a/src/server/scripts/Kalimdor/RazorfenDowns/instance_razorfen_downs.cpp b/src/server/scripts/Kalimdor/RazorfenDowns/instance_razorfen_downs.cpp index 6aad9c69986..9266aa52b25 100644 --- a/src/server/scripts/Kalimdor/RazorfenDowns/instance_razorfen_downs.cpp +++ b/src/server/scripts/Kalimdor/RazorfenDowns/instance_razorfen_downs.cpp @@ -99,14 +99,14 @@ public: OUT_LOAD_INST_DATA_COMPLETE; } - void OnGameObjectCreate(GameObject* pGo, bool /*bAdd*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case GO_GONG: - uiGongGUID = pGo->GetGUID(); + uiGongGUID = go->GetGUID(); if (m_auiEncounter[0] == DONE) - pGo->SetFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); + go->SetFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); break; default: break; @@ -123,19 +123,19 @@ public: { case 9: case 14: - if (GameObject* pGo = instance->GetGameObject(uiGongGUID)) - pGo->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); + if (GameObject* go = instance->GetGameObject(uiGongGUID)) + go->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); break; case 1: case 10: case 16: { - GameObject* pGo = instance->GetGameObject(uiGongGUID); + GameObject* go = instance->GetGameObject(uiGongGUID); - if (!pGo) + if (!go) return; - pGo->SetFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); + go->SetFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); uint32 uiCreature = 0; uint8 uiSummonTimes = 0; @@ -158,17 +158,17 @@ public: } - if (Creature* pCreature = pGo->SummonCreature(uiCreature,2502.635f,844.140f,46.896f,0.633f)) + if (Creature* creature = go->SummonCreature(uiCreature,2502.635f,844.140f,46.896f,0.633f)) { if (uiGongWaves == 10 || uiGongWaves == 1) { for (uint8 i = 0; i < uiSummonTimes; ++i) { - if (Creature* pSummon = pGo->SummonCreature(uiCreature,2502.635f + float(irand(-5,5)),844.140f + float(irand(-5,5)),46.896f,0.633f)) + if (Creature* pSummon = go->SummonCreature(uiCreature,2502.635f + float(irand(-5,5)),844.140f + float(irand(-5,5)),46.896f,0.633f)) pSummon->GetMotionMaster()->MovePoint(0,2533.479f + float(irand(-5,5)),870.020f + float(irand(-5,5)),47.678f); } } - pCreature->GetMotionMaster()->MovePoint(0,2533.479f + float(irand(-5,5)),870.020f + float(irand(-5,5)),47.678f); + creature->GetMotionMaster()->MovePoint(0,2533.479f + float(irand(-5,5)),870.020f + float(irand(-5,5)),47.678f); } break; } diff --git a/src/server/scripts/Kalimdor/RazorfenKraul/instance_razorfen_kraul.cpp b/src/server/scripts/Kalimdor/RazorfenKraul/instance_razorfen_kraul.cpp index 4a6e5573c91..3fe930b2cc8 100644 --- a/src/server/scripts/Kalimdor/RazorfenKraul/instance_razorfen_kraul.cpp +++ b/src/server/scripts/Kalimdor/RazorfenKraul/instance_razorfen_kraul.cpp @@ -69,11 +69,11 @@ public: return NULL; } - void OnGameObjectCreate(GameObject* pGo, bool /*apply*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { - case 21099: DoorWardGUID = pGo->GetGUID(); break; + case 21099: DoorWardGUID = go->GetGUID(); break; } } 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 10dea9ef9fe..8b1e1a6e483 100644 --- a/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/instance_ruins_of_ahnqiraj.cpp +++ b/src/server/scripts/Kalimdor/RuinsOfAhnQiraj/instance_ruins_of_ahnqiraj.cpp @@ -80,27 +80,27 @@ public: return false; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch (pCreature->GetEntry()) + switch (creature->GetEntry()) { case CREATURE_KURINAXX: - uiKurinaxx = pCreature->GetGUID(); + uiKurinaxx = creature->GetGUID(); break; case CREATURE_RAJAXX: - uiRajaxx = pCreature->GetGUID(); + uiRajaxx = creature->GetGUID(); break; case CREATURE_MOAM: - uiMoam = pCreature->GetGUID(); + uiMoam = creature->GetGUID(); break; case CREATURE_BURU: - uiBuru = pCreature->GetGUID(); + uiBuru = creature->GetGUID(); break; case CREATURE_AYAMISS: - uiAyamiss = pCreature->GetGUID(); + uiAyamiss = creature->GetGUID(); break; case CREATURE_OSSIRIAN: - uiOssirian = pCreature->GetGUID(); + uiOssirian = creature->GetGUID(); break; } } 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 132719cb083..84ef4d86485 100644 --- a/src/server/scripts/Kalimdor/TempleOfAhnQiraj/instance_temple_of_ahnqiraj.cpp +++ b/src/server/scripts/Kalimdor/TempleOfAhnQiraj/instance_temple_of_ahnqiraj.cpp @@ -71,15 +71,15 @@ public: CthunPhase = 0; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch (pCreature->GetEntry()) + switch (creature->GetEntry()) { - case 15263: SkeramGUID = pCreature->GetGUID(); break; - case 15544: VemGUID = pCreature->GetGUID(); break; - case 15511: KriGUID = pCreature->GetGUID(); break; - case 15276: VeklorGUID = pCreature->GetGUID(); break; - case 15275: VeknilashGUID = pCreature->GetGUID(); break; + case 15263: SkeramGUID = creature->GetGUID(); break; + case 15544: VemGUID = creature->GetGUID(); break; + case 15511: KriGUID = creature->GetGUID(); break; + case 15276: VeklorGUID = creature->GetGUID(); break; + case 15275: VeknilashGUID = creature->GetGUID(); break; } } diff --git a/src/server/scripts/Kalimdor/WailingCaverns/instance_wailing_caverns.cpp b/src/server/scripts/Kalimdor/WailingCaverns/instance_wailing_caverns.cpp index 12d6bd61247..e783ec18df0 100644 --- a/src/server/scripts/Kalimdor/WailingCaverns/instance_wailing_caverns.cpp +++ b/src/server/scripts/Kalimdor/WailingCaverns/instance_wailing_caverns.cpp @@ -55,10 +55,10 @@ public: NaralexGUID = 0; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - if (pCreature->GetEntry() == DATA_NARALEX) - NaralexGUID = pCreature->GetGUID(); + if (creature->GetEntry() == DATA_NARALEX) + NaralexGUID = creature->GetGUID(); } void SetData(uint32 type, uint32 data) diff --git a/src/server/scripts/Kalimdor/ZulFarrak/instance_zulfarrak.cpp b/src/server/scripts/Kalimdor/ZulFarrak/instance_zulfarrak.cpp index 2b8b590022d..89a57254406 100644 --- a/src/server/scripts/Kalimdor/ZulFarrak/instance_zulfarrak.cpp +++ b/src/server/scripts/Kalimdor/ZulFarrak/instance_zulfarrak.cpp @@ -120,48 +120,48 @@ public: GahzRillaEncounter = NOT_STARTED; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch (pCreature->GetEntry()) + switch (creature->GetEntry()) { case ENTRY_ZUMRAH: - ZumrahGUID = pCreature->GetGUID(); + ZumrahGUID = creature->GetGUID(); break; case ENTRY_BLY: - BlyGUID = pCreature->GetGUID(); - pCreature->SetReactState(REACT_PASSIVE); // starts out passive (in a cage) + BlyGUID = creature->GetGUID(); + creature->SetReactState(REACT_PASSIVE); // starts out passive (in a cage) break; case ENTRY_RAVEN: - RavenGUID = pCreature->GetGUID(); - pCreature->SetReactState(REACT_PASSIVE);// starts out passive (in a cage) + RavenGUID = creature->GetGUID(); + creature->SetReactState(REACT_PASSIVE);// starts out passive (in a cage) break; case ENTRY_ORO: - OroGUID = pCreature->GetGUID(); - pCreature->SetReactState(REACT_PASSIVE);// starts out passive (in a cage) + OroGUID = creature->GetGUID(); + creature->SetReactState(REACT_PASSIVE);// starts out passive (in a cage) break; case ENTRY_WEEGLI: - WeegliGUID = pCreature->GetGUID(); - pCreature->SetReactState(REACT_PASSIVE);// starts out passive (in a cage) + WeegliGUID = creature->GetGUID(); + creature->SetReactState(REACT_PASSIVE);// starts out passive (in a cage) break; case ENTRY_MURTA: - MurtaGUID = pCreature->GetGUID(); - pCreature->SetReactState(REACT_PASSIVE);// starts out passive (in a cage) + MurtaGUID = creature->GetGUID(); + creature->SetReactState(REACT_PASSIVE);// starts out passive (in a cage) break; case NPC_GAHZRILLA: if (GahzRillaEncounter >= IN_PROGRESS) - pCreature->DisappearAndDie(); + creature->DisappearAndDie(); else GahzRillaEncounter = IN_PROGRESS; break; } } - void OnGameObjectCreate(GameObject* pGo, bool /*apply*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case GO_END_DOOR: - EndDoorGUID = pGo->GetGUID(); + EndDoorGUID = go->GetGUID(); break; } } 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 ace34710b4c..c7d8c118289 100644 --- a/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/instance_azjol_nerub.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/AzjolNerub/instance_azjol_nerub.cpp @@ -69,36 +69,36 @@ public: return false; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case 28684: uiKrikthir = pCreature->GetGUID(); break; - case 28921: uiHadronox = pCreature->GetGUID(); break; - case 29120: uiAnubarak = pCreature->GetGUID(); break; - case 28730: uiWatcherGashra = pCreature->GetGUID(); break; - case 28731: uiWatcherSilthik = pCreature->GetGUID(); break; - case 28729: uiWatcherNarjil = pCreature->GetGUID(); break; + case 28684: uiKrikthir = creature->GetGUID(); break; + case 28921: uiHadronox = creature->GetGUID(); break; + case 29120: uiAnubarak = creature->GetGUID(); break; + case 28730: uiWatcherGashra = creature->GetGUID(); break; + case 28731: uiWatcherSilthik = creature->GetGUID(); break; + case 28729: uiWatcherNarjil = creature->GetGUID(); break; } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch (pGo->GetEntry()) + switch (go->GetEntry()) { case 192395: - uiKrikthirDoor = pGo->GetGUID(); + uiKrikthirDoor = go->GetGUID(); if (auiEncounter[0] == DONE) - HandleGameObject(NULL,true,pGo); + HandleGameObject(NULL,true,go); break; case 192396: - uiAnubarakDoor[0] = pGo->GetGUID(); + uiAnubarakDoor[0] = go->GetGUID(); break; case 192397: - uiAnubarakDoor[1] = pGo->GetGUID(); + uiAnubarakDoor[1] = go->GetGUID(); break; case 192398: - uiAnubarakDoor[2] = pGo->GetGUID(); + uiAnubarakDoor[2] = go->GetGUID(); break; } } diff --git a/src/server/scripts/Northrend/AzjolNerub/ahnkahet/instance_ahnkahet.cpp b/src/server/scripts/Northrend/AzjolNerub/ahnkahet/instance_ahnkahet.cpp index 1a72efe6e79..54a0e906b76 100644 --- a/src/server/scripts/Northrend/AzjolNerub/ahnkahet/instance_ahnkahet.cpp +++ b/src/server/scripts/Northrend/AzjolNerub/ahnkahet/instance_ahnkahet.cpp @@ -94,43 +94,43 @@ public: return false; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case 29309: Elder_Nadox = pCreature->GetGUID(); break; - case 29308: Prince_Taldaram = pCreature->GetGUID(); break; - case 29310: Jedoga_Shadowseeker = pCreature->GetGUID(); break; - case 29311: Herald_Volazj = pCreature->GetGUID(); break; - case 30258: Amanitar = pCreature->GetGUID(); break; - case 30114: InitiandGUIDs.insert(pCreature->GetGUID()); break; + case 29309: Elder_Nadox = creature->GetGUID(); break; + case 29308: Prince_Taldaram = creature->GetGUID(); break; + case 29310: Jedoga_Shadowseeker = creature->GetGUID(); break; + case 29311: Herald_Volazj = creature->GetGUID(); break; + case 30258: Amanitar = creature->GetGUID(); break; + case 30114: InitiandGUIDs.insert(creature->GetGUID()); break; } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { - case 193564: Prince_TaldaramPlatform = pGo->GetGUID(); - if (m_auiEncounter[1] == DONE) HandleGameObject(NULL,true,pGo); break; - case 193093: Prince_TaldaramSpheres[0] = pGo->GetGUID(); + case 193564: Prince_TaldaramPlatform = go->GetGUID(); + if (m_auiEncounter[1] == DONE) HandleGameObject(NULL,true,go); break; + case 193093: Prince_TaldaramSpheres[0] = go->GetGUID(); if (spheres[0] == IN_PROGRESS) { - pGo->SetGoState(GO_STATE_ACTIVE); - pGo->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); + go->SetGoState(GO_STATE_ACTIVE); + go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); } - else pGo->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); + else go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); break; - case 193094: Prince_TaldaramSpheres[1] = pGo->GetGUID(); + case 193094: Prince_TaldaramSpheres[1] = go->GetGUID(); if (spheres[1] == IN_PROGRESS) { - pGo->SetGoState(GO_STATE_ACTIVE); - pGo->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); + go->SetGoState(GO_STATE_ACTIVE); + go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); } - else pGo->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); + else go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); break; - case 192236: Prince_TaldaramGate = pGo->GetGUID(); // Web gate past Prince Taldaram - if (m_auiEncounter[1] == DONE)HandleGameObject(NULL,true,pGo);break; + case 192236: Prince_TaldaramGate = go->GetGUID(); // Web gate past Prince Taldaram + if (m_auiEncounter[1] == DONE)HandleGameObject(NULL,true,go);break; } } 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 900113b3017..ba6fcfdae12 100644 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_grand_champions.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheChampion/boss_grand_champions.cpp @@ -78,6 +78,7 @@ enum eSeat SEAT_ID_0 = 0 }; +/* struct Point { float x,y,z; @@ -89,7 +90,7 @@ const Point MovementPoint[] = {747.96f,620.29f,411.09f}, {750.23f,618.35f,411.09f} }; - +*/ void AggroAllPlayers(Creature* pTemp) { Map::PlayerList const &PlList = pTemp->GetMap()->GetPlayers(); 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 8d2910db245..7fd62fc13f7 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 @@ -99,7 +99,7 @@ public: return false; } - void OnCreatureCreate(Creature* pCreature, bool /*bAdd*/) + void OnCreatureCreate(Creature* creature) { Map::PlayerList const &players = instance->GetPlayers(); uint32 TeamInInstance = 0; @@ -110,56 +110,56 @@ public: TeamInInstance = pPlayer->GetTeam(); } - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { // Champions case VEHICLE_MOKRA_SKILLCRUSHER_MOUNT: if (TeamInInstance == HORDE) - pCreature->UpdateEntry(VEHICLE_MARSHAL_JACOB_ALERIUS_MOUNT, ALLIANCE); + creature->UpdateEntry(VEHICLE_MARSHAL_JACOB_ALERIUS_MOUNT, ALLIANCE); break; case VEHICLE_ERESSEA_DAWNSINGER_MOUNT: if (TeamInInstance == HORDE) - pCreature->UpdateEntry(VEHICLE_AMBROSE_BOLTSPARK_MOUNT, ALLIANCE); + creature->UpdateEntry(VEHICLE_AMBROSE_BOLTSPARK_MOUNT, ALLIANCE); break; case VEHICLE_RUNOK_WILDMANE_MOUNT: if (TeamInInstance == HORDE) - pCreature->UpdateEntry(VEHICLE_COLOSOS_MOUNT, ALLIANCE); + creature->UpdateEntry(VEHICLE_COLOSOS_MOUNT, ALLIANCE); break; case VEHICLE_ZUL_TORE_MOUNT: if (TeamInInstance == HORDE) - pCreature->UpdateEntry(VEHICLE_EVENSONG_MOUNT, ALLIANCE); + creature->UpdateEntry(VEHICLE_EVENSONG_MOUNT, ALLIANCE); break; case VEHICLE_DEATHSTALKER_VESCERI_MOUNT: if (TeamInInstance == HORDE) - pCreature->UpdateEntry(VEHICLE_LANA_STOUTHAMMER_MOUNT, ALLIANCE); + creature->UpdateEntry(VEHICLE_LANA_STOUTHAMMER_MOUNT, ALLIANCE); break; // Coliseum Announcer || Just NPC_JAEREN must be spawned. case NPC_JAEREN: - uiAnnouncerGUID = pCreature->GetGUID(); + uiAnnouncerGUID = creature->GetGUID(); if (TeamInInstance == ALLIANCE) - pCreature->UpdateEntry(NPC_ARELAS,ALLIANCE); + creature->UpdateEntry(NPC_ARELAS,ALLIANCE); break; case VEHICLE_ARGENT_WARHORSE: case VEHICLE_ARGENT_BATTLEWORG: - VehicleList.push_back(pCreature->GetGUID()); + VehicleList.push_back(creature->GetGUID()); break; case NPC_EADRIC: case NPC_PALETRESS: - uiArgentChampionGUID = pCreature->GetGUID(); + uiArgentChampionGUID = creature->GetGUID(); break; } } - void OnGameObjectCreate(GameObject* pGO, bool /*bAdd*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGO->GetEntry()) + switch(go->GetEntry()) { case GO_MAIN_GATE: - uiMainGateGUID = pGO->GetGUID(); + uiMainGateGUID = go->GetGUID(); break; case GO_CHAMPIONS_LOOT: case GO_CHAMPIONS_LOOT_H: - uiChampionLootGUID = pGO->GetGUID(); + uiChampionLootGUID = go->GetGUID(); break; } } 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 372cb70572b..3822265b2f6 100755 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_faction_champions.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_faction_champions.cpp @@ -275,9 +275,7 @@ struct boss_faction_championsAI : public ScriptedAI void UpdateThreat() { std::list<HostileReference*> const& tList = me->getThreatManager().getThreatList(); - std::list<HostileReference*>::const_iterator itr; - bool empty = true; - for (itr = tList.begin(); itr!=tList.end(); ++itr) + for (std::list<HostileReference*>::const_iterator itr = tList.begin(); itr != tList.end(); ++itr) { Unit* pUnit = Unit::GetUnit((*me), (*itr)->getUnitGuid()); if (pUnit && me->getThreatManager().getThreat(pUnit)) @@ -287,7 +285,6 @@ struct boss_faction_championsAI : public ScriptedAI float threat = CalculateThreat(me->GetDistance2d(pUnit), (float)pUnit->GetArmor(), pUnit->GetHealth()); me->getThreatManager().modifyThreatPercent(pUnit, -100); me->AddThreat(pUnit, 1000000.0f * threat); - empty = false; } } } 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 0f426a3d959..34bee4908d8 100755 --- a/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_northrend_beasts.cpp +++ b/src/server/scripts/Northrend/CrusadersColiseum/TrialOfTheCrusader/boss_northrend_beasts.cpp @@ -452,6 +452,7 @@ struct boss_jormungarAI : public ScriptedAI case 4: m_uiStage = 5; m_uiSubmergeTimer = 5*IN_MILLISECONDS; + break; default: m_uiStage = 7; } 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 41368d86415..eb1c1881927 100755 --- 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 @@ -149,63 +149,63 @@ public: void OpenDoor(uint64 guid) { if (!guid) return; - GameObject* pGo = instance->GetGameObject(guid); - if (pGo) pGo->SetGoState(GO_STATE_ACTIVE_ALTERNATIVE); + GameObject* go = instance->GetGameObject(guid); + if (go) go->SetGoState(GO_STATE_ACTIVE_ALTERNATIVE); } void CloseDoor(uint64 guid) { if (!guid) return; - GameObject* pGo = instance->GetGameObject(guid); - if (pGo) pGo->SetGoState(GO_STATE_READY); + GameObject* go = instance->GetGameObject(guid); + if (go) go->SetGoState(GO_STATE_READY); } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case NPC_BARRENT: m_uiBarrentGUID = pCreature->GetGUID(); break; - case NPC_TIRION: m_uiTirionGUID = pCreature->GetGUID(); break; - case NPC_FIZZLEBANG: m_uiFizzlebangGUID = pCreature->GetGUID(); break; - case NPC_GARROSH: m_uiGarroshGUID = pCreature->GetGUID(); break; - case NPC_VARIAN: m_uiVarianGUID = pCreature->GetGUID(); break; - - case NPC_GORMOK: m_uiGormokGUID = pCreature->GetGUID(); break; - case NPC_ACIDMAW: m_uiAcidmawGUID = pCreature->GetGUID(); break; - case NPC_DREADSCALE: m_uiDreadscaleGUID = pCreature->GetGUID(); break; - case NPC_ICEHOWL: m_uiIcehowlGUID = pCreature->GetGUID(); break; - case NPC_JARAXXUS: m_uiJaraxxusGUID = pCreature->GetGUID(); break; - case NPC_CHAMPIONS_CONTROLLER: m_uiChampionsControllerGUID = pCreature->GetGUID(); break; - case NPC_DARKBANE: m_uiDarkbaneGUID = pCreature->GetGUID(); break; - case NPC_LIGHTBANE: m_uiLightbaneGUID = pCreature->GetGUID(); break; - case NPC_ANUBARAK: m_uiAnubarakGUID = pCreature->GetGUID(); break; + case NPC_BARRENT: m_uiBarrentGUID = creature->GetGUID(); break; + case NPC_TIRION: m_uiTirionGUID = creature->GetGUID(); break; + case NPC_FIZZLEBANG: m_uiFizzlebangGUID = creature->GetGUID(); break; + case NPC_GARROSH: m_uiGarroshGUID = creature->GetGUID(); break; + case NPC_VARIAN: m_uiVarianGUID = creature->GetGUID(); break; + + case NPC_GORMOK: m_uiGormokGUID = creature->GetGUID(); break; + case NPC_ACIDMAW: m_uiAcidmawGUID = creature->GetGUID(); break; + case NPC_DREADSCALE: m_uiDreadscaleGUID = creature->GetGUID(); break; + case NPC_ICEHOWL: m_uiIcehowlGUID = creature->GetGUID(); break; + case NPC_JARAXXUS: m_uiJaraxxusGUID = creature->GetGUID(); break; + case NPC_CHAMPIONS_CONTROLLER: m_uiChampionsControllerGUID = creature->GetGUID(); break; + case NPC_DARKBANE: m_uiDarkbaneGUID = creature->GetGUID(); break; + case NPC_LIGHTBANE: m_uiLightbaneGUID = creature->GetGUID(); break; + case NPC_ANUBARAK: m_uiAnubarakGUID = creature->GetGUID(); break; } } - void OnGameObjectCreate(GameObject* pGO, bool /*bAdd*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGO->GetEntry()) + switch(go->GetEntry()) { case GO_CRUSADERS_CACHE_10: if (instance->GetSpawnMode() == RAID_DIFFICULTY_10MAN_NORMAL) - m_uiCrusadersCacheGUID = pGO->GetGUID(); + m_uiCrusadersCacheGUID = go->GetGUID(); break; case GO_CRUSADERS_CACHE_25: if (instance->GetSpawnMode() == RAID_DIFFICULTY_25MAN_NORMAL) - m_uiCrusadersCacheGUID = pGO->GetGUID(); + m_uiCrusadersCacheGUID = go->GetGUID(); break; case GO_CRUSADERS_CACHE_10_H: if (instance->GetSpawnMode() == RAID_DIFFICULTY_10MAN_HEROIC) - m_uiCrusadersCacheGUID = pGO->GetGUID(); + m_uiCrusadersCacheGUID = go->GetGUID(); break; case GO_CRUSADERS_CACHE_25_H: if (instance->GetSpawnMode() == RAID_DIFFICULTY_25MAN_HEROIC) - m_uiCrusadersCacheGUID = pGO->GetGUID(); + m_uiCrusadersCacheGUID = go->GetGUID(); break; - case GO_ARGENT_COLISEUM_FLOOR: m_uiFloorGUID = pGO->GetGUID(); break; - case GO_MAIN_GATE_DOOR: m_uiMainGateDoorGUID = pGO->GetGUID(); break; - case GO_EAST_PORTCULLIS: m_uiEastPortcullisGUID = pGO->GetGUID(); break; - case GO_WEB_DOOR: m_uiWebDoorGUID = pGO->GetGUID(); break; + case GO_ARGENT_COLISEUM_FLOOR: m_uiFloorGUID = go->GetGUID(); break; + case GO_MAIN_GATE_DOOR: m_uiMainGateDoorGUID = go->GetGUID(); break; + case GO_EAST_PORTCULLIS: m_uiEastPortcullisGUID = go->GetGUID(); break; + case GO_WEB_DOOR: m_uiWebDoorGUID = go->GetGUID(); break; case GO_TRIBUTE_CHEST_10H_25: case GO_TRIBUTE_CHEST_10H_45: @@ -215,7 +215,7 @@ public: case GO_TRIBUTE_CHEST_25H_45: case GO_TRIBUTE_CHEST_25H_50: case GO_TRIBUTE_CHEST_25H_99: - m_uiTributeChestGUID = pGO->GetGUID(); break; + m_uiTributeChestGUID = go->GetGUID(); break; } } 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 9ee754b4a56..d7282522838 100644 --- a/src/server/scripts/Northrend/DraktharonKeep/instance_drak_tharon_keep.cpp +++ b/src/server/scripts/Northrend/DraktharonKeep/instance_drak_tharon_keep.cpp @@ -88,40 +88,40 @@ public: return false; } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case GO_NOVOS_CRYSTAL_1: - uiNovosCrystal1 = pGo->GetGUID(); + uiNovosCrystal1 = go->GetGUID(); break; case GO_NOVOS_CRYSTAL_2: - uiNovosCrystal2 = pGo->GetGUID(); + uiNovosCrystal2 = go->GetGUID(); break; case GO_NOVOS_CRYSTAL_3: - uiNovosCrystal3 = pGo->GetGUID(); + uiNovosCrystal3 = go->GetGUID(); break; case GO_NOVOS_CRYSTAL_4: - uiNovosCrystal4 = pGo->GetGUID(); + uiNovosCrystal4 = go->GetGUID(); break; } } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { case NPC_TROLLGORE: - uiTrollgore = pCreature->GetGUID(); + uiTrollgore = creature->GetGUID(); break; case NPC_NOVOS: - uiNovos = pCreature->GetGUID(); + uiNovos = creature->GetGUID(); break; case NPC_KING_DRED: - uiDred = pCreature->GetGUID(); + uiDred = creature->GetGUID(); break; case NPC_THARON_JA: - uiTharonJa = pCreature->GetGUID(); + uiTharonJa = creature->GetGUID(); break; } } 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 1a48b1f4cc6..f9cb4a04db6 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 @@ -41,7 +41,7 @@ class instance_forge_of_souls : public InstanceMapScript teamInInstance = 0; } - void OnCreatureCreate(Creature* creature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { Map::PlayerList const &players = instance->GetPlayers(); if (!players.isEmpty()) 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 f86878bbc3f..73239e18028 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 @@ -150,67 +150,61 @@ public: uiEncounter[i] = NOT_STARTED; } - void OnCreatureCreate(Creature* pCreature, bool add) + void OnCreatureCreate(Creature* creature) { - if (!add) - return; - Map::PlayerList const &players = instance->GetPlayers(); if (!players.isEmpty()) if (Player* pPlayer = players.begin()->getSource()) uiTeamInInstance = pPlayer->GetTeam(); - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { case NPC_FALRIC: - uiFalric = pCreature->GetGUID(); + uiFalric = creature->GetGUID(); break; case NPC_MARWYN: - uiMarwyn = pCreature->GetGUID(); + uiMarwyn = creature->GetGUID(); break; case NPC_LICH_KING_EVENT: - uiLichKingEvent = pCreature->GetGUID(); + uiLichKingEvent = creature->GetGUID(); break; case NPC_JAINA_PART1: - uiJainaPart1 = pCreature->GetGUID(); + uiJainaPart1 = creature->GetGUID(); break; case NPC_SYLVANAS_PART1: - uiSylvanasPart1 = pCreature->GetGUID(); + uiSylvanasPart1 = creature->GetGUID(); break; } } - void OnGameObjectCreate(GameObject* pGo, bool add) + void OnGameObjectCreate(GameObject* go) { - if (!add) - return; - // TODO: init state depending on encounters - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case GO_FROSTMOURNE: - uiFrostmourne = pGo->GetGUID(); - pGo->SetFlag(GAMEOBJECT_FLAGS,GO_FLAG_INTERACT_COND); - HandleGameObject(0, false, pGo); + uiFrostmourne = go->GetGUID(); + go->SetFlag(GAMEOBJECT_FLAGS,GO_FLAG_INTERACT_COND); + HandleGameObject(0, false, go); break; case GO_FROSTMOURNE_ALTAR: - uiFrostmourneAltar = pGo->GetGUID(); - pGo->SetFlag(GAMEOBJECT_FLAGS,GO_FLAG_INTERACT_COND); - HandleGameObject(0, true, pGo); + uiFrostmourneAltar = go->GetGUID(); + go->SetFlag(GAMEOBJECT_FLAGS,GO_FLAG_INTERACT_COND); + HandleGameObject(0, true, go); break; case GO_FRONT_DOOR: - uiFrontDoor = pGo->GetGUID(); - pGo->SetFlag(GAMEOBJECT_FLAGS,GO_FLAG_INTERACT_COND); - HandleGameObject(0, true, pGo); + uiFrontDoor = go->GetGUID(); + go->SetFlag(GAMEOBJECT_FLAGS,GO_FLAG_INTERACT_COND); + HandleGameObject(0, true, go); break; case GO_ARTHAS_DOOR: - uiArthasDoor = pGo->GetGUID(); - pGo->SetFlag(GAMEOBJECT_FLAGS,GO_FLAG_INTERACT_COND); + uiArthasDoor = go->GetGUID(); + go->SetFlag(GAMEOBJECT_FLAGS,GO_FLAG_INTERACT_COND); if (uiEncounter[1] == DONE) - HandleGameObject(0, true, pGo); + HandleGameObject(0, true, go); else - HandleGameObject(0, false, pGo); + HandleGameObject(0, false, go); break; } } @@ -333,13 +327,13 @@ public: case 2: case 3: case 4: - if (Creature *pFalric = instance->GetCreature(uiFalric)) + if (Creature* pFalric = instance->GetCreature(uiFalric)) SpawnWave(pFalric); break; case 5: if (GetData(DATA_FALRIC_EVENT) == DONE) events.ScheduleEvent(EVENT_NEXT_WAVE, 10000); - else if (Creature *pFalric = instance->GetCreature(uiFalric)) + else if (Creature* pFalric = instance->GetCreature(uiFalric)) if (pFalric->AI()) pFalric->AI()->DoAction(ACTION_ENTER_COMBAT); break; @@ -347,12 +341,12 @@ public: case 7: case 8: case 9: - if (Creature *pMarwyn = instance->GetCreature(uiMarwyn)) + if (Creature* pMarwyn = instance->GetCreature(uiMarwyn)) SpawnWave(pMarwyn); break; case 10: if (GetData(DATA_MARWYN_EVENT) != DONE) // wave should not have been started if DONE. Check anyway to avoid bug exploit! - if (Creature *pMarwyn = instance->GetCreature(uiMarwyn)) + if (Creature* pMarwyn = instance->GetCreature(uiMarwyn)) if (pMarwyn->AI()) pMarwyn->AI()->DoAction(ACTION_ENTER_COMBAT); break; @@ -383,7 +377,7 @@ public: } // spawn a wave on behalf of the summoner. - void SpawnWave(Creature *pSummoner) + void SpawnWave(Creature* pSummoner) { uint32 index; 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 177b2d2d55e..a5d691768c0 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 @@ -72,7 +72,7 @@ public: return false; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { Map::PlayerList const &players = instance->GetPlayers(); @@ -82,57 +82,57 @@ public: uiTeamInInstance = pPlayer->GetTeam(); } - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { case CREATURE_KRICK: - uiKrick = pCreature->GetGUID(); + uiKrick = creature->GetGUID(); break; case CREATURE_ICK: - uiIck = pCreature->GetGUID(); + uiIck = creature->GetGUID(); break; case CREATURE_GARFROST: - uiGarfrost = pCreature->GetGUID(); + uiGarfrost = creature->GetGUID(); break; case CREATURE_TYRANNUS: - uiTyrannus = pCreature->GetGUID(); + uiTyrannus = creature->GetGUID(); break; case CREATURE_RIMEFANG: - uiRimefang = pCreature->GetGUID(); + uiRimefang = creature->GetGUID(); break; case NPC_SYLVANAS_PART1: if (uiTeamInInstance == ALLIANCE) - pCreature->UpdateEntry(NPC_JAINA_PART1, ALLIANCE); - uiJainaOrSylvanas1 = pCreature->GetGUID(); + creature->UpdateEntry(NPC_JAINA_PART1, ALLIANCE); + uiJainaOrSylvanas1 = creature->GetGUID(); break; case NPC_SYLVANAS_PART2: if (uiTeamInInstance == ALLIANCE) - pCreature->UpdateEntry(NPC_JAINA_PART2, ALLIANCE); - uiJainaOrSylvanas2 = pCreature->GetGUID(); + creature->UpdateEntry(NPC_JAINA_PART2, ALLIANCE); + uiJainaOrSylvanas2 = creature->GetGUID(); break; case NPC_KILARA: if (uiTeamInInstance == ALLIANCE) - pCreature->UpdateEntry(NPC_ELANDRA, ALLIANCE); + creature->UpdateEntry(NPC_ELANDRA, ALLIANCE); break; case NPC_KORALEN: if (uiTeamInInstance == ALLIANCE) - pCreature->UpdateEntry(NPC_KORLAEN, ALLIANCE); + creature->UpdateEntry(NPC_KORLAEN, ALLIANCE); break; case NPC_CHAMPION_1_HORDE: if (uiTeamInInstance == ALLIANCE) - pCreature->UpdateEntry(NPC_CHAMPION_1_ALLIANCE, ALLIANCE); + creature->UpdateEntry(NPC_CHAMPION_1_ALLIANCE, ALLIANCE); break; case NPC_CHAMPION_2_HORDE: if (uiTeamInInstance == ALLIANCE) - pCreature->UpdateEntry(NPC_CHAMPION_2_ALLIANCE, ALLIANCE); + creature->UpdateEntry(NPC_CHAMPION_2_ALLIANCE, ALLIANCE); break; case NPC_CHAMPION_3_HORDE: // No 3rd set for Alliance? if (uiTeamInInstance == ALLIANCE) - pCreature->UpdateEntry(NPC_CHAMPION_2_ALLIANCE, ALLIANCE); + creature->UpdateEntry(NPC_CHAMPION_2_ALLIANCE, ALLIANCE); break; } } diff --git a/src/server/scripts/Northrend/Gundrak/instance_gundrak.cpp b/src/server/scripts/Northrend/Gundrak/instance_gundrak.cpp index 82b7a5d3519..2610a1d0923 100644 --- a/src/server/scripts/Northrend/Gundrak/instance_gundrak.cpp +++ b/src/server/scripts/Northrend/Gundrak/instance_gundrak.cpp @@ -137,115 +137,115 @@ public: return false; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case CREATURE_SLAD_RAN: uiSladRan = pCreature->GetGUID(); break; - case CREATURE_MOORABI: uiMoorabi = pCreature->GetGUID(); break; - case CREATURE_GALDARAH: uiGalDarah = pCreature->GetGUID(); break; - case CREATURE_DRAKKARICOLOSSUS: uiDrakkariColossus = pCreature->GetGUID(); break; - case CREATURE_ECK: uiEckTheFerocious = pCreature->GetGUID(); break; + case CREATURE_SLAD_RAN: uiSladRan = creature->GetGUID(); break; + case CREATURE_MOORABI: uiMoorabi = creature->GetGUID(); break; + case CREATURE_GALDARAH: uiGalDarah = creature->GetGUID(); break; + case CREATURE_DRAKKARICOLOSSUS: uiDrakkariColossus = creature->GetGUID(); break; + case CREATURE_ECK: uiEckTheFerocious = creature->GetGUID(); break; case CREATURE_RUIN_DWELLER: - if (pCreature->isAlive()) - DwellerGUIDs.insert(pCreature->GetGUID()); + if (creature->isAlive()) + DwellerGUIDs.insert(creature->GetGUID()); break; } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case 192518: - uiSladRanAltar = pGo->GetGUID(); + uiSladRanAltar = go->GetGUID(); // Make sure that they start out as unusuable - pGo->SetFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); + go->SetFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); if (m_auiEncounter[0] == DONE) { if (uiSladRanStatueState == GO_STATE_ACTIVE) - pGo->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); + go->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); else { ++phase; - pGo->SetGoState(GO_STATE_ACTIVE); + go->SetGoState(GO_STATE_ACTIVE); } } break; case 192519: - uiMoorabiAltar = pGo->GetGUID(); + uiMoorabiAltar = go->GetGUID(); // Make sure that they start out as unusuable - pGo->SetFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); + go->SetFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); if (m_auiEncounter[0] == DONE) { if (uiMoorabiStatueState == GO_STATE_ACTIVE) - pGo->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); + go->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); else { ++phase; - pGo->SetGoState(GO_STATE_ACTIVE); + go->SetGoState(GO_STATE_ACTIVE); } } break; case 192520: - uiDrakkariColossusAltar = pGo->GetGUID(); + uiDrakkariColossusAltar = go->GetGUID(); // Make sure that they start out as unusuable - pGo->SetFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); + go->SetFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); if (m_auiEncounter[0] == DONE) { if (uiDrakkariColossusStatueState == GO_STATE_ACTIVE) - pGo->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); + go->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); else { ++phase; - pGo->SetGoState(GO_STATE_ACTIVE); + go->SetGoState(GO_STATE_ACTIVE); } } break; case 192564: - uiSladRanStatue = pGo->GetGUID(); - pGo->SetGoState(uiSladRanStatueState); + uiSladRanStatue = go->GetGUID(); + go->SetGoState(uiSladRanStatueState); break; case 192565: - uiMoorabiStatue = pGo->GetGUID(); - pGo->SetGoState(uiMoorabiStatueState); + uiMoorabiStatue = go->GetGUID(); + go->SetGoState(uiMoorabiStatueState); break; case 192566: - uiGalDarahStatue = pGo->GetGUID(); - pGo->SetGoState(uiGalDarahStatueState); + uiGalDarahStatue = go->GetGUID(); + go->SetGoState(uiGalDarahStatueState); break; case 192567: - uiDrakkariColossusStatue = pGo->GetGUID(); - pGo->SetGoState(uiDrakkariColossusStatueState); + uiDrakkariColossusStatue = go->GetGUID(); + go->SetGoState(uiDrakkariColossusStatueState); break; case 192632: - uiEckTheFerociousDoor = pGo->GetGUID(); + uiEckTheFerociousDoor = go->GetGUID(); if (bHeroicMode && m_auiEncounter[1] == DONE) - HandleGameObject(NULL,true,pGo); + HandleGameObject(NULL,true,go); break; case 192569: - uiEckTheFerociousDoorBehind = pGo->GetGUID(); + uiEckTheFerociousDoorBehind = go->GetGUID(); if (bHeroicMode && m_auiEncounter[4] == DONE) - HandleGameObject(NULL,true,pGo); + HandleGameObject(NULL,true,go); case 193208: - uiGalDarahDoor1 = pGo->GetGUID(); + uiGalDarahDoor1 = go->GetGUID(); if (m_auiEncounter[3] == DONE) - HandleGameObject(NULL,true,pGo); + HandleGameObject(NULL,true,go); break; case 193209: - uiGalDarahDoor2 = pGo->GetGUID(); + uiGalDarahDoor2 = go->GetGUID(); if (m_auiEncounter[3] == DONE) - HandleGameObject(NULL,true,pGo); + HandleGameObject(NULL,true,go); break; case 193188: - uiBridge = pGo->GetGUID(); - pGo->SetGoState(uiBridgeState); + uiBridge = go->GetGUID(); + go->SetGoState(uiBridgeState); break; case 192633: - uiCollision = pGo->GetGUID(); - pGo->SetGoState(uiCollisionState); + uiCollision = go->GetGUID(); + go->SetGoState(uiCollisionState); - // Can't spawn here with SpawnGameObject because pGo isn't added to world yet... + // Can't spawn here with SpawnGameObject because go isn't added to world yet... if (uiCollisionState == GO_STATE_ACTIVE_ALTERNATIVE) spawnSupport = true; break; @@ -260,18 +260,18 @@ public: m_auiEncounter[0] = data; if (data == DONE) { - GameObject* pGo = instance->GetGameObject(uiSladRanAltar); - if (pGo) - pGo->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); + GameObject* go = instance->GetGameObject(uiSladRanAltar); + if (go) + go->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); } break; case DATA_MOORABI_EVENT: m_auiEncounter[1] = data; if (data == DONE) { - GameObject* pGo = instance->GetGameObject(uiMoorabiAltar); - if (pGo) - pGo->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); + GameObject* go = instance->GetGameObject(uiMoorabiAltar); + if (go) + go->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); if (bHeroicMode) HandleGameObject(uiEckTheFerociousDoor,true); } @@ -280,9 +280,9 @@ public: m_auiEncounter[2] = data; if (data == DONE) { - GameObject* pGo = instance->GetGameObject(uiDrakkariColossusAltar); - if (pGo) - pGo->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); + GameObject* go = instance->GetGameObject(uiDrakkariColossusAltar); + if (go) + go->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_UNK1); } break; case DATA_GAL_DARAH_EVENT: @@ -506,7 +506,7 @@ class go_gundrak_altar : public GameObjectScript public: go_gundrak_altar() : GameObjectScript("go_gundrak_altar") { } - bool OnGossipHello(Player * /*pPlayer*/, GameObject *pGO) + bool OnGossipHello(Player * /*pPlayer*/, GameObject* pGO) { InstanceScript *pInstance = pGO->GetInstanceScript(); uint64 uiStatue = 0; 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 65254996eca..ce63835641b 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_blood_prince_council.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_blood_prince_council.cpp @@ -1508,9 +1508,8 @@ class spell_blood_council_shadow_prison : public SpellScriptLoader void HandleDummyTick(AuraEffect const* aurEff, AuraApplication const* aurApp) { - if (aurApp) - if (aurApp->GetTarget()->isMoving()) - aurApp->GetTarget()->CastSpell(aurApp->GetTarget(), SPELL_SHADOW_PRISON_DAMAGE, true, NULL, aurEff); + if (aurApp->GetTarget()->isMoving()) + aurApp->GetTarget()->CastSpell(aurApp->GetTarget(), SPELL_SHADOW_PRISON_DAMAGE, true, NULL, aurEff); } void Register() 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 2f5451e3f22..7e563aba735 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 @@ -61,6 +61,15 @@ enum eSpells SPELL_BLOODBOLT_WHIRL = 71772, }; +enum eShadowmourne +{ + QUEST_BLOOD_INFUSION = 24756, + ITEM_SHADOW_S_EDGE = 49888, + + SPELL_GUSHING_WOUND = 72132, + SPELL_THIRST_QUENCHED = 72154, +}; + static const uint32 vampireAuras[3][MAX_DIFFICULTY] = { {70867, 71473, 71532, 71533}, @@ -182,6 +191,12 @@ class boss_blood_queen_lana_thel : public CreatureScript instance->DoRemoveAurasDueToSpellOnPlayers(ESSENCE_OF_BLOOD_QUEEN); instance->DoRemoveAurasDueToSpellOnPlayers(ESSENCE_OF_BLOOD_QUEEN_PLR); instance->DoRemoveAurasDueToSpellOnPlayers(FRENZIED_BLOODTHIRST); + instance->DoRemoveAurasDueToSpellOnPlayers(SPELL_UNCONTROLLABLE_FRENZY); + instance->DoRemoveAurasDueToSpellOnPlayers(SPELL_BLOOD_MIRROR_DAMAGE); + instance->DoRemoveAurasDueToSpellOnPlayers(SPELL_BLOOD_MIRROR_VISUAL); + instance->DoRemoveAurasDueToSpellOnPlayers(SPELL_BLOOD_MIRROR_DUMMY); + instance->DoRemoveAurasDueToSpellOnPlayers(SPELL_DELIRIOUS_SLASH); + instance->DoRemoveAurasDueToSpellOnPlayers(SPELL_PACT_OF_THE_DARKFALLEN); instance->SetBossState(DATA_BLOOD_QUEEN_LANA_THEL, DONE); } @@ -273,6 +288,10 @@ class boss_blood_queen_lana_thel : public CreatureScript offtank->CastSpell(me->getVictim(), SPELL_BLOOD_MIRROR_DAMAGE, true); me->getVictim()->CastSpell(offtank, SPELL_BLOOD_MIRROR_DUMMY, true); DoCastVictim(SPELL_BLOOD_MIRROR_VISUAL); + if (Item* shadowsEdge = offtank->GetWeaponForAttack(BASE_ATTACK, true)) + if (!offtank->HasAura(SPELL_THIRST_QUENCHED) && shadowsEdge->GetEntry() == ITEM_SHADOW_S_EDGE && !offtank->HasAura(SPELL_GUSHING_WOUND)) + offtank->CastSpell(offtank, SPELL_GUSHING_WOUND, true); + } } events.ScheduleEvent(EVENT_BLOOD_MIRROR, 2500, EVENT_GROUP_CANCELLABLE); @@ -288,6 +307,7 @@ class boss_blood_queen_lana_thel : public CreatureScript std::list<Player*> targets; SelectRandomTarget(false, &targets); uint32 targetCount = 2; + // do not combine these checks! we want it incremented TWICE when both conditions are met if (IsHeroic()) ++targetCount; if (Is25ManRaid()) @@ -382,7 +402,7 @@ class boss_blood_queen_lana_thel : public CreatureScript } std::list<Player*>::iterator itr = tempTargets.begin(); - std::advance(itr, urand(1, tempTargets.size()-1)); + std::advance(itr, urand(0, tempTargets.size()-1)); return *itr; } @@ -436,8 +456,23 @@ class spell_blood_queen_vampiric_bite : public SpellScriptLoader spell = sSpellMgr.GetSpellForDifficultyFromSpell(spell, GetCaster()); GetCaster()->RemoveAura(spell->Id, 0, 0, AURA_REMOVE_BY_ENEMY_SPELL); GetCaster()->CastSpell(GetCaster(), SPELL_ESSENCE_OF_THE_BLOOD_QUEEN_PLR, true); + // Presence of the Darkfallen buff on Blood-Queen if (GetCaster()->GetMap()->IsHeroic()) GetCaster()->CastSpell(GetCaster(), SPELL_PRESENCE_OF_THE_DARKFALLEN, true); + // Shadowmourne questline + if (GetCaster()->ToPlayer()->GetQuestStatus(QUEST_BLOOD_INFUSION) == QUEST_STATUS_INCOMPLETE) + { + if (Aura* aura = GetCaster()->GetAura(SPELL_GUSHING_WOUND)) + { + if (aura->GetStackAmount() == 3) + { + GetCaster()->CastSpell(GetCaster(), SPELL_THIRST_QUENCHED, true); + GetCaster()->RemoveAura(aura); + } + else + GetCaster()->CastSpell(GetCaster(), SPELL_GUSHING_WOUND, true); + } + } if (InstanceScript* instance = GetCaster()->GetInstanceScript()) if (Creature* bloodQueen = ObjectAccessor::GetCreature(*GetCaster(), instance->GetData64(DATA_BLOOD_QUEEN_LANA_THEL))) bloodQueen->AI()->SetGUID(GetHitUnit()->GetGUID(), GUID_VAMPIRE); @@ -473,9 +508,6 @@ class spell_blood_queen_frenzied_bloodthirst : public SpellScriptLoader void OnRemove(AuraEffect const* /*aurEff*/, AuraApplication const* aurApp, AuraEffectHandleModes /*mode*/) { - if (!aurApp) - return; - Unit* target = aurApp->GetTarget(); if (aurApp->GetRemoveMode() == AURA_REMOVE_BY_EXPIRE) if (InstanceScript* instance = target->GetInstanceScript()) diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_professor_putricide.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_professor_putricide.cpp index bf079cfc757..49198ae8252 100755 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_professor_putricide.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_professor_putricide.cpp @@ -73,7 +73,6 @@ enum eSpells SPELL_PLAGUE_SICKNESS = 70953, SPELL_UNBOUND_PLAGUE_PROTECTION = 70955, SPELL_MUTATED_PLAGUE = 72451, - SPELL_UNHOLY_INFUSION_CREDIT = 71518, // Slime Puddle SPELL_GROW_STACKER = 70345, @@ -249,7 +248,6 @@ class boss_professor_putricide : public CreatureScript { Talk(SAY_DEATH); instance->SetBossState(DATA_PROFESSOR_PUTRICIDE, DONE); - DoCastAOE(SPELL_UNHOLY_INFUSION_CREDIT, true); } void JustSummoned(Creature* summon) @@ -760,8 +758,7 @@ class spell_putricide_gaseous_bloat : public SpellScriptLoader void HandleExtraEffect(AuraEffect const* /*aurEff*/, AuraApplication const* aurApp) { - if (aurApp->GetTarget()) - aurApp->GetTarget()->RemoveAuraFromStack(GetSpellProto()->Id, aurApp->GetBase()->GetCasterGUID()); + aurApp->GetTarget()->RemoveAuraFromStack(GetSpellProto()->Id, aurApp->GetBase()->GetCasterGUID()); } void Register() diff --git a/src/server/scripts/Northrend/IcecrownCitadel/boss_rotface.cpp b/src/server/scripts/Northrend/IcecrownCitadel/boss_rotface.cpp index ed253dd4eda..b316424987b 100644 --- a/src/server/scripts/Northrend/IcecrownCitadel/boss_rotface.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/boss_rotface.cpp @@ -712,7 +712,7 @@ class spell_rotface_unstable_ooze_explosion_suicide : public SpellScriptLoader { PreventDefaultAction(); Unit* target = aurApp->GetTarget(); - if (!target || target->GetTypeId() != TYPEID_UNIT) + if (target->GetTypeId() != TYPEID_UNIT) return; target->ToCreature()->AI()->DoAction(EVENT_UNSTABLE_DESPAWN); diff --git a/src/server/scripts/Northrend/IcecrownCitadel/instance_icecrown_citadel.cpp b/src/server/scripts/Northrend/IcecrownCitadel/instance_icecrown_citadel.cpp index a0ad03265d9..dfca787c3cc 100755 --- a/src/server/scripts/Northrend/IcecrownCitadel/instance_icecrown_citadel.cpp +++ b/src/server/scripts/Northrend/IcecrownCitadel/instance_icecrown_citadel.cpp @@ -84,11 +84,8 @@ class instance_icecrown_citadel : public InstanceMapScript teamInInstance = player->GetTeam(); } - void OnCreatureCreate(Creature* creature, bool add) + void OnCreatureCreate(Creature* creature) { - if (!add) - return; - if (!teamInInstance) { Map::PlayerList const &players = instance->GetPlayers(); @@ -178,7 +175,7 @@ class instance_icecrown_citadel : public InstanceMapScript } } - void OnGameObjectCreate(GameObject* go, bool add) + void OnGameObjectCreate(GameObject* go) { switch (go->GetEntry()) { @@ -199,7 +196,7 @@ class instance_icecrown_citadel : public InstanceMapScript case GO_SINDRAGOSA_ENTRANCE_DOOR: case GO_SINDRAGOSA_SHORTCUT_ENTRANCE_DOOR: case GO_SINDRAGOSA_SHORTCUT_EXIT_DOOR: - AddDoor(go, add); + AddDoor(go, true); break; case GO_LADY_DEATHWHISPER_ELEVATOR: ladyDeathwisperElevator = go->GetGUID(); @@ -258,6 +255,34 @@ class instance_icecrown_citadel : public InstanceMapScript } } + void OnGameObjectRemove(GameObject* go) + { + switch (go->GetEntry()) + { + case GO_DOODAD_ICECROWN_ICEWALL02: + case GO_ICEWALL: + case GO_LORD_MARROWGAR_S_ENTRANCE: + case GO_ORATORY_OF_THE_DAMNED_ENTRANCE: + case GO_ORANGE_PLAGUE_MONSTER_ENTRANCE: + case GO_GREEN_PLAGUE_MONSTER_ENTRANCE: + case GO_SCIENTIST_ENTRANCE: + case GO_CRIMSON_HALL_DOOR: + case GO_BLOOD_ELF_COUNCIL_DOOR: + case GO_BLOOD_ELF_COUNCIL_DOOR_RIGHT: + case GO_DOODAD_ICECROWN_BLOODPRINCE_DOOR_01: + case GO_DOODAD_ICECROWN_GRATE_01: + case GO_GREEN_DRAGON_BOSS_ENTRANCE: + case GO_GREEN_DRAGON_BOSS_EXIT: + case GO_SINDRAGOSA_ENTRANCE_DOOR: + case GO_SINDRAGOSA_SHORTCUT_ENTRANCE_DOOR: + case GO_SINDRAGOSA_SHORTCUT_EXIT_DOOR: + AddDoor(go, false); + break; + default: + break; + } + } + uint64 GetData64(uint32 type) { switch (type) diff --git a/src/server/scripts/Northrend/Naxxramas/boss_gothik.cpp b/src/server/scripts/Northrend/Naxxramas/boss_gothik.cpp index f46ed746c97..7aa4b0a9acd 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_gothik.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_gothik.cpp @@ -384,7 +384,7 @@ public: void UpdateAI(const uint32 diff) { - if (!UpdateCombatState() || !CheckInRoom()) + if (!UpdateVictim() || !CheckInRoom()) return; events.Update(diff); diff --git a/src/server/scripts/Northrend/Naxxramas/boss_kelthuzad.cpp b/src/server/scripts/Northrend/Naxxramas/boss_kelthuzad.cpp index e4a121aa2ae..158e19843d9 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_kelthuzad.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_kelthuzad.cpp @@ -377,7 +377,7 @@ public: void UpdateAI(const uint32 diff) { - if (!UpdateCombatState()) + if (!UpdateVictim()) return; events.Update(diff); diff --git a/src/server/scripts/Northrend/Naxxramas/boss_noth.cpp b/src/server/scripts/Northrend/Naxxramas/boss_noth.cpp index 135473a2ea4..2010173de89 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_noth.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_noth.cpp @@ -142,7 +142,7 @@ public: void UpdateAI(const uint32 diff) { - if (!UpdateCombatState() || !CheckInRoom()) + if (!UpdateVictim() || !CheckInRoom()) return; events.Update(diff); diff --git a/src/server/scripts/Northrend/Naxxramas/boss_sapphiron.cpp b/src/server/scripts/Northrend/Naxxramas/boss_sapphiron.cpp index 3ed263ffae5..e48696f23bc 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_sapphiron.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_sapphiron.cpp @@ -228,7 +228,7 @@ public: events.Update(diff); - if ((phase != PHASE_BIRTH && !UpdateCombatState()) || !CheckInRoom()) + if ((phase != PHASE_BIRTH && !UpdateVictim()) || !CheckInRoom()) return; if (CanTheHundredClub) diff --git a/src/server/scripts/Northrend/Naxxramas/instance_naxxramas.cpp b/src/server/scripts/Northrend/Naxxramas/instance_naxxramas.cpp index 6d770294c7b..62fab87714c 100644 --- a/src/server/scripts/Northrend/Naxxramas/instance_naxxramas.cpp +++ b/src/server/scripts/Northrend/Naxxramas/instance_naxxramas.cpp @@ -144,60 +144,99 @@ public: time_t minHorsemenDiedTime; time_t maxHorsemenDiedTime; - void OnCreatureCreate(Creature* pCreature, bool add) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case 15989: SapphironGUID = add ? pCreature->GetGUID() : 0; return; - case 15953: uiFaerlina = pCreature->GetGUID(); return; - case 16064: uiThane = pCreature->GetGUID(); return; - case 16065: uiLady = pCreature->GetGUID(); return; - case 30549: uiBaron = pCreature->GetGUID(); return; - case 16063: uiSir = pCreature->GetGUID(); return; - case 15928: uiThaddius = pCreature->GetGUID(); return; - case 15930: uiFeugen = pCreature->GetGUID(); return; - case 15929: uiStalagg = pCreature->GetGUID(); return; - case 15990: uiKelthuzad = pCreature->GetGUID(); return; + case 15989: SapphironGUID = creature->GetGUID(); return; + case 15953: uiFaerlina = creature->GetGUID(); return; + case 16064: uiThane = creature->GetGUID(); return; + case 16065: uiLady = creature->GetGUID(); return; + case 30549: uiBaron = creature->GetGUID(); return; + case 16063: uiSir = creature->GetGUID(); return; + case 15928: uiThaddius = creature->GetGUID(); return; + case 15930: uiFeugen = creature->GetGUID(); return; + case 15929: uiStalagg = creature->GetGUID(); return; + case 15990: uiKelthuzad = creature->GetGUID(); return; } - AddMinion(pCreature, add); + AddMinion(creature, true); } - void OnGameObjectCreate(GameObject* pGo, bool add) + void OnCreatureRemove(Creature* creature) { - if (pGo->GetGOInfo()->displayId == 6785 || pGo->GetGOInfo()->displayId == 1287) + AddMinion(creature, false); + } + + void OnGameObjectCreate(GameObject* go) + { + if (go->GetGOInfo()->displayId == 6785 || go->GetGOInfo()->displayId == 1287) { - uint32 section = GetEruptionSection(pGo->GetPositionX(), pGo->GetPositionY()); - if (add) - HeiganEruptionGUID[section].insert(pGo->GetGUID()); - else - HeiganEruptionGUID[section].erase(pGo->GetGUID()); + uint32 section = GetEruptionSection(go->GetPositionX(), go->GetPositionY()); + HeiganEruptionGUID[section].insert(go->GetGUID()); + return; } - switch(pGo->GetEntry()) + switch (go->GetEntry()) { - case GO_BIRTH: - if (!add && SapphironGUID) - { - if (Creature *pSapphiron = instance->GetCreature(SapphironGUID)) - pSapphiron->AI()->DoAction(DATA_SAPPHIRON_BIRTH); - return; - } case GO_GOTHIK_GATE: - GothikGateGUID = add ? pGo->GetGUID() : 0; - pGo->SetGoState(gothikDoorState); + GothikGateGUID = go->GetGUID(); + go->SetGoState(gothikDoorState); + break; + case GO_HORSEMEN_CHEST: + HorsemenChestGUID = go->GetGUID(); + break; + case GO_HORSEMEN_CHEST_HERO: + HorsemenChestGUID = go->GetGUID(); + break; + case GO_KELTHUZAD_PORTAL01: + uiPortals[0] = go->GetGUID(); + break; + case GO_KELTHUZAD_PORTAL02: + uiPortals[1] = go->GetGUID(); + break; + case GO_KELTHUZAD_PORTAL03: + uiPortals[2] = go->GetGUID(); + break; + case GO_KELTHUZAD_PORTAL04: + uiPortals[3] = go->GetGUID(); + break; + case GO_KELTHUZAD_TRIGGER: + uiKelthuzadTrigger = go->GetGUID(); + break; + default: + break; + } + + AddDoor(go, true); + } + + void OnGameObjectRemove(GameObject* go) + { + if (go->GetGOInfo()->displayId == 6785 || go->GetGOInfo()->displayId == 1287) + { + uint32 section = GetEruptionSection(go->GetPositionX(), go->GetPositionY()); + + HeiganEruptionGUID[section].erase(go->GetGUID()); + return; + } + + switch (go->GetEntry()) + { + case GO_BIRTH: + if (SapphironGUID) + { + if (Creature* pSapphiron = instance->GetCreature(SapphironGUID)) + pSapphiron->AI()->DoAction(DATA_SAPPHIRON_BIRTH); + return; + } + break; + default: break; - case GO_HORSEMEN_CHEST: HorsemenChestGUID = add ? pGo->GetGUID() : 0; break; - case GO_HORSEMEN_CHEST_HERO: HorsemenChestGUID = add ? pGo->GetGUID() : 0; break; - case GO_KELTHUZAD_PORTAL01: uiPortals[0] = pGo->GetGUID(); break; - case GO_KELTHUZAD_PORTAL02: uiPortals[1] = pGo->GetGUID(); break; - case GO_KELTHUZAD_PORTAL03: uiPortals[2] = pGo->GetGUID(); break; - case GO_KELTHUZAD_PORTAL04: uiPortals[3] = pGo->GetGUID(); break; - case GO_KELTHUZAD_TRIGGER: uiKelthuzadTrigger = pGo->GetGUID(); break; } - AddDoor(pGo, add); + AddDoor(go, false); } void SetData(uint32 id, uint32 value) @@ -208,8 +247,8 @@ public: HeiganErupt(value); break; case DATA_GOTHIK_GATE: - if (GameObject *pGothikGate = instance->GetGameObject(GothikGateGUID)) - pGothikGate->SetGoState(GOState(value)); + if (GameObject* gothikGate = instance->GetGameObject(GothikGateGUID)) + gothikGate->SetGoState(GOState(value)); gothikDoorState = GOState(value); break; @@ -278,7 +317,7 @@ public: if (id == BOSS_HORSEMEN && state == DONE) { - if (GameObject *pHorsemenChest = instance->GetGameObject(HorsemenChestGUID)) + if (GameObject* pHorsemenChest = instance->GetGameObject(HorsemenChestGUID)) pHorsemenChest->SetRespawnTime(pHorsemenChest->GetRespawnDelay()); } @@ -294,7 +333,7 @@ public: for (std::set<uint64>::const_iterator itr = HeiganEruptionGUID[i].begin(); itr != HeiganEruptionGUID[i].end(); ++itr) { - if (GameObject *pHeiganEruption = instance->GetGameObject(*itr)) + if (GameObject* pHeiganEruption = instance->GetGameObject(*itr)) { pHeiganEruption->SendCustomAnim(); pHeiganEruption->CastSpell(NULL, SPELL_ERUPTION); diff --git a/src/server/scripts/Northrend/Nexus/Nexus/instance_nexus.cpp b/src/server/scripts/Northrend/Nexus/Nexus/instance_nexus.cpp index 02970f242df..840e61e18d1 100644 --- a/src/server/scripts/Northrend/Nexus/Nexus/instance_nexus.cpp +++ b/src/server/scripts/Northrend/Nexus/Nexus/instance_nexus.cpp @@ -59,7 +59,7 @@ public: Keristrasza = 0; } - void OnCreatureCreate(Creature *pCreature, bool /*bAdd*/) + void OnCreatureCreate(Creature* creature) { Map::PlayerList const &players = instance->GetPlayers(); uint32 TeamInInstance = 0; @@ -69,81 +69,81 @@ public: if (Player* pPlayer = players.begin()->getSource()) TeamInInstance = pPlayer->GetTeam(); } - switch (pCreature->GetEntry()) + switch (creature->GetEntry()) { case 26763: - Anomalus = pCreature->GetGUID(); + Anomalus = creature->GetGUID(); break; case 26723: - Keristrasza = pCreature->GetGUID(); + Keristrasza = creature->GetGUID(); break; // Alliance npcs are spawned by default, if you are alliance, you will fight against horde npcs. case 26800: { if (ServerAllowsTwoSideGroups()) - pCreature->setFaction(FACTION_HOSTILE_FOR_ALL); + creature->setFaction(FACTION_HOSTILE_FOR_ALL); if (TeamInInstance == ALLIANCE) - pCreature->UpdateEntry(26799, HORDE); + creature->UpdateEntry(26799, HORDE); break; } case 26802: { if (ServerAllowsTwoSideGroups()) - pCreature->setFaction(FACTION_HOSTILE_FOR_ALL); + creature->setFaction(FACTION_HOSTILE_FOR_ALL); if (TeamInInstance == ALLIANCE) - pCreature->UpdateEntry(26801, HORDE); + creature->UpdateEntry(26801, HORDE); break; } case 26805: { if (ServerAllowsTwoSideGroups()) - pCreature->setFaction(FACTION_HOSTILE_FOR_ALL); + creature->setFaction(FACTION_HOSTILE_FOR_ALL); if (TeamInInstance == ALLIANCE) - pCreature->UpdateEntry(26803, HORDE); + creature->UpdateEntry(26803, HORDE); break; } case 27949: { if (ServerAllowsTwoSideGroups()) - pCreature->setFaction(FACTION_HOSTILE_FOR_ALL); + creature->setFaction(FACTION_HOSTILE_FOR_ALL); if (TeamInInstance == ALLIANCE) - pCreature->UpdateEntry(27947, HORDE); + creature->UpdateEntry(27947, HORDE); break; } case 26796: { if (ServerAllowsTwoSideGroups()) - pCreature->setFaction(FACTION_HOSTILE_FOR_ALL); + creature->setFaction(FACTION_HOSTILE_FOR_ALL); if (TeamInInstance == ALLIANCE) - pCreature->UpdateEntry(26798, HORDE); + creature->UpdateEntry(26798, HORDE); break; } } } - void OnGameObjectCreate(GameObject *pGo, bool /*bAdd*/) + void OnGameObjectCreate(GameObject* go) { - switch (pGo->GetEntry()) + switch (go->GetEntry()) { case 188527: { - AnomalusContainmentSphere = pGo->GetGUID(); + AnomalusContainmentSphere = go->GetGUID(); if (m_auiEncounter[1] == DONE) - pGo->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); + go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); break; } case 188528: { - OrmoroksContainmentSphere = pGo->GetGUID(); + OrmoroksContainmentSphere = go->GetGUID(); if (m_auiEncounter[2] == DONE) - pGo->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); + go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); break; } case 188526: { - TelestrasContainmentSphere = pGo->GetGUID(); + TelestrasContainmentSphere = go->GetGUID(); if (m_auiEncounter[0] == DONE) - pGo->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); + go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); break; } } @@ -169,7 +169,7 @@ public: { if (data == DONE) { - GameObject *Sphere = instance->GetGameObject(TelestrasContainmentSphere); + GameObject* Sphere = instance->GetGameObject(TelestrasContainmentSphere); if (Sphere) Sphere->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); } @@ -180,7 +180,7 @@ public: { if (data == DONE) { - if (GameObject *Sphere = instance->GetGameObject(AnomalusContainmentSphere)) + if (GameObject* Sphere = instance->GetGameObject(AnomalusContainmentSphere)) Sphere->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); } m_auiEncounter[1] = data; @@ -190,7 +190,7 @@ public: { if (data == DONE) { - if (GameObject *Sphere = instance->GetGameObject(OrmoroksContainmentSphere)) + if (GameObject* Sphere = instance->GetGameObject(OrmoroksContainmentSphere)) Sphere->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); } m_auiEncounter[2] = data; diff --git a/src/server/scripts/Northrend/Nexus/Oculus/instance_oculus.cpp b/src/server/scripts/Northrend/Nexus/Oculus/instance_oculus.cpp index ae736181566..ebdff747de0 100644 --- a/src/server/scripts/Northrend/Nexus/Oculus/instance_oculus.cpp +++ b/src/server/scripts/Northrend/Nexus/Oculus/instance_oculus.cpp @@ -57,35 +57,35 @@ public: uiPlataformUrom = 0; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { case CREATURE_DRAKOS: - uiDrakos = pCreature->GetGUID(); + uiDrakos = creature->GetGUID(); break; case CREATURE_VAROS: - uiVaros = pCreature->GetGUID(); + uiVaros = creature->GetGUID(); break; case CREATURE_UROM: - uiUrom = pCreature->GetGUID(); + uiUrom = creature->GetGUID(); break; case CREATURE_EREGOS: - uiEregos = pCreature->GetGUID(); + uiEregos = creature->GetGUID(); break; } } - void OnGameObjectCreate(GameObject* pGO, bool /*bAdd*/) + void OnGameObjectCreate(GameObject* go) { - if (pGO->GetEntry() == GO_DRAGON_CAGE_DOOR) + if (go->GetEntry() == GO_DRAGON_CAGE_DOOR) { if (GetData(DATA_DRAKOS_EVENT) == DONE) - pGO->SetGoState(GO_STATE_ACTIVE); + go->SetGoState(GO_STATE_ACTIVE); else - pGO->SetGoState(GO_STATE_READY); + go->SetGoState(GO_STATE_READY); - GameObjectList.push_back(pGO->GetGUID()); + GameObjectList.push_back(go->GetGUID()); } } @@ -150,8 +150,8 @@ public: for (std::list<uint64>::const_iterator itr = GameObjectList.begin(); itr != GameObjectList.end(); ++itr) { - if (GameObject* pGO = instance->GetGameObject(*itr)) - pGO->SetGoState(GO_STATE_ACTIVE); + if (GameObject* go = instance->GetGameObject(*itr)) + go->SetGoState(GO_STATE_ACTIVE); } } diff --git a/src/server/scripts/Northrend/ObsidianSanctum/instance_obsidian_sanctum.cpp b/src/server/scripts/Northrend/ObsidianSanctum/instance_obsidian_sanctum.cpp index 0ec9e42ebc3..a8eb91f8c8d 100644 --- a/src/server/scripts/Northrend/ObsidianSanctum/instance_obsidian_sanctum.cpp +++ b/src/server/scripts/Northrend/ObsidianSanctum/instance_obsidian_sanctum.cpp @@ -62,26 +62,26 @@ public: m_bVesperonKilled = false; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { case NPC_SARTHARION: - m_uiSartharionGUID = pCreature->GetGUID(); + m_uiSartharionGUID = creature->GetGUID(); break; //three dragons below set to active state once created. //we must expect bigger raid to encounter main boss, and then three dragons must be active due to grid differences case NPC_TENEBRON: - m_uiTenebronGUID = pCreature->GetGUID(); - pCreature->setActive(true); + m_uiTenebronGUID = creature->GetGUID(); + creature->setActive(true); break; case NPC_SHADRON: - m_uiShadronGUID = pCreature->GetGUID(); - pCreature->setActive(true); + m_uiShadronGUID = creature->GetGUID(); + creature->setActive(true); break; case NPC_VESPERON: - m_uiVesperonGUID = pCreature->GetGUID(); - pCreature->setActive(true); + m_uiVesperonGUID = creature->GetGUID(); + creature->setActive(true); break; } } 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 546409fd406..db83deca383 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 @@ -76,59 +76,59 @@ public: m_uiLokenGlobeGUID = 0; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { case NPC_BJARNGRIM: - m_uiGeneralBjarngrimGUID = pCreature->GetGUID(); + m_uiGeneralBjarngrimGUID = creature->GetGUID(); break; case NPC_VOLKHAN: - m_uiVolkhanGUID = pCreature->GetGUID(); + m_uiVolkhanGUID = creature->GetGUID(); break; case NPC_IONAR: - m_uiIonarGUID = pCreature->GetGUID(); + m_uiIonarGUID = creature->GetGUID(); break; case NPC_LOKEN: - m_uiLokenGUID = pCreature->GetGUID(); + m_uiLokenGUID = creature->GetGUID(); break; } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case GO_BJARNGRIM_DOOR: - m_uiBjarngrimDoorGUID = pGo->GetGUID(); + m_uiBjarngrimDoorGUID = go->GetGUID(); if (m_auiEncounter[0] == DONE) - pGo->SetGoState(GO_STATE_ACTIVE); + go->SetGoState(GO_STATE_ACTIVE); else - pGo->SetGoState(GO_STATE_READY); + go->SetGoState(GO_STATE_READY); break; case GO_VOLKHAN_DOOR: - m_uiVolkhanDoorGUID = pGo->GetGUID(); + m_uiVolkhanDoorGUID = go->GetGUID(); if (m_auiEncounter[1] == DONE) - pGo->SetGoState(GO_STATE_ACTIVE); + go->SetGoState(GO_STATE_ACTIVE); else - pGo->SetGoState(GO_STATE_READY); + go->SetGoState(GO_STATE_READY); break; case GO_IONAR_DOOR: - m_uiIonarDoorGUID = pGo->GetGUID(); + m_uiIonarDoorGUID = go->GetGUID(); if (m_auiEncounter[2] == DONE) - pGo->SetGoState(GO_STATE_ACTIVE); + go->SetGoState(GO_STATE_ACTIVE); else - pGo->SetGoState(GO_STATE_READY); + go->SetGoState(GO_STATE_READY); break; case GO_LOKEN_DOOR: - m_uiLokenDoorGUID = pGo->GetGUID(); + m_uiLokenDoorGUID = go->GetGUID(); if (m_auiEncounter[3] == DONE) - pGo->SetGoState(GO_STATE_ACTIVE); + go->SetGoState(GO_STATE_ACTIVE); else - pGo->SetGoState(GO_STATE_READY); + go->SetGoState(GO_STATE_READY); break; case GO_LOKEN_THRONE: - m_uiLokenGlobeGUID = pGo->GetGUID(); + m_uiLokenGlobeGUID = go->GetGUID(); break; } } 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 c7e1f627414..55d4199b6d5 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 @@ -89,65 +89,65 @@ public: m_auiEncounter[i] = NOT_STARTED; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case CREATURE_MAIDEN: uiMaidenOfGrief = pCreature->GetGUID(); break; - case CREATURE_KRYSTALLUS: uiKrystallus = pCreature->GetGUID(); break; - case CREATURE_SJONNIR: uiSjonnir = pCreature->GetGUID(); break; - case CREATURE_MARNAK: uiMarnak = pCreature->GetGUID(); break; - case CREATURE_KADDRAK: uiKaddrak = pCreature->GetGUID(); break; - case CREATURE_ABEDNEUM: uiAbedneum = pCreature->GetGUID(); break; - case CREATURE_BRANN: uiBrann = pCreature->GetGUID(); break; + case CREATURE_MAIDEN: uiMaidenOfGrief = creature->GetGUID(); break; + case CREATURE_KRYSTALLUS: uiKrystallus = creature->GetGUID(); break; + case CREATURE_SJONNIR: uiSjonnir = creature->GetGUID(); break; + case CREATURE_MARNAK: uiMarnak = creature->GetGUID(); break; + case CREATURE_KADDRAK: uiKaddrak = creature->GetGUID(); break; + case CREATURE_ABEDNEUM: uiAbedneum = creature->GetGUID(); break; + case CREATURE_BRANN: uiBrann = creature->GetGUID(); break; } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case GO_ABEDNEUM: - uiAbedneumGo = pGo->GetGUID(); + uiAbedneumGo = go->GetGUID(); break; case GO_MARNAK: - uiMarnakGo = pGo->GetGUID(); + uiMarnakGo = go->GetGUID(); break; case GO_KADDRAK: - uiKaddrakGo = pGo->GetGUID(); + uiKaddrakGo = go->GetGUID(); break; case GO_MAIDEN_DOOR: - uiMaidenOfGriefDoor = pGo->GetGUID(); + uiMaidenOfGriefDoor = go->GetGUID(); if (m_auiEncounter[0] == DONE) - pGo->SetGoState(GO_STATE_ACTIVE); + go->SetGoState(GO_STATE_ACTIVE); else - pGo->SetGoState(GO_STATE_READY); + go->SetGoState(GO_STATE_READY); break; case GO_BRANN_DOOR: - uiBrannDoor = pGo->GetGUID(); + uiBrannDoor = go->GetGUID(); if (m_auiEncounter[1] == DONE) - pGo->SetGoState(GO_STATE_ACTIVE); + go->SetGoState(GO_STATE_ACTIVE); else - pGo->SetGoState(GO_STATE_READY); + go->SetGoState(GO_STATE_READY); break; case GO_SJONNIR_DOOR: - uiSjonnirDoor = pGo->GetGUID(); + uiSjonnirDoor = go->GetGUID(); if (m_auiEncounter[2] == DONE) - pGo->SetGoState(GO_STATE_ACTIVE); + go->SetGoState(GO_STATE_ACTIVE); else - pGo->SetGoState(GO_STATE_READY); + go->SetGoState(GO_STATE_READY); break; case GO_TRIBUNAL_CONSOLE: - uiTribunalConsole = pGo->GetGUID(); + uiTribunalConsole = go->GetGUID(); break; case GO_TRIBUNAL_CHEST: case GO_TRIBUNAL_CHEST_HERO: - uiTribunalChest = pGo->GetGUID(); + uiTribunalChest = go->GetGUID(); if (m_auiEncounter[2] == DONE) - pGo->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_INTERACT_COND); + go->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_INTERACT_COND); break; case 191527: - uiTribunalSkyFloor = pGo->GetGUID(); + uiTribunalSkyFloor = go->GetGUID(); break; } } @@ -174,9 +174,9 @@ public: if (m_auiEncounter[2] == DONE) { HandleGameObject(uiSjonnirDoor,true); - GameObject *pGo = instance->GetGameObject(uiTribunalChest); - if (pGo) - pGo->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_INTERACT_COND); + GameObject* go = instance->GetGameObject(uiTribunalChest); + if (go) + go->RemoveFlag(GAMEOBJECT_FLAGS,GO_FLAG_INTERACT_COND); } break; } diff --git a/src/server/scripts/Northrend/Ulduar/ulduar/instance_ulduar.cpp b/src/server/scripts/Northrend/Ulduar/ulduar/instance_ulduar.cpp index 21e23a9c9e4..86eb822ada4 100644 --- a/src/server/scripts/Northrend/Ulduar/ulduar/instance_ulduar.cpp +++ b/src/server/scripts/Northrend/Ulduar/ulduar/instance_ulduar.cpp @@ -112,103 +112,103 @@ public: return false; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { case NPC_LEVIATHAN: - uiLeviathanGUID = pCreature->GetGUID(); + uiLeviathanGUID = creature->GetGUID(); break; case NPC_IGNIS: - uiIgnisGUID = pCreature->GetGUID(); + uiIgnisGUID = creature->GetGUID(); break; case NPC_RAZORSCALE: - uiRazorscaleGUID = pCreature->GetGUID(); + uiRazorscaleGUID = creature->GetGUID(); break; case NPC_EXPEDITION_COMMANDER: - uiExpCommanderGUID = pCreature->GetGUID(); + uiExpCommanderGUID = creature->GetGUID(); return; case NPC_XT002: - uiXT002GUID = pCreature->GetGUID(); + uiXT002GUID = creature->GetGUID(); break; // Assembly of Iron case NPC_STEELBREAKER: - uiAssemblyGUIDs[0] = pCreature->GetGUID(); + uiAssemblyGUIDs[0] = creature->GetGUID(); break; case NPC_MOLGEIM: - uiAssemblyGUIDs[1] = pCreature->GetGUID(); + uiAssemblyGUIDs[1] = creature->GetGUID(); break; case NPC_BRUNDIR: - uiAssemblyGUIDs[2] = pCreature->GetGUID(); + uiAssemblyGUIDs[2] = creature->GetGUID(); break; case NPC_KOLOGARN: - uiKologarnGUID = pCreature->GetGUID(); + uiKologarnGUID = creature->GetGUID(); break; case NPC_AURIAYA: - uiAuriayaGUID = pCreature->GetGUID(); + uiAuriayaGUID = creature->GetGUID(); break; case NPC_MIMIRON: - uiMimironGUID = pCreature->GetGUID(); + uiMimironGUID = creature->GetGUID(); break; case NPC_HODIR: - uiHodirGUID = pCreature->GetGUID(); + uiHodirGUID = creature->GetGUID(); break; case NPC_THORIM: - uiThorimGUID = pCreature->GetGUID(); + uiThorimGUID = creature->GetGUID(); break; case NPC_FREYA: - uiFreyaGUID = pCreature->GetGUID(); + uiFreyaGUID = creature->GetGUID(); break; case NPC_VEZAX: - uiVezaxGUID = pCreature->GetGUID(); + uiVezaxGUID = creature->GetGUID(); break; case NPC_YOGGSARON: - uiYoggSaronGUID = pCreature->GetGUID(); + uiYoggSaronGUID = creature->GetGUID(); break; case NPC_ALGALON: - uiAlgalonGUID = pCreature->GetGUID(); + uiAlgalonGUID = creature->GetGUID(); break; } } - void OnGameObjectCreate(GameObject* pGO, bool add) + void OnGameObjectCreate(GameObject* go) { - switch(pGO->GetEntry()) + switch(go->GetEntry()) { case GO_KOLOGARN_CHEST_HERO: case GO_KOLOGARN_CHEST: - uiKologarnChestGUID = add ? pGO->GetGUID() : NULL; + uiKologarnChestGUID = go->GetGUID(); break; case GO_THORIM_CHEST_HERO: case GO_THORIM_CHEST: - uiThorimChestGUID = add ? pGO->GetGUID() : NULL; + uiThorimChestGUID =go->GetGUID(); break; case GO_HODIR_CHEST_HERO: case GO_HODIR_CHEST: - uiHodirChestGUID = add ? pGO->GetGUID() : NULL; + uiHodirChestGUID = go->GetGUID(); break; case GO_FREYA_CHEST_HERO: case GO_FREYA_CHEST: - uiFreyaChestGUID = add ? pGO->GetGUID() : NULL; + uiFreyaChestGUID = go->GetGUID(); break; case GO_LEVIATHAN_DOOR: - uiLeviathanDoor[flag] = pGO->GetGUID(); - HandleGameObject(NULL, true, pGO); + uiLeviathanDoor[flag] = go->GetGUID(); + HandleGameObject(NULL, true, go); flag++; if (flag == 7) flag =0; break; case GO_LEVIATHAN_GATE: - uiLeviathanGateGUID = add ? pGO->GetGUID() : NULL; - HandleGameObject(NULL, false, pGO); + uiLeviathanGateGUID = go->GetGUID(); + HandleGameObject(NULL, false, go); break; } } - void ProcessEvent(GameObject* /*pGO*/, uint32 uiEventId) + void ProcessEvent(GameObject* /*go*/, uint32 uiEventId) { // Flame Leviathan's Tower Event triggers Creature* pFlameLeviathan = instance->GetCreature(uiLeviathanGUID); @@ -261,23 +261,23 @@ public: break; case TYPE_KOLOGARN: if (state == DONE) - if (GameObject* pGO = instance->GetGameObject(uiKologarnChestGUID)) - pGO->SetRespawnTime(pGO->GetRespawnDelay()); + if (GameObject* go = instance->GetGameObject(uiKologarnChestGUID)) + go->SetRespawnTime(go->GetRespawnDelay()); break; case TYPE_HODIR: if (state == DONE) - if (GameObject* pGO = instance->GetGameObject(uiHodirChestGUID)) - pGO->SetRespawnTime(pGO->GetRespawnDelay()); + if (GameObject* go = instance->GetGameObject(uiHodirChestGUID)) + go->SetRespawnTime(go->GetRespawnDelay()); break; case TYPE_THORIM: if (state == DONE) - if (GameObject* pGO = instance->GetGameObject(uiThorimChestGUID)) - pGO->SetRespawnTime(pGO->GetRespawnDelay()); + if (GameObject* go = instance->GetGameObject(uiThorimChestGUID)) + go->SetRespawnTime(go->GetRespawnDelay()); break; case TYPE_FREYA: if (state == DONE) - if (GameObject* pGO = instance->GetGameObject(uiFreyaChestGUID)) - pGO->SetRespawnTime(pGO->GetRespawnDelay()); + if (GameObject* go = instance->GetGameObject(uiFreyaChestGUID)) + go->SetRespawnTime(go->GetRespawnDelay()); break; } 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 eed33507839..c8ae6ecfabd 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/instance_utgarde_keep.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardeKeep/instance_utgarde_keep.cpp @@ -122,44 +122,44 @@ public: return NULL; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case 23953: Keleseth = pCreature->GetGUID(); break; - case 24201: Dalronn = pCreature->GetGUID(); break; - case 24200: Skarvald = pCreature->GetGUID(); break; - case 23954: Ingvar = pCreature->GetGUID(); break; + case 23953: Keleseth = creature->GetGUID(); break; + case 24201: Dalronn = creature->GetGUID(); break; + case 24200: Skarvald = creature->GetGUID(); break; + case 23954: Ingvar = creature->GetGUID(); break; } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { //door and object id - case ENTRY_BELLOW_1: forge_bellow[0] = pGo->GetGUID(); - if (forge_event[0] != NOT_STARTED)HandleGameObject(NULL,true,pGo);break; - case ENTRY_BELLOW_2: forge_bellow[1] = pGo->GetGUID(); - if (forge_event[1] != NOT_STARTED)HandleGameObject(NULL,true,pGo);break; - case ENTRY_BELLOW_3: forge_bellow[2] = pGo->GetGUID(); - if (forge_event[2] != NOT_STARTED)HandleGameObject(NULL,true,pGo);break; - case ENTRY_FORGEFIRE_1: forge_fire[0] = pGo->GetGUID(); - if (forge_event[0] != NOT_STARTED)HandleGameObject(NULL,true,pGo);break; - case ENTRY_FORGEFIRE_2: forge_fire[1] = pGo->GetGUID(); - if (forge_event[1] != NOT_STARTED)HandleGameObject(NULL,true,pGo);break; - case ENTRY_FORGEFIRE_3: forge_fire[2] = pGo->GetGUID(); - if (forge_event[2] != NOT_STARTED)HandleGameObject(NULL,true,pGo);break; - case ENTRY_GLOWING_ANVIL_1: forge_anvil[0] = pGo->GetGUID(); - if (forge_event[0] != NOT_STARTED)HandleGameObject(NULL,true,pGo);break; - case ENTRY_GLOWING_ANVIL_2: forge_anvil[1] = pGo->GetGUID(); - if (forge_event[1] != NOT_STARTED)HandleGameObject(NULL,true,pGo);break; - case ENTRY_GLOWING_ANVIL_3: forge_anvil[2] = pGo->GetGUID(); - if (forge_event[2] != NOT_STARTED)HandleGameObject(NULL,true,pGo);break; - case ENTRY_GIANT_PORTCULLIS_1: portcullis[0] = pGo->GetGUID(); - if (m_auiEncounter[2] == DONE)HandleGameObject(NULL,true,pGo);break; - case ENTRY_GIANT_PORTCULLIS_2: portcullis[1] = pGo->GetGUID(); - if (m_auiEncounter[2] == DONE)HandleGameObject(NULL,true,pGo);break; + case ENTRY_BELLOW_1: forge_bellow[0] = go->GetGUID(); + if (forge_event[0] != NOT_STARTED)HandleGameObject(NULL,true,go);break; + case ENTRY_BELLOW_2: forge_bellow[1] = go->GetGUID(); + if (forge_event[1] != NOT_STARTED)HandleGameObject(NULL,true,go);break; + case ENTRY_BELLOW_3: forge_bellow[2] = go->GetGUID(); + if (forge_event[2] != NOT_STARTED)HandleGameObject(NULL,true,go);break; + case ENTRY_FORGEFIRE_1: forge_fire[0] = go->GetGUID(); + if (forge_event[0] != NOT_STARTED)HandleGameObject(NULL,true,go);break; + case ENTRY_FORGEFIRE_2: forge_fire[1] = go->GetGUID(); + if (forge_event[1] != NOT_STARTED)HandleGameObject(NULL,true,go);break; + case ENTRY_FORGEFIRE_3: forge_fire[2] = go->GetGUID(); + if (forge_event[2] != NOT_STARTED)HandleGameObject(NULL,true,go);break; + case ENTRY_GLOWING_ANVIL_1: forge_anvil[0] = go->GetGUID(); + if (forge_event[0] != NOT_STARTED)HandleGameObject(NULL,true,go);break; + case ENTRY_GLOWING_ANVIL_2: forge_anvil[1] = go->GetGUID(); + if (forge_event[1] != NOT_STARTED)HandleGameObject(NULL,true,go);break; + case ENTRY_GLOWING_ANVIL_3: forge_anvil[2] = go->GetGUID(); + if (forge_event[2] != NOT_STARTED)HandleGameObject(NULL,true,go);break; + case ENTRY_GIANT_PORTCULLIS_1: portcullis[0] = go->GetGUID(); + if (m_auiEncounter[2] == DONE)HandleGameObject(NULL,true,go);break; + case ENTRY_GIANT_PORTCULLIS_2: portcullis[1] = go->GetGUID(); + if (m_auiEncounter[2] == DONE)HandleGameObject(NULL,true,go);break; } } diff --git a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/instance_pinnacle.cpp b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/instance_pinnacle.cpp index c5ad6e7b7bf..65b93fa2b43 100644 --- a/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/instance_pinnacle.cpp +++ b/src/server/scripts/Northrend/UtgardeKeep/UtgardePinnacle/instance_pinnacle.cpp @@ -102,41 +102,41 @@ public: return false; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case BOSS_SVALA_SORROWGRAVE: uiSvalaSorrowgrave = pCreature->GetGUID(); break; - case BOSS_GORTOK_PALEHOOF: uiGortokPalehoof = pCreature->GetGUID(); break; - case BOSS_SKADI_RUTHLESS: uiSkadiTheRuthless = pCreature->GetGUID(); break; - case BOSS_KING_YMIRON: uiKingYmiron = pCreature->GetGUID(); break; - case MOB_FRENZIED_WORGEN: uiFrenziedWorgen = pCreature->GetGUID(); break; - case MOB_RAVENOUS_FURBOLG: uiRavenousFurbolg = pCreature->GetGUID(); break; - case MOB_MASSIVE_JORMUNGAR: uiMassiveJormungar = pCreature->GetGUID(); break; - case MOB_FEROCIOUS_RHINO: uiFerociousRhino = pCreature->GetGUID(); break; - case MOB_SVALA: uiSvala = pCreature->GetGUID(); break; - case MOB_PALEHOOF_ORB: uiPalehoofOrb = pCreature->GetGUID(); break; + case BOSS_SVALA_SORROWGRAVE: uiSvalaSorrowgrave = creature->GetGUID(); break; + case BOSS_GORTOK_PALEHOOF: uiGortokPalehoof = creature->GetGUID(); break; + case BOSS_SKADI_RUTHLESS: uiSkadiTheRuthless = creature->GetGUID(); break; + case BOSS_KING_YMIRON: uiKingYmiron = creature->GetGUID(); break; + case MOB_FRENZIED_WORGEN: uiFrenziedWorgen = creature->GetGUID(); break; + case MOB_RAVENOUS_FURBOLG: uiRavenousFurbolg = creature->GetGUID(); break; + case MOB_MASSIVE_JORMUNGAR: uiMassiveJormungar = creature->GetGUID(); break; + case MOB_FEROCIOUS_RHINO: uiFerociousRhino = creature->GetGUID(); break; + case MOB_SVALA: uiSvala = creature->GetGUID(); break; + case MOB_PALEHOOF_ORB: uiPalehoofOrb = creature->GetGUID(); break; } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case ENTRY_SKADI_THE_RUTHLESS_DOOR: - uiSkadiTheRuthlessDoor = pGo->GetGUID(); - if (m_auiEncounter[2] == DONE) HandleGameObject(NULL, true, pGo); + uiSkadiTheRuthlessDoor = go->GetGUID(); + if (m_auiEncounter[2] == DONE) HandleGameObject(NULL, true, go); break; case ENTRY_KING_YMIRON_DOOR: - uiKingYmironDoor = pGo->GetGUID(); - if (m_auiEncounter[3] == DONE) HandleGameObject(NULL, true, pGo); + uiKingYmironDoor = go->GetGUID(); + if (m_auiEncounter[3] == DONE) HandleGameObject(NULL, true, go); break; case ENTRY_GORK_PALEHOOF_SPHERE: - uiGortokPalehoofSphere = pGo->GetGUID(); + uiGortokPalehoofSphere = go->GetGUID(); if (m_auiEncounter[1] == DONE) { - HandleGameObject(NULL, true, pGo); - pGo->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); + HandleGameObject(NULL, true, go); + go->SetFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); } break; } 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 7ad0df957d3..8f672f586a8 100644 --- a/src/server/scripts/Northrend/VaultOfArchavon/instance_vault_of_archavon.cpp +++ b/src/server/scripts/Northrend/VaultOfArchavon/instance_vault_of_archavon.cpp @@ -68,7 +68,7 @@ public: return false; } - void OnCreatureCreate(Creature *creature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { switch(creature->GetEntry()) { diff --git a/src/server/scripts/Northrend/VioletHold/instance_violet_hold.cpp b/src/server/scripts/Northrend/VioletHold/instance_violet_hold.cpp index c32bbfaa0d1..ec22b8125e6 100644 --- a/src/server/scripts/Northrend/VioletHold/instance_violet_hold.cpp +++ b/src/server/scripts/Northrend/VioletHold/instance_violet_hold.cpp @@ -227,85 +227,85 @@ public: return false; } - void OnCreatureCreate(Creature* pCreature, bool add) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { case CREATURE_XEVOZZ: - uiXevozz = pCreature->GetGUID(); + uiXevozz = creature->GetGUID(); break; case CREATURE_LAVANTHOR: - uiLavanthor = pCreature->GetGUID(); + uiLavanthor = creature->GetGUID(); break; case CREATURE_ICHORON: - uiIchoron = pCreature->GetGUID(); + uiIchoron = creature->GetGUID(); break; case CREATURE_ZURAMAT: - uiZuramat = pCreature->GetGUID(); + uiZuramat = creature->GetGUID(); break; case CREATURE_EREKEM: - uiErekem = pCreature->GetGUID(); + uiErekem = creature->GetGUID(); break; case CREATURE_EREKEM_GUARD: if (uiCountErekemGuards < 2) { - uiErekemGuard[uiCountErekemGuards++] = pCreature->GetGUID(); - pCreature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE|UNIT_FLAG_NON_ATTACKABLE); + uiErekemGuard[uiCountErekemGuards++] = creature->GetGUID(); + creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE|UNIT_FLAG_NON_ATTACKABLE); } break; case CREATURE_MORAGG: - uiMoragg = pCreature->GetGUID(); + uiMoragg = creature->GetGUID(); break; case CREATURE_CYANIGOSA: - uiCyanigosa = pCreature->GetGUID(); - pCreature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE|UNIT_FLAG_NON_ATTACKABLE); + uiCyanigosa = creature->GetGUID(); + creature->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE|UNIT_FLAG_NON_ATTACKABLE); break; case CREATURE_SINCLARI: - uiSinclari = pCreature->GetGUID(); + uiSinclari = creature->GetGUID(); break; } - if (add && (pCreature->GetGUID() == uiFirstBoss || pCreature->GetGUID() == uiSecondBoss)) + if (creature->GetGUID() == uiFirstBoss || creature->GetGUID() == uiSecondBoss) { - pCreature->AllLootRemovedFromCorpse(); - pCreature->RemoveLootMode(1); + creature->AllLootRemovedFromCorpse(); + creature->RemoveLootMode(1); } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case GO_EREKEM_GUARD_1_DOOR: - uiErekemLeftGuardCell = pGo->GetGUID(); + uiErekemLeftGuardCell = go->GetGUID(); break; case GO_EREKEM_GUARD_2_DOOR: - uiErekemRightGuardCell = pGo->GetGUID(); + uiErekemRightGuardCell = go->GetGUID(); break; case GO_EREKEM_DOOR: - uiErekemCell = pGo->GetGUID(); + uiErekemCell = go->GetGUID(); break; case GO_ZURAMAT_DOOR: - uiZuramatCell = pGo->GetGUID(); + uiZuramatCell = go->GetGUID(); break; case GO_LAVANTHOR_DOOR: - uiLavanthorCell = pGo->GetGUID(); + uiLavanthorCell = go->GetGUID(); break; case GO_MORAGG_DOOR: - uiMoraggCell = pGo->GetGUID(); + uiMoraggCell = go->GetGUID(); break; case GO_ICHORON_DOOR: - uiIchoronCell = pGo->GetGUID(); + uiIchoronCell = go->GetGUID(); break; case GO_XEVOZZ_DOOR: - uiXevozzCell = pGo->GetGUID(); + uiXevozzCell = go->GetGUID(); break; case GO_MAIN_DOOR: - uiMainDoor = pGo->GetGUID(); + uiMainDoor = go->GetGUID(); break; case GO_ACTIVATION_CRYSTAL: if (uiCountActivationCrystals < 3) - uiActivationCrystal[uiCountActivationCrystals++] = pGo->GetGUID(); + uiActivationCrystal[uiCountActivationCrystals++] = go->GetGUID(); break; } } @@ -468,8 +468,8 @@ public: void SpawnPortal() { SetData(DATA_PORTAL_LOCATION, (GetData(DATA_PORTAL_LOCATION) + urand(1,5))%6); - if (Creature *pSinclari = instance->GetCreature(uiSinclari)) - if(Creature *portal = pSinclari->SummonCreature(CREATURE_TELEPORTATION_PORTAL,PortalLocation[GetData(DATA_PORTAL_LOCATION)],TEMPSUMMON_CORPSE_DESPAWN)) + if (Creature* pSinclari = instance->GetCreature(uiSinclari)) + if(Creature* portal = pSinclari->SummonCreature(CREATURE_TELEPORTATION_PORTAL,PortalLocation[GetData(DATA_PORTAL_LOCATION)],TEMPSUMMON_CORPSE_DESPAWN)) uiTeleportationPortal = portal->GetGUID(); } @@ -569,11 +569,11 @@ public: case 6: if (uiFirstBoss == 0) uiFirstBoss = urand(1,6); - if (Creature *pSinclari = instance->GetCreature(uiSinclari)) + if (Creature* pSinclari = instance->GetCreature(uiSinclari)) { - if(Creature *pPortal = pSinclari->SummonCreature(CREATURE_TELEPORTATION_PORTAL, MiddleRoomPortalSaboLocation, TEMPSUMMON_CORPSE_DESPAWN)) + if(Creature* pPortal = pSinclari->SummonCreature(CREATURE_TELEPORTATION_PORTAL, MiddleRoomPortalSaboLocation, TEMPSUMMON_CORPSE_DESPAWN)) uiSaboteurPortal = pPortal->GetGUID(); - if (Creature *pAzureSaboteur = pSinclari->SummonCreature(CREATURE_SABOTEOUR, MiddleRoomLocation, TEMPSUMMON_DEAD_DESPAWN)) + if (Creature* pAzureSaboteur = pSinclari->SummonCreature(CREATURE_SABOTEOUR, MiddleRoomLocation, TEMPSUMMON_DEAD_DESPAWN)) pAzureSaboteur->CastSpell(pAzureSaboteur, SABOTEUR_SHIELD_EFFECT, false); } break; @@ -583,17 +583,17 @@ public: { uiSecondBoss = urand(1,6); } while (uiSecondBoss == uiFirstBoss); - if (Creature *pSinclari = instance->GetCreature(uiSinclari)) + if (Creature* pSinclari = instance->GetCreature(uiSinclari)) { - if(Creature *pPortal = pSinclari->SummonCreature(CREATURE_TELEPORTATION_PORTAL, MiddleRoomPortalSaboLocation, TEMPSUMMON_CORPSE_DESPAWN)) + if(Creature* pPortal = pSinclari->SummonCreature(CREATURE_TELEPORTATION_PORTAL, MiddleRoomPortalSaboLocation, TEMPSUMMON_CORPSE_DESPAWN)) uiSaboteurPortal = pPortal->GetGUID(); - if (Creature *pAzureSaboteur = pSinclari->SummonCreature(CREATURE_SABOTEOUR, MiddleRoomLocation, TEMPSUMMON_DEAD_DESPAWN)) + if (Creature* pAzureSaboteur = pSinclari->SummonCreature(CREATURE_SABOTEOUR, MiddleRoomLocation, TEMPSUMMON_DEAD_DESPAWN)) pAzureSaboteur->CastSpell(pAzureSaboteur, SABOTEUR_SHIELD_EFFECT, false); } break; case 18: { - Creature *pSinclari = instance->GetCreature(uiSinclari); + Creature* pSinclari = instance->GetCreature(uiSinclari); if (pSinclari) pSinclari->SummonCreature(CREATURE_CYANIGOSA,CyanigosasSpawnLocation,TEMPSUMMON_DEAD_DESPAWN); break; @@ -727,7 +727,7 @@ public: } // Cyanigosa is spawned but not tranformed, prefight event - Creature *pCyanigosa = instance->GetCreature(uiCyanigosa); + Creature* pCyanigosa = instance->GetCreature(uiCyanigosa); if (pCyanigosa && !pCyanigosa->HasAura(CYANIGOSA_SPELL_TRANSFORM)) { if (uiCyanigosaEventTimer <= diff) @@ -788,9 +788,9 @@ public: // TODO: All visual, spells etc for (std::set<uint64>::const_iterator itr = trashMobs.begin(); itr != trashMobs.end(); ++itr) { - Creature* pCreature = instance->GetCreature(*itr); - if (pCreature && pCreature->isAlive()) - pCreature->CastSpell(pCreature,SPELL_ARCANE_LIGHTNING,true); // Who should cast the spell? + Creature* creature = instance->GetCreature(*itr); + if (creature && creature->isAlive()) + creature->CastSpell(creature,SPELL_ARCANE_LIGHTNING,true); // Who should cast the spell? } } 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 5a0187b1b9e..03d5302da4b 100644 --- a/src/server/scripts/Outland/Auchindoun/SethekkHalls/instance_sethekk_halls.cpp +++ b/src/server/scripts/Outland/Auchindoun/SethekkHalls/instance_sethekk_halls.cpp @@ -55,21 +55,21 @@ public: m_uiIkissDoorGUID = 0; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - if (pCreature->GetEntry() == NPC_ANZU) + if (creature->GetEntry() == NPC_ANZU) { if (AnzuEncounter >= IN_PROGRESS) - pCreature->DisappearAndDie(); + creature->DisappearAndDie(); else AnzuEncounter = IN_PROGRESS; } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - if (pGo->GetEntry() == IKISS_DOOR) - m_uiIkissDoorGUID = pGo->GetGUID(); + if (go->GetEntry() == IKISS_DOOR) + m_uiIkissDoorGUID = go->GetGUID(); } void SetData(uint32 type, uint32 data) 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 44134f6917c..3c8a3c2017d 100644 --- a/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/instance_shadow_labyrinth.cpp +++ b/src/server/scripts/Outland/Auchindoun/ShadowLabyrinth/instance_shadow_labyrinth.cpp @@ -80,32 +80,32 @@ public: return false; } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case REFECTORY_DOOR: - m_uiRefectoryDoorGUID = pGo->GetGUID(); + m_uiRefectoryDoorGUID = go->GetGUID(); if (m_auiEncounter[2] == DONE) - pGo->SetGoState(GO_STATE_ACTIVE); + go->SetGoState(GO_STATE_ACTIVE); break; case SCREAMING_HALL_DOOR: - m_uiScreamingHallDoorGUID = pGo->GetGUID(); + m_uiScreamingHallDoorGUID = go->GetGUID(); if (m_auiEncounter[3] == DONE) - pGo->SetGoState(GO_STATE_ACTIVE); + go->SetGoState(GO_STATE_ACTIVE); break; } } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { case 18732: - m_uiGrandmasterVorpil = pCreature->GetGUID(); + m_uiGrandmasterVorpil = creature->GetGUID(); break; case 18796: - if (pCreature->isAlive()) + if (creature->isAlive()) { ++m_uiFelOverseerCount; sLog.outDebug("TSCR: Shadow Labyrinth: counting %u Fel Overseers.",m_uiFelOverseerCount); diff --git a/src/server/scripts/Outland/BlackTemple/instance_black_temple.cpp b/src/server/scripts/Outland/BlackTemple/instance_black_temple.cpp index cac9ebbc025..a7e6dee3271 100644 --- a/src/server/scripts/Outland/BlackTemple/instance_black_temple.cpp +++ b/src/server/scripts/Outland/BlackTemple/instance_black_temple.cpp @@ -140,51 +140,51 @@ public: return NULL; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case 22887: Najentus = pCreature->GetGUID(); break; - case 23089: Akama = pCreature->GetGUID(); break; - case 22990: Akama_Shade = pCreature->GetGUID(); break; - case 22841: ShadeOfAkama = pCreature->GetGUID(); break; - case 22898: Supremus = pCreature->GetGUID(); break; - case 22917: IllidanStormrage = pCreature->GetGUID(); break; - case 22949: GathiosTheShatterer = pCreature->GetGUID(); break; - case 22950: HighNethermancerZerevor = pCreature->GetGUID(); break; - case 22951: LadyMalande = pCreature->GetGUID(); break; - case 22952: VerasDarkshadow = pCreature->GetGUID(); break; - case 23426: IllidariCouncil = pCreature->GetGUID(); break; - case 23499: BloodElfCouncilVoice = pCreature->GetGUID(); break; + case 22887: Najentus = creature->GetGUID(); break; + case 23089: Akama = creature->GetGUID(); break; + case 22990: Akama_Shade = creature->GetGUID(); break; + case 22841: ShadeOfAkama = creature->GetGUID(); break; + case 22898: Supremus = creature->GetGUID(); break; + case 22917: IllidanStormrage = creature->GetGUID(); break; + case 22949: GathiosTheShatterer = creature->GetGUID(); break; + case 22950: HighNethermancerZerevor = creature->GetGUID(); break; + case 22951: LadyMalande = creature->GetGUID(); break; + case 22952: VerasDarkshadow = creature->GetGUID(); break; + case 23426: IllidariCouncil = creature->GetGUID(); break; + case 23499: BloodElfCouncilVoice = creature->GetGUID(); break; } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { - case 185483: NajentusGate = pGo->GetGUID();// Gate past Naj'entus (at the entrance to Supermoose's courtyards) - if (m_auiEncounter[0] == DONE)HandleGameObject(NULL,true,pGo);break; - case 185882: MainTempleDoors = pGo->GetGUID();// Main Temple Doors - right past Supermoose (Supremus) - if (m_auiEncounter[1] == DONE)HandleGameObject(NULL,true,pGo);break; - case 185478: ShadeOfAkamaDoor = pGo->GetGUID();break; - case 185480: CommonDoor = pGo->GetGUID(); - if (m_auiEncounter[3] == DONE)HandleGameObject(NULL,true,pGo);break; - case 186153: TeronDoor = pGo->GetGUID(); - if (m_auiEncounter[3] == DONE)HandleGameObject(NULL,true,pGo);break; - case 185892: GuurtogDoor = pGo->GetGUID(); - if (m_auiEncounter[4] == DONE)HandleGameObject(NULL,true,pGo);break; - case 185479: TempleDoor = pGo->GetGUID(); - if (m_auiEncounter[5] == DONE)HandleGameObject(NULL,true,pGo);break; - case 185482: MotherDoor = pGo->GetGUID(); - if (m_auiEncounter[6] == DONE)HandleGameObject(NULL,true,pGo);break; - case 185481: CouncilDoor = pGo->GetGUID(); - if (m_auiEncounter[7] == DONE)HandleGameObject(NULL,true,pGo);break; - case 186152: SimpleDoor = pGo->GetGUID(); - if (m_auiEncounter[7] == DONE)HandleGameObject(NULL,true,pGo);break; - case 185905: IllidanGate = pGo->GetGUID(); break; // Gate leading to Temple Summit - case 186261: IllidanDoor[0] = pGo->GetGUID(); break; // Right door at Temple Summit - case 186262: IllidanDoor[1] = pGo->GetGUID(); break; // Left door at Temple Summit + case 185483: NajentusGate = go->GetGUID();// Gate past Naj'entus (at the entrance to Supermoose's courtyards) + if (m_auiEncounter[0] == DONE)HandleGameObject(NULL,true,go);break; + case 185882: MainTempleDoors = go->GetGUID();// Main Temple Doors - right past Supermoose (Supremus) + if (m_auiEncounter[1] == DONE)HandleGameObject(NULL,true,go);break; + case 185478: ShadeOfAkamaDoor = go->GetGUID();break; + case 185480: CommonDoor = go->GetGUID(); + if (m_auiEncounter[3] == DONE)HandleGameObject(NULL,true,go);break; + case 186153: TeronDoor = go->GetGUID(); + if (m_auiEncounter[3] == DONE)HandleGameObject(NULL,true,go);break; + case 185892: GuurtogDoor = go->GetGUID(); + if (m_auiEncounter[4] == DONE)HandleGameObject(NULL,true,go);break; + case 185479: TempleDoor = go->GetGUID(); + if (m_auiEncounter[5] == DONE)HandleGameObject(NULL,true,go);break; + case 185482: MotherDoor = go->GetGUID(); + if (m_auiEncounter[6] == DONE)HandleGameObject(NULL,true,go);break; + case 185481: CouncilDoor = go->GetGUID(); + if (m_auiEncounter[7] == DONE)HandleGameObject(NULL,true,go);break; + case 186152: SimpleDoor = go->GetGUID(); + if (m_auiEncounter[7] == DONE)HandleGameObject(NULL,true,go);break; + case 185905: IllidanGate = go->GetGUID(); break; // Gate leading to Temple Summit + case 186261: IllidanDoor[0] = go->GetGUID(); break; // Right door at Temple Summit + case 186262: IllidanDoor[1] = go->GetGUID(); break; // Left door at Temple Summit } } 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 93c91f9b4c1..f3970a1665e 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lady_vashj.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lady_vashj.cpp @@ -492,8 +492,7 @@ public: //EnchantedElemental_Timer if (EnchantedElemental_Timer <= diff) { - Creature *Elemental; - Elemental = me->SummonCreature(ENCHANTED_ELEMENTAL, ElementPos[EnchantedElemental_Pos][0], ElementPos[EnchantedElemental_Pos][1], ElementPos[EnchantedElemental_Pos][2], ElementPos[EnchantedElemental_Pos][3], TEMPSUMMON_CORPSE_DESPAWN, 0); + me->SummonCreature(ENCHANTED_ELEMENTAL, ElementPos[EnchantedElemental_Pos][0], ElementPos[EnchantedElemental_Pos][1], ElementPos[EnchantedElemental_Pos][2], ElementPos[EnchantedElemental_Pos][3], TEMPSUMMON_CORPSE_DESPAWN, 0); if (EnchantedElemental_Pos == 7) EnchantedElemental_Pos = 0; @@ -506,9 +505,8 @@ public: //TaintedElemental_Timer if (TaintedElemental_Timer <= diff) { - Creature *Tain_Elemental; uint32 pos = rand()%8; - Tain_Elemental = me->SummonCreature(TAINTED_ELEMENTAL, ElementPos[pos][0], ElementPos[pos][1], ElementPos[pos][2], ElementPos[pos][3], TEMPSUMMON_DEAD_DESPAWN, 0); + me->SummonCreature(TAINTED_ELEMENTAL, ElementPos[pos][0], ElementPos[pos][1], ElementPos[pos][2], ElementPos[pos][3], TEMPSUMMON_DEAD_DESPAWN, 0); TaintedElemental_Timer = 120000; } else TaintedElemental_Timer -= diff; 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 670230c1eda..36d8df38744 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lurker_below.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/boss_lurker_below.cpp @@ -312,7 +312,7 @@ public: } else WaterboltTimer -= diff; } - if (!UpdateCombatState()) + if (!UpdateVictim()) return; DoMeleeAttackIfReady(); 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 79038ed4373..77730535ffb 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/instance_serpent_shrine.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SerpentShrine/instance_serpent_shrine.cpp @@ -52,9 +52,9 @@ class go_bridge_console : public GameObjectScript public: go_bridge_console() : GameObjectScript("go_bridge_console") { } - bool OnGossipHello(Player* /*pPlayer*/, GameObject* pGo) + bool OnGossipHello(Player* /*pPlayer*/, GameObject* go) { - InstanceScript* pInstance = pGo->GetInstanceScript(); + InstanceScript* pInstance = go->GetInstanceScript(); if (!pInstance) return false; @@ -210,28 +210,28 @@ public: } else FrenzySpawnTimer -= diff; } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case 184568: - ControlConsole = pGo->GetGUID(); - pGo->setActive(true); + ControlConsole = go->GetGUID(); + go->setActive(true); break; case 184203: - BridgePart[0] = pGo->GetGUID(); - pGo->setActive(true); + BridgePart[0] = go->GetGUID(); + go->setActive(true); break; case 184204: - BridgePart[1] = pGo->GetGUID(); - pGo->setActive(true); + BridgePart[1] = go->GetGUID(); + go->setActive(true); break; case 184205: - BridgePart[2] = pGo->GetGUID(); - pGo->setActive(true); + BridgePart[2] = go->GetGUID(); + go->setActive(true); break; case GAMEOBJECT_FISHINGNODE_ENTRY://no way checking if fish is hooked, so we create a timed event if (LurkerSubEvent == LURKER_NOT_STARTED) @@ -243,20 +243,20 @@ public: } } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case 21212: LadyVashj = pCreature->GetGUID(); break; - case 21214: Karathress = pCreature->GetGUID(); break; - case 21966: Sharkkis = pCreature->GetGUID(); break; - case 21217: LurkerBelow = pCreature->GetGUID(); break; - case 21965: Tidalvess = pCreature->GetGUID(); break; - case 21964: Caribdis = pCreature->GetGUID(); break; - case 21215: LeotherasTheBlind = pCreature->GetGUID(); break; + case 21212: LadyVashj = creature->GetGUID(); break; + case 21214: Karathress = creature->GetGUID(); break; + case 21966: Sharkkis = creature->GetGUID(); break; + case 21217: LurkerBelow = creature->GetGUID(); break; + case 21965: Tidalvess = creature->GetGUID(); break; + case 21964: Caribdis = creature->GetGUID(); break; + case 21215: LeotherasTheBlind = creature->GetGUID(); break; /*case TRASHMOB_COILFANG_PRIESTESS: case TRASHMOB_COILFANG_SHATTERER: - if (pCreature->isAlive()) + if (creature->isAlive()) ++TrashCount; break;*/ } 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 acdcd59187c..4a9f8ef3c6f 100644 --- a/src/server/scripts/Outland/CoilfangReservoir/SteamVault/instance_steam_vault.cpp +++ b/src/server/scripts/Outland/CoilfangReservoir/SteamVault/instance_steam_vault.cpp @@ -43,17 +43,17 @@ class go_main_chambers_access_panel : public GameObjectScript public: go_main_chambers_access_panel() : GameObjectScript("go_main_chambers_access_panel") { } - bool OnGossipHello(Player* /*pPlayer*/, GameObject* pGo) + bool OnGossipHello(Player* /*pPlayer*/, GameObject* go) { - InstanceScript* pInstance = pGo->GetInstanceScript(); + InstanceScript* pInstance = go->GetInstanceScript(); if (!pInstance) return false; - if (pGo->GetEntry() == ACCESS_PANEL_HYDRO && (pInstance->GetData(TYPE_HYDROMANCER_THESPIA) == DONE || pInstance->GetData(TYPE_HYDROMANCER_THESPIA) == SPECIAL)) + if (go->GetEntry() == ACCESS_PANEL_HYDRO && (pInstance->GetData(TYPE_HYDROMANCER_THESPIA) == DONE || pInstance->GetData(TYPE_HYDROMANCER_THESPIA) == SPECIAL)) pInstance->SetData(TYPE_HYDROMANCER_THESPIA,SPECIAL); - if (pGo->GetEntry() == ACCESS_PANEL_MEK && (pInstance->GetData(TYPE_MEKGINEER_STEAMRIGGER) == DONE || pInstance->GetData(TYPE_MEKGINEER_STEAMRIGGER) == SPECIAL)) + if (go->GetEntry() == ACCESS_PANEL_MEK && (pInstance->GetData(TYPE_MEKGINEER_STEAMRIGGER) == DONE || pInstance->GetData(TYPE_MEKGINEER_STEAMRIGGER) == SPECIAL)) pInstance->SetData(TYPE_MEKGINEER_STEAMRIGGER,SPECIAL); return true; @@ -106,23 +106,23 @@ public: return false; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case 17797: ThespiaGUID = pCreature->GetGUID(); break; - case 17796: MekgineerGUID = pCreature->GetGUID(); break; - case 17798: KalithreshGUID = pCreature->GetGUID(); break; + case 17797: ThespiaGUID = creature->GetGUID(); break; + case 17796: MekgineerGUID = creature->GetGUID(); break; + case 17798: KalithreshGUID = creature->GetGUID(); break; } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { - case MAIN_CHAMBERS_DOOR: MainChambersDoor = pGo->GetGUID(); break; - case ACCESS_PANEL_HYDRO: AccessPanelHydro = pGo->GetGUID(); break; - case ACCESS_PANEL_MEK: AccessPanelMek = pGo->GetGUID(); break; + case MAIN_CHAMBERS_DOOR: MainChambersDoor = go->GetGUID(); break; + case ACCESS_PANEL_HYDRO: AccessPanelHydro = go->GetGUID(); break; + case ACCESS_PANEL_MEK: AccessPanelMek = go->GetGUID(); break; } } diff --git a/src/server/scripts/Outland/GruulsLair/instance_gruuls_lair.cpp b/src/server/scripts/Outland/GruulsLair/instance_gruuls_lair.cpp index c5e12448b28..3e1da89564f 100644 --- a/src/server/scripts/Outland/GruulsLair/instance_gruuls_lair.cpp +++ b/src/server/scripts/Outland/GruulsLair/instance_gruuls_lair.cpp @@ -82,27 +82,27 @@ public: return false; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case 18835: KigglerTheCrazed = pCreature->GetGUID(); break; - case 18836: BlindeyeTheSeer = pCreature->GetGUID(); break; - case 18834: OlmTheSummoner = pCreature->GetGUID(); break; - case 18832: KroshFirehand = pCreature->GetGUID(); break; - case 18831: Maulgar = pCreature->GetGUID(); break; + case 18835: KigglerTheCrazed = creature->GetGUID(); break; + case 18836: BlindeyeTheSeer = creature->GetGUID(); break; + case 18834: OlmTheSummoner = creature->GetGUID(); break; + case 18832: KroshFirehand = creature->GetGUID(); break; + case 18831: Maulgar = creature->GetGUID(); break; } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case 184468: - MaulgarDoor = pGo->GetGUID(); - if (m_auiEncounter[0] == DONE) HandleGameObject(NULL, true, pGo); + MaulgarDoor = go->GetGUID(); + if (m_auiEncounter[0] == DONE) HandleGameObject(NULL, true, go); break; - case 184662: GruulDoor = pGo->GetGUID(); break; + case 184662: GruulDoor = go->GetGUID(); break; } } 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 6e47efd6dc1..c756bbd168c 100644 --- a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/instance_blood_furnace.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/instance_blood_furnace.cpp @@ -90,53 +90,48 @@ class instance_blood_furnace : public InstanceMapScript PrisonCell8GUID = 0; } - void OnCreatureCreate(Creature* pCreature, bool add) + void OnCreatureCreate(Creature* creature) { - if (!add) - return; - - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { - case 17381: The_MakerGUID = pCreature->GetGUID(); break; - case 17380: BroggokGUID = pCreature->GetGUID(); break; - case 17377: Kelidan_The_BreakerGUID = pCreature->GetGUID(); break; + case 17381: The_MakerGUID = creature->GetGUID(); break; + case 17380: BroggokGUID = creature->GetGUID(); break; + case 17377: Kelidan_The_BreakerGUID = creature->GetGUID(); break; } } - void OnGameObjectCreate(GameObject* pGo, bool add) + void OnGameObjectCreate(GameObject* go) { - if (!add) - return; - if (pGo->GetEntry() == 181766) //Final exit door - Door1GUID = pGo->GetGUID(); - if (pGo->GetEntry() == 181811) //The Maker Front door - Door2GUID = pGo->GetGUID(); - if (pGo->GetEntry() == 181812) //The Maker Rear door - Door3GUID = pGo->GetGUID(); - if (pGo->GetEntry() == 181822) //Broggok Front door - Door4GUID = pGo->GetGUID(); - if (pGo->GetEntry() == 181819) //Broggok Rear door - Door5GUID = pGo->GetGUID(); - if (pGo->GetEntry() == 181823) //Kelidan exit door - Door6GUID = pGo->GetGUID(); - - if (pGo->GetEntry() == 181813) //The Maker prison cell front right - PrisonCell1GUID = pGo->GetGUID(); - if (pGo->GetEntry() == 181814) //The Maker prison cell back right - PrisonCell2GUID = pGo->GetGUID(); - if (pGo->GetEntry() == 181816) //The Maker prison cell front left - PrisonCell3GUID = pGo->GetGUID(); - if (pGo->GetEntry() == 181815) //The Maker prison cell back left - PrisonCell4GUID = pGo->GetGUID(); - if (pGo->GetEntry() == 181821) //Broggok prison cell front right - PrisonCell5GUID = pGo->GetGUID(); - if (pGo->GetEntry() == 181818) //Broggok prison cell back right - PrisonCell6GUID = pGo->GetGUID(); - if (pGo->GetEntry() == 181820) //Broggok prison cell front left - PrisonCell7GUID = pGo->GetGUID(); - if (pGo->GetEntry() == 181817) //Broggok prison cell back left - PrisonCell8GUID = pGo->GetGUID(); + if (go->GetEntry() == 181766) //Final exit door + Door1GUID = go->GetGUID(); + if (go->GetEntry() == 181811) //The Maker Front door + Door2GUID = go->GetGUID(); + if (go->GetEntry() == 181812) //The Maker Rear door + Door3GUID = go->GetGUID(); + if (go->GetEntry() == 181822) //Broggok Front door + Door4GUID = go->GetGUID(); + if (go->GetEntry() == 181819) //Broggok Rear door + Door5GUID = go->GetGUID(); + if (go->GetEntry() == 181823) //Kelidan exit door + Door6GUID = go->GetGUID(); + + if (go->GetEntry() == 181813) //The Maker prison cell front right + PrisonCell1GUID = go->GetGUID(); + if (go->GetEntry() == 181814) //The Maker prison cell back right + PrisonCell2GUID = go->GetGUID(); + if (go->GetEntry() == 181816) //The Maker prison cell front left + PrisonCell3GUID = go->GetGUID(); + if (go->GetEntry() == 181815) //The Maker prison cell back left + PrisonCell4GUID = go->GetGUID(); + if (go->GetEntry() == 181821) //Broggok prison cell front right + PrisonCell5GUID = go->GetGUID(); + if (go->GetEntry() == 181818) //Broggok prison cell back right + PrisonCell6GUID = go->GetGUID(); + if (go->GetEntry() == 181820) //Broggok prison cell front left + PrisonCell7GUID = go->GetGUID(); + if (go->GetEntry() == 181817) //Broggok prison cell back left + PrisonCell8GUID = go->GetGUID(); } uint64 GetData64(uint32 data) 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 7c754ba2d09..73214aabcc9 100644 --- a/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/instance_hellfire_ramparts.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/HellfireRamparts/instance_hellfire_ramparts.cpp @@ -51,15 +51,15 @@ class instance_ramparts : public InstanceMapScript m_uiChestHGUID = 0; } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case 185168: - m_uiChestNGUID = pGo->GetGUID(); + m_uiChestNGUID = go->GetGUID(); break; case 185169: - m_uiChestHGUID = pGo->GetGUID(); + m_uiChestHGUID = go->GetGUID(); break; } } 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 1c733b9b5f0..c44c0db6c33 100644 --- a/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/instance_magtheridons_lair.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/MagtheridonsLair/instance_magtheridons_lair.cpp @@ -85,28 +85,28 @@ class instance_magtheridons_lair : public InstanceMapScript return false; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { case 17257: - MagtheridonGUID = pCreature->GetGUID(); + MagtheridonGUID = creature->GetGUID(); break; case 17256: - ChannelerGUID.insert(pCreature->GetGUID()); + ChannelerGUID.insert(creature->GetGUID()); break; } } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case 181713: - pGo->SetUInt32Value(GAMEOBJECT_FLAGS, 0); + go->SetUInt32Value(GAMEOBJECT_FLAGS, 0); break; case 183847: - DoorGUID = pGo->GetGUID(); + DoorGUID = go->GetGUID(); break; case 184653: // hall case 184634: // six columns @@ -115,7 +115,7 @@ class instance_magtheridons_lair : public InstanceMapScript case 184637: case 184638: case 184639: - ColumnGUID.insert(pGo->GetGUID()); + ColumnGUID.insert(go->GetGUID()); break; } } @@ -150,7 +150,7 @@ class instance_magtheridons_lair : public InstanceMapScript m_auiEncounter[1] = NOT_STARTED; for (std::set<uint64>::const_iterator i = ChannelerGUID.begin(); i != ChannelerGUID.end(); ++i) { - if (Creature *Channeler = instance->GetCreature(*i)) + if (Creature* Channeler = instance->GetCreature(*i)) { if (Channeler->isAlive()) Channeler->AI()->EnterEvadeMode(); @@ -169,12 +169,12 @@ class instance_magtheridons_lair : public InstanceMapScript // Let all five channelers aggro. for (std::set<uint64>::const_iterator i = ChannelerGUID.begin(); i != ChannelerGUID.end(); ++i) { - Creature *Channeler = instance->GetCreature(*i); + Creature* Channeler = instance->GetCreature(*i); if (Channeler && Channeler->isAlive()) Channeler->AI()->AttackStart(Channeler->SelectNearestTarget(999)); } // Release Magtheridon after two minutes. - Creature *Magtheridon = instance->GetCreature(MagtheridonGUID); + Creature* Magtheridon = instance->GetCreature(MagtheridonGUID); if (Magtheridon && Magtheridon->isAlive()) { Magtheridon->MonsterTextEmote(EMOTE_BONDS_WEAKEN, 0); @@ -186,7 +186,7 @@ class instance_magtheridons_lair : public InstanceMapScript case DONE: // Add buff and check if all channelers are dead. for (std::set<uint64>::const_iterator i = ChannelerGUID.begin(); i != ChannelerGUID.end(); ++i) { - Creature *Channeler = instance->GetCreature(*i); + Creature* Channeler = instance->GetCreature(*i); if (Channeler && Channeler->isAlive()) { //Channeler->CastSpell(Channeler, SPELL_SOUL_TRANSFER, true); @@ -221,7 +221,7 @@ class instance_magtheridons_lair : public InstanceMapScript { if (CageTimer <= diff) { - Creature *Magtheridon = instance->GetCreature(MagtheridonGUID); + Creature* Magtheridon = instance->GetCreature(MagtheridonGUID); if (Magtheridon && Magtheridon->isAlive()) { Magtheridon->clearUnitState(UNIT_STAT_STUNNED); @@ -237,7 +237,7 @@ class instance_magtheridons_lair : public InstanceMapScript { for (std::set<uint64>::const_iterator i = ChannelerGUID.begin(); i != ChannelerGUID.end(); ++i) { - if (Creature *Channeler = instance->GetCreature(*i)) + if (Creature* Channeler = instance->GetCreature(*i)) { if (Channeler->isAlive()) Channeler->AI()->EnterEvadeMode(); 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 5a14125c3f2..3a172645f12 100644 --- a/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/instance_shattered_halls.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/ShatteredHalls/instance_shattered_halls.cpp @@ -53,22 +53,22 @@ class instance_shattered_halls : public InstanceMapScript nethekurseDoorGUID = 0; } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { case DOOR_NETHEKURSE: - nethekurseDoorGUID = pGo->GetGUID(); + nethekurseDoorGUID = go->GetGUID(); break; } } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { case 16807: - nethekurseGUID = pCreature->GetGUID(); + nethekurseGUID = creature->GetGUID(); break; } } 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 3f1efa9702a..fbfd25e3a47 100644 --- a/src/server/scripts/Outland/TempestKeep/Eye/instance_the_eye.cpp +++ b/src/server/scripts/Outland/TempestKeep/Eye/instance_the_eye.cpp @@ -83,30 +83,30 @@ class instance_the_eye : public InstanceMapScript return false; } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - switch(pCreature->GetEntry()) + switch(creature->GetEntry()) { case 20064: - ThaladredTheDarkener = pCreature->GetGUID(); + ThaladredTheDarkener = creature->GetGUID(); break; case 20063: - MasterEngineerTelonicus = pCreature->GetGUID(); + MasterEngineerTelonicus = creature->GetGUID(); break; case 20062: - GrandAstromancerCapernian = pCreature->GetGUID(); + GrandAstromancerCapernian = creature->GetGUID(); break; case 20060: - LordSanguinar = pCreature->GetGUID(); + LordSanguinar = creature->GetGUID(); break; case 19622: - Kaelthas = pCreature->GetGUID(); + Kaelthas = creature->GetGUID(); break; case 18805: - Astromancer = pCreature->GetGUID(); + Astromancer = creature->GetGUID(); break; case 19514: - Alar = pCreature->GetGUID(); + Alar = creature->GetGUID(); break; } } diff --git a/src/server/scripts/Outland/TempestKeep/arcatraz/instance_arcatraz.cpp b/src/server/scripts/Outland/TempestKeep/arcatraz/instance_arcatraz.cpp index c617246918a..7fc808c8155 100644 --- a/src/server/scripts/Outland/TempestKeep/arcatraz/instance_arcatraz.cpp +++ b/src/server/scripts/Outland/TempestKeep/arcatraz/instance_arcatraz.cpp @@ -100,26 +100,26 @@ class instance_arcatraz : public InstanceMapScript } - void OnGameObjectCreate(GameObject* pGo, bool /*add*/) + void OnGameObjectCreate(GameObject* go) { - switch(pGo->GetEntry()) + switch(go->GetEntry()) { - case CONTAINMENT_CORE_SECURITY_FIELD_ALPHA: Containment_Core_Security_Field_AlphaGUID = pGo->GetGUID(); break; - case CONTAINMENT_CORE_SECURITY_FIELD_BETA: Containment_Core_Security_Field_BetaGUID = pGo->GetGUID(); break; - case POD_ALPHA: Pod_AlphaGUID = pGo->GetGUID(); break; - case POD_GAMMA: Pod_GammaGUID = pGo->GetGUID(); break; - case POD_BETA: Pod_BetaGUID = pGo->GetGUID(); break; - case POD_DELTA: Pod_DeltaGUID = pGo->GetGUID(); break; - case POD_OMEGA: Pod_OmegaGUID = pGo->GetGUID(); break; - case SEAL_SPHERE: GoSphereGUID = pGo->GetGUID(); break; - //case WARDENS_SHIELD: Wardens_ShieldGUID = pGo->GetGUID(); break; + case CONTAINMENT_CORE_SECURITY_FIELD_ALPHA: Containment_Core_Security_Field_AlphaGUID = go->GetGUID(); break; + case CONTAINMENT_CORE_SECURITY_FIELD_BETA: Containment_Core_Security_Field_BetaGUID = go->GetGUID(); break; + case POD_ALPHA: Pod_AlphaGUID = go->GetGUID(); break; + case POD_GAMMA: Pod_GammaGUID = go->GetGUID(); break; + case POD_BETA: Pod_BetaGUID = go->GetGUID(); break; + case POD_DELTA: Pod_DeltaGUID = go->GetGUID(); break; + case POD_OMEGA: Pod_OmegaGUID = go->GetGUID(); break; + case SEAL_SPHERE: GoSphereGUID = go->GetGUID(); break; + //case WARDENS_SHIELD: Wardens_ShieldGUID = go->GetGUID(); break; } } - void OnCreatureCreate(Creature* pCreature, bool /*add*/) + void OnCreatureCreate(Creature* creature) { - if (pCreature->GetEntry() == MELLICHAR) - MellicharGUID = pCreature->GetGUID(); + if (creature->GetEntry() == MELLICHAR) + MellicharGUID = creature->GetGUID(); } void SetData(uint32 type, uint32 data) @@ -132,16 +132,16 @@ class instance_arcatraz : public InstanceMapScript case TYPE_DALLIAH: if (data == DONE) { - if (GameObject *pGo = instance->GetGameObject(Containment_Core_Security_Field_BetaGUID)) - pGo->UseDoorOrButton(); + if (GameObject* go = instance->GetGameObject(Containment_Core_Security_Field_BetaGUID)) + go->UseDoorOrButton(); } m_auiEncounter[1] = data; break; case TYPE_SOCCOTHRATES: if (data == DONE) { - if (GameObject *pGo = instance->GetGameObject(Containment_Core_Security_Field_AlphaGUID)) - pGo->UseDoorOrButton(); + if (GameObject* go = instance->GetGameObject(Containment_Core_Security_Field_AlphaGUID)) + go->UseDoorOrButton(); } m_auiEncounter[2] = data; break; @@ -158,47 +158,47 @@ class instance_arcatraz : public InstanceMapScript break; case TYPE_WARDEN_1: if (data == IN_PROGRESS) - if (GameObject *pGo = instance->GetGameObject(Pod_AlphaGUID)) - pGo->UseDoorOrButton(); + if (GameObject* go = instance->GetGameObject(Pod_AlphaGUID)) + go->UseDoorOrButton(); m_auiEncounter[4] = data; break; case TYPE_WARDEN_2: if (data == IN_PROGRESS) { - if (GameObject *pGo = instance->GetGameObject(Pod_BetaGUID)) - pGo->UseDoorOrButton(); + if (GameObject* go = instance->GetGameObject(Pod_BetaGUID)) + go->UseDoorOrButton(); } m_auiEncounter[5] = data; break; case TYPE_WARDEN_3: if (data == IN_PROGRESS) { - if (GameObject *pGo = instance->GetGameObject(Pod_DeltaGUID)) - pGo->UseDoorOrButton(); + if (GameObject* go = instance->GetGameObject(Pod_DeltaGUID)) + go->UseDoorOrButton(); } m_auiEncounter[6] = data; break; case TYPE_WARDEN_4: if (data == IN_PROGRESS) { - if (GameObject *pGo = instance->GetGameObject(Pod_GammaGUID)) - pGo->UseDoorOrButton(); + if (GameObject* go = instance->GetGameObject(Pod_GammaGUID)) + go->UseDoorOrButton(); } m_auiEncounter[7] = data; break; case TYPE_WARDEN_5: if (data == IN_PROGRESS) { - if (GameObject *pGo = instance->GetGameObject(Pod_OmegaGUID)) - pGo->UseDoorOrButton(); + if (GameObject* go = instance->GetGameObject(Pod_OmegaGUID)) + go->UseDoorOrButton(); } m_auiEncounter[8] = data; break; case TYPE_SHIELD_OPEN: if (data == IN_PROGRESS) { - if (GameObject *pGo = instance->GetGameObject(Wardens_ShieldGUID)) - pGo->UseDoorOrButton(); + if (GameObject* go = instance->GetGameObject(Wardens_ShieldGUID)) + go->UseDoorOrButton(); } break; } diff --git a/src/server/scripts/Spells/spell_dk.cpp b/src/server/scripts/Spells/spell_dk.cpp index 766ff5acb4f..907f1789d95 100644 --- a/src/server/scripts/Spells/spell_dk.cpp +++ b/src/server/scripts/Spells/spell_dk.cpp @@ -140,7 +140,7 @@ public: Unit* caster = GetCaster(); if (Unit* unitTarget = GetHitUnit()) { - int32 bp = (GetHitDamage() * GetEffectValue() * unitTarget->GetDiseasesByCaster(caster->GetGUID())) / 100; + int32 bp = CalculatePctN(GetHitDamage(), GetEffectValue() * unitTarget->GetDiseasesByCaster(caster->GetGUID())); caster->CastCustomSpell(unitTarget, DK_SPELL_SCOURGE_STRIKE_TRIGGERED, &bp, NULL, NULL, true); } } diff --git a/src/server/scripts/Spells/spell_generic.cpp b/src/server/scripts/Spells/spell_generic.cpp index 188a859422f..8e943d13b1f 100644 --- a/src/server/scripts/Spells/spell_generic.cpp +++ b/src/server/scripts/Spells/spell_generic.cpp @@ -106,13 +106,13 @@ public: void HandleEffectPeriodic(AuraEffect const * /*aurEff*/, AuraApplication const * aurApp) { - if (Unit* pTarget = aurApp->GetTarget()) - if (Player* pPlayerTarget = pTarget->ToPlayer()) - if (pPlayerTarget->IsFalling()) - { - pPlayerTarget->RemoveAurasDueToSpell(SPELL_PARACHUTE); - pPlayerTarget->CastSpell(pPlayerTarget, SPELL_PARACHUTE_BUFF, true); - } + Unit* pTarget = aurApp->GetTarget(); + if (Player* pPlayerTarget = pTarget->ToPlayer()) + if (pPlayerTarget->IsFalling()) + { + pPlayerTarget->RemoveAurasDueToSpell(SPELL_PARACHUTE); + pPlayerTarget->CastSpell(pPlayerTarget, SPELL_PARACHUTE_BUFF, true); + } } void Register() @@ -246,17 +246,17 @@ public: void HandleEffectPeriodic(AuraEffect const * aurEff, AuraApplication const * aurApp) { - if (Unit* pTarget = aurApp->GetTarget()) - if (Unit* pCaster = GetCaster()) - { - int32 lifeLeeched = pTarget->CountPctFromMaxHealth(aurEff->GetAmount()); - if (lifeLeeched < 250) - lifeLeeched = 250; - // Damage - pCaster->CastCustomSpell(pTarget, SPELL_LEECHING_SWARM_DMG, &lifeLeeched, 0, 0, false); - // Heal - pCaster->CastCustomSpell(pCaster, SPELL_LEECHING_SWARM_HEAL, &lifeLeeched, 0, 0, false); - } + Unit* pTarget = aurApp->GetTarget(); + if (Unit* pCaster = GetCaster()) + { + int32 lifeLeeched = pTarget->CountPctFromMaxHealth(aurEff->GetAmount()); + if (lifeLeeched < 250) + lifeLeeched = 250; + // Damage + pCaster->CastCustomSpell(pTarget, SPELL_LEECHING_SWARM_DMG, &lifeLeeched, 0, 0, false); + // Heal + pCaster->CastCustomSpell(pCaster, SPELL_LEECHING_SWARM_HEAL, &lifeLeeched, 0, 0, false); + } } void Register() @@ -408,8 +408,6 @@ class spell_creature_permanent_feign_death : public SpellScriptLoader void HandleEffectApply(AuraEffect const * /*aurEff*/, AuraApplication const * aurApp, AuraEffectHandleModes /*mode*/) { Unit* pTarget = aurApp->GetTarget(); - if (!pTarget) - return; pTarget->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_DEAD); pTarget->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FEIGN_DEATH); @@ -528,20 +526,16 @@ class spell_gen_shroud_of_death : public SpellScriptLoader void HandleEffectApply(AuraEffect const * /*aurEff*/, AuraApplication const * aurApp, AuraEffectHandleModes /*mode*/) { - if (Unit* target = aurApp->GetTarget()) - { - target->m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_GHOST); - target->m_serverSideVisibilityDetect.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_GHOST); - } + Unit* target = aurApp->GetTarget(); + target->m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_GHOST); + target->m_serverSideVisibilityDetect.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_GHOST); } void HandleEffectRemove(AuraEffect const * /*aurEff*/, AuraApplication const * aurApp, AuraEffectHandleModes /*mode*/) { - if (Unit* target = aurApp->GetTarget()) - { - target->m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_ALIVE); - target->m_serverSideVisibilityDetect.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_ALIVE); - } + Unit* target = aurApp->GetTarget(); + target->m_serverSideVisibility.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_ALIVE); + target->m_serverSideVisibilityDetect.SetValue(SERVERSIDE_VISIBILITY_GHOST, GHOST_VISIBILITY_ALIVE); } void Register() diff --git a/src/server/scripts/Spells/spell_hunter.cpp b/src/server/scripts/Spells/spell_hunter.cpp index 5fa440c3633..5c21563123f 100644 --- a/src/server/scripts/Spells/spell_hunter.cpp +++ b/src/server/scripts/Spells/spell_hunter.cpp @@ -88,7 +88,7 @@ public: int32 TickCount = aurEff->GetTotalTicks(); spellId = HUNTER_SPELL_CHIMERA_SHOT_SERPENT; basePoint = caster->SpellDamageBonus(unitTarget, aura->GetSpellProto(), aurEff->GetAmount(), DOT, aura->GetStackAmount()); - basePoint = basePoint * TickCount * 40 / 100; + ApplyPctN(basePoint, TickCount * 40); } // Viper Sting - Instantly restores mana to you equal to 60% of the total amount drained by your Viper Sting. else if (familyFlag[1] & 0x00000080) @@ -97,11 +97,11 @@ public: spellId = HUNTER_SPELL_CHIMERA_SHOT_VIPER; // Amount of one aura tick - basePoint = aurEff->GetAmount() * unitTarget->GetMaxPower(POWER_MANA) / 100 ; - int32 casterBasePoint = aurEff->GetAmount() * unitTarget->GetMaxPower(POWER_MANA) / 50 ; + basePoint = int32(CalculatePctN(unitTarget->GetMaxPower(POWER_MANA), aurEff->GetAmount())); + int32 casterBasePoint = aurEff->GetAmount() * unitTarget->GetMaxPower(POWER_MANA) / 50; // TODO: WTF? caster uses unitTarget? if (basePoint > casterBasePoint) basePoint = casterBasePoint; - basePoint = basePoint * TickCount * 60 / 100; + ApplyPctN(basePoint, TickCount * 60); } // Scorpid Sting - Attempts to Disarm the target for 10 sec. This effect cannot occur more than once per 1 minute. else if (familyFlag[0] & 0x00008000) @@ -361,29 +361,27 @@ public: if (aurEff->GetAmount() > 0) return; - if (Unit* pTarget = aurApp->GetTarget()) + uint32 spellId = SPELL_SNIPER_TRAINING_BUFF_R1 + GetId() - SPELL_SNIPER_TRAINING_R1; + Unit * pTarget = aurApp->GetTarget(); + if (!pTarget->HasAura(spellId)) { - uint32 spellId = SPELL_SNIPER_TRAINING_BUFF_R1 + GetId() - SPELL_SNIPER_TRAINING_R1; - if (!pTarget->HasAura(spellId)) - { - const SpellEntry* triggeredSpellInfo = sSpellStore.LookupEntry(spellId); - Unit* triggerCaster = GetTriggeredSpellCaster(triggeredSpellInfo, GetCaster(), pTarget); - triggerCaster->CastSpell(pTarget, triggeredSpellInfo, true, 0, aurEff); - } + SpellEntry const * triggeredSpellInfo = sSpellStore.LookupEntry(spellId); + Unit* triggerCaster = GetTriggeredSpellCaster(triggeredSpellInfo, GetCaster(), pTarget); + triggerCaster->CastSpell(pTarget, triggeredSpellInfo, true, 0, aurEff); } } void HandleUpdatePeriodic(AuraEffect * aurEff) { - if (Unit* pTarget = GetUnitOwner()) - if (Player* pPlayerTarget = pTarget->ToPlayer()) - { - int32 baseAmount = aurEff->GetBaseAmount(); - int32 amount = pPlayerTarget->isMoving() ? - pTarget->CalculateSpellDamage(pTarget, GetSpellProto(), aurEff->GetEffIndex(), &baseAmount) : - aurEff->GetAmount() - 1; - aurEff->SetAmount(amount); - } + Unit * pTarget = GetUnitOwner(); + if (Player* pPlayerTarget = pTarget->ToPlayer()) + { + int32 baseAmount = aurEff->GetBaseAmount(); + int32 amount = pPlayerTarget->isMoving() ? + pTarget->CalculateSpellDamage(pTarget, GetSpellProto(), aurEff->GetEffIndex(), &baseAmount) : + aurEff->GetAmount() - 1; + aurEff->SetAmount(amount); + } } void Register() diff --git a/src/server/scripts/Spells/spell_item.cpp b/src/server/scripts/Spells/spell_item.cpp index f543a2baaa0..2092735d2f8 100644 --- a/src/server/scripts/Spells/spell_item.cpp +++ b/src/server/scripts/Spells/spell_item.cpp @@ -701,8 +701,7 @@ public: void OnStackChange(AuraEffect const* /*aurEff*/, AuraApplication const* aurApp, AuraEffectHandleModes /*mode*/) { Unit* target = aurApp->GetTarget(); - if (!target) - return; + switch (GetStackAmount()) { case 1: @@ -722,8 +721,7 @@ public: void OnRemove(AuraEffect const* /*aurEff*/, AuraApplication const* aurApp, AuraEffectHandleModes /*mode*/) { Unit* target = aurApp->GetTarget(); - if (!target) - return; + if (aurApp->GetRemoveMode() == AURA_REMOVE_BY_STACK) return; target->RemoveAurasDueToSpell(SPELL_SHADOWMOURNE_VISUAL_LOW); diff --git a/src/server/scripts/Spells/spell_paladin.cpp b/src/server/scripts/Spells/spell_paladin.cpp index f0ccb58d2f5..c63a699fed0 100644 --- a/src/server/scripts/Spells/spell_paladin.cpp +++ b/src/server/scripts/Spells/spell_paladin.cpp @@ -110,16 +110,15 @@ public: void HandleEffectApply(AuraEffect const * /*aurEff*/, AuraApplication const * aurApp, AuraEffectHandleModes /*mode*/) { + Unit* pTarget = aurApp->GetTarget(); if (Unit* pCaster = GetCaster()) - if (Unit* pTarget = aurApp->GetTarget()) - pCaster->CastSpell(pTarget, PALADIN_SPELL_BLESSING_OF_SANCTUARY_BUFF, true); + pCaster->CastSpell(pTarget, PALADIN_SPELL_BLESSING_OF_SANCTUARY_BUFF, true); } void HandleEffectRemove(AuraEffect const * /*aurEff*/, AuraApplication const * aurApp, AuraEffectHandleModes /*mode*/) { - if (GetCaster()) - if (Unit* pTarget = aurApp->GetTarget()) - pTarget->RemoveAura(PALADIN_SPELL_BLESSING_OF_SANCTUARY_BUFF, GetCasterGUID()); + Unit* pTarget = aurApp->GetTarget(); + pTarget->RemoveAura(PALADIN_SPELL_BLESSING_OF_SANCTUARY_BUFF, GetCasterGUID()); } void Register() diff --git a/src/server/scripts/Spells/spell_quest.cpp b/src/server/scripts/Spells/spell_quest.cpp index f99835a09f5..44c21a26932 100644 --- a/src/server/scripts/Spells/spell_quest.cpp +++ b/src/server/scripts/Spells/spell_quest.cpp @@ -202,6 +202,123 @@ public: } }; +// http://www.wowhead.com/quest=11396 Bring Down Those Shields (A) +// http://www.wowhead.com/quest=11399 Bring Down Those Shields (H) +enum eQuest11396_11399Data +{ + SPELL_FORCE_SHIELD_ARCANE_PURPLE_X3 = 43874, + SPELL_SCOURGING_CRYSTAL_CONTROLLER = 43878 +}; + +// 43874 Scourge Mur'gul Camp: Force Shield Arcane Purple x3 +class spell_q11396_11399_force_shield_arcane_purple_x3 : public SpellScriptLoader +{ +public: + spell_q11396_11399_force_shield_arcane_purple_x3() : SpellScriptLoader("spell_q11396_11399_force_shield_arcane_purple_x3") { } + + class spell_q11396_11399_force_shield_arcane_purple_x3_AuraScript : public AuraScript + { + PrepareAuraScript(spell_q11396_11399_force_shield_arcane_purple_x3_AuraScript) + void HandleEffectApply(AuraEffect const * /*aurEff*/, AuraApplication const * aurApp, AuraEffectHandleModes /*mode*/) + { + Unit* pTarget = aurApp->GetTarget(); + pTarget->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE); + pTarget->addUnitState(UNIT_STAT_ROOT); + } + + void HandleEffectRemove(AuraEffect const * /*aurEff*/, AuraApplication const * aurApp, AuraEffectHandleModes /*mode*/) + { + aurApp->GetTarget()->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_OOC_NOT_ATTACKABLE); + } + + void Register() + { + OnEffectApply += AuraEffectApplyFn(spell_q11396_11399_force_shield_arcane_purple_x3_AuraScript::HandleEffectApply, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); + OnEffectRemove += AuraEffectRemoveFn(spell_q11396_11399_force_shield_arcane_purple_x3_AuraScript::HandleEffectRemove, EFFECT_0, SPELL_AURA_DUMMY, AURA_EFFECT_HANDLE_REAL); + } + + }; + + AuraScript* GetAuraScript() const + { + return new spell_q11396_11399_force_shield_arcane_purple_x3_AuraScript(); + } +}; + +// 50133 Scourging Crystal Controller +class spell_q11396_11399_scourging_crystal_controller : public SpellScriptLoader +{ +public: + spell_q11396_11399_scourging_crystal_controller() : SpellScriptLoader("spell_q11396_11399_scourging_crystal_controller") { } + + class spell_q11396_11399_scourging_crystal_controller_SpellScript : public SpellScript + { + PrepareSpellScript(spell_q11396_11399_scourging_crystal_controller_SpellScript); + bool Validate(SpellEntry const * /*spellEntry*/) + { + if (!sSpellStore.LookupEntry(SPELL_FORCE_SHIELD_ARCANE_PURPLE_X3)) + return false; + if (!sSpellStore.LookupEntry(SPELL_SCOURGING_CRYSTAL_CONTROLLER)) + return false; + return true; + } + + void HandleDummy(SpellEffIndex /*effIndex*/) + { + if (Unit* pTarget = GetTargetUnit()) + if (pTarget->GetTypeId() == TYPEID_UNIT && pTarget->HasAura(SPELL_FORCE_SHIELD_ARCANE_PURPLE_X3)) + // Make sure nobody else is channeling the same target + if (!pTarget->HasAura(SPELL_SCOURGING_CRYSTAL_CONTROLLER)) + GetCaster()->CastSpell(pTarget, SPELL_SCOURGING_CRYSTAL_CONTROLLER, true, GetCastItem()); + } + + void Register() + { + OnEffect += SpellEffectFn(spell_q11396_11399_scourging_crystal_controller_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); + } + }; + + SpellScript* GetSpellScript() const + { + return new spell_q11396_11399_scourging_crystal_controller_SpellScript(); + }; +}; + +// 43882 Scourging Crystal Controller Dummy +class spell_q11396_11399_scourging_crystal_controller_dummy : public SpellScriptLoader +{ +public: + spell_q11396_11399_scourging_crystal_controller_dummy() : SpellScriptLoader("spell_q11396_11399_scourging_crystal_controller_dummy") { } + + class spell_q11396_11399_scourging_crystal_controller_dummy_SpellScript : public SpellScript + { + PrepareSpellScript(spell_q11396_11399_scourging_crystal_controller_dummy_SpellScript); + bool Validate(SpellEntry const * /*spellEntry*/) + { + if (!sSpellStore.LookupEntry(SPELL_FORCE_SHIELD_ARCANE_PURPLE_X3)) + return false; + return true; + } + + void HandleDummy(SpellEffIndex /*effIndex*/) + { + if (Unit* pTarget = GetTargetUnit()) + if (pTarget->GetTypeId() == TYPEID_UNIT) + pTarget->RemoveAurasDueToSpell(SPELL_FORCE_SHIELD_ARCANE_PURPLE_X3); + } + + void Register() + { + OnEffect += SpellEffectFn(spell_q11396_11399_scourging_crystal_controller_dummy_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); + } + }; + + SpellScript* GetSpellScript() const + { + return new spell_q11396_11399_scourging_crystal_controller_dummy_SpellScript(); + }; +}; + // http://www.wowhead.com/quest=11515 Blood for Blood // 44936 Quest - Fel Siphon Dummy enum eQuest11515Data @@ -558,6 +675,9 @@ void AddSC_quest_spell_scripts() new spell_q5206_test_fetid_skull(); new spell_q6124_6129_apply_salve(); new spell_q10255_administer_antidote(); + new spell_q11396_11399_force_shield_arcane_purple_x3(); + new spell_q11396_11399_scourging_crystal_controller(); + new spell_q11396_11399_scourging_crystal_controller_dummy(); new spell_q11515_fel_siphon_dummy(); new spell_q11587_arcane_prisoner_rescue(); new spell_q11730_ultrasonic_screwdriver(); diff --git a/src/server/scripts/Spells/spell_rogue.cpp b/src/server/scripts/Spells/spell_rogue.cpp index 7a0d6204aa8..ed31db2d264 100644 --- a/src/server/scripts/Spells/spell_rogue.cpp +++ b/src/server/scripts/Spells/spell_rogue.cpp @@ -111,20 +111,18 @@ public: void HandleEffectPeriodic(AuraEffect const * /*aurEff*/, AuraApplication const * aurApp) { - if (Unit* pTarget = aurApp->GetTarget()) + Unit* pTarget = aurApp->GetTarget(); + Unit* pVictim = pTarget->getVictim(); + if (pVictim && (pTarget->GetHealthPct() > pVictim->GetHealthPct())) { - Unit* pVictim = pTarget->getVictim(); - if (pVictim && (pTarget->GetHealthPct() > pVictim->GetHealthPct())) + if (!pTarget->HasAura(ROGUE_SPELL_PREY_ON_THE_WEAK)) { - if (!pTarget->HasAura(ROGUE_SPELL_PREY_ON_THE_WEAK)) - { - int32 bp = SpellMgr::CalculateSpellEffectAmount(GetSpellProto(), 0); - pTarget->CastCustomSpell(pTarget, ROGUE_SPELL_PREY_ON_THE_WEAK, &bp, 0, 0, true); - } + int32 bp = SpellMgr::CalculateSpellEffectAmount(GetSpellProto(), 0); + pTarget->CastCustomSpell(pTarget, ROGUE_SPELL_PREY_ON_THE_WEAK, &bp, 0, 0, true); } - else - pTarget->RemoveAurasDueToSpell(ROGUE_SPELL_PREY_ON_THE_WEAK); } + else + pTarget->RemoveAurasDueToSpell(ROGUE_SPELL_PREY_ON_THE_WEAK); } void Register() diff --git a/src/server/scripts/Spells/spell_shaman.cpp b/src/server/scripts/Spells/spell_shaman.cpp index 1d88e3f68b5..cdd86ce2751 100644 --- a/src/server/scripts/Spells/spell_shaman.cpp +++ b/src/server/scripts/Spells/spell_shaman.cpp @@ -117,7 +117,7 @@ public: if (AuraEffect *dummy = owner->GetAuraEffect(SHAMAN_SPELL_GLYPH_OF_MANA_TIDE, 0)) effValue += dummy->GetAmount(); // Regenerate 6% of Total Mana Every 3 secs - int32 effBasePoints0 = unitTarget->GetMaxPower(POWER_MANA) * effValue / 100; + int32 effBasePoints0 = int32(CalculatePctN(unitTarget->GetMaxPower(POWER_MANA), effValue)); caster->CastCustomSpell(unitTarget, SHAMAN_SPELL_MANA_TIDE_TOTEM, &effBasePoints0, NULL, NULL, true, NULL, NULL, GetOriginalCaster()->GetGUID()); } } @@ -156,11 +156,11 @@ public: void HandleEffectPeriodic(AuraEffect const * aurEff, AuraApplication const * aurApp) { - if (Unit* target = aurApp->GetTarget()) - if (Unit *caster = aurEff->GetBase()->GetCaster()) - if (AuraEffect* aur = caster->GetDummyAuraEffect(SPELLFAMILY_SHAMAN, 2289, 0)) - if (roll_chance_i(aur->GetBaseAmount())) - target->CastSpell(target, SHAMAN_TOTEM_SPELL_EARTHEN_POWER, true, NULL, aurEff); + Unit* target = aurApp->GetTarget(); + if (Unit *caster = aurEff->GetBase()->GetCaster()) + if (AuraEffect* aur = caster->GetDummyAuraEffect(SPELLFAMILY_SHAMAN, 2289, 0)) + if (roll_chance_i(aur->GetBaseAmount())) + target->CastSpell(target, SHAMAN_TOTEM_SPELL_EARTHEN_POWER, true, NULL, aurEff); } void Register() diff --git a/src/server/scripts/World/CMakeLists.txt b/src/server/scripts/World/CMakeLists.txt index 3cc27cd8b5e..2f015db7cb4 100644 --- a/src/server/scripts/World/CMakeLists.txt +++ b/src/server/scripts/World/CMakeLists.txt @@ -7,7 +7,6 @@ set(scripts_STAT_SRCS World/boss_taerar.cpp World/boss_ysondre.cpp World/chat_log.cpp - World/dungeon_finder.cpp World/go_scripts.cpp World/guards.cpp World/item_scripts.cpp diff --git a/src/server/scripts/World/dungeon_finder.cpp b/src/server/scripts/World/dungeon_finder.cpp deleted file mode 100644 index 60a8ede4360..00000000000 --- a/src/server/scripts/World/dungeon_finder.cpp +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (C) 2008-2010 TrinityCore <http://www.trinitycore.org/> - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -/* - * Interaction between core and LFGMgr - */ - -#include "ScriptPCH.h" -#include "LFGMgr.h" -#include "Group.h" - -class DungeonFinderScript: public GroupScript, PlayerScript -{ -public: - DungeonFinderScript(): GroupScript("DungeonFinderScript"), PlayerScript("DungeonFinderScript") { } - - void OnAddMember(Group* group, uint64 guid) - { - uint64 gguid = group->GetGUID(); - sLog.outDebug("OnAddMember [" UI64FMTD "]: added [" UI64FMTD "]", gguid, guid); - if (!gguid) - return; - - for (GroupReference *itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) - { - if (Player *plrg = itr->getSource()) - { - plrg->GetSession()->SendLfgUpdatePlayer(LFG_UPDATETYPE_CLEAR_LOCK_LIST); - plrg->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_CLEAR_LOCK_LIST); - } - } - - if (group->isLfgQueued()) - sLFGMgr.Leave(NULL, group); - - Player *plr = sObjectMgr.GetPlayer(guid); - if (plr && plr->isUsingLfg()) - sLFGMgr.Leave(plr); - } - - void OnRemoveMember(Group* group, uint64 guid, RemoveMethod& method, uint64 kicker, const char* reason) - { - uint64 gguid = group->GetGUID(); - sLog.outDebug("OnRemoveMember [" UI64FMTD "]: remove [" UI64FMTD "] Method: %d Kicker: [" UI64FMTD "] Reason: %s", gguid, guid, method, kicker, (reason ? reason : "")); - if (!gguid) - return; - - if (group->isLfgQueued()) - { - // TODO - Do not remove, just remove the one leaving and rejoin queue with all other data - sLFGMgr.Leave(NULL, group); - } - - if (!group->isLFGGroup()) - return; - - if (method == GROUP_REMOVEMETHOD_KICK) // Player have been kicked - { - // TODO - Update internal kick cooldown of kicker - std::string str_reason = ""; - if (reason) - str_reason = std::string(reason); - sLFGMgr.InitBoot(group, GUID_LOPART(kicker), GUID_LOPART(guid), str_reason); - return; - } - - if (Player *plr = sObjectMgr.GetPlayer(guid)) - { - /* - if (method == GROUP_REMOVEMETHOD_LEAVE) - // Add deserter flag - else if (group->isLfgKickActive()) - // Update internal kick cooldown of kicked - */ - - plr->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_LEADER); - if (plr->GetMap()->IsDungeon()) // Teleport player out the dungeon - sLFGMgr.TeleportPlayer(plr, true); - } - - if (!group->isLfgDungeonComplete()) // Need more players to finish the dungeon - sLFGMgr.OfferContinue(group); - } - - void OnDisband(Group* group) - { - uint64 gguid = group->GetGUID(); - sLog.outDebug("OnDisband [" UI64FMTD "]", gguid); - if (!gguid) - return; - - if (group->isLfgQueued()) - sLFGMgr.Leave(NULL, group); - - for (GroupReference *itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) - { - if (Player *plrg = itr->getSource()) - { - plrg->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_GROUP_DISBAND); - plrg->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_LEADER); - if (plrg->GetMap()->IsDungeon()) // Teleport player out the dungeon - sLFGMgr.TeleportPlayer(plrg, true); - } - } - } - - void OnChangeLeader(Group* group, uint64 newLeaderGuid, uint64 oldLeaderGuid) - { - uint64 gguid = group->GetGUID(); - sLog.outDebug("OnChangeLeader [" UI64FMTD "]: old [" UI64FMTD "] new [" UI64FMTD "]", gguid, newLeaderGuid, oldLeaderGuid); - if (!gguid) - return; - - Player *plr = sObjectMgr.GetPlayer(newLeaderGuid); - if (plr) - plr->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_LEADER); - - plr = sObjectMgr.GetPlayer(oldLeaderGuid); - if (plr) - plr->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_GROUP_DISBAND); - } - - void OnInviteMember(Group* group, uint64 guid) - { - uint64 gguid = group->GetGUID(); - sLog.outDebug("OnInviteMember [" UI64FMTD "]: invite [" UI64FMTD "] leader [" UI64FMTD "]", gguid, guid, group->GetLeaderGUID()); - if (!gguid) - return; - - sLFGMgr.Leave(NULL, group); - } - - void OnLevelChanged(Player* /*player*/, uint8 /*newLevel*/) - { - } - - void OnLogout(Player* player) - { - sLFGMgr.Leave(player); - player->GetSession()->SendLfgUpdateParty(LFG_UPDATETYPE_REMOVED_FROM_QUEUE); - player->GetSession()->SendLfgUpdatePlayer(LFG_UPDATETYPE_REMOVED_FROM_QUEUE); - player->GetSession()->SendLfgUpdateSearch(false); - } -}; - -void AddSC_dungeon_finder() -{ - new DungeonFinderScript(); -} diff --git a/src/server/scripts/World/npcs_special.cpp b/src/server/scripts/World/npcs_special.cpp index 412626d29c8..66b8e400a71 100644 --- a/src/server/scripts/World/npcs_special.cpp +++ b/src/server/scripts/World/npcs_special.cpp @@ -820,9 +820,6 @@ void npc_doctor::npc_doctorAI::UpdateAI(const uint32 diff) { if (SummonPatient_Timer <= diff) { - Creature* Patient = NULL; - Location* Point = NULL; - if (Coordinates.empty()) return; @@ -838,22 +835,21 @@ void npc_doctor::npc_doctorAI::UpdateAI(const uint32 diff) return; } - Point = *itr; - - Patient = me->SummonCreature(patientEntry, Point->x, Point->y, Point->z, Point->o, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 5000); - - if (Patient) + if (Location* Point = *itr) { - //303, this flag appear to be required for client side item->spell to work (TARGET_SINGLE_FRIEND) - Patient->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE); + if (Creature* Patient = me->SummonCreature(patientEntry, Point->x, Point->y, Point->z, Point->o, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 5000)) + { + //303, this flag appear to be required for client side item->spell to work (TARGET_SINGLE_FRIEND) + Patient->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE); - Patients.push_back(Patient->GetGUID()); - CAST_AI(npc_injured_patient::npc_injured_patientAI, Patient->AI())->Doctorguid = me->GetGUID(); + Patients.push_back(Patient->GetGUID()); + CAST_AI(npc_injured_patient::npc_injured_patientAI, Patient->AI())->Doctorguid = me->GetGUID(); - if (Point) - CAST_AI(npc_injured_patient::npc_injured_patientAI, Patient->AI())->Coord = Point; + if (Point) + CAST_AI(npc_injured_patient::npc_injured_patientAI, Patient->AI())->Coord = Point; - Coordinates.erase(itr); + Coordinates.erase(itr); + } } SummonPatient_Timer = 10000; ++SummonPatientCount; diff --git a/src/server/shared/Cryptography/Authentication/AuthCrypt.h b/src/server/shared/Cryptography/Authentication/AuthCrypt.h index 752071d177d..2336e4a76db 100755 --- a/src/server/shared/Cryptography/Authentication/AuthCrypt.h +++ b/src/server/shared/Cryptography/Authentication/AuthCrypt.h @@ -34,7 +34,7 @@ class AuthCrypt void DecryptRecv(uint8 *, size_t); void EncryptSend(uint8 *, size_t); - bool IsInitialized() { return _initialized; } + bool IsInitialized() const { return _initialized; } private: ARC4 _clientDecrypt; diff --git a/src/server/shared/Cryptography/HMACSHA1.h b/src/server/shared/Cryptography/HMACSHA1.h index e0cb89da29d..2117b52b599 100755 --- a/src/server/shared/Cryptography/HMACSHA1.h +++ b/src/server/shared/Cryptography/HMACSHA1.h @@ -38,7 +38,7 @@ class HmacHash void Finalize(); uint8 *ComputeHash(BigNumber *bn); uint8 *GetDigest() { return (uint8*)m_digest; } - int GetLength() { return SHA_DIGEST_LENGTH; } + int GetLength() const { return SHA_DIGEST_LENGTH; } private: HMAC_CTX m_ctx; uint8 m_digest[SHA_DIGEST_LENGTH]; diff --git a/src/server/shared/Cryptography/MD5.c b/src/server/shared/Cryptography/MD5.c deleted file mode 100644 index 45897503455..00000000000 --- a/src/server/shared/Cryptography/MD5.c +++ /dev/null @@ -1,385 +0,0 @@ -/* - Copyright (C) 1999, 2000, 2002 Aladdin Enterprises. All rights reserved. - - 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. - -L. Peter Deutsch -ghost@aladdin.com - -*/ -/* $Id: md5.c,v 1.6 2002/04/13 19:20:28 lpd Exp $ */ -/* - Independent implementation of MD5 (RFC 1321). - - This code implements the MD5 Algorithm defined in RFC 1321, whose - text is available at - http://www.ietf.org/rfc/rfc1321.txt - The code is derived from the text of the RFC, including the test suite - (section A.5) but excluding the rest of Appendix A. It does not include - any code or documentation that is identified in the RFC as being - copyrighted. - -The original and principal author of md5.c is L. Peter Deutsch -<ghost@aladdin.com>. Other authors are noted in the change history -that follows (in reverse chronological order): - -2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order -either statically or dynamically; added missing #include <string.h> -in library. -2002-03-11 lpd Corrected argument list for main(), and added int return -type, in test program and T value program. -2002-02-21 lpd Added missing #include <stdio.h> in test program. -2000-07-03 lpd Patched to eliminate warnings about "constant is -unsigned in ANSI C, signed in traditional"; made test program -self-checking. -1999-11-04 lpd Edited comments slightly for automatic TOC extraction. -1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5). -1999-05-03 lpd Original version. -*/ - -#include "MD5.h" -#include <string.h> - -#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */ -#ifdef ARCH_IS_BIG_ENDIAN -# define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1) -#else -# define BYTE_ORDER 0 -#endif - -#define T_MASK ((md5_word_t)~0) -#define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87) -#define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9) -#define T3 0x242070db -#define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111) -#define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050) -#define T6 0x4787c62a -#define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec) -#define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe) -#define T9 0x698098d8 -#define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850) -#define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e) -#define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841) -#define T13 0x6b901122 -#define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c) -#define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71) -#define T16 0x49b40821 -#define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d) -#define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf) -#define T19 0x265e5a51 -#define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855) -#define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2) -#define T22 0x02441453 -#define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e) -#define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437) -#define T25 0x21e1cde6 -#define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829) -#define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278) -#define T28 0x455a14ed -#define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa) -#define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07) -#define T31 0x676f02d9 -#define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375) -#define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd) -#define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e) -#define T35 0x6d9d6122 -#define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3) -#define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb) -#define T38 0x4bdecfa9 -#define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f) -#define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f) -#define T41 0x289b7ec6 -#define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805) -#define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a) -#define T44 0x04881d05 -#define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6) -#define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a) -#define T47 0x1fa27cf8 -#define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a) -#define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb) -#define T50 0x432aff97 -#define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58) -#define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6) -#define T53 0x655b59c3 -#define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d) -#define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82) -#define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e) -#define T57 0x6fa87e4f -#define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f) -#define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb) -#define T60 0x4e0811a1 -#define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d) -#define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca) -#define T63 0x2ad7d2bb -#define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e) - -static void -md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/) -{ - md5_word_t - a = pms->abcd[0], b = pms->abcd[1], - c = pms->abcd[2], d = pms->abcd[3]; - md5_word_t t; - #if BYTE_ORDER > 0 - /* Define storage only for big-endian CPUs. */ - md5_word_t X[16]; - #else - /* Define storage for little-endian or both types of CPUs. */ - md5_word_t xbuf[16]; - const md5_word_t *X; - #endif - - { - #if BYTE_ORDER == 0 - /* - * Determine dynamically whether this is a big-endian or - * little-endian machine, since we can use a more efficient - * algorithm on the latter. - */ - static const int w = 1; - - if (*((const md5_byte_t *)&w)) /* dynamic little-endian */ - #endif - #if BYTE_ORDER <= 0 /* little-endian */ - { - /* - * On little-endian machines, we can process properly aligned - * data without copying it. - */ - if (!((data - (const md5_byte_t *)0) & 3)) - { - /* data are properly aligned */ - X = (const md5_word_t *)data; - } - else - { - /* not aligned */ - memcpy(xbuf, data, 64); - X = xbuf; - } - } - #endif - #if BYTE_ORDER == 0 - else /* dynamic big-endian */ - #endif - #if BYTE_ORDER >= 0 /* big-endian */ - { - /* - * On big-endian machines, we must arrange the bytes in the - * right order. - */ - const md5_byte_t *xp = data; - int i; - - # if BYTE_ORDER == 0 - X = xbuf; /* (dynamic only) */ - # else - # define xbuf X /* (static only) */ - # endif - for (i = 0; i < 16; ++i, xp += 4) - xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24); - } - #endif - } - - #define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) - - /* Round 1. */ - /* Let [abcd k s i] denote the operation - a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */ - #define F(x, y, z) (((x) & (y)) | (~(x) & (z))) - #define SET(a, b, c, d, k, s, Ti)\ - t = a + F(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 0, 7, T1); - SET(d, a, b, c, 1, 12, T2); - SET(c, d, a, b, 2, 17, T3); - SET(b, c, d, a, 3, 22, T4); - SET(a, b, c, d, 4, 7, T5); - SET(d, a, b, c, 5, 12, T6); - SET(c, d, a, b, 6, 17, T7); - SET(b, c, d, a, 7, 22, T8); - SET(a, b, c, d, 8, 7, T9); - SET(d, a, b, c, 9, 12, T10); - SET(c, d, a, b, 10, 17, T11); - SET(b, c, d, a, 11, 22, T12); - SET(a, b, c, d, 12, 7, T13); - SET(d, a, b, c, 13, 12, T14); - SET(c, d, a, b, 14, 17, T15); - SET(b, c, d, a, 15, 22, T16); - #undef SET - - /* Round 2. */ - /* Let [abcd k s i] denote the operation - a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */ - #define G(x, y, z) (((x) & (z)) | ((y) & ~(z))) - #define SET(a, b, c, d, k, s, Ti)\ - t = a + G(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 1, 5, T17); - SET(d, a, b, c, 6, 9, T18); - SET(c, d, a, b, 11, 14, T19); - SET(b, c, d, a, 0, 20, T20); - SET(a, b, c, d, 5, 5, T21); - SET(d, a, b, c, 10, 9, T22); - SET(c, d, a, b, 15, 14, T23); - SET(b, c, d, a, 4, 20, T24); - SET(a, b, c, d, 9, 5, T25); - SET(d, a, b, c, 14, 9, T26); - SET(c, d, a, b, 3, 14, T27); - SET(b, c, d, a, 8, 20, T28); - SET(a, b, c, d, 13, 5, T29); - SET(d, a, b, c, 2, 9, T30); - SET(c, d, a, b, 7, 14, T31); - SET(b, c, d, a, 12, 20, T32); - #undef SET - - /* Round 3. */ - /* Let [abcd k s t] denote the operation - a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */ - #define H(x, y, z) ((x) ^ (y) ^ (z)) - #define SET(a, b, c, d, k, s, Ti)\ - t = a + H(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 5, 4, T33); - SET(d, a, b, c, 8, 11, T34); - SET(c, d, a, b, 11, 16, T35); - SET(b, c, d, a, 14, 23, T36); - SET(a, b, c, d, 1, 4, T37); - SET(d, a, b, c, 4, 11, T38); - SET(c, d, a, b, 7, 16, T39); - SET(b, c, d, a, 10, 23, T40); - SET(a, b, c, d, 13, 4, T41); - SET(d, a, b, c, 0, 11, T42); - SET(c, d, a, b, 3, 16, T43); - SET(b, c, d, a, 6, 23, T44); - SET(a, b, c, d, 9, 4, T45); - SET(d, a, b, c, 12, 11, T46); - SET(c, d, a, b, 15, 16, T47); - SET(b, c, d, a, 2, 23, T48); - #undef SET - - /* Round 4. */ - /* Let [abcd k s t] denote the operation - a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */ - #define I(x, y, z) ((y) ^ ((x) | ~(z))) - #define SET(a, b, c, d, k, s, Ti)\ - t = a + I(b,c,d) + X[k] + Ti;\ - a = ROTATE_LEFT(t, s) + b - /* Do the following 16 operations. */ - SET(a, b, c, d, 0, 6, T49); - SET(d, a, b, c, 7, 10, T50); - SET(c, d, a, b, 14, 15, T51); - SET(b, c, d, a, 5, 21, T52); - SET(a, b, c, d, 12, 6, T53); - SET(d, a, b, c, 3, 10, T54); - SET(c, d, a, b, 10, 15, T55); - SET(b, c, d, a, 1, 21, T56); - SET(a, b, c, d, 8, 6, T57); - SET(d, a, b, c, 15, 10, T58); - SET(c, d, a, b, 6, 15, T59); - SET(b, c, d, a, 13, 21, T60); - SET(a, b, c, d, 4, 6, T61); - SET(d, a, b, c, 11, 10, T62); - SET(c, d, a, b, 2, 15, T63); - SET(b, c, d, a, 9, 21, T64); - #undef SET - - /* Then perform the following additions. (That is increment each - of the four registers by the value it had before this block - was started.) */ - pms->abcd[0] += a; - pms->abcd[1] += b; - pms->abcd[2] += c; - pms->abcd[3] += d; -} - -void -md5_init(md5_state_t *pms) -{ - pms->count[0] = pms->count[1] = 0; - pms->abcd[0] = 0x67452301; - pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476; - pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301; - pms->abcd[3] = 0x10325476; -} - -void -md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes) -{ - const md5_byte_t *p = data; - int left = nbytes; - int offset = (pms->count[0] >> 3) & 63; - md5_word_t nbits = (md5_word_t)(nbytes << 3); - - if (nbytes <= 0) - return; - - /* Update the message length. */ - pms->count[1] += nbytes >> 29; - pms->count[0] += nbits; - if (pms->count[0] < nbits) - ++pms->count[1]; - - /* Process an initial partial block. */ - if (offset) - { - int copy = (offset + nbytes > 64 ? 64 - offset : nbytes); - - memcpy(pms->buf + offset, p, copy); - if (offset + copy < 64) - return; - p += copy; - left -= copy; - md5_process(pms, pms->buf); - } - - /* Process full blocks. */ - for (; left >= 64; p += 64, left -= 64) - md5_process(pms, p); - - /* Process a final partial block. */ - if (left) - memcpy(pms->buf, p, left); -} - -void -md5_finish(md5_state_t *pms, md5_byte_t digest[16]) -{ - static const md5_byte_t pad[64] = - { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - md5_byte_t data[8]; - int i; - - /* Save the length before padding. */ - for (i = 0; i < 8; ++i) - data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3)); - /* Pad to 56 bytes mod 64. */ - md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1); - /* Append the length. */ - md5_append(pms, data, 8); - for (i = 0; i < 16; ++i) - digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3)); -} diff --git a/src/server/shared/Cryptography/MD5.h b/src/server/shared/Cryptography/MD5.h deleted file mode 100644 index 0463051b6a6..00000000000 --- a/src/server/shared/Cryptography/MD5.h +++ /dev/null @@ -1,92 +0,0 @@ -/* - Copyright (C) 1999, 2002 Aladdin Enterprises. All rights reserved. - - 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. - -L. Peter Deutsch -ghost@aladdin.com - -*/ -/* $Id: md5.h,v 1.4 2002/04/13 19:20:28 lpd Exp $ */ -/* - Independent implementation of MD5 (RFC 1321). - - This code implements the MD5 Algorithm defined in RFC 1321, whose - text is available at - http://www.ietf.org/rfc/rfc1321.txt - The code is derived from the text of the RFC, including the test suite - (section A.5) but excluding the rest of Appendix A. It does not include - any code or documentation that is identified in the RFC as being - copyrighted. - -The original and principal author of md5.h is L. Peter Deutsch -<ghost@aladdin.com>. Other authors are noted in the change history -that follows (in reverse chronological order): - -2002-04-13 lpd Removed support for non-ANSI compilers; removed -references to Ghostscript; clarified derivation from RFC 1321; -now handles byte order either statically or dynamically. -1999-11-04 lpd Edited comments slightly for automatic TOC extraction. -1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5); -added conditionalization for C++ compilation from Martin -Purschke <purschke@bnl.gov>. -1999-05-03 lpd Original version. -*/ - -#ifndef md5_INCLUDED -# define md5_INCLUDED - -/* - * This package supports both compile-time and run-time determination of CPU - * byte order. If ARCH_IS_BIG_ENDIAN is defined as 0, the code will be - * compiled to run only on little-endian CPUs; if ARCH_IS_BIG_ENDIAN is - * defined as non-zero, the code will be compiled to run only on big-endian - * CPUs; if ARCH_IS_BIG_ENDIAN is not defined, the code will be compiled to - * run on either big- or little-endian CPUs, but will run slightly less - * efficiently on either one than if ARCH_IS_BIG_ENDIAN is defined. - */ - -typedef unsigned char md5_byte_t; /* 8-bit byte */ -typedef unsigned int md5_word_t; /* 32-bit word */ - -/* Define the state of the MD5 Algorithm. */ -typedef struct md5_state_s -{ - md5_word_t count[2]; /* message length in bits, lsw first */ - md5_word_t abcd[4]; /* digest buffer */ - md5_byte_t buf[64]; /* accumulate block */ -} md5_state_t; - -#ifdef __cplusplus -extern "C" -{ - #endif - - /* Initialize the algorithm. */ - void md5_init(md5_state_t *pms); - - /* Append a string to the message. */ - void md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes); - - /* Finish the message and return the digest. */ - void md5_finish(md5_state_t *pms, md5_byte_t digest[16]); - - #ifdef __cplusplus -} /* end extern "C" */ -#endif -#endif /* md5_INCLUDED */ - diff --git a/src/server/shared/Cryptography/SHA1.h b/src/server/shared/Cryptography/SHA1.h index 19c9f2da411..42da3c483e5 100755 --- a/src/server/shared/Cryptography/SHA1.h +++ b/src/server/shared/Cryptography/SHA1.h @@ -41,7 +41,7 @@ class SHA1Hash void Finalize(); uint8 *GetDigest(void) { return mDigest; }; - int GetLength(void) { return SHA_DIGEST_LENGTH; }; + int GetLength(void) const { return SHA_DIGEST_LENGTH; }; private: SHA_CTX mC; diff --git a/src/server/shared/DataStores/DBCFileLoader.cpp b/src/server/shared/DataStores/DBCFileLoader.cpp index 906cb95cb65..e087d5cb980 100755 --- a/src/server/shared/DataStores/DBCFileLoader.cpp +++ b/src/server/shared/DataStores/DBCFileLoader.cpp @@ -41,31 +41,50 @@ bool DBCFileLoader::Load(const char *filename, const char *fmt) if (!f) return false; - if (fread(&header,4,1,f)!=1) // Number of records + if (fread(&header,4,1,f) != 1) // Number of records + { + fclose(f); return false; + } + EndianConvert(header); - if (header!=0x43424457) - return false; //'WDBC' + if (header != 0x43424457) //'WDBC' + { + fclose(f); + return false; + } - if (fread(&recordCount,4,1,f)!=1) // Number of records + if (fread(&recordCount,4,1,f) != 1) // Number of records + { + fclose(f); return false; + } EndianConvert(recordCount); - if (fread(&fieldCount,4,1,f)!=1) // Number of fields + if (fread(&fieldCount,4,1,f) != 1) // Number of fields + { + fclose(f); return false; + } EndianConvert(fieldCount); - if (fread(&recordSize,4,1,f)!=1) // Size of a record + if (fread(&recordSize,4,1,f) != 1) // Size of a record + { + fclose(f); return false; + } EndianConvert(recordSize); - if (fread(&stringSize,4,1,f)!=1) // String size + if (fread(&stringSize,4,1,f) != 1) // String size + { + fclose(f); return false; + } EndianConvert(stringSize); @@ -83,8 +102,11 @@ bool DBCFileLoader::Load(const char *filename, const char *fmt) data = new unsigned char[recordSize*recordCount+stringSize]; stringTable = data + recordSize*recordCount; - if (fread(data,recordSize*recordCount+stringSize,1,f)!=1) + if (fread(data,recordSize*recordCount+stringSize,1,f) != 1) + { + fclose(f); return false; + } fclose(f); diff --git a/src/server/shared/DataStores/DBCFileLoader.h b/src/server/shared/DataStores/DBCFileLoader.h index 8dc06ac96ae..6675458215b 100755 --- a/src/server/shared/DataStores/DBCFileLoader.h +++ b/src/server/shared/DataStores/DBCFileLoader.h @@ -93,7 +93,7 @@ class DBCFileLoader 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() { return data != NULL; } + 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); diff --git a/src/server/shared/Database/DatabaseWorkerPool.h b/src/server/shared/Database/DatabaseWorkerPool.h index 9b912dd3854..7b742310e2c 100755 --- a/src/server/shared/Database/DatabaseWorkerPool.h +++ b/src/server/shared/Database/DatabaseWorkerPool.h @@ -18,7 +18,6 @@ #ifndef _DATABASEWORKERPOOL_H #define _DATABASEWORKERPOOL_H -#include <ace/Atomic_Op_T.h> #include <ace/Thread_Mutex.h> #include "Common.h" @@ -51,13 +50,10 @@ class PingOperation : public SQLOperation template <class T> class DatabaseWorkerPool { - private: - typedef ACE_Atomic_Op<ACE_SYNCH_MUTEX, uint32> AtomicUInt; - public: DatabaseWorkerPool() : m_queue(new ACE_Activation_Queue(new ACE_Message_Queue<ACE_MT_SYNCH>)), - m_connections(0) + m_connectionCount(0) { m_connections.resize(IDX_SIZE); @@ -84,7 +80,7 @@ class DatabaseWorkerPool T* t = new T(m_queue, m_connectionInfo); t->Open(); m_connections[IDX_ASYNC][i] = t; - ++m_connectionCount; + ++m_connectionCount[IDX_ASYNC]; } /// Open synchronous connections (direct, blocking operations) @@ -94,10 +90,10 @@ class DatabaseWorkerPool T* t = new T(m_connectionInfo); t->Open(); m_connections[IDX_SYNCH][i] = t; - ++m_connectionCount; + ++m_connectionCount[IDX_SYNCH]; } - sLog.outSQLDriver("Databasepool opened succesfuly. %u connections running.", (uint32)m_connectionCount.value()); + sLog.outSQLDriver("Databasepool opened succesfuly. %u connections running.", m_connectionCount); return true; } @@ -107,25 +103,27 @@ class DatabaseWorkerPool /// Shuts down delaythreads for this connection pool. m_queue->queue()->deactivate(); - for (uint8 i = 0; i < m_connections[IDX_ASYNC].size(); ++i) + for (uint8 i = 0; i < m_connectionCount[IDX_ASYNC]; ++i) { /// TODO: Better way. probably should flip a boolean and check it on low level code before doing anything on the mysql ctx /// Now we just wait until m_queue gives the signal to the worker threads to stop T* t = m_connections[IDX_ASYNC][i]; - t->m_worker->wait(); // t->Close(); is called from worker thread - --m_connectionCount; + DatabaseWorker* worker = t->m_worker; + worker->wait(); // t->Close(); is called from worker thread + delete worker; + --m_connectionCount[IDX_ASYNC]; } sLog.outSQLDriver("Asynchronous connections on databasepool '%s' terminated. Proceeding with synchronous connections.", m_connectionInfo.database.c_str()); /// Shut down the synchronous connections - for (uint8 i = 0; i < m_connections[IDX_SYNCH].size(); ++i) + for (uint8 i = 0; i < m_connectionCount[IDX_SYNCH]; ++i) { T* t = m_connections[IDX_SYNCH][i]; //while (1) // if (t->LockIfReady()) -- For some reason deadlocks us t->Close(); - --m_connectionCount; + --m_connectionCount[IDX_SYNCH]; } sLog.outSQLDriver("All connections on databasepool %s closed.", m_connectionInfo.database.c_str()); @@ -256,16 +254,19 @@ class DatabaseWorkerPool { if (sLog.GetSQLDriverQueryLogging()) { - if (transaction->GetSize() == 0) + switch (transaction->GetSize()) { - sLog.outSQLDriver("Transaction contains 0 queries. Not executing."); - return; - } - if (transaction->GetSize() == 1) - { - sLog.outSQLDriver("Warning: Transaction only holds 1 query, consider removing Transaction context in code."); + case 0: + sLog.outSQLDriver("Transaction contains 0 queries. Not executing."); + return; + case 1: + sLog.outSQLDriver("Warning: Transaction only holds 1 query, consider removing Transaction context in code."); + break; + default: + break; } } + Enqueue(new TransactionTask(transaction)); } @@ -313,7 +314,7 @@ class DatabaseWorkerPool void KeepAlive() { /// Ping synchronous connections - for (uint8 i = 0; i < m_connections[IDX_SYNCH].size(); ++i) + for (uint8 i = 0; i < m_connectionCount[IDX_SYNCH]; ++i) { T* t = m_connections[IDX_SYNCH][i]; if (t->LockIfReady()) @@ -350,7 +351,7 @@ class DatabaseWorkerPool T* GetFreeConnection() { uint8 i = 0; - size_t num_cons = m_connections[IDX_SYNCH].size(); + size_t num_cons = m_connectionCount[IDX_SYNCH]; for (;;) /// Block forever until a connection is free { T* t = m_connections[IDX_SYNCH][++i % num_cons ]; @@ -372,7 +373,7 @@ class DatabaseWorkerPool ACE_Activation_Queue* m_queue; //! Queue shared by async worker threads. std::vector< std::vector<T*> > m_connections; - AtomicUInt m_connectionCount; //! Counter of MySQL connections; + uint32 m_connectionCount[2]; //! Counter of MySQL connections; MySQLConnectionInfo m_connectionInfo; }; diff --git a/src/server/shared/Database/Implementation/CharacterDatabase.h b/src/server/shared/Database/Implementation/CharacterDatabase.h index 3346632e75d..f13cfef45ad 100755 --- a/src/server/shared/Database/Implementation/CharacterDatabase.h +++ b/src/server/shared/Database/Implementation/CharacterDatabase.h @@ -26,7 +26,6 @@ class CharacterDatabaseConnection : public MySQLConnection public: //- Constructors for sync and async connections CharacterDatabaseConnection(MySQLConnectionInfo& connInfo) : MySQLConnection(connInfo) {} - CharacterDatabaseConnection(ACE_Activation_Queue* q, MySQLConnectionInfo& connInfo) : MySQLConnection(q, connInfo) {} //- Loads databasetype specific prepared statements bool Open(); diff --git a/src/server/shared/Database/Implementation/LoginDatabase.h b/src/server/shared/Database/Implementation/LoginDatabase.h index 38d383eba37..df4762a3a87 100755 --- a/src/server/shared/Database/Implementation/LoginDatabase.h +++ b/src/server/shared/Database/Implementation/LoginDatabase.h @@ -26,7 +26,6 @@ class LoginDatabaseConnection : public MySQLConnection public: //- Constructors for sync and async connections LoginDatabaseConnection(MySQLConnectionInfo& connInfo) : MySQLConnection(connInfo) {} - LoginDatabaseConnection(ACE_Activation_Queue* q, MySQLConnectionInfo& connInfo) : MySQLConnection(q, connInfo) {} //- Loads databasetype specific prepared statements bool Open(); diff --git a/src/server/shared/Database/Implementation/WorldDatabase.h b/src/server/shared/Database/Implementation/WorldDatabase.h index c502ff019f9..57e1833d5de 100755 --- a/src/server/shared/Database/Implementation/WorldDatabase.h +++ b/src/server/shared/Database/Implementation/WorldDatabase.h @@ -26,7 +26,6 @@ class WorldDatabaseConnection : public MySQLConnection public: //- Constructors for sync and async connections WorldDatabaseConnection(MySQLConnectionInfo& connInfo) : MySQLConnection(connInfo) {} - WorldDatabaseConnection(ACE_Activation_Queue* q, MySQLConnectionInfo& connInfo) : MySQLConnection(q, connInfo) {} //- Loads databasetype specific prepared statements bool Open(); diff --git a/src/server/shared/Database/SQLOperation.h b/src/server/shared/Database/SQLOperation.h index bd75634636b..315167443dd 100755 --- a/src/server/shared/Database/SQLOperation.h +++ b/src/server/shared/Database/SQLOperation.h @@ -59,7 +59,7 @@ class MySQLConnection; class SQLOperation : public ACE_Method_Request { public: - SQLOperation(){}; + SQLOperation(): m_conn(NULL) {}; virtual int call() { Execute(); diff --git a/src/server/shared/Database/Transaction.h b/src/server/shared/Database/Transaction.h index 8bdb11541e7..96acef0b01c 100755 --- a/src/server/shared/Database/Transaction.h +++ b/src/server/shared/Database/Transaction.h @@ -28,6 +28,7 @@ class Transaction { friend class TransactionTask; public: + Transaction() {} ~Transaction() { Cleanup(); } void Append(PreparedStatement* statement); @@ -40,8 +41,6 @@ class Transaction void Cleanup(); std::queue<SQLElementData> m_queries; - private: - bool m_actioned; }; typedef ACE_Refcounted_Auto_Ptr<Transaction, ACE_Null_Mutex> SQLTransaction; diff --git a/src/server/shared/Logging/Log.h b/src/server/shared/Logging/Log.h index 019221f7811..2d3d5faccff 100755 --- a/src/server/shared/Logging/Log.h +++ b/src/server/shared/Logging/Log.h @@ -125,11 +125,11 @@ class Log bool IsOutDebug() const { return m_logLevel > 2 || (m_logFileLevel > 2 && logfile); } bool IsOutCharDump() const { return m_charLog_Dump; } - bool GetLogDB() { return m_enableLogDB; } - bool GetLogDBLater() { return m_enableLogDBLater; } + bool GetLogDB() const { return m_enableLogDB; } + bool GetLogDBLater() const { return m_enableLogDBLater; } void SetLogDB(bool enable) { m_enableLogDB = enable; } void SetLogDBLater(bool value) { m_enableLogDBLater = value; } - bool GetSQLDriverQueryLogging() { return m_sqlDriverQueryLogging; } + bool GetSQLDriverQueryLogging() const { return m_sqlDriverQueryLogging; } private: FILE* openLogFile(char const* configFileName,char const* configTimeStampFlag, char const* mode); FILE* openGmlogPerAccount(uint32 account); diff --git a/src/server/shared/Utilities/EventProcessor.cpp b/src/server/shared/Utilities/EventProcessor.cpp index 170fbb99f1e..7c5eef7a06e 100755 --- a/src/server/shared/Utilities/EventProcessor.cpp +++ b/src/server/shared/Utilities/EventProcessor.cpp @@ -92,7 +92,7 @@ void EventProcessor::AddEvent(BasicEvent* Event, uint64 e_time, bool set_addtime m_events.insert(std::pair<uint64, BasicEvent*>(e_time, Event)); } -uint64 EventProcessor::CalculateTime(uint64 t_offset) +uint64 EventProcessor::CalculateTime(uint64 t_offset) const { return(m_time + t_offset); } diff --git a/src/server/shared/Utilities/EventProcessor.h b/src/server/shared/Utilities/EventProcessor.h index 83272cfb98f..8ccef33e215 100755 --- a/src/server/shared/Utilities/EventProcessor.h +++ b/src/server/shared/Utilities/EventProcessor.h @@ -61,7 +61,7 @@ class EventProcessor void Update(uint32 p_time); void KillAllEvents(bool force); void AddEvent(BasicEvent* Event, uint64 e_time, bool set_addtime = true); - uint64 CalculateTime(uint64 t_offset); + uint64 CalculateTime(uint64 t_offset) const; protected: uint64 m_time; EventList m_events; diff --git a/src/server/shared/Utilities/Util.cpp b/src/server/shared/Utilities/Util.cpp index 371bd2c7e2b..bd67895ed28 100755 --- a/src/server/shared/Utilities/Util.cpp +++ b/src/server/shared/Utilities/Util.cpp @@ -18,7 +18,6 @@ #include "Util.h" -#include "socket_include.h" #include "utf8.h" #ifdef USE_SFMT_FOR_RNG #include "SFMT.h" @@ -26,6 +25,7 @@ #include "MersenneTwister.h" #endif #include <ace/TSS_T.h> +#include <ace/INET_Addr.h> #ifdef USE_SFMT_FOR_RNG typedef ACE_TSS<SFMTRand> SFMTRandTSS; diff --git a/src/server/shared/Utilities/Util.h b/src/server/shared/Utilities/Util.h index 8a49d7d9681..f6b408f84c1 100755 --- a/src/server/shared/Utilities/Util.h +++ b/src/server/shared/Utilities/Util.h @@ -80,7 +80,7 @@ inline void ApplyModUInt32Var(uint32& var, int32 val, bool apply) { int32 cur = var; cur += (apply ? val : -val); - if(cur < 0) + if (cur < 0) cur = 0; var = cur; } @@ -88,7 +88,7 @@ inline void ApplyModUInt32Var(uint32& var, int32 val, bool apply) inline void ApplyModFloatVar(float& var, float val, bool apply) { var += (apply ? val : -val); - if(var < 0) + if (var < 0) var = 0; } @@ -96,9 +96,65 @@ inline void ApplyPercentModFloatVar(float& var, float val, bool apply) { if (val == -100.0f) // prevent set var to zero val = -99.99f; - var *= (apply?(100.0f+val)/100.0f : 100.0f / (100.0f+val)); + var *= (apply ? (100.0f + val) / 100.0f : 100.0f / (100.0f + val)); } +// Percentage calculation +template <class T> +inline T CalculatePctF(T base, float pct) +{ + return T(base * pct / 100.0f); +} + +template <class T> +inline T CalculatePctN(T base, int32 pct) +{ + return T(base * float(pct) / 100.0f); +} + +template <class T> +inline T CalculatePctU(T base, uint32 pct) +{ + return T(base * float(pct) / 100.0f); +} + +template <class T> +inline T AddPctF(T& base, float pct) +{ + return base += CalculatePctF(base, pct); +} + +template <class T> +inline T AddPctN(T& base, int32 pct) +{ + return base += CalculatePctN(base, pct); +} + +template <class T> +inline T AddPctU(T& base, uint32 pct) +{ + return base += CalculatePctU(base, pct); +} + +template <class T> +inline T ApplyPctF(T& base, float pct) +{ + return base = CalculatePctF(base, pct); +} + +template <class T> +inline T ApplyPctN(T& base, int32 pct) +{ + return base = CalculatePctN(base, pct); +} + +template <class T> +inline T ApplyPctU(T& base, uint32 pct) +{ + return base = CalculatePctU(base, pct); +} + +// UTF8 handling bool Utf8toWStr(const std::string& utf8str, std::wstring& wstr); // in wsize==max size of buffer, out wsize==real string size bool Utf8toWStr(char const* utf8str, size_t csize, wchar_t* wstr, size_t& wsize); diff --git a/src/server/worldserver/CMakeLists.txt b/src/server/worldserver/CMakeLists.txt index 7f8603eede1..c3d663b7562 100644 --- a/src/server/worldserver/CMakeLists.txt +++ b/src/server/worldserver/CMakeLists.txt @@ -161,7 +161,6 @@ target_link_libraries(worldserver game shared scripts - trinitysockets collision g3dlib gsoap diff --git a/src/server/worldserver/Master.cpp b/src/server/worldserver/Master.cpp index ecfbdbc7d8e..d04d64be02f 100755 --- a/src/server/worldserver/Master.cpp +++ b/src/server/worldserver/Master.cpp @@ -36,17 +36,11 @@ #include "CliRunnable.h" #include "Log.h" #include "Master.h" -#include "RASocket.h" +#include "RARunnable.h" #include "TCSoap.h" #include "Timer.h" #include "Util.h" -#include "TcpSocket.h" -#include "Utility.h" -#include "Parse.h" -#include "Socket.h" -#include "SocketHandler.h" -#include "ListenSocket.h" #include "BigNumber.h" #ifdef _WIN32 @@ -114,53 +108,6 @@ public: } }; -class RARunnable : public ACE_Based::Runnable -{ -public: - RARunnable () {} - - void run () - { - SocketHandler h; - - // Launch the RA listener socket - ListenSocket<RASocket> RAListenSocket (h); - bool usera = sConfig.GetBoolDefault ("Ra.Enable", false); - - if (usera) - { - port_t raport = sConfig.GetIntDefault ("Ra.Port", 3443); - std::string stringip = sConfig.GetStringDefault ("Ra.IP", "0.0.0.0"); - ipaddr_t raip; - if (!Utility::u2ip (stringip, raip)) - sLog.outError ("Trinity RA can not bind to ip %s", stringip.c_str ()); - else if (RAListenSocket.Bind (raip, raport)) - sLog.outError ("Trinity RA can not bind to port %d on %s", raport, stringip.c_str ()); - else - { - h.Add (&RAListenSocket); - - sLog.outString ("Starting Remote access listner on port %d on %s", raport, stringip.c_str ()); - } - } - - // Socket Selet time is in microseconds , not miliseconds!! - uint32 socketSelecttime = sWorld.getIntConfig(CONFIG_SOCKET_SELECTTIME); - - // if use ra spend time waiting for io, if not use ra ,just sleep - if (usera) - { - while (!World::IsStopped()) - h.Select (0, socketSelecttime); - } - else - { - while (!World::IsStopped()) - ACE_Based::Thread::Sleep(static_cast<unsigned long> (socketSelecttime / 1000)); - } - } -}; - Master::Master() { } @@ -319,7 +266,7 @@ int Master::Run() } ///- Launch the world listener socket - port_t wsport = sWorld.getIntConfig(CONFIG_PORT_WORLD); + uint16 wsport = sWorld.getIntConfig(CONFIG_PORT_WORLD); std::string bind_ip = sConfig.GetStringDefault ("BindIP", "0.0.0.0"); if (sWorldSocketMgr->StartNetwork (wsport, bind_ip.c_str ()) == -1) diff --git a/src/server/worldserver/RemoteAccess/RARunnable.cpp b/src/server/worldserver/RemoteAccess/RARunnable.cpp new file mode 100644 index 00000000000..87ddd4cb43a --- /dev/null +++ b/src/server/worldserver/RemoteAccess/RARunnable.cpp @@ -0,0 +1,93 @@ +/* + * Copyright (C) 2008-2010 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +/** \file + \ingroup Trinityd + */ + +#include "Common.h" +#include "Config.h" +#include "Log.h" +#include "RARunnable.h" +#include "World.h" + +#include <ace/Reactor_Impl.h> +#include <ace/TP_Reactor.h> +#include <ace/Dev_Poll_Reactor.h> +#include <ace/Acceptor.h> +#include <ace/SOCK_Acceptor.h> + +#include "RASocket.h" + +RARunnable::RARunnable() : m_Reactor(NULL) +{ + ACE_Reactor_Impl* imp = 0; + +#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL) + + imp = new ACE_Dev_Poll_Reactor(); + + imp->max_notify_iterations (128); + imp->restart (1); + +#else + + imp = new ACE_TP_Reactor(); + imp->max_notify_iterations (128); + +#endif + + m_Reactor = new ACE_Reactor (imp, 1); +} + +RARunnable::~RARunnable() +{ + delete m_Reactor; +} + +void RARunnable::run() +{ + if (!sConfig.GetBoolDefault("Ra.Enable", false)) + return; + + ACE_Acceptor<RASocket, ACE_SOCK_ACCEPTOR> acceptor; + + uint16 raport = sConfig.GetIntDefault("Ra.Port", 3443); + std::string stringip = sConfig.GetStringDefault("Ra.IP", "0.0.0.0"); + + ACE_INET_Addr listen_addr(raport, stringip.c_str()); + + if (acceptor.open(listen_addr, m_Reactor) == -1) + { + sLog.outError("Trinity RA can not bind to port %d on %s", raport, stringip.c_str()); + return; + } + + sLog.outString("Starting Trinity RA on port %d on %s", raport, stringip.c_str()); + + while (!World::IsStopped()) + { + // don't be too smart to move this outside the loop + // the run_reactor_event_loop will modify interval + ACE_Time_Value interval(0, 100000); + + if (m_Reactor->run_reactor_event_loop(interval) == -1) + break; + } + + sLog.outStaticDebug("Trinity RA thread exiting"); +} diff --git a/src/server/worldserver/RemoteAccess/RARunnable.h b/src/server/worldserver/RemoteAccess/RARunnable.h new file mode 100644 index 00000000000..85e1dd516a0 --- /dev/null +++ b/src/server/worldserver/RemoteAccess/RARunnable.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2008-2010 TrinityCore <http://www.trinitycore.org/> + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see <http://www.gnu.org/licenses/>. + */ + +/// \addtogroup Trinityd +/// @{ +/// \file + +#ifndef _TRINITY_RARUNNABLE_H_ +#define _TRINITY_RARUNNABLE_H_ + +#include "Common.h" + +#include <ace/Reactor.h> + +class RARunnable : public ACE_Based::Runnable +{ +public: + RARunnable(); + virtual ~RARunnable(); + void run(); + +private: + ACE_Reactor* m_Reactor; + +}; + +#endif /* _TRINITY_RARUNNABLE_H_ */ +/// @} diff --git a/src/server/worldserver/RemoteAccess/RASocket.cpp b/src/server/worldserver/RemoteAccess/RASocket.cpp index ca80c3cbed0..6b073e060d7 100755 --- a/src/server/worldserver/RemoteAccess/RASocket.cpp +++ b/src/server/worldserver/RemoteAccess/RASocket.cpp @@ -28,208 +28,304 @@ #include "RASocket.h" #include "Util.h" #include "World.h" +#include "SHA1.h" -#define dropclient {Sendf("I'm busy right now, come back later."); \ - SetCloseAndDelete(); \ - return; \ +RASocket::RASocket() +{ + iMinLevel = sConfig.GetIntDefault("RA.MinLevel", 3); +} + +RASocket::~RASocket() +{ +} + +int RASocket::open(void *) +{ + ACE_INET_Addr remote_addr; + + if (peer().get_remote_addr(remote_addr) == -1) + { + sLog.outError("RASocket::open: peer().get_remote_addr error is %s", ACE_OS::strerror(errno)); + return -1; } -/// RASocket constructor -RASocket::RASocket(ISocketHandler &h): TcpSocket(h) + sLog.outRemote("Incoming connection from %s", remote_addr.get_host_addr()); + + return activate(); +} + +int RASocket::handle_close(ACE_HANDLE, ACE_Reactor_Mask) { + sLog.outRemote("Closing connection"); + peer().close_reader(); + wait(); + destroy(); + return 0; +} + +int RASocket::send(const std::string& line) +{ + return peer().send(line.c_str(), line.length()) == line.length() ? 0 : -1; +} + +int RASocket::recv_line(ACE_Message_Block& buffer) +{ + char byte; + for (;;) + { + ssize_t n = peer().recv(&byte, sizeof(byte)); + + if (n < 0) + { + return -1; + } - ///- Get the config parameters - bSecure = sConfig.GetBoolDefault( "RA.Secure", true ); - iMinLevel = sConfig.GetIntDefault( "RA.MinLevel", 3 ); + if (n == 0) + { + // EOF, connection was closed + errno = ECONNRESET; + return -1; + } + + ACE_ASSERT(n == sizeof(byte)); - ///- Initialize buffer and data - iInputLength=0; - stage=NONE; + if (byte == '\n') + break; + else if (byte == '\r') /* Ignore CR */ + continue; + else if (buffer.copy(&byte, sizeof(byte)) == -1) + return -1; + } + + const char null_term = '\0'; + if (buffer.copy(&null_term, sizeof(null_term)) == -1) + return -1; + + return 0; } -/// RASocket destructor -RASocket::~RASocket() +int RASocket::recv_line(std::string& out_line) { - sLog.outRemote("Connection was closed.\n"); + char buf[4096]; + + ACE_Data_Block db(sizeof (buf), + ACE_Message_Block::MB_DATA, + buf, + 0, + 0, + ACE_Message_Block::DONT_DELETE, + 0); + + ACE_Message_Block message_block(&db, + ACE_Message_Block::DONT_DELETE, + 0); + + if (recv_line(message_block) == -1) + { + sLog.outRemote("Recv error %s", ACE_OS::strerror(errno)); + return -1; + } + + out_line = message_block.rd_ptr(); + + return 0; } -/// Accept an incoming connection -void RASocket::OnAccept() +int RASocket::process_command(const std::string& command) { - std::string ss=GetRemoteAddress(); - sLog.outRemote("Incoming connection from %s.\n",ss.c_str()); - ///- print Motd - Sendf("%s\r\n",sWorld.GetMotd()); + if (command.length() == 0) + return 0; + + sLog.outRemote("Got command: %s", command.c_str()); + + // handle quit, exit and logout commands to terminate connection + if (command == "quit" || command == "exit" || command == "logout") { + (void) send("Bye\r\n"); + return -1; + } + + CliCommandHolder* cmd = new CliCommandHolder(this, command.c_str(), &RASocket::zprint, &RASocket::commandFinished); + sWorld.QueueCliCommand(cmd); + + // wait for result + ACE_Message_Block* mb; + for (;;) + { + if (getq(mb) == -1) + return -1; + + if (mb->msg_type() == ACE_Message_Block::MB_BREAK) + { + mb->release(); + break; + } + + if (peer().send(mb->rd_ptr(), mb->length()) != mb->length()) + { + mb->release(); + return -1; + } + + mb->release(); + } + + return 0; } -/// Read data from the network -void RASocket::OnRead() +int RASocket::check_access_level(const std::string& user) { - ///- Read data and check input length - TcpSocket::OnRead(); + std::string safe_user = user; + + AccountMgr::normalizeString(safe_user); + LoginDatabase.escape_string(safe_user); - unsigned int sz=ibuf.GetLength(); - if (iInputLength+sz>=RA_BUFF_SIZE) + QueryResult result = LoginDatabase.PQuery("SELECT a.id, aa.gmlevel, aa.RealmID FROM account a LEFT JOIN account_access aa ON (a.id = aa.id) WHERE a.username = '%s'", safe_user.c_str()); + + if (!result) { - sLog.outRemote("Input buffer overflow, possible DOS attack.\n"); - SetCloseAndDelete(); - return; + sLog.outRemote("User %s does not exist in database", user.c_str()); + return -1; } - char *inp = new char [sz+1]; - ibuf.Read(inp,sz); - - /// \todo Can somebody explain this 'Linux bugfix'? - if (stage==NONE) - if (sz>4) //linux remote telnet - if (memcmp(inp ,"USER ",5)) - { - delete [] inp;return; - printf("lin bugfix"); - } //linux bugfix - - ///- Discard data after line break or line feed - bool gotenter=false; - unsigned int y=0; - for (; y<sz; y++) - if (inp[y]=='\r'||inp[y]=='\n') + Field *fields = result->Fetch(); + + if (fields[1].GetUInt32() < iMinLevel) { - gotenter=true; - break; + sLog.outRemote("User %s has no privilege to login", user.c_str()); + return -1; } + else if (fields[2].GetInt32() != -1) + { + sLog.outRemote("User %s has to be assigned on all realms (with RealmID = '-1')", user.c_str()); + return -1; + } + + return 0; +} + +int RASocket::check_password(const std::string& user, const std::string& pass) +{ + std::string safe_user = user; + AccountMgr::normalizeString(safe_user); + LoginDatabase.escape_string(safe_user); + + std::string safe_pass = pass; + AccountMgr::normalizeString(safe_pass); + LoginDatabase.escape_string(safe_pass); + + std::string hash = sAccountMgr.CalculateShaPassHash(safe_user, safe_pass); + + QueryResult check = LoginDatabase.PQuery( + "SELECT 1 FROM account WHERE username = '%s' AND sha_pass_hash = '%s'", + safe_user.c_str(), hash.c_str()); - //No buffer overflow (checked above) - memcpy(&buff[iInputLength],inp,y); - iInputLength+=y; - delete [] inp; - if (gotenter) + if (!check) { + sLog.outRemote("Wrong password for user: %s", user.c_str()); + return -1; + } - buff[iInputLength]=0; - iInputLength=0; - switch(stage) - { - /// <ul> <li> If the input is 'USER <username>' - case NONE: - if (!memcmp(buff,"USER ",5)) //got "USER" cmd - { - szLogin=&buff[5]; - - ///- Get the password from the account table - std::string login = szLogin; - - ///- Convert Account name to Upper Format - AccountMgr::normalizeString(login); - - ///- Escape the Login to allow quotes in names - LoginDatabase.escape_string(login); - - QueryResult result = LoginDatabase.PQuery("SELECT a.id, aa.gmlevel, aa.RealmID FROM account a LEFT JOIN account_access aa ON (a.id = aa.id) WHERE a.username = '%s'",login.c_str ()); - - ///- If the user is not found, deny access - if (!result) - { - Sendf("-No such user.\r\n"); - sLog.outRemote("User %s does not exist.\n",szLogin.c_str()); - if (bSecure)SetCloseAndDelete(); - } - else - { - Field *fields = result->Fetch(); - - //szPass=fields[0].GetString(); - - ///- if gmlevel is too low, deny access - if (fields[1].GetUInt32() < iMinLevel) - { - Sendf("-Not enough privileges.\r\n"); - sLog.outRemote("User %s has no privilege.\n",szLogin.c_str()); - if (bSecure)SetCloseAndDelete(); - } - else if (fields[2].GetInt32() != -1) - { - ///- if RealmID isn't -1, deny access - Sendf("-Not enough privileges.\r\n"); - sLog.outRemote("User %s has to be assigned on all realms (with RealmID = '-1').\n",szLogin.c_str()); - if (bSecure)SetCloseAndDelete(); - } - else - { - stage=LG; - } - } - } - break; - ///<li> If the input is 'PASS <password>' (and the user already gave his username) - case LG: - if (!memcmp(buff,"PASS ",5)) //got "PASS" cmd - { //login+pass ok - ///- If password is correct, increment the number of active administrators - std::string login = szLogin; - std::string pw = &buff[5]; - - AccountMgr::normalizeString(login); - AccountMgr::normalizeString(pw); - LoginDatabase.escape_string(login); - LoginDatabase.escape_string(pw); - - QueryResult check = LoginDatabase.PQuery( - "SELECT 1 FROM account WHERE username = '%s' AND sha_pass_hash=SHA1(CONCAT('%s',':','%s'))", - login.c_str(), login.c_str(), pw.c_str()); - - if (check) - { - GetSocket(); - stage=OK; - - Sendf("+Logged in.\r\n"); - sLog.outRemote("User %s has logged in.\n",szLogin.c_str()); - Sendf("TC>"); - } - else - { - ///- Else deny access - Sendf("-Wrong pass.\r\n"); - sLog.outRemote("User %s has failed to log in.\n",szLogin.c_str()); - if (bSecure)SetCloseAndDelete(); - } - } - break; - ///<li> If user is logged, parse and execute the command - case OK: - if (strlen(buff)) - { - sLog.outRemote("Got '%s' cmd.\n",buff); - SetDeleteByHandler(false); - CliCommandHolder* cmd = new CliCommandHolder(this, buff, &RASocket::zprint, &RASocket::commandFinished); - sWorld.QueueCliCommand(cmd); - ++pendingCommands; - } - else - Sendf("TC>"); - break; - ///</ul> - }; + return 0; +} + +int RASocket::authenticate() +{ + if (send(std::string("Username: ")) == -1) + return -1; + + std::string user; + if (recv_line(user) == -1) + return -1; + + if (send(std::string("Password: ")) == -1) + return -1; + + std::string pass; + if (recv_line(pass) == -1) + return -1; + + sLog.outRemote("Login attempt for user: %s", user.c_str()); + + if (check_access_level(user) == -1) + return -1; + + if (check_password(user, pass) == -1) + return -1; + + sLog.outRemote("User login: %s", user.c_str()); + return 0; +} + +int RASocket::svc(void) +{ + if (send("Authentication required\r\n") == -1) + return -1; + + if (authenticate() == -1) + { + (void) send("Authentication failed\r\n"); + return -1; + } + + // send motd + if (send(std::string(sWorld.GetMotd()) + "\r\n") == -1) + return -1; + + for(;;) + { + // show prompt + const char* tc_prompt = "TC> "; + if (peer().send(tc_prompt, strlen(tc_prompt)) != strlen(tc_prompt)) + return -1; + + std::string line; + + if (recv_line(line) == -1) + return -1; + + if (process_command(line) == -1) + return -1; } + + return 0; } -/// Output function -void RASocket::zprint(void* callbackArg, const char * szText ) +void RASocket::zprint(void* callbackArg, const char * szText) { - if ( !szText ) + if (!szText || !callbackArg) return; - unsigned int sz=strlen(szText); - send(((RASocket*)callbackArg)->GetSocket(), szText, sz, 0); + RASocket* socket = static_cast<RASocket*>(callbackArg); + size_t sz = strlen(szText); + + ACE_Message_Block* mb = new ACE_Message_Block(sz); + mb->copy(szText, sz); + + if (socket->putq(mb, const_cast<ACE_Time_Value*>(&ACE_Time_Value::zero)) == -1) + { + sLog.outRemote("Failed to enqueue message, queue is full or closed. Error is %s", ACE_OS::strerror(errno)); + mb->release(); + } } void RASocket::commandFinished(void* callbackArg, bool /*success*/) { - RASocket* raSocket = (RASocket*)callbackArg; - raSocket->Sendf("TC>"); - uint64 remainingCommands = --raSocket->pendingCommands; + if (!callbackArg) + return; - if (remainingCommands == 0) - raSocket->SetDeleteByHandler(true); - } + RASocket* socket = static_cast<RASocket*>(callbackArg); + + ACE_Message_Block* mb = new ACE_Message_Block(); + + mb->msg_type(ACE_Message_Block::MB_BREAK); + + // the message is 0 size control message to tell that command output is finished + // hence we don't put timeout, because it shouldn't increase queue size and shouldn't block + if (socket->putq(mb) == -1) + { + // getting here is bad, command can't be marked as complete + sLog.outRemote("Failed to enqueue command end message. Error is %s", ACE_OS::strerror(errno)); + mb->release(); + } +} diff --git a/src/server/worldserver/RemoteAccess/RASocket.h b/src/server/worldserver/RemoteAccess/RASocket.h index 948f6077b00..dfc82bbf56a 100755 --- a/src/server/worldserver/RemoteAccess/RASocket.h +++ b/src/server/worldserver/RemoteAccess/RASocket.h @@ -23,48 +23,39 @@ #ifndef _RASOCKET_H #define _RASOCKET_H -#include "TcpSocket.h" - #include "Common.h" -#include <ace/Synch_Traits.h> - -#define RA_BUFF_SIZE 1024 -class ISocketHandler; - -typedef ACE_Atomic_Op<ACE_SYNCH_MUTEX, uint64> AtomicInt; +#include <ace/Synch_Traits.h> +#include <ace/Svc_Handler.h> +#include <ace/SOCK_Stream.h> +#include <ace/SOCK_Acceptor.h> /// Remote Administration socket -class RASocket: public TcpSocket +class RASocket: public ACE_Svc_Handler<ACE_SOCK_STREAM, ACE_MT_SYNCH> { public: + RASocket(); + virtual ~RASocket(); - RASocket(ISocketHandler& h); - ~RASocket(); - - void OnAccept(); - void OnRead(); - - AtomicInt pendingCommands; + virtual int svc(void); + virtual int open(void * = 0); + virtual int handle_close(ACE_HANDLE = ACE_INVALID_HANDLE, ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK); private: - char buff[RA_BUFF_SIZE]; - std::string szLogin; - - unsigned int iInputLength; - bool bSecure; - //will protect from DOS, bruteforce attacks - //some 'smart' protection must be added for more security - uint8 iMinLevel; - enum - { - NONE, //initial value - LG, //only login was entered - OK, //both login and pass were given, and they are correct and user have enough priv. - }stage; + int recv_line(std::string& out_line); + int recv_line(ACE_Message_Block& buffer); + int process_command(const std::string& command); + int authenticate(); + int check_access_level(const std::string& user); + int check_password(const std::string& user, const std::string& pass); + int send(const std::string& line); static void zprint(void* callbackArg, const char * szText ); static void commandFinished(void* callbackArg, bool success); + + private: + /// Minimum security level required to connect + uint8 iMinLevel; }; #endif /// @} diff --git a/src/server/worldserver/TCSoap/TCSoap.cpp b/src/server/worldserver/TCSoap/TCSoap.cpp index 266fbd1eeb8..eaf5f8c41ff 100755 --- a/src/server/worldserver/TCSoap/TCSoap.cpp +++ b/src/server/worldserver/TCSoap/TCSoap.cpp @@ -28,18 +28,15 @@ void TCSoapRunnable::run() pool.activate (THR_NEW_LWP | THR_JOINABLE, POOL_SIZE); struct soap soap; - int m, s; soap_init(&soap); soap_set_imode(&soap, SOAP_C_UTFSTRING); soap_set_omode(&soap, SOAP_C_UTFSTRING); - m = soap_bind(&soap, m_host.c_str(), m_port, 100); // check every 3 seconds if world ended soap.accept_timeout = 3; - soap.recv_timeout = 5; soap.send_timeout = 5; - if (m < 0) + if (soap_bind(&soap, m_host.c_str(), m_port, 100) < 0) { sLog.outError("TCSoap: couldn't bind to %s:%d", m_host.c_str(), m_port); exit(-1); @@ -49,9 +46,7 @@ void TCSoapRunnable::run() while(!World::IsStopped()) { - s = soap_accept(&soap); - - if (s < 0) + if (soap_accept(&soap) < 0) continue; // ran into an accept timeout sLog.outDebug("TCSoap: accepted connection from IP=%d.%d.%d.%d", (int)(soap.ip>>24)&0xFF, (int)(soap.ip>>16)&0xFF, (int)(soap.ip>>8)&0xFF, (int)soap.ip&0xFF); diff --git a/src/server/worldserver/TCSoap/TCSoap.h b/src/server/worldserver/TCSoap/TCSoap.h index c3cb06512b3..ec6d275a3ae 100755 --- a/src/server/worldserver/TCSoap/TCSoap.h +++ b/src/server/worldserver/TCSoap/TCSoap.h @@ -97,7 +97,7 @@ class SOAPCommand m_success = val; } - bool hasCommandSucceeded() + bool hasCommandSucceeded() const { return m_success; } diff --git a/src/server/worldserver/worldserver.conf.dist b/src/server/worldserver/worldserver.conf.dist index a74fd7c0b71..746bc019699 100644 --- a/src/server/worldserver/worldserver.conf.dist +++ b/src/server/worldserver/worldserver.conf.dist @@ -119,10 +119,10 @@ CharacterDatabase.SynchThreads = 2 # # MaxPingTime -# Description: Time (in seconds) between database pings. -# Default: 1800 - (30 minutes) +# Description: Time (in minutes) between database pings. +# Default: 30 -MaxPingTime = 1800 +MaxPingTime = 30 # # WorldServerPort @@ -391,16 +391,6 @@ CleanCharacterDB = 0 ################################################################################################### # SERVER LOGGING # -# LogSQL -# Description: Enable logging of SQL queries triggered by in game commands from in game -# All commands are written to a file: YYYY-MM-DD_logSQL.sql -# A new file will be created every day at 00:00:00. -# Default: 1 - (Enabled) -# 0 - (Disabled) - -LogSQL = 1 - -# # PidFile # Description: World daemon PID file # Example: "./worldd.pid" - (Enabled) @@ -1371,7 +1361,7 @@ DungeonFinder.Enable = 0 # # DBC.EnforceItemAttributes -# Description: Disallow overriding item attributes stored in DBC files with values from the +# Description: Disallow overriding item attributes stored in DBC files with values from the # database. # Default: 1 - (Enabled, Enforce DBC values) # 0 - (Disabled, Use database values) @@ -1641,6 +1631,7 @@ ListenRange.TextEmote = 40 # Default: 300 ListenRange.Yell = 300 + # ################################################################################################### @@ -1748,7 +1739,7 @@ AllowPlayerCommands = 1 # # PreserveCustomChannels # Description: Store custom chat channel settings like password, automatic ownership handout -# or ban list in the database. Needs to be enabled to save custom +# or ban list in the database. Needs to be enabled to save custom # world/trade/etc. channels that have automatic ownership handout disabled. # (.channel set ownership $channel off) # Default: 0 - (Disabled, Blizzlike, Channel settings are lost if last person left) @@ -1927,7 +1918,7 @@ Visibility.Distance.BGArenas = 180 Visibility.Notify.Period.OnContinents = 1000 Visibility.Notify.Period.InInstances = 1000 -Visibility.Notify.Period.InBGArenas = 1000 +Visibility.Notify.Period.InBGArenas = 1000 # ################################################################################################### @@ -2084,7 +2075,7 @@ Rate.Mining.Amount = 1 # Description: Mining rates. # Default: Chance to to mine a deposit again. -Rate.Mining.Next = 1 +Rate.Mining.Next = 1 # # Rate.Talent @@ -2529,14 +2520,6 @@ Ra.Port = 3443 Ra.MinLevel = 3 # -# Ra.Secure -# Description: Kick clients on invalid authentication. -# Default: 1 - (Enabled) -# 0 - (Disabled) - -Ra.Secure = 1 - -# # SOAP.Enable # Description: Enable soap service # Default: 0 - (Disabled) |