diff options
240 files changed, 10937 insertions, 6474 deletions
diff --git a/dep/PackageList.txt b/dep/PackageList.txt index 28099265772..56f6f28e0bf 100644 --- a/dep/PackageList.txt +++ b/dep/PackageList.txt @@ -6,15 +6,15 @@ ACE (ADAPTIVE Communication Environment) bzip2 (a freely available, patent free, high-quality data compressor) http://www.bzip.org/ - Version: 1.0.5 + Version: 1.0.6 G3D (a commercial-grade C++ 3D engine available as Open Source (BSD License) http://g3d.sourceforge.net/ - Version: 8.0-Release + Version: 8.01-Release jemalloc (a general-purpose scalable concurrent malloc-implementation) http://www.canonware.com/jemalloc/ - Version: 2.2.5 + Version: 2.1.0 MySQL (the world's most popular open source database software) http://www.mysql.com/ @@ -26,15 +26,15 @@ SFMT (SIMD-oriented Fast Mersenne Twister) utf8-cpp (UTF-8 with C++ in a Portable Way) http://utfcpp.sourceforge.net/ - Version: 2.3 + Version: 2.3.2 zlib (A Massively Spiffy Yet Delicately Unobtrusive Compression Library) http://www.zlib.net/ - Version: 1.2.5 + Version: 1.2.7 gSOAP (a portable development toolkit for C and C++ XML Web services and XML data bindings) http://gsoap2.sourceforge.net/ - Version: 2.8.2 + Version: 2.8.10 StormLib (a pack of modules, written in C++, which are able to read and also to write files from/to the MPQ archives) http://www.zezula.net/en/mpq/stormlib.html diff --git a/dep/bzip2/LICENSE b/dep/bzip2/LICENSE new file mode 100644 index 00000000000..cc614178cf7 --- /dev/null +++ b/dep/bzip2/LICENSE @@ -0,0 +1,42 @@ + +-------------------------------------------------------------------------- + +This program, "bzip2", the associated library "libbzip2", and all +documentation, are copyright (C) 1996-2010 Julian R Seward. All +rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. 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. + +3. Altered source versions must be plainly marked as such, and must + not be misrepresented as being the original software. + +4. The name of the author may not be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS +OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Julian Seward, jseward@bzip.org +bzip2/libbzip2 version 1.0.6 of 6 September 2010 + +-------------------------------------------------------------------------- diff --git a/dep/bzip2/README b/dep/bzip2/README new file mode 100644 index 00000000000..9fb0f636013 --- /dev/null +++ b/dep/bzip2/README @@ -0,0 +1,215 @@ + +This is the README for bzip2/libzip2. +This version is fully compatible with the previous public releases. + +------------------------------------------------------------------ +This file is part of bzip2/libbzip2, a program and library for +lossless, block-sorting data compression. + +bzip2/libbzip2 version 1.0.6 of 6 September 2010 +Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org> + +Please read the WARNING, DISCLAIMER and PATENTS sections in this file. + +This program is released under the terms of the license contained +in the file LICENSE. +------------------------------------------------------------------ + +Complete documentation is available in Postscript form (manual.ps), +PDF (manual.pdf) or html (manual.html). A plain-text version of the +manual page is available as bzip2.txt. + + +HOW TO BUILD -- UNIX + +Type 'make'. This builds the library libbz2.a and then the programs +bzip2 and bzip2recover. Six self-tests are run. If the self-tests +complete ok, carry on to installation: + +To install in /usr/local/bin, /usr/local/lib, /usr/local/man and +/usr/local/include, type + + make install + +To install somewhere else, eg, /xxx/yyy/{bin,lib,man,include}, type + + make install PREFIX=/xxx/yyy + +If you are (justifiably) paranoid and want to see what 'make install' +is going to do, you can first do + + make -n install or + make -n install PREFIX=/xxx/yyy respectively. + +The -n instructs make to show the commands it would execute, but not +actually execute them. + + +HOW TO BUILD -- UNIX, shared library libbz2.so. + +Do 'make -f Makefile-libbz2_so'. This Makefile seems to work for +Linux-ELF (RedHat 7.2 on an x86 box), with gcc. I make no claims +that it works for any other platform, though I suspect it probably +will work for most platforms employing both ELF and gcc. + +bzip2-shared, a client of the shared library, is also built, but not +self-tested. So I suggest you also build using the normal Makefile, +since that conducts a self-test. A second reason to prefer the +version statically linked to the library is that, on x86 platforms, +building shared objects makes a valuable register (%ebx) unavailable +to gcc, resulting in a slowdown of 10%-20%, at least for bzip2. + +Important note for people upgrading .so's from 0.9.0/0.9.5 to version +1.0.X. All the functions in the library have been renamed, from (eg) +bzCompress to BZ2_bzCompress, to avoid namespace pollution. +Unfortunately this means that the libbz2.so created by +Makefile-libbz2_so will not work with any program which used an older +version of the library. I do encourage library clients to make the +effort to upgrade to use version 1.0, since it is both faster and more +robust than previous versions. + + +HOW TO BUILD -- Windows 95, NT, DOS, Mac, etc. + +It's difficult for me to support compilation on all these platforms. +My approach is to collect binaries for these platforms, and put them +on the master web site (http://www.bzip.org). Look there. However +(FWIW), bzip2-1.0.X is very standard ANSI C and should compile +unmodified with MS Visual C. If you have difficulties building, you +might want to read README.COMPILATION.PROBLEMS. + +At least using MS Visual C++ 6, you can build from the unmodified +sources by issuing, in a command shell: + + nmake -f makefile.msc + +(you may need to first run the MSVC-provided script VCVARS32.BAT + so as to set up paths to the MSVC tools correctly). + + +VALIDATION + +Correct operation, in the sense that a compressed file can always be +decompressed to reproduce the original, is obviously of paramount +importance. To validate bzip2, I used a modified version of Mark +Nelson's churn program. Churn is an automated test driver which +recursively traverses a directory structure, using bzip2 to compress +and then decompress each file it encounters, and checking that the +decompressed data is the same as the original. + + + +Please read and be aware of the following: + +WARNING: + + This program and library (attempts to) compress data by + performing several non-trivial transformations on it. + Unless you are 100% familiar with *all* the algorithms + contained herein, and with the consequences of modifying them, + you should NOT meddle with the compression or decompression + machinery. Incorrect changes can and very likely *will* + lead to disastrous loss of data. + + +DISCLAIMER: + + I TAKE NO RESPONSIBILITY FOR ANY LOSS OF DATA ARISING FROM THE + USE OF THIS PROGRAM/LIBRARY, HOWSOEVER CAUSED. + + Every compression of a file implies an assumption that the + compressed file can be decompressed to reproduce the original. + Great efforts in design, coding and testing have been made to + ensure that this program works correctly. However, the complexity + of the algorithms, and, in particular, the presence of various + special cases in the code which occur with very low but non-zero + probability make it impossible to rule out the possibility of bugs + remaining in the program. DO NOT COMPRESS ANY DATA WITH THIS + PROGRAM UNLESS YOU ARE PREPARED TO ACCEPT THE POSSIBILITY, HOWEVER + SMALL, THAT THE DATA WILL NOT BE RECOVERABLE. + + That is not to say this program is inherently unreliable. + Indeed, I very much hope the opposite is true. bzip2/libbzip2 + has been carefully constructed and extensively tested. + + +PATENTS: + + To the best of my knowledge, bzip2/libbzip2 does not use any + patented algorithms. However, I do not have the resources + to carry out a patent search. Therefore I cannot give any + guarantee of the above statement. + + + +WHAT'S NEW IN 0.9.0 (as compared to 0.1pl2) ? + + * Approx 10% faster compression, 30% faster decompression + * -t (test mode) is a lot quicker + * Can decompress concatenated compressed files + * Programming interface, so programs can directly read/write .bz2 files + * Less restrictive (BSD-style) licensing + * Flag handling more compatible with GNU gzip + * Much more documentation, i.e., a proper user manual + * Hopefully, improved portability (at least of the library) + +WHAT'S NEW IN 0.9.5 ? + + * Compression speed is much less sensitive to the input + data than in previous versions. Specifically, the very + slow performance caused by repetitive data is fixed. + * Many small improvements in file and flag handling. + * A Y2K statement. + +WHAT'S NEW IN 1.0.0 ? + + See the CHANGES file. + +WHAT'S NEW IN 1.0.2 ? + + See the CHANGES file. + +WHAT'S NEW IN 1.0.3 ? + + See the CHANGES file. + +WHAT'S NEW IN 1.0.4 ? + + See the CHANGES file. + +WHAT'S NEW IN 1.0.5 ? + + See the CHANGES file. + +WHAT'S NEW IN 1.0.6 ? + + See the CHANGES file. + + +I hope you find bzip2 useful. Feel free to contact me at + jseward@bzip.org +if you have any suggestions or queries. Many people mailed me with +comments, suggestions and patches after the releases of bzip-0.15, +bzip-0.21, and bzip2 versions 0.1pl2, 0.9.0, 0.9.5, 1.0.0, 1.0.1, +1.0.2 and 1.0.3, and the changes in bzip2 are largely a result of this +feedback. I thank you for your comments. + +bzip2's "home" is http://www.bzip.org/ + +Julian Seward +jseward@bzip.org +Cambridge, UK. + +18 July 1996 (version 0.15) +25 August 1996 (version 0.21) + 7 August 1997 (bzip2, version 0.1) +29 August 1997 (bzip2, version 0.1pl2) +23 August 1998 (bzip2, version 0.9.0) + 8 June 1999 (bzip2, version 0.9.5) + 4 Sept 1999 (bzip2, version 0.9.5d) + 5 May 2000 (bzip2, version 1.0pre8) +30 December 2001 (bzip2, version 1.0.2pre1) +15 February 2005 (bzip2, version 1.0.3) +20 December 2006 (bzip2, version 1.0.4) +10 December 2007 (bzip2, version 1.0.5) + 6 Sept 2010 (bzip2, version 1.0.6) diff --git a/dep/bzip2/blocksort.c b/dep/bzip2/blocksort.c index bd2dec157fa..d0d662cd4e9 100644 --- a/dep/bzip2/blocksort.c +++ b/dep/bzip2/blocksort.c @@ -8,8 +8,8 @@ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward <jseward@bzip.org> + bzip2/libbzip2 version 1.0.6 of 6 September 2010 + Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org> Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. diff --git a/dep/bzip2/bzip2.c b/dep/bzip2/bzip2.c new file mode 100644 index 00000000000..6de9d1d1488 --- /dev/null +++ b/dep/bzip2/bzip2.c @@ -0,0 +1,2034 @@ + +/*-----------------------------------------------------------*/ +/*--- A block-sorting, lossless compressor bzip2.c ---*/ +/*-----------------------------------------------------------*/ + +/* ------------------------------------------------------------------ + This file is part of bzip2/libbzip2, a program and library for + lossless, block-sorting data compression. + + bzip2/libbzip2 version 1.0.6 of 6 September 2010 + Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org> + + Please read the WARNING, DISCLAIMER and PATENTS sections in the + README file. + + This program is released under the terms of the license contained + in the file LICENSE. + ------------------------------------------------------------------ */ + + +/* Place a 1 beside your platform, and 0 elsewhere. + Generic 32-bit Unix. + Also works on 64-bit Unix boxes. + This is the default. +*/ +#define BZ_UNIX 1 + +/*-- + Win32, as seen by Jacob Navia's excellent + port of (Chris Fraser & David Hanson)'s excellent + lcc compiler. Or with MS Visual C. + This is selected automatically if compiled by a compiler which + defines _WIN32, not including the Cygwin GCC. +--*/ +#define BZ_LCCWIN32 0 + +#if defined(_WIN32) && !defined(__CYGWIN__) +#undef BZ_LCCWIN32 +#define BZ_LCCWIN32 1 +#undef BZ_UNIX +#define BZ_UNIX 0 +#endif + + +/*---------------------------------------------*/ +/*-- + Some stuff for all platforms. +--*/ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <signal.h> +#include <math.h> +#include <errno.h> +#include <ctype.h> +#include "bzlib.h" + +#define ERROR_IF_EOF(i) { if ((i) == EOF) ioError(); } +#define ERROR_IF_NOT_ZERO(i) { if ((i) != 0) ioError(); } +#define ERROR_IF_MINUS_ONE(i) { if ((i) == (-1)) ioError(); } + + +/*---------------------------------------------*/ +/*-- + Platform-specific stuff. +--*/ + +#if BZ_UNIX +# include <fcntl.h> +# include <sys/types.h> +# include <utime.h> +# include <unistd.h> +# include <sys/stat.h> +# include <sys/times.h> + +# define PATH_SEP '/' +# define MY_LSTAT lstat +# define MY_STAT stat +# define MY_S_ISREG S_ISREG +# define MY_S_ISDIR S_ISDIR + +# define APPEND_FILESPEC(root, name) \ + root=snocString((root), (name)) + +# define APPEND_FLAG(root, name) \ + root=snocString((root), (name)) + +# define SET_BINARY_MODE(fd) /**/ + +# ifdef __GNUC__ +# define NORETURN __attribute__ ((noreturn)) +# else +# define NORETURN /**/ +# endif + +# ifdef __DJGPP__ +# include <io.h> +# include <fcntl.h> +# undef MY_LSTAT +# undef MY_STAT +# define MY_LSTAT stat +# define MY_STAT stat +# undef SET_BINARY_MODE +# define SET_BINARY_MODE(fd) \ + do { \ + int retVal = setmode ( fileno ( fd ), \ + O_BINARY ); \ + ERROR_IF_MINUS_ONE ( retVal ); \ + } while ( 0 ) +# endif + +# ifdef __CYGWIN__ +# include <io.h> +# include <fcntl.h> +# undef SET_BINARY_MODE +# define SET_BINARY_MODE(fd) \ + do { \ + int retVal = setmode ( fileno ( fd ), \ + O_BINARY ); \ + ERROR_IF_MINUS_ONE ( retVal ); \ + } while ( 0 ) +# endif +#endif /* BZ_UNIX */ + + + +#if BZ_LCCWIN32 +# include <io.h> +# include <fcntl.h> +# include <sys\stat.h> + +# define NORETURN /**/ +# define PATH_SEP '\\' +# define MY_LSTAT _stat +# define MY_STAT _stat +# define MY_S_ISREG(x) ((x) & _S_IFREG) +# define MY_S_ISDIR(x) ((x) & _S_IFDIR) + +# define APPEND_FLAG(root, name) \ + root=snocString((root), (name)) + +# define APPEND_FILESPEC(root, name) \ + root = snocString ((root), (name)) + +# define SET_BINARY_MODE(fd) \ + do { \ + int retVal = setmode ( fileno ( fd ), \ + O_BINARY ); \ + ERROR_IF_MINUS_ONE ( retVal ); \ + } while ( 0 ) + +#endif /* BZ_LCCWIN32 */ + + +/*---------------------------------------------*/ +/*-- + Some more stuff for all platforms :-) +--*/ + +typedef char Char; +typedef unsigned char Bool; +typedef unsigned char UChar; +typedef int Int32; +typedef unsigned int UInt32; +typedef short Int16; +typedef unsigned short UInt16; + +#define True ((Bool)1) +#define False ((Bool)0) + +/*-- + IntNative is your platform's `native' int size. + Only here to avoid probs with 64-bit platforms. +--*/ +typedef int IntNative; + + +/*---------------------------------------------------*/ +/*--- Misc (file handling) data decls ---*/ +/*---------------------------------------------------*/ + +Int32 verbosity; +Bool keepInputFiles, smallMode, deleteOutputOnInterrupt; +Bool forceOverwrite, testFailsExist, unzFailsExist, noisy; +Int32 numFileNames, numFilesProcessed, blockSize100k; +Int32 exitValue; + +/*-- source modes; F==file, I==stdin, O==stdout --*/ +#define SM_I2O 1 +#define SM_F2O 2 +#define SM_F2F 3 + +/*-- operation modes --*/ +#define OM_Z 1 +#define OM_UNZ 2 +#define OM_TEST 3 + +Int32 opMode; +Int32 srcMode; + +#define FILE_NAME_LEN 1034 + +Int32 longestFileName; +Char inName [FILE_NAME_LEN]; +Char outName[FILE_NAME_LEN]; +Char tmpName[FILE_NAME_LEN]; +Char *progName; +Char progNameReally[FILE_NAME_LEN]; +FILE *outputHandleJustInCase; +Int32 workFactor; + +static void panic ( const Char* ) NORETURN; +static void ioError ( void ) NORETURN; +static void outOfMemory ( void ) NORETURN; +static void configError ( void ) NORETURN; +static void crcError ( void ) NORETURN; +static void cleanUpAndFail ( Int32 ) NORETURN; +static void compressedStreamEOF ( void ) NORETURN; + +static void copyFileName ( Char*, Char* ); +static void* myMalloc ( Int32 ); +static void applySavedFileAttrToOutputFile ( IntNative fd ); + + + +/*---------------------------------------------------*/ +/*--- An implementation of 64-bit ints. Sigh. ---*/ +/*--- Roll on widespread deployment of ANSI C9X ! ---*/ +/*---------------------------------------------------*/ + +typedef + struct { UChar b[8]; } + UInt64; + + +static +void uInt64_from_UInt32s ( UInt64* n, UInt32 lo32, UInt32 hi32 ) +{ + n->b[7] = (UChar)((hi32 >> 24) & 0xFF); + n->b[6] = (UChar)((hi32 >> 16) & 0xFF); + n->b[5] = (UChar)((hi32 >> 8) & 0xFF); + n->b[4] = (UChar) (hi32 & 0xFF); + n->b[3] = (UChar)((lo32 >> 24) & 0xFF); + n->b[2] = (UChar)((lo32 >> 16) & 0xFF); + n->b[1] = (UChar)((lo32 >> 8) & 0xFF); + n->b[0] = (UChar) (lo32 & 0xFF); +} + + +static +double uInt64_to_double ( UInt64* n ) +{ + Int32 i; + double base = 1.0; + double sum = 0.0; + for (i = 0; i < 8; i++) { + sum += base * (double)(n->b[i]); + base *= 256.0; + } + return sum; +} + + +static +Bool uInt64_isZero ( UInt64* n ) +{ + Int32 i; + for (i = 0; i < 8; i++) + if (n->b[i] != 0) return 0; + return 1; +} + + +/* Divide *n by 10, and return the remainder. */ +static +Int32 uInt64_qrm10 ( UInt64* n ) +{ + UInt32 rem, tmp; + Int32 i; + rem = 0; + for (i = 7; i >= 0; i--) { + tmp = rem * 256 + n->b[i]; + n->b[i] = tmp / 10; + rem = tmp % 10; + } + return rem; +} + + +/* ... and the Whole Entire Point of all this UInt64 stuff is + so that we can supply the following function. +*/ +static +void uInt64_toAscii ( char* outbuf, UInt64* n ) +{ + Int32 i, q; + UChar buf[32]; + Int32 nBuf = 0; + UInt64 n_copy = *n; + do { + q = uInt64_qrm10 ( &n_copy ); + buf[nBuf] = q + '0'; + nBuf++; + } while (!uInt64_isZero(&n_copy)); + outbuf[nBuf] = 0; + for (i = 0; i < nBuf; i++) + outbuf[i] = buf[nBuf-i-1]; +} + + +/*---------------------------------------------------*/ +/*--- Processing of complete files and streams ---*/ +/*---------------------------------------------------*/ + +/*---------------------------------------------*/ +static +Bool myfeof ( FILE* f ) +{ + Int32 c = fgetc ( f ); + if (c == EOF) return True; + ungetc ( c, f ); + return False; +} + + +/*---------------------------------------------*/ +static +void compressStream ( FILE *stream, FILE *zStream ) +{ + BZFILE* bzf = NULL; + UChar ibuf[5000]; + Int32 nIbuf; + UInt32 nbytes_in_lo32, nbytes_in_hi32; + UInt32 nbytes_out_lo32, nbytes_out_hi32; + Int32 bzerr, bzerr_dummy, ret; + + SET_BINARY_MODE(stream); + SET_BINARY_MODE(zStream); + + if (ferror(stream)) goto errhandler_io; + if (ferror(zStream)) goto errhandler_io; + + bzf = BZ2_bzWriteOpen ( &bzerr, zStream, + blockSize100k, verbosity, workFactor ); + if (bzerr != BZ_OK) goto errhandler; + + if (verbosity >= 2) fprintf ( stderr, "\n" ); + + while (True) { + + if (myfeof(stream)) break; + nIbuf = fread ( ibuf, sizeof(UChar), 5000, stream ); + if (ferror(stream)) goto errhandler_io; + if (nIbuf > 0) BZ2_bzWrite ( &bzerr, bzf, (void*)ibuf, nIbuf ); + if (bzerr != BZ_OK) goto errhandler; + + } + + BZ2_bzWriteClose64 ( &bzerr, bzf, 0, + &nbytes_in_lo32, &nbytes_in_hi32, + &nbytes_out_lo32, &nbytes_out_hi32 ); + if (bzerr != BZ_OK) goto errhandler; + + if (ferror(zStream)) goto errhandler_io; + ret = fflush ( zStream ); + if (ret == EOF) goto errhandler_io; + if (zStream != stdout) { + Int32 fd = fileno ( zStream ); + if (fd < 0) goto errhandler_io; + applySavedFileAttrToOutputFile ( fd ); + ret = fclose ( zStream ); + outputHandleJustInCase = NULL; + if (ret == EOF) goto errhandler_io; + } + outputHandleJustInCase = NULL; + if (ferror(stream)) goto errhandler_io; + ret = fclose ( stream ); + if (ret == EOF) goto errhandler_io; + + if (verbosity >= 1) { + if (nbytes_in_lo32 == 0 && nbytes_in_hi32 == 0) { + fprintf ( stderr, " no data compressed.\n"); + } else { + Char buf_nin[32], buf_nout[32]; + UInt64 nbytes_in, nbytes_out; + double nbytes_in_d, nbytes_out_d; + uInt64_from_UInt32s ( &nbytes_in, + nbytes_in_lo32, nbytes_in_hi32 ); + uInt64_from_UInt32s ( &nbytes_out, + nbytes_out_lo32, nbytes_out_hi32 ); + nbytes_in_d = uInt64_to_double ( &nbytes_in ); + nbytes_out_d = uInt64_to_double ( &nbytes_out ); + uInt64_toAscii ( buf_nin, &nbytes_in ); + uInt64_toAscii ( buf_nout, &nbytes_out ); + fprintf ( stderr, "%6.3f:1, %6.3f bits/byte, " + "%5.2f%% saved, %s in, %s out.\n", + nbytes_in_d / nbytes_out_d, + (8.0 * nbytes_out_d) / nbytes_in_d, + 100.0 * (1.0 - nbytes_out_d / nbytes_in_d), + buf_nin, + buf_nout + ); + } + } + + return; + + errhandler: + BZ2_bzWriteClose64 ( &bzerr_dummy, bzf, 1, + &nbytes_in_lo32, &nbytes_in_hi32, + &nbytes_out_lo32, &nbytes_out_hi32 ); + switch (bzerr) { + case BZ_CONFIG_ERROR: + configError(); break; + case BZ_MEM_ERROR: + outOfMemory (); break; + case BZ_IO_ERROR: + errhandler_io: + ioError(); break; + default: + panic ( "compress:unexpected error" ); + } + + panic ( "compress:end" ); + /*notreached*/ +} + + + +/*---------------------------------------------*/ +static +Bool uncompressStream ( FILE *zStream, FILE *stream ) +{ + BZFILE* bzf = NULL; + Int32 bzerr, bzerr_dummy, ret, nread, streamNo, i; + UChar obuf[5000]; + UChar unused[BZ_MAX_UNUSED]; + Int32 nUnused; + void* unusedTmpV; + UChar* unusedTmp; + + nUnused = 0; + streamNo = 0; + + SET_BINARY_MODE(stream); + SET_BINARY_MODE(zStream); + + if (ferror(stream)) goto errhandler_io; + if (ferror(zStream)) goto errhandler_io; + + while (True) { + + bzf = BZ2_bzReadOpen ( + &bzerr, zStream, verbosity, + (int)smallMode, unused, nUnused + ); + if (bzf == NULL || bzerr != BZ_OK) goto errhandler; + streamNo++; + + while (bzerr == BZ_OK) { + nread = BZ2_bzRead ( &bzerr, bzf, obuf, 5000 ); + if (bzerr == BZ_DATA_ERROR_MAGIC) goto trycat; + if ((bzerr == BZ_OK || bzerr == BZ_STREAM_END) && nread > 0) + fwrite ( obuf, sizeof(UChar), nread, stream ); + if (ferror(stream)) goto errhandler_io; + } + if (bzerr != BZ_STREAM_END) goto errhandler; + + BZ2_bzReadGetUnused ( &bzerr, bzf, &unusedTmpV, &nUnused ); + if (bzerr != BZ_OK) panic ( "decompress:bzReadGetUnused" ); + + unusedTmp = (UChar*)unusedTmpV; + for (i = 0; i < nUnused; i++) unused[i] = unusedTmp[i]; + + BZ2_bzReadClose ( &bzerr, bzf ); + if (bzerr != BZ_OK) panic ( "decompress:bzReadGetUnused" ); + + if (nUnused == 0 && myfeof(zStream)) break; + } + + closeok: + if (ferror(zStream)) goto errhandler_io; + if (stream != stdout) { + Int32 fd = fileno ( stream ); + if (fd < 0) goto errhandler_io; + applySavedFileAttrToOutputFile ( fd ); + } + ret = fclose ( zStream ); + if (ret == EOF) goto errhandler_io; + + if (ferror(stream)) goto errhandler_io; + ret = fflush ( stream ); + if (ret != 0) goto errhandler_io; + if (stream != stdout) { + ret = fclose ( stream ); + outputHandleJustInCase = NULL; + if (ret == EOF) goto errhandler_io; + } + outputHandleJustInCase = NULL; + if (verbosity >= 2) fprintf ( stderr, "\n " ); + return True; + + trycat: + if (forceOverwrite) { + rewind(zStream); + while (True) { + if (myfeof(zStream)) break; + nread = fread ( obuf, sizeof(UChar), 5000, zStream ); + if (ferror(zStream)) goto errhandler_io; + if (nread > 0) fwrite ( obuf, sizeof(UChar), nread, stream ); + if (ferror(stream)) goto errhandler_io; + } + goto closeok; + } + + errhandler: + BZ2_bzReadClose ( &bzerr_dummy, bzf ); + switch (bzerr) { + case BZ_CONFIG_ERROR: + configError(); break; + case BZ_IO_ERROR: + errhandler_io: + ioError(); break; + case BZ_DATA_ERROR: + crcError(); + case BZ_MEM_ERROR: + outOfMemory(); + case BZ_UNEXPECTED_EOF: + compressedStreamEOF(); + case BZ_DATA_ERROR_MAGIC: + if (zStream != stdin) fclose(zStream); + if (stream != stdout) fclose(stream); + if (streamNo == 1) { + return False; + } else { + if (noisy) + fprintf ( stderr, + "\n%s: %s: trailing garbage after EOF ignored\n", + progName, inName ); + return True; + } + default: + panic ( "decompress:unexpected error" ); + } + + panic ( "decompress:end" ); + return True; /*notreached*/ +} + + +/*---------------------------------------------*/ +static +Bool testStream ( FILE *zStream ) +{ + BZFILE* bzf = NULL; + Int32 bzerr, bzerr_dummy, ret, nread, streamNo, i; + UChar obuf[5000]; + UChar unused[BZ_MAX_UNUSED]; + Int32 nUnused; + void* unusedTmpV; + UChar* unusedTmp; + + nUnused = 0; + streamNo = 0; + + SET_BINARY_MODE(zStream); + if (ferror(zStream)) goto errhandler_io; + + while (True) { + + bzf = BZ2_bzReadOpen ( + &bzerr, zStream, verbosity, + (int)smallMode, unused, nUnused + ); + if (bzf == NULL || bzerr != BZ_OK) goto errhandler; + streamNo++; + + while (bzerr == BZ_OK) { + nread = BZ2_bzRead ( &bzerr, bzf, obuf, 5000 ); + if (bzerr == BZ_DATA_ERROR_MAGIC) goto errhandler; + } + if (bzerr != BZ_STREAM_END) goto errhandler; + + BZ2_bzReadGetUnused ( &bzerr, bzf, &unusedTmpV, &nUnused ); + if (bzerr != BZ_OK) panic ( "test:bzReadGetUnused" ); + + unusedTmp = (UChar*)unusedTmpV; + for (i = 0; i < nUnused; i++) unused[i] = unusedTmp[i]; + + BZ2_bzReadClose ( &bzerr, bzf ); + if (bzerr != BZ_OK) panic ( "test:bzReadGetUnused" ); + if (nUnused == 0 && myfeof(zStream)) break; + + } + + if (ferror(zStream)) goto errhandler_io; + ret = fclose ( zStream ); + if (ret == EOF) goto errhandler_io; + + if (verbosity >= 2) fprintf ( stderr, "\n " ); + return True; + + errhandler: + BZ2_bzReadClose ( &bzerr_dummy, bzf ); + if (verbosity == 0) + fprintf ( stderr, "%s: %s: ", progName, inName ); + switch (bzerr) { + case BZ_CONFIG_ERROR: + configError(); break; + case BZ_IO_ERROR: + errhandler_io: + ioError(); break; + case BZ_DATA_ERROR: + fprintf ( stderr, + "data integrity (CRC) error in data\n" ); + return False; + case BZ_MEM_ERROR: + outOfMemory(); + case BZ_UNEXPECTED_EOF: + fprintf ( stderr, + "file ends unexpectedly\n" ); + return False; + case BZ_DATA_ERROR_MAGIC: + if (zStream != stdin) fclose(zStream); + if (streamNo == 1) { + fprintf ( stderr, + "bad magic number (file not created by bzip2)\n" ); + return False; + } else { + if (noisy) + fprintf ( stderr, + "trailing garbage after EOF ignored\n" ); + return True; + } + default: + panic ( "test:unexpected error" ); + } + + panic ( "test:end" ); + return True; /*notreached*/ +} + + +/*---------------------------------------------------*/ +/*--- Error [non-] handling grunge ---*/ +/*---------------------------------------------------*/ + +/*---------------------------------------------*/ +static +void setExit ( Int32 v ) +{ + if (v > exitValue) exitValue = v; +} + + +/*---------------------------------------------*/ +static +void cadvise ( void ) +{ + if (noisy) + fprintf ( + stderr, + "\nIt is possible that the compressed file(s) have become corrupted.\n" + "You can use the -tvv option to test integrity of such files.\n\n" + "You can use the `bzip2recover' program to attempt to recover\n" + "data from undamaged sections of corrupted files.\n\n" + ); +} + + +/*---------------------------------------------*/ +static +void showFileNames ( void ) +{ + if (noisy) + fprintf ( + stderr, + "\tInput file = %s, output file = %s\n", + inName, outName + ); +} + + +/*---------------------------------------------*/ +static +void cleanUpAndFail ( Int32 ec ) +{ + IntNative retVal; + struct MY_STAT statBuf; + + if ( srcMode == SM_F2F + && opMode != OM_TEST + && deleteOutputOnInterrupt ) { + + /* Check whether input file still exists. Delete output file + only if input exists to avoid loss of data. Joerg Prante, 5 + January 2002. (JRS 06-Jan-2002: other changes in 1.0.2 mean + this is less likely to happen. But to be ultra-paranoid, we + do the check anyway.) */ + retVal = MY_STAT ( inName, &statBuf ); + if (retVal == 0) { + if (noisy) + fprintf ( stderr, + "%s: Deleting output file %s, if it exists.\n", + progName, outName ); + if (outputHandleJustInCase != NULL) + fclose ( outputHandleJustInCase ); + retVal = remove ( outName ); + if (retVal != 0) + fprintf ( stderr, + "%s: WARNING: deletion of output file " + "(apparently) failed.\n", + progName ); + } else { + fprintf ( stderr, + "%s: WARNING: deletion of output file suppressed\n", + progName ); + fprintf ( stderr, + "%s: since input file no longer exists. Output file\n", + progName ); + fprintf ( stderr, + "%s: `%s' may be incomplete.\n", + progName, outName ); + fprintf ( stderr, + "%s: I suggest doing an integrity test (bzip2 -tv)" + " of it.\n", + progName ); + } + } + + if (noisy && numFileNames > 0 && numFilesProcessed < numFileNames) { + fprintf ( stderr, + "%s: WARNING: some files have not been processed:\n" + "%s: %d specified on command line, %d not processed yet.\n\n", + progName, progName, + numFileNames, numFileNames - numFilesProcessed ); + } + setExit(ec); + exit(exitValue); +} + + +/*---------------------------------------------*/ +static +void panic ( const Char* s ) +{ + fprintf ( stderr, + "\n%s: PANIC -- internal consistency error:\n" + "\t%s\n" + "\tThis is a BUG. Please report it to me at:\n" + "\tjseward@bzip.org\n", + progName, s ); + showFileNames(); + cleanUpAndFail( 3 ); +} + + +/*---------------------------------------------*/ +static +void crcError ( void ) +{ + fprintf ( stderr, + "\n%s: Data integrity error when decompressing.\n", + progName ); + showFileNames(); + cadvise(); + cleanUpAndFail( 2 ); +} + + +/*---------------------------------------------*/ +static +void compressedStreamEOF ( void ) +{ + if (noisy) { + fprintf ( stderr, + "\n%s: Compressed file ends unexpectedly;\n\t" + "perhaps it is corrupted? *Possible* reason follows.\n", + progName ); + perror ( progName ); + showFileNames(); + cadvise(); + } + cleanUpAndFail( 2 ); +} + + +/*---------------------------------------------*/ +static +void ioError ( void ) +{ + fprintf ( stderr, + "\n%s: I/O or other error, bailing out. " + "Possible reason follows.\n", + progName ); + perror ( progName ); + showFileNames(); + cleanUpAndFail( 1 ); +} + + +/*---------------------------------------------*/ +static +void mySignalCatcher ( IntNative n ) +{ + fprintf ( stderr, + "\n%s: Control-C or similar caught, quitting.\n", + progName ); + cleanUpAndFail(1); +} + + +/*---------------------------------------------*/ +static +void mySIGSEGVorSIGBUScatcher ( IntNative n ) +{ + if (opMode == OM_Z) + fprintf ( + stderr, + "\n%s: Caught a SIGSEGV or SIGBUS whilst compressing.\n" + "\n" + " Possible causes are (most likely first):\n" + " (1) This computer has unreliable memory or cache hardware\n" + " (a surprisingly common problem; try a different machine.)\n" + " (2) A bug in the compiler used to create this executable\n" + " (unlikely, if you didn't compile bzip2 yourself.)\n" + " (3) A real bug in bzip2 -- I hope this should never be the case.\n" + " The user's manual, Section 4.3, has more info on (1) and (2).\n" + " \n" + " If you suspect this is a bug in bzip2, or are unsure about (1)\n" + " or (2), feel free to report it to me at: jseward@bzip.org.\n" + " Section 4.3 of the user's manual describes the info a useful\n" + " bug report should have. If the manual is available on your\n" + " system, please try and read it before mailing me. If you don't\n" + " have the manual or can't be bothered to read it, mail me anyway.\n" + "\n", + progName ); + else + fprintf ( + stderr, + "\n%s: Caught a SIGSEGV or SIGBUS whilst decompressing.\n" + "\n" + " Possible causes are (most likely first):\n" + " (1) The compressed data is corrupted, and bzip2's usual checks\n" + " failed to detect this. Try bzip2 -tvv my_file.bz2.\n" + " (2) This computer has unreliable memory or cache hardware\n" + " (a surprisingly common problem; try a different machine.)\n" + " (3) A bug in the compiler used to create this executable\n" + " (unlikely, if you didn't compile bzip2 yourself.)\n" + " (4) A real bug in bzip2 -- I hope this should never be the case.\n" + " The user's manual, Section 4.3, has more info on (2) and (3).\n" + " \n" + " If you suspect this is a bug in bzip2, or are unsure about (2)\n" + " or (3), feel free to report it to me at: jseward@bzip.org.\n" + " Section 4.3 of the user's manual describes the info a useful\n" + " bug report should have. If the manual is available on your\n" + " system, please try and read it before mailing me. If you don't\n" + " have the manual or can't be bothered to read it, mail me anyway.\n" + "\n", + progName ); + + showFileNames(); + if (opMode == OM_Z) + cleanUpAndFail( 3 ); else + { cadvise(); cleanUpAndFail( 2 ); } +} + + +/*---------------------------------------------*/ +static +void outOfMemory ( void ) +{ + fprintf ( stderr, + "\n%s: couldn't allocate enough memory\n", + progName ); + showFileNames(); + cleanUpAndFail(1); +} + + +/*---------------------------------------------*/ +static +void configError ( void ) +{ + fprintf ( stderr, + "bzip2: I'm not configured correctly for this platform!\n" + "\tI require Int32, Int16 and Char to have sizes\n" + "\tof 4, 2 and 1 bytes to run properly, and they don't.\n" + "\tProbably you can fix this by defining them correctly,\n" + "\tand recompiling. Bye!\n" ); + setExit(3); + exit(exitValue); +} + + +/*---------------------------------------------------*/ +/*--- The main driver machinery ---*/ +/*---------------------------------------------------*/ + +/* All rather crufty. The main problem is that input files + are stat()d multiple times before use. This should be + cleaned up. +*/ + +/*---------------------------------------------*/ +static +void pad ( Char *s ) +{ + Int32 i; + if ( (Int32)strlen(s) >= longestFileName ) return; + for (i = 1; i <= longestFileName - (Int32)strlen(s); i++) + fprintf ( stderr, " " ); +} + + +/*---------------------------------------------*/ +static +void copyFileName ( Char* to, Char* from ) +{ + if ( strlen(from) > FILE_NAME_LEN-10 ) { + fprintf ( + stderr, + "bzip2: file name\n`%s'\n" + "is suspiciously (more than %d chars) long.\n" + "Try using a reasonable file name instead. Sorry! :-)\n", + from, FILE_NAME_LEN-10 + ); + setExit(1); + exit(exitValue); + } + + strncpy(to,from,FILE_NAME_LEN-10); + to[FILE_NAME_LEN-10]='\0'; +} + + +/*---------------------------------------------*/ +static +Bool fileExists ( Char* name ) +{ + FILE *tmp = fopen ( name, "rb" ); + Bool exists = (tmp != NULL); + if (tmp != NULL) fclose ( tmp ); + return exists; +} + + +/*---------------------------------------------*/ +/* Open an output file safely with O_EXCL and good permissions. + This avoids a race condition in versions < 1.0.2, in which + the file was first opened and then had its interim permissions + set safely. We instead use open() to create the file with + the interim permissions required. (--- --- rw-). + + For non-Unix platforms, if we are not worrying about + security issues, simple this simply behaves like fopen. +*/ +static +FILE* fopen_output_safely ( Char* name, const char* mode ) +{ +# if BZ_UNIX + FILE* fp; + IntNative fh; + fh = open(name, O_WRONLY|O_CREAT|O_EXCL, S_IWUSR|S_IRUSR); + if (fh == -1) return NULL; + fp = fdopen(fh, mode); + if (fp == NULL) close(fh); + return fp; +# else + return fopen(name, mode); +# endif +} + + +/*---------------------------------------------*/ +/*-- + if in doubt, return True +--*/ +static +Bool notAStandardFile ( Char* name ) +{ + IntNative i; + struct MY_STAT statBuf; + + i = MY_LSTAT ( name, &statBuf ); + if (i != 0) return True; + if (MY_S_ISREG(statBuf.st_mode)) return False; + return True; +} + + +/*---------------------------------------------*/ +/*-- + rac 11/21/98 see if file has hard links to it +--*/ +static +Int32 countHardLinks ( Char* name ) +{ + IntNative i; + struct MY_STAT statBuf; + + i = MY_LSTAT ( name, &statBuf ); + if (i != 0) return 0; + return (statBuf.st_nlink - 1); +} + + +/*---------------------------------------------*/ +/* Copy modification date, access date, permissions and owner from the + source to destination file. We have to copy this meta-info off + into fileMetaInfo before starting to compress / decompress it, + because doing it afterwards means we get the wrong access time. + + To complicate matters, in compress() and decompress() below, the + sequence of tests preceding the call to saveInputFileMetaInfo() + involves calling fileExists(), which in turn establishes its result + by attempting to fopen() the file, and if successful, immediately + fclose()ing it again. So we have to assume that the fopen() call + does not cause the access time field to be updated. + + Reading of the man page for stat() (man 2 stat) on RedHat 7.2 seems + to imply that merely doing open() will not affect the access time. + Therefore we merely need to hope that the C library only does + open() as a result of fopen(), and not any kind of read()-ahead + cleverness. + + It sounds pretty fragile to me. Whether this carries across + robustly to arbitrary Unix-like platforms (or even works robustly + on this one, RedHat 7.2) is unknown to me. Nevertheless ... +*/ +#if BZ_UNIX +static +struct MY_STAT fileMetaInfo; +#endif + +static +void saveInputFileMetaInfo ( Char *srcName ) +{ +# if BZ_UNIX + IntNative retVal; + /* Note use of stat here, not lstat. */ + retVal = MY_STAT( srcName, &fileMetaInfo ); + ERROR_IF_NOT_ZERO ( retVal ); +# endif +} + + +static +void applySavedTimeInfoToOutputFile ( Char *dstName ) +{ +# if BZ_UNIX + IntNative retVal; + struct utimbuf uTimBuf; + + uTimBuf.actime = fileMetaInfo.st_atime; + uTimBuf.modtime = fileMetaInfo.st_mtime; + + retVal = utime ( dstName, &uTimBuf ); + ERROR_IF_NOT_ZERO ( retVal ); +# endif +} + +static +void applySavedFileAttrToOutputFile ( IntNative fd ) +{ +# if BZ_UNIX + IntNative retVal; + + retVal = fchmod ( fd, fileMetaInfo.st_mode ); + ERROR_IF_NOT_ZERO ( retVal ); + + (void) fchown ( fd, fileMetaInfo.st_uid, fileMetaInfo.st_gid ); + /* chown() will in many cases return with EPERM, which can + be safely ignored. + */ +# endif +} + + +/*---------------------------------------------*/ +static +Bool containsDubiousChars ( Char* name ) +{ +# if BZ_UNIX + /* On unix, files can contain any characters and the file expansion + * is performed by the shell. + */ + return False; +# else /* ! BZ_UNIX */ + /* On non-unix (Win* platforms), wildcard characters are not allowed in + * filenames. + */ + for (; *name != '\0'; name++) + if (*name == '?' || *name == '*') return True; + return False; +# endif /* BZ_UNIX */ +} + + +/*---------------------------------------------*/ +#define BZ_N_SUFFIX_PAIRS 4 + +const Char* zSuffix[BZ_N_SUFFIX_PAIRS] + = { ".bz2", ".bz", ".tbz2", ".tbz" }; +const Char* unzSuffix[BZ_N_SUFFIX_PAIRS] + = { "", "", ".tar", ".tar" }; + +static +Bool hasSuffix ( Char* s, const Char* suffix ) +{ + Int32 ns = strlen(s); + Int32 nx = strlen(suffix); + if (ns < nx) return False; + if (strcmp(s + ns - nx, suffix) == 0) return True; + return False; +} + +static +Bool mapSuffix ( Char* name, + const Char* oldSuffix, + const Char* newSuffix ) +{ + if (!hasSuffix(name,oldSuffix)) return False; + name[strlen(name)-strlen(oldSuffix)] = 0; + strcat ( name, newSuffix ); + return True; +} + + +/*---------------------------------------------*/ +static +void compress ( Char *name ) +{ + FILE *inStr; + FILE *outStr; + Int32 n, i; + struct MY_STAT statBuf; + + deleteOutputOnInterrupt = False; + + if (name == NULL && srcMode != SM_I2O) + panic ( "compress: bad modes\n" ); + + switch (srcMode) { + case SM_I2O: + copyFileName ( inName, (Char*)"(stdin)" ); + copyFileName ( outName, (Char*)"(stdout)" ); + break; + case SM_F2F: + copyFileName ( inName, name ); + copyFileName ( outName, name ); + strcat ( outName, ".bz2" ); + break; + case SM_F2O: + copyFileName ( inName, name ); + copyFileName ( outName, (Char*)"(stdout)" ); + break; + } + + if ( srcMode != SM_I2O && containsDubiousChars ( inName ) ) { + if (noisy) + fprintf ( stderr, "%s: There are no files matching `%s'.\n", + progName, inName ); + setExit(1); + return; + } + if ( srcMode != SM_I2O && !fileExists ( inName ) ) { + fprintf ( stderr, "%s: Can't open input file %s: %s.\n", + progName, inName, strerror(errno) ); + setExit(1); + return; + } + for (i = 0; i < BZ_N_SUFFIX_PAIRS; i++) { + if (hasSuffix(inName, zSuffix[i])) { + if (noisy) + fprintf ( stderr, + "%s: Input file %s already has %s suffix.\n", + progName, inName, zSuffix[i] ); + setExit(1); + return; + } + } + if ( srcMode == SM_F2F || srcMode == SM_F2O ) { + MY_STAT(inName, &statBuf); + if ( MY_S_ISDIR(statBuf.st_mode) ) { + fprintf( stderr, + "%s: Input file %s is a directory.\n", + progName,inName); + setExit(1); + return; + } + } + if ( srcMode == SM_F2F && !forceOverwrite && notAStandardFile ( inName )) { + if (noisy) + fprintf ( stderr, "%s: Input file %s is not a normal file.\n", + progName, inName ); + setExit(1); + return; + } + if ( srcMode == SM_F2F && fileExists ( outName ) ) { + if (forceOverwrite) { + remove(outName); + } else { + fprintf ( stderr, "%s: Output file %s already exists.\n", + progName, outName ); + setExit(1); + return; + } + } + if ( srcMode == SM_F2F && !forceOverwrite && + (n=countHardLinks ( inName )) > 0) { + fprintf ( stderr, "%s: Input file %s has %d other link%s.\n", + progName, inName, n, n > 1 ? "s" : "" ); + setExit(1); + return; + } + + if ( srcMode == SM_F2F ) { + /* Save the file's meta-info before we open it. Doing it later + means we mess up the access times. */ + saveInputFileMetaInfo ( inName ); + } + + switch ( srcMode ) { + + case SM_I2O: + inStr = stdin; + outStr = stdout; + if ( isatty ( fileno ( stdout ) ) ) { + fprintf ( stderr, + "%s: I won't write compressed data to a terminal.\n", + progName ); + fprintf ( stderr, "%s: For help, type: `%s --help'.\n", + progName, progName ); + setExit(1); + return; + }; + break; + + case SM_F2O: + inStr = fopen ( inName, "rb" ); + outStr = stdout; + if ( isatty ( fileno ( stdout ) ) ) { + fprintf ( stderr, + "%s: I won't write compressed data to a terminal.\n", + progName ); + fprintf ( stderr, "%s: For help, type: `%s --help'.\n", + progName, progName ); + if ( inStr != NULL ) fclose ( inStr ); + setExit(1); + return; + }; + if ( inStr == NULL ) { + fprintf ( stderr, "%s: Can't open input file %s: %s.\n", + progName, inName, strerror(errno) ); + setExit(1); + return; + }; + break; + + case SM_F2F: + inStr = fopen ( inName, "rb" ); + outStr = fopen_output_safely ( outName, "wb" ); + if ( outStr == NULL) { + fprintf ( stderr, "%s: Can't create output file %s: %s.\n", + progName, outName, strerror(errno) ); + if ( inStr != NULL ) fclose ( inStr ); + setExit(1); + return; + } + if ( inStr == NULL ) { + fprintf ( stderr, "%s: Can't open input file %s: %s.\n", + progName, inName, strerror(errno) ); + if ( outStr != NULL ) fclose ( outStr ); + setExit(1); + return; + }; + break; + + default: + panic ( "compress: bad srcMode" ); + break; + } + + if (verbosity >= 1) { + fprintf ( stderr, " %s: ", inName ); + pad ( inName ); + fflush ( stderr ); + } + + /*--- Now the input and output handles are sane. Do the Biz. ---*/ + outputHandleJustInCase = outStr; + deleteOutputOnInterrupt = True; + compressStream ( inStr, outStr ); + outputHandleJustInCase = NULL; + + /*--- If there was an I/O error, we won't get here. ---*/ + if ( srcMode == SM_F2F ) { + applySavedTimeInfoToOutputFile ( outName ); + deleteOutputOnInterrupt = False; + if ( !keepInputFiles ) { + IntNative retVal = remove ( inName ); + ERROR_IF_NOT_ZERO ( retVal ); + } + } + + deleteOutputOnInterrupt = False; +} + + +/*---------------------------------------------*/ +static +void uncompress ( Char *name ) +{ + FILE *inStr; + FILE *outStr; + Int32 n, i; + Bool magicNumberOK; + Bool cantGuess; + struct MY_STAT statBuf; + + deleteOutputOnInterrupt = False; + + if (name == NULL && srcMode != SM_I2O) + panic ( "uncompress: bad modes\n" ); + + cantGuess = False; + switch (srcMode) { + case SM_I2O: + copyFileName ( inName, (Char*)"(stdin)" ); + copyFileName ( outName, (Char*)"(stdout)" ); + break; + case SM_F2F: + copyFileName ( inName, name ); + copyFileName ( outName, name ); + for (i = 0; i < BZ_N_SUFFIX_PAIRS; i++) + if (mapSuffix(outName,zSuffix[i],unzSuffix[i])) + goto zzz; + cantGuess = True; + strcat ( outName, ".out" ); + break; + case SM_F2O: + copyFileName ( inName, name ); + copyFileName ( outName, (Char*)"(stdout)" ); + break; + } + + zzz: + if ( srcMode != SM_I2O && containsDubiousChars ( inName ) ) { + if (noisy) + fprintf ( stderr, "%s: There are no files matching `%s'.\n", + progName, inName ); + setExit(1); + return; + } + if ( srcMode != SM_I2O && !fileExists ( inName ) ) { + fprintf ( stderr, "%s: Can't open input file %s: %s.\n", + progName, inName, strerror(errno) ); + setExit(1); + return; + } + if ( srcMode == SM_F2F || srcMode == SM_F2O ) { + MY_STAT(inName, &statBuf); + if ( MY_S_ISDIR(statBuf.st_mode) ) { + fprintf( stderr, + "%s: Input file %s is a directory.\n", + progName,inName); + setExit(1); + return; + } + } + if ( srcMode == SM_F2F && !forceOverwrite && notAStandardFile ( inName )) { + if (noisy) + fprintf ( stderr, "%s: Input file %s is not a normal file.\n", + progName, inName ); + setExit(1); + return; + } + if ( /* srcMode == SM_F2F implied && */ cantGuess ) { + if (noisy) + fprintf ( stderr, + "%s: Can't guess original name for %s -- using %s\n", + progName, inName, outName ); + /* just a warning, no return */ + } + if ( srcMode == SM_F2F && fileExists ( outName ) ) { + if (forceOverwrite) { + remove(outName); + } else { + fprintf ( stderr, "%s: Output file %s already exists.\n", + progName, outName ); + setExit(1); + return; + } + } + if ( srcMode == SM_F2F && !forceOverwrite && + (n=countHardLinks ( inName ) ) > 0) { + fprintf ( stderr, "%s: Input file %s has %d other link%s.\n", + progName, inName, n, n > 1 ? "s" : "" ); + setExit(1); + return; + } + + if ( srcMode == SM_F2F ) { + /* Save the file's meta-info before we open it. Doing it later + means we mess up the access times. */ + saveInputFileMetaInfo ( inName ); + } + + switch ( srcMode ) { + + case SM_I2O: + inStr = stdin; + outStr = stdout; + if ( isatty ( fileno ( stdin ) ) ) { + fprintf ( stderr, + "%s: I won't read compressed data from a terminal.\n", + progName ); + fprintf ( stderr, "%s: For help, type: `%s --help'.\n", + progName, progName ); + setExit(1); + return; + }; + break; + + case SM_F2O: + inStr = fopen ( inName, "rb" ); + outStr = stdout; + if ( inStr == NULL ) { + fprintf ( stderr, "%s: Can't open input file %s:%s.\n", + progName, inName, strerror(errno) ); + if ( inStr != NULL ) fclose ( inStr ); + setExit(1); + return; + }; + break; + + case SM_F2F: + inStr = fopen ( inName, "rb" ); + outStr = fopen_output_safely ( outName, "wb" ); + if ( outStr == NULL) { + fprintf ( stderr, "%s: Can't create output file %s: %s.\n", + progName, outName, strerror(errno) ); + if ( inStr != NULL ) fclose ( inStr ); + setExit(1); + return; + } + if ( inStr == NULL ) { + fprintf ( stderr, "%s: Can't open input file %s: %s.\n", + progName, inName, strerror(errno) ); + if ( outStr != NULL ) fclose ( outStr ); + setExit(1); + return; + }; + break; + + default: + panic ( "uncompress: bad srcMode" ); + break; + } + + if (verbosity >= 1) { + fprintf ( stderr, " %s: ", inName ); + pad ( inName ); + fflush ( stderr ); + } + + /*--- Now the input and output handles are sane. Do the Biz. ---*/ + outputHandleJustInCase = outStr; + deleteOutputOnInterrupt = True; + magicNumberOK = uncompressStream ( inStr, outStr ); + outputHandleJustInCase = NULL; + + /*--- If there was an I/O error, we won't get here. ---*/ + if ( magicNumberOK ) { + if ( srcMode == SM_F2F ) { + applySavedTimeInfoToOutputFile ( outName ); + deleteOutputOnInterrupt = False; + if ( !keepInputFiles ) { + IntNative retVal = remove ( inName ); + ERROR_IF_NOT_ZERO ( retVal ); + } + } + } else { + unzFailsExist = True; + deleteOutputOnInterrupt = False; + if ( srcMode == SM_F2F ) { + IntNative retVal = remove ( outName ); + ERROR_IF_NOT_ZERO ( retVal ); + } + } + deleteOutputOnInterrupt = False; + + if ( magicNumberOK ) { + if (verbosity >= 1) + fprintf ( stderr, "done\n" ); + } else { + setExit(2); + if (verbosity >= 1) + fprintf ( stderr, "not a bzip2 file.\n" ); else + fprintf ( stderr, + "%s: %s is not a bzip2 file.\n", + progName, inName ); + } + +} + + +/*---------------------------------------------*/ +static +void testf ( Char *name ) +{ + FILE *inStr; + Bool allOK; + struct MY_STAT statBuf; + + deleteOutputOnInterrupt = False; + + if (name == NULL && srcMode != SM_I2O) + panic ( "testf: bad modes\n" ); + + copyFileName ( outName, (Char*)"(none)" ); + switch (srcMode) { + case SM_I2O: copyFileName ( inName, (Char*)"(stdin)" ); break; + case SM_F2F: copyFileName ( inName, name ); break; + case SM_F2O: copyFileName ( inName, name ); break; + } + + if ( srcMode != SM_I2O && containsDubiousChars ( inName ) ) { + if (noisy) + fprintf ( stderr, "%s: There are no files matching `%s'.\n", + progName, inName ); + setExit(1); + return; + } + if ( srcMode != SM_I2O && !fileExists ( inName ) ) { + fprintf ( stderr, "%s: Can't open input %s: %s.\n", + progName, inName, strerror(errno) ); + setExit(1); + return; + } + if ( srcMode != SM_I2O ) { + MY_STAT(inName, &statBuf); + if ( MY_S_ISDIR(statBuf.st_mode) ) { + fprintf( stderr, + "%s: Input file %s is a directory.\n", + progName,inName); + setExit(1); + return; + } + } + + switch ( srcMode ) { + + case SM_I2O: + if ( isatty ( fileno ( stdin ) ) ) { + fprintf ( stderr, + "%s: I won't read compressed data from a terminal.\n", + progName ); + fprintf ( stderr, "%s: For help, type: `%s --help'.\n", + progName, progName ); + setExit(1); + return; + }; + inStr = stdin; + break; + + case SM_F2O: case SM_F2F: + inStr = fopen ( inName, "rb" ); + if ( inStr == NULL ) { + fprintf ( stderr, "%s: Can't open input file %s:%s.\n", + progName, inName, strerror(errno) ); + setExit(1); + return; + }; + break; + + default: + panic ( "testf: bad srcMode" ); + break; + } + + if (verbosity >= 1) { + fprintf ( stderr, " %s: ", inName ); + pad ( inName ); + fflush ( stderr ); + } + + /*--- Now the input handle is sane. Do the Biz. ---*/ + outputHandleJustInCase = NULL; + allOK = testStream ( inStr ); + + if (allOK && verbosity >= 1) fprintf ( stderr, "ok\n" ); + if (!allOK) testFailsExist = True; +} + + +/*---------------------------------------------*/ +static +void license ( void ) +{ + fprintf ( stderr, + + "bzip2, a block-sorting file compressor. " + "Version %s.\n" + " \n" + " Copyright (C) 1996-2010 by Julian Seward.\n" + " \n" + " This program is free software; you can redistribute it and/or modify\n" + " it under the terms set out in the LICENSE file, which is included\n" + " in the bzip2-1.0.6 source distribution.\n" + " \n" + " This program is distributed in the hope that it will be useful,\n" + " but WITHOUT ANY WARRANTY; without even the implied warranty of\n" + " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" + " LICENSE file for more details.\n" + " \n", + BZ2_bzlibVersion() + ); +} + + +/*---------------------------------------------*/ +static +void usage ( Char *fullProgName ) +{ + fprintf ( + stderr, + "bzip2, a block-sorting file compressor. " + "Version %s.\n" + "\n usage: %s [flags and input files in any order]\n" + "\n" + " -h --help print this message\n" + " -d --decompress force decompression\n" + " -z --compress force compression\n" + " -k --keep keep (don't delete) input files\n" + " -f --force overwrite existing output files\n" + " -t --test test compressed file integrity\n" + " -c --stdout output to standard out\n" + " -q --quiet suppress noncritical error messages\n" + " -v --verbose be verbose (a 2nd -v gives more)\n" + " -L --license display software version & license\n" + " -V --version display software version & license\n" + " -s --small use less memory (at most 2500k)\n" + " -1 .. -9 set block size to 100k .. 900k\n" + " --fast alias for -1\n" + " --best alias for -9\n" + "\n" + " If invoked as `bzip2', default action is to compress.\n" + " as `bunzip2', default action is to decompress.\n" + " as `bzcat', default action is to decompress to stdout.\n" + "\n" + " If no file names are given, bzip2 compresses or decompresses\n" + " from standard input to standard output. You can combine\n" + " short flags, so `-v -4' means the same as -v4 or -4v, &c.\n" +# if BZ_UNIX + "\n" +# endif + , + + BZ2_bzlibVersion(), + fullProgName + ); +} + + +/*---------------------------------------------*/ +static +void redundant ( Char* flag ) +{ + fprintf ( + stderr, + "%s: %s is redundant in versions 0.9.5 and above\n", + progName, flag ); +} + + +/*---------------------------------------------*/ +/*-- + All the garbage from here to main() is purely to + implement a linked list of command-line arguments, + into which main() copies argv[1 .. argc-1]. + + The purpose of this exercise is to facilitate + the expansion of wildcard characters * and ? in + filenames for OSs which don't know how to do it + themselves, like MSDOS, Windows 95 and NT. + + The actual Dirty Work is done by the platform- + specific macro APPEND_FILESPEC. +--*/ + +typedef + struct zzzz { + Char *name; + struct zzzz *link; + } + Cell; + + +/*---------------------------------------------*/ +static +void *myMalloc ( Int32 n ) +{ + void* p; + + p = malloc ( (size_t)n ); + if (p == NULL) outOfMemory (); + return p; +} + + +/*---------------------------------------------*/ +static +Cell *mkCell ( void ) +{ + Cell *c; + + c = (Cell*) myMalloc ( sizeof ( Cell ) ); + c->name = NULL; + c->link = NULL; + return c; +} + + +/*---------------------------------------------*/ +static +Cell *snocString ( Cell *root, Char *name ) +{ + if (root == NULL) { + Cell *tmp = mkCell(); + tmp->name = (Char*) myMalloc ( 5 + strlen(name) ); + strcpy ( tmp->name, name ); + return tmp; + } else { + Cell *tmp = root; + while (tmp->link != NULL) tmp = tmp->link; + tmp->link = snocString ( tmp->link, name ); + return root; + } +} + + +/*---------------------------------------------*/ +static +void addFlagsFromEnvVar ( Cell** argList, Char* varName ) +{ + Int32 i, j, k; + Char *envbase, *p; + + envbase = getenv(varName); + if (envbase != NULL) { + p = envbase; + i = 0; + while (True) { + if (p[i] == 0) break; + p += i; + i = 0; + while (isspace((Int32)(p[0]))) p++; + while (p[i] != 0 && !isspace((Int32)(p[i]))) i++; + if (i > 0) { + k = i; if (k > FILE_NAME_LEN-10) k = FILE_NAME_LEN-10; + for (j = 0; j < k; j++) tmpName[j] = p[j]; + tmpName[k] = 0; + APPEND_FLAG(*argList, tmpName); + } + } + } +} + + +/*---------------------------------------------*/ +#define ISFLAG(s) (strcmp(aa->name, (s))==0) + +IntNative main ( IntNative argc, Char *argv[] ) +{ + Int32 i, j; + Char *tmp; + Cell *argList; + Cell *aa; + Bool decode; + + /*-- Be really really really paranoid :-) --*/ + if (sizeof(Int32) != 4 || sizeof(UInt32) != 4 || + sizeof(Int16) != 2 || sizeof(UInt16) != 2 || + sizeof(Char) != 1 || sizeof(UChar) != 1) + configError(); + + /*-- Initialise --*/ + outputHandleJustInCase = NULL; + smallMode = False; + keepInputFiles = False; + forceOverwrite = False; + noisy = True; + verbosity = 0; + blockSize100k = 9; + testFailsExist = False; + unzFailsExist = False; + numFileNames = 0; + numFilesProcessed = 0; + workFactor = 30; + deleteOutputOnInterrupt = False; + exitValue = 0; + i = j = 0; /* avoid bogus warning from egcs-1.1.X */ + + /*-- Set up signal handlers for mem access errors --*/ + signal (SIGSEGV, mySIGSEGVorSIGBUScatcher); +# if BZ_UNIX +# ifndef __DJGPP__ + signal (SIGBUS, mySIGSEGVorSIGBUScatcher); +# endif +# endif + + copyFileName ( inName, (Char*)"(none)" ); + copyFileName ( outName, (Char*)"(none)" ); + + copyFileName ( progNameReally, argv[0] ); + progName = &progNameReally[0]; + for (tmp = &progNameReally[0]; *tmp != '\0'; tmp++) + if (*tmp == PATH_SEP) progName = tmp + 1; + + + /*-- Copy flags from env var BZIP2, and + expand filename wildcards in arg list. + --*/ + argList = NULL; + addFlagsFromEnvVar ( &argList, (Char*)"BZIP2" ); + addFlagsFromEnvVar ( &argList, (Char*)"BZIP" ); + for (i = 1; i <= argc-1; i++) + APPEND_FILESPEC(argList, argv[i]); + + + /*-- Find the length of the longest filename --*/ + longestFileName = 7; + numFileNames = 0; + decode = True; + for (aa = argList; aa != NULL; aa = aa->link) { + if (ISFLAG("--")) { decode = False; continue; } + if (aa->name[0] == '-' && decode) continue; + numFileNames++; + if (longestFileName < (Int32)strlen(aa->name) ) + longestFileName = (Int32)strlen(aa->name); + } + + + /*-- Determine source modes; flag handling may change this too. --*/ + if (numFileNames == 0) + srcMode = SM_I2O; else srcMode = SM_F2F; + + + /*-- Determine what to do (compress/uncompress/test/cat). --*/ + /*-- Note that subsequent flag handling may change this. --*/ + opMode = OM_Z; + + if ( (strstr ( progName, "unzip" ) != 0) || + (strstr ( progName, "UNZIP" ) != 0) ) + opMode = OM_UNZ; + + if ( (strstr ( progName, "z2cat" ) != 0) || + (strstr ( progName, "Z2CAT" ) != 0) || + (strstr ( progName, "zcat" ) != 0) || + (strstr ( progName, "ZCAT" ) != 0) ) { + opMode = OM_UNZ; + srcMode = (numFileNames == 0) ? SM_I2O : SM_F2O; + } + + + /*-- Look at the flags. --*/ + for (aa = argList; aa != NULL; aa = aa->link) { + if (ISFLAG("--")) break; + if (aa->name[0] == '-' && aa->name[1] != '-') { + for (j = 1; aa->name[j] != '\0'; j++) { + switch (aa->name[j]) { + case 'c': srcMode = SM_F2O; break; + case 'd': opMode = OM_UNZ; break; + case 'z': opMode = OM_Z; break; + case 'f': forceOverwrite = True; break; + case 't': opMode = OM_TEST; break; + case 'k': keepInputFiles = True; break; + case 's': smallMode = True; break; + case 'q': noisy = False; break; + case '1': blockSize100k = 1; break; + case '2': blockSize100k = 2; break; + case '3': blockSize100k = 3; break; + case '4': blockSize100k = 4; break; + case '5': blockSize100k = 5; break; + case '6': blockSize100k = 6; break; + case '7': blockSize100k = 7; break; + case '8': blockSize100k = 8; break; + case '9': blockSize100k = 9; break; + case 'V': + case 'L': license(); break; + case 'v': verbosity++; break; + case 'h': usage ( progName ); + exit ( 0 ); + break; + default: fprintf ( stderr, "%s: Bad flag `%s'\n", + progName, aa->name ); + usage ( progName ); + exit ( 1 ); + break; + } + } + } + } + + /*-- And again ... --*/ + for (aa = argList; aa != NULL; aa = aa->link) { + if (ISFLAG("--")) break; + if (ISFLAG("--stdout")) srcMode = SM_F2O; else + if (ISFLAG("--decompress")) opMode = OM_UNZ; else + if (ISFLAG("--compress")) opMode = OM_Z; else + if (ISFLAG("--force")) forceOverwrite = True; else + if (ISFLAG("--test")) opMode = OM_TEST; else + if (ISFLAG("--keep")) keepInputFiles = True; else + if (ISFLAG("--small")) smallMode = True; else + if (ISFLAG("--quiet")) noisy = False; else + if (ISFLAG("--version")) license(); else + if (ISFLAG("--license")) license(); else + if (ISFLAG("--exponential")) workFactor = 1; else + if (ISFLAG("--repetitive-best")) redundant(aa->name); else + if (ISFLAG("--repetitive-fast")) redundant(aa->name); else + if (ISFLAG("--fast")) blockSize100k = 1; else + if (ISFLAG("--best")) blockSize100k = 9; else + if (ISFLAG("--verbose")) verbosity++; else + if (ISFLAG("--help")) { usage ( progName ); exit ( 0 ); } + else + if (strncmp ( aa->name, "--", 2) == 0) { + fprintf ( stderr, "%s: Bad flag `%s'\n", progName, aa->name ); + usage ( progName ); + exit ( 1 ); + } + } + + if (verbosity > 4) verbosity = 4; + if (opMode == OM_Z && smallMode && blockSize100k > 2) + blockSize100k = 2; + + if (opMode == OM_TEST && srcMode == SM_F2O) { + fprintf ( stderr, "%s: -c and -t cannot be used together.\n", + progName ); + exit ( 1 ); + } + + if (srcMode == SM_F2O && numFileNames == 0) + srcMode = SM_I2O; + + if (opMode != OM_Z) blockSize100k = 0; + + if (srcMode == SM_F2F) { + signal (SIGINT, mySignalCatcher); + signal (SIGTERM, mySignalCatcher); +# if BZ_UNIX + signal (SIGHUP, mySignalCatcher); +# endif + } + + if (opMode == OM_Z) { + if (srcMode == SM_I2O) { + compress ( NULL ); + } else { + decode = True; + for (aa = argList; aa != NULL; aa = aa->link) { + if (ISFLAG("--")) { decode = False; continue; } + if (aa->name[0] == '-' && decode) continue; + numFilesProcessed++; + compress ( aa->name ); + } + } + } + else + + if (opMode == OM_UNZ) { + unzFailsExist = False; + if (srcMode == SM_I2O) { + uncompress ( NULL ); + } else { + decode = True; + for (aa = argList; aa != NULL; aa = aa->link) { + if (ISFLAG("--")) { decode = False; continue; } + if (aa->name[0] == '-' && decode) continue; + numFilesProcessed++; + uncompress ( aa->name ); + } + } + if (unzFailsExist) { + setExit(2); + exit(exitValue); + } + } + + else { + testFailsExist = False; + if (srcMode == SM_I2O) { + testf ( NULL ); + } else { + decode = True; + for (aa = argList; aa != NULL; aa = aa->link) { + if (ISFLAG("--")) { decode = False; continue; } + if (aa->name[0] == '-' && decode) continue; + numFilesProcessed++; + testf ( aa->name ); + } + } + if (testFailsExist && noisy) { + fprintf ( stderr, + "\n" + "You can use the `bzip2recover' program to attempt to recover\n" + "data from undamaged sections of corrupted files.\n\n" + ); + setExit(2); + exit(exitValue); + } + } + + /* Free the argument list memory to mollify leak detectors + (eg) Purify, Checker. Serves no other useful purpose. + */ + aa = argList; + while (aa != NULL) { + Cell* aa2 = aa->link; + if (aa->name != NULL) free(aa->name); + free(aa); + aa = aa2; + } + + return exitValue; +} + + +/*-----------------------------------------------------------*/ +/*--- end bzip2.c ---*/ +/*-----------------------------------------------------------*/ diff --git a/dep/bzip2/bzip2recover.c b/dep/bzip2/bzip2recover.c new file mode 100644 index 00000000000..f9de0496abf --- /dev/null +++ b/dep/bzip2/bzip2recover.c @@ -0,0 +1,514 @@ +/*-----------------------------------------------------------*/ +/*--- Block recoverer program for bzip2 ---*/ +/*--- bzip2recover.c ---*/ +/*-----------------------------------------------------------*/ + +/* ------------------------------------------------------------------ + This file is part of bzip2/libbzip2, a program and library for + lossless, block-sorting data compression. + + bzip2/libbzip2 version 1.0.6 of 6 September 2010 + Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org> + + Please read the WARNING, DISCLAIMER and PATENTS sections in the + README file. + + This program is released under the terms of the license contained + in the file LICENSE. + ------------------------------------------------------------------ */ + +/* This program is a complete hack and should be rewritten properly. + It isn't very complicated. */ + +#include <stdio.h> +#include <errno.h> +#include <stdlib.h> +#include <string.h> + + +/* This program records bit locations in the file to be recovered. + That means that if 64-bit ints are not supported, we will not + be able to recover .bz2 files over 512MB (2^32 bits) long. + On GNU supported platforms, we take advantage of the 64-bit + int support to circumvent this problem. Ditto MSVC. + + This change occurred in version 1.0.2; all prior versions have + the 512MB limitation. +*/ +#ifdef __GNUC__ + typedef unsigned long long int MaybeUInt64; +# define MaybeUInt64_FMT "%Lu" +#else +#ifdef _MSC_VER + typedef unsigned __int64 MaybeUInt64; +# define MaybeUInt64_FMT "%I64u" +#else + typedef unsigned int MaybeUInt64; +# define MaybeUInt64_FMT "%u" +#endif +#endif + +typedef unsigned int UInt32; +typedef int Int32; +typedef unsigned char UChar; +typedef char Char; +typedef unsigned char Bool; +#define True ((Bool)1) +#define False ((Bool)0) + + +#define BZ_MAX_FILENAME 2000 + +Char inFileName[BZ_MAX_FILENAME]; +Char outFileName[BZ_MAX_FILENAME]; +Char progName[BZ_MAX_FILENAME]; + +MaybeUInt64 bytesOut = 0; +MaybeUInt64 bytesIn = 0; + + +/*---------------------------------------------------*/ +/*--- Header bytes ---*/ +/*---------------------------------------------------*/ + +#define BZ_HDR_B 0x42 /* 'B' */ +#define BZ_HDR_Z 0x5a /* 'Z' */ +#define BZ_HDR_h 0x68 /* 'h' */ +#define BZ_HDR_0 0x30 /* '0' */ + + +/*---------------------------------------------------*/ +/*--- I/O errors ---*/ +/*---------------------------------------------------*/ + +/*---------------------------------------------*/ +static void readError ( void ) +{ + fprintf ( stderr, + "%s: I/O error reading `%s', possible reason follows.\n", + progName, inFileName ); + perror ( progName ); + fprintf ( stderr, "%s: warning: output file(s) may be incomplete.\n", + progName ); + exit ( 1 ); +} + + +/*---------------------------------------------*/ +static void writeError ( void ) +{ + fprintf ( stderr, + "%s: I/O error reading `%s', possible reason follows.\n", + progName, inFileName ); + perror ( progName ); + fprintf ( stderr, "%s: warning: output file(s) may be incomplete.\n", + progName ); + exit ( 1 ); +} + + +/*---------------------------------------------*/ +static void mallocFail ( Int32 n ) +{ + fprintf ( stderr, + "%s: malloc failed on request for %d bytes.\n", + progName, n ); + fprintf ( stderr, "%s: warning: output file(s) may be incomplete.\n", + progName ); + exit ( 1 ); +} + + +/*---------------------------------------------*/ +static void tooManyBlocks ( Int32 max_handled_blocks ) +{ + fprintf ( stderr, + "%s: `%s' appears to contain more than %d blocks\n", + progName, inFileName, max_handled_blocks ); + fprintf ( stderr, + "%s: and cannot be handled. To fix, increase\n", + progName ); + fprintf ( stderr, + "%s: BZ_MAX_HANDLED_BLOCKS in bzip2recover.c, and recompile.\n", + progName ); + exit ( 1 ); +} + + + +/*---------------------------------------------------*/ +/*--- Bit stream I/O ---*/ +/*---------------------------------------------------*/ + +typedef + struct { + FILE* handle; + Int32 buffer; + Int32 buffLive; + Char mode; + } + BitStream; + + +/*---------------------------------------------*/ +static BitStream* bsOpenReadStream ( FILE* stream ) +{ + BitStream *bs = malloc ( sizeof(BitStream) ); + if (bs == NULL) mallocFail ( sizeof(BitStream) ); + bs->handle = stream; + bs->buffer = 0; + bs->buffLive = 0; + bs->mode = 'r'; + return bs; +} + + +/*---------------------------------------------*/ +static BitStream* bsOpenWriteStream ( FILE* stream ) +{ + BitStream *bs = malloc ( sizeof(BitStream) ); + if (bs == NULL) mallocFail ( sizeof(BitStream) ); + bs->handle = stream; + bs->buffer = 0; + bs->buffLive = 0; + bs->mode = 'w'; + return bs; +} + + +/*---------------------------------------------*/ +static void bsPutBit ( BitStream* bs, Int32 bit ) +{ + if (bs->buffLive == 8) { + Int32 retVal = putc ( (UChar) bs->buffer, bs->handle ); + if (retVal == EOF) writeError(); + bytesOut++; + bs->buffLive = 1; + bs->buffer = bit & 0x1; + } else { + bs->buffer = ( (bs->buffer << 1) | (bit & 0x1) ); + bs->buffLive++; + }; +} + + +/*---------------------------------------------*/ +/*-- + Returns 0 or 1, or 2 to indicate EOF. +--*/ +static Int32 bsGetBit ( BitStream* bs ) +{ + if (bs->buffLive > 0) { + bs->buffLive --; + return ( ((bs->buffer) >> (bs->buffLive)) & 0x1 ); + } else { + Int32 retVal = getc ( bs->handle ); + if ( retVal == EOF ) { + if (errno != 0) readError(); + return 2; + } + bs->buffLive = 7; + bs->buffer = retVal; + return ( ((bs->buffer) >> 7) & 0x1 ); + } +} + + +/*---------------------------------------------*/ +static void bsClose ( BitStream* bs ) +{ + Int32 retVal; + + if ( bs->mode == 'w' ) { + while ( bs->buffLive < 8 ) { + bs->buffLive++; + bs->buffer <<= 1; + }; + retVal = putc ( (UChar) (bs->buffer), bs->handle ); + if (retVal == EOF) writeError(); + bytesOut++; + retVal = fflush ( bs->handle ); + if (retVal == EOF) writeError(); + } + retVal = fclose ( bs->handle ); + if (retVal == EOF) { + if (bs->mode == 'w') writeError(); else readError(); + } + free ( bs ); +} + + +/*---------------------------------------------*/ +static void bsPutUChar ( BitStream* bs, UChar c ) +{ + Int32 i; + for (i = 7; i >= 0; i--) + bsPutBit ( bs, (((UInt32) c) >> i) & 0x1 ); +} + + +/*---------------------------------------------*/ +static void bsPutUInt32 ( BitStream* bs, UInt32 c ) +{ + Int32 i; + + for (i = 31; i >= 0; i--) + bsPutBit ( bs, (c >> i) & 0x1 ); +} + + +/*---------------------------------------------*/ +static Bool endsInBz2 ( Char* name ) +{ + Int32 n = strlen ( name ); + if (n <= 4) return False; + return + (name[n-4] == '.' && + name[n-3] == 'b' && + name[n-2] == 'z' && + name[n-1] == '2'); +} + + +/*---------------------------------------------------*/ +/*--- ---*/ +/*---------------------------------------------------*/ + +/* This logic isn't really right when it comes to Cygwin. */ +#ifdef _WIN32 +# define BZ_SPLIT_SYM '\\' /* path splitter on Windows platform */ +#else +# define BZ_SPLIT_SYM '/' /* path splitter on Unix platform */ +#endif + +#define BLOCK_HEADER_HI 0x00003141UL +#define BLOCK_HEADER_LO 0x59265359UL + +#define BLOCK_ENDMARK_HI 0x00001772UL +#define BLOCK_ENDMARK_LO 0x45385090UL + +/* Increase if necessary. However, a .bz2 file with > 50000 blocks + would have an uncompressed size of at least 40GB, so the chances + are low you'll need to up this. +*/ +#define BZ_MAX_HANDLED_BLOCKS 50000 + +MaybeUInt64 bStart [BZ_MAX_HANDLED_BLOCKS]; +MaybeUInt64 bEnd [BZ_MAX_HANDLED_BLOCKS]; +MaybeUInt64 rbStart[BZ_MAX_HANDLED_BLOCKS]; +MaybeUInt64 rbEnd [BZ_MAX_HANDLED_BLOCKS]; + +Int32 main ( Int32 argc, Char** argv ) +{ + FILE* inFile; + FILE* outFile; + BitStream* bsIn, *bsWr; + Int32 b, wrBlock, currBlock, rbCtr; + MaybeUInt64 bitsRead; + + UInt32 buffHi, buffLo, blockCRC; + Char* p; + + strcpy ( progName, argv[0] ); + inFileName[0] = outFileName[0] = 0; + + fprintf ( stderr, + "bzip2recover 1.0.6: extracts blocks from damaged .bz2 files.\n" ); + + if (argc != 2) { + fprintf ( stderr, "%s: usage is `%s damaged_file_name'.\n", + progName, progName ); + switch (sizeof(MaybeUInt64)) { + case 8: + fprintf(stderr, + "\trestrictions on size of recovered file: None\n"); + break; + case 4: + fprintf(stderr, + "\trestrictions on size of recovered file: 512 MB\n"); + fprintf(stderr, + "\tto circumvent, recompile with MaybeUInt64 as an\n" + "\tunsigned 64-bit int.\n"); + break; + default: + fprintf(stderr, + "\tsizeof(MaybeUInt64) is not 4 or 8 -- " + "configuration error.\n"); + break; + } + exit(1); + } + + if (strlen(argv[1]) >= BZ_MAX_FILENAME-20) { + fprintf ( stderr, + "%s: supplied filename is suspiciously (>= %d chars) long. Bye!\n", + progName, (int)strlen(argv[1]) ); + exit(1); + } + + strcpy ( inFileName, argv[1] ); + + inFile = fopen ( inFileName, "rb" ); + if (inFile == NULL) { + fprintf ( stderr, "%s: can't read `%s'\n", progName, inFileName ); + exit(1); + } + + bsIn = bsOpenReadStream ( inFile ); + fprintf ( stderr, "%s: searching for block boundaries ...\n", progName ); + + bitsRead = 0; + buffHi = buffLo = 0; + currBlock = 0; + bStart[currBlock] = 0; + + rbCtr = 0; + + while (True) { + b = bsGetBit ( bsIn ); + bitsRead++; + if (b == 2) { + if (bitsRead >= bStart[currBlock] && + (bitsRead - bStart[currBlock]) >= 40) { + bEnd[currBlock] = bitsRead-1; + if (currBlock > 0) + fprintf ( stderr, " block %d runs from " MaybeUInt64_FMT + " to " MaybeUInt64_FMT " (incomplete)\n", + currBlock, bStart[currBlock], bEnd[currBlock] ); + } else + currBlock--; + break; + } + buffHi = (buffHi << 1) | (buffLo >> 31); + buffLo = (buffLo << 1) | (b & 1); + if ( ( (buffHi & 0x0000ffff) == BLOCK_HEADER_HI + && buffLo == BLOCK_HEADER_LO) + || + ( (buffHi & 0x0000ffff) == BLOCK_ENDMARK_HI + && buffLo == BLOCK_ENDMARK_LO) + ) { + if (bitsRead > 49) { + bEnd[currBlock] = bitsRead-49; + } else { + bEnd[currBlock] = 0; + } + if (currBlock > 0 && + (bEnd[currBlock] - bStart[currBlock]) >= 130) { + fprintf ( stderr, " block %d runs from " MaybeUInt64_FMT + " to " MaybeUInt64_FMT "\n", + rbCtr+1, bStart[currBlock], bEnd[currBlock] ); + rbStart[rbCtr] = bStart[currBlock]; + rbEnd[rbCtr] = bEnd[currBlock]; + rbCtr++; + } + if (currBlock >= BZ_MAX_HANDLED_BLOCKS) + tooManyBlocks(BZ_MAX_HANDLED_BLOCKS); + currBlock++; + + bStart[currBlock] = bitsRead; + } + } + + bsClose ( bsIn ); + + /*-- identified blocks run from 1 to rbCtr inclusive. --*/ + + if (rbCtr < 1) { + fprintf ( stderr, + "%s: sorry, I couldn't find any block boundaries.\n", + progName ); + exit(1); + }; + + fprintf ( stderr, "%s: splitting into blocks\n", progName ); + + inFile = fopen ( inFileName, "rb" ); + if (inFile == NULL) { + fprintf ( stderr, "%s: can't open `%s'\n", progName, inFileName ); + exit(1); + } + bsIn = bsOpenReadStream ( inFile ); + + /*-- placate gcc's dataflow analyser --*/ + blockCRC = 0; bsWr = 0; + + bitsRead = 0; + outFile = NULL; + wrBlock = 0; + while (True) { + b = bsGetBit(bsIn); + if (b == 2) break; + buffHi = (buffHi << 1) | (buffLo >> 31); + buffLo = (buffLo << 1) | (b & 1); + if (bitsRead == 47+rbStart[wrBlock]) + blockCRC = (buffHi << 16) | (buffLo >> 16); + + if (outFile != NULL && bitsRead >= rbStart[wrBlock] + && bitsRead <= rbEnd[wrBlock]) { + bsPutBit ( bsWr, b ); + } + + bitsRead++; + + if (bitsRead == rbEnd[wrBlock]+1) { + if (outFile != NULL) { + bsPutUChar ( bsWr, 0x17 ); bsPutUChar ( bsWr, 0x72 ); + bsPutUChar ( bsWr, 0x45 ); bsPutUChar ( bsWr, 0x38 ); + bsPutUChar ( bsWr, 0x50 ); bsPutUChar ( bsWr, 0x90 ); + bsPutUInt32 ( bsWr, blockCRC ); + bsClose ( bsWr ); + } + if (wrBlock >= rbCtr) break; + wrBlock++; + } else + if (bitsRead == rbStart[wrBlock]) { + /* Create the output file name, correctly handling leading paths. + (31.10.2001 by Sergey E. Kusikov) */ + Char* split; + Int32 ofs, k; + for (k = 0; k < BZ_MAX_FILENAME; k++) + outFileName[k] = 0; + strcpy (outFileName, inFileName); + split = strrchr (outFileName, BZ_SPLIT_SYM); + if (split == NULL) { + split = outFileName; + } else { + ++split; + } + /* Now split points to the start of the basename. */ + ofs = split - outFileName; + sprintf (split, "rec%5d", wrBlock+1); + for (p = split; *p != 0; p++) if (*p == ' ') *p = '0'; + strcat (outFileName, inFileName + ofs); + + if ( !endsInBz2(outFileName)) strcat ( outFileName, ".bz2" ); + + fprintf ( stderr, " writing block %d to `%s' ...\n", + wrBlock+1, outFileName ); + + outFile = fopen ( outFileName, "wb" ); + if (outFile == NULL) { + fprintf ( stderr, "%s: can't write `%s'\n", + progName, outFileName ); + exit(1); + } + bsWr = bsOpenWriteStream ( outFile ); + bsPutUChar ( bsWr, BZ_HDR_B ); + bsPutUChar ( bsWr, BZ_HDR_Z ); + bsPutUChar ( bsWr, BZ_HDR_h ); + bsPutUChar ( bsWr, BZ_HDR_0 + 9 ); + bsPutUChar ( bsWr, 0x31 ); bsPutUChar ( bsWr, 0x41 ); + bsPutUChar ( bsWr, 0x59 ); bsPutUChar ( bsWr, 0x26 ); + bsPutUChar ( bsWr, 0x53 ); bsPutUChar ( bsWr, 0x59 ); + } + } + + fprintf ( stderr, "%s: finished\n", progName ); + return 0; +} + + + +/*-----------------------------------------------------------*/ +/*--- end bzip2recover.c ---*/ +/*-----------------------------------------------------------*/ diff --git a/dep/bzip2/bzlib.c b/dep/bzip2/bzlib.c index ef86c91e695..bd358a793b8 100644 --- a/dep/bzip2/bzlib.c +++ b/dep/bzip2/bzlib.c @@ -8,8 +8,8 @@ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward <jseward@bzip.org> + bzip2/libbzip2 version 1.0.6 of 6 September 2010 + Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org> Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. diff --git a/dep/bzip2/bzlib.h b/dep/bzip2/bzlib.h index c5b75d6d8ff..8277123da8c 100644 --- a/dep/bzip2/bzlib.h +++ b/dep/bzip2/bzlib.h @@ -8,8 +8,8 @@ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward <jseward@bzip.org> + bzip2/libbzip2 version 1.0.6 of 6 September 2010 + Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org> Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. diff --git a/dep/bzip2/bzlib_private.h b/dep/bzip2/bzlib_private.h index 23427879b18..5d0217f4635 100644 --- a/dep/bzip2/bzlib_private.h +++ b/dep/bzip2/bzlib_private.h @@ -8,8 +8,8 @@ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward <jseward@bzip.org> + bzip2/libbzip2 version 1.0.6 of 6 September 2010 + Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org> Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. @@ -36,7 +36,7 @@ /*-- General stuff. --*/ -#define BZ_VERSION "1.0.5, 10-Dec-2007" +#define BZ_VERSION "1.0.6, 6-Sept-2010" typedef char Char; typedef unsigned char Bool; diff --git a/dep/bzip2/compress.c b/dep/bzip2/compress.c index 8c80a079700..caf7696011b 100644 --- a/dep/bzip2/compress.c +++ b/dep/bzip2/compress.c @@ -8,8 +8,8 @@ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward <jseward@bzip.org> + bzip2/libbzip2 version 1.0.6 of 6 September 2010 + Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org> Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. diff --git a/dep/bzip2/crctable.c b/dep/bzip2/crctable.c index 215687b2c05..1fea7e946c5 100644 --- a/dep/bzip2/crctable.c +++ b/dep/bzip2/crctable.c @@ -8,8 +8,8 @@ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward <jseward@bzip.org> + bzip2/libbzip2 version 1.0.6 of 6 September 2010 + Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org> Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. diff --git a/dep/bzip2/decompress.c b/dep/bzip2/decompress.c index bba5e0fa36d..311f5668f9a 100644 --- a/dep/bzip2/decompress.c +++ b/dep/bzip2/decompress.c @@ -8,8 +8,8 @@ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward <jseward@bzip.org> + bzip2/libbzip2 version 1.0.6 of 6 September 2010 + Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org> Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. @@ -381,6 +381,13 @@ Int32 BZ2_decompress ( DState* s ) es = -1; N = 1; do { + /* Check that N doesn't get too big, so that es doesn't + go negative. The maximum value that can be + RUNA/RUNB encoded is equal to the block size (post + the initial RLE), viz, 900k, so bounding N at 2 + million should guard against overflow without + rejecting any legitimate inputs. */ + if (N >= 2*1024*1024) RETURN(BZ_DATA_ERROR); if (nextSym == BZ_RUNA) es = es + (0+1) * N; else if (nextSym == BZ_RUNB) es = es + (1+1) * N; N = N * 2; @@ -485,15 +492,28 @@ Int32 BZ2_decompress ( DState* s ) RETURN(BZ_DATA_ERROR); /*-- Set up cftab to facilitate generation of T^(-1) --*/ + /* Check: unzftab entries in range. */ + for (i = 0; i <= 255; i++) { + if (s->unzftab[i] < 0 || s->unzftab[i] > nblock) + RETURN(BZ_DATA_ERROR); + } + /* Actually generate cftab. */ s->cftab[0] = 0; for (i = 1; i <= 256; i++) s->cftab[i] = s->unzftab[i-1]; for (i = 1; i <= 256; i++) s->cftab[i] += s->cftab[i-1]; + /* Check: cftab entries in range. */ for (i = 0; i <= 256; i++) { if (s->cftab[i] < 0 || s->cftab[i] > nblock) { /* s->cftab[i] can legitimately be == nblock */ RETURN(BZ_DATA_ERROR); } } + /* Check: cftab entries non-descending. */ + for (i = 1; i <= 256; i++) { + if (s->cftab[i-1] > s->cftab[i]) { + RETURN(BZ_DATA_ERROR); + } + } s->state_out_len = 0; s->state_out_ch = 0; diff --git a/dep/bzip2/huffman.c b/dep/bzip2/huffman.c index 87e79e38af0..2283fdbc5a1 100644 --- a/dep/bzip2/huffman.c +++ b/dep/bzip2/huffman.c @@ -8,8 +8,8 @@ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward <jseward@bzip.org> + bzip2/libbzip2 version 1.0.6 of 6 September 2010 + Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org> Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. diff --git a/dep/bzip2/randtable.c b/dep/bzip2/randtable.c index 068b76367bc..6d624599061 100644 --- a/dep/bzip2/randtable.c +++ b/dep/bzip2/randtable.c @@ -8,8 +8,8 @@ This file is part of bzip2/libbzip2, a program and library for lossless, block-sorting data compression. - bzip2/libbzip2 version 1.0.5 of 10 December 2007 - Copyright (C) 1996-2007 Julian Seward <jseward@bzip.org> + bzip2/libbzip2 version 1.0.6 of 6 September 2010 + Copyright (C) 1996-2010 Julian Seward <jseward@bzip.org> Please read the WARNING, DISCLAIMER and PATENTS sections in the README file. diff --git a/dep/g3dlite/include/G3D/AABox.h b/dep/g3dlite/include/G3D/AABox.h index 2e8da1f6098..d57320d73eb 100644 --- a/dep/g3dlite/include/G3D/AABox.h +++ b/dep/g3dlite/include/G3D/AABox.h @@ -20,6 +20,7 @@ #include "G3D/debug.h" #include "G3D/Array.h" #include "G3D/Plane.h" +#include "G3D/Sphere.h" namespace G3D { @@ -259,6 +260,8 @@ public: void getBounds(AABox& out) const { out = *this; } + + void getBounds(Sphere& out) const; }; } diff --git a/dep/g3dlite/include/G3D/Any.h b/dep/g3dlite/include/G3D/Any.h index c267eedd22f..e2d0fbe7e62 100644 --- a/dep/g3dlite/include/G3D/Any.h +++ b/dep/g3dlite/include/G3D/Any.h @@ -17,7 +17,9 @@ #include "G3D/platform.h" #include "G3D/Table.h" #include "G3D/Array.h" +#include "G3D/Set.h" #include "G3D/AtomicInt32.h" +#include "G3D/stringutils.h" #include <string> // needed for Token @@ -448,7 +450,6 @@ public: */ std::string resolveStringAsFilename() const; - /** If this is named ARRAY or TABLE, returns the name. */ const std::string& name() const; @@ -518,7 +519,7 @@ public: // Needed to prevent the operator[](int) overload from catching // string literals - inline const Any& operator[](const char* key) const { + const Any& operator[](const char* key) const { return operator[](std::string(key)); } @@ -548,7 +549,7 @@ public: Any& operator[](const std::string& key); /** \copydoc Any::operator[](const std::string&) */ - inline Any& operator[](const char* key) { + Any& operator[](const char* key) { return operator[](std::string(key)); } @@ -636,6 +637,124 @@ private: }; // class Any + +/** + Convenient iteration over the keys of a Any::TABLE, usually + for implementing construction of an object from an Any. + + Getting an element using either iteration or explicit requests + consumes that element from the iterator (but not from the Any!) + It is an error to consume the same element more than once from + the same iterator. + + <pre> + AnyKeyIterator r(a); + r.getIfPresent("enabled", enabled); + r.getIfPresent("showSamples", showSamples); + r.getIfPresent("showTiles", showTiles); + + r.verifyDone(); + </pre> + + \beta +*/ +class AnyTableReader { +private: + Any m_any; + Set<std::string> m_alreadyRead; +public: + + /** Verifies that \a is a TABLE with the given \a name. */ + AnyTableReader(const std::string& name, const Any& a) : m_any(a) { + try { + m_any.verifyType(Any::TABLE); + m_any.verifyName(name); + } catch (const ParseError& e) { + // If an exception is thrown, the destructors will not be + // invoked automatically. + m_any.~Any(); + m_alreadyRead.~Set(); + throw e; + } + } + + /** Verifies that \a is a TABLE. */ + AnyTableReader(const Any& a) : m_any(a) { + try { + m_any.verifyType(Any::TABLE); + } catch (const ParseError& e) { + // If an exception is thrown, the destructors will not be + // invoked automatically. + m_any.~Any(); + m_alreadyRead.~Set(); + throw e; + } + } + + bool hasMore() const { + return m_any.size() > m_alreadyRead.size(); + } + + /** Verifies that all keys have been read. */ + void verifyDone() const { + if (hasMore()) { + // Generate all keys + // Remove the ones we've read + // Assert the rest + // any.verify(""); + } + } + +#if 0 + /** Returns the current key */ + const std::string& key() const; + + /** Returns the current value */ + const Any& value() const; + + AnyKeyIterator& operator++(); +#endif + + /** If key \s appears in the any, reads its value into \a v and + removes that key from the ones available to iterate over. + + If key \s does not appear in the any, throws a G3D::ParseError. + + Assumes that if key \s appears in the any it has not already been extracted + by this iterator. If it has been read before, an assertion will fail in debug mode. + + */ + template<class ValueType> + void get(const std::string& s, ValueType& v) { + v = m_any[s]; + m_alreadyRead.insert(toLower(s)); + } + + /** Get the value associated with a key only if the key is actually present. + + If key \s appears in the any, reads its value into \a v and + removes that key from the ones available to iterate over. + + If key \s does not appear in the any, does nothing. + + Assumes that if key \s appears in the any it has not already been extracted + by this iterator. If it has been read before, an assertion will fail in debug mode. + + \return True if the value was read. + */ + template<class ValueType> + bool getIfPresent(const std::string& s, ValueType& v) { + if (m_any.containsKey(s)) { + debugAssertM(! m_alreadyRead.contains(toLower(s)), "read twice"); + + get(s, v); + return true; + } else { + return false; + } + } +}; + } // namespace G3D #endif diff --git a/dep/g3dlite/include/G3D/PointHashGrid.h b/dep/g3dlite/include/G3D/PointHashGrid.h index 5b128d1b5d9..d0b60a88ae5 100644 --- a/dep/g3dlite/include/G3D/PointHashGrid.h +++ b/dep/g3dlite/include/G3D/PointHashGrid.h @@ -360,7 +360,7 @@ public: m_arrayIndex(0), m_epoch(0) {} Iterator(const ThisType* grid) : - m_isEnd(false), + m_isEnd(grid->size() == 0), m_grid(grid), m_tableIterator( grid->m_data.begin() ), m_arrayIndex(0), @@ -387,6 +387,10 @@ public: } } + bool hasMore() const { + return ! m_isEnd; + } + bool operator==(const Iterator& other) const { return !(*this != other); } diff --git a/dep/g3dlite/include/G3D/Quat.inl b/dep/g3dlite/include/G3D/Quat.inl deleted file mode 100644 index 9e4c861d93b..00000000000 --- a/dep/g3dlite/include/G3D/Quat.inl +++ /dev/null @@ -1,36 +0,0 @@ -/** - Quat.inl - - @cite Quaternion implementation based on Watt & Watt page 363. - Thanks to Max McGuire for slerp optimizations. - - @maintainer Morgan McGuire, matrix@graphics3d.com - - @created 2002-01-23 - @edited 2004-03-04 - */ - -namespace G3D { - -inline float& Quat::operator[] (int i) { - debugAssert(i >= 0); - debugAssert(i < 4); - return ((float*)this)[i]; -} - -inline const float& Quat::operator[] (int i) const { - debugAssert(i >= 0); - debugAssert(i < 4); - return ((float*)this)[i]; -} - -inline Quat Quat::operator-(const Quat& other) const { - return Quat(x - other.x, y - other.y, z - other.z, w - other.w); -} - -inline Quat Quat::operator+(const Quat& other) const { - return Quat(x + other.x, y + other.y, z + other.z, w + other.w); -} - -} - diff --git a/dep/g3dlite/include/G3D/Sphere.h b/dep/g3dlite/include/G3D/Sphere.h index 595b61c4bf1..d1448261d9f 100644 --- a/dep/g3dlite/include/G3D/Sphere.h +++ b/dep/g3dlite/include/G3D/Sphere.h @@ -15,7 +15,6 @@ #include "G3D/platform.h" #include "G3D/Vector3.h" #include "G3D/Array.h" -#include "G3D/Sphere.h" namespace G3D { diff --git a/dep/g3dlite/include/G3D/Table.h b/dep/g3dlite/include/G3D/Table.h index 896a5a2a08a..ab0b114b1c4 100644 --- a/dep/g3dlite/include/G3D/Table.h +++ b/dep/g3dlite/include/G3D/Table.h @@ -86,12 +86,11 @@ namespace G3D { <PRE> template<> struct HashTrait<MyEnum> { - static size_t equals(const MyEnum& key) const { return reinterpret_cast<size_t>( key ); } + static size_t hashCode(const MyEnum& key) const { return reinterpret_cast<size_t>( key ); } }; </PRE> - And rely on the default enum operator==. - + and rely on the default enum operator==. Periodically check that debugGetLoad() is low (> 0.1). When it gets near 1.0 your hash function is badly designed and maps too many inputs to diff --git a/dep/g3dlite/include/G3D/Vector2.inl b/dep/g3dlite/include/G3D/Vector2.inl deleted file mode 100644 index 4f7c55a39cf..00000000000 --- a/dep/g3dlite/include/G3D/Vector2.inl +++ /dev/null @@ -1,18 +0,0 @@ -/** - @file Vector2.inl - - @maintainer Morgan McGuire, matrix@graphics3d.com - @cite Portions by Laura Wollstadt, graphics3d.com - - @cite Portions based on Dave Eberly'x Magic Software Library - at http://www.magic-software.com - - @created 2001-06-02 - @edited 2006-01-14 - - Copyright 2000-2006, Morgan McGuire. - All rights reserved. - */ - -} - diff --git a/dep/g3dlite/include/G3D/Vector3.inl b/dep/g3dlite/include/G3D/Vector3.inl deleted file mode 100644 index 9211c2a70fd..00000000000 --- a/dep/g3dlite/include/G3D/Vector3.inl +++ /dev/null @@ -1,249 +0,0 @@ -/** - @file Vector3.inl - - @maintainer Morgan McGuire, matrix@graphics3d.com - - @cite Portions based on Dave Eberly's Magic Software Library at http://www.magic-software.com - - @created 2001-06-02 - @edited 2004-05-21 - Copyright 2000-2004, Morgan McGuire. - All rights reserved. - */ - -//---------------------------------------------------------------------------- -#ifdef SSE - // If you receive an error on this line, it is because you do not have the file - // xmmintrin.h needed for MMX & SSE extensions. Download and install - // - // http://download.microsoft.com/download/vstudio60ent/SP5/Wideband-Full/WIN98Me/EN-US/vs6sp5.exe - // and - // http://download.microsoft.com/download/vb60ent/Update/6/W9X2KXP/EN-US/vcpp5.exe - // - // to get this file. -# include <xmmintrin.h> -#endif - -inline unsigned int hashCode(const G3D::Vector3& v) { - return v.hashCode(); -} - -namespace G3D { - -//---------------------------------------------------------------------------- -inline Vector3::Vector3() : x(0.0f), y(0.0f), z(0.0f) { -} - -//---------------------------------------------------------------------------- - -inline Vector3::Vector3 (float fX, float fY, float fZ) : x(fX), y(fY), z(fZ) { -} - -//---------------------------------------------------------------------------- -inline Vector3::Vector3 (float V[3]) : x(V[0]), y(V[1]), z(V[2]){ -} -//---------------------------------------------------------------------------- -inline Vector3::Vector3 (double V[3]) : x((float)V[0]), y((float)V[1]), z((float)V[2]){ -} - -//---------------------------------------------------------------------------- -inline Vector3::Vector3 (const Vector3& V) : x(V.x), y(V.y), z(V.z) { -} - -//---------------------------------------------------------------------------- - -//inline Vector3::Vector3 (const __m128& m) { - // Cast from SSE packed floats -// *this = *(Vector3*)&m; -//} - -//---------------------------------------------------------------------------- -inline const float& Vector3::operator[] (int i) const { - return ((float*)this)[i]; -} - -inline float& Vector3::operator[] (int i) { - return ((float*)this)[i]; -} - -//---------------------------------------------------------------------------- -inline Vector3& Vector3::operator= (const Vector3& rkVector) { - x = rkVector.x; - y = rkVector.y; - z = rkVector.z; - return *this; -} - -//---------------------------------------------------------------------------- - -inline bool Vector3::fuzzyEq(const Vector3& other) const { - return G3D::fuzzyEq((*this - other).squaredMagnitude(), 0); -} - -//---------------------------------------------------------------------------- - -inline bool Vector3::fuzzyNe(const Vector3& other) const { - return G3D::fuzzyNe((*this - other).squaredMagnitude(), 0); -} - -//---------------------------------------------------------------------------- - -inline bool Vector3::isFinite() const { - return G3D::isFinite(x) && G3D::isFinite(y) && G3D::isFinite(z); -} - -//---------------------------------------------------------------------------- -inline bool Vector3::operator== (const Vector3& rkVector) const { - return ( x == rkVector.x && y == rkVector.y && z == rkVector.z ); -} - -//---------------------------------------------------------------------------- -inline bool Vector3::operator!= (const Vector3& rkVector) const { - return ( x != rkVector.x || y != rkVector.y || z != rkVector.z ); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::operator+ (const Vector3& rkVector) const { - return Vector3(x + rkVector.x, y + rkVector.y, z + rkVector.z); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::operator- (const Vector3& rkVector) const { - return Vector3(x - rkVector.x, y - rkVector.y, z - rkVector.z); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::operator* (const Vector3& rkVector) const { - return Vector3(x * rkVector.x, y * rkVector.y, z * rkVector.z); -} - -inline Vector3 Vector3::operator*(float f) const { - return Vector3(x * f, y * f, z * f); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::operator/ (const Vector3& rkVector) const { - return Vector3(x / rkVector.x, y / rkVector.y, z / rkVector.z); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::operator- () const { - return Vector3(-x, -y, -z); -} - -//---------------------------------------------------------------------------- -inline Vector3& Vector3::operator+= (const Vector3& rkVector) { - x += rkVector.x; - y += rkVector.y; - z += rkVector.z; - return *this; -} - -//---------------------------------------------------------------------------- -inline Vector3& Vector3::operator-= (const Vector3& rkVector) { - x -= rkVector.x; - y -= rkVector.y; - z -= rkVector.z; - return *this; -} - -//---------------------------------------------------------------------------- -inline Vector3& Vector3::operator*= (float fScalar) { - x *= fScalar; - y *= fScalar; - z *= fScalar; - return *this; -} - -//---------------------------------------------------------------------------- -inline Vector3& Vector3::operator*= (const Vector3& rkVector) { - x *= rkVector.x; - y *= rkVector.y; - z *= rkVector.z; - return *this; -} - -//---------------------------------------------------------------------------- -inline Vector3& Vector3::operator/= (const Vector3& rkVector) { - x /= rkVector.x; - y /= rkVector.y; - z /= rkVector.z; - return *this; -} - -//---------------------------------------------------------------------------- -inline float Vector3::squaredMagnitude () const { - return x*x + y*y + z*z; -} - -//---------------------------------------------------------------------------- -inline float Vector3::squaredLength () const { - return squaredMagnitude(); -} - -//---------------------------------------------------------------------------- -inline float Vector3::magnitude() const { - return sqrtf(x*x + y*y + z*z); -} - -//---------------------------------------------------------------------------- -inline float Vector3::length() const { - return magnitude(); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::direction () const { - float lenSquared = squaredMagnitude(); - float invSqrt = 1.0f / sqrtf(lenSquared); - return Vector3(x * invSqrt, y * invSqrt, z * invSqrt); -} - -//---------------------------------------------------------------------------- - -inline Vector3 Vector3::fastDirection () const { - float lenSquared = x * x + y * y + z * z; - float invSqrt = rsq(lenSquared); - return Vector3(x * invSqrt, y * invSqrt, z * invSqrt); -} - -//---------------------------------------------------------------------------- -inline float Vector3::dot (const Vector3& rkVector) const { - return x*rkVector.x + y*rkVector.y + z*rkVector.z; -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::cross (const Vector3& rkVector) const { - return Vector3(y*rkVector.z - z*rkVector.y, z*rkVector.x - x*rkVector.z, - x*rkVector.y - y*rkVector.x); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::unitCross (const Vector3& rkVector) const { - Vector3 kCross(y*rkVector.z - z*rkVector.y, z*rkVector.x - x*rkVector.z, - x*rkVector.y - y*rkVector.x); - kCross.unitize(); - return kCross; -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::min(const Vector3 &v) const { - return Vector3(G3D::min(v.x, x), G3D::min(v.y, y), G3D::min(v.z, z)); -} - -//---------------------------------------------------------------------------- -inline Vector3 Vector3::max(const Vector3 &v) const { - return Vector3(G3D::max(v.x, x), G3D::max(v.y, y), G3D::max(v.z, z)); -} - -//---------------------------------------------------------------------------- -inline bool Vector3::isZero() const { - return G3D::fuzzyEq(squaredMagnitude(), 0.0f); -} - -//---------------------------------------------------------------------------- - -inline bool Vector3::isUnit() const { - return G3D::fuzzyEq(squaredMagnitude(), 1.0f); -} - -} // namespace diff --git a/dep/g3dlite/include/G3D/Vector4.inl b/dep/g3dlite/include/G3D/Vector4.inl deleted file mode 100644 index 576cca83b56..00000000000 --- a/dep/g3dlite/include/G3D/Vector4.inl +++ /dev/null @@ -1,191 +0,0 @@ -/** - @file Vector4.inl - - @maintainer Morgan McGuire, matrix@graphics3d.com - - @created 2002-07-09 - @edited 2003-02-10 - */ - -//---------------------------------------------------------------------------- - -inline unsigned int hashCode(const G3D::Vector4& v) { - return v.hashCode(); -} - -namespace G3D { - -//---------------------------------------------------------------------------- -inline Vector4::Vector4() { - x = y = z = w = 0; -} - -//---------------------------------------------------------------------------- - -inline Vector4::Vector4 (float fX, float fY, float fZ, float fW) { - x = fX; - y = fY; - z = fZ; - w = fW; -} - -//---------------------------------------------------------------------------- -inline Vector4::Vector4 (float afCoordinate[4]) { - x = afCoordinate[0]; - y = afCoordinate[1]; - z = afCoordinate[2]; - w = afCoordinate[3]; -} - -//---------------------------------------------------------------------------- -inline Vector4::Vector4(const Vector4& rkVector) { - x = rkVector.x; - y = rkVector.y; - z = rkVector.z; - w = rkVector.w; -} -//---------------------------------------------------------------------------- -inline Vector4::Vector4(const Vector3& rkVector, float fW) { - x = rkVector.x; - y = rkVector.y; - z = rkVector.z; - w = fW; -} - -//---------------------------------------------------------------------------- -inline float& Vector4::operator[] (int i) { - return ((float*)this)[i]; -} - -//---------------------------------------------------------------------------- -inline const float& Vector4::operator[] (int i) const { - return ((float*)this)[i]; -} - -//---------------------------------------------------------------------------- -inline Vector4::operator float* () { - return (float*)this; -} - -inline Vector4::operator const float* () const { - return (float*)this; -} - -//---------------------------------------------------------------------------- -inline Vector4& Vector4::operator= (const Vector4& rkVector) { - x = rkVector.x; - y = rkVector.y; - z = rkVector.z; - w = rkVector.w; - return *this; -} - -//---------------------------------------------------------------------------- -inline bool Vector4::operator== (const Vector4& rkVector) const { - return ( (x == rkVector.x) && (y == rkVector.y) && (z == rkVector.z) && (w == rkVector.w)); -} - -//---------------------------------------------------------------------------- -inline bool Vector4::operator!= (const Vector4& rkVector) const { - return ( x != rkVector.x || y != rkVector.y || z != rkVector.z || w != rkVector.w); -} - -//---------------------------------------------------------------------------- -inline Vector4 Vector4::operator+ (const Vector4& rkVector) const { - return Vector4(x + rkVector.x, y + rkVector.y, z + rkVector.z, w + rkVector.w); -} - -//---------------------------------------------------------------------------- -inline Vector4 Vector4::operator- (const Vector4& rkVector) const { - return Vector4(x - rkVector.x, y - rkVector.y, z - rkVector.z, w - rkVector.w); -} - -//---------------------------------------------------------------------------- -inline Vector4 Vector4::operator* (float fScalar) const { - return Vector4(fScalar*x, fScalar*y, fScalar*z, fScalar*w); -} - -//---------------------------------------------------------------------------- -inline Vector4 Vector4::operator- () const { - return Vector4( -x, -y, -z, -w); -} - -//---------------------------------------------------------------------------- -inline Vector4& Vector4::operator+= (const Vector4& rkVector) { - x += rkVector.x; - y += rkVector.y; - z += rkVector.z; - w += rkVector.w; - return *this; -} - -//---------------------------------------------------------------------------- -inline Vector4& Vector4::operator-= (const Vector4& rkVector) { - x -= rkVector.x; - y -= rkVector.y; - z -= rkVector.z; - w -= rkVector.w; - return *this; -} - -//---------------------------------------------------------------------------- - -inline Vector4 Vector4::lerp(const Vector4& v, float alpha) const { - return (*this) + (v - *this) * alpha; -} - -//---------------------------------------------------------------------------- -inline Vector4& Vector4::operator*= (float fScalar) { - x *= fScalar; - y *= fScalar; - z *= fScalar; - w *= fScalar; - return *this; -} - -//---------------------------------------------------------------------------- -inline float Vector4::dot(const Vector4& rkVector) const { - return x*rkVector.x + y*rkVector.y + z*rkVector.z + w*rkVector.w; -} - -//---------------------------------------------------------------------------- -inline Vector4 Vector4::min(const Vector4 &v) const { - return Vector4(G3D::min(v.x, x), G3D::min(v.y, y), G3D::min(v.z, z), G3D::min(v.w, w)); -} - -//---------------------------------------------------------------------------- -inline Vector4 Vector4::max(const Vector4 &v) const { - return Vector4(G3D::max(v.x, x), G3D::max(v.y, y), G3D::max(v.z, z), G3D::max(v.w, w)); -} - -//---------------------------------------------------------------------------- -inline bool Vector4::isZero() const { - return (x == 0.0f) && (y == 0.0f) && (z == 0.0f) && (w == 0.0f); -} - -//---------------------------------------------------------------------------- - -inline bool Vector4::isFinite() const { - return G3D::isFinite(x) && G3D::isFinite(y) && G3D::isFinite(z) && G3D::isFinite(w); -} - -//---------------------------------------------------------------------------- - -inline bool Vector4::isUnit() const { - return squaredLength() == 1.0; -} - -//---------------------------------------------------------------------------- - -inline float Vector4::length() const { - return sqrtf(squaredLength()); -} - -//---------------------------------------------------------------------------- - -inline float Vector4::squaredLength() const { - return x * x + y * y + z * z + w * w; -} - -} - diff --git a/dep/g3dlite/include/G3D/g3dmath.inl b/dep/g3dlite/include/G3D/g3dmath.inl deleted file mode 100644 index 9bf661a7ebc..00000000000 --- a/dep/g3dlite/include/G3D/g3dmath.inl +++ /dev/null @@ -1,288 +0,0 @@ -/** - @file g3dmath.inl - - @maintainer Morgan McGuire, matrix@graphics3d.com - - @created 2001-06-02 - @edited 2006-01-14 - */ - -#include <stdlib.h> - -#ifdef _MSC_VER -// Disable conditional expression is constant, which occurs incorrectly on inlined functions -# pragma warning (push) -# pragma warning( disable : 4127 ) -#endif - -namespace G3D { - -inline bool isNaN(double x) { - bool b1 = (x < 0.0); - bool b2 = (x >= 0.0); - bool b3 = !(b1 || b2); - return b3; -} - -inline bool isFinite(double x) { - return ! isNaN(x) && (x < G3D::inf()) && (x > -G3D::inf()); -} - -//---------------------------------------------------------------------------- -inline int iAbs (int iValue) { - return ( iValue >= 0 ? iValue : -iValue ); -} - -//---------------------------------------------------------------------------- -inline int iCeil (double fValue) { - return int(::ceil(fValue)); -} - -//---------------------------------------------------------------------------- - -inline int iClamp(int val, int low, int hi) { - debugAssert(low <= hi); - if (val <= low) { - return low; - } else if (val >= hi) { - return hi; - } else { - return val; - } -} - -//---------------------------------------------------------------------------- - -inline double clamp(double val, double low, double hi) { - debugAssert(low <= hi); - if (val <= low) { - return low; - } else if (val >= hi) { - return hi; - } else { - return val; - } -} - -inline float clamp(float val, float low, float hi) { - debugAssert(low <= hi); - if (val <= low) { - return low; - } else if (val >= hi) { - return hi; - } else { - return val; - } -} -//---------------------------------------------------------------------------- - -inline int iWrap(int val, int hi) { - if (val < 0) { - return ((val % hi) + hi) % hi; - } else { - return val % hi; - } -} - -//---------------------------------------------------------------------------- -inline int iFloor (double fValue) { - return int(::floor(fValue)); -} - -//---------------------------------------------------------------------------- -inline int iSign (int iValue) { - return ( iValue > 0 ? + 1 : ( iValue < 0 ? -1 : 0 ) ); -} - -inline int iSign (double fValue) { - return ( fValue > 0.0 ? + 1 : ( fValue < 0.0 ? -1 : 0 ) ); -} - -//---------------------------------------------------------------------------- -inline double abs (double fValue) { - return double(::fabs(fValue)); -} - -//---------------------------------------------------------------------------- -inline double aCos (double fValue) { - if ( -1.0 < fValue ) { - if ( fValue < 1.0 ) - return double(::acos(fValue)); - else - return 0.0; - } else { - return G3D_PI; - } -} - -//---------------------------------------------------------------------------- -inline double aSin (double fValue) { - if ( -1.0 < fValue ) { - if ( fValue < 1.0 ) { - return double(::asin(fValue)); - } else { - return -G3D_HALF_PI; - } - } else { - return G3D_HALF_PI; - } -} - -//---------------------------------------------------------------------------- -inline double aTan (double fValue) { - return double(::atan(fValue)); -} - -//---------------------------------------------------------------------------- -inline double aTan2 (double fY, double fX) { - return double(::atan2(fY, fX)); -} - -//---------------------------------------------------------------------------- -inline double sign (double fValue) { - if (fValue > 0.0) { - return 1.0; - } - - if (fValue < 0.0) { - return -1.0; - } - - return 0.0; -} - -inline double G3D_DEPRECATED unitRandom () { - return double(::rand()) / double(RAND_MAX); -} - -inline float uniformRandom(float low, float hi) { - return (hi - low) * float(::rand()) / float(RAND_MAX) + low; -} - -//---------------------------------------------------------------------------- -inline double G3D_DEPRECATED symmetricRandom () { - return 2.0 * double(::rand()) / double(RAND_MAX) - 1.0; -} - -//---------------------------------------------------------------------------- -inline double square(double x) { - return x * x; -} - -//---------------------------------------------------------------------------- -inline double sumSquares(double x, double y) { - return x*x + y*y; -} - -//---------------------------------------------------------------------------- -inline double sumSquares(double x, double y, double z) { - return x*x + y*y + z*z; -} - -//---------------------------------------------------------------------------- -inline double distance(double x, double y) { - return sqrt(sumSquares(x, y)); -} - -//---------------------------------------------------------------------------- -inline double distance(double x, double y, double z) { - return sqrt(sumSquares(x, y, z)); -} - -//---------------------------------------------------------------------------- - -/** @deprecated use G3D::min */ -inline int iMin(int x, int y) { - return (x >= y) ? y : x; -} - -//---------------------------------------------------------------------------- -/** @deprecated use G3D::min */ -inline int iMax(int x, int y) { - return (x >= y) ? x : y; -} - -//---------------------------------------------------------------------------- -inline int ceilPow2(unsigned int in) { - in -= 1; - - in |= in >> 16; - in |= in >> 8; - in |= in >> 4; - in |= in >> 2; - in |= in >> 1; - - return in + 1; -} - -inline bool isPow2(int num) { - return ((num & -num) == num); -} - -inline bool isOdd(int num) { - return (num & 1) == 1; -} - -inline bool isEven(int num) { - return (num & 1) == 0; -} - -inline double toRadians(double deg) { - return deg * G3D_PI / 180.0; -} - -inline double toDegrees(double rad) { - return rad * 180.0 / G3D_PI; -} - -/** - Computes an appropriate epsilon for comparing a and b. - */ -inline double eps(double a, double b) { - // For a and b to be nearly equal, they must have nearly - // the same magnitude. This means that we can ignore b - // since it either has the same magnitude or the comparison - // will fail anyway. - (void)b; - const double aa = abs(a) + 1; - if (aa == inf()) { - return fuzzyEpsilon; - } else { - return fuzzyEpsilon * aa; - } -} - -inline bool fuzzyEq(double a, double b) { - return (a == b) || (abs(a - b) <= eps(a, b)); -} - -inline bool fuzzyNe(double a, double b) { - return ! fuzzyEq(a, b); -} - -inline bool fuzzyGt(double a, double b) { - return a > b + eps(a, b); -} - -inline bool fuzzyGe(double a, double b) { - return a > b - eps(a, b); -} - -inline bool fuzzyLt(double a, double b) { - return a < b - eps(a, b); -} - -inline bool fuzzyLe(double a, double b) { - return a < b + eps(a, b); -} - -inline int iMod3(int x) { - return x % 3; -} - -} // namespace G3D - -#ifdef _MSC_VER -// Disable conditional expression is constant, which occurs incorrectly on inlined functions -# pragma warning (pop) -#endif diff --git a/dep/g3dlite/include/G3D/platform.h b/dep/g3dlite/include/G3D/platform.h index d399135101b..c8d2f0b6534 100644 --- a/dep/g3dlite/include/G3D/platform.h +++ b/dep/g3dlite/include/G3D/platform.h @@ -6,7 +6,7 @@ @maintainer Morgan McGuire, http://graphics.cs.williams.edu @created 2003-06-09 - @edited 2010-01-11 + @edited 2010-08-11 */ #ifndef G3D_platform_h @@ -16,7 +16,7 @@ The version number of G3D in the form: MmmBB -> version M.mm [beta BB] */ -#define G3D_VER 80000 +#define G3D_VER 80100 // fatal error for unsupported architectures #if defined(__powerpc__) diff --git a/dep/g3dlite/source/AABox.cpp b/dep/g3dlite/source/AABox.cpp index 035497aa3c4..8e66456c013 100644 --- a/dep/g3dlite/source/AABox.cpp +++ b/dep/g3dlite/source/AABox.cpp @@ -282,6 +282,10 @@ bool AABox::culledBy( return false; } +void AABox::getBounds(Sphere& s) const { + s.center = center(); + s.radius = extent().length() / 2; +} bool AABox::intersects(const class Sphere& sphere) const { double d = 0; diff --git a/dep/g3dlite/source/Log.cpp b/dep/g3dlite/source/Log.cpp index d44d88d0242..f437351cfbd 100644 --- a/dep/g3dlite/source/Log.cpp +++ b/dep/g3dlite/source/Log.cpp @@ -23,23 +23,23 @@ namespace G3D { void logPrintf(const char* fmt, ...) { - va_list arg_list; - va_start(arg_list, fmt); + va_list arg_list; + va_start(arg_list, fmt); Log::common()->vprintf(fmt, arg_list); va_end(arg_list); } void logLazyPrintf(const char* fmt, ...) { - va_list arg_list; - va_start(arg_list, fmt); + va_list arg_list; + va_start(arg_list, fmt); Log::common()->lazyvprintf(fmt, arg_list); va_end(arg_list); } Log* Log::commonLog = NULL; -Log::Log(const std::string& filename, int stripFromStackBottom) : +Log::Log(const std::string& filename, int stripFromStackBottom) : stripFromStackBottom(stripFromStackBottom) { this->filename = filename; @@ -50,7 +50,7 @@ Log::Log(const std::string& filename, int stripFromStackBottom) : std::string drive, base, ext; Array<std::string> path; parseFilename(filename, drive, path, base, ext); - std::string logName = base + ((ext != "") ? ("." + ext) : ""); + std::string logName = base + ((ext != "") ? ("." + ext) : ""); // Write time is greater than 1ms. This may be a network drive.... try another file. #ifdef G3D_WIN32 @@ -80,7 +80,7 @@ Log::Log(const std::string& filename, int stripFromStackBottom) : Log::~Log() { section("Shutdown"); println("Closing log file"); - + // Make sure we don't leave a dangling pointer if (Log::commonLog == this) { Log::commonLog = NULL; diff --git a/dep/g3dlite/source/RegistryUtil.cpp b/dep/g3dlite/source/RegistryUtil.cpp index fc4cebc2ee5..28ff6955d9b 100644 --- a/dep/g3dlite/source/RegistryUtil.cpp +++ b/dep/g3dlite/source/RegistryUtil.cpp @@ -257,7 +257,7 @@ bool RegistryUtil::writeString(const std::string& key, const std::string& value, // static helpers -static HKEY getRootKeyFromString(const char* str, size_t length) { +static HKEY getRootKeyFromString(const char* str, uint32 length) { debugAssert(str); if (str) { diff --git a/dep/g3dlite/source/System.cpp b/dep/g3dlite/source/System.cpp index 5170ba44941..809f05c0ab4 100644 --- a/dep/g3dlite/source/System.cpp +++ b/dep/g3dlite/source/System.cpp @@ -920,9 +920,12 @@ RealTime System::time() { //////////////////////////////////////////////////////////////// -#define REALPTR_TO_USERPTR(x) ((uint8*)(x) + sizeof (void *)) -#define USERPTR_TO_REALPTR(x) ((uint8*)(x) - sizeof (void *)) -#define REALBLOCK_SIZE(x) ((x) + sizeof (void *)) + +#define REALPTR_TO_USERPTR(x) ((uint8*)(x) + sizeof(uint32)) +#define USERPTR_TO_REALPTR(x) ((uint8*)(x) - sizeof(uint32)) +#define USERSIZE_TO_REALSIZE(x) ((x) + sizeof(uint32)) +#define REALSIZE_FROM_USERPTR(u) (*(uint32*)USERPTR_TO_REALPTR(ptr) + sizeof(uint32)) +#define USERSIZE_FROM_USERPTR(u) (*(uint32*)USERPTR_TO_REALPTR(ptr)) class BufferPool { public: @@ -947,13 +950,19 @@ public: private: + /** Pointer given to the program. Unless in the tiny heap, the user size of the block is stored right in front of the pointer as a uint32.*/ + typedef void* UserPtr; + + /** Actual block allocated on the heap */ + typedef void* RealPtr; + class MemBlock { public: - void* ptr; - size_t bytes; + UserPtr ptr; + size_t bytes; inline MemBlock() : ptr(NULL), bytes(0) {} - inline MemBlock(void* p, size_t b) : ptr(p), bytes(b) {} + inline MemBlock(UserPtr p, size_t b) : ptr(p), bytes(b) {} }; MemBlock smallPool[maxSmallBuffers]; @@ -1010,13 +1019,13 @@ private: /** Malloc out of the tiny heap. Returns NULL if allocation failed. */ - inline void* tinyMalloc(size_t bytes) { + inline UserPtr tinyMalloc(size_t bytes) { // Note that we ignore the actual byte size // and create a constant size block. (void)bytes; assert(tinyBufferSize >= bytes); - void* ptr = NULL; + UserPtr ptr = NULL; if (tinyPoolSize > 0) { --tinyPoolSize; @@ -1040,20 +1049,20 @@ private: } /** Returns true if this is a pointer into the tiny heap. */ - bool inTinyHeap(void* ptr) { + bool inTinyHeap(UserPtr ptr) { return (ptr >= tinyHeap) && (ptr < (uint8*)tinyHeap + maxTinyBuffers * tinyBufferSize); } - void tinyFree(void* ptr) { + void tinyFree(UserPtr ptr) { assert(ptr); assert(tinyPoolSize < maxTinyBuffers); // "Tried to free a tiny pool buffer when the tiny pool freelist is full."); # ifdef G3D_DEBUG if (tinyPoolSize > 0) { - void* prevOnHeap = tinyPool[tinyPoolSize - 1]; + UserPtr prevOnHeap = tinyPool[tinyPoolSize - 1]; assert(prevOnHeap != ptr); // "System::malloc heap corruption detected: " // "the last two pointers on the freelist are identical (during tinyFree)."); @@ -1070,7 +1079,8 @@ private: void flushPool(MemBlock* pool, int& poolSize) { for (int i = 0; i < poolSize; ++i) { - ::free(pool[i].ptr); + bytesAllocated -= USERSIZE_TO_REALSIZE(pool[i].bytes); + ::free(USERPTR_TO_REALPTR(pool[i].ptr)); pool[i].ptr = NULL; pool[i].bytes = 0; } @@ -1078,24 +1088,23 @@ private: } - /** Allocate out of a specific pool-> Return NULL if no suitable - memory was found. - - */ - void* malloc(MemBlock* pool, int& poolSize, size_t bytes) { + /** Allocate out of a specific pool. Return NULL if no suitable + memory was found. */ + UserPtr malloc(MemBlock* pool, int& poolSize, size_t bytes) { // OPT: find the smallest block that satisfies the request. - // See if there's something we can use in the buffer pool-> + // See if there's something we can use in the buffer pool. // Search backwards since usually we'll re-use the last one. for (int i = (int)poolSize - 1; i >= 0; --i) { if (pool[i].bytes >= bytes) { - // We found a suitable entry in the pool-> + // We found a suitable entry in the pool. // No need to offset the pointer; it is already offset - void* ptr = pool[i].ptr; + UserPtr ptr = pool[i].ptr; - // Remove this element from the pool + // Remove this element from the pool, replacing it with + // the one from the end (same as Array::fastRemove) --poolSize; pool[i] = pool[poolSize]; @@ -1159,6 +1168,8 @@ public: ~BufferPool() { ::free(tinyHeap); + flushPool(smallPool, smallPoolSize); + flushPool(medPool, medPoolSize); #if 0 //-------------------------------- old mutex # ifdef G3D_WIN32 DeleteCriticalSection(&mutex); @@ -1169,7 +1180,7 @@ public: } - void* realloc(void* ptr, size_t bytes) { + UserPtr realloc(UserPtr ptr, size_t bytes) { if (ptr == NULL) { return malloc(bytes); } @@ -1181,7 +1192,7 @@ public: } else { // Free the old pointer and malloc - void* newPtr = malloc(bytes); + UserPtr newPtr = malloc(bytes); System::memcpy(newPtr, ptr, tinyBufferSize); tinyFree(ptr); return newPtr; @@ -1191,28 +1202,28 @@ public: // In one of our heaps. // See how big the block really was - size_t realSize = *(uint32*)USERPTR_TO_REALPTR(ptr); - if (bytes <= realSize) { + size_t userSize = USERSIZE_FROM_USERPTR(ptr); + if (bytes <= userSize) { // The old block was big enough. return ptr; } - // Need to reallocate - void* newPtr = malloc(bytes); - System::memcpy(newPtr, ptr, realSize); + // Need to reallocate and move + UserPtr newPtr = malloc(bytes); + System::memcpy(newPtr, ptr, userSize); free(ptr); return newPtr; } } - void* malloc(size_t bytes) { + UserPtr malloc(size_t bytes) { lock(); ++totalMallocs; if (bytes <= tinyBufferSize) { - void* ptr = tinyMalloc(bytes); + UserPtr ptr = tinyMalloc(bytes); if (ptr) { ++mallocsFromTinyPool; @@ -1226,7 +1237,7 @@ public: // through to a small buffer if (bytes <= smallBufferSize) { - void* ptr = malloc(smallPool, smallPoolSize, bytes); + UserPtr ptr = malloc(smallPool, smallPoolSize, bytes); if (ptr) { ++mallocsFromSmallPool; @@ -1239,7 +1250,7 @@ public: // through into a medium allocation because that would // waste the medium buffer's resources. - void* ptr = malloc(medPool, medPoolSize, bytes); + UserPtr ptr = malloc(medPool, medPoolSize, bytes); if (ptr) { ++mallocsFromMedPool; @@ -1249,37 +1260,37 @@ public: } } - bytesAllocated += REALBLOCK_SIZE(bytes); + bytesAllocated += USERSIZE_TO_REALSIZE(bytes); unlock(); // Heap allocate // Allocate 4 extra bytes for our size header (unfortunate, // since malloc already added its own header). - void* ptr = ::malloc(REALBLOCK_SIZE(bytes)); + RealPtr ptr = ::malloc(USERSIZE_TO_REALSIZE(bytes)); if (ptr == NULL) { // Flush memory pools to try and recover space flushPool(smallPool, smallPoolSize); flushPool(medPool, medPoolSize); - ptr = ::malloc(REALBLOCK_SIZE(bytes)); + ptr = ::malloc(USERSIZE_TO_REALSIZE(bytes)); } if (ptr == NULL) { if ((System::outOfMemoryCallback() != NULL) && - (System::outOfMemoryCallback()(REALBLOCK_SIZE(bytes), true) == true)) { + (System::outOfMemoryCallback()(USERSIZE_TO_REALSIZE(bytes), true) == true)) { // Re-attempt the malloc - ptr = ::malloc(REALBLOCK_SIZE(bytes)); + ptr = ::malloc(USERSIZE_TO_REALSIZE(bytes)); } } if (ptr == NULL) { if (System::outOfMemoryCallback() != NULL) { // Notify the application - System::outOfMemoryCallback()(REALBLOCK_SIZE(bytes), false); + System::outOfMemoryCallback()(USERSIZE_TO_REALSIZE(bytes), false); } # ifdef G3D_DEBUG - debugPrintf("::malloc(%d) returned NULL\n", (int)REALBLOCK_SIZE(bytes)); + debugPrintf("::malloc(%d) returned NULL\n", (int)USERSIZE_TO_REALSIZE(bytes)); # endif debugAssertM(ptr != NULL, "::malloc returned NULL. Either the " @@ -1294,7 +1305,7 @@ public: } - void free(void* ptr) { + void free(UserPtr ptr) { if (ptr == NULL) { // Free does nothing on null pointers return; @@ -1309,7 +1320,7 @@ public: return; } - uint32 bytes = *(uint32*)USERPTR_TO_REALPTR(ptr); + uint32 bytes = USERSIZE_FROM_USERPTR(ptr); lock(); if (bytes <= smallBufferSize) { @@ -1327,7 +1338,7 @@ public: return; } } - bytesAllocated -= REALBLOCK_SIZE(bytes); + bytesAllocated -= USERSIZE_TO_REALSIZE(bytes); unlock(); // Free; the buffer pools are full or this is too big to store. diff --git a/dep/g3dlite/source/TextInput.cpp b/dep/g3dlite/source/TextInput.cpp index 09abacc7391..354d0de13c0 100644 --- a/dep/g3dlite/source/TextInput.cpp +++ b/dep/g3dlite/source/TextInput.cpp @@ -128,32 +128,34 @@ Token TextInput::read() { } -std::string TextInput::readUntilNewlineAsString() { - // Go to the front of the next token - Token t = read(); - // Reset the position to the start of this token +std::string TextInput::readUntilNewlineAsString() { +/* + // Reset the read position back to the start of that token currentCharOffset = t.bytePosition(); + lineNumber = t.line(); + charNumber = t.character(); stack.clear(); if (currentCharOffset == buffer.size()) { // End of file return ""; } - + */ std::string s; // Read until newline or eof char c = '\0'; do { - c = buffer[currentCharOffset]; - if (c == '\r' || c == '\n') { - // Done - break; - } else { - s += c; - ++currentCharOffset; - } + c = buffer[currentCharOffset]; + if (c == '\r' || c == '\n') { + // Done + break; + } else { + s += c; + ++currentCharOffset; + ++charNumber; + } } while (currentCharOffset < buffer.size()); return s; diff --git a/dep/g3dlite/source/g3dmath.cpp b/dep/g3dlite/source/g3dmath.cpp index e846f8c6080..84e8345bff4 100644 --- a/dep/g3dlite/source/g3dmath.cpp +++ b/dep/g3dlite/source/g3dmath.cpp @@ -41,7 +41,7 @@ double inf() { } bool isNaN(float x) { - static const float n = fnan(); + static const float n = nan(); return memcmp(&x, &n, sizeof(float)) == 0; } diff --git a/dep/gsoap/gsoap.stub b/dep/gsoap/gsoap.stub new file mode 100644 index 00000000000..be215b46655 --- /dev/null +++ b/dep/gsoap/gsoap.stub @@ -0,0 +1 @@ +int ns1__executeCommand(char* command, char** result); diff --git a/dep/gsoap/soapC.cpp b/dep/gsoap/soapC.cpp index 7fefc27f5d1..2c675cc339d 100644 --- a/dep/gsoap/soapC.cpp +++ b/dep/gsoap/soapC.cpp @@ -1,8 +1,11 @@ /* soapC.cpp - Generated by gSOAP 2.8.2 from stub.h - Copyright(C) 2000-2011, Robert van Engelen, Genivia Inc. All Rights Reserved. - The generated code is released under one of the following licenses: - GPL OR Genivia's license for commercial use. + Generated by gSOAP 2.8.10 from gsoap.stub + +Copyright(C) 2000-2012, Robert van Engelen, Genivia Inc. All Rights Reserved. +The generated code is released under one of the following licenses: +1) GPL or 2) Genivia's license for commercial use. +This program is released under the GPL with the additional exemption that +compiling, linking, and/or using OpenSSL is allowed. */ #if defined(__BORLANDC__) @@ -12,15 +15,17 @@ #include "soapH.h" -SOAP_SOURCE_STAMP("@(#) soapC.cpp ver 2.8.2 2011-04-26 21:49:07 GMT") +SOAP_SOURCE_STAMP("@(#) soapC.cpp ver 2.8.10 2012-09-02 20:48:00 GMT") #ifndef WITH_NOGLOBAL -SOAP_FMAC3 void SOAP_FMAC4 soap_serializeheader(struct soap *soap) +SOAP_FMAC3 int SOAP_FMAC4 soap_getheader(struct soap *soap) { - if (soap->header) - soap_serialize_SOAP_ENV__Header(soap, soap->header); + soap->part = SOAP_IN_HEADER; + soap->header = soap_in_SOAP_ENV__Header(soap, "SOAP-ENV:Header", soap->header, NULL); + soap->part = SOAP_END_HEADER; + return soap->header == NULL; } SOAP_FMAC3 int SOAP_FMAC4 soap_putheader(struct soap *soap) @@ -34,12 +39,10 @@ SOAP_FMAC3 int SOAP_FMAC4 soap_putheader(struct soap *soap) return SOAP_OK; } -SOAP_FMAC3 int SOAP_FMAC4 soap_getheader(struct soap *soap) +SOAP_FMAC3 void SOAP_FMAC4 soap_serializeheader(struct soap *soap) { - soap->part = SOAP_IN_HEADER; - soap->header = soap_in_SOAP_ENV__Header(soap, "SOAP-ENV:Header", NULL, NULL); - soap->part = SOAP_END_HEADER; - return soap->header == NULL; + if (soap->header) + soap_serialize_SOAP_ENV__Header(soap, soap->header); } SOAP_FMAC3 void SOAP_FMAC4 soap_header(struct soap *soap) @@ -90,7 +93,7 @@ SOAP_FMAC3 int SOAP_FMAC4 soap_getfault(struct soap *soap) SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultcode(struct soap *soap) { soap_fault(soap); - if (soap->version == 2) + if (soap->version == 2 && soap->fault->SOAP_ENV__Code) return (const char**)&soap->fault->SOAP_ENV__Code->SOAP_ENV__Value; return (const char**)&soap->fault->faultcode; } @@ -108,6 +111,17 @@ SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultsubcode(struct soap *soap) return (const char**)&soap->fault->faultcode; } +SOAP_FMAC3 const char * SOAP_FMAC4 soap_check_faultsubcode(struct soap *soap) +{ + soap_fault(soap); + if (soap->version == 2) + { if (soap->fault->SOAP_ENV__Code && soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode && soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode) + return soap->fault->SOAP_ENV__Code->SOAP_ENV__Subcode->SOAP_ENV__Value; + return NULL; + } + return soap->fault->faultcode; +} + SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultstring(struct soap *soap) { soap_fault(soap); @@ -133,6 +147,16 @@ SOAP_FMAC3 const char ** SOAP_FMAC4 soap_faultdetail(struct soap *soap) return (const char**)&soap->fault->SOAP_ENV__Detail->__any; } +SOAP_FMAC3 const char * SOAP_FMAC4 soap_check_faultdetail(struct soap *soap) +{ + soap_fault(soap); + if (soap->version == 2 && soap->fault->SOAP_ENV__Detail) + return soap->fault->SOAP_ENV__Detail->__any; + if (soap->fault->detail) + return soap->fault->detail->__any; + return NULL; +} + #endif #ifndef WITH_NOIDREF @@ -158,7 +182,7 @@ SOAP_FMAC3 int SOAP_FMAC4 soap_getindependent(struct soap *soap) extern "C" { #endif SOAP_FMAC3 void * SOAP_FMAC4 soap_getelement(struct soap *soap, int *type) -{ +{ (void)type; if (soap_peek_element(soap)) return NULL; if (!*soap->id || !(*type = soap_lookup_type(soap, soap->id))) @@ -280,7 +304,7 @@ SOAP_FMAC3 int SOAP_FMAC4 soap_putindependent(struct soap *soap) extern "C" { #endif SOAP_FMAC3 int SOAP_FMAC4 soap_putelement(struct soap *soap, const void *ptr, const char *tag, int id, int type) -{ +{ (void)tag; switch (type) { case SOAP_TYPE_byte: @@ -340,7 +364,7 @@ SOAP_FMAC3 void SOAP_FMAC4 soap_markelement(struct soap *soap, const void *ptr, #endif SOAP_FMAC3 void * SOAP_FMAC4 soap_instantiate(struct soap *soap, int t, const char *type, const char *arrayType, size_t *n) -{ +{ (void)type; switch (t) { case SOAP_TYPE_ns1__executeCommandResponse: @@ -446,7 +470,7 @@ SOAP_FMAC3 void SOAP_FMAC4 soap_default_byte(struct soap *soap, char *a) } SOAP_FMAC3 int SOAP_FMAC4 soap_out_byte(struct soap *soap, const char *tag, int id, const char *a, const char *type) -{ +{ (void)soap; (void)type; (void)tag; (void)id; return soap_outbyte(soap, tag, id, a, type, SOAP_TYPE_byte); } @@ -483,7 +507,7 @@ SOAP_FMAC3 void SOAP_FMAC4 soap_default_int(struct soap *soap, int *a) } SOAP_FMAC3 int SOAP_FMAC4 soap_out_int(struct soap *soap, const char *tag, int id, const int *a, const char *type) -{ +{ (void)soap; (void)type; (void)tag; (void)id; return soap_outint(soap, tag, id, a, type, SOAP_TYPE_int); } @@ -542,13 +566,14 @@ SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Fault(struct soap *soap, con SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Fault(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Fault *a, const char *type) { const char *soap_tmp_faultcode = soap_QName2s(soap, a->faultcode); + (void)soap; (void)tag; (void)id; (void)type; if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Fault), type)) return soap->error; if (soap_out__QName(soap, "faultcode", -1, (char*const*)&soap_tmp_faultcode, "")) return soap->error; - if (soap_out_string(soap, "faultstring", -1, &a->faultstring, "xsd:string")) + if (soap_out_string(soap, "faultstring", -1, &a->faultstring, "")) return soap->error; - if (soap_out_string(soap, "faultactor", -1, &a->faultactor, "xsd:string")) + if (soap_out_string(soap, "faultactor", -1, &a->faultactor, "")) return soap->error; if (soap_out_PointerToSOAP_ENV__Detail(soap, "detail", -1, &a->detail, "")) return soap->error; @@ -692,7 +717,7 @@ SOAP_FMAC1 struct SOAP_ENV__Fault * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Fault( SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Fault(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) { - (void)soap; (void)st; (void)len; (void)n; /* appease -Wall -Werror */ + (void)soap; (void)tt; (void)st; (void)len; (void)n; /* appease -Wall -Werror */ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct SOAP_ENV__Fault %p -> %p\n", q, p)); *(struct SOAP_ENV__Fault*)p = *(struct SOAP_ENV__Fault*)q; } @@ -715,6 +740,7 @@ SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Reason(struct soap *soap, co SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Reason(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Reason *a, const char *type) { + (void)soap; (void)tag; (void)id; (void)type; if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Reason), type)) return soap->error; if (soap->lang) @@ -803,7 +829,7 @@ SOAP_FMAC1 struct SOAP_ENV__Reason * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Reaso SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Reason(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) { - (void)soap; (void)st; (void)len; (void)n; /* appease -Wall -Werror */ + (void)soap; (void)tt; (void)st; (void)len; (void)n; /* appease -Wall -Werror */ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct SOAP_ENV__Reason %p -> %p\n", q, p)); *(struct SOAP_ENV__Reason*)p = *(struct SOAP_ENV__Reason*)q; } @@ -828,6 +854,7 @@ SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Detail(struct soap *soap, co SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Detail(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Detail *a, const char *type) { + (void)soap; (void)tag; (void)id; (void)type; if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Detail), type)) return soap->error; soap_outliteral(soap, "-any", &a->__any, NULL); @@ -921,7 +948,7 @@ SOAP_FMAC1 struct SOAP_ENV__Detail * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Detai SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Detail(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) { - (void)soap; (void)st; (void)len; (void)n; /* appease -Wall -Werror */ + (void)soap; (void)tt; (void)st; (void)len; (void)n; /* appease -Wall -Werror */ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct SOAP_ENV__Detail %p -> %p\n", q, p)); *(struct SOAP_ENV__Detail*)p = *(struct SOAP_ENV__Detail*)q; } @@ -947,6 +974,7 @@ SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Code(struct soap *soap, cons SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Code(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Code *a, const char *type) { const char *soap_tmp_SOAP_ENV__Value = soap_QName2s(soap, a->SOAP_ENV__Value); + (void)soap; (void)tag; (void)id; (void)type; if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Code), type)) return soap->error; if (soap_out__QName(soap, "SOAP-ENV:Value", -1, (char*const*)&soap_tmp_SOAP_ENV__Value, "")) @@ -1041,7 +1069,7 @@ SOAP_FMAC1 struct SOAP_ENV__Code * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Code(st SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Code(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) { - (void)soap; (void)st; (void)len; (void)n; /* appease -Wall -Werror */ + (void)soap; (void)tt; (void)st; (void)len; (void)n; /* appease -Wall -Werror */ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct SOAP_ENV__Code %p -> %p\n", q, p)); *(struct SOAP_ENV__Code*)p = *(struct SOAP_ENV__Code*)q; } @@ -1062,6 +1090,7 @@ SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_SOAP_ENV__Header(struct soap *soap, co SOAP_FMAC3 int SOAP_FMAC4 soap_out_SOAP_ENV__Header(struct soap *soap, const char *tag, int id, const struct SOAP_ENV__Header *a, const char *type) { + (void)soap; (void)tag; (void)id; (void)type; if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_SOAP_ENV__Header), type)) return soap->error; return soap_element_end_out(soap, tag); @@ -1140,7 +1169,7 @@ SOAP_FMAC1 struct SOAP_ENV__Header * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Heade SOAP_FMAC3 void SOAP_FMAC4 soap_copy_SOAP_ENV__Header(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) { - (void)soap; (void)st; (void)len; (void)n; /* appease -Wall -Werror */ + (void)soap; (void)tt; (void)st; (void)len; (void)n; /* appease -Wall -Werror */ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct SOAP_ENV__Header %p -> %p\n", q, p)); *(struct SOAP_ENV__Header*)p = *(struct SOAP_ENV__Header*)q; } @@ -1161,9 +1190,10 @@ SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_ns1__executeCommand(struct soap *soap, SOAP_FMAC3 int SOAP_FMAC4 soap_out_ns1__executeCommand(struct soap *soap, const char *tag, int id, const struct ns1__executeCommand *a, const char *type) { + (void)soap; (void)tag; (void)id; (void)type; if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_ns1__executeCommand), type)) return soap->error; - if (soap_out_string(soap, "command", -1, &a->command, "xsd:string")) + if (soap_out_string(soap, "command", -1, &a->command, "")) return soap->error; return soap_element_end_out(soap, tag); } @@ -1247,7 +1277,7 @@ SOAP_FMAC1 struct ns1__executeCommand * SOAP_FMAC2 soap_instantiate_ns1__execute SOAP_FMAC3 void SOAP_FMAC4 soap_copy_ns1__executeCommand(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) { - (void)soap; (void)st; (void)len; (void)n; /* appease -Wall -Werror */ + (void)soap; (void)tt; (void)st; (void)len; (void)n; /* appease -Wall -Werror */ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct ns1__executeCommand %p -> %p\n", q, p)); *(struct ns1__executeCommand*)p = *(struct ns1__executeCommand*)q; } @@ -1266,9 +1296,10 @@ SOAP_FMAC3 void SOAP_FMAC4 soap_serialize_ns1__executeCommandResponse(struct soa SOAP_FMAC3 int SOAP_FMAC4 soap_out_ns1__executeCommandResponse(struct soap *soap, const char *tag, int id, const struct ns1__executeCommandResponse *a, const char *type) { + (void)soap; (void)tag; (void)id; (void)type; if (soap_element_begin_out(soap, tag, soap_embedded_id(soap, id, a, SOAP_TYPE_ns1__executeCommandResponse), type)) return soap->error; - if (soap_out_PointerTostring(soap, "result", -1, &a->result, "xsd:string")) + if (soap_out_PointerTostring(soap, "result", -1, &a->result, "")) return soap->error; return soap_element_end_out(soap, tag); } @@ -1352,7 +1383,7 @@ SOAP_FMAC1 struct ns1__executeCommandResponse * SOAP_FMAC2 soap_instantiate_ns1_ SOAP_FMAC3 void SOAP_FMAC4 soap_copy_ns1__executeCommandResponse(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) { - (void)soap; (void)st; (void)len; (void)n; /* appease -Wall -Werror */ + (void)soap; (void)tt; (void)st; (void)len; (void)n; /* appease -Wall -Werror */ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying struct ns1__executeCommandResponse %p -> %p\n", q, p)); *(struct ns1__executeCommandResponse*)p = *(struct ns1__executeCommandResponse*)q; } @@ -1383,6 +1414,8 @@ SOAP_FMAC3 struct SOAP_ENV__Reason ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Reas *a = NULL; if (!soap->null && *soap->href != '#') { soap_revert(soap); + *a = (struct SOAP_ENV__Reason *)soap_malloc(soap, sizeof(struct SOAP_ENV__Reason)); + soap_default_SOAP_ENV__Reason(soap, *a); if (!(*a = soap_in_SOAP_ENV__Reason(soap, tag, *a, type))) return NULL; } @@ -1438,6 +1471,8 @@ SOAP_FMAC3 struct SOAP_ENV__Detail ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Deta *a = NULL; if (!soap->null && *soap->href != '#') { soap_revert(soap); + *a = (struct SOAP_ENV__Detail *)soap_malloc(soap, sizeof(struct SOAP_ENV__Detail)); + soap_default_SOAP_ENV__Detail(soap, *a); if (!(*a = soap_in_SOAP_ENV__Detail(soap, tag, *a, type))) return NULL; } @@ -1493,6 +1528,8 @@ SOAP_FMAC3 struct SOAP_ENV__Code ** SOAP_FMAC4 soap_in_PointerToSOAP_ENV__Code(s *a = NULL; if (!soap->null && *soap->href != '#') { soap_revert(soap); + *a = (struct SOAP_ENV__Code *)soap_malloc(soap, sizeof(struct SOAP_ENV__Code)); + soap_default_SOAP_ENV__Code(soap, *a); if (!(*a = soap_in_SOAP_ENV__Code(soap, tag, *a, type))) return NULL; } diff --git a/dep/gsoap/soapH.h b/dep/gsoap/soapH.h index e51d3defaaf..06e9ec21239 100644 --- a/dep/gsoap/soapH.h +++ b/dep/gsoap/soapH.h @@ -1,8 +1,11 @@ /* soapH.h - Generated by gSOAP 2.8.2 from stub.h - Copyright(C) 2000-2011, Robert van Engelen, Genivia Inc. All Rights Reserved. - The generated code is released under one of the following licenses: - GPL OR Genivia's license for commercial use. + Generated by gSOAP 2.8.10 from gsoap.stub + +Copyright(C) 2000-2012, Robert van Engelen, Genivia Inc. All Rights Reserved. +The generated code is released under one of the following licenses: +1) GPL or 2) Genivia's license for commercial use. +This program is released under the GPL with the additional exemption that +compiling, linking, and/or using OpenSSL is allowed. */ #ifndef soapH_H diff --git a/dep/gsoap/soapServer.cpp b/dep/gsoap/soapServer.cpp index 8c8206fb3ef..b6304a3e525 100644 --- a/dep/gsoap/soapServer.cpp +++ b/dep/gsoap/soapServer.cpp @@ -1,8 +1,11 @@ /* soapServer.cpp - Generated by gSOAP 2.8.2 from stub.h - Copyright(C) 2000-2011, Robert van Engelen, Genivia Inc. All Rights Reserved. - The generated code is released under one of the following licenses: - GPL OR Genivia's license for commercial use. + Generated by gSOAP 2.8.10 from gsoap.stub + +Copyright(C) 2000-2012, Robert van Engelen, Genivia Inc. All Rights Reserved. +The generated code is released under one of the following licenses: +1) GPL or 2) Genivia's license for commercial use. +This program is released under the GPL with the additional exemption that +compiling, linking, and/or using OpenSSL is allowed. */ #if defined(__BORLANDC__) @@ -11,7 +14,7 @@ #endif #include "soapH.h" -SOAP_SOURCE_STAMP("@(#) soapServer.cpp ver 2.8.2 2011-04-26 21:49:07 GMT") +SOAP_SOURCE_STAMP("@(#) soapServer.cpp ver 2.8.10 2012-09-02 20:48:00 GMT") SOAP_FMAC5 int SOAP_FMAC6 soap_serve(struct soap *soap) @@ -67,6 +70,7 @@ SOAP_FMAC5 int SOAP_FMAC6 soap_serve_ns1__executeCommand(struct soap *soap) soap_tmp_string = NULL; soap_tmp_ns1__executeCommandResponse.result = &soap_tmp_string; soap_default_ns1__executeCommand(soap, &soap_tmp_ns1__executeCommand); + soap->encodingStyle = NULL; if (!soap_get_ns1__executeCommand(soap, &soap_tmp_ns1__executeCommand, "ns1:executeCommand", NULL)) return soap->error; if (soap_body_end_in(soap) diff --git a/dep/gsoap/soapStub.h b/dep/gsoap/soapStub.h index 85f3119b9ff..fbdd170e0f4 100644 --- a/dep/gsoap/soapStub.h +++ b/dep/gsoap/soapStub.h @@ -1,13 +1,20 @@ /* soapStub.h - Generated by gSOAP 2.8.2 from stub.h - Copyright(C) 2000-2011, Robert van Engelen, Genivia Inc. All Rights Reserved. - The generated code is released under one of the following licenses: - GPL OR Genivia's license for commercial use. + Generated by gSOAP 2.8.10 from gsoap.stub + +Copyright(C) 2000-2012, Robert van Engelen, Genivia Inc. All Rights Reserved. +The generated code is released under one of the following licenses: +1) GPL or 2) Genivia's license for commercial use. +This program is released under the GPL with the additional exemption that +compiling, linking, and/or using OpenSSL is allowed. */ #ifndef soapStub_H #define soapStub_H #include "stdsoap2.h" +#if GSOAP_VERSION != 20810 +# error "GSOAP VERSION MISMATCH IN GENERATED CODE: PLEASE REINSTALL PACKAGE" +#endif + /******************************************************************************\ * * diff --git a/dep/gsoap/stdsoap2.cpp b/dep/gsoap/stdsoap2.cpp index ed0922d86f2..36a8901dcab 100644 --- a/dep/gsoap/stdsoap2.cpp +++ b/dep/gsoap/stdsoap2.cpp @@ -1,17 +1,17 @@ /* - stdsoap2.c[pp] 2.8.2 + stdsoap2.c[pp] 2.8.10 gSOAP runtime engine gSOAP XML Web services tools -Copyright (C) 2000-2011, Robert van Engelen, Genivia Inc., All Rights Reserved. +Copyright (C) 2000-2012, Robert van Engelen, Genivia Inc., All Rights Reserved. This part of the software is released under ONE of the following licenses: GPL, or the gSOAP public license, or Genivia's license for commercial use. -------------------------------------------------------------------------------- Contributors: Wind River Systems Inc., for the following additions under gSOAP public license: - - vxWorks compatible + - vxWorks compatible options -------------------------------------------------------------------------------- gSOAP public license. @@ -24,7 +24,7 @@ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Initial Developer of the Original Code is Robert A. van Engelen. -Copyright (C) 2000-2011, Robert van Engelen, Genivia Inc., All Rights Reserved. +Copyright (C) 2000-2012, Robert van Engelen, Genivia Inc., All Rights Reserved. -------------------------------------------------------------------------------- GPL license. @@ -49,25 +49,18 @@ compiling, linking, and/or using OpenSSL is allowed. -------------------------------------------------------------------------------- A commercial use license is available from Genivia, Inc., contact@genivia.com -------------------------------------------------------------------------------- - -Installation note: - -Win32 build needs "ws2_32.lib" -To do this in Visual C++ 6.0, go to "Project", "settings", select the "Link" -tab (the project file needs to be selected in the file view) and add -"ws2_32.lib" to the "Object/library modules" entry - -On Mac OS X with gcc (GCC) 3.1 20020420 (prerelease) you MUST compile with --fstack_check when using -O2 because gcc 3.1 has a bug that smashes the stack -when locally allocated data exceeds 64K. - */ +#define GSOAP_LIB_VERSION 20810 + #ifdef AS400 # pragma convert(819) /* EBCDIC to ASCII */ #endif #include "stdsoap2.h" +#if GSOAP_VERSION != GSOAP_LIB_VERSION +# error "GSOAP VERSION MISMATCH IN LIBRARY: PLEASE REINSTALL PACKAGE" +#endif #ifdef __BORLANDC__ # pragma warn -8060 @@ -83,10 +76,10 @@ when locally allocated data exceeds 64K. #endif #ifdef __cplusplus -SOAP_SOURCE_STAMP("@(#) stdsoap2.cpp ver 2.8.2 2011-04-17 00:00:00 GMT") +SOAP_SOURCE_STAMP("@(#) stdsoap2.cpp ver 2.8.10 2012-08-16 00:00:00 GMT") extern "C" { #else -SOAP_SOURCE_STAMP("@(#) stdsoap2.c ver 2.8.2 2011-04-17 00:00:00 GMT") +SOAP_SOURCE_STAMP("@(#) stdsoap2.c ver 2.8.10 2012-08-16 00:00:00 GMT") #endif /* 8bit character representing unknown/nonrepresentable character data (e.g. not supported by current locale with multibyte support enabled) */ @@ -101,7 +94,7 @@ SOAP_SOURCE_STAMP("@(#) stdsoap2.c ver 2.8.2 2011-04-17 00:00:00 GMT") #define SOAP_QT (soap_wchar)(-5) /* XML-specific '"' */ #define SOAP_AP (soap_wchar)(-6) /* XML-specific ''' */ -#define soap_blank(c) ((c) >= 0 && (c) <= 32) +#define soap_blank(c) ((c)+1 > 0 && (c) <= 32) #define soap_notblank(c) ((c) > 32) #if defined(WIN32) && !defined(UNDER_CE) @@ -138,8 +131,10 @@ static int soap_isxdigit(int); static void *fplugin(struct soap*, const char*); static size_t soap_count_attachments(struct soap *soap); static int soap_try_connect_command(struct soap*, int http_command, const char *endpoint, const char *action); +#ifdef WITH_NTLM +static int soap_ntlm_handshake(struct soap *soap, int command, const char *endpoint, const char *host, int port); +#endif #ifndef WITH_NOIDREF -static void soap_update_ptrs(struct soap*, char*, char*, char*, char*); static int soap_has_copies(struct soap*, const char*, const char*); static void soap_init_iht(struct soap*); static void soap_free_iht(struct soap*); @@ -152,7 +147,7 @@ static void soap_free_pht(struct soap*); static const char *soap_set_validation_fault(struct soap*, const char*, const char*); static int soap_isnumeric(struct soap*, const char*); static struct soap_nlist *soap_push_ns(struct soap *soap, const char *id, const char *ns, short utilized); -static void soap_utilize_ns(struct soap *soap, const char *tag, size_t n); +static void soap_utilize_ns(struct soap *soap, const char *tag); #endif #ifndef WITH_LEANER @@ -208,9 +203,9 @@ static const char *soap_decode(char*, size_t, const char*, const char*); #ifndef PALM_1 static soap_wchar soap_getchunkchar(struct soap*); static const char *http_error(struct soap*, int); -static int http_put(struct soap*); static int http_get(struct soap*); static int http_405(struct soap*); +static int http_200(struct soap*); static int http_post(struct soap*, const char*, const char*, int, const char*, const char*, size_t); static int http_send_header(struct soap*, const char*); static int http_post_header(struct soap*, const char*, const char*); @@ -538,6 +533,7 @@ extern int h_errno; static int fsend(struct soap *soap, const char *s, size_t n) { register int nwritten, err; + SOAP_SOCKET sk; #if defined(__cplusplus) && !defined(WITH_LEAN) && !defined(WITH_COMPAT) if (soap->os) { soap->os->write(s, (std::streamsize)n); @@ -547,23 +543,26 @@ fsend(struct soap *soap, const char *s, size_t n) return SOAP_EOF; } #endif + sk = soap->sendsk; + if (!soap_valid_socket(sk)) + sk = soap->socket; while (n) - { if (soap_valid_socket(soap->socket)) + { if (soap_valid_socket(sk)) { if (soap->send_timeout) { for (;;) { register int r; #ifdef WITH_OPENSSL if (soap->ssl) - r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_ALL, soap->send_timeout); + r = tcp_select(soap, sk, SOAP_TCP_SELECT_ALL, soap->send_timeout); else #endif #ifdef WITH_GNUTLS if (soap->session) - r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_ALL, soap->send_timeout); + r = tcp_select(soap, sk, SOAP_TCP_SELECT_ALL, soap->send_timeout); else #endif - r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, soap->send_timeout); + r = tcp_select(soap, sk, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, soap->send_timeout); if (r > 0) break; if (!r) @@ -590,25 +589,25 @@ fsend(struct soap *soap, const char *s, size_t n) #ifndef WITH_LEAN if ((soap->omode & SOAP_IO_UDP)) { if (soap->peerlen) - nwritten = sendto(soap->socket, (char*)s, (SOAP_WINSOCKINT)n, soap->socket_flags, (struct sockaddr*)&soap->peer, (SOAP_WINSOCKINT)soap->peerlen); + nwritten = sendto(sk, (char*)s, (SOAP_WINSOCKINT)n, soap->socket_flags, (struct sockaddr*)&soap->peer, (SOAP_WINSOCKINT)soap->peerlen); else - nwritten = send(soap->socket, s, (SOAP_WINSOCKINT)n, soap->socket_flags); + nwritten = send(sk, s, (SOAP_WINSOCKINT)n, soap->socket_flags); /* retry and back-off algorithm */ /* TODO: this is not very clear from specs so verify and limit conditions under which we should loop (e.g. ENOBUFS) */ if (nwritten < 0) { int udp_repeat; int udp_delay; if ((soap->connect_flags & SO_BROADCAST)) - udp_repeat = 3; /* SOAP-over-UDP MULTICAST_UDP_REPEAT - 1 */ + udp_repeat = 2; /* SOAP-over-UDP MULTICAST_UDP_REPEAT - 1 */ else udp_repeat = 1; /* SOAP-over-UDP UNICAST_UDP_REPEAT - 1 */ udp_delay = ((unsigned int)soap_random % 201) + 50; /* UDP_MIN_DELAY .. UDP_MAX_DELAY */ do - { tcp_select(soap, soap->socket, SOAP_TCP_SELECT_ERR, -1000 * udp_delay); + { tcp_select(soap, sk, SOAP_TCP_SELECT_ERR, -1000 * udp_delay); if (soap->peerlen) - nwritten = sendto(soap->socket, (char*)s, (SOAP_WINSOCKINT)n, soap->socket_flags, (struct sockaddr*)&soap->peer, (SOAP_WINSOCKINT)soap->peerlen); + nwritten = sendto(sk, (char*)s, (SOAP_WINSOCKINT)n, soap->socket_flags, (struct sockaddr*)&soap->peer, (SOAP_WINSOCKINT)soap->peerlen); else - nwritten = send(soap->socket, s, (SOAP_WINSOCKINT)n, soap->socket_flags); + nwritten = send(sk, s, (SOAP_WINSOCKINT)n, soap->socket_flags); udp_delay <<= 1; if (udp_delay > 500) /* UDP_UPPER_DELAY */ udp_delay = 500; @@ -619,14 +618,14 @@ fsend(struct soap *soap, const char *s, size_t n) else #endif #if !defined(PALM) && !defined(AS400) - nwritten = send(soap->socket, s, (int)n, soap->socket_flags); + nwritten = send(sk, s, (int)n, soap->socket_flags); #else - nwritten = send(soap->socket, (void*)s, n, soap->socket_flags); + nwritten = send(sk, (void*)s, n, soap->socket_flags); #endif if (nwritten <= 0) { register int r = 0; - err = soap_socket_errno(soap->socket); + err = soap_socket_errno(sk); #ifdef WITH_OPENSSL if (soap->ssl && (r = SSL_get_error(soap->ssl, nwritten)) != SSL_ERROR_NONE && r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE) { soap->errnum = err; @@ -645,14 +644,14 @@ fsend(struct soap *soap, const char *s, size_t n) { #if defined(WITH_OPENSSL) if (soap->ssl && r == SSL_ERROR_WANT_READ) - r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, soap->send_timeout ? soap->send_timeout : -10000); + r = tcp_select(soap, sk, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, soap->send_timeout ? soap->send_timeout : -10000); else #elif defined(WITH_GNUTLS) if (soap->session && !gnutls_record_get_direction(soap->session)) - r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, soap->send_timeout ? soap->send_timeout : -10000); + r = tcp_select(soap, sk, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, soap->send_timeout ? soap->send_timeout : -10000); else #endif - r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, soap->send_timeout ? soap->send_timeout : -10000); + r = tcp_select(soap, sk, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, soap->send_timeout ? soap->send_timeout : -10000); if (!r && soap->send_timeout) return SOAP_EOF; if (r < 0 && soap->errnum != SOAP_EINTR) @@ -775,7 +774,7 @@ soap_flush(struct soap *soap) do { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Deflating %u bytes\n", soap->d_stream->avail_in)); if (deflate(soap->d_stream, Z_NO_FLUSH) != Z_OK) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unable to deflate: %s\n", soap->d_stream->msg?soap->d_stream->msg:SOAP_STR_EOS)); + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unable to deflate: %s\n", soap->d_stream->msg ? soap->d_stream->msg : SOAP_STR_EOS)); return soap->error = SOAP_ZLIB_ERROR; } if (!soap->d_stream->avail_out) @@ -870,6 +869,7 @@ static size_t frecv(struct soap *soap, char *s, size_t n) { register int r; register int retries = 100; /* max 100 retries with non-blocking sockets */ + SOAP_SOCKET sk; soap->errnum = 0; #if defined(__cplusplus) && !defined(WITH_LEAN) && !defined(WITH_COMPAT) if (soap->is) @@ -878,7 +878,10 @@ frecv(struct soap *soap, char *s, size_t n) return 0; } #endif - if (soap_valid_socket(soap->socket)) + sk = soap->recvsk; + if (!soap_valid_socket(sk)) + sk = soap->socket; + if (soap_valid_socket(sk)) { for (;;) { #ifdef WITH_OPENSSL @@ -890,7 +893,7 @@ frecv(struct soap *soap, char *s, size_t n) if (soap->recv_timeout) #endif { for (;;) - { r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, soap->recv_timeout); + { r = tcp_select(soap, sk, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, soap->recv_timeout); if (r > 0) break; if (!r) @@ -930,7 +933,7 @@ frecv(struct soap *soap, char *s, size_t n) if ((soap->omode & SOAP_IO_UDP)) { SOAP_SOCKLEN_T k = (SOAP_SOCKLEN_T)sizeof(soap->peer); memset((void*)&soap->peer, 0, sizeof(soap->peer)); - r = recvfrom(soap->socket, s, (SOAP_WINSOCKINT)n, soap->socket_flags, (struct sockaddr*)&soap->peer, &k); /* portability note: see SOAP_SOCKLEN_T definition in stdsoap2.h */ + r = recvfrom(sk, s, (SOAP_WINSOCKINT)n, soap->socket_flags, (struct sockaddr*)&soap->peer, &k); /* portability note: see SOAP_SOCKLEN_T definition in stdsoap2.h */ soap->peerlen = (size_t)k; #ifndef WITH_IPV6 soap->ip = ntohl(soap->peer.sin_addr.s_addr); @@ -938,13 +941,13 @@ frecv(struct soap *soap, char *s, size_t n) } else #endif - r = recv(soap->socket, s, (int)n, soap->socket_flags); + r = recv(sk, s, (int)n, soap->socket_flags); #ifdef PALM /* CycleSyncDisplay(curStatusMsg); */ #endif if (r >= 0) return (size_t)r; - r = soap_socket_errno(soap->socket); + r = soap_socket_errno(sk); if (r != SOAP_EINTR && r != SOAP_EAGAIN && r != SOAP_EWOULDBLOCK) { soap->errnum = r; return 0; @@ -952,14 +955,14 @@ frecv(struct soap *soap, char *s, size_t n) } #if defined(WITH_OPENSSL) if (soap->ssl && err == SSL_ERROR_WANT_WRITE) - r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, soap->recv_timeout ? soap->recv_timeout : 5); + r = tcp_select(soap, sk, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, soap->recv_timeout ? soap->recv_timeout : 5); else #elif defined(WITH_GNUTLS) if (soap->session && gnutls_record_get_direction(soap->session)) - r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, soap->recv_timeout ? soap->recv_timeout : 5); + r = tcp_select(soap, sk, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, soap->recv_timeout ? soap->recv_timeout : 5); else #endif - r = tcp_select(soap, soap->socket, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, soap->recv_timeout ? soap->recv_timeout : 5); + r = tcp_select(soap, sk, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, soap->recv_timeout ? soap->recv_timeout : 5); if (!r && soap->recv_timeout) return 0; if (r < 0) @@ -970,7 +973,7 @@ frecv(struct soap *soap, char *s, size_t n) if (retries-- <= 0) return 0; #ifdef PALM - r = soap_socket_errno(soap->socket); + r = soap_socket_errno(sk); if (r != SOAP_EINTR && retries-- <= 0) { soap->errnum = r; return 0; @@ -1076,10 +1079,9 @@ soap_recv_raw(struct soap *soap) } } else if (r != Z_BUF_ERROR) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inflate error: %s\n", soap->d_stream->msg?soap->d_stream->msg:SOAP_STR_EOS)); + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Inflate error: %s\n", soap->d_stream->msg ? soap->d_stream->msg : SOAP_STR_EOS)); soap->d_stream->next_out = Z_NULL; - soap->error = SOAP_ZLIB_ERROR; - return EOF; + return soap->error = SOAP_ZLIB_ERROR; } } zlib_again: @@ -1110,7 +1112,9 @@ zlib_again: DBGMSG(RECV, soap->buf, ret); soap->bufidx = 0; if (!ret) - return soap->ahead = EOF; + { soap->ahead = EOF; + return EOF; + } } else soap->bufidx = soap->buflen; @@ -1118,7 +1122,9 @@ zlib_again: DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Getting chunk size (idx=%u len=%u)\n", (unsigned int)soap->bufidx, (unsigned int)soap->buflen)); while (!soap_isxdigit((int)(c = soap_getchunkchar(soap)))) { if ((int)c == EOF) - return soap->ahead = EOF; + { soap->ahead = EOF; + return EOF; + } } do *t++ = (char)c; @@ -1126,7 +1132,9 @@ zlib_again: while ((int)c != EOF && c != '\n') c = soap_getchunkchar(soap); if ((int)c == EOF) - return soap->ahead = EOF; + { soap->ahead = EOF; + return EOF; + } *t = '\0'; DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Chunk size = %s (hex)\n", tmp)); soap->chunksize = (size_t)soap_strtoul(tmp, &t, 16); @@ -1194,10 +1202,9 @@ zlib_again: #endif } else - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unable to inflate: (%d) %s\n", r, soap->d_stream->msg?soap->d_stream->msg:SOAP_STR_EOS)); + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unable to inflate: (%d) %s\n", r, soap->d_stream->msg ? soap->d_stream->msg : SOAP_STR_EOS)); soap->d_stream->next_out = Z_NULL; - soap->error = SOAP_ZLIB_ERROR; - return EOF; + return soap->error = SOAP_ZLIB_ERROR; } } #endif @@ -1283,19 +1290,22 @@ soap_recv(struct soap *soap) } } while (soap->ffilterrecv) - { int err = soap->filterstop; - if (err) + { int err, last = soap->filterstop; + if (last) soap->bufidx = soap->buflen = 0; - else - err = soap_recv_raw(soap); /* do not call again after EOF */ - if ((soap->error = soap->ffilterrecv(soap, soap->buf, &soap->buflen, sizeof(soap->buf)))) - return soap->error; + if ((err = soap->ffilterrecv(soap, soap->buf, &soap->buflen, sizeof(soap->buf)))) + return soap->error = err; if (soap->buflen) - { soap->filterstop = err; + { soap->bufidx = 0; + soap->filterstop = last; return SOAP_OK; } - if (err) - return err; + if (last) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Returning postponed error %d\n", last)); + soap->filterstop = SOAP_OK; + return last; + } + soap->filterstop = soap_recv_raw(soap); /* do not call again after EOF */ } #endif return soap_recv_raw(soap); @@ -1505,7 +1515,7 @@ soap_get(struct soap *soap) { c = soap_get0(soap); if (c == '>') { soap->cdata = 0; - soap_get1(soap); + c = soap_get1(soap); c = soap_get1(soap); } else @@ -1702,12 +1712,11 @@ SOAP_FMAC2 soap_getutf8(struct soap *soap) { register soap_wchar c, c1, c2, c3, c4; c = soap->ahead; - if (c > 0x7F) - { soap->ahead = 0; - return c; - } - c = soap_get(soap); - if (c < 0x80 || (soap->mode & SOAP_ENC_LATIN)) + if (c) + soap->ahead = 0; + else + c = soap_get(soap); + if (c < 0x80 || c > 0xFF || (soap->mode & SOAP_ENC_LATIN)) return c; c1 = soap_get1(soap); if (c1 < 0x80) @@ -1896,7 +1905,7 @@ SOAP_FMAC1 unsigned char* SOAP_FMAC2 soap_getbase64(struct soap *soap, int *n, int malloc_flag) -{ +{ (void)malloc_flag; #ifdef WITH_DOM if ((soap->mode & SOAP_XML_DOM) && soap->dom) { soap->dom->data = soap_string_in(soap, 0, -1, -1); @@ -1921,6 +1930,8 @@ soap_getbase64(struct soap *soap, int *n, int malloc_flag) register int j = 0; do { register soap_wchar c = soap_get(soap); + if (c < SOAP_AP) + c &= 0x7FFFFFFF; if (c == '=' || c < 0) { unsigned char *p; switch (j) @@ -2037,14 +2048,13 @@ SOAP_FMAC2 soap_xop_forward(struct soap *soap, unsigned char **ptr, int *size, char **id, char **type, char **options) { /* Check MTOM xop:Include element (within hex/base64Binary) */ /* TODO: this code to be obsoleted with new import/xop.h conventions */ - int body = soap->body; /* should save type too? */ + short body = soap->body; /* should save type too? */ if (!soap_peek_element(soap)) { if (!soap_element_begin_in(soap, "xop:Include", 0, NULL)) - { if (soap_dime_forward(soap, ptr, size, id, type, options)) + { if (soap_dime_forward(soap, ptr, size, id, type, options) + || (soap->body && soap_element_end_in(soap, "xop:Include"))) return soap->error; } - if (soap->body && soap_element_end_in(soap, NULL)) - return soap->error; } soap->body = body; return SOAP_OK; @@ -2176,11 +2186,14 @@ soap_pop_block(struct soap *soap, struct soap_blist *b) #endif /******************************************************************************/ -#ifndef WITH_NOIDREF #ifndef PALM_1 -static void -soap_update_ptrs(struct soap *soap, char *start, char *end, char *p1, char *p2) -{ int i; +SOAP_FMAC1 +void +SOAP_FMAC2 +soap_update_pointers(struct soap *soap, char *start, char *end, char *p1, char *p2) +{ +#ifndef WITH_NOIDREF + int i; register struct soap_ilist *ip = NULL; register struct soap_flist *fp = NULL; #ifndef WITH_LEANER @@ -2218,7 +2231,7 @@ soap_update_ptrs(struct soap *soap, char *start, char *end, char *p1, char *p2) #ifndef WITH_LEANER for (xp = soap->xlist; xp; xp = xp->next) { if (xp->ptr && (char*)xp->ptr >= start && (char*)xp->ptr < end) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Update id='%s' %p -> %p\n", xp->id?xp->id:SOAP_STR_EOS, xp->ptr, (char*)xp->ptr + (p1-p2))); + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Update id='%s' %p -> %p\n", xp->id ? xp->id : SOAP_STR_EOS, xp->ptr, (char*)xp->ptr + (p1-p2))); xp->ptr = (unsigned char**)((char*)xp->ptr + (p1-p2)); xp->size = (int*)((char*)xp->size + (p1-p2)); xp->type = (char**)((char*)xp->type + (p1-p2)); @@ -2226,8 +2239,10 @@ soap_update_ptrs(struct soap *soap, char *start, char *end, char *p1, char *p2) } } #endif -} +#else + (void)soap; (void)start; (void)end; (void)p1; (void)p2; #endif +} #endif /******************************************************************************/ @@ -2469,11 +2484,11 @@ soap_save_block(struct soap *soap, struct soap_blist *b, char *p, int flag) if (p) { for (s = p, q = soap_first_block(soap, b); q; q = soap_next_block(soap, b)) { n = soap_block_size(soap, b); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy %u bytes from %p to %p\n", (unsigned int)n, q, s)); #ifndef WITH_NOIDREF if (flag) - soap_update_ptrs(soap, q, q + n, s, q); + soap_update_pointers(soap, q, q + n, s, q); #endif - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copy %u bytes from %p to %p\n", (unsigned int)n, q, s)); memcpy(s, q, n); s += n; } @@ -2701,12 +2716,7 @@ soap_push_namespace(struct soap *soap, const char *id, const char *ns) if (p) { for (i = 0; p->id; p++, i++) { if (p->ns && !strcmp(ns, p->ns)) - { if (p->out) - { SOAP_FREE(soap, p->out); - p->out = NULL; - } break; - } if (p->out) { if (!strcmp(ns, p->out)) break; @@ -2733,10 +2743,10 @@ soap_push_namespace(struct soap *soap, const char *id, const char *ns) soap->nlist = np; np->level = soap->level; np->index = i; - strcpy(np->id, id); + strcpy((char*)np->id, id); DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Push namespace binding (level=%u) '%s' '%s'\n", soap->level, id, ns)); if (i < 0) - { np->ns = strcpy(np->id + n + 1, ns); + { np->ns = strcpy((char*)np->id + n + 1, ns); DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Push NOT OK: no match found for '%s' in namespace mapping table (added to stack anyway)\n", ns)); } else @@ -3067,6 +3077,7 @@ soap_ssl_init() #ifdef WITH_OPENSSL SSL_library_init(); OpenSSL_add_all_algorithms(); /* 2.8.1 change (wsseapi.c) */ + OpenSSL_add_all_digests(); #ifndef WITH_LEAN SSL_load_error_strings(); #endif @@ -3122,7 +3133,11 @@ soap_ssl_error(struct soap *soap, int ret) strcpy(soap->msgbuf, "EOF was observed that violates the protocol. The client probably provided invalid authentication information."); break; case -1: +#ifdef HAVE_SNPRINTF + soap_snprintf(soap->msgbuf, sizeof(soap->msgbuf), "Error observed by underlying BIO: %s", strerror(errno)); +#else sprintf(soap->msgbuf, "Error observed by underlying BIO: %s", strerror(errno)); +#endif break; } } @@ -3333,12 +3348,22 @@ ssl_verify_callback(int ok, X509_STORE_CTX *store) #ifdef SOAP_DEBUG if (!ok) { char buf[1024]; + int err = X509_STORE_CTX_get_error(store); X509 *cert = X509_STORE_CTX_get_current_cert(store); - fprintf(stderr, "SSL verify error or warning with certificate at depth %d: %s\n", X509_STORE_CTX_get_error_depth(store), X509_verify_cert_error_string(X509_STORE_CTX_get_error(store))); + fprintf(stderr, "SSL verify error or warning with certificate at depth %d: %s\n", X509_STORE_CTX_get_error_depth(store), X509_verify_cert_error_string(err)); X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf)); fprintf(stderr, "certificate issuer %s\n", buf); X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf)); fprintf(stderr, "certificate subject %s\n", buf); + /* accept self signed certificates and certificates out of date */ + switch (err) + { case X509_V_ERR_CERT_NOT_YET_VALID: + case X509_V_ERR_CERT_HAS_EXPIRED: + case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: + case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: + X509_STORE_CTX_set_error(store, X509_V_OK); + ok = 1; + } } #endif /* Note: return 1 to continue, but unsafe progress will be terminated by OpenSSL */ @@ -3353,13 +3378,16 @@ ssl_verify_callback(int ok, X509_STORE_CTX *store) static int ssl_verify_callback_allow_expired_certificate(int ok, X509_STORE_CTX *store) { ok = ssl_verify_callback(ok, store); - if (ok == 0 && X509_STORE_CTX_get_error(store) == X509_V_ERR_CERT_HAS_EXPIRED) - { -#ifdef SOAP_DEBUG - fprintf(stderr, "ignoring certificate expiration\n"); -#endif - X509_STORE_CTX_set_error(store, X509_V_OK); - ok = 1; + if (!ok) + { /* accept self signed certificates and certificates out of date */ + switch (X509_STORE_CTX_get_error(store)) + { case X509_V_ERR_CERT_NOT_YET_VALID: + case X509_V_ERR_CERT_HAS_EXPIRED: + case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: + case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: + X509_STORE_CTX_set_error(store, X509_V_OK); + ok = 1; + } } /* Note: return 1 to continue, but unsafe progress will be terminated by SSL */ return ok; @@ -3414,11 +3442,11 @@ SOAP_FMAC1 int SOAP_FMAC2 soap_ssl_accept(struct soap *soap) -{ SOAP_SOCKET fd = soap->socket; +{ SOAP_SOCKET sk = soap->socket; #ifdef WITH_OPENSSL BIO *bio; int retries, r, s; - if (!soap_valid_socket(fd)) + if (!soap_valid_socket(sk)) return soap_set_receiver_error(soap, "SSL/TLS error", "No socket in soap_ssl_accept()", SOAP_SSL_ERROR); soap->ssl_flags &= ~SOAP_SSL_CLIENT; if (!soap->ctx && (soap->error = soap->fsslauth(soap))) @@ -3430,12 +3458,12 @@ soap_ssl_accept(struct soap *soap) } else SSL_clear(soap->ssl); - bio = BIO_new_socket((int)fd, BIO_NOCLOSE); + bio = BIO_new_socket((int)sk, BIO_NOCLOSE); SSL_set_bio(soap->ssl, bio, bio); /* Set SSL sockets to non-blocking */ retries = 0; if (soap->accept_timeout) - { SOAP_SOCKNONBLOCK(fd) + { SOAP_SOCKNONBLOCK(sk) retries = 10*soap->accept_timeout; } if (retries <= 0) @@ -3447,14 +3475,14 @@ soap_ssl_accept(struct soap *soap) err = SSL_get_error(soap->ssl, r); if (err == SSL_ERROR_WANT_ACCEPT || err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) { if (err == SSL_ERROR_WANT_READ) - s = tcp_select(soap, fd, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, -100000); + s = tcp_select(soap, sk, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, -100000); else - s = tcp_select(soap, fd, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, -100000); + s = tcp_select(soap, sk, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, -100000); if (s < 0 && soap->errnum != SOAP_EINTR) break; } else - { soap->errnum = soap_socket_errno(fd); + { soap->errnum = soap_socket_errno(sk); break; } } @@ -3480,17 +3508,17 @@ soap_ssl_accept(struct soap *soap) #endif #ifdef WITH_GNUTLS int retries = 0, r; - if (!soap_valid_socket(fd)) + if (!soap_valid_socket(sk)) return soap_set_receiver_error(soap, "SSL/TLS error", "No socket in soap_ssl_accept()", SOAP_SSL_ERROR); soap->ssl_flags &= ~SOAP_SSL_CLIENT; if (!soap->session && (soap->error = soap->fsslauth(soap))) { soap_closesock(soap); return soap->error; } - gnutls_transport_set_ptr(soap->session, (gnutls_transport_ptr_t)(long)fd); + gnutls_transport_set_ptr(soap->session, (gnutls_transport_ptr_t)(long)sk); /* Set SSL sockets to non-blocking */ if (soap->accept_timeout) - { SOAP_SOCKNONBLOCK(fd) + { SOAP_SOCKNONBLOCK(sk) retries = 10*soap->accept_timeout; } if (retries <= 0) @@ -3502,14 +3530,14 @@ soap_ssl_accept(struct soap *soap) break; if (r == GNUTLS_E_AGAIN || r == GNUTLS_E_INTERRUPTED) { if (!gnutls_record_get_direction(soap->session)) - s = tcp_select(soap, fd, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, -100000); + s = tcp_select(soap, sk, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, -100000); else - s = tcp_select(soap, fd, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, -100000); + s = tcp_select(soap, sk, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, -100000); if (s < 0 && soap->errnum != SOAP_EINTR) break; } else - { soap->errnum = soap_socket_errno(fd); + { soap->errnum = soap_socket_errno(sk); break; } } @@ -3526,9 +3554,9 @@ soap_ssl_accept(struct soap *soap) } #endif if (soap->recv_timeout || soap->send_timeout) - SOAP_SOCKNONBLOCK(fd) + SOAP_SOCKNONBLOCK(sk) else - SOAP_SOCKBLOCK(fd) + SOAP_SOCKBLOCK(sk) soap->imode |= SOAP_ENC_SSL; soap->omode |= SOAP_ENC_SSL; return SOAP_OK; @@ -3672,7 +3700,7 @@ tcp_connect(struct soap *soap, const char *endpoint, const char *host, int port) #ifdef WITH_IPV6 struct addrinfo hints, *res, *ressave; #endif - SOAP_SOCKET fd; + SOAP_SOCKET sk; int err = 0; #ifndef WITH_LEAN #ifndef WIN32 @@ -3714,7 +3742,7 @@ tcp_connect(struct soap *soap, const char *endpoint, const char *host, int port) } ressave = res; again: - fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); + sk = socket(res->ai_family, res->ai_socktype, res->ai_protocol); soap->errmode = 0; #else #ifndef WITH_LEAN @@ -3722,12 +3750,12 @@ again: #endif #ifndef WITH_LEAN if ((soap->omode & SOAP_IO_UDP)) - fd = socket(AF_INET, SOCK_DGRAM, 0); + sk = socket(AF_INET, SOCK_DGRAM, 0); else #endif - fd = socket(AF_INET, SOCK_STREAM, 0); + sk = socket(AF_INET, SOCK_STREAM, 0); #endif - if (!soap_valid_socket(fd)) + if (!soap_valid_socket(sk)) { #ifdef WITH_IPV6 if (res->ai_next) @@ -3735,7 +3763,7 @@ again: goto again; } #endif - soap->errnum = soap_socket_errno(fd); + soap->errnum = soap_socket_errno(sk); soap_set_sender_error(soap, tcp_error(soap), "socket failed in tcp_connect()", SOAP_TCP_ERROR); #ifdef WITH_IPV6 freeaddrinfo(ressave); @@ -3745,10 +3773,10 @@ again: #ifdef SOCKET_CLOSE_ON_EXEC #ifdef WIN32 #ifndef UNDER_CE - SetHandleInformation((HANDLE)fd, HANDLE_FLAG_INHERIT, 0); + SetHandleInformation((HANDLE)sk, HANDLE_FLAG_INHERIT, 0); #endif #else - fcntl(fd, F_SETFD, 1); + fcntl(sk, F_SETFD, 1); #endif #endif #ifndef WITH_LEAN @@ -3757,57 +3785,57 @@ again: memset((void*)&linger, 0, sizeof(linger)); linger.l_onoff = 1; linger.l_linger = soap->linger_time; - if (setsockopt(fd, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(struct linger))) - { soap->errnum = soap_socket_errno(fd); + if (setsockopt(sk, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(struct linger))) + { soap->errnum = soap_socket_errno(sk); soap_set_sender_error(soap, tcp_error(soap), "setsockopt SO_LINGER failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); #ifdef WITH_IPV6 freeaddrinfo(ressave); #endif return SOAP_INVALID_SOCKET; } } - else if (soap->connect_flags && setsockopt(fd, SOL_SOCKET, soap->connect_flags, (char*)&set, sizeof(int))) - { soap->errnum = soap_socket_errno(fd); + else if (soap->connect_flags && setsockopt(sk, SOL_SOCKET, soap->connect_flags, (char*)&set, sizeof(int))) + { soap->errnum = soap_socket_errno(sk); soap_set_sender_error(soap, tcp_error(soap), "setsockopt failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); #ifdef WITH_IPV6 freeaddrinfo(ressave); #endif return SOAP_INVALID_SOCKET; } - if ((soap->keep_alive || soap->tcp_keep_alive) && setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (char*)&set, sizeof(int))) - { soap->errnum = soap_socket_errno(fd); + if ((soap->keep_alive || soap->tcp_keep_alive) && setsockopt(sk, SOL_SOCKET, SO_KEEPALIVE, (char*)&set, sizeof(int))) + { soap->errnum = soap_socket_errno(sk); soap_set_sender_error(soap, tcp_error(soap), "setsockopt SO_KEEPALIVE failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); #ifdef WITH_IPV6 freeaddrinfo(ressave); #endif return SOAP_INVALID_SOCKET; } - if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(int))) - { soap->errnum = soap_socket_errno(fd); + if (setsockopt(sk, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(int))) + { soap->errnum = soap_socket_errno(sk); soap_set_sender_error(soap, tcp_error(soap), "setsockopt SO_SNDBUF failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); #ifdef WITH_IPV6 freeaddrinfo(ressave); #endif return SOAP_INVALID_SOCKET; } - if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (char*)&len, sizeof(int))) - { soap->errnum = soap_socket_errno(fd); + if (setsockopt(sk, SOL_SOCKET, SO_RCVBUF, (char*)&len, sizeof(int))) + { soap->errnum = soap_socket_errno(sk); soap_set_sender_error(soap, tcp_error(soap), "setsockopt SO_RCVBUF failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); #ifdef WITH_IPV6 freeaddrinfo(ressave); #endif return SOAP_INVALID_SOCKET; } #ifdef TCP_KEEPIDLE - if (soap->tcp_keep_idle && setsockopt((SOAP_SOCKET)fd, IPPROTO_TCP, TCP_KEEPIDLE, (char*)&(soap->tcp_keep_idle), sizeof(int))) - { soap->errnum = soap_socket_errno(fd); + if (soap->tcp_keep_idle && setsockopt((SOAP_SOCKET)sk, IPPROTO_TCP, TCP_KEEPIDLE, (char*)&(soap->tcp_keep_idle), sizeof(int))) + { soap->errnum = soap_socket_errno(sk); soap_set_sender_error(soap, tcp_error(soap), "setsockopt TCP_KEEPIDLE failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, (SOAP_SOCKET)fd); + soap->fclosesocket(soap, (SOAP_SOCKET)sk); #ifdef WITH_IPV6 freeaddrinfo(ressave); #endif @@ -3815,10 +3843,10 @@ again: } #endif #ifdef TCP_KEEPINTVL - if (soap->tcp_keep_intvl && setsockopt((SOAP_SOCKET)fd, IPPROTO_TCP, TCP_KEEPINTVL, (char*)&(soap->tcp_keep_intvl), sizeof(int))) - { soap->errnum = soap_socket_errno(fd); + if (soap->tcp_keep_intvl && setsockopt((SOAP_SOCKET)sk, IPPROTO_TCP, TCP_KEEPINTVL, (char*)&(soap->tcp_keep_intvl), sizeof(int))) + { soap->errnum = soap_socket_errno(sk); soap_set_sender_error(soap, tcp_error(soap), "setsockopt TCP_KEEPINTVL failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, (SOAP_SOCKET)fd); + soap->fclosesocket(soap, (SOAP_SOCKET)sk); #ifdef WITH_IPV6 freeaddrinfo(ressave); #endif @@ -3826,10 +3854,10 @@ again: } #endif #ifdef TCP_KEEPCNT - if (soap->tcp_keep_cnt && setsockopt((SOAP_SOCKET)fd, IPPROTO_TCP, TCP_KEEPCNT, (char*)&(soap->tcp_keep_cnt), sizeof(int))) - { soap->errnum = soap_socket_errno(fd); + if (soap->tcp_keep_cnt && setsockopt((SOAP_SOCKET)sk, IPPROTO_TCP, TCP_KEEPCNT, (char*)&(soap->tcp_keep_cnt), sizeof(int))) + { soap->errnum = soap_socket_errno(sk); soap_set_sender_error(soap, tcp_error(soap), "setsockopt TCP_KEEPCNT failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, (SOAP_SOCKET)fd); + soap->fclosesocket(soap, (SOAP_SOCKET)sk); #ifdef WITH_IPV6 freeaddrinfo(ressave); #endif @@ -3837,10 +3865,10 @@ again: } #endif #ifdef TCP_NODELAY - if (!(soap->omode & SOAP_IO_UDP) && setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char*)&set, sizeof(int))) - { soap->errnum = soap_socket_errno(fd); + if (!(soap->omode & SOAP_IO_UDP) && setsockopt(sk, IPPROTO_TCP, TCP_NODELAY, (char*)&set, sizeof(int))) + { soap->errnum = soap_socket_errno(sk); soap_set_sender_error(soap, tcp_error(soap), "setsockopt TCP_NODELAY failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); #ifdef WITH_IPV6 freeaddrinfo(ressave); #endif @@ -3857,29 +3885,29 @@ again: if ((soap->omode & SOAP_IO_UDP)) { if (soap->ipv4_multicast_ttl) { unsigned char ttl = soap->ipv4_multicast_ttl; - if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_TTL, (char*)&ttl, sizeof(ttl))) - { soap->errnum = soap_socket_errno(fd); + if (setsockopt(sk, IPPROTO_IP, IP_MULTICAST_TTL, (char*)&ttl, sizeof(ttl))) + { soap->errnum = soap_socket_errno(sk); soap_set_sender_error(soap, tcp_error(soap), "setsockopt IP_MULTICAST_TTL failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); return SOAP_INVALID_SOCKET; } } if ((soap->omode & SOAP_IO_UDP) && soap->ipv4_multicast_if && !soap->ipv6_multicast_if) - { if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, (char*)soap->ipv4_multicast_if, sizeof(struct in_addr))) + { if (setsockopt(sk, IPPROTO_IP, IP_MULTICAST_IF, (char*)soap->ipv4_multicast_if, sizeof(struct in_addr))) #ifndef WINDOWS - { soap->errnum = soap_socket_errno(fd); + { soap->errnum = soap_socket_errno(sk); soap_set_sender_error(soap, tcp_error(soap), "setsockopt IP_MULTICAST_IF failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); return SOAP_INVALID_SOCKET; } #else #ifndef IP_MULTICAST_IF #define IP_MULTICAST_IF 2 #endif - if (setsockopt(fd, IPPROTO_IP, IP_MULTICAST_IF, (char*)soap->ipv4_multicast_if, sizeof(struct in_addr))) - { soap->errnum = soap_socket_errno(fd); + if (setsockopt(sk, IPPROTO_IP, IP_MULTICAST_IF, (char*)soap->ipv4_multicast_if, sizeof(struct in_addr))) + { soap->errnum = soap_socket_errno(sk); soap_set_sender_error(soap, tcp_error(soap), "setsockopt IP_MULTICAST_IF failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); return SOAP_INVALID_SOCKET; } #endif @@ -3887,7 +3915,7 @@ again: } #endif #endif - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Opening socket %d to host='%s' port=%d\n", fd, host, port)); + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Opening socket %d to host='%s' port=%d\n", sk, host, port)); #ifndef WITH_IPV6 soap->peerlen = sizeof(soap->peer); memset((void*)&soap->peer, 0, sizeof(soap->peer)); @@ -3896,7 +3924,7 @@ again: if (soap->proxy_host) { if (soap->fresolve(soap, soap->proxy_host, &soap->peer.sin_addr)) { soap_set_sender_error(soap, tcp_error(soap), "get proxy host by name failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); return SOAP_INVALID_SOCKET; } soap->peer.sin_port = htons((short)soap->proxy_port); @@ -3904,7 +3932,7 @@ again: else { if (soap->fresolve(soap, host, &soap->peer.sin_addr)) { soap_set_sender_error(soap, tcp_error(soap), "get host by name failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); return SOAP_INVALID_SOCKET; } soap->peer.sin_port = htons((short)port); @@ -3912,34 +3940,34 @@ again: soap->errmode = 0; #ifndef WITH_LEAN if ((soap->omode & SOAP_IO_UDP)) - return fd; + return sk; #endif #else if ((soap->omode & SOAP_IO_UDP)) { memcpy(&soap->peer, res->ai_addr, res->ai_addrlen); soap->peerlen = res->ai_addrlen; freeaddrinfo(ressave); - return fd; + return sk; } #endif #ifndef WITH_LEAN if (soap->connect_timeout) - SOAP_SOCKNONBLOCK(fd) + SOAP_SOCKNONBLOCK(sk) else - SOAP_SOCKBLOCK(fd) + SOAP_SOCKBLOCK(sk) retries = 10; #endif for (;;) { #ifdef WITH_IPV6 - if (connect(fd, res->ai_addr, (int)res->ai_addrlen)) + if (connect(sk, res->ai_addr, (int)res->ai_addrlen)) #else - if (connect(fd, (struct sockaddr*)&soap->peer, sizeof(soap->peer))) + if (connect(sk, (struct sockaddr*)&soap->peer, sizeof(soap->peer))) #endif - { err = soap_socket_errno(fd); + { err = soap_socket_errno(sk); #ifndef WITH_LEAN if (err == SOAP_EADDRINUSE) - { soap->fclosesocket(soap, fd); + { soap->fclosesocket(soap, sk); if (retries-- > 0) goto again; } @@ -3948,13 +3976,13 @@ again: SOAP_SOCKLEN_T k; for (;;) { register int r; - r = tcp_select(soap, fd, SOAP_TCP_SELECT_SND, soap->connect_timeout); + r = tcp_select(soap, sk, SOAP_TCP_SELECT_SND, soap->connect_timeout); if (r > 0) break; if (!r) { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Connect timeout\n")); soap_set_sender_error(soap, "Timeout", "connect failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); #ifdef WITH_IPV6 freeaddrinfo(ressave); #endif @@ -3964,7 +3992,7 @@ again: if (r != SOAP_EINTR) { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not connect to host\n")); soap_set_sender_error(soap, tcp_error(soap), "connect failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); #ifdef WITH_IPV6 freeaddrinfo(ressave); #endif @@ -3972,13 +4000,13 @@ again: } } k = (SOAP_SOCKLEN_T)sizeof(soap->errnum); - if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, (char*)&soap->errnum, &k) && !soap->errnum) /* portability note: see SOAP_SOCKLEN_T definition in stdsoap2.h */ + if (!getsockopt(sk, SOL_SOCKET, SO_ERROR, (char*)&soap->errnum, &k) && !soap->errnum) /* portability note: see SOAP_SOCKLEN_T definition in stdsoap2.h */ break; DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not connect to host\n")); if (!soap->errnum) - soap->errnum = soap_socket_errno(fd); + soap->errnum = soap_socket_errno(sk); soap_set_sender_error(soap, tcp_error(soap), "connect failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); #ifdef WITH_IPV6 freeaddrinfo(ressave); #endif @@ -3988,7 +4016,7 @@ again: #ifdef WITH_IPV6 if (res->ai_next) { res = res->ai_next; - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); goto again; } #endif @@ -3996,7 +4024,7 @@ again: { soap->errnum = err; DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not connect to host\n")); soap_set_sender_error(soap, tcp_error(soap), "connect failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); #ifdef WITH_IPV6 freeaddrinfo(ressave); #endif @@ -4010,7 +4038,7 @@ again: soap->peerlen = 0; /* IPv6: already connected so use send() */ freeaddrinfo(ressave); #endif - soap->socket = fd; + soap->socket = sk; soap->imode &= ~SOAP_ENC_SSL; soap->omode &= ~SOAP_ENC_SSL; if (!soap_tag_cmp(endpoint, "https:*")) @@ -4025,46 +4053,45 @@ again: soap_mode om = soap->omode; /* make sure we only parse HTTP */ size_t n = soap->count; /* save the content length */ const char *userid, *passwd; + int status = soap->status; /* save the current status/command */ + short keep_alive = soap->keep_alive; /* save the KA status */ soap->omode &= ~SOAP_ENC; /* mask IO and ENC */ soap->omode |= SOAP_IO_BUFFER; DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Connecting to %s proxy server\n", soap->proxy_http_version)); - sprintf(soap->tmpbuf, "CONNECT %s:%d HTTP/%s", host, port, soap->proxy_http_version); - if (soap_begin_send(soap) - || (soap->error = soap->fposthdr(soap, soap->tmpbuf, NULL))) - { soap->fclosesocket(soap, fd); - return SOAP_INVALID_SOCKET; - } -#ifndef WITH_LEAN - if (soap->proxy_userid && soap->proxy_passwd && strlen(soap->proxy_userid) + strlen(soap->proxy_passwd) < 761) - { sprintf(soap->tmpbuf + 262, "%s:%s", soap->proxy_userid, soap->proxy_passwd); - strcpy(soap->tmpbuf, "Basic "); - soap_s2base64(soap, (const unsigned char*)(soap->tmpbuf + 262), soap->tmpbuf + 6, (int)strlen(soap->tmpbuf + 262)); - if ((soap->error = soap->fposthdr(soap, "Proxy-Authorization", soap->tmpbuf))) - { soap->fclosesocket(soap, fd); +#ifdef WITH_NTLM + if (soap->ntlm_challenge) + { if (soap_ntlm_handshake(soap, SOAP_CONNECT, endpoint, host, port)) return soap->error; - } } #endif - if ((soap->error = soap->fposthdr(soap, NULL, NULL)) - || soap_flush(soap)) - { soap->fclosesocket(soap, fd); + if (soap_begin_send(soap)) + { soap->fclosesocket(soap, sk); + return SOAP_INVALID_SOCKET; + } + soap->status = SOAP_CONNECT; + soap->keep_alive = 1; + if ((soap->error = soap->fpost(soap, endpoint, host, port, NULL, NULL, 0)) + || soap_end_send(soap)) + { soap->fclosesocket(soap, sk); return SOAP_INVALID_SOCKET; } + soap->keep_alive = keep_alive; soap->omode = om; om = soap->imode; soap->imode &= ~SOAP_ENC; /* mask IO and ENC */ userid = soap->userid; /* preserve */ passwd = soap->passwd; /* preserve */ if ((soap->error = soap->fparse(soap))) - { soap->fclosesocket(soap, fd); + { soap->fclosesocket(soap, sk); return SOAP_INVALID_SOCKET; } + soap->status = status; /* restore */ soap->userid = userid; /* restore */ soap->passwd = passwd; /* restore */ soap->imode = om; /* restore */ soap->count = n; /* restore */ if (soap_begin_send(soap)) - { soap->fclosesocket(soap, fd); + { soap->fclosesocket(soap, sk); return SOAP_INVALID_SOCKET; } if (endpoint) @@ -4074,13 +4101,15 @@ again: #ifdef WITH_OPENSSL soap->ssl_flags |= SOAP_SSL_CLIENT; if (!soap->ctx && (soap->error = soap->fsslauth(soap))) - { soap->fclosesocket(soap, fd); + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "SSL required, but no ctx set\n")); + soap->fclosesocket(soap, sk); + soap->error = SOAP_SSL_ERROR; return SOAP_INVALID_SOCKET; } if (!soap->ssl) { soap->ssl = SSL_new(soap->ctx); if (!soap->ssl) - { soap->fclosesocket(soap, fd); + { soap->fclosesocket(soap, sk); soap->error = SOAP_SSL_ERROR; return SOAP_INVALID_SOCKET; } @@ -4095,16 +4124,16 @@ again: } soap->imode |= SOAP_ENC_SSL; soap->omode |= SOAP_ENC_SSL; - bio = BIO_new_socket((int)fd, BIO_NOCLOSE); + bio = BIO_new_socket((int)sk, BIO_NOCLOSE); SSL_set_bio(soap->ssl, bio, bio); /* Connect timeout: set SSL sockets to non-blocking */ retries = 0; if (soap->connect_timeout) - { SOAP_SOCKNONBLOCK(fd) + { SOAP_SOCKNONBLOCK(sk) retries = 10*soap->connect_timeout; } else - SOAP_SOCKBLOCK(fd) + SOAP_SOCKBLOCK(sk) if (retries <= 0) retries = 100; /* timeout: 10 sec retries, 100 times 0.1 sec */ /* Try connecting until success or timeout (when nonblocking) */ @@ -4114,37 +4143,37 @@ again: if (err == SSL_ERROR_WANT_CONNECT || err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) { register int s; if (err == SSL_ERROR_WANT_READ) - s = tcp_select(soap, fd, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, -100000); + s = tcp_select(soap, sk, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, -100000); else - s = tcp_select(soap, fd, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, -100000); + s = tcp_select(soap, sk, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, -100000); if (s < 0 && soap->errnum != SOAP_EINTR) { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "SSL_connect/select error in tcp_connect\n")); soap_set_sender_error(soap, soap_ssl_error(soap, r), "SSL_connect failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); return SOAP_INVALID_SOCKET; } if (s == 0 && retries-- <= 0) { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "SSL/TLS connect timeout\n")); soap_set_sender_error(soap, "Timeout", "SSL_connect failed in tcp_connect()", SOAP_TCP_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); return SOAP_INVALID_SOCKET; } } else { soap_set_sender_error(soap, soap_ssl_error(soap, r), "SSL_connect error in tcp_connect()", SOAP_SSL_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); return SOAP_INVALID_SOCKET; } } } while (!SSL_is_init_finished(soap->ssl)); /* Set SSL sockets to nonblocking */ - SOAP_SOCKNONBLOCK(fd) + SOAP_SOCKNONBLOCK(sk) /* Check server credentials when required */ if ((soap->ssl_flags & SOAP_SSL_REQUIRE_SERVER_AUTHENTICATION)) { int err; if ((err = SSL_get_verify_result(soap->ssl)) != X509_V_OK) { soap_set_sender_error(soap, X509_verify_cert_error_string(err), "SSL/TLS certificate presented by peer cannot be verified in tcp_connect()", SOAP_SSL_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); return SOAP_INVALID_SOCKET; } if (!(soap->ssl_flags & SOAP_SSL_SKIP_HOST_CHECK)) @@ -4155,7 +4184,7 @@ again: peer = SSL_get_peer_certificate(soap->ssl); if (!peer) { soap_set_sender_error(soap, "SSL/TLS error", "No SSL/TLS certificate was presented by the peer in tcp_connect()", SOAP_SSL_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); return SOAP_INVALID_SOCKET; } ext_count = X509_get_ext_count(peer); @@ -4249,7 +4278,7 @@ again: X509_free(peer); if (!ok) { soap_set_sender_error(soap, "SSL/TLS error", "SSL/TLS certificate host name mismatch in tcp_connect()", SOAP_SSL_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); return SOAP_INVALID_SOCKET; } } @@ -4258,17 +4287,17 @@ again: #ifdef WITH_GNUTLS soap->ssl_flags |= SOAP_SSL_CLIENT; if (!soap->session && (soap->error = soap->fsslauth(soap))) - { soap->fclosesocket(soap, fd); + { soap->fclosesocket(soap, sk); return SOAP_INVALID_SOCKET; } - gnutls_transport_set_ptr(soap->session, (gnutls_transport_ptr_t)(long)fd); + gnutls_transport_set_ptr(soap->session, (gnutls_transport_ptr_t)(long)sk); /* Set SSL sockets to non-blocking */ if (soap->connect_timeout) - { SOAP_SOCKNONBLOCK(fd) + { SOAP_SOCKNONBLOCK(sk) retries = 10*soap->connect_timeout; } else - SOAP_SOCKBLOCK(fd) + SOAP_SOCKBLOCK(sk) if (retries <= 0) retries = 100; /* timeout: 10 sec retries, 100 times 0.1 sec */ while ((r = gnutls_handshake(soap->session))) @@ -4278,42 +4307,42 @@ again: break; if (r == GNUTLS_E_AGAIN || r == GNUTLS_E_INTERRUPTED) { if (!gnutls_record_get_direction(soap->session)) - s = tcp_select(soap, fd, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, -100000); + s = tcp_select(soap, sk, SOAP_TCP_SELECT_RCV | SOAP_TCP_SELECT_ERR, -100000); else - s = tcp_select(soap, fd, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, -100000); + s = tcp_select(soap, sk, SOAP_TCP_SELECT_SND | SOAP_TCP_SELECT_ERR, -100000); if (s < 0 && soap->errnum != SOAP_EINTR) break; } else - { soap->errnum = soap_socket_errno(fd); + { soap->errnum = soap_socket_errno(sk); break; } } if (r) { soap_set_sender_error(soap, soap_ssl_error(soap, r), "SSL/TLS handshake failed", SOAP_SSL_ERROR); - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); return SOAP_INVALID_SOCKET; } if ((soap->ssl_flags & SOAP_SSL_REQUIRE_SERVER_AUTHENTICATION)) { const char *err = ssl_verify(soap, host); if (err) - { soap->fclosesocket(soap, fd); + { soap->fclosesocket(soap, sk); soap->error = soap_set_sender_error(soap, "SSL/TLS error", err, SOAP_SSL_ERROR); return SOAP_INVALID_SOCKET; } } #endif #else - soap->fclosesocket(soap, fd); + soap->fclosesocket(soap, sk); soap->error = SOAP_SSL_ERROR; return SOAP_INVALID_SOCKET; #endif } if (soap->recv_timeout || soap->send_timeout) - SOAP_SOCKNONBLOCK(fd) + SOAP_SOCKNONBLOCK(sk) else - SOAP_SOCKBLOCK(fd) - return fd; + SOAP_SOCKBLOCK(sk) + return sk; } #endif #endif @@ -4322,7 +4351,7 @@ again: #ifndef WITH_NOIO #ifndef PALM_1 static int -tcp_select(struct soap *soap, SOAP_SOCKET s, int flags, int timeout) +tcp_select(struct soap *soap, SOAP_SOCKET sk, int flags, int timeout) { register int r; struct timeval tv; fd_set fd[3], *rfd, *sfd, *efd; @@ -4333,12 +4362,12 @@ tcp_select(struct soap *soap, SOAP_SOCKET s, int flags, int timeout) if (1) #else /* if fd max set size exceeded, use poll() */ - if ((int)s >= (int)FD_SETSIZE) + if ((int)sk >= (int)FD_SETSIZE) #endif #ifdef HAVE_POLL { struct pollfd pollfd; int retries = 0; - pollfd.fd = (int)s; + pollfd.fd = (int)sk; pollfd.events = 0; if (flags & SOAP_TCP_SELECT_RCV) pollfd.events |= POLLIN; @@ -4379,17 +4408,17 @@ tcp_select(struct soap *soap, SOAP_SOCKET s, int flags, int timeout) if (flags & SOAP_TCP_SELECT_RCV) { rfd = &fd[0]; FD_ZERO(rfd); - FD_SET(s, rfd); + FD_SET(sk, rfd); } if (flags & SOAP_TCP_SELECT_SND) { sfd = &fd[1]; FD_ZERO(sfd); - FD_SET(s, sfd); + FD_SET(sk, sfd); } if (flags & SOAP_TCP_SELECT_ERR) { efd = &fd[2]; FD_ZERO(efd); - FD_SET(s, efd); + FD_SET(sk, efd); } if (timeout >= 0) { tv.tv_sec = timeout; @@ -4399,14 +4428,14 @@ tcp_select(struct soap *soap, SOAP_SOCKET s, int flags, int timeout) { tv.tv_sec = -timeout / 1000000; tv.tv_usec = -timeout % 1000000; } - r = select((int)s + 1, rfd, sfd, efd, &tv); + r = select((int)sk + 1, rfd, sfd, efd, &tv); if (r > 0) { r = 0; - if ((flags & SOAP_TCP_SELECT_RCV) && FD_ISSET(s, rfd)) + if ((flags & SOAP_TCP_SELECT_RCV) && FD_ISSET(sk, rfd)) r |= SOAP_TCP_SELECT_RCV; - if ((flags & SOAP_TCP_SELECT_SND) && FD_ISSET(s, sfd)) + if ((flags & SOAP_TCP_SELECT_SND) && FD_ISSET(sk, sfd)) r |= SOAP_TCP_SELECT_SND; - if ((flags & SOAP_TCP_SELECT_ERR) && FD_ISSET(s, efd)) + if ((flags & SOAP_TCP_SELECT_ERR) && FD_ISSET(sk, efd)) r |= SOAP_TCP_SELECT_ERR; } else if (r < 0) @@ -4421,18 +4450,19 @@ tcp_select(struct soap *soap, SOAP_SOCKET s, int flags, int timeout) #ifndef PALM_1 static SOAP_SOCKET tcp_accept(struct soap *soap, SOAP_SOCKET s, struct sockaddr *a, int *n) -{ SOAP_SOCKET fd; - fd = accept(s, a, (SOAP_SOCKLEN_T*)n); /* portability note: see SOAP_SOCKLEN_T definition in stdsoap2.h */ +{ SOAP_SOCKET sk; + (void)soap; + sk = accept(s, a, (SOAP_SOCKLEN_T*)n); /* portability note: see SOAP_SOCKLEN_T definition in stdsoap2.h */ #ifdef SOCKET_CLOSE_ON_EXEC #ifdef WIN32 #ifndef UNDER_CE - SetHandleInformation((HANDLE)fd, HANDLE_FLAG_INHERIT, 0); + SetHandleInformation((HANDLE)sk, HANDLE_FLAG_INHERIT, 0); #endif #else - fcntl(fd, F_SETFD, FD_CLOEXEC); + fcntl(sk, F_SETFD, FD_CLOEXEC); #endif #endif - return fd; + return sk; } #endif #endif @@ -4533,9 +4563,10 @@ tcp_disconnect(struct soap *soap) #ifndef WITH_NOIO #ifndef PALM_1 static int -tcp_closesocket(struct soap *soap, SOAP_SOCKET fd) -{ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Close socket %d\n", (int)fd)); - return soap_closesocket(fd); +tcp_closesocket(struct soap *soap, SOAP_SOCKET sk) +{ (void)soap; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Close socket %d\n", (int)sk)); + return soap_closesocket(sk); } #endif #endif @@ -4544,9 +4575,10 @@ tcp_closesocket(struct soap *soap, SOAP_SOCKET fd) #ifndef WITH_NOIO #ifndef PALM_1 static int -tcp_shutdownsocket(struct soap *soap, SOAP_SOCKET fd, int how) -{ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Shutdown socket %d how=%d\n", (int)fd, how)); - return shutdown(fd, how); +tcp_shutdownsocket(struct soap *soap, SOAP_SOCKET sk, int how) +{ (void)soap; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Shutdown socket %d how=%d\n", (int)sk, how)); + return shutdown(sk, how); } #endif #endif @@ -4569,7 +4601,7 @@ soap_bind(struct soap *soap, const char *host, int port, int backlog) #endif #endif #ifndef WITH_LEAN -#ifndef WITH_WIN32 +#ifndef WIN32 int len = SOAP_BUFLEN; #else int len = SOAP_BUFLEN + 1; /* speeds up windows xfer */ @@ -4623,6 +4655,7 @@ soap_bind(struct soap *soap, const char *host, int port, int backlog) soap_set_receiver_error(soap, tcp_error(soap), "socket failed in soap_bind()", SOAP_TCP_ERROR); return SOAP_INVALID_SOCKET; } + soap->port = port; #ifndef WITH_LEAN if ((soap->omode & SOAP_IO_UDP)) soap->socket = soap->master; @@ -4642,7 +4675,7 @@ soap_bind(struct soap *soap, const char *host, int port, int backlog) soap_set_receiver_error(soap, tcp_error(soap), "setsockopt failed in soap_bind()", SOAP_TCP_ERROR); return SOAP_INVALID_SOCKET; } - if (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) && setsockopt(soap->master, SOL_SOCKET, SO_KEEPALIVE, (char*)&set, sizeof(int))) + if (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) && (!((soap->imode | soap->omode) & SOAP_IO_UDP)) && setsockopt(soap->master, SOL_SOCKET, SO_KEEPALIVE, (char*)&set, sizeof(int))) { soap->errnum = soap_socket_errno(soap->master); soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_KEEPALIVE failed in soap_bind()", SOAP_TCP_ERROR); return SOAP_INVALID_SOCKET; @@ -4669,14 +4702,14 @@ soap_bind(struct soap *soap, const char *host, int port, int backlog) #ifdef WITH_IPV6_V6ONLY if (setsockopt(soap->master, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&set, sizeof(int))) { soap->errnum = soap_socket_errno(soap->master); - soap_set_receiver_error(soap, tcp_error(soap), "setsockopt IPV6_V6ONLY failed in soap_bind()", SOAP_TCP_ERROR); + soap_set_receiver_error(soap, tcp_error(soap), "setsockopt set IPV6_V6ONLY failed in soap_bind()", SOAP_TCP_ERROR); return SOAP_INVALID_SOCKET; } #endif #ifdef WITH_NO_IPV6_V6ONLY if (setsockopt(soap->master, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&unset, sizeof(int))) { soap->errnum = soap_socket_errno(soap->master); - soap_set_receiver_error(soap, tcp_error(soap), "setsockopt IPV6_V6ONLY failed in soap_bind()", SOAP_TCP_ERROR); + soap_set_receiver_error(soap, tcp_error(soap), "setsockopt unset IPV6_V6ONLY failed in soap_bind()", SOAP_TCP_ERROR); return SOAP_INVALID_SOCKET; } #endif @@ -4784,8 +4817,9 @@ SOAP_SOCKET SOAP_FMAC2 soap_accept(struct soap *soap) { int n = (int)sizeof(soap->peer); + register int err; #ifndef WITH_LEAN -#ifndef WITH_WIN32 +#ifndef WIN32 int len = SOAP_BUFLEN; #else int len = SOAP_BUFLEN + 1; /* speeds up windows xfer */ @@ -4793,124 +4827,123 @@ soap_accept(struct soap *soap) int set = 1; #endif soap->error = SOAP_OK; -#ifndef WITH_LEAN - if ((soap->omode & SOAP_IO_UDP)) - return soap->socket = soap->master; -#endif memset((void*)&soap->peer, 0, sizeof(soap->peer)); soap->socket = SOAP_INVALID_SOCKET; soap->errmode = 0; soap->keep_alive = 0; - if (soap_valid_socket(soap->master)) - { register int err; - for (;;) - { if (soap->accept_timeout || soap->send_timeout || soap->recv_timeout) - { for (;;) - { register int r; - r = tcp_select(soap, soap->master, SOAP_TCP_SELECT_ALL, soap->accept_timeout ? soap->accept_timeout : 60); - if (r > 0) - break; - if (!r && soap->accept_timeout) - { soap_set_receiver_error(soap, "Timeout", "accept failed in soap_accept()", SOAP_TCP_ERROR); + if (!soap_valid_socket(soap->master)) + { soap->errnum = 0; + soap_set_receiver_error(soap, tcp_error(soap), "no master socket in soap_accept()", SOAP_TCP_ERROR); + return SOAP_INVALID_SOCKET; + } +#ifndef WITH_LEAN + if ((soap->omode & SOAP_IO_UDP)) + return soap->socket = soap->master; +#endif + for (;;) + { if (soap->accept_timeout || soap->send_timeout || soap->recv_timeout) + { for (;;) + { register int r; + r = tcp_select(soap, soap->master, SOAP_TCP_SELECT_ALL, soap->accept_timeout ? soap->accept_timeout : 60); + if (r > 0) + break; + if (!r && soap->accept_timeout) + { soap_set_receiver_error(soap, "Timeout", "accept failed in soap_accept()", SOAP_TCP_ERROR); + return SOAP_INVALID_SOCKET; + } + if (r < 0) + { r = soap->errnum; + if (r != SOAP_EINTR) + { soap_closesock(soap); + soap_set_sender_error(soap, tcp_error(soap), "accept failed in soap_accept()", SOAP_TCP_ERROR); return SOAP_INVALID_SOCKET; } - if (r < 0) - { r = soap->errnum; - if (r != SOAP_EINTR) - { soap_closesock(soap); - soap_set_sender_error(soap, tcp_error(soap), "accept failed in soap_accept()", SOAP_TCP_ERROR); - return SOAP_INVALID_SOCKET; - } - } } } - if (soap->accept_timeout) - SOAP_SOCKNONBLOCK(soap->master) - else - SOAP_SOCKBLOCK(soap->master) - soap->socket = soap->faccept(soap, soap->master, (struct sockaddr*)&soap->peer, &n); - soap->peerlen = (size_t)n; - if (soap_valid_socket(soap->socket)) - { + } + if (soap->accept_timeout) + SOAP_SOCKNONBLOCK(soap->master) + else + SOAP_SOCKBLOCK(soap->master) + soap->socket = soap->faccept(soap, soap->master, (struct sockaddr*)&soap->peer, &n); + soap->peerlen = (size_t)n; + if (soap_valid_socket(soap->socket)) + { #ifdef WITH_IPV6 -/* Use soap->host to store the numeric form of the remote host */ - getnameinfo((struct sockaddr*)&soap->peer, n, soap->host, sizeof(soap->host), NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV); - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Accept socket %d from %s\n", soap->socket, soap->host)); - soap->ip = 0; /* info stored in soap->peer and soap->host */ - soap->port = 0; /* info stored in soap->peer and soap->host */ + unsigned int ip1, ip2, ip3, ip4; + char port[16]; + getnameinfo((struct sockaddr*)&soap->peer, n, soap->host, sizeof(soap->host), port, 16, NI_NUMERICHOST | NI_NUMERICSERV); + sscanf(soap->host, "%u.%u.%u.%u", &ip1, &ip2, &ip3, &ip4); + soap->ip = (unsigned long)ip1 << 24 | (unsigned long)ip2 << 16 | (unsigned long)ip3 << 8 | (unsigned long)ip4; + soap->port = soap_strtol(port, NULL, 10); #else - soap->ip = ntohl(soap->peer.sin_addr.s_addr); - soap->port = (int)ntohs(soap->peer.sin_port); /* does not return port number on some systems */ - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Accept socket %d at port %d from IP %d.%d.%d.%d\n", soap->socket, soap->port, (int)(soap->ip>>24)&0xFF, (int)(soap->ip>>16)&0xFF, (int)(soap->ip>>8)&0xFF, (int)soap->ip&0xFF)); + soap->ip = ntohl(soap->peer.sin_addr.s_addr); + sprintf(soap->host, "%u.%u.%u.%u", (int)(soap->ip>>24)&0xFF, (int)(soap->ip>>16)&0xFF, (int)(soap->ip>>8)&0xFF, (int)soap->ip&0xFF); + soap->port = (int)ntohs(soap->peer.sin_port); /* does not return port number on some systems */ #endif + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Accept socket %d at port %d from IP %s\n", soap->socket, soap->port, soap->host)); #ifndef WITH_LEAN - if (soap->accept_flags == SO_LINGER) - { struct linger linger; - memset((void*)&linger, 0, sizeof(linger)); - linger.l_onoff = 1; - linger.l_linger = soap->linger_time; - if (setsockopt(soap->socket, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(struct linger))) - { soap->errnum = soap_socket_errno(soap->socket); - soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_LINGER failed in soap_accept()", SOAP_TCP_ERROR); - soap_closesock(soap); - return SOAP_INVALID_SOCKET; - } - } - else if (soap->accept_flags && setsockopt(soap->socket, SOL_SOCKET, soap->accept_flags, (char*)&set, sizeof(int))) + if (soap->accept_flags == SO_LINGER) + { struct linger linger; + memset((void*)&linger, 0, sizeof(linger)); + linger.l_onoff = 1; + linger.l_linger = soap->linger_time; + if (setsockopt(soap->socket, SOL_SOCKET, SO_LINGER, (char*)&linger, sizeof(struct linger))) { soap->errnum = soap_socket_errno(soap->socket); - soap_set_receiver_error(soap, tcp_error(soap), "setsockopt failed in soap_accept()", SOAP_TCP_ERROR); - soap_closesock(soap); - return SOAP_INVALID_SOCKET; - } - if (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) && setsockopt(soap->socket, SOL_SOCKET, SO_KEEPALIVE, (char*)&set, sizeof(int))) - { soap->errnum = soap_socket_errno(soap->socket); - soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_KEEPALIVE failed in soap_accept()", SOAP_TCP_ERROR); - soap_closesock(soap); - return SOAP_INVALID_SOCKET; - } - if (setsockopt(soap->socket, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(int))) - { soap->errnum = soap_socket_errno(soap->socket); - soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_SNDBUF failed in soap_accept()", SOAP_TCP_ERROR); - soap_closesock(soap); - return SOAP_INVALID_SOCKET; - } - if (setsockopt(soap->socket, SOL_SOCKET, SO_RCVBUF, (char*)&len, sizeof(int))) - { soap->errnum = soap_socket_errno(soap->socket); - soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_RCVBUF failed in soap_accept()", SOAP_TCP_ERROR); + soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_LINGER failed in soap_accept()", SOAP_TCP_ERROR); soap_closesock(soap); return SOAP_INVALID_SOCKET; } + } + else if (soap->accept_flags && setsockopt(soap->socket, SOL_SOCKET, soap->accept_flags, (char*)&set, sizeof(int))) + { soap->errnum = soap_socket_errno(soap->socket); + soap_set_receiver_error(soap, tcp_error(soap), "setsockopt failed in soap_accept()", SOAP_TCP_ERROR); + soap_closesock(soap); + return SOAP_INVALID_SOCKET; + } + if (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) && setsockopt(soap->socket, SOL_SOCKET, SO_KEEPALIVE, (char*)&set, sizeof(int))) + { soap->errnum = soap_socket_errno(soap->socket); + soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_KEEPALIVE failed in soap_accept()", SOAP_TCP_ERROR); + soap_closesock(soap); + return SOAP_INVALID_SOCKET; + } + if (setsockopt(soap->socket, SOL_SOCKET, SO_SNDBUF, (char*)&len, sizeof(int))) + { soap->errnum = soap_socket_errno(soap->socket); + soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_SNDBUF failed in soap_accept()", SOAP_TCP_ERROR); + soap_closesock(soap); + return SOAP_INVALID_SOCKET; + } + if (setsockopt(soap->socket, SOL_SOCKET, SO_RCVBUF, (char*)&len, sizeof(int))) + { soap->errnum = soap_socket_errno(soap->socket); + soap_set_receiver_error(soap, tcp_error(soap), "setsockopt SO_RCVBUF failed in soap_accept()", SOAP_TCP_ERROR); + soap_closesock(soap); + return SOAP_INVALID_SOCKET; + } #ifdef TCP_NODELAY - if (!(soap->omode & SOAP_IO_UDP) && setsockopt(soap->socket, IPPROTO_TCP, TCP_NODELAY, (char*)&set, sizeof(int))) - { soap->errnum = soap_socket_errno(soap->socket); - soap_set_receiver_error(soap, tcp_error(soap), "setsockopt TCP_NODELAY failed in soap_accept()", SOAP_TCP_ERROR); - soap_closesock(soap); - return SOAP_INVALID_SOCKET; - } -#endif -#endif - soap->keep_alive = (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) != 0); - if (soap->send_timeout || soap->recv_timeout) - SOAP_SOCKNONBLOCK(soap->socket) - else - SOAP_SOCKBLOCK(soap->socket) - return soap->socket; - } - err = soap_socket_errno(soap->socket); - if (err != 0 && err != SOAP_EINTR && err != SOAP_EAGAIN && err != SOAP_EWOULDBLOCK) - { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Accept failed from %s\n", soap->host)); - soap->errnum = err; - soap_set_receiver_error(soap, tcp_error(soap), "accept failed in soap_accept()", SOAP_TCP_ERROR); + if (setsockopt(soap->socket, IPPROTO_TCP, TCP_NODELAY, (char*)&set, sizeof(int))) + { soap->errnum = soap_socket_errno(soap->socket); + soap_set_receiver_error(soap, tcp_error(soap), "setsockopt TCP_NODELAY failed in soap_accept()", SOAP_TCP_ERROR); soap_closesock(soap); return SOAP_INVALID_SOCKET; } +#endif +#endif + soap->keep_alive = (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) != 0); + if (soap->send_timeout || soap->recv_timeout) + SOAP_SOCKNONBLOCK(soap->socket) + else + SOAP_SOCKBLOCK(soap->socket) + return soap->socket; + } + err = soap_socket_errno(soap->socket); + if (err != 0 && err != SOAP_EINTR && err != SOAP_EAGAIN && err != SOAP_EWOULDBLOCK) + { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Accept failed from %s\n", soap->host)); + soap->errnum = err; + soap_set_receiver_error(soap, tcp_error(soap), "accept failed in soap_accept()", SOAP_TCP_ERROR); + soap_closesock(soap); + return SOAP_INVALID_SOCKET; } } - else - { soap->errnum = 0; - soap_set_receiver_error(soap, tcp_error(soap), "no master socket in soap_accept()", SOAP_TCP_ERROR); - return SOAP_INVALID_SOCKET; - } } #endif #endif @@ -4949,6 +4982,19 @@ soap_closesock(struct soap *soap) #endif /******************************************************************************/ +#ifndef PALM_1 +SOAP_FMAC1 +int +SOAP_FMAC2 +soap_force_closesock(struct soap *soap) +{ soap->keep_alive = 0; + if (soap_valid_socket(soap->socket)) + return soap_closesocket(soap->socket); + return SOAP_OK; +} +#endif + +/******************************************************************************/ #ifndef WITH_NOIO #ifndef PALM_2 SOAP_FMAC1 @@ -5004,11 +5050,11 @@ soap_done(struct soap *soap) soap->fmalloc = NULL; #ifndef WITH_NOHTTP soap->fpost = http_post; - soap->fput = http_put; soap->fget = http_get; + soap->fput = http_405; soap->fdel = http_405; - soap->fopt = http_405; - soap->fhead = http_405; + soap->fopt = http_200; + soap->fhead = http_200; soap->fform = NULL; soap->fposthdr = http_post_header; soap->fresponse = http_response; @@ -5106,7 +5152,11 @@ soap_done(struct soap *soap) } #endif #ifdef WITH_C_LOCALE +# ifdef WIN32 + _free_locale(soap->c_locale); +# else freelocale(soap->c_locale); +# endif #endif #ifdef WITH_ZLIB if (soap->d_stream) @@ -5147,16 +5197,24 @@ soap_done(struct soap *soap) int http_parse(struct soap *soap) { char header[SOAP_HDRLEN], *s; - unsigned short httpcmd = 0, status = 0; + unsigned short httpcmd = 0; + int status = 0; DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Waiting for HTTP request/response...\n")); *soap->endpoint = '\0'; soap->length = 0; - soap->userid = NULL; - soap->passwd = NULL; - soap->action = NULL; - soap->authrealm = NULL; +#ifdef WITH_NTLM + if (!soap->ntlm_challenge) +#endif + { soap->userid = NULL; + soap->passwd = NULL; + soap->authrealm = NULL; + } +#ifdef WITH_NTLM + soap->ntlm_challenge = NULL; +#endif soap->proxy_from = NULL; soap->http_content = NULL; + soap->action = NULL; soap->status = 0; do { if (soap_getline(soap, soap->msgbuf, sizeof(soap->msgbuf))) @@ -5245,6 +5303,8 @@ http_parse(struct soap *soap) n = sizeof(soap->endpoint) - 1; strncpy(soap->path, soap->msgbuf + l, n - m); soap->path[n - m] = '\0'; + if (*soap->path && *soap->path != '/') + *soap->endpoint = '\0'; strcat(soap->endpoint, soap->path); DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Target endpoint='%s'\n", soap->endpoint)); if (httpcmd > 1) @@ -5277,7 +5337,7 @@ http_parse(struct soap *soap) may not have a body. When content length, content type, or chunking is used assume there is a message to parse, either XML or HTTP. */ - if (soap->length > 0 || (soap->http_content && soap->recv_timeout) || (soap->imode & SOAP_IO) == SOAP_IO_CHUNK) + if (soap->length > 0 || (soap->http_content && (!soap->keep_alive || soap->recv_timeout)) || (soap->imode & SOAP_IO) == SOAP_IO_CHUNK) { if ((soap->status > 200 && soap->status <= 299) || soap->status == 400 || soap->status == 500) @@ -5392,8 +5452,14 @@ http_parse_header(struct soap *soap, const char *key, const char *val) } } } - else if (!soap_tag_cmp(key, "WWW-Authenticate")) - { soap->authrealm = soap_strdup(soap, soap_get_header_attribute(soap, val + 6, "realm")); + else if (!soap_tag_cmp(key, "WWW-Authenticate") || !soap_tag_cmp(key, "Proxy-Authenticate")) + { +#ifdef WITH_NTLM + if (!soap_tag_cmp(val, "NTLM*")) + soap->ntlm_challenge = soap_strdup(soap, val + 4); + else +#endif + soap->authrealm = soap_strdup(soap, soap_get_header_attribute(soap, val + 6, "realm")); } else if (!soap_tag_cmp(key, "Expect")) { if (!soap_tag_cmp(val, "100-continue")) @@ -5522,6 +5588,7 @@ soap_decode(char *buf, size_t len, const char *val, const char *sep) static const char* http_error(struct soap *soap, int status) { register const char *msg = SOAP_STR_EOS; + (void)soap; #ifndef WITH_LEAN msg = soap_code_str(h_http_error_codes, status); if (!msg) @@ -5533,21 +5600,25 @@ http_error(struct soap *soap, int status) #endif /******************************************************************************/ + #ifndef WITH_NOHTTP #ifndef PALM_1 static int -http_put(struct soap *soap) -{ return http_parse(soap); +http_get(struct soap *soap) +{ (void)soap; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "HTTP GET request\n")); + return SOAP_GET_METHOD; } #endif #endif -/******************************************************************************/ +/******************************************************************************/ #ifndef WITH_NOHTTP #ifndef PALM_1 static int -http_get(struct soap *soap) -{ return SOAP_GET_METHOD; +http_405(struct soap *soap) +{ return 405; + (void)soap; } #endif #endif @@ -5556,8 +5627,8 @@ http_get(struct soap *soap) #ifndef WITH_NOHTTP #ifndef PALM_1 static int -http_405(struct soap *soap) -{ return 405; +http_200(struct soap *soap) +{ return soap_send_empty_response(soap, 200); } #endif #endif @@ -5569,10 +5640,23 @@ static int http_post(struct soap *soap, const char *endpoint, const char *host, int port, const char *path, const char *action, size_t count) { register const char *s; register int err; - if (soap->status == SOAP_GET) - s = "GET"; - else - s = "POST"; + switch (soap->status) + { case SOAP_GET: + s = "GET"; + break; + case SOAP_PUT: + s = "PUT"; + break; + case SOAP_DEL: + s = "DELETE"; + break; + case SOAP_CONNECT: + s = "CONNECT"; + break; + default: + s = "POST"; + } + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "HTTP %s to %s\n", s, endpoint ? endpoint : "(null)")); #ifdef PALM if (!endpoint || (soap_tag_cmp(endpoint, "http:*") && soap_tag_cmp(endpoint, "https:*") && strncmp(endpoint, "httpg:", 6)) && strncmp(endpoint, "_beam:", 6) && strncmp(endpoint, "_local:", 7) && strncmp(endpoint, "_btobex:", 8)) #else @@ -5580,24 +5664,30 @@ http_post(struct soap *soap, const char *endpoint, const char *host, int port, c #endif return SOAP_OK; if (strlen(endpoint) + strlen(soap->http_version) > sizeof(soap->tmpbuf) - 80) - return soap->error = SOAP_EOM; - if (soap->proxy_host && soap_tag_cmp(endpoint, "https:*")) + return soap->error = SOAP_EOM; /* prevent overrun */ + if (soap->status == SOAP_CONNECT) + sprintf(soap->tmpbuf, "%s %s:%d HTTP/%s", s, soap->host, soap->port, soap->http_version); + else if (soap->proxy_host && endpoint) sprintf(soap->tmpbuf, "%s %s HTTP/%s", s, endpoint, soap->http_version); else sprintf(soap->tmpbuf, "%s /%s HTTP/%s", s, (*path == '/' ? path + 1 : path), soap->http_version); if ((err = soap->fposthdr(soap, soap->tmpbuf, NULL))) return err; #ifdef WITH_OPENSSL - if ((soap->ssl && soap->port != 443) || (!soap->ssl && soap->port != 80)) - sprintf(soap->tmpbuf, "%s:%d", host, port); - else - strcpy(soap->tmpbuf, host); + if ((soap->ssl && port != 443) || (!soap->ssl && port != 80)) #else if (port != 80) - sprintf(soap->tmpbuf, "%s:%d", host, port); +#endif + { +#ifdef WITH_IPV6 + if (*host != '[' && strchr(host, ':')) + sprintf(soap->tmpbuf, "[%s]:%d", host, port); /* RFC 2732 */ + else +#endif + sprintf(soap->tmpbuf, "%s:%d", host, port); + } else strcpy(soap->tmpbuf, host); -#endif if ((err = soap->fposthdr(soap, "Host", soap->tmpbuf))) return err; if ((err = soap->fposthdr(soap, "User-Agent", "gSOAP/2.8"))) @@ -5614,16 +5704,30 @@ http_post(struct soap *soap, const char *endpoint, const char *host, int port, c #endif #ifndef WITH_LEAN if (soap->userid && soap->passwd && strlen(soap->userid) + strlen(soap->passwd) < 761) - { sprintf(soap->tmpbuf + 262, "%s:%s", soap->userid, soap->passwd); - strcpy(soap->tmpbuf, "Basic "); - soap_s2base64(soap, (const unsigned char*)(soap->tmpbuf + 262), soap->tmpbuf + 6, (int)strlen(soap->tmpbuf + 262)); + { +#ifdef WITH_NTLM + if (soap->ntlm_challenge && strlen(soap->ntlm_challenge) + 6 < sizeof(soap->tmpbuf)) + sprintf(soap->tmpbuf, "NTLM %s", soap->ntlm_challenge); + else +#endif + { strcpy(soap->tmpbuf, "Basic "); + sprintf(soap->tmpbuf + 262, "%s:%s", soap->userid, soap->passwd); + soap_s2base64(soap, (const unsigned char*)(soap->tmpbuf + 262), soap->tmpbuf + 6, (int)strlen(soap->tmpbuf + 262)); + } if ((err = soap->fposthdr(soap, "Authorization", soap->tmpbuf))) return err; } if (soap->proxy_userid && soap->proxy_passwd && strlen(soap->proxy_userid) + strlen(soap->proxy_passwd) < 761) - { sprintf(soap->tmpbuf + 262, "%s:%s", soap->proxy_userid, soap->proxy_passwd); - strcpy(soap->tmpbuf, "Basic "); - soap_s2base64(soap, (const unsigned char*)(soap->tmpbuf + 262), soap->tmpbuf + 6, (int)strlen(soap->tmpbuf + 262)); + { +#ifdef WITH_NTLM + if (soap->ntlm_challenge && strlen(soap->ntlm_challenge) + 6 < sizeof(soap->tmpbuf)) + sprintf(soap->tmpbuf, "NTLM %s", soap->ntlm_challenge); + else +#endif + { strcpy(soap->tmpbuf, "Basic "); + sprintf(soap->tmpbuf + 262, "%s:%s", soap->proxy_userid, soap->proxy_passwd); + soap_s2base64(soap, (const unsigned char*)(soap->tmpbuf + 262), soap->tmpbuf + 6, (int)strlen(soap->tmpbuf + 262)); + } if ((err = soap->fposthdr(soap, "Proxy-Authorization", soap->tmpbuf))) return err; } @@ -5637,7 +5741,7 @@ http_post(struct soap *soap, const char *endpoint, const char *host, int port, c return soap->error; #endif #endif - if (soap->status != SOAP_GET && soap->version == 1) + if (action && soap->status != SOAP_GET && soap->status != SOAP_DEL) { sprintf(soap->tmpbuf, "\"%s\"", action && strlen(action) < sizeof(soap->tmpbuf) - 3 ? action : SOAP_STR_EOS); if ((err = soap->fposthdr(soap, "SOAPAction", soap->tmpbuf))) return err; @@ -5699,7 +5803,7 @@ http_response(struct soap *soap, int status, size_t count) if (count || ((soap->omode & SOAP_IO) == SOAP_IO_CHUNK)) s = "200 OK"; else - s = "202 ACCEPTED"; + s = "202 Accepted"; DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Status = %s\n", s)); #ifdef WMW_RPM_IO if (soap->rpmreqid || soap_valid_socket(soap->master) || soap_valid_socket(soap->socket)) /* RPM behaves as if standalone */ @@ -5842,9 +5946,9 @@ soap_cookie(struct soap *soap, const char *name, const char *domain, const char path = SOAP_STR_EOS; else if (*path == '/') path++; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Search cookie %s domain=%s path=%s\n", name, domain?domain:"(null)", path?path:"(null)")); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Search cookie %s domain=%s path=%s\n", name, domain ? domain : "(null)", path ? path : "(null)")); for (p = soap->cookies; p; p = p->next) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Cookie in database: %s=%s domain=%s path=%s env=%hd\n", p->name, p->value?p->value:"(null)", p->domain?p->domain:"(null)", p->path?p->path:"(null)", p->env)); + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Cookie in database: %s=%s domain=%s path=%s env=%hd\n", p->name, p->value ? p->value : "(null)", p->domain ? p->domain : "(null)", p->path ? p->path : "(null)", p->env)); if (!strcmp(p->name, name) && p->domain && p->path @@ -5871,7 +5975,7 @@ soap_set_cookie(struct soap *soap, const char *name, const char *value, const ch else if (*path == '/') path++; q = soap_cookie(soap, name, domain, path); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Set %scookie: %s=%s domain=%s path=%s\n", q ? SOAP_STR_EOS : "new ", name, value?value:"(null)", domain?domain:"(null)", path?path:"(null)")); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Set %scookie: %s=%s domain=%s path=%s\n", q ? SOAP_STR_EOS : "new ", name, value ? value : "(null)", domain ? domain : "(null)", path ? path : "(null)")); if (!q) { if ((q = (struct soap_cookie*)SOAP_MALLOC(soap, sizeof(struct soap_cookie)))) { if ((q->name = (char*)SOAP_MALLOC(soap, strlen(name)+1))) @@ -5940,13 +6044,13 @@ soap_clr_cookie(struct soap *soap, const char *name, const char *domain, const c if (!domain) domain = soap->cookie_domain; if (!domain) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Error in clear cookie %s: cookie domain not set\n", name?name:"(null)")); + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Error in clear cookie %s: cookie domain not set\n", name ? name : "(null)")); return; } if (!path) path = soap->cookie_path; if (!path) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Error in clear cookie %s: cookie path not set\n", name?name:"(null)")); + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Error in clear cookie %s: cookie path not set\n", name ? name : "(null)")); return; } if (*path == '/') @@ -6006,7 +6110,7 @@ int SOAP_FMAC2 soap_set_cookie_expire(struct soap *soap, const char *name, long expire, const char *domain, const char *path) { struct soap_cookie *p; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Set cookie expiration max-age %ld: %s domain=%s path=%s\n", expire, name, domain?domain:"(null)", path?path:"(null)")); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Set cookie expiration max-age %ld: %s domain=%s path=%s\n", expire, name, domain ? domain : "(null)", path ? path : "(null)")); if ((p = soap_cookie(soap, name, domain, path))) { p->maxage = expire; p->modified = 1; @@ -6123,6 +6227,9 @@ soap_putcookies(struct soap *soap, const char *domain, const char *path, int sec unsigned int version = 0; time_t now = time(NULL); char *s, tmp[4096]; + if (!domain || !path) + return SOAP_OK; + s = tmp; p = &soap->cookies; DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Sending cookies for domain=%s path=%s\n", domain, path)); if (*path == '/') @@ -6169,30 +6276,53 @@ soap_putcookies(struct soap *soap, const char *domain, const char *path, int sec if (flag && (!q->path || !strncmp(q->path, path, strlen(q->path))) && (!q->secure || secure)) - { s = tmp; + { size_t n = 12; + if (q->name) + n += 3*strlen(q->name); + if (q->value && *q->value) + n += 3*strlen(q->value) + 1; + if (q->path && *q->path) + n += strlen(q->path) + 9; + if (q->domain) + n += strlen(q->domain) + 11; + if (tmp - s + n > sizeof(tmp)) + { if (s == tmp) + return SOAP_OK; /* HTTP header size overflow */ + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Cookie: %s\n", tmp)); + if ((soap->error = soap->fposthdr(soap, "Cookie", tmp))) + return soap->error; + s = tmp; + } + else if (s != tmp) + { strcat(s, " "); + s++; + } if (q->version != version) { sprintf(s, "$Version=%u;", q->version); version = q->version; + s += strlen(s); } if (q->name) - s += soap_encode_cookie(q->name, s, tmp-s+4080); + s += soap_encode_cookie(q->name, s, tmp+sizeof(tmp)-s-16); if (q->value && *q->value) { *s++ = '='; - s += soap_encode_cookie(q->value, s, tmp-s+4080); + s += soap_encode_cookie(q->value, s, tmp+sizeof(tmp)-s-16); } - if (q->path && *q->path && (int)strlen(q->path) < tmp-s+4080) + if (q->path) { sprintf(s, ";$Path=\"/%s\"", (*q->path == '/' ? q->path + 1 : q->path)); s += strlen(s); } - if (q->domain && (int)strlen(q->domain) < tmp-s+4080) - sprintf(s, ";$Domain=\"%s\"", q->domain); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Cookie: %s\n", tmp)); - if ((soap->error = soap->fposthdr(soap, "Cookie", tmp))) - return soap->error; + if (q->domain) + { sprintf(s, ";$Domain=\"%s\"", q->domain); + s += strlen(s); + } } p = &q->next; } } + if (s != tmp) + if ((soap->error = soap->fposthdr(soap, "Cookie", tmp))) + return soap->error; return SOAP_OK; } @@ -6322,7 +6452,7 @@ soap_getcookies(struct soap *soap, const char *val) p->secure = 1; else { if (p) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Got environment cookie %s=%s domain=%s path=%s expire=%ld secure=%d\n", p->name, p->value?p->value:"(null)", p->domain?p->domain:"(null)", p->path?p->path:"(null)", p->expire, p->secure)); + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Got environment cookie %s=%s domain=%s path=%s expire=%ld secure=%d\n", p->name, p->value ? p->value : "(null)", p->domain ? p->domain : "(null)", p->path ? p->path : "(null)", p->expire, p->secure)); if ((q = soap_set_cookie(soap, p->name, p->value, p->domain, p->path))) { q->version = p->version; q->expire = p->expire; @@ -6374,7 +6504,7 @@ soap_getcookies(struct soap *soap, const char *val) } } if (p) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Got environment cookie %s=%s domain=%s path=%s expire=%ld secure=%d\n", p->name, p->value?p->value:"(null)", p->domain?p->domain:"(null)", p->path?p->path:"(null)", p->expire, p->secure)); + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Got environment cookie %s=%s domain=%s path=%s expire=%ld secure=%d\n", p->name, p->value ? p->value : "(null)", p->domain ? p->domain : "(null)", p->path ? p->path : "(null)", p->expire, p->secure)); if ((q = soap_set_cookie(soap, p->name, p->value, p->domain, p->path))) { q->version = p->version; q->expire = p->expire; @@ -6506,30 +6636,10 @@ soap_init_pht(struct soap *soap) SOAP_FMAC1 struct soap* SOAP_FMAC2 -soap_new1(soap_mode mode) -{ return soap_new2(mode, mode); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -struct soap* -SOAP_FMAC2 -soap_new() -{ return soap_new2(SOAP_IO_DEFAULT, SOAP_IO_DEFAULT); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -struct soap* -SOAP_FMAC2 -soap_new2(soap_mode imode, soap_mode omode) +soap_versioning(soap_new)(soap_mode imode, soap_mode omode) { struct soap *soap = (struct soap*)malloc(sizeof(struct soap)); if (soap) - soap_init2(soap, imode, omode); + soap_versioning(soap_init)(soap, imode, omode); return soap; } #endif @@ -6597,6 +6707,7 @@ soap_embed(struct soap *soap, const void *p, const struct soap_array *a, int n, soap_set_embedded(soap, pp); } return i; + (void)soap; } #endif #endif @@ -6649,7 +6760,7 @@ soap_pointer_enter(struct soap *soap, const void *p, const struct soap_array *a, h = soap_hash_ptr(a->__ptr); else h = soap_hash_ptr(p); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Pointer enter location=%p array=%p size=%d dim=%d type=%d id=%d\n", p, a?a->__ptr:NULL, a?a->__size:0, n, type, soap->idnum+1)); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Pointer enter location=%p array=%p size=%d dim=%d type=%d id=%d\n", p, a ? a->__ptr : NULL, a ? a->__size : 0, n, type, soap->idnum+1)); pp->next = soap->pht[h]; pp->type = type; pp->mark1 = 0; @@ -6659,6 +6770,7 @@ soap_pointer_enter(struct soap *soap, const void *p, const struct soap_array *a, soap->pht[h] = pp; pp->id = ++soap->idnum; return pp->id; + (void)n; } #endif #endif @@ -6747,6 +6859,7 @@ soap_begin_count(struct soap *soap) soap->encoding = 0; soap->part = SOAP_BEGIN; soap->event = 0; + soap->evlev = 0; soap->idnum = 0; soap_clr_attr(soap); soap_set_local_namespaces(soap); @@ -6829,7 +6942,7 @@ soap_begin_send(struct soap *soap) #ifdef WIN32 #ifndef UNDER_CE #ifndef WITH_FASTCGI - if (!soap_valid_socket(soap->socket)) /* Set win32 stdout or soap->sendfd to BINARY, e.g. to support DIME */ + if (!soap_valid_socket(soap->socket) && !soap->os) /* Set win32 stdout or soap->sendfd to BINARY, e.g. to support DIME */ #ifdef __BORLANDC__ setmode(soap->sendfd, _O_BINARY); #else @@ -7084,7 +7197,7 @@ soap_attachment(struct soap *soap, const char *tag, int id, const void *p, const int i; if (!p || !a->__ptr || (!aid && !atype)) return soap_element_id(soap, tag, id, p, a, n, type, t); - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Attachment tag='%s' id='%s' (%d) type='%s'\n", tag, aid?aid:SOAP_STR_EOS, id, atype?atype:SOAP_STR_EOS)); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Attachment tag='%s' id='%s' (%d) type='%s'\n", tag, aid ? aid : SOAP_STR_EOS, id, atype ? atype : SOAP_STR_EOS)); i = soap_array_pointer_lookup(soap, p, a, n, t, &pp); if (!i) { i = soap_pointer_enter(soap, p, a, n, t, &pp); @@ -7213,7 +7326,7 @@ soap_enter(struct soap *soap, const char *id) ip = (struct soap_ilist*)SOAP_MALLOC(soap, sizeof(struct soap_ilist) + strlen(id)); if (ip) { h = soap_hash(id); - strcpy(ip->id, id); + strcpy((char*)ip->id, id); ip->next = soap->iht[h]; soap->iht[h] = ip; } @@ -7400,13 +7513,16 @@ soap_dealloc(struct soap *soap, void *p) SOAP_FREE(soap, q); } /* we must assume these were deallocated: */ + soap->http_content = NULL; soap->action = NULL; soap->fault = NULL; soap->header = NULL; soap->userid = NULL; soap->passwd = NULL; soap->authrealm = NULL; - soap->http_content = NULL; +#ifdef WITH_NTLM + soap->ntlm_challenge = NULL; +#endif #ifndef WITH_LEANER soap_clr_mime(soap); #endif @@ -7537,32 +7653,33 @@ soap_link(struct soap *soap, void *p, int t, int n, int (*fdelete)(struct soap_c /******************************************************************************/ #ifndef PALM_2 SOAP_FMAC1 -void +int SOAP_FMAC2 soap_unlink(struct soap *soap, const void *p) { register char **q; register struct soap_clist **cp; - if (!soap || !p) - return; - for (q = (char**)&soap->alist; *q; q = *(char***)q) - { if (p == (void*)(*q - *(size_t*)(*q + sizeof(void*)))) - { *q = **(char***)q; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unlinked data %p\n", p)); + if (soap && p) + { for (q = (char**)&soap->alist; *q; q = *(char***)q) + { if (p == (void*)(*q - *(size_t*)(*q + sizeof(void*)))) + { *q = **(char***)q; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unlinked data %p\n", p)); #ifdef SOAP_MEM_DEBUG - soap_track_unlink(soap, p); + soap_track_unlink(soap, p); #endif - return; + return SOAP_OK; /* found and removed from dealloc chain */ + } } - } - for (cp = &soap->clist; *cp; cp = &(*cp)->next) - { if (p == (*cp)->ptr) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unlinked class instance %p\n", p)); - q = (char**)*cp; - *cp = (*cp)->next; - SOAP_FREE(soap, q); - return; + for (cp = &soap->clist; *cp; cp = &(*cp)->next) + { if (p == (*cp)->ptr) + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unlinked class instance %p\n", p)); + q = (char**)*cp; + *cp = (*cp)->next; + SOAP_FREE(soap, q); + return SOAP_OK; /* found and removed from dealloc chain */ + } } } + return SOAP_ERR; } #endif @@ -7802,6 +7919,7 @@ SOAP_FMAC2 soap_fcopy(struct soap *soap, int st, int tt, void *p, size_t len, const void *q, size_t n) { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Copying data type=%d (target type=%d) %p -> %p (%lu bytes)\n", st, tt, q, p, (unsigned long)n)); memcpy(p, q, n); + (void)soap; (void)st; (void)tt; (void)len; } #endif @@ -7867,7 +7985,7 @@ soap_end_send(struct soap *soap) soap->mode &= ~SOAP_ENC_ZLIB; soap->zlib_state = SOAP_ZLIB_NONE; if (deflateEnd(soap->d_stream) != Z_OK || r != Z_STREAM_END) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unable to end deflate: %s\n", soap->d_stream->msg?soap->d_stream->msg:SOAP_STR_EOS)); + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Unable to end deflate: %s\n", soap->d_stream->msg ? soap->d_stream->msg : SOAP_STR_EOS)); return soap->error = SOAP_ZLIB_ERROR; } #ifdef WITH_GZIP @@ -8004,7 +8122,7 @@ soap_end_recv(struct soap *soap) for (i = 0; i < 8; i++) { if ((int)(c = soap_get1(soap)) == EOF) { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Gzip error: unable to read crc value\n")); - return soap->error = SOAP_EOF; + return soap->error = SOAP_ZLIB_ERROR; } soap->z_buf[i] = (char)c; } @@ -8232,6 +8350,7 @@ soap_copy_context(struct soap *copy, const struct soap *soap) return NULL; if (copy) { register struct soap_plugin *p = NULL; + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Copying context\n")); #ifdef __cplusplus *copy = *soap; #else @@ -8241,6 +8360,9 @@ soap_copy_context(struct soap *copy, const struct soap *soap) copy->error = SOAP_OK; copy->userid = NULL; copy->passwd = NULL; +#ifdef WITH_NTLM + copy->ntlm_challenge = NULL; +#endif copy->nlist = NULL; copy->blist = NULL; copy->clist = NULL; @@ -8260,8 +8382,18 @@ soap_copy_context(struct soap *copy, const struct soap *soap) soap_set_sent_logfile(copy, soap->logfile[SOAP_INDEX_SENT]); soap_set_recv_logfile(copy, soap->logfile[SOAP_INDEX_RECV]); #endif + copy->namespaces = NULL; + copy->local_namespaces = NULL; + if (soap->local_namespaces) + soap_set_namespaces(copy, soap->local_namespaces); + else + soap_set_namespaces(copy, soap->namespaces); #ifdef WITH_C_LOCALE +# ifdef WIN32 + copy->c_locale = _create_locale(LC_ALL, "C"); +# else copy->c_locale = duplocale(soap->c_locale); +# endif #else copy->c_locale = NULL; #endif @@ -8326,7 +8458,10 @@ soap_copy_stream(struct soap *copy, struct soap *soap) copy->mode = soap->mode; copy->imode = soap->imode; copy->omode = soap->omode; + copy->master = soap->master; copy->socket = soap->socket; + copy->sendsk = soap->sendsk; + copy->recvsk = soap->recvsk; copy->recv_timeout = soap->recv_timeout; copy->send_timeout = soap->send_timeout; #if defined(__cplusplus) && !defined(WITH_LEAN) @@ -8350,23 +8485,27 @@ soap_copy_stream(struct soap *copy, struct soap *soap) #ifndef WITH_NOIO copy->peer = soap->peer; copy->peerlen = soap->peerlen; + copy->ip = soap->ip; + copy->port = soap->port; + memcpy(copy->host, soap->host, sizeof(soap->host)); + memcpy(copy->endpoint, soap->endpoint, sizeof(soap->endpoint)); #endif #ifdef WITH_OPENSSL - copy->bio = NULL; - copy->ctx = NULL; - copy->ssl = NULL; - if (soap->ssl) - copy->ssl = SSL_dup(soap->ssl); + copy->bio = soap->bio; + copy->ctx = soap->ctx; + copy->ssl = soap->ssl; #endif #ifdef WITH_GNUTLS - copy->session = soap->session; /* TODO: Oops, GNUTLS provides a dup? */ + copy->session = soap->session; #endif #ifdef WITH_ZLIB copy->zlib_state = soap->zlib_state; copy->zlib_in = soap->zlib_in; copy->zlib_out = soap->zlib_out; - copy->d_stream = (z_stream*)SOAP_MALLOC(copy, sizeof(z_stream)); - memcpy(copy->d_stream, soap->d_stream, sizeof(z_stream)); + if (!copy->d_stream) + copy->d_stream = (z_stream*)SOAP_MALLOC(copy, sizeof(z_stream)); + if (copy->d_stream) + memcpy(copy->d_stream, soap->d_stream, sizeof(z_stream)); copy->z_crc = soap->z_crc; copy->z_ratio_in = soap->z_ratio_in; copy->z_ratio_out = soap->z_ratio_out; @@ -8375,7 +8514,8 @@ soap_copy_stream(struct soap *copy, struct soap *soap) copy->z_level = soap->z_level; if (soap->z_buf && soap->zlib_state != SOAP_ZLIB_NONE) { copy->z_buf = (char*)SOAP_MALLOC(copy, SOAP_BUFLEN); - memcpy(copy->z_buf, soap->z_buf, sizeof(soap->z_buf)); + if (copy->z_buf) + memcpy(copy->z_buf, soap->z_buf, SOAP_BUFLEN); } copy->z_dict = soap->z_dict; copy->z_dict_len = soap->z_dict_len; @@ -8411,10 +8551,18 @@ soap_copy_stream(struct soap *copy, struct soap *soap) SOAP_FREE(copy, nq); } } - copy->level = soap->level; + memcpy(copy->tag, soap->tag, sizeof(copy->tag)); + memcpy(copy->id, soap->id, sizeof(copy->id)); + memcpy(copy->href, soap->href, sizeof(copy->href)); + memcpy(copy->type, soap->type, sizeof(copy->type)); + copy->other = soap->other; + copy->root = soap->root; + copy->null = soap->null; copy->body = soap->body; + copy->part = soap->part; + copy->mustUnderstand = soap->mustUnderstand; + copy->level = soap->level; copy->peeked = soap->peeked; - memcpy(copy->tag, soap->tag, sizeof(copy->tag)); /* copy attributes */ for (tq = soap->attributes; tq; tq = tq->next) { struct soap_attribute *tr = tp; @@ -8440,24 +8588,22 @@ void SOAP_FMAC2 soap_free_stream(struct soap *soap) { soap->socket = SOAP_INVALID_SOCKET; + soap->sendsk = SOAP_INVALID_SOCKET; + soap->recvsk = SOAP_INVALID_SOCKET; #ifdef WITH_OPENSSL soap->bio = NULL; - if (soap->ssl) - SSL_free(soap->ssl); + soap->ctx = NULL; soap->ssl = NULL; #endif #ifdef WITH_GNUTLS soap->xcred = NULL; soap->acred = NULL; soap->cache = NULL; - soap->session = NULL; /* TODO: GNUTLS free here when dupped */ + soap->session = NULL; soap->dh_params = NULL; soap->rsa_params = NULL; #endif #ifdef WITH_ZLIB - if (soap->d_stream) - SOAP_FREE(soap, soap->d_stream); - soap->d_stream = NULL; if (soap->z_buf) SOAP_FREE(soap, soap->z_buf); soap->z_buf = NULL; @@ -8470,7 +8616,7 @@ soap_free_stream(struct soap *soap) SOAP_FMAC1 void SOAP_FMAC2 -soap_init(struct soap *soap) +soap_versioning(soap_init)(struct soap *soap, soap_mode imode, soap_mode omode) { size_t i; soap->state = SOAP_INIT; #ifdef SOAP_MEM_DEBUG @@ -8480,7 +8626,7 @@ soap_init(struct soap *soap) soap_init_logs(soap); #endif #ifdef SOAP_DEBUG -#ifdef TANDEM +#ifdef TANDEM_NONSTOP soap_set_test_logfile(soap, "TESTLOG"); soap_set_sent_logfile(soap, "SENTLOG"); soap_set_recv_logfile(soap, "RECVLOG"); @@ -8491,21 +8637,26 @@ soap_init(struct soap *soap) #endif #endif soap->version = 0; - soap_imode(soap, SOAP_IO_DEFAULT); - soap_omode(soap, SOAP_IO_DEFAULT); + soap_mode(soap, imode); + soap_imode(soap, imode); + soap_omode(soap, omode); soap->plugins = NULL; soap->user = NULL; for (i = 0; i < sizeof(soap->data)/sizeof(*soap->data); i++) soap->data[i] = NULL; soap->userid = NULL; soap->passwd = NULL; + soap->authrealm = NULL; +#ifdef WITH_NTLM + soap->ntlm_challenge = NULL; +#endif #ifndef WITH_NOHTTP soap->fpost = http_post; - soap->fput = http_put; soap->fget = http_get; + soap->fput = http_405; soap->fdel = http_405; - soap->fopt = http_405; - soap->fhead = http_405; + soap->fopt = http_200; + soap->fhead = http_200; soap->fform = NULL; soap->fposthdr = http_post_header; soap->fresponse = http_response; @@ -8611,6 +8762,8 @@ soap_init(struct soap *soap) soap->fault = NULL; soap->master = SOAP_INVALID_SOCKET; soap->socket = SOAP_INVALID_SOCKET; + soap->sendsk = SOAP_INVALID_SOCKET; + soap->recvsk = SOAP_INVALID_SOCKET; soap->os = NULL; soap->is = NULL; #ifndef WITH_LEANER @@ -8639,7 +8792,6 @@ soap_init(struct soap *soap) soap->proxy_port = 8080; soap->proxy_userid = NULL; soap->proxy_passwd = NULL; - soap->authrealm = NULL; soap->prolog = NULL; #ifdef WITH_ZLIB soap->zlib_state = SOAP_ZLIB_NONE; @@ -8709,7 +8861,11 @@ soap_init(struct soap *soap) soap->rsa_params = NULL; #endif #ifdef WITH_C_LOCALE +# ifdef WIN32 + soap->c_locale = _create_locale(LC_ALL, "C"); +# else soap->c_locale = newlocale(LC_ALL_MASK, "C", NULL); +# endif #else soap->c_locale = NULL; #endif @@ -8726,6 +8882,7 @@ soap_init(struct soap *soap) soap->ns = 0; soap->part = SOAP_END; soap->event = 0; + soap->evlev = 0; soap->alloced = 0; soap->count = 0; soap->length = 0; @@ -8740,28 +8897,6 @@ soap_init(struct soap *soap) #endif /******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_init1(struct soap *soap, soap_mode mode) -{ soap_init2(soap, mode, mode); -} -#endif - -/******************************************************************************/ -#ifndef PALM_1 -SOAP_FMAC1 -void -SOAP_FMAC2 -soap_init2(struct soap *soap, soap_mode imode, soap_mode omode) -{ soap_init(soap); - soap_imode(soap, imode); - soap_omode(soap, omode); -} -#endif - -/******************************************************************************/ #ifndef PALM_2 SOAP_FMAC1 void @@ -8772,7 +8907,6 @@ soap_begin(struct soap *soap) { soap->buflen = 0; soap->bufidx = 0; } - soap->keep_alive = (((soap->imode | soap->omode) & SOAP_IO_KEEPALIVE) != 0); soap->null = 0; soap->position = 0; soap->encoding = 0; @@ -8781,6 +8915,7 @@ soap_begin(struct soap *soap) soap->ns = 0; soap->part = SOAP_END; soap->event = 0; + soap->evlev = 0; soap->alloced = 0; soap->count = 0; soap->length = 0; @@ -8903,6 +9038,8 @@ soap_set_local_namespaces(struct soap *soap) soap->version = 2; } soap->local_namespaces = ns2; + for (; ns2->id; ns2++) + ns2->out = NULL; } } } @@ -8976,7 +9113,7 @@ soap_push_ns(struct soap *soap, const char *id, const char *ns, short utilized) return NULL; } } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Adding namespace binding (level=%u) '%s' '%s' utilized=%d\n", soap->level, id, ns?ns:"(null)", utilized)); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Adding namespace binding (level=%u) '%s' '%s' utilized=%d\n", soap->level, id, ns ? ns : "(null)", utilized)); n = strlen(id); if (ns) k = strlen(ns); @@ -8989,9 +9126,9 @@ soap_push_ns(struct soap *soap, const char *id, const char *ns, short utilized) } np->next = soap->nlist; soap->nlist = np; - strcpy(np->id, id); + strcpy((char*)np->id, id); if (ns) - np->ns = strcpy(np->id + n + 1, ns); + np->ns = strcpy((char*)np->id + n + 1, ns); else np->ns = NULL; np->level = soap->level; @@ -9003,8 +9140,13 @@ soap_push_ns(struct soap *soap, const char *id, const char *ns, short utilized) /******************************************************************************/ #ifndef WITH_LEAN static void -soap_utilize_ns(struct soap *soap, const char *tag, size_t n) -{ register struct soap_nlist *np = soap_lookup_ns(soap, tag, n); +soap_utilize_ns(struct soap *soap, const char *tag) +{ register struct soap_nlist *np; + size_t n = 0; + const char *t = strchr(tag, ':'); + if (t) + n = t - tag; + np = soap_lookup_ns(soap, tag, n); DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Utilizing namespace of '%s'\n", tag)); if (np) { if (np->index == 0) @@ -9028,7 +9170,8 @@ soap_element(struct soap *soap, const char *tag, int id, const char *type) #ifndef WITH_LEAN register const char *s; #endif - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Element begin tag='%s' id='%d' type='%s'\n", tag, id, type?type:SOAP_STR_EOS)); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Element begin tag='%s' level='%u' id='%d' type='%s'\n", tag, soap->level, id, type ? type : SOAP_STR_EOS)); + soap->level++; #ifdef WITH_DOM #ifndef WITH_LEAN if (soap->wsuid && soap_tagsearch(soap->wsuid, tag)) @@ -9039,12 +9182,20 @@ soap_element(struct soap *soap, const char *tag, int id, const char *type) if (soap_set_attr(soap, "wsu:Id", soap->tag, 1)) return soap->error; } - if (soap->event == SOAP_SEC_BEGIN && (soap->mode & SOAP_XML_CANONICAL) && !(soap->mode & SOAP_DOM_ASIS)) - { register struct soap_nlist *np; - /* wsu:Id found: clear xmlns renderings, so re-emit them for exc-c14n */ - for (np = soap->nlist; np; np = np->next) - { if (np->index == 2) - np->index = 0; + if ((soap->mode & SOAP_XML_CANONICAL) && !(soap->mode & SOAP_DOM_ASIS)) + { if (soap->evlev >= soap->level) + soap->evlev = 0; + if (soap->event == SOAP_SEC_BEGIN && !soap->evlev) + { register struct soap_nlist *np; + /* non-nested wsu:Id found: clear xmlns, re-emit them for exc-c14n */ + for (np = soap->nlist; np; np = np->next) + { if (np->index == 2) + { struct soap_nlist *np1 = soap_push_ns(soap, np->id, np->ns, 1); + if (np1) + np1->index = 0; + } + } + soap->evlev = soap->level; } } #endif @@ -9080,7 +9231,6 @@ soap_element(struct soap *soap, const char *tag, int id, const char *type) else { #endif - soap->level++; #ifndef WITH_LEAN if (!soap->ns) { if (!(soap->mode & SOAP_XML_CANONICAL) @@ -9135,26 +9285,30 @@ soap_element(struct soap *soap, const char *tag, int id, const char *type) soap->ns = 1; /* namespace table control: ns = 0 or 2 to start, then 1 to stop dumping the table */ #ifndef WITH_LEAN if (soap->mode & SOAP_XML_CANONICAL) - { const char *t = strchr(tag, ':'); - if (t) - soap_utilize_ns(soap, tag, t - tag); - } + soap_utilize_ns(soap, tag); #endif if (id > 0) { sprintf(soap->tmpbuf, "_%d", id); if (soap_attribute(soap, "id", soap->tmpbuf)) return soap->error; } - if (type && *type && soap->part != SOAP_IN_HEADER) /* TODO: filter Header? */ - { if (soap_attribute(soap, "xsi:type", type)) - return soap->error; + if (type && *type && !(soap->mode & SOAP_XML_NOTYPE) && soap->part != SOAP_IN_HEADER) + { const char *t = type; #ifndef WITH_LEAN - if (soap->mode & SOAP_XML_CANONICAL) - { const char *t = strchr(type, ':'); + if (soap->mode & SOAP_XML_DEFAULTNS) + { t = strchr(type, ':'); if (t) - soap_utilize_ns(soap, type, t - type); + t++; + else + t = type; } #endif + if (soap->attributes ? soap_set_attr(soap, "xsi:type", t, 1) : soap_attribute(soap, "xsi:type", t)) + return soap->error; +#ifndef WITH_LEAN + if (soap->mode & SOAP_XML_CANONICAL) + soap_utilize_ns(soap, type); +#endif } if (soap->null && soap->position > 0) { register int i; @@ -9189,8 +9343,8 @@ soap_element(struct soap *soap, const char *tag, int id, const char *type) } soap->null = 0; soap->position = 0; - if (soap->event == SOAP_SEC_BEGIN && (soap->mode & SOAP_XML_CANONICAL)) - soap->event = SOAP_SEC_SIGN; + if (soap->event == SOAP_SEC_BEGIN) + soap->event = 0; return SOAP_OK; } #endif @@ -9358,10 +9512,7 @@ soap_array_begin_out(struct soap *soap, const char *tag, int id, const char *typ } #ifndef WITH_LEAN if ((soap->mode & SOAP_XML_CANONICAL)) - { const char *s = strchr(type, ':'); - if (s) - soap_utilize_ns(soap, type, s - type); - } + soap_utilize_ns(soap, type); #endif return soap_element_start_end_out(soap, NULL); } @@ -9379,14 +9530,11 @@ soap_element_start_end_out(struct soap *soap, const char *tag) { struct soap_nlist *np; for (tp = soap->attributes; tp; tp = tp->next) { if (tp->visible && tp->name) - { const char *s = strchr(tp->name, ':'); - if (s) - soap_utilize_ns(soap, tp->name, s - tp->name); - } + soap_utilize_ns(soap, tp->name); } for (np = soap->nlist; np; np = np->next) { if (np->index == 1 && np->ns) - { sprintf(soap->tmpbuf, "xmlns:%s", np->id); + { sprintf(soap->tmpbuf, *(np->id) ? "xmlns:%s" : "xmlns", np->id); DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Enabling utilized binding (level=%u) %s='%s'\n", np->level, soap->tmpbuf, np->ns)); soap_set_attr(soap, soap->tmpbuf, np->ns, 1); np->index = 2; @@ -9636,6 +9784,7 @@ soap_check_result(struct soap *soap, const char *tag) { soap_instring(soap, ":result", NULL, NULL, 0, 2, -1, -1); /* just ignore content for compliance reasons, but should compare tag to element's QName value? */ } + (void)tag; } #endif @@ -9664,16 +9813,9 @@ soap_attribute(struct soap *soap, const char *name, const char *value) #endif #ifndef WITH_LEAN if (soap->mode & SOAP_XML_CANONICAL) - { /* TODO: consider using this code to handle default namespace bindings + { /* push namespace */ if (!strncmp(name, "xmlns", 5) && (name[5] == ':' || name[5] == '\0')) - { if (name[5] == ':') - soap_push_ns(soap, name + 6, value, 0); - else - soap_push_ns(soap, "", value, 0); - } - */ - if (!strncmp(name, "xmlns:", 6)) - soap_push_ns(soap, name + 6, value, 0); + soap_push_ns(soap, name + 5 + (name[5] == ':'), value, 0); else if (soap_set_attr(soap, name, value, 1)) return soap->error; } @@ -9710,7 +9852,8 @@ soap_element_begin_in(struct soap *soap, const char *tag, int nillable, const ch return soap->error = SOAP_NULL; if (soap->body) soap->level++; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Begin element found (level=%u) '%s'='%s'\n", soap->level, soap->tag, tag?tag:SOAP_STR_EOS )); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Begin element found (level=%u) '%s'='%s'\n", soap->level, soap->tag, tag ? tag : SOAP_STR_EOS )); + soap->error = SOAP_OK; } } else if (soap->error == SOAP_NO_TAG && tag && *tag == '-') @@ -9749,7 +9892,7 @@ soap_element_end_in(struct soap *soap, const char *tag) do { while (((c = soap_get(soap)) != SOAP_TT)) { if ((int)c == EOF) - return soap->error = SOAP_EOF; + return soap->error = SOAP_CHK_EOF; if (c == SOAP_LT) n++; else if (c == '/') @@ -9769,7 +9912,7 @@ soap_element_end_in(struct soap *soap, const char *tag) } *s = '\0'; if ((int)c == EOF) - return soap->error = SOAP_EOF; + return soap->error = SOAP_CHK_EOF; while (soap_blank(c)) c = soap_get(soap); if (c != SOAP_GT) @@ -9784,12 +9927,12 @@ soap_element_end_in(struct soap *soap, const char *tag) if (tag && (soap->mode & SOAP_XML_STRICT)) { soap_pop_namespace(soap); if (soap_match_tag(soap, soap->tag, tag)) - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End element tag '%s' does not match '%s'\n", soap->tag, tag?tag:SOAP_STR_EOS)); + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End element tag '%s' does not match '%s'\n", soap->tag, tag ? tag : SOAP_STR_EOS)); return soap->error = SOAP_SYNTAX_ERROR; } } #endif - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End element found (level=%u) '%s'='%s'\n", soap->level, soap->tag, tag?tag:SOAP_STR_EOS)); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "End element found (level=%u) '%s'='%s'\n", soap->level, soap->tag, tag ? tag : SOAP_STR_EOS)); soap->level--; return SOAP_OK; } @@ -9831,7 +9974,7 @@ soap_set_attr(struct soap *soap, const char *name, const char *value, int flag) { register struct soap_attribute *tp; if (*name == '-') return SOAP_OK; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Set attribute %s='%s'\n", name, value?value:SOAP_STR_EOS)); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Set attribute %s='%s'\n", name, value ? value : SOAP_STR_EOS)); for (tp = soap->attributes; tp; tp = tp->next) { if (!strcmp(tp->name, name)) break; @@ -9883,7 +10026,7 @@ soap_set_attr(struct soap *soap, const char *name, const char *value, int flag) { tp->next = soap->attributes; soap->attributes = tp; } - strcpy(tp->name, name); + strcpy((char*)tp->name, name); tp->value = NULL; } else if (tp->visible) @@ -9906,9 +10049,9 @@ soap_set_attr(struct soap *soap, const char *name, const char *value, int flag) if (!strncmp(tp->name, "xmlns:", 6)) tp->ns = tp->value; tp->visible = 2; - tp->flag = flag; + tp->flag = (short)flag; #ifndef WITH_LEAN - if (soap->event != SOAP_SEC_SIGN && !strcmp(name, "wsu:Id")) + if (!strcmp(name, "wsu:Id")) { soap->event = SOAP_SEC_BEGIN; strncpy(soap->id, value, sizeof(soap->id)); soap->id[sizeof(soap->id)-1] = '\0'; @@ -9996,7 +10139,7 @@ soap_getattrval(struct soap *soap, char *s, size_t n, soap_wchar d) } default: if ((int)c == EOF) - return soap->error = SOAP_EOF; + return soap->error = SOAP_CHK_EOF; *s++ = (char)c; } } @@ -10085,8 +10228,19 @@ soap_peek_element(struct soap *soap) soap->position = 0; soap->null = 0; soap->mustUnderstand = 0; - /* skip BOM */ - if ((c = soap_getchar(soap)) != 0xEF || (c = soap_get1(soap)) != 0xBB || (c = soap_get1(soap)) != 0xBF) + /* UTF-8 BOM? */ + c = soap_getchar(soap); + if (c == 0xEF && soap_get0(soap) == 0xBB) + { c = soap_get1(soap); + if ((c = soap_get1(soap)) == 0xBF) + soap->mode &= ~SOAP_ENC_LATIN; + else + soap_unget(soap, (0x0F << 12) | (0xBB << 6) | (c & 0x3F)); /* UTF-8 */ + } + else if ((c == 0xFE && soap_get0(soap) == 0xFF) /* UTF-16 BE */ + || (c == 0xFF && soap_get0(soap) == 0xFE)) /* UTF-16 LE */ + return soap->error = SOAP_UTF_ERROR; + else soap_unget(soap, c); c = soap_get(soap); #ifdef WITH_DOM @@ -10116,7 +10270,7 @@ soap_peek_element(struct soap *soap) if (c != SOAP_LT) { *soap->tag = '\0'; if ((int)c == EOF) - return soap->error = SOAP_EOF; + return soap->error = SOAP_CHK_EOF; soap_unget(soap, c > 0 ? c | 0x80000000 : c); #ifdef WITH_DOM /* whitespace leading to end tag is significant for DOM */ @@ -10221,7 +10375,7 @@ soap_peek_element(struct soap *soap) { tp = (struct soap_attribute*)SOAP_MALLOC(soap, sizeof(struct soap_attribute) + strlen(soap->tmpbuf)); if (!tp) return soap->error = SOAP_EOM; - strcpy(tp->name, soap->tmpbuf); + strcpy((char*)tp->name, soap->tmpbuf); tp->value = NULL; tp->size = 0; tp->ns = NULL; @@ -10254,6 +10408,7 @@ soap_peek_element(struct soap *soap) return soap->error; if (tp->value) SOAP_FREE(soap, tp->value); + tp->value = NULL; for (;;) { if (soap_getattrval(soap, soap->labbuf + soap->labidx, soap->lablen - soap->labidx, c)) { if (soap->error != SOAP_EOM) @@ -10333,7 +10488,7 @@ soap_peek_element(struct soap *soap) } #endif if ((int)c == EOF) - return soap->error = SOAP_EOF; + return soap->error = SOAP_CHK_EOF; if (!(soap->body = (c != '/'))) do c = soap_get1(soap); while (soap_blank(c)); @@ -10342,8 +10497,6 @@ soap_peek_element(struct soap *soap) { if (!soap->body && soap->dom->prnt) soap->dom = soap->dom->prnt; } - if (soap->feltbegin) - return soap->error = soap->feltbegin(soap, soap->tag); #endif for (tp = soap->attributes; tp; tp = tp->next) { if (tp->visible && tp->value) @@ -10436,6 +10589,10 @@ soap_peek_element(struct soap *soap) } } } +#ifdef WITH_DOM + if (soap->feltbegin) + return soap->error = soap->feltbegin(soap, soap->tag); +#endif return soap->error = SOAP_OK; } #endif @@ -10536,7 +10693,7 @@ soap_string_out(struct soap *soap, const char *s, int flag) if (soap->mode & SOAP_C_MBSTRING) { wchar_t wc; register int m = mbtowc(&wc, t - 1, MB_CUR_MAX); - if (m > 0 && (soap_wchar)wc != c) + if (m > 0 && !((soap_wchar)wc == c && m == 1 && c < 0x80)) { if (soap_send_raw(soap, s, t - s - 1) || soap_pututf8(soap, wc)) return soap->error; s = t += m - 1; @@ -10649,11 +10806,11 @@ soap_string_in(struct soap *soap, int flag, long minlen, long maxlen) if ((int)c == EOF) goto end; if ((c >= 0x80 || c < SOAP_AP) && state != 1 && !(soap->mode & SOAP_ENC_LATIN)) - { if (c >= 0x80) + { if ((c & 0x7FFFFFFF) >= 0x80) { soap_unget(soap, c); c = soap_getutf8(soap); } - if (soap->mode & SOAP_C_UTFSTRING) + if ((c & 0x7FFFFFFF) >= 0x80 && (soap->mode & SOAP_C_UTFSTRING)) { c &= 0x7FFFFFFF; t = buf; if (c < 0x0800) @@ -10688,17 +10845,17 @@ soap_string_in(struct soap *soap, int flag, long minlen, long maxlen) { case 1: if (c == ']') state = 4; - *s++ = c; + *s++ = (char)c; continue; case 2: if (c == '-') state = 6; - *s++ = c; + *s++ = (char)c; continue; case 3: if (c == '?') state = 8; - *s++ = c; + *s++ = (char)c; continue; /* CDATA */ case 4: @@ -10706,14 +10863,14 @@ soap_string_in(struct soap *soap, int flag, long minlen, long maxlen) state = 5; else state = 1; - *s++ = c; + *s++ = (char)c; continue; case 5: if (c == '>') state = 0; else state = 1; - *s++ = c; + *s++ = (char)c; continue; /* comment */ case 6: @@ -10721,14 +10878,14 @@ soap_string_in(struct soap *soap, int flag, long minlen, long maxlen) state = 7; else state = 2; - *s++ = c; + *s++ = (char)c; continue; case 7: if (c == '>') state = 0; else state = 2; - *s++ = c; + *s++ = (char)c; continue; /* PI */ case 8: @@ -10736,7 +10893,7 @@ soap_string_in(struct soap *soap, int flag, long minlen, long maxlen) state = 0; else state = 3; - *s++ = c; + *s++ = (char)c; continue; } switch (c) @@ -10830,7 +10987,7 @@ soap_string_in(struct soap *soap, int flag, long minlen, long maxlen) #ifndef WITH_LEANER #ifdef HAVE_WCTOMB if (soap->mode & SOAP_C_MBSTRING) - { m = wctomb(buf, c & 0x7FFFFFFF); + { m = wctomb(buf, (wchar_t)(c & 0x7FFFFFFF)); if (m >= 1 && m <= (int)MB_CUR_MAX) { t = buf; *s++ = *t++; @@ -11001,7 +11158,7 @@ soap_string_in(struct soap *soap, int flag, long minlen, long maxlen) #ifndef WITH_LEANER #ifdef HAVE_WCTOMB if (soap->mode & SOAP_C_MBSTRING) - { m = wctomb(buf, c & 0x7FFFFFFF); + { m = wctomb(buf, (wchar_t)(c & 0x7FFFFFFF)); if (m >= 1 && m <= (int)MB_CUR_MAX) { t = buf; *s++ = *t++; @@ -11266,7 +11423,7 @@ soap_wstring_in(struct soap *soap, int flag, long minlen, long maxlen) if ((int)c == EOF) goto end; if (sizeof(wchar_t) < 4 && c > 0xFFFF) - { wchar_t c1, c2; + { soap_wchar c1, c2; /* http://unicode.org/faq/utf_bom.html#utf16-2 */ c1 = 0xD800 - (0x10000 >> 10) + (c >> 10); c2 = 0xDC00 + (c & 0x3FF); @@ -11511,7 +11668,7 @@ soap_s2LONG64(struct soap *soap, const char *s, LONG64 *p) soap_reset_errno; #endif #endif - *p = strtoll(s, &r, 10); + *p = soap_strtoll(s, &r, 10); if (s == r || *r #ifndef WITH_NOIO #ifndef WITH_LEAN @@ -11726,7 +11883,11 @@ soap_float2s(struct soap *soap, float n) return "-INF"; s = soap->tmpbuf; #if defined(HAVE_SPRINTF_L) +# ifdef WIN32 + _sprintf_s_l(s, _countof(soap->tmpbuf), soap->float_format, soap->c_locale, n); +# else sprintf_l(s, soap->c_locale, soap->float_format, n); +# endif #else sprintf(s, soap->float_format, n); s = strchr(s, ','); /* convert decimal comma to DP */ @@ -11772,7 +11933,11 @@ soap_s2float(struct soap *soap, const char *s, float *p) /* On some systems strtof requires -std=c99 or does not even link: so we try to use strtod first */ #if defined(HAVE_STRTOD_L) char *r; +# ifdef WIN32 + *p = (float)_strtod_l(s, &r, soap->c_locale); +# else *p = (float)strtod_l(s, &r, soap->c_locale); +# endif if (*r) #elif defined(HAVE_STRTOD) char *r; @@ -11872,7 +12037,11 @@ soap_double2s(struct soap *soap, double n) return "-INF"; s = soap->tmpbuf; #if defined(HAVE_SPRINTF_L) +# ifdef WIN32 + _sprintf_s_l(s, _countof(soap->tmpbuf), soap->double_format, soap->c_locale, n); +# else sprintf_l(s, soap->c_locale, soap->double_format, n); +# endif #else sprintf(s, soap->double_format, n); s = strchr(s, ','); /* convert decimal comma to DP */ @@ -11917,7 +12086,11 @@ soap_s2double(struct soap *soap, const char *s, double *p) { #if defined(HAVE_STRTOD_L) char *r; +# ifdef WIN32 + *p = _strtod_l(s, &r, soap->c_locale); +# else *p = strtod_l(s, &r, soap->c_locale); +# endif if (*r) #elif defined(HAVE_STRTOD) char *r; @@ -12313,7 +12486,7 @@ soap_s2ULONG64(struct soap *soap, const char *s, ULONG64 *p) soap_reset_errno; #endif #endif - *p = strtoull(s, &r, 10); + *p = soap_strtoull(s, &r, 10); if ((s == r && (soap->mode & SOAP_XML_STRICT)) || *r #ifndef WITH_NOIO #ifndef WITH_LEAN @@ -12414,7 +12587,7 @@ soap_s2QName(struct soap *soap, const char *s, char **t, long minlen, long maxle break; /* find next QName */ n = 1; - while (s[n] && !soap_blank(s[n])) + while (s[n] && !soap_blank((soap_wchar)s[n])) n++; np = soap->nlist; /* if there is no namespace stack, or prefix is "xml" then copy string */ @@ -12455,7 +12628,7 @@ soap_s2QName(struct soap *soap, const char *s, char **t, long minlen, long maxle soap_append_lab(soap, "\"", 1); } else - { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "\nNamespace prefix of '%s' not defined (index=%d, URI=%s)\n", s, np->index, np->ns?np->ns:SOAP_STR_EOS)); + { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "\nNamespace prefix of '%s' not defined (index=%d, URI=%s)\n", s, np->index, np->ns ? np->ns : SOAP_STR_EOS)); return soap->error = SOAP_NAMESPACE; } } @@ -12506,10 +12679,7 @@ soap_QName2s(struct soap *soap, const char *s) { soap_append_lab(soap, s, n); #ifndef WITH_LEAN if ((soap->mode & SOAP_XML_CANONICAL)) - { const char *r = strchr(s, ':'); - if (r) - soap_utilize_ns(soap, s, r - s); - } + soap_utilize_ns(soap, s); #endif } else /* URL-based string prefix */ @@ -12688,7 +12858,8 @@ SOAP_FMAC1 char ** SOAP_FMAC2 soap_instring(struct soap *soap, const char *tag, char **p, const char *type, int t, int flag, long minlen, long maxlen) -{ if (soap_element_begin_in(soap, tag, 1, NULL)) +{ (void)type; + if (soap_element_begin_in(soap, tag, 1, NULL)) { if (!tag || *tag != '-' || soap->error != SOAP_NO_TAG) return NULL; soap->error = SOAP_OK; @@ -12754,7 +12925,8 @@ SOAP_FMAC1 wchar_t ** SOAP_FMAC2 soap_inwstring(struct soap *soap, const char *tag, wchar_t **p, const char *type, int t, long minlen, long maxlen) -{ if (soap_element_begin_in(soap, tag, 1, NULL)) +{ (void)type; + if (soap_element_begin_in(soap, tag, 1, NULL)) { if (!tag || *tag != '-' || soap->error != SOAP_NO_TAG) return NULL; soap->error = SOAP_OK; @@ -13217,7 +13389,7 @@ soap_getline(struct soap *soap, char *s, int len) if (c == '\r' || c == '\n') break; if ((int)c == EOF) - return soap->error = SOAP_EOF; + return soap->error = SOAP_CHK_EOF; *s++ = (char)c; } if (c != '\n') @@ -13231,7 +13403,7 @@ soap_getline(struct soap *soap, char *s, int len) break; } else if ((int)c == EOF) - return soap->error = SOAP_EOF; + return soap->error = SOAP_CHK_EOF; if (i < 0) return soap->error = SOAP_HDR; } @@ -13346,7 +13518,7 @@ SOAP_FMAC2 soap_putdimehdr(struct soap *soap) { unsigned char tmp[12]; size_t optlen = 0, idlen = 0, typelen = 0; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Put DIME header id='%s'\n", soap->dime.id?soap->dime.id:SOAP_STR_EOS)); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Put DIME header id='%s'\n", soap->dime.id ? soap->dime.id : SOAP_STR_EOS)); if (soap->dime.options) optlen = (((unsigned char)soap->dime.options[2] << 8) | ((unsigned char)soap->dime.options[3])) + 4; if (soap->dime.id) @@ -13442,7 +13614,7 @@ soap_putdime(struct soap *soap) bufsize = sizeof(soap->tmpbuf); if (!(bufsize = soap->fdimeread(soap, handle, soap->tmpbuf, bufsize))) { DBGLOG(TEST, SOAP_MESSAGE(fdebug, "fdimeread failed: insufficient data (%lu bytes remaining from %lu bytes)\n", (unsigned long)size, (unsigned long)content->size)); - soap->error = SOAP_EOF; + soap->error = SOAP_CHK_EOF; break; } if (soap_send_raw(soap, soap->tmpbuf, bufsize)) @@ -13484,7 +13656,7 @@ soap_getdimefield(struct soap *soap, size_t n) { s = p; for (i = n; i > 0; i--) { if ((int)(c = soap_get1(soap)) == EOF) - { soap->error = SOAP_EOF; + { soap->error = SOAP_CHK_EOF; return NULL; } *s++ = (char)c; @@ -13518,7 +13690,7 @@ soap_getdimehdr(struct soap *soap) DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Get DIME header\n")); if (soap->dime.buflen || soap->dime.chunksize) { if (soap_move(soap, (long)(soap->dime.size - soap_tell(soap)))) - return soap->error = SOAP_EOF; + return soap->error = SOAP_CHK_EOF; soap_unget(soap, soap_getchar(soap)); /* skip padding and get hdr */ DBGLOG(TEST, SOAP_MESSAGE(fdebug, "... From chunked\n")); return SOAP_OK; @@ -13526,7 +13698,7 @@ soap_getdimehdr(struct soap *soap) s = (char*)tmp; for (i = 12; i > 0; i--) { if ((int)(c = soap_getchar(soap)) == EOF) - return soap->error = SOAP_EOF; + return soap->error = SOAP_CHK_EOF; *s++ = (char)c; } if ((tmp[0] & 0xF8) != SOAP_DIME_VERSION) @@ -13543,7 +13715,7 @@ soap_getdimehdr(struct soap *soap) return soap->error; if (!(soap->dime.type = soap_getdimefield(soap, typelen)) && soap->error) return soap->error; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "DIME id=%s, type=%s, options=%s\n", soap->dime.id?soap->dime.id:SOAP_STR_EOS, soap->dime.type?soap->dime.type:"", soap->dime.options?soap->dime.options+4:SOAP_STR_EOS)); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "DIME id=%s, type=%s, options=%s\n", soap->dime.id ? soap->dime.id : SOAP_STR_EOS, soap->dime.type ? soap->dime.type : "", soap->dime.options ? soap->dime.options+4 : SOAP_STR_EOS)); if (soap->dime.flags & SOAP_DIME_ME) soap->mode &= ~SOAP_ENC_DIME; return SOAP_OK; @@ -13795,7 +13967,7 @@ soap_get_mime_attachment(struct soap *soap, void *handle) return NULL; } } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Parsing MIME content id=%s type=%s\n", content->id?content->id:SOAP_STR_EOS, content->type?content->type:SOAP_STR_EOS)); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Parsing MIME content id=%s type=%s\n", content->id ? content->id : SOAP_STR_EOS, content->type ? content->type : SOAP_STR_EOS)); if (!content->ptr && soap_new_block(soap) == NULL) { soap->error = SOAP_EOM; return NULL; @@ -13816,7 +13988,7 @@ soap_get_mime_attachment(struct soap *soap, void *handle) { if (!flag) { c = soap_get1(soap); if ((int)c == EOF) - { soap->error = SOAP_EOF; + { soap->error = SOAP_CHK_EOF; return NULL; } } @@ -13829,7 +14001,7 @@ soap_get_mime_attachment(struct soap *soap, void *handle) do c = soap_getchar(soap); while (c == *t++); if ((int)c == EOF) - { soap->error = SOAP_EOF; + { soap->error = SOAP_CHK_EOF; return NULL; } if (!*--t) @@ -13954,7 +14126,7 @@ int SOAP_FMAC2 soap_putmimehdr(struct soap *soap, struct soap_multipart *content) { const char *s; - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "MIME attachment type=%s\n", content->type?content->type:SOAP_STR_EOS)); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "MIME attachment type=%s\n", content->type ? content->type : SOAP_STR_EOS)); if (soap_send3(soap, "\r\n--", soap->mime.boundary, "\r\n")) return soap->error; if (content->type && soap_send3(soap, "Content-Type: ", content->type, "\r\n")) @@ -14245,7 +14417,7 @@ soap_getgziphdr(struct soap *soap) DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Get gzip header\n")); for (i = 0; i < 9; i++) { if ((int)(c = soap_get1(soap) == EOF)) - return soap->error = SOAP_EOF; + return soap->error = SOAP_ZLIB_ERROR; if (i == 1 && c == 8) soap->z_dict = 0; if (i == 2) @@ -14254,7 +14426,7 @@ soap_getgziphdr(struct soap *soap) if (f & 0x04) /* FEXTRA */ { for (i = soap_get1(soap) | (soap_get1(soap) << 8); i; i--) { if ((int)soap_get1(soap) == EOF) - return soap->error = SOAP_EOF; + return soap->error = SOAP_ZLIB_ERROR; } } if (f & 0x08) /* skip FNAME */ @@ -14272,7 +14444,7 @@ soap_getgziphdr(struct soap *soap) c = soap_get1(soap); } if ((int)c == EOF) - return soap->error = SOAP_EOF; + return soap->error = SOAP_ZLIB_ERROR; return SOAP_OK; } #endif @@ -14292,7 +14464,10 @@ soap_begin_serve(struct soap *soap) } #endif soap_begin(soap); - if (soap_begin_recv(soap)) + if (soap_begin_recv(soap) + || soap_envelope_begin_in(soap) + || soap_recv_header(soap) + || soap_body_begin_in(soap)) { if (soap->error < SOAP_STOP) { #ifdef WITH_FASTCGI @@ -14303,10 +14478,6 @@ soap_begin_serve(struct soap *soap) } return soap_closesock(soap); } - if (soap_envelope_begin_in(soap) - || soap_recv_header(soap) - || soap_body_begin_in(soap)) - return soap->error; return SOAP_OK; } #endif @@ -14317,7 +14488,7 @@ SOAP_FMAC1 int SOAP_FMAC2 soap_begin_recv(struct soap *soap) -{ soap_wchar c; +{ register soap_wchar c; DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Initializing for input\n")); soap->error = SOAP_OK; soap->filterstop = SOAP_OK; @@ -14350,6 +14521,7 @@ soap_begin_recv(struct soap *soap) soap->header = NULL; soap->fault = NULL; soap->status = 0; + soap->fform = NULL; #ifndef WITH_LEANER soap->dom = NULL; soap->dime.chunksize = 0; @@ -14366,7 +14538,7 @@ soap_begin_recv(struct soap *soap) #ifdef WIN32 #ifndef UNDER_CE #ifndef WITH_FASTCGI - if (!soap_valid_socket(soap->socket)) + if (!soap_valid_socket(soap->socket) && !soap->is) /* Set win32 stdout or soap->sendfd to BINARY, e.g. to support DIME */ #ifdef __BORLANDC__ setmode(soap->recvfd, _O_BINARY); #else @@ -14433,14 +14605,24 @@ soap_begin_recv(struct soap *soap) else #endif { /* skip BOM */ - if (c == 0xEF && (c = soap_getchar(soap)) == 0xBB && (c = soap_getchar(soap)) == 0xBF) - c = soap_getchar(soap); + if (c == 0xEF && soap_get0(soap) == 0xBB) + { c = soap_get1(soap); + if ((c = soap_get1(soap)) == 0xBF) + { soap->mode &= ~SOAP_ENC_LATIN; + c = soap_getchar(soap); + } + else + c = (0x0F << 12) | (0xBB << 6) | (c & 0x3F); /* UTF-8 */ + } + else if ((c == 0xFE && soap_get0(soap) == 0xFF) /* UTF-16 BE */ + || (c == 0xFF && soap_get0(soap) == 0xFE)) /* UTF-16 LE */ + return soap->error = SOAP_UTF_ERROR; /* skip space */ while (soap_blank(c)) c = soap_getchar(soap); } if ((int)c == EOF) - return soap->error = SOAP_EOF; + return soap->error = SOAP_CHK_EOF; soap_unget(soap, c); #ifndef WITH_NOHTTP /* if not XML or MIME/DIME/ZLIB, assume HTTP header */ @@ -14453,7 +14635,13 @@ soap_begin_recv(struct soap *soap) return soap->error; } if (soap->error == SOAP_STOP) + { if (soap->fform) + { soap->error = soap->fform(soap); + if (soap->error == SOAP_OK) + soap->error = SOAP_STOP; /* prevents further processing */ + } return soap->error; + } soap->mode = soap->imode; /* if imode is changed, effectuate */ soap->imode = m; /* restore imode */ #ifdef WITH_ZLIB @@ -14532,7 +14720,7 @@ soap_begin_recv(struct soap *soap) if (soap->mode & SOAP_ENC_MIME) { do /* skip preamble */ { if ((int)(c = soap_getchar(soap)) == EOF) - return soap->error = SOAP_EOF; + return soap->error = SOAP_CHK_EOF; } while (c != '-' || soap_get0(soap) != '-'); soap_unget(soap, c); if (soap_getmimehdr(soap)) @@ -14614,7 +14802,8 @@ SOAP_FMAC1 int SOAP_FMAC2 soap_envelope_end_out(struct soap *soap) -{ if (soap_element_end_out(soap, "SOAP-ENV:Envelope") || soap_send_raw(soap, "\r\n", 2)) /* 2.8: always emit \r\n after SOAP Envelope */ +{ if (soap_element_end_out(soap, "SOAP-ENV:Envelope") + || soap_send_raw(soap, "\r\n", 2)) /* 2.8: always emit \r\n */ return soap->error; #ifndef WITH_LEANER if ((soap->mode & SOAP_IO_LENGTH) && (soap->mode & SOAP_ENC_DIME) && !(soap->mode & SOAP_ENC_MTOM)) @@ -14959,23 +15148,32 @@ soap_try_connect_command(struct soap *soap, int http_command, const char *endpoi } else #endif + soap->action = soap_strdup(soap, action); if (soap->fopen && *soap->host) { if (!soap->keep_alive || !soap_valid_socket(soap->socket) || strcmp(soap->host, host) || soap->port != port || !soap->fpoll || soap->fpoll(soap)) { soap->error = SOAP_OK; - soap->keep_alive = 0; /* to force close */ - soap->omode &= ~SOAP_IO_UDP; /* to force close */ - soap_closesock(soap); - DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Connect/reconnect to host='%s' path='%s' port=%d\n", soap->host, soap->path, soap->port)); #ifndef WITH_LEAN if (!strncmp(endpoint, "soap.udp:", 9)) soap->omode |= SOAP_IO_UDP; + else #endif - soap->socket = soap->fopen(soap, endpoint, soap->host, soap->port); - if (soap->error) - return soap->error; - soap->keep_alive = ((soap->omode & SOAP_IO_KEEPALIVE) != 0); + { soap->keep_alive = 0; /* to force close */ + soap->omode &= ~SOAP_IO_UDP; /* to force close */ + } + soap_closesock(soap); + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "Connect/reconnect to '%s' host='%s' path='%s' port=%d\n", endpoint?endpoint:"(null)", soap->host, soap->path, soap->port)); + if (!soap->keep_alive || !soap_valid_socket(soap->socket)) + { soap->socket = soap->fopen(soap, endpoint, soap->host, soap->port); + if (soap->error) + return soap->error; + soap->keep_alive = ((soap->omode & SOAP_IO_KEEPALIVE) != 0); + } } } +#ifdef WITH_NTLM + if (soap_ntlm_handshake(soap, SOAP_GET, endpoint, soap->host, soap->port)) + return soap->error; +#endif count = soap_count_attachments(soap); if (soap_begin_send(soap)) return soap->error; @@ -14984,7 +15182,6 @@ soap_try_connect_command(struct soap *soap, int http_command, const char *endpoi soap->mode |= SOAP_IO_BUFFER; } #ifndef WITH_NOHTTP - soap->action = soap_strdup(soap, action); if ((soap->mode & SOAP_IO) != SOAP_IO_STORE && !(soap->mode & SOAP_ENC_XML) && endpoint) { unsigned int k = soap->mode; soap->mode &= ~(SOAP_IO | SOAP_ENC_ZLIB); @@ -15000,7 +15197,7 @@ soap_try_connect_command(struct soap *soap, int http_command, const char *endpoi #endif soap->mode = k; } - if (http_command == SOAP_GET) + if (http_command == SOAP_GET || http_command == SOAP_DEL) return soap_end_send(soap); #endif return SOAP_OK; @@ -15008,6 +15205,80 @@ soap_try_connect_command(struct soap *soap, int http_command, const char *endpoi #endif /******************************************************************************/ +#ifdef WITH_NTLM +#ifndef PALM_1 +static int +soap_ntlm_handshake(struct soap *soap, int command, const char *endpoint, const char *host, int port) +{ /* requires libntlm from http://www.nongnu.org/libntlm/ */ + const char *userid = (soap->proxy_userid ? soap->proxy_userid : soap->userid); + const char *passwd = (soap->proxy_passwd ? soap->proxy_passwd : soap->passwd); + struct SOAP_ENV__Header *oldheader; + if (soap->ntlm_challenge && userid && passwd && soap->authrealm) + { tSmbNtlmAuthRequest req; + tSmbNtlmAuthResponse res; + tSmbNtlmAuthChallenge ch; + short k = soap->keep_alive; + size_t l = soap->length; + size_t c = soap->count; + soap_mode m = soap->mode, o = soap->omode; + int s = soap->status; + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "NTLM '%s'\n", soap->ntlm_challenge)); + if (!*soap->ntlm_challenge) + { DBGLOG(TEST,SOAP_MESSAGE(fdebug, "NTLM S->C Type 1: received NTLM authentication challenge from server\n")); + /* S -> C 401 Unauthorized + WWW-Authenticate: NTLM + */ + buildSmbNtlmAuthRequest(&req, userid, soap->authrealm); + soap->ntlm_challenge = soap_s2base64(soap, (unsigned char*)&req, NULL, SmbLength(&req)); + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "NTLM C->S Type 2: sending NTLM authorization to server\nAuthorization: NTLM %s\n", soap->ntlm_challenge)); + /* C -> S GET ... + Authorization: NTLM TlRMTVNTUAABAAAAA7IAAAoACgApAAAACQAJACAAAABMSUdIVENJVFlVUlNBLU1JTk9S + */ + soap->omode = SOAP_IO_BUFFER; + if (soap_begin_send(soap)) + return soap->error; + soap->keep_alive = 1; + soap->status = command; + if (soap->fpost(soap, endpoint, host, port, soap->path, soap->action, 0) + || soap_end_send(soap)) + return soap->error; + soap->mode = m; + soap->keep_alive = k; + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "NTLM S->C Type 2: waiting on server NTLM response\n")); + oldheader = soap->header; + if (soap_begin_recv(soap)) + if (soap->error == SOAP_EOF) + return soap->error; + soap_end_recv(soap); + soap->header = oldheader; + soap->length = l; + if (soap->status != 401 && soap->status != 407) + return soap->error = SOAP_NTLM_ERROR; + soap->error = SOAP_OK; + } + /* S -> C 401 Unauthorized + WWW-Authenticate: NTLM TlRMTVNTUAACAAAAAAAAACgAAAABggAAU3J2Tm9uY2UAAAAAAAAAAA== + */ + soap_base642s(soap, soap->ntlm_challenge, (char*)&ch, sizeof(tSmbNtlmAuthChallenge), NULL); + buildSmbNtlmAuthResponse(&ch, &res, userid, passwd); + soap->ntlm_challenge = soap_s2base64(soap, (unsigned char*)&res, NULL, SmbLength(&res)); + DBGLOG(TEST,SOAP_MESSAGE(fdebug, "NTLM C->S Type 3: sending NTLM authorization to server\nAuthorization: NTLM %s\n", soap->ntlm_challenge)); + /* C -> S GET ... + Authorization: NTLM TlRMTVNTUAADAAAAGAAYAHIAAAAYABgAigAAABQAFABAAAAADAAMAFQAAAASABIAYAAAAAAAAACiAAAAAYIAAFUAUgBTAEEALQBNAEkATgBPAFIAWgBhAHAAaABvAGQATABJAEcASABUAEMASQBUAFkArYfKbe/jRoW5xDxHeoxC1gBmfWiS5+iX4OAN4xBKG/IFPwfH3agtPEia6YnhsADT + */ + soap->keep_alive = k; + soap->length = l; + soap->count = c; + soap->mode = m; + soap->omode = o; + soap->status = s; + } + return SOAP_OK; +} +#endif +#endif + +/******************************************************************************/ #ifndef WITH_LEAN SOAP_FMAC1 char* @@ -15055,7 +15326,8 @@ SOAP_FMAC1 const char* SOAP_FMAC2 soap_base642s(struct soap *soap, const char *s, char *t, size_t l, int *n) -{ register int i, j, c; +{ register size_t i, j; + register soap_wchar c; register unsigned long m; register const char *p; if (!s || !*s) @@ -15066,7 +15338,7 @@ soap_base642s(struct soap *soap, const char *s, char *t, size_t l, int *n) return SOAP_NON_NULL; } if (!t) - { l = (strlen(s) + 3) / 4 * 3; + { l = (strlen(s) + 3) / 4 * 3 + 1; /* make sure enough space for \0 */ t = (char*)soap_malloc(soap, l); } if (!t) @@ -15093,7 +15365,9 @@ soap_base642s(struct soap *soap, const char *s, char *t, size_t l, int *n) i += 2; } if (n) - *n += i; + *n += (int)i; + if (l >= j) + *t = '\0'; return p; } c -= '+'; @@ -15111,14 +15385,15 @@ soap_base642s(struct soap *soap, const char *s, char *t, size_t l, int *n) return NULL; } } - *t++ = (char)((m >> 16) & 0xFF); - *t++ = (char)((m >> 8) & 0xFF); - *t++ = (char)(m & 0xFF); if (l < 3) { if (n) - *n += i; + *n += (int)i; + *t = '\0'; return p; } + *t++ = (char)((m >> 16) & 0xFF); + *t++ = (char)((m >> 8) & 0xFF); + *t++ = (char)(m & 0xFF); l -= 3; } if (n) @@ -15168,7 +15443,7 @@ soap_hex2s(struct soap *soap, const char *s, char *t, size_t l, int *n) return SOAP_NON_NULL; } if (!t) - { l = strlen(s) / 2; + { l = strlen(s) / 2 + 1; /* make sure enough space for \0 */ t = (char*)soap_malloc(soap, l); } if (!t) @@ -15182,11 +15457,13 @@ soap_hex2s(struct soap *soap, const char *s, char *t, size_t l, int *n) d2 = *s++; if (!d2) break; - *t++ = ((d1 >= 'A' ? (d1 & 0x7) + 9 : d1 - '0') << 4) + (d2 >= 'A' ? (d2 & 0x7) + 9 : d2 - '0'); + *t++ = (char)(((d1 >= 'A' ? (d1 & 0x7) + 9 : d1 - '0') << 4) + (d2 >= 'A' ? (d2 & 0x7) + 9 : d2 - '0')); l--; } if (n) *n = (int)(t - p); + if (l) + *t = '\0'; return p; } #endif @@ -15198,13 +15475,13 @@ SOAP_FMAC1 int SOAP_FMAC2 soap_puthttphdr(struct soap *soap, int status, size_t count) -{ if (soap->status != SOAP_GET) +{ if (soap->status != SOAP_GET && soap->status != SOAP_DEL && soap->status != SOAP_CONNECT) { register const char *s = "text/xml; charset=utf-8"; register int err = SOAP_OK; #ifndef WITH_LEANER register const char *r = NULL; #endif - if ((status == SOAP_FILE || soap->status == SOAP_POST_FILE) && soap->http_content) + if ((status == SOAP_FILE || soap->status == SOAP_PUT || soap->status == SOAP_POST_FILE) && soap->http_content) s = soap->http_content; else if (status == SOAP_HTML) s = "text/html; charset=utf-8"; @@ -15245,12 +15522,12 @@ soap_puthttphdr(struct soap *soap, int status, size_t count) } s = soap->tmpbuf; } - if (status == SOAP_OK && soap->version == 2 && soap->action && strlen(soap->action) < sizeof(soap->tmpbuf) - 80) - { sprintf(soap->tmpbuf, "%s; action=\"%s\"", s, soap->action); - s = soap->tmpbuf; - } + else + s = strcpy(soap->tmpbuf, s); + if (status == SOAP_OK && soap->version == 2 && soap->action && strlen(soap->action) + strlen(s) < sizeof(soap->tmpbuf) - 80) + sprintf(soap->tmpbuf + strlen(s), "; action=\"%s\"", soap->action); #endif - if (s && (err = soap->fposthdr(soap, "Content-Type", s))) + if ((err = soap->fposthdr(soap, "Content-Type", s))) return err; #ifdef WITH_ZLIB if ((soap->omode & SOAP_ENC_ZLIB)) @@ -15286,9 +15563,17 @@ soap_puthttphdr(struct soap *soap, int status, size_t count) static const char* soap_set_validation_fault(struct soap *soap, const char *s, const char *t) { if (*soap->tag) - sprintf(soap->msgbuf, "Validation constraint violation: %s%s in element '%s'", s, t?t:SOAP_STR_EOS, soap->tag); +#ifdef HAVE_SNPRINTF + soap_snprintf(soap->msgbuf, sizeof(soap->msgbuf), "Validation constraint violation: %s%s in element '%s'", s, t ? t : SOAP_STR_EOS, soap->tag); +#else + sprintf(soap->msgbuf, "Validation constraint violation: %s%s in element '%s'", s, t ? t : SOAP_STR_EOS, soap->tag); +#endif else - sprintf(soap->msgbuf, "Validation constraint violation: %s%s", s, t?t:SOAP_STR_EOS); +#ifdef HAVE_SNPRINTF + soap_snprintf(soap->msgbuf, sizeof(soap->msgbuf), "Validation constraint violation: %s%s", s, t ? t : SOAP_STR_EOS); +#else + sprintf(soap->msgbuf, "Validation constraint violation: %s%s", s, t ? t : SOAP_STR_EOS); +#endif return soap->msgbuf; } #endif @@ -15330,11 +15615,15 @@ soap_set_fault(struct soap *soap) *s = "Well-formedness violation"; break; case SOAP_NO_TAG: - *s = "No XML root element"; + *s = "No tag: no XML root element or missing SOAP message body element"; break; case SOAP_MUSTUNDERSTAND: *c = "SOAP-ENV:MustUnderstand"; +#ifdef HAVE_SNPRINTF + soap_snprintf(soap->msgbuf, sizeof(soap->msgbuf), "The data in element '%s' must be understood but cannot be handled", soap->tag); +#else sprintf(soap->msgbuf, "The data in element '%s' must be understood but cannot be handled", soap->tag); +#endif *s = soap->msgbuf; break; case SOAP_VERSIONMISMATCH: @@ -15355,7 +15644,11 @@ soap_set_fault(struct soap *soap) *s = "Fatal error"; break; case SOAP_NO_METHOD: +#ifdef HAVE_SNPRINTF + soap_snprintf(soap->msgbuf, sizeof(soap->msgbuf), "Method '%s' not implemented: method name or namespace not recognized", soap->tag); +#else sprintf(soap->msgbuf, "Method '%s' not implemented: method name or namespace not recognized", soap->tag); +#endif *s = soap->msgbuf; break; case SOAP_NO_DATA: @@ -15386,7 +15679,7 @@ soap_set_fault(struct soap *soap) *s = soap_set_validation_fault(soap, "nil not allowed", NULL); break; case SOAP_DUPLICATE_ID: - *s = soap_set_validation_fault(soap, "multiple definitions of id ", soap->id); + *s = soap_set_validation_fault(soap, "multiple definitions (use the SOAP_XML_TREE flag) of the same id ", soap->id); if (soap->version == 2) *soap_faultsubcode(soap) = "SOAP-ENC:DuplicateID"; break; @@ -15411,6 +15704,9 @@ soap_set_fault(struct soap *soap) case SOAP_HTTP_ERROR: *s = "An HTTP processing error occurred"; break; + case SOAP_NTLM_ERROR: + *s = "An HTTP NTLM authentication error occurred"; + break; case SOAP_SSL_ERROR: #ifdef WITH_OPENSSL *s = "SSL/TLS error"; @@ -15444,7 +15740,11 @@ soap_set_fault(struct soap *soap) break; case SOAP_ZLIB_ERROR: #ifdef WITH_ZLIB - sprintf(soap->msgbuf, "Zlib/gzip error: '%s'", soap->d_stream->msg?soap->d_stream->msg:SOAP_STR_EOS); +#ifdef HAVE_SNPRINTF + soap_snprintf(soap->msgbuf, sizeof(soap->msgbuf), "Zlib/gzip error: '%s'", soap->d_stream->msg ? soap->d_stream->msg : SOAP_STR_EOS); +#else + sprintf(soap->msgbuf, "Zlib/gzip error: '%s'", soap->d_stream->msg ? soap->d_stream->msg : SOAP_STR_EOS); +#endif *s = soap->msgbuf; #else *s = "Zlib/gzip not installed for (de)compression: recompile with -DWITH_GZIP"; @@ -15465,8 +15765,11 @@ soap_set_fault(struct soap *soap) case SOAP_FD_EXCEEDED: *s = "Maximum number of open connections was reached (no define HAVE_POLL): increase FD_SETSIZE"; break; + case SOAP_UTF_ERROR: + *s = "UTF content encoding error"; + break; case SOAP_STOP: - *s = "Stopped: no response to be sent or received (informative)"; + *s = "Stopped: no response sent or received (informative)"; break; #endif case SOAP_EOF: @@ -15488,7 +15791,12 @@ soap_set_fault(struct soap *soap) #ifndef WITH_NOHTTP #ifndef WITH_LEAN if (soap->error > 200 && soap->error < 600) - { sprintf(soap->msgbuf, "HTTP Error: %d %s", soap->error, http_error(soap, soap->error)); + { +#ifdef HAVE_SNPRINTF + soap_snprintf(soap->msgbuf, sizeof(soap->msgbuf), "HTTP Error: %d %s", soap->error, http_error(soap, soap->error)); +#else + sprintf(soap->msgbuf, "HTTP Error: %d %s", soap->error, http_error(soap, soap->error)); +#endif *s = soap->msgbuf; } else @@ -15617,12 +15925,14 @@ int SOAP_FMAC2 soap_send_empty_response(struct soap *soap, int httpstatuscode) { register soap_mode m = soap->omode; - soap->count = 0; - if ((m & SOAP_IO) == SOAP_IO_CHUNK) - soap->omode = (m & ~SOAP_IO) | SOAP_IO_BUFFER; - if (!soap_response(soap, httpstatuscode) && !soap_end_send(soap)) - soap->error = SOAP_STOP; /* stops the server's response */ - soap->omode = m; + if (!(m & SOAP_IO_UDP)) + { soap->count = 0; + if ((m & SOAP_IO) == SOAP_IO_CHUNK) + soap->omode = (m & ~SOAP_IO) | SOAP_IO_BUFFER; + if (!soap_response(soap, httpstatuscode) && !soap_end_send(soap)) + soap->error = SOAP_STOP; /* stops the server's processing of request */ + soap->omode = m; + } return soap_closesock(soap); } #endif @@ -15635,10 +15945,12 @@ SOAP_FMAC1 int SOAP_FMAC2 soap_recv_empty_response(struct soap *soap) -{ if (!soap_begin_recv(soap)) - soap_end_recv(soap); - else if (soap->error == SOAP_NO_DATA || soap->error == 202) - soap->error = SOAP_OK; +{ if (!(soap->omode & SOAP_IO_UDP)) + { if (!soap_begin_recv(soap)) + soap_end_recv(soap); + else if (soap->error == SOAP_NO_DATA || soap->error == 202) + soap->error = SOAP_OK; + } return soap_closesock(soap); } #endif @@ -15805,16 +16117,15 @@ soap_print_fault(struct soap *soap, FILE *fd) { if (soap_check_state(soap)) fprintf(fd, "Error: soap struct state not initialized\n"); else if (soap->error) - { const char *c, *v = NULL, *s, **d; - d = soap_faultcode(soap); - if (!*d) + { const char **c, *v = NULL, *s, *d; + c = soap_faultcode(soap); + if (!*c) soap_set_fault(soap); - c = *d; if (soap->version == 2) - v = *soap_faultsubcode(soap); + v = soap_check_faultsubcode(soap); s = *soap_faultstring(soap); - d = soap_faultdetail(soap); - fprintf(fd, "%s%d fault: %s [%s]\n\"%s\"\nDetail: %s\n", soap->version ? "SOAP 1." : "Error ", soap->version ? (int)soap->version : soap->error, c, v ? v : "no subcode", s ? s : "[no reason]", d && *d ? *d : "[no detail]"); + d = soap_check_faultdetail(soap); + fprintf(fd, "%s%d fault: %s [%s]\n\"%s\"\nDetail: %s\n", soap->version ? "SOAP 1." : "Error ", soap->version ? (int)soap->version : soap->error, *c, v ? v : "no subcode", s ? s : "[no reason]", d ? d : "[no detail]"); } } #endif @@ -15824,6 +16135,7 @@ soap_print_fault(struct soap *soap, FILE *fd) #ifdef __cplusplus #ifndef WITH_LEAN #ifndef WITH_NOSTDLIB +#ifndef WITH_COMPAT SOAP_FMAC1 void SOAP_FMAC2 @@ -15831,29 +16143,29 @@ soap_stream_fault(struct soap *soap, std::ostream& os) { if (soap_check_state(soap)) os << "Error: soap struct state not initialized\n"; else if (soap->error) - { const char *c, *v = NULL, *s, **d; - d = soap_faultcode(soap); - if (!*d) + { const char **c, *v = NULL, *s, *d; + c = soap_faultcode(soap); + if (!*c) soap_set_fault(soap); - c = *d; if (soap->version == 2) - v = *soap_faultsubcode(soap); + v = soap_check_faultsubcode(soap); s = *soap_faultstring(soap); - d = soap_faultdetail(soap); + d = soap_check_faultdetail(soap); os << (soap->version ? "SOAP 1." : "Error ") << (soap->version ? (int)soap->version : soap->error) - << " fault: " << c + << " fault: " << *c << "[" << (v ? v : "no subcode") << "]" << std::endl << "\"" << (s ? s : "[no reason]") << "\"" << std::endl - << "Detail: " << (d && *d ? *d : "[no detail]") + << "Detail: " << (d ? d : "[no detail]") << std::endl; } } #endif #endif #endif +#endif /******************************************************************************/ #ifndef WITH_LEAN @@ -15865,27 +16177,21 @@ soap_sprint_fault(struct soap *soap, char *buf, size_t len) { if (soap_check_state(soap)) strncpy(buf, "Error: soap struct not initialized", len); else if (soap->error) - { const char *c, *v = NULL, *s, **d; - d = soap_faultcode(soap); - if (!*d) + { const char **c, *v = NULL, *s, *d; + c = soap_faultcode(soap); + if (!*c) soap_set_fault(soap); - c = *d; if (soap->version == 2) v = *soap_faultsubcode(soap); s = *soap_faultstring(soap); - d = soap_faultdetail(soap); + d = soap_check_faultdetail(soap); #ifdef HAVE_SNPRINTF -# ifdef WIN32 - _snprintf -# else - snprintf -# endif - (buf, len, "%s%d fault: %s [%s]\n\"%s\"\nDetail: %s\n", soap->version ? "SOAP 1." : "Error ", soap->version ? (int)soap->version : soap->error, c, v ? v : "no subcode", s ? s : "[no reason]", d && *d ? *d : "[no detail]"); + soap_snprintf(buf, len, "%s%d fault: %s [%s]\n\"%s\"\nDetail: %s\n", soap->version ? "SOAP 1." : "Error ", soap->version ? (int)soap->version : soap->error, *c, v ? v : "no subcode", s ? s : "[no reason]", d ? d : "[no detail]"); #else - if (len > 40 + (v ? strlen(v) : 0) + (s ? strlen(s) : 0) + (d && *d ? strlen(*d) : 0)) - sprintf(buf, "%s%d fault: %s [%s]\n\"%s\"\nDetail: %s\n", soap->version ? "SOAP 1." : "Error ", soap->version ? (int)soap->version : soap->error, c, v ? v : "no subcode", s ? s : "[no reason]", d && *d ? *d : "[no detail]"); + if (len > 40 + (v ? strlen(v) : 0) + (s ? strlen(s) : 0) + (d ? strlen(d) : 0)) + sprintf(buf, "%s%d fault: %s [%s]\n\"%s\"\nDetail: %s\n", soap->version ? "SOAP 1." : "Error ", soap->version ? (int)soap->version : soap->error, *c, v ? v : "no subcode", s ? s : "[no reason]", d ? d : "[no detail]"); else if (len > 40) - sprintf(buf, "%s%d fault: %s\n", soap->version ? "SOAP 1." : "Error ", soap->version ? (int)soap->version : soap->error, c); + sprintf(buf, "%s%d fault: %s\n", soap->version ? "SOAP 1." : "Error ", soap->version ? (int)soap->version : soap->error, *c); else buf[0] = '\0'; #endif @@ -15920,8 +16226,8 @@ soap_print_fault_location(struct soap *soap, FILE *fd) fprintf(fd, "%s%c\n<!-- ** HERE ** -->\n", soap->buf, c1); if (soap->bufidx < soap->buflen) fprintf(fd, "%s\n", soap->buf + soap->bufidx); - soap->buf[i] = c1; - soap->buf[j] = c2; + soap->buf[i] = (char)c1; + soap->buf[j] = (char)c2; } #endif } @@ -15949,7 +16255,7 @@ soap_register_plugin_arg(struct soap *soap, int (*fcreate)(struct soap*, struct DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Registered '%s' plugin\n", p->id)); return SOAP_OK; } - DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not register plugin '%s': plugin returned error %d (or fdelete callback not set)\n", p->id?p->id:"?", r)); + DBGLOG(TEST, SOAP_MESSAGE(fdebug, "Could not register plugin '%s': plugin returned error %d (or fdelete callback not set)\n", p->id ? p->id : "?", r)); SOAP_FREE(soap, p); return r; } diff --git a/dep/gsoap/stdsoap2.h b/dep/gsoap/stdsoap2.h index 238b7f175ac..87185924135 100644 --- a/dep/gsoap/stdsoap2.h +++ b/dep/gsoap/stdsoap2.h @@ -1,10 +1,10 @@ /* - stdsoap2.h 2.8.2 + stdsoap2.h 2.8.10 gSOAP runtime engine gSOAP XML Web services tools -Copyright (C) 2000-2011, Robert van Engelen, Genivia Inc., All Rights Reserved. +Copyright (C) 2000-2012, Robert van Engelen, Genivia Inc., All Rights Reserved. This part of the software is released under ONE of the following licenses: GPL, or the gSOAP public license, or Genivia's license for commercial use. -------------------------------------------------------------------------------- @@ -24,7 +24,7 @@ WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. The Initial Developer of the Original Code is Robert A. van Engelen. -Copyright (C) 2000-2011, Robert van Engelen, Genivia Inc., All Rights Reserved. +Copyright (C) 2000-2012, Robert van Engelen, Genivia Inc., All Rights Reserved. -------------------------------------------------------------------------------- GPL license. @@ -51,6 +51,8 @@ A commercial use license is available from Genivia, Inc., contact@genivia.com -------------------------------------------------------------------------------- */ +#define GSOAP_VERSION 20810 + #ifdef WITH_SOAPDEFS_H # include "soapdefs.h" /* include user-defined stuff */ #endif @@ -129,6 +131,13 @@ A commercial use license is available from Genivia, Inc., contact@genivia.com # endif #endif +/* for legacy purposes we use WIN32 macro even though 64 bit is supported */ +#ifdef _WIN64 +# ifndef WIN32 +# define WIN32 +# endif +#endif + #ifdef _WIN32_WCE # ifndef UNDER_CE # define UNDER_CE _WIN32_WCE @@ -211,8 +220,14 @@ A commercial use license is available from Genivia, Inc., contact@genivia.com # define HAVE_STRRCHR # define HAVE_STRTOD # define HAVE_SSCANF +# define HAVE_STRTOD_L +# define HAVE_SPRINTF_L # define HAVE_STRTOL # define HAVE_STRTOUL +# if _MSC_VER >= 1300 +# define HAVE_STRTOLL // use _strtoi64 +# define HAVE_STRTOULL // use _strtoui64 +# endif # define HAVE_SYS_TIMEB_H # define HAVE_FTIME # define HAVE_GMTIME @@ -293,7 +308,6 @@ A commercial use license is available from Genivia, Inc., contact@genivia.com # define HAVE_WCTOMB # define HAVE_MBTOWC # define HAVE_ISNAN -# define HAVE_ISINF # elif defined(FREEBSD) || defined(__FreeBSD__) || defined(OPENBSD) # define HAVE_POLL # define HAVE_SNPRINTF @@ -472,6 +486,19 @@ A commercial use license is available from Genivia, Inc., contact@genivia.com # define ULONG64 unsigned LONG64 # define SOAP_LONG_FORMAT "%ld" # define SOAP_ULONG_FORMAT "%lu" +# elif defined(SUN_OS) +# define HAVE_SNPRINTF +# define HAVE_STRRCHR +# define HAVE_STRTOD +# define HAVE_SSCANF +# define HAVE_STRTOL +# define HAVE_STRTOUL +# define HAVE_SYS_TIMEB_H +# define HAVE_FTIME +# define HAVE_RAND_R +# define HAVE_GETHOSTBYNAME_R +# define HAVE_GMTIME_R +# define HAVE_LOCALTIME_R # else /* Default assumptions for supported functions */ # define HAVE_SNPRINTF @@ -515,11 +542,17 @@ A commercial use license is available from Genivia, Inc., contact@genivia.com # endif #endif -/* native Win and HP-UX compilers don't like empty structs */ +/* native Win, HP-UX, and AIX compilers don't like empty structs */ #if defined(WIN32) || defined(HP_UX) || defined(_AIX41) || defined(_AIX43) || defined(VXWORKS) # define WITH_NOEMPTYSTRUCT #endif +#ifdef WITH_PURE_VIRTUAL +# define SOAP_PURE_VIRTUAL = 0 +#else +# define SOAP_PURE_VIRTUAL +#endif + #ifdef HP_UX # undef HAVE_STRTOLL # undef HAVE_STRTOULL @@ -534,8 +567,11 @@ A commercial use license is available from Genivia, Inc., contact@genivia.com /* if we have xlocale.h we use it to avoid decimal point conversion issues */ #ifdef WITH_C_LOCALE -# include <locale.h> -# include <xlocale.h> +# ifdef WIN32 +# include <locale.h> +# else +# include <xlocale.h> +# endif #else # undef HAVE_STRTOF_L # undef HAVE_STRTOD_L @@ -543,7 +579,7 @@ A commercial use license is available from Genivia, Inc., contact@genivia.com # undef HAVE_SPRINTF_L #endif -#ifdef TANDEM +#ifdef TANDEM_NONSTOP # define SOAP_BUFLEN (32767) /*# define WITH_NOSTDLIB */ /* uncommment to remove stdlib dependences */ # define WITH_NOIO /* no IO dependences, e.g. remove TCP/IP */ @@ -586,6 +622,10 @@ A commercial use license is available from Genivia, Inc., contact@genivia.com # include <limits.h> #endif +#ifdef WITH_NTLM +# include <ntlm.h> +#endif + #ifdef HAVE_POLL # include <poll.h> #endif @@ -672,14 +712,6 @@ A commercial use license is available from Genivia, Inc., contact@genivia.com # define SOAP_WINSOCKINT size_t #endif -#ifdef WITH_IPV6 -# ifdef IPV6_V6ONLY -# if !defined(WITH_NO_IPV6_V6ONLY) && !defined(WITH_IPV6_V6ONLY) -# define WITH_NO_IPV6_V6ONLY /* turn on IPv6-IPv4 switching */ -# endif -# endif -#endif - #if defined(WITH_IPV6_V6ONLY) || defined(WITH_NO_IPV6_V6ONLY) # ifndef WITH_IPV6 # define WITH_IPV6 @@ -691,9 +723,17 @@ A commercial use license is available from Genivia, Inc., contact@genivia.com # include <io.h> # include <fcntl.h> # endif -# include <winsock2.h> /* Visual Studio 2005 users: you must install the Platform SDK (R2) */ -# include <ws2tcpip.h> -# include <wspiapi.h> +// When you get macro redefinition errors when compiling the code below: +// try arrange your include list that <windows.h> is included after "stdsoap2.h" +// or define _WINSOCKAPI_ first: +// #define _WINSOCKAPI_ // stops windows.h including winsock.h +// #include <windows.h> +// #include "stdsoap2.h" +# include <winsock2.h> /* Visual Studio 2005 users: install Platform SDK (R2) */ +# include <ws2tcpip.h> +// # define _WSPIAPI_COUNTOF /* DEV NOTE: enble to fix problems with VC6 */ +// # include <wspiapi.h> +# include <ws2spi.h> /* DEV NOTE: replaces older wspiapi.h above */ # ifdef WITH_IPV6 # define SOAP_GAI_STRERROR gai_strerrorA # endif @@ -790,9 +830,9 @@ extern "C" { # endif #elif defined(SOCKLEN_T) # define SOAP_SOCKLEN_T SOCKLEN_T -#elif defined(__socklen_t_defined) || defined(_SOCKLEN_T) || defined(CYGWIN) || defined(FREEBSD) || defined(__FreeBSD__) || defined(OPENBSD) || defined(__QNX__) || defined(QNX) || defined(OS390) || defined(HP_UX) +#elif defined(__socklen_t_defined) || defined(_SOCKLEN_T) || defined(CYGWIN) || defined(FREEBSD) || defined(__FreeBSD__) || defined(OPENBSD) || defined(__QNX__) || defined(QNX) || defined(OS390) # define SOAP_SOCKLEN_T socklen_t -#elif defined(IRIX) || defined(WIN32) || defined(__APPLE__) || defined(SUN_OS) || defined(OPENSERVER) || defined(TRU64) || defined(VXWORKS) +#elif defined(IRIX) || defined(WIN32) || defined(__APPLE__) || defined(SUN_OS) || defined(OPENSERVER) || defined(TRU64) || defined(VXWORKS) || defined(HP_UX) # define SOAP_SOCKLEN_T int #else # define SOAP_SOCKLEN_T size_t @@ -822,6 +862,12 @@ extern "C" { # define FD_SETSIZE (1024) #endif +#ifdef WITH_LEAN +# define SOAP_CHK_EOF SOAP_EOF +#else +# define SOAP_CHK_EOF (soap->error ? soap->error : SOAP_EOF) +#endif + #if defined(SYMBIAN) # define LONG64 long # define ULONG64 unsigned LONG64 @@ -874,7 +920,6 @@ extern "C" { #elif defined(PALM) # define soap_int32 Int32 #elif defined(_AIX) -# define SOAP_NEW(type) new type /* AIX compilers don't like new (t) */ # if defined(_AIX43) # define soap_int32 int32_t # else @@ -1133,6 +1178,14 @@ extern const char soap_base64o[], soap_base64i[]; #define soap_isninfd(n) ((n) < 0 && soap_isinf(n)) #define soap_isninff(n) ((n) < 0 && soap_isinf(n)) +#ifdef HAVE_SNPRINTF +# ifdef WIN32 +# define soap_snprintf _snprintf +# else +# define soap_snprintf snprintf +# endif +#endif + /* gSOAP error codes */ #define SOAP_EOF EOF @@ -1184,6 +1237,8 @@ extern const char soap_base64o[], soap_base64i[]; #define SOAP_OCCURS 44 #define SOAP_LENGTH 45 #define SOAP_FD_EXCEEDED 46 +#define SOAP_UTF_ERROR 47 +#define SOAP_NTLM_ERROR 48 #define soap_xml_error_check(e) ((e) == SOAP_TAG_MISMATCH || (e) == SOAP_NO_TAG || (e) == SOAP_SYNTAX_ERROR || (e) == SOAP_NAMESPACE || (e) == SOAP_DUPLICATE_ID || (e) == SOAP_MISSING_ID || (e) == SOAP_REQUIRED || (e) == SOAP_PROHIBITED || (e) == SOAP_OCCURS || (e) == SOAP_LENGTH || (e) == SOAP_NULL || (e) == SOAP_HREF) #define soap_soap_error_check(e) ((e) == SOAP_CLI_FAULT || (e) == SOAP_SVR_FAULT || (e) == SOAP_VERSIONMISMATCH || (e) == SOAP_MUSTUNDERSTAND || (e) == SOAP_FAULT || (e) == SOAP_NO_METHOD) @@ -1199,7 +1254,7 @@ extern const char soap_base64o[], soap_base64i[]; /* Exceptional gSOAP HTTP server response status codes >= 1000 */ #define SOAP_STOP 1000 /* No HTTP response */ -#define SOAP_FORM 1001 /* Form request/response */ +#define SOAP_FORM 1001 /* Request (form) data is present, no HTTP response */ #define SOAP_HTML 1002 /* Custom HTML response */ #define SOAP_FILE 1003 /* Custom file-based response */ @@ -1208,6 +1263,9 @@ extern const char soap_base64o[], soap_base64i[]; #define SOAP_POST 2000 /* POST request */ #define SOAP_POST_FILE 2001 /* Custom file-based POST request */ #define SOAP_GET 2002 /* GET request */ +#define SOAP_PUT 2003 /* PUT request */ +#define SOAP_DEL 2004 /* DELETE request */ +#define SOAP_CONNECT 2005 /* CONNECT request */ /* gSOAP DIME */ @@ -1254,21 +1312,22 @@ typedef soap_int32 soap_mode; #define SOAP_XML_DEFAULTNS 0x00008000 /* out: emit xmlns="..." */ #define SOAP_XML_CANONICAL 0x00010000 /* out: excC14N canonical XML */ #define SOAP_XML_TREE 0x00020000 /* out: XML tree (no id/ref) */ -#define SOAP_XML_GRAPH 0x00040000 /* see DOM manual */ -#define SOAP_XML_NIL 0x00080000 /* out: NULLs as xsi:nil */ +#define SOAP_XML_NIL 0x00040000 /* out: NULLs as xsi:nil */ +#define SOAP_XML_NOTYPE 0x00080000 /* out: NULLs as xsi:nil */ -#define SOAP_C_NOIOB 0x00100000 /* don't fault on array index out of bounds (just ignore) */ -#define SOAP_C_UTFSTRING 0x00200000 /* (de)serialize strings with UTF8 content */ -#define SOAP_C_MBSTRING 0x00400000 /* (de)serialize strings with multi-byte content */ -#define SOAP_C_NILSTRING 0x00800000 /* serialize empty strings as nil (omitted) */ +#define SOAP_DOM_TREE 0x00100000 /* see DOM manual */ +#define SOAP_DOM_NODE 0x00200000 +#define SOAP_DOM_ASIS 0x00400000 -#define SOAP_XML_DOM 0x01000000 +#define SOAP_C_NOIOB 0x01000000 /* don't fault on array index out of bounds (just ignore) */ +#define SOAP_C_UTFSTRING 0x02000000 /* (de)serialize strings with UTF8 content */ +#define SOAP_C_MBSTRING 0x04000000 /* (de)serialize strings with multi-byte content */ +#define SOAP_C_NILSTRING 0x08000000 /* serialize empty strings as nil (omitted) */ -#define SOAP_DOM_TREE 0x02000000 -#define SOAP_DOM_NODE 0x04000000 -#define SOAP_DOM_ASIS 0x08000000 +#define SOAP_XML_DOM 0x10000000 /* enable internal DOM */ +#define SOAP_XML_GRAPH 0x20000000 /* id-ref graph in DOM */ -#define SOAP_MIME_POSTCHECK 0x10000000 /* MIME flag (internal) */ +#define SOAP_MIME_POSTCHECK 0x40000000 /* MIME flag (internal) */ #define SOAP_SEC_WSUID 0x80000000 /* Add Body wsu:Id */ @@ -1303,7 +1362,7 @@ typedef soap_int32 soap_mode; #define soap_check_state(soap) (!(soap) || ((soap)->state != SOAP_INIT && (soap)->state != SOAP_COPY)) -/* parts, states, and events */ +/* parts */ #define SOAP_BEGIN 0 #define SOAP_IN_ENVELOPE 2 @@ -1315,8 +1374,11 @@ typedef soap_int32 soap_mode; #define SOAP_END_ENVELOPE 8 #define SOAP_END 9 -#define SOAP_SEC_BEGIN 10 -#define SOAP_SEC_SIGN 11 +/* events */ + +#define SOAP_SEC_BEGIN 1 +#define SOAP_SEC_SIGN 2 +#define SOAP_SEC_DECRYPT 3 /* DEBUG macros */ @@ -1349,13 +1411,17 @@ typedef soap_int32 soap_mode; #endif #ifndef SOAP_NEW /* use C++ new operator */ -# if (__GNUC__ <= 2) && !defined(__BORLANDC__) /* Borland uses GNU C? */ +# if (defined(__GNUC__) && (__GNUC__ <= 2) && !defined(__BORLANDC__)) || defined(__clang__) || defined(_AIX) # define SOAP_NEW(type) new type /* old form w/o parenthesis */ # else # define SOAP_NEW(type) new (type) /* prefer with parenthesis */ # endif #endif +#ifndef SOAP_PLACEMENT_NEW +# define SOAP_PLACEMENT_NEW(buf, type) new (buf) type +#endif + #ifndef SOAP_NEW_COPY /* use C++ new operator for ::copy() */ # define SOAP_NEW_COPY(clas) new clas /* prefer w/o parenthesis */ #endif @@ -1792,9 +1858,15 @@ struct SOAP_STD_API soap struct soap_plugin *plugins; /* linked list of plug-in data */ const char *userid; /* HTTP Basic authorization userid */ const char *passwd; /* HTTP Basic authorization passwd */ + const char *authrealm; /* HTTP authentication realm (NTLM domain) */ +#if !defined(WITH_LEAN) || defined(WITH_NTLM) + const char *ntlm_challenge; /* HTTP NTLM challenge key string */ + short ntlm_auth; /* HTTP NTLM authentication type */ + short ntlm_stage; /* HTTP NTLM stage 0..3 */ +#endif int (*fpost)(struct soap*, const char*, const char*, int, const char*, const char*, size_t); int (*fget)(struct soap*); /* HTTP GET hook (not set by default) */ - int (*fput)(struct soap*); /* HTTP PUT hook (handled as POST) */ + int (*fput)(struct soap*); /* HTTP PUT hook (handled as POST by default) */ int (*fdel)(struct soap*); /* HTTP DELETE hook (not set by default) */ int (*fopt)(struct soap*); /* HTTP OPTIONS hook (not set by default) */ int (*fhead)(struct soap*); /* HTTP HEAD hook (not set by default) */ @@ -1847,11 +1919,13 @@ struct SOAP_STD_API soap size_t (*fmimeread)(struct soap*, void*, char*, size_t); int (*fmimewrite)(struct soap*, void*, const char*, size_t); #endif - SOAP_SOCKET master; - SOAP_SOCKET socket; + SOAP_SOCKET master; /* socket bound to TCP/IP port */ + SOAP_SOCKET socket; /* socket to send and receive */ + SOAP_SOCKET sendsk; /* socket to send (overrides ::socket) */ + SOAP_SOCKET recvsk; /* socket to receive (overrides ::socket) */ #if defined(__cplusplus) && !defined(WITH_LEAN) && !defined(WITH_COMPAT) - std::ostream *os; - std::istream *is; + std::ostream *os; /* stream to send */ + std::istream *is; /* stream to receive */ #else void *os; /* preserve struct size */ void *is; /* preserve struct size */ @@ -1860,8 +1934,8 @@ struct SOAP_STD_API soap int sendfd; /* WinCE FD to send */ int recvfd; /* WinCE FD to receive */ #else - FILE *sendfd; - FILE *recvfd; + FILE *sendfd; /* FD to send */ + FILE *recvfd; /* FD to receive */ #endif size_t bufidx; /* index in soap.buf[] */ size_t buflen; /* length of soap.buf[] content */ @@ -1885,9 +1959,9 @@ struct SOAP_STD_API soap char arraySize[SOAP_TAGLEN]; char arrayOffset[SOAP_TAGLEN]; short other; - short position; - int positions[SOAP_MAXDIMS]; short root; + int position; + int positions[SOAP_MAXDIMS]; struct soap_attribute *attributes; /* attribute list */ short encoding; /* when set, output encodingStyle */ short mustUnderstand; /* a mustUnderstand element was parsed or is output */ @@ -1895,6 +1969,7 @@ struct SOAP_STD_API soap short ns; /* when not set, output full xmlns bindings */ short part; /* SOAP part state (header or body) */ short event; /* engine events and states for use by plugins */ + unsigned int evlev; /* event level */ short alloced; short peeked; size_t chunksize; @@ -1903,7 +1978,6 @@ struct SOAP_STD_API soap char path[SOAP_TAGLEN]; char host[SOAP_TAGLEN]; char *action; - char *authrealm; /* HTTP authentication realm */ char *prolog; /* XML declaration prolog */ unsigned long ip; /* IP number */ int port; /* port number */ @@ -1990,7 +2064,11 @@ struct SOAP_STD_API soap char session_host[SOAP_TAGLEN]; int session_port; #ifdef WITH_C_LOCALE +# ifdef WIN32 + _locale_t c_locale; /* set to C locale by default */ +# else locale_t c_locale; /* set to C locale by default */ +# endif #else void *c_locale; #endif @@ -2073,13 +2151,26 @@ soap_wchar soap_get0(struct soap*); soap_wchar soap_get1(struct soap*); #endif +#define soap_versioning_paste(name, ext) name##_LIBRARY_VERSION_REQUIRED_##ext +#define soap_versioning_ext(name, ext) soap_versioning_paste(name, ext) +#define soap_versioning(name) soap_versioning_ext(name, GSOAP_VERSION) + +#define soap_init(soap) soap_init1(soap, SOAP_IO_DEFAULT) +#define soap_init1(soap, mode) soap_init2(soap, mode, mode) +#define soap_init2(soap, imode, omode) soap_versioning(soap_init)(soap, imode, omode) + +#define soap_new() soap_new1(SOAP_IO_DEFAULT) +#define soap_new1(mode) soap_new2(mode, mode) +#define soap_new2(imode, omode) soap_versioning(soap_new)(imode, omode) + #define soap_revget1(soap) ((soap)->bufidx--) #define soap_unget(soap, c) ((soap)->ahead = c) #define soap_register_plugin(soap, plugin) soap_register_plugin_arg(soap, plugin, NULL) -#define soap_imode(soap, n) ((soap)->mode = (soap)->imode = (n)) +#define soap_mode(soap, n) ((soap)->mode = (soap)->imode = (soap)->omode = (n)) +#define soap_imode(soap, n) ((soap)->imode = (n)) +#define soap_omode(soap, n) ((soap)->omode = (n)) #define soap_set_imode(soap, n) ((soap)->imode |= (n)) #define soap_clr_imode(soap, n) ((soap)->imode &= ~(n)) -#define soap_omode(soap, n) ((soap)->mode = (soap)->omode = (n)) #define soap_set_omode(soap, n) ((soap)->omode |= (n)) #define soap_clr_omode(soap, n) ((soap)->omode &= ~(n)) #define soap_set_mode(soap, n) ((soap)->imode |= (n), (soap)->omode |= (n)) @@ -2104,6 +2195,18 @@ soap_wchar soap_get1(struct soap*); SOAP_FMAC1 unsigned long SOAP_FMAC2 soap_strtoul(const char *s, char **t, int b); #endif +#ifdef WIN32 +# define soap_strtoll _strtoi64 +#else +# define soap_strtoll strtoll +#endif + +#ifdef WIN32 +# define soap_strtoull _strtoui64 +#else +# define soap_strtoull strtoull +#endif + #if defined(WITH_OPENSSL) # define soap_random soap_rand() SOAP_FMAC1 int SOAP_FMAC2 soap_rand(void); @@ -2131,18 +2234,29 @@ SOAP_FMAC1 int SOAP_FMAC2 soap_rand(void); # define soap_markelement(s, p, n) (0) #endif -SOAP_FMAC1 void SOAP_FMAC2 soap_header(struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_fault(struct soap*); -SOAP_FMAC1 const char** SOAP_FMAC2 soap_faultcode(struct soap*); -SOAP_FMAC1 const char** SOAP_FMAC2 soap_faultsubcode(struct soap*); -SOAP_FMAC1 const char** SOAP_FMAC2 soap_faultstring(struct soap*); -SOAP_FMAC1 const char** SOAP_FMAC2 soap_faultdetail(struct soap*); +/* soap_traverse() traversal/walker routines take walker function arguments */ +typedef void soap_walker(struct soap*, void*, int, const char*, const char*); + +SOAP_FMAC5 int SOAP_FMAC6 soap_serve(struct soap *soap); +SOAP_FMAC5 int SOAP_FMAC6 soap_serve_request(struct soap *soap); + +#ifndef WITH_NOGLOBAL +SOAP_FMAC3 void SOAP_FMAC4 soap_header(struct soap*); +SOAP_FMAC3 void SOAP_FMAC4 soap_fault(struct soap*); +SOAP_FMAC3 const char** SOAP_FMAC4 soap_faultcode(struct soap*); +SOAP_FMAC3 const char** SOAP_FMAC4 soap_faultsubcode(struct soap*); +SOAP_FMAC3 const char** SOAP_FMAC4 soap_faultstring(struct soap*); +SOAP_FMAC3 const char** SOAP_FMAC4 soap_faultdetail(struct soap*); +SOAP_FMAC3 const char* SOAP_FMAC4 soap_check_faultsubcode(struct soap*); +SOAP_FMAC3 const char* SOAP_FMAC4 soap_check_faultdetail(struct soap*); +SOAP_FMAC3 void SOAP_FMAC4 soap_serializefault(struct soap*); +#endif + SOAP_FMAC1 void SOAP_FMAC2 soap_serializeheader(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_putheader(struct soap*); SOAP_FMAC1 int SOAP_FMAC2 soap_getheader(struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_serializefault(struct soap*); -SOAP_FMAC1 int SOAP_FMAC2 soap_putfault(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_putheader(struct soap*); SOAP_FMAC1 int SOAP_FMAC2 soap_getfault(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_putfault(struct soap*); SOAP_FMAC1 void SOAP_FMAC2 soap_ssl_init(void); SOAP_FMAC1 int SOAP_FMAC2 soap_poll(struct soap*); @@ -2234,7 +2348,7 @@ SOAP_FMAC1 int SOAP_FMAC2 soap_end_recv(struct soap*); SOAP_FMAC1 void* SOAP_FMAC2 soap_malloc(struct soap*, size_t); SOAP_FMAC1 void SOAP_FMAC2 soap_dealloc(struct soap*, void*); SOAP_FMAC1 struct soap_clist * SOAP_FMAC2 soap_link(struct soap*, void*, int, int, int (*fdelete)(struct soap_clist*)); -SOAP_FMAC1 void SOAP_FMAC2 soap_unlink(struct soap*, const void*); +SOAP_FMAC1 int SOAP_FMAC2 soap_unlink(struct soap*, const void*); SOAP_FMAC1 void SOAP_FMAC2 soap_free_temp(struct soap*); SOAP_FMAC1 void SOAP_FMAC2 soap_del(struct soap*); @@ -2262,18 +2376,15 @@ SOAP_FMAC1 char* SOAP_FMAC2 soap_putoffset(struct soap*, int); SOAP_FMAC1 char* SOAP_FMAC2 soap_putoffsets(struct soap*, const int *, int); SOAP_FMAC1 int SOAP_FMAC2 soap_closesock(struct soap*); +SOAP_FMAC1 int SOAP_FMAC2 soap_force_closesock(struct soap*); -SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_new(void); -SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_new1(soap_mode); -SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_new2(soap_mode, soap_mode); +SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_versioning(soap_new)(soap_mode, soap_mode); SOAP_FMAC1 void SOAP_FMAC2 soap_free(struct soap*); SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_copy(const struct soap*); SOAP_FMAC1 struct soap *SOAP_FMAC2 soap_copy_context(struct soap*, const struct soap*); SOAP_FMAC1 void SOAP_FMAC2 soap_copy_stream(struct soap*, struct soap*); SOAP_FMAC1 void SOAP_FMAC2 soap_free_stream(struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_init(struct soap*); -SOAP_FMAC1 void SOAP_FMAC2 soap_init1(struct soap*, soap_mode); -SOAP_FMAC1 void SOAP_FMAC2 soap_init2(struct soap*, soap_mode, soap_mode); +SOAP_FMAC1 void SOAP_FMAC2 soap_versioning(soap_init)(struct soap*, soap_mode, soap_mode); SOAP_FMAC1 void SOAP_FMAC2 soap_done(struct soap*); SOAP_FMAC1 void SOAP_FMAC2 soap_cleanup(struct soap*); SOAP_FMAC1 void SOAP_FMAC2 soap_begin(struct soap*); @@ -2353,6 +2464,7 @@ SOAP_FMAC1 char* SOAP_FMAC2 soap_next_block(struct soap*, struct soap_blist*); SOAP_FMAC1 size_t SOAP_FMAC2 soap_block_size(struct soap*, struct soap_blist*); SOAP_FMAC1 char* SOAP_FMAC2 soap_save_block(struct soap*, struct soap_blist*, char*, int); SOAP_FMAC1 void SOAP_FMAC2 soap_end_block(struct soap*, struct soap_blist*); +SOAP_FMAC1 void SOAP_FMAC2 soap_update_pointers(struct soap *soap, char *start, char *end, char *p1, char *p2); SOAP_FMAC1 int SOAP_FMAC2 soap_envelope_begin_out(struct soap*); SOAP_FMAC1 int soap_envelope_end_out(struct soap*); @@ -2382,8 +2494,10 @@ SOAP_FMAC1 int SOAP_FMAC2 soap_recv_fault(struct soap*, int check); SOAP_FMAC1 void SOAP_FMAC2 soap_print_fault(struct soap*, FILE*); SOAP_FMAC1 void SOAP_FMAC2 soap_print_fault_location(struct soap*, FILE*); # ifndef WITH_LEAN -# ifdef __cplusplus +# ifndef WITH_COMPAT +# ifdef __cplusplus SOAP_FMAC1 void SOAP_FMAC2 soap_stream_fault(struct soap*, std::ostream&); +# endif # endif SOAP_FMAC1 char* SOAP_FMAC2 soap_sprint_fault(struct soap*, char*, size_t); # endif diff --git a/dep/gsoap/tc_upgrades.txt b/dep/gsoap/tc_upgrades.txt new file mode 100644 index 00000000000..04298b2ae82 --- /dev/null +++ b/dep/gsoap/tc_upgrades.txt @@ -0,0 +1,12 @@ +* Generate new headers based on TrinityCore soap-services stub: +gsoap/bin/linux386/soapcpp2 -1 -S -L -w -x -y soap.stub + +* Copy the following files from the gsoap package: +gsoap/stdsoap2.h +gsoap/stdsoap2.cpp + +* Remove the following files after generation: +ns1.nsmap +soapObject.h + +* Test compile and see if SOAP works... diff --git a/dep/utf8cpp/utf8/checked.h b/dep/utf8cpp/utf8/checked.h index a1d2035364d..3b00644444c 100644 --- a/dep/utf8cpp/utf8/checked.h +++ b/dep/utf8cpp/utf8/checked.h @@ -34,7 +34,7 @@ DEALINGS IN THE SOFTWARE. namespace utf8 { // Base for the exceptions that may be thrown from the library - class exception : public std::exception { + class exception : public ::std::exception { }; // Exceptions that may be thrown from the library functions. @@ -69,12 +69,38 @@ namespace utf8 /// The library API - functions intended to be called by the users + template <typename octet_iterator> + octet_iterator append(uint32_t cp, octet_iterator result) + { + if (!utf8::internal::is_code_point_valid(cp)) + throw invalid_code_point(cp); + + if (cp < 0x80) // one octet + *(result++) = static_cast<uint8_t>(cp); + else if (cp < 0x800) { // two octets + *(result++) = static_cast<uint8_t>((cp >> 6) | 0xc0); + *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80); + } + else if (cp < 0x10000) { // three octets + *(result++) = static_cast<uint8_t>((cp >> 12) | 0xe0); + *(result++) = static_cast<uint8_t>(((cp >> 6) & 0x3f) | 0x80); + *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80); + } + else { // four octets + *(result++) = static_cast<uint8_t>((cp >> 18) | 0xf0); + *(result++) = static_cast<uint8_t>(((cp >> 12) & 0x3f) | 0x80); + *(result++) = static_cast<uint8_t>(((cp >> 6) & 0x3f) | 0x80); + *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80); + } + return result; + } + template <typename octet_iterator, typename output_iterator> output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out, uint32_t replacement) { while (start != end) { octet_iterator sequence_start = start; - internal::utf_error err_code = internal::validate_next(start, end); + internal::utf_error err_code = utf8::internal::validate_next(start, end); switch (err_code) { case internal::UTF8_OK : for (octet_iterator it = sequence_start; it != start; ++it) @@ -83,16 +109,16 @@ namespace utf8 case internal::NOT_ENOUGH_ROOM: throw not_enough_room(); case internal::INVALID_LEAD: - append (replacement, out); + utf8::append (replacement, out); ++start; break; case internal::INCOMPLETE_SEQUENCE: case internal::OVERLONG_SEQUENCE: case internal::INVALID_CODE_POINT: - append (replacement, out); + utf8::append (replacement, out); ++start; // just one replacement mark for the sequence - while (internal::is_trail(*start) && start != end) + while (start != end && utf8::internal::is_trail(*start)) ++start; break; } @@ -103,41 +129,15 @@ namespace utf8 template <typename octet_iterator, typename output_iterator> inline output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out) { - static const uint32_t replacement_marker = internal::mask16(0xfffd); - return replace_invalid(start, end, out, replacement_marker); - } - - template <typename octet_iterator> - octet_iterator append(uint32_t cp, octet_iterator result) - { - if (!internal::is_code_point_valid(cp)) - throw invalid_code_point(cp); - - if (cp < 0x80) // one octet - *(result++) = static_cast<uint8_t>(cp); - else if (cp < 0x800) { // two octets - *(result++) = static_cast<uint8_t>((cp >> 6) | 0xc0); - *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80); - } - else if (cp < 0x10000) { // three octets - *(result++) = static_cast<uint8_t>((cp >> 12) | 0xe0); - *(result++) = static_cast<uint8_t>(((cp >> 6) & 0x3f) | 0x80); - *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80); - } - else { // four octets - *(result++) = static_cast<uint8_t>((cp >> 18) | 0xf0); - *(result++) = static_cast<uint8_t>(((cp >> 12) & 0x3f) | 0x80); - *(result++) = static_cast<uint8_t>(((cp >> 6) & 0x3f) | 0x80); - *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80); - } - return result; + static const uint32_t replacement_marker = utf8::internal::mask16(0xfffd); + return utf8::replace_invalid(start, end, out, replacement_marker); } template <typename octet_iterator> uint32_t next(octet_iterator& it, octet_iterator end) { uint32_t cp = 0; - internal::utf_error err_code = internal::validate_next(it, end, &cp); + internal::utf_error err_code = utf8::internal::validate_next(it, end, cp); switch (err_code) { case internal::UTF8_OK : break; @@ -156,18 +156,22 @@ namespace utf8 template <typename octet_iterator> uint32_t peek_next(octet_iterator it, octet_iterator end) { - return next(it, end); + return utf8::next(it, end); } template <typename octet_iterator> uint32_t prior(octet_iterator& it, octet_iterator start) { + // can't do much if it == start + if (it == start) + throw not_enough_room(); + octet_iterator end = it; - while (internal::is_trail(*(--it))) - if (it < start) + // Go back until we hit either a lead octet or start + while (utf8::internal::is_trail(*(--it))) + if (it == start) throw invalid_utf8(*it); // error - no lead byte in the sequence - octet_iterator temp = it; - return next(temp, end); + return utf8::peek_next(it, end); } /// Deprecated in versions that include "prior" @@ -175,18 +179,18 @@ namespace utf8 uint32_t previous(octet_iterator& it, octet_iterator pass_start) { octet_iterator end = it; - while (internal::is_trail(*(--it))) + while (utf8::internal::is_trail(*(--it))) if (it == pass_start) throw invalid_utf8(*it); // error - no lead byte in the sequence octet_iterator temp = it; - return next(temp, end); + return utf8::next(temp, end); } template <typename octet_iterator, typename distance_type> void advance (octet_iterator& it, distance_type n, octet_iterator end) { for (distance_type i = 0; i < n; ++i) - next(it, end); + utf8::next(it, end); } template <typename octet_iterator> @@ -195,7 +199,7 @@ namespace utf8 { typename std::iterator_traits<octet_iterator>::difference_type dist; for (dist = 0; first < last; ++dist) - next(first, last); + utf8::next(first, last); return dist; } @@ -203,12 +207,12 @@ namespace utf8 octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result) { while (start != end) { - uint32_t cp = internal::mask16(*start++); + uint32_t cp = utf8::internal::mask16(*start++); // Take care of surrogate pairs first - if (internal::is_lead_surrogate(cp)) { + if (utf8::internal::is_lead_surrogate(cp)) { if (start != end) { - uint32_t trail_surrogate = internal::mask16(*start++); - if (internal::is_trail_surrogate(trail_surrogate)) + uint32_t trail_surrogate = utf8::internal::mask16(*start++); + if (utf8::internal::is_trail_surrogate(trail_surrogate)) cp = (cp << 10) + trail_surrogate + internal::SURROGATE_OFFSET; else throw invalid_utf16(static_cast<uint16_t>(trail_surrogate)); @@ -218,10 +222,10 @@ namespace utf8 } // Lone trail surrogate - else if (internal::is_trail_surrogate(cp)) + else if (utf8::internal::is_trail_surrogate(cp)) throw invalid_utf16(static_cast<uint16_t>(cp)); - result = append(cp, result); + result = utf8::append(cp, result); } return result; } @@ -230,7 +234,7 @@ namespace utf8 u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result) { while (start != end) { - uint32_t cp = next(start, end); + uint32_t cp = utf8::next(start, end); if (cp > 0xffff) { //make a surrogate pair *result++ = static_cast<uint16_t>((cp >> 10) + internal::LEAD_OFFSET); *result++ = static_cast<uint16_t>((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN); @@ -245,7 +249,7 @@ namespace utf8 octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result) { while (start != end) - result = append(*(start++), result); + result = utf8::append(*(start++), result); return result; } @@ -254,7 +258,7 @@ namespace utf8 u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result) { while (start != end) - (*result++) = next(start, end); + (*result++) = utf8::next(start, end); return result; } @@ -280,7 +284,7 @@ namespace utf8 uint32_t operator * () const { octet_iterator temp = it; - return next(temp, range_end); + return utf8::next(temp, range_end); } bool operator == (const iterator& rhs) const { @@ -294,24 +298,24 @@ namespace utf8 } iterator& operator ++ () { - next(it, range_end); + utf8::next(it, range_end); return *this; } iterator operator ++ (int) { iterator temp = *this; - next(it, range_end); + utf8::next(it, range_end); return temp; } iterator& operator -- () { - prior(it, range_start); + utf8::prior(it, range_start); return *this; } iterator operator -- (int) { iterator temp = *this; - prior(it, range_start); + utf8::prior(it, range_start); return temp; } }; // class iterator diff --git a/dep/utf8cpp/utf8/core.h b/dep/utf8cpp/utf8/core.h index ec709f12006..693d388c078 100644 --- a/dep/utf8cpp/utf8/core.h +++ b/dep/utf8cpp/utf8/core.h @@ -68,7 +68,7 @@ namespace internal template<typename octet_type> inline bool is_trail(octet_type oc) { - return ((mask8(oc) >> 6) == 0x2); + return ((utf8::internal::mask8(oc) >> 6) == 0x2); } template <typename u16> @@ -92,14 +92,14 @@ namespace internal template <typename u32> inline bool is_code_point_valid(u32 cp) { - return (cp <= CODE_POINT_MAX && !is_surrogate(cp) && cp != 0xfffe && cp != 0xffff); + return (cp <= CODE_POINT_MAX && !utf8::internal::is_surrogate(cp)); } template <typename octet_iterator> inline typename std::iterator_traits<octet_iterator>::difference_type sequence_length(octet_iterator lead_it) { - uint8_t lead = mask8(*lead_it); + uint8_t lead = utf8::internal::mask8(*lead_it); if (lead < 0x80) return 1; else if ((lead >> 5) == 0x6) @@ -133,123 +133,94 @@ namespace internal enum utf_error {UTF8_OK, NOT_ENOUGH_ROOM, INVALID_LEAD, INCOMPLETE_SEQUENCE, OVERLONG_SEQUENCE, INVALID_CODE_POINT}; - /// get_sequence_x functions decode utf-8 sequences of the length x + /// Helper for get_sequence_x + template <typename octet_iterator> + utf_error increase_safely(octet_iterator& it, octet_iterator end) + { + if (++it == end) + return NOT_ENOUGH_ROOM; + + if (!utf8::internal::is_trail(*it)) + return INCOMPLETE_SEQUENCE; + + return UTF8_OK; + } + #define UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(IT, END) {utf_error ret = increase_safely(IT, END); if (ret != UTF8_OK) return ret;} + + /// get_sequence_x functions decode utf-8 sequences of the length x template <typename octet_iterator> - utf_error get_sequence_1(octet_iterator& it, octet_iterator end, uint32_t* code_point) + utf_error get_sequence_1(octet_iterator& it, octet_iterator end, uint32_t& code_point) { - if (it != end) { - if (code_point) - *code_point = mask8(*it); - return UTF8_OK; - } - return NOT_ENOUGH_ROOM; + if (it == end) + return NOT_ENOUGH_ROOM; + + code_point = utf8::internal::mask8(*it); + + return UTF8_OK; } template <typename octet_iterator> - utf_error get_sequence_2(octet_iterator& it, octet_iterator end, uint32_t* code_point) + utf_error get_sequence_2(octet_iterator& it, octet_iterator end, uint32_t& code_point) { - utf_error ret_code = NOT_ENOUGH_ROOM; + if (it == end) + return NOT_ENOUGH_ROOM; + + code_point = utf8::internal::mask8(*it); - if (it != end) { - uint32_t cp = mask8(*it); - if (++it != end) { - if (is_trail(*it)) { - cp = ((cp << 6) & 0x7ff) + ((*it) & 0x3f); + UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end) - if (code_point) - *code_point = cp; - ret_code = UTF8_OK; - } - else - ret_code = INCOMPLETE_SEQUENCE; - } - else - ret_code = NOT_ENOUGH_ROOM; - } + code_point = ((code_point << 6) & 0x7ff) + ((*it) & 0x3f); - return ret_code; + return UTF8_OK; } template <typename octet_iterator> - utf_error get_sequence_3(octet_iterator& it, octet_iterator end, uint32_t* code_point) + utf_error get_sequence_3(octet_iterator& it, octet_iterator end, uint32_t& code_point) { - utf_error ret_code = NOT_ENOUGH_ROOM; - - if (it != end) { - uint32_t cp = mask8(*it); - if (++it != end) { - if (is_trail(*it)) { - cp = ((cp << 12) & 0xffff) + ((mask8(*it) << 6) & 0xfff); - if (++it != end) { - if (is_trail(*it)) { - cp += (*it) & 0x3f; - - if (code_point) - *code_point = cp; - ret_code = UTF8_OK; - } - else - ret_code = INCOMPLETE_SEQUENCE; - } - else - ret_code = NOT_ENOUGH_ROOM; - } - else - ret_code = INCOMPLETE_SEQUENCE; - } - else - ret_code = NOT_ENOUGH_ROOM; - } + if (it == end) + return NOT_ENOUGH_ROOM; + + code_point = utf8::internal::mask8(*it); + + UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end) + + code_point = ((code_point << 12) & 0xffff) + ((utf8::internal::mask8(*it) << 6) & 0xfff); + + UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end) - return ret_code; + code_point += (*it) & 0x3f; + + return UTF8_OK; } template <typename octet_iterator> - utf_error get_sequence_4(octet_iterator& it, octet_iterator end, uint32_t* code_point) + utf_error get_sequence_4(octet_iterator& it, octet_iterator end, uint32_t& code_point) { - utf_error ret_code = NOT_ENOUGH_ROOM; - - if (it != end) { - uint32_t cp = mask8(*it); - if (++it != end) { - if (is_trail(*it)) { - cp = ((cp << 18) & 0x1fffff) + ((mask8(*it) << 12) & 0x3ffff); - if (++it != end) { - if (is_trail(*it)) { - cp += (mask8(*it) << 6) & 0xfff; - if (++it != end) { - if (is_trail(*it)) { - cp += (*it) & 0x3f; - - if (code_point) - *code_point = cp; - ret_code = UTF8_OK; - } - else - ret_code = INCOMPLETE_SEQUENCE; - } - else - ret_code = NOT_ENOUGH_ROOM; - } - else - ret_code = INCOMPLETE_SEQUENCE; - } - else - ret_code = NOT_ENOUGH_ROOM; - } - else - ret_code = INCOMPLETE_SEQUENCE; - } - else - ret_code = NOT_ENOUGH_ROOM; - } + if (it == end) + return NOT_ENOUGH_ROOM; - return ret_code; + code_point = utf8::internal::mask8(*it); + + UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end) + + code_point = ((code_point << 18) & 0x1fffff) + ((utf8::internal::mask8(*it) << 12) & 0x3ffff); + + UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end) + + code_point += (utf8::internal::mask8(*it) << 6) & 0xfff; + + UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR(it, end) + + code_point += (*it) & 0x3f; + + return UTF8_OK; } + #undef UTF8_CPP_INCREASE_AND_RETURN_ON_ERROR + template <typename octet_iterator> - utf_error validate_next(octet_iterator& it, octet_iterator end, uint32_t* code_point) + utf_error validate_next(octet_iterator& it, octet_iterator end, uint32_t& code_point) { // Save the original value of it so we can go back in case of failure // Of course, it does not make much sense with i.e. stream iterators @@ -258,34 +229,33 @@ namespace internal uint32_t cp = 0; // Determine the sequence length based on the lead octet typedef typename std::iterator_traits<octet_iterator>::difference_type octet_difference_type; - octet_difference_type length = sequence_length(it); - if (length == 0) - return INVALID_LEAD; + const octet_difference_type length = utf8::internal::sequence_length(it); - // Now that we have a valid sequence length, get trail octets and calculate the code point + // Get trail octets and calculate the code point utf_error err = UTF8_OK; switch (length) { + case 0: + return INVALID_LEAD; case 1: - err = get_sequence_1(it, end, &cp); + err = utf8::internal::get_sequence_1(it, end, cp); break; case 2: - err = get_sequence_2(it, end, &cp); + err = utf8::internal::get_sequence_2(it, end, cp); break; case 3: - err = get_sequence_3(it, end, &cp); + err = utf8::internal::get_sequence_3(it, end, cp); break; case 4: - err = get_sequence_4(it, end, &cp); + err = utf8::internal::get_sequence_4(it, end, cp); break; } if (err == UTF8_OK) { // Decoding succeeded. Now, security checks... - if (is_code_point_valid(cp)) { - if (!is_overlong_sequence(cp, length)){ + if (utf8::internal::is_code_point_valid(cp)) { + if (!utf8::internal::is_overlong_sequence(cp, length)){ // Passed! Return here. - if (code_point) - *code_point = cp; + code_point = cp; ++it; return UTF8_OK; } @@ -303,7 +273,8 @@ namespace internal template <typename octet_iterator> inline utf_error validate_next(octet_iterator& it, octet_iterator end) { - return validate_next(it, end, 0); + uint32_t ignored; + return utf8::internal::validate_next(it, end, ignored); } } // namespace internal @@ -318,7 +289,7 @@ namespace internal { octet_iterator result = start; while (result != end) { - internal::utf_error err_code = internal::validate_next(result, end); + utf8::internal::utf_error err_code = utf8::internal::validate_next(result, end); if (err_code != internal::UTF8_OK) return result; } @@ -328,27 +299,27 @@ namespace internal template <typename octet_iterator> inline bool is_valid(octet_iterator start, octet_iterator end) { - return (find_invalid(start, end) == end); + return (utf8::find_invalid(start, end) == end); } template <typename octet_iterator> inline bool starts_with_bom (octet_iterator it, octet_iterator end) { return ( - ((it != end) && (internal::mask8(*it++)) == bom[0]) && - ((it != end) && (internal::mask8(*it++)) == bom[1]) && - ((it != end) && (internal::mask8(*it)) == bom[2]) + ((it != end) && (utf8::internal::mask8(*it++)) == bom[0]) && + ((it != end) && (utf8::internal::mask8(*it++)) == bom[1]) && + ((it != end) && (utf8::internal::mask8(*it)) == bom[2]) ); } - //Deprecated in release 2.3 + //Deprecated in release 2.3 template <typename octet_iterator> inline bool is_bom (octet_iterator it) { return ( - (internal::mask8(*it++)) == bom[0] && - (internal::mask8(*it++)) == bom[1] && - (internal::mask8(*it)) == bom[2] + (utf8::internal::mask8(*it++)) == bom[0] && + (utf8::internal::mask8(*it++)) == bom[1] && + (utf8::internal::mask8(*it)) == bom[2] ); } } // namespace utf8 diff --git a/dep/utf8cpp/utf8/unchecked.h b/dep/utf8cpp/utf8/unchecked.h index 2f3eb4d1d02..b4547fad945 100644 --- a/dep/utf8cpp/utf8/unchecked.h +++ b/dep/utf8cpp/utf8/unchecked.h @@ -60,7 +60,7 @@ namespace utf8 template <typename octet_iterator> uint32_t next(octet_iterator& it) { - uint32_t cp = internal::mask8(*it); + uint32_t cp = utf8::internal::mask8(*it); typename std::iterator_traits<octet_iterator>::difference_type length = utf8::internal::sequence_length(it); switch (length) { case 1: @@ -71,15 +71,15 @@ namespace utf8 break; case 3: ++it; - cp = ((cp << 12) & 0xffff) + ((internal::mask8(*it) << 6) & 0xfff); + cp = ((cp << 12) & 0xffff) + ((utf8::internal::mask8(*it) << 6) & 0xfff); ++it; cp += (*it) & 0x3f; break; case 4: ++it; - cp = ((cp << 18) & 0x1fffff) + ((internal::mask8(*it) << 12) & 0x3ffff); + cp = ((cp << 18) & 0x1fffff) + ((utf8::internal::mask8(*it) << 12) & 0x3ffff); ++it; - cp += (internal::mask8(*it) << 6) & 0xfff; + cp += (utf8::internal::mask8(*it) << 6) & 0xfff; ++it; cp += (*it) & 0x3f; break; @@ -91,29 +91,29 @@ namespace utf8 template <typename octet_iterator> uint32_t peek_next(octet_iterator it) { - return next(it); + return utf8::unchecked::next(it); } template <typename octet_iterator> uint32_t prior(octet_iterator& it) { - while (internal::is_trail(*(--it))) ; + while (utf8::internal::is_trail(*(--it))) ; octet_iterator temp = it; - return next(temp); + return utf8::unchecked::next(temp); } // Deprecated in versions that include prior, but only for the sake of consistency (see utf8::previous) template <typename octet_iterator> inline uint32_t previous(octet_iterator& it) { - return prior(it); + return utf8::unchecked::prior(it); } template <typename octet_iterator, typename distance_type> void advance (octet_iterator& it, distance_type n) { for (distance_type i = 0; i < n; ++i) - next(it); + utf8::unchecked::next(it); } template <typename octet_iterator> @@ -122,7 +122,7 @@ namespace utf8 { typename std::iterator_traits<octet_iterator>::difference_type dist; for (dist = 0; first < last; ++dist) - next(first); + utf8::unchecked::next(first); return dist; } @@ -130,13 +130,13 @@ namespace utf8 octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result) { while (start != end) { - uint32_t cp = internal::mask16(*start++); + uint32_t cp = utf8::internal::mask16(*start++); // Take care of surrogate pairs first - if (internal::is_lead_surrogate(cp)) { - uint32_t trail_surrogate = internal::mask16(*start++); + if (utf8::internal::is_lead_surrogate(cp)) { + uint32_t trail_surrogate = utf8::internal::mask16(*start++); cp = (cp << 10) + trail_surrogate + internal::SURROGATE_OFFSET; } - result = append(cp, result); + result = utf8::unchecked::append(cp, result); } return result; } @@ -145,7 +145,7 @@ namespace utf8 u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result) { while (start < end) { - uint32_t cp = next(start); + uint32_t cp = utf8::unchecked::next(start); if (cp > 0xffff) { //make a surrogate pair *result++ = static_cast<uint16_t>((cp >> 10) + internal::LEAD_OFFSET); *result++ = static_cast<uint16_t>((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN); @@ -160,7 +160,7 @@ namespace utf8 octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result) { while (start != end) - result = append(*(start++), result); + result = utf8::unchecked::append(*(start++), result); return result; } @@ -169,7 +169,7 @@ namespace utf8 u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result) { while (start < end) - (*result++) = next(start); + (*result++) = utf8::unchecked::next(start); return result; } @@ -186,7 +186,7 @@ namespace utf8 uint32_t operator * () const { octet_iterator temp = it; - return next(temp); + return utf8::unchecked::next(temp); } bool operator == (const iterator& rhs) const { @@ -198,24 +198,24 @@ namespace utf8 } iterator& operator ++ () { - std::advance(it, internal::sequence_length(it)); + ::std::advance(it, utf8::internal::sequence_length(it)); return *this; } iterator operator ++ (int) { iterator temp = *this; - std::advance(it, internal::sequence_length(it)); + ::std::advance(it, utf8::internal::sequence_length(it)); return temp; } iterator& operator -- () { - prior(it); + utf8::unchecked::prior(it); return *this; } iterator operator -- (int) { iterator temp = *this; - prior(it); + utf8::unchecked::prior(it); return temp; } }; // class iterator diff --git a/dep/zlib/adler32.c b/dep/zlib/adler32.c index 65ad6a5adc4..a868f073d8a 100644 --- a/dep/zlib/adler32.c +++ b/dep/zlib/adler32.c @@ -1,5 +1,5 @@ /* adler32.c -- compute the Adler-32 checksum of a data stream - * Copyright (C) 1995-2007 Mark Adler + * Copyright (C) 1995-2011 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -9,9 +9,9 @@ #define local static -local uLong adler32_combine_(uLong adler1, uLong adler2, z_off64_t len2); +local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2)); -#define BASE 65521UL /* largest prime smaller than 65536 */ +#define BASE 65521 /* largest prime smaller than 65536 */ #define NMAX 5552 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ @@ -21,39 +21,44 @@ local uLong adler32_combine_(uLong adler1, uLong adler2, z_off64_t len2); #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); #define DO16(buf) DO8(buf,0); DO8(buf,8); -/* use NO_DIVIDE if your processor does not do division in hardware */ +/* use NO_DIVIDE if your processor does not do division in hardware -- + try it both ways to see which is faster */ #ifdef NO_DIVIDE -# define MOD(a) \ +/* note that this assumes BASE is 65521, where 65536 % 65521 == 15 + (thank you to John Reiser for pointing this out) */ +# define CHOP(a) \ + do { \ + unsigned long tmp = a >> 16; \ + a &= 0xffffUL; \ + a += (tmp << 4) - tmp; \ + } while (0) +# define MOD28(a) \ do { \ - if (a >= (BASE << 16)) a -= (BASE << 16); \ - if (a >= (BASE << 15)) a -= (BASE << 15); \ - if (a >= (BASE << 14)) a -= (BASE << 14); \ - if (a >= (BASE << 13)) a -= (BASE << 13); \ - if (a >= (BASE << 12)) a -= (BASE << 12); \ - if (a >= (BASE << 11)) a -= (BASE << 11); \ - if (a >= (BASE << 10)) a -= (BASE << 10); \ - if (a >= (BASE << 9)) a -= (BASE << 9); \ - if (a >= (BASE << 8)) a -= (BASE << 8); \ - if (a >= (BASE << 7)) a -= (BASE << 7); \ - if (a >= (BASE << 6)) a -= (BASE << 6); \ - if (a >= (BASE << 5)) a -= (BASE << 5); \ - if (a >= (BASE << 4)) a -= (BASE << 4); \ - if (a >= (BASE << 3)) a -= (BASE << 3); \ - if (a >= (BASE << 2)) a -= (BASE << 2); \ - if (a >= (BASE << 1)) a -= (BASE << 1); \ + CHOP(a); \ if (a >= BASE) a -= BASE; \ } while (0) -# define MOD4(a) \ +# define MOD(a) \ do { \ - if (a >= (BASE << 4)) a -= (BASE << 4); \ - if (a >= (BASE << 3)) a -= (BASE << 3); \ - if (a >= (BASE << 2)) a -= (BASE << 2); \ - if (a >= (BASE << 1)) a -= (BASE << 1); \ + CHOP(a); \ + MOD28(a); \ + } while (0) +# define MOD63(a) \ + do { /* this assumes a is not negative */ \ + z_off64_t tmp = a >> 32; \ + a &= 0xffffffffL; \ + a += (tmp << 8) - (tmp << 5) + tmp; \ + tmp = a >> 16; \ + a &= 0xffffL; \ + a += (tmp << 4) - tmp; \ + tmp = a >> 16; \ + a &= 0xffffL; \ + a += (tmp << 4) - tmp; \ if (a >= BASE) a -= BASE; \ } while (0) #else # define MOD(a) a %= BASE -# define MOD4(a) a %= BASE +# define MOD28(a) a %= BASE +# define MOD63(a) a %= BASE #endif /* ========================================================================= */ @@ -92,7 +97,7 @@ uLong ZEXPORT adler32(adler, buf, len) } if (adler >= BASE) adler -= BASE; - MOD4(sum2); /* only added so many BASE's */ + MOD28(sum2); /* only added so many BASE's */ return adler | (sum2 << 16); } @@ -137,8 +142,13 @@ local uLong adler32_combine_(adler1, adler2, len2) unsigned long sum2; unsigned rem; + /* for negative len, return invalid adler32 as a clue for debugging */ + if (len2 < 0) + return 0xffffffffUL; + /* the derivation of this formula is left as an exercise for the reader */ - rem = (unsigned)(len2 % BASE); + MOD63(len2); /* assumes len2 >= 0 */ + rem = (unsigned)len2; sum1 = adler1 & 0xffff; sum2 = rem * sum1; MOD(sum2); diff --git a/dep/zlib/crc32.c b/dep/zlib/crc32.c index 91be372d224..979a7190a3c 100644 --- a/dep/zlib/crc32.c +++ b/dep/zlib/crc32.c @@ -1,5 +1,5 @@ /* crc32.c -- compute the CRC-32 of a data stream - * Copyright (C) 1995-2006, 2010 Mark Adler + * Copyright (C) 1995-2006, 2010, 2011, 2012 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h * * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster @@ -17,6 +17,8 @@ of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should first call get_crc_table() to initialize the tables before allowing more than one thread to use crc32(). + + DYNAMIC_CRC_TABLE and MAKECRCH can be #defined to write out crc32.h. */ #ifdef MAKECRCH @@ -30,31 +32,11 @@ #define local static -/* Find a four-byte integer type for crc32_little() and crc32_big(). */ -#ifndef NOBYFOUR -# ifdef STDC /* need ANSI C limits.h to determine sizes */ -# include <limits.h> -# define BYFOUR -# if (UINT_MAX == 0xffffffffUL) - typedef unsigned int u4; -# else -# if (ULONG_MAX == 0xffffffffUL) - typedef unsigned long u4; -# else -# if (USHRT_MAX == 0xffffffffUL) - typedef unsigned short u4; -# else -# undef BYFOUR /* can't find a four-byte integer type! */ -# endif -# endif -# endif -# endif /* STDC */ -#endif /* !NOBYFOUR */ - /* Definitions for doing the crc four data bytes at a time. */ +#if !defined(NOBYFOUR) && defined(Z_U4) +# define BYFOUR +#endif #ifdef BYFOUR -# define REV(w) ((((w)>>24)&0xff)+(((w)>>8)&0xff00)+ \ - (((w)&0xff00)<<8)+(((w)&0xff)<<24)) local unsigned long crc32_little OF((unsigned long, const unsigned char FAR *, unsigned)); local unsigned long crc32_big OF((unsigned long, @@ -68,16 +50,16 @@ local unsigned long gf2_matrix_times OF((unsigned long *mat, unsigned long vec)); local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); -local uLong crc32_combine_(uLong crc1, uLong crc2, z_off64_t len2); +local uLong crc32_combine_ OF((uLong crc1, uLong crc2, z_off64_t len2)); #ifdef DYNAMIC_CRC_TABLE local volatile int crc_table_empty = 1; -local unsigned long FAR crc_table[TBLS][256]; +local z_crc_t FAR crc_table[TBLS][256]; local void make_crc_table OF((void)); #ifdef MAKECRCH - local void write_table OF((FILE *, const unsigned long FAR *)); + local void write_table OF((FILE *, const z_crc_t FAR *)); #endif /* MAKECRCH */ /* Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: @@ -107,9 +89,9 @@ local void make_crc_table OF((void)); */ local void make_crc_table() { - unsigned long c; + z_crc_t c; int n, k; - unsigned long poly; /* polynomial exclusive-or pattern */ + z_crc_t poly; /* polynomial exclusive-or pattern */ /* terms of polynomial defining this crc (except x^32): */ static volatile int first = 1; /* flag to limit concurrent making */ static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; @@ -121,13 +103,13 @@ local void make_crc_table() first = 0; /* make exclusive-or pattern from polynomial (0xedb88320UL) */ - poly = 0UL; - for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++) - poly |= 1UL << (31 - p[n]); + poly = 0; + for (n = 0; n < (int)(sizeof(p)/sizeof(unsigned char)); n++) + poly |= (z_crc_t)1 << (31 - p[n]); /* generate a crc for every 8-bit value */ for (n = 0; n < 256; n++) { - c = (unsigned long)n; + c = (z_crc_t)n; for (k = 0; k < 8; k++) c = c & 1 ? poly ^ (c >> 1) : c >> 1; crc_table[0][n] = c; @@ -138,11 +120,11 @@ local void make_crc_table() and then the byte reversal of those as well as the first table */ for (n = 0; n < 256; n++) { c = crc_table[0][n]; - crc_table[4][n] = REV(c); + crc_table[4][n] = ZSWAP32(c); for (k = 1; k < 4; k++) { c = crc_table[0][c & 0xff] ^ (c >> 8); crc_table[k][n] = c; - crc_table[k + 4][n] = REV(c); + crc_table[k + 4][n] = ZSWAP32(c); } } #endif /* BYFOUR */ @@ -164,7 +146,7 @@ local void make_crc_table() if (out == NULL) return; fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n"); fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); - fprintf(out, "local const unsigned long FAR "); + fprintf(out, "local const z_crc_t FAR "); fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); write_table(out, crc_table[0]); # ifdef BYFOUR @@ -184,12 +166,13 @@ local void make_crc_table() #ifdef MAKECRCH local void write_table(out, table) FILE *out; - const unsigned long FAR *table; + const z_crc_t FAR *table; { int n; for (n = 0; n < 256; n++) - fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n], + fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", + (unsigned long)(table[n]), n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); } #endif /* MAKECRCH */ @@ -204,13 +187,13 @@ local void write_table(out, table) /* ========================================================================= * This function can be used by asm versions of crc32() */ -const unsigned long FAR * ZEXPORT get_crc_table() +const z_crc_t FAR * ZEXPORT get_crc_table() { #ifdef DYNAMIC_CRC_TABLE if (crc_table_empty) make_crc_table(); #endif /* DYNAMIC_CRC_TABLE */ - return (const unsigned long FAR *)crc_table; + return (const z_crc_t FAR *)crc_table; } /* ========================================================================= */ @@ -232,7 +215,7 @@ unsigned long ZEXPORT crc32(crc, buf, len) #ifdef BYFOUR if (sizeof(void *) == sizeof(ptrdiff_t)) { - u4 endian; + z_crc_t endian; endian = 1; if (*((unsigned char *)(&endian))) @@ -266,17 +249,17 @@ local unsigned long crc32_little(crc, buf, len) const unsigned char FAR *buf; unsigned len; { - register u4 c; - register const u4 FAR *buf4; + register z_crc_t c; + register const z_crc_t FAR *buf4; - c = (u4)crc; + c = (z_crc_t)crc; c = ~c; while (len && ((ptrdiff_t)buf & 3)) { c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); len--; } - buf4 = (const u4 FAR *)(const void FAR *)buf; + buf4 = (const z_crc_t FAR *)(const void FAR *)buf; while (len >= 32) { DOLIT32; len -= 32; @@ -306,17 +289,17 @@ local unsigned long crc32_big(crc, buf, len) const unsigned char FAR *buf; unsigned len; { - register u4 c; - register const u4 FAR *buf4; + register z_crc_t c; + register const z_crc_t FAR *buf4; - c = REV((u4)crc); + c = ZSWAP32((z_crc_t)crc); c = ~c; while (len && ((ptrdiff_t)buf & 3)) { c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); len--; } - buf4 = (const u4 FAR *)(const void FAR *)buf; + buf4 = (const z_crc_t FAR *)(const void FAR *)buf; buf4--; while (len >= 32) { DOBIG32; @@ -333,7 +316,7 @@ local unsigned long crc32_big(crc, buf, len) c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); } while (--len); c = ~c; - return (unsigned long)(REV(c)); + return (unsigned long)(ZSWAP32(c)); } #endif /* BYFOUR */ diff --git a/dep/zlib/crc32.h b/dep/zlib/crc32.h index 8053b6117c0..9e0c7781025 100644 --- a/dep/zlib/crc32.h +++ b/dep/zlib/crc32.h @@ -2,7 +2,7 @@ * Generated automatically by crc32.c */ -local const unsigned long FAR crc_table[TBLS][256] = +local const z_crc_t FAR crc_table[TBLS][256] = { { 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, diff --git a/dep/zlib/deflate.c b/dep/zlib/deflate.c index 5c4022f3d47..9e4c2cbc8af 100644 --- a/dep/zlib/deflate.c +++ b/dep/zlib/deflate.c @@ -1,5 +1,5 @@ /* deflate.c -- compress data using the deflation algorithm - * Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler + * Copyright (C) 1995-2012 Jean-loup Gailly and Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -37,7 +37,7 @@ * REFERENCES * * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". - * Available in http://www.ietf.org/rfc/rfc1951.txt + * Available in http://tools.ietf.org/html/rfc1951 * * A description of the Rabin and Karp algorithm is given in the book * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. @@ -52,7 +52,7 @@ #include "deflate.h" const char deflate_copyright[] = - " deflate 1.2.5 Copyright 1995-2010 Jean-loup Gailly and Mark Adler "; + " deflate 1.2.7 Copyright 1995-2012 Jean-loup Gailly and Mark Adler "; /* If you use the zlib library in a product, an acknowledgment is welcome in the documentation of your product. If for some reason you cannot @@ -155,6 +155,9 @@ local const config configuration_table[10] = { struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ #endif +/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */ +#define RANK(f) (((f) << 1) - ((f) > 4 ? 9 : 0)) + /* =========================================================================== * Update a hash value with the given input byte * IN assertion: all calls to to UPDATE_HASH are made with consecutive @@ -235,10 +238,19 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, strm->msg = Z_NULL; if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else strm->zalloc = zcalloc; strm->opaque = (voidpf)0; +#endif } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif #ifdef FASTEST if (level != 0) level = 1; @@ -314,43 +326,70 @@ int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) uInt dictLength; { deflate_state *s; - uInt length = dictLength; - uInt n; - IPos hash_head = 0; + uInt str, n; + int wrap; + unsigned avail; + unsigned char *next; - if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL || - strm->state->wrap == 2 || - (strm->state->wrap == 1 && strm->state->status != INIT_STATE)) + if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL) return Z_STREAM_ERROR; - s = strm->state; - if (s->wrap) - strm->adler = adler32(strm->adler, dictionary, dictLength); + wrap = s->wrap; + if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead) + return Z_STREAM_ERROR; - if (length < MIN_MATCH) return Z_OK; - if (length > s->w_size) { - length = s->w_size; - dictionary += dictLength - length; /* use the tail of the dictionary */ + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap == 1) + strm->adler = adler32(strm->adler, dictionary, dictLength); + s->wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s->w_size) { + if (wrap == 0) { /* already empty otherwise */ + CLEAR_HASH(s); + s->strstart = 0; + s->block_start = 0L; + s->insert = 0; + } + dictionary += dictLength - s->w_size; /* use the tail */ + dictLength = s->w_size; } - zmemcpy(s->window, dictionary, length); - s->strstart = length; - s->block_start = (long)length; - /* Insert all strings in the hash table (except for the last two bytes). - * s->lookahead stays null, so s->ins_h will be recomputed at the next - * call of fill_window. - */ - s->ins_h = s->window[0]; - UPDATE_HASH(s, s->ins_h, s->window[1]); - for (n = 0; n <= length - MIN_MATCH; n++) { - INSERT_STRING(s, n, hash_head); + /* insert dictionary into window and hash */ + avail = strm->avail_in; + next = strm->next_in; + strm->avail_in = dictLength; + strm->next_in = (Bytef *)dictionary; + fill_window(s); + while (s->lookahead >= MIN_MATCH) { + str = s->strstart; + n = s->lookahead - (MIN_MATCH-1); + do { + UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +#ifndef FASTEST + s->prev[str & s->w_mask] = s->head[s->ins_h]; +#endif + s->head[s->ins_h] = (Pos)str; + str++; + } while (--n); + s->strstart = str; + s->lookahead = MIN_MATCH-1; + fill_window(s); } - if (hash_head) hash_head = 0; /* to make compiler happy */ + s->strstart += s->lookahead; + s->block_start = (long)s->strstart; + s->insert = s->lookahead; + s->lookahead = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + strm->next_in = next; + strm->avail_in = avail; + s->wrap = wrap; return Z_OK; } /* ========================================================================= */ -int ZEXPORT deflateReset (strm) +int ZEXPORT deflateResetKeep (strm) z_streamp strm; { deflate_state *s; @@ -380,12 +419,23 @@ int ZEXPORT deflateReset (strm) s->last_flush = Z_NO_FLUSH; _tr_init(s); - lm_init(s); return Z_OK; } /* ========================================================================= */ +int ZEXPORT deflateReset (strm) + z_streamp strm; +{ + int ret; + + ret = deflateResetKeep(strm); + if (ret == Z_OK) + lm_init(strm->state); + return ret; +} + +/* ========================================================================= */ int ZEXPORT deflateSetHeader (strm, head) z_streamp strm; gz_headerp head; @@ -397,14 +447,42 @@ int ZEXPORT deflateSetHeader (strm, head) } /* ========================================================================= */ +int ZEXPORT deflatePending (strm, pending, bits) + unsigned *pending; + int *bits; + z_streamp strm; +{ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + if (pending != Z_NULL) + *pending = strm->state->pending; + if (bits != Z_NULL) + *bits = strm->state->bi_valid; + return Z_OK; +} + +/* ========================================================================= */ int ZEXPORT deflatePrime (strm, bits, value) z_streamp strm; int bits; int value; { + deflate_state *s; + int put; + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; - strm->state->bi_valid = bits; - strm->state->bi_buf = (ush)(value & ((1 << bits) - 1)); + s = strm->state; + if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3)) + return Z_BUF_ERROR; + do { + put = Buf_size - s->bi_valid; + if (put > bits) + put = bits; + s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid); + s->bi_valid += put; + _tr_flush_bits(s); + value >>= put; + bits -= put; + } while (bits); return Z_OK; } @@ -562,19 +640,22 @@ local void putShortMSB (s, b) local void flush_pending(strm) z_streamp strm; { - unsigned len = strm->state->pending; + unsigned len; + deflate_state *s = strm->state; + _tr_flush_bits(s); + len = s->pending; if (len > strm->avail_out) len = strm->avail_out; if (len == 0) return; - zmemcpy(strm->next_out, strm->state->pending_out, len); + zmemcpy(strm->next_out, s->pending_out, len); strm->next_out += len; - strm->state->pending_out += len; + s->pending_out += len; strm->total_out += len; strm->avail_out -= len; - strm->state->pending -= len; - if (strm->state->pending == 0) { - strm->state->pending_out = strm->state->pending_buf; + s->pending -= len; + if (s->pending == 0) { + s->pending_out = s->pending_buf; } } @@ -801,7 +882,7 @@ int ZEXPORT deflate (strm, flush) * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ - } else if (strm->avail_in == 0 && flush <= old_flush && + } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) && flush != Z_FINISH) { ERR_RETURN(strm, Z_BUF_ERROR); } @@ -850,6 +931,7 @@ int ZEXPORT deflate (strm, flush) if (s->lookahead == 0) { s->strstart = 0; s->block_start = 0L; + s->insert = 0; } } } @@ -945,12 +1027,12 @@ int ZEXPORT deflateCopy (dest, source) ss = source->state; - zmemcpy(dest, source, sizeof(z_stream)); + zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); if (ds == Z_NULL) return Z_MEM_ERROR; dest->state = (struct internal_state FAR *) ds; - zmemcpy(ds, ss, sizeof(deflate_state)); + zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state)); ds->strm = dest; ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); @@ -966,8 +1048,8 @@ int ZEXPORT deflateCopy (dest, source) } /* following zmemcpy do not work for 16-bit MSDOS */ zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); - zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos)); - zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos)); + zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos)); + zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos)); zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); @@ -1001,15 +1083,15 @@ local int read_buf(strm, buf, size) strm->avail_in -= len; + zmemcpy(buf, strm->next_in, len); if (strm->state->wrap == 1) { - strm->adler = adler32(strm->adler, strm->next_in, len); + strm->adler = adler32(strm->adler, buf, len); } #ifdef GZIP else if (strm->state->wrap == 2) { - strm->adler = crc32(strm->adler, strm->next_in, len); + strm->adler = crc32(strm->adler, buf, len); } #endif - zmemcpy(buf, strm->next_in, len); strm->next_in += len; strm->total_in += len; @@ -1036,6 +1118,7 @@ local void lm_init (s) s->strstart = 0; s->block_start = 0L; s->lookahead = 0; + s->insert = 0; s->match_length = s->prev_length = MIN_MATCH-1; s->match_available = 0; s->ins_h = 0; @@ -1310,6 +1393,8 @@ local void fill_window(s) unsigned more; /* Amount of free space at the end of the window. */ uInt wsize = s->w_size; + Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + do { more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); @@ -1362,7 +1447,7 @@ local void fill_window(s) #endif more += wsize; } - if (s->strm->avail_in == 0) return; + if (s->strm->avail_in == 0) break; /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && @@ -1381,12 +1466,24 @@ local void fill_window(s) s->lookahead += n; /* Initialize the hash value now that we have some input: */ - if (s->lookahead >= MIN_MATCH) { - s->ins_h = s->window[s->strstart]; - UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); + if (s->lookahead + s->insert >= MIN_MATCH) { + uInt str = s->strstart - s->insert; + s->ins_h = s->window[str]; + UPDATE_HASH(s, s->ins_h, s->window[str + 1]); #if MIN_MATCH != 3 Call UPDATE_HASH() MIN_MATCH-3 more times #endif + while (s->insert) { + UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +#ifndef FASTEST + s->prev[str & s->w_mask] = s->head[s->ins_h]; +#endif + s->head[s->ins_h] = (Pos)str; + str++; + s->insert--; + if (s->lookahead + s->insert < MIN_MATCH) + break; + } } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. @@ -1427,6 +1524,9 @@ local void fill_window(s) s->high_water += init; } } + + Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, + "not enough room for search"); } /* =========================================================================== @@ -1506,8 +1606,14 @@ local block_state deflate_stored(s, flush) FLUSH_BLOCK(s, 0); } } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if ((long)s->strstart > s->block_start) + FLUSH_BLOCK(s, 0); + return block_done; } /* =========================================================================== @@ -1603,8 +1709,14 @@ local block_state deflate_fast(s, flush) } if (bflush) FLUSH_BLOCK(s, 0); } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; + s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; } #ifndef FASTEST @@ -1728,8 +1840,14 @@ local block_state deflate_slow(s, flush) _tr_tally_lit(s, s->window[s->strstart-1], bflush); s->match_available = 0; } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; + s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; } #endif /* FASTEST */ @@ -1749,11 +1867,11 @@ local block_state deflate_rle(s, flush) for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes - * for the longest encodable run. + * for the longest run, plus one for the unrolled loop. */ - if (s->lookahead < MAX_MATCH) { + if (s->lookahead <= MAX_MATCH) { fill_window(s); - if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) { + if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) { return need_more; } if (s->lookahead == 0) break; /* flush the current block */ @@ -1776,6 +1894,7 @@ local block_state deflate_rle(s, flush) if (s->match_length > s->lookahead) s->match_length = s->lookahead; } + Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ @@ -1796,8 +1915,14 @@ local block_state deflate_rle(s, flush) } if (bflush) FLUSH_BLOCK(s, 0); } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; } /* =========================================================================== @@ -1829,6 +1954,12 @@ local block_state deflate_huff(s, flush) s->strstart++; if (bflush) FLUSH_BLOCK(s, 0); } - FLUSH_BLOCK(s, flush == Z_FINISH); - return flush == Z_FINISH ? finish_done : block_done; + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; } diff --git a/dep/zlib/deflate.h b/dep/zlib/deflate.h index cbf0d1ea5d9..fbac44d908e 100644 --- a/dep/zlib/deflate.h +++ b/dep/zlib/deflate.h @@ -1,5 +1,5 @@ /* deflate.h -- internal compression state - * Copyright (C) 1995-2010 Jean-loup Gailly + * Copyright (C) 1995-2012 Jean-loup Gailly * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -48,6 +48,9 @@ #define MAX_BITS 15 /* All codes must not exceed MAX_BITS bits */ +#define Buf_size 16 +/* size of bit buffer in bi_buf */ + #define INIT_STATE 42 #define EXTRA_STATE 69 #define NAME_STATE 73 @@ -188,7 +191,7 @@ typedef struct internal_state { int nice_match; /* Stop searching when current match exceeds this */ /* used by trees.c: */ - /* Didn't use ct_data typedef below to supress compiler warning */ + /* Didn't use ct_data typedef below to suppress compiler warning */ struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ @@ -244,7 +247,7 @@ typedef struct internal_state { ulg opt_len; /* bit length of current block with optimal trees */ ulg static_len; /* bit length of current block with static trees */ uInt matches; /* number of string matches in current block */ - int last_eob_len; /* bit length of EOB code for last block */ + uInt insert; /* bytes at end of window left to insert */ #ifdef DEBUG ulg compressed_len; /* total bit length of compressed file mod 2^32 */ @@ -294,6 +297,7 @@ void ZLIB_INTERNAL _tr_init OF((deflate_state *s)); int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len, int last)); +void ZLIB_INTERNAL _tr_flush_bits OF((deflate_state *s)); void ZLIB_INTERNAL _tr_align OF((deflate_state *s)); void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len, int last)); diff --git a/dep/zlib/gzguts.h b/dep/zlib/gzguts.h index 0f8fb79f87d..ee3f281aa57 100644 --- a/dep/zlib/gzguts.h +++ b/dep/zlib/gzguts.h @@ -1,5 +1,5 @@ /* gzguts.h -- zlib internal header definitions for gz* operations - * Copyright (C) 2004, 2005, 2010 Mark Adler + * Copyright (C) 2004, 2005, 2010, 2011, 2012 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -12,7 +12,7 @@ # endif #endif -#if ((__GNUC__-0) * 10 + __GNUC_MINOR__-0 >= 33) && !defined(NO_VIZ) +#ifdef HAVE_HIDDEN # define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) #else # define ZLIB_INTERNAL @@ -27,13 +27,65 @@ #endif #include <fcntl.h> +#ifdef _WIN32 +# include <stddef.h> +#endif + +#if defined(__TURBOC__) || defined(_MSC_VER) || defined(_WIN32) +# include <io.h> +#endif + #ifdef NO_DEFLATE /* for compatibility with old definition */ # define NO_GZCOMPRESS #endif -#ifdef _MSC_VER -# include <io.h> -# define vsnprintf _vsnprintf +#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#if defined(__CYGWIN__) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#if defined(MSDOS) && defined(__BORLANDC__) && (BORLANDC > 0x410) +# ifndef HAVE_VSNPRINTF +# define HAVE_VSNPRINTF +# endif +#endif + +#ifndef HAVE_VSNPRINTF +# ifdef MSDOS +/* vsnprintf may exist on some MS-DOS compilers (DJGPP?), + but for now we just assume it doesn't. */ +# define NO_vsnprintf +# endif +# ifdef __TURBOC__ +# define NO_vsnprintf +# endif +# ifdef WIN32 +/* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ +# if !defined(vsnprintf) && !defined(NO_vsnprintf) +# if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 ) +# define vsnprintf _vsnprintf +# endif +# endif +# endif +# ifdef __SASC +# define NO_vsnprintf +# endif +# ifdef VMS +# define NO_vsnprintf +# endif +# ifdef __OS400__ +# define NO_vsnprintf +# endif +# ifdef __MVS__ +# define NO_vsnprintf +# endif #endif #ifndef local @@ -52,7 +104,7 @@ # include <windows.h> # define zstrerror() gz_strwinerror((DWORD)GetLastError()) #else -# ifdef STDC +# ifndef NO_STRERROR # include <errno.h> # define zstrerror() strerror(errno) # else @@ -68,6 +120,13 @@ ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); #endif +/* default memLevel */ +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif + /* default i/o buffer size -- double this for output when reading */ #define GZBUFSIZE 8192 @@ -84,23 +143,25 @@ /* internal gzip file state data structure */ typedef struct { + /* exposed contents for gzgetc() macro */ + struct gzFile_s x; /* "x" for exposed */ + /* x.have: number of bytes available at x.next */ + /* x.next: next output data to deliver or write */ + /* x.pos: current position in uncompressed data */ /* used for both reading and writing */ int mode; /* see gzip modes above */ int fd; /* file descriptor */ char *path; /* path or fd for error messages */ - z_off64_t pos; /* current position in uncompressed data */ unsigned size; /* buffer size, zero if not allocated yet */ unsigned want; /* requested buffer size, default is GZBUFSIZE */ unsigned char *in; /* input buffer */ unsigned char *out; /* output buffer (double-sized when reading) */ - unsigned char *next; /* next output data to deliver or write */ + int direct; /* 0 if processing gzip, 1 if transparent */ /* just for reading */ - unsigned have; /* amount of output data unused at next */ - int eof; /* true if end of input file reached */ - z_off64_t start; /* where the gzip data started, for rewinding */ - z_off64_t raw; /* where the raw data started, for seeking */ int how; /* 0: get header, 1: copy, 2: decompress */ - int direct; /* true if last read direct, false if gzip */ + z_off64_t start; /* where the gzip data started, for rewinding */ + int eof; /* true if end of input file reached */ + int past; /* true if read requested past end */ /* just for writing */ int level; /* compression level */ int strategy; /* compression strategy */ diff --git a/dep/zlib/gzlib.c b/dep/zlib/gzlib.c index 603e60ed544..ca55c6ea926 100644 --- a/dep/zlib/gzlib.c +++ b/dep/zlib/gzlib.c @@ -1,19 +1,23 @@ /* gzlib.c -- zlib functions common to reading and writing gzip files - * Copyright (C) 2004, 2010 Mark Adler + * Copyright (C) 2004, 2010, 2011, 2012 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #include "gzguts.h" +#if defined(_WIN32) && !defined(__BORLANDC__) +# define LSEEK _lseeki64 +#else #if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 # define LSEEK lseek64 #else # define LSEEK lseek #endif +#endif /* Local functions */ local void gz_reset OF((gz_statep)); -local gzFile gz_open OF((const char *, int, const char *)); +local gzFile gz_open OF((const void *, int, const char *)); #if defined UNDER_CE @@ -71,25 +75,37 @@ char ZLIB_INTERNAL *gz_strwinerror (error) local void gz_reset(state) gz_statep state; { + state->x.have = 0; /* no output data available */ if (state->mode == GZ_READ) { /* for reading ... */ - state->have = 0; /* no output data available */ state->eof = 0; /* not at end of file */ + state->past = 0; /* have not read past end yet */ state->how = LOOK; /* look for gzip header */ - state->direct = 1; /* default for empty file */ } state->seek = 0; /* no seek request pending */ gz_error(state, Z_OK, NULL); /* clear error */ - state->pos = 0; /* no uncompressed data yet */ + state->x.pos = 0; /* no uncompressed data yet */ state->strm.avail_in = 0; /* no input data yet */ } /* Open a gzip file either by name or file descriptor. */ local gzFile gz_open(path, fd, mode) - const char *path; + const void *path; int fd; const char *mode; { gz_statep state; + size_t len; + int oflag; +#ifdef O_CLOEXEC + int cloexec = 0; +#endif +#ifdef O_EXCL + int exclusive = 0; +#endif + + /* check input */ + if (path == NULL) + return NULL; /* allocate gzFile structure to return */ state = malloc(sizeof(gz_state)); @@ -103,6 +119,7 @@ local gzFile gz_open(path, fd, mode) state->mode = GZ_NONE; state->level = Z_DEFAULT_COMPRESSION; state->strategy = Z_DEFAULT_STRATEGY; + state->direct = 0; while (*mode) { if (*mode >= '0' && *mode <= '9') state->level = *mode - '0'; @@ -124,6 +141,16 @@ local gzFile gz_open(path, fd, mode) return NULL; case 'b': /* ignore -- will request binary anyway */ break; +#ifdef O_CLOEXEC + case 'e': + cloexec = 1; + break; +#endif +#ifdef O_EXCL + case 'x': + exclusive = 1; + break; +#endif case 'f': state->strategy = Z_FILTERED; break; @@ -135,6 +162,8 @@ local gzFile gz_open(path, fd, mode) break; case 'F': state->strategy = Z_FIXED; + case 'T': + state->direct = 1; default: /* could consider as an error, but just ignore */ ; } @@ -147,30 +176,67 @@ local gzFile gz_open(path, fd, mode) return NULL; } + /* can't force transparent read */ + if (state->mode == GZ_READ) { + if (state->direct) { + free(state); + return NULL; + } + state->direct = 1; /* for empty file */ + } + /* save the path name for error messages */ - state->path = malloc(strlen(path) + 1); +#ifdef _WIN32 + if (fd == -2) { + len = wcstombs(NULL, path, 0); + if (len == (size_t)-1) + len = 0; + } + else +#endif + len = strlen(path); + state->path = malloc(len + 1); if (state->path == NULL) { free(state); return NULL; } - strcpy(state->path, path); +#ifdef _WIN32 + if (fd == -2) + if (len) + wcstombs(state->path, path, len + 1); + else + *(state->path) = 0; + else +#endif + strcpy(state->path, path); - /* open the file with the appropriate mode (or just use fd) */ - state->fd = fd != -1 ? fd : - open(path, + /* compute the flags for open() */ + oflag = #ifdef O_LARGEFILE - O_LARGEFILE | + O_LARGEFILE | #endif #ifdef O_BINARY - O_BINARY | + O_BINARY | +#endif +#ifdef O_CLOEXEC + (cloexec ? O_CLOEXEC : 0) | #endif - (state->mode == GZ_READ ? - O_RDONLY : - (O_WRONLY | O_CREAT | ( - state->mode == GZ_WRITE ? - O_TRUNC : - O_APPEND))), - 0666); + (state->mode == GZ_READ ? + O_RDONLY : + (O_WRONLY | O_CREAT | +#ifdef O_EXCL + (exclusive ? O_EXCL : 0) | +#endif + (state->mode == GZ_WRITE ? + O_TRUNC : + O_APPEND))); + + /* open the file with the appropriate flags (or just use fd) */ + state->fd = fd > -1 ? fd : ( +#ifdef _WIN32 + fd == -2 ? _wopen(path, oflag, 0666) : +#endif + open(path, oflag, 0666)); if (state->fd == -1) { free(state->path); free(state); @@ -225,6 +291,16 @@ gzFile ZEXPORT gzdopen(fd, mode) } /* -- see zlib.h -- */ +#ifdef _WIN32 +gzFile ZEXPORT gzopen_w(path, mode) + const wchar_t *path; + const char *mode; +{ + return gz_open(path, -2, mode); +} +#endif + +/* -- see zlib.h -- */ int ZEXPORT gzbuffer(file, size) gzFile file; unsigned size; @@ -243,8 +319,8 @@ int ZEXPORT gzbuffer(file, size) return -1; /* check and set requested size */ - if (size == 0) - return -1; + if (size < 2) + size = 2; /* need two bytes to check magic header */ state->want = size; return 0; } @@ -261,7 +337,8 @@ int ZEXPORT gzrewind(file) state = (gz_statep)file; /* check that we're reading and that there's no error */ - if (state->mode != GZ_READ || state->err != Z_OK) + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) return -1; /* back up and start over */ @@ -289,7 +366,7 @@ z_off64_t ZEXPORT gzseek64(file, offset, whence) return -1; /* check that there's no error */ - if (state->err != Z_OK) + if (state->err != Z_OK && state->err != Z_BUF_ERROR) return -1; /* can only seek from start or relative to current position */ @@ -298,31 +375,32 @@ z_off64_t ZEXPORT gzseek64(file, offset, whence) /* normalize offset to a SEEK_CUR specification */ if (whence == SEEK_SET) - offset -= state->pos; + offset -= state->x.pos; else if (state->seek) offset += state->skip; state->seek = 0; /* if within raw area while reading, just go there */ if (state->mode == GZ_READ && state->how == COPY && - state->pos + offset >= state->raw) { - ret = LSEEK(state->fd, offset - state->have, SEEK_CUR); + state->x.pos + offset >= 0) { + ret = LSEEK(state->fd, offset - state->x.have, SEEK_CUR); if (ret == -1) return -1; - state->have = 0; + state->x.have = 0; state->eof = 0; + state->past = 0; state->seek = 0; gz_error(state, Z_OK, NULL); state->strm.avail_in = 0; - state->pos += offset; - return state->pos; + state->x.pos += offset; + return state->x.pos; } /* calculate skip amount, rewinding if needed for back seek when reading */ if (offset < 0) { if (state->mode != GZ_READ) /* writing -- can't go backwards */ return -1; - offset += state->pos; + offset += state->x.pos; if (offset < 0) /* before start of file! */ return -1; if (gzrewind(file) == -1) /* rewind, then skip to offset */ @@ -331,11 +409,11 @@ z_off64_t ZEXPORT gzseek64(file, offset, whence) /* if reading, skip what's in output buffer (one less gzgetc() check) */ if (state->mode == GZ_READ) { - n = GT_OFF(state->have) || (z_off64_t)state->have > offset ? - (unsigned)offset : state->have; - state->have -= n; - state->next += n; - state->pos += n; + n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > offset ? + (unsigned)offset : state->x.have; + state->x.have -= n; + state->x.next += n; + state->x.pos += n; offset -= n; } @@ -344,7 +422,7 @@ z_off64_t ZEXPORT gzseek64(file, offset, whence) state->seek = 1; state->skip = offset; } - return state->pos + offset; + return state->x.pos + offset; } /* -- see zlib.h -- */ @@ -373,7 +451,7 @@ z_off64_t ZEXPORT gztell64(file) return -1; /* return position */ - return state->pos + (state->seek ? state->skip : 0); + return state->x.pos + (state->seek ? state->skip : 0); } /* -- see zlib.h -- */ @@ -433,8 +511,7 @@ int ZEXPORT gzeof(file) return 0; /* return end-of-file state */ - return state->mode == GZ_READ ? - (state->eof && state->strm.avail_in == 0 && state->have == 0) : 0; + return state->mode == GZ_READ ? state->past : 0; } /* -- see zlib.h -- */ @@ -471,8 +548,10 @@ void ZEXPORT gzclearerr(file) return; /* clear error and end-of-file */ - if (state->mode == GZ_READ) + if (state->mode == GZ_READ) { state->eof = 0; + state->past = 0; + } gz_error(state, Z_OK, NULL); } @@ -494,6 +573,10 @@ void ZLIB_INTERNAL gz_error(state, err, msg) state->msg = NULL; } + /* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */ + if (err != Z_OK && err != Z_BUF_ERROR) + state->x.have = 0; + /* set error code, and if no message, then done */ state->err = err; if (msg == NULL) diff --git a/dep/zlib/gzread.c b/dep/zlib/gzread.c index 548201ab009..3493d34d4ea 100644 --- a/dep/zlib/gzread.c +++ b/dep/zlib/gzread.c @@ -1,5 +1,5 @@ /* gzread.c -- zlib functions for reading gzip files - * Copyright (C) 2004, 2005, 2010 Mark Adler + * Copyright (C) 2004, 2005, 2010, 2011, 2012 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -8,10 +8,9 @@ /* Local functions */ local int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *)); local int gz_avail OF((gz_statep)); -local int gz_next4 OF((gz_statep, unsigned long *)); -local int gz_head OF((gz_statep)); +local int gz_look OF((gz_statep)); local int gz_decomp OF((gz_statep)); -local int gz_make OF((gz_statep)); +local int gz_fetch OF((gz_statep)); local int gz_skip OF((gz_statep, z_off64_t)); /* Use read() to load a buffer -- return -1 on error, otherwise 0. Read from @@ -46,67 +45,47 @@ local int gz_load(state, buf, len, have) error, 0 otherwise. Note that the eof flag is set when the end of the input file is reached, even though there may be unused data in the buffer. Once that data has been used, no more attempts will be made to read the file. - gz_avail() assumes that strm->avail_in == 0. */ + If strm->avail_in != 0, then the current data is moved to the beginning of + the input buffer, and then the remainder of the buffer is loaded with the + available data from the input file. */ local int gz_avail(state) gz_statep state; { + unsigned got; z_streamp strm = &(state->strm); - if (state->err != Z_OK) + if (state->err != Z_OK && state->err != Z_BUF_ERROR) return -1; if (state->eof == 0) { - if (gz_load(state, state->in, state->size, - (unsigned *)&(strm->avail_in)) == -1) + if (strm->avail_in) { /* copy what's there to the start */ + unsigned char *p = state->in, *q = strm->next_in; + unsigned n = strm->avail_in; + do { + *p++ = *q++; + } while (--n); + } + if (gz_load(state, state->in + strm->avail_in, + state->size - strm->avail_in, &got) == -1) return -1; + strm->avail_in += got; strm->next_in = state->in; } return 0; } -/* Get next byte from input, or -1 if end or error. */ -#define NEXT() ((strm->avail_in == 0 && gz_avail(state) == -1) ? -1 : \ - (strm->avail_in == 0 ? -1 : \ - (strm->avail_in--, *(strm->next_in)++))) - -/* Get a four-byte little-endian integer and return 0 on success and the value - in *ret. Otherwise -1 is returned and *ret is not modified. */ -local int gz_next4(state, ret) - gz_statep state; - unsigned long *ret; -{ - int ch; - unsigned long val; - z_streamp strm = &(state->strm); - - val = NEXT(); - val += (unsigned)NEXT() << 8; - val += (unsigned long)NEXT() << 16; - ch = NEXT(); - if (ch == -1) - return -1; - val += (unsigned long)ch << 24; - *ret = val; - return 0; -} - -/* Look for gzip header, set up for inflate or copy. state->have must be zero. +/* Look for gzip header, set up for inflate or copy. state->x.have must be 0. If this is the first time in, allocate required memory. state->how will be left unchanged if there is no more input data available, will be set to COPY if there is no gzip header and direct copying will be performed, or it will - be set to GZIP for decompression, and the gzip header will be skipped so - that the next available input data is the raw deflate stream. If direct - copying, then leftover input data from the input buffer will be copied to - the output buffer. In that case, all further file reads will be directly to - either the output buffer or a user buffer. If decompressing, the inflate - state and the check value will be initialized. gz_head() will return 0 on - success or -1 on failure. Failures may include read errors or gzip header - errors. */ -local int gz_head(state) + be set to GZIP for decompression. If direct copying, then leftover input + data from the input buffer will be copied to the output buffer. In that + case, all further file reads will be directly to either the output buffer or + a user buffer. If decompressing, the inflate state will be initialized. + gz_look() will return 0 on success or -1 on failure. */ +local int gz_look(state) gz_statep state; { z_streamp strm = &(state->strm); - int flags; - unsigned len; /* allocate read buffers and inflate memory */ if (state->size == 0) { @@ -129,7 +108,7 @@ local int gz_head(state) state->strm.opaque = Z_NULL; state->strm.avail_in = 0; state->strm.next_in = Z_NULL; - if (inflateInit2(&(state->strm), -15) != Z_OK) { /* raw inflate */ + if (inflateInit2(&(state->strm), 15 + 16) != Z_OK) { /* gunzip */ free(state->out); free(state->in); state->size = 0; @@ -138,83 +117,45 @@ local int gz_head(state) } } - /* get some data in the input buffer */ - if (strm->avail_in == 0) { + /* get at least the magic bytes in the input buffer */ + if (strm->avail_in < 2) { if (gz_avail(state) == -1) return -1; if (strm->avail_in == 0) return 0; } - /* look for the gzip magic header bytes 31 and 139 */ - if (strm->next_in[0] == 31) { - strm->avail_in--; - strm->next_in++; - if (strm->avail_in == 0 && gz_avail(state) == -1) - return -1; - if (strm->avail_in && strm->next_in[0] == 139) { - /* we have a gzip header, woo hoo! */ - strm->avail_in--; - strm->next_in++; - - /* skip rest of header */ - if (NEXT() != 8) { /* compression method */ - gz_error(state, Z_DATA_ERROR, "unknown compression method"); - return -1; - } - flags = NEXT(); - if (flags & 0xe0) { /* reserved flag bits */ - gz_error(state, Z_DATA_ERROR, "unknown header flags set"); - return -1; - } - NEXT(); /* modification time */ - NEXT(); - NEXT(); - NEXT(); - NEXT(); /* extra flags */ - NEXT(); /* operating system */ - if (flags & 4) { /* extra field */ - len = (unsigned)NEXT(); - len += (unsigned)NEXT() << 8; - while (len--) - if (NEXT() < 0) - break; - } - if (flags & 8) /* file name */ - while (NEXT() > 0) - ; - if (flags & 16) /* comment */ - while (NEXT() > 0) - ; - if (flags & 2) { /* header crc */ - NEXT(); - NEXT(); - } - /* an unexpected end of file is not checked for here -- it will be - noticed on the first request for uncompressed data */ - - /* set up for decompression */ - inflateReset(strm); - strm->adler = crc32(0L, Z_NULL, 0); - state->how = GZIP; - state->direct = 0; - return 0; - } - else { - /* not a gzip file -- save first byte (31) and fall to raw i/o */ - state->out[0] = 31; - state->have = 1; - } + /* look for gzip magic bytes -- if there, do gzip decoding (note: there is + a logical dilemma here when considering the case of a partially written + gzip file, to wit, if a single 31 byte is written, then we cannot tell + whether this is a single-byte file, or just a partially written gzip + file -- for here we assume that if a gzip file is being written, then + the header will be written in a single operation, so that reading a + single byte is sufficient indication that it is not a gzip file) */ + if (strm->avail_in > 1 && + strm->next_in[0] == 31 && strm->next_in[1] == 139) { + inflateReset(strm); + state->how = GZIP; + state->direct = 0; + return 0; + } + + /* no gzip header -- if we were decoding gzip before, then this is trailing + garbage. Ignore the trailing garbage and finish. */ + if (state->direct == 0) { + strm->avail_in = 0; + state->eof = 1; + state->x.have = 0; + return 0; } - /* doing raw i/o, save start of raw data for seeking, copy any leftover - input to output -- this assumes that the output buffer is larger than - the input buffer, which also assures space for gzungetc() */ - state->raw = state->pos; - state->next = state->out; + /* doing raw i/o, copy any leftover input to output -- this assumes that + the output buffer is larger than the input buffer, which also assures + space for gzungetc() */ + state->x.next = state->out; if (strm->avail_in) { - memcpy(state->next + state->have, strm->next_in, strm->avail_in); - state->have += strm->avail_in; + memcpy(state->x.next, strm->next_in, strm->avail_in); + state->x.have = strm->avail_in; strm->avail_in = 0; } state->how = COPY; @@ -223,19 +164,15 @@ local int gz_head(state) } /* Decompress from input to the provided next_out and avail_out in the state. - If the end of the compressed data is reached, then verify the gzip trailer - check value and length (modulo 2^32). state->have and state->next are set - to point to the just decompressed data, and the crc is updated. If the - trailer is verified, state->how is reset to LOOK to look for the next gzip - stream or raw data, once state->have is depleted. Returns 0 on success, -1 - on failure. Failures may include invalid compressed data or a failed gzip - trailer verification. */ + On return, state->x.have and state->x.next point to the just decompressed + data. If the gzip stream completes, state->how is reset to LOOK to look for + the next gzip stream or raw data, once state->x.have is depleted. Returns 0 + on success, -1 on failure. */ local int gz_decomp(state) gz_statep state; { - int ret; + int ret = Z_OK; unsigned had; - unsigned long crc, len; z_streamp strm = &(state->strm); /* fill output buffer up to end of deflate stream */ @@ -245,15 +182,15 @@ local int gz_decomp(state) if (strm->avail_in == 0 && gz_avail(state) == -1) return -1; if (strm->avail_in == 0) { - gz_error(state, Z_DATA_ERROR, "unexpected end of file"); - return -1; + gz_error(state, Z_BUF_ERROR, "unexpected end of file"); + break; } /* decompress and handle errors */ ret = inflate(strm, Z_NO_FLUSH); if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) { gz_error(state, Z_STREAM_ERROR, - "internal error: inflate stream corrupt"); + "internal error: inflate stream corrupt"); return -1; } if (ret == Z_MEM_ERROR) { @@ -262,67 +199,55 @@ local int gz_decomp(state) } if (ret == Z_DATA_ERROR) { /* deflate stream invalid */ gz_error(state, Z_DATA_ERROR, - strm->msg == NULL ? "compressed data error" : strm->msg); + strm->msg == NULL ? "compressed data error" : strm->msg); return -1; } } while (strm->avail_out && ret != Z_STREAM_END); - /* update available output and crc check value */ - state->have = had - strm->avail_out; - state->next = strm->next_out - state->have; - strm->adler = crc32(strm->adler, state->next, state->have); + /* update available output */ + state->x.have = had - strm->avail_out; + state->x.next = strm->next_out - state->x.have; - /* check gzip trailer if at end of deflate stream */ - if (ret == Z_STREAM_END) { - if (gz_next4(state, &crc) == -1 || gz_next4(state, &len) == -1) { - gz_error(state, Z_DATA_ERROR, "unexpected end of file"); - return -1; - } - if (crc != strm->adler) { - gz_error(state, Z_DATA_ERROR, "incorrect data check"); - return -1; - } - if (len != (strm->total_out & 0xffffffffL)) { - gz_error(state, Z_DATA_ERROR, "incorrect length check"); - return -1; - } - state->how = LOOK; /* ready for next stream, once have is 0 (leave - state->direct unchanged to remember how) */ - } + /* if the gzip stream completed successfully, look for another */ + if (ret == Z_STREAM_END) + state->how = LOOK; /* good decompression */ return 0; } -/* Make data and put in the output buffer. Assumes that state->have == 0. +/* Fetch data and put it in the output buffer. Assumes state->x.have is 0. Data is either copied from the input file or decompressed from the input file depending on state->how. If state->how is LOOK, then a gzip header is - looked for (and skipped if found) to determine wither to copy or decompress. - Returns -1 on error, otherwise 0. gz_make() will leave state->have as COPY - or GZIP unless the end of the input file has been reached and all data has - been processed. */ -local int gz_make(state) + looked for to determine whether to copy or decompress. Returns -1 on error, + otherwise 0. gz_fetch() will leave state->how as COPY or GZIP unless the + end of the input file has been reached and all data has been processed. */ +local int gz_fetch(state) gz_statep state; { z_streamp strm = &(state->strm); - if (state->how == LOOK) { /* look for gzip header */ - if (gz_head(state) == -1) - return -1; - if (state->have) /* got some data from gz_head() */ + do { + switch(state->how) { + case LOOK: /* -> LOOK, COPY (only if never GZIP), or GZIP */ + if (gz_look(state) == -1) + return -1; + if (state->how == LOOK) + return 0; + break; + case COPY: /* -> COPY */ + if (gz_load(state, state->out, state->size << 1, &(state->x.have)) + == -1) + return -1; + state->x.next = state->out; return 0; - } - if (state->how == COPY) { /* straight copy */ - if (gz_load(state, state->out, state->size << 1, &(state->have)) == -1) - return -1; - state->next = state->out; - } - else if (state->how == GZIP) { /* decompress */ - strm->avail_out = state->size << 1; - strm->next_out = state->out; - if (gz_decomp(state) == -1) - return -1; - } + case GZIP: /* -> GZIP or LOOK (if end of gzip stream) */ + strm->avail_out = state->size << 1; + strm->next_out = state->out; + if (gz_decomp(state) == -1) + return -1; + } + } while (state->x.have == 0 && (!state->eof || strm->avail_in)); return 0; } @@ -336,12 +261,12 @@ local int gz_skip(state, len) /* skip over len bytes or reach end-of-file, whichever comes first */ while (len) /* skip over whatever is in output buffer */ - if (state->have) { - n = GT_OFF(state->have) || (z_off64_t)state->have > len ? - (unsigned)len : state->have; - state->have -= n; - state->next += n; - state->pos += n; + if (state->x.have) { + n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > len ? + (unsigned)len : state->x.have; + state->x.have -= n; + state->x.next += n; + state->x.pos += n; len -= n; } @@ -352,7 +277,7 @@ local int gz_skip(state, len) /* need more data to skip -- load up output buffer */ else { /* get more output, looking for header if required */ - if (gz_make(state) == -1) + if (gz_fetch(state) == -1) return -1; } return 0; @@ -374,14 +299,15 @@ int ZEXPORT gzread(file, buf, len) state = (gz_statep)file; strm = &(state->strm); - /* check that we're reading and that there's no error */ - if (state->mode != GZ_READ || state->err != Z_OK) + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) return -1; /* since an int is returned, make sure len fits in one, otherwise return with an error (this avoids the flaw in the interface) */ if ((int)len < 0) { - gz_error(state, Z_BUF_ERROR, "requested length does not fit in int"); + gz_error(state, Z_DATA_ERROR, "requested length does not fit in int"); return -1; } @@ -400,24 +326,26 @@ int ZEXPORT gzread(file, buf, len) got = 0; do { /* first just try copying data from the output buffer */ - if (state->have) { - n = state->have > len ? len : state->have; - memcpy(buf, state->next, n); - state->next += n; - state->have -= n; + if (state->x.have) { + n = state->x.have > len ? len : state->x.have; + memcpy(buf, state->x.next, n); + state->x.next += n; + state->x.have -= n; } /* output buffer empty -- return if we're at the end of the input */ - else if (state->eof && strm->avail_in == 0) + else if (state->eof && strm->avail_in == 0) { + state->past = 1; /* tried to read past end */ break; + } /* need output data -- for small len or new stream load up our output buffer */ else if (state->how == LOOK || len < (state->size << 1)) { /* get more output, looking for header if required */ - if (gz_make(state) == -1) + if (gz_fetch(state) == -1) return -1; - continue; /* no progress yet -- go back to memcpy() above */ + continue; /* no progress yet -- go back to copy above */ /* the copy above assures that we will leave with space in the output buffer, allowing at least one gzungetc() to succeed */ } @@ -434,15 +362,15 @@ int ZEXPORT gzread(file, buf, len) strm->next_out = buf; if (gz_decomp(state) == -1) return -1; - n = state->have; - state->have = 0; + n = state->x.have; + state->x.have = 0; } /* update progress */ len -= n; buf = (char *)buf + n; got += n; - state->pos += n; + state->x.pos += n; } while (len); /* return number of bytes read into user buffer (will fit in int) */ @@ -450,6 +378,7 @@ int ZEXPORT gzread(file, buf, len) } /* -- see zlib.h -- */ +#undef gzgetc int ZEXPORT gzgetc(file) gzFile file; { @@ -462,15 +391,16 @@ int ZEXPORT gzgetc(file) return -1; state = (gz_statep)file; - /* check that we're reading and that there's no error */ - if (state->mode != GZ_READ || state->err != Z_OK) + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) return -1; /* try output buffer (no need to check for skip request) */ - if (state->have) { - state->have--; - state->pos++; - return *(state->next)++; + if (state->x.have) { + state->x.have--; + state->x.pos++; + return *(state->x.next)++; } /* nothing there -- try gzread() */ @@ -478,6 +408,12 @@ int ZEXPORT gzgetc(file) return ret < 1 ? -1 : buf[0]; } +int ZEXPORT gzgetc_(file) +gzFile file; +{ + return gzgetc(file); +} + /* -- see zlib.h -- */ int ZEXPORT gzungetc(c, file) int c; @@ -490,8 +426,9 @@ int ZEXPORT gzungetc(c, file) return -1; state = (gz_statep)file; - /* check that we're reading and that there's no error */ - if (state->mode != GZ_READ || state->err != Z_OK) + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) return -1; /* process a skip request */ @@ -506,32 +443,34 @@ int ZEXPORT gzungetc(c, file) return -1; /* if output buffer empty, put byte at end (allows more pushing) */ - if (state->have == 0) { - state->have = 1; - state->next = state->out + (state->size << 1) - 1; - state->next[0] = c; - state->pos--; + if (state->x.have == 0) { + state->x.have = 1; + state->x.next = state->out + (state->size << 1) - 1; + state->x.next[0] = c; + state->x.pos--; + state->past = 0; return c; } /* if no room, give up (must have already done a gzungetc()) */ - if (state->have == (state->size << 1)) { - gz_error(state, Z_BUF_ERROR, "out of room to push characters"); + if (state->x.have == (state->size << 1)) { + gz_error(state, Z_DATA_ERROR, "out of room to push characters"); return -1; } /* slide output data if needed and insert byte before existing data */ - if (state->next == state->out) { - unsigned char *src = state->out + state->have; + if (state->x.next == state->out) { + unsigned char *src = state->out + state->x.have; unsigned char *dest = state->out + (state->size << 1); while (src > state->out) *--dest = *--src; - state->next = dest; + state->x.next = dest; } - state->have++; - state->next--; - state->next[0] = c; - state->pos--; + state->x.have++; + state->x.next--; + state->x.next[0] = c; + state->x.pos--; + state->past = 0; return c; } @@ -551,8 +490,9 @@ char * ZEXPORT gzgets(file, buf, len) return NULL; state = (gz_statep)file; - /* check that we're reading and that there's no error */ - if (state->mode != GZ_READ || state->err != Z_OK) + /* check that we're reading and that there's no (serious) error */ + if (state->mode != GZ_READ || + (state->err != Z_OK && state->err != Z_BUF_ERROR)) return NULL; /* process a skip request */ @@ -569,32 +509,31 @@ char * ZEXPORT gzgets(file, buf, len) left = (unsigned)len - 1; if (left) do { /* assure that something is in the output buffer */ - if (state->have == 0) { - if (gz_make(state) == -1) - return NULL; /* error */ - if (state->have == 0) { /* end of file */ - if (buf == str) /* got bupkus */ - return NULL; - break; /* got something -- return it */ - } + if (state->x.have == 0 && gz_fetch(state) == -1) + return NULL; /* error */ + if (state->x.have == 0) { /* end of file */ + state->past = 1; /* read past end */ + break; /* return what we have */ } /* look for end-of-line in current output buffer */ - n = state->have > left ? left : state->have; - eol = memchr(state->next, '\n', n); + n = state->x.have > left ? left : state->x.have; + eol = memchr(state->x.next, '\n', n); if (eol != NULL) - n = (unsigned)(eol - state->next) + 1; + n = (unsigned)(eol - state->x.next) + 1; /* copy through end-of-line, or remainder if not found */ - memcpy(buf, state->next, n); - state->have -= n; - state->next += n; - state->pos += n; + memcpy(buf, state->x.next, n); + state->x.have -= n; + state->x.next += n; + state->x.pos += n; left -= n; buf += n; } while (left && eol == NULL); - /* found end-of-line or out of space -- terminate string and return it */ + /* return terminated string, or if nothing, end of file */ + if (buf == str) + return NULL; buf[0] = 0; return str; } @@ -610,16 +549,12 @@ int ZEXPORT gzdirect(file) return 0; state = (gz_statep)file; - /* check that we're reading */ - if (state->mode != GZ_READ) - return 0; - /* if the state is not known, but we can find out, then do so (this is mainly for right after a gzopen() or gzdopen()) */ - if (state->how == LOOK && state->have == 0) - (void)gz_head(state); + if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0) + (void)gz_look(state); - /* return 1 if reading direct, 0 if decompressing a gzip stream */ + /* return 1 if transparent, 0 if processing a gzip stream */ return state->direct; } @@ -627,7 +562,7 @@ int ZEXPORT gzdirect(file) int ZEXPORT gzclose_r(file) gzFile file; { - int ret; + int ret, err; gz_statep state; /* get internal structure */ @@ -645,9 +580,10 @@ int ZEXPORT gzclose_r(file) free(state->out); free(state->in); } + err = state->err == Z_BUF_ERROR ? Z_BUF_ERROR : Z_OK; gz_error(state, Z_OK, NULL); free(state->path); ret = close(state->fd); free(state); - return ret ? Z_ERRNO : Z_OK; + return ret ? Z_ERRNO : err; } diff --git a/dep/zlib/gzwrite.c b/dep/zlib/gzwrite.c index e8defc6887a..27cb3428e32 100644 --- a/dep/zlib/gzwrite.c +++ b/dep/zlib/gzwrite.c @@ -1,5 +1,5 @@ /* gzwrite.c -- zlib functions for writing gzip files - * Copyright (C) 2004, 2005, 2010 Mark Adler + * Copyright (C) 2004, 2005, 2010, 2011, 2012 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -18,44 +18,55 @@ local int gz_init(state) int ret; z_streamp strm = &(state->strm); - /* allocate input and output buffers */ + /* allocate input buffer */ state->in = malloc(state->want); - state->out = malloc(state->want); - if (state->in == NULL || state->out == NULL) { - if (state->out != NULL) - free(state->out); - if (state->in != NULL) - free(state->in); + if (state->in == NULL) { gz_error(state, Z_MEM_ERROR, "out of memory"); return -1; } - /* allocate deflate memory, set up for gzip compression */ - strm->zalloc = Z_NULL; - strm->zfree = Z_NULL; - strm->opaque = Z_NULL; - ret = deflateInit2(strm, state->level, Z_DEFLATED, - 15 + 16, 8, state->strategy); - if (ret != Z_OK) { - free(state->in); - gz_error(state, Z_MEM_ERROR, "out of memory"); - return -1; + /* only need output buffer and deflate state if compressing */ + if (!state->direct) { + /* allocate output buffer */ + state->out = malloc(state->want); + if (state->out == NULL) { + free(state->in); + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } + + /* allocate deflate memory, set up for gzip compression */ + strm->zalloc = Z_NULL; + strm->zfree = Z_NULL; + strm->opaque = Z_NULL; + ret = deflateInit2(strm, state->level, Z_DEFLATED, + MAX_WBITS + 16, DEF_MEM_LEVEL, state->strategy); + if (ret != Z_OK) { + free(state->out); + free(state->in); + gz_error(state, Z_MEM_ERROR, "out of memory"); + return -1; + } } /* mark state as initialized */ state->size = state->want; - /* initialize write buffer */ - strm->avail_out = state->size; - strm->next_out = state->out; - state->next = strm->next_out; + /* initialize write buffer if compressing */ + if (!state->direct) { + strm->avail_out = state->size; + strm->next_out = state->out; + state->x.next = strm->next_out; + } return 0; } /* Compress whatever is at avail_in and next_in and write to the output file. Return -1 if there is an error writing to the output file, otherwise 0. flush is assumed to be a valid deflate() flush value. If flush is Z_FINISH, - then the deflate() state is reset to start a new gzip stream. */ + then the deflate() state is reset to start a new gzip stream. If gz->direct + is true, then simply write to the output file without compressing, and + ignore flush. */ local int gz_comp(state, flush) gz_statep state; int flush; @@ -68,6 +79,17 @@ local int gz_comp(state, flush) if (state->size == 0 && gz_init(state) == -1) return -1; + /* write directly if requested */ + if (state->direct) { + got = write(state->fd, strm->next_in, strm->avail_in); + if (got < 0 || (unsigned)got != strm->avail_in) { + gz_error(state, Z_ERRNO, zstrerror()); + return -1; + } + strm->avail_in = 0; + return 0; + } + /* run deflate() on provided input until it produces no more output */ ret = Z_OK; do { @@ -75,8 +97,8 @@ local int gz_comp(state, flush) doing Z_FINISH then don't write until we get to Z_STREAM_END */ if (strm->avail_out == 0 || (flush != Z_NO_FLUSH && (flush != Z_FINISH || ret == Z_STREAM_END))) { - have = (unsigned)(strm->next_out - state->next); - if (have && ((got = write(state->fd, state->next, have)) < 0 || + have = (unsigned)(strm->next_out - state->x.next); + if (have && ((got = write(state->fd, state->x.next, have)) < 0 || (unsigned)got != have)) { gz_error(state, Z_ERRNO, zstrerror()); return -1; @@ -85,7 +107,7 @@ local int gz_comp(state, flush) strm->avail_out = state->size; strm->next_out = state->out; } - state->next = strm->next_out; + state->x.next = strm->next_out; } /* compress */ @@ -131,7 +153,7 @@ local int gz_zero(state, len) } strm->avail_in = n; strm->next_in = state->in; - state->pos += n; + state->x.pos += n; if (gz_comp(state, Z_NO_FLUSH) == -1) return -1; len -= n; @@ -163,7 +185,7 @@ int ZEXPORT gzwrite(file, buf, len) /* since an int is returned, make sure len fits in one, otherwise return with an error (this avoids the flaw in the interface) */ if ((int)len < 0) { - gz_error(state, Z_BUF_ERROR, "requested length does not fit in int"); + gz_error(state, Z_DATA_ERROR, "requested length does not fit in int"); return 0; } @@ -193,7 +215,7 @@ int ZEXPORT gzwrite(file, buf, len) n = len; memcpy(strm->next_in + strm->avail_in, buf, n); strm->avail_in += n; - state->pos += n; + state->x.pos += n; buf = (char *)buf + n; len -= n; if (len && gz_comp(state, Z_NO_FLUSH) == -1) @@ -208,7 +230,7 @@ int ZEXPORT gzwrite(file, buf, len) /* directly compress user buffer to file */ strm->avail_in = len; strm->next_in = (voidp)buf; - state->pos += len; + state->x.pos += len; if (gz_comp(state, Z_NO_FLUSH) == -1) return 0; } @@ -249,15 +271,15 @@ int ZEXPORT gzputc(file, c) if (strm->avail_in == 0) strm->next_in = state->in; strm->next_in[strm->avail_in++] = c; - state->pos++; - return c; + state->x.pos++; + return c & 0xff; } /* no room in buffer or not initialized, use gz_write() */ buf[0] = c; if (gzwrite(file, buf, 1) != 1) return -1; - return c; + return c & 0xff; } /* -- see zlib.h -- */ @@ -274,7 +296,7 @@ int ZEXPORT gzputs(file, str) return ret == 0 && len != 0 ? -1 : ret; } -#ifdef STDC +#if defined(STDC) || defined(Z_HAVE_STDARG_H) #include <stdarg.h> /* -- see zlib.h -- */ @@ -316,19 +338,19 @@ int ZEXPORTVA gzprintf (gzFile file, const char *format, ...) va_start(va, format); #ifdef NO_vsnprintf # ifdef HAS_vsprintf_void - (void)vsprintf(state->in, format, va); + (void)vsprintf((char *)(state->in), format, va); va_end(va); for (len = 0; len < size; len++) if (state->in[len] == 0) break; # else - len = vsprintf(state->in, format, va); + len = vsprintf((char *)(state->in), format, va); va_end(va); # endif #else # ifdef HAS_vsnprintf_void - (void)vsnprintf(state->in, size, format, va); + (void)vsnprintf((char *)(state->in), size, format, va); va_end(va); - len = strlen(state->in); + len = strlen((char *)(state->in)); # else len = vsnprintf((char *)(state->in), size, format, va); va_end(va); @@ -342,11 +364,11 @@ int ZEXPORTVA gzprintf (gzFile file, const char *format, ...) /* update buffer and position, defer compression until needed */ strm->avail_in = (unsigned)len; strm->next_in = state->in; - state->pos += len; + state->x.pos += len; return len; } -#else /* !STDC */ +#else /* !STDC && !Z_HAVE_STDARG_H */ /* -- see zlib.h -- */ int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, @@ -366,6 +388,10 @@ int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, state = (gz_statep)file; strm = &(state->strm); + /* check that can really pass pointer in ints */ + if (sizeof(int) != sizeof(void *)) + return 0; + /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return 0; @@ -390,22 +416,23 @@ int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, state->in[size - 1] = 0; #ifdef NO_snprintf # ifdef HAS_sprintf_void - sprintf(state->in, format, a1, a2, a3, a4, a5, a6, a7, a8, + sprintf((char *)(state->in), format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); for (len = 0; len < size; len++) if (state->in[len] == 0) break; # else - len = sprintf(state->in, format, a1, a2, a3, a4, a5, a6, a7, a8, - a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); + len = sprintf((char *)(state->in), format, a1, a2, a3, a4, a5, a6, a7, a8, + a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); # endif #else # ifdef HAS_snprintf_void - snprintf(state->in, size, format, a1, a2, a3, a4, a5, a6, a7, a8, + snprintf((char *)(state->in), size, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); - len = strlen(state->in); + len = strlen((char *)(state->in)); # else - len = snprintf(state->in, size, format, a1, a2, a3, a4, a5, a6, a7, a8, - a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); + len = snprintf((char *)(state->in), size, format, a1, a2, a3, a4, a5, a6, + a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, + a19, a20); # endif #endif @@ -416,7 +443,7 @@ int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, /* update buffer and position, defer compression until needed */ strm->avail_in = (unsigned)len; strm->next_in = state->in; - state->pos += len; + state->x.pos += len; return len; } @@ -500,7 +527,7 @@ int ZEXPORT gzsetparams(file, level, strategy) int ZEXPORT gzclose_w(file) gzFile file; { - int ret = 0; + int ret = Z_OK; gz_statep state; /* get internal structure */ @@ -515,17 +542,24 @@ int ZEXPORT gzclose_w(file) /* check for seek request */ if (state->seek) { state->seek = 0; - ret += gz_zero(state, state->skip); + if (gz_zero(state, state->skip) == -1) + ret = state->err; } /* flush, free memory, and close file */ - ret += gz_comp(state, Z_FINISH); - (void)deflateEnd(&(state->strm)); - free(state->out); - free(state->in); + if (state->size) { + if (gz_comp(state, Z_FINISH) == -1) + ret = state->err; + if (!state->direct) { + (void)deflateEnd(&(state->strm)); + free(state->out); + } + free(state->in); + } gz_error(state, Z_OK, NULL); free(state->path); - ret += close(state->fd); + if (close(state->fd) == -1) + ret = Z_ERRNO; free(state); - return ret ? Z_ERRNO : Z_OK; + return ret; } diff --git a/dep/zlib/infback.c b/dep/zlib/infback.c index af3a8c965d5..981aff17c2d 100644 --- a/dep/zlib/infback.c +++ b/dep/zlib/infback.c @@ -1,5 +1,5 @@ /* infback.c -- inflate using a call-back interface - * Copyright (C) 1995-2009 Mark Adler + * Copyright (C) 1995-2011 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -42,10 +42,19 @@ int stream_size; return Z_STREAM_ERROR; strm->msg = Z_NULL; /* in case we return an error */ if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else strm->zalloc = zcalloc; strm->opaque = (voidpf)0; +#endif } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif state = (struct inflate_state FAR *)ZALLOC(strm, 1, sizeof(struct inflate_state)); if (state == Z_NULL) return Z_MEM_ERROR; @@ -394,7 +403,6 @@ void FAR *out_desc; PULLBYTE(); } if (here.val < 16) { - NEEDBITS(here.bits); DROPBITS(here.bits); state->lens[state->have++] = here.val; } diff --git a/dep/zlib/inffixed.h b/dep/zlib/inffixed.h index 75ed4b5978d..d6283277694 100644 --- a/dep/zlib/inffixed.h +++ b/dep/zlib/inffixed.h @@ -2,9 +2,9 @@ * Generated automatically by makefixed(). */ - /* WARNING: this file should *not* be used by applications. It - is part of the implementation of the compression library and - is subject to change. Applications should only use zlib.h. + /* WARNING: this file should *not* be used by applications. + It is part of the implementation of this library and is + subject to change. Applications should only use zlib.h. */ static const code lenfix[512] = { diff --git a/dep/zlib/inflate.c b/dep/zlib/inflate.c index a8431abeacf..47418a1e1e1 100644 --- a/dep/zlib/inflate.c +++ b/dep/zlib/inflate.c @@ -1,5 +1,5 @@ /* inflate.c -- zlib decompression - * Copyright (C) 1995-2010 Mark Adler + * Copyright (C) 1995-2012 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -100,7 +100,7 @@ local int updatewindow OF((z_streamp strm, unsigned out)); local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf, unsigned len)); -int ZEXPORT inflateReset(strm) +int ZEXPORT inflateResetKeep(strm) z_streamp strm; { struct inflate_state FAR *state; @@ -109,15 +109,13 @@ z_streamp strm; state = (struct inflate_state FAR *)strm->state; strm->total_in = strm->total_out = state->total = 0; strm->msg = Z_NULL; - strm->adler = 1; /* to support ill-conceived Java test suite */ + if (state->wrap) /* to support ill-conceived Java test suite */ + strm->adler = state->wrap & 1; state->mode = HEAD; state->last = 0; state->havedict = 0; state->dmax = 32768U; state->head = Z_NULL; - state->wsize = 0; - state->whave = 0; - state->wnext = 0; state->hold = 0; state->bits = 0; state->lencode = state->distcode = state->next = state->codes; @@ -127,6 +125,19 @@ z_streamp strm; return Z_OK; } +int ZEXPORT inflateReset(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + state->wsize = 0; + state->whave = 0; + state->wnext = 0; + return inflateResetKeep(strm); +} + int ZEXPORT inflateReset2(strm, windowBits) z_streamp strm; int windowBits; @@ -180,10 +191,19 @@ int stream_size; if (strm == Z_NULL) return Z_STREAM_ERROR; strm->msg = Z_NULL; /* in case we return an error */ if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else strm->zalloc = zcalloc; strm->opaque = (voidpf)0; +#endif } - if (strm->zfree == (free_func)0) strm->zfree = zcfree; + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif state = (struct inflate_state FAR *) ZALLOC(strm, 1, sizeof(struct inflate_state)); if (state == Z_NULL) return Z_MEM_ERROR; @@ -321,8 +341,8 @@ void makefixed() low = 0; for (;;) { if ((low % 7) == 0) printf("\n "); - printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits, - state.lencode[low].val); + printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op, + state.lencode[low].bits, state.lencode[low].val); if (++low == size) break; putchar(','); } @@ -499,11 +519,6 @@ unsigned out; bits -= bits & 7; \ } while (0) -/* Reverse the bytes in a 32-bit value */ -#define REVERSE(q) \ - ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ - (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) - /* inflate() uses a state machine to process as much input data and generate as much output data as possible before returning. The state machine is @@ -797,7 +812,7 @@ int flush; #endif case DICTID: NEEDBITS(32); - strm->adler = state->check = REVERSE(hold); + strm->adler = state->check = ZSWAP32(hold); INITBITS(); state->mode = DICT; case DICT: @@ -925,7 +940,6 @@ int flush; PULLBYTE(); } if (here.val < 16) { - NEEDBITS(here.bits); DROPBITS(here.bits); state->lens[state->have++] = here.val; } @@ -1170,7 +1184,7 @@ int flush; #ifdef GUNZIP state->flags ? hold : #endif - REVERSE(hold)) != state->check) { + ZSWAP32(hold)) != state->check) { strm->msg = (char *)"incorrect data check"; state->mode = BAD; break; @@ -1214,7 +1228,8 @@ int flush; */ inf_leave: RESTORE(); - if (state->wsize || (state->mode < CHECK && out != strm->avail_out)) + if (state->wsize || (out != strm->avail_out && state->mode < BAD && + (state->mode < CHECK || flush != Z_FINISH))) if (updatewindow(strm, out)) { state->mode = MEM; return Z_MEM_ERROR; @@ -1255,7 +1270,10 @@ const Bytef *dictionary; uInt dictLength; { struct inflate_state FAR *state; - unsigned long id; + unsigned long dictid; + unsigned char *next; + unsigned avail; + int ret; /* check state */ if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; @@ -1263,29 +1281,27 @@ uInt dictLength; if (state->wrap != 0 && state->mode != DICT) return Z_STREAM_ERROR; - /* check for correct dictionary id */ + /* check for correct dictionary identifier */ if (state->mode == DICT) { - id = adler32(0L, Z_NULL, 0); - id = adler32(id, dictionary, dictLength); - if (id != state->check) + dictid = adler32(0L, Z_NULL, 0); + dictid = adler32(dictid, dictionary, dictLength); + if (dictid != state->check) return Z_DATA_ERROR; } - /* copy dictionary to window */ - if (updatewindow(strm, strm->avail_out)) { + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + next = strm->next_out; + avail = strm->avail_out; + strm->next_out = (Bytef *)dictionary + dictLength; + strm->avail_out = 0; + ret = updatewindow(strm, dictLength); + strm->avail_out = avail; + strm->next_out = next; + if (ret) { state->mode = MEM; return Z_MEM_ERROR; } - if (dictLength > state->wsize) { - zmemcpy(state->window, dictionary + dictLength - state->wsize, - state->wsize); - state->whave = state->wsize; - } - else { - zmemcpy(state->window + state->wsize - dictLength, dictionary, - dictLength); - state->whave = dictLength; - } state->havedict = 1; Tracev((stderr, "inflate: dictionary set\n")); return Z_OK; @@ -1433,8 +1449,8 @@ z_streamp source; } /* copy state */ - zmemcpy(dest, source, sizeof(z_stream)); - zmemcpy(copy, state, sizeof(struct inflate_state)); + zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); + zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state)); if (state->lencode >= state->codes && state->lencode <= state->codes + ENOUGH - 1) { copy->lencode = copy->codes + (state->lencode - state->codes); diff --git a/dep/zlib/inftrees.c b/dep/zlib/inftrees.c index 11e9c52accb..abcd7c45ed3 100644 --- a/dep/zlib/inftrees.c +++ b/dep/zlib/inftrees.c @@ -1,5 +1,5 @@ /* inftrees.c -- generate Huffman trees for efficient decoding - * Copyright (C) 1995-2010 Mark Adler + * Copyright (C) 1995-2012 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -9,7 +9,7 @@ #define MAXBITS 15 const char inflate_copyright[] = - " inflate 1.2.5 Copyright 1995-2010 Mark Adler "; + " inflate 1.2.7 Copyright 1995-2012 Mark Adler "; /* If you use the zlib library in a product, an acknowledgment is welcome in the documentation of your product. If for some reason you cannot @@ -62,7 +62,7 @@ unsigned short FAR *work; 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; static const unsigned short lext[31] = { /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, - 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 73, 195}; + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 78, 68}; static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, @@ -289,38 +289,14 @@ unsigned short FAR *work; } } - /* - Fill in rest of table for incomplete codes. This loop is similar to the - loop above in incrementing huff for table indices. It is assumed that - len is equal to curr + drop, so there is no loop needed to increment - through high index bits. When the current sub-table is filled, the loop - drops back to the root table to fill in any remaining entries there. - */ - here.op = (unsigned char)64; /* invalid code marker */ - here.bits = (unsigned char)(len - drop); - here.val = (unsigned short)0; - while (huff != 0) { - /* when done with sub-table, drop back to root table */ - if (drop != 0 && (huff & mask) != low) { - drop = 0; - len = root; - next = *table; - here.bits = (unsigned char)len; - } - - /* put invalid code marker in table */ - next[huff >> drop] = here; - - /* backwards increment the len-bit code huff */ - incr = 1U << (len - 1); - while (huff & incr) - incr >>= 1; - if (incr != 0) { - huff &= incr - 1; - huff += incr; - } - else - huff = 0; + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff != 0) { + here.op = (unsigned char)64; /* invalid code marker */ + here.bits = (unsigned char)(len - drop); + here.val = (unsigned short)0; + next[huff] = here; } /* set return parameters */ diff --git a/dep/zlib/trees.c b/dep/zlib/trees.c index 56e9bb1c115..8c32b214b1d 100644 --- a/dep/zlib/trees.c +++ b/dep/zlib/trees.c @@ -1,5 +1,5 @@ /* trees.c -- output deflated data using Huffman coding - * Copyright (C) 1995-2010 Jean-loup Gailly + * Copyright (C) 1995-2012 Jean-loup Gailly * detect_data_type() function provided freely by Cosmin Truta, 2006 * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -74,11 +74,6 @@ local const uch bl_order[BL_CODES] * probability, to avoid transmitting the lengths for unused bit length codes. */ -#define Buf_size (8 * 2*sizeof(char)) -/* Number of bits used within bi_buf. (bi_buf might be implemented on - * more than 16 bits on some systems.) - */ - /* =========================================================================== * Local data. These are initialized only once. */ @@ -399,7 +394,6 @@ void ZLIB_INTERNAL _tr_init(s) s->bi_buf = 0; s->bi_valid = 0; - s->last_eob_len = 8; /* enough lookahead for inflate */ #ifdef DEBUG s->compressed_len = 0L; s->bits_sent = 0L; @@ -883,15 +877,17 @@ void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last) } /* =========================================================================== + * Flush the bits in the bit buffer to pending output (leaves at most 7 bits) + */ +void ZLIB_INTERNAL _tr_flush_bits(s) + deflate_state *s; +{ + bi_flush(s); +} + +/* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. - * The current inflate code requires 9 bits of lookahead. If the - * last two codes for the previous block (real code plus EOB) were coded - * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode - * the last real code. In this case we send two empty static blocks instead - * of one. (There are no problems if the previous block is stored or fixed.) - * To simplify the code, we assume the worst case of last real code encoded - * on one bit only. */ void ZLIB_INTERNAL _tr_align(s) deflate_state *s; @@ -902,20 +898,6 @@ void ZLIB_INTERNAL _tr_align(s) s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ #endif bi_flush(s); - /* Of the 10 bits for the empty block, we have already sent - * (10 - bi_valid) bits. The lookahead for the last real code (before - * the EOB of the previous block) was thus at least one plus the length - * of the EOB plus what we have just sent of the empty static block. - */ - if (1 + s->last_eob_len + 10 - s->bi_valid < 9) { - send_bits(s, STATIC_TREES<<1, 3); - send_code(s, END_BLOCK, static_ltree); -#ifdef DEBUG - s->compressed_len += 10L; -#endif - bi_flush(s); - } - s->last_eob_len = 7; } /* =========================================================================== @@ -1118,7 +1100,6 @@ local void compress_block(s, ltree, dtree) } while (lx < s->last_lit); send_code(s, END_BLOCK, ltree); - s->last_eob_len = ltree[END_BLOCK].Len; } /* =========================================================================== @@ -1226,7 +1207,6 @@ local void copy_block(s, buf, len, header) int header; /* true if block header must be written */ { bi_windup(s); /* align on byte boundary */ - s->last_eob_len = 8; /* enough lookahead for inflate */ if (header) { put_short(s, (ush)len); diff --git a/dep/zlib/zconf.h b/dep/zlib/zconf.h index 02ce56c4313..8a46a58b30c 100644 --- a/dep/zlib/zconf.h +++ b/dep/zlib/zconf.h @@ -1,5 +1,5 @@ /* zconf.h -- configuration of the zlib compression library - * Copyright (C) 1995-2010 Jean-loup Gailly. + * Copyright (C) 1995-2012 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -15,6 +15,7 @@ * this permanently in zconf.h using "./configure --zprefix". */ #ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ +# define Z_PREFIX_SET /* all linked symbols */ # define _dist_code z__dist_code @@ -27,9 +28,11 @@ # define adler32 z_adler32 # define adler32_combine z_adler32_combine # define adler32_combine64 z_adler32_combine64 -# define compress z_compress -# define compress2 z_compress2 -# define compressBound z_compressBound +# ifndef Z_SOLO +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# endif # define crc32 z_crc32 # define crc32_combine z_crc32_combine # define crc32_combine64 z_crc32_combine64 @@ -40,44 +43,52 @@ # define deflateInit2_ z_deflateInit2_ # define deflateInit_ z_deflateInit_ # define deflateParams z_deflateParams +# define deflatePending z_deflatePending # define deflatePrime z_deflatePrime # define deflateReset z_deflateReset +# define deflateResetKeep z_deflateResetKeep # define deflateSetDictionary z_deflateSetDictionary # define deflateSetHeader z_deflateSetHeader # define deflateTune z_deflateTune # define deflate_copyright z_deflate_copyright # define get_crc_table z_get_crc_table -# define gz_error z_gz_error -# define gz_intmax z_gz_intmax -# define gz_strwinerror z_gz_strwinerror -# define gzbuffer z_gzbuffer -# define gzclearerr z_gzclearerr -# define gzclose z_gzclose -# define gzclose_r z_gzclose_r -# define gzclose_w z_gzclose_w -# define gzdirect z_gzdirect -# define gzdopen z_gzdopen -# define gzeof z_gzeof -# define gzerror z_gzerror -# define gzflush z_gzflush -# define gzgetc z_gzgetc -# define gzgets z_gzgets -# define gzoffset z_gzoffset -# define gzoffset64 z_gzoffset64 -# define gzopen z_gzopen -# define gzopen64 z_gzopen64 -# define gzprintf z_gzprintf -# define gzputc z_gzputc -# define gzputs z_gzputs -# define gzread z_gzread -# define gzrewind z_gzrewind -# define gzseek z_gzseek -# define gzseek64 z_gzseek64 -# define gzsetparams z_gzsetparams -# define gztell z_gztell -# define gztell64 z_gztell64 -# define gzungetc z_gzungetc -# define gzwrite z_gzwrite +# ifndef Z_SOLO +# define gz_error z_gz_error +# define gz_intmax z_gz_intmax +# define gz_strwinerror z_gz_strwinerror +# define gzbuffer z_gzbuffer +# define gzclearerr z_gzclearerr +# define gzclose z_gzclose +# define gzclose_r z_gzclose_r +# define gzclose_w z_gzclose_w +# define gzdirect z_gzdirect +# define gzdopen z_gzdopen +# define gzeof z_gzeof +# define gzerror z_gzerror +# define gzflush z_gzflush +# define gzgetc z_gzgetc +# define gzgetc_ z_gzgetc_ +# define gzgets z_gzgets +# define gzoffset z_gzoffset +# define gzoffset64 z_gzoffset64 +# define gzopen z_gzopen +# define gzopen64 z_gzopen64 +# ifdef _WIN32 +# define gzopen_w z_gzopen_w +# endif +# define gzprintf z_gzprintf +# define gzputc z_gzputc +# define gzputs z_gzputs +# define gzread z_gzread +# define gzrewind z_gzrewind +# define gzseek z_gzseek +# define gzseek64 z_gzseek64 +# define gzsetparams z_gzsetparams +# define gztell z_gztell +# define gztell64 z_gztell64 +# define gzungetc z_gzungetc +# define gzwrite z_gzwrite +# endif # define inflate z_inflate # define inflateBack z_inflateBack # define inflateBackEnd z_inflateBackEnd @@ -95,13 +106,18 @@ # define inflateSync z_inflateSync # define inflateSyncPoint z_inflateSyncPoint # define inflateUndermine z_inflateUndermine +# define inflateResetKeep z_inflateResetKeep # define inflate_copyright z_inflate_copyright # define inflate_fast z_inflate_fast # define inflate_table z_inflate_table -# define uncompress z_uncompress +# ifndef Z_SOLO +# define uncompress z_uncompress +# endif # define zError z_zError -# define zcalloc z_zcalloc -# define zcfree z_zcfree +# ifndef Z_SOLO +# define zcalloc z_zcalloc +# define zcfree z_zcfree +# endif # define zlibCompileFlags z_zlibCompileFlags # define zlibVersion z_zlibVersion @@ -111,7 +127,9 @@ # define alloc_func z_alloc_func # define charf z_charf # define free_func z_free_func -# define gzFile z_gzFile +# ifndef Z_SOLO +# define gzFile z_gzFile +# endif # define gz_header z_gz_header # define gz_headerp z_gz_headerp # define in_func z_in_func @@ -197,6 +215,12 @@ # endif #endif +#if defined(ZLIB_CONST) && !defined(z_const) +# define z_const const +#else +# define z_const +#endif + /* Some Mac compilers merge all .h files incorrectly: */ #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) # define NO_DUMMY_DECL @@ -243,6 +267,14 @@ # endif #endif +#ifndef Z_ARG /* function prototypes for stdarg */ +# if defined(STDC) || defined(Z_HAVE_STDARG_H) +# define Z_ARG(args) args +# else +# define Z_ARG(args) () +# endif +#endif + /* The following definitions for FAR are needed only for MSDOS mixed * model programming (small or medium model with some far allocations). * This was tested only with MSC; for other MSDOS compilers you may have @@ -356,12 +388,45 @@ typedef uLong FAR uLongf; typedef Byte *voidp; #endif +/* ./configure may #define Z_U4 here */ + +#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) +# include <limits.h> +# if (UINT_MAX == 0xffffffffUL) +# define Z_U4 unsigned +# else +# if (ULONG_MAX == 0xffffffffUL) +# define Z_U4 unsigned long +# else +# if (USHRT_MAX == 0xffffffffUL) +# define Z_U4 unsigned short +# endif +# endif +# endif +#endif + +#ifdef Z_U4 + typedef Z_U4 z_crc_t; +#else + typedef unsigned long z_crc_t; +#endif + #ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ # define Z_HAVE_UNISTD_H #endif +#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_STDARG_H +#endif + #ifdef STDC -# include <sys/types.h> /* for off_t */ +# ifndef Z_SOLO +# include <sys/types.h> /* for off_t */ +# endif +#endif + +#ifdef _WIN32 +# include <stddef.h> /* for wchar_t */ #endif /* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and @@ -370,21 +435,38 @@ typedef uLong FAR uLongf; * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as * equivalently requesting no 64-bit operations */ -#if -_LARGEFILE64_SOURCE - -1 == 1 +#if defined(LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 # undef _LARGEFILE64_SOURCE #endif -#if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) -# include <unistd.h> /* for SEEK_* and off_t */ -# ifdef VMS -# include <unixio.h> /* for off_t */ -# endif -# ifndef z_off_t -# define z_off_t off_t +#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) +# define Z_HAVE_UNISTD_H +#endif +#ifndef Z_SOLO +# if defined(Z_HAVE_UNISTD_H) || defined(LARGEFILE64_SOURCE) +# include <unistd.h> /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ +# ifdef VMS +# include <unixio.h> /* for off_t */ +# endif +# ifndef z_off_t +# define z_off_t off_t +# endif # endif #endif -#ifndef SEEK_SET +#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 +# define Z_LFS64 +#endif + +#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) +# define Z_LARGE64 +#endif + +#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) +# define Z_WANT64 +#endif + +#if !defined(SEEK_SET) && !defined(Z_SOLO) # define SEEK_SET 0 /* Seek from beginning of file. */ # define SEEK_CUR 1 /* Seek from current position. */ # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ @@ -394,18 +476,14 @@ typedef uLong FAR uLongf; # define z_off_t long #endif -#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 +#if !defined(_WIN32) && defined(Z_LARGE64) # define z_off64_t off64_t #else -# define z_off64_t z_off_t -#endif - -#if defined(__OS400__) -# define NO_vsnprintf -#endif - -#if defined(__MVS__) -# define NO_vsnprintf +# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) +# define z_off64_t __int64 +# else +# define z_off64_t z_off_t +# endif #endif /* MVS linker does not support external names larger than 8 bytes */ diff --git a/dep/zlib/zlib.h b/dep/zlib/zlib.h index bfbba83e8ee..3edf3acdb57 100644 --- a/dep/zlib/zlib.h +++ b/dep/zlib/zlib.h @@ -1,7 +1,7 @@ /* zlib.h -- interface of the 'zlib' general purpose compression library - version 1.2.5, April 19th, 2010 + version 1.2.7, May 2nd, 2012 - Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler + Copyright (C) 1995-2012 Jean-loup Gailly and Mark Adler This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages @@ -24,8 +24,8 @@ The data format used by the zlib library is described by RFCs (Request for - Comments) 1950 to 1952 in the files http://www.ietf.org/rfc/rfc1950.txt - (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format). + Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950 + (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). */ #ifndef ZLIB_H @@ -37,11 +37,11 @@ extern "C" { #endif -#define ZLIB_VERSION "1.2.5" -#define ZLIB_VERNUM 0x1250 +#define ZLIB_VERSION "1.2.7" +#define ZLIB_VERNUM 0x1270 #define ZLIB_VER_MAJOR 1 #define ZLIB_VER_MINOR 2 -#define ZLIB_VER_REVISION 5 +#define ZLIB_VER_REVISION 7 #define ZLIB_VER_SUBREVISION 0 /* @@ -83,15 +83,15 @@ typedef void (*free_func) OF((voidpf opaque, voidpf address)); struct internal_state; typedef struct z_stream_s { - Bytef *next_in; /* next input byte */ + z_const Bytef *next_in; /* next input byte */ uInt avail_in; /* number of bytes available at next_in */ - uLong total_in; /* total nb of input bytes read so far */ + uLong total_in; /* total number of input bytes read so far */ Bytef *next_out; /* next output byte should be put there */ uInt avail_out; /* remaining free space at next_out */ - uLong total_out; /* total nb of bytes output so far */ + uLong total_out; /* total number of bytes output so far */ - char *msg; /* last error message, NULL if no error */ + z_const char *msg; /* last error message, NULL if no error */ struct internal_state FAR *state; /* not visible by applications */ alloc_func zalloc; /* used to allocate the internal state */ @@ -327,8 +327,9 @@ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); Z_FINISH can be used immediately after deflateInit if all the compression is to be done in a single step. In this case, avail_out must be at least the - value returned by deflateBound (see below). If deflate does not return - Z_STREAM_END, then it must be called again as described above. + value returned by deflateBound (see below). Then deflate is guaranteed to + return Z_STREAM_END. If not enough output space is provided, deflate will + not return Z_STREAM_END, and it must be called again as described above. deflate() sets strm->adler to the adler32 checksum of all input read so far (that is, total_in bytes). @@ -451,23 +452,29 @@ ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); error. However if all decompression is to be performed in a single step (a single call of inflate), the parameter flush should be set to Z_FINISH. In this case all pending input is processed and all pending output is flushed; - avail_out must be large enough to hold all the uncompressed data. (The size - of the uncompressed data may have been saved by the compressor for this - purpose.) The next operation on this stream must be inflateEnd to deallocate - the decompression state. The use of Z_FINISH is never required, but can be - used to inform inflate that a faster approach may be used for the single - inflate() call. + avail_out must be large enough to hold all of the uncompressed data for the + operation to complete. (The size of the uncompressed data may have been + saved by the compressor for this purpose.) The use of Z_FINISH is not + required to perform an inflation in one step. However it may be used to + inform inflate that a faster approach can be used for the single inflate() + call. Z_FINISH also informs inflate to not maintain a sliding window if the + stream completes, which reduces inflate's memory footprint. If the stream + does not complete, either because not all of the stream is provided or not + enough output space is provided, then a sliding window will be allocated and + inflate() can be called again to continue the operation as if Z_NO_FLUSH had + been used. In this implementation, inflate() always flushes as much output as possible to the output buffer, and always uses the faster approach on the - first call. So the only effect of the flush parameter in this implementation - is on the return value of inflate(), as noted below, or when it returns early - because Z_BLOCK or Z_TREES is used. + first call. So the effects of the flush parameter in this implementation are + on the return value of inflate() as noted below, when inflate() returns early + when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of + memory for a sliding window when Z_FINISH is used. If a preset dictionary is needed after this call (see inflateSetDictionary - below), inflate sets strm->adler to the adler32 checksum of the dictionary + below), inflate sets strm->adler to the Adler-32 checksum of the dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise it sets - strm->adler to the adler32 checksum of all output produced so far (that is, + strm->adler to the Adler-32 checksum of all output produced so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described below. At the end of the stream, inflate() checks that its computed adler32 checksum is equal to that saved by the compressor and returns Z_STREAM_END @@ -478,7 +485,9 @@ ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); initializing with inflateInit2(). Any information contained in the gzip header is not retained, so applications that need that information should instead use raw inflate, see inflateInit2() below, or inflateBack() and - perform their own processing of the gzip header and trailer. + perform their own processing of the gzip header and trailer. When processing + gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output + producted so far. The CRC-32 is checked against the gzip trailer. inflate() returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if the end of the compressed data has @@ -580,10 +589,15 @@ ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, uInt dictLength)); /* Initializes the compression dictionary from the given byte sequence - without producing any compressed output. This function must be called - immediately after deflateInit, deflateInit2 or deflateReset, before any call - of deflate. The compressor and decompressor must use exactly the same - dictionary (see inflateSetDictionary). + without producing any compressed output. When using the zlib format, this + function must be called immediately after deflateInit, deflateInit2 or + deflateReset, and before any call of deflate. When doing raw deflate, this + function must be called either before any call of deflate, or immediately + after the completion of a deflate block, i.e. after all input has been + consumed and all output has been delivered when using any of the flush + options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The + compressor and decompressor must use exactly the same dictionary (see + inflateSetDictionary). The dictionary should consist of strings (byte sequences) that are likely to be encountered later in the data to be compressed, with the most commonly @@ -610,8 +624,8 @@ ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is inconsistent (for example if deflate has already been called for this stream - or if the compression method is bsort). deflateSetDictionary does not - perform any compression: this will be done by deflate(). + or if not at a block boundary for raw deflate). deflateSetDictionary does + not perform any compression: this will be done by deflate(). */ ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, @@ -688,8 +702,28 @@ ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, deflation of sourceLen bytes. It must be called after deflateInit() or deflateInit2(), and after deflateSetHeader(), if used. This would be used to allocate an output buffer for deflation in a single pass, and so would be - called before deflate(). -*/ + called before deflate(). If that first deflate() call is provided the + sourceLen input bytes, an output buffer allocated to the size returned by + deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed + to return Z_STREAM_END. Note that it is possible for the compressed size to + be larger than the value returned by deflateBound() if flush options other + than Z_FINISH or Z_NO_FLUSH are used. +*/ + +ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm, + unsigned *pending, + int *bits)); +/* + deflatePending() returns the number of bytes and bits of output that have + been generated, but not yet provided in the available output. The bytes not + provided would be due to the available output space having being consumed. + The number of bits of output not provided are between 0 and 7, where they + await more bits to join them in order to fill out a full byte. If pending + or bits are Z_NULL, then those values are not set. + + deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. + */ ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, int bits, @@ -703,8 +737,9 @@ ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, than or equal to 16, and that many of the least significant bits of value will be inserted in the output. - deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source - stream state was inconsistent. + deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough + room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the + source stream state was inconsistent. */ ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, @@ -790,10 +825,11 @@ ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, if that call returned Z_NEED_DICT. The dictionary chosen by the compressor can be determined from the adler32 value returned by that call of inflate. The compressor and decompressor must use exactly the same dictionary (see - deflateSetDictionary). For raw inflate, this function can be called - immediately after inflateInit2() or inflateReset() and before any call of - inflate() to set the dictionary. The application must insure that the - dictionary that was used for compression is provided. + deflateSetDictionary). For raw inflate, this function can be called at any + time to set the dictionary. If the provided dictionary is smaller than the + window and there is already data in the window, then the provided dictionary + will amend what's there. The application must insure that the dictionary + that was used for compression is provided. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is @@ -805,17 +841,21 @@ ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); /* - Skips invalid compressed data until a full flush point (see above the - description of deflate with Z_FULL_FLUSH) can be found, or until all + Skips invalid compressed data until a possible full flush point (see above + for the description of deflate with Z_FULL_FLUSH) can be found, or until all available input is skipped. No output is provided. - inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR - if no more input was provided, Z_DATA_ERROR if no flush point has been - found, or Z_STREAM_ERROR if the stream structure was inconsistent. In the - success case, the application may save the current current value of total_in - which indicates where valid compressed data was found. In the error case, - the application may repeatedly call inflateSync, providing more input each - time, until success or end of the input data. + inflateSync searches for a 00 00 FF FF pattern in the compressed data. + All full flush points have this pattern, but not all occurences of this + pattern are full flush points. + + inflateSync returns Z_OK if a possible full flush point has been found, + Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point + has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. + In the success case, the application may save the current current value of + total_in which indicates where valid compressed data was found. In the + error case, the application may repeatedly call inflateSync, providing more + input each time, until success or end of the input data. */ ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, @@ -962,7 +1002,7 @@ ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, See inflateBack() for the usage of these routines. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of - the paramaters are invalid, Z_MEM_ERROR if the internal state could not be + the parameters are invalid, Z_MEM_ERROR if the internal state could not be allocated, or Z_VERSION_ERROR if the version of the library does not match the version of the header file. */ @@ -1088,6 +1128,7 @@ ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); 27-31: 0 (reserved) */ +#ifndef Z_SOLO /* utility functions */ @@ -1149,10 +1190,11 @@ ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output - buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In + the case where there is not enough room, uncompress() will fill the output + buffer with the uncompressed data up to that point. */ - /* gzip file access functions */ /* @@ -1162,7 +1204,7 @@ ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, wrapper, documented in RFC 1952, wrapped around a deflate stream. */ -typedef voidp gzFile; /* opaque gzip file descriptor */ +typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ /* ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); @@ -1172,13 +1214,28 @@ ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' for fixed code compression as in "wb9F". (See the description of - deflateInit2 for more information about the strategy parameter.) Also "a" - can be used instead of "w" to request that the gzip stream that will be - written be appended to the file. "+" will result in an error, since reading - and writing to the same gzip file is not supported. + deflateInit2 for more information about the strategy parameter.) 'T' will + request transparent writing or appending with no compression and not using + the gzip format. + + "a" can be used instead of "w" to request that the gzip stream that will + be written be appended to the file. "+" will result in an error, since + reading and writing to the same gzip file is not supported. The addition of + "x" when writing will create the file exclusively, which fails if the file + already exists. On systems that support it, the addition of "e" when + reading or writing will set the flag to close the file on an execve() call. + + These functions, as well as gzip, will read and decode a sequence of gzip + streams in a file. The append function of gzopen() can be used to create + such a file. (Also see gzflush() for another way to do this.) When + appending, gzopen does not test whether the file begins with a gzip stream, + nor does it look for the end of the gzip streams to begin appending. gzopen + will simply append a gzip stream to the existing file. gzopen can be used to read a file which is not in gzip format; in this - case gzread will directly read from the file without decompression. + case gzread will directly read from the file without decompression. When + reading, this will be detected automatically by looking for the magic two- + byte gzip header. gzopen returns NULL if the file could not be opened, if there was insufficient memory to allocate the gzFile state, or if an invalid mode was @@ -1197,7 +1254,11 @@ ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, mode);. The duplicated descriptor should be saved to avoid a leak, since - gzdopen does not close fd if it fails. + gzdopen does not close fd if it fails. If you are using fileno() to get the + file descriptor from a FILE *, then you will have to use dup() to avoid + double-close()ing the file descriptor. Both gzclose() and fclose() will + close the associated file descriptor, so they need to have different file + descriptors. gzdopen returns NULL if there was insufficient memory to allocate the gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not @@ -1235,14 +1296,26 @@ ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); /* Reads the given number of uncompressed bytes from the compressed file. If - the input file was not in gzip format, gzread copies the given number of - bytes into the buffer. + the input file is not in gzip format, gzread copies the given number of + bytes into the buffer directly from the file. After reaching the end of a gzip stream in the input, gzread will continue - to read, looking for another gzip stream, or failing that, reading the rest - of the input file directly without decompression. The entire input file - will be read if gzread is called until it returns less than the requested - len. + to read, looking for another gzip stream. Any number of gzip streams may be + concatenated in the input file, and will all be decompressed by gzread(). + If something other than a gzip stream is encountered after a gzip stream, + that remaining trailing garbage is ignored (and no error is returned). + + gzread can be used to read a gzip file that is being concurrently written. + Upon reaching the end of the input, gzread will return with the available + data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then + gzclearerr can be used to clear the end of file indicator in order to permit + gzread to be tried again. Z_OK indicates that a gzip stream was completed + on the last gzread. Z_BUF_ERROR indicates that the input file ended in the + middle of a gzip stream. Note that gzread does not return -1 in the event + of an incomplete gzip stream. This error is deferred until gzclose(), which + will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip + stream. Alternatively, gzerror can be used before gzclose to detect this + case. gzread returns the number of uncompressed bytes actually read, less than len for end of file, or -1 for error. @@ -1256,7 +1329,7 @@ ZEXTERN int ZEXPORT gzwrite OF((gzFile file, error. */ -ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...)); +ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...)); /* Converts, formats, and writes the arguments to the compressed file under control of the format string, as in fprintf. gzprintf returns the number of @@ -1301,7 +1374,10 @@ ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); /* Reads one byte from the compressed file. gzgetc returns this byte or -1 - in case of end of file or error. + in case of end of file or error. This is implemented as a macro for speed. + As such, it does not do all of the checking the other functions do. I.e. + it does not check to see if file is NULL, nor whether the structure file + points to has been clobbered or not. */ ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); @@ -1397,9 +1473,7 @@ ZEXTERN int ZEXPORT gzeof OF((gzFile file)); ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); /* Returns true (1) if file is being copied directly while reading, or false - (0) if file is a gzip stream being decompressed. This state can change from - false to true while reading the input file if the end of a gzip stream is - reached, but is followed by data that is not another gzip stream. + (0) if file is a gzip stream being decompressed. If the input file is empty, gzdirect() will return true, since the input does not contain a gzip stream. @@ -1408,6 +1482,13 @@ ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); cause buffers to be allocated to allow reading the file to determine if it is a gzip file. Therefore if gzbuffer() is used, it should be called before gzdirect(). + + When writing, gzdirect() returns true (1) if transparent writing was + requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: + gzdirect() is not needed when writing. Transparent writing must be + explicitly requested, so the application already knows the answer. When + linking statically, using gzdirect() will include all of the zlib code for + gzip file reading and decompression, which may not be desired.) */ ZEXTERN int ZEXPORT gzclose OF((gzFile file)); @@ -1419,7 +1500,8 @@ ZEXTERN int ZEXPORT gzclose OF((gzFile file)); must not be called more than once on the same allocation. gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a - file operation error, or Z_OK on success. + file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the + last read ended in the middle of a gzip stream, or Z_OK on success. */ ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); @@ -1457,6 +1539,7 @@ ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); file that is being written concurrently. */ +#endif /* !Z_SOLO */ /* checksum functions */ @@ -1492,16 +1575,17 @@ ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of - seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. + seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note + that the z_off_t type (like off_t) is a signed integer. If len2 is + negative, the result has no meaning or utility. */ ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); /* Update a running CRC-32 with the bytes buf[0..len-1] and return the updated CRC-32. If buf is Z_NULL, this function returns the required - initial value for the for the crc. Pre- and post-conditioning (one's - complement) is performed within this function so it shouldn't be done by the - application. + initial value for the crc. Pre- and post-conditioning (one's complement) is + performed within this function so it shouldn't be done by the application. Usage example: @@ -1544,17 +1628,42 @@ ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, const char *version, int stream_size)); #define deflateInit(strm, level) \ - deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream)) + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) #define inflateInit(strm) \ - inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream)) + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ - (strategy), ZLIB_VERSION, sizeof(z_stream)) + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) #define inflateInit2(strm, windowBits) \ - inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream)) + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) #define inflateBackInit(strm, windowBits, window) \ inflateBackInit_((strm), (windowBits), (window), \ - ZLIB_VERSION, sizeof(z_stream)) + ZLIB_VERSION, (int)sizeof(z_stream)) + +#ifndef Z_SOLO + +/* gzgetc() macro and its supporting function and exposed data structure. Note + * that the real internal state is much larger than the exposed structure. + * This abbreviated structure exposes just enough for the gzgetc() macro. The + * user should not mess with these exposed elements, since their names or + * behavior could change in the future, perhaps even capriciously. They can + * only be used by the gzgetc() macro. You have been warned. + */ +struct gzFile_s { + unsigned have; + unsigned char *next; + z_off64_t pos; +}; +ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ +#ifdef Z_PREFIX_SET +# undef z_gzgetc +# define z_gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc(g)) +#else +# define gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc(g)) +#endif /* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if @@ -1562,7 +1671,7 @@ ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, * functions are changed to 64 bits) -- in case these are set on systems * without large file support, _LFS64_LARGEFILE must also be true */ -#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 +#ifdef Z_LARGE64 ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); @@ -1571,14 +1680,23 @@ ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); #endif -#if !defined(ZLIB_INTERNAL) && _FILE_OFFSET_BITS-0 == 64 && _LFS64_LARGEFILE-0 -# define gzopen gzopen64 -# define gzseek gzseek64 -# define gztell gztell64 -# define gzoffset gzoffset64 -# define adler32_combine adler32_combine64 -# define crc32_combine crc32_combine64 -# ifdef _LARGEFILE64_SOURCE +#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) +# ifdef Z_PREFIX_SET +# define z_gzopen z_gzopen64 +# define z_gzseek z_gzseek64 +# define z_gztell z_gztell64 +# define z_gzoffset z_gzoffset64 +# define z_adler32_combine z_adler32_combine64 +# define z_crc32_combine z_crc32_combine64 +# else +# define gzopen gzopen64 +# define gzseek gzseek64 +# define gztell gztell64 +# define gzoffset gzoffset64 +# define adler32_combine adler32_combine64 +# define crc32_combine crc32_combine64 +# endif +# ifndef Z_LARGE64 ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); @@ -1595,6 +1713,13 @@ ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); #endif +#else /* Z_SOLO */ + + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); + +#endif /* !Z_SOLO */ + /* hack for buggy compilers */ #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) struct internal_state {int dummy;}; @@ -1603,8 +1728,14 @@ ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, /* undocumented functions */ ZEXTERN const char * ZEXPORT zError OF((int)); ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); -ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void)); +ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table OF((void)); ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); +ZEXTERN int ZEXPORT inflateResetKeep OF((z_streamp)); +ZEXTERN int ZEXPORT deflateResetKeep OF((z_streamp)); +#if defined(_WIN32) && !defined(Z_SOLO) +ZEXTERN gzFile ZEXPORT gzopen_w OF((const wchar_t *path, + const char *mode)); +#endif #ifdef __cplusplus } diff --git a/dep/zlib/zutil.c b/dep/zlib/zutil.c index 898ed345b0e..65e0d3b72b0 100644 --- a/dep/zlib/zutil.c +++ b/dep/zlib/zutil.c @@ -1,11 +1,14 @@ /* zutil.c -- target dependent utility functions for the compression library - * Copyright (C) 1995-2005, 2010 Jean-loup Gailly. + * Copyright (C) 1995-2005, 2010, 2011, 2012 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #include "zutil.h" +#ifndef Z_SOLO +# include "gzguts.h" +#endif #ifndef NO_DUMMY_DECL struct internal_state {int dummy;}; /* for buggy compilers */ @@ -85,27 +88,27 @@ uLong ZEXPORT zlibCompileFlags() #ifdef FASTEST flags += 1L << 21; #endif -#ifdef STDC +#if defined(STDC) || defined(Z_HAVE_STDARG_H) # ifdef NO_vsnprintf - flags += 1L << 25; + flags += 1L << 25; # ifdef HAS_vsprintf_void - flags += 1L << 26; + flags += 1L << 26; # endif # else # ifdef HAS_vsnprintf_void - flags += 1L << 26; + flags += 1L << 26; # endif # endif #else - flags += 1L << 24; + flags += 1L << 24; # ifdef NO_snprintf - flags += 1L << 25; + flags += 1L << 25; # ifdef HAS_sprintf_void - flags += 1L << 26; + flags += 1L << 26; # endif # else # ifdef HAS_snprintf_void - flags += 1L << 26; + flags += 1L << 26; # endif # endif #endif @@ -181,6 +184,7 @@ void ZLIB_INTERNAL zmemzero(dest, len) } #endif +#ifndef Z_SOLO #ifdef SYS16BIT @@ -316,3 +320,5 @@ void ZLIB_INTERNAL zcfree (opaque, ptr) } #endif /* MY_ZCALLOC */ + +#endif /* !Z_SOLO */ diff --git a/dep/zlib/zutil.h b/dep/zlib/zutil.h index 258fa88799a..4e3dcc6ae9f 100644 --- a/dep/zlib/zutil.h +++ b/dep/zlib/zutil.h @@ -1,5 +1,5 @@ /* zutil.h -- internal interface and configuration of the compression library - * Copyright (C) 1995-2010 Jean-loup Gailly. + * Copyright (C) 1995-2012 Jean-loup Gailly. * For conditions of distribution and use, see copyright notice in zlib.h */ @@ -13,7 +13,7 @@ #ifndef ZUTIL_H #define ZUTIL_H -#if ((__GNUC__-0) * 10 + __GNUC_MINOR__-0 >= 33) && !defined(NO_VIZ) +#ifdef HAVE_HIDDEN # define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) #else # define ZLIB_INTERNAL @@ -21,7 +21,7 @@ #include "zlib.h" -#ifdef STDC +#if defined(STDC) && !defined(Z_SOLO) # if !(defined(_WIN32_WCE) && defined(_MSC_VER)) # include <stddef.h> # endif @@ -29,6 +29,10 @@ # include <stdlib.h> #endif +#ifdef Z_SOLO + typedef long ptrdiff_t; /* guess -- will be caught if guess is wrong */ +#endif + #ifndef local # define local static #endif @@ -78,16 +82,18 @@ extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) # define OS_CODE 0x00 -# if defined(__TURBOC__) || defined(__BORLANDC__) -# if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) - /* Allow compilation with ANSI keywords only enabled */ - void _Cdecl farfree( void *block ); - void *_Cdecl farmalloc( unsigned long nbytes ); -# else -# include <alloc.h> +# ifndef Z_SOLO +# if defined(__TURBOC__) || defined(__BORLANDC__) +# if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) + /* Allow compilation with ANSI keywords only enabled */ + void _Cdecl farfree( void *block ); + void *_Cdecl farmalloc( unsigned long nbytes ); +# else +# include <alloc.h> +# endif +# else /* MSC or DJGPP */ +# include <malloc.h> # endif -# else /* MSC or DJGPP */ -# include <malloc.h> # endif #endif @@ -107,18 +113,20 @@ extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ #ifdef OS2 # define OS_CODE 0x06 -# ifdef M_I86 +# if defined(M_I86) && !defined(Z_SOLO) # include <malloc.h> # endif #endif #if defined(MACOS) || defined(TARGET_OS_MAC) # define OS_CODE 0x07 -# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os -# include <unix.h> /* for fdopen */ -# else -# ifndef fdopen -# define fdopen(fd,mode) NULL /* No fdopen() */ +# ifndef Z_SOLO +# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os +# include <unix.h> /* for fdopen */ +# else +# ifndef fdopen +# define fdopen(fd,mode) NULL /* No fdopen() */ +# endif # endif # endif #endif @@ -153,14 +161,14 @@ extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ # endif #endif -#if defined(__BORLANDC__) +#if defined(__BORLANDC__) && !defined(MSDOS) #pragma warn -8004 #pragma warn -8008 #pragma warn -8066 #endif /* provide prototypes for these when building zlib without LFS */ -#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0 +#if !defined(_WIN32) && (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0) ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); #endif @@ -177,42 +185,7 @@ extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ /* functions */ -#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550) -# ifndef HAVE_VSNPRINTF -# define HAVE_VSNPRINTF -# endif -#endif -#if defined(__CYGWIN__) -# ifndef HAVE_VSNPRINTF -# define HAVE_VSNPRINTF -# endif -#endif -#ifndef HAVE_VSNPRINTF -# ifdef MSDOS - /* vsnprintf may exist on some MS-DOS compilers (DJGPP?), - but for now we just assume it doesn't. */ -# define NO_vsnprintf -# endif -# ifdef __TURBOC__ -# define NO_vsnprintf -# endif -# ifdef WIN32 - /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */ -# if !defined(vsnprintf) && !defined(NO_vsnprintf) -# if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 ) -# define vsnprintf _vsnprintf -# endif -# endif -# endif -# ifdef __SASC -# define NO_vsnprintf -# endif -#endif -#ifdef VMS -# define NO_vsnprintf -#endif - -#if defined(pyr) +#if defined(pyr) || defined(Z_SOLO) # define NO_MEMCPY #endif #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) @@ -261,14 +234,19 @@ extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ # define Tracecv(c,x) #endif - -voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items, - unsigned size)); -void ZLIB_INTERNAL zcfree OF((voidpf opaque, voidpf ptr)); +#ifndef Z_SOLO + voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items, + unsigned size)); + void ZLIB_INTERNAL zcfree OF((voidpf opaque, voidpf ptr)); +#endif #define ZALLOC(strm, items, size) \ (*((strm)->zalloc))((strm)->opaque, (items), (size)) #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) #define TRY_FREE(s, p) {if (p) ZFREE(s, p);} +/* Reverse the bytes in a 32-bit value */ +#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ + (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) + #endif /* ZUTIL_H */ diff --git a/doc/gpl-2.0.txt b/doc/GPL-2.0.txt index d159169d105..d159169d105 100644 --- a/doc/gpl-2.0.txt +++ b/doc/GPL-2.0.txt diff --git a/sql/old/3.3.5a/2012_08_04_03_world_disables.sql b/sql/old/3.3.5a/2012_08_04_03_world_disables.sql index 21b55a3e930..e2d1ca1ff6b 100644 --- a/sql/old/3.3.5a/2012_08_04_03_world_disables.sql +++ b/sql/old/3.3.5a/2012_08_04_03_world_disables.sql @@ -1,4 +1,4 @@ -DELETE FROM `disables` WHERE `sourceType`=1 AND `entry` IN (9754,9755,10215,11522,12445,12731,12923,13541); +DELETE FROM `disables` WHERE `sourceType`=1 AND `entry` IN (9754,9755,10215,11522,12445,12731,12923,13541,7797,7869,7870,7906,9378,9611,9880,9881,9908,9909,9949,9950,10088,10181,10214,10454,11197,11226,11577,11874,11937,12485,12600,13123,13210,13317,13990); INSERT INTO `disables` (`sourceType`,`entry`,`flags`,`params_0`,`params_1`,`comment`) VALUES (1,9754,0,'','','Deprecated quest: '), (1,9755,0,'','','Deprecated quest: '), diff --git a/sql/updates/characters/2012_08_27_00_characters_guild_bank_eventlog.sql b/sql/updates/characters/2012_08_27_00_characters_guild_bank_eventlog.sql new file mode 100644 index 00000000000..c019bc81504 --- /dev/null +++ b/sql/updates/characters/2012_08_27_00_characters_guild_bank_eventlog.sql @@ -0,0 +1 @@ +DELETE FROM `guild_bank_eventlog` WHERE `EventType` IN (3,7) AND `TabId`=`DestTabId`; -- delete log entries of item moves within one tab diff --git a/sql/updates/world/2012_08_23_00_world_wintergrasp_spell_script_names.sql b/sql/updates/world/2012_08_23_00_world_wintergrasp_spell_script_names.sql new file mode 100644 index 00000000000..a3dbf81d425 --- /dev/null +++ b/sql/updates/world/2012_08_23_00_world_wintergrasp_spell_script_names.sql @@ -0,0 +1,3 @@ +DELETE FROM `spell_script_names` WHERE `spell_id` = 54640; +INSERT INTO `spell_script_names` (`spell_id`,`ScriptName`) VALUES +(54640, 'spell_wintergrasp_defender_teleport'); diff --git a/sql/updates/world/2012_08_23_01_world_wintergrasp_gameobject.sql b/sql/updates/world/2012_08_23_01_world_wintergrasp_gameobject.sql new file mode 100644 index 00000000000..27f7b4027f1 --- /dev/null +++ b/sql/updates/world/2012_08_23_01_world_wintergrasp_gameobject.sql @@ -0,0 +1 @@ +DELETE FROM `gameobject` WHERE `guid` IN (67259,67135,60476,66674,66675,67127,67128,66728,66731,67125,66730,66732,67126,67256,67132,67133,66733,67134,67251,67255,67129,67130,67131,67253,67258,67259,67260,75975,75976,76021,76022,66729,66718,66719,66720,66721,66722,66723,66724,66725,66726); diff --git a/sql/updates/world/2012_08_25_00_world_creature_template.sql b/sql/updates/world/2012_08_25_00_world_creature_template.sql new file mode 100644 index 00000000000..f7ec4c87fb9 --- /dev/null +++ b/sql/updates/world/2012_08_25_00_world_creature_template.sql @@ -0,0 +1,3 @@ +-- Wintergrasp Siege Turret +UPDATE `creature_template` SET `faction_A`=1732,`faction_H`=1732 WHERE `entry`=28319; -- Alliance +UPDATE `creature_template` SET `faction_A`=1735,`faction_H`=1735 WHERE `entry`=32629; -- Horde diff --git a/sql/updates/world/2012_08_25_01_world_creature_template.sql b/sql/updates/world/2012_08_25_01_world_creature_template.sql new file mode 100644 index 00000000000..ef8e5bdd8fc --- /dev/null +++ b/sql/updates/world/2012_08_25_01_world_creature_template.sql @@ -0,0 +1 @@ +UPDATE `creature_template` SET `faction_A`=103,`faction_H`=103 WHERE `entry` IN (30890,31540); -- Twilight Whelp diff --git a/sql/updates/world/2012_08_26_00_world_conditions.sql b/sql/updates/world/2012_08_26_00_world_conditions.sql new file mode 100644 index 00000000000..c33d9bfc878 --- /dev/null +++ b/sql/updates/world/2012_08_26_00_world_conditions.sql @@ -0,0 +1,5 @@ +DELETE FROM `conditions` WHERE `SourceTypeOrReferenceId`=13 AND `SourceEntry`=61632; +INSERT INTO `conditions` (`SourceTypeOrReferenceId`,`SourceGroup`,`SourceEntry`,`SourceId`,`ElseGroup`,`ConditionTypeOrReference`,`ConditionTarget`,`ConditionValue1`,`ConditionValue2`,`ConditionValue3`,`NegativeCondition`,`ErrorTextId`,`ScriptName`,`Comment`) VALUES +(13,7,61632,0,0,31,0,3,30449,0,0,0,'','Sartharion Berserk - Only hit Tenebron, Shadron & Vesperon'), +(13,7,61632,0,1,31,0,3,30451,0,0,0,'','Sartharion Berserk - Only hit Tenebron, Shadron & Vesperon'), +(13,7,61632,0,2,31,0,3,30452,0,0,0,'','Sartharion Berserk - Only hit Tenebron, Shadron & Vesperon'); diff --git a/sql/updates/world/2012_08_26_00_world_spell_script_names_434.sql b/sql/updates/world/2012_08_26_00_world_spell_script_names_434.sql new file mode 100644 index 00000000000..d9bb921bf8a --- /dev/null +++ b/sql/updates/world/2012_08_26_00_world_spell_script_names_434.sql @@ -0,0 +1,3 @@ +DELETE FROM `spell_script_names` WHERE `spell_id`=15473; +INSERT INTO `spell_script_names` (`spell_id`,`ScriptName`) VALUES +(15473,'spell_pri_shadowform'); diff --git a/sql/updates/world/2012_08_26_01_world_creature.sql b/sql/updates/world/2012_08_26_01_world_creature.sql new file mode 100644 index 00000000000..af14886850d --- /dev/null +++ b/sql/updates/world/2012_08_26_01_world_creature.sql @@ -0,0 +1 @@ +UPDATE `creature` SET `phaseMask`=256 WHERE `id`=34300; diff --git a/sql/updates/world/2012_08_26_02_world_spell_area.sql b/sql/updates/world/2012_08_26_02_world_spell_area.sql new file mode 100644 index 00000000000..c4eae68e3c4 --- /dev/null +++ b/sql/updates/world/2012_08_26_02_world_spell_area.sql @@ -0,0 +1,3 @@ +DELETE FROM `spell_area` WHERE spell=58045; +INSERT INTO `spell_area` (`spell`,`area`,`quest_start`,`quest_start_active`,`quest_end`,`aura_spell`,`racemask`,`gender`,`autocast`) VALUES +(58045,4197,0,0,0,0,0,2,1); diff --git a/sql/updates/world/2012_08_26_03_world_spell_area.sql b/sql/updates/world/2012_08_26_03_world_spell_area.sql new file mode 100644 index 00000000000..65072d2b4a7 --- /dev/null +++ b/sql/updates/world/2012_08_26_03_world_spell_area.sql @@ -0,0 +1,3 @@ +DELETE FROM `spell_area` WHERE spell=74411 AND `area`=4197; +INSERT INTO `spell_area` (`spell`,`area`,`quest_start`,`quest_start_active`,`quest_end`,`aura_spell`,`racemask`,`gender`,`autocast`) VALUES +(74411,4197,0,0,0,0,0,2,1); diff --git a/sql/updates/world/2012_08_27_00_world_creature_template.sql b/sql/updates/world/2012_08_27_00_world_creature_template.sql new file mode 100644 index 00000000000..804d7b5c61d --- /dev/null +++ b/sql/updates/world/2012_08_27_00_world_creature_template.sql @@ -0,0 +1,2 @@ +-- NPC script linking for Wyrmrest Defender ID: 27629 +UPDATE `creature_template` SET `ScriptName`='npc_wyrmrest_defender' WHERE `entry`=27629; diff --git a/sql/updates/world/2012_08_27_00_world_spell_script_name.sql b/sql/updates/world/2012_08_27_00_world_spell_script_name.sql new file mode 100644 index 00000000000..1d036df0a65 --- /dev/null +++ b/sql/updates/world/2012_08_27_00_world_spell_script_name.sql @@ -0,0 +1,4 @@ +-- Spell script name linking for Defending Wyrmrest Temple: Character Script Cast From Gossip ID: 49123 +DELETE FROM `spell_script_names` WHERE `spell_id`=49213; +INSERT INTO `spell_script_names` (`spell_id`, `ScriptName`) VALUES +(49213,'spell_q12372_cast_from_gossip_trigger'); diff --git a/sql/updates/world/2012_08_27_01_world_sai.sql b/sql/updates/world/2012_08_27_01_world_sai.sql new file mode 100644 index 00000000000..302c3ac1942 --- /dev/null +++ b/sql/updates/world/2012_08_27_01_world_sai.sql @@ -0,0 +1,13 @@ +DELETE FROM `creature_ai_scripts` WHERE `creature_id`=17398; +UPDATE `creature_template` SET `AIName`='SmartAI' WHERE `entry`=17398; + +DELETE FROM `smart_scripts` WHERE `entryorguid` IN (-85712,-85717,-85719,-85724); +INSERT INTO `smart_scripts` (`entryorguid`, `source_type`, `id`, `link`, `event_type`, `event_phase_mask`, `event_chance`, `event_flags`, `event_param1`, `event_param2`, `event_param3`, `event_param4`, `action_type`, `action_param1`, `action_param2`, `action_param3`, `action_param4`, `action_param5`, `action_param6`, `target_type`, `target_param1`, `target_param2`, `target_param3`, `target_x`, `target_y`, `target_z`, `target_o`, `comment`) VALUES +(-85724, 0, 0, 0, 6, 0, 100, 0, 0, 0, 0, 0, 9, 29607, 0, 0, 0, 0, 0, 14, 22299, 0, 0, 0, 0, 0, 0, 'Blood Furnace - First Cell'), +(-85719, 0, 0, 0, 6, 0, 100, 0, 0, 0, 0, 0, 9, 29607, 0, 0, 0, 0, 0, 14, 22297, 0, 0, 0, 0, 0, 0, 'Blood Furnace - Second Cell'), +(-85717, 0, 0, 0, 6, 0, 100, 0, 0, 0, 0, 0, 9, 29607, 0, 0, 0, 0, 0, 14, 22298, 0, 0, 0, 0, 0, 0, 'Blood Furnace - Third Cell'), +(-85712, 0, 0, 0, 6, 0, 100, 0, 0, 0, 0, 0, 9, 29607, 0, 0, 0, 0, 0, 14, 22296, 0, 0, 0, 0, 0, 0, 'Blood Furnace - Fourth Cell'); + +DELETE FROM `gameobject_scripts` WHERE `id`=150441; +INSERT INTO `gameobject_scripts` (`id`, `delay`, `command`, `datalong`, `datalong2`, `dataint`, `x`, `y`, `z`, `o`) VALUES +(150441, 3, 11, 22295, 0, 0, 0, 0, 0, 0); diff --git a/sql/updates/world/2012_08_27_02_world_creature.sql b/sql/updates/world/2012_08_27_02_world_creature.sql new file mode 100644 index 00000000000..3595ea7b576 --- /dev/null +++ b/sql/updates/world/2012_08_27_02_world_creature.sql @@ -0,0 +1,4 @@ +SET @GUID = 42638; -- Set by TDB team (need X) +DELETE FROM `creature` WHERE `guid`=@GUID AND `id`=7172; +INSERT INTO `creature` (`guid`, `id`, `map`, `spawnMask`, `phaseMask`, `modelid`, `equipment_id`, `position_x`, `position_y`, `position_z`, `orientation`, `spawntimesecs`, `spawndist`, `currentwaypoint`, `curhealth`, `curmana`, `MovementType`, `npcflag`, `unit_flags`, `dynamicflags`) VALUES +(@GUID,7172,70,1,1,0,0,150.466,306.014,-49.543,5.2359,300,0,0,1,0,0,0,0,0); diff --git a/sql/updates/world/2012_08_27_02_world_playercreateinfo_spell.sql b/sql/updates/world/2012_08_27_02_world_playercreateinfo_spell.sql new file mode 100644 index 00000000000..9c664142bba --- /dev/null +++ b/sql/updates/world/2012_08_27_02_world_playercreateinfo_spell.sql @@ -0,0 +1,9 @@ +DELETE FROM `playercreateinfo_spell` WHERE `Spell` IN (59221,59535,59536,59538,59539,59540,59541); +INSERT INTO `playercreateinfo_spell` (`race`, `class`, `Spell`, `Note`) VALUES +(11,1,59221,'Shadow Resistance'), +(11,2,59535,'Shadow Resistance'), +(11,3,59536,'Shadow Resistance'), +(11,5,59538,'Shadow Resistance'), +(11,6,59539,'Shadow Resistance'), +(11,7,59540,'Shadow Resistance'), +(11,8,59541,'Shadow Resistance'); diff --git a/sql/updates/world/2012_08_27_03_world_gameobject.sql b/sql/updates/world/2012_08_27_03_world_gameobject.sql new file mode 100644 index 00000000000..1bf836c96e0 --- /dev/null +++ b/sql/updates/world/2012_08_27_03_world_gameobject.sql @@ -0,0 +1,6 @@ +-- Spawn Blackened Urn (194092) GO based on sniff by Aokromes +SET @GUID := 334; -- Set by TDB team + +DELETE FROM `gameobject` WHERE `id`=194092; +INSERT INTO `gameobject` (`guid`,`id`,`map`,`spawnMask`,`phaseMask`,`position_x`,`position_y`,`position_z`,`orientation`,`rotation0`,`rotation1`,`rotation2`,`rotation3`,`spawntimesecs`,`animprogress`,`state`) VALUES +(@GUID,194092,532,1,1,-11126.87,-1874.455,91.47264,6.056293,0,0,-0.113203,0.9935719,180,100,1); diff --git a/sql/updates/world/2012_08_27_04_world_quest_template.sql b/sql/updates/world/2012_08_27_04_world_quest_template.sql new file mode 100644 index 00000000000..9169a6e5862 --- /dev/null +++ b/sql/updates/world/2012_08_27_04_world_quest_template.sql @@ -0,0 +1 @@ +UPDATE `quest_template` SET `NextQuestId`=12257 WHERE `ID`=12468; diff --git a/sql/updates/world/2012_08_27_05_world_sai.sql b/sql/updates/world/2012_08_27_05_world_sai.sql new file mode 100644 index 00000000000..3da0143e6e6 --- /dev/null +++ b/sql/updates/world/2012_08_27_05_world_sai.sql @@ -0,0 +1,56 @@ +-- A Race Against Time (11671) + +SET @NPC_SALRAND := 25584; -- Inquisitor Salrand +SET @NPC_BERYL_INVISMAN := 25594; -- Beryl Point InvisMan +SET @GOB_BERYL_SHIELD := 187773; -- Beryl Shield +SET @GOB_BERYL_SHIELD_FOCUS := 300176; -- TEMP Beryl Force Shield +SET @SPELL_BEAM := 45777; -- Salrand's Beam +SET @SPELL_THROW_DETONATOR := 45780; -- Throw Beryl Shield Detonator +SET @SPELL_SUMMON_DETONATOR := 45791; -- Summon Beryl Detonator +SET @SPELL_EXPLOSION := 45796; -- Beryl Shield Explosion +SET @SPELL_LOCKBOX := 45809; -- Summon Salrand's Lockbox +SET @GUID := 60441; -- used for a wrong go spawn,will reuse + +UPDATE `gameobject_template` SET `data1`=80 WHERE `entry`=300176; -- spell focus radius +UPDATE `gameobject_template` SET `flags`=32 WHERE `entry`=187773; -- shield:nodespawn flag + +-- missing spell focus +DELETE FROM `gameobject` WHERE `guid`=@GUID; +INSERT INTO `gameobject` (`guid`,`id`,`map`,`spawnMask`,`phaseMask`,`position_x`,`position_y`,`position_z`,`orientation`,`rotation0`,`rotation1`,`rotation2`,`rotation3`,`spawntimesecs`,`animprogress`,`state`) VALUES +(@GUID,@GOB_BERYL_SHIELD_FOCUS,571,1,1,3392.85,6161.089,79.8313,0,0,0,0,0,300,0,1); + +UPDATE `creature_template` SET `InhabitType`=0x4,`unit_flags`=0x100,`AIName`='SmartAI' WHERE `entry`=@NPC_SALRAND; +UPDATE `creature_template` SET `AIName`='SmartAI' WHERE `entry`=@NPC_BERYL_INVISMAN; + +DELETE FROM `creature_template_addon` WHERE `entry`=@NPC_SALRAND; +INSERT INTO `creature_template_addon` (`entry`,`mount`,`bytes1`,`bytes2`,`auras`) VALUES +(@NPC_SALRAND,0,0x0,0x1,'45775'); + +DELETE FROM `creature_ai_scripts` WHERE `creature_id`=@NPC_SALRAND; +DELETE FROM `smart_scripts` WHERE (`source_type`=0 AND `entryorguid` IN (@NPC_SALRAND,@NPC_BERYL_INVISMAN)) OR (`source_type`=9 AND `entryorguid` IN (@NPC_SALRAND*100,@NPC_BERYL_INVISMAN*100)); +INSERT INTO `smart_scripts` (`entryorguid`,`source_type`,`id`,`link`,`event_type`,`event_phase_mask`,`event_chance`,`event_flags`,`event_param1`,`event_param2`,`event_param3`,`event_param4`,`action_type`,`action_param1`,`action_param2`,`action_param3`,`action_param4`,`action_param5`,`action_param6`,`target_type`,`target_param1`,`target_param2`,`target_param3`,`target_x`,`target_y`,`target_z`,`target_o`,`comment`) VALUES +(@NPC_SALRAND,0,0,0,38,0,100,1,1,1,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,'On data 1 1 - Say'), +(@NPC_SALRAND,0,1,2,38,0,100,1,1,2,0,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,'On data 1 2 - Say'), +(@NPC_SALRAND,0,2,0,61,0,100,1,0,0,0,0,80,@NPC_SALRAND*100,0,0,0,0,0,1,0,0,0,0,0,0,0,'On link - Run script'), +(@NPC_SALRAND,0,3,4,6,0,100,1,0,0,0,0,11,@SPELL_LOCKBOX,0,0,0,0,0,1,0,0,0,0,0,0,0,'On death - Cast spell'), +(@NPC_SALRAND,0,4,0,61,0,100,1,0,0,0,0,1,2,0,0,0,0,0,1,0,0,0,0,0,0,0,'On death - Say'), +(@NPC_SALRAND,0,5,0,11,0,100,1,0,0,0,0,24,0,0,0,0,0,0,15,0,0,0,0,0,0,0,'On respawn - Evade'), +(@NPC_SALRAND*100,9,0,0,0,0,100,0,0,0,0,0,60,0,0,0,0,0,0,1,0,0,0,0,0,0,0,'On script - set fly off'), +(@NPC_SALRAND*100,9,1,0,0,0,100,0,0,0,0,0,69,0,0,0,0,0,0,8,0,0,0,3392.852,6161.092,79.83095,0,'On script - Move to pos'), +(@NPC_SALRAND*100,9,2,0,0,0,100,0,3000,3000,0,0,19,256,0,0,0,0,0,1,0,0,0,0,0,0,0,'On script - Set unit flags'), +-- +(@NPC_BERYL_INVISMAN,0,0,0,8,0,100,0,@SPELL_THROW_DETONATOR,0,0,0,80,@NPC_BERYL_INVISMAN*100,0,0,0,0,0,1,0,0,0,0,0,0,0,'On spellhit - Run Script'), +(@NPC_BERYL_INVISMAN*100,9,0,0,0,0,100,0,0,0,0,0,11,@SPELL_SUMMON_DETONATOR,0,0,0,0,0,1,0,0,0,0,0,0,0,'On script - Cast Spell'), +(@NPC_BERYL_INVISMAN*100,9,1,0,0,0,100,0,0,0,0,0,45,1,1,0,0,0,0,19,@NPC_SALRAND,100,0,0,0,0,0,'On script - Set Data'), +(@NPC_BERYL_INVISMAN*100,9,2,0,0,0,100,0,8000,8000,0,0,45,1,2,0,0,0,0,19,@NPC_SALRAND,100,0,0,0,0,0,'On script - Set Data'), +(@NPC_BERYL_INVISMAN*100,9,3,0,0,0,100,0,2000,2000,0,0,11,@SPELL_EXPLOSION,0,0,0,0,0,1,0,0,0,0,0,0,0,'On script - Cast Spell'); + +DELETE FROM `creature_text` WHERE `entry`=@NPC_SALRAND; +INSERT INTO `creature_text` (`entry`,`groupid`,`id`,`text`,`type`,`language`,`probability`,`emote`,`duration`,`sound`,`comment`) VALUES +(@NPC_SALRAND,0,0,'What is the meaning of this disturbance?!',14,0,100,0,0,0,'Inquisitor Salrand to Beryl Point InvisMan'), +(@NPC_SALRAND,1,0,'Who dares interrupt my work!? Show yourself, coward!',14,0,100,0,0,0,'Inquisitor Salrand to Beryl Point InvisMan'), +(@NPC_SALRAND,2,0,'I''ve destroyed the key! Your cherished archmage belongs to Malygos!',12,0,100,0,0,0,'Inquisitor Salrand'); + +DELETE FROM `conditions` WHERE `SourceTypeOrReferenceId`=13 AND `SourceEntry`=@SPELL_THROW_DETONATOR; +INSERT INTO `conditions` (`SourceTypeOrReferenceId`,`SourceGroup`,`SourceEntry`,`SourceId`,`ElseGroup`,`ConditionTypeOrReference`,`ConditionTarget`,`ConditionValue1`,`ConditionValue2`,`ConditionValue3`,`NegativeCondition`,`ErrorTextId`,`ScriptName`,`Comment`) VALUES +(13,1,@SPELL_THROW_DETONATOR,0,0,31,0,3,@NPC_BERYL_INVISMAN,0,0,0,'','Throw Beryl Shield Detonator target npc'); diff --git a/sql/updates/world/2012_08_27_06_world_sai.sql b/sql/updates/world/2012_08_27_06_world_sai.sql new file mode 100644 index 00000000000..8b1aafd1558 --- /dev/null +++ b/sql/updates/world/2012_08_27_06_world_sai.sql @@ -0,0 +1,43 @@ +-- Fix {Q/A} The Shining Light ID: 11288 +-- Makes it blizzlike timed 10 minutes +UPDATE `quest_template` SET `LimitTime`=600 WHERE `id`=11288; +-- Decomposing Ghoul SAI +SET @Ghoul := 24177; +SET @SpellTrigger := 43202; +SET @Spell := 43203; +SET @Ares := 24189; +UPDATE `creature_template` SET `AIname`='SmartAI' WHERE `entry`=@Ghoul; +DELETE FROM `smart_scripts` WHERE `source_type`=0 AND `entryorguid`=@Ghoul; +INSERT INTO `smart_scripts` (`entryorguid`,`source_type`,`id`,`link`,`event_type`,`event_phase_mask`,`event_chance`,`event_flags`,`event_param1`,`event_param2`,`event_param3`,`event_param4`,`action_type`,`action_param1`,`action_param2`,`action_param3`,`action_param4`,`action_param5`,`action_param6`,`target_type`,`target_param1`,`target_param2`,`target_param3`,`target_x`,`target_y`,`target_z`,`target_o`,`comment`) VALUES +(@Ghoul,0,0,0,1,0,100,0,20000,300000,50000,350000,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,'Decomposing Ghoul - Occ - Say random text'), +(@Ghoul,0,1,2,8,0,100,0,@Spell,0,0,0,18,33685506,0,0,0,0,0,1,0,0,0,0,0,0,0,'Decomposing Ghoul - On hit by spell - Set unit flag for not targetable'), +(@Ghoul,0,2,3,61,0,100,0,0,0,0,0,2,35,0,0,0,0,0,1,0,0,0,0,0,0,0,'Decomposing Ghoul - Linked with previous event - Switch faction to clear aggro'), +(@Ghoul,0,3,0,61,0,100,0,0,0,0,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,'Decomposing Ghoul - Linked with previous event - Say random text'), +(@Ghoul,0,4,5,1,0,100,0,3500,3500,3500,3500,19,33685506,0,0,0,0,0,1,0,0,0,0,0,0,0,'Decomposing Ghoul - OOC for 3,5 sec - Remove unit flag'), +(@Ghoul,0,5,0,61,0,100,0,0,0,0,0,2,14,0,0,0,0,0,1,0,0,0,0,0,0,0,'Decomposing Ghoul - Linked with previous event - Change faction back to 14'); +-- Add SAI for Ares - quest giver +UPDATE `creature_template` SET `AIname`='SmartAI' WHERE `entry`=@Ares; +DELETE FROM `smart_scripts` WHERE `source_type`=0 AND `entryorguid`=@Ares; +INSERT INTO `smart_scripts` (`entryorguid`,`source_type`,`id`,`link`,`event_type`,`event_phase_mask`,`event_chance`,`event_flags`,`event_param1`,`event_param2`,`event_param3`,`event_param4`,`action_type`,`action_param1`,`action_param2`,`action_param3`,`action_param4`,`action_param5`,`action_param6`,`target_type`,`target_param1`,`target_param2`,`target_param3`,`target_x`,`target_y`,`target_z`,`target_o`,`comment`) VALUES +(@Ares,0,0,0,19,0,100,0,11288,0,0,0,85,@SpellTrigger,0,0,0,0,0,7,0,0,0,0,0,0,0,'Ares - On target quest accepted 11288 - Cast spell Shining Light'); +-- Decomposing Ghoul texts +DELETE FROM `creature_text` WHERE `entry`=@Ghoul; +INSERT INTO `creature_text` (`entry`,`groupid`,`id`,`text`,`type`,`language`,`probability`,`emote`,`duration`,`sound`,`comment`) VALUES +(@Ghoul,0,1,'Light... light so bright...',12,0,50,0,0,0,'Decomposing Ghoul - On spell hit'), +(@Ghoul,0,2,'ARGHHHH...',12,0,50,0,0,0,'Decomposing Ghoul - On spell hit'), +(@Ghoul,0,3,'Away... go...',12,0,50,0,0,0,'Decomposing Ghoul - On spell hit'), +(@Ghoul,0,4,'Bad light... hurt...',12,0,50,0,0,0,'Decomposing Ghoul - On spell hit'), +(@Ghoul,0,5,'BURNS! IT BURNS!',12,0,50,0,0,0,'Decomposing Ghoul - On spell hit'), +(@Ghoul,1,1,'So... Hungry...',12,0,50,0,0,0,'Decomposing Ghoul - OOC'), +(@Ghoul,1,2,'Closer... come closer...',12,0,50,0,0,0,'Decomposing Ghoul - OOC'), +(@Ghoul,1,3,'FEED ME...',12,0,50,0,0,0,'Decomposing Ghoul - OOC'), +(@Ghoul,1,4,'FOOD! EAT YOU!',12,0,50,0,0,0,'Decomposing Ghoul - OOC'), +(@Ghoul,1,5,'BRAINNNS!',12,0,50,0,0,0,'Decomposing Ghoul - OOC'); +-- Add conditions for spell Shining Light to hit only Ghouls +DELETE FROM `conditions` WHERE `SourceEntry`=@Spell AND `SourceTypeOrReferenceId`=13; +INSERT INTO `conditions` (`SourceTypeOrReferenceId`, `SourceGroup`, `SourceEntry`, `SourceId`, `ElseGroup`, `ConditionTypeOrReference`, `ConditionTarget`, `ConditionValue1`, `ConditionValue2`, `ConditionValue3`, `NegativeCondition`, `ErrorTextId`, `ScriptName`, `Comment`) VALUES +(13,1,@Spell,0,0,31,0,3,@Ghoul,0,0,0,'', 'Shinning Light can only hit Decomposing Ghouls'); +-- Add conditions for spell Shining Light to be available only, if on quest +DELETE FROM `conditions` WHERE `SourceEntry`=@Spell AND `SourceTypeOrReferenceId`=17; +INSERT INTO `conditions` (`SourceTypeOrReferenceId`, `SourceGroup`, `SourceEntry`, `SourceId`, `ElseGroup`, `ConditionTypeOrReference`, `ConditionTarget`, `ConditionValue1`, `ConditionValue2`, `ConditionValue3`, `NegativeCondition`, `ErrorTextId`, `ScriptName`, `Comment`) VALUES +(17,0,@Spell,0,0,9,0,11288,0,0,0,0,'', 'Shinning Light can only hit targets on the quest'); diff --git a/sql/updates/world/2012_08_27_07_world_spell_area.sql b/sql/updates/world/2012_08_27_07_world_spell_area.sql new file mode 100644 index 00000000000..18be6ff0dbe --- /dev/null +++ b/sql/updates/world/2012_08_27_07_world_spell_area.sql @@ -0,0 +1,4 @@ +-- Fix quest - The Angry Gorloc ID: 12578 +DELETE FROM `spell_area` WHERE `spell`=54057; +INSERT INTO `spell_area` (`spell`, `area`, `quest_start`, `quest_start_active`, `quest_end`, `aura_spell`, `racemask`, `gender`, `autocast`) VALUES +(54057, 4297, 12578, 1, 12578, 0, 0, 2, 1); diff --git a/sql/updates/world/2012_08_27_08_world_misc.sql b/sql/updates/world/2012_08_27_08_world_misc.sql new file mode 100644 index 00000000000..62a57cd42de --- /dev/null +++ b/sql/updates/world/2012_08_27_08_world_misc.sql @@ -0,0 +1,29 @@ +-- Fire Upon the Waters (12243) quest fix +-- add Fire Upon the Waters Kill Credit Bunny at sail locations +SET @GUID =42887; +DELETE FROM `creature` WHERE `id`=28013; +INSERT INTO `creature` (`guid`,`id`,`map`,`spawnMask`,`phaseMask`,`modelid`,`equipment_id`,`position_x`,`position_y`,`position_z`,`orientation`,`spawntimesecs`,`spawndist`,`currentwaypoint`,`curhealth`,`curmana`,`MovementType`,`npcflag`,`unit_flags`,`dynamicflags`) VALUES +(@GUID+0,28013,571,1,1,0,0,2488.86,-400.017,19.0803,2.99498,300,0,0,42,0,0,0,33554432,0), +(@GUID+1,28013,571,1,1,0,0,2458.96,-401.066,20.7778,0.108631,300,0,0,42,0,0,0,33554432,0); + +-- SAI +UPDATE `creature_template` SET `AIName` = 'SmartAI' WHERE `entry` = 28013; +DELETE FROM `smart_scripts` WHERE `entryorguid`=28013 AND `source_type`=0; +INSERT INTO `smart_scripts` (`entryorguid`,`source_type`,`id`,`link`,`event_type`,`event_phase_mask`,`event_chance`,`event_flags`,`event_param1`,`event_param2`,`event_param3`,`event_param4`,`action_type`,`action_param1`,`action_param2`,`action_param3`,`action_param4`,`action_param5`,`action_param6`,`target_type`,`target_param1`,`target_param2`,`target_param3`,`target_x`,`target_y`,`target_z`,`target_o`,`comment`) VALUES +(28013,0,0,0,8,0,100,0,48455,0,0,0,33,28013,0,0,0,0,0,7,0,0,0,0,0,0,0,"Fire Upon the Waters Kill Credit Bunny - On SpellHit Apothecary's Burning Water - Call KilledMonster Fire Upon the Waters Kill Credit Bunny"); + +-- Ensure spell only works on Fire Upon the Waters Kill Credit Bunny +DELETE FROM `conditions` WHERE `SourceTypeOrReferenceId`=13 AND `SourceEntry`=48455; +INSERT INTO `conditions` (`SourceTypeOrReferenceId`,`SourceGroup`,`SourceEntry`,`SourceId`,`ElseGroup`,`ConditionTypeOrReference`,`ConditionTarget`,`ConditionValue1`,`ConditionValue2`,`ConditionValue3`,`NegativeCondition`,`ErrorTextId`,`ScriptName`,`Comment`) VALUES +(13,1,48455,0,0,31,0,3,28013,0,0,0,'',"Fire Upon the Waters - spell to Fire Upon the Waters Kill Credit Bunny"); + +-- add quest item loot to Captain Shely +DELETE FROM `creature_loot_template` WHERE `entry`=27232; +INSERT INTO `creature_loot_template` (`entry`,`item`,`ChanceOrQuestChance`,`lootmode`,`groupid`,`mincountOrRef`,`maxcount`) VALUES +(27232,37305,-100,1,0,1,1), -- Captain Shely's Rutters +(27232,43851,25,1,0,1,1), -- Fur Clothing Scraps +(27232,33470,10,1,0,1,3), -- Frostweave Cloth +(27232,33443,5,1,0,1,1), -- Sour Goat Cheese +(27232,33444,2,1,0,1,1), -- Pungent Seal Whey +(27232,22829,1,1,0,1,1), -- Super Healing Potion +(27232,45912,0.05,1,0,1,1); -- Book Glyph of Mastery diff --git a/sql/updates/world/2012_08_27_09_world_conditions.sql b/sql/updates/world/2012_08_27_09_world_conditions.sql new file mode 100644 index 00000000000..6d536859060 --- /dev/null +++ b/sql/updates/world/2012_08_27_09_world_conditions.sql @@ -0,0 +1,8 @@ +DELETE FROM `conditions` WHERE `SourceTypeOrReferenceId`=13 AND `SourceEntry` IN (62973,62991); +INSERT INTO `conditions` (`SourceTypeOrReferenceId`, `SourceGroup`, `SourceEntry`, `SourceId`, `ElseGroup`, `ConditionTypeOrReference`, `ConditionTarget`, `ConditionValue1`, `ConditionValue2`, `ConditionValue3`, `NegativeCondition`, `ErrorTextId`, `ScriptName`, `Comment`) VALUES +(13,3,62973,0,0, 1,0,62972,0,0,0,0,'','Foam Sword Attack'), +(13,3,62973,0,0,31,0,4,0,0,0,0,'','Foam Sword Attack'), +(13,3,62973,0,0,33,0,1,0,0,1,0,'','Foam Sword Attack'), +(13,3,62991,0,0, 1,0,62972,0,0,0,0,'','Bonked!'), +(13,3,62991,0,0,31,0,4,0,0,0,0,'','Bonked!'), +(13,3,62991,0,0,33,0,1,0,0,1,0,'','Bonked!'); diff --git a/sql/updates/world/2012_08_27_10_world_spell_script_names.sql b/sql/updates/world/2012_08_27_10_world_spell_script_names.sql new file mode 100644 index 00000000000..9ffb153f498 --- /dev/null +++ b/sql/updates/world/2012_08_27_10_world_spell_script_names.sql @@ -0,0 +1,4 @@ +DELETE FROM `spell_script_names` WHERE `spell_id`IN (64142,62991); +INSERT INTO `spell_script_names` (`spell_id`,`ScriptName`) VALUES +(64142,'spell_gen_upper_deck_create_foam_sword'), +(62991,'spell_gen_bonked'); diff --git a/sql/updates/world/2012_08_28_00_world_spell_script_name.sql b/sql/updates/world/2012_08_28_00_world_spell_script_name.sql new file mode 100644 index 00000000000..01cfeb35f1f --- /dev/null +++ b/sql/updates/world/2012_08_28_00_world_spell_script_name.sql @@ -0,0 +1,4 @@ +-- Spell script name linking for Defending Wyrmrest Temple: Destabilize Azure Dragonshrine Effect +DELETE FROM `spell_script_names` WHERE `spell_id`=49370 ; +INSERT INTO `spell_script_names` VALUES +(49370,'spell_q12372_destabilize_azure_dragonshrine_dummy'); diff --git a/sql/updates/world/2012_08_28_01_world_achievement_criteria_data.sql b/sql/updates/world/2012_08_28_01_world_achievement_criteria_data.sql new file mode 100644 index 00000000000..bf247399553 --- /dev/null +++ b/sql/updates/world/2012_08_28_01_world_achievement_criteria_data.sql @@ -0,0 +1,6 @@ +DELETE FROM `achievement_criteria_data` WHERE `criteria_id` IN (11478,11479,12827,12828); +INSERT INTO `achievement_criteria_data` (`criteria_id`, `type`, `value1`, `value2`, `ScriptName`) VALUES +(11478, 12, 0, 0, ''), -- Koralon the Flame Watcher (10 player) +(11479, 12, 1, 0, ''), -- Koralon the Flame Watcher (25 player) +(12827, 12, 0, 0, ''), -- Toravon the Ice Watcher (10 player) +(12828, 12, 1, 0, ''); -- Toravon the Ice Watcher (25 player) diff --git a/sql/updates/world/2012_08_29_00_world_blood_furnace.sql b/sql/updates/world/2012_08_29_00_world_blood_furnace.sql new file mode 100644 index 00000000000..85b493da202 --- /dev/null +++ b/sql/updates/world/2012_08_29_00_world_blood_furnace.sql @@ -0,0 +1,290 @@ +SET @GUID := 138106; -- 149 + +-- Delete old data before inserting new data. This could make trouble later on. +DELETE `creature_addon` FROM `creature_addon` INNER JOIN `creature` ON `creature`.`guid`=`creature_addon`.`guid` WHERE `map`=542; +DELETE `creature_formations` FROM `creature_formations` INNER JOIN `creature` ON `creature`.`guid`=`creature_formations`.`memberGUID` OR `creature`.`guid`=`creature_formations`.`leaderGUID` WHERE `map`=542; +DELETE `linked_respawn` FROM `linked_respawn` INNER JOIN `creature` ON `creature`.`guid`=`linked_respawn`.`linkedGuid` WHERE `map`=542; + + +-- CREATURE_TEMPLATE +-- Trash +UPDATE `creature_template` SET `speed_walk`=1.1 WHERE `entry`=17624; +UPDATE `creature_template` SET `AIName`='' WHERE `entry`=17398; +-- Broggok +UPDATE `creature_template` SET `unit_flags`=`unit_flags`|256|512|2 WHERE `entry` IN(17380,18601); + +-- CREATURE +DELETE FROM `creature` WHERE `guid` BETWEEN @GUID AND @GUID+148 OR `map`=542; +INSERT INTO `creature`(`guid`,`id`,`map`,`spawnMask`,`position_x`,`position_y`,`position_z`,`orientation`,`spawntimesecs`,`curhealth`,`curmana`,`MovementType`) VALUES +(@GUID+88,17414,542,3,317.15,189.009,10.0509,1.88412,7200,10472,5875,0), +(@GUID+92,17414,542,3,436.311,198.522,11.4389,1.34468,7200,10472,5875,0), +(@GUID+91,17414,542,3,345.706,198.519,11.139,1.6879,7200,10472,5875,0), +(@GUID+96,17398,542,3,379.741,192.233,9.59787,3.36158,7200,7210,0,0), +(@GUID+103,17414,542,3,448.428,190.764,9.6054,1.01795,7200,10472,5875,0), +(@GUID+97,17395,542,3,373.636,184.777,9.59848,1.15697,7200,10472,17625,0), +(@GUID+95,17371,542,3,371.98,194.243,9.59956,5.36434,7200,10472,5875,0), +(@GUID+94,17491,542,3,480.502,180.017,9.61526,3.42991,7200,7479,0,0), +(@GUID+26,17398,542,3,412.728,85.7323,9.65141,0.141552,7200,6963,0,0), +(@GUID+125,17477,542,3,485.76,8.63405,9.54898,1.43024,7200,4126,9944,0), +(@GUID+68,17371,542,3,327.262,30.5611,9.61686,4.68833,7200,10472,5875,2), +(@GUID+124,17477,542,3,490.168,11.6964,9.54898,1.13336,7200,4126,9944,0), +(@GUID+123,17477,542,3,489.518,5.51373,9.54353,1.96038,7200,4126,9944,0), +(@GUID+122,17371,542,3,494.46,7.58925,9.54249,2.87616,7200,10472,5875,0), +(@GUID+112,17414,542,3,479.898,98.2961,9.62183,6.09707,7200,10472,5875,0), +(@GUID+120,17491,542,3,433.6,-18.2301,9.55216,0.450845,7200,7479,0,0), +(@GUID+126,17477,542,3,484.202,13.9732,9.5505,6.25258,7200,4126,9944,0), +(@GUID+128,17371,542,3,465.905,-19.9126,9.55319,5.19624,7200,10472,5875,2), +(@GUID+129,17371,542,3,476.506,-63.3028,9.54636,0,7200,10472,5875,2), +(@GUID+131,17491,542,3,495.566,-43.8895,9.5591,2.9343,7200,7479,0,0), +(@GUID+46,17477,542,3,-10.8822,-85.2033,-41.3341,2.09342,7200,4126,9944,0), +(@GUID+55,17397,542,3,224.587,-96.0037,9.61879,0.647748,7200,11965,2486,0), +(@GUID+54,17397,542,3,231.512,-91.5716,9.62435,3.65189,7200,11965,2486,0), +(@GUID+56,17477,542,3,227.94,-93.8952,9.61879,0.561355,7200,4126,9944,0), +(@GUID+53,17491,542,3,234.022,-106.406,9.61037,1.88867,7200,7479,0,0), +(@GUID+52,17477,542,3,28.2572,-85.4531,-41.0542,4.63284,7200,4126,9944,0), +(@GUID+59,17477,542,3,241.827,-68.3783,9.61987,1.82585,7200,4126,9944,0), +(@GUID+58,17397,542,3,242.883,-72.4289,9.61514,1.81799,7200,11965,2486,0), +(@GUID+57,17397,542,3,240.674,-64.4904,9.62484,5.05383,7200,11965,2486,0), +(@GUID+14,21174,542,3,320.912,-83.0625,-133.307,3.00197,7200,8338000,0,0), +(@GUID+136,17477,542,3,412.944,-83.971,9.61695,5.1156,7200,4126,9944,0), +(@GUID+137,17477,542,3,420.081,-88.5245,9.62061,0.206074,7200,4126,9944,0), +(@GUID+139,17491,542,3,404.193,-62.5071,9.61827,5.54913,7200,7479,0,0), +(@GUID+134,17477,542,3,432.656,-78.7667,9.62296,1.5821,7200,4126,9944,0), +(@GUID+140,17477,542,3,419.961,-76.9838,9.62318,5.67087,7200,4126,9944,0), +(@GUID+135,17477,542,3,427.911,-69.9011,9.61668,4.99622,7200,4126,9944,0), +(@GUID+142,18894,542,3,355.194,-175.571,-25.5497,0.0701911,7200,14958,0,0), +(@GUID+144,18894,542,3,325.278,-191.535,-25.5078,1.49412,7200,14958,0,0), +(@GUID+145,17371,542,3,312.396,-174.925,-25.5082,6.21829,7200,10472,5875,0), +(@GUID+146,18894,542,3,312.116,-179.382,-25.5071,6.20258,7200,14958,0,0), +(@GUID+147,18894,542,3,313.392,-170.618,-25.5086,6.20651,7200,14958,0,0), +(@GUID+78,17371,542,3,331.268,69.7599,9.61402,1.77024,7200,10472,5875,0), +(@GUID+70,17397,542,3,313.949,13.7401,9.61652,4.38997,7200,11965,2486,0), +(@GUID+69,17395,542,3,311.261,7.92634,9.62195,0.656179,7200,10472,17625,0), +(@GUID+71,17397,542,3,317.184,8.72084,9.6192,2.67896,7200,11965,2486,0), +(@GUID+75,17491,542,3,314.564,-7.67602,9.6169,2.30511,7200,7479,0,0), +(@GUID+77,17370,542,3,331.076,28.8939,9.62118,4.2576,7200,14958,0,0), +(@GUID+73,17395,542,3,338.84,8.10661,9.61679,5.05086,7200,10472,17625,0), +(@GUID+72,17395,542,3,338.242,1.09978,9.61664,1.01391,7200,10472,17625,0), +(@GUID+25,17398,542,3,413.285,81.8238,9.65038,0.154642,7200,6963,0,0), +(@GUID+24,17398,542,3,500.076,84.7778,9.65474,3.08941,7200,6963,0,0), +(@GUID+23,17398,542,3,502.724,82.8731,9.65935,3.08941,7200,6963,0,0), +(@GUID+22,17398,542,3,498.962,83.0695,9.6524,3.08941,7200,6963,0,0), +(@GUID+21,17398,542,3,498.393,86.641,9.65219,3.19309,7200,6963,0,0), +(@GUID+104,17414,542,3,327.172,188.393,9.61882,1.09492,7200,10472,5875,0), +(@GUID+27,17398,542,3,409.226,83.2983,9.65786,0.141552,7200,6963,0,0), +(@GUID+28,17398,542,3,412.081,112.626,9.65613,6.1865,7200,6963,0,0), +(@GUID+29,17398,542,3,412.462,116.555,9.65317,6.1865,7200,6963,0,0), +(@GUID+30,17398,542,3,411.735,114.446,9.65571,0.00803471,7200,6963,0,0), +(@GUID+31,17398,542,3,409.699,113.048,9.65731,0.0185067,7200,6963,0,0), +(@GUID+32,17398,542,3,407.17,115.172,9.66061,0.0185067,7200,6963,0,0), +(@GUID+33,17398,542,3,495.677,116.285,9.64388,3.14963,7200,6963,0,0), +(@GUID+34,17398,542,3,495.696,113.877,9.64425,3.14963,7200,6963,0,0), +(@GUID+35,17398,542,3,499.774,112.283,9.65334,3.14963,7200,6963,0,0), +(@GUID+36,17398,542,3,503.042,114.321,9.65788,3.14963,7200,6963,0,0), +(@GUID+37,17398,542,3,503.024,116.589,9.65788,3.14963,7200,6963,0,0), +(@GUID+38,17398,542,3,499.499,118.085,9.65347,3.14963,7200,6963,0,0), +(@GUID+111,17414,542,3,482.454,103.335,9.61156,5.27398,7200,10472,5875,0), +(@GUID+110,17414,542,3,458.068,92.7015,9.61519,1.89206,7200,10472,5875,0), +(@GUID+109,17414,542,3,452.317,94.5807,9.61519,0.545102,7200,10843,6015,0), +(@GUID+108,17395,542,3,457.121,99.2828,9.61496,4.44777,7200,10472,17625,0), +(@GUID+102,17370,542,3,466.171,176.663,9.6201,2.8927,7200,14958,0,2), +(@GUID+98,17371,542,3,412.814,195.493,9.60144,3.55951,7200,10472,5875,0), +(@GUID+100,17395,542,3,403.447,190.68,9.59739,0.0770466,7200,10472,17625,0), +(@GUID+99,17398,542,3,411.319,185.388,9.60154,2.28952,7200,6963,0,0), +(@GUID+101,17370,542,3,466.657,179.674,9.61915,2.88877,7200,14958,0,2), +(@GUID+76,17370,542,3,323.216,28.6452,9.62206,4.92205,7200,14958,0,0), +(@GUID+74,17397,542,3,344.219,5.00403,9.62297,3.2955,7200,11965,2486,0), +(@GUID+67,17370,542,3,286.75,-7.12364,9.33158,3.50552,7200,14958,0,0), +(@GUID+65,17370,542,3,258.511,-30.4009,6.95261,4.07258,7200,14958,0,0), +(@GUID+63,17371,542,3,246.377,-85.311,9.61661,3.04947,7200,10472,5875,2), +(@GUID+62,17477,542,3,226.371,-71.3008,9.61766,2.01394,7200,4126,9944,0), +(@GUID+60,17397,542,3,224.497,-68.0896,9.62108,5.19786,7200,11965,2486,0), +(@GUID+61,17397,542,3,227.979,-74.6894,9.61909,1.96987,7200,11965,2486,0), +(@GUID+106,17626,542,3,458.614,116.989,9.61455,3.07559,7200,14958,0,0), +(@GUID+43,17491,542,3,182.461,-68.9882,9.62108,3.98337,7200,7479,0,0), +(@GUID+42,17491,542,3,107.083,-96.6171,-14.2289,0.930522,7200,7479,0,0), +(@GUID+51,17397,542,3,27.6779,-90.5785,-40.7088,1.48496,7200,11965,2486,0), +(@GUID+82,17414,542,3,304.249,103.356,9.62076,5.61477,7200,10843,6015,0), +(@GUID+83,17371,542,3,308.919,100.519,9.62138,2.61455,7200,10472,5875,0), +(@GUID+86,17626,542,3,356.154,108.175,9.62332,4.06125,7200,14958,0,0), +(@GUID+85,17371,542,3,343.419,102.651,9.6201,5.16709,7200,10472,5875,0), +(@GUID+93,17414,542,3,346.912,193.875,9.60419,1.74602,7200,10472,5875,0), +(@GUID+115,17414,542,3,476.291,65.9018,9.60985,3.98357,7200,10472,5875,0), +(@GUID+114,17414,542,3,469.409,65.9985,9.61271,5.036,7200,10843,6015,0), +(@GUID+116,17371,542,3,472.66,59.4292,9.6097,1.58025,7200,10472,5875,0), +(@GUID+105,17624,542,3,456.429,118.903,9.61496,3.16198,7200,16023,0,0), +(@GUID+107,17626,542,3,458.704,120.842,9.61456,3.1619,7200,14958,0,2), +(@GUID+127,18894,542,3,462.905,-19.9126,9.55215,5.18053,7200,14958,0,0), +(@GUID+41,17377,542,3,325.862,-87.2087,-24.6512,5.87314,43200,34830,6156,0), +(@GUID+143,18894,542,3,333.631,-192.252,-25.5027,1.51768,7200,14958,0,0), +(@GUID+148,17371,542,3,329.584,-189.111,-25.5067,1.50511,7200,10472,5875,0), +(@GUID+132,17371,542,3,424.675,-83.9057,9.6166,0.059993,7200,10472,5875,0), +(@GUID+130,18894,542,3,475.417,-66.3289,9.54527,0,7200,14958,0,0), +(@GUID+40,18894,542,3,455.566,-79.108,9.61164,0.09548,7200,14958,0,0), +(@GUID+39,18894,542,3,455.793,-89.9999,9.60743,0.09548,7200,14958,0,0), +(@GUID+121,17371,542,3,487.933,17.2848,9.55353,4.54905,7200,10472,5875,0), +(@GUID+119,17414,542,3,445.422,63.6577,9.61209,3.54218,7200,10472,5875,0), +(@GUID+118,17371,542,3,442.237,56.965,9.61104,1.84965,7200,10472,5875,0), +(@GUID+117,17371,542,3,437.232,64.7644,9.60927,5.1656,7200,10472,5875,0), +(@GUID+113,17414,542,3,483.48,91.8948,9.62303,1.14828,7200,10472,5875,0), +(@GUID+20,17398,542,3,437.158,201.984,11.6815,4.639,7200,6963,0,0), +(@GUID+19,17398,542,3,345.078,202.309,11.6826,4.90708,7200,6963,0,0), +(@GUID+18,17398,542,3,314.478,195.642,11.6815,5.01966,7200,6963,0,0), +(@GUID+17,17381,542,3,327.17,137.816,9.61546,4.72121,43200,38722,0,0), +(@GUID+90,17370,542,3,372.443,187.252,9.59815,3.08144,7200,14958,0,2), +(@GUID+87,17491,542,3,301.987,172.031,9.61921,0.398146,7200,7479,0,0), +(@GUID+89,17370,542,3,372.443,191.252,9.59815,3.3214,7200,14958,0,2), +(@GUID+80,17626,542,3,343.075,57.8455,9.6156,0,7200,14958,0,0), +(@GUID+81,17624,542,3,327.255,54.8455,9.61645,0,7200,16023,0,2), +(@GUID+15,17414,542,3,352.426,85.7746,9.6222,6.27838,7200,10472,5875,0), +(@GUID+84,17414,542,3,346.54,96.449,9.6201,2.21792,7200,10472,5875,0), +(@GUID+16,17414,542,3,302.425,61.1739,9.61642,3.14962,7200,10472,5875,0), +(@GUID+79,17414,542,3,328.075,76.9842,9.61402,5.19851,7200,10472,5875,0), +(@GUID+133,17477,542,3,433.797,-90.9604,9.62448,1.93317,7200,4126,9944,0), +(@GUID+141,18894,542,3,355.299,-163.451,-25.5338,6.16881,7200,14958,0,0), +(@GUID+138,17477,542,3,423.255,-96.3954,9.61869,1.21688,7200,4126,9944,0), +(@GUID+66,17626,542,3,279.674,1.44232,8.11077,3.8723,7200,14958,0,0), +(@GUID+64,17626,542,3,250.468,-24.7817,6.95538,4.23202,7200,14958,0,0), +(@GUID+50,17397,542,3,29.672,-80.5135,-40.787,4.36738,7200,11965,2486,0), +(@GUID+44,17397,542,3,-12.9018,-81.3588,-41.3358,5.36252,7200,11965,2486,0), +(@GUID+47,17397,542,3,6.99569,-89.3037,-41.3305,1.28394,7200,11965,2486,0), +(@GUID+45,17397,542,3,-9.04048,-88.5931,-41.3341,1.99081,7200,11965,2486,0), +(@GUID+49,17477,542,3,8.90866,-85.0585,-41.3294,1.02944,7200,4126,9944,0), +(@GUID+48,17397,542,3,10.3856,-81.342,-41.3294,4.24882,7200,11965,2486,0), +(@GUID+9,17380,542,3,455.336,-1.82919,9.6299,1.43117,43200,30960,18468,0), +(@GUID+8,17370,542,3,7.83757,-54.6224,-41.258,1.62316,7200,14958,0,0), +(@GUID+7,17370,542,3,-4.06964,-56.7616,-41.258,1.41372,7200,14958,0,0), +(@GUID+6,17370,542,3,49.3209,-93.3478,-40.1855,2.86234,7200,14958,0,0), +(@GUID+5,17370,542,3,49.2232,-75.6242,-40.1856,2.98451,7200,14958,0,0), +(@GUID+4,17256,542,3,369.461,-118.757,-137.368,2.54818,604800,152964,1016100,0), +(@GUID+3,17256,542,3,369.15,-55.5658,-137.368,3.71755,604800,152964,1016100,0), +(@GUID+2,17256,542,3,307.784,-31.8502,-137.368,4.95674,604800,152964,1016100,0), +(@GUID+1,17256,542,3,274.133,-87.1647,-137.368,0.017453,604800,152964,1016100,0), +(@GUID+0,17256,542,3,308.203,-141.769,-137.368,1.36136,604800,152964,1016100,0); + +-- GAMEOBJECT_TEMPLATE +UPDATE `gameobject_template` SET `ScriptName`='go_broggok_lever' WHERE `entry`=181982; + +-- CREATURE_MODEL_INFO +-- Old modelid_other_gender 12471. Need to do this because modelid in creature uses creature_model_info, too... so it would still bug. +UPDATE `creature_model_info` SET `modelid_other_gender`=0 WHERE `modelid`=16332; + +-- CREATURE_ADDON +DELETE FROM `creature_addon` WHERE `guid` BETWEEN @GUID AND @GUID+144; +INSERT INTO `creature_addon`(`guid`,`path_id`,`bytes2`) VALUES +(@GUID+0,0,4097), +(@GUID+1,0,4097), +(@GUID+2,0,4097), +(@GUID+3,0,4097), +(@GUID+4,0,4097), +(@GUID+15,856820,0), +(@GUID+63,(@GUID+63)*10,0), +(@GUID+68,(@GUID+68)*10,0), +(@GUID+81,(@GUID+81)*10,0), +(@GUID+89,(@GUID+89)*10,0), +(@GUID+90,(@GUID+90)*10,0), +(@GUID+101,(@GUID+101)*10,0), +(@GUID+102,(@GUID+102)*10,0), +(@GUID+107,(@GUID+107)*10,0), +(@GUID+128,(@GUID+128)*10,0), +(@GUID+129,(@GUID+129)*10,0); + +-- CREATURE_FORMATIONS +DELETE FROM `creature_formations` WHERE `leaderGUID` BETWEEN @GUID AND @GUID+148 OR `memberGUID` BETWEEN @GUID AND @GUID+148; +INSERT INTO `creature_formations`(`leaderGUID`,`memberGUID`,`dist`,`angle`,`groupAI`) VALUES +(@GUID+81,@GUID+81,0,0,2), +(@GUID+81,@GUID+80,3,290,2), +(@GUID+107,@GUID+107,0,0,2), +(@GUID+107,@GUID+105,4,220,2), +(@GUID+107,@GUID+106,3,285,2), +(@GUID+129,@GUID+129,0,0,2), +(@GUID+129,@GUID+130,3,90,2), +(@GUID+143,@GUID+143,0,0,2), +(@GUID+143,@GUID+148,3,120,2), +(@GUID+143,@GUID+144,3,240,2), +(@GUID+146,@GUID+146,0,0,2), +(@GUID+146,@GUID+145,3,120,2), +(@GUID+146,@GUID+147,3,240,2), +(@GUID+128,@GUID+128,0,0,2), +(@GUID+128,@GUID+127,4,45,2); + +-- WAYPOINT_DATA +DELETE FROM `waypoint_data` WHERE `id` BETWEEN @GUID*10 AND (@GUID+148)*10; +INSERT INTO `waypoint_data`(`id`,`point`,`position_x`,`position_y`,`position_z`) VALUES +((@GUID+63 )*10,1,247.229,-66.59,9.62258), +((@GUID+63 )*10,2,246.245,-85.1909,9.61548), +((@GUID+63 )*10,3,219.765,-84.577,9.58612), +((@GUID+63 )*10,4,246.377,-85.311,9.61661), +((@GUID+68 )*10,1,328.417,-4.58593,9.61603), +((@GUID+68 )*10,2,327.28,24.0565,9.61603), +((@GUID+81 )*10,1,327.255,54.8455,9.61346), +((@GUID+81 )*10,18,322.72,55.3961,9.6137), +((@GUID+81 )*10,17,317.328,58.7127,9.6137), +((@GUID+81 )*10,16,315.042,62.5956,9.61509), +((@GUID+81 )*10,15,312.513,72.6059,9.6179), +((@GUID+81 )*10,14,311.755,83.2112,9.6179), +((@GUID+81 )*10,13,312.519,89.5342,9.6179), +((@GUID+81 )*10,12,313.959,93.8532,9.61756), +((@GUID+81 )*10,11,317.588,98.5635,9.61631), +((@GUID+81 )*10,10,322.28,101.14,9.61572), +((@GUID+81 )*10,9,328.8,102.991,9.61528), +((@GUID+81 )*10,8,334.164,102.162,9.61808), +((@GUID+81 )*10,7,339.203,99.0606,9.61948), +((@GUID+81 )*10,6,342.812,94.2829,9.61948), +((@GUID+81 )*10,5,345.611,85.8321,9.61948), +((@GUID+81 )*10,4,344.882,74.8707,9.61869), +((@GUID+81 )*10,3,343.069,64.3213,9.61614), +((@GUID+81 )*10,2,340.959,59.932,9.61435), +((@GUID+89 )*10,1,372.443,191.252,9.59815), +((@GUID+89 )*10,2,329.021,185.273,9.61524), +((@GUID+90 )*10,1,372.443,187.252,9.59815), +((@GUID+90 )*10,2,329.021,181.273,9.61524), +((@GUID+101)*10,1,416.026,191.714,9.59825), +((@GUID+101)*10,2,466.657,179.674,9.61915), +((@GUID+102)*10,1,415.314,187.668,9.59825), +((@GUID+102)*10,2,466.171,176.663,9.6201), +((@GUID+107)*10,18,464.47,117.962,9.62), +((@GUID+107)*10,17,471.688,113.794,9.62), +((@GUID+107)*10,16,477.046,107.409,9.62), +((@GUID+107)*10,15,479.897,99.5768,9.62), +((@GUID+107)*10,14,479.897,91.2417,9.62), +((@GUID+107)*10,13,477.046,83.4093,9.62), +((@GUID+107)*10,12,471.688,77.0242,9.62), +((@GUID+107)*10,11,464.47,72.8567,9.62), +((@GUID+107)*10,10,456.261,71.4093,9.62), +((@GUID+107)*10,9,448.053,72.8567,9.62), +((@GUID+107)*10,8,440.834,77.0242,9.62), +((@GUID+107)*10,7,435.477,83.4093,9.62), +((@GUID+107)*10,6,432.626,91.2417,9.62), +((@GUID+107)*10,5,432.626,99.5768,9.62), +((@GUID+107)*10,4,435.477,107.409,9.62), +((@GUID+107)*10,3,440.834,113.794,9.62), +((@GUID+107)*10,2,448.053,117.962,9.62), +((@GUID+107)*10,1,456.261,119.409,9.62), +((@GUID+128)*10,1,475.83,-58.5353,9.5419), +((@GUID+128)*10,2,474.83,-54.6723,9.5419), +((@GUID+128)*10,3,465.9,-19.9126,9.55319), +((@GUID+128)*10,4,466.89,-23.7756,9.55319), +((@GUID+129)*10,1,482.43,-67.1466,9.56), +((@GUID+129)*10,2,486.942,-69.7513,9.56), +((@GUID+129)*10,3,490.29,-73.742,9.56), +((@GUID+129)*10,4,492.072,-78.6373,9.56), +((@GUID+129)*10,5,492.072,-83.8467,9.56), +((@GUID+129)*10,6,490.29,-88.742,9.56), +((@GUID+129)*10,7,486.942,-92.7327,9.56), +((@GUID+129)*10,8,482.43,-95.3374,9.56), +((@GUID+129)*10,9,477.3,-96.242,9.56), +((@GUID+129)*10,10,472.17,-95.3374,9.56), +((@GUID+129)*10,11,467.658,-92.7327,9.56), +((@GUID+129)*10,12,464.31,-88.742,9.56), +((@GUID+129)*10,13,462.528,-83.8467,9.56), +((@GUID+129)*10,14,462.528,-78.6373,9.56), +((@GUID+129)*10,15,464.31,-73.742,9.56), +((@GUID+129)*10,16,467.658,-69.7513,9.56), +((@GUID+129)*10,17,472.17,-67.1466,9.56), +((@GUID+129)*10,18,477.3,-66.242,9.56); + +-- Revert a previous bad fix +DELETE FROM `creature_ai_scripts` WHERE `creature_id`=17398; +DELETE FROM `smart_scripts` WHERE `entryorguid` IN (-85712,-85717,-85719,-85724) AND `source_type`=0; +DELETE FROM `gameobject_scripts` WHERE `id`=150441; diff --git a/sql/updates/world/2012_08_30_00_world_creature_template.sql b/sql/updates/world/2012_08_30_00_world_creature_template.sql new file mode 100644 index 00000000000..27c1c1dedd4 --- /dev/null +++ b/sql/updates/world/2012_08_30_00_world_creature_template.sql @@ -0,0 +1 @@ +ALTER TABLE `creature_template` ADD `unit_flags2` int(10) UNSIGNED NOT NULL DEFAULT '0' AFTER `unit_flags`; diff --git a/sql/updates/world/2012_08_30_00_world_spell_script_names.sql b/sql/updates/world/2012_08_30_00_world_spell_script_names.sql new file mode 100644 index 00000000000..d7602dd8c79 --- /dev/null +++ b/sql/updates/world/2012_08_30_00_world_spell_script_names.sql @@ -0,0 +1,8 @@ +DELETE FROM `spell_script_names` WHERE `spell_id` IN (41054, 63418, 69893, 45205, 69896, 57594); +INSERT INTO `spell_script_names` VALUES +(41054, "spell_gen_clone_weapon_aura"), +(63418, "spell_gen_clone_weapon_aura"), +(69893, "spell_gen_clone_weapon_aura"), +(45205, "spell_gen_clone_weapon_aura"), +(69896, "spell_gen_clone_weapon_aura"), +(57594, "spell_gen_clone_weapon_aura"); diff --git a/sql/updates/world/2012_08_31_00_world_command.sql b/sql/updates/world/2012_08_31_00_world_command.sql new file mode 100644 index 00000000000..c0686d6d907 --- /dev/null +++ b/sql/updates/world/2012_08_31_00_world_command.sql @@ -0,0 +1,14 @@ +DELETE FROM `command` WHERE `name`='explorecheat'; +DELETE FROM `command` WHERE `name`='taxicheat'; +DELETE FROM `command` WHERE `name`='waterwalk'; + +DELETE FROM `command` WHERE `name`='cheat' OR `name` LIKE 'cheat%'; +INSERT INTO `command` (`name`, `security`, `help`) VALUES +('cheat', 2, 'Syntax: .cheat $subcommand\r\nType .cheat to see the list of possible subcommands or .help cheat $subcommand to see info on subcommands'), +('cheat god', 2, 'Syntax: .cheat god [on/off]\r\nEnables or disables your character''s ability to take damage.'), +('cheat casttime', 2, 'Syntax: .cheat casttime [on/off]\r\nEnables or disables your character''s spell cast times.'), +('cheat cooldown', 2, 'Syntax: .cheat cooldown [on/off]\r\nEnables or disables your character''s spell cooldowns.'), +('cheat power', 2, 'Syntax: .cheat power [on/off]\r\nEnables or disables your character''s spell cost (e.g mana).'), +('cheat waterwalk', 2, 'Syntax: .cheat waterwalk on/off\r\nSet on/off waterwalk state for selected player or self if no player selected.'), +('cheat explore', 2, 'Syntax: .cheat explore #flag\r\nReveal or hide all maps for the selected player. If no player is selected, hide or reveal maps to you.\r\nUse a #flag of value 1 to reveal, use a #flag value of 0 to hide all maps.'), +('cheat taxi', 2, 'Syntax: .cheat taxi on/off\r\nTemporary grant access or remove to all taxi routes for the selected character.\r\n If no character is selected, hide or reveal all routes to you.Visited taxi nodes sill accessible after removing access.'); diff --git a/sql/updates/world/2012_08_31_00_world_sai.sql b/sql/updates/world/2012_08_31_00_world_sai.sql new file mode 100644 index 00000000000..fd7e0d7810f --- /dev/null +++ b/sql/updates/world/2012_08_31_00_world_sai.sql @@ -0,0 +1,50 @@ +-- Defending Your Title (13423) +-- Taking on All Challengers (12971) + +SET @NPC_CHALLENGER := 30012; -- Victorious Challenger +SET @QUEST1 := 12971; +SET @QUEST2 := 13423; +SET @GOSSIP_MENUID := 9865; +SET @SPELL_SUNDER := 11971; -- Sunder Armor +SET @SPELL_REND := 11977; -- Rend + +UPDATE `creature_template` SET `faction_A`=2109,`faction_H`=2109,`unit_flags`=0x8000,`npcflag`=0x1,`gossip_menu_id`=@GOSSIP_MENUID,`AIName`='SmartAI',`ScriptName`='' WHERE `entry`=@NPC_CHALLENGER; + +DELETE FROM `creature_template_addon` WHERE `entry`=@NPC_CHALLENGER; +INSERT INTO `creature_template_addon` (`entry`,`mount`,`bytes1`,`bytes2`,`auras`) VALUES +(@NPC_CHALLENGER,0,0x0,0x1,''); + +DELETE FROM `creature_text` WHERE `entry`=@NPC_CHALLENGER; +INSERT INTO `creature_text` (`entry`,`groupid`,`id`,`text`,`type`,`language`,`probability`,`emote`,`duration`,`sound`,`comment`) VALUES +(@NPC_CHALLENGER,0,0,'You will not defeat me!',12,0,100,0,0,0,'Victorious Challenger'), +(@NPC_CHALLENGER,0,1,'You''re not worthy of Thorim!',12,0,100,0,0,0,'Victorious Challenger'), +(@NPC_CHALLENGER,0,2,'Good luck... You''ll need it!',12,0,100,0,0,0,'Victorious Challenger'), +(@NPC_CHALLENGER,0,3,'May the best win!',12,0,100,0,0,0,'Victorious Challenger'); + +DELETE FROM `gossip_menu` WHERE `entry`=@GOSSIP_MENUID; +INSERT INTO `gossip_menu` (`entry`,`text_id`) VALUES +(@GOSSIP_MENUID,13660); + +DELETE FROM `gossip_menu_option` WHERE `menu_id`=@GOSSIP_MENUID; +INSERT INTO `gossip_menu_option` (`menu_id`,`id`,`option_icon`,`option_text`,`option_id`,`npc_option_npcflag`,`action_menu_id`,`action_poi_id`,`box_coded`,`box_money`,`box_text`) VALUES +(@GOSSIP_MENUID,0,0,'Let''s do this, sister.',1,1,0,0,0,0,''); + +DELETE FROM `creature_equip_template` WHERE `entry`=@NPC_CHALLENGER; +INSERT INTO `creature_equip_template` (`entry`,`itemEntry1`,`itemEntry2`,`itemEntry3`) VALUES +(@NPC_CHALLENGER,40542,39288,0); + +DELETE FROM `smart_scripts` WHERE (`source_type`=0 AND `entryorguid`=@NPC_CHALLENGER) OR (`source_type`=9 AND `entryorguid`=@NPC_CHALLENGER*100); +INSERT INTO `smart_scripts` (`entryorguid`,`source_type`,`id`,`link`,`event_type`,`event_phase_mask`,`event_chance`,`event_flags`,`event_param1`,`event_param2`,`event_param3`,`event_param4`,`action_type`,`action_param1`,`action_param2`,`action_param3`,`action_param4`,`action_param5`,`action_param6`,`target_type`,`target_param1`,`target_param2`,`target_param3`,`target_x`,`target_y`,`target_z`,`target_o`,`comment`) VALUES +(@NPC_CHALLENGER,0,0,0,25,0,100,0,0,0,0,0,2,0,0,0,0,0,0,1,0,0,0,0,0,0,0,'Victorious Challenger - On Reset - Set Default Faction'), +(@NPC_CHALLENGER,0,1,2,62,0,100,0,@GOSSIP_MENUID,0,0,0,72,0,0,0,0,0,0,7,0,0,0,0,0,0,0,'Victorious Challenger - On Gossip - Close Gossip'), +(@NPC_CHALLENGER,0,2,0,61,0,100,0,0,0,0,0,80,@NPC_CHALLENGER*100,0,0,0,0,0,1,0,0,0,0,0,0,0,'Victorious Challenger - On Gossip - Run Timed Script'), +(@NPC_CHALLENGER,0,3,0,9,0,100,0,0,5,5000,10000,11,@SPELL_SUNDER,0,0,0,0,0,2,0,0,0,0,0,0,0,'Victorious Challenger - On Range - Cast Sunder Armor'), +(@NPC_CHALLENGER,0,4,0,0,0,100,0,10000,15000,15000,20000,11,@SPELL_REND,0,0,0,0,0,2,0,0,0,0,0,0,0,'Victorious Challenger - IC - Cast Rend'), +(@NPC_CHALLENGER*100,9,0,0,0,0,100,0,1000,1000,1000,1000,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,'Victorious Challenger - Timed - Talk'), +(@NPC_CHALLENGER*100,9,1,0,0,0,100,0,3000,3000,3000,3000,2,14,0,0,0,0,0,1,0,0,0,0,0,0,0,'Victorious Challenger - Timed - Set Faction Hostile'), +(@NPC_CHALLENGER*100,9,2,0,0,0,100,0,0,0,0,0,49,0,0,0,0,0,0,7,0,0,0,0,0,0,0,'Victorious Challenger - Timed - Attack Invoker'); + +DELETE FROM `conditions` WHERE `SourceTypeOrReferenceId`=15 AND `SourceGroup`=@GOSSIP_MENUID; +INSERT INTO `conditions` (`SourceTypeOrReferenceId`,`SourceGroup`,`SourceEntry`,`SourceId`,`ElseGroup`,`ConditionTypeOrReference`,`ConditionTarget`,`ConditionValue1`,`ConditionValue2`,`ConditionValue3`,`NegativeCondition`,`ErrorTextId`,`ScriptName`,`Comment`) VALUES +(15,@GOSSIP_MENUID,0,0,0,9,0,@QUEST1,0,0,0,0,'','Show gossip option 0 if player has quest Taking on All Challengers'), +(15,@GOSSIP_MENUID,0,0,1,9,0,@QUEST2,0,0,0,0,'','Show gossip option 0 if player has quest Defending Your Title'); diff --git a/sql/updates/world/2012_09_01_00_world_spell_script_names.sql b/sql/updates/world/2012_09_01_00_world_spell_script_names.sql new file mode 100644 index 00000000000..add7621b74c --- /dev/null +++ b/sql/updates/world/2012_09_01_00_world_spell_script_names.sql @@ -0,0 +1,4 @@ +-- Unlocking zuluhed chains +DELETE FROM `spell_script_names` WHERE `spell_id`=38790; +INSERT INTO `spell_script_names` (`spell_id`, `ScriptName`) VALUES +(38790, 'spell_unlocking_zuluheds_chains'); diff --git a/sql/updates/world/2012_09_02_00_world_quest_template.sql b/sql/updates/world/2012_09_02_00_world_quest_template.sql new file mode 100644 index 00000000000..d7e3948ef4f --- /dev/null +++ b/sql/updates/world/2012_09_02_00_world_quest_template.sql @@ -0,0 +1,49 @@ +-- Kandrostrasz <Brood of Alexstrasza> (15503) quests RequiredClasses fix by nelegalno +UPDATE `quest_template` SET `RequiredClasses` = 1 WHERE `Id` IN (8559,8560); -- Warrior +UPDATE `quest_template` SET `RequiredClasses` = 2 WHERE `Id` IN (8629,8655); -- Paladin +UPDATE `quest_template` SET `RequiredClasses` = 4 WHERE `Id` IN (8626,8658); -- Hunter +UPDATE `quest_template` SET `RequiredClasses` = 8 WHERE `Id` IN (8637,8640); -- Rogue +UPDATE `quest_template` SET `RequiredClasses` = 16 WHERE `Id` IN (8593,8596); -- Priest +UPDATE `quest_template` SET `RequiredClasses` = 64 WHERE `Id` IN (8621,8624); -- Shaman +UPDATE `quest_template` SET `RequiredClasses` = 128 WHERE `Id` IN (8631,8634); -- Mage +UPDATE `quest_template` SET `RequiredClasses` = 256 WHERE `Id` IN (8660,8663); -- Warlock +UPDATE `quest_template` SET `RequiredClasses` = 1024 WHERE `Id` IN (8665,8668); -- Druid + +-- Andorgos <Brood of Malygos> (15502) quests RequiredClasses fix by nelegalno +UPDATE `quest_template` SET `RequiredClasses` = 1 WHERE `Id` IN (8544,8561); -- Warrior +UPDATE `quest_template` SET `RequiredClasses` = 2 WHERE `Id` IN (8628,8630); -- Paladin +UPDATE `quest_template` SET `RequiredClasses` = 4 WHERE `Id` IN (8657,8659); -- Hunter +UPDATE `quest_template` SET `RequiredClasses` = 8 WHERE `Id` IN (8639,8641); -- Rogue +UPDATE `quest_template` SET `RequiredClasses` = 16 WHERE `Id` IN (8592,8594); -- Priest +UPDATE `quest_template` SET `RequiredClasses` = 64 WHERE `Id` IN (8602,8623); -- Shaman +UPDATE `quest_template` SET `RequiredClasses` = 128 WHERE `Id` IN (8625,8632); -- Mage +UPDATE `quest_template` SET `RequiredClasses` = 256 WHERE `Id` IN (8662,8664); -- Warlock +UPDATE `quest_template` SET `RequiredClasses` = 1024 WHERE `Id` IN (8667,8669); -- Druid + +-- Craftsman Wilhelm <Brotherhood of the Light> (16376) NPCs quests +UPDATE `quest_template` SET `RequiredClasses` = 3 WHERE `Id` IN (9234,9235,9236); -- Warrior, Paladin +UPDATE `quest_template` SET `RequiredClasses` = 68 WHERE `Id` IN (9244,9245,9246); -- Hunter, Shaman +UPDATE `quest_template` SET `RequiredClasses` = 400 WHERE `Id` IN (9238,9239,9240); -- Priest, Mage, Warlock +UPDATE `quest_template` SET `RequiredClasses` = 1032 WHERE `Id` IN (9241,9242,9243); -- Rogue, Druid + +-- Zanza the Restless (15042) NPCs quests +UPDATE `quest_template` SET `RequiredClasses` = 1 WHERE `Id` = 8184; -- Warrior +UPDATE `quest_template` SET `RequiredClasses` = 2 WHERE `Id` = 8185; -- Paladin +UPDATE `quest_template` SET `RequiredClasses` = 4 WHERE `Id` = 8187; -- Hunter +UPDATE `quest_template` SET `RequiredClasses` = 8 WHERE `Id` = 8186; -- Rogue +UPDATE `quest_template` SET `RequiredClasses` = 16 WHERE `Id` = 8191; -- Priest +UPDATE `quest_template` SET `RequiredClasses` = 64 WHERE `Id` = 8188; -- Shaman +UPDATE `quest_template` SET `RequiredClasses` = 128 WHERE `Id` = 8189; -- Mage +UPDATE `quest_template` SET `RequiredClasses` = 256 WHERE `Id` = 8190; -- Warlock +UPDATE `quest_template` SET `RequiredClasses` = 1024 WHERE `Id` = 8192; -- Druid + +-- Vethsera <Brood of Ysera> (15504) quests RequiredClasses fix by nelegalno +UPDATE `quest_template` SET `RequiredClasses` = 1 WHERE `Id` = 8562; -- Warrior +UPDATE `quest_template` SET `RequiredClasses` = 2 WHERE `Id` = 8627; -- Paladin +UPDATE `quest_template` SET `RequiredClasses` = 4 WHERE `Id` = 8656; -- Hunter +UPDATE `quest_template` SET `RequiredClasses` = 8 WHERE `Id` = 8638; -- Rogue +UPDATE `quest_template` SET `RequiredClasses` = 16 WHERE `Id` = 8603; -- Priest +UPDATE `quest_template` SET `RequiredClasses` = 64 WHERE `Id` = 8622; -- Shaman +UPDATE `quest_template` SET `RequiredClasses` = 128 WHERE `Id` = 8633; -- Mage +UPDATE `quest_template` SET `RequiredClasses` = 256 WHERE `Id` = 8661; -- Warlock +UPDATE `quest_template` SET `RequiredClasses` = 1024 WHERE `Id` = 8666; -- Druid diff --git a/sql/updates/world/2012_09_02_01_world_sai.sql b/sql/updates/world/2012_09_02_01_world_sai.sql new file mode 100644 index 00000000000..971c50d9c05 --- /dev/null +++ b/sql/updates/world/2012_09_02_01_world_sai.sql @@ -0,0 +1,36 @@ +-- Lok'lira the Crone +SET @ENTRY := 29975; +UPDATE `creature_template` SET `AIName`='SmartAI', `ScriptName`='' WHERE `entry`=@ENTRY; +DELETE FROM `smart_scripts` WHERE `entryorguid`=@ENTRY AND `source_type`=0; +INSERT INTO `smart_scripts` (`entryorguid`,`source_type`,`id`,`link`,`event_type`,`event_phase_mask`,`event_chance`,`event_flags`,`event_param1`,`event_param2`,`event_param3`,`event_param4`,`action_type`,`action_param1`,`action_param2`,`action_param3`,`action_param4`,`action_param5`,`action_param6`,`target_type`,`target_param1`,`target_param2`,`target_param3`,`target_x`,`target_y`,`target_z`,`target_o`,`comment`) VALUES +(@ENTRY,0,0,1,62,0,100,0,9910,0,0,0,33,30467,0,0,0,0,0,7,0,0,0,0,0,0,0,'Loklira - gossip select 4 - The Hyldsmeet Kill credit'), +(@ENTRY,0,1,0,61,0,100,0,0,0,0,0,72,0,0,0,0,0,0,7,0,0,0,0,0,0,0,'Loklira - gossip select 4 - Close gossip'); + +UPDATE `gossip_menu_option` SET `action_menu_id`=9908 WHERE `menu_id`=9907; +UPDATE `gossip_menu_option` SET `action_menu_id`=9909 WHERE `menu_id`=9908; +UPDATE `gossip_menu_option` SET `action_menu_id`=9910 WHERE `menu_id`=9909; + +DELETE FROM `conditions` WHERE `SourceTypeOrReferenceId`=15 AND `SourceGroup`=9907; +INSERT INTO `conditions` (`SourceTypeOrReferenceId`,`SourceGroup`,`SourceEntry`,`ElseGroup`,`ConditionTypeOrReference`,`ConditionValue1`,`ConditionValue2`,`ConditionValue3`,`ErrorTextId`,`ScriptName`,`Comment`) VALUES +(15,9907,0,0,9,12970,0,0,0,'','Loklira - Show gossip if quest accepted'); + +-- Thorim +SET @THORIM :=29445; +UPDATE `creature` SET `modelid`=0 WHERE `id`=@THORIM; +UPDATE `creature_template` SET `AIName`='SmartAI', `ScriptName`='' WHERE `entry`=@THORIM; +DELETE FROM `creature_addon` WHERE `guid`=97128; +DELETE FROM `creature_template_addon` WHERE `entry`=@THORIM; +INSERT INTO `creature_template_addon` (`entry`,`path_id`,`mount`,`bytes1`,`bytes2`,`emote`,`auras`) VALUES +(@THORIM,0,0,1,0,0,''); + +DELETE FROM `smart_scripts` WHERE `entryorguid`=@THORIM AND `source_type`=0; +INSERT INTO `smart_scripts` (`entryorguid`,`source_type`,`id`,`link`,`event_type`,`event_phase_mask`,`event_chance`,`event_flags`,`event_param1`,`event_param2`,`event_param3`,`event_param4`,`action_type`,`action_param1`,`action_param2`,`action_param3`,`action_param4`,`action_param5`,`action_param6`,`target_type`,`target_param1`,`target_param2`,`target_param3`,`target_x`,`target_y`,`target_z`,`target_o`,`comment`) VALUES +(@THORIM,0,0,0,62,0,100,0,9926,0,0,0,33,30514,0,0,0,0,0,7,0,0,0,0,0,0,0,'Thorim - gossip select - give quest credit'); + +UPDATE `gossip_menu_option` SET `action_menu_id`=9927 WHERE `menu_id`=9924; +UPDATE `gossip_menu_option` SET `action_menu_id`=9926 WHERE `menu_id`=9927; +UPDATE `gossip_menu_option` SET `action_menu_id`=9925 WHERE `menu_id`=9926; + +DELETE FROM `conditions` WHERE `SourceTypeOrReferenceId`=15 AND `SourceGroup`=9924; +INSERT INTO `conditions` (`SourceTypeOrReferenceId`,`SourceGroup`,`SourceEntry`,`ElseGroup`,`ConditionTypeOrReference`,`ConditionValue1`,`ConditionValue2`,`ConditionValue3`,`ErrorTextId`,`ScriptName`,`Comment`) VALUES +(15,9924,0,0,9,13064,0,0,0,'','Thorim - Show gossip if quest accepted'); diff --git a/sql/updates/world/2012_09_03_00_world_misc.sql b/sql/updates/world/2012_09_03_00_world_misc.sql new file mode 100644 index 00000000000..e8910c78b40 --- /dev/null +++ b/sql/updates/world/2012_09_03_00_world_misc.sql @@ -0,0 +1,36 @@ +-- Cold Hearted (12856) + +SET @NPC_CAPTIVE_DRAKE := 29708; -- Captive Proto-Drake +SET @NPC_FREED_DRAKE := 29709; -- Freed Proto-Drake +SET @NPC_PRISONER := 29639; -- Brunnhildar Prisoner +SET @NPC_LIBERATED := 29734; -- Liberated Brunnhildar + +SET @SPELL_SUM_FREE_DRAKE := 55028; -- Summon Freed Proto-Drake +SET @SPELL_ICE_SHARD := 55046; -- Ice Shard (Rank 3) +SET @SPELL_FREE_PRISONER := 55048; -- Free Brunnhildar Prisoner +SET @AURA_IMPRISONMENT := 54894; -- Icy Imprisonment + + +UPDATE `creature_template` SET `speed_walk`=1,`speed_run`=1.14286,`spell1`=@SPELL_ICE_SHARD,`HoverHeight`=4,`unit_flags`=0x1000008,`InhabitType`=4,`ScriptName`='npc_freed_protodrake' WHERE `entry`=@NPC_FREED_DRAKE; +UPDATE `creature_template` SET `unit_flags`=33554432,`AIName`='SmartAI' WHERE `entry`=@NPC_LIBERATED; + +DELETE FROM `npc_spellclick_spells` WHERE `npc_entry`=@NPC_CAPTIVE_DRAKE; +INSERT INTO `npc_spellclick_spells` (`npc_entry`,`spell_id`,`cast_flags`,`user_type`) VALUES +(@NPC_CAPTIVE_DRAKE,@SPELL_SUM_FREE_DRAKE,1,0); + +DELETE FROM `creature_template_addon` WHERE `entry`=@NPC_FREED_DRAKE; +INSERT INTO `creature_template_addon` (`entry`,`mount`,`bytes1`,`bytes2`,`auras`) VALUES +(@NPC_FREED_DRAKE,0,0x3000000,0x1,'55034 61183'); + +DELETE FROM `creature_text` WHERE `entry`=@NPC_FREED_DRAKE; +INSERT INTO `creature_text` (`entry`,`groupid`,`id`,`text`,`type`,`language`,`probability`,`emote`,`duration`,`sound`,`comment`) VALUES +(@NPC_FREED_DRAKE,0,0,'Return to Brunnhildar Village!',42,0,100,0,0,0,'Freed Proto-Drake'), +(@NPC_FREED_DRAKE,0,1,'The proto-drake smells freedom and flies homeward!',41,0,100,0,0,0,'Freed Proto-Drake'); + +DELETE FROM `spell_scripts` WHERE `id`=@SPELL_FREE_PRISONER; +INSERT INTO `spell_scripts` (`id`,`effIndex`,`delay`,`command`,`datalong`,`datalong2`,`dataint`,`x`,`y`,`z`,`o`) VALUES +(@SPELL_FREE_PRISONER,0,0,14,@AURA_IMPRISONMENT,0,0,0,0,0,0); + +DELETE FROM `smart_scripts` WHERE `source_type`=0 AND `entryorguid`=@NPC_LIBERATED; +INSERT INTO `smart_scripts` (`entryorguid`,`source_type`,`id`,`link`,`event_type`,`event_phase_mask`,`event_chance`,`event_flags`,`event_param1`,`event_param2`,`event_param3`,`event_param4`,`action_type`,`action_param1`,`action_param2`,`action_param3`,`action_param4`,`action_param5`,`action_param6`,`target_type`,`target_param1`,`target_param2`,`target_param3`,`target_x`,`target_y`,`target_z`,`target_o`,`comment`) VALUES +(@NPC_LIBERATED,0,0,0,54,0,100,0,0,0,0,0,41,30000,0,0,0,0,0,1,0,0,0,0,0,0,0,'Liberated Brunnhildar - On Spawn - Despawn in 30 seconds'); diff --git a/src/server/authserver/Authentication/AuthCodes.cpp b/src/server/authserver/Authentication/AuthCodes.cpp index 7a97cbee3de..bdb96ca0d25 100644 --- a/src/server/authserver/Authentication/AuthCodes.cpp +++ b/src/server/authserver/Authentication/AuthCodes.cpp @@ -16,17 +16,65 @@ */ #include "AuthCodes.h" +#include <cstddef> namespace AuthHelper { - bool IsAcceptedClientBuild(int build) + static RealmBuildInfo const PostBcAcceptedClientBuilds[] = + { + {15595, 4, 3, 4, ' '}, + {14545, 4, 2, 2, ' '}, + {13623, 4, 0, 6, 'a'}, + {12340, 3, 3, 5, 'a'}, + {11723, 3, 3, 3, 'a'}, + {11403, 3, 3, 2, ' '}, + {11159, 3, 3, 0, 'a'}, + {10505, 3, 2, 2, 'a'}, + {9947, 3, 1, 3, ' '}, + {8606, 2, 4, 3, ' '}, + {0, 0, 0, 0, ' '} // terminator + }; + + static RealmBuildInfo const PreBcAcceptedClientBuilds[] = + { + {6005, 1, 12, 2, ' '}, + {5875, 1, 12, 1, ' '}, + {0, 0, 0, 0, ' '} // terminator + }; + + bool IsPreBCAcceptedClientBuild(int build) { - static int accepted_versions[] = TRINITYCORE_ACCEPTED_CLIENT_BUILD; + for (int i = 0; PreBcAcceptedClientBuilds[i].Build; ++i) + if (PreBcAcceptedClientBuilds[i].Build == build) + return true; - for (int i = 0; accepted_versions[i]; ++i) - if (build == accepted_versions[i]) + return false; + } + + bool IsPostBCAcceptedClientBuild(int build) + { + for (int i = 0; PostBcAcceptedClientBuilds[i].Build; ++i) + if (PostBcAcceptedClientBuilds[i].Build == build) return true; return false; } + + bool IsAcceptedClientBuild(int build) + { + return (IsPostBCAcceptedClientBuild(build) || IsPreBCAcceptedClientBuild(build)); + } + + RealmBuildInfo const* GetBuildInfo(int build) + { + for (int i = 0; PostBcAcceptedClientBuilds[i].Build; ++i) + if (PostBcAcceptedClientBuilds[i].Build == build) + return &PostBcAcceptedClientBuilds[i]; + + for (int i = 0; PreBcAcceptedClientBuilds[i].Build; ++i) + if (PreBcAcceptedClientBuilds[i].Build == build) + return &PreBcAcceptedClientBuilds[i]; + + return NULL; + } }; diff --git a/src/server/authserver/Authentication/AuthCodes.h b/src/server/authserver/Authentication/AuthCodes.h index 9d631a5800d..148225377ff 100755 --- a/src/server/authserver/Authentication/AuthCodes.h +++ b/src/server/authserver/Authentication/AuthCodes.h @@ -65,12 +65,28 @@ enum LoginResult LOGIN_LOCKED_ENFORCED = 0x10, }; -#define TRINITYCORE_ACCEPTED_CLIENT_BUILD {15595, 12340, 0} // accept one Cataclysm and one Wrath of the Lich King build +enum ExpansionFlags +{ + POST_BC_EXP_FLAG = 0x2, + PRE_BC_EXP_FLAG = 0x1, + NO_VALID_EXP_FLAG = 0x0 +}; +struct RealmBuildInfo +{ + int Build; + int MajorVersion; + int MinorVersion; + int BugfixVersion; + int HotfixVersion; +}; namespace AuthHelper { + RealmBuildInfo const* GetBuildInfo(int build); bool IsAcceptedClientBuild(int build); + bool IsPostBCAcceptedClientBuild(int build); + bool IsPreBCAcceptedClientBuild(int build); }; #endif diff --git a/src/server/authserver/Main.cpp b/src/server/authserver/Main.cpp index b938706a0be..ed0fa9ab06a 100755 --- a/src/server/authserver/Main.cpp +++ b/src/server/authserver/Main.cpp @@ -80,7 +80,7 @@ extern int main(int argc, char **argv) { if (++c >= argc) { - sLog->outError(LOG_FILTER_AUTHSERVER, "Runtime-Error: -c option requires an input argument"); + printf("Runtime-Error: -c option requires an input argument"); usage(argv[0]); return 1; } @@ -92,8 +92,8 @@ extern int main(int argc, char **argv) if (!ConfigMgr::Load(cfg_file)) { - sLog->outError(LOG_FILTER_AUTHSERVER, "Invalid or missing configuration file : %s", cfg_file); - sLog->outError(LOG_FILTER_AUTHSERVER, "Verify that the file exists and has \'[authserver]\' written in the top of the file!"); + printf("Invalid or missing configuration file : %s", cfg_file); + printf("Verify that the file exists and has \'[authserver]\' written in the top of the file!"); return 1; } diff --git a/src/server/authserver/Server/AuthSocket.cpp b/src/server/authserver/Server/AuthSocket.cpp index c0cf24efbfb..d55d2cf02b3 100644 --- a/src/server/authserver/Server/AuthSocket.cpp +++ b/src/server/authserver/Server/AuthSocket.cpp @@ -196,7 +196,7 @@ const AuthHandler table[] = Patcher PatchesCache; // Constructor - set the N and g values for SRP6 -AuthSocket::AuthSocket(RealmSocket& socket) : socket_(socket) +AuthSocket::AuthSocket(RealmSocket& socket) : socket_(socket), pPatch(NULL) { N.SetHexStr("894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7"); g.SetDword(7); @@ -343,6 +343,7 @@ bool AuthSocket::_HandleLogonChallenge() _login = (const char*)ch->I; _build = ch->build; + _expversion = uint8(AuthHelper::IsPostBCAcceptedClientBuild(_build) ? POST_BC_EXP_FLAG : (AuthHelper::IsPreBCAcceptedClientBuild(_build) ? PRE_BC_EXP_FLAG : NO_VALID_EXP_FLAG)); _os = (const char*)ch->os; if (_os.size() > 4) @@ -357,13 +358,13 @@ bool AuthSocket::_HandleLogonChallenge() // Verify that this IP is not in the ip_banned table LoginDatabase.Execute(LoginDatabase.GetPreparedStatement(LOGIN_DEL_EXPIRED_IP_BANS)); - const std::string& ip_address = socket().getRemoteAddress(); - PreparedStatement *stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_IP_BANNED); + std::string const& ip_address = socket().getRemoteAddress(); + PreparedStatement* stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_IP_BANNED); stmt->setString(0, ip_address); PreparedQueryResult result = LoginDatabase.Query(stmt); if (result) { - pkt << (uint8)WOW_FAIL_BANNED; + pkt << uint8(WOW_FAIL_BANNED); sLog->outDebug(LOG_FILTER_AUTHSERVER, "'%s:%d' [AuthChallenge] Banned ip tries to login!",socket().getRemoteAddress().c_str(), socket().getRemotePort()); } else @@ -388,7 +389,7 @@ bool AuthSocket::_HandleLogonChallenge() if (strcmp(fields[3].GetCString(), ip_address.c_str())) { sLog->outDebug(LOG_FILTER_AUTHSERVER, "[AuthChallenge] Account IP differs"); - pkt << uint8(WOW_FAIL_SUSPENDED); + pkt << (uint8) WOW_FAIL_SUSPENDED; locked = true; } else @@ -410,12 +411,12 @@ bool AuthSocket::_HandleLogonChallenge() { if ((*banresult)[0].GetUInt64() == (*banresult)[1].GetUInt64()) { - pkt << (uint8)WOW_FAIL_BANNED; + pkt << uint8(WOW_FAIL_BANNED); sLog->outDebug(LOG_FILTER_AUTHSERVER, "'%s:%d' [AuthChallenge] Banned account %s tried to login!", socket().getRemoteAddress().c_str(), socket().getRemotePort(), _login.c_str ()); } else { - pkt << (uint8)WOW_FAIL_SUSPENDED; + pkt << uint8(WOW_FAIL_SUSPENDED); sLog->outDebug(LOG_FILTER_AUTHSERVER, "'%s:%d' [AuthChallenge] Temporarily banned account %s tried to login!", socket().getRemoteAddress().c_str(), socket().getRemotePort(), _login.c_str ()); } } @@ -449,11 +450,10 @@ bool AuthSocket::_HandleLogonChallenge() unk3.SetRand(16 * 8); // Fill the response packet with the result - // If the client has no valid version - if (!AuthHelper::IsAcceptedClientBuild(_build)) - pkt << uint8(WOW_FAIL_VERSION_INVALID); - else + if (AuthHelper::IsAcceptedClientBuild(_build)) pkt << uint8(WOW_SUCCESS); + else + pkt << uint8(WOW_FAIL_VERSION_INVALID); // B may be calculated < 32B so we force minimal length to 32B pkt.append(B.AsByteArray(32), 32); // 32 bytes @@ -498,7 +498,7 @@ bool AuthSocket::_HandleLogonChallenge() } } else //no account - pkt << uint8(WOW_FAIL_UNKNOWN_ACCOUNT); + pkt << (uint8)WOW_FAIL_UNKNOWN_ACCOUNT; } socket().send((char const*)pkt.contents(), pkt.size()); @@ -515,6 +515,15 @@ bool AuthSocket::_HandleLogonProof() if (!socket().recv((char *)&lp, sizeof(sAuthLogonProof_C))) return false; + // If the client has no valid version + if (_expversion == NO_VALID_EXP_FLAG) + { + // Check if we have the appropriate patch on the disk + sLog->outDebug(LOG_FILTER_NETWORKIO, "Client with invalid version, patching is not implemented"); + socket().shutdown(); + return true; + } + // Continue the SRP6 calculation based on data received from the client BigNumber A; @@ -615,14 +624,26 @@ bool AuthSocket::_HandleLogonProof() sha.UpdateBigNumbers(&A, &M, &K, NULL); sha.Finalize(); - sAuthLogonProof_S proof; - memcpy(proof.M2, sha.GetDigest(), 20); - proof.cmd = AUTH_LOGON_PROOF; - proof.error = 0; - proof.unk1 = 0x00800000; // Accountflags. 0x01 = GM, 0x08 = Trial, 0x00800000 = Pro pass (arena tournament) - proof.unk2 = 0x00; // SurveyId - proof.unk3 = 0x00; - socket().send((char *)&proof, sizeof(proof)); + if (_expversion & POST_BC_EXP_FLAG) // 2.x and 3.x clients + { + sAuthLogonProof_S proof; + memcpy(proof.M2, sha.GetDigest(), 20); + proof.cmd = AUTH_LOGON_PROOF; + proof.error = 0; + proof.unk1 = 0x00800000; // Accountflags. 0x01 = GM, 0x08 = Trial, 0x00800000 = Pro pass (arena tournament) + proof.unk2 = 0x00; // SurveyId + proof.unk3 = 0x00; + socket().send((char *)&proof, sizeof(proof)); + } + else + { + sAuthLogonProof_S_Old proof; + memcpy(proof.M2, sha.GetDigest(), 20); + proof.cmd = AUTH_LOGON_PROOF; + proof.error = 0; + proof.unk2 = 0x00; + socket().send((char *)&proof, sizeof(proof)); + } _authed = true; } @@ -731,6 +752,7 @@ bool AuthSocket::_HandleReconnectChallenge() // Reinitialize build, expansion and the account securitylevel _build = ch->build; + _expversion = uint8(AuthHelper::IsPostBCAcceptedClientBuild(_build) ? POST_BC_EXP_FLAG : (AuthHelper::IsPreBCAcceptedClientBuild(_build) ? PRE_BC_EXP_FLAG : NO_VALID_EXP_FLAG)); _os = (const char*)ch->os; if (_os.size() > 4) @@ -830,57 +852,87 @@ bool AuthSocket::_HandleRealmList() for (RealmList::RealmMap::const_iterator i = sRealmList->begin(); i != sRealmList->end(); ++i) { // don't work with realms which not compatible with the client - if (i->second.gamebuild != _build) - continue; - - uint8 AmountOfCharacters; + bool okBuild = ((_expversion & POST_BC_EXP_FLAG) && i->second.gamebuild == _build) || ((_expversion & PRE_BC_EXP_FLAG) && !AuthHelper::IsPreBCAcceptedClientBuild(i->second.gamebuild)); // No SQL injection. id of realm is controlled by the database. + uint32 flag = i->second.flag; + RealmBuildInfo const* buildInfo = AuthHelper::GetBuildInfo(i->second.gamebuild); + if (!okBuild) + { + if (!buildInfo) + continue; + + flag |= REALM_FLAG_OFFLINE | REALM_FLAG_SPECIFYBUILD; // tell the client what build the realm is for + } + + if (!buildInfo) + flag &= ~REALM_FLAG_SPECIFYBUILD; + + std::string name = i->first; + if (_expversion & PRE_BC_EXP_FLAG && flag & REALM_FLAG_SPECIFYBUILD) + { + std::ostringstream ss; + ss << name << " (" << buildInfo->MajorVersion << '.' << buildInfo->MinorVersion << '.' << buildInfo->BugfixVersion << ')'; + name = ss.str(); + } + + uint8 lock = (i->second.allowedSecurityLevel > _accountSecurityLevel) ? 1 : 0; + + uint8 AmountOfCharacters = 0; stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_NUM_CHARS_ON_REALM); stmt->setUInt32(0, i->second.m_ID); stmt->setUInt32(1, id); result = LoginDatabase.Query(stmt); if (result) AmountOfCharacters = (*result)[0].GetUInt8(); - else - AmountOfCharacters = 0; - - uint8 lock = (i->second.allowedSecurityLevel > _accountSecurityLevel) ? 1 : 0; pkt << i->second.icon; // realm type - pkt << lock; // if 1, then realm locked - pkt << uint8(i->second.flag); // RealmFlags - pkt << i->first; + if (_expversion & POST_BC_EXP_FLAG) // only 2.x and 3.x clients + pkt << lock; // if 1, then realm locked + pkt << uint8(flag); // RealmFlags + pkt << name; pkt << i->second.address; pkt << i->second.populationLevel; pkt << AmountOfCharacters; pkt << i->second.timezone; // realm category - pkt << uint8(0x2C); // unk, may be realm number/id? + if (_expversion & POST_BC_EXP_FLAG) // 2.x and 3.x clients + pkt << uint8(0x2C); // unk, may be realm number/id? + else + pkt << uint8(0x0); // 1.12.1 and 1.12.2 clients - if (i->second.flag & REALM_FLAG_SPECIFYBUILD) + if (_expversion & POST_BC_EXP_FLAG && flag & REALM_FLAG_SPECIFYBUILD) { - // TODO: Make this customizable - pkt << uint8(3); - pkt << uint8(3); - pkt << uint8(5); - pkt << uint16(12340); + pkt << uint8(buildInfo->MajorVersion); + pkt << uint8(buildInfo->MinorVersion); + pkt << uint8(buildInfo->BugfixVersion); + pkt << uint16(buildInfo->Build); } ++RealmListSize; } - pkt << uint8(0x10); - pkt << uint8(0x00); - + if (_expversion & POST_BC_EXP_FLAG) // 2.x and 3.x clients + { + pkt << uint8(0x10); + pkt << uint8(0x00); + } + else // 1.12.1 and 1.12.2 clients + { + pkt << uint8(0x00); + pkt << uint8(0x02); + } // make a ByteBuffer which stores the RealmList's size ByteBuffer RealmListSizeBuffer; - RealmListSizeBuffer << (uint32)0; - RealmListSizeBuffer << uint16(RealmListSize); + RealmListSizeBuffer << uint32(0); + if (_expversion & POST_BC_EXP_FLAG) // only 2.x and 3.x clients + RealmListSizeBuffer << uint16(RealmListSize); + else + RealmListSizeBuffer << uint32(RealmListSize); ByteBuffer hdr; hdr << uint8(REALM_LIST); - hdr << uint16((pkt.size() + RealmListSizeBuffer.size())); + hdr << uint16(pkt.size() + RealmListSizeBuffer.size()); hdr.append(RealmListSizeBuffer); // append RealmList's size buffer hdr.append(pkt); // append realms in the realmlist @@ -894,7 +946,7 @@ bool AuthSocket::_HandleXferResume() { sLog->outDebug(LOG_FILTER_AUTHSERVER, "Entering _HandleXferResume"); // Check packet length and patch existence - if (socket().recv_len() < 9 || !pPatch) + if (socket().recv_len() < 9 || !pPatch) // FIXME: pPatch is never used { sLog->outError(LOG_FILTER_AUTHSERVER, "Error while resuming patch transfer (wrong packet)"); return false; @@ -948,7 +1000,9 @@ PatcherRunnable::PatcherRunnable(class AuthSocket* as) } // Send content of patch file to the client -void PatcherRunnable::run() {} +void PatcherRunnable::run() +{ +} // Preload MD5 hashes of existing patch files on server #ifndef _WIN32 diff --git a/src/server/authserver/Server/AuthSocket.h b/src/server/authserver/Server/AuthSocket.h index edd2b345183..9be2136b55c 100755 --- a/src/server/authserver/Server/AuthSocket.h +++ b/src/server/authserver/Server/AuthSocket.h @@ -70,6 +70,7 @@ private: std::string _localizationName; std::string _os; uint16 _build; + uint8 _expversion; AccountTypes _accountSecurityLevel; }; diff --git a/src/server/authserver/authserver.conf.dist b/src/server/authserver/authserver.conf.dist index ee7e5970155..67d22c49da1 100644 --- a/src/server/authserver/authserver.conf.dist +++ b/src/server/authserver/authserver.conf.dist @@ -9,6 +9,7 @@ # EXAMPLE CONFIG # AUTH SERVER SETTINGS # MYSQL SETTINGS +# LOGGING SYSTEM SETTINGS # ################################################################################################### @@ -148,7 +149,7 @@ LoginDatabase.WorkerThreads = 1 ################################################################################################### # -# Logging system options. +# LOGGING SYSTEM SETTINGS # # Appender config values: Given a appender "name" # Appender.name @@ -247,3 +248,6 @@ Logger.Root=0,3,Console Auth # Default: "root" Loggers=Root + +# +###################################################################################################
\ No newline at end of file diff --git a/src/server/collision/Maps/MapTree.cpp b/src/server/collision/Maps/MapTree.cpp index 6489ddd7a4f..f35e36d92fd 100644 --- a/src/server/collision/Maps/MapTree.cpp +++ b/src/server/collision/Maps/MapTree.cpp @@ -124,8 +124,8 @@ namespace VMAP return intersectionCallBack.result; } - StaticMapTree::StaticMapTree(uint32 mapID, const std::string &basePath): - iMapID(mapID), iTreeValues(0), iBasePath(basePath) + StaticMapTree::StaticMapTree(uint32 mapID, const std::string &basePath) + : iMapID(mapID), iTreeValues(0), iBasePath(basePath), iIsTiled(false) { if (iBasePath.length() > 0 && iBasePath[iBasePath.length()-1] != '/' && iBasePath[iBasePath.length()-1] != '\\') { diff --git a/src/server/collision/Maps/TileAssembler.cpp b/src/server/collision/Maps/TileAssembler.cpp index 207b652a4d6..8458ffdd5d3 100644 --- a/src/server/collision/Maps/TileAssembler.cpp +++ b/src/server/collision/Maps/TileAssembler.cpp @@ -54,11 +54,8 @@ namespace VMAP //================================================================= TileAssembler::TileAssembler(const std::string& pSrcDirName, const std::string& pDestDirName) + : iSrcDir(pSrcDirName), iDestDir(pDestDirName), iCurrentUniqueNameId(0), iFilterMethod(NULL) { - iCurrentUniqueNameId = 0; - iFilterMethod = NULL; - iSrcDir = pSrcDirName; - iDestDir = pDestDirName; //mkdir(iDestDir); //init(); } diff --git a/src/server/collision/Models/ModelInstance.h b/src/server/collision/Models/ModelInstance.h index 1118b654578..2745628ac7e 100755 --- a/src/server/collision/Models/ModelInstance.h +++ b/src/server/collision/Models/ModelInstance.h @@ -63,7 +63,7 @@ namespace VMAP class ModelInstance: public ModelSpawn { public: - ModelInstance(): iModel(0) {} + ModelInstance(): iModel(0), iInvScale(0.0f) {} ModelInstance(const ModelSpawn &spawn, WorldModel* model); void setUnloaded() { iModel = 0; } bool intersectRay(const G3D::Ray& pRay, float& pMaxDist, bool pStopAtFirstHit) const; diff --git a/src/server/game/AI/ScriptedAI/ScriptedCreature.h b/src/server/game/AI/ScriptedAI/ScriptedCreature.h index ba0a94d2590..aa46d555b7d 100644 --- a/src/server/game/AI/ScriptedAI/ScriptedCreature.h +++ b/src/server/game/AI/ScriptedAI/ScriptedCreature.h @@ -41,8 +41,10 @@ class SummonList : public std::list<uint64> template <class Predicate> void DoAction(int32 info, Predicate& predicate, uint16 max = 0) { - Trinity::Containers::RandomResizeList<uint64, Predicate>(*this, predicate, max); - for (iterator i = begin(); i != end(); ) + // We need to use a copy of SummonList here, otherwise original SummonList would be modified + std::list<uint64> listCopy = *this; + Trinity::Containers::RandomResizeList<uint64, Predicate>(listCopy, predicate, max); + for (iterator i = listCopy.begin(); i != listCopy.end(); ) { Creature* summon = Unit::GetCreature(*me, *i++); if (summon && summon->IsAIEnabled) diff --git a/src/server/game/AI/SmartScripts/SmartScript.cpp b/src/server/game/AI/SmartScripts/SmartScript.cpp index 6e5a34e8c33..69ecb1ef581 100644 --- a/src/server/game/AI/SmartScripts/SmartScript.cpp +++ b/src/server/game/AI/SmartScripts/SmartScript.cpp @@ -79,6 +79,7 @@ SmartScript::SmartScript() { go = NULL; me = NULL; + trigger = NULL; mEventPhase = 0; mPathId = 0; mTargetStorage = new ObjectListMap(); @@ -92,6 +93,7 @@ SmartScript::SmartScript() meOrigGUID = 0; goOrigGUID = 0; mLastInvoker = 0; + mScriptType = SMART_SCRIPT_TYPE_CREATURE; } SmartScript::~SmartScript() @@ -1117,10 +1119,10 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u } case SMART_ACTION_SUMMON_CREATURE: { - float x, y, z, o; ObjectList* targets = GetTargets(e, unit); if (targets) { + float x, y, z, o; for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) { (*itr)->GetPosition(x, y, z, o); @@ -1149,10 +1151,10 @@ void SmartScript::ProcessAction(SmartScriptHolder& e, Unit* unit, uint32 var0, u if (!GetBaseObject()) break; - float x, y, z, o; ObjectList* targets = GetTargets(e, unit); if (targets) { + float x, y, z, o; for (ObjectList::const_iterator itr = targets->begin(); itr != targets->end(); ++itr) { if (!IsUnit(*itr)) diff --git a/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp b/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp index a40024a81cd..37fd91fcc1b 100644 --- a/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp +++ b/src/server/game/AI/SmartScripts/SmartScriptMgr.cpp @@ -913,7 +913,7 @@ bool SmartAIMgr::IsEventValid(SmartScriptHolder& e) return true; } -bool SmartAIMgr::IsTextValid(SmartScriptHolder const& e, uint32 id) +/*bool SmartAIMgr::IsTextValid(SmartScriptHolder const& e, uint32 id) // unused { bool error = false; uint32 entry = 0; @@ -938,4 +938,4 @@ bool SmartAIMgr::IsTextValid(SmartScriptHolder const& e, uint32 id) return false; } return true; -} +}*/ diff --git a/src/server/game/AI/SmartScripts/SmartScriptMgr.h b/src/server/game/AI/SmartScripts/SmartScriptMgr.h index 2a81339a930..b0a3c5b6bb6 100644 --- a/src/server/game/AI/SmartScripts/SmartScriptMgr.h +++ b/src/server/game/AI/SmartScripts/SmartScriptMgr.h @@ -1216,16 +1216,9 @@ enum SmartCastFlags // one line in DB is one event struct SmartScriptHolder { - SmartScriptHolder() - { - timer = 0; - active = false; - runOnce = false; - link = 0; - entryOrGuid = 0; - event_id = 0; - enableTimed = false; - } + SmartScriptHolder() : timer(0), active(false), runOnce(false), link(0), entryOrGuid(0), + event_id(0), enableTimed(false), source_type(SMART_SCRIPT_TYPE_CREATURE) {} + int32 entryOrGuid; SmartScriptType source_type; uint32 event_id; @@ -1437,7 +1430,7 @@ class SmartAIMgr return true; } - bool IsTextValid(SmartScriptHolder const& e, uint32 id); + //bool IsTextValid(SmartScriptHolder const& e, uint32 id); }; #define sSmartScriptMgr ACE_Singleton<SmartAIMgr, ACE_Null_Mutex>::instance() diff --git a/src/server/game/Achievements/AchievementMgr.cpp b/src/server/game/Achievements/AchievementMgr.cpp index 7a73b9f8f69..ee2795a83a8 100644 --- a/src/server/game/Achievements/AchievementMgr.cpp +++ b/src/server/game/Achievements/AchievementMgr.cpp @@ -80,7 +80,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) return false; } - switch (criteria->requiredType) + switch (criteria->type) { case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE: case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG: @@ -108,7 +108,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) default: if (dataType != ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT) { - sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` has data for non-supported criteria type (Entry: %u Type: %u), ignored.", criteria->ID, criteria->requiredType); + sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` has data for non-supported criteria type (Entry: %u Type: %u), ignored.", criteria->ID, criteria->type); return false; } break; @@ -124,7 +124,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (!creature.id || !sObjectMgr->GetCreatureTemplate(creature.id)) { sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_CREATURE (%u) has non-existing creature id in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, creature.id); + criteria->ID, criteria->type, dataType, creature.id); return false; } return true; @@ -132,19 +132,19 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (!classRace.class_id && !classRace.race_id) { sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) must not have 0 in either value field, ignored.", - criteria->ID, criteria->requiredType, dataType); + criteria->ID, criteria->type, dataType); return false; } if (classRace.class_id && ((1 << (classRace.class_id-1)) & CLASSMASK_ALL_PLAYABLE) == 0) { sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) has non-existing class in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, classRace.class_id); + criteria->ID, criteria->type, dataType, classRace.class_id); return false; } if (classRace.race_id && ((1 << (classRace.race_id-1)) & RACEMASK_ALL_PLAYABLE) == 0) { sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) has non-existing race in value2 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, classRace.race_id); + criteria->ID, criteria->type, dataType, classRace.race_id); return false; } return true; @@ -152,7 +152,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (health.percent < 1 || health.percent > 100) { sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_PLAYER_LESS_HEALTH (%u) has wrong percent value in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, health.percent); + criteria->ID, criteria->type, dataType, health.percent); return false; } return true; @@ -163,19 +163,19 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (!spellEntry) { sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has wrong spell id in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.spell_id); + criteria->ID, criteria->type, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.spell_id); return false; } if (aura.effect_idx >= 3) { sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has wrong spell effect index in value2 (%u), ignored.", - criteria->ID, criteria->requiredType, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.effect_idx); + criteria->ID, criteria->type, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.effect_idx); return false; } if (!spellEntry->Effects[aura.effect_idx].ApplyAuraName) { sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has non-aura spell effect (ID: %u Effect: %u), ignores.", - criteria->ID, criteria->requiredType, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.spell_id, aura.effect_idx); + criteria->ID, criteria->type, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.spell_id, aura.effect_idx); return false; } return true; @@ -184,7 +184,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (level.minlevel > STRONG_MAX_LEVEL) { sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL (%u) has wrong minlevel in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, level.minlevel); + criteria->ID, criteria->type, dataType, level.minlevel); return false; } return true; @@ -192,7 +192,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (gender.gender > GENDER_NONE) { sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER (%u) has wrong gender in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, gender.gender); + criteria->ID, criteria->type, dataType, gender.gender); return false; } return true; @@ -200,7 +200,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (!ScriptId) { sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT (%u) does not have ScriptName set, ignored.", - criteria->ID, criteria->requiredType, dataType); + criteria->ID, criteria->type, dataType); return false; } return true; @@ -208,7 +208,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (map_players.maxcount <= 0) { sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT (%u) has wrong max players count in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, map_players.maxcount); + criteria->ID, criteria->type, dataType, map_players.maxcount); return false; } return true; @@ -216,7 +216,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (team.team != ALLIANCE && team.team != HORDE) { sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM (%u) has unknown team in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, team.team); + criteria->ID, criteria->type, dataType, team.team); return false; } return true; @@ -224,7 +224,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (drunk.state >= MAX_DRUNKEN) { sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK (%u) has unknown drunken state in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, drunk.state); + criteria->ID, criteria->type, dataType, drunk.state); return false; } return true; @@ -232,7 +232,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (!sHolidaysStore.LookupEntry(holiday.id)) { sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY (%u) has unknown holiday in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, holiday.id); + criteria->ID, criteria->type, dataType, holiday.id); return false; } return true; @@ -242,7 +242,7 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (equipped_item.item_quality >= MAX_ITEM_QUALITY) { sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_requirement` (Entry: %u Type: %u) for requirement ACHIEVEMENT_CRITERIA_REQUIRE_S_EQUIPED_ITEM (%u) has unknown quality state in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, equipped_item.item_quality); + criteria->ID, criteria->type, dataType, equipped_item.item_quality); return false; } return true; @@ -250,29 +250,29 @@ bool AchievementCriteriaData::IsValid(AchievementCriteriaEntry const* criteria) if (!classRace.class_id && !classRace.race_id) { sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) must not have 0 in either value field, ignored.", - criteria->ID, criteria->requiredType, dataType); + criteria->ID, criteria->type, dataType); return false; } if (classRace.class_id && ((1 << (classRace.class_id-1)) & CLASSMASK_ALL_PLAYABLE) == 0) { sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) has non-existing class in value1 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, classRace.class_id); + criteria->ID, criteria->type, dataType, classRace.class_id); return false; } if (classRace.race_id && ((1 << (classRace.race_id-1)) & RACEMASK_ALL_PLAYABLE) == 0) { sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) has non-existing race in value2 (%u), ignored.", - criteria->ID, criteria->requiredType, dataType, classRace.race_id); + criteria->ID, criteria->type, dataType, classRace.race_id); return false; } return true; default: - sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) has data for non-supported data type (%u), ignored.", criteria->ID, criteria->requiredType, dataType); + sLog->outError(LOG_FILTER_SQL, "Table `achievement_criteria_data` (Entry: %u Type: %u) has data for non-supported data type (%u), ignored.", criteria->ID, criteria->type, dataType); return false; } } -bool AchievementCriteriaData::Meets(uint32 criteria_id, Player const* source, Unit const* target, uint32 miscvalue1 /*= 0*/) const +bool AchievementCriteriaData::Meets(uint32 criteria_id, Player const* source, Unit const* target, uint32 miscValue1 /*= 0*/) const { switch (dataType) { @@ -307,7 +307,7 @@ bool AchievementCriteriaData::Meets(uint32 criteria_id, Player const* source, Un case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA: return target && target->HasAuraEffect(aura.spell_id, aura.effect_idx); case ACHIEVEMENT_CRITERIA_DATA_TYPE_VALUE: - return miscvalue1 >= value.minvalue; + return miscValue1 >= value.minvalue; case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL: if (!target) return false; @@ -353,11 +353,11 @@ bool AchievementCriteriaData::Meets(uint32 criteria_id, Player const* source, Un ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT, criteria_id, map->GetId()); return false; } - return instance->CheckAchievementCriteriaMeet(criteria_id, source, target, miscvalue1); + return instance->CheckAchievementCriteriaMeet(criteria_id, source, target, miscValue1); } case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_EQUIPED_ITEM: { - ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(miscvalue1); + ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(miscValue1); if (!pProto) return false; return pProto->ItemLevel >= equipped_item.item_level && pProto->Quality >= equipped_item.item_quality; @@ -368,10 +368,10 @@ bool AchievementCriteriaData::Meets(uint32 criteria_id, Player const* source, Un return false; } -bool AchievementCriteriaDataSet::Meets(Player const* source, Unit const* target, uint32 miscvalue /*= 0*/) const +bool AchievementCriteriaDataSet::Meets(Player const* source, Unit const* target, uint32 miscValue /*= 0*/) const { for (Storage::const_iterator itr = storage.begin(); itr != storage.end(); ++itr) - if (!itr->Meets(criteria_id, source, target, miscvalue)) + if (!itr->Meets(criteria_id, source, target, miscValue)) return false; return true; @@ -454,9 +454,9 @@ void AchievementMgr<Guild>::RemoveCriteriaProgress(const AchievementCriteriaEntr } template<class T> -void AchievementMgr<T>::ResetAchievementCriteria(AchievementCriteriaTypes type, uint32 miscvalue1, uint32 miscvalue2, bool evenIfCriteriaComplete) +void AchievementMgr<T>::ResetAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1, uint32 miscValue2, bool evenIfCriteriaComplete) { - sLog->outDebug(LOG_FILTER_ACHIEVEMENTSYS, "AchievementMgr::ResetAchievementCriteria(%u, %u, %u)", type, miscvalue1, miscvalue2); + sLog->outDebug(LOG_FILTER_ACHIEVEMENTSYS, "AchievementMgr::ResetAchievementCriteria(%u, %u, %u)", type, miscValue1, miscValue2); // disable for gamemasters with GM-mode enabled if (GetOwner()->isGameMaster()) @@ -467,7 +467,7 @@ void AchievementMgr<T>::ResetAchievementCriteria(AchievementCriteriaTypes type, { AchievementCriteriaEntry const* achievementCriteria = (*i); - AchievementEntry const* achievement = sAchievementStore.LookupEntry(achievementCriteria->referredAchievement); + AchievementEntry const* achievement = sAchievementMgr->GetAchievement(achievementCriteria->achievement); if (!achievement) continue; @@ -476,9 +476,9 @@ void AchievementMgr<T>::ResetAchievementCriteria(AchievementCriteriaTypes type, continue; for (uint8 j = 0; j < MAX_CRITERIA_REQUIREMENTS; ++j) - if (achievementCriteria->additionalRequirements[j].additionalRequirement_type == miscvalue1 && + if (achievementCriteria->additionalRequirements[j].additionalRequirement_type == miscValue1 && (!achievementCriteria->additionalRequirements[j].additionalRequirement_value || - achievementCriteria->additionalRequirements[j].additionalRequirement_value == miscvalue2)) + achievementCriteria->additionalRequirements[j].additionalRequirement_value == miscValue2)) { RemoveCriteriaProgress(achievementCriteria); break; @@ -487,7 +487,7 @@ void AchievementMgr<T>::ResetAchievementCriteria(AchievementCriteriaTypes type, } template<> -void AchievementMgr<Guild>::ResetAchievementCriteria(AchievementCriteriaTypes /*type*/, uint32 /*miscvalue1*/, uint32 /*miscvalue2*/, bool /*evenIfCriteriaComplete*/) +void AchievementMgr<Guild>::ResetAchievementCriteria(AchievementCriteriaTypes /*type*/, uint32 /*miscValue1*/, uint32 /*miscValue2*/, bool /*evenIfCriteriaComplete*/) { // Not needed } @@ -703,7 +703,7 @@ void AchievementMgr<Player>::LoadFromDB(PreparedQueryResult achievementResult, P uint32 achievementid = fields[0].GetUInt16(); // must not happen: cleanup at server startup in sAchievementMgr->LoadCompletedAchievements() - AchievementEntry const* achievement = sAchievementStore.LookupEntry(achievementid); + AchievementEntry const* achievement = sAchievementMgr->GetAchievement(achievementid); if (!achievement) continue; @@ -718,11 +718,13 @@ void AchievementMgr<Player>::LoadFromDB(PreparedQueryResult achievementResult, P if (!GetOwner()->HasTitle(titleEntry)) GetOwner()->SetTitle(titleEntry); - } while (achievementResult->NextRow()); + } + while (achievementResult->NextRow()); } if (criteriaResult) { + time_t now = time(NULL); do { Field* fields = criteriaResult->Fetch(); @@ -730,7 +732,7 @@ void AchievementMgr<Player>::LoadFromDB(PreparedQueryResult achievementResult, P uint32 counter = fields[1].GetUInt32(); time_t date = time_t(fields[2].GetUInt32()); - AchievementCriteriaEntry const* criteria = sAchievementCriteriaStore.LookupEntry(id); + AchievementCriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(id); if (!criteria) { // we will remove not existed criteria for all characters @@ -743,14 +745,15 @@ void AchievementMgr<Player>::LoadFromDB(PreparedQueryResult achievementResult, P continue; } - if (criteria->timeLimit && time_t(date + criteria->timeLimit) < time(NULL)) + if (criteria->timeLimit && time_t(date + criteria->timeLimit) < now) continue; CriteriaProgress& progress = m_criteriaProgress[id]; progress.counter = counter; progress.date = date; progress.changed = false; - } while (criteriaResult->NextRow()); + } + while (criteriaResult->NextRow()); } } @@ -765,7 +768,7 @@ void AchievementMgr<Guild>::LoadFromDB(PreparedQueryResult achievementResult, Pr uint32 achievementid = fields[0].GetUInt16(); // must not happen: cleanup at server startup in sAchievementMgr->LoadCompletedAchievements() - AchievementEntry const* achievement = sAchievementStore.LookupEntry(achievementid); + AchievementEntry const* achievement = sAchievementMgr->GetAchievement(achievementid); if (!achievement) continue; @@ -776,8 +779,8 @@ void AchievementMgr<Guild>::LoadFromDB(PreparedQueryResult achievementResult, Pr ca.guids.insert(MAKE_NEW_GUID(atol(guids[i]), 0, HIGHGUID_PLAYER)); ca.changed = false; - - } while (achievementResult->NextRow()); + } + while (achievementResult->NextRow()); } if (criteriaResult) @@ -791,11 +794,11 @@ void AchievementMgr<Guild>::LoadFromDB(PreparedQueryResult achievementResult, Pr time_t date = time_t(fields[2].GetUInt32()); uint64 guid = fields[3].GetUInt32(); - AchievementCriteriaEntry const* criteria = sAchievementCriteriaStore.LookupEntry(id); + AchievementCriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(id); if (!criteria) { // we will remove not existed criteria for all guilds - sLog->outError(LOG_FILTER_GENERAL, "Non-existing achievement criteria %u data removed from table `guild_achievement_progress`.", id); + sLog->outError(LOG_FILTER_ACHIEVEMENTSYS, "Non-existing achievement criteria %u data removed from table `guild_achievement_progress`.", id); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEV_PROGRESS_CRITERIA); stmt->setUInt16(0, uint16(id)); @@ -839,7 +842,7 @@ void AchievementMgr<Player>::Reset() m_completedAchievements.clear(); m_criteriaProgress.clear(); - DeleteFromDB(_owner->GetGUIDLow()); + DeleteFromDB(GetOwner()->GetGUIDLow()); // re-fill data CheckAllAchievementCriteria(GetOwner()); @@ -874,23 +877,21 @@ void AchievementMgr<Guild>::Reset() } while (!m_criteriaProgress.empty()) - if (AchievementCriteriaEntry const* criteria = sAchievementCriteriaStore.LookupEntry(m_criteriaProgress.begin()->first)) + if (AchievementCriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(m_criteriaProgress.begin()->first)) RemoveCriteriaProgress(criteria); m_completedAchievements.clear(); - DeleteFromDB(_owner->GetId()); + DeleteFromDB(GetOwner()->GetId()); } template<class T> void AchievementMgr<T>::SendAchievementEarned(AchievementEntry const* achievement) const { - // Don't send for achievements with ACHIEVEMENT_FLAG_TRACKING + // Don't send for achievements with ACHIEVEMENT_FLAG_HIDDEN if (achievement->flags & ACHIEVEMENT_FLAG_HIDDEN) return; - #ifdef TRINITY_DEBUG - sLog->outDebug(LOG_FILTER_ACHIEVEMENTSYS, "AchievementMgr::SendAchievementEarned(%u)", achievement->ID); - #endif + sLog->outDebug(LOG_FILTER_ACHIEVEMENTSYS, "AchievementMgr::SendAchievementEarned(%u)", achievement->ID); if (Guild* guild = sGuildMgr->GetGuildById(GetOwner()->GetGuildId())) { @@ -902,7 +903,7 @@ void AchievementMgr<T>::SendAchievementEarned(AchievementEntry const* achievemen if (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_KILL | ACHIEVEMENT_FLAG_REALM_FIRST_REACH)) { // broadcast realm first reached - WorldPacket data(SMSG_SERVER_FIRST_ACHIEVEMENT, strlen(GetOwner()->GetName())+1+8+4+4); + WorldPacket data(SMSG_SERVER_FIRST_ACHIEVEMENT, strlen(GetOwner()->GetName()) + 1 + 8 + 4 + 4); data << GetOwner()->GetName(); data << uint64(GetOwner()->GetGUID()); data << uint32(achievement->ID); @@ -969,7 +970,7 @@ void AchievementMgr<T>::SendCriteriaUpdate(AchievementCriteriaEntry const* /*ent template<> void AchievementMgr<Player>::SendCriteriaUpdate(AchievementCriteriaEntry const* entry, CriteriaProgress const* progress, uint32 timeElapsed, bool timedCompleted) const { - WorldPacket data(SMSG_CRITERIA_UPDATE, 8+4+8); + WorldPacket data(SMSG_CRITERIA_UPDATE, 8 + 4 + 8); data << uint32(entry->ID); // the counter is packed like a packed Guid @@ -1051,7 +1052,7 @@ void AchievementMgr<T>::CheckAllAchievementCriteria(Player* referencePlayer) UpdateAchievementCriteria(AchievementCriteriaTypes(i), 0, 0, NULL, referencePlayer); } -static const uint32 achievIdByArenaSlot[MAX_ARENA_SLOT] = { 1057, 1107, 1108 }; +static const uint32 achievIdByArenaSlot[MAX_ARENA_SLOT] = {1057, 1107, 1108}; static const uint32 achievIdForDungeon[][4] = { // ach_cr_id, is_dungeon, is_raid, is_heroic_dungeon @@ -1071,9 +1072,9 @@ template<> bool IsGuild<Guild>() { return true; } * this function will be called whenever the user might have done a criteria relevant action */ template<class T> -void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 /*= 0*/, uint32 miscValue2 /*= 0*/, Unit* unit /*= NULL*/, Player* referencePlayer /*= NULL*/) +void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 /*= 0*/, uint32 miscValue2 /*= 0*/, Unit const* unit /*= NULL*/, Player* referencePlayer /*= NULL*/) { - sLog->outDebug(LOG_FILTER_ACHIEVEMENTSYS, "AchievementMgr::UpdateAchievementCriteria(%u, %u, %u)", type, miscValue1, miscValue2); + sLog->outDebug(LOG_FILTER_ACHIEVEMENTSYS, "UpdateAchievementCriteria(%u, %u, %u)", type, miscValue1, miscValue2); // disable for gamemasters with GM-mode enabled if (referencePlayer->isGameMaster()) @@ -1083,9 +1084,12 @@ void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i != achievementCriteriaList.end(); ++i) { AchievementCriteriaEntry const* achievementCriteria = (*i); - AchievementEntry const* achievement = sAchievementStore.LookupEntry(achievementCriteria->referredAchievement); + AchievementEntry const* achievement = sAchievementMgr->GetAchievement(achievementCriteria->achievement); if (!achievement) + { + sLog->outError(LOG_FILTER_ACHIEVEMENTSYS, "UpdateAchievementCriteria: Achievement %u not found!", achievementCriteria->achievement); continue; + } if (!CanUpdateCriteria(achievementCriteria, achievement, miscValue1, miscValue2, unit, referencePlayer)) continue; @@ -1108,12 +1112,37 @@ void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN: case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS: case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS: - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; + case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM: + case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM: + case ACHIEVEMENT_CRITERIA_TYPE_DEATH: + case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST: + case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP: + case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON: + case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE: + case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER: + case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM: + case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET: + case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2: + case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL: + case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2: + case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA: + case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM: + case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT: + case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT: + case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE: + case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT: + case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT: + case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL: + case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS: + case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE: + case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE: + case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL: + case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL: + case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS: + case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA: SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); break; - // std case: increment at miscvalue1 + // std case: increment at miscValue1 case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS: case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS: case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD: @@ -1124,82 +1153,42 @@ void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS:/* FIXME: for online player only currently */ case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED: case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED: - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; + case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG: + case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND: + case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE: + case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE: SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_ACCUMULATE); break; - // std case: high value at miscvalue1 + case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE: + case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE: + case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM: + case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM: + case ACHIEVEMENT_CRITERIA_TYPE_CURRENCY: + SetCriteriaProgress(achievementCriteria, miscValue2, referencePlayer, PROGRESS_ACCUMULATE); + break; + // std case: high value at miscValue1 case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD: /* FIXME: for online player only currently */ case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED: case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED: - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_HIGHEST); break; - - // specialized cases - case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST: - { - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; - - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; - } - case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG: - { - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; - if (achievementCriteria->win_bg.bgMapID != referencePlayer->GetMapId()) - continue; - - SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_ACCUMULATE); - break; - } - case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE: - { - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; - if (achievementCriteria->kill_creature.creatureID != miscValue1) - continue; - - SetCriteriaProgress(achievementCriteria, miscValue2, referencePlayer, PROGRESS_ACCUMULATE); - break; - } case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL: SetCriteriaProgress(achievementCriteria, referencePlayer->getLevel(), referencePlayer); break; case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL: - // update at loading or specific skill update - if (miscValue1 && miscValue1 != achievementCriteria->reach_skill_level.skillID) - continue; if (uint32 skillvalue = referencePlayer->GetBaseSkillValue(achievementCriteria->reach_skill_level.skillID)) SetCriteriaProgress(achievementCriteria, skillvalue, referencePlayer); break; case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL: - // update at loading or specific skill update - if (miscValue1 && miscValue1 != achievementCriteria->learn_skill_level.skillID) - continue; if (uint32 maxSkillvalue = referencePlayer->GetPureMaxSkillValue(achievementCriteria->learn_skill_level.skillID)) SetCriteriaProgress(achievementCriteria, maxSkillvalue, referencePlayer); break; - case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT: - if (m_completedAchievements.find(achievementCriteria->complete_achievement.linkedAchievement) != m_completedAchievements.end()) - SetCriteriaProgress(achievementCriteria, 1, referencePlayer); - break; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT: - { SetCriteriaProgress(achievementCriteria, referencePlayer->GetRewardedQuestCount(), referencePlayer); break; - } case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY: { time_t nextDailyResetTime = sWorld->GetNextDailyQuestsResetTime(); @@ -1218,7 +1207,7 @@ void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, // 1st time. Start count. progressType = PROGRESS_SET; else if (progress->date < (nextDailyResetTime - 2 * DAY)) - // last progress is older than 2 days. Player missed 1 day => Retart count. + // last progress is older than 2 days. Player missed 1 day => Restart count. progressType = PROGRESS_SET; else if (progress->date < (nextDailyResetTime - DAY)) // last progress is between 1 and 2 days. => 1st time of the day. @@ -1232,10 +1221,6 @@ void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, } case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE: { - // speedup for non-login case - if (miscValue1 && miscValue1 != achievementCriteria->complete_quests_in_zone.zoneID) - continue; - uint32 counter = 0; const RewardedQuestSet &rewQuests = referencePlayer->getRewardedQuests(); @@ -1248,371 +1233,34 @@ void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, SetCriteriaProgress(achievementCriteria, counter, referencePlayer); break; } - case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND: - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; - if (referencePlayer->GetMapId() != achievementCriteria->complete_battleground.mapID) - continue; - SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_ACCUMULATE); - break; - case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP: - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; - if (referencePlayer->GetMapId() != achievementCriteria->death_at_map.mapID) - continue; - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; - case ACHIEVEMENT_CRITERIA_TYPE_DEATH: - { - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; - // skip wrong arena achievements, if not achievIdByArenaSlot then normal total death counter - bool notfit = false; - for (int j = 0; j < MAX_ARENA_SLOT; ++j) - { - if (achievIdByArenaSlot[j] == achievement->ID) - { - Battleground* bg = referencePlayer->GetBattleground(); - if (!bg || !bg->isArena() || ArenaTeam::GetSlotByType(bg->GetArenaType()) != j) - notfit = true; - - break; - } - } - if (notfit) - continue; - - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; - } - case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON: - { - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; - - Map const* map = referencePlayer->IsInWorld() ? referencePlayer->GetMap() : sMapMgr->FindMap(referencePlayer->GetMapId(), referencePlayer->GetInstanceId()); - if (!map || !map->IsDungeon()) - continue; - - // search case - bool found = false; - for (int j = 0; achievIdForDungeon[j][0]; ++j) - { - if (achievIdForDungeon[j][0] == achievement->ID) - { - if (map->IsRaid()) - { - // if raid accepted (ignore difficulty) - if (!achievIdForDungeon[j][2]) - break; // for - } - else if (referencePlayer->GetDungeonDifficulty() == DUNGEON_DIFFICULTY_NORMAL) - { - // dungeon in normal mode accepted - if (!achievIdForDungeon[j][1]) - break; // for - } - else - { - // dungeon in heroic mode accepted - if (!achievIdForDungeon[j][3]) - break; // for - } - - found = true; - break; // for - } - } - if (!found) - continue; - - //FIXME: work only for instances where max == min for players - if (((InstanceMap*)map)->GetMaxPlayers() != achievementCriteria->death_in_dungeon.manLimit) - continue; - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; - - } - case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE: - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; - if (miscValue1 != achievementCriteria->killed_by_creature.creatureEntry) - continue; - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; - case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER: - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; - - // if team check required: must kill by opposition faction - if (achievement->ID == 318 && miscValue2 == referencePlayer->GetTeam()) - continue; - - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING: - { - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; - - // miscvalue1 is the ingame fallheight*100 as stored in dbc + // miscValue1 is the ingame fallheight*100 as stored in dbc SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer); break; - } - case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM: - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; - if (miscValue2 != achievementCriteria->death_from.type) - continue; - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST: - { - // if miscvalues != 0, it contains the questID. - if (miscValue1) - { - if (miscValue1 != achievementCriteria->complete_quest.questID) - continue; - } - else - { - // login case. - if (!referencePlayer->GetQuestRewardStatus(achievementCriteria->complete_quest.questID)) - continue; - } - - if (AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria)) - if (!data->Meets(referencePlayer, unit)) - continue; - - SetCriteriaProgress(achievementCriteria, 1, referencePlayer); - break; - } - case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET: - case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2: - { - if (!miscValue1 || miscValue1 != achievementCriteria->be_spell_target.spellID) - continue; - - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; - } - case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL: - case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2: - { - if (!miscValue1 || miscValue1 != achievementCriteria->cast_spell.spellID) - continue; - - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; - } case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL: - if (miscValue1 && miscValue1 != achievementCriteria->learn_spell.spellID) - continue; - - if (referencePlayer->HasSpell(achievementCriteria->learn_spell.spellID)) - SetCriteriaProgress(achievementCriteria, 1, referencePlayer); - break; - case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE: - { - // miscvalue1=loot_type (note: 0 = LOOT_CORPSE and then it ignored) - // miscvalue2=count of item loot - if (!miscValue1 || !miscValue2) - continue; - if (miscValue1 != achievementCriteria->loot_type.lootType) - continue; - - SetCriteriaProgress(achievementCriteria, miscValue2, referencePlayer, PROGRESS_ACCUMULATE); - break; - } - case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM: - // speedup for non-login case - if (miscValue1 && achievementCriteria->own_item.itemID != miscValue1) - continue; - SetCriteriaProgress(achievementCriteria, miscValue2, referencePlayer, PROGRESS_ACCUMULATE); - break; - case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA: - if (!miscValue1) // no update at login - continue; - - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; - case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM: - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; - - if (achievementCriteria->use_item.itemID != miscValue1) - continue; - - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; - case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM: - // You _have_ to loot that item, just owning it when logging in does _not_ count! - if (!miscValue1) - continue; - if (miscValue1 != achievementCriteria->own_item.itemID) - continue; - SetCriteriaProgress(achievementCriteria, miscValue2, referencePlayer, PROGRESS_ACCUMULATE); - break; case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA: - { - WorldMapOverlayEntry const* worldOverlayEntry = sWorldMapOverlayStore.LookupEntry(achievementCriteria->explore_area.areaReference); - if (!worldOverlayEntry) - break; - - bool matchFound = false; - for (int j = 0; j < MAX_WORLD_MAP_OVERLAY_AREA_IDX; ++j) - { - uint32 area_id = worldOverlayEntry->areatableID[j]; - if (!area_id) // array have 0 only in empty tail - break; - - int32 exploreFlag = GetAreaFlagByAreaID(area_id); - if (exploreFlag < 0) - continue; - - uint32 playerIndexOffset = uint32(exploreFlag) / 32; - uint32 mask = 1<< (uint32(exploreFlag) % 32); - - if (referencePlayer->GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + playerIndexOffset) & mask) - { - matchFound = true; - break; - } - } - - if (matchFound) - SetCriteriaProgress(achievementCriteria, 1, referencePlayer); + case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP: + case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM: + case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM: + case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT: + SetCriteriaProgress(achievementCriteria, 1, referencePlayer); break; - } case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT: SetCriteriaProgress(achievementCriteria, referencePlayer->GetBankBagSlotCount(), referencePlayer); break; case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION: { - // skip faction check only at loading - if (miscValue1 && miscValue1 != achievementCriteria->gain_reputation.factionID) - continue; - int32 reputation = referencePlayer->GetReputationMgr().GetReputation(achievementCriteria->gain_reputation.factionID); if (reputation > 0) SetCriteriaProgress(achievementCriteria, reputation, referencePlayer); break; } case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION: - { SetCriteriaProgress(achievementCriteria, referencePlayer->GetReputationMgr().GetExaltedFactionCount(), referencePlayer); break; - } - case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP: - { - // skip for login case - if (!miscValue1) - continue; - SetCriteriaProgress(achievementCriteria, 1, referencePlayer); - break; - } - case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM: - { - // miscvalue1 = itemid - // miscvalue2 = itemSlot - if (!miscValue1) - continue; - - if (miscValue2 != achievementCriteria->equip_epic_item.itemSlot) - continue; - - SetCriteriaProgress(achievementCriteria, 1, referencePlayer); - break; - } - - case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT: - case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT: - { - // miscvalue1 = itemid - // miscvalue2 = diced value - if (!miscValue1) - continue; - if (miscValue2 != achievementCriteria->roll_greed_on_loot.rollValue) - continue; - - ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(miscValue1); - if (!pProto) - continue; - - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; - } - case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE: - { - // miscvalue1 = emote - if (!miscValue1) - continue; - if (miscValue1 != achievementCriteria->do_emote.emoteID) - continue; - - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; - } - case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE: - case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE: - { - if (!miscValue1) - continue; - - if (achievementCriteria->additionalRequirements[0].additionalRequirement_type == ACHIEVEMENT_CRITERIA_CONDITION_BG_MAP) - { - if (referencePlayer->GetMapId() != achievementCriteria->additionalRequirements[0].additionalRequirement_value) - continue; - - // map specific case (BG in fact) expected player targeted damage/heal - if (!unit || unit->GetTypeId() != TYPEID_PLAYER) - continue; - } - - SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_ACCUMULATE); - break; - } - case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM: - // miscvalue1 = item_id - if (!miscValue1) - continue; - if (miscValue1 != achievementCriteria->equip_item.itemID) - continue; - - SetCriteriaProgress(achievementCriteria, 1, referencePlayer); - break; - case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT: - // miscvalue1 = go entry - if (!miscValue1) - continue; - if (miscValue1 != achievementCriteria->use_gameobject.goEntry) - continue; - - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; - case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT: - if (!miscValue1) - continue; - if (miscValue1 != achievementCriteria->fish_in_gameobject.goEntry) - continue; - - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS: { - if (miscValue1 && miscValue1 != achievementCriteria->learn_skillline_spell.skillLine) - continue; - uint32 spellCount = 0; for (PlayerSpellMap::const_iterator spellIter = referencePlayer->GetSpellMap().begin(); spellIter != referencePlayer->GetSpellMap().end(); @@ -1628,13 +1276,6 @@ void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, SetCriteriaProgress(achievementCriteria, spellCount, referencePlayer); break; } - case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL: - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; - - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION: SetCriteriaProgress(achievementCriteria, referencePlayer->GetReputationMgr().GetReveredFactionCount(), referencePlayer); break; @@ -1644,23 +1285,8 @@ void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS: SetCriteriaProgress(achievementCriteria, referencePlayer->GetReputationMgr().GetVisibleFactionCount(), referencePlayer); break; - case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM: - case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM: - { - // AchievementMgr::UpdateAchievementCriteria might also be called on login - skip in this case - if (!miscValue1) - continue; - ItemTemplate const* proto = sObjectMgr->GetItemTemplate(miscValue1); - if (!proto || proto->Quality < ITEM_QUALITY_EPIC) - continue; - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; - } case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE: { - if (miscValue1 && miscValue1 != achievementCriteria->learn_skill_line.skillLine) - continue; - uint32 spellCount = 0; for (PlayerSpellMap::const_iterator spellIter = referencePlayer->GetSpellMap().begin(); spellIter != referencePlayer->GetSpellMap().end(); @@ -1677,18 +1303,6 @@ void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, case ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL: SetCriteriaProgress(achievementCriteria, referencePlayer->GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS), referencePlayer); break; - case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS: - if (!miscValue1 || miscValue1 != achievementCriteria->hk_class.classID) - continue; - - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; - case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE: - if (!miscValue1 || miscValue1 != achievementCriteria->hk_race.raceID) - continue; - - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED: SetCriteriaProgress(achievementCriteria, referencePlayer->GetMoney(), referencePlayer, PROGRESS_HIGHEST); break; @@ -1698,7 +1312,7 @@ void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, { uint32 points = 0; for (CompletedAchievementMap::iterator itr = m_completedAchievements.begin(); itr != m_completedAchievements.end(); ++itr) - if (AchievementEntry const* pAchievement = sAchievementStore.LookupEntry(itr->first)) + if (AchievementEntry const* pAchievement = sAchievementMgr->GetAchievement(itr->first)) points += pAchievement->points; SetCriteriaProgress(achievementCriteria, points, referencePlayer, PROGRESS_SET); } @@ -1706,33 +1320,6 @@ void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_ACCUMULATE); break; } - case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE: - { - if (!miscValue1 || miscValue1 != achievementCriteria->bg_objective.objectiveId) - continue; - - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; - } - case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL: - case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL: - case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS: - { - // skip login update - if (!miscValue1) - continue; - - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; - } - case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA: - { - if (!miscValue1 || miscValue1 != achievementCriteria->honorable_kill_at_area.areaID) - continue; - - SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE); - break; - } case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING: { uint32 reqTeamType = achievementCriteria->highest_team_rating.teamtype; @@ -1744,7 +1331,7 @@ void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_HIGHEST); } - else // login case + else // login case { for (uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot) { @@ -1774,7 +1361,7 @@ void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_HIGHEST); } - else // login case + else // login case { for (uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot) { @@ -1796,15 +1383,6 @@ void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, break; } - case ACHIEVEMENT_CRITERIA_TYPE_CURRENCY: - if (!miscValue1 || !miscValue2) - continue; - if (miscValue1 != achievementCriteria->currencyGain.currency) - continue; - if (int64(miscValue2) < 0) - continue; - SetCriteriaProgress(achievementCriteria, miscValue2, referencePlayer, PROGRESS_ACCUMULATE); - break; // FIXME: not triggered in code as result, need to implement case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_RAID: case ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA: @@ -1812,7 +1390,6 @@ void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, case ACHIEVEMENT_CRITERIA_TYPE_OWN_RANK: case ACHIEVEMENT_CRITERIA_TYPE_EARNED_PVP_TITLE: case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE: - case ACHIEVEMENT_CRITERIA_TYPE_TOTAL: case ACHIEVEMENT_CRITERIA_TYPE_SPENT_GOLD_GUILD_REPAIRS: case ACHIEVEMENT_CRITERIA_TYPE_REACH_GUILD_LEVEL: case ACHIEVEMENT_CRITERIA_TYPE_CRAFT_ITEMS_GUILD: @@ -1882,7 +1459,7 @@ bool AchievementMgr<T>::IsCompletedCriteria(AchievementCriteriaEntry const* achi if (!progress) return false; - switch (achievementCriteria->requiredType) + switch (achievementCriteria->type) { case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG: return progress->counter >= achievementCriteria->win_bg.winCount; @@ -2045,16 +1622,16 @@ bool AchievementMgr<T>::IsCompletedAchievement(AchievementEntry const* entry) return false; // for achievement with referenced achievement criterias get from referenced and counter from self - uint32 achievmentForTestId = entry->refAchievement ? entry->refAchievement : entry->ID; - uint32 achievmentForTestCount = entry->count; + uint32 achievementForTestId = entry->refAchievement ? entry->refAchievement : entry->ID; + uint32 achievementForTestCount = entry->count; - AchievementCriteriaEntryList const* cList = sAchievementMgr->GetAchievementCriteriaByAchievement(achievmentForTestId); + AchievementCriteriaEntryList const* cList = sAchievementMgr->GetAchievementCriteriaByAchievement(achievementForTestId); if (!cList) return false; uint32 count = 0; // For SUMM achievements, we have to count the progress of each criteria of the achievement. - // Oddly, the target count is NOT countained in the achievement, but in each individual criteria + // Oddly, the target count is NOT contained in the achievement, but in each individual criteria if (entry->flags & ACHIEVEMENT_FLAG_SUMM) { for (AchievementCriteriaEntryList::const_iterator itr = cList->begin(); itr != cList->end(); ++itr) @@ -2089,12 +1666,12 @@ bool AchievementMgr<T>::IsCompletedAchievement(AchievementEntry const* entry) completed_all = false; // completed as have req. count of completed criterias - if (achievmentForTestCount > 0 && achievmentForTestCount <= count) + if (achievementForTestCount > 0 && achievementForTestCount <= count) return true; } // all criterias completed requirement - if (completed_all && achievmentForTestCount == 0) + if (completed_all && achievementForTestCount == 0) return true; return false; @@ -2162,7 +1739,7 @@ void AchievementMgr<T>::SetCriteriaProgress(AchievementCriteriaEntry const* entr progress->changed = true; progress->date = time(NULL); // set the date to the latest update. - AchievementEntry const* achievement = sAchievementStore.LookupEntry(entry->referredAchievement); + AchievementEntry const* achievement = sAchievementMgr->GetAchievement(entry->achievement); uint32 timeElapsed = 0; bool criteriaComplete = IsCompletedCriteria(entry, achievement); @@ -2192,7 +1769,7 @@ void AchievementMgr<T>::UpdateTimedAchievements(uint32 timeDiff) // Time is up, remove timer and reset progress if (itr->second <= timeDiff) { - AchievementCriteriaEntry const* entry = sAchievementCriteriaStore.LookupEntry(itr->first); + AchievementCriteriaEntry const* entry = sAchievementMgr->GetAchievementCriteria(itr->first); RemoveCriteriaProgress(entry); m_timedAchievements.erase(itr++); } @@ -2219,7 +1796,7 @@ void AchievementMgr<Player>::StartTimedAchievement(AchievementCriteriaTimedTypes if ((*i)->timedCriteriaMiscId != entry) continue; - AchievementEntry const* achievement = sAchievementStore.LookupEntry((*i)->referredAchievement); + AchievementEntry const* achievement = sAchievementMgr->GetAchievement((*i)->achievement); if (m_timedAchievements.find((*i)->ID) == m_timedAchievements.end() && !IsCompletedCriteria(*i, achievement)) { // Start the timer @@ -2238,7 +1815,7 @@ template<class T> void AchievementMgr<T>::RemoveTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry) { AchievementCriteriaEntryList const& achievementCriteriaList = sAchievementMgr->GetTimedAchievementCriteriaByType(type); - for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i!=achievementCriteriaList.end(); ++i) + for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i != achievementCriteriaList.end(); ++i) { if ((*i)->timedCriteriaMiscId != entry) continue; @@ -2262,7 +1839,7 @@ void AchievementMgr<T>::CompletedAchievement(AchievementEntry const* achievement sLog->outInfo(LOG_FILTER_ACHIEVEMENTSYS, "AchievementMgr::CompletedAchievement(%u)", achievement->ID); // disable for gamemasters with GM-mode enabled - if (_owner->isGameMaster()) + if (GetOwner()->isGameMaster()) return; if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER || HasAchieved(achievement->ID)) @@ -2338,7 +1915,7 @@ void AchievementMgr<T>::CompletedAchievement(AchievementEntry const* achievement template<> void AchievementMgr<Guild>::CompletedAchievement(AchievementEntry const* achievement, Player* referencePlayer) { - sLog->outInfo(LOG_FILTER_GENERAL, "AchievementMgr<Guild>::CompletedAchievement(%u)", achievement->ID); + sLog->outDebug(LOG_FILTER_ACHIEVEMENTSYS, "AchievementMgr<Guild>::CompletedAchievement(%u)", achievement->ID); if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER || HasAchieved(achievement->ID)) return; @@ -2370,7 +1947,7 @@ struct VisibleAchievementPred { bool operator()(CompletedAchievementMap::value_type const& val) { - AchievementEntry const* achievement = sAchievementStore.LookupEntry(val.first); + AchievementEntry const* achievement = sAchievementMgr->GetAchievement(val.first); return achievement && !(achievement->flags & ACHIEVEMENT_FLAG_HIDDEN); } }; @@ -2450,7 +2027,7 @@ void AchievementMgr<T>::SendAllAchievementData(Player* /*receiver*/) const template<> void AchievementMgr<Guild>::SendAllAchievementData(Player* receiver) const { - WorldPacket data(SMSG_GUILD_ACHIEVEMENT_DATA, m_completedAchievements.size() * (4 + 4) + 4); + WorldPacket data(SMSG_GUILD_ACHIEVEMENT_DATA, m_completedAchievements.size() * (4 + 4) + 3); data.WriteBits(m_completedAchievements.size(), 23); for (CompletedAchievementMap::const_iterator itr = m_completedAchievements.begin(); itr != m_completedAchievements.end(); ++itr) { @@ -2652,22 +2229,64 @@ bool AchievementMgr<T>::HasAchieved(uint32 achievementId) const } template<class T> -bool AchievementMgr<T>::CanUpdateCriteria(AchievementCriteriaEntry const* criteria, AchievementEntry const* achievement, uint64 miscValue1, uint64 /*miscValue2*/, Unit* unit, Player* referencePlayer) +bool AchievementMgr<T>::CanUpdateCriteria(AchievementCriteriaEntry const* criteria, AchievementEntry const* achievement, uint64 miscValue1, uint64 miscValue2, Unit const* unit, Player* referencePlayer) { if (DisableMgr::IsDisabledFor(DISABLE_TYPE_ACHIEVEMENT_CRITERIA, criteria->ID, NULL)) + { + sLog->outTrace(LOG_FILTER_ACHIEVEMENTSYS, "CanUpdateCriteria: %s (Id: %u Type %s) Disabled", + criteria->name, criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type)); return false; + } if (achievement->mapID != -1 && referencePlayer->GetMapId() != uint32(achievement->mapID)) + { + sLog->outTrace(LOG_FILTER_ACHIEVEMENTSYS, "CanUpdateCriteria: %s (Id: %u Type %s) Wrong map", + criteria->name, criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type)); return false; + } + + if ((achievement->requiredFaction == ACHIEVEMENT_FACTION_HORDE && referencePlayer->GetTeam() != HORDE) || + (achievement->requiredFaction == ACHIEVEMENT_FACTION_ALLIANCE && referencePlayer->GetTeam() != ALLIANCE)) + { + sLog->outTrace(LOG_FILTER_ACHIEVEMENTSYS, "CanUpdateCriteria: %s (Id: %u Type %s) Wrong faction", + criteria->name, criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type)); + return false; + } - // don't update already completed criteria if (IsCompletedCriteria(criteria, achievement)) + { + sLog->outTrace(LOG_FILTER_ACHIEVEMENTSYS, "CanUpdateCriteria: %s (Id: %u Type %s) Is Completed", + criteria->name, criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type)); return false; + } - if ((achievement->requiredFaction == ACHIEVEMENT_FACTION_HORDE && referencePlayer->GetTeam() != HORDE) || - (achievement->requiredFaction == ACHIEVEMENT_FACTION_ALLIANCE && referencePlayer->GetTeam() != ALLIANCE)) + if (!RequirementsSatisfied(criteria, miscValue1, miscValue2, unit, referencePlayer)) + { + sLog->outTrace(LOG_FILTER_ACHIEVEMENTSYS, "CanUpdateCriteria: %s (Id: %u Type %s) Requirements not satisfied", + criteria->name, criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type)); return false; + } + if (!AdditionalRequirementsSatisfied(criteria, miscValue1, miscValue2, unit, referencePlayer)) + { + sLog->outTrace(LOG_FILTER_ACHIEVEMENTSYS, "CanUpdateCriteria: %s (Id: %u Type %s) Additional requirements not satisfied", + criteria->name, criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type)); + return false; + } + + if (!ConditionsSatisfied(criteria, referencePlayer)) + { + sLog->outTrace(LOG_FILTER_ACHIEVEMENTSYS, "CanUpdateCriteria: %s (Id: %u Type %s) Conditions not satisfied", + criteria->name, criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type)); + return false; + } + + return true; +} + +template<class T> +bool AchievementMgr<T>::ConditionsSatisfied(AchievementCriteriaEntry const *criteria, Player* referencePlayer) const +{ for (uint32 i = 0; i < MAX_CRITERIA_REQUIREMENTS; ++i) { if (!criteria->additionalRequirements[i].additionalRequirement_type) @@ -2688,128 +2307,716 @@ bool AchievementMgr<T>::CanUpdateCriteria(AchievementCriteriaEntry const* criter } } - // additional conditions - for (int8 i = 0; i < MAX_ADDITIONAL_CRITERIA_CONDITIONS; ++i) + return true; +} + +template<class T> +bool AchievementMgr<T>::RequirementsSatisfied(AchievementCriteriaEntry const *achievementCriteria, uint64 miscValue1, uint64 miscValue2, Unit const *unit, Player* referencePlayer) const +{ + switch (AchievementCriteriaTypes(achievementCriteria->type)) { - if (!criteria->additionalConditionType[i]) - continue; + case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS: + case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST: + case ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION: + case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING: + case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN: + case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS: + case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS: + case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER: + case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_MAIL: + case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS: + case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING: + case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID: + case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD: + case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED: + case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED: + case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT: + case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED: + case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL: + case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY: + case ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL: + case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD: + case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS: + case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS: + case ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED: + case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED: + case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED: + case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL: + case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED: + case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED: + case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS: + case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP: + case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL: + case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA: + case ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS: + if (!miscValue1) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT: + case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY: + case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT: + case ACHIEVEMENT_CRITERIA_TYPE_EARNED_PVP_TITLE: + case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS: + case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION: + case ACHIEVEMENT_CRITERIA_TYPE_GAIN_HONORED_REPUTATION: + case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION: + case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED: + case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING: + case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING: + case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS: + case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL: + break; + case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT: + if (m_completedAchievements.find(achievementCriteria->complete_achievement.linkedAchievement) == m_completedAchievements.end()) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG: + if (!miscValue1 || achievementCriteria->win_bg.bgMapID != referencePlayer->GetMapId()) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE: + if (!miscValue1 || achievementCriteria->kill_creature.creatureID != miscValue1) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL: + // update at loading or specific skill update + if (miscValue1 && miscValue1 != achievementCriteria->reach_skill_level.skillID) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL: + // update at loading or specific skill update + if (miscValue1 && miscValue1 != achievementCriteria->learn_skill_level.skillID) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE: + if (miscValue1 && miscValue1 != achievementCriteria->complete_quests_in_zone.zoneID) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND: + if (!miscValue1 || referencePlayer->GetMapId() != achievementCriteria->complete_battleground.mapID) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP: + if (!miscValue1 || referencePlayer->GetMapId() != achievementCriteria->death_at_map.mapID) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_DEATH: + { + if (!miscValue1) + return false; + // skip wrong arena achievements, if not achievIdByArenaSlot then normal total death counter + bool notfit = false; + for (int j = 0; j < MAX_ARENA_SLOT; ++j) + { + if (achievIdByArenaSlot[j] == achievementCriteria->achievement) + { + Battleground* bg = referencePlayer->GetBattleground(); + if (!bg || !bg->isArena() || ArenaTeam::GetSlotByType(bg->GetArenaType()) != j) + notfit = true; + break; + } + } + if (notfit) + return false; + break; + } + case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON: + { + if (!miscValue1) + return false; - uint32 value = criteria->additionalConditionValue[i]; - switch (criteria->additionalConditionType[i]) + Map const* map = referencePlayer->IsInWorld() ? referencePlayer->GetMap() : sMapMgr->FindMap(referencePlayer->GetMapId(), referencePlayer->GetInstanceId()); + if (!map || !map->IsDungeon()) + return false; + + // search case + bool found = false; + for (int j = 0; achievIdForDungeon[j][0]; ++j) + { + if (achievIdForDungeon[j][0] == achievementCriteria->achievement) + { + if (map->IsRaid()) + { + // if raid accepted (ignore difficulty) + if (!achievIdForDungeon[j][2]) + break; // for + } + else if (referencePlayer->GetDungeonDifficulty() == DUNGEON_DIFFICULTY_NORMAL) + { + // dungeon in normal mode accepted + if (!achievIdForDungeon[j][1]) + break; // for + } + else + { + // dungeon in heroic mode accepted + if (!achievIdForDungeon[j][3]) + break; // for + } + + found = true; + break; // for + } + } + if (!found) + return false; + + //FIXME: work only for instances where max == min for players + if (((InstanceMap*)map)->GetMaxPlayers() != achievementCriteria->death_in_dungeon.manLimit) + return false; + break; + } + case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE: + if (!miscValue1 || miscValue1 != achievementCriteria->killed_by_creature.creatureEntry) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER: + if (!miscValue1) + return false; + + // if team check required: must kill by opposition faction + if (achievementCriteria->achievement == 318 && miscValue2 == referencePlayer->GetTeam()) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM: + if (!miscValue1 || miscValue2 != achievementCriteria->death_from.type) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST: { - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_PLAYER: - if (!unit || !unit->ToPlayer()) + // if miscValues != 0, it contains the questID. + if (miscValue1) + { + if (miscValue1 != achievementCriteria->complete_quest.questID) return false; - break; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_DEAD: - if (!unit || unit->isAlive()) + } + else + { + // login case. + if (!referencePlayer->GetQuestRewardStatus(achievementCriteria->complete_quest.questID)) return false; - break; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_MOUNTED: - if (!unit || !unit->IsMounted()) + } + + if (AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria)) + if (!data->Meets(referencePlayer, unit)) return false; + break; + } + case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET: + case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2: + if (!miscValue1 || miscValue1 != achievementCriteria->be_spell_target.spellID) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL: + case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2: + if (!miscValue1 || miscValue1 != achievementCriteria->cast_spell.spellID) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL: + if (miscValue1 && miscValue1 != achievementCriteria->learn_spell.spellID) + return false; + + if (!referencePlayer->HasSpell(achievementCriteria->learn_spell.spellID)) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE: + // miscValue1 = loot_type (note: 0 = LOOT_CORPSE and then it ignored) + // miscValue2 = count of item loot + if (!miscValue1 || !miscValue2 || miscValue1 != achievementCriteria->loot_type.lootType) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM: + if (miscValue1 && achievementCriteria->own_item.itemID != miscValue1) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM: + if (!miscValue1 || achievementCriteria->use_item.itemID != miscValue1) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM: + if (!miscValue1 || miscValue1 != achievementCriteria->own_item.itemID) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA: + { + WorldMapOverlayEntry const* worldOverlayEntry = sWorldMapOverlayStore.LookupEntry(achievementCriteria->explore_area.areaReference); + if (!worldOverlayEntry) break; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MAP_DIFFICULTY: - if (uint32(referencePlayer->GetMap()->GetDifficulty()) != value) + + bool matchFound = false; + for (int j = 0; j < MAX_WORLD_MAP_OVERLAY_AREA_IDX; ++j) + { + uint32 area_id = worldOverlayEntry->areatableID[j]; + if (!area_id) // array have 0 only in empty tail + break; + + int32 exploreFlag = GetAreaFlagByAreaID(area_id); + if (exploreFlag < 0) + continue; + + uint32 playerIndexOffset = uint32(exploreFlag) / 32; + uint32 mask = 1 << (uint32(exploreFlag) % 32); + + if (referencePlayer->GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + playerIndexOffset) & mask) + { + matchFound = true; + break; + } + } + + if (!matchFound) + return false; + break; + } + case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION: + if (miscValue1 && miscValue1 != achievementCriteria->gain_reputation.factionID) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM: + // miscValue1 = itemid miscValue2 = itemSlot + if (!miscValue1 || miscValue2 != achievementCriteria->equip_epic_item.itemSlot) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT: + case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT: + { + // miscValue1 = itemid miscValue2 = diced value + if (!miscValue1 || miscValue2 != achievementCriteria->roll_greed_on_loot.rollValue) + return false; + + ItemTemplate const* proto = sObjectMgr->GetItemTemplate(uint32(miscValue1)); + if (!proto) + return false; + break; + } + case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE: + if (!miscValue1 || miscValue1 != achievementCriteria->do_emote.emoteID) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE: + case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE: + if (!miscValue1) + return false; + + if (achievementCriteria->additionalRequirements[0].additionalRequirement_type == ACHIEVEMENT_CRITERIA_CONDITION_BG_MAP) + { + if (referencePlayer->GetMapId() != achievementCriteria->additionalRequirements[0].additionalRequirement_value) return false; - break; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_MAP: - if (referencePlayer->GetMapId() != value) + + // map specific case (BG in fact) expected player targeted damage/heal + if (!unit || unit->GetTypeId() != TYPEID_PLAYER) + return false; + } + break; + case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM: + // miscValue1 = item_id + if (!miscValue1 || miscValue1 != achievementCriteria->equip_item.itemID) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT: + if (!miscValue1 || miscValue1 != achievementCriteria->use_gameobject.goEntry) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT: + if (!miscValue1 || miscValue1 != achievementCriteria->fish_in_gameobject.goEntry) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS: + if (miscValue1 && miscValue1 != achievementCriteria->learn_skillline_spell.skillLine) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM: + case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM: + { + if (!miscValue1) + return false; + ItemTemplate const* proto = sObjectMgr->GetItemTemplate(miscValue1); + if (!proto || proto->Quality < ITEM_QUALITY_EPIC) + return false; + break; + } + case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE: + if (miscValue1 && miscValue1 != achievementCriteria->learn_skill_line.skillLine) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS: + if (!miscValue1 || miscValue1 != achievementCriteria->hk_class.classID) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE: + if (!miscValue1 || miscValue1 != achievementCriteria->hk_race.raceID) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE: + if (!miscValue1 || miscValue1 != achievementCriteria->bg_objective.objectiveId) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA: + if (!miscValue1 || miscValue1 != achievementCriteria->honorable_kill_at_area.areaID) + return false; + break; + case ACHIEVEMENT_CRITERIA_TYPE_CURRENCY: + if (!miscValue1 || !miscValue2 || int64(miscValue2) < 0 + || miscValue1 != achievementCriteria->currencyGain.currency) + return false; + break; + default: + break; + } + return true; +} + +template<class T> +bool AchievementMgr<T>::AdditionalRequirementsSatisfied(AchievementCriteriaEntry const *criteria, uint64 miscValue1, uint64 /*miscValue2*/, Unit const* unit, Player* referencePlayer) const +{ + for (uint8 i = 0; i < MAX_ADDITIONAL_CRITERIA_CONDITIONS; ++i) + { + uint32 const reqType = criteria->additionalConditionType[i]; + uint32 const reqValue = criteria->additionalConditionValue[i]; + + switch (AchievementCriteriaAdditionalCondition(reqType)) + { + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CREATURE_ENTRY: // 4 + if (!unit || unit->GetEntry() != reqValue) return false; break; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_ZONE: - if (referencePlayer->GetZoneId() != value) + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_PLAYER: // 5 + if (!unit || unit->GetTypeId() != TYPEID_PLAYER) return false; break; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_AREA: - if (referencePlayer->GetAreaId() != value) + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_DEAD: // 6 + if (!unit || unit->isAlive()) return false; break; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_ENEMY: + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_ENEMY: // 7 if (!unit) return false; if (const Player* player = unit->ToPlayer()) if (player->GetTeam() == referencePlayer->GetTeam()) return false; break; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CREATURE_ENTRY: - if (!unit || !unit->ToCreature()) + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_HAS_AURA: // 8 + if (!referencePlayer->HasAura(reqValue)) + return false; + break; + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_HAS_AURA: // 10 + if (!unit || !unit->HasAura(reqValue)) return false; - if (unit->ToCreature()->GetEntry() != value) + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_MOUNTED: // 11 + if (!unit || !unit->IsMounted()) return false; break; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_HAS_AURA: - if (!referencePlayer->HasAura(value)) + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_QUALITY_MIN: // 14 + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_QUALITY_EQUALS: // 15 + { + // miscValue1 is itemid + ItemTemplate const * const item = sObjectMgr->GetItemTemplate(uint32(miscValue1)); + if (!item || item->Quality < reqValue) return false; break; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_HAS_AURA: - if (!unit || !unit->HasAura(value)) + } + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MAP_DIFFICULTY: // 20 + if (uint32(referencePlayer->GetMap()->GetDifficulty()) != reqValue) return false; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_QUALITY_MIN: - if (ItemTemplate const * itemProto = sObjectMgr->GetItemTemplate(miscValue1)) - if (itemProto->Quality < value) - return false; break; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_QUALITY_EQUALS: - if (ItemTemplate const * itemProto = sObjectMgr->GetItemTemplate(miscValue1)) - if (itemProto->Quality < value) - return false; + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_MAP: // 32 + if (referencePlayer->GetMapId() != reqValue) + return false; break; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_RACE: - if (referencePlayer->getRace() != value) + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_ZONE: // 18 + if (referencePlayer->GetZoneId() != reqValue) return false; break; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_CLASS: - if (referencePlayer->getClass() != value) + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_AREA: // 17 + if (referencePlayer->GetAreaId() != reqValue) return false; break; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_RACE: - if (!unit || !unit->ToPlayer()) - break; - if (unit->ToPlayer()->getRace() != value) + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_RACE: // 25 + if (referencePlayer->getRace() != reqValue) return false; break; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CLASS: - if (!unit || !unit->ToPlayer()) - break; - if (unit->ToPlayer()->getClass() != value) + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_CLASS: // 26 + if (referencePlayer->getClass() != reqValue) + return false; + break; + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_RACE: // 27 + if (!unit || unit->GetTypeId() != TYPEID_PLAYER || unit->getRace() != reqValue) + return false; + break; + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CLASS: // 28 + if (!unit || unit->GetTypeId() != TYPEID_PLAYER || unit->getClass() != reqValue) return false; break; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MAX_GROUP_MEMBERS: - if (referencePlayer->GetGroup() && referencePlayer->GetGroup()->GetMembersCount() >= value) + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MAX_GROUP_MEMBERS: // 29 + if (referencePlayer->GetGroup() && referencePlayer->GetGroup()->GetMembersCount() >= reqValue) return false; break; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CREATURE_TYPE: - if (!unit || !unit->ToCreature()) + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CREATURE_TYPE: // 30 + { + if (!unit) return false; - if (unit->ToCreature()->GetCreatureType() != value) + Creature const * const creature = unit->ToCreature(); + if (!creature || creature->GetCreatureType() != reqValue) return false; break; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_LEVEL: - if (referencePlayer->getLevel() != value) + } + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TITLE_BIT_INDEX: // 38 + // miscValue1 is title's bit index + if (miscValue1 != reqValue) return false; break; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_LEVEL: - if (!unit || unit->getLevel() != value) + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_LEVEL: // 39 + if (referencePlayer->getLevel() != reqValue) return false; break; - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_HEALTH_PERCENT_BELOW: - if (!unit || unit->GetHealthPct() >= value) + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_LEVEL: // 40 + if (!unit || unit->getLevel() != reqValue) return false; break; - // generic, compare miscValue1 with DBC value - case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TITLE_BIT_INDEX: - if (miscValue1 != value) + case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_HEALTH_PERCENT_BELOW: // 46 + if (!unit || unit->GetHealthPct() >= reqValue) return false; break; default: break; } } - return true; } +char const* AchievementGlobalMgr::GetCriteriaTypeString(uint32 type) +{ + return GetCriteriaTypeString(AchievementCriteriaTypes(type)); +} + +char const* AchievementGlobalMgr::GetCriteriaTypeString(AchievementCriteriaTypes type) +{ + switch (type) + { + case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE: + return "KILL_CREATURE"; + case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG: + return "TYPE_WIN_BG"; + case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ARCHAEOLOGY_PROJECTS: + return "COMPLETE_RESEARCH"; + case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL: + return "REACH_LEVEL"; + case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL: + return "REACH_SKILL_LEVEL"; + case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT: + return "COMPLETE_ACHIEVEMENT"; + case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT: + return "COMPLETE_QUEST_COUNT"; + case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY: + return "COMPLETE_DAILY_QUEST_DAILY"; + case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE: + return "COMPLETE_QUESTS_IN_ZONE"; + case ACHIEVEMENT_CRITERIA_TYPE_CURRENCY: + return "CURRENCY"; + case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE: + return "DAMAGE_DONE"; + case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST: + return "COMPLETE_DAILY_QUEST"; + case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND: + return "COMPLETE_BATTLEGROUND"; + case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP: + return "DEATH_AT_MAP"; + case ACHIEVEMENT_CRITERIA_TYPE_DEATH: + return "DEATH"; + case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON: + return "DEATH_IN_DUNGEON"; + case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_RAID: + return "COMPLETE_RAID"; + case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE: + return "KILLED_BY_CREATURE"; + case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER: + return "KILLED_BY_PLAYER"; + case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING: + return "FALL_WITHOUT_DYING"; + case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM: + return "DEATHS_FROM"; + case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST: + return "COMPLETE_QUEST"; + case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET: + return "BE_SPELL_TARGET"; + case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL: + return "CAST_SPELL"; + case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE: + return "BG_OBJECTIVE_CAPTURE"; + case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA: + return "HONORABLE_KILL_AT_AREA"; + case ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA: + return "WIN_ARENA"; + case ACHIEVEMENT_CRITERIA_TYPE_PLAY_ARENA: + return "PLAY_ARENA"; + case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL: + return "LEARN_SPELL"; + case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL: + return "HONORABLE_KILL"; + case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM: + return "OWN_ITEM"; + case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA: + return "WIN_RATED_ARENA"; + case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING: + return "HIGHEST_TEAM_RATING"; + case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING: + return "HIGHEST_PERSONAL_RATING"; + case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL: + return "LEARN_SKILL_LEVEL"; + case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM: + return "USE_ITEM"; + case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM: + return "LOOT_ITEM"; + case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA: + return "EXPLORE_AREA"; + case ACHIEVEMENT_CRITERIA_TYPE_OWN_RANK: + return "OWN_RANK"; + case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT: + return "BUY_BANK_SLOT"; + case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION: + return "GAIN_REPUTATION"; + case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION: + return "GAIN_EXALTED_REPUTATION"; + case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP: + return "VISIT_BARBER_SHOP"; + case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM: + return "EQUIP_EPIC_ITEM"; + case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT: + return "ROLL_NEED_ON_LOOT"; + case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT: + return "GREED_ON_LOOT"; + case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS: + return "HK_CLASS"; + case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE: + return "HK_RACE"; + case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE: + return "DO_EMOTE"; + case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE: + return "HEALING_DONE"; + case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS: + return "GET_KILLING_BLOWS"; + case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM: + return "EQUIP_ITEM"; + case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS: + return "MONEY_FROM_VENDORS"; + case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS: + return "GOLD_SPENT_FOR_TALENTS"; + case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS: + return "NUMBER_OF_TALENT_RESETS"; + case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD: + return "MONEY_FROM_QUEST_REWARD"; + case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING: + return "GOLD_SPENT_FOR_TRAVELLING"; + case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER: + return "GOLD_SPENT_AT_BARBER"; + case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_MAIL: + return "GOLD_SPENT_FOR_MAIL"; + case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY: + return "LOOT_MONEY"; + case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT: + return "USE_GAMEOBJECT"; + case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2: + return "BE_SPELL_TARGET2"; + case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL: + return "SPECIAL_PVP_KILL"; + case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT: + return "FISH_IN_GAMEOBJECT"; + case ACHIEVEMENT_CRITERIA_TYPE_EARNED_PVP_TITLE: + return "EARNED_PVP_TITLE"; + case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS: + return "LEARN_SKILLLINE_SPELLS"; + case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL: + return "WIN_DUEL"; + case ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL: + return "LOSE_DUEL"; + case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE: + return "KILL_CREATURE_TYPE"; + case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS: + return "GOLD_EARNED_BY_AUCTIONS"; + case ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION: + return "CREATE_AUCTION"; + case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID: + return "HIGHEST_AUCTION_BID"; + case ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS: + return "WON_AUCTIONS"; + case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD: + return "HIGHEST_AUCTION_SOLD"; + case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED: + return "HIGHEST_GOLD_VALUE_OWNED"; + case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION: + return "GAIN_REVERED_REPUTATION"; + case ACHIEVEMENT_CRITERIA_TYPE_GAIN_HONORED_REPUTATION: + return "GAIN_HONORED_REPUTATION"; + case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS: + return "KNOWN_FACTIONS"; + case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM: + return "LOOT_EPIC_ITEM"; + case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM: + return "RECEIVE_EPIC_ITEM"; + case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED: + return "ROLL_NEED"; + case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED: + return "ROLL_GREED"; + case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT: + return "HIT_DEALT"; + case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED: + return "HIT_RECEIVED"; + case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED: + return "TOTAL_DAMAGE_RECEIVED"; + case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED: + return "HIGHEST_HEAL_CASTED"; + case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED: + return "TOTAL_HEALING_RECEIVED"; + case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED: + return "HIGHEST_HEALING_RECEIVED"; + case ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED: + return "QUEST_ABANDONED"; + case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN: + return "FLIGHT_PATHS_TAKEN"; + case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE: + return "LOOT_TYPE"; + case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2: + return "CAST_SPELL2"; + case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE: + return "LEARN_SKILL_LINE"; + case ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL: + return "EARN_HONORABLE_KILL"; + case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS: + return "ACCEPTED_SUMMONINGS"; + case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS: + return "EARN_ACHIEVEMENT_POINTS"; + case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS: + return "USE_LFD_TO_GROUP_WITH_PLAYERS"; + case ACHIEVEMENT_CRITERIA_TYPE_SPENT_GOLD_GUILD_REPAIRS: + return "SPENT_GOLD_GUILD_REPAIRS"; + case ACHIEVEMENT_CRITERIA_TYPE_REACH_GUILD_LEVEL: + return "REACH_GUILD_LEVEL"; + case ACHIEVEMENT_CRITERIA_TYPE_CRAFT_ITEMS_GUILD: + return "CRAFT_ITEMS_GUILD"; + case ACHIEVEMENT_CRITERIA_TYPE_CATCH_FROM_POOL: + return "CATCH_FROM_POOL"; + case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_BANK_SLOTS: + return "BUY_GUILD_BANK_SLOTS"; + case ACHIEVEMENT_CRITERIA_TYPE_EARN_GUILD_ACHIEVEMENT_POINTS: + return "EARN_GUILD_ACHIEVEMENT_POINTS"; + case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_BATTLEGROUND: + return "WIN_RATED_BATTLEGROUND"; + case ACHIEVEMENT_CRITERIA_TYPE_REACH_BG_RATING: + return "REACH_BG_RATING"; + case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_TABARD: + return "BUY_GUILD_TABARD"; + case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_GUILD: + return "COMPLETE_QUESTS_GUILD"; + case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILLS_GUILD: + return "HONORABLE_KILLS_GUILD"; + case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE_GUILD: + return "KILL_CREATURE_TYPE_GUILD"; + default: + return "MISSING_TYPE"; + } + return ""; +} + template class AchievementMgr<Guild>; template class AchievementMgr<Player>; @@ -2828,18 +3035,18 @@ void AchievementGlobalMgr::LoadAchievementCriteriaList() uint32 guildCriterias = 0; for (uint32 entryId = 0; entryId < sAchievementCriteriaStore.GetNumRows(); ++entryId) { - AchievementCriteriaEntry const* criteria = sAchievementCriteriaStore.LookupEntry(entryId); + AchievementCriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(entryId); if (!criteria) continue; - AchievementEntry const* achievement = sAchievementStore.LookupEntry(criteria->referredAchievement); + AchievementEntry const* achievement = sAchievementMgr->GetAchievement(criteria->achievement); - m_AchievementCriteriaListByAchievement[criteria->referredAchievement].push_back(criteria); + m_AchievementCriteriaListByAchievement[criteria->achievement].push_back(criteria); if (achievement && achievement->flags & ACHIEVEMENT_FLAG_GUILD) - ++guildCriterias, m_GuildAchievementCriteriasByType[criteria->requiredType].push_back(criteria); + ++guildCriterias, m_GuildAchievementCriteriasByType[criteria->type].push_back(criteria); else - ++criterias, m_AchievementCriteriasByType[criteria->requiredType].push_back(criteria); + ++criterias, m_AchievementCriteriasByType[criteria->type].push_back(criteria); if (criteria->timeLimit) m_AchievementCriteriasByTimedType[criteria->timedCriteriaStartType].push_back(criteria); @@ -2862,7 +3069,7 @@ void AchievementGlobalMgr::LoadAchievementReferenceList() for (uint32 entryId = 0; entryId < sAchievementStore.GetNumRows(); ++entryId) { - AchievementEntry const* achievement = sAchievementStore.LookupEntry(entryId); + AchievementEntry const* achievement = sAchievementMgr->GetAchievement(entryId); if (!achievement || !achievement->refAchievement) continue; @@ -2871,7 +3078,7 @@ void AchievementGlobalMgr::LoadAchievementReferenceList() } // Once Bitten, Twice Shy (10 player) - Icecrown Citadel - if (AchievementEntry const* achievement = sAchievementStore.LookupEntry(4539)) + if (AchievementEntry const* achievement = sAchievementMgr->GetAchievement(4539)) const_cast<AchievementEntry*>(achievement)->mapID = 631; // Correct map requirement (currently has Ulduar) sLog->outInfo(LOG_FILTER_SERVER_LOADING, ">> Loaded %u achievement references in %u ms", count, GetMSTimeDiffToNow(oldMSTime)); @@ -2898,7 +3105,7 @@ void AchievementGlobalMgr::LoadAchievementCriteriaData() Field* fields = result->Fetch(); uint32 criteria_id = fields[0].GetUInt32(); - AchievementCriteriaEntry const* criteria = sAchievementCriteriaStore.LookupEntry(criteria_id); + AchievementCriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(criteria_id); if (!criteria) { @@ -2955,7 +3162,7 @@ void AchievementGlobalMgr::LoadCompletedAchievements() Field* fields = result->Fetch(); uint16 achievementId = fields[0].GetUInt16(); - const AchievementEntry* achievement = sAchievementStore.LookupEntry(achievementId); + const AchievementEntry* achievement = sAchievementMgr->GetAchievement(achievementId); if (!achievement) { // Remove non existent achievements from all characters @@ -2971,7 +3178,8 @@ void AchievementGlobalMgr::LoadCompletedAchievements() } else if (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_REACH | ACHIEVEMENT_FLAG_REALM_FIRST_KILL)) m_allCompletedAchievements.insert(achievementId); - } while (result->NextRow()); + } + while (result->NextRow()); sLog->outInfo(LOG_FILTER_SERVER_LOADING, ">> Loaded %lu completed achievements in %u ms", (unsigned long)m_allCompletedAchievements.size(), GetMSTimeDiffToNow(oldMSTime)); } @@ -2982,7 +3190,7 @@ void AchievementGlobalMgr::LoadRewards() m_achievementRewards.clear(); // need for reload case - // 0 1 2 3 4 5 6 + // 0 1 2 3 4 5 6 QueryResult result = WorldDatabase.Query("SELECT entry, title_A, title_H, item, sender, subject, text FROM achievement_reward"); if (!result) @@ -2997,10 +3205,10 @@ void AchievementGlobalMgr::LoadRewards() { Field* fields = result->Fetch(); uint32 entry = fields[0].GetUInt32(); - const AchievementEntry* pAchievement = sAchievementStore.LookupEntry(entry); + const AchievementEntry* pAchievement = GetAchievement(entry); if (!pAchievement) { - sLog->outError(LOG_FILTER_SQL, "Table `achievement_reward` has wrong achievement (Entry: %u), ignore", entry); + sLog->outError(LOG_FILTER_SQL, "Table `achievement_reward` has wrong achievement (Entry: %u), ignored.", entry); continue; } @@ -3015,7 +3223,7 @@ void AchievementGlobalMgr::LoadRewards() // must be title or mail at least if (!reward.titleId[0] && !reward.titleId[1] && !reward.sender) { - sLog->outError(LOG_FILTER_SQL, "Table `achievement_reward` (Entry: %u) not have title or item reward data, ignore.", entry); + sLog->outError(LOG_FILTER_SQL, "Table `achievement_reward` (Entry: %u) does not have title or item reward data, ignored.", entry); continue; } @@ -3074,7 +3282,6 @@ void AchievementGlobalMgr::LoadRewards() m_achievementRewards[entry] = reward; ++count; - } while (result->NextRow()); @@ -3117,7 +3324,18 @@ void AchievementGlobalMgr::LoadRewardLocales() ObjectMgr::AddLocaleString(fields[1 + 2 * (i - 1)].GetString(), locale, data.subject); ObjectMgr::AddLocaleString(fields[1 + 2 * (i - 1) + 1].GetString(), locale, data.text); } - } while (result->NextRow()); + } + while (result->NextRow()); sLog->outInfo(LOG_FILTER_SERVER_LOADING, ">> Loaded %lu achievement reward locale strings in %u ms", (unsigned long)m_achievementRewardLocales.size(), GetMSTimeDiffToNow(oldMSTime)); } + +AchievementEntry const* AchievementGlobalMgr::GetAchievement(uint32 achievementId) const +{ + return sAchievementStore.LookupEntry(achievementId); +} + +AchievementCriteriaEntry const* AchievementGlobalMgr::GetAchievementCriteria(uint32 criteriaId) const +{ + return sAchievementCriteriaStore.LookupEntry(criteriaId); +} diff --git a/src/server/game/Achievements/AchievementMgr.h b/src/server/game/Achievements/AchievementMgr.h index bcedbd09901..4196f6728fe 100755 --- a/src/server/game/Achievements/AchievementMgr.h +++ b/src/server/game/Achievements/AchievementMgr.h @@ -15,6 +15,7 @@ * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ + #ifndef __TRINITY_ACHIEVEMENTMGR_H #define __TRINITY_ACHIEVEMENTMGR_H @@ -67,6 +68,7 @@ enum AchievementCriteriaDataType #define MAX_ACHIEVEMENT_CRITERIA_DATA_TYPE 22 // maximum value in AchievementCriteriaDataType enum class Player; class Unit; +class WorldPacket; struct AchievementCriteriaData { @@ -217,10 +219,6 @@ struct CompletedAchievementData typedef UNORDERED_MAP<uint32, CriteriaProgress> CriteriaProgressMap; typedef UNORDERED_MAP<uint32, CompletedAchievementData> CompletedAchievementMap; -class Unit; -class Player; -class WorldPacket; - template<class T> class AchievementMgr { @@ -232,8 +230,8 @@ class AchievementMgr static void DeleteFromDB(uint32 lowguid); void LoadFromDB(PreparedQueryResult achievementResult, PreparedQueryResult criteriaResult); void SaveToDB(SQLTransaction& trans); - void ResetAchievementCriteria(AchievementCriteriaTypes type, uint32 miscvalue1 = 0, uint32 miscvalue2 = 0, bool evenIfCriteriaComplete = false); - void UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 = 0, uint32 miscValue2 = 0, Unit* unit = NULL, Player* referencePlayer = NULL); + void ResetAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 = 0, uint32 miscValue2 = 0, bool evenIfCriteriaComplete = false); + void UpdateAchievementCriteria(AchievementCriteriaTypes type, uint32 miscValue1 = 0, uint32 miscValue2 = 0, Unit const* unit = NULL, Player* referencePlayer = NULL); void CompletedAchievement(AchievementEntry const* entry, Player* referencePlayer); void CheckAllAchievementCriteria(Player* referencePlayer); void SendAllAchievementData(Player* receiver) const; @@ -255,9 +253,13 @@ class AchievementMgr void CompletedCriteriaFor(AchievementEntry const* achievement, Player* referencePlayer); bool IsCompletedCriteria(AchievementCriteriaEntry const* achievementCriteria, AchievementEntry const* achievement); bool IsCompletedAchievement(AchievementEntry const* entry); - bool CanUpdateCriteria(AchievementCriteriaEntry const* criteria, AchievementEntry const* achievement, uint64 miscValue1, uint64 miscValue2, Unit* unit, Player* referencePlayer); + bool CanUpdateCriteria(AchievementCriteriaEntry const* criteria, AchievementEntry const* achievement, uint64 miscValue1, uint64 miscValue2, Unit const* unit, Player* referencePlayer); void SendPacket(WorldPacket* data) const; + bool ConditionsSatisfied(AchievementCriteriaEntry const *criteria, Player* referencePlayer) const; + bool RequirementsSatisfied(AchievementCriteriaEntry const *criteria, uint64 miscValue1, uint64 miscValue2, Unit const* unit, Player* referencePlayer) const; + bool AdditionalRequirementsSatisfied(AchievementCriteriaEntry const* criteria, uint64 miscValue1, uint64 miscValue2, Unit const* unit, Player* referencePlayer) const; + T* _owner; CriteriaProgressMap m_criteriaProgress; CompletedAchievementMap m_completedAchievements; @@ -272,6 +274,9 @@ class AchievementGlobalMgr ~AchievementGlobalMgr() {} public: + static char const* GetCriteriaTypeString(AchievementCriteriaTypes type); + static char const* GetCriteriaTypeString(uint32 type); + AchievementCriteriaEntryList const& GetAchievementCriteriaByType(AchievementCriteriaTypes type, bool guild = false) const { return guild ? m_GuildAchievementCriteriasByType[type] : m_AchievementCriteriasByType[type]; @@ -346,6 +351,8 @@ class AchievementGlobalMgr void LoadCompletedAchievements(); void LoadRewards(); void LoadRewardLocales(); + AchievementEntry const* GetAchievement(uint32 achievementId) const; + AchievementCriteriaEntry const* GetAchievementCriteria(uint32 achievementId) const; private: AchievementCriteriaDataMap m_criteriaDataMap; diff --git a/src/server/game/Addons/AddonMgr.h b/src/server/game/Addons/AddonMgr.h index 38338b3980f..fd227b258c5 100755 --- a/src/server/game/Addons/AddonMgr.h +++ b/src/server/game/Addons/AddonMgr.h @@ -25,13 +25,7 @@ struct AddonInfo { AddonInfo(const std::string& name, uint8 enabled, uint32 crc, uint8 state, bool crcOrPubKey) - { - Name = name; - Enabled = enabled; - CRC = crc; - State = state; - UsePublicKeyOrCRC = crcOrPubKey; - } + : Name(name), Enabled(enabled), CRC(crc), State(state), UsePublicKeyOrCRC(crcOrPubKey) {} std::string Name; uint8 Enabled; diff --git a/src/server/game/Battlefield/Battlefield.cpp b/src/server/game/Battlefield/Battlefield.cpp index 99852f14277..ee976e0f704 100644 --- a/src/server/game/Battlefield/Battlefield.cpp +++ b/src/server/game/Battlefield/Battlefield.cpp @@ -34,6 +34,8 @@ Battlefield::Battlefield() { + m_Guid = MAKE_NEW_GUID(m_TypeId, 0, HIGHGUID_TYPE_BATTLEGROUND); + m_Timer = 0; m_IsEnabled = true; m_isActive = false; @@ -100,7 +102,7 @@ void Battlefield::HandlePlayerLeaveZone(Player* player, uint32 /*zone*/) if (m_PlayersInWar[player->GetTeamId()].find(player->GetGUID()) != m_PlayersInWar[player->GetTeamId()].end()) { m_PlayersInWar[player->GetTeamId()].erase(player->GetGUID()); - player->GetSession()->SendBfLeaveMessage(m_BattleId); + player->GetSession()->SendBfLeaveMessage(m_Guid); if (Group* group = player->GetGroup()) // Remove the player from the raid group group->RemoveMember(player->GetGUID()); @@ -133,7 +135,7 @@ bool Battlefield::Update(uint32 diff) m_Timer -= diff; // Invite players a few minutes before the battle's beginning - if (!m_StartGrouping && m_Timer <= m_StartGroupingTimer) + if (!IsWarTime() && !m_StartGrouping && m_Timer <= m_StartGroupingTimer) { m_StartGrouping = true; InvitePlayersInZoneToQueue(); @@ -155,13 +157,13 @@ bool Battlefield::Update(uint32 diff) if (m_uiKickDontAcceptTimer <= diff) { for (int team = 0; team < 2; team++) - for (PlayerTimerMap::iterator itr = m_InvitedPlayers[team].begin(); itr != m_InvitedPlayers[team].end(); itr++) + for (PlayerTimerMap::iterator itr = m_InvitedPlayers[team].begin(); itr != m_InvitedPlayers[team].end(); ++itr) if ((*itr).second <= time(NULL)) KickPlayerFromBattlefield((*itr).first); InvitePlayersInZoneToWar(); for (int team = 0; team < 2; team++) - for (PlayerTimerMap::iterator itr = m_PlayersWillBeKick[team].begin(); itr != m_PlayersWillBeKick[team].end(); itr++) + for (PlayerTimerMap::iterator itr = m_PlayersWillBeKick[team].begin(); itr != m_PlayersWillBeKick[team].end(); ++itr) if ((*itr).second <= time(NULL)) KickPlayerFromBattlefield((*itr).first); @@ -203,7 +205,7 @@ void Battlefield::InvitePlayerToQueue(Player* player) return; if (m_PlayersInQueue[player->GetTeamId()].size() <= m_MinPlayer || m_PlayersInQueue[GetOtherTeam(player->GetTeamId())].size() >= m_MinPlayer) - player->GetSession()->SendBfInvitePlayerToQueue(m_BattleId); + player->GetSession()->SendBfInvitePlayerToQueue(m_Guid); } void Battlefield::InvitePlayersInQueueToWar() @@ -272,7 +274,7 @@ void Battlefield::InvitePlayerToWar(Player* player) m_PlayersWillBeKick[player->GetTeamId()].erase(player->GetGUID()); m_InvitedPlayers[player->GetTeamId()][player->GetGUID()] = time(NULL) + m_TimeForAcceptInvite; - player->GetSession()->SendBfInvitePlayerToWar(m_BattleId, m_ZoneId, m_TimeForAcceptInvite); + player->GetSession()->SendBfInvitePlayerToWar(m_Guid, m_ZoneId, m_TimeForAcceptInvite); } void Battlefield::InitStalker(uint32 entry, float x, float y, float z, float o) @@ -368,7 +370,7 @@ void Battlefield::PlayerAcceptInviteToQueue(Player* player) // Add player in queue m_PlayersInQueue[player->GetTeamId()].insert(player->GetGUID()); // Send notification - player->GetSession()->SendBfQueueInviteResponse(m_BattleId, m_ZoneId); + player->GetSession()->SendBfQueueInviteResponse(m_Guid, m_ZoneId); } // Called in WorldSession::HandleBfExitRequest @@ -386,7 +388,7 @@ void Battlefield::PlayerAcceptInviteToWar(Player* player) if (AddOrSetPlayerToCorrectBfGroup(player)) { - player->GetSession()->SendBfEntered(m_BattleId); + player->GetSession()->SendBfEntered(m_Guid); m_PlayersInWar[player->GetTeamId()].insert(player->GetGUID()); m_InvitedPlayers[player->GetTeamId()].erase(player->GetGUID()); @@ -862,7 +864,8 @@ BfCapturePoint::BfCapturePoint(Battlefield* battlefield) : m_Bf(battlefield), m_ { m_team = TEAM_NEUTRAL; m_value = 0; - m_maxValue = 0; + m_minValue = 0.0f; + m_maxValue = 0.0f; m_State = BF_CAPTUREPOINT_OBJECTIVESTATE_NEUTRAL; m_OldState = BF_CAPTUREPOINT_OBJECTIVESTATE_NEUTRAL; m_capturePointEntry = 0; diff --git a/src/server/game/Battlefield/Battlefield.h b/src/server/game/Battlefield/Battlefield.h index 07daf33d431..175bb039744 100644 --- a/src/server/game/Battlefield/Battlefield.h +++ b/src/server/game/Battlefield/Battlefield.h @@ -239,6 +239,7 @@ class Battlefield : public ZoneScript uint32 GetTypeId() { return m_TypeId; } uint32 GetZoneId() { return m_ZoneId; } + uint64 GetGUID() { return m_Guid; } void TeamApplyBuff(TeamId team, uint32 spellId, uint32 spellId2 = 0); @@ -357,6 +358,8 @@ class Battlefield : public ZoneScript void InitStalker(uint32 entry, float x, float y, float z, float o); protected: + uint64 m_Guid; + uint64 StalkerGuid; uint32 m_Timer; // Global timer for event bool m_IsEnabled; diff --git a/src/server/game/Battlefield/BattlefieldHandler.cpp b/src/server/game/Battlefield/BattlefieldHandler.cpp index b852082d582..f16237b6e31 100644 --- a/src/server/game/Battlefield/BattlefieldHandler.cpp +++ b/src/server/game/Battlefield/BattlefieldHandler.cpp @@ -21,130 +21,298 @@ #include "ObjectMgr.h" #include "WorldPacket.h" #include "WorldSession.h" +#include "Object.h" #include "Battlefield.h" #include "BattlefieldMgr.h" #include "Opcodes.h" //This send to player windows for invite player to join the war -//Param1:(BattleId) the BattleId of Bf +//Param1:(guid) the guid of Bf //Param2:(ZoneId) the zone where the battle is (4197 for wg) //Param3:(time) Time in second that the player have for accept -void WorldSession::SendBfInvitePlayerToWar(uint32 BattleId, uint32 ZoneId, uint32 p_time) +void WorldSession::SendBfInvitePlayerToWar(uint64 guid, uint32 zoneId, uint32 pTime) { - //Send packet - WorldPacket data(SMSG_BATTLEFIELD_MGR_ENTRY_INVITE, 12); - data << uint32(BattleId); - data << uint32(ZoneId); - data << uint32((time(NULL) + p_time)); + ObjectGuid guidBytes = guid; + + WorldPacket data(SMSG_BATTLEFIELD_MGR_ENTRY_INVITE, 16); + + data.WriteBit(guidBytes[5]); + data.WriteBit(guidBytes[3]); + data.WriteBit(guidBytes[7]); + data.WriteBit(guidBytes[2]); + data.WriteBit(guidBytes[6]); + data.WriteBit(guidBytes[4]); + data.WriteBit(guidBytes[1]); + data.WriteBit(guidBytes[0]); + + data.WriteByteSeq(guidBytes[6]); + data << uint32(zoneId); // Zone Id + data.WriteByteSeq(guidBytes[1]); + data.WriteByteSeq(guidBytes[3]); + data.WriteByteSeq(guidBytes[4]); + data.WriteByteSeq(guidBytes[2]); + data.WriteByteSeq(guidBytes[0]); + data << uint32(time(NULL) + pTime); // Invite lasts until + data.WriteByteSeq(guidBytes[7]); + data.WriteByteSeq(guidBytes[5]); //Sending the packet to player SendPacket(&data); } //This send invitation to player to join the queue -//Param1:(BattleId) the BattleId of Bf -void WorldSession::SendBfInvitePlayerToQueue(uint32 BattleId) +void WorldSession::SendBfInvitePlayerToQueue(uint64 guid) { + ObjectGuid guidBytes = guid; + WorldPacket data(SMSG_BATTLEFIELD_MGR_QUEUE_INVITE, 5); - data << uint32(BattleId); - data << uint8(1); //warmup ? used ? + data.WriteBit(1); // unk + data.WriteBit(0); // Has Warmup + data.WriteBit(1); // unk + data.WriteBit(guidBytes[0]); + data.WriteBit(1); // unk + data.WriteBit(guidBytes[2]); + data.WriteBit(guidBytes[6]); + data.WriteBit(guidBytes[3]); + data.WriteBit(1); // unk + data.WriteBit(0); // unk + data.WriteBit(guidBytes[1]); + data.WriteBit(guidBytes[5]); + data.WriteBit(guidBytes[4]); + data.WriteBit(1); // unk + data.WriteBit(guidBytes[7]); + + data.FlushBits(); + + data.WriteByteSeq(guidBytes[2]); + data.WriteByteSeq(guidBytes[3]); + data.WriteByteSeq(guidBytes[6]); + data << uint8(1); // Warmup + data.WriteByteSeq(guidBytes[5]); + data.WriteByteSeq(guidBytes[0]); + data.WriteByteSeq(guidBytes[4]); + data.WriteByteSeq(guidBytes[1]); + data.WriteByteSeq(guidBytes[7]); //Sending packet to player SendPacket(&data); } //This send packet for inform player that he join queue -//Param1:(BattleId) the BattleId of Bf +//Param1:(guid) the guid of Bf //Param2:(ZoneId) the zone where the battle is (4197 for wg) //Param3:(CanQueue) if able to queue //Param4:(Full) on log in is full -void WorldSession::SendBfQueueInviteResponse(uint32 BattleId,uint32 ZoneId, bool CanQueue, bool Full) +void WorldSession::SendBfQueueInviteResponse(uint64 guid, uint32 ZoneId, bool CanQueue, bool Full) { - WorldPacket data(SMSG_BATTLEFIELD_MGR_QUEUE_REQUEST_RESPONSE, 11); - data << uint32(BattleId); + const bool hasSecondGuid = false; + const bool warmup = true; + ObjectGuid guidBytes = guid; + + WorldPacket data(SMSG_BATTLEFIELD_MGR_QUEUE_REQUEST_RESPONSE, 16); + + data.WriteBit(guidBytes[1]); + data.WriteBit(guidBytes[6]); + data.WriteBit(guidBytes[5]); + data.WriteBit(guidBytes[7]); + data.WriteBit(Full); // Logging In, VERIFYME + data.WriteBit(guidBytes[0]); + data.WriteBit(!hasSecondGuid); + data.WriteBit(guidBytes[4]); + + // if (hasSecondGuid) 7 3 0 4 2 6 1 5 + + data.WriteBit(guidBytes[3]); + data.WriteBit(guidBytes[2]); + + // if (hasSecondGuid) 2 5 3 0 4 6 1 7 + + data.FlushBits(); + + data << uint8(CanQueue); // Accepted + + data.WriteByteSeq(guidBytes[1]); + data.WriteByteSeq(guidBytes[3]); + data.WriteByteSeq(guidBytes[6]); + data.WriteByteSeq(guidBytes[7]); + data.WriteByteSeq(guidBytes[0]); + + data << uint8(warmup); + + data.WriteByteSeq(guidBytes[2]); + data.WriteByteSeq(guidBytes[4]); + data.WriteByteSeq(guidBytes[5]); + data << uint32(ZoneId); - data << uint8((CanQueue ? 1 : 0)); //Accepted //0 you cannot queue wg //1 you are queued - data << uint8((Full ? 0 : 1)); //Logging In //0 wg full //1 queue for upcoming - data << uint8(1); //Warmup + SendPacket(&data); } //This is call when player accept to join war -//Param1:(BattleId) the BattleId of Bf -void WorldSession::SendBfEntered(uint32 BattleId) +void WorldSession::SendBfEntered(uint64 guid) { -// m_PlayerInWar[player->GetTeamId()].insert(player->GetGUID()); - WorldPacket data(SMSG_BATTLEFIELD_MGR_ENTERED, 7); - data << uint32(BattleId); - data << uint8(1); //unk - data << uint8(1); //unk - data << uint8(_player->isAFK() ? 1 : 0); //Clear AFK + uint8 isAFK = _player->isAFK() ? 1 : 0; + ObjectGuid guidBytes = guid; + + WorldPacket data(SMSG_BATTLEFIELD_MGR_ENTERED, 11); + + data.WriteBit(0); // unk + data.WriteBit(isAFK); // Clear AFK + data.WriteBit(guidBytes[1]); + data.WriteBit(guidBytes[4]); + data.WriteBit(guidBytes[5]); + data.WriteBit(guidBytes[0]); + data.WriteBit(guidBytes[3]); + data.WriteBit(0); // unk + data.WriteBit(guidBytes[6]); + data.WriteBit(guidBytes[7]); + data.WriteBit(guidBytes[2]); + + data.FlushBits(); + + data.WriteByteSeq(guidBytes[5]); + data.WriteByteSeq(guidBytes[3]); + data.WriteByteSeq(guidBytes[0]); + data.WriteByteSeq(guidBytes[4]); + data.WriteByteSeq(guidBytes[1]); + data.WriteByteSeq(guidBytes[7]); + data.WriteByteSeq(guidBytes[2]); + data.WriteByteSeq(guidBytes[6]); + SendPacket(&data); } -void WorldSession::SendBfLeaveMessage(uint32 BattleId, BFLeaveReason reason) +void WorldSession::SendBfLeaveMessage(uint64 guid, BFLeaveReason reason) { - WorldPacket data(SMSG_BATTLEFIELD_MGR_EJECTED, 7); - data << uint32(BattleId); - data << uint8(reason);//byte Reason - data << uint8(2);//byte BattleStatus - data << uint8(0);//bool Relocated + ObjectGuid guidBytes = guid; + + WorldPacket data(SMSG_BATTLEFIELD_MGR_EJECTED, 11); + + data.WriteBit(guidBytes[2]); + data.WriteBit(guidBytes[5]); + data.WriteBit(guidBytes[1]); + data.WriteBit(guidBytes[0]); + data.WriteBit(guidBytes[3]); + data.WriteBit(guidBytes[6]); + data.WriteBit(0); // Relocated + data.WriteBit(guidBytes[7]); + data.WriteBit(guidBytes[4]); + + data.FlushBits(); + + data << uint8(2); // BattleStatus + data.WriteByteSeq(guidBytes[1]); + data.WriteByteSeq(guidBytes[7]); + data.WriteByteSeq(guidBytes[4]); + data.WriteByteSeq(guidBytes[2]); + data.WriteByteSeq(guidBytes[3]); + data << uint8(reason); // Reason + data.WriteByteSeq(guidBytes[6]); + data.WriteByteSeq(guidBytes[0]); + data.WriteByteSeq(guidBytes[5]); + SendPacket(&data); } //Send by client when he click on accept for queue -void WorldSession::HandleBfQueueInviteResponse(WorldPacket & recv_data) +void WorldSession::HandleBfQueueInviteResponse(WorldPacket& recvData) { - uint32 BattleId; - uint8 Accepted; + uint8 accepted; + ObjectGuid guid; + + guid[2] = recvData.ReadBit(); + guid[0] = recvData.ReadBit(); + guid[4] = recvData.ReadBit(); + guid[3] = recvData.ReadBit(); + guid[5] = recvData.ReadBit(); + guid[7] = recvData.ReadBit(); + accepted = recvData.ReadBit(); + guid[1] = recvData.ReadBit(); + guid[6] = recvData.ReadBit(); + + recvData.ReadByteSeq(guid[1]); + recvData.ReadByteSeq(guid[3]); + recvData.ReadByteSeq(guid[2]); + recvData.ReadByteSeq(guid[4]); + recvData.ReadByteSeq(guid[6]); + recvData.ReadByteSeq(guid[7]); + recvData.ReadByteSeq(guid[0]); + recvData.ReadByteSeq(guid[5]); - recv_data >> BattleId >> Accepted; - sLog->outError(LOG_FILTER_GENERAL, "HandleQueueInviteResponse: BattleID:%u Accepted:%u", BattleId, Accepted); - Battlefield* Bf = sBattlefieldMgr->GetBattlefieldByBattleId(BattleId); - if (!Bf) + sLog->outError(LOG_FILTER_GENERAL, "HandleQueueInviteResponse: GUID:"UI64FMTD" Accepted:%u", (uint64)guid, accepted); + + Battlefield* bf = sBattlefieldMgr->GetBattlefieldByGUID(guid); + if (!bf) return; - if (Accepted) - { - Bf->PlayerAcceptInviteToQueue(_player); - } + if (accepted) + bf->PlayerAcceptInviteToQueue(_player); } //Send by client on clicking in accept or refuse of invitation windows for join game -void WorldSession::HandleBfEntryInviteResponse(WorldPacket & recv_data) +void WorldSession::HandleBfEntryInviteResponse(WorldPacket& recvData) { - uint32 BattleId; - uint8 Accepted; + uint8 accepted; + ObjectGuid guid; + + guid[6] = recvData.ReadBit(); + guid[1] = recvData.ReadBit(); + accepted = recvData.ReadBit(); + guid[5] = recvData.ReadBit(); + guid[3] = recvData.ReadBit(); + guid[2] = recvData.ReadBit(); + guid[0] = recvData.ReadBit(); + guid[7] = recvData.ReadBit(); + guid[4] = recvData.ReadBit(); + + recvData.ReadByteSeq(guid[0]); + recvData.ReadByteSeq(guid[3]); + recvData.ReadByteSeq(guid[4]); + recvData.ReadByteSeq(guid[2]); + recvData.ReadByteSeq(guid[1]); + recvData.ReadByteSeq(guid[6]); + recvData.ReadByteSeq(guid[7]); + recvData.ReadByteSeq(guid[5]); + + sLog->outError(LOG_FILTER_GENERAL, "HandleBattlefieldInviteResponse: GUID:"UI64FMTD" Accepted:%u", (uint64)guid, accepted); - recv_data >> BattleId >> Accepted; - sLog->outError(LOG_FILTER_GENERAL, "HandleBattlefieldInviteResponse: BattleID:%u Accepted:%u", BattleId, Accepted); - Battlefield* Bf = sBattlefieldMgr->GetBattlefieldByBattleId(BattleId); - if (!Bf) + Battlefield* bf = sBattlefieldMgr->GetBattlefieldByGUID(guid); + if (!bf) return; - //If player accept invitation - if (Accepted) - { - Bf->PlayerAcceptInviteToWar(_player); - } + if (accepted) + bf->PlayerAcceptInviteToWar(_player); else - { - if (_player->GetZoneId() == Bf->GetZoneId()) - Bf->KickPlayerFromBattlefield(_player->GetGUID()); - } + if (_player->GetZoneId() == bf->GetZoneId()) + bf->KickPlayerFromBattlefield(_player->GetGUID()); } -void WorldSession::HandleBfExitRequest(WorldPacket & recv_data) +void WorldSession::HandleBfExitRequest(WorldPacket& recvData) { - uint32 BattleId; + ObjectGuid guid; - recv_data >> BattleId; - sLog->outError(LOG_FILTER_GENERAL, "HandleBfExitRequest: BattleID:%u ", BattleId); - Battlefield* Bf = sBattlefieldMgr->GetBattlefieldByBattleId(BattleId); - if (!Bf) - return; + guid[2] = recvData.ReadBit(); + guid[0] = recvData.ReadBit(); + guid[3] = recvData.ReadBit(); + guid[7] = recvData.ReadBit(); + guid[4] = recvData.ReadBit(); + guid[5] = recvData.ReadBit(); + guid[6] = recvData.ReadBit(); + guid[1] = recvData.ReadBit(); + + recvData.ReadByteSeq(guid[5]); + recvData.ReadByteSeq(guid[2]); + recvData.ReadByteSeq(guid[0]); + recvData.ReadByteSeq(guid[1]); + recvData.ReadByteSeq(guid[4]); + recvData.ReadByteSeq(guid[3]); + recvData.ReadByteSeq(guid[7]); + recvData.ReadByteSeq(guid[6]); + + sLog->outError(LOG_FILTER_GENERAL, "HandleBfExitRequest: GUID:"UI64FMTD" ", (uint64)guid); - Bf->AskToLeaveQueue(_player); + if (Battlefield* bf = sBattlefieldMgr->GetBattlefieldByGUID(guid)) + bf->AskToLeaveQueue(_player); } diff --git a/src/server/game/Battlefield/BattlefieldMgr.cpp b/src/server/game/Battlefield/BattlefieldMgr.cpp index 6122b25e8e8..d2ecf43ee9b 100644 --- a/src/server/game/Battlefield/BattlefieldMgr.cpp +++ b/src/server/game/Battlefield/BattlefieldMgr.cpp @@ -118,6 +118,15 @@ Battlefield *BattlefieldMgr::GetBattlefieldByBattleId(uint32 battleid) return NULL; } +Battlefield* BattlefieldMgr::GetBattlefieldByGUID(uint64 guid) +{ + for (BattlefieldSet::iterator itr = m_BattlefieldSet.begin(); itr != m_BattlefieldSet.end(); ++itr) + if ((*itr)->GetGUID() == guid) + return (*itr); + + return NULL; +} + void BattlefieldMgr::Update(uint32 diff) { m_UpdateTimer += diff; diff --git a/src/server/game/Battlefield/BattlefieldMgr.h b/src/server/game/Battlefield/BattlefieldMgr.h index 4ee37e424fd..b448cd4ead2 100644 --- a/src/server/game/Battlefield/BattlefieldMgr.h +++ b/src/server/game/Battlefield/BattlefieldMgr.h @@ -48,6 +48,7 @@ class BattlefieldMgr // return assigned battlefield Battlefield *GetBattlefieldToZoneId(uint32 zoneid); Battlefield *GetBattlefieldByBattleId(uint32 battleid); + Battlefield *GetBattlefieldByGUID(uint64 guid); ZoneScript *GetZoneScript(uint32 zoneId); diff --git a/src/server/game/Battlefield/Zones/BattlefieldWG.cpp b/src/server/game/Battlefield/Zones/BattlefieldWG.cpp index 634b1bb2cea..09783176094 100644 --- a/src/server/game/Battlefield/Zones/BattlefieldWG.cpp +++ b/src/server/game/Battlefield/Zones/BattlefieldWG.cpp @@ -25,12 +25,6 @@ #include "SpellAuras.h" #include "Vehicle.h" -enum WintergrastData -{ - BATTLEFIELD_WG_ZONEID = 4197, // Wintergrasp - BATTLEFIELD_WG_MAPID = 571, // Northrend -}; - enum WGVehicles { NPC_WG_SEIGE_ENGINE_ALLIANCE = 28312, @@ -39,6 +33,12 @@ enum WGVehicles NPC_WG_CATAPULT = 27881, }; +BattlefieldWG::~BattlefieldWG() +{ + for (Workshop::const_iterator itr = WorkshopsList.begin(); itr != WorkshopsList.end(); ++itr) + delete *itr; +} + bool BattlefieldWG::SetupBattlefield() { InitStalker(BATTLEFIELD_WG_NPC_STALKER, WintergraspStalkerPos[0], WintergraspStalkerPos[1], WintergraspStalkerPos[2], WintergraspStalkerPos[3]); @@ -172,6 +172,8 @@ bool BattlefieldWG::SetupBattlefield() GameObject* go = SpawnGameObject(WGGameObjectBuilding[i].entry, WGGameObjectBuilding[i].x, WGGameObjectBuilding[i].y, WGGameObjectBuilding[i].z, WGGameObjectBuilding[i].o); BfWGGameObjectBuilding* b = new BfWGGameObjectBuilding(this); b->Init(go, WGGameObjectBuilding[i].type, WGGameObjectBuilding[i].WorldState, WGGameObjectBuilding[i].nameId); + if (!IsEnabled() && go->GetEntry() == GO_WINTERGRASP_VAULT_GATE) + go->SetDestructibleState(GO_DESTRUCTIBLE_DESTROYED); BuildingsInZone.insert(b); } @@ -538,7 +540,6 @@ void BattlefieldWG::OnCreatureCreate(Creature* creature) { UpdateData(BATTLEFIELD_WG_DATA_VEHICLE_H, 1); creature->AddAura(SPELL_HORDE_FLAG, creature); - creature->setFaction(creator->getFaction()); m_vehicles[team].insert(creature->GetGUID()); UpdateVehicleCountWG(); } @@ -555,7 +556,6 @@ void BattlefieldWG::OnCreatureCreate(Creature* creature) { UpdateData(BATTLEFIELD_WG_DATA_VEHICLE_A, 1); creature->AddAura(SPELL_ALLIANCE_FLAG, creature); - creature->setFaction(creator->getFaction()); m_vehicles[team].insert(creature->GetGUID()); UpdateVehicleCountWG(); } @@ -1084,10 +1084,12 @@ WintergraspCapturePoint::WintergraspCapturePoint(BattlefieldWG* battlefield, Tea { m_Bf = battlefield; m_team = teamInControl; + m_Workshop = NULL; } void WintergraspCapturePoint::ChangeTeam(TeamId /*oldTeam*/) { + ASSERT(m_Workshop); m_Workshop->GiveControlTo(m_team, false); } diff --git a/src/server/game/Battlefield/Zones/BattlefieldWG.h b/src/server/game/Battlefield/Zones/BattlefieldWG.h index be062704b52..734154020d9 100644 --- a/src/server/game/Battlefield/Zones/BattlefieldWG.h +++ b/src/server/game/Battlefield/Zones/BattlefieldWG.h @@ -29,7 +29,7 @@ uint32 const VehNumWorldState[2] = { 3680, 3490 }; uint32 const MaxVehNumWorldState[2] = { 3681, 3491 }; uint32 const ClockWorldState[2] = { 3781, 4354 }; -uint32 const WintergraspFaction[3] = { 1, 2, 35 }; +uint32 const WintergraspFaction[3] = { 1732, 1735, 35 }; float const WintergraspStalkerPos[4] = { 0, 0, 0, 0 }; class BattlefieldWG; @@ -44,6 +44,12 @@ typedef std::set<WGWorkshop*> Workshop; typedef std::set<Group*> GroupSet; //typedef std::set<WintergraspCapturePoint *> CapturePointSet; unused ? +enum WintergrastData +{ + BATTLEFIELD_WG_ZONEID = 4197, // Wintergrasp + BATTLEFIELD_WG_MAPID = 571, // Northrend +}; + enum WintergraspSpells { // Wartime auras @@ -273,6 +279,7 @@ class WintergraspCapturePoint : public BfCapturePoint class BattlefieldWG : public Battlefield { public: + ~BattlefieldWG(); /** * \brief Called when the battle start * - Spawn relic and turret @@ -434,7 +441,6 @@ class BattlefieldWG : public Battlefield GameObject* m_titansRelic; }; -uint32 const NORTHREND_WINTERGRASP = 4197; uint8 const WG_MAX_OBJ = 32; uint8 const WG_KEEPGAMEOBJECT_MAX = 44; uint8 const WG_MAX_TURRET = 15; @@ -539,6 +545,12 @@ enum WintergraspGameObject GO_WINTERGRASP_SHADOWSIGHT_TOWER = 190356, GO_WINTERGRASP_WINTER_S_EDGE_TOWER = 190357, GO_WINTERGRASP_FLAMEWATCH_TOWER = 190358, + + GO_WINTERGRASP_FORTRESS_GATE = 190375, + GO_WINTERGRASP_VAULT_GATE = 191810, + + GO_WINTERGRASP_KEEP_COLLISION_WALL = 194323, + }; struct WintergraspObjectPositionData @@ -609,10 +621,10 @@ const WintergraspBuildingSpawnData WGGameObjectBuilding[WG_MAX_OBJ] = { 190358, 3706, 4459.1f, 1944.33f, 434.991f, -2.00276f, BATTLEFIELD_WG_OBJECTTYPE_TOWER, BATTLEFIELD_WG_TEXT_TOWER_NAME_E }, // Door of forteress (Not spawned in db) - { 190375, 3763, 5162.99f, 2841.23f, 410.162f, -3.13286f, BATTLEFIELD_WG_OBJECTTYPE_DOOR, 0 }, + { GO_WINTERGRASP_FORTRESS_GATE, 3763, 5162.99f, 2841.23f, 410.162f, -3.13286f, BATTLEFIELD_WG_OBJECTTYPE_DOOR, 0 }, // Last door (Not spawned in db) - { 191810, 3773, 5397.11f, 2841.54f, 425.899f, 3.14159f, BATTLEFIELD_WG_OBJECTTYPE_DOOR_LAST, 0 }, + { GO_WINTERGRASP_VAULT_GATE, 3773, 5397.11f, 2841.54f, 425.899f, 3.14159f, BATTLEFIELD_WG_OBJECTTYPE_DOOR_LAST, 0 }, }; @@ -1195,6 +1207,9 @@ struct BfWGGameObjectBuilding if (m_Build->IsDestructibleBuilding()) { m_Build->SetDestructibleState(GO_DESTRUCTIBLE_REBUILDING, NULL, true); + if (m_Build->GetEntry() == GO_WINTERGRASP_VAULT_GATE) + if (GameObject* go = m_Build->FindNearestGameObject(GO_WINTERGRASP_KEEP_COLLISION_WALL, 10.0f)) + go->EnableCollision(true); // Update worldstate m_State = BATTLEFIELD_WG_OBJECTSTATE_ALLIANCE_INTACT - (m_Team * 3); @@ -1250,6 +1265,8 @@ struct BfWGGameObjectBuilding m_WG->UpdatedDestroyedTowerCount(TeamId(m_Team)); break; case BATTLEFIELD_WG_OBJECTTYPE_DOOR_LAST: + if (GameObject* go = m_Build->FindNearestGameObject(GO_WINTERGRASP_KEEP_COLLISION_WALL, 10.0f)) + go->EnableCollision(false); m_WG->SetRelicInteractible(true); if (m_WG->GetRelic()) m_WG->GetRelic()->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_IN_USE); @@ -1403,7 +1420,7 @@ struct BfWGGameObjectBuilding { Position towerCannonPos; TowerCannon[towerid].TurretTop[i].GetPosition(&towerCannonPos); - if (Creature *turret = m_WG->SpawnCreature(28366, towerCannonPos, TeamId(0))) + if (Creature* turret = m_WG->SpawnCreature(28366, towerCannonPos, TeamId(0))) { m_TurretTopList.insert(turret->GetGUID()); switch (go->GetEntry()) @@ -1473,17 +1490,17 @@ struct BfWGGameObjectBuilding switch (m_Build->GetEntry()) { - case 190221: - case 190373: - case 190377: - case 190378: + case GO_WINTERGRASP_FORTRESS_TOWER_1: + case GO_WINTERGRASP_FORTRESS_TOWER_2: + case GO_WINTERGRASP_FORTRESS_TOWER_3: + case GO_WINTERGRASP_FORTRESS_TOWER_4: { creature->setFaction(WintergraspFaction[m_WG->GetDefenderTeam()]); break; } - case 190356: - case 190357: - case 190358: + case GO_WINTERGRASP_SHADOWSIGHT_TOWER: + case GO_WINTERGRASP_WINTER_S_EDGE_TOWER: + case GO_WINTERGRASP_FLAMEWATCH_TOWER: { creature->setFaction(WintergraspFaction[m_WG->GetAttackerTeam()]); break; @@ -1509,17 +1526,17 @@ struct BfWGGameObjectBuilding switch (m_Build->GetEntry()) { - case 190221: - case 190373: - case 190377: - case 190378: + case GO_WINTERGRASP_FORTRESS_TOWER_1: + case GO_WINTERGRASP_FORTRESS_TOWER_2: + case GO_WINTERGRASP_FORTRESS_TOWER_3: + case GO_WINTERGRASP_FORTRESS_TOWER_4: { creature->setFaction(WintergraspFaction[m_WG->GetDefenderTeam()]); break; } - case 190356: - case 190357: - case 190358: + case GO_WINTERGRASP_SHADOWSIGHT_TOWER: + case GO_WINTERGRASP_WINTER_S_EDGE_TOWER: + case GO_WINTERGRASP_FLAMEWATCH_TOWER: { creature->setFaction(WintergraspFaction[m_WG->GetAttackerTeam()]); break; @@ -1643,9 +1660,9 @@ struct WintergraspWorkshopData // Spawning Associate gameobject and store them void AddGameObject(WintergraspObjectPositionData obj) { - if (GameObject *gameobject = m_WG->SpawnGameObject(obj.entryHorde, obj.x, obj.y, obj.z, obj.o)) + if (GameObject* gameobject = m_WG->SpawnGameObject(obj.entryHorde, obj.x, obj.y, obj.z, obj.o)) m_GameObjectOnPoint[TEAM_HORDE].insert(gameobject); - if (GameObject *gameobject = m_WG->SpawnGameObject(obj.entryAlliance, obj.x, obj.y, obj.z, obj.o)) + if (GameObject* gameobject = m_WG->SpawnGameObject(obj.entryAlliance, obj.x, obj.y, obj.z, obj.o)) m_GameObjectOnPoint[TEAM_ALLIANCE].insert(gameobject); } diff --git a/src/server/game/Battlegrounds/ArenaTeam.cpp b/src/server/game/Battlegrounds/ArenaTeam.cpp index 61b15bdd182..e88c501398e 100755 --- a/src/server/game/Battlegrounds/ArenaTeam.cpp +++ b/src/server/game/Battlegrounds/ArenaTeam.cpp @@ -24,16 +24,9 @@ #include "ArenaTeamMgr.h" ArenaTeam::ArenaTeam() + : TeamId(0), Type(0), TeamName(), CaptainGuid(0), BackgroundColor(0), EmblemStyle(0), EmblemColor(0), + BorderStyle(0), BorderColor(0) { - TeamId = 0; - Type = 0; - TeamName = ""; - CaptainGuid = 0; - BackgroundColor = 0; - EmblemStyle = 0; - EmblemColor = 0; - BorderStyle = 0; - BorderColor = 0; Stats.WeekGames = 0; Stats.SeasonGames = 0; Stats.Rank = 0; @@ -343,7 +336,7 @@ void ArenaTeam::Disband(WorldSession* session) // Broadcast update if (session) { - BroadcastEvent(ERR_ARENA_TEAM_DISBANDED_S, 0, 2, session->GetPlayerName().c_str(), GetName(), ""); + BroadcastEvent(ERR_ARENA_TEAM_DISBANDED_S, 0, 2, session->GetPlayerName(), GetName(), ""); if (Player* player = session->GetPlayer()) sLog->outInfo(LOG_FILTER_ARENAS, "Player: %s [GUID: %u] disbanded arena team type: %u [Id: %u].", player->GetName(), player->GetGUIDLow(), GetType(), GetId()); diff --git a/src/server/game/Battlegrounds/Battleground.cpp b/src/server/game/Battlegrounds/Battleground.cpp index 98b95b5d32b..ab69ed40943 100755 --- a/src/server/game/Battlegrounds/Battleground.cpp +++ b/src/server/game/Battlegrounds/Battleground.cpp @@ -131,6 +131,7 @@ void Battleground::BroadcastWorker(Do& _do) Battleground::Battleground() { + m_Guid = MAKE_NEW_GUID(m_TypeID, 0, HIGHGUID_TYPE_BATTLEGROUND); m_TypeID = BATTLEGROUND_TYPE_NONE; m_RandomTypeID = BATTLEGROUND_TYPE_NONE; m_InstanceID = 0; @@ -493,7 +494,7 @@ inline void Battleground::_ProcessJoin(uint32 diff) WorldPacket status; BattlegroundQueueTypeId bgQueueTypeId = sBattlegroundMgr->BGQueueTypeId(m_TypeID, GetArenaType()); uint32 queueSlot = player->GetBattlegroundQueueIndex(bgQueueTypeId); - sBattlegroundMgr->BuildBattlegroundStatusPacket(&status, this, queueSlot, STATUS_IN_PROGRESS, 0, GetStartTime(), GetArenaType()); + sBattlegroundMgr->BuildBattlegroundStatusPacket(&status, this, player, queueSlot, STATUS_IN_PROGRESS, 0, GetStartTime(), GetArenaType()); player->GetSession()->SendPacket(&status); player->RemoveAurasDueToSpell(SPELL_ARENA_PREPARATION); @@ -914,7 +915,7 @@ void Battleground::EndBattleground(uint32 winner) player->GetSession()->SendPacket(&data); BattlegroundQueueTypeId bgQueueTypeId = BattlegroundMgr::BGQueueTypeId(GetTypeID(), GetArenaType()); - sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, this, player->GetBattlegroundQueueIndex(bgQueueTypeId), STATUS_IN_PROGRESS, TIME_TO_AUTOREMOVE, GetStartTime(), GetArenaType()); + sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, this, player, player->GetBattlegroundQueueIndex(bgQueueTypeId), STATUS_IN_PROGRESS, TIME_TO_AUTOREMOVE, GetStartTime(), GetArenaType()); player->GetSession()->SendPacket(&data); player->UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND, 1); } @@ -1020,7 +1021,7 @@ void Battleground::RemovePlayerAtLeave(uint64 guid, bool Transport, bool SendPac if (SendPacket) { WorldPacket data; - sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, this, player->GetBattlegroundQueueIndex(bgQueueTypeId), STATUS_NONE, 0, 0, 0); + sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, this, player, player->GetBattlegroundQueueIndex(bgQueueTypeId), STATUS_NONE, 0, 0, 0); player->GetSession()->SendPacket(&data); } @@ -1144,14 +1145,14 @@ void Battleground::AddPlayer(Player* player) UpdatePlayersCountByTeam(team, false); // +1 player WorldPacket data; - sBattlegroundMgr->BuildPlayerJoinedBattlegroundPacket(&data, player); + sBattlegroundMgr->BuildPlayerJoinedBattlegroundPacket(&data, player->GetGUID()); SendPacketToTeam(team, &data, player, false); // BG Status packet WorldPacket status; BattlegroundQueueTypeId bgQueueTypeId = sBattlegroundMgr->BGQueueTypeId(m_TypeID, GetArenaType()); uint32 queueSlot = player->GetBattlegroundQueueIndex(bgQueueTypeId); - sBattlegroundMgr->BuildBattlegroundStatusPacket(&status, this, queueSlot, STATUS_IN_PROGRESS, 0, GetStartTime(), GetArenaType(), isArena() ? 0 : 1); + sBattlegroundMgr->BuildBattlegroundStatusPacket(&status, this, player, queueSlot, STATUS_IN_PROGRESS, 0, GetStartTime(), GetArenaType(), isArena() ? 0 : 1); player->GetSession()->SendPacket(&status); player->RemoveAurasByType(SPELL_AURA_MOUNTED); @@ -1860,7 +1861,7 @@ void Battleground::PlayerAddedToBGCheckIfBGIsRunning(Player* player) sBattlegroundMgr->BuildPvpLogDataPacket(&data, this); player->GetSession()->SendPacket(&data); - sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, this, player->GetBattlegroundQueueIndex(bgQueueTypeId), STATUS_IN_PROGRESS, GetEndTime(), GetStartTime(), GetArenaType()); + sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, this, player, player->GetBattlegroundQueueIndex(bgQueueTypeId), STATUS_IN_PROGRESS, GetEndTime(), GetStartTime(), GetArenaType()); player->GetSession()->SendPacket(&data); } diff --git a/src/server/game/Battlegrounds/Battleground.h b/src/server/game/Battlegrounds/Battleground.h index 234cda4105c..29523864329 100755 --- a/src/server/game/Battlegrounds/Battleground.h +++ b/src/server/game/Battlegrounds/Battleground.h @@ -133,12 +133,12 @@ enum BattlegroundBuffObjects enum BattlegroundRandomRewards { - BG_REWARD_WINNER_HONOR_FIRST = 30, - BG_REWARD_WINNER_ARENA_FIRST = 25, - BG_REWARD_WINNER_HONOR_LAST = 15, - BG_REWARD_WINNER_ARENA_LAST = 0, - BG_REWARD_LOSER_HONOR_FIRST = 5, - BG_REWARD_LOSER_HONOR_LAST = 5 + BG_REWARD_WINNER_HONOR_FIRST = 270, + BG_REWARD_WINNER_CONQUEST_FIRST = 100, + BG_REWARD_WINNER_HONOR_LAST = 135, + BG_REWARD_WINNER_CONQUEST_LAST = 50, + BG_REWARD_LOSER_HONOR_FIRST = 45, + BG_REWARD_LOSER_HONOR_LAST = 35 }; const uint32 Buff_Entries[3] = { BG_OBJECTID_SPEEDBUFF_ENTRY, BG_OBJECTID_REGENBUFF_ENTRY, BG_OBJECTID_BERSERKERBUFF_ENTRY }; @@ -342,6 +342,7 @@ class Battleground /* Battleground */ // Get methods: char const* GetName() const { return m_Name; } + uint64 GetGUID() { return m_Guid; } BattlegroundTypeId GetTypeID(bool GetRandom = false) const { return GetRandom ? m_RandomTypeID : m_TypeID; } BattlegroundBracketId GetBracketId() const { return m_BracketId; } uint32 GetInstanceID() const { return m_InstanceID; } @@ -635,6 +636,7 @@ class Battleground bool m_PrematureCountDown; uint32 m_PrematureCountDownTimer; char const* m_Name; + uint64 m_Guid; /* Pre- and post-update hooks */ diff --git a/src/server/game/Battlegrounds/BattlegroundMgr.cpp b/src/server/game/Battlegrounds/BattlegroundMgr.cpp index 86b06de2cec..afc63ed6704 100755 --- a/src/server/game/Battlegrounds/BattlegroundMgr.cpp +++ b/src/server/game/Battlegrounds/BattlegroundMgr.cpp @@ -180,102 +180,275 @@ void BattlegroundMgr::Update(uint32 diff) } } -void BattlegroundMgr::BuildBattlegroundStatusPacket(WorldPacket* data, Battleground* bg, uint8 QueueSlot, uint8 StatusID, uint32 Time1, uint32 Time2, uint8 arenatype, uint8 uiFrame) +void BattlegroundMgr::BuildBattlegroundStatusPacket(WorldPacket *data, Battleground *bg, Player * pPlayer, uint8 QueueSlot, uint8 StatusID, uint32 Time1, uint32 Time2, uint8 arenatype, uint8 uiFrame) { - // we can be in 2 queues in same time... + if (!bg) + StatusID = STATUS_NONE; - if (StatusID == 0 || !bg) - { - data->Initialize(SMSG_BATTLEFIELD_STATUS, 4+8); - *data << uint32(QueueSlot); // queue id (0...1) - *data << uint64(0); - return; - } + ObjectGuid guidBytes1 = pPlayer->GetGUID(); + ObjectGuid guidBytes2 = bg->GetGUID(); - data->Initialize(SMSG_BATTLEFIELD_STATUS, (4+8+1+1+4+1+4+4+4)); - *data << uint32(QueueSlot); // queue id (0...1) - player can be in 2 queues in time - // The following segment is read as uint64 in client but can be appended as their original type. - *data << uint8(arenatype); - sLog->outDebug(LOG_FILTER_NETWORKIO, "BattlegroundMgr::BuildBattlegroundStatusPacket: arenatype = %u for bg instanceID %u, TypeID %u.", arenatype, bg->GetClientInstanceID(), bg->GetTypeID()); - *data << uint8(bg->isArena() ? 0xC : 0x2); - *data << uint32(bg->GetTypeID()); - *data << uint16(0x1F90); - // End of uint64 segment, decomposed this way for simplicity - *data << uint8(0); // 3.3.0, some level, only saw 80... - *data << uint8(0); // 3.3.0, some level, only saw 80... - *data << uint32(bg->GetClientInstanceID()); - // alliance/horde for BG and skirmish/rated for Arenas - // following displays the minimap-icon 0 = faction icon 1 = arenaicon - *data << uint8(bg->isRated()); // 1 for rated match, 0 for bg or non rated match - - *data << uint32(StatusID); // status switch (StatusID) { - case STATUS_WAIT_QUEUE: // status_in_queue - *data << uint32(Time1); // average wait time, milliseconds - *data << uint32(Time2); // time in queue, updated every minute!, milliseconds + case STATUS_NONE: + { + //data->Initialize(SMSG_BATTLEFIELD_STATUS_FAILED); + sLog->outDebug(LOG_FILTER_NETWORKIO, ">>>>> STATUS_NONE"); break; - case STATUS_WAIT_JOIN: // status_invite - *data << uint32(bg->GetMapId()); // map id - *data << uint64(0); // 3.3.5, unknown - *data << uint32(Time1); // time to remove from queue, milliseconds + } + case STATUS_WAIT_QUEUE: + { + data->Initialize(SMSG_BATTLEFIELD_STATUS_QUEUED); + + data->WriteBit(guidBytes1[3]); + data->WriteBit(guidBytes1[0]); + data->WriteBit(guidBytes2[3]); + data->WriteBit(guidBytes1[2]); + data->WriteBit(0); // unk + data->WriteBit(0); // Join Failed + data->WriteBit(guidBytes2[2]); + data->WriteBit(guidBytes1[1]); + data->WriteBit(guidBytes2[0]); + data->WriteBit(guidBytes2[6]); + data->WriteBit(guidBytes2[4]); + data->WriteBit(guidBytes1[6]); + data->WriteBit(guidBytes1[7]); + data->WriteBit(guidBytes2[7]); + data->WriteBit(guidBytes2[5]); + data->WriteBit(guidBytes1[4]); + data->WriteBit(guidBytes1[5]); + data->WriteBit(0); // unk + data->WriteBit(0); // unk + data->WriteBit(guidBytes2[1]); + + data->FlushBits(); + + data->WriteByteSeq(guidBytes1[0]); + *data << uint32(0); // unk + data->WriteByteSeq(guidBytes2[5]); + data->WriteByteSeq(guidBytes1[3]); + *data << uint32(0); // unk + data->WriteByteSeq(guidBytes2[7]); + data->WriteByteSeq(guidBytes2[1]); + data->WriteByteSeq(guidBytes2[2]); + *data << uint8(0); // unk + data->WriteByteSeq(guidBytes2[4]); + data->WriteByteSeq(guidBytes1[2]); + *data << uint8(0); // unk + data->WriteByteSeq(guidBytes2[6]); + data->WriteByteSeq(guidBytes1[7]); + data->WriteByteSeq(guidBytes2[3]); + data->WriteByteSeq(guidBytes1[6]); + data->WriteByteSeq(guidBytes2[0]); + *data << uint32(bg->GetStartTime()); // Time + *data << uint32(0); // unk + *data << uint8(bg->GetMinLevel()); // Min Level + *data << uint32(0); // unk + data->WriteByteSeq(guidBytes1[1]); + data->WriteByteSeq(guidBytes1[5]); + *data << uint32(0); // unk + data->WriteByteSeq(guidBytes1[4]); + break; - case STATUS_IN_PROGRESS: // status_in_progress - *data << uint32(bg->GetMapId()); // map id - *data << uint64(0); // 3.3.5, unknown - *data << uint32(Time1); // time to bg auto leave, 0 at bg start, 120000 after bg end, milliseconds - *data << uint32(Time2); // time from bg start, milliseconds - *data << uint8(uiFrame); + } + case STATUS_WAIT_JOIN: + { + data->Initialize(SMSG_BATTLEFIELD_STATUS_NEEDCONFIRMATION, 44); + + *data << uint32(bg->GetClientInstanceID()); // Client Instance ID + *data << uint32(Time1); // Time until closed + *data << uint8(0); // unk + *data << uint32(QueueSlot); // Queue slot + *data << uint32(Time2); // Time + *data << uint8(bg->GetMinLevel()); // Min Level + *data << uint32(bg->GetStatus()); // Status + *data << uint32(bg->GetMapId()); // Map Id + *data << uint8(0); // unk + + data->WriteBit(guidBytes1[5]); + data->WriteBit(guidBytes1[2]); + data->WriteBit(guidBytes1[1]); + data->WriteBit(guidBytes2[2]); + data->WriteBit(guidBytes1[4]); + data->WriteBit(guidBytes2[6]); + data->WriteBit(guidBytes2[3]); + data->WriteBit(bg->isRated()); // Is Rated + data->WriteBit(guidBytes1[7]); + data->WriteBit(guidBytes1[3]); + data->WriteBit(guidBytes2[7]); + data->WriteBit(guidBytes2[0]); + data->WriteBit(guidBytes2[4]); + data->WriteBit(guidBytes1[6]); + data->WriteBit(guidBytes2[1]); + data->WriteBit(guidBytes2[5]); + data->WriteBit(guidBytes1[0]); + + data->FlushBits(); + + data->WriteByteSeq(guidBytes2[6]); + data->WriteByteSeq(guidBytes2[5]); + data->WriteByteSeq(guidBytes2[7]); + data->WriteByteSeq(guidBytes2[0]); + data->WriteByteSeq(guidBytes1[0]); + data->WriteByteSeq(guidBytes1[7]); + data->WriteByteSeq(guidBytes2[4]); + data->WriteByteSeq(guidBytes1[1]); + data->WriteByteSeq(guidBytes2[0]); + data->WriteByteSeq(guidBytes1[4]); + data->WriteByteSeq(guidBytes2[1]); + data->WriteByteSeq(guidBytes1[5]); + data->WriteByteSeq(guidBytes2[3]); + data->WriteByteSeq(guidBytes1[6]); + data->WriteByteSeq(guidBytes1[2]); + data->WriteByteSeq(guidBytes1[3]); break; - default: - sLog->outError(LOG_FILTER_BATTLEGROUND, "Unknown BG status!"); + } + case STATUS_IN_PROGRESS: + { + data->Initialize(SMSG_BATTLEFIELD_STATUS_ACTIVE, 49); + + data->WriteBit(guidBytes1[2]); + data->WriteBit(guidBytes1[7]); + data->WriteBit(guidBytes2[7]); + data->WriteBit(guidBytes2[1]); + data->WriteBit(guidBytes1[5]); + data->WriteBit(0); // Unk + data->WriteBit(guidBytes2[0]); + data->WriteBit(guidBytes1[1]); + data->WriteBit(guidBytes2[3]); + data->WriteBit(guidBytes1[6]); + data->WriteBit(guidBytes2[5]); + data->WriteBit(0); // Unk Bit 64 + data->WriteBit(guidBytes1[4]); + data->WriteBit(guidBytes2[6]); + data->WriteBit(guidBytes2[4]); + data->WriteBit(guidBytes2[2]); + data->WriteBit(guidBytes1[3]); + data->WriteBit(guidBytes1[0]); + + data->FlushBits(); + + data->WriteByteSeq(guidBytes2[4]); + data->WriteByteSeq(guidBytes2[5]); + data->WriteByteSeq(guidBytes1[5]); + data->WriteByteSeq(guidBytes2[1]); + data->WriteByteSeq(guidBytes2[6]); + data->WriteByteSeq(guidBytes2[3]); + data->WriteByteSeq(guidBytes2[7]); + data->WriteByteSeq(guidBytes1[6]); + + *data << uint32(Time2); // Time + *data << uint8(bg->GetPlayersCountByTeam(bg->GetPlayerTeam(pPlayer->GetGUID()))); // Teamsize + + data->WriteByteSeq(guidBytes1[4]); + data->WriteByteSeq(guidBytes1[1]); + + *data << uint32(QueueSlot); // Queue slot + *data << uint8(bg->GetMaxLevel()); // Max Level + *data << uint32(bg->GetStatus()); // Status + *data << uint32(bg->GetMapId()); // Map Id + *data << uint8(bg->GetMinLevel()); // Min Level + *data << uint32(Time1); // Time until closed + + data->WriteByteSeq(guidBytes1[2]); + + *data << uint32(bg->GetStartTime()); // Time since started + + data->WriteByteSeq(guidBytes1[0]); + data->WriteByteSeq(guidBytes1[3]); + data->WriteByteSeq(guidBytes1[2]); + + *data << uint32(bg->GetClientInstanceID()); // Client Instance ID + + data->WriteByteSeq(guidBytes2[0]); + data->WriteByteSeq(guidBytes1[7]); break; + } + case STATUS_WAIT_LEAVE: + { + data->Initialize(SMSG_BATTLEFIELD_STATUS_WAITFORGROUPS, 48); + + *data << uint8(0); // unk + *data << uint32(bg->GetStatus()); // Status + *data << uint32(QueueSlot); // Queue slot + *data << uint32(Time1); // Time until closed + *data << uint32(0); // unk + *data << uint8(0); // unk + *data << uint8(0); // unk + *data << uint8(bg->GetMinLevel()); // Min Level + *data << uint8(0); // unk + *data << uint8(0); // unk + *data << uint32(bg->GetMapId()); // Map Id + *data << uint32(Time2); // Time + *data << uint8(0); // unk + + data->WriteBit(guidBytes2[0]); + data->WriteBit(guidBytes2[1]); + data->WriteBit(guidBytes2[7]); + data->WriteBit(guidBytes1[7]); + data->WriteBit(guidBytes1[0]); + data->WriteBit(guidBytes2[4]); + data->WriteBit(guidBytes1[6]); + data->WriteBit(guidBytes1[2]); + data->WriteBit(guidBytes1[3]); + data->WriteBit(guidBytes2[3]); + data->WriteBit(guidBytes1[4]); + data->WriteBit(guidBytes2[5]); + data->WriteBit(guidBytes1[5]); + data->WriteBit(guidBytes2[2]); + data->WriteBit(bg->isRated()); // Is Rated + data->WriteBit(guidBytes1[1]); + data->WriteBit(guidBytes2[6]); + + data->FlushBits(); + + data->WriteByteSeq(guidBytes1[0]); + data->WriteByteSeq(guidBytes2[4]); + data->WriteByteSeq(guidBytes1[3]); + data->WriteByteSeq(guidBytes2[1]); + data->WriteByteSeq(guidBytes2[0]); + data->WriteByteSeq(guidBytes2[2]); + data->WriteByteSeq(guidBytes1[2]); + data->WriteByteSeq(guidBytes2[7]); + data->WriteByteSeq(guidBytes1[1]); + data->WriteByteSeq(guidBytes1[6]); + data->WriteByteSeq(guidBytes2[6]); + data->WriteByteSeq(guidBytes2[5]); + data->WriteByteSeq(guidBytes1[5]); + data->WriteByteSeq(guidBytes1[4]); + data->WriteByteSeq(guidBytes1[7]); + data->WriteByteSeq(guidBytes2[3]); + break; + } } } void BattlegroundMgr::BuildPvpLogDataPacket(WorldPacket* data, Battleground* bg) { - uint8 type = (bg->isArena() ? 1 : 0); - // last check on 3.0.3 - data->Initialize(MSG_PVP_LOG_DATA, (1+1+4+40*bg->GetPlayerScoresSize())); - *data << uint8(type); // type (battleground=0/arena=1) - - if (type) // arena - { - // it seems this must be according to BG_WINNER_A/H and _NOT_ BG_TEAM_A/H - for (int8 i = 1; i >= 0; --i) - { - int32 rating_change = bg->GetArenaTeamRatingChangeByIndex(i); + uint8 isRated = (bg->isRated() ? 1 : 0); // type (normal=0/rated=1) -- ATM arena or bg, RBG NYI + uint8 isArena = (bg->isArena() ? 1 : 0); // Arena names - uint32 pointsLost = rating_change < 0 ? -rating_change : 0; - uint32 pointsGained = rating_change > 0 ? rating_change : 0; - uint32 MatchmakerRating = bg->GetArenaMatchmakerRatingByIndex(i); + data->Initialize(SMSG_PVP_LOG_DATA, (1+1+4+40*bg->GetPlayerScoresSize())); + data->WriteBit(isArena); + data->WriteBit(isRated); - *data << uint32(pointsLost); // Rating Lost - *data << uint32(pointsGained); // Rating gained - *data << uint32(MatchmakerRating); // Matchmaking Value - sLog->outDebug(LOG_FILTER_BATTLEGROUND, "rating change: %d", rating_change); - } + if (isArena) + { for (int8 i = 1; i >= 0; --i) { if (ArenaTeam* at = sArenaTeamMgr->GetArenaTeamById(bg->GetArenaTeamIdByIndex(i))) - *data << at->GetName(); + data->WriteBits(at->GetName().length(), 8); else - *data << uint8(0); + data->WriteBits(0, 8); } } - if (bg->GetStatus() != STATUS_WAIT_LEAVE) - *data << uint8(0); // bg not ended - else - { - *data << uint8(1); // bg ended - *data << uint8(bg->GetWinner()); // who win - } + size_t count_pos = data->bitwpos(); + + data->WriteBits(0, 21); // Placeholder - size_t wpos = data->wpos(); - uint32 scoreCount = 0; - *data << uint32(scoreCount); // placeholder + int32 count = 0; + ByteBuffer buff; Battleground::BattlegroundScoreMap::const_iterator itr2 = bg->GetPlayerScoresBegin(); for (Battleground::BattlegroundScoreMap::const_iterator itr = itr2; itr != bg->GetPlayerScoresEnd();) @@ -286,145 +459,211 @@ void BattlegroundMgr::BuildPvpLogDataPacket(WorldPacket* data, Battleground* bg) sLog->outError(LOG_FILTER_BATTLEGROUND, "Player " UI64FMTD " has scoreboard entry for battleground %u but is not in battleground!", itr->first, bg->GetTypeID(true)); continue; } - - *data << uint64(itr2->first); - *data << uint32(itr2->second->KillingBlows); - if (type == 0) + ObjectGuid guid = itr2->first; + Player* player = ObjectAccessor::FindPlayer(itr2->first); + data->WriteBit(0); // Unk 1 + data->WriteBit(0); // Unk 2 + data->WriteBit(guid[2]); + data->WriteBit(!isArena); // Unk 3 -- Prolly if (bg) + data->WriteBit(0); // Unk 4 + data->WriteBit(0); // Unk 5 + data->WriteBit(0); // Unk 6 + data->WriteBit(guid[3]); + data->WriteBit(guid[0]); + data->WriteBit(guid[5]); + data->WriteBit(guid[1]); + data->WriteBit(guid[6]); + data->WriteBit(player->GetTeam() == ALLIANCE); + data->WriteBit(guid[7]); + + buff << uint32(itr2->second->HealingDone); // healing done + buff << uint32(itr2->second->DamageDone); // damage done + + if (!isArena) // Unk 3 prolly is (bg) { - *data << uint32(itr2->second->HonorableKills); - *data << uint32(itr2->second->Deaths); - *data << uint32(itr2->second->BonusHonor); + buff << uint32(itr2->second->BonusHonor); + buff << uint32(itr2->second->Deaths); + buff << uint32(itr2->second->HonorableKills); } - else - { - Player* player = ObjectAccessor::FindPlayer(itr2->first); - uint32 team = bg->GetPlayerTeam(itr2->first); - if (!team && player) - team = player->GetBGTeam(); - *data << uint8(team == ALLIANCE ? 1 : 0); // green or yellow - } - *data << uint32(itr2->second->DamageDone); // damage done - *data << uint32(itr2->second->HealingDone); // healing done - switch (bg->GetTypeID(true)) // battleground specific things + + buff.WriteByteSeq(guid[4]); + buff << uint32(itr2->second->KillingBlows); + + // if (unk 5) << uint32() unk + + buff.WriteByteSeq(guid[5]); + + // if (unk 6) << uint32() unk + // if (unk 2) << uint32() unk + + buff.WriteByteSeq(guid[1]); + buff.WriteByteSeq(guid[6]); + + buff << int32(player->GetPrimaryTalentTree(player->GetActiveSpec())); + + switch (bg->GetTypeID(true)) // Custom values { case BATTLEGROUND_RB: switch (bg->GetMapId()) { case 489: - *data << uint32(0x00000002); // count of next fields - *data << uint32(((BattlegroundWGScore*)itr2->second)->FlagCaptures); // flag captures - *data << uint32(((BattlegroundWGScore*)itr2->second)->FlagReturns); // flag returns + data->WriteBits(0x00000002, 24); + buff << uint32(((BattlegroundWGScore*)itr2->second)->FlagCaptures); // flag captures + buff << uint32(((BattlegroundWGScore*)itr2->second)->FlagReturns); // flag returns break; case 566: - *data << uint32(0x00000001); // count of next fields - *data << uint32(((BattlegroundEYScore*)itr2->second)->FlagCaptures); // flag captures + data->WriteBits(0x00000001, 24); + buff << uint32(((BattlegroundEYScore*)itr2->second)->FlagCaptures); // flag captures break; case 529: - *data << uint32(0x00000002); // count of next fields - *data << uint32(((BattlegroundABScore*)itr2->second)->BasesAssaulted); // bases asssulted - *data << uint32(((BattlegroundABScore*)itr2->second)->BasesDefended); // bases defended + data->WriteBits(0x00000002, 24); + buff << uint32(((BattlegroundABScore*)itr2->second)->BasesAssaulted); // bases asssulted + buff << uint32(((BattlegroundABScore*)itr2->second)->BasesDefended); // bases defended break; case 30: - *data << uint32(0x00000005); // count of next fields - *data << uint32(((BattlegroundAVScore*)itr2->second)->GraveyardsAssaulted); // GraveyardsAssaulted - *data << uint32(((BattlegroundAVScore*)itr2->second)->GraveyardsDefended); // GraveyardsDefended - *data << uint32(((BattlegroundAVScore*)itr2->second)->TowersAssaulted); // TowersAssaulted - *data << uint32(((BattlegroundAVScore*)itr2->second)->TowersDefended); // TowersDefended - *data << uint32(((BattlegroundAVScore*)itr2->second)->MinesCaptured); // MinesCaptured + data->WriteBits(0x00000005, 24); + buff << uint32(((BattlegroundAVScore*)itr2->second)->GraveyardsAssaulted); // GraveyardsAssaulted + buff << uint32(((BattlegroundAVScore*)itr2->second)->GraveyardsDefended); // GraveyardsDefended + buff << uint32(((BattlegroundAVScore*)itr2->second)->TowersAssaulted); // TowersAssaulted + buff << uint32(((BattlegroundAVScore*)itr2->second)->TowersDefended); // TowersDefended + buff << uint32(((BattlegroundAVScore*)itr2->second)->MinesCaptured); // MinesCaptured break; case 607: - *data << uint32(0x00000002); // count of next fields - *data << uint32(((BattlegroundSAScore*)itr2->second)->demolishers_destroyed); - *data << uint32(((BattlegroundSAScore*)itr2->second)->gates_destroyed); + data->WriteBits(0x00000002, 24); + buff << uint32(((BattlegroundSAScore*)itr2->second)->demolishers_destroyed); + buff << uint32(((BattlegroundSAScore*)itr2->second)->gates_destroyed); break; case 628: // IC - *data << uint32(0x00000002); // count of next fields - *data << uint32(((BattlegroundICScore*)itr2->second)->BasesAssaulted); // bases asssulted - *data << uint32(((BattlegroundICScore*)itr2->second)->BasesDefended); // bases defended + data->WriteBits(0x00000002, 24); + buff << uint32(((BattlegroundICScore*)itr2->second)->BasesAssaulted); // bases asssulted + buff << uint32(((BattlegroundICScore*)itr2->second)->BasesDefended); // bases defended + break; case 726: - *data << uint32(0x00000002); // count of next fields - *data << uint32(((BattlegroundTPScore*)itr2->second)->FlagCaptures); // flag captures - *data << uint32(((BattlegroundTPScore*)itr2->second)->FlagReturns); // flag returns + data->WriteBits(0x00000002, 24); + buff << uint32(((BattlegroundTPScore*)itr2->second)->FlagCaptures); // flag captures + buff << uint32(((BattlegroundTPScore*)itr2->second)->FlagReturns); // flag returns break; case 761: - *data << uint32(0x00000002); // count of next fields - *data << uint32(((BattlegroundBFGScore*)itr2->second)->BasesAssaulted); // bases asssulted - *data << uint32(((BattlegroundBFGScore*)itr2->second)->BasesDefended); // bases defended + data->WriteBits(0x00000002, 24); + buff << uint32(((BattlegroundBFGScore*)itr2->second)->BasesAssaulted); // bases asssulted + buff << uint32(((BattlegroundBFGScore*)itr2->second)->BasesDefended); // bases defended break; default: - *data << uint32(0); + data->WriteBits(0, 24); break; } + break; case BATTLEGROUND_AV: - *data << uint32(0x00000005); // count of next fields - *data << uint32(((BattlegroundAVScore*)itr2->second)->GraveyardsAssaulted); // GraveyardsAssaulted - *data << uint32(((BattlegroundAVScore*)itr2->second)->GraveyardsDefended); // GraveyardsDefended - *data << uint32(((BattlegroundAVScore*)itr2->second)->TowersAssaulted); // TowersAssaulted - *data << uint32(((BattlegroundAVScore*)itr2->second)->TowersDefended); // TowersDefended - *data << uint32(((BattlegroundAVScore*)itr2->second)->MinesCaptured); // MinesCaptured + data->WriteBits(0x00000005, 24); + buff << uint32(((BattlegroundAVScore*)itr2->second)->GraveyardsAssaulted); // GraveyardsAssaulted + buff << uint32(((BattlegroundAVScore*)itr2->second)->GraveyardsDefended); // GraveyardsDefended + buff << uint32(((BattlegroundAVScore*)itr2->second)->TowersAssaulted); // TowersAssaulted + buff << uint32(((BattlegroundAVScore*)itr2->second)->TowersDefended); // TowersDefended + buff << uint32(((BattlegroundAVScore*)itr2->second)->MinesCaptured); // MinesCaptured break; case BATTLEGROUND_WS: - *data << uint32(0x00000002); // count of next fields - *data << uint32(((BattlegroundWGScore*)itr2->second)->FlagCaptures); // flag captures - *data << uint32(((BattlegroundWGScore*)itr2->second)->FlagReturns); // flag returns + data->WriteBits(0x00000002, 24); + buff << uint32(((BattlegroundWGScore*)itr2->second)->FlagCaptures); // flag captures + buff << uint32(((BattlegroundWGScore*)itr2->second)->FlagReturns); // flag returns break; case BATTLEGROUND_AB: - *data << uint32(0x00000002); // count of next fields - *data << uint32(((BattlegroundABScore*)itr2->second)->BasesAssaulted); // bases asssulted - *data << uint32(((BattlegroundABScore*)itr2->second)->BasesDefended); // bases defended + data->WriteBits(0x00000002, 24); + buff << uint32(((BattlegroundABScore*)itr2->second)->BasesAssaulted); // bases asssulted + buff << uint32(((BattlegroundABScore*)itr2->second)->BasesDefended); // bases defended break; case BATTLEGROUND_EY: - *data << uint32(0x00000001); // count of next fields - *data << uint32(((BattlegroundEYScore*)itr2->second)->FlagCaptures); // flag captures + data->WriteBits(0x00000001, 24); + buff << uint32(((BattlegroundEYScore*)itr2->second)->FlagCaptures); // flag captures break; case BATTLEGROUND_SA: - *data << uint32(0x00000002); // count of next fields - *data << uint32(((BattlegroundSAScore*)itr2->second)->demolishers_destroyed); - *data << uint32(((BattlegroundSAScore*)itr2->second)->gates_destroyed); + data->WriteBits(0x00000002, 24); + buff << uint32(((BattlegroundSAScore*)itr2->second)->demolishers_destroyed); + buff << uint32(((BattlegroundSAScore*)itr2->second)->gates_destroyed); break; - case BATTLEGROUND_IC: // wotlk - *data << uint32(0x00000002); // count of next fields - *data << uint32(((BattlegroundICScore*)itr2->second)->BasesAssaulted); // bases asssulted - *data << uint32(((BattlegroundICScore*)itr2->second)->BasesDefended); // bases defended + case BATTLEGROUND_IC: + data->WriteBits(0x00000002, 24); + buff << uint32(((BattlegroundICScore*)itr2->second)->BasesAssaulted); // bases asssulted + buff << uint32(((BattlegroundICScore*)itr2->second)->BasesDefended); // bases defended break; case BATTLEGROUND_TP: - *data << uint32(0x00000002); // count of next fields - *data << uint32(((BattlegroundTPScore*)itr2->second)->FlagCaptures); // flag captures - *data << uint32(((BattlegroundTPScore*)itr2->second)->FlagReturns); // flag returns + data->WriteBits(0x00000002, 24); + buff << uint32(((BattlegroundTPScore*)itr2->second)->FlagCaptures); // flag captures + buff << uint32(((BattlegroundTPScore*)itr2->second)->FlagReturns); // flag returns + break; case BATTLEGROUND_BFG: - *data << uint32(0x00000002); // count of next fields - *data << uint32(((BattlegroundBFGScore*)itr2->second)->BasesAssaulted); // bases asssulted - *data << uint32(((BattlegroundBFGScore*)itr2->second)->BasesDefended); // bases defended + data->WriteBits(0x00000002, 24); + buff << uint32(((BattlegroundBFGScore*)itr2->second)->BasesAssaulted); // bases asssulted + buff << uint32(((BattlegroundBFGScore*)itr2->second)->BasesDefended); // bases defended + break; case BATTLEGROUND_NA: case BATTLEGROUND_BE: case BATTLEGROUND_AA: case BATTLEGROUND_RL: case BATTLEGROUND_DS: // wotlk case BATTLEGROUND_RV: // wotlk - *data << uint32(0); + data->WriteBits(0, 24); break; default: - sLog->outDebug(LOG_FILTER_NETWORKIO, "Unhandled MSG_PVP_LOG_DATA for BG id %u", bg->GetTypeID()); - *data << uint32(0); + data->WriteBits(0, 24); break; } - // should never happen - if (++scoreCount >= bg->GetMaxPlayers() && itr != bg->GetPlayerScoresEnd()) + data->WriteBit(guid[4]); + + buff.WriteByteSeq(guid[0]); + buff.WriteByteSeq(guid[3]); + + // if (unk 4) << uint32() unk + + buff.WriteByteSeq(guid[7]); + buff.WriteByteSeq(guid[2]); + + ++count; + } + + data->WriteBit(bg->GetStatus() == STATUS_WAIT_LEAVE); // If Ended + data->FlushBits(); + data->PutBits<int32>(count_pos, count, 21); // Number of Players + + if (isRated) // arena TODO : Fix Order on Rated Implementation + { + // it seems this must be according to BG_WINNER_A/H and _NOT_ BG_TEAM_A/H + for (int8 i = 1; i >= 0; --i) { - sLog->outError(LOG_FILTER_BATTLEGROUND, "Battleground %u scoreboard has more entries (%u) than allowed players in this bg (%u)", bg->GetTypeID(true), bg->GetPlayerScoresSize(), bg->GetMaxPlayers()); - break; + int32 rating_change = bg->GetArenaTeamRatingChangeByIndex(i); + + uint32 pointsLost = rating_change < 0 ? -rating_change : 0; + uint32 pointsGained = rating_change > 0 ? rating_change : 0; + uint32 MatchmakerRating = bg->GetArenaMatchmakerRatingByIndex(i); + + *data << uint32(pointsLost); // Rating Lost + *data << uint32(pointsGained); // Rating gained + *data << uint32(MatchmakerRating); // Matchmaking Value + sLog->outDebug(LOG_FILTER_BATTLEGROUND, "rating change: %d", rating_change); } } - data->put(wpos, scoreCount); + data->append(buff); + + if (isArena) + for (int8 i = 1; i >= 0; --i) + if (ArenaTeam* at = sArenaTeamMgr->GetArenaTeamById(bg->GetArenaTeamIdByIndex(i))) + data->WriteString(at->GetName()); + + *data << uint8(0); // unk + + if (bg->GetStatus() == STATUS_WAIT_LEAVE) + *data << uint8(bg->GetWinner()); // who win + + *data << uint8(0); // unk } -void BattlegroundMgr::BuildGroupJoinedBattlegroundPacket(WorldPacket* data, GroupJoinBattlegroundResult result) +void BattlegroundMgr::BuildGroupJoinedBattlegroundPacket(WorldPacket* data, Battleground* bg, Player* pPlayer, GroupJoinBattlegroundResult result) { - data->Initialize(SMSG_GROUP_JOINED_BATTLEGROUND, 4); - *data << int32(result); - if (result == ERR_BATTLEGROUND_JOIN_TIMED_OUT || result == ERR_BATTLEGROUND_JOIN_FAILED) - *data << uint64(0); // player guid + ObjectGuid guidBytes1 = pPlayer->GetGUID(); + ObjectGuid guidBytes2 = bg->GetGUID(); + + data->Initialize(SMSG_BATTLEFIELD_STATUS_FAILED); + } void BattlegroundMgr::BuildUpdateWorldStatePacket(WorldPacket* data, uint32 field, uint32 value) @@ -442,14 +681,52 @@ void BattlegroundMgr::BuildPlaySoundPacket(WorldPacket* data, uint32 soundid) void BattlegroundMgr::BuildPlayerLeftBattlegroundPacket(WorldPacket* data, uint64 guid) { + ObjectGuid guidBytes = guid; + data->Initialize(SMSG_BATTLEGROUND_PLAYER_LEFT, 8); - *data << uint64(guid); + + data->WriteBit(guidBytes[7]); + data->WriteBit(guidBytes[6]); + data->WriteBit(guidBytes[2]); + data->WriteBit(guidBytes[4]); + data->WriteBit(guidBytes[5]); + data->WriteBit(guidBytes[1]); + data->WriteBit(guidBytes[3]); + data->WriteBit(guidBytes[0]); + + data->WriteByteSeq(guidBytes[4]); + data->WriteByteSeq(guidBytes[2]); + data->WriteByteSeq(guidBytes[5]); + data->WriteByteSeq(guidBytes[7]); + data->WriteByteSeq(guidBytes[0]); + data->WriteByteSeq(guidBytes[6]); + data->WriteByteSeq(guidBytes[1]); + data->WriteByteSeq(guidBytes[3]); } -void BattlegroundMgr::BuildPlayerJoinedBattlegroundPacket(WorldPacket* data, Player* player) +void BattlegroundMgr::BuildPlayerJoinedBattlegroundPacket(WorldPacket* data, uint64 guid) { + ObjectGuid guidBytes = guid; + data->Initialize(SMSG_BATTLEGROUND_PLAYER_JOINED, 8); - *data << uint64(player->GetGUID()); + + data->WriteBit(guidBytes[0]); + data->WriteBit(guidBytes[4]); + data->WriteBit(guidBytes[3]); + data->WriteBit(guidBytes[5]); + data->WriteBit(guidBytes[7]); + data->WriteBit(guidBytes[6]); + data->WriteBit(guidBytes[2]); + data->WriteBit(guidBytes[1]); + + data->WriteByteSeq(guidBytes[1]); + data->WriteByteSeq(guidBytes[5]); + data->WriteByteSeq(guidBytes[3]); + data->WriteByteSeq(guidBytes[2]); + data->WriteByteSeq(guidBytes[0]); + data->WriteByteSeq(guidBytes[7]); + data->WriteByteSeq(guidBytes[4]); + data->WriteByteSeq(guidBytes[6]); } Battleground* BattlegroundMgr::GetBattlegroundThroughClientInstance(uint32 instanceId, BattlegroundTypeId bgTypeId) @@ -846,63 +1123,68 @@ void BattlegroundMgr::BuildBattlegroundListPacket(WorldPacket* data, uint64 guid if (!player) return; - uint32 winner_kills = player->GetRandomWinner() ? BG_REWARD_WINNER_HONOR_LAST : BG_REWARD_WINNER_HONOR_FIRST; - uint32 winner_arena = player->GetRandomWinner() ? BG_REWARD_WINNER_ARENA_LAST : BG_REWARD_WINNER_ARENA_FIRST; - uint32 loser_kills = player->GetRandomWinner() ? BG_REWARD_LOSER_HONOR_LAST : BG_REWARD_LOSER_HONOR_FIRST; + uint32 winner_conquest = player->GetRandomWinner() ? BG_REWARD_WINNER_CONQUEST_FIRST : BG_REWARD_WINNER_CONQUEST_LAST; + uint32 winner_honor = player->GetRandomWinner() ? BG_REWARD_WINNER_HONOR_FIRST : BG_REWARD_WINNER_HONOR_LAST; + uint32 loser_honor = !player->GetRandomWinner() ? BG_REWARD_LOSER_HONOR_FIRST : BG_REWARD_LOSER_HONOR_LAST; - winner_kills = Trinity::Honor::hk_honor_at_level(player->getLevel(), float(winner_kills)); - loser_kills = Trinity::Honor::hk_honor_at_level(player->getLevel(), float(loser_kills)); + ObjectGuid guidBytes = guid; data->Initialize(SMSG_BATTLEFIELD_LIST); - // TODO: Fix guid - *data << uint64(guid); // battlemaster guid + *data << uint32(winner_conquest); // Winner Conquest Reward or Random Winner Conquest Reward + *data << uint32(winner_conquest); // Winner Conquest Reward or Random Winner Conquest Reward + *data << uint32(loser_honor); // Loser Honor Reward or Random Loser Honor Reward *data << uint32(bgTypeId); // battleground id - *data << uint8(0); // unk - *data << uint8(0); // unk - - // Rewards - *data << uint8(player->GetRandomWinner()); // 3.3.3 hasWin - *data << uint32(winner_kills); // 3.3.3 winHonor - *data << uint32(winner_arena); // 3.3.3 winArena - *data << uint32(loser_kills); // 3.3.3 lossHonor - - uint8 isRandom = bgTypeId == BATTLEGROUND_RB; - - *data << uint8(isRandom); // 3.3.3 isRandom - if (isRandom) - { - // Rewards (random) - *data << uint8(player->GetRandomWinner()); // 3.3.3 hasWin_Random - *data << uint32(winner_kills); // 3.3.3 winHonor_Random - *data << uint32(winner_arena); // 3.3.3 winArena_Random - *data << uint32(loser_kills); // 3.3.3 lossHonor_Random - } - - if (bgTypeId == BATTLEGROUND_AA) // arena + *data << uint32(loser_honor); // Loser Honor Reward or Random Loser Honor Reward + *data << uint32(winner_honor); // Winner Honor Reward or Random Winner Honor Reward + *data << uint32(winner_honor); // Winner Honor Reward or Random Winner Honor Reward + *data << uint8(0); // max level + *data << uint8(0); // min level + + data->WriteBit(guidBytes[0]); + data->WriteBit(guidBytes[1]); + data->WriteBit(guidBytes[7]); + data->WriteBit(0); // unk + data->WriteBit(0); // unk + + data->FlushBits(); + size_t count_pos = data->bitwpos(); + data->WriteBits(0, 24); // placeholder + + data->WriteBit(guidBytes[6]); + data->WriteBit(guidBytes[4]); + data->WriteBit(guidBytes[2]); + data->WriteBit(guidBytes[3]); + data->WriteBit(0); // unk + data->WriteBit(guidBytes[5]); + data->WriteBit(0); // unk + + data->FlushBits(); + + data->WriteByteSeq(guidBytes[6]); + data->WriteByteSeq(guidBytes[1]); + data->WriteByteSeq(guidBytes[7]); + data->WriteByteSeq(guidBytes[5]); + + if (Battleground* bgTemplate = sBattlegroundMgr->GetBattlegroundTemplate(bgTypeId)) { - *data << uint32(0); // unk (count?) - } - else // battleground - { - size_t count_pos = data->wpos(); - *data << uint32(0); // number of bg instances - - if (Battleground* bgTemplate = sBattlegroundMgr->GetBattlegroundTemplate(bgTypeId)) + // expected bracket entry + if (PvPDifficultyEntry const* bracketEntry = GetBattlegroundBracketByLevel(bgTemplate->GetMapId(), player->getLevel())) { - // expected bracket entry - if (PvPDifficultyEntry const* bracketEntry = GetBattlegroundBracketByLevel(bgTemplate->GetMapId(), player->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) { - 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) - { - *data << uint32(*itr); - ++count; - } - data->put<uint32>(count_pos, count); + *data << uint32(*itr); // instance id + ++count; } + data->PutBits(count_pos, count, 24); // bg instance count } } + + data->WriteByteSeq(guidBytes[0]); + data->WriteByteSeq(guidBytes[2]); + data->WriteByteSeq(guidBytes[4]); + data->WriteByteSeq(guidBytes[3]); } void BattlegroundMgr::SendToBattleground(Player* player, uint32 instanceId, BattlegroundTypeId bgTypeId) diff --git a/src/server/game/Battlegrounds/BattlegroundMgr.h b/src/server/game/Battlegrounds/BattlegroundMgr.h index 4edad4da742..a161f36fc6d 100755 --- a/src/server/game/Battlegrounds/BattlegroundMgr.h +++ b/src/server/game/Battlegrounds/BattlegroundMgr.h @@ -66,14 +66,14 @@ class BattlegroundMgr void Update(uint32 diff); /* Packet Building */ - void BuildPlayerJoinedBattlegroundPacket(WorldPacket* data, Player* player); + void BuildPlayerJoinedBattlegroundPacket(WorldPacket* data, uint64 guid); void BuildPlayerLeftBattlegroundPacket(WorldPacket* data, uint64 guid); void BuildBattlegroundListPacket(WorldPacket* data, uint64 guid, Player* player, BattlegroundTypeId bgTypeId); - void BuildGroupJoinedBattlegroundPacket(WorldPacket* data, GroupJoinBattlegroundResult result); + void BuildGroupJoinedBattlegroundPacket(WorldPacket* data, Battleground* bg, Player* player, GroupJoinBattlegroundResult result); void BuildUpdateWorldStatePacket(WorldPacket* data, uint32 field, uint32 value); void BuildPvpLogDataPacket(WorldPacket* data, Battleground* bg); - void BuildBattlegroundStatusPacket(WorldPacket* data, Battleground* bg, uint8 QueueSlot, uint8 StatusID, uint32 Time1, uint32 Time2, uint8 arenatype, uint8 uiFrame = 1); - void BuildPlaySoundPacket(WorldPacket* data, uint32 soundid); + void BuildBattlegroundStatusPacket(WorldPacket* data, Battleground* bg, Player* player, uint8 queueSlot, uint8 statusId, uint32 time1, uint32 time2, uint8 arenaType, uint8 uiFrame = 1); + void BuildPlaySoundPacket(WorldPacket* data, uint32 soundId); void SendAreaSpiritHealerQueryOpcode(Player* player, Battleground* bg, uint64 guid); /* Battlegrounds */ diff --git a/src/server/game/Battlegrounds/BattlegroundQueue.cpp b/src/server/game/Battlegrounds/BattlegroundQueue.cpp index 85d41977d13..7e7502b0538 100755 --- a/src/server/game/Battlegrounds/BattlegroundQueue.cpp +++ b/src/server/game/Battlegrounds/BattlegroundQueue.cpp @@ -391,7 +391,7 @@ void BattlegroundQueue::RemovePlayer(uint64 guid, bool decreaseInvitedCount) plr2->RemoveBattlegroundQueueId(bgQueueTypeId); // must be called this way, because if you move this call to // queue->removeplayer, it causes bugs WorldPacket data; - sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, queueSlot, STATUS_NONE, 0, 0, 0); + sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, plr2, queueSlot, STATUS_NONE, 0, 0, 0); plr2->GetSession()->SendPacket(&data); } // then actually delete, this may delete the group as well! @@ -470,7 +470,7 @@ bool BattlegroundQueue::InviteGroupToBG(GroupQueueInfo* ginfo, Battleground* bg, sLog->outDebug(LOG_FILTER_BATTLEGROUND, "Battleground: invited player %s (%u) to BG instance %u queueindex %u bgtype %u, I can't help it if they don't press the enter battle button.", player->GetName(), player->GetGUIDLow(), bg->GetInstanceID(), queueSlot, bg->GetTypeID()); // send status packet - sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, queueSlot, STATUS_WAIT_JOIN, INVITE_ACCEPT_WAIT_TIME, 0, ginfo->ArenaType); + sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, player, queueSlot, STATUS_WAIT_JOIN, INVITE_ACCEPT_WAIT_TIME, 0, ginfo->ArenaType); player->GetSession()->SendPacket(&data); } return true; @@ -1022,7 +1022,7 @@ bool BGQueueInviteEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/) { WorldPacket data; //we must send remaining time in queue - sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, queueSlot, STATUS_WAIT_JOIN, INVITE_ACCEPT_WAIT_TIME - INVITATION_REMIND_TIME, 0, m_ArenaType); + sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, player, queueSlot, STATUS_WAIT_JOIN, INVITE_ACCEPT_WAIT_TIME - INVITATION_REMIND_TIME, 0, m_ArenaType); player->GetSession()->SendPacket(&data); } } @@ -1070,7 +1070,7 @@ bool BGQueueRemoveEvent::Execute(uint64 /*e_time*/, uint32 /*p_time*/) sBattlegroundMgr->ScheduleQueueUpdate(0, 0, m_BgQueueTypeId, m_BgTypeId, bg->GetBracketId()); WorldPacket data; - sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, queueSlot, STATUS_NONE, 0, 0, 0); + sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, player, queueSlot, STATUS_NONE, 0, 0, 0); player->GetSession()->SendPacket(&data); } } diff --git a/src/server/game/Battlegrounds/Zones/BattlegroundWS.cpp b/src/server/game/Battlegrounds/Zones/BattlegroundWS.cpp index 051234f1e4f..d2f5d43c187 100755 --- a/src/server/game/Battlegrounds/Zones/BattlegroundWS.cpp +++ b/src/server/game/Battlegrounds/Zones/BattlegroundWS.cpp @@ -52,6 +52,8 @@ BattlegroundWS::BattlegroundWS() StartMessageIds[BG_STARTING_EVENT_SECOND] = LANG_BG_WS_START_ONE_MINUTE; StartMessageIds[BG_STARTING_EVENT_THIRD] = LANG_BG_WS_START_HALF_MINUTE; StartMessageIds[BG_STARTING_EVENT_FOURTH] = LANG_BG_WS_HAS_BEGUN; + _flagSpellForceTimer = 0; + _bothFlagsKept = false; _flagDebuffState = 0; } diff --git a/src/server/game/Chat/Chat.h b/src/server/game/Chat/Chat.h index c0560ee0e27..bbb9870338c 100644 --- a/src/server/game/Chat/Chat.h +++ b/src/server/game/Chat/Chat.h @@ -47,8 +47,8 @@ class ChatHandler { public: WorldSession* GetSession() { return m_session; } - explicit ChatHandler(WorldSession* session) : m_session(session) {} - explicit ChatHandler(Player* player) : m_session(player->GetSession()) {} + explicit ChatHandler(WorldSession* session) : m_session(session), sentErrorMessage(false) {} + explicit ChatHandler(Player* player) : m_session(player->GetSession()), sentErrorMessage(false) {} virtual ~ChatHandler() {} static void FillMessageData(WorldPacket* data, WorldSession* session, uint8 type, uint32 language, const char *channelName, uint64 target_guid, const char *message, Unit* speaker, const char* addonPrefix = NULL); @@ -126,7 +126,7 @@ class ChatHandler bool ShowHelpForCommand(ChatCommand* table, const char* cmd); protected: - explicit ChatHandler() : m_session(NULL) {} // for CLI subclass + explicit ChatHandler() : m_session(NULL), sentErrorMessage(false) {} // for CLI subclass static bool SetDataForCommandInTable(ChatCommand* table, const char* text, uint32 security, std::string const& help, std::string const& fullcommand); bool ExecuteCommandInTable(ChatCommand* table, const char* text, const std::string& fullcmd); bool ShowHelpForSubCommands(ChatCommand* table, char const* cmd, char const* subcmd); diff --git a/src/server/game/Combat/UnitEvents.h b/src/server/game/Combat/UnitEvents.h index de60491de89..07d8b20af52 100755 --- a/src/server/game/Combat/UnitEvents.h +++ b/src/server/game/Combat/UnitEvents.h @@ -123,8 +123,8 @@ class ThreatManagerEvent : public ThreatRefStatusChangeEvent private: ThreatContainer* iThreatContainer; public: - ThreatManagerEvent(uint32 pType) : ThreatRefStatusChangeEvent(pType) {} - ThreatManagerEvent(uint32 pType, HostileReference* pHostileReference) : ThreatRefStatusChangeEvent(pType, pHostileReference) {} + ThreatManagerEvent(uint32 pType) : ThreatRefStatusChangeEvent(pType), iThreatContainer(NULL) {} + ThreatManagerEvent(uint32 pType, HostileReference* pHostileReference) : ThreatRefStatusChangeEvent(pType, pHostileReference), iThreatContainer(NULL) {} void setThreatContainer(ThreatContainer* pThreatContainer) { iThreatContainer = pThreatContainer; } diff --git a/src/server/game/Conditions/ConditionMgr.cpp b/src/server/game/Conditions/ConditionMgr.cpp index ab3c6aba791..d1db3d9577c 100755 --- a/src/server/game/Conditions/ConditionMgr.cpp +++ b/src/server/game/Conditions/ConditionMgr.cpp @@ -867,7 +867,6 @@ void ConditionMgr::LoadConditions(bool isReload) valid = true; ++count; continue; // do not add to m_AllocatedMemory to avoid double deleting - break; } case CONDITION_SOURCE_TYPE_SPELL_IMPLICIT_TARGET: valid = addToSpellImplicitTargetConditions(cond); diff --git a/src/server/game/DataStores/DBCEnums.h b/src/server/game/DataStores/DBCEnums.h index cd8accd3759..5ab9949d9cf 100755 --- a/src/server/game/DataStores/DBCEnums.h +++ b/src/server/game/DataStores/DBCEnums.h @@ -19,18 +19,21 @@ #ifndef DBCENUMS_H #define DBCENUMS_H -// Client expected level limitation, like as used in DBC item max levels for "until max player level" -// use as default max player level, must be fit max level for used client -// also see MAX_LEVEL and STRONG_MAX_LEVEL define -#define DEFAULT_MAX_LEVEL 85 - -// client supported max level for player/pets/etc. Avoid overflow or client stability affected. -// also see GT_MAX_LEVEL define -#define MAX_LEVEL 100 - -// Server side limitation. Base at used code requirements. -// also see MAX_LEVEL and GT_MAX_LEVEL define -#define STRONG_MAX_LEVEL 255 +enum LevelLimit +{ + // Client expected level limitation, like as used in DBC item max levels for "until max player level" + // use as default max player level, must be fit max level for used client + // also see MAX_LEVEL and STRONG_MAX_LEVEL define + DEFAULT_MAX_LEVEL = 85, + + // client supported max level for player/pets/etc. Avoid overflow or client stability affected. + // also see GT_MAX_LEVEL define + MAX_LEVEL = 100, + + // Server side limitation. Base at used code requirements. + // also see MAX_LEVEL and GT_MAX_LEVEL define + STRONG_MAX_LEVEL = 255, +}; enum BattlegroundBracketId // bracketId for level ranges { @@ -58,27 +61,30 @@ enum AchievementFaction enum AchievementFlags { - ACHIEVEMENT_FLAG_COUNTER = 0x00000001, // Just count statistic (never stop and complete) - ACHIEVEMENT_FLAG_HIDDEN = 0x00000002, // Not sent to client - internal use only - ACHIEVEMENT_FLAG_PLAY_NO_VISUAL = 0x00000004, // Client does not play achievement earned visual - ACHIEVEMENT_FLAG_SUMM = 0x00000008, // Use summ criteria value from all reqirements (and calculate max value) - ACHIEVEMENT_FLAG_MAX_USED = 0x00000010, // Show max criteria (and calculate max value ??) - ACHIEVEMENT_FLAG_REQ_COUNT = 0x00000020, // Use not zero req count (and calculate max value) - ACHIEVEMENT_FLAG_AVERAGE = 0x00000040, // Show as average value (value / time_in_days) depend from other flag (by def use last criteria value) - ACHIEVEMENT_FLAG_BAR = 0x00000080, // Show as progress bar (value / max vale) depend from other flag (by def use last criteria value) - ACHIEVEMENT_FLAG_REALM_FIRST_REACH = 0x00000100, // - ACHIEVEMENT_FLAG_REALM_FIRST_KILL = 0x00000200, // - ACHIEVEMENT_FLAG_UNK3 = 0x00000400, // ACHIEVEMENT_FLAG_HIDE_NAME_IN_TIE - ACHIEVEMENT_FLAG_REALM_FIRST_GUILD = 0x00000800, // first guild on realm done something - ACHIEVEMENT_FLAG_SHOW_IN_GUILD_NEWS = 0x00001000, // Shows in guild news - ACHIEVEMENT_FLAG_SHOW_IN_GUILD_HEADER = 0x00002000, // Shows in guild news header - ACHIEVEMENT_FLAG_GUILD = 0x00004000, // - ACHIEVEMENT_FLAG_SHOW_GUILD_MEMBERS = 0x00008000, // - ACHIEVEMENT_FLAG_SHOW_CRITERIA_MEMBERS = 0x00010000, // - + ACHIEVEMENT_FLAG_COUNTER = 0x00000001, // Just count statistic (never stop and complete) + ACHIEVEMENT_FLAG_HIDDEN = 0x00000002, // Not sent to client - internal use only + ACHIEVEMENT_FLAG_PLAY_NO_VISUAL = 0x00000004, // Client does not play achievement earned visual + ACHIEVEMENT_FLAG_SUMM = 0x00000008, // Use summ criteria value from all requirements (and calculate max value) + ACHIEVEMENT_FLAG_MAX_USED = 0x00000010, // Show max criteria (and calculate max value ??) + ACHIEVEMENT_FLAG_REQ_COUNT = 0x00000020, // Use not zero req count (and calculate max value) + ACHIEVEMENT_FLAG_AVERAGE = 0x00000040, // Show as average value (value / time_in_days) depend from other flag (by def use last criteria value) + ACHIEVEMENT_FLAG_BAR = 0x00000080, // Show as progress bar (value / max vale) depend from other flag (by def use last criteria value) + ACHIEVEMENT_FLAG_REALM_FIRST_REACH = 0x00000100, // + ACHIEVEMENT_FLAG_REALM_FIRST_KILL = 0x00000200, // + ACHIEVEMENT_FLAG_UNK3 = 0x00000400, // ACHIEVEMENT_FLAG_HIDE_NAME_IN_TIE + ACHIEVEMENT_FLAG_REALM_FIRST_GUILD = 0x00000800, // first guild on realm done something + ACHIEVEMENT_FLAG_SHOW_IN_GUILD_NEWS = 0x00001000, // Shows in guild news + ACHIEVEMENT_FLAG_SHOW_IN_GUILD_HEADER = 0x00002000, // Shows in guild news header + ACHIEVEMENT_FLAG_GUILD = 0x00004000, // + ACHIEVEMENT_FLAG_SHOW_GUILD_MEMBERS = 0x00008000, // + ACHIEVEMENT_FLAG_SHOW_CRITERIA_MEMBERS = 0x00010000, // }; -#define MAX_CRITERIA_REQUIREMENTS 2 +enum +{ + MAX_CRITERIA_REQUIREMENTS = 2, + MAX_ADDITIONAL_CRITERIA_CONDITIONS = 3 +}; enum AchievementCriteriaCondition { @@ -92,80 +98,53 @@ enum AchievementCriteriaCondition ACHIEVEMENT_CRITERIA_CONDITION_UNK3 = 13, // unk }; -#define MAX_ADDITIONAL_CRITERIA_CONDITIONS 3 - enum AchievementCriteriaAdditionalCondition { - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_DRUNK_VALUE = 1, // NYI - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK2 = 2, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_LEVEL = 3, // NYI - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CREATURE_ENTRY = 4, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_PLAYER = 5, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_DEAD = 6, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_ENEMY = 7, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_HAS_AURA = 8, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK9 = 9, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_HAS_AURA = 10, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_MOUNTED = 11, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK12 = 12, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK13 = 13, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_QUALITY_MIN = 14, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_QUALITY_EQUALS = 15, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK16 = 16, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_AREA = 17, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_ZONE = 18, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK19 = 19, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MAP_DIFFICULTY = 20, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CREATURE_YIELDS_XP = 21, // NYI - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK22 = 22, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK23 = 23, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_ARENA_TEAM_SIZE = 24, // NYI - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_RACE = 25, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_CLASS = 26, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_RACE = 27, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CLASS = 28, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MAX_GROUP_MEMBERS = 29, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CREATURE_TYPE = 30, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK31 = 31, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_MAP = 32, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_CLASS = 33, // NYI - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_SUBCLASS = 34, // NYI - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK35 = 35, // related to timed completing-quests achievements - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK36 = 36, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MIN_PERSONAL_RATING = 37, // NYI (when implementing don't forget about ACHIEVEMENT_CRITERIA_CONDITION_NO_LOSE) - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TITLE_BIT_INDEX = 38, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_LEVEL = 39, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_LEVEL = 40, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_ZONE = 41, // NYI - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK42 = 42, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK43 = 43, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK44 = 44, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK45 = 45, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_HEALTH_PERCENT_BELOW = 46, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK47 = 47, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK48 = 48, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK49 = 49, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK50 = 50, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK51 = 51, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK52 = 52, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK53 = 53, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK54 = 54, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK55 = 55, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MIN_ACHIEVEMENT_POINTS = 56, // NYI - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK57 = 57, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_REQUIRES_LFG_GROUP = 58, // NYI - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK59 = 59, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK60 = 60, - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_REQUIRES_GUILD_GROUP = 61, // NYI - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_GUILD_REPUTATION = 62, // NYI - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_RATED_BATTLEGROUND = 63, // NYI - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK64 = 64, // unused in 4.0.6a - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK65 = 65, // Archaeology, item quality related - ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK66 = 66, // Archaeology, race related + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_DRUNK_VALUE = 1, // NYI + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK2 = 2, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_LEVEL = 3, // NYI + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CREATURE_ENTRY = 4, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_PLAYER = 5, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_DEAD = 6, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_ENEMY = 7, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_HAS_AURA = 8, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_HAS_AURA = 10, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_MOUNTED = 11, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_QUALITY_MIN = 14, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_QUALITY_EQUALS = 15, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK16 = 16, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_AREA = 17, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_ZONE = 18, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MAP_DIFFICULTY = 20, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CREATURE_YIELDS_XP = 21, // NYI + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_ARENA_TEAM_SIZE = 24, // NYI + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_RACE = 25, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_CLASS = 26, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_RACE = 27, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CLASS = 28, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MAX_GROUP_MEMBERS = 29, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CREATURE_TYPE = 30, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_MAP = 32, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_CLASS = 33, // NYI + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_SUBCLASS = 34, // NYI + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK35 = 35, // related to timed completing-quests achievements + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MIN_PERSONAL_RATING = 37, // NYI (when implementing don't forget about ACHIEVEMENT_CRITERIA_CONDITION_NO_LOSE) + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TITLE_BIT_INDEX = 38, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_LEVEL = 39, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_LEVEL = 40, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_ZONE = 41, // NYI + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_HEALTH_PERCENT_BELOW = 46, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK55 = 55, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MIN_ACHIEVEMENT_POINTS = 56, // NYI + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_REQUIRES_LFG_GROUP = 58, // NYI + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_UNK60 = 60, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_REQUIRES_GUILD_GROUP = 61, // NYI + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_GUILD_REPUTATION = 62, // NYI + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_RATED_BATTLEGROUND = 63, // NYI + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_PROJECT_RARITY = 65, + ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_PROJECT_RACE = 66, }; -#define MAX_ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TYPE 66 - enum AchievementCriteriaFlags { ACHIEVEMENT_CRITERIA_FLAG_SHOW_PROGRESS_BAR = 0x00000001, // Show progress as bar @@ -198,8 +177,7 @@ enum AchievementCriteriaTypes ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL = 7, ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT = 8, ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT = 9, - // you have to complete a daily quest x times in a row - ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY = 10, + ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY = 10, // you have to complete a daily quest x times in a row ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE = 11, ACHIEVEMENT_CRITERIA_TYPE_CURRENCY = 12, ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE = 13, @@ -234,18 +212,15 @@ enum AchievementCriteriaTypes ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT = 45, ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION = 46, ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION = 47, - // noted: rewarded as soon as the player payed, not at taking place at the seat ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP = 48, ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM = 49, - // TODO: itemlevel is mentioned in text but not present in dbc - ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT = 50, + ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT = 50, // TODO: itemlevel is mentioned in text but not present in dbc ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT = 51, ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS = 52, ACHIEVEMENT_CRITERIA_TYPE_HK_RACE = 53, ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE = 54, ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE = 55, - // TODO: in some cases map not present, and in some cases need do without die - ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS = 56, + ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS = 56, // TODO: in some cases map not present, and in some cases need do without die ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM = 57, ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS = 59, ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS = 60, @@ -259,13 +234,11 @@ enum AchievementCriteriaTypes ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2 = 69, ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL = 70, ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT = 72, - // TODO: title id is not mentioned in dbc - ACHIEVEMENT_CRITERIA_TYPE_EARNED_PVP_TITLE = 74, + ACHIEVEMENT_CRITERIA_TYPE_EARNED_PVP_TITLE = 74, // TODO: title id is not mentioned in dbc ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS = 75, ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL = 76, ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL = 77, - // TODO: creature type (demon, undead etc.) is not stored in dbc - ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE = 78, + ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE = 78, // TODO: creature type (demon, undead etc.) is not stored in dbc ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS = 80, ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION = 82, ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID = 83, @@ -288,8 +261,7 @@ enum AchievementCriteriaTypes ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED = 107, ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN = 108, ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE = 109, - // TODO: target entry is missing - ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2 = 110, + ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2 = 110, // TODO: target entry is missing ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE = 112, ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL = 113, ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS = 114, @@ -326,10 +298,10 @@ enum AchievementCriteriaTypes ACHIEVEMENT_CRITERIA_TYPE_UNK148 = 148, ACHIEVEMENT_CRITERIA_TYPE_UNK149 = 149, ACHIEVEMENT_CRITERIA_TYPE_UNK150 = 150, - // 0..144 => 145 criteria types total - ACHIEVEMENT_CRITERIA_TYPE_TOTAL = 151, }; +#define ACHIEVEMENT_CRITERIA_TYPE_TOTAL 151 + enum AchievementCategory { CATEGORY_CHILDRENS_WEEK = 163, diff --git a/src/server/game/DataStores/DBCStructure.h b/src/server/game/DataStores/DBCStructure.h index b12aee36fc1..1d397e8f3ec 100644 --- a/src/server/game/DataStores/DBCStructure.h +++ b/src/server/game/DataStores/DBCStructure.h @@ -67,8 +67,8 @@ struct AchievementCategoryEntry struct AchievementCriteriaEntry { uint32 ID; // 0 - uint32 referredAchievement; // 1 - uint32 requiredType; // 2 + uint32 achievement; // 1 + uint32 type; // 2 union { // ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE = 0 diff --git a/src/server/game/Entities/Corpse/Corpse.cpp b/src/server/game/Entities/Corpse/Corpse.cpp index 653a731b5b2..3e7dfc125f9 100755 --- a/src/server/game/Entities/Corpse/Corpse.cpp +++ b/src/server/game/Entities/Corpse/Corpse.cpp @@ -26,8 +26,7 @@ #include "GossipDef.h" #include "World.h" -Corpse::Corpse(CorpseType type) : WorldObject(type != CORPSE_BONES) -, m_type(type) +Corpse::Corpse(CorpseType type) : WorldObject(type != CORPSE_BONES), m_type(type) { m_objectType |= TYPEMASK_CORPSE; m_objectTypeId = TYPEID_CORPSE; @@ -39,6 +38,7 @@ Corpse::Corpse(CorpseType type) : WorldObject(type != CORPSE_BONES) m_time = time(NULL); lootForBody = false; + lootRecipient = NULL; } Corpse::~Corpse() diff --git a/src/server/game/Entities/Creature/Creature.cpp b/src/server/game/Entities/Creature/Creature.cpp index 6e2fc197a5f..6270b3b64c0 100755 --- a/src/server/game/Entities/Creature/Creature.cpp +++ b/src/server/game/Entities/Creature/Creature.cpp @@ -381,7 +381,7 @@ bool Creature::UpdateEntry(uint32 Entry, uint32 team, const CreatureData* data) SetAttackTime(RANGED_ATTACK, cInfo->rangeattacktime); SetUInt32Value(UNIT_FIELD_FLAGS, unit_flags); - SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER); + SetUInt32Value(UNIT_FIELD_FLAGS_2, cInfo->unit_flags2); SetUInt32Value(UNIT_DYNAMIC_FLAGS, dynamicflags); diff --git a/src/server/game/Entities/Creature/Creature.h b/src/server/game/Entities/Creature/Creature.h index 14a680d62d1..669d8461d34 100755 --- a/src/server/game/Entities/Creature/Creature.h +++ b/src/server/game/Entities/Creature/Creature.h @@ -112,6 +112,7 @@ struct CreatureTemplate uint32 rangeattacktime; uint32 unit_class; // enum Classes. Note only 4 classes are known for creatures. uint32 unit_flags; // enum UnitFlags mask values + uint32 unit_flags2; // enum UnitFlags2 mask values uint32 dynamicflags; uint32 family; // enum CreatureFamily values (optional) uint32 trainer_type; diff --git a/src/server/game/Entities/Creature/GossipDef.cpp b/src/server/game/Entities/Creature/GossipDef.cpp index 05ec6f6920d..52a9de09f30 100755 --- a/src/server/game/Entities/Creature/GossipDef.cpp +++ b/src/server/game/Entities/Creature/GossipDef.cpp @@ -417,8 +417,8 @@ void PlayerMenu::SendQuestQueryResponse(Quest const* quest) const data << int32(quest->GetRewSpellCast()); // casted spell // rewarded honor points - data << Trinity::Honor::hk_honor_at_level(_session->GetPlayer()->getLevel(), quest->GetRewHonorMultiplier()); - data << float(0); // new reward honor (multipled by ~62 at client side) + data << uint32(quest->GetRewHonorAddition()); + data << float(quest->GetRewHonorMultiplier()); data << uint32(quest->GetSrcItemId()); // source item id data << uint32(quest->GetFlags() & 0xFFFF); // quest flags data << uint32(quest->GetMinimapTargetMark()); // minimap target mark (skull, etc. missing enum) diff --git a/src/server/game/Entities/Creature/TemporarySummon.h b/src/server/game/Entities/Creature/TemporarySummon.h index f82dfa53f4d..b60197ff613 100755 --- a/src/server/game/Entities/Creature/TemporarySummon.h +++ b/src/server/game/Entities/Creature/TemporarySummon.h @@ -29,7 +29,7 @@ class TempSummon : public Creature void Update(uint32 time); virtual void InitStats(uint32 lifetime); virtual void InitSummon(); - void UnSummon(uint32 msTime = 0); + virtual void UnSummon(uint32 msTime = 0); void RemoveFromWorld(); void SetTempSummonType(TempSummonType type); void SaveToDB(uint32 /*mapid*/, uint8 /*spawnMask*/, uint32 /*phaseMask*/) {} diff --git a/src/server/game/Entities/GameObject/GameObject.cpp b/src/server/game/Entities/GameObject/GameObject.cpp index 18ed5632793..db0903832c0 100755 --- a/src/server/game/Entities/GameObject/GameObject.cpp +++ b/src/server/game/Entities/GameObject/GameObject.cpp @@ -1419,7 +1419,8 @@ void GameObject::Use(Unit* user) // full amount unique participants including original summoner if (GetUniqueUseCount() == info->summoningRitual.reqParticipants) { - spellCaster = m_ritualOwner ? m_ritualOwner : spellCaster; + if (m_ritualOwner) + spellCaster = m_ritualOwner; spellId = info->summoningRitual.spellId; diff --git a/src/server/game/Entities/Item/Item.cpp b/src/server/game/Entities/Item/Item.cpp index 3eb9aabab14..faa91c2672a 100755 --- a/src/server/game/Entities/Item/Item.cpp +++ b/src/server/game/Entities/Item/Item.cpp @@ -1039,7 +1039,7 @@ Item* Item::CreateItem(uint32 item, uint32 count, Player const* player) if (count > pProto->GetMaxStackSize()) count = pProto->GetMaxStackSize(); - ASSERT(count !=0 && "pProto->Stackable == 0 but checked at loading already"); + ASSERT(count != 0 && "pProto->Stackable == 0 but checked at loading already"); Item* pItem = NewItemOrBag(pProto); if (pItem->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_ITEM), item, player)) diff --git a/src/server/game/Entities/Object/Object.cpp b/src/server/game/Entities/Object/Object.cpp index 2ccb5b68bca..4b4bcfd019a 100644 --- a/src/server/game/Entities/Object/Object.cpp +++ b/src/server/game/Entities/Object/Object.cpp @@ -1916,10 +1916,10 @@ bool WorldObject::canSeeOrDetect(WorldObject const* obj, bool ignoreStealth, boo if (obj->IsAlwaysVisibleFor(this) || CanAlwaysSee(obj)) return true; - bool corpseCheck = false; bool corpseVisibility = false; if (distanceCheck) { + bool corpseCheck = false; if (Player const* thisPlayer = ToPlayer()) { if (thisPlayer->isDead() && thisPlayer->GetHealth() > 0 && // Cheap way to check for ghost state diff --git a/src/server/game/Entities/Object/ObjectDefines.h b/src/server/game/Entities/Object/ObjectDefines.h index 9fd4279a79c..b971943954e 100755 --- a/src/server/game/Entities/Object/ObjectDefines.h +++ b/src/server/game/Entities/Object/ObjectDefines.h @@ -43,6 +43,7 @@ enum HighGuid HIGHGUID_VEHICLE = 0xF15, // blizz F550 HIGHGUID_DYNAMICOBJECT = 0xF10, // blizz F100 HIGHGUID_CORPSE = 0xF101, // blizz F100 + HIGHGUID_TYPE_BATTLEGROUND = 0x1F1, // new 4.x HIGHGUID_MO_TRANSPORT = 0x1FC, // blizz 1FC0 (for GAMEOBJECT_TYPE_MO_TRANSPORT) HIGHGUID_GROUP = 0x1F5, HIGHGUID_GUILD = 0x1FF5, // new 4.x diff --git a/src/server/game/Entities/Player/Player.cpp b/src/server/game/Entities/Player/Player.cpp index 800498a82dd..180f43109f2 100644 --- a/src/server/game/Entities/Player/Player.cpp +++ b/src/server/game/Entities/Player/Player.cpp @@ -846,6 +846,8 @@ Player::Player(WorldSession* session): Unit(true), m_achievementMgr(this), m_rep m_SeasonalQuestChanged = false; SetPendingBind(0, 0); + + _activeCheats = CHEAT_NONE; memset(_voidStorageItems, 0, VOID_STORAGE_MAX_SLOT * sizeof(VoidStorageItem*)); } @@ -7337,7 +7339,6 @@ bool Player::HasCurrency(uint32 id, uint32 count) const PlayerCurrenciesMap::const_iterator itr = m_currencies.find(id); return itr != m_currencies.end() && itr->second.totalCount >= count; } - void Player::ModifyCurrency(uint32 id, int32 count, bool printLog/* = true*/) { if (!count) @@ -7379,7 +7380,6 @@ void Player::ModifyCurrency(uint32 id, int32 count, bool printLog/* = true*/) newTotalCount = int32(currency->TotalCap); newWeekCount -= delta; } - // TODO: fix conquest points uint32 weekCap = _GetCurrencyWeekCap(currency); if (weekCap && int32(weekCap) < newTotalCount) @@ -7599,13 +7599,9 @@ void Player::UpdateZone(uint32 newZone, uint32 newArea) { SetGroupUpdateFlag(GROUP_UPDATE_FULL); if (GetSession() && group->isLFGGroup() && sLFGMgr->IsTeleported(GetGUID())) - { for (GroupReference* itr = group->GetFirstMember(); itr != NULL; itr = itr->next()) - { if (Player* member = itr->getSource()) GetSession()->SendNameQueryOpcode(member->GetGUID()); - } - } } m_zoneUpdateId = newZone; @@ -7670,8 +7666,7 @@ void Player::UpdateZone(uint32 newZone, uint32 newArea) if (GetRestType() == REST_TYPE_IN_TAVERN) // Still inside a tavern or has recently left { // Remove rest state if we have recently left a tavern. - // Why is 40 yd hardcoded? - if (GetMapId() != GetInnPosMapId() || GetExactDist(GetInnPosX(), GetInnPosY(), GetInnPosZ()) > 40.0f) + if (GetMapId() != GetInnPosMapId() || GetExactDist(GetInnPosX(), GetInnPosY(), GetInnPosZ()) > 1.0f) { RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING); SetRestType(REST_TYPE_NO); @@ -9139,9 +9134,6 @@ void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid) case 2918: NumberOfFields = 8; break; - case 139: - NumberOfFields = 41; - break; case 1377: NumberOfFields = 15; break; @@ -9229,46 +9221,6 @@ void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid) case 2257: // Deeprun Tram case 3703: // Shattrath City break; - case 139: // Eastern Plaguelands - if (pvp && pvp->GetTypeId() == OUTDOOR_PVP_EP) - pvp->FillInitialWorldStates(data); - else - { - data << uint32(0x97a) << uint32(0x0); // 10 2426 - data << uint32(0x917) << uint32(0x0); // 11 2327 - data << uint32(0x918) << uint32(0x0); // 12 2328 - data << uint32(0x97b) << uint32(0x32); // 13 2427 - data << uint32(0x97c) << uint32(0x32); // 14 2428 - data << uint32(0x933) << uint32(0x1); // 15 2355 - data << uint32(0x946) << uint32(0x0); // 16 2374 - data << uint32(0x947) << uint32(0x0); // 17 2375 - data << uint32(0x948) << uint32(0x0); // 18 2376 - data << uint32(0x949) << uint32(0x0); // 19 2377 - data << uint32(0x94a) << uint32(0x0); // 20 2378 - data << uint32(0x94b) << uint32(0x0); // 21 2379 - data << uint32(0x932) << uint32(0x0); // 22 2354 - data << uint32(0x934) << uint32(0x0); // 23 2356 - data << uint32(0x935) << uint32(0x0); // 24 2357 - data << uint32(0x936) << uint32(0x0); // 25 2358 - data << uint32(0x937) << uint32(0x0); // 26 2359 - data << uint32(0x938) << uint32(0x0); // 27 2360 - data << uint32(0x939) << uint32(0x1); // 28 2361 - data << uint32(0x930) << uint32(0x1); // 29 2352 - data << uint32(0x93a) << uint32(0x0); // 30 2362 - data << uint32(0x93b) << uint32(0x0); // 31 2363 - data << uint32(0x93c) << uint32(0x0); // 32 2364 - data << uint32(0x93d) << uint32(0x0); // 33 2365 - data << uint32(0x944) << uint32(0x0); // 34 2372 - data << uint32(0x945) << uint32(0x0); // 35 2373 - data << uint32(0x931) << uint32(0x1); // 36 2353 - data << uint32(0x93e) << uint32(0x0); // 37 2366 - data << uint32(0x931) << uint32(0x1); // 38 2367 ?? grey horde not in dbc! send for consistency's sake, and to match field count - data << uint32(0x940) << uint32(0x0); // 39 2368 - data << uint32(0x941) << uint32(0x0); // 7 2369 - data << uint32(0x942) << uint32(0x0); // 8 2370 - data << uint32(0x943) << uint32(0x0); // 9 2371 - } - break; case 1377: // Silithus if (pvp && pvp->GetTypeId() == OUTDOOR_PVP_SI) pvp->FillInitialWorldStates(data); @@ -15601,7 +15553,6 @@ bool Player::TakeQuestSourceItem(uint32 questId, bool msg) { uint32 srcItemId = quest->GetSrcItemId(); ItemTemplate const* item = sObjectMgr->GetItemTemplate(srcItemId); - bool destroyItem = true; if (srcItemId > 0) { @@ -15621,6 +15572,7 @@ bool Player::TakeQuestSourceItem(uint32 questId, bool msg) return false; } + bool destroyItem = true; for (uint8 n = 0; n < QUEST_ITEM_OBJECTIVES_COUNT; ++n) if (item->StartQuest == questId && srcItemId == quest->RequiredItemId[n]) destroyItem = false; @@ -17039,7 +16991,7 @@ bool Player::LoadFromDB(uint32 guid, SQLQueryHolder *holder) SetUInt64Value(PLAYER_FARSIGHT, 0); SetCreatorGUID(0); - RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVE); + RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVEMENT); // reset some aura modifiers before aura apply SetUInt32Value(PLAYER_TRACK_CREATURES, 0); @@ -17465,8 +17417,8 @@ void Player::_LoadInventory(PreparedQueryResult result, uint32 timeDiff) { uint32 zoneId = GetZoneId(); - std::map<uint64, Bag*> bagMap; // fast guid lookup for bags - std::map<uint64, Item*> invalidBagMap; // fast guid lookup for bags + std::map<uint32, Bag*> bagMap; // fast guid lookup for bags + std::map<uint32, Item*> invalidBagMap; // fast guid lookup for bags std::list<Item*> problematicItems; SQLTransaction trans = CharacterDatabase.BeginTransaction(); @@ -17525,7 +17477,7 @@ void Player::_LoadInventory(PreparedQueryResult result, uint32 timeDiff) { item->SetSlot(NULL_SLOT); // Item is in the bag, find the bag - std::map<uint64, Bag*>::iterator itr = bagMap.find(bagGuid); + std::map<uint32, Bag*>::iterator itr = bagMap.find(bagGuid); if (itr != bagMap.end()) { ItemPosCountVec dest; @@ -17535,8 +17487,8 @@ void Player::_LoadInventory(PreparedQueryResult result, uint32 timeDiff) } else if (invalidBagMap.find(bagGuid) != invalidBagMap.end()) { - std::map<uint64, Item*>::iterator itr = invalidBagMap.find(bagGuid); - if (std::find(problematicItems.begin(),problematicItems.end(),itr->second) != problematicItems.end()) + std::map<uint32, Item*>::iterator itr = invalidBagMap.find(bagGuid); + if (std::find(problematicItems.begin(), problematicItems.end(), itr->second) != problematicItems.end()) err = EQUIP_ERR_INTERNAL_BAG_ERROR; } else @@ -17632,7 +17584,6 @@ void Player::_LoadVoidStorage(PreparedQueryResult result) Item* Player::_LoadItem(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, Field* fields) { - PreparedStatement* stmt = NULL; Item* item = NULL; uint32 itemGuid = fields[13].GetUInt32(); uint32 itemEntry = fields[14].GetUInt32(); @@ -17642,6 +17593,8 @@ Item* Player::_LoadItem(SQLTransaction& trans, uint32 zoneId, uint32 timeDiff, F item = NewItemOrBag(proto); if (item->LoadFromDB(itemGuid, GetGUID(), fields, itemEntry)) { + PreparedStatement* stmt = NULL; + // Do not allow to have item limited to another map/zone in alive state if (isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(), zoneId)) { diff --git a/src/server/game/Entities/Player/Player.h b/src/server/game/Entities/Player/Player.h index 09c7e0ff2a1..c4047485033 100755 --- a/src/server/game/Entities/Player/Player.h +++ b/src/server/game/Entities/Player/Player.h @@ -115,7 +115,7 @@ struct PlayerTalent // Spell modifier (used for modify other spells) struct SpellModifier { - SpellModifier(Aura* _ownerAura = NULL) : charges(0), ownerAura(_ownerAura) {} + SpellModifier(Aura* _ownerAura = NULL) : op(SPELLMOD_DAMAGE), type(SPELLMOD_FLAT), charges(0), value(0), mask(), spellId(0), ownerAura(_ownerAura) {} SpellModOp op : 8; SpellModType type : 8; int16 charges : 16; @@ -875,6 +875,16 @@ enum PlayerRestState REST_STATE_RAF_LINKED = 0x06 }; +enum PlayerCommandStates +{ + CHEAT_NONE = 0x00, + CHEAT_GOD = 0x01, + CHEAT_CASTTIME = 0x02, + CHEAT_COOLDOWN = 0x04, + CHEAT_POWER = 0x08, + CHEAT_WATERWALK = 0x10 +}; + class PlayerTaxi { public: @@ -1196,6 +1206,11 @@ class Player : public Unit, public GridObject<Player> void InitStatsForLevel(bool reapplyMods = false); + // .cheat command related + bool GetCommandStatus(uint32 command) const { return _activeCheats & command; } + void SetCommandStatusOn(uint32 command) { _activeCheats |= command; } + void SetCommandStatusOff(uint32 command) { _activeCheats &= ~command; } + // Played Time Stuff time_t m_logintime; time_t m_Last_tick; @@ -2936,6 +2951,8 @@ class Player : public Unit, public GridObject<Player> InstanceTimeMap _instanceResetTimes; uint32 _pendingBindId; uint32 _pendingBindTimer; + + uint32 _activeCheats; }; void AddItemsSetItem(Player*player, Item* item); diff --git a/src/server/game/Entities/Player/SocialMgr.h b/src/server/game/Entities/Player/SocialMgr.h index 3c7d13070fa..99a40d6110f 100755 --- a/src/server/game/Entities/Player/SocialMgr.h +++ b/src/server/game/Entities/Player/SocialMgr.h @@ -54,24 +54,12 @@ struct FriendInfo uint8 Class; std::string Note; - FriendInfo() + FriendInfo() : Status(FRIEND_STATUS_OFFLINE), Flags(0), Area(0), Level(0), Class(0), Note() { - Status = FRIEND_STATUS_OFFLINE; - Flags = 0; - Area = 0; - Level = 0; - Class = 0; - Note = ""; } - FriendInfo(uint8 flags, const std::string& note) + FriendInfo(uint8 flags, const std::string& note) : Status(FRIEND_STATUS_OFFLINE), Flags(flags), Area(0), Level(0), Class(0), Note(note) { - Status = FRIEND_STATUS_OFFLINE; - Flags = flags; - Area = 0; - Level = 0; - Class = 0; - Note = note; } }; diff --git a/src/server/game/Entities/Totem/Totem.cpp b/src/server/game/Entities/Totem/Totem.cpp index 80c5de35e59..a9a0484a4ea 100755 --- a/src/server/game/Entities/Totem/Totem.cpp +++ b/src/server/game/Entities/Totem/Totem.cpp @@ -86,7 +86,7 @@ void Totem::InitStats(uint32 duration) void Totem::InitSummon() { - if (m_type == TOTEM_PASSIVE) + if (m_type == TOTEM_PASSIVE && GetSpell()) { CastSpell(this, GetSpell(), true); } @@ -96,10 +96,10 @@ void Totem::InitSummon() CastSpell(this, GetSpell(1), true); } -void Totem::UnSummon() +void Totem::UnSummon(uint32 msTime) { CombatStop(); - RemoveAurasDueToSpell(GetSpell()); + RemoveAurasDueToSpell(GetSpell(), GetGUID()); // clear owner's totem slot for (int i = SUMMON_SLOT_TOTEM; i < MAX_TOTEM_SLOT; ++i) @@ -111,7 +111,11 @@ void Totem::UnSummon() } } - m_owner->RemoveAurasDueToSpell(GetSpell()); + m_owner->RemoveAurasDueToSpell(GetSpell(), GetGUID()); + + // Remove Sentry Totem Aura + if (GetEntry() == SENTRY_TOTEM_ENTRY) + m_owner->RemoveAurasDueToSpell(SENTRY_TOTEM_SPELLID); //remove aura all party members too if (Player* owner = m_owner->ToPlayer()) @@ -127,7 +131,7 @@ void Totem::UnSummon() { Player* target = itr->getSource(); if (target && group->SameSubGroup(owner, target)) - target->RemoveAurasDueToSpell(GetSpell()); + target->RemoveAurasDueToSpell(GetSpell(), GetGUID()); } } } diff --git a/src/server/game/Entities/Totem/Totem.h b/src/server/game/Entities/Totem/Totem.h index c33b8776660..6271253498d 100755 --- a/src/server/game/Entities/Totem/Totem.h +++ b/src/server/game/Entities/Totem/Totem.h @@ -27,8 +27,10 @@ enum TotemType TOTEM_ACTIVE = 1, TOTEM_STATUE = 2 // copied straight from MaNGOS, may need more implementation to work }; +// Some Totems cast spells that are not in creature DB +#define SENTRY_TOTEM_SPELLID 6495 -#define SENTRY_TOTEM_ENTRY 3968 +#define SENTRY_TOTEM_ENTRY 3968 class Totem : public Minion { @@ -38,7 +40,7 @@ class Totem : public Minion void Update(uint32 time); void InitStats(uint32 duration); void InitSummon(); - void UnSummon(); + void UnSummon(uint32 msTime = 0); uint32 GetSpell(uint8 slot = 0) const { return m_spells[slot]; } uint32 GetTotemDuration() const { return m_duration; } void SetTotemDuration(uint32 duration) { m_duration = duration; } diff --git a/src/server/game/Entities/Unit/Unit.cpp b/src/server/game/Entities/Unit/Unit.cpp index 76644b1aa99..8c372bad34a 100755 --- a/src/server/game/Entities/Unit/Unit.cpp +++ b/src/server/game/Entities/Unit/Unit.cpp @@ -159,7 +159,7 @@ m_movedPlayer(NULL), m_lastSanctuaryTime(0), IsAIEnabled(false), NeedChangeAI(fa m_ControlledByPlayer(false), movespline(new Movement::MoveSpline()), i_AI(NULL), i_disabledAI(NULL), m_procDeep(0), m_removedAurasCount(0), i_motionMaster(this), m_ThreatManager(this), m_vehicle(NULL), m_vehicleKit(NULL), m_unitTypeMask(UNIT_MASK_NONE), -m_HostileRefManager(this) +m_HostileRefManager(this), m_TempSpeed(0.0f), m_AutoRepeatFirstCast(false) { #ifdef _MSC_VER #pragma warning(default:4355) @@ -544,6 +544,10 @@ uint32 Unit::DealDamage(Unit* victim, uint32 damage, CleanDamage const* cleanDam if (IsAIEnabled) GetAI()->DamageDealt(victim, damage, damagetype); + if (victim->GetTypeId() == TYPEID_PLAYER) + if (victim->ToPlayer()->GetCommandStatus(CHEAT_GOD)) + return 0; + // Signal to pets that their owner was attacked if (victim->GetTypeId() == TYPEID_PLAYER) { @@ -13066,7 +13070,8 @@ void Unit::DeleteCharmInfo() CharmInfo::CharmInfo(Unit* unit) : m_unit(unit), m_CommandState(COMMAND_FOLLOW), m_petnumber(0), m_barInit(false), - m_isCommandAttack(false), m_isAtStay(false), m_isFollowing(false), m_isReturning(false) + m_isCommandAttack(false), m_isAtStay(false), m_isFollowing(false), m_isReturning(false), + m_stayX(0.0f), m_stayY(0.0f), m_stayZ(0.0f) { for (uint8 i = 0; i < MAX_SPELL_CHARM; ++i) m_charmspells[i].SetActionAndType(0, ACT_DISABLED); @@ -15654,14 +15659,14 @@ void Unit::SetAuraStack(uint32 spellId, Unit* target, uint32 stack) aura->SetStackAmount(stack); } -void Unit::SendPlaySpellVisual(uint32 id) +void Unit::SendPlaySpellVisualKit(uint32 id, uint32 unkParam) { ObjectGuid guid = GetGUID(); - WorldPacket data(SMSG_PLAY_SPELL_VISUAL, 4 * 3 + 8); - data << uint32(0); - data << uint32(id); // SpellVisualKit.dbc index + WorldPacket data(SMSG_PLAY_SPELL_VISUAL_KIT, 4 + 4+ 4 + 8); data << uint32(0); + data << uint32(id); // SpellVisualKit.dbc index + data << uint32(unkParam); data.WriteBit(guid[4]); data.WriteBit(guid[7]); data.WriteBit(guid[5]); @@ -15679,15 +15684,7 @@ void Unit::SendPlaySpellVisual(uint32 id) data.WriteByteSeq(guid[2]); data.WriteByteSeq(guid[3]); data.WriteByteSeq(guid[5]); - SendMessageToSet(&data, false); -} - -void Unit::SendPlaySpellImpact(uint64 guid, uint32 id) -{ - WorldPacket data(SMSG_PLAY_SPELL_IMPACT, 8 + 4); - data << uint64(guid); // target - data << uint32(id); // SpellVisualKit.dbc index - SendMessageToSet(&data, false); + SendMessageToSet(&data, true); } void Unit::ApplyResilience(Unit const* victim, float* crit, int32* damage, bool isCrit, CombatRating type) const diff --git a/src/server/game/Entities/Unit/Unit.h b/src/server/game/Entities/Unit/Unit.h index 9dcb981c95a..4e68ae9a3a0 100755 --- a/src/server/game/Entities/Unit/Unit.h +++ b/src/server/game/Entities/Unit/Unit.h @@ -623,17 +623,24 @@ enum UnitFlags // Value masks for UNIT_FIELD_FLAGS_2 enum UnitFlags2 { - UNIT_FLAG2_FEIGN_DEATH = 0x00000001, - UNIT_FLAG2_UNK1 = 0x00000002, // Hide unit model (show only player equip) - UNIT_FLAG2_IGNORE_REPUTATION = 0x00000004, - UNIT_FLAG2_COMPREHEND_LANG = 0x00000008, - UNIT_FLAG2_MIRROR_IMAGE = 0x00000010, - UNIT_FLAG2_FORCE_MOVE = 0x00000040, - UNIT_FLAG2_DISARM_OFFHAND = 0x00000080, - UNIT_FLAG2_DISARM_RANGED = 0x00000400, // this does not disable ranged weapon display (maybe additional flag needed?) - UNIT_FLAG2_REGENERATE_POWER = 0x00000800, - UNIT_FLAG2_ALLOW_ENEMY_INTERACT = 0x00004000, - UNIT_FLAG2_ALLOW_CHEAT_SPELLS = 0x00040000, // allows casting spells with AttributesEx7 & SPELL_ATTR7_IS_CHEAT_SPELL + UNIT_FLAG2_FEIGN_DEATH = 0x00000001, + UNIT_FLAG2_UNK1 = 0x00000002, // Hide unit model (show only player equip) + UNIT_FLAG2_IGNORE_REPUTATION = 0x00000004, + UNIT_FLAG2_COMPREHEND_LANG = 0x00000008, + UNIT_FLAG2_MIRROR_IMAGE = 0x00000010, + UNIT_FLAG2_INSTANTLY_APPEAR_MODEL = 0x00000020, // Unit model instantly appears when summoned (does not fade in) + UNIT_FLAG2_FORCE_MOVEMENT = 0x00000040, + UNIT_FLAG2_DISARM_OFFHAND = 0x00000080, + UNIT_FLAG2_DISABLE_PRED_STATS = 0x00000100, // Player has disabled predicted stats (Used by raid frames) + UNIT_FLAG2_DISARM_RANGED = 0x00000400, // this does not disable ranged weapon display (maybe additional flag needed?) + UNIT_FLAG2_REGENERATE_POWER = 0x00000800, + UNIT_FLAG2_RESTRICT_PARTY_INTERACTION = 0x00001000, // Restrict interaction to party or raid + UNIT_FLAG2_PREVENT_SPELL_CLICK = 0x00002000, // Prevent spellclick + UNIT_FLAG2_ALLOW_ENEMY_INTERACT = 0x00004000, + UNIT_FLAG2_DISABLE_TURN = 0x00008000, + UNIT_FLAG2_UNK2 = 0x00010000, + UNIT_FLAG2_PLAY_DEATH_ANIM = 0x00020000, // Plays special death animation upon death + UNIT_FLAG2_ALLOW_CHEAT_SPELLS = 0x00040000, // Allows casting spells with AttributesEx7 & SPELL_ATTR7_IS_CHEAT_SPELL }; /// Non Player Character flags @@ -1572,8 +1579,7 @@ class Unit : public WorldObject Aura* AddAura(uint32 spellId, Unit* target); Aura* AddAura(SpellInfo const* spellInfo, uint8 effMask, Unit* target); void SetAuraStack(uint32 spellId, Unit* target, uint32 stack); - void SendPlaySpellVisual(uint32 id); - void SendPlaySpellImpact(uint64 guid, uint32 id); + void SendPlaySpellVisualKit(uint32 id, uint32 unkParam); void DeMorph(); @@ -2192,10 +2198,14 @@ class Unit : public WorldObject virtual bool isBeingLoaded() const { return false;} bool IsDuringRemoveFromWorld() const {return m_duringRemoveFromWorld;} - Pet* ToPet(){ if (isPet()) return reinterpret_cast<Pet*>(this); else return NULL; } - Totem* ToTotem(){ if (isTotem()) return reinterpret_cast<Totem*>(this); else return NULL; } + Pet* ToPet() { if (isPet()) return reinterpret_cast<Pet*>(this); else return NULL; } + Pet const* ToPet() const { if (isPet()) return reinterpret_cast<Pet const*>(this); else return NULL; } + + Totem* ToTotem() { if (isTotem()) return reinterpret_cast<Totem*>(this); else return NULL; } + Totem const* ToTotem() const { if (isTotem()) return reinterpret_cast<Totem const*>(this); else return NULL; } + TempSummon* ToTempSummon() { if (isSummon()) return reinterpret_cast<TempSummon*>(this); else return NULL; } - const TempSummon* ToTempSummon() const { if (isSummon()) return reinterpret_cast<const TempSummon*>(this); else return NULL; } + TempSummon const* ToTempSummon() const { if (isSummon()) return reinterpret_cast<TempSummon const*>(this); else return NULL; } void SetTarget(uint64 guid) { diff --git a/src/server/game/Globals/ObjectMgr.cpp b/src/server/game/Globals/ObjectMgr.cpp index b87cb2d7fbf..2f128a70b02 100644 --- a/src/server/game/Globals/ObjectMgr.cpp +++ b/src/server/game/Globals/ObjectMgr.cpp @@ -369,17 +369,17 @@ void ObjectMgr::LoadCreatureTemplates() QueryResult result = WorldDatabase.Query("SELECT entry, difficulty_entry_1, difficulty_entry_2, difficulty_entry_3, KillCredit1, KillCredit2, modelid1, modelid2, modelid3, " // 9 10 11 12 13 14 15 16 17 18 19 20 21 "modelid4, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, exp, exp_unk, faction_A, faction_H, npcflag, speed_walk, " - // 22 23 24 25 26 27 28 29 30 31 32 33 - "speed_run, scale, rank, mindmg, maxdmg, dmgschool, attackpower, dmg_multiplier, baseattacktime, rangeattacktime, unit_class, unit_flags, " - // 34 35 36 37 38 39 40 41 42 43 + // 22 23 24 25 26 27 28 29 30 31 32 33 34 + "speed_run, scale, rank, mindmg, maxdmg, dmgschool, attackpower, dmg_multiplier, baseattacktime, rangeattacktime, unit_class, unit_flags, unit_flags2, " + // 35 36 37 38 39 40 41 42 43 44 "dynamicflags, family, trainer_type, trainer_spell, trainer_class, trainer_race, minrangedmg, maxrangedmg, rangedattackpower, type, " - // 44 45 46 47 48 49 50 51 52 53 54 + // 45 46 47 48 49 50 51 52 53 54 55 "type_flags, type_flags2, lootid, pickpocketloot, skinloot, resistance1, resistance2, resistance3, resistance4, resistance5, resistance6, " - // 55 56 57 58 59 60 61 62 63 64 65 66 67 68 + // 56 57 58 59 60 61 62 63 64 65 66 67 68 69 "spell1, spell2, spell3, spell4, spell5, spell6, spell7, spell8, PetSpellDataId, VehicleId, mingold, maxgold, AIName, MovementType, " - // 69 70 71 72 73 74 75 76 77 78 79 80 + // 70 71 72 73 74 75 76 77 78 79 80 81 "InhabitType, HoverHeight, Health_mod, Mana_mod, Mana_mod_extra, Armor_mod, RacialLeader, questItem1, questItem2, questItem3, questItem4, questItem5, " - // 81 82 83 84 85 86 87 + // 82 83 84 85 86 87 88 " questItem6, movementId, RegenHealth, equipment_id, mechanic_immune_mask, flags_extra, ScriptName " "FROM creature_template;"); @@ -436,51 +436,52 @@ void ObjectMgr::LoadCreatureTemplates() creatureTemplate.rangeattacktime = fields[31].GetUInt32(); creatureTemplate.unit_class = uint32(fields[32].GetUInt8()); creatureTemplate.unit_flags = fields[33].GetUInt32(); - creatureTemplate.dynamicflags = fields[34].GetUInt32(); - creatureTemplate.family = uint32(fields[35].GetUInt8()); - creatureTemplate.trainer_type = uint32(fields[36].GetUInt8()); - creatureTemplate.trainer_spell = fields[37].GetUInt32(); - creatureTemplate.trainer_class = uint32(fields[38].GetUInt8()); - creatureTemplate.trainer_race = uint32(fields[39].GetUInt8()); - creatureTemplate.minrangedmg = fields[40].GetFloat(); - creatureTemplate.maxrangedmg = fields[41].GetFloat(); - creatureTemplate.rangedattackpower = uint32(fields[42].GetUInt16()); - creatureTemplate.type = uint32(fields[43].GetUInt8()); - creatureTemplate.type_flags = fields[44].GetUInt32(); - creatureTemplate.type_flags2 = fields[45].GetUInt32(); - creatureTemplate.lootid = fields[46].GetUInt32(); - creatureTemplate.pickpocketLootId = fields[47].GetUInt32(); - creatureTemplate.SkinLootId = fields[48].GetUInt32(); + creatureTemplate.unit_flags2 = fields[34].GetUInt32(); + creatureTemplate.dynamicflags = fields[35].GetUInt32(); + creatureTemplate.family = uint32(fields[36].GetUInt8()); + creatureTemplate.trainer_type = uint32(fields[37].GetUInt8()); + creatureTemplate.trainer_spell = fields[38].GetUInt32(); + creatureTemplate.trainer_class = uint32(fields[39].GetUInt8()); + creatureTemplate.trainer_race = uint32(fields[40].GetUInt8()); + creatureTemplate.minrangedmg = fields[41].GetFloat(); + creatureTemplate.maxrangedmg = fields[42].GetFloat(); + creatureTemplate.rangedattackpower = uint32(fields[43].GetUInt16()); + creatureTemplate.type = uint32(fields[44].GetUInt8()); + creatureTemplate.type_flags = fields[45].GetUInt32(); + creatureTemplate.type_flags2 = fields[46].GetUInt32(); + creatureTemplate.lootid = fields[47].GetUInt32(); + creatureTemplate.pickpocketLootId = fields[48].GetUInt32(); + creatureTemplate.SkinLootId = fields[49].GetUInt32(); for (uint8 i = SPELL_SCHOOL_HOLY; i < MAX_SPELL_SCHOOL; ++i) - creatureTemplate.resistance[i] = fields[49 + i - 1].GetInt16(); + creatureTemplate.resistance[i] = fields[50 + i - 1].GetInt16(); for (uint8 i = 0; i < CREATURE_MAX_SPELLS; ++i) - creatureTemplate.spells[i] = fields[55 + i].GetUInt32(); - - creatureTemplate.PetSpellDataId = fields[63].GetUInt32(); - creatureTemplate.VehicleId = fields[64].GetUInt32(); - creatureTemplate.mingold = fields[65].GetUInt32(); - creatureTemplate.maxgold = fields[66].GetUInt32(); - creatureTemplate.AIName = fields[67].GetString(); - creatureTemplate.MovementType = uint32(fields[68].GetUInt8()); - creatureTemplate.InhabitType = uint32(fields[69].GetUInt8()); - creatureTemplate.HoverHeight = fields[70].GetFloat(); - creatureTemplate.ModHealth = fields[71].GetFloat(); - creatureTemplate.ModMana = fields[72].GetFloat(); - creatureTemplate.ModManaExtra = fields[73].GetFloat(); - creatureTemplate.ModArmor = fields[74].GetFloat(); - creatureTemplate.RacialLeader = fields[75].GetBool(); + creatureTemplate.spells[i] = fields[56 + i].GetUInt32(); + + creatureTemplate.PetSpellDataId = fields[64].GetUInt32(); + creatureTemplate.VehicleId = fields[65].GetUInt32(); + creatureTemplate.mingold = fields[66].GetUInt32(); + creatureTemplate.maxgold = fields[67].GetUInt32(); + creatureTemplate.AIName = fields[68].GetString(); + creatureTemplate.MovementType = uint32(fields[69].GetUInt8()); + creatureTemplate.InhabitType = uint32(fields[70].GetUInt8()); + creatureTemplate.HoverHeight = fields[71].GetFloat(); + creatureTemplate.ModHealth = fields[72].GetFloat(); + creatureTemplate.ModMana = fields[73].GetFloat(); + creatureTemplate.ModManaExtra = fields[74].GetFloat(); + creatureTemplate.ModArmor = fields[75].GetFloat(); + creatureTemplate.RacialLeader = fields[76].GetBool(); for (uint8 i = 0; i < MAX_CREATURE_QUEST_ITEMS; ++i) - creatureTemplate.questItems[i] = fields[76 + i].GetUInt32(); + creatureTemplate.questItems[i] = fields[77 + i].GetUInt32(); - creatureTemplate.movementId = fields[82].GetUInt32(); - creatureTemplate.RegenHealth = fields[83].GetBool(); - creatureTemplate.equipmentId = fields[84].GetUInt32(); - creatureTemplate.MechanicImmuneMask = fields[85].GetUInt32(); - creatureTemplate.flags_extra = fields[86].GetUInt32(); - creatureTemplate.ScriptID = GetScriptId(fields[87].GetCString()); + creatureTemplate.movementId = fields[83].GetUInt32(); + creatureTemplate.RegenHealth = fields[84].GetBool(); + creatureTemplate.equipmentId = fields[85].GetUInt32(); + creatureTemplate.MechanicImmuneMask = fields[86].GetUInt32(); + creatureTemplate.flags_extra = fields[87].GetUInt32(); + creatureTemplate.ScriptID = GetScriptId(fields[88].GetCString()); ++count; } @@ -7875,8 +7876,6 @@ void ObjectMgr::LoadTrainerSpell() // For reload case _cacheTrainerSpellStore.clear(); - std::set<uint32> skip_trainers; - QueryResult result = WorldDatabase.Query("SELECT b.entry, a.spell, a.spellcost, a.reqskill, a.reqskillvalue, a.reqlevel FROM npc_trainer AS a " "INNER JOIN npc_trainer AS b ON a.entry = -(b.spell) " "UNION SELECT * FROM npc_trainer WHERE spell > 0"); diff --git a/src/server/game/Grids/NGrid.h b/src/server/game/Grids/NGrid.h index b5701a7a590..6bf558a4d5e 100755 --- a/src/server/game/Grids/NGrid.h +++ b/src/server/game/Grids/NGrid.h @@ -79,9 +79,8 @@ class NGrid public: typedef Grid<ACTIVE_OBJECT, WORLD_OBJECT_TYPES, GRID_OBJECT_TYPES> GridType; NGrid(uint32 id, int32 x, int32 y, time_t expiry, bool unload = true) - : i_gridId(id), i_x(x), i_y(y), i_cellstate(GRID_STATE_INVALID), i_GridObjectDataLoaded(false) + : i_gridId(id), i_x(x), i_y(y), i_cellstate(GRID_STATE_INVALID), i_GridObjectDataLoaded(false), i_GridInfo(GridInfo(expiry, unload)) { - i_GridInfo = GridInfo(expiry, unload); } GridType& GetGridType(const uint32 x, const uint32 y) diff --git a/src/server/game/Groups/Group.cpp b/src/server/game/Groups/Group.cpp index d0bbaffacea..b9ede2ec985 100755 --- a/src/server/game/Groups/Group.cpp +++ b/src/server/game/Groups/Group.cpp @@ -1531,6 +1531,7 @@ void Group::SendUpdateToPlayer(uint64 playerGUID, MemberSlot* slot) { data << uint8(sLFGMgr->GetState(m_guid) == LFG_STATE_FINISHED_DUNGEON ? 2 : 0); // FIXME - Dungeon save status? 2 = done data << uint32(sLFGMgr->GetDungeon(m_guid)); + data << uint8(0); // 4.x new } data << uint64(m_guid); @@ -1543,7 +1544,7 @@ void Group::SendUpdateToPlayer(uint64 playerGUID, MemberSlot* slot) Player* member = ObjectAccessor::FindPlayer(citr->guid); - uint8 onlineState = (member) ? MEMBER_STATUS_ONLINE : MEMBER_STATUS_OFFLINE; + uint8 onlineState = member ? MEMBER_STATUS_ONLINE : MEMBER_STATUS_OFFLINE; onlineState = onlineState | ((isBGGroup() || isBFGroup()) ? MEMBER_STATUS_PVP : 0); data << citr->name; diff --git a/src/server/game/Groups/Group.h b/src/server/game/Groups/Group.h index e6da9caea32..c24b3f3deae 100755 --- a/src/server/game/Groups/Group.h +++ b/src/server/game/Groups/Group.h @@ -96,36 +96,38 @@ enum GroupType enum GroupUpdateFlags { GROUP_UPDATE_FLAG_NONE = 0x00000000, // nothing - GROUP_UPDATE_FLAG_STATUS = 0x00000001, // uint16, flags - GROUP_UPDATE_FLAG_CUR_HP = 0x00000002, // uint32 - GROUP_UPDATE_FLAG_MAX_HP = 0x00000004, // uint32 - GROUP_UPDATE_FLAG_POWER_TYPE = 0x00000008, // uint8 - GROUP_UPDATE_FLAG_CUR_POWER = 0x00000010, // uint16 - GROUP_UPDATE_FLAG_MAX_POWER = 0x00000020, // uint16 - GROUP_UPDATE_FLAG_LEVEL = 0x00000040, // uint16 - GROUP_UPDATE_FLAG_ZONE = 0x00000080, // uint16 - GROUP_UPDATE_FLAG_POSITION = 0x00000100, // uint16, uint16 - GROUP_UPDATE_FLAG_AURAS = 0x00000200, // uint64 mask, for each bit set uint32 spellid + uint8 unk - GROUP_UPDATE_FLAG_PET_GUID = 0x00000400, // uint64 pet guid - GROUP_UPDATE_FLAG_PET_NAME = 0x00000800, // pet name, NULL terminated string - GROUP_UPDATE_FLAG_PET_MODEL_ID = 0x00001000, // uint16, model id - GROUP_UPDATE_FLAG_PET_CUR_HP = 0x00002000, // uint32 pet cur health - GROUP_UPDATE_FLAG_PET_MAX_HP = 0x00004000, // uint32 pet max health - GROUP_UPDATE_FLAG_PET_POWER_TYPE = 0x00008000, // uint8 pet power type - GROUP_UPDATE_FLAG_PET_CUR_POWER = 0x00010000, // uint16 pet cur power - GROUP_UPDATE_FLAG_PET_MAX_POWER = 0x00020000, // uint16 pet max power - GROUP_UPDATE_FLAG_PET_AURAS = 0x00040000, // uint64 mask, for each bit set uint32 spellid + uint8 unk, pet auras... - GROUP_UPDATE_FLAG_VEHICLE_SEAT = 0x00080000, // uint8, uint64, if (uint32 != 0) { uint32, if (uint16 & 0x40) { uint32, uint32, uint32 } } - GROUP_UPDATE_FLAG_UNKNOWN_1 = 0x00100000, // uint32 - GROUP_UPDATE_FLAG_UNKNOWN_2 = 0x00200000, // uint32, uint32, string - GROUP_UPDATE_PET = 0x0007FC00, // all pet flags - GROUP_UPDATE_FULL = 0x0007FFFF, // all known flags + GROUP_UPDATE_FLAG_STATUS = 0x00000001, // uint16 (GroupMemberStatusFlag) + GROUP_UPDATE_FLAG_CUR_HP = 0x00000002, // uint32 (HP) + GROUP_UPDATE_FLAG_MAX_HP = 0x00000004, // uint32 (HP) + GROUP_UPDATE_FLAG_POWER_TYPE = 0x00000008, // uint8 (PowerType) + GROUP_UPDATE_FLAG_CUR_POWER = 0x00000010, // int16 (power value) + GROUP_UPDATE_FLAG_MAX_POWER = 0x00000020, // int16 (power value) + GROUP_UPDATE_FLAG_LEVEL = 0x00000040, // uint16 (level value) + GROUP_UPDATE_FLAG_ZONE = 0x00000080, // uint16 (zone id) + GROUP_UPDATE_FLAG_UNK100 = 0x00000100, // int16 (unk) + GROUP_UPDATE_FLAG_POSITION = 0x00000200, // uint16 (x), uint16 (y), uint16 (z) + GROUP_UPDATE_FLAG_AURAS = 0x00000400, // uint8 (unk), uint64 (mask), uint32 (count), for each bit set: uint32 (spell id) + uint16 (AuraFlags) (if has flags Scalable -> 3x int32 (bps)) + GROUP_UPDATE_FLAG_PET_GUID = 0x00000800, // uint64 (pet guid) + GROUP_UPDATE_FLAG_PET_NAME = 0x00001000, // cstring (name, NULL terminated string) + GROUP_UPDATE_FLAG_PET_MODEL_ID = 0x00002000, // uint16 (model id) + GROUP_UPDATE_FLAG_PET_CUR_HP = 0x00004000, // uint32 (HP) + GROUP_UPDATE_FLAG_PET_MAX_HP = 0x00008000, // uint32 (HP) + GROUP_UPDATE_FLAG_PET_POWER_TYPE = 0x00010000, // uint8 (PowerType) + GROUP_UPDATE_FLAG_PET_CUR_POWER = 0x00020000, // uint16 (power value) + GROUP_UPDATE_FLAG_PET_MAX_POWER = 0x00040000, // uint16 (power value) + GROUP_UPDATE_FLAG_PET_AURAS = 0x00080000, // [see GROUP_UPDATE_FLAG_AURAS] + GROUP_UPDATE_FLAG_VEHICLE_SEAT = 0x00100000, // int32 (vehicle seat id) + GROUP_UPDATE_FLAG_PHASE = 0x00200000, // int32 (unk), uint32 (phase count), for (count) uint16(phaseId) + + GROUP_UPDATE_PET = GROUP_UPDATE_FLAG_PET_GUID | GROUP_UPDATE_FLAG_PET_NAME | GROUP_UPDATE_FLAG_PET_MODEL_ID | + GROUP_UPDATE_FLAG_PET_CUR_HP | GROUP_UPDATE_FLAG_PET_MAX_HP | GROUP_UPDATE_FLAG_PET_POWER_TYPE | + GROUP_UPDATE_FLAG_PET_CUR_POWER | GROUP_UPDATE_FLAG_PET_MAX_POWER | GROUP_UPDATE_FLAG_PET_AURAS, // all pet flags + GROUP_UPDATE_FULL = GROUP_UPDATE_FLAG_STATUS | GROUP_UPDATE_FLAG_CUR_HP | GROUP_UPDATE_FLAG_MAX_HP | + GROUP_UPDATE_FLAG_POWER_TYPE | GROUP_UPDATE_FLAG_CUR_POWER | GROUP_UPDATE_FLAG_MAX_POWER | + GROUP_UPDATE_FLAG_LEVEL | GROUP_UPDATE_FLAG_ZONE | GROUP_UPDATE_FLAG_POSITION | + GROUP_UPDATE_FLAG_AURAS | GROUP_UPDATE_PET | GROUP_UPDATE_FLAG_PHASE, // all known flags, except UNK100 and VEHICLE_SEAT }; -#define GROUP_UPDATE_FLAGS_COUNT 20 - // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 -static const uint8 GroupUpdateLength[GROUP_UPDATE_FLAGS_COUNT] = { 0, 2, 2, 2, 1, 2, 2, 2, 2, 4, 8, 8, 1, 2, 2, 2, 1, 2, 2, 8}; - class Roll : public LootValidatorRef { public: diff --git a/src/server/game/Guilds/Guild.cpp b/src/server/game/Guilds/Guild.cpp index 4b193b62b2b..ba9d8610c12 100644 --- a/src/server/game/Guilds/Guild.cpp +++ b/src/server/game/Guilds/Guild.cpp @@ -99,9 +99,13 @@ inline void Guild::LogHolder::AddEvent(SQLTransaction& trans, LogEntry* entry) // Writes information about all events into packet. inline void Guild::LogHolder::WritePacket(WorldPacket& data) const { - data << uint8(m_log.size()); + ByteBuffer buffer; + data.WriteBits(m_log.size(), 23); for (GuildLog::const_iterator itr = m_log.begin(); itr != m_log.end(); ++itr) - (*itr)->WritePacket(data); + (*itr)->WritePacket(data, buffer); + + data.FlushBits(); + data.append(buffer); } inline uint32 Guild::LogHolder::GetNextGUID() @@ -138,20 +142,56 @@ void Guild::EventLogEntry::SaveToDB(SQLTransaction& trans) const CharacterDatabase.ExecuteOrAppend(trans, stmt); } -void Guild::EventLogEntry::WritePacket(WorldPacket& data) const +void Guild::EventLogEntry::WritePacket(WorldPacket& data, ByteBuffer& content) const { - // Event type - data << uint8(m_eventType); - // Player 1 - data << uint64(MAKE_NEW_GUID(m_playerGuid1, 0, HIGHGUID_PLAYER)); - // Player 2 not for left/join guild events - if (m_eventType != GUILD_EVENT_LOG_JOIN_GUILD && m_eventType != GUILD_EVENT_LOG_LEAVE_GUILD) - data << uint64(MAKE_NEW_GUID(m_playerGuid2, 0, HIGHGUID_PLAYER)); - // New Rank - only for promote/demote guild events - if (m_eventType == GUILD_EVENT_LOG_PROMOTE_PLAYER || m_eventType == GUILD_EVENT_LOG_DEMOTE_PLAYER) - data << uint8(m_newRank); + ObjectGuid guid1 = MAKE_NEW_GUID(m_playerGuid1, 0, HIGHGUID_PLAYER); + ObjectGuid guid2 = MAKE_NEW_GUID(m_playerGuid2, 0, HIGHGUID_PLAYER); + + data.WriteBit(guid1[2]); + data.WriteBit(guid1[4]); + data.WriteBit(guid2[7]); + data.WriteBit(guid2[6]); + data.WriteBit(guid1[3]); + data.WriteBit(guid2[3]); + data.WriteBit(guid2[5]); + data.WriteBit(guid1[7]); + data.WriteBit(guid1[5]); + data.WriteBit(guid1[0]); + data.WriteBit(guid2[4]); + data.WriteBit(guid2[2]); + data.WriteBit(guid2[0]); + data.WriteBit(guid2[1]); + data.WriteBit(guid1[1]); + data.WriteBit(guid1[6]); + + content.WriteByteSeq(guid2[3]); + content.WriteByteSeq(guid2[2]); + content.WriteByteSeq(guid2[5]); + + // New Rank + content << uint8(m_newRank); + + content.WriteByteSeq(guid2[4]); + content.WriteByteSeq(guid1[0]); + content.WriteByteSeq(guid1[4]); + // Event timestamp - data << uint32(::time(NULL) - m_timestamp); + content << uint32(::time(NULL) - m_timestamp); + + content.WriteByteSeq(guid1[7]); + content.WriteByteSeq(guid1[3]); + content.WriteByteSeq(guid2[0]); + content.WriteByteSeq(guid2[6]); + content.WriteByteSeq(guid2[7]); + content.WriteByteSeq(guid1[5]); + + // Event type + content << uint8(m_eventType); + + content.WriteByteSeq(guid2[1]); + content.WriteByteSeq(guid1[2]); + content.WriteByteSeq(guid1[6]); + content.WriteByteSeq(guid1[1]); } /////////////////////////////////////////////////////////////////////////////// @@ -181,20 +221,52 @@ void Guild::BankEventLogEntry::SaveToDB(SQLTransaction& trans) const CharacterDatabase.ExecuteOrAppend(trans, stmt); } -void Guild::BankEventLogEntry::WritePacket(WorldPacket& data) const +void Guild::BankEventLogEntry::WritePacket(WorldPacket& data, ByteBuffer& content) const { - data << uint8(m_eventType); - data << uint64(MAKE_NEW_GUID(m_playerGuid, 0, HIGHGUID_PLAYER)); - data << uint32(m_itemOrMoney); - // if ( m_eventType != 4 || m_eventType != 5 || m_eventType != 6 || m_eventType != 8 || m_eventType != 9 ) - if (m_eventType < GUILD_BANK_LOG_DEPOSIT_MONEY) - { - data << uint32(m_itemStackCount); - if (m_eventType == GUILD_BANK_LOG_MOVE_ITEM || m_eventType == GUILD_BANK_LOG_MOVE_ITEM2) - data << uint8(m_destTabId); - } + ObjectGuid logGuid = MAKE_NEW_GUID(m_playerGuid, 0, HIGHGUID_PLAYER); + + bool hasItem = m_eventType == GUILD_BANK_LOG_DEPOSIT_ITEM || m_eventType == GUILD_BANK_LOG_WITHDRAW_ITEM || + m_eventType == GUILD_BANK_LOG_MOVE_ITEM || m_eventType == GUILD_BANK_LOG_MOVE_ITEM2; + + bool itemMoved = (m_eventType == GUILD_BANK_LOG_MOVE_ITEM || m_eventType == GUILD_BANK_LOG_MOVE_ITEM2); + + bool hasStack = (hasItem && m_itemStackCount > 1) || itemMoved; + + data.WriteBit(IsMoneyEvent()); + data.WriteBit(logGuid[4]); + data.WriteBit(logGuid[1]); + data.WriteBit(hasItem); + data.WriteBit(hasStack); + data.WriteBit(logGuid[2]); + data.WriteBit(logGuid[5]); + data.WriteBit(logGuid[3]); + data.WriteBit(logGuid[6]); + data.WriteBit(logGuid[0]); + data.WriteBit(itemMoved); + data.WriteBit(logGuid[7]); - data << uint32(time(NULL) - m_timestamp); + content.WriteByteSeq(logGuid[6]); + content.WriteByteSeq(logGuid[1]); + content.WriteByteSeq(logGuid[5]); + if (hasStack) + content << uint32(m_itemStackCount); + + content << uint8(m_eventType); + content.WriteByteSeq(logGuid[2]); + content.WriteByteSeq(logGuid[4]); + content.WriteByteSeq(logGuid[0]); + content.WriteByteSeq(logGuid[7]); + content.WriteByteSeq(logGuid[3]); + if (hasItem) + content << uint32(m_itemOrMoney); + + content << uint32(time(NULL) - m_timestamp); + + if (IsMoneyEvent()) + content << uint64(m_itemOrMoney); + + if (itemMoved) + content << uint8(m_destTabId); } /////////////////////////////////////////////////////////////////////////////// @@ -403,12 +475,12 @@ void Guild::BankTab::SetText(const std::string& text) // Sets/removes contents of specified slot. // If pItem == NULL contents are removed. -bool Guild::BankTab::SetItem(SQLTransaction& trans, uint8 slotId, Item* pItem) +bool Guild::BankTab::SetItem(SQLTransaction& trans, uint8 slotId, Item* item) { if (slotId >= GUILD_BANK_MAX_SLOTS) return false; - m_items[slotId] = pItem; + m_items[slotId] = item; PreparedStatement* stmt = NULL; @@ -418,28 +490,29 @@ bool Guild::BankTab::SetItem(SQLTransaction& trans, uint8 slotId, Item* pItem) stmt->setUInt8 (2, slotId); CharacterDatabase.ExecuteOrAppend(trans, stmt); - if (pItem) + if (item) { stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_BANK_ITEM); stmt->setUInt32(0, m_guildId); stmt->setUInt8 (1, m_tabId); stmt->setUInt8 (2, slotId); - stmt->setUInt32(3, pItem->GetGUIDLow()); + stmt->setUInt32(3, item->GetGUIDLow()); CharacterDatabase.ExecuteOrAppend(trans, stmt); - pItem->SetUInt64Value(ITEM_FIELD_CONTAINED, 0); - pItem->SetUInt64Value(ITEM_FIELD_OWNER, 0); - pItem->FSetState(ITEM_NEW); - pItem->SaveToDB(trans); // Not in inventory and can be saved standalone + item->SetUInt64Value(ITEM_FIELD_CONTAINED, 0); + item->SetUInt64Value(ITEM_FIELD_OWNER, 0); + item->FSetState(ITEM_NEW); + item->SaveToDB(trans); // Not in inventory and can be saved standalone } return true; } -void Guild::BankTab::SendText(const Guild* guild, WorldSession* session) const +void Guild::BankTab::SendText(Guild const* guild, WorldSession* session) const { - WorldPacket data(MSG_QUERY_GUILD_BANK_TEXT, 1 + m_text.size() + 1); - data << uint8(m_tabId); - data << m_text; + WorldPacket data(SMSG_GUILD_BANK_QUERY_TEXT_RESULT, 1 + m_text.size() + 1); + data.WriteBits(m_text.length(), 14); + data << uint32(m_tabId); + data.WriteString(m_text); if (session) session->SendPacket(&data); @@ -1119,6 +1192,15 @@ void Guild::Disband() sGuildMgr->RemoveGuild(m_id); } +void Guild::SaveToDB() +{ + SQLTransaction trans = CharacterDatabase.BeginTransaction(); + + m_achievementMgr.SaveToDB(trans); + + CharacterDatabase.CommitTransaction(trans); +} + /////////////////////////////////////////////////////////////////////////////// // HANDLE CLIENT COMMANDS void Guild::HandleRoster(WorldSession* session /*= NULL*/) @@ -1833,6 +1915,8 @@ void Guild::HandleMemberLogout(WorldSession* session) member->UpdateLogoutTime(); } _BroadcastEvent(GE_SIGNED_OFF, player->GetGUID(), player->GetName()); + + SaveToDB(); } void Guild::HandleDisband(WorldSession* session) @@ -1871,10 +1955,10 @@ void Guild::HandleGuildPartyRequest(WorldSession* session) // Send data to client void Guild::SendEventLog(WorldSession* session) const { - WorldPacket data(MSG_GUILD_EVENT_LOG_QUERY, 1 + m_eventLog->GetSize() * (1 + 8 + 4)); + WorldPacket data(SMSG_GUILD_EVENT_LOG_QUERY_RESULT, 1 + m_eventLog->GetSize() * (1 + 8 + 4)); m_eventLog->WritePacket(data); session->SendPacket(&data); - sLog->outDebug(LOG_FILTER_GUILD, "WORLD: Sent (MSG_GUILD_EVENT_LOG_QUERY)"); + sLog->outDebug(LOG_FILTER_GUILD, "WORLD: Sent (SMSG_GUILD_EVENT_LOG_QUERY_RESULT)"); } void Guild::SendBankLog(WorldSession* session, uint8 tabId) const @@ -1882,12 +1966,15 @@ void Guild::SendBankLog(WorldSession* session, uint8 tabId) const // GUILD_BANK_MAX_TABS send by client for money log if (tabId < _GetPurchasedTabsSize() || tabId == GUILD_BANK_MAX_TABS) { - const LogHolder* pLog = m_bankEventLog[tabId]; - WorldPacket data(MSG_GUILD_BANK_LOG_QUERY, pLog->GetSize() * (4 * 4 + 1) + 1 + 1); - data << uint8(tabId); - pLog->WritePacket(data); + LogHolder const* log = m_bankEventLog[tabId]; + WorldPacket data(SMSG_GUILD_BANK_LOG_QUERY_RESULT, log->GetSize() * (4 * 4 + 1) + 1 + 1); + data.WriteBit(GetLevel() >= 5 && tabId == GUILD_BANK_MAX_TABS); // has Cash Flow perk + log->WritePacket(data); + data << uint32(tabId); + //if (tabId == GUILD_BANK_MAX_TABS && hasCashFlow) + // data << uint64(cashFlowContribution); session->SendPacket(&data); - sLog->outDebug(LOG_FILTER_GUILD, "WORLD: Sent (MSG_GUILD_BANK_LOG_QUERY)"); + sLog->outDebug(LOG_FILTER_GUILD, "WORLD: Sent (SMSG_GUILD_BANK_LOG_QUERY_RESULT) for tab %u", tabId); } } @@ -1978,8 +2065,8 @@ void Guild::SendBankList(WorldSession* session, uint8 tabId, bool withContent, b void Guild::SendBankTabText(WorldSession* session, uint8 tabId) const { - if (const BankTab* pTab = GetBankTab(tabId)) - pTab->SendText(this, session); + if (BankTab const* tab = GetBankTab(tabId)) + tab->SendText(this, session); } void Guild::SendPermissions(WorldSession* session) const @@ -2758,6 +2845,10 @@ void Guild::_LogBankEvent(SQLTransaction& trans, GuildBankEventLogTypes eventTyp if (tabId > GUILD_BANK_MAX_TABS) return; + // not logging moves within the same tab + if (eventType == GUILD_BANK_LOG_MOVE_ITEM && tabId == destTabId) + return; + uint8 dbTabId = tabId; if (BankEventLogEntry::IsMoneyEvent(eventType)) { diff --git a/src/server/game/Guilds/Guild.h b/src/server/game/Guilds/Guild.h index 67888f636ff..1adf1675c45 100755 --- a/src/server/game/Guilds/Guild.h +++ b/src/server/game/Guilds/Guild.h @@ -184,15 +184,16 @@ enum GuildBankRights enum GuildBankEventLogTypes { - GUILD_BANK_LOG_DEPOSIT_ITEM = 1, - GUILD_BANK_LOG_WITHDRAW_ITEM = 2, - GUILD_BANK_LOG_MOVE_ITEM = 3, - GUILD_BANK_LOG_DEPOSIT_MONEY = 4, - GUILD_BANK_LOG_WITHDRAW_MONEY = 5, - GUILD_BANK_LOG_REPAIR_MONEY = 6, - GUILD_BANK_LOG_MOVE_ITEM2 = 7, - GUILD_BANK_LOG_UNK1 = 8, - GUILD_BANK_LOG_BUY_SLOT = 9, + GUILD_BANK_LOG_DEPOSIT_ITEM = 1, + GUILD_BANK_LOG_WITHDRAW_ITEM = 2, + GUILD_BANK_LOG_MOVE_ITEM = 3, + GUILD_BANK_LOG_DEPOSIT_MONEY = 4, + GUILD_BANK_LOG_WITHDRAW_MONEY = 5, + GUILD_BANK_LOG_REPAIR_MONEY = 6, + GUILD_BANK_LOG_MOVE_ITEM2 = 7, + GUILD_BANK_LOG_UNK1 = 8, + GUILD_BANK_LOG_BUY_SLOT = 9, + GUILD_BANK_LOG_CASH_FLOW_DEPOSIT = 10, }; enum GuildEventLogTypes @@ -357,7 +358,7 @@ private: uint32 GetGUID() const { return m_guid; } virtual void SaveToDB(SQLTransaction& trans) const = 0; - virtual void WritePacket(WorldPacket& data) const = 0; + virtual void WritePacket(WorldPacket& data, ByteBuffer& content) const = 0; protected: uint32 m_guildId; @@ -378,7 +379,7 @@ private: ~EventLogEntry() { } void SaveToDB(SQLTransaction& trans) const; - void WritePacket(WorldPacket& data) const; + void WritePacket(WorldPacket& data, ByteBuffer& content) const; private: GuildEventLogTypes m_eventType; @@ -396,7 +397,13 @@ private: return eventType == GUILD_BANK_LOG_DEPOSIT_MONEY || eventType == GUILD_BANK_LOG_WITHDRAW_MONEY || - eventType == GUILD_BANK_LOG_REPAIR_MONEY; + eventType == GUILD_BANK_LOG_REPAIR_MONEY || + eventType == GUILD_BANK_LOG_CASH_FLOW_DEPOSIT; + } + + bool IsMoneyEvent() const + { + return IsMoneyEvent(m_eventType); } BankEventLogEntry(uint32 guildId, uint32 guid, GuildBankEventLogTypes eventType, uint8 tabId, uint32 playerGuid, uint32 itemOrMoney, uint16 itemStackCount, uint8 destTabId) : @@ -410,7 +417,7 @@ private: ~BankEventLogEntry() { } void SaveToDB(SQLTransaction& trans) const; - void WritePacket(WorldPacket& data) const; + void WritePacket(WorldPacket& data, ByteBuffer& content) const; private: GuildBankEventLogTypes m_eventType; @@ -502,16 +509,16 @@ private: bool LoadItemFromDB(Field* fields); void Delete(SQLTransaction& trans, bool removeItemsFromDB = false); - void SetInfo(const std::string& name, const std::string& icon); - void SetText(const std::string& text); - void SendText(const Guild* guild, WorldSession* session) const; + void SetInfo(std::string const& name, std::string const& icon); + void SetText(std::string const& text); + void SendText(Guild const* guild, WorldSession* session) const; std::string const& GetName() const { return m_name; } std::string const& GetIcon() const { return m_icon; } std::string const& GetText() const { return m_text; } inline Item* GetItem(uint8 slotId) const { return slotId < GUILD_BANK_MAX_SLOTS ? m_items[slotId] : NULL; } - bool SetItem(SQLTransaction& trans, uint8 slotId, Item* pItem); + bool SetItem(SQLTransaction& trans, uint8 slotId, Item* item); private: uint32 m_guildId; @@ -623,6 +630,8 @@ public: bool Create(Player* pLeader, const std::string& name); void Disband(); + void SaveToDB(); + // Getters uint32 GetId() const { return m_id; } uint64 GetGUID() const { return MAKE_NEW_GUID(m_id, 0, HIGHGUID_GUILD); } @@ -699,6 +708,7 @@ public: void DeleteMember(uint64 guid, bool isDisbanding = false, bool isKicked = false); bool ChangeMemberRank(uint64 guid, uint8 newRank); bool IsMember(uint64 guid); + uint32 GetMembersCount() { return m_members.size(); } // Bank void SwapItems(Player* player, uint8 tabId, uint8 slotId, uint8 destTabId, uint8 destSlotId, uint32 splitedAmount); diff --git a/src/server/game/Guilds/GuildMgr.cpp b/src/server/game/Guilds/GuildMgr.cpp index 473fe32ec27..04b0cfeaa39 100644 --- a/src/server/game/Guilds/GuildMgr.cpp +++ b/src/server/game/Guilds/GuildMgr.cpp @@ -39,6 +39,12 @@ void GuildMgr::RemoveGuild(uint32 guildId) GuildStore.erase(guildId); } +void GuildMgr::SaveGuilds() +{ + for (GuildContainer::iterator itr = GuildStore.begin(); itr != GuildStore.end(); ++itr) + itr->second->SaveToDB(); +} + uint32 GuildMgr::GenerateGuildId() { if (NextGuildId >= 0xFFFFFFFE) diff --git a/src/server/game/Guilds/GuildMgr.h b/src/server/game/Guilds/GuildMgr.h index d9c18a8026d..4b999c9231a 100644 --- a/src/server/game/Guilds/GuildMgr.h +++ b/src/server/game/Guilds/GuildMgr.h @@ -40,6 +40,8 @@ public: void AddGuild(Guild* guild); void RemoveGuild(uint32 guildId); + void SaveGuilds(); + uint32 GenerateGuildId(); void SetNextGuildId(uint32 Id) { NextGuildId = Id; } diff --git a/src/server/game/Handlers/AddonHandler.cpp b/src/server/game/Handlers/AddonHandler.cpp index f86dacbc55e..c3ffeace3fb 100755 --- a/src/server/game/Handlers/AddonHandler.cpp +++ b/src/server/game/Handlers/AddonHandler.cpp @@ -37,26 +37,6 @@ bool AddonHandler::BuildAddonPacket(WorldPacket* Source, WorldPacket* Target) uint32 CurrentPosition; uint32 TempValue; - unsigned char tdata[256] = - { - 0xC3, 0x5B, 0x50, 0x84, 0xB9, 0x3E, 0x32, 0x42, 0x8C, 0xD0, 0xC7, 0x48, 0xFA, 0x0E, 0x5D, 0x54, - 0x5A, 0xA3, 0x0E, 0x14, 0xBA, 0x9E, 0x0D, 0xB9, 0x5D, 0x8B, 0xEE, 0xB6, 0x84, 0x93, 0x45, 0x75, - 0xFF, 0x31, 0xFE, 0x2F, 0x64, 0x3F, 0x3D, 0x6D, 0x07, 0xD9, 0x44, 0x9B, 0x40, 0x85, 0x59, 0x34, - 0x4E, 0x10, 0xE1, 0xE7, 0x43, 0x69, 0xEF, 0x7C, 0x16, 0xFC, 0xB4, 0xED, 0x1B, 0x95, 0x28, 0xA8, - 0x23, 0x76, 0x51, 0x31, 0x57, 0x30, 0x2B, 0x79, 0x08, 0x50, 0x10, 0x1C, 0x4A, 0x1A, 0x2C, 0xC8, - 0x8B, 0x8F, 0x05, 0x2D, 0x22, 0x3D, 0xDB, 0x5A, 0x24, 0x7A, 0x0F, 0x13, 0x50, 0x37, 0x8F, 0x5A, - 0xCC, 0x9E, 0x04, 0x44, 0x0E, 0x87, 0x01, 0xD4, 0xA3, 0x15, 0x94, 0x16, 0x34, 0xC6, 0xC2, 0xC3, - 0xFB, 0x49, 0xFE, 0xE1, 0xF9, 0xDA, 0x8C, 0x50, 0x3C, 0xBE, 0x2C, 0xBB, 0x57, 0xED, 0x46, 0xB9, - 0xAD, 0x8B, 0xC6, 0xDF, 0x0E, 0xD6, 0x0F, 0xBE, 0x80, 0xB3, 0x8B, 0x1E, 0x77, 0xCF, 0xAD, 0x22, - 0xCF, 0xB7, 0x4B, 0xCF, 0xFB, 0xF0, 0x6B, 0x11, 0x45, 0x2D, 0x7A, 0x81, 0x18, 0xF2, 0x92, 0x7E, - 0x98, 0x56, 0x5D, 0x5E, 0x69, 0x72, 0x0A, 0x0D, 0x03, 0x0A, 0x85, 0xA2, 0x85, 0x9C, 0xCB, 0xFB, - 0x56, 0x6E, 0x8F, 0x44, 0xBB, 0x8F, 0x02, 0x22, 0x68, 0x63, 0x97, 0xBC, 0x85, 0xBA, 0xA8, 0xF7, - 0xB5, 0x40, 0x68, 0x3C, 0x77, 0x86, 0x6F, 0x4B, 0xD7, 0x88, 0xCA, 0x8A, 0xD7, 0xCE, 0x36, 0xF0, - 0x45, 0x6E, 0xD5, 0x64, 0x79, 0x0F, 0x17, 0xFC, 0x64, 0xDD, 0x10, 0x6F, 0xF3, 0xF5, 0xE0, 0xA6, - 0xC3, 0xFB, 0x1B, 0x8C, 0x29, 0xEF, 0x8E, 0xE5, 0x34, 0xCB, 0xD1, 0x2A, 0xCE, 0x79, 0xC3, 0x9A, - 0x0D, 0x36, 0xEA, 0x01, 0xE0, 0xAA, 0x91, 0x20, 0x54, 0xF0, 0x72, 0xD8, 0x1E, 0xC7, 0x89, 0xD2 - }; - // broken addon packet, can't be received from real client if (Source->rpos() + 4 > Source->size()) return false; @@ -110,7 +90,28 @@ bool AddonHandler::BuildAddonPacket(WorldPacket* Source, WorldPacket* Target) uint8 unk = (crc != 0x4c1c776d); // If addon is Standard addon CRC *Target << uint8(unk); if (unk) + { + unsigned char tdata[256] = + { + 0xC3, 0x5B, 0x50, 0x84, 0xB9, 0x3E, 0x32, 0x42, 0x8C, 0xD0, 0xC7, 0x48, 0xFA, 0x0E, 0x5D, 0x54, + 0x5A, 0xA3, 0x0E, 0x14, 0xBA, 0x9E, 0x0D, 0xB9, 0x5D, 0x8B, 0xEE, 0xB6, 0x84, 0x93, 0x45, 0x75, + 0xFF, 0x31, 0xFE, 0x2F, 0x64, 0x3F, 0x3D, 0x6D, 0x07, 0xD9, 0x44, 0x9B, 0x40, 0x85, 0x59, 0x34, + 0x4E, 0x10, 0xE1, 0xE7, 0x43, 0x69, 0xEF, 0x7C, 0x16, 0xFC, 0xB4, 0xED, 0x1B, 0x95, 0x28, 0xA8, + 0x23, 0x76, 0x51, 0x31, 0x57, 0x30, 0x2B, 0x79, 0x08, 0x50, 0x10, 0x1C, 0x4A, 0x1A, 0x2C, 0xC8, + 0x8B, 0x8F, 0x05, 0x2D, 0x22, 0x3D, 0xDB, 0x5A, 0x24, 0x7A, 0x0F, 0x13, 0x50, 0x37, 0x8F, 0x5A, + 0xCC, 0x9E, 0x04, 0x44, 0x0E, 0x87, 0x01, 0xD4, 0xA3, 0x15, 0x94, 0x16, 0x34, 0xC6, 0xC2, 0xC3, + 0xFB, 0x49, 0xFE, 0xE1, 0xF9, 0xDA, 0x8C, 0x50, 0x3C, 0xBE, 0x2C, 0xBB, 0x57, 0xED, 0x46, 0xB9, + 0xAD, 0x8B, 0xC6, 0xDF, 0x0E, 0xD6, 0x0F, 0xBE, 0x80, 0xB3, 0x8B, 0x1E, 0x77, 0xCF, 0xAD, 0x22, + 0xCF, 0xB7, 0x4B, 0xCF, 0xFB, 0xF0, 0x6B, 0x11, 0x45, 0x2D, 0x7A, 0x81, 0x18, 0xF2, 0x92, 0x7E, + 0x98, 0x56, 0x5D, 0x5E, 0x69, 0x72, 0x0A, 0x0D, 0x03, 0x0A, 0x85, 0xA2, 0x85, 0x9C, 0xCB, 0xFB, + 0x56, 0x6E, 0x8F, 0x44, 0xBB, 0x8F, 0x02, 0x22, 0x68, 0x63, 0x97, 0xBC, 0x85, 0xBA, 0xA8, 0xF7, + 0xB5, 0x40, 0x68, 0x3C, 0x77, 0x86, 0x6F, 0x4B, 0xD7, 0x88, 0xCA, 0x8A, 0xD7, 0xCE, 0x36, 0xF0, + 0x45, 0x6E, 0xD5, 0x64, 0x79, 0x0F, 0x17, 0xFC, 0x64, 0xDD, 0x10, 0x6F, 0xF3, 0xF5, 0xE0, 0xA6, + 0xC3, 0xFB, 0x1B, 0x8C, 0x29, 0xEF, 0x8E, 0xE5, 0x34, 0xCB, 0xD1, 0x2A, 0xCE, 0x79, 0xC3, 0x9A, + 0x0D, 0x36, 0xEA, 0x01, 0xE0, 0xAA, 0x91, 0x20, 0x54, 0xF0, 0x72, 0xD8, 0x1E, 0xC7, 0x89, 0xD2 + }; Target->append(tdata, sizeof(tdata)); + } *Target << uint32(0); } diff --git a/src/server/game/Handlers/BattleGroundHandler.cpp b/src/server/game/Handlers/BattleGroundHandler.cpp index d1da504008e..085b5181913 100755 --- a/src/server/game/Handlers/BattleGroundHandler.cpp +++ b/src/server/game/Handlers/BattleGroundHandler.cpp @@ -72,17 +72,35 @@ void WorldSession::SendBattleGroundList(uint64 guid, BattlegroundTypeId bgTypeId void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket & recvData) { - uint64 guid; uint32 bgTypeId_; uint32 instanceId; - uint8 joinAsGroup; + uint8 asGroup; bool isPremade = false; Group* grp = NULL; - - recvData >> guid; // battlemaster guid - recvData >> bgTypeId_; // battleground type id (DBC id) - recvData >> instanceId; // instance id, 0 if First Available selected - recvData >> joinAsGroup; // join as group + ObjectGuid guid; + + recvData >> instanceId; // Instance Id + guid[2] = recvData.ReadBit(); + guid[0] = recvData.ReadBit(); + guid[3] = recvData.ReadBit(); + guid[1] = recvData.ReadBit(); + guid[5] = recvData.ReadBit(); + asGroup = recvData.ReadBit(); // As Group + guid[4] = recvData.ReadBit(); + guid[6] = recvData.ReadBit(); + guid[7] = recvData.ReadBit(); + + recvData.ReadByteSeq(guid[2]); + recvData.ReadByteSeq(guid[6]); + recvData.ReadByteSeq(guid[4]); + recvData.ReadByteSeq(guid[3]); + recvData.ReadByteSeq(guid[7]); + recvData.ReadByteSeq(guid[0]); + recvData.ReadByteSeq(guid[5]); + recvData.ReadByteSeq(guid[1]); + + //extract from guid + bgTypeId_ = GUID_LOPART(guid); if (!sBattlemasterListStore.LookupEntry(bgTypeId_)) { @@ -95,10 +113,9 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket & recvData) ChatHandler(this).PSendSysMessage(LANG_BG_DISABLED); return; } - BattlegroundTypeId bgTypeId = BattlegroundTypeId(bgTypeId_); - sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_BATTLEMASTER_JOIN Message from (GUID: %u TypeId:%u)", GUID_LOPART(guid), GuidHigh2TypeId(GUID_HIPART(guid))); + //sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_BATTLEMASTER_JOIN Message from (GUID:"UI64FMTD" TypeId:%u)", guid, bgTypeId_); // can do this, since it's battleground, not arena BattlegroundQueueTypeId bgQueueTypeId = BattlegroundMgr::BGQueueTypeId(bgTypeId, 0); @@ -126,13 +143,13 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket & recvData) GroupJoinBattlegroundResult err; // check queue conditions - if (!joinAsGroup) + if (!asGroup) { if (GetPlayer()->isUsingLfg()) { // player is using dungeon finder or raid finder WorldPacket data; - sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, ERR_LFG_CANT_USE_BATTLEGROUND); + sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, bg, _player, ERR_LFG_CANT_USE_BATTLEGROUND); GetPlayer()->GetSession()->SendPacket(&data); return; } @@ -141,7 +158,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket & recvData) if (!_player->CanJoinToBattleground()) { WorldPacket data; - sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, ERR_GROUP_JOIN_BATTLEGROUND_DESERTERS); + sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, bg, _player, ERR_GROUP_JOIN_BATTLEGROUND_DESERTERS); _player->GetSession()->SendPacket(&data); return; } @@ -150,7 +167,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket & recvData) { //player is already in random queue WorldPacket data; - sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, ERR_IN_RANDOM_BG); + sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, bg, _player, ERR_IN_RANDOM_BG); _player->GetSession()->SendPacket(&data); return; } @@ -159,7 +176,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket & recvData) { //player is already in queue, can't start random queue WorldPacket data; - sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, ERR_IN_NON_RANDOM_BG); + sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, bg, _player, ERR_IN_NON_RANDOM_BG); _player->GetSession()->SendPacket(&data); return; } @@ -173,7 +190,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket & recvData) if (!_player->HasFreeBattlegroundQueueId()) { WorldPacket data; - sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, ERR_BATTLEGROUND_TOO_MANY_QUEUES); + sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, bg, _player, ERR_BATTLEGROUND_TOO_MANY_QUEUES); _player->GetSession()->SendPacket(&data); return; } @@ -187,7 +204,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket & recvData) WorldPacket data; // send status packet (in queue) - sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, queueSlot, STATUS_WAIT_QUEUE, avgTime, 0, ginfo->ArenaType); + sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, _player, queueSlot, STATUS_WAIT_QUEUE, avgTime, 0, ginfo->ArenaType); SendPacket(&data); sLog->outDebug(LOG_FILTER_BATTLEGROUND, "Battleground: player joined queue for bg queue type %u bg type %u: GUID %u, NAME %s", bgQueueTypeId, bgTypeId, _player->GetGUIDLow(), _player->GetName()); } @@ -223,7 +240,7 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket & recvData) if (err <= 0) { - sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, err); + sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, bg, _player, err); member->GetSession()->SendPacket(&data); continue; } @@ -232,9 +249,9 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket & recvData) uint32 queueSlot = member->AddBattlegroundQueueId(bgQueueTypeId); // send status packet (in queue) - sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, queueSlot, STATUS_WAIT_QUEUE, avgTime, 0, ginfo->ArenaType); + sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, member, queueSlot, STATUS_WAIT_QUEUE, avgTime, 0, ginfo->ArenaType); member->GetSession()->SendPacket(&data); - sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, err); + sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, bg, _player, err); member->GetSession()->SendPacket(&data); sLog->outDebug(LOG_FILTER_BATTLEGROUND, "Battleground: player joined queue for bg queue type %u bg type %u: GUID %u, NAME %s", bgQueueTypeId, bgTypeId, member->GetGUIDLow(), member->GetName()); } @@ -246,13 +263,14 @@ void WorldSession::HandleBattlemasterJoinOpcode(WorldPacket & recvData) void WorldSession::HandleBattlegroundPlayerPositionsOpcode(WorldPacket & /*recvData*/) { - sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd MSG_BATTLEGROUND_PLAYER_POSITIONS Message"); + sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_BATTLEGROUND_PLAYER_POSITIONS Message"); Battleground* bg = _player->GetBattleground(); if (!bg) // can't be received if player not in battleground return; - uint32 count = 0; + uint32 acount = 0; + uint32 hcount = 0; Player* aplr = NULL; Player* hplr = NULL; @@ -260,31 +278,75 @@ void WorldSession::HandleBattlegroundPlayerPositionsOpcode(WorldPacket & /*recvD { aplr = ObjectAccessor::FindPlayer(guid); if (aplr) - ++count; + ++acount; } if (uint64 guid = bg->GetFlagPickerGUID(BG_TEAM_HORDE)) { hplr = ObjectAccessor::FindPlayer(guid); if (hplr) - ++count; + ++hcount; } - WorldPacket data(MSG_BATTLEGROUND_PLAYER_POSITIONS, 4 + 4 + 16 * count); - data << 0; - data << count; - if (aplr) + ObjectGuid aguid = aplr ? aplr->GetGUID() : 0; + ObjectGuid hguid = hplr ? hplr->GetGUID() : 0; + + WorldPacket data(SMSG_BATTLEFIELD_PLAYER_POSITIONS); + + data.WriteBits(acount, 22); + for (uint8 i = 0; i < acount; i++) { - data << uint64(aplr->GetGUID()); - data << float(aplr->GetPositionX()); - data << float(aplr->GetPositionY()); + data.WriteBit(aguid[3]); + data.WriteBit(aguid[5]); + data.WriteBit(aguid[1]); + data.WriteBit(aguid[6]); + data.WriteBit(aguid[7]); + data.WriteBit(aguid[0]); + data.WriteBit(aguid[2]); + data.WriteBit(aguid[4]); } - if (hplr) + data.WriteBits(hcount, 22); + for (uint8 i = 0; i < hcount; i++) { - data << uint64(hplr->GetGUID()); - data << float(hplr->GetPositionX()); + data.WriteBit(hguid[6]); + data.WriteBit(hguid[5]); + data.WriteBit(hguid[4]); + data.WriteBit(hguid[7]); + data.WriteBit(hguid[2]); + data.WriteBit(hguid[1]); + data.WriteBit(hguid[0]); + data.WriteBit(hguid[3]); + } + + data.FlushBits(); + + for (uint8 i = 0; i < hcount; i++) + { + data.WriteByteSeq(hguid[2]); + data.WriteByteSeq(hguid[1]); data << float(hplr->GetPositionY()); + data.WriteByteSeq(hguid[5]); + data.WriteByteSeq(hguid[4]); + data.WriteByteSeq(hguid[7]); + data.WriteByteSeq(hguid[0]); + data.WriteByteSeq(hguid[6]); + data.WriteByteSeq(hguid[3]); + data << float(hplr->GetPositionX()); + } + + for (uint8 i = 0; i < acount; i++) + { + data.WriteByteSeq(aguid[6]); + data << float(aplr->GetPositionX()); + data.WriteByteSeq(aguid[5]); + data.WriteByteSeq(aguid[3]); + data << float(aplr->GetPositionY()); + data.WriteByteSeq(aguid[1]); + data.WriteByteSeq(aguid[7]); + data.WriteByteSeq(aguid[0]); + data.WriteByteSeq(aguid[2]); + data.WriteByteSeq(aguid[4]); } SendPacket(&data); @@ -292,7 +354,7 @@ void WorldSession::HandleBattlegroundPlayerPositionsOpcode(WorldPacket & /*recvD void WorldSession::HandlePVPLogDataOpcode(WorldPacket & /*recvData*/) { - sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd MSG_PVP_LOG_DATA Message"); + sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_PVP_LOG_DATA Message"); Battleground* bg = _player->GetBattleground(); if (!bg) @@ -306,7 +368,7 @@ void WorldSession::HandlePVPLogDataOpcode(WorldPacket & /*recvData*/) sBattlegroundMgr->BuildPvpLogDataPacket(&data, bg); SendPacket(&data); - sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent MSG_PVP_LOG_DATA Message"); + sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_PVP_LOG_DATA Message"); } void WorldSession::HandleBattlefieldListOpcode(WorldPacket& recvData) @@ -332,13 +394,35 @@ void WorldSession::HandleBattleFieldPortOpcode(WorldPacket &recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_BATTLEFIELD_PORT Message"); - uint8 type; // arenatype if arena - uint8 unk2; // unk, can be 0x0 (may be if was invited?) and 0x1 + uint32 time; + uint32 type; // guessed uint32 bgTypeId_; // type id from dbc - uint16 unk; // 0x1F90 constant? uint8 action; // enter battle 0x1, leave queue 0x0 - - recvData >> type >> unk2 >> bgTypeId_ >> unk >> action; + ObjectGuid guid; + + recvData >> time; + recvData >> type; + recvData >> bgTypeId_; + + guid[0] = recvData.ReadBit(); + guid[1] = recvData.ReadBit(); + guid[5] = recvData.ReadBit(); + guid[6] = recvData.ReadBit(); + guid[7] = recvData.ReadBit(); + guid[4] = recvData.ReadBit(); + guid[3] = recvData.ReadBit(); + guid[2] = recvData.ReadBit(); + + action = recvData.ReadBit(); + + recvData.ReadByteSeq(guid[1]); + recvData.ReadByteSeq(guid[3]); + recvData.ReadByteSeq(guid[5]); + recvData.ReadByteSeq(guid[7]); + recvData.ReadByteSeq(guid[0]); + recvData.ReadByteSeq(guid[2]); + recvData.ReadByteSeq(guid[6]); + recvData.ReadByteSeq(guid[4]); if (!sBattlemasterListStore.LookupEntry(bgTypeId_)) { @@ -394,7 +478,7 @@ void WorldSession::HandleBattleFieldPortOpcode(WorldPacket &recvData) { //send bg command result to show nice message WorldPacket data2; - sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data2, ERR_GROUP_JOIN_BATTLEGROUND_DESERTERS); + sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data2, bg, _player, ERR_GROUP_JOIN_BATTLEGROUND_DESERTERS); _player->GetSession()->SendPacket(&data2); action = 0; sLog->outDebug(LOG_FILTER_BATTLEGROUND, "Battleground: player %s (%u) has a deserter debuff, do not port him to battleground!", _player->GetName(), _player->GetGUIDLow()); @@ -431,7 +515,7 @@ void WorldSession::HandleBattleFieldPortOpcode(WorldPacket &recvData) _player->CleanupAfterTaxiFlight(); } - sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, queueSlot, STATUS_IN_PROGRESS, 0, bg->GetStartTime(), bg->GetArenaType()); + sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, _player, queueSlot, STATUS_IN_PROGRESS, 0, bg->GetStartTime(), bg->GetArenaType()); _player->GetSession()->SendPacket(&data); // remove battleground queue status from BGmgr bgQueue.RemovePlayer(_player->GetGUID(), false); @@ -463,7 +547,7 @@ void WorldSession::HandleBattleFieldPortOpcode(WorldPacket &recvData) } } _player->RemoveBattlegroundQueueId(bgQueueTypeId); // must be called this way, because if you move this call to queue->removeplayer, it causes bugs - sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, queueSlot, STATUS_NONE, 0, 0, 0); + sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, _player, queueSlot, STATUS_NONE, 0, 0, 0); bgQueue.RemovePlayer(_player->GetGUID(), true); // player left queue, we should update it - do not update Arena Queue if (!ginfo.ArenaType) @@ -477,14 +561,9 @@ void WorldSession::HandleBattleFieldPortOpcode(WorldPacket &recvData) } } -void WorldSession::HandleLeaveBattlefieldOpcode(WorldPacket& recvData) +void WorldSession::HandleBattlefieldLeaveOpcode(WorldPacket& recvData) { - sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_LEAVE_BATTLEFIELD Message"); - - recvData.read_skip<uint8>(); // unk1 - recvData.read_skip<uint8>(); // unk2 - recvData.read_skip<uint32>(); // BattlegroundTypeId - recvData.read_skip<uint16>(); // unk3 + sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_BATTLEFIELD_LEAVE Message"); // not allow leave battleground in combat if (_player->isInCombat()) @@ -519,7 +598,7 @@ void WorldSession::HandleBattlefieldStatusOpcode(WorldPacket & /*recvData*/) { // this line is checked, i only don't know if GetStartTime is changing itself after bg end! // send status in Battleground - sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, i, STATUS_IN_PROGRESS, bg->GetEndTime(), bg->GetStartTime(), arenaType); + sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, GetPlayer(), i, STATUS_IN_PROGRESS, bg->GetEndTime(), bg->GetStartTime(), arenaType); SendPacket(&data); continue; } @@ -537,7 +616,7 @@ void WorldSession::HandleBattlefieldStatusOpcode(WorldPacket & /*recvData*/) continue; uint32 remainingTime = getMSTimeDiff(getMSTime(), ginfo.RemoveInviteTime); // send status invited to Battleground - sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, i, STATUS_WAIT_JOIN, remainingTime, 0, arenaType); + sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, GetPlayer(), i, STATUS_WAIT_JOIN, remainingTime, 0, arenaType); SendPacket(&data); } else @@ -553,7 +632,7 @@ void WorldSession::HandleBattlefieldStatusOpcode(WorldPacket & /*recvData*/) uint32 avgTime = bgQueue.GetAverageQueueWaitTime(&ginfo, bracketEntry->GetBracketId()); // send status in Battleground Queue - sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, i, STATUS_WAIT_QUEUE, avgTime, getMSTimeDiff(ginfo.JoinTime, getMSTime()), arenaType); + sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, GetPlayer(), i, STATUS_WAIT_QUEUE, avgTime, getMSTimeDiff(ginfo.JoinTime, getMSTime()), arenaType); SendPacket(&data); } } @@ -696,7 +775,7 @@ void WorldSession::HandleBattlemasterJoinArena(WorldPacket & recvData) if (err <= 0) { - sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, err); + sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, bg, _player, err); member->GetSession()->SendPacket(&data); continue; } @@ -705,9 +784,9 @@ void WorldSession::HandleBattlemasterJoinArena(WorldPacket & recvData) uint32 queueSlot = member->AddBattlegroundQueueId(bgQueueTypeId); // send status packet (in queue) - sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, queueSlot, STATUS_WAIT_QUEUE, avgTime, 0, arenatype); + sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, member, queueSlot, STATUS_WAIT_QUEUE, avgTime, 0, arenatype); member->GetSession()->SendPacket(&data); - sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, err); + sBattlegroundMgr->BuildGroupJoinedBattlegroundPacket(&data, bg, _player, err); member->GetSession()->SendPacket(&data); sLog->outDebug(LOG_FILTER_BATTLEGROUND, "Battleground: player joined queue for arena as group bg queue type %u bg type %u: GUID %u, NAME %s", bgQueueTypeId, bgTypeId, member->GetGUIDLow(), member->GetName()); } @@ -720,7 +799,7 @@ void WorldSession::HandleBattlemasterJoinArena(WorldPacket & recvData) WorldPacket data; // send status packet (in queue) - sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, queueSlot, STATUS_WAIT_QUEUE, avgTime, 0, arenatype); + sBattlegroundMgr->BuildBattlegroundStatusPacket(&data, bg, GetPlayer(), queueSlot, STATUS_WAIT_QUEUE, avgTime, 0, arenatype); SendPacket(&data); sLog->outDebug(LOG_FILTER_BATTLEGROUND, "Battleground: player joined queue for arena, skirmish, bg queue type %u bg type %u: GUID %u, NAME %s", bgQueueTypeId, bgTypeId, _player->GetGUIDLow(), _player->GetName()); } diff --git a/src/server/game/Handlers/CharacterHandler.cpp b/src/server/game/Handlers/CharacterHandler.cpp index 649f09ad212..c7b66381158 100644 --- a/src/server/game/Handlers/CharacterHandler.cpp +++ b/src/server/game/Handlers/CharacterHandler.cpp @@ -740,11 +740,7 @@ void WorldSession::HandleCharDeleteOpcode(WorldPacket & recvData) { std::string dump; if (PlayerDumpWriter().GetDump(GUID_LOPART(guid), dump)) - { - std::ostringstream ss; - ss << GetAccountId() << '_' << name.c_str(); - sLog->outCharDump(ss.str().c_str(), dump.c_str(), GetAccountId(), GUID_LOPART(guid), name.c_str()); - } + sLog->outCharDump(dump.c_str(), GetAccountId(), GUID_LOPART(guid), name.c_str()); } Player::DeleteFromDB(guid, GetAccountId()); diff --git a/src/server/game/Handlers/GroupHandler.cpp b/src/server/game/Handlers/GroupHandler.cpp index ae549d76b33..1d6cbf61c68 100644 --- a/src/server/game/Handlers/GroupHandler.cpp +++ b/src/server/game/Handlers/GroupHandler.cpp @@ -33,6 +33,7 @@ #include "Vehicle.h" #include "DB2Structure.h" #include "DB2Stores.h" +#include "SpellAuraEffects.h" class Aura; @@ -180,7 +181,7 @@ void WorldSession::HandleGroupInviteOpcode(WorldPacket & recvData) data.WriteBit(invitedGuid[4]); - data.WriteBits(strlen(player->GetName()), 7); // Invited name length + data.WriteBits(strlen(GetPlayer()->GetName()), 7); // Inviter name length data.WriteBits(0, 24); // Count 2 @@ -211,7 +212,7 @@ void WorldSession::HandleGroupInviteOpcode(WorldPacket & recvData) data.WriteByteSeq(invitedGuid[7]); - data.WriteString(player->GetName()); // invited name + data.WriteString(GetPlayer()->GetName()); // inviter name data << int32(0); @@ -282,7 +283,7 @@ void WorldSession::HandleGroupInviteOpcode(WorldPacket & recvData) data.WriteBit(invitedGuid[4]); - data.WriteBits(strlen(player->GetName()), 7); // Invited name length + data.WriteBits(strlen(GetPlayer()->GetName()), 7); // Inviter name length data.WriteBits(0, 24); // Count 2 @@ -313,7 +314,7 @@ void WorldSession::HandleGroupInviteOpcode(WorldPacket & recvData) data.WriteByteSeq(invitedGuid[7]); - data.WriteString(player->GetName()); + data.WriteString(GetPlayer()->GetName()); data << int32(0); @@ -390,9 +391,8 @@ void WorldSession::HandleGroupInviteResponseOpcode(WorldPacket& recvData) return; // report - std::string name = std::string(GetPlayer()->GetName()); - WorldPacket data(SMSG_GROUP_DECLINE, name.length()); - data << name.c_str(); + WorldPacket data(SMSG_GROUP_DECLINE, strlen(GetPlayer()->GetName())); + data << GetPlayer()->GetName(); leader->GetSession()->SendPacket(&data); } } @@ -510,6 +510,80 @@ void WorldSession::HandleGroupSetLeaderOpcode(WorldPacket& recvData) group->SendUpdate(); } +void WorldSession::HandleGroupSetRolesOpcode(WorldPacket& recvData) +{ + sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_GROUP_SET_ROLES"); + + uint32 newRole; + ObjectGuid guid1; // Assigner GUID + ObjectGuid guid2; // Target GUID + + guid1 = GetPlayer()->GetGUID(); + + recvData >> newRole; + + guid2[2] = recvData.ReadBit(); + guid2[6] = recvData.ReadBit(); + guid2[3] = recvData.ReadBit(); + guid2[7] = recvData.ReadBit(); + guid2[5] = recvData.ReadBit(); + guid2[1] = recvData.ReadBit(); + guid2[0] = recvData.ReadBit(); + guid2[4] = recvData.ReadBit(); + + recvData.ReadByteSeq(guid2[6]); + recvData.ReadByteSeq(guid2[4]); + recvData.ReadByteSeq(guid2[1]); + recvData.ReadByteSeq(guid2[3]); + recvData.ReadByteSeq(guid2[0]); + recvData.ReadByteSeq(guid2[5]); + recvData.ReadByteSeq(guid2[2]); + recvData.ReadByteSeq(guid2[7]); + + WorldPacket data(SMSG_GROUP_SET_ROLE, 24); + + data.WriteBit(guid1[1]); + data.WriteBit(guid2[0]); + data.WriteBit(guid2[2]); + data.WriteBit(guid2[4]); + data.WriteBit(guid2[7]); + data.WriteBit(guid2[3]); + data.WriteBit(guid1[7]); + data.WriteBit(guid2[5]); + data.WriteBit(guid1[5]); + data.WriteBit(guid1[4]); + data.WriteBit(guid1[3]); + data.WriteBit(guid2[6]); + data.WriteBit(guid1[2]); + data.WriteBit(guid1[6]); + data.WriteBit(guid2[1]); + data.WriteBit(guid1[0]); + + data.WriteByteSeq(guid1[7]); + data.WriteByteSeq(guid2[3]); + data.WriteByteSeq(guid1[6]); + data.WriteByteSeq(guid2[4]); + data.WriteByteSeq(guid2[0]); + data << uint32(newRole); // New Role + data.WriteByteSeq(guid2[6]); + data.WriteByteSeq(guid2[2]); + data.WriteByteSeq(guid1[0]); + data.WriteByteSeq(guid1[4]); + data.WriteByteSeq(guid2[1]); + data.WriteByteSeq(guid1[3]); + data.WriteByteSeq(guid1[5]); + data.WriteByteSeq(guid1[2]); + data.WriteByteSeq(guid2[5]); + data.WriteByteSeq(guid2[7]); + data.WriteByteSeq(guid1[1]); + data << uint32(0); // Old Role + + if (GetPlayer()->GetGroup()) + GetPlayer()->GetGroup()->BroadcastPacket(&data, false); + else + SendPacket(&data); +} + void WorldSession::HandleGroupDisbandOpcode(WorldPacket& /*recvData*/) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_GROUP_DISBAND"); @@ -857,64 +931,82 @@ void WorldSession::BuildPartyMemberStatsChangedPacket(Player* player, WorldPacke if (mask & GROUP_UPDATE_FLAG_PET_POWER_TYPE) // same for pets mask |= (GROUP_UPDATE_FLAG_PET_CUR_POWER | GROUP_UPDATE_FLAG_PET_MAX_POWER); - uint32 byteCount = 0; - for (int i = 1; i < GROUP_UPDATE_FLAGS_COUNT; ++i) - if (mask & (1 << i)) - byteCount += GroupUpdateLength[i]; - - data->Initialize(SMSG_PARTY_MEMBER_STATS, 8 + 4 + byteCount); + data->Initialize(SMSG_PARTY_MEMBER_STATS, 80); // average value data->append(player->GetPackGUID()); - *data << (uint32) mask; + *data << uint32(mask); if (mask & GROUP_UPDATE_FLAG_STATUS) { if (player) { if (player->IsPvP()) - *data << (uint16) (MEMBER_STATUS_ONLINE | MEMBER_STATUS_PVP); + *data << uint16(MEMBER_STATUS_ONLINE | MEMBER_STATUS_PVP); else - *data << (uint16) MEMBER_STATUS_ONLINE; + *data << uint16(MEMBER_STATUS_ONLINE); } else - *data << (uint16) MEMBER_STATUS_OFFLINE; + *data << uint16(MEMBER_STATUS_OFFLINE); } if (mask & GROUP_UPDATE_FLAG_CUR_HP) - *data << (uint32) player->GetHealth(); + *data << uint32(player->GetHealth()); if (mask & GROUP_UPDATE_FLAG_MAX_HP) - *data << (uint32) player->GetMaxHealth(); + *data << uint32(player->GetMaxHealth()); Powers powerType = player->getPowerType(); if (mask & GROUP_UPDATE_FLAG_POWER_TYPE) - *data << (uint8) powerType; + *data << uint8(powerType); if (mask & GROUP_UPDATE_FLAG_CUR_POWER) - *data << (uint16) player->GetPower(powerType); + *data << uint16(player->GetPower(powerType)); if (mask & GROUP_UPDATE_FLAG_MAX_POWER) - *data << (uint16) player->GetMaxPower(powerType); + *data << uint16(player->GetMaxPower(powerType)); if (mask & GROUP_UPDATE_FLAG_LEVEL) - *data << (uint16) player->getLevel(); + *data << uint16(player->getLevel()); if (mask & GROUP_UPDATE_FLAG_ZONE) - *data << (uint16) player->GetZoneId(); + *data << uint16(player->GetZoneId()); + + if (mask & GROUP_UPDATE_FLAG_UNK100) + *data << uint16(0); if (mask & GROUP_UPDATE_FLAG_POSITION) - *data << (uint16) player->GetPositionX() << (uint16) player->GetPositionY(); + *data << uint16(player->GetPositionX()) << uint16(player->GetPositionY()) << uint16(player->GetPositionZ()); if (mask & GROUP_UPDATE_FLAG_AURAS) { + *data << uint8(0); uint64 auramask = player->GetAuraUpdateMaskForRaid(); *data << uint64(auramask); + *data << uint32(MAX_AURAS); // count for (uint32 i = 0; i < MAX_AURAS; ++i) { if (auramask & (uint64(1) << i)) { AuraApplication const* aurApp = player->GetVisibleAura(i); - *data << uint32(aurApp ? aurApp->GetBase()->GetId() : 0); - *data << uint8(1); + if (!aurApp) + { + *data << uint32(0); + *data << uint16(0); + continue; + } + + *data << uint32(aurApp->GetBase()->GetId()); + *data << uint16(aurApp->GetFlags()); + + if (aurApp->GetFlags() & AFLAG_ANY_EFFECT_AMOUNT_SENT) + { + for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) + { + if (AuraEffect const* eff = aurApp->GetBase()->GetEffect(i)) + *data << int32(eff->GetAmount()); + else + *data << int32(0); + } + } } } } @@ -923,9 +1015,9 @@ void WorldSession::BuildPartyMemberStatsChangedPacket(Player* player, WorldPacke if (mask & GROUP_UPDATE_FLAG_PET_GUID) { if (pet) - *data << (uint64) pet->GetGUID(); + *data << uint64(pet->GetGUID()); else - *data << (uint64) 0; + *data << uint64(0); } if (mask & GROUP_UPDATE_FLAG_PET_NAME) @@ -933,81 +1025,113 @@ void WorldSession::BuildPartyMemberStatsChangedPacket(Player* player, WorldPacke if (pet) *data << pet->GetName(); else - *data << (uint8) 0; + *data << uint8(0); } if (mask & GROUP_UPDATE_FLAG_PET_MODEL_ID) { if (pet) - *data << (uint16) pet->GetDisplayId(); + *data << uint16(pet->GetDisplayId()); else - *data << (uint16) 0; + *data << uint16(0); } if (mask & GROUP_UPDATE_FLAG_PET_CUR_HP) { if (pet) - *data << (uint32) pet->GetHealth(); + *data << uint32(pet->GetHealth()); else - *data << (uint32) 0; + *data << uint32(0); } if (mask & GROUP_UPDATE_FLAG_PET_MAX_HP) { if (pet) - *data << (uint32) pet->GetMaxHealth(); + *data << uint32(pet->GetMaxHealth()); else - *data << (uint32) 0; + *data << uint32(0); } if (mask & GROUP_UPDATE_FLAG_PET_POWER_TYPE) { if (pet) - *data << (uint8) pet->getPowerType(); + *data << uint8(pet->getPowerType()); else - *data << (uint8) 0; + *data << uint8(0); } if (mask & GROUP_UPDATE_FLAG_PET_CUR_POWER) { if (pet) - *data << (uint16) pet->GetPower(pet->getPowerType()); + *data << uint16(pet->GetPower(pet->getPowerType())); else - *data << (uint16) 0; + *data << uint16(0); } if (mask & GROUP_UPDATE_FLAG_PET_MAX_POWER) { if (pet) - *data << (uint16) pet->GetMaxPower(pet->getPowerType()); + *data << uint16(pet->GetMaxPower(pet->getPowerType())); else - *data << (uint16) 0; + *data << uint16(0); } if (mask & GROUP_UPDATE_FLAG_VEHICLE_SEAT) { if (Vehicle* veh = player->GetVehicle()) - *data << (uint32) veh->GetVehicleInfo()->m_seatID[player->m_movementInfo.t_seat]; + *data << uint32(veh->GetVehicleInfo()->m_seatID[player->m_movementInfo.t_seat]); + else + *data << uint32(0); } if (mask & GROUP_UPDATE_FLAG_PET_AURAS) { if (pet) { + *data << uint8(0); uint64 auramask = pet->GetAuraUpdateMaskForRaid(); *data << uint64(auramask); + *data << uint32(MAX_AURAS); // count for (uint32 i = 0; i < MAX_AURAS; ++i) { if (auramask & (uint64(1) << i)) { - AuraApplication const* aurApp = player->GetVisibleAura(i); - *data << uint32(aurApp ? aurApp->GetBase()->GetId() : 0); - *data << uint8(1); + AuraApplication const* aurApp = pet->GetVisibleAura(i); + if (!aurApp) + { + *data << uint32(0); + *data << uint16(0); + continue; + } + + *data << uint32(aurApp->GetBase()->GetId()); + *data << uint16(aurApp->GetFlags()); + + if (aurApp->GetFlags() & AFLAG_ANY_EFFECT_AMOUNT_SENT) + { + for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) + { + if (AuraEffect const* eff = aurApp->GetBase()->GetEffect(i)) + *data << int32(eff->GetAmount()); + else + *data << int32(0); + } + } } } } else - *data << (uint64) 0; + { + *data << uint8(0); + *data << uint64(0); + } + } + + if (mask & GROUP_UPDATE_FLAG_PHASE) + { + *data << uint32(8); // either 0 or 8, same unk found in SMSG_PHASESHIFT + *data << uint32(0); // count + // for (count) *data << uint16(phaseId) } } @@ -1015,15 +1139,15 @@ void WorldSession::BuildPartyMemberStatsChangedPacket(Player* player, WorldPacke void WorldSession::HandleRequestPartyMemberStatsOpcode(WorldPacket& recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_REQUEST_PARTY_MEMBER_STATS"); - uint64 Guid; - recvData >> Guid; + uint64 guid; + recvData >> guid; - Player* player = HashMapHolder<Player>::Find(Guid); + Player* player = HashMapHolder<Player>::Find(guid); if (!player) { WorldPacket data(SMSG_PARTY_MEMBER_STATS_FULL, 3+4+2); data << uint8(0); // only for SMSG_PARTY_MEMBER_STATS_FULL, probably arena/bg related - data.appendPackGUID(Guid); + data.appendPackGUID(guid); data << (uint32) GROUP_UPDATE_FLAG_STATUS; data << (uint16) MEMBER_STATUS_OFFLINE; SendPacket(&data); @@ -1036,84 +1160,113 @@ void WorldSession::HandleRequestPartyMemberStatsOpcode(WorldPacket& recvData) data << uint8(0); // only for SMSG_PARTY_MEMBER_STATS_FULL, probably arena/bg related data.append(player->GetPackGUID()); - uint32 mask1 = 0x00040BFF; // common mask, real flags used 0x000040BFF - if (pet) - mask1 = 0x7FFFFFFF; // for hunters and other classes with pets + uint32 mask1 = GROUP_UPDATE_FULL; - Powers powerType = player->getPowerType(); - data << (uint32) mask1; // group update mask - data << (uint16) MEMBER_STATUS_ONLINE; // member's online status - data << (uint32) player->GetHealth(); // GROUP_UPDATE_FLAG_CUR_HP - data << (uint32) player->GetMaxHealth(); // GROUP_UPDATE_FLAG_MAX_HP - data << (uint8) powerType; // GROUP_UPDATE_FLAG_POWER_TYPE - data << (uint16) player->GetPower(powerType); // GROUP_UPDATE_FLAG_CUR_POWER - data << (uint16) player->GetMaxPower(powerType); // GROUP_UPDATE_FLAG_MAX_POWER - data << (uint16) player->getLevel(); // GROUP_UPDATE_FLAG_LEVEL - data << (uint16) player->GetZoneId(); // GROUP_UPDATE_FLAG_ZONE - data << (uint16) player->GetPositionX(); // GROUP_UPDATE_FLAG_POSITION - data << (uint16) player->GetPositionY(); // GROUP_UPDATE_FLAG_POSITION + if (!pet) + mask1 &= ~GROUP_UPDATE_PET; + Powers powerType = player->getPowerType(); + data << uint32(mask1); // group update mask + data << uint16(MEMBER_STATUS_ONLINE); // member's online status, GROUP_UPDATE_FLAG_STATUS + data << uint32(player->GetHealth()); // GROUP_UPDATE_FLAG_CUR_HP + data << uint32(player->GetMaxHealth()); // GROUP_UPDATE_FLAG_MAX_HP + data << uint8 (powerType); // GROUP_UPDATE_FLAG_POWER_TYPE + data << uint16(player->GetPower(powerType)); // GROUP_UPDATE_FLAG_CUR_POWER + data << uint16(player->GetMaxPower(powerType)); // GROUP_UPDATE_FLAG_MAX_POWER + data << uint16(player->getLevel()); // GROUP_UPDATE_FLAG_LEVEL + data << uint16(player->GetZoneId()); // GROUP_UPDATE_FLAG_ZONE + data << uint16(player->GetPositionX()); // GROUP_UPDATE_FLAG_POSITION + data << uint16(player->GetPositionY()); // GROUP_UPDATE_FLAG_POSITION + data << uint16(player->GetPositionZ()); // GROUP_UPDATE_FLAG_POSITION + + // GROUP_UPDATE_FLAG_AURAS + data << uint8(1); uint64 auramask = 0; size_t maskPos = data.wpos(); - data << (uint64) auramask; // placeholder + data << uint64(auramask); // placeholder + data << uint32(MAX_AURAS); // count for (uint8 i = 0; i < MAX_AURAS; ++i) { - if (AuraApplication * aurApp = player->GetVisibleAura(i)) + if (AuraApplication const* aurApp = player->GetVisibleAura(i)) { auramask |= (uint64(1) << i); - data << (uint32) aurApp->GetBase()->GetId(); - data << (uint8) 1; + + data << uint32(aurApp->GetBase()->GetId()); + data << uint16(aurApp->GetFlags()); + + if (aurApp->GetFlags() & AFLAG_ANY_EFFECT_AMOUNT_SENT) + { + for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) + { + if (AuraEffect const* eff = aurApp->GetBase()->GetEffect(i)) + data << int32(eff->GetAmount()); + else + data << int32(0); + } + } } } - data.put<uint64>(maskPos, auramask); // GROUP_UPDATE_FLAG_AURAS + data.put<uint64>(maskPos, auramask); // GROUP_UPDATE_FLAG_AURAS if (pet) { Powers petpowertype = pet->getPowerType(); - data << (uint64) pet->GetGUID(); // GROUP_UPDATE_FLAG_PET_GUID + data << uint64(pet->GetGUID()); // GROUP_UPDATE_FLAG_PET_GUID data << pet->GetName(); // GROUP_UPDATE_FLAG_PET_NAME - data << (uint16) pet->GetDisplayId(); // GROUP_UPDATE_FLAG_PET_MODEL_ID - data << (uint32) pet->GetHealth(); // GROUP_UPDATE_FLAG_PET_CUR_HP - data << (uint32) pet->GetMaxHealth(); // GROUP_UPDATE_FLAG_PET_MAX_HP - data << (uint8) petpowertype; // GROUP_UPDATE_FLAG_PET_POWER_TYPE - data << (uint16) pet->GetPower(petpowertype); // GROUP_UPDATE_FLAG_PET_CUR_POWER - data << (uint16) pet->GetMaxPower(petpowertype); // GROUP_UPDATE_FLAG_PET_MAX_POWER - + data << uint16(pet->GetDisplayId()); // GROUP_UPDATE_FLAG_PET_MODEL_ID + data << uint32(pet->GetHealth()); // GROUP_UPDATE_FLAG_PET_CUR_HP + data << uint32(pet->GetMaxHealth()); // GROUP_UPDATE_FLAG_PET_MAX_HP + data << uint8 (petpowertype); // GROUP_UPDATE_FLAG_PET_POWER_TYPE + data << uint16(pet->GetPower(petpowertype)); // GROUP_UPDATE_FLAG_PET_CUR_POWER + data << uint16(pet->GetMaxPower(petpowertype)); // GROUP_UPDATE_FLAG_PET_MAX_POWER + + // GROUP_UPDATE_FLAG_PET_AURAS + data << uint8(1); uint64 petauramask = 0; size_t petMaskPos = data.wpos(); - data << (uint64) petauramask; // placeholder + data << uint64(petauramask); // placeholder + data << uint32(MAX_AURAS); // count for (uint8 i = 0; i < MAX_AURAS; ++i) { - if (AuraApplication * auraApp = pet->GetVisibleAura(i)) + if (AuraApplication const* aurApp = pet->GetVisibleAura(i)) { petauramask |= (uint64(1) << i); - data << (uint32) auraApp->GetBase()->GetId(); - data << (uint8) 1; + + data << uint32(aurApp->GetBase()->GetId()); + data << uint16(aurApp->GetFlags()); + + if (aurApp->GetFlags() & AFLAG_ANY_EFFECT_AMOUNT_SENT) + { + for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) + { + if (AuraEffect const* eff = aurApp->GetBase()->GetEffect(i)) + data << int32(eff->GetAmount()); + else + data << int32(0); + } + } } } + data.put<uint64>(petMaskPos, petauramask); // GROUP_UPDATE_FLAG_PET_AURAS } - else - { - data << (uint8) 0; // GROUP_UPDATE_FLAG_PET_NAME - data << (uint64) 0; // GROUP_UPDATE_FLAG_PET_AURAS - } + // else not needed, flags do not include any PET_ update + + // GROUP_UPDATE_FLAG_PHASE + data << uint32(8); // either 0 or 8, same unk found in SMSG_PHASESHIFT + data << uint32(0); // count + // for (count) *data << uint16(phaseId) SendPacket(&data); } -/*!*/void WorldSession::HandleRequestRaidInfoOpcode(WorldPacket & /*recvData*/) +void WorldSession::HandleRequestRaidInfoOpcode(WorldPacket& /*recvData*/) { // every time the player checks the character screen _player->SendRaidInfo(); } -/*void WorldSession::HandleGroupCancelOpcode(WorldPacket & recvData) -{ - sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: got CMSG_GROUP_CANCEL."); -}*/ - -void WorldSession::HandleOptOutOfLootOpcode(WorldPacket & recvData) +void WorldSession::HandleOptOutOfLootOpcode(WorldPacket& recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_OPT_OUT_OF_LOOT"); diff --git a/src/server/game/Handlers/GuildHandler.cpp b/src/server/game/Handlers/GuildHandler.cpp index 778ecc2659f..b3c2d4ae030 100755 --- a/src/server/game/Handlers/GuildHandler.cpp +++ b/src/server/game/Handlers/GuildHandler.cpp @@ -397,7 +397,7 @@ void WorldSession::HandleSaveGuildEmblemOpcode(WorldPacket& recvPacket) void WorldSession::HandleGuildEventLogQueryOpcode(WorldPacket& /* recvPacket */) { - sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received (MSG_GUILD_EVENT_LOG_QUERY)"); + sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received (CMSG_GUILD_EVENT_LOG_QUERY)"); if (Guild* guild = _GetPlayerGuild(this)) guild->SendEventLog(this); @@ -613,7 +613,7 @@ void WorldSession::HandleGuildBankLogQuery(WorldPacket & recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received (MSG_GUILD_BANK_LOG_QUERY)"); - uint8 tabId; + uint32 tabId; recvData >> tabId; if (Guild* guild = _GetPlayerGuild(this)) @@ -622,7 +622,7 @@ void WorldSession::HandleGuildBankLogQuery(WorldPacket & recvData) void WorldSession::HandleQueryGuildBankTabText(WorldPacket &recvData) { - sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received MSG_QUERY_GUILD_BANK_TEXT"); + sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_GUILD_BANK_QUERY_TEXT"); uint8 tabId; recvData >> tabId; @@ -635,11 +635,11 @@ void WorldSession::HandleSetGuildBankTabText(WorldPacket& recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_SET_GUILD_BANK_TEXT"); - uint8 tabId; + uint32 tabId; recvData >> tabId; - std::string text; - recvData >> text; + uint32 textLen = recvData.ReadBits(14); + std::string text = recvData.ReadString(textLen); if (Guild* guild = _GetPlayerGuild(this)) guild->SetBankTabText(tabId, text); diff --git a/src/server/game/Handlers/ItemHandler.cpp b/src/server/game/Handlers/ItemHandler.cpp index ad8846ab071..3b38db78d94 100644 --- a/src/server/game/Handlers/ItemHandler.cpp +++ b/src/server/game/Handlers/ItemHandler.cpp @@ -754,16 +754,14 @@ void WorldSession::SendListInventory(uint64 vendorGuid) if (vendorItem->Type == ITEM_VENDOR_TYPE_ITEM) { ItemTemplate const* itemTemplate = sObjectMgr->GetItemTemplate(vendorItem->item); - if (!itemTemplate) continue; + if (!itemTemplate) + continue; + uint32 leftInStock = !vendorItem->maxcount ? 0xFFFFFFFF : vendor->GetVendorItemCurrentCount(vendorItem); if (!_player->isGameMaster()) // ignore conditions if GM on { // Respect allowed class - if (!(itemTemplate->AllowableClass & _player->getClassMask())) - continue; - - // Do not sell BOP items - if (itemTemplate->Bonding == BIND_WHEN_PICKED_UP) + if (!(itemTemplate->AllowableClass & _player->getClassMask()) && itemTemplate->Bonding == BIND_WHEN_PICKED_UP) continue; // Only display items in vendor lists for the team the player is on @@ -772,13 +770,11 @@ void WorldSession::SendListInventory(uint64 vendorGuid) continue; // Items sold out are not displayed in list - uint32 leftInStock = !vendorItem->maxcount ? 0xFFFFFFFF : vendor->GetVendorItemCurrentCount(vendorItem); if (leftInStock == 0) continue; } int32 price = vendorItem->IsGoldRequired(itemTemplate) ? uint32(floor(itemTemplate->BuyPrice * discountMod)) : 0; - uint32 leftInStock = !vendorItem->maxcount ? 0xFFFFFFFF : vendor->GetVendorItemCurrentCount(vendorItem); itemsData << uint32(count++ + 1); // client expects counting to start at 1 itemsData << uint32(itemTemplate->MaxDurability); @@ -803,10 +799,11 @@ void WorldSession::SendListInventory(uint64 vendorGuid) else if (vendorItem->Type == ITEM_VENDOR_TYPE_CURRENCY) { CurrencyTypesEntry const* currencyTemplate = sCurrencyTypesStore.LookupEntry(vendorItem->item); + if (!currencyTemplate) + continue; - if (!currencyTemplate) continue; - - if (vendorItem->ExtendedCost == 0) continue; // there's no price defined for currencies, only extendedcost is used + if (vendorItem->ExtendedCost == 0) + continue; // there's no price defined for currencies, only extendedcost is used uint32 precision = (currencyTemplate->Flags & CURRENCY_FLAG_HIGH_PRECISION) ? 100 : 1; @@ -820,6 +817,7 @@ void WorldSession::SendListInventory(uint64 vendorGuid) } else enablers.push_back(1); + enablers.push_back(1); // unk bit itemsData << uint32(vendorItem->item); @@ -833,40 +831,40 @@ void WorldSession::SendListInventory(uint64 vendorGuid) // else error } - uint8* guidBytes = (uint8*)&vendorGuid; + ObjectGuid guid = vendorGuid; WorldPacket data(SMSG_LIST_INVENTORY, 12 + itemsData.size()); - data.WriteBit(guidBytes[1]); - data.WriteBit(guidBytes[0]); + data.WriteBit(guid[1]); + data.WriteBit(guid[0]); data.WriteBits(count, 21); // item count - data.WriteBit(guidBytes[3]); - data.WriteBit(guidBytes[6]); - data.WriteBit(guidBytes[5]); - data.WriteBit(guidBytes[2]); - data.WriteBit(guidBytes[7]); + data.WriteBit(guid[3]); + data.WriteBit(guid[6]); + data.WriteBit(guid[5]); + data.WriteBit(guid[2]); + data.WriteBit(guid[7]); for (std::vector<bool>::const_iterator itr = enablers.begin(); itr != enablers.end(); ++itr) data.WriteBit(*itr); - data.WriteBit(guidBytes[4]); + data.WriteBit(guid[4]); data.FlushBits(); data.append(itemsData); - data.WriteByteSeq(guidBytes[5]); - data.WriteByteSeq(guidBytes[4]); - data.WriteByteSeq(guidBytes[1]); - data.WriteByteSeq(guidBytes[0]); - data.WriteByteSeq(guidBytes[6]); + data.WriteByteSeq(guid[5]); + data.WriteByteSeq(guid[4]); + data.WriteByteSeq(guid[1]); + data.WriteByteSeq(guid[0]); + data.WriteByteSeq(guid[6]); data << uint8(count == 0); // unk byte, item count 0: 1, item count != 0: 0 or some "random" value below 300 - data.WriteByteSeq(guidBytes[2]); - data.WriteByteSeq(guidBytes[3]); - data.WriteByteSeq(guidBytes[7]); + data.WriteByteSeq(guid[2]); + data.WriteByteSeq(guid[3]); + data.WriteByteSeq(guid[7]); SendPacket(&data); } @@ -1622,6 +1620,9 @@ void WorldSession::HandleTransmogrifyItems(WorldPacket& recvData) itemTransmogrified->SetNotRefundable(player); itemTransmogrified->ClearSoulboundTradeable(player); + if (itemTransmogrifier->GetTemplate()->Bonding == BIND_WHEN_EQUIPED || itemTransmogrifier->GetTemplate()->Bonding == BIND_WHEN_USE) + itemTransmogrifier->SetBinding(true); + itemTransmogrifier->SetOwnerGUID(player->GetGUID()); itemTransmogrifier->SetNotRefundable(player); itemTransmogrifier->ClearSoulboundTradeable(player); diff --git a/src/server/game/Handlers/MiscHandler.cpp b/src/server/game/Handlers/MiscHandler.cpp index 677b3cccf82..18ec0067623 100644 --- a/src/server/game/Handlers/MiscHandler.cpp +++ b/src/server/game/Handlers/MiscHandler.cpp @@ -85,7 +85,7 @@ void WorldSession::HandleRepopRequestOpcode(WorldPacket& recvData) GetPlayer()->RepopAtGraveyard(); } -void WorldSession::HandleGossipSelectOptionOpcode(WorldPacket & recvData) +void WorldSession::HandleGossipSelectOptionOpcode(WorldPacket& recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_GOSSIP_SELECT_OPTION"); @@ -170,7 +170,7 @@ void WorldSession::HandleGossipSelectOptionOpcode(WorldPacket & recvData) } } -void WorldSession::HandleWhoOpcode(WorldPacket & recvData) +void WorldSession::HandleWhoOpcode(WorldPacket& recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_WHO Message"); @@ -367,7 +367,7 @@ void WorldSession::HandleWhoOpcode(WorldPacket & recvData) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Send SMSG_WHO Message"); } -void WorldSession::HandleLogoutRequestOpcode(WorldPacket & /*recvData*/) +void WorldSession::HandleLogoutRequestOpcode(WorldPacket& /*recvData*/) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_LOGOUT_REQUEST Message, security - %u", GetSecurity()); @@ -420,12 +420,12 @@ void WorldSession::HandleLogoutRequestOpcode(WorldPacket & /*recvData*/) LogoutRequest(time(NULL)); } -void WorldSession::HandlePlayerLogoutOpcode(WorldPacket & /*recvData*/) +void WorldSession::HandlePlayerLogoutOpcode(WorldPacket& /*recvData*/) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_PLAYER_LOGOUT Message"); } -void WorldSession::HandleLogoutCancelOpcode(WorldPacket & /*recvData*/) +void WorldSession::HandleLogoutCancelOpcode(WorldPacket& /*recvData*/) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Recvd CMSG_LOGOUT_CANCEL Message"); @@ -485,7 +485,7 @@ void WorldSession::HandleTogglePvP(WorldPacket& recvData) // pvp->HandlePlayerActivityChanged(_player); } -void WorldSession::HandleZoneUpdateOpcode(WorldPacket & recvData) +void WorldSession::HandleZoneUpdateOpcode(WorldPacket& recvData) { uint32 newZone; recvData >> newZone; @@ -506,7 +506,7 @@ void WorldSession::HandleReturnToGraveyard(WorldPacket& /*recvPacket*/) GetPlayer()->RepopAtGraveyard(); } -void WorldSession::HandleSetSelectionOpcode(WorldPacket & recvData) +void WorldSession::HandleSetSelectionOpcode(WorldPacket& recvData) { uint64 guid; recvData >> guid; @@ -514,9 +514,9 @@ void WorldSession::HandleSetSelectionOpcode(WorldPacket & recvData) _player->SetSelection(guid); } -void WorldSession::HandleStandStateChangeOpcode(WorldPacket & recvData) +void WorldSession::HandleStandStateChangeOpcode(WorldPacket& recvData) { - // sLog->outDebug(LOG_FILTER_PACKETIO, "WORLD: Received CMSG_STANDSTATECHANGE"); -- too many spam in log at lags/debug stop + // sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_STANDSTATECHANGE"); -- too many spam in log at lags/debug stop uint32 animstate; recvData >> animstate; @@ -530,7 +530,7 @@ void WorldSession::HandleContactListOpcode(WorldPacket& recvData) _player->GetSocial()->SendSocialList(_player); } -void WorldSession::HandleAddFriendOpcode(WorldPacket & recvData) +void WorldSession::HandleAddFriendOpcode(WorldPacket& recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_ADD_FRIEND"); @@ -623,7 +623,7 @@ void WorldSession::HandleDelFriendOpcode(WorldPacket& recvData) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent motd (SMSG_FRIEND_STATUS)"); } -void WorldSession::HandleAddIgnoreOpcode(WorldPacket & recvData) +void WorldSession::HandleAddIgnoreOpcode(WorldPacket& recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_ADD_IGNORE"); @@ -681,7 +681,7 @@ void WorldSession::HandleAddIgnoreOpcodeCallBack(PreparedQueryResult result) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent (SMSG_FRIEND_STATUS)"); } -void WorldSession::HandleDelIgnoreOpcode(WorldPacket & recvData) +void WorldSession::HandleDelIgnoreOpcode(WorldPacket& recvData) { uint64 IgnoreGUID; @@ -705,7 +705,7 @@ void WorldSession::HandleSetContactNotesOpcode(WorldPacket& recvData) _player->GetSocial()->SetFriendNote(GUID_LOPART(guid), note); } -void WorldSession::HandleBugOpcode(WorldPacket & recvData) +void WorldSession::HandleBugOpcode(WorldPacket& recvData) { uint32 suggestion, contentlen, typelen; std::string content, type; @@ -938,7 +938,7 @@ void WorldSession::HandleAreaTriggerOpcode(WorldPacket& recvData) player->TeleportTo(at->target_mapId, at->target_X, at->target_Y, at->target_Z, at->target_Orientation, TELE_TO_NOT_LEAVE_TRANSPORT); } -void WorldSession::HandleUpdateAccountData(WorldPacket &recvData) +void WorldSession::HandleUpdateAccountData(WorldPacket& recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_UPDATE_ACCOUNT_DATA"); @@ -1084,12 +1084,12 @@ void WorldSession::HandleCompleteCinematic(WorldPacket& /*recvData*/) sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_COMPLETE_CINEMATIC"); } -void WorldSession::HandleNextCinematicCamera(WorldPacket & /*recvData*/) +void WorldSession::HandleNextCinematicCamera(WorldPacket& /*recvData*/) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_NEXT_CINEMATIC_CAMERA"); } -void WorldSession::HandleMoveTimeSkippedOpcode(WorldPacket & recvData) +void WorldSession::HandleMoveTimeSkippedOpcode(WorldPacket& recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_MOVE_TIME_SKIPPED"); @@ -1132,7 +1132,7 @@ void WorldSession::HandleMoveTimeSkippedOpcode(WorldPacket & recvData) */ } -void WorldSession::HandleFeatherFallAck(WorldPacket &recvData) +void WorldSession::HandleFeatherFallAck(WorldPacket& recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_MOVE_FEATHER_FALL_ACK"); @@ -1190,11 +1190,11 @@ void WorldSession::HandleMoveRootAck(WorldPacket& recvData) */ } -void WorldSession::HandleSetActionBarToggles(WorldPacket& recvPacket) +void WorldSession::HandleSetActionBarToggles(WorldPacket& recvData) { uint8 actionBar; - recvPacket >> actionBar; + recvData >> actionBar; if (!GetPlayer()) // ignore until not logged (check needed because STATUS_AUTHED) { @@ -1253,29 +1253,61 @@ void WorldSession::HandleInspectOpcode(WorldPacket& recvData) data << uint64(guild->GetGUID()); data << uint32(guild->GetLevel()); data << uint64(0/*guild->GetXP()*/); - data << uint32(0/*guild->GetMembersCount()*/); // number of members + data << uint32(guild->GetMembersCount()); } SendPacket(&data); } void WorldSession::HandleInspectHonorStatsOpcode(WorldPacket& recvData) { - uint64 guid; - recvData >> guid; + ObjectGuid guid; + guid[1] = recvData.ReadBit(); + guid[5] = recvData.ReadBit(); + guid[7] = recvData.ReadBit(); + guid[3] = recvData.ReadBit(); + guid[2] = recvData.ReadBit(); + guid[4] = recvData.ReadBit(); + guid[0] = recvData.ReadBit(); + guid[6] = recvData.ReadBit(); + recvData.ReadByteSeq(guid[4]); + recvData.ReadByteSeq(guid[7]); + recvData.ReadByteSeq(guid[0]); + recvData.ReadByteSeq(guid[5]); + recvData.ReadByteSeq(guid[1]); + recvData.ReadByteSeq(guid[6]); + recvData.ReadByteSeq(guid[2]); + recvData.ReadByteSeq(guid[3]); Player* player = ObjectAccessor::FindPlayer(guid); if (!player) { - sLog->outDebug(LOG_FILTER_NETWORKIO, "MSG_INSPECT_HONOR_STATS: No player found from GUID: " UI64FMTD, guid); + sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_INSPECT_HONOR_STATS: No player found from GUID: " UI64FMTD, guid); return; } - WorldPacket data(SMSG_INSPECT_HONOR_STATS, 4+1+4+8); - data << uint32(player->GetUInt32Value(PLAYER_FIELD_KILLS)); - data << uint8(0); // rank + ObjectGuid playerGuid = player->GetGUID(); + WorldPacket data(SMSG_INSPECT_HONOR_STATS, 8+1+4+4); + data.WriteBit(playerGuid[4]); + data.WriteBit(playerGuid[3]); + data.WriteBit(playerGuid[6]); + data.WriteBit(playerGuid[2]); + data.WriteBit(playerGuid[5]); + data.WriteBit(playerGuid[0]); + data.WriteBit(playerGuid[7]); + data.WriteBit(playerGuid[1]); + data << uint8(0); // rank + data << uint16(player->GetUInt16Value(PLAYER_FIELD_KILLS, 1)); // yesterday kills + data << uint16(player->GetUInt16Value(PLAYER_FIELD_KILLS, 0)); // today kills + data.WriteByteSeq(playerGuid[2]); + data.WriteByteSeq(playerGuid[0]); + data.WriteByteSeq(playerGuid[6]); + data.WriteByteSeq(playerGuid[3]); + data.WriteByteSeq(playerGuid[4]); + data.WriteByteSeq(playerGuid[1]); + data.WriteByteSeq(playerGuid[5]); data << uint32(player->GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS)); - data << uint64(player->GetGUID()); + data.WriteByteSeq(playerGuid[7]); SendPacket(&data); } @@ -1371,7 +1403,7 @@ void WorldSession::HandleWhoisOpcode(WorldPacket& recvData) sLog->outDebug(LOG_FILTER_NETWORKIO, "Received whois command from player %s for character %s", GetPlayer()->GetName(), charname.c_str()); } -void WorldSession::HandleComplainOpcode(WorldPacket & recvData) +void WorldSession::HandleComplainOpcode(WorldPacket& recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_COMPLAIN"); @@ -1412,7 +1444,7 @@ void WorldSession::HandleComplainOpcode(WorldPacket & recvData) sLog->outDebug(LOG_FILTER_NETWORKIO, "REPORT SPAM: type %u, guid %u, unk1 %u, unk2 %u, unk3 %u, unk4 %u, message %s", spam_type, GUID_LOPART(spammer_guid), unk1, unk2, unk3, unk4, description.c_str()); } -void WorldSession::HandleRealmSplitOpcode(WorldPacket & recvData) +void WorldSession::HandleRealmSplitOpcode(WorldPacket& recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "CMSG_REALM_SPLIT"); @@ -1512,7 +1544,7 @@ void WorldSession::HandleResetInstancesOpcode(WorldPacket& /*recvData*/) _player->ResetInstances(INSTANCE_RESET_ALL, false); } -void WorldSession::HandleSetDungeonDifficultyOpcode(WorldPacket & recvData) +void WorldSession::HandleSetDungeonDifficultyOpcode(WorldPacket& recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "MSG_SET_DUNGEON_DIFFICULTY"); @@ -1569,7 +1601,7 @@ void WorldSession::HandleSetDungeonDifficultyOpcode(WorldPacket & recvData) } } -void WorldSession::HandleSetRaidDifficultyOpcode(WorldPacket & recvData) +void WorldSession::HandleSetRaidDifficultyOpcode(WorldPacket& recvData) { sLog->outDebug(LOG_FILTER_NETWORKIO, "MSG_SET_RAID_DIFFICULTY"); @@ -1626,7 +1658,7 @@ void WorldSession::HandleSetRaidDifficultyOpcode(WorldPacket & recvData) } } -void WorldSession::HandleCancelMountAuraOpcode(WorldPacket & /*recvData*/) +void WorldSession::HandleCancelMountAuraOpcode(WorldPacket& /*recvData*/) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_CANCEL_MOUNT_AURA"); @@ -1647,7 +1679,7 @@ void WorldSession::HandleCancelMountAuraOpcode(WorldPacket & /*recvData*/) _player->RemoveAurasByType(SPELL_AURA_MOUNTED); } -void WorldSession::HandleMoveSetCanFlyAckOpcode(WorldPacket & recvData) +void WorldSession::HandleMoveSetCanFlyAckOpcode(WorldPacket& recvData) { // fly mode on/off sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_MOVE_SET_CAN_FLY_ACK"); @@ -1729,7 +1761,7 @@ void WorldSession::SendSetPhaseShift(uint32 PhaseShift) } // Battlefield and Battleground -void WorldSession::HandleAreaSpiritHealerQueryOpcode(WorldPacket & recv_data) +void WorldSession::HandleAreaSpiritHealerQueryOpcode(WorldPacket& recv_data) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_AREA_SPIRIT_HEALER_QUERY"); @@ -1752,7 +1784,7 @@ void WorldSession::HandleAreaSpiritHealerQueryOpcode(WorldPacket & recv_data) bf->SendAreaSpiritHealerQueryOpcode(_player,guid); } -void WorldSession::HandleAreaSpiritHealerQueueOpcode(WorldPacket & recv_data) +void WorldSession::HandleAreaSpiritHealerQueueOpcode(WorldPacket& recv_data) { sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: CMSG_AREA_SPIRIT_HEALER_QUEUE"); diff --git a/src/server/game/Handlers/NPCHandler.cpp b/src/server/game/Handlers/NPCHandler.cpp index 32636d51f49..554030270d9 100755 --- a/src/server/game/Handlers/NPCHandler.cpp +++ b/src/server/game/Handlers/NPCHandler.cpp @@ -236,13 +236,13 @@ void WorldSession::SendTrainerList(uint64 guid, const std::string& strTitle) SendPacket(&data); } -void WorldSession::HandleTrainerBuySpellOpcode(WorldPacket & recvData) +void WorldSession::HandleTrainerBuySpellOpcode(WorldPacket& recvData) { uint64 guid; - uint32 spellId = 0; - int32 unkInt; + uint32 spellId; + uint32 trainerId; - recvData >> guid >> unkInt >> spellId; + recvData >> guid >> trainerId >> spellId; sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_TRAINER_BUY_SPELL NpcGUID=%u, learn spell id is: %u", uint32(GUID_LOPART(guid)), spellId); Creature* unit = GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_TRAINER); @@ -257,33 +257,48 @@ void WorldSession::HandleTrainerBuySpellOpcode(WorldPacket & recvData) GetPlayer()->RemoveAurasByType(SPELL_AURA_FEIGN_DEATH); if (!unit->isCanTrainingOf(_player, true)) + { + SendTrainerBuyFailed(guid, spellId, 0); return; + } // check present spell in trainer spell list TrainerSpellData const* trainer_spells = unit->GetTrainerSpells(); if (!trainer_spells) + { + SendTrainerBuyFailed(guid, spellId, 0); return; + } // not found, cheat? TrainerSpell const* trainer_spell = trainer_spells->Find(spellId); if (!trainer_spell) + { + SendTrainerBuyFailed(guid, spellId, 0); return; + } // can't be learn, cheat? Or double learn with lags... if (_player->GetTrainerSpellState(trainer_spell) != TRAINER_SPELL_GREEN) + { + SendTrainerBuyFailed(guid, spellId, 0); return; + } // apply reputation discount uint32 nSpellCost = uint32(floor(trainer_spell->spellCost * _player->GetReputationPriceDiscount(unit))); // check money requirement if (!_player->HasEnoughMoney(uint64(nSpellCost))) + { + SendTrainerBuyFailed(guid, spellId, 1); return; + } _player->ModifyMoney(-int64(nSpellCost)); - unit->SendPlaySpellVisual(179); // 53 SpellCastDirected - unit->SendPlaySpellImpact(_player->GetGUID(), 362); // 113 EmoteSalute + unit->SendPlaySpellVisualKit(179, 0); // 53 SpellCastDirected + _player->SendPlaySpellVisualKit(362, 1); // 113 EmoteSalute // learn explicitly or cast explicitly if (trainer_spell->IsCastable()) @@ -293,8 +308,16 @@ void WorldSession::HandleTrainerBuySpellOpcode(WorldPacket & recvData) WorldPacket data(SMSG_TRAINER_BUY_SUCCEEDED, 12); data << uint64(guid); - data << uint32(spellId); // should be same as in packet from client - data << uint32(0); // "Trainer service", 1 = "Not enough money for trainer service <TS>". 0 = "Trainer service <TS> unavailable" + data << uint32(spellId); + SendPacket(&data); +} + +void WorldSession::SendTrainerBuyFailed(uint64 guid, uint32 spellId, uint32 reason) +{ + WorldPacket data(SMSG_TRAINER_BUY_FAILED, 16); + data << uint64(guid); + data << uint32(spellId); // should be same as in packet from client + data << uint32(reason); // 1 == "Not enough money for trainer service." 0 == "Trainer service %d unavailable." SendPacket(&data); } @@ -490,10 +513,9 @@ void WorldSession::SendBindPoint(Creature* npc) // send spell for homebinding (3286) npc->CastSpell(_player, bindspell, true); - WorldPacket data(SMSG_TRAINER_BUY_SUCCEEDED, (8+4)); + WorldPacket data(SMSG_TRAINER_BUY_SUCCEEDED, 12); data << uint64(npc->GetGUID()); data << uint32(bindspell); - data << uint32(0); // "Trainer service", 1 = "Not enough money for trainer service <TS>". 0 = "Trainer service <TS> unavailable" SendPacket(&data); _player->PlayerTalkClass->SendCloseGossip(); diff --git a/src/server/game/Handlers/SpellHandler.cpp b/src/server/game/Handlers/SpellHandler.cpp index 6aeb61b222b..de881e0608d 100755 --- a/src/server/game/Handlers/SpellHandler.cpp +++ b/src/server/game/Handlers/SpellHandler.cpp @@ -562,8 +562,8 @@ void WorldSession::HandleTotemDestroyed(WorldPacket& recvPacket) return; Creature* totem = GetPlayer()->GetMap()->GetCreature(_player->m_SummonSlot[slotId]); - // Don't unsummon sentry totem - if (totem && totem->isTotem() && totem->GetEntry() != SENTRY_TOTEM_ENTRY) + + if (totem && totem->isTotem()) totem->ToTotem()->UnSummon(); } diff --git a/src/server/game/Maps/Map.cpp b/src/server/game/Maps/Map.cpp index c1510bef543..6b115878135 100755 --- a/src/server/game/Maps/Map.cpp +++ b/src/server/game/Maps/Map.cpp @@ -2689,7 +2689,7 @@ uint32 InstanceMap::GetMaxResetDelay() const /* ******* Battleground Instance Maps ******* */ BattlegroundMap::BattlegroundMap(uint32 id, time_t expiry, uint32 InstanceId, Map* _parent, uint8 spawnMode) - : Map(id, expiry, InstanceId, spawnMode, _parent) + : Map(id, expiry, InstanceId, spawnMode, _parent), m_bg(NULL) { //lets initialize visibility distance for BG/Arenas BattlegroundMap::InitVisibilityDistance(); diff --git a/src/server/game/Movement/MovementGenerators/FleeingMovementGenerator.cpp b/src/server/game/Movement/MovementGenerators/FleeingMovementGenerator.cpp index 08e27abf050..7e130a2c143 100755 --- a/src/server/game/Movement/MovementGenerators/FleeingMovementGenerator.cpp +++ b/src/server/game/Movement/MovementGenerators/FleeingMovementGenerator.cpp @@ -407,10 +407,6 @@ bool TimedFleeingMovementGenerator::Update(Unit & owner, const uint32& time_diff if (i_totalFleeTime.Passed()) return false; - i_totalFleeTime.Update(time_diff); - if (i_totalFleeTime.Passed()) - return false; - // This calls grant-parent Update method hiden by FleeingMovementGenerator::Update(Creature &, const uint32 &) version // This is done instead of casting Unit& to Creature& and call parent method, then we can use Unit directly return MovementGeneratorMedium< Creature, FleeingMovementGenerator<Creature> >::Update(owner, time_diff); diff --git a/src/server/game/OutdoorPvP/OutdoorPvP.cpp b/src/server/game/OutdoorPvP/OutdoorPvP.cpp index 4db35d5bc79..5a4d5734929 100755 --- a/src/server/game/OutdoorPvP/OutdoorPvP.cpp +++ b/src/server/game/OutdoorPvP/OutdoorPvP.cpp @@ -29,8 +29,8 @@ #include "GridNotifiersImpl.h" #include "CellImpl.h" -OPvPCapturePoint::OPvPCapturePoint(OutdoorPvP* pvp): -m_capturePointGUID(0), m_capturePoint(NULL), m_maxValue(0), m_maxSpeed(0), +OPvPCapturePoint::OPvPCapturePoint(OutdoorPvP* pvp) : +m_capturePointGUID(0), m_capturePoint(NULL), m_minValue(0.0f), m_maxValue(0.0f), m_maxSpeed(0), m_value(0), m_team(TEAM_NEUTRAL), m_OldState(OBJECTIVESTATE_NEUTRAL), m_State(OBJECTIVESTATE_NEUTRAL), m_neutralValuePct(0), m_PvP(pvp) { diff --git a/src/server/game/OutdoorPvP/OutdoorPvP.h b/src/server/game/OutdoorPvP/OutdoorPvP.h index 6ea13d353c5..d2f1362dc82 100755 --- a/src/server/game/OutdoorPvP/OutdoorPvP.h +++ b/src/server/game/OutdoorPvP/OutdoorPvP.h @@ -31,10 +31,9 @@ enum OutdoorPvPTypes OUTDOOR_PVP_TF = 3, OUTDOOR_PVP_ZM = 4, OUTDOOR_PVP_SI = 5, - OUTDOOR_PVP_EP = 6, }; -#define MAX_OUTDOORPVP_TYPES 7 +#define MAX_OUTDOORPVP_TYPES 6 enum ObjectiveStates { diff --git a/src/server/game/Quests/QuestDef.cpp b/src/server/game/Quests/QuestDef.cpp index 2a16756161b..6aa9500b998 100755 --- a/src/server/game/Quests/QuestDef.cpp +++ b/src/server/game/Quests/QuestDef.cpp @@ -347,10 +347,11 @@ uint32 Quest::CalculateHonorGain(uint8 level) const /*if (GetRewHonorAddition() > 0 || GetRewHonorMultiplier() > 0.0f) { // values stored from 0.. for 1... - TeamContributionPointsEntry const* tc = sTeamContributionPointsStore.LookupEntry(level-1); + TeamContributionPointsEntry const* tc = sTeamContributionPointsStore.LookupEntry(level); if (!tc) return 0; - honor = uint32(tc->value * GetRewHonorMultiplier() * 0.1000000014901161); + + honor = uint32(tc->value * GetRewHonorMultiplier() * 0.1f); honor += GetRewHonorAddition(); }*/ diff --git a/src/server/game/Quests/QuestDef.h b/src/server/game/Quests/QuestDef.h index 2b4ad24e78f..53ba7ea0d09 100755 --- a/src/server/game/Quests/QuestDef.h +++ b/src/server/game/Quests/QuestDef.h @@ -213,7 +213,7 @@ class Quest int32 GetZoneOrSort() const { return ZoneOrSort; } uint32 GetMinLevel() const { return MinLevel; } uint32 GetMaxLevel() const { return MaxLevel; } - uint32 GetQuestLevel() const { return Level; } + int32 GetQuestLevel() const { return Level; } uint32 GetType() const { return Type; } uint32 GetRequiredClasses() const { return RequiredClasses; } uint32 GetRequiredRaces() const { return RequiredRaces; } diff --git a/src/server/game/Reputation/ReputationMgr.h b/src/server/game/Reputation/ReputationMgr.h index a073845ea73..f950cbb82c2 100755 --- a/src/server/game/Reputation/ReputationMgr.h +++ b/src/server/game/Reputation/ReputationMgr.h @@ -65,7 +65,7 @@ class ReputationMgr { public: // constructors and global modifiers explicit ReputationMgr(Player* owner) : _player(owner), - _visibleFactionCount(0), _honoredFactionCount(0), _reveredFactionCount(0), _exaltedFactionCount(0) {} + _visibleFactionCount(0), _honoredFactionCount(0), _reveredFactionCount(0), _exaltedFactionCount(0), _sendFactionIncreased(false) {} ~ReputationMgr() {} void SaveToDB(SQLTransaction& trans); diff --git a/src/server/game/Scripting/ScriptLoader.cpp b/src/server/game/Scripting/ScriptLoader.cpp index 5e6caec1f29..ac0d9466736 100755 --- a/src/server/game/Scripting/ScriptLoader.cpp +++ b/src/server/game/Scripting/ScriptLoader.cpp @@ -50,6 +50,7 @@ void AddSC_ban_commandscript(); void AddSC_bf_commandscript(); void AddSC_cast_commandscript(); void AddSC_character_commandscript(); +void AddSC_cheat_commandscript(); void AddSC_debug_commandscript(); void AddSC_disable_commandscript(); void AddSC_event_commandscript(); @@ -318,6 +319,7 @@ void AddSC_bug_trio(); void AddSC_boss_sartura(); void AddSC_boss_skeram(); void AddSC_boss_twinemperors(); +void AddSC_boss_ouro(); void AddSC_mob_anubisath_sentinel(); void AddSC_instance_temple_of_ahnqiraj(); void AddSC_wailing_caverns(); //Wailing caverns @@ -593,7 +595,6 @@ void AddSC_zangarmarsh(); // battlegrounds // outdoor pvp -void AddSC_outdoorpvp_ep(); void AddSC_outdoorpvp_hp(); void AddSC_outdoorpvp_na(); void AddSC_outdoorpvp_si(); @@ -659,6 +660,7 @@ void AddCommandScripts() AddSC_bf_commandscript(); AddSC_cast_commandscript(); AddSC_character_commandscript(); + AddSC_cheat_commandscript(); AddSC_debug_commandscript(); AddSC_disable_commandscript(); AddSC_event_commandscript(); @@ -939,6 +941,7 @@ void AddKalimdorScripts() AddSC_boss_sartura(); AddSC_boss_skeram(); AddSC_boss_twinemperors(); + AddSC_boss_ouro(); AddSC_mob_anubisath_sentinel(); AddSC_instance_temple_of_ahnqiraj(); AddSC_wailing_caverns(); //Wailing caverns @@ -1224,7 +1227,6 @@ void AddNorthrendScripts() void AddOutdoorPvPScripts() { #ifdef SCRIPTS - AddSC_outdoorpvp_ep(); AddSC_outdoorpvp_hp(); AddSC_outdoorpvp_na(); AddSC_outdoorpvp_si(); diff --git a/src/server/game/Server/Protocol/Opcodes.cpp b/src/server/game/Server/Protocol/Opcodes.cpp index a3c807c09c8..6eeb3661028 100644 --- a/src/server/game/Server/Protocol/Opcodes.cpp +++ b/src/server/game/Server/Protocol/Opcodes.cpp @@ -99,16 +99,16 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(CMSG_AUTOSTORE_LOOT_ITEM, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleAutostoreLootItemOpcode ); DEFINE_OPCODE_HANDLER(CMSG_AUTO_DECLINE_GUILD_INVITES, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); DEFINE_OPCODE_HANDLER(CMSG_BANKER_ACTIVATE, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleBankerActivateOpcode ); - DEFINE_OPCODE_HANDLER(CMSG_BATTLEFIELD_LEAVE, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); + DEFINE_OPCODE_HANDLER(CMSG_BATTLEFIELD_LEAVE, STATUS_LOGGEDIN, PROCESS_INPLACE, &WorldSession::HandleBattlefieldLeaveOpcode ); DEFINE_OPCODE_HANDLER(CMSG_BATTLEFIELD_LIST, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleBattlefieldListOpcode ); - DEFINE_OPCODE_HANDLER(CMSG_BATTLEFIELD_MGR_ENTRY_INVITE_RESPONSE, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); - DEFINE_OPCODE_HANDLER(CMSG_BATTLEFIELD_MGR_EXIT_REQUEST, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); - DEFINE_OPCODE_HANDLER(CMSG_BATTLEFIELD_MGR_QUEUE_INVITE_RESPONSE, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); + DEFINE_OPCODE_HANDLER(CMSG_BATTLEFIELD_MGR_ENTRY_INVITE_RESPONSE, STATUS_LOGGEDIN, PROCESS_INPLACE, &WorldSession::HandleBfEntryInviteResponse ); + DEFINE_OPCODE_HANDLER(CMSG_BATTLEFIELD_MGR_EXIT_REQUEST, STATUS_LOGGEDIN, PROCESS_INPLACE, &WorldSession::HandleBfExitRequest ); + DEFINE_OPCODE_HANDLER(CMSG_BATTLEFIELD_MGR_QUEUE_INVITE_RESPONSE, STATUS_LOGGEDIN, PROCESS_INPLACE, &WorldSession::HandleBfQueueInviteResponse ); DEFINE_OPCODE_HANDLER(CMSG_BATTLEFIELD_MGR_QUEUE_REQUEST, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); - DEFINE_OPCODE_HANDLER(CMSG_BATTLEFIELD_PORT, STATUS_UNHANDLED, PROCESS_THREADUNSAFE, &WorldSession::HandleBattleFieldPortOpcode ); + DEFINE_OPCODE_HANDLER(CMSG_BATTLEFIELD_PORT, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleBattleFieldPortOpcode ); DEFINE_OPCODE_HANDLER(CMSG_BATTLEFIELD_STATUS, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleBattlefieldStatusOpcode ); - DEFINE_OPCODE_HANDLER(CMSG_BATTLEGROUND_PLAYER_POSITIONS, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); - DEFINE_OPCODE_HANDLER(CMSG_BATTLEMASTER_JOIN, STATUS_UNHANDLED, PROCESS_THREADUNSAFE, &WorldSession::HandleBattlemasterJoinOpcode ); + DEFINE_OPCODE_HANDLER(CMSG_BATTLEGROUND_PLAYER_POSITIONS, STATUS_LOGGEDIN, PROCESS_INPLACE, &WorldSession::HandleBattlegroundPlayerPositionsOpcode); + DEFINE_OPCODE_HANDLER(CMSG_BATTLEMASTER_JOIN, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleBattlemasterJoinOpcode ); DEFINE_OPCODE_HANDLER(CMSG_BATTLEMASTER_JOIN_ARENA, STATUS_UNHANDLED, PROCESS_THREADUNSAFE, &WorldSession::HandleBattlemasterJoinArena ); DEFINE_OPCODE_HANDLER(CMSG_BATTLEMASTER_JOIN_RATED, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); DEFINE_OPCODE_HANDLER(CMSG_BEGIN_TRADE, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleBeginTradeOpcode ); @@ -236,10 +236,10 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(CMSG_GROUP_DISBAND, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGroupDisbandOpcode ); DEFINE_OPCODE_HANDLER(CMSG_GROUP_INVITE, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGroupInviteOpcode ); DEFINE_OPCODE_HANDLER(CMSG_GROUP_INVITE_RESPONSE, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGroupInviteResponseOpcode ); - DEFINE_OPCODE_HANDLER(CMSG_GROUP_RAID_CONVERT, STATUS_UNHANDLED, PROCESS_THREADUNSAFE, &WorldSession::HandleGroupRaidConvertOpcode ); + DEFINE_OPCODE_HANDLER(CMSG_GROUP_RAID_CONVERT, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGroupRaidConvertOpcode ); DEFINE_OPCODE_HANDLER(CMSG_GROUP_REQUEST_JOIN_UPDATES, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); DEFINE_OPCODE_HANDLER(CMSG_GROUP_SET_LEADER, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGroupSetLeaderOpcode ); - DEFINE_OPCODE_HANDLER(CMSG_GROUP_SET_ROLES, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); + DEFINE_OPCODE_HANDLER(CMSG_GROUP_SET_ROLES, STATUS_LOGGEDIN, PROCESS_INPLACE, &WorldSession::HandleGroupSetRolesOpcode ); DEFINE_OPCODE_HANDLER(CMSG_GROUP_SWAP_SUB_GROUP, STATUS_UNHANDLED, PROCESS_THREADUNSAFE, &WorldSession::HandleGroupSwapSubGroupOpcode ); DEFINE_OPCODE_HANDLER(CMSG_GROUP_UNINVITE_GUID, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGroupUninviteGuidOpcode ); DEFINE_OPCODE_HANDLER(CMSG_GUILD_ACCEPT, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGuildAcceptOpcode ); @@ -250,11 +250,10 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(CMSG_GUILD_BANKER_ACTIVATE, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGuildBankerActivate ); DEFINE_OPCODE_HANDLER(CMSG_GUILD_BANK_BUY_TAB, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGuildBankBuyTab ); DEFINE_OPCODE_HANDLER(CMSG_GUILD_BANK_DEPOSIT_MONEY, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGuildBankDepositMoney ); - DEFINE_OPCODE_HANDLER(CMSG_GUILD_BANK_LOG_QUERY, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); + DEFINE_OPCODE_HANDLER(CMSG_GUILD_BANK_LOG_QUERY, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGuildBankLogQuery ); DEFINE_OPCODE_HANDLER(CMSG_GUILD_BANK_MONEY_WITHDRAWN_QUERY, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGuildBankMoneyWithdrawn ); DEFINE_OPCODE_HANDLER(CMSG_GUILD_BANK_QUERY_TAB, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGuildBankQueryTab ); - DEFINE_OPCODE_HANDLER(CMSG_GUILD_BANK_QUERY_TEXT, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); - DEFINE_OPCODE_HANDLER(CMSG_GUILD_BANK_SET_TAB_TEXT, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); + DEFINE_OPCODE_HANDLER(CMSG_GUILD_BANK_QUERY_TEXT, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleQueryGuildBankTabText ); DEFINE_OPCODE_HANDLER(CMSG_GUILD_BANK_SWAP_ITEMS, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGuildBankSwapItems ); DEFINE_OPCODE_HANDLER(CMSG_GUILD_BANK_UPDATE_TAB, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGuildBankUpdateTab ); DEFINE_OPCODE_HANDLER(CMSG_GUILD_BANK_WITHDRAW_MONEY, STATUS_UNHANDLED, PROCESS_THREADUNSAFE, &WorldSession::HandleGuildBankWithdrawMoney ); @@ -263,7 +262,7 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(CMSG_GUILD_DEL_RANK, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGuildDelRankOpcode ); DEFINE_OPCODE_HANDLER(CMSG_GUILD_DEMOTE, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGuildDemoteOpcode ); DEFINE_OPCODE_HANDLER(CMSG_GUILD_DISBAND, STATUS_UNHANDLED, PROCESS_THREADUNSAFE, &WorldSession::HandleGuildDisbandOpcode ); - DEFINE_OPCODE_HANDLER(CMSG_GUILD_EVENT_LOG_QUERY, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); + DEFINE_OPCODE_HANDLER(CMSG_GUILD_EVENT_LOG_QUERY, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGuildEventLogQueryOpcode ); DEFINE_OPCODE_HANDLER(CMSG_GUILD_INFO_TEXT, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGuildChangeInfoTextOpcode ); DEFINE_OPCODE_HANDLER(CMSG_GUILD_INVITE, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGuildInviteOpcode ); DEFINE_OPCODE_HANDLER(CMSG_GUILD_LEAVE, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGuildLeaveOpcode ); @@ -290,6 +289,7 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(CMSG_IGNORE_TRADE, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleIgnoreTradeOpcode ); DEFINE_OPCODE_HANDLER(CMSG_INITIATE_TRADE, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleInitiateTradeOpcode ); DEFINE_OPCODE_HANDLER(CMSG_INSPECT, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleInspectOpcode ); + DEFINE_OPCODE_HANDLER(CMSG_INSPECT_HONOR_STATS, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleInspectHonorStatsOpcode ); DEFINE_OPCODE_HANDLER(CMSG_INSTANCE_LOCK_WARNING_RESPONSE, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); DEFINE_OPCODE_HANDLER(CMSG_ITEM_REFUND, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleItemRefund ); DEFINE_OPCODE_HANDLER(CMSG_ITEM_REFUND_INFO, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleItemRefundInfoRequest ); @@ -414,7 +414,7 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(CMSG_PLAYER_VEHICLE_ENTER, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleEnterPlayerVehicle ); DEFINE_OPCODE_HANDLER(CMSG_PLAY_DANCE, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); DEFINE_OPCODE_HANDLER(CMSG_PUSHQUESTTOPARTY, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandlePushQuestToParty ); - DEFINE_OPCODE_HANDLER(CMSG_PVP_LOG_DATA, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); + DEFINE_OPCODE_HANDLER(CMSG_PVP_LOG_DATA, STATUS_LOGGEDIN, PROCESS_INPLACE, &WorldSession::HandlePVPLogDataOpcode ); DEFINE_OPCODE_HANDLER(CMSG_QUERY_BATTLEFIELD_STATE, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); DEFINE_OPCODE_HANDLER(CMSG_QUERY_GUILD_MEMBERS_FOR_RECIPE, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); DEFINE_OPCODE_HANDLER(CMSG_QUERY_GUILD_MEMBER_RECIPES, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); @@ -451,10 +451,9 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(CMSG_REQUEST_ACCOUNT_DATA, STATUS_AUTHED, PROCESS_THREADUNSAFE, &WorldSession::HandleRequestAccountData ); DEFINE_OPCODE_HANDLER(CMSG_REQUEST_CATEGORY_COOLDOWNS, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); DEFINE_OPCODE_HANDLER(CMSG_REQUEST_CEMETERY_LIST, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); - DEFINE_OPCODE_HANDLER(CMSG_REQUEST_HONOR_STATS, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); DEFINE_OPCODE_HANDLER(CMSG_REQUEST_HOTFIX, STATUS_AUTHED, PROCESS_INPLACE, &WorldSession::HandleRequestHotfix ); DEFINE_OPCODE_HANDLER(CMSG_REQUEST_INSPECT_RATED_BG_STATS, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); - DEFINE_OPCODE_HANDLER(CMSG_REQUEST_PARTY_MEMBER_STATS, STATUS_UNHANDLED, PROCESS_THREADUNSAFE, &WorldSession::HandleRequestPartyMemberStatsOpcode); + DEFINE_OPCODE_HANDLER(CMSG_REQUEST_PARTY_MEMBER_STATS, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleRequestPartyMemberStatsOpcode); DEFINE_OPCODE_HANDLER(CMSG_REQUEST_PET_INFO, STATUS_UNHANDLED, PROCESS_THREADUNSAFE, &WorldSession::HandleRequestPetInfoOpcode ); DEFINE_OPCODE_HANDLER(CMSG_REQUEST_PVP_OPTIONS_ENABLED, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); DEFINE_OPCODE_HANDLER(CMSG_REQUEST_PVP_REWARDS, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); @@ -490,6 +489,7 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(CMSG_SET_EVERYONE_IS_ASSISTANT, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); DEFINE_OPCODE_HANDLER(CMSG_SET_FACTION_ATWAR, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleSetFactionAtWar ); DEFINE_OPCODE_HANDLER(CMSG_SET_FACTION_INACTIVE, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleSetFactionInactiveOpcode ); + DEFINE_OPCODE_HANDLER(CMSG_SET_GUILD_BANK_TEXT, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleSetGuildBankTabText ); DEFINE_OPCODE_HANDLER(CMSG_SET_PET_SLOT, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); DEFINE_OPCODE_HANDLER(CMSG_SET_PLAYER_DECLINED_NAMES, STATUS_AUTHED, PROCESS_THREADUNSAFE, &WorldSession::HandleSetPlayerDeclinedNames ); DEFINE_OPCODE_HANDLER(CMSG_SET_PREFERED_CEMETERY, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); @@ -541,8 +541,8 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(CMSG_UNLEARN_SPECIALIZATION, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); DEFINE_OPCODE_HANDLER(CMSG_UNREGISTER_ALL_ADDON_PREFIXES, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleUnregisterAddonPrefixesOpcode); DEFINE_OPCODE_HANDLER(CMSG_UPDATE_ACCOUNT_DATA, STATUS_AUTHED, PROCESS_THREADUNSAFE, &WorldSession::HandleUpdateAccountData ); - DEFINE_OPCODE_HANDLER(CMSG_UPDATE_MISSILE_TRAJECTORY, STATUS_UNHANDLED, PROCESS_THREADUNSAFE, &WorldSession::HandleUpdateMissileTrajectory ); - DEFINE_OPCODE_HANDLER(CMSG_UPDATE_PROJECTILE_POSITION, STATUS_UNHANDLED, PROCESS_THREADUNSAFE, &WorldSession::HandleUpdateProjectilePosition ); + DEFINE_OPCODE_HANDLER(CMSG_UPDATE_MISSILE_TRAJECTORY, STATUS_UNHANDLED, PROCESS_THREADUNSAFE, &WorldSession::HandleUpdateMissileTrajectory ); + DEFINE_OPCODE_HANDLER(CMSG_UPDATE_PROJECTILE_POSITION, STATUS_UNHANDLED, PROCESS_THREADUNSAFE, &WorldSession::HandleUpdateProjectilePosition ); DEFINE_OPCODE_HANDLER(CMSG_USED_FOLLOW, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); DEFINE_OPCODE_HANDLER(CMSG_USE_ITEM, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleUseItemOpcode ); DEFINE_OPCODE_HANDLER(CMSG_VIOLENCE_LEVEL, STATUS_AUTHED, PROCESS_INPLACE, &WorldSession::HandleViolenceLevel ); @@ -561,8 +561,8 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(CMSG_WRAP_ITEM, STATUS_UNHANDLED, PROCESS_THREADUNSAFE, &WorldSession::HandleWrapItemOpcode ); DEFINE_OPCODE_HANDLER(CMSG_ZONEUPDATE, STATUS_LOGGEDIN, PROCESS_THREADSAFE, &WorldSession::HandleZoneUpdateOpcode ); DEFINE_OPCODE_HANDLER(MSG_AUCTION_HELLO, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleAuctionHelloOpcode ); - DEFINE_OPCODE_HANDLER(MSG_CHANNEL_START, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); - DEFINE_OPCODE_HANDLER(MSG_CHANNEL_UPDATE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); + DEFINE_OPCODE_HANDLER(MSG_CHANNEL_START, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(MSG_CHANNEL_UPDATE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(MSG_CORPSE_QUERY, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleCorpseQueryOpcode ); DEFINE_OPCODE_HANDLER(MSG_INSPECT_ARENA_TEAMS, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleInspectArenaTeamsOpcode ); DEFINE_OPCODE_HANDLER(MSG_LIST_STABLED_PETS, STATUS_UNHANDLED, PROCESS_THREADUNSAFE, &WorldSession::HandleListStabledPetsOpcode ); @@ -592,7 +592,7 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(MSG_MOVE_STOP_STRAFE, STATUS_LOGGEDIN, PROCESS_THREADSAFE, &WorldSession::HandleMovementOpcodes ); DEFINE_OPCODE_HANDLER(MSG_MOVE_STOP_SWIM, STATUS_LOGGEDIN, PROCESS_THREADSAFE, &WorldSession::HandleMovementOpcodes ); DEFINE_OPCODE_HANDLER(MSG_MOVE_STOP_TURN, STATUS_LOGGEDIN, PROCESS_THREADSAFE, &WorldSession::HandleMovementOpcodes ); - DEFINE_OPCODE_HANDLER(MSG_MOVE_TELEPORT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); + DEFINE_OPCODE_HANDLER(MSG_MOVE_TELEPORT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(MSG_MOVE_TELEPORT_ACK, STATUS_LOGGEDIN, PROCESS_THREADSAFE, &WorldSession::HandleMoveTeleportAck ); DEFINE_OPCODE_HANDLER(MSG_MOVE_TELEPORT_CHEAT, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); DEFINE_OPCODE_HANDLER(MSG_MOVE_TIME_SKIPPED, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); @@ -608,7 +608,7 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(MSG_QUERY_NEXT_MAIL_TIME, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleQueryNextMailTime ); DEFINE_OPCODE_HANDLER(MSG_QUEST_PUSH_RESULT, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleQuestPushResult ); DEFINE_OPCODE_HANDLER(MSG_RAID_READY_CHECK, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleRaidReadyCheckOpcode ); - DEFINE_OPCODE_HANDLER(MSG_RAID_READY_CHECK_CONFIRM, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_NULL ); + DEFINE_OPCODE_HANDLER(MSG_RAID_READY_CHECK_CONFIRM, STATUS_LOGGEDIN, PROCESS_INPLACE, &WorldSession::Handle_NULL ); DEFINE_OPCODE_HANDLER(MSG_RAID_READY_CHECK_FINISHED, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleRaidReadyCheckFinishedOpcode); DEFINE_OPCODE_HANDLER(MSG_RAID_TARGET_UPDATE, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleRaidTargetUpdateOpcode ); DEFINE_OPCODE_HANDLER(MSG_RANDOM_ROLL, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleRandomRollOpcode ); @@ -664,26 +664,27 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(SMSG_AVAILABLE_VOICE_CHANNEL, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_AVERAGE_ITEM_LEVEL_INFORM, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_BARBER_SHOP_RESULT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_LIST, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_MGR_EJECTED, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_LIST, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_MGR_EJECTED, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_MGR_EJECT_PENDING, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_MGR_ENTERED, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_MGR_ENTRY_INVITE, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_MGR_ENTERED, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_MGR_ENTRY_INVITE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_MGR_EXIT_REQUEST, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_MGR_QUEUE_INVITE, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_MGR_QUEUE_REQUEST_RESPONSE, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_MGR_QUEUE_INVITE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_MGR_QUEUE_REQUEST_RESPONSE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_MGR_STATE_CHANGE, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_PLAYER_POSITIONS, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_PLAYER_POSITIONS, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_PORT_DENIED, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_RATED_INFO, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_STATUS, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_STATUS2, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_STATUS3, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_STATUS4, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_STATUS_FAILED, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_STATUS_QUEUED, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_STATUS_ACTIVE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_STATUS_NEEDCONFIRMATION, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_STATUS_WAITFORGROUPS, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_STATUS_FAILED, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_BATTLEGROUND_INFO_THROTTLED, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_BATTLEGROUND_PLAYER_JOINED, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_BATTLEGROUND_PLAYER_LEFT, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_BATTLEGROUND_PLAYER_JOINED, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_BATTLEGROUND_PLAYER_LEFT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_BINDER_CONFIRM, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_BINDPOINTUPDATE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_BREAK_TARGET, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); @@ -838,21 +839,20 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(SMSG_GROUPACTION_THROTTLED, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_GROUP_CANCEL, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_GROUP_DECLINE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_GROUP_DESTROYED, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_GROUP_DESTROYED, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_GROUP_INVITE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_GROUP_JOINED_BATTLEGROUND, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_GROUP_LIST, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_GROUP_LIST, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_GROUP_SET_LEADER, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_GROUP_SET_ROLE, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_GROUP_UNINVITE, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_GROUP_SET_ROLE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_GROUP_UNINVITE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_GUILD_ACHIEVEMENT_DATA, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_GUILD_ACHIEVEMENT_DELETED, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_GUILD_ACHIEVEMENT_EARNED, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_GUILD_ACHIEVEMENT_MEMBERS, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_GUILD_BANK_LIST, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_GUILD_BANK_LOG_QUERY_RESULTS, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_GUILD_BANK_LOG_QUERY_RESULT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_GUILD_BANK_MONEY_WITHDRAWN, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_GUILD_BANK_QUERY_TEXT_RESULTS, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_GUILD_BANK_QUERY_TEXT_RESULT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_GUILD_CHALLENGE_COMPLETED, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_GUILD_CHALLENGE_UPDATED, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_GUILD_CHANGE_NAME_RESULT, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); @@ -862,7 +862,7 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(SMSG_GUILD_CRITERIA_DELETED, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_GUILD_DECLINE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_GUILD_EVENT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_GUILD_EVENT_LOG_QUERY, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_GUILD_EVENT_LOG_QUERY_RESULT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_GUILD_FLAGGED_FOR_RENAME, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_GUILD_INVITE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_GUILD_INVITE_CANCEL, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); @@ -898,7 +898,7 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(SMSG_INITIAL_SPELLS, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_INIT_CURRENCY, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_INIT_WORLD_STATES, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_INSPECT_HONOR_STATS, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_INSPECT_HONOR_STATS, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_INSPECT_RATED_BG_STATS, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_INSPECT_RESULTS_UPDATE, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_INSPECT_TALENT, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); @@ -1041,8 +1041,8 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(SMSG_PAGE_TEXT_QUERY_RESPONSE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_PARTYKILLLOG, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_PARTY_COMMAND_RESULT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_PARTY_MEMBER_STATS, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_PARTY_MEMBER_STATS_FULL, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_PARTY_MEMBER_STATS, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_PARTY_MEMBER_STATS_FULL, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_PAUSE_MIRROR_TIMER, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_PERIODICAURALOG, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_PETGODMODE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); @@ -1079,8 +1079,8 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(SMSG_PLAY_MUSIC, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_PLAY_OBJECT_SOUND, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_PLAY_SOUND, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_PLAY_SPELL_VISUAL, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_PLAY_SPELL_VISUAL_KIT, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_PLAY_SPELL_VISUAL, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_PLAY_SPELL_VISUAL_KIT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_PLAY_TIME_WARNING, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_PONG, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_POWER_UPDATE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); @@ -1088,7 +1088,7 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(SMSG_PROCRESIST, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_PROPOSE_LEVEL_GRANT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_PVP_CREDIT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_PVP_LOG_DATA, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_PVP_LOG_DATA, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_PVP_OPTIONS_ENABLED, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_QUERY_QUESTS_COMPLETED_RESPONSE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_QUERY_TIME_RESPONSE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); @@ -1112,7 +1112,7 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(SMSG_QUEST_NPC_QUERY_RESPONSE, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_QUEST_POI_QUERY_RESPONSE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_QUEST_QUERY_RESPONSE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_RAID_GROUP_ONLY, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_RAID_GROUP_ONLY, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_RAID_INSTANCE_INFO, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_RAID_INSTANCE_MESSAGE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_RAID_MARKERS_CHANGED, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); @@ -1244,8 +1244,8 @@ void InitOpcodes() DEFINE_OPCODE_HANDLER(SMSG_TOTEM_CREATED, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_TRADE_STATUS, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_TRADE_STATUS_EXTENDED, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_TRAINER_BUY_FAILED, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - DEFINE_OPCODE_HANDLER(SMSG_TRAINER_BUY_SUCCEEDED, STATUS_UNHANDLED, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_TRAINER_BUY_FAILED, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + DEFINE_OPCODE_HANDLER(SMSG_TRAINER_BUY_SUCCEEDED, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_TRAINER_LIST, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_TRANSFER_ABORTED, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); DEFINE_OPCODE_HANDLER(SMSG_TRANSFER_PENDING, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); @@ -1422,7 +1422,6 @@ void InitOpcodes() //DEFINE_OPCODE_HANDLER(CMSG_INSTANCE_LOCK_RESPONSE, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleInstanceLockResponse ); //DEFINE_OPCODE_HANDLER(CMSG_LEARN_DANCE_MOVE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); //DEFINE_OPCODE_HANDLER(CMSG_LEARN_SPELL, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); - //DEFINE_OPCODE_HANDLER(CMSG_LEAVE_BATTLEFIELD, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleLeaveBattlefieldOpcode ); //DEFINE_OPCODE_HANDLER(CMSG_LEVEL_CHEAT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); //DEFINE_OPCODE_HANDLER(CMSG_LFD_PARTY_LOCK_INFO_REQUEST, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleLfgPartyLockInfoRequestOpcode); //DEFINE_OPCODE_HANDLER(CMSG_LFD_PLAYER_LOCK_INFO_REQUEST, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleLfgPlayerLockInfoRequestOpcode); @@ -1507,7 +1506,6 @@ void InitOpcodes() //DEFINE_OPCODE_HANDLER(CMSG_SET_GLYPH, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); //DEFINE_OPCODE_HANDLER(CMSG_SET_GLYPH_SLOT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); //DEFINE_OPCODE_HANDLER(CMSG_SET_GRANTABLE_LEVELS, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); - //DEFINE_OPCODE_HANDLER(CMSG_SET_GUILD_BANK_TEXT, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleSetGuildBankTabText ); //DEFINE_OPCODE_HANDLER(CMSG_SET_LFG_COMMENT, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleLfgSetCommentOpcode ); //DEFINE_OPCODE_HANDLER(CMSG_SET_PAID_SERVICE_CHEAT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); //DEFINE_OPCODE_HANDLER(CMSG_SET_PVP_RANK_CHEAT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); @@ -1551,7 +1549,6 @@ void InitOpcodes() //DEFINE_OPCODE_HANDLER(CMSG_WEATHER_SPEED_CHEAT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); //DEFINE_OPCODE_HANDLER(CMSG_XP_CHEAT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); //DEFINE_OPCODE_HANDLER(CMSG_ZONE_MAP, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); - //DEFINE_OPCODE_HANDLER(MSG_BATTLEGROUND_PLAYER_POSITIONS, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleBattlegroundPlayerPositionsOpcode); //DEFINE_OPCODE_HANDLER(MSG_DELAY_GHOST_TELEPORT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); //DEFINE_OPCODE_HANDLER(MSG_DEV_SHOWLABEL, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); //DEFINE_OPCODE_HANDLER(MSG_GM_ACCOUNT_ONLINE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); @@ -1562,9 +1559,6 @@ void InitOpcodes() //DEFINE_OPCODE_HANDLER(MSG_GM_RESETINSTANCELIMIT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); //DEFINE_OPCODE_HANDLER(MSG_GM_SHOWLABEL, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); //DEFINE_OPCODE_HANDLER(MSG_GM_SUMMON, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); - //DEFINE_OPCODE_HANDLER(MSG_GUILD_BANK_LOG_QUERY, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGuildBankLogQuery ); - //DEFINE_OPCODE_HANDLER(MSG_GUILD_EVENT_LOG_QUERY, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleGuildEventLogQueryOpcode ); - //DEFINE_OPCODE_HANDLER(MSG_INSPECT_HONOR_STATS, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleInspectHonorStatsOpcode ); //DEFINE_OPCODE_HANDLER(MSG_MOVE_FEATHER_FALL, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); //DEFINE_OPCODE_HANDLER(MSG_MOVE_GRAVITY_CHNG, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); //DEFINE_OPCODE_HANDLER(MSG_MOVE_HOVER, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); @@ -1592,13 +1586,9 @@ void InitOpcodes() //DEFINE_OPCODE_HANDLER(MSG_MOVE_WATER_WALK, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); //DEFINE_OPCODE_HANDLER(MSG_NULL_ACTION, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); //DEFINE_OPCODE_HANDLER(MSG_PVP_LOG_DATA, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandlePVPLogDataOpcode ); - //DEFINE_OPCODE_HANDLER(MSG_QUERY_GUILD_BANK_TEXT, STATUS_LOGGEDIN, PROCESS_THREADUNSAFE, &WorldSession::HandleQueryGuildBankTabText ); - //DEFINE_OPCODE_HANDLER(MSG_START_MOVE_FORWARD, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); //DEFINE_OPCODE_HANDLER(MSG_VIEW_PHASE_SHIFT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_NULL ); //DEFINE_OPCODE_HANDLER(SMSG_AFK_MONITOR_INFO_RESPONSE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); //DEFINE_OPCODE_HANDLER(SMSG_AURACASTLOG, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - //DEFINE_OPCODE_HANDLER(SMSG_BATTLEFIELD_STATUS1, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - //DEFINE_OPCODE_HANDLER(SMSG_BATTLEGROUND_PLAYER_POSITIONS, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); //DEFINE_OPCODE_HANDLER(SMSG_BINDZONEREPLY, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); //DEFINE_OPCODE_HANDLER(SMSG_BUY_BANK_SLOT_RESULT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); //DEFINE_OPCODE_HANDLER(SMSG_CALENDAR_ACTION_PENDING, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); @@ -1672,7 +1662,6 @@ void InitOpcodes() //DEFINE_OPCODE_HANDLER(SMSG_NPC_WONT_TALK, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); //DEFINE_OPCODE_HANDLER(SMSG_PET_UNLEARN_CONFIRM, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); //DEFINE_OPCODE_HANDLER(SMSG_PLAYER_UNK_DEAD_ALIVE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - //DEFINE_OPCODE_HANDLER(SMSG_PLAY_SPELL_IMPACT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); //DEFINE_OPCODE_HANDLER(SMSG_PROFILEDATA_RESPONSE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); //DEFINE_OPCODE_HANDLER(SMSG_PUREMOUNT_CANCELLED_OBSOLETE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); //DEFINE_OPCODE_HANDLER(SMSG_PVP_QUEUE_STATS, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); @@ -1690,7 +1679,7 @@ void InitOpcodes() //DEFINE_OPCODE_HANDLER(SMSG_SERVER_BUCK_DATA, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); //DEFINE_OPCODE_HANDLER(SMSG_SERVER_BUCK_DATA_START, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); //DEFINE_OPCODE_HANDLER(SMSG_SETUP_RESEARCH_HISTORY, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - //DEFINE_OPCODE_HANDLER(SMSG_SET_EXTRA_AURA_INFO_NEED_UPDATE_OBSOLETE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); + //DEFINE_OPCODE_HANDLER(SMSG_SET_EXTRA_AURA_INFO_NEED_UPDATE_OBSOLETE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); //DEFINE_OPCODE_HANDLER(SMSG_SET_EXTRA_AURA_INFO_OBSOLETE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); //DEFINE_OPCODE_HANDLER(SMSG_SHOW_MAILBOX, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); //DEFINE_OPCODE_HANDLER(SMSG_SPELL_CHANCE_PROC_LOG, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); @@ -1707,7 +1696,6 @@ void InitOpcodes() //DEFINE_OPCODE_HANDLER(SMSG_SPLINE_SET_SWIM_SPEED, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); //DEFINE_OPCODE_HANDLER(SMSG_SPLINE_SET_TURN_RATE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); //DEFINE_OPCODE_HANDLER(SMSG_SPLINE_SET_WALK_SPEED, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); - //DEFINE_OPCODE_HANDLER(SMSG_TRAINER_BUY_RESULT, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); //DEFINE_OPCODE_HANDLER(SMSG_VOICE_SESSION_ADJUST_PRIORITY, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); //DEFINE_OPCODE_HANDLER(SMSG_VOICE_SESSION_ENABLE, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); //DEFINE_OPCODE_HANDLER(SMSG_ZONE_MAP, STATUS_NEVER, PROCESS_INPLACE, &WorldSession::Handle_ServerSide ); diff --git a/src/server/game/Server/Protocol/Opcodes.h b/src/server/game/Server/Protocol/Opcodes.h index 07cfdf39bb1..b948ce76ca6 100755 --- a/src/server/game/Server/Protocol/Opcodes.h +++ b/src/server/game/Server/Protocol/Opcodes.h @@ -247,7 +247,6 @@ enum Opcodes CMSG_GUILD_BANK_NOTE = 0x0000, CMSG_GUILD_BANK_QUERY_TAB = 0x2E35, CMSG_GUILD_BANK_QUERY_TEXT = 0x3220, - CMSG_GUILD_BANK_SET_TAB_TEXT = 0x3023, CMSG_GUILD_BANK_SWAP_ITEMS = 0x2315, CMSG_GUILD_BANK_UPDATE_TAB = 0x0106, CMSG_GUILD_BANK_WITHDRAW_MONEY = 0x0037, @@ -285,6 +284,7 @@ enum Opcodes CMSG_IGNORE_TRADE = 0x7112, CMSG_INITIATE_TRADE = 0x7916, CMSG_INSPECT = 0x0927, + CMSG_INSPECT_HONOR_STATS = 0x791E, CMSG_INSTANCE_LOCK_WARNING_RESPONSE = 0x6234, CMSG_ITEM_REFUND = 0x6134, CMSG_ITEM_REFUND_INFO = 0x2206, @@ -294,7 +294,6 @@ enum Opcodes CMSG_LEARN_PREVIEW_TALENTS = 0x2415, CMSG_LEARN_PREVIEW_TALENTS_PET = 0x6E24, CMSG_LEARN_TALENT = 0x0306, - CMSG_LEAVE_BATTLEFIELD = 0x0000, CMSG_LEAVE_CHANNEL = 0x2D56, CMSG_LFG_GET_PLAYER_INFO = 0x0000, CMSG_LFG_GET_STATUS = 0x2581, @@ -464,7 +463,6 @@ enum Opcodes CMSG_REQUEST_ACCOUNT_DATA = 0x6505, CMSG_REQUEST_CATEGORY_COOLDOWNS = 0x7102, CMSG_REQUEST_CEMETERY_LIST = 0x720A, - CMSG_REQUEST_HONOR_STATS = 0x791E, CMSG_REQUEST_HOTFIX = 0x2401, CMSG_REQUEST_INSPECT_RATED_BG_STATS = 0x3010, CMSG_REQUEST_PARTY_MEMBER_STATS = 0x0C04, @@ -509,7 +507,7 @@ enum Opcodes CMSG_SET_FACTION_ATWAR = 0x0706, CMSG_SET_FACTION_CHEAT = 0x0000, CMSG_SET_FACTION_INACTIVE = 0x0E37, - CMSG_SET_GUILD_BANK_TEXT = 0x0000, + CMSG_SET_GUILD_BANK_TEXT = 0x3023, CMSG_SET_LFG_COMMENT = 0x0000, CMSG_SET_PET_SLOT = 0x3A04, CMSG_SET_PLAYER_DECLINED_NAMES = 0x6316, @@ -589,15 +587,12 @@ enum Opcodes CMSG_WRAP_ITEM = 0x4F06, CMSG_ZONEUPDATE = 0x4F37, MSG_AUCTION_HELLO = 0x2307, - MSG_BATTLEGROUND_PLAYER_POSITIONS = 0x0000, MSG_CHANNEL_START = 0x0A15, // SMSG only? MSG_CHANNEL_UPDATE = 0x2417, // SMSG only? MSG_CORPSE_QUERY = 0x4336, MSG_GM_BIND_OTHER = 0x0000, MSG_GM_SHOWLABEL = 0x0000, MSG_GM_SUMMON = 0x0000, - MSG_GUILD_BANK_LOG_QUERY = 0x0000, - MSG_GUILD_EVENT_LOG_QUERY = 0x0000, MSG_INSPECT_ARENA_TEAMS = 0x2704, MSG_LIST_STABLED_PETS = 0x0834, MSG_MINIMAP_PING = 0x6635, @@ -658,7 +653,6 @@ enum Opcodes MSG_PETITION_DECLINE = 0x4905, MSG_PETITION_RENAME = 0x4005, MSG_PVP_LOG_DATA = 0x0000, - MSG_QUERY_GUILD_BANK_TEXT = 0x0000, MSG_QUERY_NEXT_MAIL_TIME = 0x0F04, MSG_QUEST_PUSH_RESULT = 0x4515, MSG_RAID_READY_CHECK = 0x2304, @@ -733,15 +727,14 @@ enum Opcodes SMSG_BATTLEFIELD_PORT_DENIED = 0x35A3, SMSG_BATTLEFIELD_RATED_INFO = 0x54A3, SMSG_BATTLEFIELD_STATUS = 0x7DA1, - SMSG_BATTLEFIELD_STATUS1 = 0x0000, - SMSG_BATTLEFIELD_STATUS2 = 0x74A4, - SMSG_BATTLEFIELD_STATUS3 = 0x59A0, - SMSG_BATTLEFIELD_STATUS4 = 0x75A2, + SMSG_BATTLEFIELD_STATUS_QUEUED = 0x35A1, + SMSG_BATTLEFIELD_STATUS_ACTIVE = 0x74A4, + SMSG_BATTLEFIELD_STATUS_NEEDCONFIRMATION = 0x59A0, + SMSG_BATTLEFIELD_STATUS_WAITFORGROUPS = 0x75A2, SMSG_BATTLEFIELD_STATUS_FAILED = 0x71A7, SMSG_BATTLEGROUND_INFO_THROTTLED = 0x34B2, SMSG_BATTLEGROUND_PLAYER_JOINED = 0x50B0, SMSG_BATTLEGROUND_PLAYER_LEFT = 0x59A6, - SMSG_BATTLEGROUND_PLAYER_POSITIONS = 0x0000, SMSG_BINDER_CONFIRM = 0x2835, SMSG_BINDPOINTUPDATE = 0x0527, SMSG_BINDZONEREPLY = 0x0000, @@ -912,7 +905,6 @@ enum Opcodes SMSG_GROUP_DECLINE = 0x6835, SMSG_GROUP_DESTROYED = 0x2207, SMSG_GROUP_INVITE = 0x31B2, - SMSG_GROUP_JOINED_BATTLEGROUND = 0x35A1, SMSG_GROUP_LIST = 0x4C24, SMSG_GROUP_SET_LEADER = 0x0526, SMSG_GROUP_SET_ROLE = 0x39A6, @@ -922,9 +914,9 @@ enum Opcodes SMSG_GUILD_ACHIEVEMENT_EARNED = 0x50B5, SMSG_GUILD_ACHIEVEMENT_MEMBERS = 0x38A5, SMSG_GUILD_BANK_LIST = 0x78A5, - SMSG_GUILD_BANK_LOG_QUERY_RESULTS = 0x30B2, + SMSG_GUILD_BANK_LOG_QUERY_RESULT = 0x30B2, SMSG_GUILD_BANK_MONEY_WITHDRAWN = 0x5DB4, - SMSG_GUILD_BANK_QUERY_TEXT_RESULTS = 0x75A3, + SMSG_GUILD_BANK_QUERY_TEXT_RESULT = 0x75A3, SMSG_GUILD_CANCEL = 0x0000, SMSG_GUILD_CHALLENGE_COMPLETED = 0x39A3, SMSG_GUILD_CHALLENGE_UPDATED = 0x18B1, @@ -935,7 +927,7 @@ enum Opcodes SMSG_GUILD_CRITERIA_DELETED = 0x55B1, SMSG_GUILD_DECLINE = 0x2C07, SMSG_GUILD_EVENT = 0x0705, - SMSG_GUILD_EVENT_LOG_QUERY = 0x10B2, + SMSG_GUILD_EVENT_LOG_QUERY_RESULT = 0x10B2, SMSG_GUILD_FLAGGED_FOR_RENAME = 0x30B6, SMSG_GUILD_INVITE = 0x14A2, SMSG_GUILD_INVITE_CANCEL = 0x0606, @@ -1177,7 +1169,6 @@ enum Opcodes SMSG_PLAY_MUSIC = 0x4B06, SMSG_PLAY_OBJECT_SOUND = 0x2635, SMSG_PLAY_SOUND = 0x2134, - SMSG_PLAY_SPELL_IMPACT = 0x0000, SMSG_PLAY_SPELL_VISUAL = 0x10B1, SMSG_PLAY_SPELL_VISUAL_KIT = 0x55A5, SMSG_PLAY_TIME_WARNING = 0x4814, @@ -1349,7 +1340,6 @@ enum Opcodes SMSG_TRADE_STATUS = 0x5CA3, SMSG_TRADE_STATUS_EXTENDED = 0x70A2, SMSG_TRAINER_BUY_FAILED = 0x0004, - SMSG_TRAINER_BUY_RESULT = 0x0000, SMSG_TRAINER_BUY_SUCCEEDED = 0x6A05, SMSG_TRAINER_LIST = 0x4414, SMSG_TRANSFER_ABORTED = 0x0537, diff --git a/src/server/game/Server/WorldSession.h b/src/server/game/Server/WorldSession.h index ac8e48a0c04..0ac7884efe2 100755 --- a/src/server/game/Server/WorldSession.h +++ b/src/server/game/Server/WorldSession.h @@ -545,6 +545,7 @@ class WorldSession void HandleGroupUninviteOpcode(WorldPacket& recvPacket); void HandleGroupUninviteGuidOpcode(WorldPacket& recvPacket); void HandleGroupSetLeaderOpcode(WorldPacket& recvPacket); + void HandleGroupSetRolesOpcode(WorldPacket& recvData); void HandleGroupDisbandOpcode(WorldPacket& recvPacket); void HandleOptOutOfLootOpcode(WorldPacket& recvData); void HandleLootMethodOpcode(WorldPacket& recvPacket); @@ -618,6 +619,7 @@ class WorldSession void HandleStableRevivePet(WorldPacket& recvPacket); void HandleStableSwapPet(WorldPacket& recvPacket); void HandleStableSwapPetCallback(PreparedQueryResult result, uint32 petId); + void SendTrainerBuyFailed(uint64 guid, uint32 spellId, uint32 reason); void HandleDuelAcceptedOpcode(WorldPacket& recvPacket); void HandleDuelCancelledOpcode(WorldPacket& recvPacket); @@ -787,7 +789,7 @@ class WorldSession void HandlePVPLogDataOpcode(WorldPacket& recvData); void HandleBattleFieldPortOpcode(WorldPacket& recvData); void HandleBattlefieldListOpcode(WorldPacket& recvData); - void HandleLeaveBattlefieldOpcode(WorldPacket& recvData); + void HandleBattlefieldLeaveOpcode(WorldPacket& recvData); void HandleBattlemasterJoinArena(WorldPacket& recvData); void HandleReportPvPAFK(WorldPacket& recvData); @@ -808,14 +810,14 @@ class WorldSession void HandleInstanceLockResponse(WorldPacket& recvPacket); // Battlefield - void SendBfInvitePlayerToWar(uint32 BattleId,uint32 ZoneId,uint32 time); - void SendBfInvitePlayerToQueue(uint32 BattleId); - void SendBfQueueInviteResponse(uint32 BattleId,uint32 ZoneId, bool CanQueue = true, bool Full = false); - void SendBfEntered(uint32 BattleId); - void SendBfLeaveMessage(uint32 BattleId, BFLeaveReason reason = BF_LEAVE_REASON_EXITED); - void HandleBfQueueInviteResponse(WorldPacket &recv_data); - void HandleBfEntryInviteResponse(WorldPacket &recv_data); - void HandleBfExitRequest(WorldPacket &recv_data); + void SendBfInvitePlayerToWar(uint64 guid, uint32 zoneId, uint32 pTime); + void SendBfInvitePlayerToQueue(uint64 guid); + void SendBfQueueInviteResponse(uint64 guid, uint32 zoneId, bool canQueue = true, bool full = false); + void SendBfEntered(uint64 guid); + void SendBfLeaveMessage(uint64 guid, BFLeaveReason reason = BF_LEAVE_REASON_EXITED); + void HandleBfQueueInviteResponse(WorldPacket& recvData); + void HandleBfEntryInviteResponse(WorldPacket& recvData); + void HandleBfExitRequest(WorldPacket& recvData); // Looking for Dungeon/Raid void HandleLfgSetCommentOpcode(WorldPacket& recvData); diff --git a/src/server/game/Spells/Auras/SpellAuraEffects.cpp b/src/server/game/Spells/Auras/SpellAuraEffects.cpp index be18785e76e..30614c655fa 100644 --- a/src/server/game/Spells/Auras/SpellAuraEffects.cpp +++ b/src/server/game/Spells/Auras/SpellAuraEffects.cpp @@ -2913,13 +2913,13 @@ void AuraEffect::HandleForceMoveForward(AuraApplication const* aurApp, uint8 mod Unit* target = aurApp->GetTarget(); if (apply) - target->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVE); + target->SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVEMENT); else { // do not remove unit flag if there are more than this auraEffect of that kind on unit on unit if (target->HasAuraType(GetAuraType())) return; - target->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVE); + target->RemoveFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_FORCE_MOVEMENT); } } diff --git a/src/server/game/Spells/Spell.cpp b/src/server/game/Spells/Spell.cpp index 98833c3eb41..1655256666f 100755 --- a/src/server/game/Spells/Spell.cpp +++ b/src/server/game/Spells/Spell.cpp @@ -88,7 +88,7 @@ SpellDestination::SpellDestination(WorldObject const& wObj) } -SpellCastTargets::SpellCastTargets() : m_elevation(0), m_speed(0) +SpellCastTargets::SpellCastTargets() : m_elevation(0), m_speed(0), m_strTarget() { m_objectTarget = NULL; m_itemTarget = NULL; @@ -97,7 +97,6 @@ SpellCastTargets::SpellCastTargets() : m_elevation(0), m_speed(0) m_itemTargetGUID = 0; m_itemTargetEntry = 0; - m_strTarget = ""; m_targetMask = 0; } @@ -3002,7 +3001,13 @@ void Spell::prepare(SpellCastTargets const* targets, AuraEffect const* triggered // calculate cast time (calculated after first CheckCast check to prevent charge counting for first CheckCast fail) m_casttime = m_spellInfo->CalcCastTime(m_caster, this); if (m_caster->GetTypeId() == TYPEID_PLAYER) + { m_caster->ToPlayer()->SetSpellModTakingSpell(this, false); + + // Set casttime to 0 if .cheat casttime is enabled. + if (m_caster->ToPlayer()->GetCommandStatus(CHEAT_CASTTIME)) + m_casttime = 0; + } // don't allow channeled spells / spells with cast time to be casted while moving // (even if they are interrupted on moving, spells with almost immediate effect get to have their effect processed before movement interrupter kicks in) @@ -3294,7 +3299,13 @@ void Spell::cast(bool skipCheck) } if (m_caster->GetTypeId() == TYPEID_PLAYER) + { m_caster->ToPlayer()->SetSpellModTakingSpell(this, false); + + //Clear spell cooldowns after every spell is cast if .cheat cooldown is enabled. + if (m_caster->ToPlayer()->GetCommandStatus(CHEAT_COOLDOWN)) + m_caster->ToPlayer()->RemoveSpellCooldown(m_spellInfo->Id, true); + } SetExecutedCurrently(false); } @@ -4029,41 +4040,47 @@ void Spell::SendSpellGo() m_caster->SendMessageToSet(&data, true); } +/// Writes miss and hit targets for a SMSG_SPELL_GO packet void Spell::WriteSpellGoTargets(WorldPacket* data) { // This function also fill data for channeled spells: // m_needAliveTargetMask req for stop channelig if one target die - uint32 hit = m_UniqueGOTargetInfo.size(); // Always hits on GO - uint32 miss = 0; for (std::list<TargetInfo>::iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if ((*ihit).effectMask == 0) // No effect apply - all immuned add state - { // possibly SPELL_MISS_IMMUNE2 for this?? ihit->missCondition = SPELL_MISS_IMMUNE2; - ++miss; - } - else if ((*ihit).missCondition == SPELL_MISS_NONE) - ++hit; - else - ++miss; } - *data << (uint8)hit; - for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) + // Hit and miss target counts are both uint8, that limits us to 255 targets for each + // sending more than 255 targets crashes the client (since count sent would be wrong) + // Spells like 40647 (with a huge radius) can easily reach this limit (spell might need + // target conditions but we still need to limit the number of targets sent and keeping + // correct count for both hit and miss). + + uint32 hit = 0; + size_t hitPos = data->wpos(); + *data << (uint8)0; // placeholder + for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end() && hit <= 255; ++ihit) { if ((*ihit).missCondition == SPELL_MISS_NONE) // Add only hits { *data << uint64(ihit->targetGUID); m_channelTargetEffectMask |=ihit->effectMask; + ++hit; } } - for (std::list<GOTargetInfo>::const_iterator ighit = m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end(); ++ighit) + for (std::list<GOTargetInfo>::const_iterator ighit = m_UniqueGOTargetInfo.begin(); ighit != m_UniqueGOTargetInfo.end() && hit <= 255; ++ighit) + { *data << uint64(ighit->targetGUID); // Always hits + ++hit; + } - *data << (uint8)miss; - for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) + uint32 miss = 0; + size_t missPos = data->wpos(); + *data << (uint8)0; // placeholder + for (std::list<TargetInfo>::const_iterator ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end() && miss <= 255; ++ihit) { if (ihit->missCondition != SPELL_MISS_NONE) // Add only miss { @@ -4071,11 +4088,15 @@ void Spell::WriteSpellGoTargets(WorldPacket* data) *data << uint8(ihit->missCondition); if (ihit->missCondition == SPELL_MISS_REFLECT) *data << uint8(ihit->reflectResult); + ++miss; } } // Reset m_needAliveTargetMask for non channeled spell if (!m_spellInfo->IsChanneled()) m_channelTargetEffectMask = 0; + + data->put<uint8>(hitPos, (uint8)hit); + data->put<uint8>(missPos, (uint8)miss); } void Spell::SendLogExecute() @@ -4334,6 +4355,13 @@ void Spell::TakePower() if (m_CastItem || m_triggeredByAuraSpell) return; + //Don't take power if the spell is cast while .cheat power is enabled. + if (m_caster->GetTypeId() == TYPEID_PLAYER) + { + if (m_caster->ToPlayer()->GetCommandStatus(CHEAT_POWER)) + return; + } + Powers powerType = Powers(m_spellInfo->PowerType); bool hit = true; if (m_caster->GetTypeId() == TYPEID_PLAYER) @@ -6788,9 +6816,9 @@ SpellCastResult Spell::CanOpenLock(uint32 effIndex, uint32 lockId, SkillType& sk 0 : m_caster->ToPlayer()->GetSkillValue(skillId); // skill bonus provided by casting spell (mostly item spells) - // add the damage modifier from the spell casted (cheat lock / skeleton key etc.) + // add the effect base points modifier from the spell casted (cheat lock / skeleton key etc.) if (m_spellInfo->Effects[effIndex].TargetA.GetTarget() == TARGET_GAMEOBJECT_ITEM_TARGET || m_spellInfo->Effects[effIndex].TargetB.GetTarget() == TARGET_GAMEOBJECT_ITEM_TARGET) - skillValue += uint32(CalculateDamage(effIndex, NULL)); + skillValue += m_spellInfo->Effects[effIndex].CalcValue(); if (skillValue < reqSkillValue) return SPELL_FAILED_LOW_CASTLEVEL; @@ -7156,6 +7184,10 @@ void Spell::TriggerGlobalCooldown() if (!gcd) return; + if (m_caster->GetTypeId() == TYPEID_PLAYER) + if (m_caster->ToPlayer()->GetCommandStatus(CHEAT_COOLDOWN)) + return; + // Global cooldown can't leave range 1..1.5 secs // There are some spells (mostly not casted directly by player) that have < 1 sec and > 1.5 sec global cooldowns // but as tests show are not affected by any spell mods. diff --git a/src/server/game/Spells/SpellEffects.cpp b/src/server/game/Spells/SpellEffects.cpp index be5d4e3fa74..8369a1b61c5 100644 --- a/src/server/game/Spells/SpellEffects.cpp +++ b/src/server/game/Spells/SpellEffects.cpp @@ -295,6 +295,10 @@ void Spell::EffectInstaKill(SpellEffIndex /*effIndex*/) if (!unitTarget || !unitTarget->isAlive()) return; + if (unitTarget->GetTypeId() == TYPEID_PLAYER) + if (unitTarget->ToPlayer()->GetCommandStatus(CHEAT_GOD)) + return; + if (m_caster == unitTarget) // prevent interrupt message finish(); @@ -330,10 +334,9 @@ void Spell::EffectSchoolDMG(SpellEffIndex effIndex) if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH_TARGET) return; - bool apply_direct_bonus = true; - if (unitTarget && unitTarget->isAlive()) { + bool apply_direct_bonus = true; switch (m_spellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: @@ -4008,17 +4011,6 @@ void Spell::EffectScriptEffect(SpellEffIndex effIndex) unitTarget->CastSpell(unitTarget, spellTarget[urand(0, 4)], true); break; } - case 64142: // Upper Deck - Create Foam Sword - if (unitTarget->GetTypeId() != TYPEID_PLAYER) - return; - Player* player = unitTarget->ToPlayer(); - static uint32 const itemId[] = {45061, 45176, 45177, 45178, 45179, 0}; - // player can only have one of these items - for (uint32 const* itr = &itemId[0]; *itr; ++itr) - if (player->HasItemCount(*itr, 1, true)) - return; - DoCreateItem(effIndex, itemId[urand(0, 4)]); - return; } break; } diff --git a/src/server/game/Spells/SpellMgr.cpp b/src/server/game/Spells/SpellMgr.cpp index 5c2b007493c..fe7a0eab229 100644 --- a/src/server/game/Spells/SpellMgr.cpp +++ b/src/server/game/Spells/SpellMgr.cpp @@ -1167,6 +1167,26 @@ bool SpellArea::IsFitToRequirements(Player const* player, uint32 newZone, uint32 return spellId == 56617; } break; + case 57940: // Essence of Wintergrasp - Northrend + case 58045: // Essence of Wintergrasp - Wintergrasp + { + if (!player) + return false; + + if (Battlefield* battlefieldWG = sBattlefieldMgr->GetBattlefieldByBattleId(BATTLEFIELD_BATTLEID_WG)) + return battlefieldWG->IsEnabled() && (player->GetTeamId() == battlefieldWG->GetDefenderTeam()) && !battlefieldWG->IsWarTime(); + break; + } + case 74411: // Battleground - Dampening + { + if (!player) + return false; + + if (Battlefield* bf = sBattlefieldMgr->GetBattlefieldToZoneId(player->GetZoneId())) + return bf->IsWarTime(); + break; + } + } return true; diff --git a/src/server/game/Spells/SpellMgr.h b/src/server/game/Spells/SpellMgr.h index dcf3c38fe4f..9c5619ef5f6 100755 --- a/src/server/game/Spells/SpellMgr.h +++ b/src/server/game/Spells/SpellMgr.h @@ -441,7 +441,7 @@ class PetAura typedef UNORDERED_MAP<uint32, uint32> PetAuraMap; public: - PetAura() + PetAura() : removeOnChangePet(false), damage(0) { auras.clear(); } diff --git a/src/server/game/World/World.cpp b/src/server/game/World/World.cpp index 936b2d3629b..0a9af095352 100644 --- a/src/server/game/World/World.cpp +++ b/src/server/game/World/World.cpp @@ -1197,6 +1197,9 @@ void World::LoadConfigSettings(bool reload) // MySQL ping time interval m_int_configs[CONFIG_DB_PING_INTERVAL] = ConfigMgr::GetIntDefault("MaxPingTime", 30); + // Guild save interval + m_int_configs[CONFIG_GUILD_SAVE_INTERVAL] = ConfigMgr::GetIntDefault("GuildSaveInterval", 15); + // misc m_bool_configs[CONFIG_PDUMP_NO_PATHS] = ConfigMgr::GetBoolDefault("PlayerDump.DisallowPaths", true); m_bool_configs[CONFIG_PDUMP_NO_OVERWRITE] = ConfigMgr::GetBoolDefault("PlayerDump.DisallowOverwrite", true); @@ -1679,6 +1682,8 @@ void World::SetInitialWorldSettings() m_timers[WUPDATE_PINGDB].SetInterval(getIntConfig(CONFIG_DB_PING_INTERVAL)*MINUTE*IN_MILLISECONDS); // Mysql ping time in minutes + m_timers[WUPDATE_GUILDSAVE].SetInterval(getIntConfig(CONFIG_GUILD_SAVE_INTERVAL) * MINUTE * IN_MILLISECONDS); + //to set mailtimer to return mails every day between 4 and 5 am //mailtimer is increased when updating auctions //one second is 1000 -(tested on win system) @@ -2035,6 +2040,12 @@ void World::Update(uint32 diff) WorldDatabase.KeepAlive(); } + if (m_timers[WUPDATE_GUILDSAVE].Passed()) + { + m_timers[WUPDATE_GUILDSAVE].Reset(); + sGuildMgr->SaveGuilds(); + } + // update the instance reset times sInstanceSaveMgr->Update(); @@ -2926,7 +2937,7 @@ void World::LoadCharacterNameData() QueryResult result = CharacterDatabase.Query("SELECT guid, name, race, gender, class FROM characters WHERE deleteDate IS NULL"); if (!result) { - sLog->outError(LOG_FILTER_SQL, "No character name data loaded, empty query"); + sLog->outInfo(LOG_FILTER_SERVER_LOADING, "No character name data loaded, empty query"); return; } diff --git a/src/server/game/World/World.h b/src/server/game/World/World.h index 841ae2530ca..b25444f4865 100755 --- a/src/server/game/World/World.h +++ b/src/server/game/World/World.h @@ -86,6 +86,7 @@ enum WorldTimers WUPDATE_MAILBOXQUEUE, WUPDATE_DELETECHARS, WUPDATE_PINGDB, + WUPDATE_GUILDSAVE, WUPDATE_COUNT }; @@ -335,6 +336,7 @@ enum WorldIntConfigs CONFIG_WINTERGRASP_BATTLETIME, CONFIG_WINTERGRASP_NOBATTLETIME, CONFIG_WINTERGRASP_RESTART_AFTER_CRASH, + CONFIG_GUILD_SAVE_INTERVAL, INT_CONFIG_VALUE_COUNT }; diff --git a/src/server/scripts/Commands/CMakeLists.txt b/src/server/scripts/Commands/CMakeLists.txt index d5ebeab3b8a..177b3a479f5 100644 --- a/src/server/scripts/Commands/CMakeLists.txt +++ b/src/server/scripts/Commands/CMakeLists.txt @@ -16,6 +16,7 @@ set(scripts_STAT_SRCS Commands/cs_bf.cpp Commands/cs_cast.cpp Commands/cs_character.cpp + Commands/cs_cheat.cpp Commands/cs_debug.cpp Commands/cs_disable.cpp Commands/cs_event.cpp diff --git a/src/server/scripts/Commands/cs_cheat.cpp b/src/server/scripts/Commands/cs_cheat.cpp new file mode 100644 index 00000000000..1911c6d476b --- /dev/null +++ b/src/server/scripts/Commands/cs_cheat.cpp @@ -0,0 +1,281 @@ +/* + * Copyright (C) 2008-2012 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/>. + */ + +/* ScriptData +Name: cheat_commandscript +%Complete: 100 +Comment: All cheat related commands +Category: commandscripts +EndScriptData */ + +#include "ScriptMgr.h" +#include "ObjectMgr.h" +#include "Chat.h" + +class cheat_commandscript : public CommandScript +{ +public: + cheat_commandscript() : CommandScript("cheat_commandscript") { } + + ChatCommand* GetCommands() const + { + + static ChatCommand cheatCommandTable[] = + { + { "god", SEC_GAMEMASTER, false, &HandleGodModeCheatCommand, "", NULL }, + { "casttime", SEC_GAMEMASTER, false, &HandleCasttimeCheatCommand, "", NULL }, + { "cooldown", SEC_GAMEMASTER, false, &HandleCoolDownCheatCommand, "", NULL }, + { "power", SEC_GAMEMASTER, false, &HandlePowerCheatCommand, "", NULL }, + { "waterwalk", SEC_GAMEMASTER, false, &HandleWaterWalkCheatCommand, "", NULL }, + { "taxi", SEC_GAMEMASTER, false, &HandleTaxiCheatCommand, "", NULL }, + { "explore", SEC_GAMEMASTER, false, &HandleExploreCheatCommand, "", NULL }, + { NULL, 0, false, NULL, "", NULL } + + }; + + static ChatCommand commandTable[] = + { + { "cheat", SEC_GAMEMASTER, false, NULL, "", cheatCommandTable }, + { NULL, 0, false, NULL, "", NULL } + }; + return commandTable; + } + + static bool HandleGodModeCheatCommand(ChatHandler* handler, const char* args) + { + if (!handler->GetSession() && !handler->GetSession()->GetPlayer()) + return false; + + std::string argstr = (char*)args; + + if (!*args) + argstr = (handler->GetSession()->GetPlayer()->GetCommandStatus(CHEAT_GOD)) ? "off" : "on"; + + if (argstr == "off") + { + handler->GetSession()->GetPlayer()->SetCommandStatusOff(CHEAT_GOD); + handler->SendSysMessage("Godmode is OFF. You can take damage."); + return true; + } + else if (argstr == "on") + { + handler->GetSession()->GetPlayer()->SetCommandStatusOn(CHEAT_GOD); + handler->SendSysMessage("Godmode is ON. You won't take damage."); + return true; + } + + return false; + } + + static bool HandleCasttimeCheatCommand(ChatHandler* handler, const char* args) + { + if (!handler->GetSession() && !handler->GetSession()->GetPlayer()) + return false; + + std::string argstr = (char*)args; + + if (!*args) + argstr = (handler->GetSession()->GetPlayer()->GetCommandStatus(CHEAT_CASTTIME)) ? "off" : "on"; + + if (argstr == "off") + { + handler->GetSession()->GetPlayer()->SetCommandStatusOff(CHEAT_CASTTIME); + handler->SendSysMessage("CastTime Cheat is OFF. Your spells will have a casttime."); + return true; + } + else if (argstr == "on") + { + handler->GetSession()->GetPlayer()->SetCommandStatusOn(CHEAT_CASTTIME); + handler->SendSysMessage("CastTime Cheat is ON. Your spells won't have a casttime."); + return true; + } + + return false; + } + + static bool HandleCoolDownCheatCommand(ChatHandler* handler, const char* args) + { + if (!handler->GetSession() && !handler->GetSession()->GetPlayer()) + return false; + + std::string argstr = (char*)args; + + if (!*args) + argstr = (handler->GetSession()->GetPlayer()->GetCommandStatus(CHEAT_COOLDOWN)) ? "off" : "on"; + + if (argstr == "off") + { + handler->GetSession()->GetPlayer()->SetCommandStatusOff(CHEAT_COOLDOWN); + handler->SendSysMessage("Cooldown Cheat is OFF. You are on the global cooldown."); + return true; + } + else if (argstr == "on") + { + handler->GetSession()->GetPlayer()->SetCommandStatusOn(CHEAT_COOLDOWN); + handler->SendSysMessage("Cooldown Cheat is ON. You are not on the global cooldown."); + return true; + } + + return false; + } + + static bool HandlePowerCheatCommand(ChatHandler* handler, const char* args) + { + if (!handler->GetSession() && !handler->GetSession()->GetPlayer()) + return false; + + std::string argstr = (char*)args; + + if (!*args) + argstr = (handler->GetSession()->GetPlayer()->GetCommandStatus(CHEAT_POWER)) ? "off" : "on"; + + if (argstr == "off") + { + handler->GetSession()->GetPlayer()->SetCommandStatusOff(CHEAT_POWER); + handler->SendSysMessage("Power Cheat is OFF. You need mana/rage/energy to use spells."); + return true; + } + else if (argstr == "on") + { + handler->GetSession()->GetPlayer()->SetCommandStatusOn(CHEAT_POWER); + handler->SendSysMessage("Power Cheat is ON. You don't need mana/rage/energy to use spells."); + return true; + } + + return false; + } + + static bool HandleWaterWalkCheatCommand(ChatHandler* handler, const char* args) + { + if (!handler->GetSession() && !handler->GetSession()->GetPlayer()) + return false; + + std::string argstr = (char*)args; + + if (!*args) + { + argstr = (handler->GetSession()->GetPlayer()->GetCommandStatus(CHEAT_WATERWALK)) ? "off" : "on"; + if (handler->GetSession()->GetPlayer()->GetCommandStatus(CHEAT_WATERWALK)) + argstr = "off"; + else + argstr = "on"; + } + + if (argstr == "off") + { + handler->GetSession()->GetPlayer()->SetCommandStatusOff(CHEAT_WATERWALK); + handler->GetSession()->GetPlayer()->SendMovementSetWaterWalking(false); // OFF + handler->SendSysMessage("Waterwalking is OFF. You can't walk on water."); + return true; + } + else if (argstr == "on") + { + handler->GetSession()->GetPlayer()->SetCommandStatusOn(CHEAT_WATERWALK); + handler->GetSession()->GetPlayer()->SendMovementSetWaterWalking(true); // ON + handler->SendSysMessage("Waterwalking is ON. You can walk on water."); + return true; + } + + return false; + } + + static bool HandleTaxiCheatCommand(ChatHandler* handler, const char* args) + { + if (!*args) + { + handler->SendSysMessage(LANG_USE_BOL); + handler->SetSentErrorMessage(true); + return false; + } + + std::string argstr = (char*)args; + + Player* chr = handler->getSelectedPlayer(); + + if (!chr) + chr = handler->GetSession()->GetPlayer(); + else if (handler->HasLowerSecurity(chr, 0)) // check online security + return false; + + if (argstr == "on") + { + chr->SetTaxiCheater(true); + handler->PSendSysMessage(LANG_YOU_GIVE_TAXIS, handler->GetNameLink(chr).c_str()); + if (handler->needReportToTarget(chr)) + ChatHandler(chr).PSendSysMessage(LANG_YOURS_TAXIS_ADDED, handler->GetNameLink().c_str()); + return true; + } + + if (argstr == "off") + { + chr->SetTaxiCheater(false); + handler->PSendSysMessage(LANG_YOU_REMOVE_TAXIS, handler->GetNameLink(chr).c_str()); + if (handler->needReportToTarget(chr)) + ChatHandler(chr).PSendSysMessage(LANG_YOURS_TAXIS_REMOVED, handler->GetNameLink().c_str()); + + return true; + } + + handler->SendSysMessage(LANG_USE_BOL); + handler->SetSentErrorMessage(true); + return false; + } + + static bool HandleExploreCheatCommand(ChatHandler* handler, const char *args) + { + if (!*args) + return false; + + int flag = atoi((char*)args); + + Player* chr = handler->getSelectedPlayer(); + if (chr == NULL) + { + handler->SendSysMessage(LANG_NO_CHAR_SELECTED); + handler->SetSentErrorMessage(true); + return false; + } + + if (flag != 0) + { + handler->PSendSysMessage(LANG_YOU_SET_EXPLORE_ALL, handler->GetNameLink(chr).c_str()); + if (handler->needReportToTarget(chr)) + ChatHandler(chr).PSendSysMessage(LANG_YOURS_EXPLORE_SET_ALL, handler->GetNameLink().c_str()); + } + else + { + handler->PSendSysMessage(LANG_YOU_SET_EXPLORE_NOTHING, handler->GetNameLink(chr).c_str()); + if (handler->needReportToTarget(chr)) + ChatHandler(chr).PSendSysMessage(LANG_YOURS_EXPLORE_SET_NOTHING, handler->GetNameLink().c_str()); + } + + for (uint8 i = 0; i < PLAYER_EXPLORED_ZONES_SIZE; ++i) + { + if (flag != 0) + handler->GetSession()->GetPlayer()->SetFlag(PLAYER_EXPLORED_ZONES_1+i, 0xFFFFFFFF); + else + handler->GetSession()->GetPlayer()->SetFlag(PLAYER_EXPLORED_ZONES_1+i, 0); + } + + return true; + } +}; + +void AddSC_cheat_commandscript() +{ + new cheat_commandscript(); +} diff --git a/src/server/scripts/Commands/cs_misc.cpp b/src/server/scripts/Commands/cs_misc.cpp index 7ea681170b4..68e68ba7892 100644 --- a/src/server/scripts/Commands/cs_misc.cpp +++ b/src/server/scripts/Commands/cs_misc.cpp @@ -82,10 +82,8 @@ public: { "saveall", SEC_MODERATOR, true, &HandleSaveAllCommand, "", NULL }, { "kick", SEC_GAMEMASTER, true, &HandleKickPlayerCommand, "", NULL }, { "start", SEC_PLAYER, false, &HandleStartCommand, "", NULL }, - { "taxicheat", SEC_MODERATOR, false, &HandleTaxiCheatCommand, "", NULL }, { "linkgrave", SEC_ADMINISTRATOR, false, &HandleLinkGraveCommand, "", NULL }, { "neargrave", SEC_ADMINISTRATOR, false, &HandleNearGraveCommand, "", NULL }, - { "explorecheat", SEC_ADMINISTRATOR, false, &HandleExploreCheatCommand, "", NULL }, { "showarea", SEC_ADMINISTRATOR, false, &HandleShowAreaCommand, "", NULL }, { "hidearea", SEC_ADMINISTRATOR, false, &HandleHideAreaCommand, "", NULL }, { "additem", SEC_ADMINISTRATOR, false, &HandleAddItemCommand, "", NULL }, @@ -106,7 +104,6 @@ public: { "combatstop", SEC_GAMEMASTER, true, &HandleCombatStopCommand, "", NULL }, { "flusharenapoints", SEC_ADMINISTRATOR, false, &HandleFlushArenaPointsCommand, "", NULL }, { "repairitems", SEC_GAMEMASTER, true, &HandleRepairitemsCommand, "", NULL }, - { "waterwalk", SEC_GAMEMASTER, false, &HandleWaterwalkCommand, "", NULL }, { "freeze", SEC_MODERATOR, false, &HandleFreezeCommand, "", NULL }, { "unfreeze", SEC_MODERATOR, false, &HandleUnFreezeCommand, "", NULL }, { "listfreeze", SEC_MODERATOR, false, &HandleListFreezeCommand, "", NULL }, @@ -960,49 +957,6 @@ public: player->CastSpell(player, 7355, false); return true; } - // Enable on\off all taxi paths - static bool HandleTaxiCheatCommand(ChatHandler* handler, char const* args) - { - if (!*args) - { - handler->SendSysMessage(LANG_USE_BOL); - handler->SetSentErrorMessage(true); - return false; - } - - std::string argStr = (char*)args; - - Player* chr = handler->getSelectedPlayer(); - - if (!chr) - chr = handler->GetSession()->GetPlayer(); - else if (handler->HasLowerSecurity(chr, 0)) // check online security - return false; - - if (argStr == "on") - { - chr->SetTaxiCheater(true); - handler->PSendSysMessage(LANG_YOU_GIVE_TAXIS, handler->GetNameLink(chr).c_str()); - if (handler->needReportToTarget(chr)) - ChatHandler(chr).PSendSysMessage(LANG_YOURS_TAXIS_ADDED, handler->GetNameLink().c_str()); - return true; - } - - if (argStr == "off") - { - chr->SetTaxiCheater(false); - handler->PSendSysMessage(LANG_YOU_REMOVE_TAXIS, handler->GetNameLink(chr).c_str()); - if (handler->needReportToTarget(chr)) - ChatHandler(chr).PSendSysMessage(LANG_YOURS_TAXIS_REMOVED, handler->GetNameLink().c_str()); - - return true; - } - - handler->SendSysMessage(LANG_USE_BOL); - handler->SetSentErrorMessage(true); - - return false; - } static bool HandleLinkGraveCommand(ChatHandler* handler, char const* args) { @@ -1123,45 +1077,6 @@ public: return true; } - static bool HandleExploreCheatCommand(ChatHandler* handler, char const* args) - { - if (!*args) - return false; - - int32 flag = int32(atoi((char*)args)); - - Player* playerTarget = handler->getSelectedPlayer(); - if (!playerTarget) - { - handler->SendSysMessage(LANG_NO_CHAR_SELECTED); - handler->SetSentErrorMessage(true); - return false; - } - - if (flag != 0) - { - handler->PSendSysMessage(LANG_YOU_SET_EXPLORE_ALL, handler->GetNameLink(playerTarget).c_str()); - if (handler->needReportToTarget(playerTarget)) - ChatHandler(playerTarget).PSendSysMessage(LANG_YOURS_EXPLORE_SET_ALL, handler->GetNameLink().c_str()); - } - else - { - handler->PSendSysMessage(LANG_YOU_SET_EXPLORE_NOTHING, handler->GetNameLink(playerTarget).c_str()); - if (handler->needReportToTarget(playerTarget)) - ChatHandler(playerTarget).PSendSysMessage(LANG_YOURS_EXPLORE_SET_NOTHING, handler->GetNameLink().c_str()); - } - - for (uint8 i = 0; i < PLAYER_EXPLORED_ZONES_SIZE; ++i) - { - if (flag != 0) - handler->GetSession()->GetPlayer()->SetFlag(PLAYER_EXPLORED_ZONES_1+i, 0xFFFFFFFF); - else - handler->GetSession()->GetPlayer()->SetFlag(PLAYER_EXPLORED_ZONES_1+i, 0); - } - - return true; - } - static bool HandleShowAreaCommand(ChatHandler* handler, char const* args) { if (!*args) @@ -2193,39 +2108,6 @@ public: return true; } - static bool HandleWaterwalkCommand(ChatHandler* handler, char const* args) - { - if (!*args) - return false; - - Player* player = handler->getSelectedPlayer(); - if (!player) - { - handler->PSendSysMessage(LANG_NO_CHAR_SELECTED); - handler->SetSentErrorMessage(true); - return false; - } - - // check online security - if (handler->HasLowerSecurity(player, 0)) - return false; - - if (strncmp(args, "on", 3) == 0) - player->SendMovementSetWaterWalking(true); - else if (strncmp(args, "off", 4) == 0) - player->SendMovementSetWaterWalking(false); - else - { - handler->SendSysMessage(LANG_USE_BOL); - return false; - } - - handler->PSendSysMessage(LANG_YOU_SET_WATERWALK, args, handler->GetNameLink(player).c_str()); - if (handler->needReportToTarget(player)) - ChatHandler(player).PSendSysMessage(LANG_YOUR_WATERWALK_SET, args, handler->GetNameLink().c_str()); - return true; - } - // Send mail by command static bool HandleSendMailCommand(ChatHandler* handler, char const* args) { diff --git a/src/server/scripts/Commands/cs_wp.cpp b/src/server/scripts/Commands/cs_wp.cpp index 99ec263b8f9..e3cd185e4a3 100644 --- a/src/server/scripts/Commands/cs_wp.cpp +++ b/src/server/scripts/Commands/cs_wp.cpp @@ -642,19 +642,13 @@ public: { handler->PSendSysMessage("|cff00ff00DEBUG: wp modify del, PathID: |r|cff00ffff%u|r", pathid); - // wpCreature - Creature* wpCreature = NULL; - if (wpGuid != 0) - { - wpCreature = handler->GetSession()->GetPlayer()->GetMap()->GetCreature(MAKE_NEW_GUID(wpGuid, VISUAL_WAYPOINT, HIGHGUID_UNIT)); - if (wpCreature) + if (Creature* wpCreature = handler->GetSession()->GetPlayer()->GetMap()->GetCreature(MAKE_NEW_GUID(wpGuid, VISUAL_WAYPOINT, HIGHGUID_UNIT))) { wpCreature->CombatStop(); wpCreature->DeleteFromDB(); wpCreature->AddObjectToRemoveList(); } - } PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_DEL_WAYPOINT_DATA); @@ -681,15 +675,12 @@ public: Player* chr = handler->GetSession()->GetPlayer(); Map* map = chr->GetMap(); { - // wpCreature - Creature* wpCreature = NULL; // What to do: // Move the visual spawnpoint // Respawn the owner of the waypoints if (wpGuid != 0) { - wpCreature = map->GetCreature(MAKE_NEW_GUID(wpGuid, VISUAL_WAYPOINT, HIGHGUID_UNIT)); - if (wpCreature) + if (Creature* wpCreature = map->GetCreature(MAKE_NEW_GUID(wpGuid, VISUAL_WAYPOINT, HIGHGUID_UNIT))) { wpCreature->CombatStop(); wpCreature->DeleteFromDB(); diff --git a/src/server/scripts/EasternKingdoms/BlackwingLair/boss_chromaggus.cpp b/src/server/scripts/EasternKingdoms/BlackwingLair/boss_chromaggus.cpp index 204fbe5223b..25c3f2e41e3 100644 --- a/src/server/scripts/EasternKingdoms/BlackwingLair/boss_chromaggus.cpp +++ b/src/server/scripts/EasternKingdoms/BlackwingLair/boss_chromaggus.cpp @@ -243,11 +243,9 @@ public: std::list<HostileReference*> threatlist = me->getThreatManager().getThreatList(); for (std::list<HostileReference*>::const_iterator i = threatlist.begin(); i != threatlist.end(); ++i) { - Unit* unit; if ((*i) && (*i)->getSource()) { - unit = Unit::GetUnit(*me, (*i)->getUnitGuid()); - if (unit) + if (Unit* unit = Unit::GetUnit(*me, (*i)->getUnitGuid())) { //Cast affliction DoCast(unit, RAND(SPELL_BROODAF_BLUE, SPELL_BROODAF_BLACK, diff --git a/src/server/scripts/EasternKingdoms/Karazhan/boss_moroes.cpp b/src/server/scripts/EasternKingdoms/Karazhan/boss_moroes.cpp index 06c1243645c..533a1aac2f0 100644 --- a/src/server/scripts/EasternKingdoms/Karazhan/boss_moroes.cpp +++ b/src/server/scripts/EasternKingdoms/Karazhan/boss_moroes.cpp @@ -201,12 +201,11 @@ public: { for (uint8 i = 0; i < 4; ++i) { - Creature* Temp = NULL; if (AddGUID[i]) { - Temp = Creature::GetCreature((*me), AddGUID[i]); - if (Temp && Temp->isAlive()) - Temp->DisappearAndDie(); + Creature* temp = Creature::GetCreature((*me), AddGUID[i]); + if (temp && temp->isAlive()) + temp->DisappearAndDie(); } } } @@ -215,14 +214,13 @@ public: { for (uint8 i = 0; i < 4; ++i) { - Creature* Temp = NULL; if (AddGUID[i]) { - Temp = Creature::GetCreature((*me), AddGUID[i]); - if (Temp && Temp->isAlive()) + Creature* temp = Creature::GetCreature((*me), AddGUID[i]); + if (temp && temp->isAlive()) { - Temp->AI()->AttackStart(me->getVictim()); - DoZoneInCombat(Temp); + temp->AI()->AttackStart(me->getVictim()); + DoZoneInCombat(temp); } else EnterEvadeMode(); } @@ -250,13 +248,12 @@ public: { for (uint8 i = 0; i < 4; ++i) { - Creature* Temp = NULL; if (AddGUID[i]) { - Temp = Unit::GetCreature((*me), AddGUID[i]); - if (Temp && Temp->isAlive()) - if (!Temp->getVictim()) - Temp->AI()->AttackStart(me->getVictim()); + Creature* temp = Unit::GetCreature((*me), AddGUID[i]); + if (temp && temp->isAlive()) + if (!temp->getVictim()) + temp->AI()->AttackStart(me->getVictim()); } } CheckAdds_Timer = 5000; diff --git a/src/server/scripts/EasternKingdoms/MoltenCore/boss_golemagg.cpp b/src/server/scripts/EasternKingdoms/MoltenCore/boss_golemagg.cpp index 84e9957a60c..fa99078cedb 100644 --- a/src/server/scripts/EasternKingdoms/MoltenCore/boss_golemagg.cpp +++ b/src/server/scripts/EasternKingdoms/MoltenCore/boss_golemagg.cpp @@ -77,7 +77,7 @@ class boss_golemagg : public CreatureScript void DamageTaken(Unit* /*attacker*/, uint32& /*damage*/) { - if (HealthBelowPct(10) || me->HasAura(SPELL_ENRAGE)) + if (!HealthBelowPct(10) || me->HasAura(SPELL_ENRAGE)) return; DoCast(me, SPELL_ENRAGE, true); diff --git a/src/server/scripts/EasternKingdoms/ShadowfangKeep/instance_shadowfang_keep.cpp b/src/server/scripts/EasternKingdoms/ShadowfangKeep/instance_shadowfang_keep.cpp index d4c037d45c3..b405f9eba85 100644 --- a/src/server/scripts/EasternKingdoms/ShadowfangKeep/instance_shadowfang_keep.cpp +++ b/src/server/scripts/EasternKingdoms/ShadowfangKeep/instance_shadowfang_keep.cpp @@ -240,7 +240,6 @@ public: return; Creature* pArchmage = instance->GetCreature(uiArchmageArugalGUID); - Creature* summon = NULL; if (!pArchmage || !pArchmage->isAlive()) return; @@ -252,7 +251,8 @@ public: switch (uiPhase) { case 1: - summon = pArchmage->SummonCreature(pArchmage->GetEntry(), SpawnLocation[4], TEMPSUMMON_TIMED_DESPAWN, 10000); + { + Creature* summon = pArchmage->SummonCreature(pArchmage->GetEntry(), SpawnLocation[4], TEMPSUMMON_TIMED_DESPAWN, 10000); summon->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC); summon->SetReactState(REACT_DEFENSIVE); summon->CastSpell(summon, SPELL_ASHCROMBE_TELEPORT, true); @@ -260,13 +260,16 @@ public: uiTimer = 2000; uiPhase = 2; break; + } case 2: + { pArchmage->SummonCreature(NPC_ARUGAL_VOIDWALKER, SpawnLocation[0], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 60000); pArchmage->SummonCreature(NPC_ARUGAL_VOIDWALKER, SpawnLocation[1], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 60000); pArchmage->SummonCreature(NPC_ARUGAL_VOIDWALKER, SpawnLocation[2], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 60000); pArchmage->SummonCreature(NPC_ARUGAL_VOIDWALKER, SpawnLocation[3], TEMPSUMMON_CORPSE_TIMED_DESPAWN, 60000); uiPhase = 0; break; + } } } else uiTimer -= uiDiff; diff --git a/src/server/scripts/EasternKingdoms/Uldaman/boss_archaedas.cpp b/src/server/scripts/EasternKingdoms/Uldaman/boss_archaedas.cpp index 3ffb873e4d2..74fad4f94d8 100644 --- a/src/server/scripts/EasternKingdoms/Uldaman/boss_archaedas.cpp +++ b/src/server/scripts/EasternKingdoms/Uldaman/boss_archaedas.cpp @@ -95,14 +95,17 @@ class boss_archaedas : public CreatureScript me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); } - void ActivateMinion(uint64 uiGuid, bool bFlag) + void ActivateMinion(uint64 uiGuid, bool flag) { - Unit* pMinion = Unit::GetUnit(*me, uiGuid); + Unit* minion = Unit::GetUnit(*me, uiGuid); - if (pMinion && pMinion->isAlive()) + if (minion && minion->isAlive()) { - DoCast(pMinion, SPELL_AWAKEN_VAULT_WALKER, bFlag); - pMinion->CastSpell(pMinion, SPELL_ARCHAEDAS_AWAKEN, true); + DoCast(minion, SPELL_AWAKEN_VAULT_WALKER, flag); + minion->CastSpell(minion, SPELL_ARCHAEDAS_AWAKEN, true); + minion->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); + minion->RemoveFlag(UNIT_FIELD_FLAGS,UNIT_FLAG_DISABLE_MOVE); + minion->setFaction(14); } } diff --git a/src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp b/src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp index ade07039a23..ee82da668f8 100644 --- a/src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp +++ b/src/server/scripts/EasternKingdoms/Uldaman/instance_uldaman.cpp @@ -202,6 +202,9 @@ class instance_uldaman : public InstanceMapScript continue; archaedas->CastSpell(target, SPELL_AWAKEN_VAULT_WALKER, true); target->CastSpell(target, SPELL_ARCHAEDAS_AWAKEN, true); + target->RemoveFlag(UNIT_FIELD_FLAGS,UNIT_FLAG_DISABLE_MOVE); + target->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); + target->setFaction(14); return; // only want the first one we find } } diff --git a/src/server/scripts/EasternKingdoms/ZulAman/boss_zuljin.cpp b/src/server/scripts/EasternKingdoms/ZulAman/boss_zuljin.cpp index 1009d3e0a0a..8fb3dd55077 100644 --- a/src/server/scripts/EasternKingdoms/ZulAman/boss_zuljin.cpp +++ b/src/server/scripts/EasternKingdoms/ZulAman/boss_zuljin.cpp @@ -315,14 +315,12 @@ class boss_zuljin : public CreatureScript { for (uint8 i = 0; i < 4; ++i) { - Unit* Temp = NULL; if (SpiritGUID[i]) { - Temp = Unit::GetUnit(*me, SpiritGUID[i]); - if (Temp) + if (Unit* temp = Unit::GetUnit(*me, SpiritGUID[i])) { - Temp->SetVisible(false); - Temp->setDeathState(DEAD); + temp->SetVisible(false); + temp->setDeathState(DEAD); } } SpiritGUID[i] = 0; diff --git a/src/server/scripts/EasternKingdoms/wetlands.cpp b/src/server/scripts/EasternKingdoms/wetlands.cpp index fac8fb51c2d..34e6e7c9ddf 100644 --- a/src/server/scripts/EasternKingdoms/wetlands.cpp +++ b/src/server/scripts/EasternKingdoms/wetlands.cpp @@ -60,12 +60,12 @@ public: { npc_tapoke_slim_jahnAI(Creature* creature) : npc_escortAI(creature) { } - bool m_bFriendSummoned; + bool IsFriendSummoned; void Reset() { if (!HasEscortState(STATE_ESCORT_ESCORTING)) - m_bFriendSummoned = false; + IsFriendSummoned = false; } void WaypointReached(uint32 waypointId) @@ -83,14 +83,12 @@ public: void EnterCombat(Unit* /*who*/) { - Player* player = GetPlayerForEscort(); - - if (HasEscortState(STATE_ESCORT_ESCORTING) && !m_bFriendSummoned && player) + if (HasEscortState(STATE_ESCORT_ESCORTING) && !IsFriendSummoned && GetPlayerForEscort()) { for (uint8 i = 0; i < 3; ++i) DoCast(me, SPELL_CALL_FRIENDS, true); - m_bFriendSummoned = true; + IsFriendSummoned = true; } } diff --git a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.cpp b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.cpp index 5b6dc784113..ee7ef383603 100644 --- a/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.cpp +++ b/src/server/scripts/Kalimdor/CavernsOfTime/BattleForMountHyjal/hyjal.cpp @@ -222,11 +222,9 @@ public: ItemPosCountVec dest; uint8 msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, ITEM_TEAR_OF_GODDESS, 1); if (msg == EQUIP_ERR_OK) - { - Item* item = player->StoreNewItem(dest, ITEM_TEAR_OF_GODDESS, true); - if (item && player) + if (Item* item = player->StoreNewItem(dest, ITEM_TEAR_OF_GODDESS, true)) player->SendNewItem(item, 1, true, false, true); - } + player->SEND_GOSSIP_MENU(907, creature->GetGUID()); } return true; diff --git a/src/server/scripts/Kalimdor/silithus.cpp b/src/server/scripts/Kalimdor/silithus.cpp index 1636c867b30..1fe945b06d4 100644 --- a/src/server/scripts/Kalimdor/silithus.cpp +++ b/src/server/scripts/Kalimdor/silithus.cpp @@ -224,7 +224,6 @@ public: }; - /*### ## go_wind_stone ###*/ diff --git a/src/server/scripts/Northrend/Naxxramas/boss_gothik.cpp b/src/server/scripts/Northrend/Naxxramas/boss_gothik.cpp index 2ea234775c0..d335d36e112 100644 --- a/src/server/scripts/Northrend/Naxxramas/boss_gothik.cpp +++ b/src/server/scripts/Northrend/Naxxramas/boss_gothik.cpp @@ -314,15 +314,14 @@ class boss_gothik : public CreatureScript bool CheckGroupSplitted() { - bool checklife = false; - bool checkdead = false; - Map* map = me->GetMap(); if (map && map->IsDungeon()) { Map::PlayerList const &PlayerList = map->GetPlayers(); if (!PlayerList.isEmpty()) { + bool checklife = false; + bool checkdead = false; for (Map::PlayerList::const_iterator i = PlayerList.begin(); i != PlayerList.end(); ++i) { if (i->getSource() && i->getSource()->isAlive() && diff --git a/src/server/scripts/Northrend/dragonblight.cpp b/src/server/scripts/Northrend/dragonblight.cpp index ecc012eb25d..1f1d24453ee 100644 --- a/src/server/scripts/Northrend/dragonblight.cpp +++ b/src/server/scripts/Northrend/dragonblight.cpp @@ -79,16 +79,16 @@ public: enum StrengthenAncientsMisc { - SAY_WALKER_FRIENDLY = 0, - SAY_WALKER_ENEMY = 1, - SAY_LOTHALOR = 0, + SAY_WALKER_FRIENDLY = 0, + SAY_WALKER_ENEMY = 1, + SAY_LOTHALOR = 0, - SPELL_CREATE_ITEM_BARK = 47550, - SPELL_CONFUSED = 47044, + SPELL_CREATE_ITEM_BARK = 47550, + SPELL_CONFUSED = 47044, - NPC_LOTHALOR = 26321, + NPC_LOTHALOR = 26321, - FACTION_WALKER_ENEMY = 14, + FACTION_WALKER_ENEMY = 14, }; class spell_q12096_q12092_dummy : public SpellScriptLoader // Strengthen the Ancients: On Interact Dummy to Woodlands Walker @@ -170,9 +170,56 @@ public: } }; +/*###### +## wyrmrest_defender +######*/ + +enum WyrmDefenderEnum +{ + QUEST_DEFENDING_WYRMREST_TEMPLE = 12372, + GOSSIP_TEXTID_DEF1 = 12899, + GOSSIP_TEXTID_DEF2 = 12900, + SPELL_CHARACTER_SCRIPT = 49213 +}; + +#define GOSSIP_ITEM_1 "We need to get into the fight. Are you ready?" + +class npc_wyrmrest_defender : public CreatureScript +{ + public: + npc_wyrmrest_defender() : CreatureScript("npc_wyrmrest_defender") { } + + bool OnGossipHello(Player* player, Creature* creature) + { + if (player->GetQuestStatus(QUEST_DEFENDING_WYRMREST_TEMPLE) == QUEST_STATUS_INCOMPLETE) + { + player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); + player->SEND_GOSSIP_MENU(GOSSIP_TEXTID_DEF1, creature->GetGUID()); + } + else + player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); + + return true; + } + + bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) + { + player->PlayerTalkClass->ClearMenus(); + if (action == GOSSIP_ACTION_INFO_DEF+1) + { + player->SEND_GOSSIP_MENU(GOSSIP_TEXTID_DEF2, creature->GetGUID()); + // Makes player cast trigger spell for 49207 on self + player->CastSpell(player, SPELL_CHARACTER_SCRIPT, true); + } + + return true; + } +}; + void AddSC_dragonblight() { new npc_alexstrasza_wr_gate; new spell_q12096_q12092_dummy; new spell_q12096_q12092_bark; + new npc_wyrmrest_defender; } diff --git a/src/server/scripts/Northrend/storm_peaks.cpp b/src/server/scripts/Northrend/storm_peaks.cpp index 6bf342e4643..976a6e5dba5 100644 --- a/src/server/scripts/Northrend/storm_peaks.cpp +++ b/src/server/scripts/Northrend/storm_peaks.cpp @@ -20,6 +20,7 @@ #include "ScriptedGossip.h" #include "ScriptedEscortAI.h" #include "Vehicle.h" +#include "CombatAI.h" /*###### ## npc_agnetta_tyrsdottar @@ -131,229 +132,6 @@ public: } }; -/*###### -## npc_thorim -######*/ - -#define GOSSIP_HN "Thorim?" -#define GOSSIP_SN1 "Can you tell me what became of Sif?" -#define GOSSIP_SN2 "He did more than that, Thorim. He controls Ulduar now." -#define GOSSIP_SN3 "It needn't end this way." - -enum eThorim -{ - QUEST_SIBLING_RIVALRY = 13064, - NPC_THORIM = 29445, - GOSSIP_TEXTID_THORIM1 = 13799, - GOSSIP_TEXTID_THORIM2 = 13801, - GOSSIP_TEXTID_THORIM3 = 13802, - GOSSIP_TEXTID_THORIM4 = 13803 -}; - -class npc_thorim : public CreatureScript -{ -public: - npc_thorim() : CreatureScript("npc_thorim") { } - - bool OnGossipHello(Player* player, Creature* creature) - { - if (creature->isQuestGiver()) - player->PrepareQuestMenu(creature->GetGUID()); - - if (player->GetQuestStatus(QUEST_SIBLING_RIVALRY) == QUEST_STATUS_INCOMPLETE) { - player->ADD_GOSSIP_ITEM(0, GOSSIP_HN, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); - player->SEND_GOSSIP_MENU(GOSSIP_TEXTID_THORIM1, creature->GetGUID()); - return true; - } - return false; - } - - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) - { - player->PlayerTalkClass->ClearMenus(); - switch (action) - { - case GOSSIP_ACTION_INFO_DEF+1: - player->ADD_GOSSIP_ITEM(0, GOSSIP_SN1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2); - player->SEND_GOSSIP_MENU(GOSSIP_TEXTID_THORIM2, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+2: - player->ADD_GOSSIP_ITEM(0, GOSSIP_SN2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+3); - player->SEND_GOSSIP_MENU(GOSSIP_TEXTID_THORIM3, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+3: - player->ADD_GOSSIP_ITEM(0, GOSSIP_SN3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+4); - player->SEND_GOSSIP_MENU(GOSSIP_TEXTID_THORIM4, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+4: - player->CLOSE_GOSSIP_MENU(); - player->CompleteQuest(QUEST_SIBLING_RIVALRY); - break; - } - return true; - } -}; - -/*###### -## npc_victorious_challenger -######*/ - -#define GOSSIP_CHALLENGER "Let's do this, sister." - -enum eVictoriousChallenger -{ - QUEST_TAKING_ALL_CHALLENGERS = 12971, - QUEST_DEFENDING_YOUR_TITLE = 13423, - - SPELL_SUNDER_ARMOR = 11971, - SPELL_REND_VC = 11977 -}; - -class npc_victorious_challenger : public CreatureScript -{ -public: - npc_victorious_challenger() : CreatureScript("npc_victorious_challenger") { } - - struct npc_victorious_challengerAI : public ScriptedAI - { - npc_victorious_challengerAI(Creature* creature) : ScriptedAI(creature) {} - - uint32 SunderArmorTimer; - uint32 RendTimer; - - void Reset() - { - me->RestoreFaction(); - - SunderArmorTimer = 10000; - RendTimer = 15000; - } - - void UpdateAI(const uint32 diff) - { - //Return since we have no target - if (!UpdateVictim()) - return; - - if (RendTimer < diff) - { - DoCast(me->getVictim(), SPELL_REND_VC, true); - RendTimer = 15000; - }else RendTimer -= diff; - - if (SunderArmorTimer < diff) - { - DoCast(me->getVictim(), SPELL_SUNDER_ARMOR, true); - SunderArmorTimer = 10000; - }else SunderArmorTimer -= diff; - - DoMeleeAttackIfReady(); - } - - void KilledUnit(Unit* /*victim*/) - { - me->RestoreFaction(); - } - - }; - - bool OnGossipHello(Player* player, Creature* creature) - { - if (creature->isQuestGiver()) - player->PrepareQuestMenu(creature->GetGUID()); - - if (player->GetQuestStatus(QUEST_TAKING_ALL_CHALLENGERS) == QUEST_STATUS_INCOMPLETE || player->GetQuestStatus(QUEST_DEFENDING_YOUR_TITLE) == QUEST_STATUS_INCOMPLETE) - { - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_CHALLENGER, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); - player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); - return true; - } - - return false; - } - - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) - { - player->PlayerTalkClass->ClearMenus(); - if (action == GOSSIP_ACTION_INFO_DEF+1) - { - player->CLOSE_GOSSIP_MENU(); - creature->setFaction(14); - creature->AI()->AttackStart(player); - } - - return true; - } - - CreatureAI* GetAI(Creature* creature) const - { - return new npc_victorious_challengerAI(creature); - } -}; - -/*###### -## npc_loklira_crone -######*/ - -#define GOSSIP_LOKLIRACRONE "Tell me about this proposal" -#define GOSSIP_LOKLIRACRONE1 "What happened then?" -#define GOSSIP_LOKLIRACRONE2 "You want me to take part in the Hyldsmeet to end the war?" -#define GOSSIP_LOKLIRACRONE3 "Very well. I'll take part in this competition." - -enum eLokliraCrone -{ - QUEST_HYLDSMEET = 12970, - - GOSSIP_TEXTID_LOK1 = 13778, - GOSSIP_TEXTID_LOK2 = 13779, - GOSSIP_TEXTID_LOK3 = 13780 -}; - -class npc_loklira_crone : public CreatureScript -{ -public: - npc_loklira_crone() : CreatureScript("npc_loklira_crone") { } - - bool OnGossipHello(Player* player, Creature* creature) - { - if (creature->isQuestGiver()) - player->PrepareQuestMenu(creature->GetGUID()); - - if (player->GetQuestStatus(QUEST_HYLDSMEET) == QUEST_STATUS_INCOMPLETE) - { - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_LOKLIRACRONE, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); - player->SEND_GOSSIP_MENU(player->GetGossipTextId(creature), creature->GetGUID()); - return true; - } - return false; - } - - bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) - { - player->PlayerTalkClass->ClearMenus(); - switch (action) - { - case GOSSIP_ACTION_INFO_DEF+1: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_LOKLIRACRONE1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2); - player->SEND_GOSSIP_MENU(GOSSIP_TEXTID_LOK1, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+2: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_LOKLIRACRONE2, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+3); - player->SEND_GOSSIP_MENU(GOSSIP_TEXTID_LOK2, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+3: - player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_LOKLIRACRONE3, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+4); - player->SEND_GOSSIP_MENU(GOSSIP_TEXTID_LOK3, creature->GetGUID()); - break; - case GOSSIP_ACTION_INFO_DEF+4: - player->CLOSE_GOSSIP_MENU(); - player->CompleteQuest(QUEST_HYLDSMEET); - break; - } - return true; - } -}; - ///////////////////// ///npc_injured_goblin ///////////////////// @@ -506,14 +284,12 @@ public: ## npc_brunnhildar_prisoner ######*/ -enum brunhildar { - NPC_QUEST_GIVER = 29592, - +enum BrunnhildarPrisoner { SPELL_ICE_PRISON = 54894, - SPELL_KILL_CREDIT_PRISONER = 55144, - SPELL_KILL_CREDIT_DRAKE = 55143, - SPELL_SUMMON_LIBERATED = 55073, - SPELL_ICE_LANCE = 55046 + SPELL_ICE_LANCE = 55046, + SPELL_FREE_PRISONER = 55048, + SPELL_RIDE_DRAKE = 55074, + SPELL_SHARD_IMPACT = 55047 }; class npc_brunnhildar_prisoner : public CreatureScript @@ -525,129 +301,169 @@ public: { npc_brunnhildar_prisonerAI(Creature* creature) : ScriptedAI(creature) {} - uint64 drakeGUID; - uint16 enter_timer; - bool hasEmptySeats; + bool freed; void Reset() { + freed = false; me->CastSpell(me, SPELL_ICE_PRISON, true); - enter_timer = 0; - drakeGUID = 0; - hasEmptySeats = false; } - void UpdateAI(const uint32 diff) + void JustRespawned() + { + Reset(); + } + + void UpdateAI(const uint32 /*diff*/) { - //TODO: not good script - if (!drakeGUID) + if (!freed) return; - Creature* drake = Unit::GetCreature(*me, drakeGUID); - if (!drake) + if (!me->HasUnitState(UNIT_STATE_ONVEHICLE)) { - drakeGUID = 0; - return; + me->DespawnOrUnsummon(); } + } - // drake unsummoned, passengers dropped - if (!me->IsOnVehicle(drake) && !hasEmptySeats) - me->DespawnOrUnsummon(3000); - - if (enter_timer <= 0) + void SpellHit(Unit* caster, const SpellInfo* spell) + { + if (spell->Id != SPELL_ICE_LANCE) return; - if (enter_timer < diff) + if (caster->GetVehicleKit()->GetAvailableSeatCount() != 0) { - enter_timer = 0; - if (hasEmptySeats) - me->JumpTo(drake, 25.0f); - else - Reset(); + me->CastSpell(me, SPELL_FREE_PRISONER, true); + me->CastSpell(caster, SPELL_RIDE_DRAKE, true); + me->CastSpell(me, SPELL_SHARD_IMPACT, true); + freed = true; } - else - enter_timer -= diff; + } + }; + + CreatureAI* GetAI(Creature* creature) const + { + return new npc_brunnhildar_prisonerAI(creature); + } +}; + +/*###### +## npc_freed_protodrake +######*/ + +enum FreedProtoDrake +{ + AREA_VALLEY_OF_ANCIENT_WINTERS = 4437, + TEXT_EMOTE = 0, + SPELL_KILL_CREDIT_PRISONER = 55144, + SPELL_SUMMON_LIBERATED = 55073, + SPELL_KILL_CREDIT_DRAKE = 55143 +}; + +const Position FreedDrakeWaypoints[16] = +{ + {7294.96f, -2418.733f, 823.869f, 0.0f}, + {7315.984f, -2331.46f, 826.3972f, 0.0f}, + {7271.826f, -2271.479f, 833.5917f, 0.0f}, + {7186.253f, -2218.475f, 847.5632f, 0.0f}, + {7113.195f, -2164.288f, 850.2301f, 0.0f}, + {7078.018f, -2063.106f, 854.7581f, 0.0f}, + {7073.221f, -1983.382f, 861.9246f, 0.0f}, + {7061.455f, -1885.899f, 865.119f, 0.0f}, + {7033.32f, -1826.775f, 876.2578f, 0.0f}, + {6999.902f, -1784.012f, 897.4521f, 0.0f}, + {6954.913f, -1747.043f, 897.4521f, 0.0f}, + {6933.856f, -1720.698f, 882.2022f, 0.0f}, + {6932.729f, -1687.306f, 866.1189f, 0.0f}, + {6952.458f, -1663.802f, 849.8133f, 0.0f}, + {7002.819f, -1651.681f, 831.397f, 0.0f}, + {7026.531f, -1649.239f, 828.8406f, 0.0f} +}; + + +class npc_freed_protodrake : public CreatureScript +{ +public: + npc_freed_protodrake() : CreatureScript("npc_freed_protodrake") { } + + struct npc_freed_protodrakeAI : public VehicleAI + { + npc_freed_protodrakeAI(Creature* creature) : VehicleAI(creature) {} + + bool autoMove; + bool wpReached; + uint16 CheckTimer; + uint16 countWP; + + void Reset() + { + autoMove = false; + wpReached = false; + CheckTimer = 5000; + countWP = 0; } - void MoveInLineOfSight(Unit* who) + void MovementInform(uint32 type, uint32 id) { - if (!who || !drakeGUID) + if (type != POINT_MOTION_TYPE) return; - Creature* drake = Unit::GetCreature(*me, drakeGUID); - if (!drake) + if (id < 15) { - drakeGUID = 0; - return; + ++countWP; + wpReached = true; } - - if (!me->IsOnVehicle(drake) && !me->HasAura(SPELL_ICE_PRISON)) + else + // drake reached village { - if (who->IsVehicle() && me->IsWithinDist(who, 25.0f, true) && who->ToCreature() && who->ToCreature()->GetEntry() == 29709) + // get player that rides drake (from seat 0) + Unit* player = me->GetVehicleKit()->GetPassenger(0); + if (player && player->GetTypeId() == TYPEID_PLAYER) { - uint8 seat = who->GetVehicleKit()->GetNextEmptySeat(0, true); - if (seat <= 0) - return; - - me->EnterVehicle(who, seat); - me->SendMovementFlagUpdate(); - hasEmptySeats = false; + // for each prisoner on drake,give credit + for (uint8 i = 1; i < 4; ++i) + if (Unit* prisoner = me->GetVehicleKit()->GetPassenger(i)) + { + if (prisoner->GetTypeId() != TYPEID_UNIT) + return; + prisoner->CastSpell(player, SPELL_KILL_CREDIT_PRISONER, true); + prisoner->CastSpell(prisoner, SPELL_SUMMON_LIBERATED, true); + prisoner->ExitVehicle(); + } + me->CastSpell(me, SPELL_KILL_CREDIT_DRAKE, true); + player->ExitVehicle(); } } + } - if (who->ToCreature() && me->IsOnVehicle(drake)) + void UpdateAI(const uint32 diff) + { + if (!autoMove) { - if (who->ToCreature()->GetEntry() == NPC_QUEST_GIVER && me->IsWithinDist(who, 15.0f, false)) + if (CheckTimer < diff) { - Unit* rider = drake->GetVehicleKit()->GetPassenger(0); - if (!rider) - return; - - rider->CastSpell(rider, SPELL_KILL_CREDIT_PRISONER, true); - - me->ExitVehicle(); - me->CastSpell(me, SPELL_SUMMON_LIBERATED, true); - me->DespawnOrUnsummon(500); - - // drake is empty now, deliver credit for drake and despawn him - if (drake->GetVehicleKit()->HasEmptySeat(1) && - drake->GetVehicleKit()->HasEmptySeat(2) && - drake->GetVehicleKit()->HasEmptySeat(3)) + CheckTimer = 5000; + if (me->GetAreaId() == AREA_VALLEY_OF_ANCIENT_WINTERS) { - // not working rider->CastSpell(rider, SPELL_KILL_CREDIT_DRAKE, true); - if (rider->ToPlayer()) - rider->ToPlayer()->KilledMonsterCredit(29709, 0); - - drake->DespawnOrUnsummon(0); + Talk(TEXT_EMOTE, me->GetVehicleKit()->GetPassenger(0)->GetGUID()); + autoMove = true; + wpReached = true; } } + else + CheckTimer -= diff; } - } - - void SpellHit(Unit* hitter, const SpellInfo* spell) - { - if (!hitter || !spell) - return; - - if (spell->Id != SPELL_ICE_LANCE) - return; - - me->RemoveAura(SPELL_ICE_PRISON); - enter_timer = 500; - if (hitter->IsVehicle()) - drakeGUID = hitter->GetGUID(); - else - return; - - if (hitter->GetVehicleKit()->GetNextEmptySeat(0, true)) - hasEmptySeats = true; + if (wpReached && autoMove) + { + wpReached = false; + me->GetMotionMaster()->MovePoint(countWP, FreedDrakeWaypoints[countWP]); + } } }; CreatureAI* GetAI(Creature* creature) const { - return new npc_brunnhildar_prisonerAI(creature); + return new npc_freed_protodrakeAI(creature); } }; @@ -752,12 +568,10 @@ void AddSC_storm_peaks() { new npc_agnetta_tyrsdottar(); new npc_frostborn_scout(); - new npc_thorim(); - new npc_victorious_challenger(); - new npc_loklira_crone(); new npc_injured_goblin(); new npc_roxi_ramrocket(); new npc_brunnhildar_prisoner(); + new npc_freed_protodrake(); new npc_icefang(); new npc_hyldsmeet_protodrake(); } diff --git a/src/server/scripts/Northrend/wintergrasp.cpp b/src/server/scripts/Northrend/wintergrasp.cpp index fc967acf9e2..59e9a31c4cf 100644 --- a/src/server/scripts/Northrend/wintergrasp.cpp +++ b/src/server/scripts/Northrend/wintergrasp.cpp @@ -119,8 +119,6 @@ class npc_wg_demolisher_engineer : public CreatureScript if (creature->isQuestGiver()) player->PrepareQuestMenu(creature->GetGUID()); - Battlefield* wintergrasp = sBattlefieldMgr->GetBattlefieldByBattleId(BATTLEFIELD_BATTLEID_WG); - if (canBuild(creature)) { if (player->HasAura(SPELL_CORPORAL)) @@ -143,8 +141,6 @@ class npc_wg_demolisher_engineer : public CreatureScript { player->CLOSE_GOSSIP_MENU(); - Battlefield* wintergrasp= sBattlefieldMgr->GetBattlefieldByBattleId(BATTLEFIELD_BATTLEID_WG); - if (canBuild(creature)) { switch (action - GOSSIP_ACTION_INFO_DEF) @@ -169,9 +165,9 @@ class npc_wg_demolisher_engineer : public CreatureScript bool canBuild(Creature* creature) { Battlefield* wintergrasp = sBattlefieldMgr->GetBattlefieldByBattleId(BATTLEFIELD_BATTLEID_WG); - if (!wintergrasp) return false; + switch (creature->GetEntry()) { case NPC_GOBLIN_MECHANIC: @@ -207,7 +203,7 @@ class npc_wg_spirit_guide : public CreatureScript return true; } - bool OnGossipSelect(Player* player, Creature* /*creature*/ , uint32 /*sender */ , uint32 action) + bool OnGossipSelect(Player* player, Creature* /*creature*/, uint32 /*sender*/, uint32 action) { player->CLOSE_GOSSIP_MENU(); @@ -307,15 +303,13 @@ class go_wg_vehicle_teleporter : public GameObjectScript { if (_checkTimer <= diff) { - // Tabulation madness in the hole! - for (uint8 i = 0; i < MAX_WINTERGRASP_VEHICLES; i++) - if (Creature* vehicleCreature = go->FindNearestCreature(vehiclesList[i], 3.0f, true)) - if (!vehicleCreature->HasAura(SPELL_VEHICLE_TELEPORT)) - if (Vehicle* vehicle = vehicleCreature->GetVehicle()) - if (Unit* passenger = vehicle->GetPassenger(0)) - if (go->GetUInt32Value(GAMEOBJECT_FACTION) == passenger->getFaction()) - if (Creature* teleportTrigger = vehicleCreature->FindNearestCreature(NPC_WORLD_TRIGGER_LARGE_AOI_NOT_IMMUNE_PC_NPC, 100.0f, true)) - teleportTrigger->CastSpell(vehicleCreature, SPELL_VEHICLE_TELEPORT, true); + if (Battlefield* wg = sBattlefieldMgr->GetBattlefieldByBattleId(BATTLEFIELD_BATTLEID_WG)) + // Tabulation madness in the hole! + for (uint8 i = 0; i < MAX_WINTERGRASP_VEHICLES; i++) + if (Creature* vehicleCreature = go->FindNearestCreature(vehiclesList[i], 3.0f, true)) + if (!vehicleCreature->HasAura(SPELL_VEHICLE_TELEPORT) && vehicleCreature->getFaction() == WintergraspFaction[wg->GetDefenderTeam()]) + if (Creature* teleportTrigger = vehicleCreature->FindNearestCreature(NPC_WORLD_TRIGGER_LARGE_AOI_NOT_IMMUNE_PC_NPC, 100.0f, true)) + teleportTrigger->CastSpell(vehicleCreature, SPELL_VEHICLE_TELEPORT, true); _checkTimer = 1000; } @@ -326,7 +320,7 @@ class go_wg_vehicle_teleporter : public GameObjectScript uint32 _checkTimer; }; - GameObjectAI* GetGameObjectAI(GameObject* go) const + GameObjectAI* GetAI(GameObject* go) const { return new go_wg_vehicle_teleporterAI(go); } @@ -508,7 +502,7 @@ class spell_wintergrasp_grab_passenger : public SpellScriptLoader void HandleScript(SpellEffIndex /*effIndex*/) { if (Player* target = GetHitPlayer()) - target->CastSpell(GetCaster(), SPELL_RIDE_WG_VEHICLE, true); + target->CastSpell(GetCaster(), SPELL_RIDE_WG_VEHICLE, false); } void Register() @@ -547,6 +541,36 @@ public: } }; +class spell_wintergrasp_defender_teleport : public SpellScriptLoader +{ +public: + spell_wintergrasp_defender_teleport() : SpellScriptLoader("spell_wintergrasp_defender_teleport") { } + + class spell_wintergrasp_defender_teleport_SpellScript : public SpellScript + { + PrepareSpellScript(spell_wintergrasp_defender_teleport_SpellScript); + + SpellCastResult CheckCast() + { + if (Battlefield* wg = sBattlefieldMgr->GetBattlefieldByBattleId(BATTLEFIELD_BATTLEID_WG)) + if (Player* target = GetExplTargetUnit()->ToPlayer()) + if (target->GetTeamId() != wg->GetDefenderTeam()) + return SPELL_FAILED_BAD_TARGETS; + return SPELL_CAST_OK; + } + + void Register() + { + OnCheckCast += SpellCheckCastFn(spell_wintergrasp_defender_teleport_SpellScript::CheckCast); + } + }; + + SpellScript* GetSpellScript() const + { + return new spell_wintergrasp_defender_teleport_SpellScript(); + } +}; + void AddSC_wintergrasp() { new npc_wg_queue(); @@ -557,4 +581,5 @@ void AddSC_wintergrasp() new spell_wintergrasp_force_building(); new spell_wintergrasp_grab_passenger(); new achievement_wg_didnt_stand_a_chance(); + new spell_wintergrasp_defender_teleport(); } diff --git a/src/server/scripts/OutdoorPvP/CMakeLists.txt b/src/server/scripts/OutdoorPvP/CMakeLists.txt index 237b974aa9d..15d7dbd7e8d 100644 --- a/src/server/scripts/OutdoorPvP/CMakeLists.txt +++ b/src/server/scripts/OutdoorPvP/CMakeLists.txt @@ -17,8 +17,6 @@ set(scripts_STAT_SRCS OutdoorPvP/OutdoorPvPNA.cpp OutdoorPvP/OutdoorPvPHP.cpp OutdoorPvP/OutdoorPvPTF.h - OutdoorPvP/OutdoorPvPEP.h - OutdoorPvP/OutdoorPvPEP.cpp OutdoorPvP/OutdoorPvPHP.h OutdoorPvP/OutdoorPvPZM.h OutdoorPvP/OutdoorPvPNA.h diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPEP.cpp b/src/server/scripts/OutdoorPvP/OutdoorPvPEP.cpp deleted file mode 100755 index 2a94ddb3134..00000000000 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPEP.cpp +++ /dev/null @@ -1,785 +0,0 @@ -/* - * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -#include "ScriptMgr.h" -#include "OutdoorPvPEP.h" -#include "WorldPacket.h" -#include "Player.h" -#include "GameObject.h" -#include "ObjectMgr.h" -#include "ObjectAccessor.h" -#include "OutdoorPvPMgr.h" -#include "Creature.h" -#include "Language.h" -#include "World.h" -#include "GossipDef.h" - -OPvPCapturePointEP_EWT::OPvPCapturePointEP_EWT(OutdoorPvP* pvp) -: OPvPCapturePoint(pvp), m_TowerState(EP_TS_N), m_UnitsSummonedSide(0) -{ - SetCapturePointData(EPCapturePoints[EP_EWT].entry, EPCapturePoints[EP_EWT].map, EPCapturePoints[EP_EWT].x, EPCapturePoints[EP_EWT].y, EPCapturePoints[EP_EWT].z, EPCapturePoints[EP_EWT].o, EPCapturePoints[EP_EWT].rot0, EPCapturePoints[EP_EWT].rot1, EPCapturePoints[EP_EWT].rot2, EPCapturePoints[EP_EWT].rot3); - AddObject(EP_EWT_FLAGS, EPTowerFlags[EP_EWT].entry, EPTowerFlags[EP_EWT].map, EPTowerFlags[EP_EWT].x, EPTowerFlags[EP_EWT].y, EPTowerFlags[EP_EWT].z, EPTowerFlags[EP_EWT].o, EPTowerFlags[EP_EWT].rot0, EPTowerFlags[EP_EWT].rot1, EPTowerFlags[EP_EWT].rot2, EPTowerFlags[EP_EWT].rot3); -} - -void OPvPCapturePointEP_EWT::ChangeState() -{ - // if changing from controlling alliance to horde or vice versa - if ( m_OldState == OBJECTIVESTATE_ALLIANCE && m_OldState != m_State ) - { - sWorld->SendZoneText(EP_GraveYardZone, sObjectMgr->GetTrinityStringForDBCLocale(LANG_OPVP_EP_LOSE_EWT_A)); - ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_EWT, 0); - } - else if ( m_OldState == OBJECTIVESTATE_HORDE && m_OldState != m_State ) - { - sWorld->SendZoneText(EP_GraveYardZone, sObjectMgr->GetTrinityStringForDBCLocale(LANG_OPVP_EP_LOSE_EWT_H)); - ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_EWT, 0); - } - - uint32 artkit = 21; - - switch (m_State) - { - case OBJECTIVESTATE_ALLIANCE: - m_TowerState = EP_TS_A; - artkit = 2; - SummonSupportUnitAtNorthpassTower(ALLIANCE); - ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_EWT, ALLIANCE); - if (m_OldState != m_State) sWorld->SendZoneText(EP_GraveYardZone, sObjectMgr->GetTrinityStringForDBCLocale(LANG_OPVP_EP_CAPTURE_EWT_A)); - break; - case OBJECTIVESTATE_HORDE: - m_TowerState = EP_TS_H; - artkit = 1; - SummonSupportUnitAtNorthpassTower(HORDE); - ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_EWT, HORDE); - if (m_OldState != m_State) sWorld->SendZoneText(EP_GraveYardZone, sObjectMgr->GetTrinityStringForDBCLocale(LANG_OPVP_EP_CAPTURE_EWT_H)); - break; - case OBJECTIVESTATE_NEUTRAL: - m_TowerState = EP_TS_N; - break; - case OBJECTIVESTATE_NEUTRAL_ALLIANCE_CHALLENGE: - case OBJECTIVESTATE_HORDE_ALLIANCE_CHALLENGE: - m_TowerState = EP_TS_N_A; - break; - case OBJECTIVESTATE_NEUTRAL_HORDE_CHALLENGE: - case OBJECTIVESTATE_ALLIANCE_HORDE_CHALLENGE: - m_TowerState = EP_TS_N_H; - break; - } - - GameObject* flag = HashMapHolder<GameObject>::Find(m_capturePointGUID); - GameObject* flag2 = HashMapHolder<GameObject>::Find(m_Objects[EP_EWT_FLAGS]); - if (flag) - { - flag->SetGoArtKit(artkit); - } - if (flag2) - { - flag2->SetGoArtKit(artkit); - } - - UpdateTowerState(); - - // complete quest objective - if (m_TowerState == EP_TS_A || m_TowerState == EP_TS_H) - SendObjectiveComplete(EP_EWT_CM, 0); -} - -void OPvPCapturePointEP_EWT::SendChangePhase() -{ - // send this too, sometimes the slider disappears, dunno why :( - SendUpdateWorldState(EP_UI_TOWER_SLIDER_DISPLAY, 1); - // send these updates to only the ones in this objective - uint32 phase = (uint32)ceil((m_value + m_maxValue) / (2 * m_maxValue) * 100.0f); - SendUpdateWorldState(EP_UI_TOWER_SLIDER_POS, phase); - // send this too, sometimes it resets :S - SendUpdateWorldState(EP_UI_TOWER_SLIDER_N, m_neutralValuePct); -} - -void OPvPCapturePointEP_EWT::FillInitialWorldStates(WorldPacket &data) -{ - data << EP_EWT_A << uint32(bool(m_TowerState & EP_TS_A)); - data << EP_EWT_H << uint32(bool(m_TowerState & EP_TS_H)); - data << EP_EWT_N_A << uint32(bool(m_TowerState & EP_TS_N_A)); - data << EP_EWT_N_H << uint32(bool(m_TowerState & EP_TS_N_H)); - data << EP_EWT_N << uint32(bool(m_TowerState & EP_TS_N)); -} - -void OPvPCapturePointEP_EWT::UpdateTowerState() -{ - m_PvP->SendUpdateWorldState(EP_EWT_A, bool(m_TowerState & EP_TS_A)); - m_PvP->SendUpdateWorldState(EP_EWT_H, bool(m_TowerState & EP_TS_H)); - m_PvP->SendUpdateWorldState(EP_EWT_N_A, bool(m_TowerState & EP_TS_N_A)); - m_PvP->SendUpdateWorldState(EP_EWT_N_H, bool(m_TowerState & EP_TS_N_H)); - m_PvP->SendUpdateWorldState(EP_EWT_N, bool(m_TowerState & EP_TS_N)); -} - -bool OPvPCapturePointEP_EWT::HandlePlayerEnter(Player* player) -{ - if (OPvPCapturePoint::HandlePlayerEnter(player)) - { - player->SendUpdateWorldState(EP_UI_TOWER_SLIDER_DISPLAY, 1); - uint32 phase = (uint32)ceil((m_value + m_maxValue) / (2 * m_maxValue) * 100.0f); - player->SendUpdateWorldState(EP_UI_TOWER_SLIDER_POS, phase); - player->SendUpdateWorldState(EP_UI_TOWER_SLIDER_N, m_neutralValuePct); - return true; - } - return false; -} - -void OPvPCapturePointEP_EWT::HandlePlayerLeave(Player* player) -{ - player->SendUpdateWorldState(EP_UI_TOWER_SLIDER_DISPLAY, 0); - OPvPCapturePoint::HandlePlayerLeave(player); -} - -void OPvPCapturePointEP_EWT::SummonSupportUnitAtNorthpassTower(uint32 team) -{ - if (m_UnitsSummonedSide != team) - { - m_UnitsSummonedSide = team; - const creature_type * ct = NULL; - if (team == ALLIANCE) - ct=EP_EWT_Summons_A; - else - ct=EP_EWT_Summons_H; - - for (uint8 i = 0; i < EP_EWT_NUM_CREATURES; ++i) - { - DelCreature(i); - AddCreature(i, ct[i].entry, ct[i].teamval, ct[i].map, ct[i].x, ct[i].y, ct[i].z, ct[i].o, 1000000); - } - } -} - -// NPT -OPvPCapturePointEP_NPT::OPvPCapturePointEP_NPT(OutdoorPvP* pvp) -: OPvPCapturePoint(pvp), m_TowerState(EP_TS_N), m_SummonedGOSide(0) -{ - SetCapturePointData(EPCapturePoints[EP_NPT].entry, EPCapturePoints[EP_NPT].map, EPCapturePoints[EP_NPT].x, EPCapturePoints[EP_NPT].y, EPCapturePoints[EP_NPT].z, EPCapturePoints[EP_NPT].o, EPCapturePoints[EP_NPT].rot0, EPCapturePoints[EP_NPT].rot1, EPCapturePoints[EP_NPT].rot2, EPCapturePoints[EP_NPT].rot3); - AddObject(EP_NPT_FLAGS, EPTowerFlags[EP_NPT].entry, EPTowerFlags[EP_NPT].map, EPTowerFlags[EP_NPT].x, EPTowerFlags[EP_NPT].y, EPTowerFlags[EP_NPT].z, EPTowerFlags[EP_NPT].o, EPTowerFlags[EP_NPT].rot0, EPTowerFlags[EP_NPT].rot1, EPTowerFlags[EP_NPT].rot2, EPTowerFlags[EP_NPT].rot3); -} - -void OPvPCapturePointEP_NPT::ChangeState() -{ - // if changing from controlling alliance to horde or vice versa - if ( m_OldState == OBJECTIVESTATE_ALLIANCE && m_OldState != m_State ) - { - sWorld->SendZoneText(EP_GraveYardZone, sObjectMgr->GetTrinityStringForDBCLocale(LANG_OPVP_EP_LOSE_NPT_A)); - ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_NPT, 0); - } - else if ( m_OldState == OBJECTIVESTATE_HORDE && m_OldState != m_State ) - { - sWorld->SendZoneText(EP_GraveYardZone, sObjectMgr->GetTrinityStringForDBCLocale(LANG_OPVP_EP_LOSE_NPT_H)); - ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_NPT, 0); - } - - uint32 artkit = 21; - - switch (m_State) - { - case OBJECTIVESTATE_ALLIANCE: - m_TowerState = EP_TS_A; - artkit = 2; - SummonGO(ALLIANCE); - ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_NPT, ALLIANCE); - if (m_OldState != m_State) sWorld->SendZoneText(EP_GraveYardZone, sObjectMgr->GetTrinityStringForDBCLocale(LANG_OPVP_EP_CAPTURE_NPT_A)); - break; - case OBJECTIVESTATE_HORDE: - m_TowerState = EP_TS_H; - artkit = 1; - SummonGO(HORDE); - ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_NPT, HORDE); - if (m_OldState != m_State) sWorld->SendZoneText(EP_GraveYardZone, sObjectMgr->GetTrinityStringForDBCLocale(LANG_OPVP_EP_CAPTURE_NPT_H)); - break; - case OBJECTIVESTATE_NEUTRAL: - m_TowerState = EP_TS_N; - m_SummonedGOSide = 0; - DelObject(EP_NPT_BUFF); - break; - case OBJECTIVESTATE_NEUTRAL_ALLIANCE_CHALLENGE: - m_TowerState = EP_TS_N_A; - break; - case OBJECTIVESTATE_HORDE_ALLIANCE_CHALLENGE: - m_TowerState = EP_TS_N_A; - m_SummonedGOSide = 0; - DelObject(EP_NPT_BUFF); - break; - case OBJECTIVESTATE_NEUTRAL_HORDE_CHALLENGE: - m_TowerState = EP_TS_N_H; - break; - case OBJECTIVESTATE_ALLIANCE_HORDE_CHALLENGE: - m_TowerState = EP_TS_N_H; - m_SummonedGOSide = 0; - DelObject(EP_NPT_BUFF); - break; - } - - GameObject* flag = HashMapHolder<GameObject>::Find(m_capturePointGUID); - GameObject* flag2 = HashMapHolder<GameObject>::Find(m_Objects[EP_NPT_FLAGS]); - if (flag) - { - flag->SetGoArtKit(artkit); - } - if (flag2) - { - flag2->SetGoArtKit(artkit); - } - - UpdateTowerState(); - - // complete quest objective - if (m_TowerState == EP_TS_A || m_TowerState == EP_TS_H) - SendObjectiveComplete(EP_NPT_CM, 0); -} - -void OPvPCapturePointEP_NPT::SendChangePhase() -{ - // send this too, sometimes the slider disappears, dunno why :( - SendUpdateWorldState(EP_UI_TOWER_SLIDER_DISPLAY, 1); - // send these updates to only the ones in this objective - uint32 phase = (uint32)ceil((m_value + m_maxValue) / (2 * m_maxValue) * 100.0f); - SendUpdateWorldState(EP_UI_TOWER_SLIDER_POS, phase); - // send this too, sometimes it resets :S - SendUpdateWorldState(EP_UI_TOWER_SLIDER_N, m_neutralValuePct); -} - -void OPvPCapturePointEP_NPT::FillInitialWorldStates(WorldPacket &data) -{ - data << EP_NPT_A << uint32(bool(m_TowerState & EP_TS_A)); - data << EP_NPT_H << uint32(bool(m_TowerState & EP_TS_H)); - data << EP_NPT_N_A << uint32(bool(m_TowerState & EP_TS_N_A)); - data << EP_NPT_N_H << uint32(bool(m_TowerState & EP_TS_N_H)); - data << EP_NPT_N << uint32(bool(m_TowerState & EP_TS_N)); -} - -void OPvPCapturePointEP_NPT::UpdateTowerState() -{ - m_PvP->SendUpdateWorldState(EP_NPT_A, bool(m_TowerState & EP_TS_A)); - m_PvP->SendUpdateWorldState(EP_NPT_H, bool(m_TowerState & EP_TS_H)); - m_PvP->SendUpdateWorldState(EP_NPT_N_A, bool(m_TowerState & EP_TS_N_A)); - m_PvP->SendUpdateWorldState(EP_NPT_N_H, bool(m_TowerState & EP_TS_N_H)); - m_PvP->SendUpdateWorldState(EP_NPT_N, bool(m_TowerState & EP_TS_N)); -} - -bool OPvPCapturePointEP_NPT::HandlePlayerEnter(Player* player) -{ - if (OPvPCapturePoint::HandlePlayerEnter(player)) - { - player->SendUpdateWorldState(EP_UI_TOWER_SLIDER_DISPLAY, 1); - uint32 phase = (uint32)ceil((m_value + m_maxValue) / (2 * m_maxValue) * 100.0f); - player->SendUpdateWorldState(EP_UI_TOWER_SLIDER_POS, phase); - player->SendUpdateWorldState(EP_UI_TOWER_SLIDER_N, m_neutralValuePct); - return true; - } - return false; -} - -void OPvPCapturePointEP_NPT::HandlePlayerLeave(Player* player) -{ - player->SendUpdateWorldState(EP_UI_TOWER_SLIDER_DISPLAY, 0); - OPvPCapturePoint::HandlePlayerLeave(player); -} - -void OPvPCapturePointEP_NPT::SummonGO(uint32 team) -{ - if (m_SummonedGOSide != team) - { - m_SummonedGOSide = team; - DelObject(EP_NPT_BUFF); - AddObject(EP_NPT_BUFF, EP_NPT_LordaeronShrine.entry, EP_NPT_LordaeronShrine.map, EP_NPT_LordaeronShrine.x, EP_NPT_LordaeronShrine.y, EP_NPT_LordaeronShrine.z, EP_NPT_LordaeronShrine.o, EP_NPT_LordaeronShrine.rot0, EP_NPT_LordaeronShrine.rot1, EP_NPT_LordaeronShrine.rot2, EP_NPT_LordaeronShrine.rot3); - GameObject* go = HashMapHolder<GameObject>::Find(m_Objects[EP_NPT_BUFF]); - if (go) - go->SetUInt32Value(GAMEOBJECT_FACTION, (team == ALLIANCE ? 84 : 83)); - } -} - -// CGT -OPvPCapturePointEP_CGT::OPvPCapturePointEP_CGT(OutdoorPvP* pvp) -: OPvPCapturePoint(pvp), m_TowerState(EP_TS_N), m_GraveyardSide(0) -{ - SetCapturePointData(EPCapturePoints[EP_CGT].entry, EPCapturePoints[EP_CGT].map, EPCapturePoints[EP_CGT].x, EPCapturePoints[EP_CGT].y, EPCapturePoints[EP_CGT].z, EPCapturePoints[EP_CGT].o, EPCapturePoints[EP_CGT].rot0, EPCapturePoints[EP_CGT].rot1, EPCapturePoints[EP_CGT].rot2, EPCapturePoints[EP_CGT].rot3); - AddObject(EP_CGT_FLAGS, EPTowerFlags[EP_CGT].entry, EPTowerFlags[EP_CGT].map, EPTowerFlags[EP_CGT].x, EPTowerFlags[EP_CGT].y, EPTowerFlags[EP_CGT].z, EPTowerFlags[EP_CGT].o, EPTowerFlags[EP_CGT].rot0, EPTowerFlags[EP_CGT].rot1, EPTowerFlags[EP_CGT].rot2, EPTowerFlags[EP_CGT].rot3); -} - -void OPvPCapturePointEP_CGT::ChangeState() -{ - // if changing from controlling alliance to horde or vice versa - if ( m_OldState == OBJECTIVESTATE_ALLIANCE && m_OldState != m_State ) - { - sWorld->SendZoneText(EP_GraveYardZone, sObjectMgr->GetTrinityStringForDBCLocale(LANG_OPVP_EP_LOSE_CGT_A)); - ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_CGT, 0); - } - else if ( m_OldState == OBJECTIVESTATE_HORDE && m_OldState != m_State ) - { - sWorld->SendZoneText(EP_GraveYardZone, sObjectMgr->GetTrinityStringForDBCLocale(LANG_OPVP_EP_LOSE_CGT_H)); - ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_CGT, 0); - } - - uint32 artkit = 21; - - switch (m_State) - { - case OBJECTIVESTATE_ALLIANCE: - m_TowerState = EP_TS_A; - artkit = 2; - LinkGraveYard(ALLIANCE); - ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_CGT, ALLIANCE); - if (m_OldState != m_State) sWorld->SendZoneText(EP_GraveYardZone, sObjectMgr->GetTrinityStringForDBCLocale(LANG_OPVP_EP_CAPTURE_CGT_A)); - break; - case OBJECTIVESTATE_HORDE: - m_TowerState = EP_TS_H; - artkit = 1; - LinkGraveYard(HORDE); - ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_CGT, HORDE); - if (m_OldState != m_State) sWorld->SendZoneText(EP_GraveYardZone, sObjectMgr->GetTrinityStringForDBCLocale(LANG_OPVP_EP_CAPTURE_CGT_H)); - break; - case OBJECTIVESTATE_NEUTRAL: - m_TowerState = EP_TS_N; - break; - case OBJECTIVESTATE_NEUTRAL_ALLIANCE_CHALLENGE: - case OBJECTIVESTATE_HORDE_ALLIANCE_CHALLENGE: - m_TowerState = EP_TS_N_A; - break; - case OBJECTIVESTATE_NEUTRAL_HORDE_CHALLENGE: - case OBJECTIVESTATE_ALLIANCE_HORDE_CHALLENGE: - m_TowerState = EP_TS_N_H; - break; - } - - GameObject* flag = HashMapHolder<GameObject>::Find(m_capturePointGUID); - GameObject* flag2 = HashMapHolder<GameObject>::Find(m_Objects[EP_CGT_FLAGS]); - if (flag) - { - flag->SetGoArtKit(artkit); - } - if (flag2) - { - flag2->SetGoArtKit(artkit); - } - - UpdateTowerState(); - - // complete quest objective - if (m_TowerState == EP_TS_A || m_TowerState == EP_TS_H) - SendObjectiveComplete(EP_CGT_CM, 0); -} - -void OPvPCapturePointEP_CGT::SendChangePhase() -{ - // send this too, sometimes the slider disappears, dunno why :( - SendUpdateWorldState(EP_UI_TOWER_SLIDER_DISPLAY, 1); - // send these updates to only the ones in this objective - uint32 phase = (uint32)ceil((m_value + m_maxValue) / (2 * m_maxValue) * 100.0f); - SendUpdateWorldState(EP_UI_TOWER_SLIDER_POS, phase); - // send this too, sometimes it resets :S - SendUpdateWorldState(EP_UI_TOWER_SLIDER_N, m_neutralValuePct); -} - -void OPvPCapturePointEP_CGT::FillInitialWorldStates(WorldPacket &data) -{ - data << EP_CGT_A << uint32(bool(m_TowerState & EP_TS_A)); - data << EP_CGT_H << uint32(bool(m_TowerState & EP_TS_H)); - data << EP_CGT_N_A << uint32(bool(m_TowerState & EP_TS_N_A)); - data << EP_CGT_N_H << uint32(bool(m_TowerState & EP_TS_N_H)); - data << EP_CGT_N << uint32(bool(m_TowerState & EP_TS_N)); -} - -void OPvPCapturePointEP_CGT::UpdateTowerState() -{ - m_PvP->SendUpdateWorldState(EP_CGT_A, bool(m_TowerState & EP_TS_A)); - m_PvP->SendUpdateWorldState(EP_CGT_H, bool(m_TowerState & EP_TS_H)); - m_PvP->SendUpdateWorldState(EP_CGT_N_A, bool(m_TowerState & EP_TS_N_A)); - m_PvP->SendUpdateWorldState(EP_CGT_N_H, bool(m_TowerState & EP_TS_N_H)); - m_PvP->SendUpdateWorldState(EP_CGT_N, bool(m_TowerState & EP_TS_N)); -} - -bool OPvPCapturePointEP_CGT::HandlePlayerEnter(Player* player) -{ - if (OPvPCapturePoint::HandlePlayerEnter(player)) - { - player->SendUpdateWorldState(EP_UI_TOWER_SLIDER_DISPLAY, 1); - uint32 phase = (uint32)ceil((m_value + m_maxValue) / (2 * m_maxValue) * 100.0f); - player->SendUpdateWorldState(EP_UI_TOWER_SLIDER_POS, phase); - player->SendUpdateWorldState(EP_UI_TOWER_SLIDER_N, m_neutralValuePct); - return true; - } - return false; -} - -void OPvPCapturePointEP_CGT::HandlePlayerLeave(Player* player) -{ - player->SendUpdateWorldState(EP_UI_TOWER_SLIDER_DISPLAY, 0); - OPvPCapturePoint::HandlePlayerLeave(player); -} - -void OPvPCapturePointEP_CGT::LinkGraveYard(uint32 team) -{ - if (m_GraveyardSide != team) - { - m_GraveyardSide = team; - sObjectMgr->RemoveGraveYardLink(EP_GraveYardId, EP_GraveYardZone, team, false); - sObjectMgr->AddGraveYardLink(EP_GraveYardId, EP_GraveYardZone, team, false); - } -} - -// PWT -OPvPCapturePointEP_PWT::OPvPCapturePointEP_PWT(OutdoorPvP* pvp) -: OPvPCapturePoint(pvp), m_FlightMasterSpawned(0), m_TowerState(EP_TS_N) -{ - SetCapturePointData(EPCapturePoints[EP_PWT].entry, EPCapturePoints[EP_PWT].map, EPCapturePoints[EP_PWT].x, EPCapturePoints[EP_PWT].y, EPCapturePoints[EP_PWT].z, EPCapturePoints[EP_PWT].o, EPCapturePoints[EP_PWT].rot0, EPCapturePoints[EP_PWT].rot1, EPCapturePoints[EP_PWT].rot2, EPCapturePoints[EP_PWT].rot3); - AddObject(EP_PWT_FLAGS, EPTowerFlags[EP_PWT].entry, EPTowerFlags[EP_PWT].map, EPTowerFlags[EP_PWT].x, EPTowerFlags[EP_PWT].y, EPTowerFlags[EP_PWT].z, EPTowerFlags[EP_PWT].o, EPTowerFlags[EP_PWT].rot0, EPTowerFlags[EP_PWT].rot1, EPTowerFlags[EP_PWT].rot2, EPTowerFlags[EP_PWT].rot3); -} - -void OPvPCapturePointEP_PWT::ChangeState() -{ - // if changing from controlling alliance to horde or vice versa - if ( m_OldState == OBJECTIVESTATE_ALLIANCE && m_OldState != m_State ) - { - sWorld->SendZoneText(EP_GraveYardZone, sObjectMgr->GetTrinityStringForDBCLocale(LANG_OPVP_EP_LOSE_PWT_A)); - ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_PWT, 0); - } - else if ( m_OldState == OBJECTIVESTATE_HORDE && m_OldState != m_State ) - { - sWorld->SendZoneText(EP_GraveYardZone, sObjectMgr->GetTrinityStringForDBCLocale(LANG_OPVP_EP_LOSE_PWT_H)); - ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_PWT, 0); - } - - uint32 artkit = 21; - - switch (m_State) - { - case OBJECTIVESTATE_ALLIANCE: - m_TowerState = EP_TS_A; - SummonFlightMaster(ALLIANCE); - artkit = 2; - ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_PWT, ALLIANCE); - if (m_OldState != m_State) sWorld->SendZoneText(EP_GraveYardZone, sObjectMgr->GetTrinityStringForDBCLocale(LANG_OPVP_EP_CAPTURE_PWT_A)); - break; - case OBJECTIVESTATE_HORDE: - m_TowerState = EP_TS_H; - SummonFlightMaster(HORDE); - artkit = 1; - ((OutdoorPvPEP*)m_PvP)->SetControlledState(EP_PWT, HORDE); - if (m_OldState != m_State) sWorld->SendZoneText(EP_GraveYardZone, sObjectMgr->GetTrinityStringForDBCLocale(LANG_OPVP_EP_CAPTURE_PWT_H)); - break; - case OBJECTIVESTATE_NEUTRAL: - m_TowerState = EP_TS_N; - DelCreature(EP_PWT_FLIGHTMASTER); - m_FlightMasterSpawned = 0; - break; - case OBJECTIVESTATE_NEUTRAL_ALLIANCE_CHALLENGE: - m_TowerState = EP_TS_N_A; - break; - case OBJECTIVESTATE_HORDE_ALLIANCE_CHALLENGE: - m_TowerState = EP_TS_N_A; - DelCreature(EP_PWT_FLIGHTMASTER); - m_FlightMasterSpawned = 0; - break; - case OBJECTIVESTATE_NEUTRAL_HORDE_CHALLENGE: - m_TowerState = EP_TS_N_H; - break; - case OBJECTIVESTATE_ALLIANCE_HORDE_CHALLENGE: - m_TowerState = EP_TS_N_H; - DelCreature(EP_PWT_FLIGHTMASTER); - m_FlightMasterSpawned = 0; - break; - } - - GameObject* flag = HashMapHolder<GameObject>::Find(m_capturePointGUID); - GameObject* flag2 = HashMapHolder<GameObject>::Find(m_Objects[EP_PWT_FLAGS]); - if (flag) - { - flag->SetGoArtKit(artkit); - } - if (flag2) - { - flag2->SetGoArtKit(artkit); - } - - UpdateTowerState(); - - // complete quest objective - if (m_TowerState == EP_TS_A || m_TowerState == EP_TS_H) - SendObjectiveComplete(EP_PWT_CM, 0); -} - -void OPvPCapturePointEP_PWT::SendChangePhase() -{ - // send this too, sometimes the slider disappears, dunno why :( - SendUpdateWorldState(EP_UI_TOWER_SLIDER_DISPLAY, 1); - // send these updates to only the ones in this objective - uint32 phase = (uint32)ceil((m_value + m_maxValue) / (2 * m_maxValue) * 100.0f); - SendUpdateWorldState(EP_UI_TOWER_SLIDER_POS, phase); - // send this too, sometimes it resets :S - SendUpdateWorldState(EP_UI_TOWER_SLIDER_N, m_neutralValuePct); -} - -void OPvPCapturePointEP_PWT::FillInitialWorldStates(WorldPacket &data) -{ - data << EP_PWT_A << uint32(bool(m_TowerState & EP_TS_A)); - data << EP_PWT_H << uint32(bool(m_TowerState & EP_TS_H)); - data << EP_PWT_N_A << uint32(bool(m_TowerState & EP_TS_N_A)); - data << EP_PWT_N_H << uint32(bool(m_TowerState & EP_TS_N_H)); - data << EP_PWT_N << uint32(bool(m_TowerState & EP_TS_N)); -} - -void OPvPCapturePointEP_PWT::UpdateTowerState() -{ - m_PvP->SendUpdateWorldState(EP_PWT_A, bool(m_TowerState & EP_TS_A)); - m_PvP->SendUpdateWorldState(EP_PWT_H, bool(m_TowerState & EP_TS_H)); - m_PvP->SendUpdateWorldState(EP_PWT_N_A, bool(m_TowerState & EP_TS_N_A)); - m_PvP->SendUpdateWorldState(EP_PWT_N_H, bool(m_TowerState & EP_TS_N_H)); - m_PvP->SendUpdateWorldState(EP_PWT_N, bool(m_TowerState & EP_TS_N)); -} - -bool OPvPCapturePointEP_PWT::HandlePlayerEnter(Player* player) -{ - if (OPvPCapturePoint::HandlePlayerEnter(player)) - { - player->SendUpdateWorldState(EP_UI_TOWER_SLIDER_DISPLAY, 1); - uint32 phase = (uint32)ceil((m_value + m_maxValue) / (2 * m_maxValue) * 100.0f); - player->SendUpdateWorldState(EP_UI_TOWER_SLIDER_POS, phase); - player->SendUpdateWorldState(EP_UI_TOWER_SLIDER_N, m_neutralValuePct); - return true; - } - return false; -} - -void OPvPCapturePointEP_PWT::HandlePlayerLeave(Player* player) -{ - player->SendUpdateWorldState(EP_UI_TOWER_SLIDER_DISPLAY, 0); - OPvPCapturePoint::HandlePlayerLeave(player); -} - -void OPvPCapturePointEP_PWT::SummonFlightMaster(uint32 team) -{ - if (m_FlightMasterSpawned != team) - { - m_FlightMasterSpawned = team; - DelCreature(EP_PWT_FLIGHTMASTER); - AddCreature(EP_PWT_FLIGHTMASTER, EP_PWT_FlightMaster.entry, team, EP_PWT_FlightMaster.map, EP_PWT_FlightMaster.x, EP_PWT_FlightMaster.y, EP_PWT_FlightMaster.z, EP_PWT_FlightMaster.o); - /* - // sky - we need update gso code - - Creature* c = HashMapHolder<Creature>::Find(m_Creatures[EP_PWT_FLIGHTMASTER]); - //Spawn flight master as friendly to capturing team - c->SetUInt32Value(GAMEOBJECT_FACTION, (team == ALLIANCE ? 55 : 68)); - if (c) - { - GossipOption gso; - gso.Action = GOSSIP_OPTION_OUTDOORPVP; - gso.GossipId = 0; - gso.OptionText.assign(sObjectMgr->GetTrinityStringForDBCLocale(LANG_OPVP_EP_FLIGHT_NPT)); - gso.Id = 50; - gso.Icon = 0; - gso.NpcFlag = 0; - gso.BoxMoney = 0; - gso.Coded = false; - c->addGossipOption(gso); - - gso.Action = GOSSIP_OPTION_OUTDOORPVP; - gso.GossipId = 0; - gso.OptionText.assign(sObjectMgr->GetTrinityStringForDBCLocale(LANG_OPVP_EP_FLIGHT_EWT)); - gso.Id = 50; - gso.Icon = 0; - gso.NpcFlag = 0; - gso.BoxMoney = 0; - gso.Coded = false; - c->addGossipOption(gso); - - gso.Action = GOSSIP_OPTION_OUTDOORPVP; - gso.GossipId = 0; - gso.OptionText.assign(sObjectMgr->GetTrinityStringForDBCLocale(LANG_OPVP_EP_FLIGHT_CGT)); - gso.Id = 50; - gso.Icon = 0; - gso.NpcFlag = 0; - gso.BoxMoney = 0; - gso.Coded = false; - c->addGossipOption(gso); - } - */ - } -} - -// ep -OutdoorPvPEP::OutdoorPvPEP() -{ - m_TypeId = OUTDOOR_PVP_EP; - memset(EP_Controls, 0, sizeof(EP_Controls)); - m_AllianceTowersControlled = 0; - m_HordeTowersControlled = 0; -} - -bool OutdoorPvPEP::SetupOutdoorPvP() -{ - for (uint8 i = 0; i < EPBuffZonesNum; ++i) - RegisterZone(EPBuffZones[i]); - - AddCapturePoint(new OPvPCapturePointEP_EWT(this)); - AddCapturePoint(new OPvPCapturePointEP_PWT(this)); - AddCapturePoint(new OPvPCapturePointEP_CGT(this)); - AddCapturePoint(new OPvPCapturePointEP_NPT(this)); - return true; -} - -bool OutdoorPvPEP::Update(uint32 diff) -{ - if (OutdoorPvP::Update(diff)) - { - m_AllianceTowersControlled = 0; - m_HordeTowersControlled = 0; - for (int i = 0; i < EP_TOWER_NUM; ++i) - { - if (EP_Controls[i] == ALLIANCE) - ++m_AllianceTowersControlled; - else if (EP_Controls[i] == HORDE) - ++m_HordeTowersControlled; - SendUpdateWorldState(EP_UI_TOWER_COUNT_A, m_AllianceTowersControlled); - SendUpdateWorldState(EP_UI_TOWER_COUNT_H, m_HordeTowersControlled); - BuffTeams(); - } - return true; - } - return false; -} - -void OutdoorPvPEP::HandlePlayerEnterZone(Player* player, uint32 zone) -{ - // add buffs - if (player->GetTeam() == ALLIANCE) - { - if (m_AllianceTowersControlled && m_AllianceTowersControlled < 5) - player->CastSpell(player, EP_AllianceBuffs[m_AllianceTowersControlled-1], true); - } - else - { - if (m_HordeTowersControlled && m_HordeTowersControlled < 5) - player->CastSpell(player, EP_HordeBuffs[m_HordeTowersControlled-1], true); - } - OutdoorPvP::HandlePlayerEnterZone(player, zone); -} - -void OutdoorPvPEP::HandlePlayerLeaveZone(Player* player, uint32 zone) -{ - // remove buffs - if (player->GetTeam() == ALLIANCE) - { - for (int i = 0; i < 4; ++i) - player->RemoveAurasDueToSpell(EP_AllianceBuffs[i]); - } - else - { - for (int i = 0; i < 4; ++i) - player->RemoveAurasDueToSpell(EP_HordeBuffs[i]); - } - OutdoorPvP::HandlePlayerLeaveZone(player, zone); -} - -void OutdoorPvPEP::BuffTeams() -{ - for (PlayerSet::iterator itr = m_players[0].begin(); itr != m_players[0].end(); ++itr) - { - Player* player = *itr; - { - for (int i = 0; i < 4; ++i) - player->RemoveAurasDueToSpell(EP_AllianceBuffs[i]); - if (m_AllianceTowersControlled && m_AllianceTowersControlled < 5) - player->CastSpell(player, EP_AllianceBuffs[m_AllianceTowersControlled-1], true); - } - } - for (PlayerSet::iterator itr = m_players[1].begin(); itr != m_players[1].end(); ++itr) - { - Player* player = *itr; - { - for (int i = 0; i < 4; ++i) - player->RemoveAurasDueToSpell(EP_HordeBuffs[i]); - if (m_HordeTowersControlled && m_HordeTowersControlled < 5) - player->CastSpell(player, EP_HordeBuffs[m_HordeTowersControlled-1], true); - } - } -} - -void OutdoorPvPEP::SetControlledState(uint32 index, uint32 state) -{ - EP_Controls[index] = state; -} - -void OutdoorPvPEP::FillInitialWorldStates(WorldPacket & data) -{ - data << EP_UI_TOWER_COUNT_A << m_AllianceTowersControlled; - data << EP_UI_TOWER_COUNT_H << m_HordeTowersControlled; - data << EP_UI_TOWER_SLIDER_DISPLAY << uint32(0); - data << EP_UI_TOWER_SLIDER_POS << uint32(50); - data << EP_UI_TOWER_SLIDER_N << uint32(100); - for (OPvPCapturePointMap::iterator itr = m_capturePoints.begin(); itr != m_capturePoints.end(); ++itr) - { - itr->second->FillInitialWorldStates(data); - } -} - -void OutdoorPvPEP::SendRemoveWorldStates(Player* player) -{ - player->SendUpdateWorldState(EP_UI_TOWER_COUNT_A, 0); - player->SendUpdateWorldState(EP_UI_TOWER_COUNT_H, 0); - player->SendUpdateWorldState(EP_UI_TOWER_SLIDER_DISPLAY, 0); - player->SendUpdateWorldState(EP_UI_TOWER_SLIDER_POS, 0); - player->SendUpdateWorldState(EP_UI_TOWER_SLIDER_N, 0); - - player->SendUpdateWorldState(EP_EWT_A, 0); - player->SendUpdateWorldState(EP_EWT_H, 0); - player->SendUpdateWorldState(EP_EWT_N, 0); - player->SendUpdateWorldState(EP_EWT_N_A, 0); - player->SendUpdateWorldState(EP_EWT_N_H, 0); - - player->SendUpdateWorldState(EP_PWT_A, 0); - player->SendUpdateWorldState(EP_PWT_H, 0); - player->SendUpdateWorldState(EP_PWT_N, 0); - player->SendUpdateWorldState(EP_PWT_N_A, 0); - player->SendUpdateWorldState(EP_PWT_N_H, 0); - - player->SendUpdateWorldState(EP_NPT_A, 0); - player->SendUpdateWorldState(EP_NPT_H, 0); - player->SendUpdateWorldState(EP_NPT_N, 0); - player->SendUpdateWorldState(EP_NPT_N_A, 0); - player->SendUpdateWorldState(EP_NPT_N_H, 0); - - player->SendUpdateWorldState(EP_CGT_A, 0); - player->SendUpdateWorldState(EP_CGT_H, 0); - player->SendUpdateWorldState(EP_CGT_N, 0); - player->SendUpdateWorldState(EP_CGT_N_A, 0); - player->SendUpdateWorldState(EP_CGT_N_H, 0); -} - -class OutdoorPvP_eastern_plaguelands : public OutdoorPvPScript -{ - public: - - OutdoorPvP_eastern_plaguelands() - : OutdoorPvPScript("outdoorpvp_ep") - { - } - - OutdoorPvP* GetOutdoorPvP() const - { - return new OutdoorPvPEP(); - } -}; - -void AddSC_outdoorpvp_ep() -{ - new OutdoorPvP_eastern_plaguelands(); -} diff --git a/src/server/scripts/OutdoorPvP/OutdoorPvPEP.h b/src/server/scripts/OutdoorPvP/OutdoorPvPEP.h deleted file mode 100755 index 14712e0150d..00000000000 --- a/src/server/scripts/OutdoorPvP/OutdoorPvPEP.h +++ /dev/null @@ -1,331 +0,0 @@ -/* - * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> - * - * This program is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; either version 2 of the License, or (at your - * option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for - * more details. - * - * You should have received a copy of the GNU General Public License along - * with this program. If not, see <http://www.gnu.org/licenses/>. - */ - -#ifndef OUTDOOR_PVP_EP_ -#define OUTDOOR_PVP_EP_ - -#include "DBCStructure.h" -#include "OutdoorPvP.h" - -const uint32 EP_AllianceBuffs[4] = {11413, 11414, 11415, 1386}; - -const uint32 EP_HordeBuffs[4] = {30880, 30683, 30682, 29520}; - -const uint32 EP_GraveYardZone = 139; - -const uint32 EP_GraveYardId = 927; - -const uint8 EPBuffZonesNum = 3; - -const uint32 EP_EWT_CM = 17690; -const uint32 EP_CGT_CM = 17689; -const uint32 EP_NPT_CM = 17696; -const uint32 EP_PWT_CM = 17698; - -const uint32 EPBuffZones[EPBuffZonesNum] = {139, 2017, 2057}; - -enum EP_TaxiNodes -{ - EP_CGT_Taxi = 87, - EP_EWT_Taxi = 86, - EP_NPT_Taxi = 85, - EP_PWT_Taxi = 84 -}; - -enum EP_EastwallTowerWorldStates -{ - EP_EWT_A = 2354, - EP_EWT_H = 2356, - EP_EWT_N_A = 2359, // ally conquested - EP_EWT_N_H = 2360, - EP_EWT_N = 2361 -}; - -enum EP_NorthpassTowerWorldStates -{ - EP_NPT_N = 2352, - EP_NPT_N_A = 2362, - EP_NPT_N_H = 2363, - EP_NPT_A = 2372, - EP_NPT_H = 2373 -}; - -enum EP_PlagewoodTowerWorldStates -{ - EP_PWT_N_A = 2366, - EP_PWT_N_H = 2353, //2367 not present! use neutral! - EP_PWT_A = 2370, - EP_PWT_H = 2371, - EP_PWT_N = 2353 -}; - -enum EP_CrownGuardTowerWorldStates -{ - EP_CGT_N_A = 2374, - EP_CGT_N_H = 2375, - EP_CGT_A = 2378, - EP_CGT_H = 2379, - EP_CGT_N = 2355 -}; - -enum EP_WorldStates -{ - EP_UI_TOWER_SLIDER_DISPLAY = 2426, - EP_UI_TOWER_SLIDER_POS = 2427, - EP_UI_TOWER_SLIDER_N = 2428, - - EP_UI_TOWER_COUNT_A = 2327, - EP_UI_TOWER_COUNT_H = 2328 -}; - -enum EP_Summons -{ - EP_EWT_COMMANDER = 0, - EP_EWT_SOLDIER1, - EP_EWT_SOLDIER2, - EP_EWT_SOLDIER3, - EP_EWT_SOLDIER4, - EP_PWT_FLIGHTMASTER, -}; - -enum EP_GoSummons -{ - EP_NPT_BUFF = 0, - EP_NPT_FLAGS, - EP_EWT_FLAGS, - EP_CGT_FLAGS, - EP_PWT_FLAGS -}; - -enum EP_Towers -{ - EP_EWT = 0, // plaguelands 03 - EP_NPT, // plaguelands 01 - EP_PWT, // plaguelands 04 - EP_CGT, // plaguelands 02 - EP_TOWER_NUM -}; - -const go_type EPCapturePoints[EP_TOWER_NUM] = -{ - {182097, 0, 2574.51f, -4794.89f, 144.704f, -1.45003f, -0.097056f, 0.095578f, -0.656229f, 0.742165f}, - {181899, 0, 3181.08f, -4379.36f, 174.123f, -2.03472f, -0.065392f, 0.119494f, -0.842275f, 0.521553f}, - {182098, 0, 2962.71f, -3042.31f, 154.789f, 2.08426f, -0.074807f, -0.113837f, 0.855928f, 0.49883f}, - {182096, 0, 1860.85f, -3731.23f, 196.716f, -2.53214f, 0.033967f, -0.131914f, 0.944741f, -0.298177f} -}; - -const go_type EPTowerFlags[EP_TOWER_NUM] = -{ - {182106, 0, 2569.60f, -4772.93f, 115.399f, 2.72271f, 0.0f, 0.0f, 0.978148f, 0.207912f}, - {182106, 0, 3148.17f, -4365.51f, 145.029f, 1.53589f, 0.0f, 0.0f, 0.694658f, 0.71934f}, - {182106, 0, 2992.63f, -3022.95f, 125.593f, 3.03687f, 0.0f, 0.0f, 0.99863f, 0.052336f}, - {182106, 0, 1838.42f, -3703.56f, 167.713f, 0.890118f, 0.0f, 0.0f, 0.430511f, 0.902585f} -}; - -const uint32 EPTowerPlayerEnterEvents[EP_TOWER_NUM] = {10691, 10699, 10701, 10705}; - -const uint32 EPTowerPlayerLeaveEvents[EP_TOWER_NUM] = {10692, 10698, 10700, 10704}; - -const uint8 EP_NUM_CREATURES = 6; -const uint8 EP_EWT_NUM_CREATURES = 5; - -// one lordaeron commander, 4 soldiers -// should be spawned at EWT and follow a path, but trans-grid pathing isn't safe, so summon them directly at NPT -const creature_type EP_EWT_Summons_A[EP_EWT_NUM_CREATURES] = -{ - {17635, 469, 0, 3167.61f, -4352.09f, 138.20f, 4.5811f}, - {17647, 469, 0, 3172.74f, -4352.99f, 139.14f, 4.9873f}, - {17647, 469, 0, 3165.89f, -4354.46f, 138.67f, 3.7244f}, - {17647, 469, 0, 3164.65f, -4350.26f, 138.22f, 2.4794f}, - {17647, 469, 0, 3169.91f, -4349.68f, 138.37f, 0.7444f} -}; - -const creature_type EP_EWT_Summons_H[EP_EWT_NUM_CREATURES] = -{ - {17995, 67, 0, 3167.61f, -4352.09f, 138.20f, 4.5811f}, - {17996, 67, 0, 3172.74f, -4352.99f, 139.14f, 4.9873f}, - {17996, 67, 0, 3165.89f, -4354.46f, 138.67f, 3.7244f}, - {17996, 67, 0, 3164.65f, -4350.26f, 138.22f, 2.4794f}, - {17996, 67, 0, 3169.91f, -4349.68f, 138.37f, 0.7444f} -}; - -enum EP_TowerStates -{ - EP_TS_N = 1, - EP_TS_N_A = 2, - EP_TS_N_H = 4, - EP_TS_A_P = 8, - EP_TS_H_P = 16, - EP_TS_A = 32, - EP_TS_H = 64 -}; - -// when spawning, pay attention at setting the faction manually! -const creature_type EP_PWT_FlightMaster = {17209, 0, 0, 2987.5f, -3049.11f, 120.126f, 5.75959f}; - -// after spawning, modify the faction so that only the controller will be able to use it with SetUInt32Value(GAMEOBJECT_FACTION, faction_id); -const go_type EP_NPT_LordaeronShrine = {181682, 0, 3167.72f, -4355.91f, 138.785f, 1.69297f, 0.0f, 0.0f, 0.748956f, 0.66262f}; - -class OutdoorPvPEP; - -class OPvPCapturePointEP_EWT : public OPvPCapturePoint -{ - public: - - OPvPCapturePointEP_EWT(OutdoorPvP* pvp); - - void ChangeState(); - - void SendChangePhase(); - - void FillInitialWorldStates(WorldPacket & data); - - // used when player is activated/inactivated in the area - bool HandlePlayerEnter(Player* player); - void HandlePlayerLeave(Player* player); - - protected: - - void SummonSupportUnitAtNorthpassTower(uint32 team); - - void UpdateTowerState(); - - protected: - - uint32 m_TowerState; - - uint32 m_UnitsSummonedSide; -}; - -class OPvPCapturePointEP_NPT : public OPvPCapturePoint -{ - public: - - OPvPCapturePointEP_NPT(OutdoorPvP* pvp); - - void ChangeState(); - - void SendChangePhase(); - - void FillInitialWorldStates(WorldPacket & data); - - // used when player is activated/inactivated in the area - bool HandlePlayerEnter(Player* player); - void HandlePlayerLeave(Player* player); - - protected: - - void SummonGO(uint32 team); - - void UpdateTowerState(); - - protected: - - uint32 m_TowerState; - - uint32 m_SummonedGOSide; -}; - -class OPvPCapturePointEP_CGT : public OPvPCapturePoint -{ - public: - - OPvPCapturePointEP_CGT(OutdoorPvP* pvp); - - void ChangeState(); - - void SendChangePhase(); - - void FillInitialWorldStates(WorldPacket & data); - - // used when player is activated/inactivated in the area - bool HandlePlayerEnter(Player* player); - void HandlePlayerLeave(Player* player); - - protected: - - void LinkGraveYard(uint32 team); - - void UpdateTowerState(); - - protected: - - uint32 m_TowerState; - - uint32 m_GraveyardSide; -}; - -class OPvPCapturePointEP_PWT : public OPvPCapturePoint -{ - public: - - OPvPCapturePointEP_PWT(OutdoorPvP* pvp); - - void ChangeState(); - - void SendChangePhase(); - - void FillInitialWorldStates(WorldPacket & data); - - // used when player is activated/inactivated in the area - bool HandlePlayerEnter(Player* player); - void HandlePlayerLeave(Player* player); - - protected: - - void SummonFlightMaster(uint32 team); - - void UpdateTowerState(); - - protected: - - uint32 m_FlightMasterSpawned; - - uint32 m_TowerState; -}; - -class OutdoorPvPEP : public OutdoorPvP -{ - public: - - OutdoorPvPEP(); - - bool SetupOutdoorPvP(); - - void HandlePlayerEnterZone(Player* player, uint32 zone); - void HandlePlayerLeaveZone(Player* player, uint32 zone); - - bool Update(uint32 diff); - - void FillInitialWorldStates(WorldPacket &data); - - void SendRemoveWorldStates(Player* player); - - void BuffTeams(); - - void SetControlledState(uint32 index, uint32 state); - - private: - - // how many towers are controlled - uint32 EP_Controls[EP_TOWER_NUM]; - - uint32 m_AllianceTowersControlled; - uint32 m_HordeTowersControlled; -}; - -#endif diff --git a/src/server/scripts/Outland/BlackTemple/boss_mother_shahraz.cpp b/src/server/scripts/Outland/BlackTemple/boss_mother_shahraz.cpp index 1b2fe61e87c..ec25a8f9f60 100644 --- a/src/server/scripts/Outland/BlackTemple/boss_mother_shahraz.cpp +++ b/src/server/scripts/Outland/BlackTemple/boss_mother_shahraz.cpp @@ -248,11 +248,9 @@ public: { for (uint8 i = 0; i < 3; ++i) { - Unit* unit = NULL; if (TargetGUID[i]) { - unit = Unit::GetUnit(*me, TargetGUID[i]); - if (unit) + if (Unit* unit = Unit::GetUnit(*me, TargetGUID[i])) unit->CastSpell(unit, SPELL_ATTRACTION, true); TargetGUID[i] = 0; } diff --git a/src/server/scripts/Outland/BlackTemple/illidari_council.cpp b/src/server/scripts/Outland/BlackTemple/illidari_council.cpp index 710f5c82fab..673d4bcc96f 100644 --- a/src/server/scripts/Outland/BlackTemple/illidari_council.cpp +++ b/src/server/scripts/Outland/BlackTemple/illidari_council.cpp @@ -299,12 +299,11 @@ public: for (uint8 i = 0; i < 4; ++i) { - Unit* Member = NULL; if (Council[i]) { - Member = Unit::GetUnit(*me, Council[i]); - if (Member && Member->isAlive()) - CAST_CRE(Member)->AI()->AttackStart(target); + Unit* member = Unit::GetUnit(*me, Council[i]); + if (member && member->isAlive()) + CAST_CRE(member)->AI()->AttackStart(target); } } diff --git a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/blood_furnace.h b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/blood_furnace.h index e34e86c16a7..ed8c5351493 100644 --- a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/blood_furnace.h +++ b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/blood_furnace.h @@ -39,5 +39,9 @@ #define DATA_PRISON_CELL6 18 #define DATA_PRISON_CELL7 19 #define DATA_PRISON_CELL8 20 +#define DATA_BROGGOK_LEVER 21 +#define ACTION_ACTIVATE_BROGGOK 22 +#define ACTION_RESET_BROGGOK 23 +#define ACTION_PREPARE_BROGGOK 24 #endif diff --git a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_broggok.cpp b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_broggok.cpp index 3a2e0834fed..84d292e1fe4 100644 --- a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_broggok.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_broggok.cpp @@ -47,9 +47,9 @@ class boss_broggok : public CreatureScript { } - struct boss_broggokAI : public ScriptedAI + struct boss_broggokAI : public BossAI { - boss_broggokAI(Creature* creature) : ScriptedAI(creature) + boss_broggokAI(Creature* creature) : BossAI(creature, DATA_BROGGOK) { instance = creature->GetInstanceScript(); } @@ -59,27 +59,21 @@ class boss_broggok : public CreatureScript uint32 AcidSpray_Timer; uint32 PoisonSpawn_Timer; uint32 PoisonBolt_Timer; + bool canAttack; void Reset() { + _Reset(); AcidSpray_Timer = 10000; PoisonSpawn_Timer = 5000; PoisonBolt_Timer = 7000; - if (instance) - { - instance->SetData(TYPE_BROGGOK_EVENT, NOT_STARTED); - instance->HandleGameObject(instance->GetData64(DATA_DOOR4), true); - } + DoAction(ACTION_RESET_BROGGOK); + instance->SetData(TYPE_BROGGOK_EVENT, NOT_STARTED); } void EnterCombat(Unit* /*who*/) { DoScriptText(SAY_AGGRO, me); - if (instance) - { - instance->SetData(TYPE_BROGGOK_EVENT, IN_PROGRESS); - instance->HandleGameObject(instance->GetData64(DATA_DOOR4), false); - } } void JustSummoned(Creature* summoned) @@ -94,7 +88,8 @@ class boss_broggok : public CreatureScript { if (!UpdateVictim()) return; - + if (!canAttack) + return; if (AcidSpray_Timer <= diff) { DoCast(me->getVictim(), SPELL_SLIME_SPRAY); @@ -132,6 +127,26 @@ class boss_broggok : public CreatureScript } } + void DoAction(int32 const action) + { + switch (action) + { + case ACTION_PREPARE_BROGGOK: + me->SetInCombatWithZone(); + break; + case ACTION_ACTIVATE_BROGGOK: + me->SetReactState(REACT_AGGRESSIVE); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC | UNIT_FLAG_NON_ATTACKABLE); + canAttack = true; + break; + case ACTION_RESET_BROGGOK: + me->SetReactState(REACT_PASSIVE); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC | UNIT_FLAG_NON_ATTACKABLE); + canAttack = false; + break; + } + } + }; CreatureAI* GetAI(Creature* creature) const @@ -140,7 +155,27 @@ class boss_broggok : public CreatureScript } }; +class go_broggok_lever : public GameObjectScript +{ + public: + go_broggok_lever() : GameObjectScript("go_broggok_lever") {} + + bool OnGossipHello(Player* player, GameObject* go) + { + if (InstanceScript* instance = go->GetInstanceScript()) + if (instance->GetData(TYPE_BROGGOK_EVENT) != DONE && instance->GetData(TYPE_BROGGOK_EVENT) != IN_PROGRESS) + { + instance->SetData(TYPE_BROGGOK_EVENT, IN_PROGRESS); + if (Creature* broggok = Creature::GetCreature(*go, instance->GetData64(DATA_BROGGOK))) + broggok->AI()->DoAction(ACTION_PREPARE_BROGGOK); + } + go->UseDoorOrButton(); + return false; + } +}; + void AddSC_boss_broggok() { new boss_broggok(); + new go_broggok_lever(); } diff --git a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_kelidan_the_breaker.cpp b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_kelidan_the_breaker.cpp index a0bcc396fdb..3c07862e0f6 100644 --- a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_kelidan_the_breaker.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/boss_kelidan_the_breaker.cpp @@ -57,7 +57,9 @@ enum eKelidan SPELL_VORTEX = 37370, ENTRY_KELIDAN = 17377, - ENTRY_CHANNELER = 17653 + ENTRY_CHANNELER = 17653, + + ACTION_ACTIVATE_ADDS = 92 }; const float ShadowmoonChannelers[5][4]= @@ -107,6 +109,8 @@ class boss_kelidan_the_breaker : public CreatureScript Firenova = false; addYell = false; SummonChannelers(); + me->SetReactState(REACT_PASSIVE); + me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC | UNIT_FLAG_NON_ATTACKABLE); if (instance) instance->SetData(TYPE_KELIDAN_THE_BREAKER_EVENT, NOT_STARTED); } @@ -152,7 +156,8 @@ class boss_kelidan_the_breaker : public CreatureScript if (channeler && channeler->isAlive()) return; } - + me->SetReactState(REACT_AGGRESSIVE); + me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC | UNIT_FLAG_NON_ATTACKABLE); if (killer) me->AI()->AttackStart(killer); } @@ -269,7 +274,6 @@ class boss_kelidan_the_breaker : public CreatureScript DoMeleeAttackIfReady(); } - }; CreatureAI* GetAI(Creature* creature) const @@ -295,16 +299,11 @@ class mob_shadowmoon_channeler : public CreatureScript { public: - mob_shadowmoon_channeler() - : CreatureScript("mob_shadowmoon_channeler") - { - } + mob_shadowmoon_channeler() : CreatureScript("mob_shadowmoon_channeler") {} struct mob_shadowmoon_channelerAI : public ScriptedAI { - mob_shadowmoon_channelerAI(Creature* creature) : ScriptedAI(creature) - { - } + mob_shadowmoon_channelerAI(Creature* creature) : ScriptedAI(creature){} uint32 ShadowBolt_Timer; uint32 MarkOfShadow_Timer; 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 4c434feb4ec..893f97fe711 100644 --- a/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/instance_blood_furnace.cpp +++ b/src/server/scripts/Outland/HellfireCitadel/BloodFurnace/instance_blood_furnace.cpp @@ -26,6 +26,7 @@ EndScriptData */ #include "ScriptMgr.h" #include "InstanceScript.h" #include "blood_furnace.h" +#include "CreatureAI.h" #define ENTRY_SEWER1 181823 #define ENTRY_SEWER2 181766 @@ -35,9 +36,7 @@ class instance_blood_furnace : public InstanceMapScript { public: instance_blood_furnace() - : InstanceMapScript("instance_blood_furnace", 542) - { - } + : InstanceMapScript("instance_blood_furnace", 542) {} struct instance_blood_furnace_InstanceMapScript : public InstanceScript { @@ -63,6 +62,18 @@ class instance_blood_furnace : public InstanceMapScript uint64 PrisonCell7GUID; uint64 PrisonCell8GUID; + std::set<uint64> PrisonersCell5; + std::set<uint64> PrisonersCell6; + std::set<uint64> PrisonersCell7; + std::set<uint64> PrisonersCell8; + + uint8 PrisonerCounter5; + uint8 PrisonerCounter6; + uint8 PrisonerCounter7; + uint8 PrisonerCounter8; + + uint64 BroggokLeverGUID; + uint32 m_auiEncounter[MAX_ENCOUNTER]; std::string str_data; @@ -89,24 +100,45 @@ class instance_blood_furnace : public InstanceMapScript PrisonCell6GUID = 0; PrisonCell7GUID = 0; PrisonCell8GUID = 0; + + PrisonersCell5.clear(); + PrisonersCell6.clear(); + PrisonersCell7.clear(); + PrisonersCell8.clear(); + + PrisonerCounter5 = 0; + PrisonerCounter6 = 0; + PrisonerCounter7 = 0; + PrisonerCounter8 = 0; + + BroggokLeverGUID = 0; } void OnCreatureCreate(Creature* creature) { switch (creature->GetEntry()) { - case 17381: - The_MakerGUID = creature->GetGUID(); - break; - case 17380: - BroggokGUID = creature->GetGUID(); - break; - case 17377: - Kelidan_The_BreakerGUID = creature->GetGUID(); - break; + case 17381: + The_MakerGUID = creature->GetGUID(); + break; + case 17380: + BroggokGUID = creature->GetGUID(); + break; + case 17377: + Kelidan_The_BreakerGUID = creature->GetGUID(); + break; + case 17398: + StorePrisoner(creature); + break; } } + void OnCreatureDeath(Creature* unit) + { + if (unit && unit->GetTypeId() == TYPEID_UNIT && unit->GetEntry() == 17398) + PrisonerDied(unit->GetGUID()); + } + void OnGameObjectCreate(GameObject* go) { if (go->GetEntry() == 181766) //Final exit door @@ -138,6 +170,9 @@ class instance_blood_furnace : public InstanceMapScript PrisonCell7GUID = go->GetGUID(); if (go->GetEntry() == 181817) //Broggok prison cell back left PrisonCell8GUID = go->GetGUID(); + + if (go->GetEntry() == 181982) + BroggokLeverGUID = go->GetGUID(); //Broggok lever } uint64 GetData64(uint32 data) @@ -161,18 +196,25 @@ class instance_blood_furnace : public InstanceMapScript case DATA_PRISON_CELL6: return PrisonCell6GUID; case DATA_PRISON_CELL7: return PrisonCell7GUID; case DATA_PRISON_CELL8: return PrisonCell8GUID; + case DATA_BROGGOK_LEVER: return BroggokLeverGUID; } - return 0; } - void SetData(uint32 /*type*/, uint32 data) + void SetData(uint32 type, uint32 data) { - switch (data) + switch (type) { - case TYPE_THE_MAKER_EVENT: m_auiEncounter[0] = data; break; - case TYPE_BROGGOK_EVENT: m_auiEncounter[1] = data; break; - case TYPE_KELIDAN_THE_BREAKER_EVENT: m_auiEncounter[2] = data; break; + case TYPE_THE_MAKER_EVENT: + m_auiEncounter[0] = data; + break; + case TYPE_BROGGOK_EVENT: + m_auiEncounter[1] = data; + UpdateBroggokEvent(data); + break; + case TYPE_KELIDAN_THE_BREAKER_EVENT: + m_auiEncounter[2] = data; + break; } if (data == DONE) @@ -189,15 +231,14 @@ class instance_blood_furnace : public InstanceMapScript } } - uint32 GetData(uint32 data) + uint32 GetData(uint32 type) { - switch (data) + switch (type) { case TYPE_THE_MAKER_EVENT: return m_auiEncounter[0]; case TYPE_BROGGOK_EVENT: return m_auiEncounter[1]; case TYPE_KELIDAN_THE_BREAKER_EVENT: return m_auiEncounter[2]; } - return 0; } @@ -225,6 +266,147 @@ class instance_blood_furnace : public InstanceMapScript OUT_LOAD_INST_DATA_COMPLETE; } + + void UpdateBroggokEvent(uint32 data) + { + switch (data) + { + case IN_PROGRESS: + ActivateCell(DATA_PRISON_CELL5); + HandleGameObject(Door4GUID, false); + break; + case NOT_STARTED: + ResetPrisons(); + HandleGameObject(Door5GUID, false); + HandleGameObject(Door4GUID, true); + if (GameObject* lever = instance->GetGameObject(BroggokLeverGUID)) + lever->Respawn(); + break; + } + } + + void ResetPrisons() + { + PrisonerCounter5 = PrisonersCell5.size(); + ResetPrisoners(PrisonersCell5); + HandleGameObject(PrisonCell5GUID, false); + + PrisonerCounter6 = PrisonersCell6.size(); + ResetPrisoners(PrisonersCell6); + HandleGameObject(PrisonCell6GUID, false); + + PrisonerCounter7 = PrisonersCell7.size(); + ResetPrisoners(PrisonersCell7); + HandleGameObject(PrisonCell7GUID, false); + + PrisonerCounter8 = PrisonersCell8.size(); + ResetPrisoners(PrisonersCell8); + HandleGameObject(PrisonCell8GUID, false); + } + + void ResetPrisoners(std::set<uint64> prisoners) + { + for (std::set<uint64>::iterator i = prisoners.begin(); i != prisoners.end(); ++i) + if (Creature* prisoner = instance->GetCreature(*i)) + ResetPrisoner(prisoner); + } + + void ResetPrisoner(Creature* prisoner) + { + if (!prisoner->isAlive()) + prisoner->Respawn(true); + prisoner->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC | UNIT_FLAG_NON_ATTACKABLE); + } + + void StorePrisoner(Creature* creature) + { + float posX = creature->GetPositionX(); + float posY = creature->GetPositionY(); + + if (posX >= 405.0f && posX <= 423.0f) + { + if (posY >= 106.0f && posY <= 123.0f) + { + PrisonersCell5.insert(creature->GetGUID()); + ++PrisonerCounter5; + } + else if (posY >= 76.0f && posY <= 91.0f) + { + PrisonersCell6.insert(creature->GetGUID()); + ++PrisonerCounter6; + } + else return; + } + else if (posX >= 490.0f && posX <= 506.0f) + { + if (posY >= 106.0f && posY <= 123.0f) + { + PrisonersCell7.insert(creature->GetGUID()); + ++PrisonerCounter7; + } + else if (posY >= 76.0f && posY <= 91.0f) + { + PrisonersCell8.insert(creature->GetGUID()); + ++PrisonerCounter8; + } + else + return; + } + else + return; + + ResetPrisoner(creature); + } + + void PrisonerDied(uint64 guid) + { + if (PrisonersCell5.find(guid) != PrisonersCell5.end() && --PrisonerCounter5 <= 0) + ActivateCell(DATA_PRISON_CELL6); + else if (PrisonersCell6.find(guid) != PrisonersCell6.end() && --PrisonerCounter6 <= 0) + ActivateCell(DATA_PRISON_CELL7); + else if (PrisonersCell7.find(guid) != PrisonersCell7.end() && --PrisonerCounter7 <= 0) + ActivateCell(DATA_PRISON_CELL8); + else if (PrisonersCell8.find(guid) != PrisonersCell8.end() && --PrisonerCounter8 <= 0) + ActivateCell(DATA_DOOR5); + } + + void ActivateCell(uint8 id) + { + switch (id) + { + case DATA_PRISON_CELL5: + HandleGameObject(PrisonCell5GUID,true); + ActivatePrisoners(PrisonersCell5); + break; + case DATA_PRISON_CELL6: + HandleGameObject(PrisonCell6GUID,true); + ActivatePrisoners(PrisonersCell6); + break; + case DATA_PRISON_CELL7: + HandleGameObject(PrisonCell7GUID,true); + ActivatePrisoners(PrisonersCell7); + break; + case DATA_PRISON_CELL8: + HandleGameObject(PrisonCell8GUID,true); + ActivatePrisoners(PrisonersCell8); + break; + case DATA_DOOR5: + HandleGameObject(Door5GUID,true); + if (Creature* broggok = instance->GetCreature(BroggokGUID)) + broggok->AI()->DoAction(ACTION_ACTIVATE_BROGGOK); + break; + } + } + + void ActivatePrisoners(std::set<uint64> prisoners) + { + for (std::set<uint64>::iterator i = prisoners.begin(); i != prisoners.end(); ++i) + if (Creature* prisoner = instance->GetCreature(*i)) + { + prisoner->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC | UNIT_FLAG_IMMUNE_TO_NPC | UNIT_FLAG_NON_ATTACKABLE); + prisoner->SetInCombatWithZone(); + } + } }; InstanceScript* GetInstanceScript(InstanceMap* map) const diff --git a/src/server/scripts/Outland/shadowmoon_valley.cpp b/src/server/scripts/Outland/shadowmoon_valley.cpp index c79bf74aab6..1656f7221ed 100644 --- a/src/server/scripts/Outland/shadowmoon_valley.cpp +++ b/src/server/scripts/Outland/shadowmoon_valley.cpp @@ -45,6 +45,7 @@ EndContentData */ #include "ScriptedGossip.h" #include "ScriptedEscortAI.h" #include "Group.h" +#include "SpellScript.h" /*##### # mob_mature_netherwing_drake @@ -1868,9 +1869,41 @@ public: }; }; -/*##### -# -######*/ +enum ZuluhedChains +{ + QUEST_ZULUHED = 10866, + NPC_KARYNAKU = 22112, +}; + +class spell_unlocking_zuluheds_chains : public SpellScriptLoader +{ + public: + spell_unlocking_zuluheds_chains() : SpellScriptLoader("spell_unlocking_zuluheds_chains") { } + + class spell_unlocking_zuluheds_chains_SpellScript : public SpellScript + { + PrepareSpellScript(spell_unlocking_zuluheds_chains_SpellScript); + + void HandleOnCast() + { + // FIXME: Hackish solution, a better way to reward killcredit should be found + if (Unit* caster = GetCaster()) + if(Player* player = caster->ToPlayer()) + if (player->GetQuestStatus(QUEST_ZULUHED) == QUEST_STATUS_INCOMPLETE) + player->CastedCreatureOrGO(NPC_KARYNAKU, MAKE_NEW_GUID(0, NPC_KARYNAKU, HIGHGUID_UNIT), 0); + } + + void Register() + { + OnCast += SpellCastFn(spell_unlocking_zuluheds_chains_SpellScript::HandleOnCast); + } + }; + + SpellScript* GetSpellScript() const + { + return new spell_unlocking_zuluheds_chains_SpellScript(); + } +}; void AddSC_shadowmoon_valley() { @@ -1889,4 +1922,5 @@ void AddSC_shadowmoon_valley() new mob_illidari_spawn(); new mob_torloth_the_magnificent(); new npc_enraged_spirit(); + new spell_unlocking_zuluheds_chains(); } diff --git a/src/server/scripts/Spells/spell_generic.cpp b/src/server/scripts/Spells/spell_generic.cpp index a35d243593e..2aed2517975 100644 --- a/src/server/scripts/Spells/spell_generic.cpp +++ b/src/server/scripts/Spells/spell_generic.cpp @@ -950,14 +950,14 @@ class spell_generic_clone : public SpellScriptLoader enum CloneWeaponSpells { - SPELL_COPY_WEAPON = 41055, - SPELL_COPY_WEAPON_2 = 63416, - SPELL_COPY_WEAPON_3 = 69891, + SPELL_COPY_WEAPON_AURA = 41054, + SPELL_COPY_WEAPON_2_AURA = 63418, + SPELL_COPY_WEAPON_3_AURA = 69893, - SPELL_COPY_OFFHAND = 45206, - SPELL_COPY_OFFHAND_2 = 69892, + SPELL_COPY_OFFHAND_AURA = 45205, + SPELL_COPY_OFFHAND_2_AURA = 69896, - SPELL_COPY_RANGED = 57593 + SPELL_COPY_RANGED_AURA = 57594 }; class spell_generic_clone_weapon : public SpellScriptLoader @@ -969,80 +969,147 @@ class spell_generic_clone_weapon : public SpellScriptLoader { PrepareSpellScript(spell_generic_clone_weapon_SpellScript); - bool Validate(SpellInfo const* /*spellEntry*/) - { - if (!sSpellMgr->GetSpellInfo(SPELL_COPY_WEAPON) || !sSpellMgr->GetSpellInfo(SPELL_COPY_WEAPON_2) || !sSpellMgr->GetSpellInfo(SPELL_COPY_WEAPON_3) || !sSpellMgr->GetSpellInfo(SPELL_COPY_OFFHAND) - || !sSpellMgr->GetSpellInfo(SPELL_COPY_OFFHAND_2) || !sSpellMgr->GetSpellInfo(SPELL_COPY_RANGED)) - return false; - return true; - } - void HandleScriptEffect(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); Unit* caster = GetCaster(); + if (Unit* target = GetHitUnit()) { uint32 spellId = uint32(GetSpellInfo()->Effects[EFFECT_0].CalcValue()); - target->CastSpell(caster, spellId, true); + caster->CastSpell(target, spellId, true); + } + } - if (target->GetTypeId() == TYPEID_PLAYER) - return; + void Register() + { + OnEffectHitTarget += SpellEffectFn(spell_generic_clone_weapon_SpellScript::HandleScriptEffect, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); + } + }; + + SpellScript* GetSpellScript() const + { + return new spell_generic_clone_weapon_SpellScript(); + } +}; + +class spell_gen_clone_weapon_aura : public SpellScriptLoader +{ + public: + spell_gen_clone_weapon_aura() : SpellScriptLoader("spell_gen_clone_weapon_aura") { } + + class spell_gen_clone_weapon_auraScript : public AuraScript + { + PrepareAuraScript(spell_gen_clone_weapon_auraScript); + + uint32 prevItem; + + bool Validate(SpellInfo const* /*spellEntry*/) + { + if (!sSpellMgr->GetSpellInfo(SPELL_COPY_WEAPON_AURA) || !sSpellMgr->GetSpellInfo(SPELL_COPY_WEAPON_2_AURA) || !sSpellMgr->GetSpellInfo(SPELL_COPY_WEAPON_3_AURA) + || !sSpellMgr->GetSpellInfo(SPELL_COPY_OFFHAND_AURA) || !sSpellMgr->GetSpellInfo(SPELL_COPY_OFFHAND_2_AURA) || !sSpellMgr->GetSpellInfo(SPELL_COPY_RANGED_AURA)) + return false; + return true; + } + + void OnApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) + { + Unit* caster = GetCaster(); + Unit* target = GetTarget(); + + if (!caster) + return; - switch (GetSpellInfo()->Id) + switch (GetSpellInfo()->Id) + { + case SPELL_COPY_WEAPON_AURA: + case SPELL_COPY_WEAPON_2_AURA: + case SPELL_COPY_WEAPON_3_AURA: { - case SPELL_COPY_WEAPON: - case SPELL_COPY_WEAPON_2: - case SPELL_COPY_WEAPON_3: + prevItem = target->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID); + + if (Player* player = caster->ToPlayer()) { - if (Player* player = caster->ToPlayer()) - { - if (Item* mainItem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND)) - target->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID, mainItem->GetEntry()); - } - else - target->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID, caster->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID)); - break; + if (Item* mainItem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND)) + target->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID, mainItem->GetEntry()); } - case SPELL_COPY_OFFHAND: - case SPELL_COPY_OFFHAND_2: + else + target->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID, caster->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID)); + break; + } + case SPELL_COPY_OFFHAND_AURA: + case SPELL_COPY_OFFHAND_2_AURA: + { + prevItem = target->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID) + 1; + + if (Player* player = caster->ToPlayer()) { - if (Player* player = caster->ToPlayer()) - { - if (Item* offItem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND)) - target->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 1, offItem->GetEntry()); - } - else - target->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 1, caster->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 1)); - break; + if (Item* offItem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND)) + target->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 1, offItem->GetEntry()); } - case SPELL_COPY_RANGED: + else + target->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 1, caster->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 1)); + break; + } + case SPELL_COPY_RANGED_AURA: + { + prevItem = target->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID) + 2; + + if (Player* player = caster->ToPlayer()) { - if (Player* player = caster->ToPlayer()) - { - if (Item* rangedItem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED)) - target->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 2, rangedItem->GetEntry()); - } - else - target->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 2, caster->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 2)); - break; + if (Item* rangedItem = player->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED)) + target->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 2, rangedItem->GetEntry()); } - default: - break; + else + target->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 2, caster->GetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 2)); + break; + } + default: + break; + } + } + + void OnRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) + { + Unit* target = GetTarget(); + + switch (GetSpellInfo()->Id) + { + case SPELL_COPY_WEAPON_AURA: + case SPELL_COPY_WEAPON_2_AURA: + case SPELL_COPY_WEAPON_3_AURA: + { + target->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID, prevItem); + break; + } + case SPELL_COPY_OFFHAND_AURA: + case SPELL_COPY_OFFHAND_2_AURA: + { + target->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 1, prevItem); + break; + } + case SPELL_COPY_RANGED_AURA: + { + target->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID + 2, prevItem); + break; } + default: + break; } } void Register() { - OnEffectHitTarget += SpellEffectFn(spell_generic_clone_weapon_SpellScript::HandleScriptEffect, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); + OnEffectApply += AuraEffectApplyFn(spell_gen_clone_weapon_auraScript::OnApply, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY, AURA_EFFECT_HANDLE_REAL_OR_REAPPLY_MASK); + OnEffectRemove += AuraEffectRemoveFn(spell_gen_clone_weapon_auraScript::OnRemove, EFFECT_0, SPELL_AURA_PERIODIC_DUMMY, AURA_EFFECT_HANDLE_REAL_OR_REAPPLY_MASK); } + }; - SpellScript* GetSpellScript() const + AuraScript* GetAuraScript() const { - return new spell_generic_clone_weapon_SpellScript(); + return new spell_gen_clone_weapon_auraScript(); } }; @@ -1844,16 +1911,18 @@ class spell_gen_break_shield: public SpellScriptLoader Unit::AuraApplicationMap const& auras = target->GetAppliedAuras(); for (Unit::AuraApplicationMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) { - Aura* aura = itr->second->GetBase(); - SpellInfo const* auraInfo = aura->GetSpellInfo(); - if (aura && auraInfo->SpellIconID == 2007 && aura->HasEffectType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN)) + if (Aura* aura = itr->second->GetBase()) { - aura->ModStackAmount(-1, AURA_REMOVE_BY_ENEMY_SPELL); - // Remove dummys from rider (Necessary for updating visual shields) - if (Unit* rider = target->GetCharmer()) - if (Aura* defend = rider->GetAura(aura->GetId())) - defend->ModStackAmount(-1, AURA_REMOVE_BY_ENEMY_SPELL); - break; + SpellInfo const* auraInfo = aura->GetSpellInfo(); + if (auraInfo && auraInfo->SpellIconID == 2007 && aura->HasEffectType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN)) + { + aura->ModStackAmount(-1, AURA_REMOVE_BY_ENEMY_SPELL); + // Remove dummys from rider (Necessary for updating visual shields) + if (Unit* rider = target->GetCharmer()) + if (Aura* defend = rider->GetAura(aura->GetId())) + defend->ModStackAmount(-1, AURA_REMOVE_BY_ENEMY_SPELL); + break; + } } } break; @@ -1972,16 +2041,18 @@ class spell_gen_mounted_charge: public SpellScriptLoader Unit::AuraApplicationMap const& auras = target->GetAppliedAuras(); for (Unit::AuraApplicationMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) { - Aura* aura = itr->second->GetBase(); - SpellInfo const* auraInfo = aura->GetSpellInfo(); - if (aura && auraInfo->SpellIconID == 2007 && aura->HasEffectType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN)) + if (Aura* aura = itr->second->GetBase()) { - aura->ModStackAmount(-1, AURA_REMOVE_BY_ENEMY_SPELL); - // Remove dummys from rider (Necessary for updating visual shields) - if (Unit* rider = target->GetCharmer()) - if (Aura* defend = rider->GetAura(aura->GetId())) - defend->ModStackAmount(-1, AURA_REMOVE_BY_ENEMY_SPELL); - break; + SpellInfo const* auraInfo = aura->GetSpellInfo(); + if (auraInfo && auraInfo->SpellIconID == 2007 && aura->HasEffectType(SPELL_AURA_MOD_DAMAGE_PERCENT_TAKEN)) + { + aura->ModStackAmount(-1, AURA_REMOVE_BY_ENEMY_SPELL); + // Remove dummys from rider (Necessary for updating visual shields) + if (Unit* rider = target->GetCharmer()) + if (Aura* defend = rider->GetAura(aura->GetId())) + defend->ModStackAmount(-1, AURA_REMOVE_BY_ENEMY_SPELL); + break; + } } } break; @@ -3077,6 +3148,96 @@ class spell_gen_mount : public SpellScriptLoader uint32 _mount310; }; +enum FoamSword +{ + ITEM_FOAM_SWORD_GREEN = 45061, + ITEM_FOAM_SWORD_PINK = 45176, + ITEM_FOAM_SWORD_BLUE = 45177, + ITEM_FOAM_SWORD_RED = 45178, + ITEM_FOAM_SWORD_YELLOW = 45179, + + SPELL_BONKED = 62991, + SPELL_FOAM_SWORD_DEFEAT = 62994, + SPELL_ON_GUARD = 62972, +}; + +class spell_gen_upper_deck_create_foam_sword : public SpellScriptLoader +{ + public: + spell_gen_upper_deck_create_foam_sword() : SpellScriptLoader("spell_gen_upper_deck_create_foam_sword") { } + + class spell_gen_upper_deck_create_foam_sword_SpellScript : public SpellScript + { + PrepareSpellScript(spell_gen_upper_deck_create_foam_sword_SpellScript); + + void HandleScript(SpellEffIndex effIndex) + { + if (Player* player = GetHitPlayer()) + { + static uint32 const itemId[5] = { ITEM_FOAM_SWORD_GREEN, ITEM_FOAM_SWORD_PINK, ITEM_FOAM_SWORD_BLUE, ITEM_FOAM_SWORD_RED, ITEM_FOAM_SWORD_YELLOW }; + // player can only have one of these items + for (uint8 i = 0; i < 5; ++i) + { + if (player->HasItemCount(itemId[i], 1, true)) + return; + } + + CreateItem(effIndex, itemId[urand(0, 4)]); + } + } + + void Register() + { + OnEffectHitTarget += SpellEffectFn(spell_gen_upper_deck_create_foam_sword_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); + } + }; + + SpellScript* GetSpellScript() const + { + return new spell_gen_upper_deck_create_foam_sword_SpellScript(); + } +}; + +class spell_gen_bonked : public SpellScriptLoader +{ + public: + spell_gen_bonked() : SpellScriptLoader("spell_gen_bonked") { } + + class spell_gen_bonked_SpellScript : public SpellScript + { + PrepareSpellScript(spell_gen_bonked_SpellScript); + + void HandleScript(SpellEffIndex /*effIndex*/) + { + if (Player* target = GetHitPlayer()) + { + Aura const* aura = GetHitAura(); + if (!(aura && aura->GetStackAmount() == 3)) + return; + + target->CastSpell(target, SPELL_FOAM_SWORD_DEFEAT, true); + target->RemoveAurasDueToSpell(SPELL_BONKED); + + if (Aura const* aura = target->GetAura(SPELL_ON_GUARD)) + { + if (Item* item = target->GetItemByGuid(aura->GetCastItemGUID())) + target->DestroyItemCount(item->GetEntry(), 1, true); + } + } + } + + void Register() + { + OnEffectHitTarget += SpellEffectFn(spell_gen_bonked_SpellScript::HandleScript, EFFECT_1, SPELL_EFFECT_SCRIPT_EFFECT); + } + }; + + SpellScript* GetSpellScript() const + { + return new spell_gen_bonked_SpellScript(); + } +}; + void AddSC_generic_spell_scripts() { new spell_gen_absorb0_hitlimit1(); @@ -3100,6 +3261,7 @@ void AddSC_generic_spell_scripts() new spell_gen_profession_research(); new spell_generic_clone(); new spell_generic_clone_weapon(); + new spell_gen_clone_weapon_aura(); new spell_gen_seaforium_blast(); new spell_gen_turkey_marker(); new spell_gen_lifeblood(); @@ -3149,4 +3311,6 @@ void AddSC_generic_spell_scripts() new spell_gen_mount("spell_blazing_hippogryph", 0, 0, 0, SPELL_BLAZING_HIPPOGRYPH_150, SPELL_BLAZING_HIPPOGRYPH_280); new spell_gen_mount("spell_celestial_steed", 0, SPELL_CELESTIAL_STEED_60, SPELL_CELESTIAL_STEED_100, SPELL_CELESTIAL_STEED_150, SPELL_CELESTIAL_STEED_280, SPELL_CELESTIAL_STEED_310); new spell_gen_mount("spell_x53_touring_rocket", 0, 0, 0, SPELL_X53_TOURING_ROCKET_150, SPELL_X53_TOURING_ROCKET_280, SPELL_X53_TOURING_ROCKET_310); + new spell_gen_upper_deck_create_foam_sword(); + new spell_gen_bonked(); } diff --git a/src/server/scripts/Spells/spell_priest.cpp b/src/server/scripts/Spells/spell_priest.cpp index 3d8ca3e729b..be5ec311c39 100644 --- a/src/server/scripts/Spells/spell_priest.cpp +++ b/src/server/scripts/Spells/spell_priest.cpp @@ -39,6 +39,9 @@ enum PriestSpells PRIEST_ICON_ID_EMPOWERED_RENEW_TALENT = 3021, PRIEST_ICON_ID_PAIN_AND_SUFFERING = 2874, PRIEST_SHADOW_WORD_DEATH = 32409, + PRIEST_SHADOWFORM_VISUAL_WITHOUT_GLYPH = 107903, + PRIEST_SHADOWFORM_VISUAL_WITH_GLYPH = 107904, + PRIEST_GLYPH_OF_SHADOW = 107906, }; // Guardian Spirit @@ -449,6 +452,46 @@ class spell_pri_shadow_word_death : public SpellScriptLoader } }; +class spell_pri_shadowform : public SpellScriptLoader +{ + public: + spell_pri_shadowform() : SpellScriptLoader("spell_pri_shadowform") { } + + class spell_pri_shadowform_AuraScript : public AuraScript + { + PrepareAuraScript(spell_pri_shadowform_AuraScript); + + bool Validate(SpellInfo const* /*entry*/) + { + if (!sSpellMgr->GetSpellInfo(PRIEST_SHADOWFORM_VISUAL_WITHOUT_GLYPH) || + !sSpellMgr->GetSpellInfo(PRIEST_SHADOWFORM_VISUAL_WITH_GLYPH)) + return false; + return true; + } + + void HandleEffectApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) + { + GetTarget()->CastSpell(GetTarget(), GetTarget()->HasAura(PRIEST_GLYPH_OF_SHADOW) ? PRIEST_SHADOWFORM_VISUAL_WITH_GLYPH : PRIEST_SHADOWFORM_VISUAL_WITHOUT_GLYPH, true); + } + + void HandleEffectRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) + { + GetTarget()->RemoveAurasDueToSpell(GetTarget()->HasAura(PRIEST_GLYPH_OF_SHADOW) ? PRIEST_SHADOWFORM_VISUAL_WITH_GLYPH : PRIEST_SHADOWFORM_VISUAL_WITHOUT_GLYPH); + } + + void Register() + { + AfterEffectApply += AuraEffectApplyFn(spell_pri_shadowform_AuraScript::HandleEffectApply, EFFECT_0, SPELL_AURA_MOD_SHAPESHIFT, AURA_EFFECT_HANDLE_REAL_OR_REAPPLY_MASK); + AfterEffectRemove += AuraEffectRemoveFn(spell_pri_shadowform_AuraScript::HandleEffectRemove, EFFECT_0, SPELL_AURA_MOD_SHAPESHIFT, AURA_EFFECT_HANDLE_REAL_OR_REAPPLY_MASK); + } + }; + + AuraScript* GetAuraScript() const + { + return new spell_pri_shadowform_AuraScript(); + } +}; + void AddSC_priest_spell_scripts() { new spell_pri_guardian_spirit(); @@ -461,4 +504,5 @@ void AddSC_priest_spell_scripts() new spell_pri_vampiric_touch(); new spell_priest_renew(); new spell_pri_shadow_word_death(); + new spell_pri_shadowform(); } diff --git a/src/server/scripts/Spells/spell_quest.cpp b/src/server/scripts/Spells/spell_quest.cpp index 5648c510413..cbf45910495 100644 --- a/src/server/scripts/Spells/spell_quest.cpp +++ b/src/server/scripts/Spells/spell_quest.cpp @@ -1245,6 +1245,75 @@ class spell_q12735_song_of_cleansing : public SpellScriptLoader } }; +enum DefendingWyrmrestTemple +{ + SPELL_SUMMON_WYRMREST_DEFENDER = 49207 +}; + +class spell_q12372_cast_from_gossip_trigger : public SpellScriptLoader +{ + public: + spell_q12372_cast_from_gossip_trigger() : SpellScriptLoader("spell_q12372_cast_from_gossip_trigger") { } + + class spell_q12372_cast_from_gossip_trigger_SpellScript : public SpellScript + { + PrepareSpellScript(spell_q12372_cast_from_gossip_trigger_SpellScript); + + void HandleScript(SpellEffIndex /*effIndex*/) + { + GetCaster()->CastSpell(GetCaster(), SPELL_SUMMON_WYRMREST_DEFENDER, true); + } + + void Register() + { + OnEffectHitTarget += SpellEffectFn(spell_q12372_cast_from_gossip_trigger_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT); + } + }; + + SpellScript* GetSpellScript() const + { + return new spell_q12372_cast_from_gossip_trigger_SpellScript(); + } +}; + +// http://www.wowhead.com/quest=12372 Defending Wyrmrest Temple +// 49370 - Wyrmrest Defender: Destabilize Azure Dragonshrine Effect +enum Quest12372Data +{ + NPC_WYRMREST_TEMPLE_CREDIT = 27698, +}; + +class spell_q12372_destabilize_azure_dragonshrine_dummy : public SpellScriptLoader +{ + public: + spell_q12372_destabilize_azure_dragonshrine_dummy() : SpellScriptLoader("spell_q12372_destabilize_azure_dragonshrine_dummy") { } + + class spell_q12372_destabilize_azure_dragonshrine_dummy_SpellScript : public SpellScript + { + PrepareSpellScript(spell_q12372_destabilize_azure_dragonshrine_dummy_SpellScript); + + void HandleDummy(SpellEffIndex /*effIndex*/) + { + if (GetHitCreature()) + if (Unit* caster = GetOriginalCaster()) + if (Vehicle* vehicle = caster->GetVehicleKit()) + if (Unit* passenger = vehicle->GetPassenger(0)) + if (Player* player = passenger->ToPlayer()) + player->KilledMonsterCredit(NPC_WYRMREST_TEMPLE_CREDIT, 0); + } + + void Register() + { + OnEffectHitTarget += SpellEffectFn(spell_q12372_destabilize_azure_dragonshrine_dummy_SpellScript::HandleDummy, EFFECT_0, SPELL_EFFECT_DUMMY); + } + }; + + SpellScript* GetSpellScript() const + { + return new spell_q12372_destabilize_azure_dragonshrine_dummy_SpellScript(); + } +}; + void AddSC_quest_spell_scripts() { new spell_q55_sacred_cleansing(); @@ -1274,4 +1343,6 @@ void AddSC_quest_spell_scripts() new spell_q12277_wintergarde_mine_explosion(); new spell_q12066_bunny_kill_credit(); new spell_q12735_song_of_cleansing(); + new spell_q12372_cast_from_gossip_trigger(); + new spell_q12372_destabilize_azure_dragonshrine_dummy(); } diff --git a/src/server/scripts/Spells/spell_shaman.cpp b/src/server/scripts/Spells/spell_shaman.cpp index c863c2363af..1c6e6e11f04 100644 --- a/src/server/scripts/Spells/spell_shaman.cpp +++ b/src/server/scripts/Spells/spell_shaman.cpp @@ -35,6 +35,8 @@ enum ShamanSpells SHAMAN_SPELL_FIRE_NOVA_TRIGGERED_R1 = 8349, SHAMAN_SPELL_SATED = 57724, SHAMAN_SPELL_EXHAUSTION = 57723, + HUNTER_SPELL_INSANITY = 95809, + MAGE_SPELL_TEMPORAL_DISPLACEMENT = 80354, SHAMAN_SPELL_STORM_EARTH_AND_FIRE = 51483, EARTHBIND_TOTEM_SPELL_EARTHGRAB = 64695, @@ -319,6 +321,8 @@ class spell_sha_bloodlust : public SpellScriptLoader void RemoveInvalidTargets(std::list<WorldObject*>& targets) { targets.remove_if(Trinity::UnitAuraCheck(true, SHAMAN_SPELL_SATED)); + targets.remove_if(Trinity::UnitAuraCheck(true, HUNTER_SPELL_INSANITY)); + targets.remove_if(Trinity::UnitAuraCheck(true, MAGE_SPELL_TEMPORAL_DISPLACEMENT)); } void ApplyDebuff() @@ -361,6 +365,8 @@ class spell_sha_heroism : public SpellScriptLoader void RemoveInvalidTargets(std::list<WorldObject*>& targets) { targets.remove_if(Trinity::UnitAuraCheck(true, SHAMAN_SPELL_EXHAUSTION)); + targets.remove_if(Trinity::UnitAuraCheck(true, HUNTER_SPELL_INSANITY)); + targets.remove_if(Trinity::UnitAuraCheck(true, MAGE_SPELL_TEMPORAL_DISPLACEMENT)); } void ApplyDebuff() diff --git a/src/server/scripts/World/achievement_scripts.cpp b/src/server/scripts/World/achievement_scripts.cpp index 60572ee3e6a..a6f4f7f64f9 100755 --- a/src/server/scripts/World/achievement_scripts.cpp +++ b/src/server/scripts/World/achievement_scripts.cpp @@ -278,6 +278,9 @@ class achievement_tilted : public AchievementCriteriaScript bool OnCheck(Player* player, Unit* /*target*/) { + if (!player) + return false; + bool checkArea = player->GetAreaId() == AREA_ARGENT_TOURNAMENT_FIELDS || player->GetAreaId() == AREA_RING_OF_ASPIRANTS || player->GetAreaId() == AREA_RING_OF_ARGENT_VALIANTS || @@ -285,7 +288,7 @@ class achievement_tilted : public AchievementCriteriaScript player->GetAreaId() == AREA_RING_OF_HORDE_VALIANTS || player->GetAreaId() == AREA_RING_OF_CHAMPIONS; - return player && checkArea && player->duel && player->duel->isMounted; + return checkArea && player->duel && player->duel->isMounted; } }; diff --git a/src/server/shared/Cryptography/BigNumber.cpp b/src/server/shared/Cryptography/BigNumber.cpp index 364ee76ec75..146b2c37ad3 100755 --- a/src/server/shared/Cryptography/BigNumber.cpp +++ b/src/server/shared/Cryptography/BigNumber.cpp @@ -75,7 +75,7 @@ void BigNumber::SetRand(int numbits) BN_rand(_bn, numbits, 0, 1); } -BigNumber BigNumber::operator=(const BigNumber &bn) +BigNumber& BigNumber::operator=(const BigNumber &bn) { if (this == &bn) return *this; diff --git a/src/server/shared/Cryptography/BigNumber.h b/src/server/shared/Cryptography/BigNumber.h index 6646245a6a0..a27d74fb5c7 100755 --- a/src/server/shared/Cryptography/BigNumber.h +++ b/src/server/shared/Cryptography/BigNumber.h @@ -39,7 +39,7 @@ class BigNumber void SetRand(int numbits); - BigNumber operator=(const BigNumber &bn); + BigNumber& operator=(const BigNumber &bn); BigNumber operator+=(const BigNumber &bn); BigNumber operator+(const BigNumber &bn) diff --git a/src/server/shared/DataStores/DBCFileLoader.cpp b/src/server/shared/DataStores/DBCFileLoader.cpp index f909c8566bb..85b61c4f143 100755 --- a/src/server/shared/DataStores/DBCFileLoader.cpp +++ b/src/server/shared/DataStores/DBCFileLoader.cpp @@ -23,10 +23,8 @@ #include "DBCFileLoader.h" #include "Errors.h" -DBCFileLoader::DBCFileLoader() +DBCFileLoader::DBCFileLoader() : stringTable(NULL), data(NULL), fieldsOffset(NULL) { - data = NULL; - fieldsOffset = NULL; } bool DBCFileLoader::Load(const char* filename, const char* fmt) diff --git a/src/server/shared/Database/AdhocStatement.cpp b/src/server/shared/Database/AdhocStatement.cpp index 9e795ae853a..95dce77e53c 100755 --- a/src/server/shared/Database/AdhocStatement.cpp +++ b/src/server/shared/Database/AdhocStatement.cpp @@ -44,6 +44,7 @@ bool BasicStatementTask::Execute() ResultSet* result = m_conn->Query(m_sql); if (!result || !result->GetRowCount()) { + delete result; m_result.set(QueryResult(NULL)); return false; } diff --git a/src/server/shared/Database/DatabaseWorkerPool.h b/src/server/shared/Database/DatabaseWorkerPool.h index 9d6fabb9dfa..001e74fc6c6 100755 --- a/src/server/shared/Database/DatabaseWorkerPool.h +++ b/src/server/shared/Database/DatabaseWorkerPool.h @@ -224,7 +224,10 @@ class DatabaseWorkerPool ResultSet* result = conn->Query(sql); conn->Unlock(); if (!result || !result->GetRowCount()) + { + delete result; return QueryResult(NULL); + } result->NextRow(); return QueryResult(result); @@ -275,7 +278,10 @@ class DatabaseWorkerPool delete stmt; if (!ret || !ret->GetRowCount()) + { + delete ret; return PreparedQueryResult(NULL); + } return PreparedQueryResult(ret); } diff --git a/src/server/shared/Database/Implementation/WorldDatabase.cpp b/src/server/shared/Database/Implementation/WorldDatabase.cpp index 74cd57f74c0..95c888249cd 100755 --- a/src/server/shared/Database/Implementation/WorldDatabase.cpp +++ b/src/server/shared/Database/Implementation/WorldDatabase.cpp @@ -78,7 +78,7 @@ void WorldDatabaseConnection::DoPrepareStatements() PREPARE_STATEMENT(WORLD_INS_CREATURE_TRANSPORT, "INSERT INTO creature_transport (guid, npc_entry, transport_entry, TransOffsetX, TransOffsetY, TransOffsetZ, TransOffsetO) values (?, ?, ?, ?, ?, ?, ?)", CONNECTION_ASYNC); PREPARE_STATEMENT(WORLD_UPD_CREATURE_TRANSPORT_EMOTE, "UPDATE creature_transport SET emote = ? WHERE transport_entry = ? AND guid = ?", CONNECTION_ASYNC); PREPARE_STATEMENT(WORLD_SEL_COMMANDS, "SELECT name, security, help FROM command", CONNECTION_SYNCH); - PREPARE_STATEMENT(WORLD_SEL_CREATURE_TEMPLATE, "SELECT difficulty_entry_1, difficulty_entry_2, difficulty_entry_3, KillCredit1, KillCredit2, modelid1, modelid2, modelid3, modelid4, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, exp, faction_A, faction_H, npcflag, speed_walk, speed_run, scale, rank, mindmg, maxdmg, dmgschool, attackpower, dmg_multiplier, baseattacktime, rangeattacktime, unit_class, unit_flags, dynamicflags, family, trainer_type, trainer_spell, trainer_class, trainer_race, minrangedmg, maxrangedmg, rangedattackpower, type, type_flags, lootid, pickpocketloot, skinloot, resistance1, resistance2, resistance3, resistance4, resistance5, resistance6, spell1, spell2, spell3, spell4, spell5, spell6, spell7, spell8, PetSpellDataId, VehicleId, mingold, maxgold, AIName, MovementType, InhabitType, HoverHeight, Health_mod, Mana_mod, Mana_mod_extra, Armor_mod, RacialLeader, questItem1, questItem2, questItem3, questItem4, questItem5, questItem6, movementId, RegenHealth, equipment_id, mechanic_immune_mask, flags_extra, ScriptName FROM creature_template WHERE entry = ?", CONNECTION_SYNCH); + PREPARE_STATEMENT(WORLD_SEL_CREATURE_TEMPLATE, "SELECT difficulty_entry_1, difficulty_entry_2, difficulty_entry_3, KillCredit1, KillCredit2, modelid1, modelid2, modelid3, modelid4, name, subname, IconName, gossip_menu_id, minlevel, maxlevel, exp, faction_A, faction_H, npcflag, speed_walk, speed_run, scale, rank, mindmg, maxdmg, dmgschool, attackpower, dmg_multiplier, baseattacktime, rangeattacktime, unit_class, unit_flags, unit_flags2, dynamicflags, family, trainer_type, trainer_spell, trainer_class, trainer_race, minrangedmg, maxrangedmg, rangedattackpower, type, type_flags, lootid, pickpocketloot, skinloot, resistance1, resistance2, resistance3, resistance4, resistance5, resistance6, spell1, spell2, spell3, spell4, spell5, spell6, spell7, spell8, PetSpellDataId, VehicleId, mingold, maxgold, AIName, MovementType, InhabitType, HoverHeight, Health_mod, Mana_mod, Mana_mod_extra, Armor_mod, RacialLeader, questItem1, questItem2, questItem3, questItem4, questItem5, questItem6, movementId, RegenHealth, equipment_id, mechanic_immune_mask, flags_extra, ScriptName FROM creature_template WHERE entry = ?", CONNECTION_SYNCH); PREPARE_STATEMENT(WORLD_SEL_WAYPOINT_SCRIPT_BY_ID, "SELECT guid, delay, command, datalong, datalong2, dataint, x, y, z, o FROM waypoint_scripts WHERE id = ?", CONNECTION_SYNCH); PREPARE_STATEMENT(WORLD_SEL_IP2NATION_COUNTRY, "SELECT c.country FROM ip2nationCountries c, ip2nation i WHERE i.ip < ? AND c.code = i.country ORDER BY i.ip DESC LIMIT 0,1", CONNECTION_SYNCH); PREPARE_STATEMENT(WORLD_SEL_ITEM_TEMPLATE_BY_NAME, "SELECT entry FROM item_template WHERE name = ?", CONNECTION_SYNCH); diff --git a/src/server/shared/Database/PreparedStatement.cpp b/src/server/shared/Database/PreparedStatement.cpp index 08b554ff696..76dc7206bd7 100755 --- a/src/server/shared/Database/PreparedStatement.cpp +++ b/src/server/shared/Database/PreparedStatement.cpp @@ -445,6 +445,7 @@ bool PreparedStatementTask::Execute() PreparedResultSet* result = m_conn->Query(m_stmt); if (!result || !result->GetRowCount()) { + delete result; m_result.set(PreparedQueryResult(NULL)); return false; } diff --git a/src/server/shared/Database/QueryHolder.cpp b/src/server/shared/Database/QueryHolder.cpp index 99772c7e323..0908ad410cd 100755 --- a/src/server/shared/Database/QueryHolder.cpp +++ b/src/server/shared/Database/QueryHolder.cpp @@ -116,6 +116,12 @@ PreparedQueryResult SQLQueryHolder::GetPreparedResult(size_t index) void SQLQueryHolder::SetResult(size_t index, ResultSet* result) { + if (result && !result->GetRowCount()) + { + delete result; + result = NULL; + } + /// store the result in the holder if (index < m_queries.size()) m_queries[index].second.qresult = result; @@ -123,6 +129,12 @@ void SQLQueryHolder::SetResult(size_t index, ResultSet* result) void SQLQueryHolder::SetPreparedResult(size_t index, PreparedResultSet* result) { + if (result && !result->GetRowCount()) + { + delete result; + result = NULL; + } + /// store the result in the holder if (index < m_queries.size()) m_queries[index].second.presult = result; diff --git a/src/server/shared/Logging/Log.cpp b/src/server/shared/Logging/Log.cpp index 3a24190d8fa..88259831095 100644 --- a/src/server/shared/Logging/Log.cpp +++ b/src/server/shared/Logging/Log.cpp @@ -103,7 +103,7 @@ void Log::CreateAppenderFromConfig(const char* name) LogLevel level = LogLevel(atoi(*iter)); if (level > LOG_LEVEL_FATAL) { - fprintf(stderr, "Log::CreateAppenderFromConfig: Wrong Log Level %u for appender %s\n", level, name); + fprintf(stderr, "Log::CreateAppenderFromConfig: Wrong Log Level %d for appender %s\n", level, name); return; } @@ -158,7 +158,7 @@ void Log::CreateAppenderFromConfig(const char* name) break; } default: - fprintf(stderr, "Log::CreateAppenderFromConfig: Unknown type %u for appender %s\n", type, name); + fprintf(stderr, "Log::CreateAppenderFromConfig: Unknown type %d for appender %s\n", type, name); break; } } @@ -260,14 +260,9 @@ void Log::ReadLoggersFromConfig() } while (ss); - LoggerMap::const_iterator it = loggers.begin(); - - while (it != loggers.end() && it->first) - ++it; - // root logger must exist. Marking as disabled as its not configured - if (it == loggers.end()) - loggers[0].Create("root", LOG_FILTER_GENERAL, LOG_LEVEL_DISABLED); + if (loggers.find(LOG_FILTER_GENERAL) == loggers.end()) + loggers[LOG_FILTER_GENERAL].Create("root", LOG_FILTER_GENERAL, LOG_LEVEL_DISABLED); } void Log::EnableDBAppenders() @@ -349,10 +344,7 @@ bool Log::SetLogLevel(std::string const& name, const char* newLevelc, bool isLog bool Log::ShouldLog(LogFilterType type, LogLevel level) const { - LoggerMap::const_iterator it = loggers.begin(); - while (it != loggers.end() && it->second.getType() != type) - ++it; - + LoggerMap::const_iterator it = loggers.find(type); if (it != loggers.end()) { LogLevel loggerLevel = it->second.getLogLevel(); @@ -443,19 +435,20 @@ void Log::outFatal(LogFilterType filter, const char * str, ...) va_end(ap); } -void Log::outCharDump(const char* param, const char * str, ...) +void Log::outCharDump(char const* str, uint32 accountId, uint32 guid, char const* name) { if (!str || !ShouldLog(LOG_FILTER_PLAYER_DUMP, LOG_LEVEL_INFO)) return; - va_list ap; - va_start(ap, str); - char text[MAX_QUERY_LEN]; - vsnprintf(text, MAX_QUERY_LEN, str, ap); - va_end(ap); + std::ostringstream ss; + ss << "== START DUMP == (account: " << accountId << " guid: " << guid << " name: " << name + << ")\n" << str << "\n== END DUMP ==\n"; + + LogMessage* msg = new LogMessage(LOG_LEVEL_INFO, LOG_FILTER_PLAYER_DUMP, ss.str()); + ss.clear(); + ss << guid << '_' << name; - LogMessage* msg = new LogMessage(LOG_LEVEL_INFO, LOG_FILTER_PLAYER_DUMP, text); - msg->param1 = param; + msg->param1 = ss.str(); write(msg); } diff --git a/src/server/shared/Logging/Log.h b/src/server/shared/Logging/Log.h index cd1e9dc80df..7980df0d52a 100644 --- a/src/server/shared/Logging/Log.h +++ b/src/server/shared/Logging/Log.h @@ -56,7 +56,7 @@ class Log void EnableDBAppenders(); void outCommand(uint32 account, const char * str, ...) ATTR_PRINTF(3, 4); - void outCharDump(const char* param, const char* str, ...) ATTR_PRINTF(3, 4); + void outCharDump(char const* str, uint32 account_id, uint32 guid, char const* name); static std::string GetTimestampStr(); void SetRealmID(uint32 id); diff --git a/src/server/shared/Packets/ByteBuffer.h b/src/server/shared/Packets/ByteBuffer.h index 0b08b4118d4..e4535378a48 100755 --- a/src/server/shared/Packets/ByteBuffer.h +++ b/src/server/shared/Packets/ByteBuffer.h @@ -189,6 +189,37 @@ class ByteBuffer put(pos, (uint8 *)&value, sizeof(value)); } + /** + * @name PutBits + * @brief Places specified amount of bits of value at specified position in packet. + * To ensure all bits are correctly written, only call this method after + * bit flush has been performed + + * @param pos Position to place the value at, in bits. The entire value must fit in the packet + * It is advised to obtain the position using bitwpos() function. + + * @param value Data to write. + * @param bitCount Number of bits to store the value on. + */ + template <typename T> void PutBits(size_t pos, T value, uint32 bitCount) + { + if (!bitCount) + throw ByteBufferSourceException((pos + bitCount) / 8, size(), 0); + + if (pos + bitCount > size() * 8) + throw ByteBufferPositionException(false, (pos + bitCount) / 8, size(), (bitCount - 1) / 8 + 1); + + for (int32 i = 0; i < bitCount; ++i) + { + size_t wp = (pos + i) / 8; + size_t bit = (pos + i) % 8; + if ((value >> (bitCount - i - 1)) & 1) + _storage[wp] |= 1 << (7 - bit); + else + _storage[wp] &= ~(1 << (7 - bit)); + } + } + ByteBuffer &operator<<(uint8 value) { append<uint8>(value); @@ -382,6 +413,16 @@ class ByteBuffer return _wpos; } + /// Returns position of last written bit + size_t bitwpos() const { return _wpos * 8 + 8 - _bitpos; } + + size_t bitwpos(size_t newPos) + { + _wpos = newPos / 8; + _bitpos = 8 - (newPos % 8); + return _wpos * 8 + 8 - _bitpos; + } + template<typename T> void read_skip() { read_skip(sizeof(T)); } diff --git a/src/server/shared/Utilities/ServiceWin32.cpp b/src/server/shared/Utilities/ServiceWin32.cpp index c6e9d385be3..91a78af1adc 100755 --- a/src/server/shared/Utilities/ServiceWin32.cpp +++ b/src/server/shared/Utilities/ServiceWin32.cpp @@ -52,8 +52,6 @@ typedef WINADVAPI BOOL (WINAPI *CSD_T)(SC_HANDLE, DWORD, LPCVOID); bool WinServiceInstall() { - CSD_T ChangeService_Config2; - HMODULE advapi32; SC_HANDLE serviceControlManager = OpenSCManager(0, 0, SC_MANAGER_CREATE_SERVICE); if (serviceControlManager) @@ -79,7 +77,7 @@ bool WinServiceInstall() 0); // no password if (service) { - advapi32 = GetModuleHandle("ADVAPI32.DLL"); + HMODULE advapi32 = GetModuleHandle("ADVAPI32.DLL"); if (!advapi32) { CloseServiceHandle(service); @@ -87,7 +85,7 @@ bool WinServiceInstall() return false; } - ChangeService_Config2 = (CSD_T) GetProcAddress(advapi32, "ChangeServiceConfig2A"); + CSD_T ChangeService_Config2 = (CSD_T) GetProcAddress(advapi32, "ChangeServiceConfig2A"); if (!ChangeService_Config2) { CloseServiceHandle(service); diff --git a/src/server/shared/Utilities/Util.cpp b/src/server/shared/Utilities/Util.cpp index 7bedf9690ca..9917bbb5309 100755 --- a/src/server/shared/Utilities/Util.cpp +++ b/src/server/shared/Utilities/Util.cpp @@ -217,7 +217,7 @@ uint32 CreatePIDFile(const std::string& filename) pid_t pid = getpid(); #endif - fprintf(pid_file, "%d", pid ); + fprintf(pid_file, "%u", pid ); fclose(pid_file); return (uint32)pid; diff --git a/src/server/worldserver/Main.cpp b/src/server/worldserver/Main.cpp index 862ed28f2d3..7e43cf87dfc 100755 --- a/src/server/worldserver/Main.cpp +++ b/src/server/worldserver/Main.cpp @@ -81,7 +81,7 @@ extern int main(int argc, char **argv) { if (++c >= argc) { - sLog->outError(LOG_FILTER_WORLDSERVER, "Runtime-Error: -c option requires an input argument"); + printf("Runtime-Error: -c option requires an input argument"); usage(argv[0]); return 1; } @@ -97,25 +97,25 @@ extern int main(int argc, char **argv) { if (++c >= argc) { - sLog->outError(LOG_FILTER_WORLDSERVER, "Runtime-Error: -s option requires an input argument"); + printf("Runtime-Error: -s option requires an input argument"); usage(argv[0]); return 1; } if (strcmp(argv[c], "install") == 0) { if (WinServiceInstall()) - sLog->outInfo(LOG_FILTER_WORLDSERVER, "Installing service"); + printf("Installing service"); return 1; } else if (strcmp(argv[c], "uninstall") == 0) { if (WinServiceUninstall()) - sLog->outInfo(LOG_FILTER_WORLDSERVER, "Uninstalling service"); + printf("Uninstalling service"); return 1; } else { - sLog->outError(LOG_FILTER_WORLDSERVER, "Runtime-Error: unsupported option %s", argv[c]); + printf("Runtime-Error: unsupported option %s", argv[c]); usage(argv[0]); return 1; } @@ -131,8 +131,8 @@ extern int main(int argc, char **argv) if (!ConfigMgr::Load(cfg_file)) { - sLog->outError(LOG_FILTER_WORLDSERVER, "Invalid or missing configuration file : %s", cfg_file); - sLog->outError(LOG_FILTER_WORLDSERVER, "Verify that the file exists and has \'[worldserver]' written in the top of the file!"); + printf("Invalid or missing configuration file : %s", cfg_file); + printf("Verify that the file exists and has \'[worldserver]' written in the top of the file!"); return 1; } sLog->outInfo(LOG_FILTER_WORLDSERVER, "Using configuration file %s.", cfg_file); diff --git a/src/server/worldserver/TCSoap/TCSoap.h b/src/server/worldserver/TCSoap/TCSoap.h index 285adaaaf4b..51ffb3a91c8 100755 --- a/src/server/worldserver/TCSoap/TCSoap.h +++ b/src/server/worldserver/TCSoap/TCSoap.h @@ -51,7 +51,7 @@ class SOAPCommand { public: SOAPCommand(): - pendingCommands(0, USYNC_THREAD, "pendingCommands") + pendingCommands(0, USYNC_THREAD, "pendingCommands"), m_success(false) { } diff --git a/src/server/worldserver/worldserver.conf.dist b/src/server/worldserver/worldserver.conf.dist index fbd45bec8e1..5a9a1b86866 100644 --- a/src/server/worldserver/worldserver.conf.dist +++ b/src/server/worldserver/worldserver.conf.dist @@ -26,6 +26,7 @@ # CONSOLE AND REMOTE ACCESS # CHARACTER DELETE OPTIONS # CUSTOM SERVER OPTIONS +# LOGGING SYSTEM SETTINGS # ################################################################################################### @@ -49,7 +50,7 @@ # # RealmID # Description: ID of the Realm using this config. -# Important: RealmID must match the realmlist inside the realmd database. +# Important: RealmID must match the realmlist inside the auth database. # Default: 1 RealmID = 1 @@ -174,7 +175,7 @@ Compression = 1 # PlayerLimit # Description: Maximum number of players in the world. Excluding Mods, GMs and Admins. # Important: If you want to block players and only allow Mods, GMs or Admins to join the -# server, use the DB field "realmd.realmlist.allowedSecurityLevel". +# server, use the DB field "auth.realmlist.allowedSecurityLevel". # Default: 100 - (Enabled) # 1+ - (Enabled) # 0 - (Disabled, No limit) @@ -392,6 +393,14 @@ CleanCharacterDB = 0 PersistentCharacterCleanFlags = 0 # +# GuildSaveInterval +# Description: Time (in minutes) between guild experience saves +# Default: 15 +# + +GuildSaveInterval = 15 + +# ################################################################################################### ################################################################################################### @@ -2645,7 +2654,7 @@ PlayerDump.DisallowOverwrite = 1 ################################################################################################### # -# Logging system options. +# LOGGING SYSTEM SETTINGS # # Appender config values: Given a appender "name" # Appender.name @@ -2788,7 +2797,7 @@ Appenders=Console Server GM DBErrors Char RA Warden Chat # Logger.Root=0,5,Console Server -Logger.Chat=22,3,Chat +Logger.Chat=22,2,Chat Logger.DBErrors=26,5,Console Server DBErrors Logger.GM=27,3,Console Server GM Logger.RA=28,3,RA @@ -2809,3 +2818,6 @@ Logger.Opcodes=41,6,Console Server # Default: "Root Chat DBErrors GM RA Warden Character Load" Loggers=Root Chat DBErrors GM RA Warden Character Load WorldServer Opcodes + +# +###################################################################################################
\ No newline at end of file diff --git a/src/tools/map_extractor/System.cpp b/src/tools/map_extractor/System.cpp index 448cf2320b2..63132d269b2 100644 --- a/src/tools/map_extractor/System.cpp +++ b/src/tools/map_extractor/System.cpp @@ -9,6 +9,7 @@ #include "direct.h" #else #include <sys/stat.h> +#include <unistd.h> #define ERROR_PATH_NOT_FOUND ERROR_FILE_NOT_FOUND #endif @@ -957,7 +958,7 @@ void ExtractMapsFromMpq(uint32 build) printf("Convert map files\n"); for (uint32 z = 0; z < map_count; ++z) { - printf("Extract %s (%d/%d) \n", map_ids[z].name, z+1, map_count); + printf("Extract %s (%d/%u) \n", map_ids[z].name, z+1, map_count); // Loadup map grid data sprintf(mpq_map_name, "World\\Maps\\%s\\%s.wdt", map_ids[z].name, map_ids[z].name); WDT_file wdt; diff --git a/src/tools/vmap4_extractor/adtfile.cpp b/src/tools/vmap4_extractor/adtfile.cpp index c53b63ffa5e..d2ad71b8179 100644 --- a/src/tools/vmap4_extractor/adtfile.cpp +++ b/src/tools/vmap4_extractor/adtfile.cpp @@ -26,7 +26,7 @@ #define snprintf _snprintf #endif -const char * GetPlainName(const char * FileName) +char const* GetPlainName(char const* FileName) { const char * szTemp; @@ -35,7 +35,7 @@ const char * GetPlainName(const char * FileName) return FileName; } -char * GetPlainName(char * FileName) +char* GetPlainName(char* FileName) { char * szTemp; @@ -44,24 +44,21 @@ char * GetPlainName(char * FileName) return FileName; } -void fixnamen(char *name, size_t len) +void fixnamen(char* name, size_t len) { - for (size_t i=0; i<len-3; i++) + for (size_t i = 0; i < len-3; i++) { - if (i>0 && name[i]>='A' && name[i]<='Z' && isalpha(name[i-1])) - { + if (i > 0 && name[i] >= 'A' && name[i] <= 'Z' && isalpha(name[i-1])) name[i] |= 0x20; - } else if ((i==0 || !isalpha(name[i-1])) && name[i]>='a' && name[i]<='z') - { + else if ((i == 0 || !isalpha(name[i-1])) && name[i]>='a' && name[i]<='z') name[i] &= ~0x20; - } } //extension in lowercase - for(size_t i=len-3; i<len; i++) + for (size_t i = len - 3; i < len; i++) name[i] |= 0x20; } -void fixname2(char *name, size_t len) +void fixname2(char* name, size_t len) { for (size_t i=0; i<len-3; i++) { @@ -70,10 +67,10 @@ void fixname2(char *name, size_t len) } } -char * GetExtension(char * FileName) +char* GetExtension(char* FileName) { - char * szTemp; - if((szTemp = strrchr(FileName, '.')) != NULL) + char* szTemp; + if (szTemp = strrchr(FileName, '.')) return szTemp; return NULL; } @@ -101,7 +98,7 @@ bool ADTFile::init(uint32 map_num, uint32 tileX, uint32 tileY) xMap = TempMapNumber.substr(TempMapNumber.find("_")+1,(TempMapNumber.find_last_of("_")-1) - (TempMapNumber.find("_"))); yMap = TempMapNumber.substr(TempMapNumber.find_last_of("_")+1,(TempMapNumber.length()) - (TempMapNumber.find_last_of("_"))); Adtfilename.erase((Adtfilename.length()-xMap.length()-yMap.length()-2), (xMap.length()+yMap.length()+2)); - string AdtMapNumber = xMap + ' ' + yMap + ' ' + GetPlainName((char*)Adtfilename.c_str()); + //string AdtMapNumber = xMap + ' ' + yMap + ' ' + GetPlainName((char*)Adtfilename.c_str()); //printf("Processing map %s...\n", AdtMapNumber.c_str()); //printf("MapNumber = %s\n", TempMapNumber.c_str()); //printf("xMap = %s\n", xMap.c_str()); @@ -161,18 +158,17 @@ bool ADTFile::init(uint32 map_num, uint32 tileX, uint32 tileY) { if (size) { - char *buf = new char[size]; + char* buf = new char[size]; ADT.read(buf, size); - char *p=buf; + char* p=buf; int q = 0; WmoInstansName = new string[size]; while (p<buf+size) { - string path(p); - char* s=GetPlainName(p); - fixnamen(s,strlen(s)); - fixname2(s,strlen(s)); - p=p+strlen(p)+1; + char* s = GetPlainName(p); + fixnamen(s, strlen(s)); + fixname2(s, strlen(s)); + p += strlen(p) + 1; WmoInstansName[q++] = s; } delete[] buf; diff --git a/src/tools/vmap4_extractor/model.cpp b/src/tools/vmap4_extractor/model.cpp index d98dca9001b..7a03cea23c0 100644 --- a/src/tools/vmap4_extractor/model.cpp +++ b/src/tools/vmap4_extractor/model.cpp @@ -28,15 +28,14 @@ extern HANDLE WorldMpq; Model::Model(std::string &filename) : filename(filename), vertices(0), indices(0) { + memset(&header, 0, sizeof(header)); } bool Model::open() { MPQFile f(WorldMpq, filename.c_str()); - ok = !f.isEof(); - - if (!ok) + if (f.isEof()) { f.close(); // Do not show this error on console to avoid confusion, the extractor can continue working even if some models fail to load @@ -54,9 +53,7 @@ bool Model::open() vertices = new Vec3D[header.nBoundingVertices]; f.read(vertices,header.nBoundingVertices*12); for (uint32 i=0; i<header.nBoundingVertices; i++) - { vertices[i] = fixCoordSystem(vertices[i]); - } f.seek(0); f.seekRelative(header.ofsBoundingTriangles); indices = new uint16[header.nBoundingTriangles]; @@ -75,13 +72,13 @@ bool Model::open() bool Model::ConvertToVMAPModel(const char * outfilename) { int N[12] = {0,0,0,0,0,0,0,0,0,0,0,0}; - FILE * output=fopen(outfilename,"wb"); - if(!output) + FILE* output=fopen(outfilename, "wb"); + if (!output) { printf("Can't create the output file '%s'\n",outfilename); return false; } - fwrite(szRawVMAPMagic,8,1,output); + fwrite(szRawVMAPMagic, 8, 1, output); uint32 nVertices = 0; nVertices = header.nBoundingVertices; fwrite(&nVertices, sizeof(int), 1, output); @@ -103,20 +100,18 @@ bool Model::ConvertToVMAPModel(const char * outfilename) wsize = sizeof(uint32) + sizeof(unsigned short) * nIndexes; fwrite(&wsize, sizeof(int), 1, output); fwrite(&nIndexes, sizeof(uint32), 1, output); - if(nIndexes >0) - { + if (nIndexes >0) fwrite(indices, sizeof(unsigned short), nIndexes, output); - } - fwrite("VERT",4, 1, output); + + fwrite("VERT", 4, 1, output); wsize = sizeof(int) + sizeof(float) * 3 * nVertices; fwrite(&wsize, sizeof(int), 1, output); fwrite(&nVertices, sizeof(int), 1, output); - if(nVertices >0) + if (nVertices >0) { for(uint32 vpos=0; vpos <nVertices; ++vpos) - { std::swap(vertices[vpos].y, vertices[vpos].z); - } + fwrite(vertices, sizeof(float)*3, nVertices, output); } @@ -136,24 +131,24 @@ Vec3D fixCoordSystem2(Vec3D v) return Vec3D(v.x, v.z, v.y); } -ModelInstance::ModelInstance(MPQFile &f,const char* ModelInstName, uint32 mapID, uint32 tileX, uint32 tileY, FILE *pDirfile) +ModelInstance::ModelInstance(MPQFile& f, char const* ModelInstName, uint32 mapID, uint32 tileX, uint32 tileY, FILE *pDirfile) + : model(NULL), d1(0), w(0.0f) { float ff[3]; f.read(&id, 4); - f.read(ff,12); - pos = fixCoords(Vec3D(ff[0],ff[1],ff[2])); - f.read(ff,12); - rot = Vec3D(ff[0],ff[1],ff[2]); - f.read(&scale,4); + f.read(ff, 12); + pos = fixCoords(Vec3D(ff[0], ff[1], ff[2])); + f.read(ff, 12); + rot = Vec3D(ff[0], ff[1], ff[2]); + f.read(&scale, 4); // scale factor - divide by 1024. blizzard devs must be on crack, why not just use a float? sc = scale / 1024.0f; char tempname[512]; sprintf(tempname, "%s/%s", szWorkDirWmo, ModelInstName); - FILE *input; - input = fopen(tempname, "r+b"); + FILE* input = fopen(tempname, "r+b"); - if(!input) + if (!input) { //printf("ModelInstance::ModelInstance couldn't open %s\n", tempname); return; @@ -169,7 +164,9 @@ ModelInstance::ModelInstance(MPQFile &f,const char* ModelInstName, uint32 mapID, uint16 adtId = 0;// not used for models uint32 flags = MOD_M2; - if(tileX == 65 && tileY == 65) flags |= MOD_WORLDSPAWN; + if (tileX == 65 && tileY == 65) + flags |= MOD_WORLDSPAWN; + //write mapID, tileX, tileY, Flags, ID, Pos, Rot, Scale, name fwrite(&mapID, sizeof(uint32), 1, pDirfile); fwrite(&tileX, sizeof(uint32), 1, pDirfile); diff --git a/src/tools/vmap4_extractor/model.h b/src/tools/vmap4_extractor/model.h index 9000d7e4822..acd31d58ec9 100644 --- a/src/tools/vmap4_extractor/model.h +++ b/src/tools/vmap4_extractor/model.h @@ -20,12 +20,9 @@ #define MODEL_H #include "vec3d.h" -//#include "mpq.h" #include "modelheaders.h" #include <vector> -class Model; -class WMOInstance; class MPQFile; Vec3D fixCoordSystem(Vec3D v); @@ -34,18 +31,14 @@ class Model { public: ModelHeader header; - uint32 offsBB_vertices, offsBB_indices; - Vec3D *BB_vertices, *vertices; - uint16 *BB_indices, *indices; - size_t nIndices; + Vec3D* vertices; + uint16* indices; bool open(); - bool ConvertToVMAPModel(const char * outfilename); + bool ConvertToVMAPModel(char const* outfilename); - bool ok; - - Model(std::string &filename); - ~Model() {_unload();} + Model(std::string& filename); + ~Model() { _unload(); } private: void _unload() @@ -55,22 +48,22 @@ private: vertices = NULL; indices = NULL; } + std::string filename; - char outfilename; }; class ModelInstance { public: - Model *model; + Model* model; uint32 id; Vec3D pos, rot; unsigned int d1, scale; - float w,sc; + float w, sc; - ModelInstance() {} - ModelInstance(MPQFile &f,const char* ModelInstName, uint32 mapID, uint32 tileX, uint32 tileY, FILE *pDirfile); + ModelInstance() : model(NULL), d1(0), scale(0), w(0.0f), sc(0.0f), id(0) {} + ModelInstance(MPQFile& f, char const* ModelInstName, uint32 mapID, uint32 tileX, uint32 tileY, FILE* pDirfile); }; diff --git a/src/tools/vmap4_extractor/vmapexport.cpp b/src/tools/vmap4_extractor/vmapexport.cpp index 489655659c3..eebc763f2f2 100644 --- a/src/tools/vmap4_extractor/vmapexport.cpp +++ b/src/tools/vmap4_extractor/vmapexport.cpp @@ -334,12 +334,12 @@ bool ExtractSingleWmo(std::string& fname) int p = 0; //Select root wmo files - const char * rchr = strrchr(plain_name, '_'); + char const* rchr = strrchr(plain_name, '_'); if(rchr != NULL) { char cpy[4]; - strncpy((char*)cpy,rchr,4); - for (int i=0;i < 4; ++i) + strncpy((char*)cpy, rchr, 4); + for (int i = 0; i < 4; ++i) { int m = cpy[i]; if(isdigit(m)) @@ -375,7 +375,7 @@ bool ExtractSingleWmo(std::string& fname) strcpy(temp, fname.c_str()); temp[fname.length()-4] = 0; char groupFileName[1024]; - sprintf(groupFileName,"%s_%03d.wmo",temp, i); + sprintf(groupFileName, "%s_%03u.wmo", temp, i); //printf("Trying to open groupfile %s\n",groupFileName); string s = groupFileName; diff --git a/src/tools/vmap4_extractor/wdtfile.cpp b/src/tools/vmap4_extractor/wdtfile.cpp index 2dd7396ae7d..9e208dac8dc 100644 --- a/src/tools/vmap4_extractor/wdtfile.cpp +++ b/src/tools/vmap4_extractor/wdtfile.cpp @@ -80,9 +80,8 @@ bool WDTFile::init(char *map_id, unsigned int mapID) char *p=buf; int q = 0; gWmoInstansName = new string[size]; - while (p<buf+size) + while (p < buf + size) { - string path(p); char* s=wdtGetPlainName(p); fixnamen(s,strlen(s)); p=p+strlen(p)+1; @@ -91,23 +90,20 @@ bool WDTFile::init(char *map_id, unsigned int mapID) delete[] buf; } } - else if (!strcmp(fourcc,"MODF")) + else if (!strcmp(fourcc, "MODF")) { // global wmo instance data if (size) { gnWMO = (int)size / 64; - string gWMO_mapname; - string fake_mapname; - fake_mapname = "65 65 "; - //gWMO_mapname = fake_mapname + filename; - gWMO_mapname = fake_mapname + std::string(map_id); - for (int i=0; i<gnWMO; ++i) + + for (int i = 0; i < gnWMO; ++i) { int id; WDT.read(&id, 4); - WMOInstance inst(WDT,gWmoInstansName[id].c_str(),mapID, 65, 65, dirfile); + WMOInstance inst(WDT,gWmoInstansName[id].c_str(), mapID, 65, 65, dirfile); } + delete[] gWmoInstansName; } } diff --git a/src/tools/vmap4_extractor/wdtfile.h b/src/tools/vmap4_extractor/wdtfile.h index ef3ec6db98c..b085965343a 100644 --- a/src/tools/vmap4_extractor/wdtfile.h +++ b/src/tools/vmap4_extractor/wdtfile.h @@ -13,16 +13,15 @@ class WDTFile public: WDTFile(char* file_name, char* file_name1); ~WDTFile(void); - bool init(char *map_id, unsigned int mapID); + bool init(char* map_id, unsigned int mapID); string* gWmoInstansName; - int gnWMO, nMaps; + int gnWMO; ADTFile* GetMap(int x, int z); private: MPQFile WDT; - bool maps[64][64]; string filename; }; diff --git a/src/tools/vmap4_extractor/wmo.cpp b/src/tools/vmap4_extractor/wmo.cpp index 8bba5610c88..85cae02e41c 100644 --- a/src/tools/vmap4_extractor/wmo.cpp +++ b/src/tools/vmap4_extractor/wmo.cpp @@ -31,8 +31,12 @@ using namespace std; extern uint16 *LiqType; -WMORoot::WMORoot(std::string &filename) : filename(filename) +WMORoot::WMORoot(std::string &filename) + : filename(filename), col(0), nTextures(0), nGroups(0), nP(0), nLights(0), + nModels(0), nDoodads(0), nDoodadSets(0), RootWMOID(0), liquidType(0) { + memset(bbcorn1, 0, sizeof(bbcorn1)); + memset(bbcorn2, 0, sizeof(bbcorn2)); } extern HANDLE WorldMpq; @@ -59,7 +63,7 @@ bool WMORoot::open() size_t nextpos = f.getPos() + size; - if (!strcmp(fourcc,"MOHD"))//header + if (!strcmp(fourcc,"MOHD")) // header { f.read(&nTextures, 4); f.read(&nGroups, 4); @@ -70,8 +74,8 @@ bool WMORoot::open() f.read(&nDoodadSets, 4); f.read(&col, 4); f.read(&RootWMOID, 4); - f.read(bbcorn1,12); - f.read(bbcorn2,12); + f.read(bbcorn1, 12); + f.read(bbcorn2, 12); f.read(&liquidType, 4); break; } @@ -122,15 +126,15 @@ bool WMORoot::open() return true; } -bool WMORoot::ConvertToVMAPRootWmo(FILE *pOutfile) +bool WMORoot::ConvertToVMAPRootWmo(FILE* pOutfile) { //printf("Convert RootWmo...\n"); - fwrite(szRawVMAPMagic,1,8,pOutfile); + fwrite(szRawVMAPMagic, 1, 8, pOutfile); unsigned int nVectors = 0; - fwrite(&nVectors,sizeof(nVectors),1,pOutfile); // will be filled later - fwrite(&nGroups,4,1,pOutfile); - fwrite(&RootWMOID,4,1,pOutfile); + fwrite(&nVectors,sizeof(nVectors), 1, pOutfile); // will be filled later + fwrite(&nGroups, 4, 1, pOutfile); + fwrite(&RootWMOID, 4, 1, pOutfile); return true; } @@ -138,9 +142,13 @@ WMORoot::~WMORoot() { } -WMOGroup::WMOGroup(std::string &filename) : filename(filename), - MOPY(0), MOVI(0), MoviEx(0), MOVT(0), MOBA(0), MobaEx(0), hlq(0), LiquEx(0), LiquBytes(0) +WMOGroup::WMOGroup(const std::string &filename) : + filename(filename), MOPY(0), MOVI(0), MoviEx(0), MOVT(0), MOBA(0), MobaEx(0), + hlq(0), LiquEx(0), LiquBytes(0), groupName(0), descGroupName(0), mogpFlags(0), + mopy_size(0), moba_size(0), LiquEx_size(0), nVertices(0), nTriangles(0) { + memset(bbcorn1, 0, sizeof(bbcorn1)); + memset(bbcorn2, 0, sizeof(bbcorn2)); } bool WMOGroup::open() @@ -239,7 +247,7 @@ bool WMOGroup::open() return true; } -int WMOGroup::ConvertToVMAPGroupWmo(FILE *output, WMORoot *rootWMO, bool pPreciseVectorData) +int WMOGroup::ConvertToVMAPGroupWmo(FILE *output, WMORoot *rootWMO, bool preciseVectorData) { fwrite(&mogpFlags,sizeof(uint32),1,output); fwrite(&groupWMOID,sizeof(uint32),1,output); @@ -248,7 +256,7 @@ int WMOGroup::ConvertToVMAPGroupWmo(FILE *output, WMORoot *rootWMO, bool pPrecis fwrite(bbcorn2, sizeof(float), 3, output); fwrite(&liquflags,sizeof(uint32),1,output); int nColTriangles = 0; - if(pPreciseVectorData) + if (preciseVectorData) { char GRP[] = "GRP "; fwrite(GRP,1,4,output); @@ -481,10 +489,9 @@ WMOGroup::~WMOGroup() delete [] LiquBytes; } -WMOInstance::WMOInstance(MPQFile &f,const char* WmoInstName, uint32 mapID, uint32 tileX, uint32 tileY, FILE *pDirfile) +WMOInstance::WMOInstance(MPQFile& f, char const* WmoInstName, uint32 mapID, uint32 tileX, uint32 tileY, FILE* pDirfile) + : currx(0), curry(0), wmo(NULL), doodadset(0), pos(), indx(0), d3(0) { - pos = Vec3D(0,0,0); - float ff[3]; f.read(&id, 4); f.read(ff,12); diff --git a/src/tools/vmap4_extractor/wmo.h b/src/tools/vmap4_extractor/wmo.h index 7020bb90f12..02e4be4aa79 100644 --- a/src/tools/vmap4_extractor/wmo.h +++ b/src/tools/vmap4_extractor/wmo.h @@ -50,14 +50,13 @@ public: float bbcorn1[3]; float bbcorn2[3]; - WMORoot(std::string &filename); + WMORoot(std::string& filename); ~WMORoot(); bool open(); - bool ConvertToVMAPRootWmo(FILE *output); + bool ConvertToVMAPRootWmo(FILE* output); private: std::string filename; - char outfilename; }; struct WMOLiquidHeader @@ -89,30 +88,29 @@ public: uint16 nBatchB; uint32 nBatchC, fogIdx, liquidType, groupWMOID; - int mopy_size,moba_size; + int mopy_size, moba_size; int LiquEx_size; unsigned int nVertices; // number when loaded int nTriangles; // number when loaded - char *MOPY; - uint16 *MOVI; - uint16 *MoviEx; - float *MOVT; - uint16 *MOBA; - int *MobaEx; - WMOLiquidHeader *hlq; - WMOLiquidVert *LiquEx; - char *LiquBytes; + char* MOPY; + uint16* MOVI; + uint16* MoviEx; + float* MOVT; + uint16* MOBA; + int* MobaEx; + WMOLiquidHeader* hlq; + WMOLiquidVert* LiquEx; + char* LiquBytes; uint32 liquflags; - WMOGroup(std::string &filename); + WMOGroup(std::string const& filename); ~WMOGroup(); bool open(); - int ConvertToVMAPGroupWmo(FILE *output, WMORoot *rootWMO, bool pPreciseVectorData); + int ConvertToVMAPGroupWmo(FILE* output, WMORoot* rootWMO, bool preciseVectorData); private: std::string filename; - char outfilename; }; class WMOInstance @@ -122,13 +120,13 @@ public: std::string MapName; int currx; int curry; - WMOGroup *wmo; + WMOGroup* wmo; Vec3D pos; Vec3D pos2, pos3, rot; - uint32 indx,id, d2, d3; + uint32 indx, id, d2, d3; int doodadset; - WMOInstance(MPQFile &f,const char* WmoInstName, uint32 mapID, uint32 tileX, uint32 tileY, FILE *pDirfile); + WMOInstance(MPQFile&f , char const* WmoInstName, uint32 mapID, uint32 tileX, uint32 tileY, FILE* pDirfile); static void reset(); }; |