aboutsummaryrefslogtreecommitdiff
path: root/src/shared
diff options
context:
space:
mode:
Diffstat (limited to 'src/shared')
-rw-r--r--src/shared/Auth/AuthCrypt.cpp85
-rw-r--r--src/shared/Auth/AuthCrypt.h20
-rw-r--r--src/shared/Auth/BigNumber.cpp4
-rw-r--r--src/shared/Auth/BigNumber.h4
-rw-r--r--src/shared/Auth/CMakeLists.txt2
-rw-r--r--src/shared/Auth/Hmac.cpp26
-rw-r--r--src/shared/Auth/Hmac.h13
-rw-r--r--src/shared/Auth/Makefile.am43
-rw-r--r--src/shared/Auth/SARC4.cpp52
-rw-r--r--src/shared/Auth/SARC4.h36
-rw-r--r--src/shared/Auth/Sha1.cpp4
-rw-r--r--src/shared/Auth/Sha1.h4
-rw-r--r--src/shared/Base.cpp68
-rw-r--r--src/shared/Base.h55
-rw-r--r--src/shared/ByteBuffer.h156
-rw-r--r--src/shared/CMakeLists.txt9
-rw-r--r--src/shared/Common.cpp4
-rw-r--r--src/shared/Common.h59
-rw-r--r--src/shared/Config/Config.cpp118
-rw-r--r--src/shared/Config/Config.h20
-rw-r--r--src/shared/Config/ConfigEnv.h4
-rw-r--r--src/shared/Config/Makefile.am42
-rw-r--r--src/shared/Config/dotconfpp/dotconfpp.cpp36
-rw-r--r--src/shared/Config/dotconfpp/dotconfpp.h13
-rw-r--r--src/shared/Config/dotconfpp/mempool.cpp6
-rw-r--r--src/shared/Database/CMakeLists.txt15
-rw-r--r--src/shared/Database/DBCEnums.h123
-rw-r--r--src/shared/Database/DBCFileLoader.cpp (renamed from src/shared/Database/dbcfile.cpp)53
-rw-r--r--src/shared/Database/DBCFileLoader.h (renamed from src/shared/Database/dbcfile.h)21
-rw-r--r--src/shared/Database/DBCStore.h94
-rw-r--r--src/shared/Database/DBCStores.cpp654
-rw-r--r--src/shared/Database/DBCStores.h208
-rw-r--r--src/shared/Database/DBCStructure.h904
-rw-r--r--src/shared/Database/DBCfmt.cpp86
-rw-r--r--src/shared/Database/Database.cpp26
-rw-r--r--src/shared/Database/Database.h25
-rw-r--r--src/shared/Database/DatabaseEnv.h7
-rw-r--r--src/shared/Database/DatabaseImpl.h8
-rw-r--r--src/shared/Database/DatabaseMysql.cpp95
-rw-r--r--src/shared/Database/DatabaseMysql.h13
-rw-r--r--src/shared/Database/DatabasePostgre.cpp108
-rw-r--r--src/shared/Database/DatabasePostgre.h13
-rw-r--r--src/shared/Database/DatabaseSqlite.cpp104
-rw-r--r--src/shared/Database/DatabaseSqlite.h46
-rw-r--r--src/shared/Database/Field.cpp4
-rw-r--r--src/shared/Database/Field.h6
-rw-r--r--src/shared/Database/Makefile.am59
-rw-r--r--src/shared/Database/MySQLDelayThread.h4
-rw-r--r--src/shared/Database/PGSQLDelayThread.h4
-rw-r--r--src/shared/Database/QueryResult.h60
-rw-r--r--src/shared/Database/QueryResultMysql.cpp13
-rw-r--r--src/shared/Database/QueryResultMysql.h6
-rw-r--r--src/shared/Database/QueryResultPostgre.cpp9
-rw-r--r--src/shared/Database/QueryResultPostgre.h4
-rw-r--r--src/shared/Database/QueryResultSqlite.cpp99
-rw-r--r--src/shared/Database/QueryResultSqlite.h46
-rw-r--r--src/shared/Database/SQLStorage.cpp26
-rw-r--r--src/shared/Database/SQLStorage.h4
-rw-r--r--src/shared/Database/SQLStorageImpl.h12
-rw-r--r--src/shared/Database/SqlDelayThread.cpp6
-rw-r--r--src/shared/Database/SqlDelayThread.h21
-rw-r--r--src/shared/Database/SqlOperations.cpp6
-rw-r--r--src/shared/Database/SqlOperations.h11
-rw-r--r--src/shared/Errors.h15
-rw-r--r--src/shared/LockedQueue.h144
-rw-r--r--src/shared/Log.cpp574
-rw-r--r--src/shared/Log.h164
-rw-r--r--src/shared/Makefile.am85
-rw-r--r--src/shared/MemoryLeaks.cpp32
-rw-r--r--src/shared/MemoryLeaks.h48
-rw-r--r--src/shared/Mthread.cpp206
-rw-r--r--src/shared/Mthread.h63
-rw-r--r--src/shared/PacketLog.cpp4
-rw-r--r--src/shared/PacketLog.h4
-rw-r--r--src/shared/ProgressBar.cpp4
-rw-r--r--src/shared/ProgressBar.h4
-rw-r--r--src/shared/ServiceWin32.cpp10
-rw-r--r--src/shared/ServiceWin32.h4
-rw-r--r--src/shared/SystemConfig.h6
-rw-r--r--src/shared/SystemConfig.h.in103
-rw-r--r--src/shared/Threading.cpp205
-rw-r--r--src/shared/Threading.h99
-rw-r--r--src/shared/Timer.h4
-rw-r--r--src/shared/Util.cpp71
-rw-r--r--src/shared/Util.h258
-rw-r--r--src/shared/WorldPacket.h4
-rw-r--r--src/shared/vmap/BaseModel.cpp4
-rw-r--r--src/shared/vmap/BaseModel.h4
-rw-r--r--src/shared/vmap/CoordModelMapping.cpp103
-rw-r--r--src/shared/vmap/CoordModelMapping.h5
-rw-r--r--src/shared/vmap/DebugCmdLogger.cpp6
-rw-r--r--src/shared/vmap/DebugCmdLogger.h4
-rw-r--r--src/shared/vmap/IVMapManager.h4
-rw-r--r--src/shared/vmap/Makefile.am58
-rw-r--r--src/shared/vmap/ManagedModelContainer.cpp4
-rw-r--r--src/shared/vmap/ManagedModelContainer.h4
-rw-r--r--src/shared/vmap/ModelContainer.cpp4
-rw-r--r--src/shared/vmap/ModelContainer.h4
-rw-r--r--src/shared/vmap/NodeValueAccess.h4
-rw-r--r--src/shared/vmap/ShortBox.h4
-rw-r--r--src/shared/vmap/ShortVector.h4
-rw-r--r--src/shared/vmap/SubModel.cpp4
-rw-r--r--src/shared/vmap/SubModel.h4
-rw-r--r--src/shared/vmap/TileAssembler.cpp769
-rw-r--r--src/shared/vmap/TileAssembler.h4
-rw-r--r--src/shared/vmap/TreeNode.cpp4
-rw-r--r--src/shared/vmap/TreeNode.h4
-rw-r--r--src/shared/vmap/VMapDefinitions.h4
-rw-r--r--src/shared/vmap/VMapFactory.cpp4
-rw-r--r--src/shared/vmap/VMapFactory.h4
-rw-r--r--src/shared/vmap/VMapManager.cpp4
-rw-r--r--src/shared/vmap/VMapManager.h4
-rw-r--r--src/shared/vmap/VMapTools.h4
113 files changed, 2982 insertions, 4044 deletions
diff --git a/src/shared/Auth/AuthCrypt.cpp b/src/shared/Auth/AuthCrypt.cpp
index 7cbb7f13648..e8126ad9f73 100644
--- a/src/shared/Auth/AuthCrypt.cpp
+++ b/src/shared/Auth/AuthCrypt.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -20,65 +20,62 @@
#include "AuthCrypt.h"
#include "Hmac.h"
+#include "Log.h"
+#include "BigNumber.h"
AuthCrypt::AuthCrypt()
{
_initialized = false;
}
-void AuthCrypt::Init()
+AuthCrypt::~AuthCrypt()
{
- _send_i = _send_j = _recv_i = _recv_j = 0;
- _initialized = true;
-}
-void AuthCrypt::DecryptRecv(uint8 *data, size_t len)
-{
- if (!_initialized) return;
- if (len < CRYPTED_RECV_LEN) return;
-
- for (size_t t = 0; t < CRYPTED_RECV_LEN; t++)
- {
- _recv_i %= _key.size();
- uint8 x = (data[t] - _recv_j) ^ _key[_recv_i];
- ++_recv_i;
- _recv_j = data[t];
- data[t] = x;
- }
}
-void AuthCrypt::EncryptSend(uint8 *data, size_t len)
+void AuthCrypt::Init(BigNumber *K)
{
- if (!_initialized) return;
- if (len < CRYPTED_SEND_LEN) return;
-
- for (size_t t = 0; t < CRYPTED_SEND_LEN; t++)
- {
- _send_i %= _key.size();
- uint8 x = (data[t] ^ _key[_send_i]) + _send_j;
- ++_send_i;
- data[t] = _send_j = x;
- }
-}
+ uint8 ServerEncryptionKey[SEED_KEY_SIZE] = { 0x22, 0xBE, 0xE5, 0xCF, 0xBB, 0x07, 0x64, 0xD9, 0x00, 0x45, 0x1B, 0xD0, 0x24, 0xB8, 0xD5, 0x45 };
+ HmacHash serverEncryptHmac(SEED_KEY_SIZE, (uint8*)ServerEncryptionKey);
+ uint8 *encryptHash = serverEncryptHmac.ComputeHash(K);
-void AuthCrypt::SetKey(BigNumber *bn)
-{
- uint8 *key = new uint8[SHA_DIGEST_LENGTH];
- GenerateKey(key, bn);
- _key.resize(SHA_DIGEST_LENGTH);
- std::copy(key, key + SHA_DIGEST_LENGTH, _key.begin());
- delete key;
+ uint8 ServerDecryptionKey[SEED_KEY_SIZE] = { 0xF4, 0x66, 0x31, 0x59, 0xFC, 0x83, 0x6E, 0x31, 0x31, 0x02, 0x51, 0xD5, 0x44, 0x31, 0x67, 0x98 };
+ HmacHash clientDecryptHmac(SEED_KEY_SIZE, (uint8*)ServerDecryptionKey);
+ uint8 *decryptHash = clientDecryptHmac.ComputeHash(K);
+
+ //SARC4 _serverDecrypt(encryptHash);
+ _clientDecrypt.Init(decryptHash);
+ _serverEncrypt.Init(encryptHash);
+ //SARC4 _clientEncrypt(decryptHash);
+
+ uint8 syncBuf[1024];
+
+ memset(syncBuf, 0, 1024);
+
+ _serverEncrypt.UpdateData(1024, syncBuf);
+ //_clientEncrypt.UpdateData(1024, syncBuf);
+
+ memset(syncBuf, 0, 1024);
+
+ //_serverDecrypt.UpdateData(1024, syncBuf);
+ _clientDecrypt.UpdateData(1024, syncBuf);
+
+ _initialized = true;
}
-AuthCrypt::~AuthCrypt()
+void AuthCrypt::DecryptRecv(uint8 *data, size_t len)
{
+ if (!_initialized)
+ return;
+
+ _clientDecrypt.UpdateData(len, data);
}
-void AuthCrypt::GenerateKey(uint8 *key, BigNumber *bn)
+void AuthCrypt::EncryptSend(uint8 *data, size_t len)
{
- HmacHash hash;
- hash.UpdateBigNumber(bn);
- hash.Finalize();
- memcpy(key, hash.GetDigest(), SHA_DIGEST_LENGTH);
+ if (!_initialized)
+ return;
+
+ _serverEncrypt.UpdateData(len, data);
}
diff --git a/src/shared/Auth/AuthCrypt.h b/src/shared/Auth/AuthCrypt.h
index 020f8bcdc96..226fde018ae 100644
--- a/src/shared/Auth/AuthCrypt.h
+++ b/src/shared/Auth/AuthCrypt.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -22,7 +22,7 @@
#define _AUTHCRYPT_H
#include <Common.h>
-#include <vector>
+#include "SARC4.h"
class BigNumber;
@@ -32,23 +32,15 @@ class AuthCrypt
AuthCrypt();
~AuthCrypt();
- const static size_t CRYPTED_SEND_LEN = 4;
- const static size_t CRYPTED_RECV_LEN = 6;
-
- void Init();
-
- void SetKey(BigNumber *);
-
+ void Init(BigNumber *K);
void DecryptRecv(uint8 *, size_t);
void EncryptSend(uint8 *, size_t);
bool IsInitialized() { return _initialized; }
- static void GenerateKey(uint8 *, BigNumber *);
-
private:
- std::vector<uint8> _key;
- uint8 _send_i, _send_j, _recv_i, _recv_j;
+ SARC4 _clientDecrypt;
+ SARC4 _serverEncrypt;
bool _initialized;
};
#endif
diff --git a/src/shared/Auth/BigNumber.cpp b/src/shared/Auth/BigNumber.cpp
index da31da3a522..7872b141f3d 100644
--- a/src/shared/Auth/BigNumber.cpp
+++ b/src/shared/Auth/BigNumber.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/Auth/BigNumber.h b/src/shared/Auth/BigNumber.h
index df25e4f934d..b9038e86b13 100644
--- a/src/shared/Auth/BigNumber.h
+++ b/src/shared/Auth/BigNumber.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/Auth/CMakeLists.txt b/src/shared/Auth/CMakeLists.txt
index f0714509e1d..536853e560e 100644
--- a/src/shared/Auth/CMakeLists.txt
+++ b/src/shared/Auth/CMakeLists.txt
@@ -12,6 +12,8 @@ SET(trinityauth_STAT_SRCS
Sha1.h
md5.c
md5.h
+ SARC4.cpp
+ SARC4.h
)
add_library(trinityauth STATIC ${trinityauth_STAT_SRCS})
diff --git a/src/shared/Auth/Hmac.cpp b/src/shared/Auth/Hmac.cpp
index 615edd26ca5..985b4fb9a56 100644
--- a/src/shared/Auth/Hmac.cpp
+++ b/src/shared/Auth/Hmac.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -21,17 +21,16 @@
#include "Auth/Hmac.h"
#include "BigNumber.h"
-HmacHash::HmacHash()
+HmacHash::HmacHash(uint32 len, uint8 *seed)
{
- uint8 temp[SEED_KEY_SIZE] = { 0x38, 0xA7, 0x83, 0x15, 0xF8, 0x92, 0x25, 0x30, 0x71, 0x98, 0x67, 0xB1, 0x8C, 0x4, 0xE2, 0xAA };
- memcpy(&m_key, &temp, SEED_KEY_SIZE);
+ ASSERT(len == SEED_KEY_SIZE);
+
HMAC_CTX_init(&m_ctx);
- HMAC_Init_ex(&m_ctx, &m_key, SEED_KEY_SIZE, EVP_sha1(), NULL);
+ HMAC_Init_ex(&m_ctx, seed, SEED_KEY_SIZE, EVP_sha1(), NULL);
}
HmacHash::~HmacHash()
{
- memset(&m_key, 0x00, SEED_KEY_SIZE);
HMAC_CTX_cleanup(&m_ctx);
}
@@ -45,15 +44,16 @@ void HmacHash::UpdateData(const uint8 *data, int length)
HMAC_Update(&m_ctx, data, length);
}
-void HmacHash::Initialize()
-{
- HMAC_Init_ex(&m_ctx, &m_key, SEED_KEY_SIZE, EVP_sha1(), NULL);
-}
-
void HmacHash::Finalize()
{
uint32 length = 0;
- HMAC_Final(&m_ctx, m_digest, &length);
+ HMAC_Final(&m_ctx, (uint8*)m_digest, &length);
ASSERT(length == SHA_DIGEST_LENGTH)
}
+uint8 *HmacHash::ComputeHash(BigNumber *bn)
+{
+ HMAC_Update(&m_ctx, bn->AsByteArray(), bn->GetNumBytes());
+ Finalize();
+ return (uint8*)m_digest;
+}
diff --git a/src/shared/Auth/Hmac.h b/src/shared/Auth/Hmac.h
index 5b7c4040f13..76a302d68de 100644
--- a/src/shared/Auth/Hmac.h
+++ b/src/shared/Auth/Hmac.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -32,17 +32,16 @@ class BigNumber;
class HmacHash
{
public:
- HmacHash();
+ HmacHash(uint32 len, uint8 *seed);
~HmacHash();
void UpdateBigNumber(BigNumber *bn);
void UpdateData(const uint8 *data, int length);
- void Initialize();
void Finalize();
- uint8 *GetDigest() { return m_digest; };
- int GetLength() { return SHA_DIGEST_LENGTH; };
+ uint8 *ComputeHash(BigNumber *bn);
+ uint8 *GetDigest() { return (uint8*)m_digest; }
+ int GetLength() { return SHA_DIGEST_LENGTH; }
private:
HMAC_CTX m_ctx;
- uint8 m_key[SEED_KEY_SIZE];
uint8 m_digest[SHA_DIGEST_LENGTH];
};
#endif
diff --git a/src/shared/Auth/Makefile.am b/src/shared/Auth/Makefile.am
new file mode 100644
index 00000000000..bc1a39868f5
--- /dev/null
+++ b/src/shared/Auth/Makefile.am
@@ -0,0 +1,43 @@
+# Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+#
+# Copyright (C) 2008-2009 Trinity <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, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+## Process this file with automake to produce Makefile.in
+
+## Sub-directories to parse
+
+## CPP flags for includes, defines, etc.
+AM_CPPFLAGS = $(TRINI_INCLUDES) -I$(top_builddir)/src/shared -I$(srcdir) -I$(srcdir)/../../../dep/include -I$(srcdir)/../../framework -I$(srcdir)/../../shared -I$(srcdir)/../../../dep/include/g3dlite
+
+## Build MaNGOS shared library and its parts as convenience library.
+# All libraries will be convenience libraries. Might be changed to shared
+# later.
+noinst_LIBRARIES = libmangosauth.a
+
+libmangosauth_a_SOURCES = \
+ AuthCrypt.cpp \
+ AuthCrypt.h \
+ BigNumber.cpp \
+ BigNumber.h \
+ Hmac.cpp \
+ Hmac.h \
+ SARC4.cpp \
+ SARC4.h \
+ Sha1.cpp \
+ Sha1.h \
+ md5.c \
+ md5.h
diff --git a/src/shared/Auth/SARC4.cpp b/src/shared/Auth/SARC4.cpp
new file mode 100644
index 00000000000..f59bb7f0c53
--- /dev/null
+++ b/src/shared/Auth/SARC4.cpp
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "Auth/SARC4.h"
+#include <openssl/sha.h>
+
+SARC4::SARC4()
+{
+ EVP_CIPHER_CTX_init(&m_ctx);
+ EVP_EncryptInit_ex(&m_ctx, EVP_rc4(), NULL, NULL, NULL);
+ EVP_CIPHER_CTX_set_key_length(&m_ctx, SHA_DIGEST_LENGTH);
+}
+
+SARC4::SARC4(uint8 *seed)
+{
+ EVP_CIPHER_CTX_init(&m_ctx);
+ EVP_EncryptInit_ex(&m_ctx, EVP_rc4(), NULL, NULL, NULL);
+ EVP_CIPHER_CTX_set_key_length(&m_ctx, SHA_DIGEST_LENGTH);
+ EVP_EncryptInit_ex(&m_ctx, NULL, NULL, seed, NULL);
+}
+
+SARC4::~SARC4()
+{
+ EVP_CIPHER_CTX_cleanup(&m_ctx);
+}
+
+void SARC4::Init(uint8 *seed)
+{
+ EVP_EncryptInit_ex(&m_ctx, NULL, NULL, seed, NULL);
+}
+
+void SARC4::UpdateData(int len, uint8 *data)
+{
+ int outlen = 0;
+ EVP_EncryptUpdate(&m_ctx, data, &outlen, data, len);
+ EVP_EncryptFinal_ex(&m_ctx, data, &outlen);
+}
diff --git a/src/shared/Auth/SARC4.h b/src/shared/Auth/SARC4.h
new file mode 100644
index 00000000000..3f15328d6cb
--- /dev/null
+++ b/src/shared/Auth/SARC4.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _AUTH_SARC4_H
+#define _AUTH_SARC4_H
+
+#include "Common.h"
+#include <openssl/evp.h>
+
+class SARC4
+{
+ public:
+ SARC4();
+ SARC4(uint8 *seed);
+ ~SARC4();
+ void Init(uint8 *seed);
+ void UpdateData(int len, uint8 *data);
+ private:
+ EVP_CIPHER_CTX m_ctx;
+};
+#endif
diff --git a/src/shared/Auth/Sha1.cpp b/src/shared/Auth/Sha1.cpp
index 90334543b82..8743a14b838 100644
--- a/src/shared/Auth/Sha1.cpp
+++ b/src/shared/Auth/Sha1.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/Auth/Sha1.h b/src/shared/Auth/Sha1.h
index 6794d3bd103..68c61eb7a8e 100644
--- a/src/shared/Auth/Sha1.h
+++ b/src/shared/Auth/Sha1.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/Base.cpp b/src/shared/Base.cpp
deleted file mode 100644
index ca5094810d6..00000000000
--- a/src/shared/Base.cpp
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- Base class interface
- Copyright (C) 1998,1999 by Andrew Zabolotny
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public
- License along with this library; if not, write to the Free
- Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-*/
-
-#include "Base.h"
-
-Base::~Base ()
-{
-}
-
-/**
- * Decrement object's reference count; as soon as the last reference
- * to the object is removed, it is destroyed.
- */
-
-void Base::DecRef ()
-{
- if (!--RefCount)
- delete this;
-}
-
-/**
- * Object initialization. The initial reference count is set to one;
- * this means if you call DecRef() immediately after creating the object,
- * it will be destroyed.
- */
-Base::Base ()
-{
- RefCount = 1;
-}
-
-/**
- * Increment reference count.
- * Every time when you copy a pointer to a object and store it for
- * later use you MUST call IncRef() on it; this will allow to keep
- * objects as long as they are referenced by some entity.
- */
-void Base::IncRef ()
-{
- ++RefCount;
-
-}
-
-/**
- * Query number of references to this object.
- * I would rather prefer to have the reference counter strictly private,
- * but sometimes, mostly for debugging, such a function can help.
- */
-int Base::GetRefCount ()
-{
- return RefCount;
-}
-
diff --git a/src/shared/Base.h b/src/shared/Base.h
deleted file mode 100644
index e14ea6b27b9..00000000000
--- a/src/shared/Base.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- Base class interface
- Copyright (C) 1998,1999 by Andrew Zabolotny
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public
- License along with this library; if not, write to the Free
- Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-*/
-
-#ifndef __BASE_H__
-#define __BASE_H__
-
-#include "Common.h"
-
-/**
- * This class is intended to be a base class for every other class.
- * It defines the basic interface available for any object.
- */
-class Base
-{
- private:
- /// Object reference count
- int RefCount;
-
- protected:
- /**
- * Destroy this object. Destructor is virtual, because class contains
- * virtual methods; also it is private because it is never intended
- * to be called directly; use DecRef() instead: when reference counter
- * reaches zero, the object will be destroyed.
- */
- virtual ~Base ();
-
- public:
-
- Base ();
-
- void IncRef ();
-
- void DecRef ();
- int GetRefCount ();
-
-};
-#endif // __BASE_H__
-
diff --git a/src/shared/ByteBuffer.h b/src/shared/ByteBuffer.h
index fb2d7cfc7b9..75c33dcf3ca 100644
--- a/src/shared/ByteBuffer.h
+++ b/src/shared/ByteBuffer.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -36,11 +36,13 @@ class ByteBuffer
{
_storage.reserve(DEFAULT_SIZE);
}
+
// constructor
ByteBuffer(size_t res): _rpos(0), _wpos(0)
{
_storage.reserve(res);
}
+
// copy constructor
ByteBuffer(const ByteBuffer &buf): _rpos(buf._rpos), _wpos(buf._wpos), _storage(buf._storage) { }
@@ -67,16 +69,19 @@ class ByteBuffer
append<uint8>(value);
return *this;
}
+
ByteBuffer &operator<<(uint16 value)
{
append<uint16>(value);
return *this;
}
+
ByteBuffer &operator<<(uint32 value)
{
append<uint32>(value);
return *this;
}
+
ByteBuffer &operator<<(uint64 value)
{
append<uint64>(value);
@@ -89,16 +94,19 @@ class ByteBuffer
append<int8>(value);
return *this;
}
+
ByteBuffer &operator<<(int16 value)
{
append<int16>(value);
return *this;
}
+
ByteBuffer &operator<<(int32 value)
{
append<int32>(value);
return *this;
}
+
ByteBuffer &operator<<(int64 value)
{
append<int64>(value);
@@ -111,17 +119,20 @@ class ByteBuffer
append<float>(value);
return *this;
}
+
ByteBuffer &operator<<(double value)
{
append<double>(value);
return *this;
}
+
ByteBuffer &operator<<(const std::string &value)
{
append((uint8 const *)value.c_str(), value.length());
append((uint8)0);
return *this;
}
+
ByteBuffer &operator<<(const char *str)
{
append((uint8 const *)str, str ? strlen(str) : 0);
@@ -140,16 +151,19 @@ class ByteBuffer
value = read<uint8>();
return *this;
}
+
ByteBuffer &operator>>(uint16 &value)
{
value = read<uint16>();
return *this;
}
+
ByteBuffer &operator>>(uint32 &value)
{
value = read<uint32>();
return *this;
}
+
ByteBuffer &operator>>(uint64 &value)
{
value = read<uint64>();
@@ -162,16 +176,19 @@ class ByteBuffer
value = read<int8>();
return *this;
}
+
ByteBuffer &operator>>(int16 &value)
{
value = read<int16>();
return *this;
}
+
ByteBuffer &operator>>(int32 &value)
{
value = read<int32>();
return *this;
}
+
ByteBuffer &operator>>(int64 &value)
{
value = read<int64>();
@@ -183,20 +200,22 @@ class ByteBuffer
value = read<float>();
return *this;
}
+
ByteBuffer &operator>>(double &value)
{
value = read<double>();
return *this;
}
+
ByteBuffer &operator>>(std::string& value)
{
value.clear();
while (rpos() < size()) // prevent crash at wrong string format in packet
{
- char c=read<char>();
- if (c==0)
+ char c = read<char>();
+ if (c == 0)
break;
- value+=c;
+ value += c;
}
return *this;
}
@@ -212,7 +231,7 @@ class ByteBuffer
{
_rpos = rpos_;
return _rpos;
- };
+ }
size_t wpos() const { return _wpos; }
@@ -224,13 +243,14 @@ class ByteBuffer
template <typename T> T read()
{
- T r=read<T>(_rpos);
+ T r = read<T>(_rpos);
_rpos += sizeof(T);
return r;
- };
+ }
+
template <typename T> T read(size_t pos) const
{
- ASSERT(pos + sizeof(T) <= size() || PrintPosError(false,pos,sizeof(T)));
+ ASSERT(pos + sizeof(T) <= size() || PrintPosError(false, pos, sizeof(T)));
T val = *((T const*)&_storage[pos]);
EndianConvert(val);
return val;
@@ -238,11 +258,37 @@ class ByteBuffer
void read(uint8 *dest, size_t len)
{
- ASSERT(_rpos + len <= size() || PrintPosError(false,_rpos,len));
+ ASSERT(_rpos + len <= size() || PrintPosError(false, _rpos, len));
memcpy(dest, &_storage[_rpos], len);
_rpos += len;
}
+ bool readPackGUID(uint64& guid)
+ {
+ if(rpos() + 1 > size())
+ return false;
+
+ guid = 0;
+
+ uint8 guidmark = 0;
+ (*this) >> guidmark;
+
+ for(int i = 0; i < 8; ++i)
+ {
+ if(guidmark & (uint8(1) << i))
+ {
+ if(rpos() + 1 > size())
+ return false;
+
+ uint8 bit;
+ (*this) >> bit;
+ guid |= (uint64(bit) << (i * 8));
+ }
+ }
+
+ return true;
+ }
+
const uint8 *contents() const { return &_storage[0]; }
size_t size() const { return _storage.size(); }
@@ -253,28 +299,33 @@ class ByteBuffer
_storage.resize(newsize);
_rpos = 0;
_wpos = size();
- };
+ }
+
void reserve(size_t ressize)
{
- if (ressize > size()) _storage.reserve(ressize);
- };
+ if (ressize > size())
+ _storage.reserve(ressize);
+ }
void append(const std::string& str)
{
- append((uint8 const*)str.c_str(),str.size() + 1);
+ append((uint8 const*)str.c_str(), str.size() + 1);
}
+
void append(const char *src, size_t cnt)
{
return append((const uint8 *)src, cnt);
}
- template<class T>
- void append(const T *src, size_t cnt)
+
+ template<class T> void append(const T *src, size_t cnt)
{
- return append((const uint8 *)src, cnt*sizeof(T));
+ return append((const uint8 *)src, cnt * sizeof(T));
}
+
void append(const uint8 *src, size_t cnt)
{
- if (!cnt) return;
+ if (!cnt)
+ return;
ASSERT(size() < 10000000);
@@ -283,20 +334,35 @@ class ByteBuffer
memcpy(&_storage[_wpos], src, cnt);
_wpos += cnt;
}
+
void append(const ByteBuffer& buffer)
{
- if(buffer.size()) append(buffer.contents(),buffer.size());
+ if(buffer.wpos())
+ append(buffer.contents(), buffer.wpos());
+ }
+
+ // can be used in SMSG_MONSTER_MOVE opcode
+ void appendPackXYZ(float x, float y, float z)
+ {
+ uint32 packed = 0;
+ packed |= ((int)(x / 0.25f) & 0x7FF);
+ packed |= ((int)(y / 0.25f) & 0x7FF) << 11;
+ packed |= ((int)(z / 0.25f) & 0x3FF) << 22;
+ *this << packed;
}
void appendPackGUID(uint64 guid)
{
+ if (_storage.size() < _wpos + sizeof(guid) + 1)
+ _storage.resize(_wpos + sizeof(guid) + 1);
+
size_t mask_position = wpos();
*this << uint8(0);
- for(uint8 i = 0; i < 8; i++)
+ for(uint8 i = 0; i < 8; ++i)
{
if(guid & 0xFF)
{
- _storage[mask_position] |= uint8(1<<i);
+ _storage[mask_position] |= uint8(1 << i);
*this << uint8(guid & 0xFF);
}
@@ -306,16 +372,17 @@ class ByteBuffer
void put(size_t pos, const uint8 *src, size_t cnt)
{
- ASSERT(pos + cnt <= size() || PrintPosError(true,pos,cnt));
+ ASSERT(pos + cnt <= size() || PrintPosError(true, pos, cnt));
memcpy(&_storage[pos], src, cnt);
}
+
void print_storage() const
{
if(!sLog.IsOutDebug()) // optimize disabled debug output
return;
- sLog.outDebug("STORAGE_SIZE: %u", size() );
- for(uint32 i = 0; i < size(); i++)
+ sLog.outDebug("STORAGE_SIZE: %lu", (unsigned long)size() );
+ for(uint32 i = 0; i < size(); ++i)
sLog.outDebugInLine("%u - ", read<uint8>(i) );
sLog.outDebug(" ");
}
@@ -325,8 +392,8 @@ class ByteBuffer
if(!sLog.IsOutDebug()) // optimize disabled debug output
return;
- sLog.outDebug("STORAGE_SIZE: %u", size() );
- for(uint32 i = 0; i < size(); i++)
+ sLog.outDebug("STORAGE_SIZE: %lu", (unsigned long)size() );
+ for(uint32 i = 0; i < size(); ++i)
sLog.outDebugInLine("%c", read<uint8>(i) );
sLog.outDebug(" ");
}
@@ -337,16 +404,13 @@ class ByteBuffer
return;
uint32 j = 1, k = 1;
- sLog.outDebug("STORAGE_SIZE: %u", size() );
-
- if(sLog.IsIncludeTime())
- sLog.outDebugInLine(" ");
+ sLog.outDebug("STORAGE_SIZE: %lu", (unsigned long)size() );
- for(uint32 i = 0; i < size(); i++)
+ for(uint32 i = 0; i < size(); ++i)
{
- if ((i == (j*8)) && ((i != (k*16))))
+ if ((i == (j * 8)) && ((i != (k * 16))))
{
- if (read<uint8>(i) < 0x0F)
+ if (read<uint8>(i) < 0x10)
{
sLog.outDebugInLine("| 0%X ", read<uint8>(i) );
}
@@ -356,21 +420,17 @@ class ByteBuffer
}
++j;
}
- else if (i == (k*16))
+ else if (i == (k * 16))
{
- if (read<uint8>(i) < 0x0F)
+ if (read<uint8>(i) < 0x10)
{
sLog.outDebugInLine("\n");
- if(sLog.IsIncludeTime())
- sLog.outDebugInLine(" ");
sLog.outDebugInLine("0%X ", read<uint8>(i) );
}
else
{
sLog.outDebugInLine("\n");
- if(sLog.IsIncludeTime())
- sLog.outDebugInLine(" ");
sLog.outDebugInLine("%X ", read<uint8>(i) );
}
@@ -380,7 +440,7 @@ class ByteBuffer
}
else
{
- if (read<uint8>(i) < 0x0F)
+ if (read<uint8>(i) < 0x10)
{
sLog.outDebugInLine("0%X ", read<uint8>(i) );
}
@@ -396,7 +456,7 @@ class ByteBuffer
protected:
bool PrintPosError(bool add, size_t pos, size_t esize) const
{
- sLog.outError("ERROR: Attempt %s in ByteBuffer (pos: %u size: %u) value with size: %u",(add ? "put" : "get"),pos, size(), esize);
+ sLog.outError("ERROR: Attempt %s in ByteBuffer (pos: %lu size: %lu) value with size: %lu",(add ? "put" : "get"),(unsigned long)pos, (unsigned long)size(), (unsigned long)esize);
// assert must fail after function call
return false;
@@ -409,7 +469,7 @@ class ByteBuffer
template <typename T> ByteBuffer &operator<<(ByteBuffer &b, std::vector<T> v)
{
b << (uint32)v.size();
- for (typename std::vector<T>::iterator i = v.begin(); i != v.end(); i++)
+ for (typename std::vector<T>::iterator i = v.begin(); i != v.end(); ++i)
{
b << *i;
}
@@ -433,7 +493,7 @@ template <typename T> ByteBuffer &operator>>(ByteBuffer &b, std::vector<T> &v)
template <typename T> ByteBuffer &operator<<(ByteBuffer &b, std::list<T> v)
{
b << (uint32)v.size();
- for (typename std::list<T>::iterator i = v.begin(); i != v.end(); i++)
+ for (typename std::list<T>::iterator i = v.begin(); i != v.end(); ++i)
{
b << *i;
}
@@ -457,7 +517,7 @@ template <typename T> ByteBuffer &operator>>(ByteBuffer &b, std::list<T> &v)
template <typename K, typename V> ByteBuffer &operator<<(ByteBuffer &b, std::map<K, V> &m)
{
b << (uint32)m.size();
- for (typename std::map<K, V>::iterator i = m.begin(); i != m.end(); i++)
+ for (typename std::map<K, V>::iterator i = m.begin(); i != m.end(); ++i)
{
b << i->first << i->second;
}
@@ -478,5 +538,13 @@ template <typename K, typename V> ByteBuffer &operator>>(ByteBuffer &b, std::map
}
return b;
}
+
+// TODO: Make a ByteBuffer.cpp and move all this inlining to it.
+template<> inline std::string ByteBuffer::read<std::string>()
+{
+ std::string tmp;
+ *this >> tmp;
+ return tmp;
+}
#endif
diff --git a/src/shared/CMakeLists.txt b/src/shared/CMakeLists.txt
index 9205f145e48..de73967546b 100644
--- a/src/shared/CMakeLists.txt
+++ b/src/shared/CMakeLists.txt
@@ -6,18 +6,15 @@ add_subdirectory(Database)
########### next target ###############
SET(shared_STAT_SRCS
- Base.cpp
- Base.h
ByteBuffer.h
Common.cpp
Common.h
Errors.h
Log.cpp
Log.h
- Mthread.cpp
- Mthread.h
ProgressBar.cpp
ProgressBar.h
+ Threading.cpp
Timer.h
Util.cpp
Util.h
@@ -26,3 +23,7 @@ SET(shared_STAT_SRCS
)
add_definitions(-fopenmp)
add_library(shared STATIC ${shared_STAT_SRCS})
+target_link_libraries(
+shared
+${ACE_LIBRARY}
+)
diff --git a/src/shared/Common.cpp b/src/shared/Common.cpp
index a31c88fdba5..27ae9184d69 100644
--- a/src/shared/Common.cpp
+++ b/src/shared/Common.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/Common.h b/src/shared/Common.h
index 5e6a2cca520..735c57eedbe 100644
--- a/src/shared/Common.h
+++ b/src/shared/Common.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -62,24 +62,17 @@
#include "Platform/Define.h"
#if COMPILER == COMPILER_MICROSOFT
-
-#pragma warning(disable:4996)
-
+# pragma warning(disable:4996) // 'function': was declared deprecated
#ifndef __SHOW_STUPID_WARNINGS__
-
-#pragma warning(disable:4244)
-
-#pragma warning(disable:4267)
-
-#pragma warning(disable:4800)
-
-#pragma warning(disable:4018)
-
-#pragma warning(disable:4311)
-
-#pragma warning(disable:4305)
-
-#pragma warning(disable:4005)
+# pragma warning(disable:4005) // 'identifier' : macro redefinition
+# pragma warning(disable:4018) // 'expression' : signed/unsigned mismatch
+# pragma warning(disable:4244) // 'argument' : conversion from 'type1' to 'type2', possible loss of data
+# pragma warning(disable:4267) // 'var' : conversion from 'size_t' to 'type', possible loss of data
+# pragma warning(disable:4305) // 'identifier' : truncation from 'type1' to 'type2'
+# pragma warning(disable:4311) // 'variable' : pointer truncation from 'type' to 'type'
+# pragma warning(disable:4355) // 'this' : used in base member initializer list
+# pragma warning(disable:4800) // 'type' : forcing value to bool 'true' or 'false' (performance warning)
+# pragma warning(disable:4522) //warning when class has 2 constructosr
#endif // __SHOW_STUPID_WARNINGS__
#endif // __GNUC__
@@ -91,6 +84,7 @@
#include <math.h>
#include <errno.h>
#include <signal.h>
+#include <assert.h>
#if PLATFORM == PLATFORM_WINDOWS
#define STRCASECMP stricmp
@@ -106,10 +100,14 @@
#include <sstream>
#include <algorithm>
-#include <zthread/FastMutex.h>
-#include <zthread/LockedQueue.h>
-#include <zthread/Runnable.h>
-#include <zthread/Thread.h>
+#include "LockedQueue.h"
+#include "Threading.h"
+
+#include <ace/Basic_Types.h>
+#include <ace/Guard_T.h>
+#include <ace/RW_Thread_Mutex.h>
+#include <ace/Thread_Mutex.h>
+
#if PLATFORM == PLATFORM_WINDOWS
# define FD_SETSIZE 4096
@@ -133,8 +131,6 @@
#include <float.h>
#define I64FMT "%016I64X"
-#define I64FMTD "%I64u"
-#define SI64FMTD "%I64d"
#define snprintf _snprintf
#define atoll __atoi64
#define vsnprintf _vsnprintf
@@ -146,10 +142,15 @@
#define stricmp strcasecmp
#define strnicmp strncasecmp
#define I64FMT "%016llX"
-#define I64FMTD "%llu"
-#define SI64FMTD "%lld"
+
#endif
+#define UI64FMTD ACE_UINT64_FORMAT_SPECIFIER
+#define UI64LIT(N) ACE_UINT64_LITERAL(N)
+
+#define SI64FMTD ACE_INT64_FORMAT_SPECIFIER
+#define SI64LIT(N) ACE_INT64_LITERAL(N)
+
inline float finiteAlways(float f) { return finite(f) ? f : 0.0f; }
#define atol(a) strtoul( a, NULL, 10)
@@ -161,7 +162,9 @@ enum TimeConstants
MINUTE = 60,
HOUR = MINUTE*60,
DAY = HOUR*24,
- MONTH = DAY*30
+ MONTH = DAY*30,
+ YEAR = MONTH*12,
+ IN_MILISECONDS = 1000
};
enum AccountTypes
diff --git a/src/shared/Config/Config.cpp b/src/shared/Config/Config.cpp
index 4f9402b5f01..b56b804b50a 100644
--- a/src/shared/Config/Config.cpp
+++ b/src/shared/Config/Config.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -60,118 +60,48 @@ bool Config::Reload()
return true;
}
-bool Config::GetString(const char* name, std::string *value)
-{
- if(!mConf)
- return false;
-
- DOTCONFDocumentNode const *node = mConf->findNode(name);
- if(!node || !node->getValue())
- return false;
-
- *value = node->getValue();
-
- return true;
-}
-
-bool Config::GetString(const char* name, char const **value)
-{
- if(!mConf)
- return false;
-
- DOTCONFDocumentNode const *node = mConf->findNode(name);
- if(!node || !node->getValue())
- return false;
-
- *value = node->getValue();
-
- return true;
-}
-
-
-std::string Config::GetStringDefault(const char* name, const char* def)
+std::string Config::GetStringDefault(const char * name, std::string def)
{
if(!mConf)
return std::string(def);
-
- DOTCONFDocumentNode const *node = mConf->findNode(name);
+ const DOTCONFDocumentNode * node = mConf->findNode(name);
if(!node || !node->getValue())
return std::string(def);
-
return std::string(node->getValue());
-}
-
+};
-bool Config::GetBool(const char* name, bool *value)
+bool Config::GetBoolDefault(const char * name, const bool def)
{
if(!mConf)
return false;
-
- DOTCONFDocumentNode const *node = mConf->findNode(name);
+ const DOTCONFDocumentNode * node = mConf->findNode(name);
if(!node || !node->getValue())
- return false;
-
- const char* str = node->getValue();
+ return def;
+ const char * str = node->getValue();
if(strcmp(str, "true") == 0 || strcmp(str, "TRUE") == 0 ||
strcmp(str, "yes") == 0 || strcmp(str, "YES") == 0 ||
strcmp(str, "1") == 0)
- {
- *value = true;
- }
+ return true;
else
- *value = false;
-
- return true;
-}
-
-
-bool Config::GetBoolDefault(const char* name, const bool def)
-{
- bool val;
- return GetBool(name, &val) ? val : def;
-}
-
+ return false;
+};
-bool Config::GetInt(const char* name, int *value)
+int32 Config::GetIntDefault(const char * name, const int32 def)
{
if(!mConf)
- return false;
-
- DOTCONFDocumentNode const *node = mConf->findNode(name);
+ return def;
+ const DOTCONFDocumentNode * node = mConf->findNode(name);
if(!node || !node->getValue())
- return false;
-
- *value = atoi(node->getValue());
-
- return true;
-}
-
+ return def;
+ return atoi(node->getValue());
+};
-bool Config::GetFloat(const char* name, float *value)
+float Config::GetFloatDefault(const char * name, const float def)
{
if(!mConf)
- return false;
-
- DOTCONFDocumentNode const *node = mConf->findNode(name);
+ return def;
+ const DOTCONFDocumentNode * node = mConf->findNode(name);
if(!node || !node->getValue())
- return false;
-
- *value = atof(node->getValue());
-
- return true;
-}
-
-
-int Config::GetIntDefault(const char* name, const int def)
-{
- int val;
- return GetInt(name, &val) ? val : def;
-}
-
-
-float Config::GetFloatDefault(const char* name, const float def)
-{
- float val;
- return (GetFloat(name, &val) ? val : def);
-}
-
+ return def;
+ return atof(node->getValue());
+};
diff --git a/src/shared/Config/Config.h b/src/shared/Config/Config.h
index 4dbff1b1153..7070e6180c0 100644
--- a/src/shared/Config/Config.h
+++ b/src/shared/Config/Config.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -35,18 +35,10 @@ class TRINITY_DLL_SPEC Config
bool SetSource(const char *file, bool ignorecase = true);
bool Reload();
- bool GetString(const char* name, std::string *value);
- bool GetString(const char* name, char const **value);
- std::string GetStringDefault(const char* name, const char* def);
-
- bool GetBool(const char* name, bool *value);
- bool GetBoolDefault(const char* name, const bool def = false);
-
- bool GetInt(const char* name, int *value);
- int GetIntDefault(const char* name, const int def);
-
- bool GetFloat(const char* name, float *value);
- float GetFloatDefault(const char* name, const float def);
+ std::string GetStringDefault(const char * name, std::string def);
+ bool GetBoolDefault(const char * name, const bool def);
+ int32 GetIntDefault(const char * name, const int32 def);
+ float GetFloatDefault(const char * name, const float def);
std::string GetFilename() const { return mFilename; }
private:
diff --git a/src/shared/Config/ConfigEnv.h b/src/shared/Config/ConfigEnv.h
index eaa86c882df..75209a7fc6b 100644
--- a/src/shared/Config/ConfigEnv.h
+++ b/src/shared/Config/ConfigEnv.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/Config/Makefile.am b/src/shared/Config/Makefile.am
new file mode 100644
index 00000000000..4854095b98c
--- /dev/null
+++ b/src/shared/Config/Makefile.am
@@ -0,0 +1,42 @@
+# Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+#
+# Copyright (C) 2008-2009 Trinity <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, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+## Process this file with automake to produce Makefile.in
+
+## Sub-directories to parse
+
+## CPP flags for includes, defines, etc.
+AM_CPPFLAGS = $(TRINI_INCLUDES) -I$(top_builddir)/src/shared -I$(srcdir) -I$(srcdir)/../../../dep/include -I$(srcdir)/../../framework -I$(srcdir)/../../shared -I$(srcdir)/../../../dep/include/g3dlite
+
+## Build MaNGOS shared library and its parts as convenience library.
+# All libraries will be convenience libraries. Might be changed to shared
+# later.
+noinst_LIBRARIES = libmangosconfig.a
+
+libmangosconfig_a_SOURCES = \
+ dotconfpp/dotconfpp.cpp \
+ dotconfpp/dotconfpp.h \
+ dotconfpp/mempool.cpp \
+ dotconfpp/mempool.h \
+ Config.cpp \
+ Config.h \
+ ConfigEnv.h
+
+# VC++ project workspace for dotconfpp
+EXTRA_DIST = \
+ ConfigLibrary.vcproj
diff --git a/src/shared/Config/dotconfpp/dotconfpp.cpp b/src/shared/Config/dotconfpp/dotconfpp.cpp
index 3e2aa8683fe..e779637256e 100644
--- a/src/shared/Config/dotconfpp/dotconfpp.cpp
+++ b/src/shared/Config/dotconfpp/dotconfpp.cpp
@@ -3,6 +3,18 @@
#include "dotconfpp.h"
+#ifdef WIN32
+#define PATH_MAX _MAX_PATH
+#define strcasecmp stricmp
+#define realpath(path,resolved_path) _fullpath(resolved_path, path, _MAX_PATH)
+#include <io.h>
+#else
+#include <unistd.h>
+#include <limits.h>
+#include <stdint.h>
+#include <strings.h>
+#endif
+
#if !defined(R_OK)
#define R_OK 04
#endif
@@ -55,13 +67,13 @@ DOTCONFDocument::DOTCONFDocument(DOTCONFDocument::CaseSensitive caseSensitivity)
DOTCONFDocument::~DOTCONFDocument()
{
- for(std::list<DOTCONFDocumentNode*>::iterator i = nodeTree.begin(); i != nodeTree.end(); i++){
+ for(std::list<DOTCONFDocumentNode*>::iterator i = nodeTree.begin(); i != nodeTree.end(); ++i){
delete(*i);
}
- for(std::list<char*>::iterator i = requiredOptions.begin(); i != requiredOptions.end(); i++){
+ for(std::list<char*>::iterator i = requiredOptions.begin(); i != requiredOptions.end(); ++i){
free(*i);
}
- for(std::list<char*>::iterator i = processedFiles.begin(); i != processedFiles.end(); i++){
+ for(std::list<char*>::iterator i = processedFiles.begin(); i != processedFiles.end(); ++i){
free(*i);
}
free(fileName);
@@ -138,7 +150,7 @@ int DOTCONFDocument::cleanupLine(char * line)
quoted = !quoted;
++line; continue;
}
- if(isspace(*line) && !quoted){
+ if(isspace((unsigned char)*line) && !quoted){
*bg++ = 0;
if(strlen(start)){
@@ -154,7 +166,7 @@ int DOTCONFDocument::cleanupLine(char * line)
words.push_back(word);
}
start = bg;
- while(isspace(*++line)) {}
+ while(isspace((unsigned char)*++line)) {}
continue;
}
@@ -177,7 +189,7 @@ int DOTCONFDocument::parseLine()
DOTCONFDocumentNode * tagNode = NULL;
bool newNode = false;
- for(std::list<char*>::iterator i = words.begin(); i != words.end(); i++) {
+ for(std::list<char*>::iterator i = words.begin(); i != words.end(); ++i) {
word = *i;
if(*word == '<'){
@@ -295,7 +307,7 @@ int DOTCONFDocument::checkConfig(const std::list<DOTCONFDocumentNode*>::iterator
DOTCONFDocumentNode * tagNode = NULL;
int vi = 0;
- for(std::list<DOTCONFDocumentNode*>::iterator i = from; i != nodeTree.end(); i++){
+ for(std::list<DOTCONFDocumentNode*>::iterator i = from; i != nodeTree.end(); ++i){
tagNode = *i;
if(!tagNode->closed){
error(tagNode->lineNum, tagNode->fileName, "unclosed tag %s", tagNode->name);
@@ -359,7 +371,7 @@ int DOTCONFDocument::setContent(const char * _fileName)
std::list<DOTCONFDocumentNode*>::iterator from;
DOTCONFDocumentNode * tagNode = NULL;
int vi = 0;
- for(std::list<DOTCONFDocumentNode*>::iterator i = nodeTree.begin(); i!=nodeTree.end(); i++){
+ for(std::list<DOTCONFDocumentNode*>::iterator i = nodeTree.begin(); i!=nodeTree.end(); ++i){
tagNode = *i;
if(!cmp_func("DOTCONFPPIncludeFile", tagNode->name)){
vi = 0;
@@ -374,7 +386,7 @@ int DOTCONFDocument::setContent(const char * _fileName)
}
bool processed = false;
- for(std::list<char*>::const_iterator itInode = processedFiles.begin(); itInode != processedFiles.end(); itInode++){
+ for(std::list<char*>::const_iterator itInode = processedFiles.begin(); itInode != processedFiles.end(); ++itInode){
if(!strcmp(*itInode, realpathBuf)){
processed = true;
break;
@@ -417,9 +429,9 @@ int DOTCONFDocument::setContent(const char * _fileName)
int DOTCONFDocument::checkRequiredOptions()
{
- for(std::list<char*>::const_iterator ci = requiredOptions.begin(); ci != requiredOptions.end(); ci++){
+ for(std::list<char*>::const_iterator ci = requiredOptions.begin(); ci != requiredOptions.end(); ++ci){
bool matched = false;
- for(std::list<DOTCONFDocumentNode*>::iterator i = nodeTree.begin(); i!=nodeTree.end(); i++){
+ for(std::list<DOTCONFDocumentNode*>::iterator i = nodeTree.begin(); i!=nodeTree.end(); ++i){
if(!cmp_func((*i)->name, *ci)){
matched = true;
break;
@@ -567,7 +579,7 @@ const DOTCONFDocumentNode * DOTCONFDocument::findNode(const char * nodeName, con
if( i != nodeTree.end() ) ++i;
}
- for(; i!=nodeTree.end(); i++){
+ for(; i!=nodeTree.end(); ++i){
if((*i)->parentNode != parentNode){
continue;
diff --git a/src/shared/Config/dotconfpp/dotconfpp.h b/src/shared/Config/dotconfpp/dotconfpp.h
index 7887f86ccc1..51455854ee7 100644
--- a/src/shared/Config/dotconfpp/dotconfpp.h
+++ b/src/shared/Config/dotconfpp/dotconfpp.h
@@ -15,19 +15,6 @@
#include <sys/types.h>
#include <sys/stat.h>
-#ifdef WIN32
-#define PATH_MAX _MAX_PATH
-#define snprintf _snprintf
-#define strcasecmp stricmp
-#define realpath(path,resolved_path) _fullpath(resolved_path, path, _MAX_PATH)
-#include <io.h>
-#else
-#include <unistd.h>
-#include <limits.h>
-#include <stdint.h>
-#include <strings.h>
-#endif
-
#include "mempool.h"
class DOTCONFDocument;
diff --git a/src/shared/Config/dotconfpp/mempool.cpp b/src/shared/Config/dotconfpp/mempool.cpp
index 487dae0bd0a..cec8e8d119f 100644
--- a/src/shared/Config/dotconfpp/mempool.cpp
+++ b/src/shared/Config/dotconfpp/mempool.cpp
@@ -22,7 +22,7 @@ AsyncDNSMemPool::AsyncDNSMemPool(size_t _defaultSize):
AsyncDNSMemPool::~AsyncDNSMemPool()
{
- for(size_t i = 0; i<chunksCount; i++){
+ for(size_t i = 0; i<chunksCount; ++i){
delete chunks[i];
}
::free(chunks);
@@ -53,7 +53,7 @@ void AsyncDNSMemPool::addNewChunk(size_t size)
void * AsyncDNSMemPool::alloc(size_t size)
{
PoolChunk * chunk = NULL;
- for(size_t i = 0; i<chunksCount; i++){
+ for(size_t i = 0; i<chunksCount; ++i){
chunk = chunks[i];
if((chunk->size - chunk->pos) >= size){
chunk->pos += size;
@@ -71,7 +71,7 @@ void AsyncDNSMemPool::free()
size_t psz = 0;
++poolUsageCounter;
- for(size_t i = 0; i<chunksCount; i++){
+ for(size_t i = 0; i<chunksCount; ++i){
pu += chunks[i]->pos;
psz += chunks[i]->size;
chunks[i]->pos = 0;
diff --git a/src/shared/Database/CMakeLists.txt b/src/shared/Database/CMakeLists.txt
index 78cc48436e7..c8d087b518f 100644
--- a/src/shared/Database/CMakeLists.txt
+++ b/src/shared/Database/CMakeLists.txt
@@ -1,18 +1,15 @@
SET(trinitydatabase_STAT_SRCS
- DBCStores.cpp
- DBCStores.h
- DBCStructure.h
- DBCfmt.cpp
+ DBCFileLoader.cpp
+ DBCFileLoader.h
+ DBCStore.h
Database.cpp
Database.h
- DatabaseEnv.h
+ DatabaseEnv.h
DatabaseImpl.h
DatabaseMysql.cpp
DatabasePostgre.cpp
DatabaseMysql.h
DatabasePostgre.h
- DatabaseSqlite.cpp
- DatabaseSqlite.h
Field.cpp
Field.h
MySQLDelayThread.h
@@ -22,16 +19,12 @@ SET(trinitydatabase_STAT_SRCS
QueryResultMysql.h
QueryResultPostgre.cpp
QueryResultPostgre.h
- QueryResultSqlite.cpp
- QueryResultSqlite.h
SQLStorage.cpp
SQLStorage.h
SqlDelayThread.cpp
SqlDelayThread.h
SqlOperations.cpp
SqlOperations.h
- dbcfile.cpp
- dbcfile.h
)
add_library(trinitydatabase STATIC ${trinitydatabase_STAT_SRCS})
diff --git a/src/shared/Database/DBCEnums.h b/src/shared/Database/DBCEnums.h
deleted file mode 100644
index fbd87aafbe7..00000000000
--- a/src/shared/Database/DBCEnums.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
-* Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/>
-*
-* This program is free software; you can redistribute it and/or modify
-* it under the terms of the GNU General Public License as published by
-* the Free Software Foundation; either version 2 of the License, or
-* (at your option) any later version.
-*
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-* GNU General Public License for more details.
-*
-* You should have received a copy of the GNU General Public License
-* along with this program; if not, write to the Free Software
-* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-*/
-
-#ifndef DBCENUMS_H
-#define DBCENUMS_H
-
-// 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 AreaTeams
-{
- AREATEAM_NONE = 0,
- AREATEAM_ALLY = 2,
- AREATEAM_HORDE = 4
-};
-
-enum AreaFlags
-{
- AREA_FLAG_SNOW = 0x00000001, // snow (only Dun Morogh, Naxxramas, Razorfen Downs and Winterspring)
- AREA_FLAG_UNK1 = 0x00000002, // unknown, (only Naxxramas and Razorfen Downs)
- AREA_FLAG_UNK2 = 0x00000004, // Only used on development map
- AREA_FLAG_SLAVE_CAPITAL = 0x00000008, // slave capital city flag?
- AREA_FLAG_UNK3 = 0x00000010, // unknown
- AREA_FLAG_SLAVE_CAPITAL2 = 0x00000020, // slave capital city flag?
- AREA_FLAG_UNK4 = 0x00000040, // many zones have this flag
- AREA_FLAG_ARENA = 0x00000080, // arena, both instanced and world arenas
- AREA_FLAG_CAPITAL = 0x00000100, // main capital city flag
- AREA_FLAG_CITY = 0x00000200, // only for one zone named "City" (where it located?)
- AREA_FLAG_OUTLAND = 0x00000400, // outland zones? (only Eye of the Storm not have this flag, but have 0x00004000 flag)
- AREA_FLAG_SANCTUARY = 0x00000800, // sanctuary area (PvP disabled)
- AREA_FLAG_NEED_FLY = 0x00001000, // only Netherwing Ledge, Socrethar's Seat, Tempest Keep, The Arcatraz, The Botanica, The Mechanar, Sorrow Wing Point, Dragonspine Ridge, Netherwing Mines, Dragonmaw Base Camp, Dragonmaw Skyway
- AREA_FLAG_UNUSED1 = 0x00002000, // not used now (no area/zones with this flag set in 2.4.2)
- AREA_FLAG_OUTLAND2 = 0x00004000, // outland zones? (only Circle of Blood Arena not have this flag, but have 0x00000400 flag)
- AREA_FLAG_PVP = 0x00008000, // pvp objective area? (Death's Door also has this flag although it's no pvp object area)
- AREA_FLAG_ARENA_INSTANCE = 0x00010000, // used by instanced arenas only
- AREA_FLAG_UNUSED2 = 0x00020000, // not used now (no area/zones with this flag set in 2.4.2)
- AREA_FLAG_UNK5 = 0x00040000, // just used for Amani Pass, Hatchet Hills
- AREA_FLAG_LOWLEVEL = 0x00100000 // used for some starting areas with area_level <=15
-};
-
-enum FactionTemplateFlags
-{
- FACTION_TEMPLATE_FLAG_CONTESTED_GUARD = 0x00001000, // faction will attack players that were involved in PvP combats
-};
-
-enum FactionMasks
-{
- FACTION_MASK_PLAYER = 1, // any player
- FACTION_MASK_ALLIANCE = 2, // player or creature from alliance team
- FACTION_MASK_HORDE = 4, // player or creature from horde team
- FACTION_MASK_MONSTER = 8 // aggressive creature from monster team
- // if none flags set then non-aggressive creature
-};
-
-enum MapTypes
-{
- MAP_COMMON = 0,
- MAP_INSTANCE = 1,
- MAP_RAID = 2,
- MAP_BATTLEGROUND = 3,
- MAP_ARENA = 4
-};
-
-enum AbilytyLearnType
-{
- ABILITY_LEARNED_ON_GET_PROFESSION_SKILL = 1,
- ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL = 2
-};
-
-enum ItemEnchantmentType
-{
- ITEM_ENCHANTMENT_TYPE_NONE = 0,
- ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL = 1,
- ITEM_ENCHANTMENT_TYPE_DAMAGE = 2,
- ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL = 3,
- ITEM_ENCHANTMENT_TYPE_RESISTANCE = 4,
- ITEM_ENCHANTMENT_TYPE_STAT = 5,
- ITEM_ENCHANTMENT_TYPE_TOTEM = 6
-};
-
-enum ItemEnchantmentAuraId
-{
- ITEM_ENCHANTMENT_AURAID_POISON = 26,
- ITEM_ENCHANTMENT_AURAID_NORMAL = 28,
- ITEM_ENCHANTMENT_AURAID_FIRE = 32,
- ITEM_ENCHANTMENT_AURAID_FROST = 33,
- ITEM_ENCHANTMENT_AURAID_NATURE = 81,
- ITEM_ENCHANTMENT_AURAID_SHADOW = 107
-};
-
-enum TotemCategoryType
-{
- TOTEM_CATEGORY_TYPE_KNIFE = 1,
- TOTEM_CATEGORY_TYPE_TOTEM = 2,
- TOTEM_CATEGORY_TYPE_ROD = 3,
- TOTEM_CATEGORY_TYPE_PICK = 21,
- TOTEM_CATEGORY_TYPE_STONE = 22,
- TOTEM_CATEGORY_TYPE_HAMMER = 23,
- TOTEM_CATEGORY_TYPE_SPANNER = 24
-};
-
-#endif
-
diff --git a/src/shared/Database/dbcfile.cpp b/src/shared/Database/DBCFileLoader.cpp
index 9b363dbff8d..23f602f5c93 100644
--- a/src/shared/Database/dbcfile.cpp
+++ b/src/shared/Database/DBCFileLoader.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -22,15 +22,15 @@
#include <stdlib.h>
#include <string.h>
-#include "dbcfile.h"
+#include "DBCFileLoader.h"
-DBCFile::DBCFile()
+DBCFileLoader::DBCFileLoader()
{
data = NULL;
fieldsOffset = NULL;
}
-bool DBCFile::Load(const char *filename, const char *fmt)
+bool DBCFileLoader::Load(const char *filename, const char *fmt)
{
uint32 header;
@@ -39,23 +39,35 @@ bool DBCFile::Load(const char *filename, const char *fmt)
delete [] data;
data=NULL;
}
+
FILE * f=fopen(filename,"rb");
if(!f)return false;
- fread(&header,4,1,f); // Number of records
+ if(fread(&header,4,1,f)!=1) // Number of records
+ return false;
+
EndianConvert(header);
if(header!=0x43424457)
- {
- //printf("not dbc file");
return false; //'WDBC'
- }
- fread(&recordCount,4,1,f); // Number of records
+
+ if(fread(&recordCount,4,1,f)!=1) // Number of records
+ return false;
+
EndianConvert(recordCount);
- fread(&fieldCount,4,1,f); // Number of fields
+
+ if(fread(&fieldCount,4,1,f)!=1) // Number of fields
+ return false;
+
EndianConvert(fieldCount);
- fread(&recordSize,4,1,f); // Size of a record
+
+ if(fread(&recordSize,4,1,f)!=1) // Size of a record
+ return false;
+
EndianConvert(recordSize);
- fread(&stringSize,4,1,f); // String size
+
+ if(fread(&stringSize,4,1,f)!=1) // String size
+ return false;
+
EndianConvert(stringSize);
fieldsOffset = new uint32[fieldCount];
@@ -71,12 +83,15 @@ bool DBCFile::Load(const char *filename, const char *fmt)
data = new unsigned char[recordSize*recordCount+stringSize];
stringTable = data + recordSize*recordCount;
- fread(data,recordSize*recordCount+stringSize,1,f);
+
+ if(fread(data,recordSize*recordCount+stringSize,1,f)!=1)
+ return false;
+
fclose(f);
return true;
}
-DBCFile::~DBCFile()
+DBCFileLoader::~DBCFileLoader()
{
if(data)
delete [] data;
@@ -84,13 +99,13 @@ DBCFile::~DBCFile()
delete [] fieldsOffset;
}
-DBCFile::Record DBCFile::getRecord(size_t id)
+DBCFileLoader::Record DBCFileLoader::getRecord(size_t id)
{
assert(data);
return Record(*this, data + id*recordSize);
}
-uint32 DBCFile::GetFormatRecordSize(const char * format,int32* index_pos)
+uint32 DBCFileLoader::GetFormatRecordSize(const char * format,int32* index_pos)
{
uint32 recordsize = 0;
int32 i = -1;
@@ -122,7 +137,7 @@ uint32 DBCFile::GetFormatRecordSize(const char * format,int32* index_pos)
return recordsize;
}
-char* DBCFile::AutoProduceData(const char* format, uint32& records, char**& indexTable)
+char* DBCFileLoader::AutoProduceData(const char* format, uint32& records, char**& indexTable)
{
/*
format STRING, NA, FLOAT,NA,INT <=>
@@ -205,7 +220,7 @@ char* DBCFile::AutoProduceData(const char* format, uint32& records, char**& inde
return dataTable;
}
-char* DBCFile::AutoProduceStrings(const char* format, char* dataTable)
+char* DBCFileLoader::AutoProduceStrings(const char* format, char* dataTable)
{
if(strlen(format)!=fieldCount)
return NULL;
diff --git a/src/shared/Database/dbcfile.h b/src/shared/Database/DBCFileLoader.h
index aa36f6003dc..13562148dfc 100644
--- a/src/shared/Database/dbcfile.h
+++ b/src/shared/Database/DBCFileLoader.h
@@ -1,7 +1,5 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
- *
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -18,8 +16,8 @@
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
-#ifndef DBCFILE_H
-#define DBCFILE_H
+#ifndef DBC_FILE_LOADER_H
+#define DBC_FILE_LOADER_H
#include "Platform/Define.h"
#include "Utilities/ByteConverter.h"
#include <cassert>
@@ -37,11 +35,11 @@ enum
FT_LOGIC='l' //Logical (boolean)
};
-class DBCFile
+class DBCFileLoader
{
public:
- DBCFile();
- ~DBCFile();
+ DBCFileLoader();
+ ~DBCFileLoader();
bool Load(const char *filename, const char *fmt);
@@ -77,11 +75,11 @@ class DBCFile
}
private:
- Record(DBCFile &file_, unsigned char *offset_): offset(offset_), file(file_) {}
+ Record(DBCFileLoader &file_, unsigned char *offset_): offset(offset_), file(file_) {}
unsigned char *offset;
- DBCFile &file;
+ DBCFileLoader &file;
- friend class DBCFile;
+ friend class DBCFileLoader;
};
@@ -107,4 +105,3 @@ class DBCFile
unsigned char *stringTable;
};
#endif
-
diff --git a/src/shared/Database/DBCStore.h b/src/shared/Database/DBCStore.h
new file mode 100644
index 00000000000..523d5c5a0b3
--- /dev/null
+++ b/src/shared/Database/DBCStore.h
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef DBCSTORE_H
+#define DBCSTORE_H
+
+#include "DBCFileLoader.h"
+
+template<class T>
+class DBCStorage
+{
+ typedef std::list<char*> StringPoolList;
+ public:
+ explicit DBCStorage(const char *f) : nCount(0), fieldCount(0), fmt(f), indexTable(NULL), m_dataTable(NULL) { }
+ ~DBCStorage() { Clear(); }
+
+ T const* LookupEntry(uint32 id) const { return (id>=nCount)?NULL:indexTable[id]; }
+ uint32 GetNumRows() const { return nCount; }
+ char const* GetFormat() const { return fmt; }
+ uint32 GetFieldCount() const { return fieldCount; }
+
+ bool Load(char const* fn)
+ {
+ DBCFileLoader dbc;
+ // Check if load was sucessful, only then continue
+ if(!dbc.Load(fn, fmt))
+ return false;
+
+ fieldCount = dbc.GetCols();
+ m_dataTable = (T*)dbc.AutoProduceData(fmt,nCount,(char**&)indexTable);
+ m_stringPoolList.push_back(dbc.AutoProduceStrings(fmt,(char*)m_dataTable));
+
+ // error in dbc file at loading if NULL
+ return indexTable!=NULL;
+ }
+
+ bool LoadStringsFrom(char const* fn)
+ {
+ // DBC must be already loaded using Load
+ if(!indexTable)
+ return false;
+
+ DBCFileLoader dbc;
+ // Check if load was successful, only then continue
+ if(!dbc.Load(fn, fmt))
+ return false;
+
+ m_stringPoolList.push_back(dbc.AutoProduceStrings(fmt,(char*)m_dataTable));
+
+ return true;
+ }
+
+ void Clear()
+ {
+ if (!indexTable)
+ return;
+
+ delete[] ((char*)indexTable);
+ indexTable = NULL;
+ delete[] ((char*)m_dataTable);
+ m_dataTable = NULL;
+
+ while(!m_stringPoolList.empty())
+ {
+ delete[] m_stringPoolList.front();
+ m_stringPoolList.pop_front();
+ }
+ nCount = 0;
+ }
+
+ private:
+ uint32 nCount;
+ uint32 fieldCount;
+ char const* fmt;
+ T** indexTable;
+ T* m_dataTable;
+ StringPoolList m_stringPoolList;
+};
+#endif
diff --git a/src/shared/Database/DBCStores.cpp b/src/shared/Database/DBCStores.cpp
deleted file mode 100644
index 2031457ceaf..00000000000
--- a/src/shared/Database/DBCStores.cpp
+++ /dev/null
@@ -1,654 +0,0 @@
-/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
- *
- * Copyright (C) 2008 Trinity <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, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-#include "DBCStores.h"
-//#include "DataStore.h"
-#include "Policies/SingletonImp.h"
-#include "Log.h"
-#include "ProgressBar.h"
-
-#include "DBCfmt.cpp"
-
-#include <map>
-
-typedef std::map<uint16,uint32> AreaFlagByAreaID;
-typedef std::map<uint32,uint32> AreaFlagByMapID;
-
-DBCStorage <AreaTableEntry> sAreaStore(AreaTableEntryfmt);
-static AreaFlagByAreaID sAreaFlagByAreaID;
-static AreaFlagByMapID sAreaFlagByMapID; // for instances without generated *.map files
-
-DBCStorage <AreaTriggerEntry> sAreaTriggerStore(AreaTriggerEntryfmt);
-DBCStorage <AuctionHouseEntry> sAuctionHouseStore(AuctionHouseEntryfmt);
-DBCStorage <BankBagSlotPricesEntry> sBankBagSlotPricesStore(BankBagSlotPricesEntryfmt);
-DBCStorage <BattlemasterListEntry> sBattlemasterListStore(BattlemasterListEntryfmt);
-DBCStorage <CharStartOutfitEntry> sCharStartOutfitStore(CharStartOutfitEntryfmt);
-DBCStorage <CharTitlesEntry> sCharTitlesStore(CharTitlesEntryfmt);
-DBCStorage <ChatChannelsEntry> sChatChannelsStore(ChatChannelsEntryfmt);
-DBCStorage <ChrClassesEntry> sChrClassesStore(ChrClassesEntryfmt);
-DBCStorage <ChrRacesEntry> sChrRacesStore(ChrRacesEntryfmt);
-DBCStorage <CreatureDisplayInfoEntry> sCreatureDisplayInfoStore(CreatureDisplayInfofmt);
-DBCStorage <CreatureFamilyEntry> sCreatureFamilyStore(CreatureFamilyfmt);
-DBCStorage <CreatureSpellDataEntry> sCreatureSpellDataStore(CreatureSpellDatafmt);
-
-DBCStorage <DurabilityQualityEntry> sDurabilityQualityStore(DurabilityQualityfmt);
-DBCStorage <DurabilityCostsEntry> sDurabilityCostsStore(DurabilityCostsfmt);
-
-DBCStorage <EmotesTextEntry> sEmotesTextStore(EmoteEntryfmt);
-
-typedef std::map<uint32,SimpleFactionsList> FactionTeamMap;
-static FactionTeamMap sFactionTeamMap;
-DBCStorage <FactionEntry> sFactionStore(FactionEntryfmt);
-DBCStorage <FactionTemplateEntry> sFactionTemplateStore(FactionTemplateEntryfmt);
-
-DBCStorage <GemPropertiesEntry> sGemPropertiesStore(GemPropertiesEntryfmt);
-
-DBCStorage <GtCombatRatingsEntry> sGtCombatRatingsStore(GtCombatRatingsfmt);
-DBCStorage <GtChanceToMeleeCritBaseEntry> sGtChanceToMeleeCritBaseStore(GtChanceToMeleeCritBasefmt);
-DBCStorage <GtChanceToMeleeCritEntry> sGtChanceToMeleeCritStore(GtChanceToMeleeCritfmt);
-DBCStorage <GtChanceToSpellCritBaseEntry> sGtChanceToSpellCritBaseStore(GtChanceToSpellCritBasefmt);
-DBCStorage <GtChanceToSpellCritEntry> sGtChanceToSpellCritStore(GtChanceToSpellCritfmt);
-DBCStorage <GtOCTRegenHPEntry> sGtOCTRegenHPStore(GtOCTRegenHPfmt);
-//DBCStorage <GtOCTRegenMPEntry> sGtOCTRegenMPStore(GtOCTRegenMPfmt); -- not used currently
-DBCStorage <GtRegenHPPerSptEntry> sGtRegenHPPerSptStore(GtRegenHPPerSptfmt);
-DBCStorage <GtRegenMPPerSptEntry> sGtRegenMPPerSptStore(GtRegenMPPerSptfmt);
-DBCStorage <ItemEntry> sItemStore(Itemfmt);
-//DBCStorage <ItemCondExtCostsEntry> sItemCondExtCostsStore(ItemCondExtCostsEntryfmt);
-//DBCStorage <ItemDisplayInfoEntry> sItemDisplayInfoStore(ItemDisplayTemplateEntryfmt); -- not used currently
-DBCStorage <ItemExtendedCostEntry> sItemExtendedCostStore(ItemExtendedCostEntryfmt);
-DBCStorage <ItemRandomPropertiesEntry> sItemRandomPropertiesStore(ItemRandomPropertiesfmt);
-DBCStorage <ItemRandomSuffixEntry> sItemRandomSuffixStore(ItemRandomSuffixfmt);
-DBCStorage <ItemSetEntry> sItemSetStore(ItemSetEntryfmt);
-
-DBCStorage <LockEntry> sLockStore(LockEntryfmt);
-
-DBCStorage <MailTemplateEntry> sMailTemplateStore(MailTemplateEntryfmt);
-DBCStorage <MapEntry> sMapStore(MapEntryfmt);
-
-DBCStorage <QuestSortEntry> sQuestSortStore(QuestSortEntryfmt);
-
-DBCStorage <RandomPropertiesPointsEntry> sRandomPropertiesPointsStore(RandomPropertiesPointsfmt);
-
-DBCStorage <SkillLineEntry> sSkillLineStore(SkillLinefmt);
-DBCStorage <SkillLineAbilityEntry> sSkillLineAbilityStore(SkillLineAbilityfmt);
-
-DBCStorage <SoundEntriesEntry> sSoundEntriesStore(SoundEntriesfmt);
-
-DBCStorage <SpellItemEnchantmentEntry> sSpellItemEnchantmentStore(SpellItemEnchantmentfmt);
-DBCStorage <SpellItemEnchantmentConditionEntry> sSpellItemEnchantmentConditionStore(SpellItemEnchantmentConditionfmt);
-DBCStorage <SpellEntry> sSpellStore(SpellEntryfmt);
-SpellCategoryStore sSpellCategoryStore;
-PetFamilySpellsStore sPetFamilySpellsStore;
-
-DBCStorage <SpellCastTimesEntry> sSpellCastTimesStore(SpellCastTimefmt);
-DBCStorage <SpellDurationEntry> sSpellDurationStore(SpellDurationfmt);
-DBCStorage <SpellFocusObjectEntry> sSpellFocusObjectStore(SpellFocusObjectfmt);
-DBCStorage <SpellRadiusEntry> sSpellRadiusStore(SpellRadiusfmt);
-DBCStorage <SpellRangeEntry> sSpellRangeStore(SpellRangefmt);
-DBCStorage <SpellShapeshiftEntry> sSpellShapeshiftStore(SpellShapeshiftfmt);
-DBCStorage <StableSlotPricesEntry> sStableSlotPricesStore(StableSlotPricesfmt);
-DBCStorage <TalentEntry> sTalentStore(TalentEntryfmt);
-TalentSpellPosMap sTalentSpellPosMap;
-DBCStorage <TalentTabEntry> sTalentTabStore(TalentTabEntryfmt);
-
-// store absolute bit position for first rank for talent inspect
-typedef std::map<uint32,uint32> TalentInspectMap;
-static TalentInspectMap sTalentPosInInspect;
-static TalentInspectMap sTalentTabSizeInInspect;
-static uint32 sTalentTabPages[12/*MAX_CLASSES*/][3];
-
-DBCStorage <TaxiNodesEntry> sTaxiNodesStore(TaxiNodesEntryfmt);
-TaxiMask sTaxiNodesMask;
-
-// DBC used only for initialization sTaxiPathSetBySource at startup.
-TaxiPathSetBySource sTaxiPathSetBySource;
-DBCStorage <TaxiPathEntry> sTaxiPathStore(TaxiPathEntryfmt);
-
-// DBC used only for initialization sTaxiPathSetBySource at startup.
-TaxiPathNodesByPath sTaxiPathNodesByPath;
-
-static DBCStorage <TaxiPathNodeEntry> sTaxiPathNodeStore(TaxiPathNodeEntryfmt);
-DBCStorage <TotemCategoryEntry> sTotemCategoryStore(TotemCategoryEntryfmt);
-DBCStorage <WorldMapAreaEntry> sWorldMapAreaStore(WorldMapAreaEntryfmt);
-DBCStorage <WorldSafeLocsEntry> sWorldSafeLocsStore(WorldSafeLocsEntryfmt);
-
-typedef std::list<std::string> StoreProblemList;
-
-static bool LoadDBC_assert_print(uint32 fsize,uint32 rsize, const std::string& filename)
-{
- sLog.outError("ERROR: Size of '%s' setted by format string (%u) not equal size of C++ structure (%u).",filename.c_str(),fsize,rsize);
-
- // assert must fail after function call
- return false;
-}
-
-template<class T>
-inline void LoadDBC(uint32& availableDbcLocales,barGoLink& bar, StoreProblemList& errlist, DBCStorage<T>& storage, const std::string& dbc_path, const std::string& filename)
-{
- // compatibility format and C++ structure sizes
- assert(DBCFile::GetFormatRecordSize(storage.GetFormat()) == sizeof(T) || LoadDBC_assert_print(DBCFile::GetFormatRecordSize(storage.GetFormat()),sizeof(T),filename));
-
- std::string dbc_filename = dbc_path + filename;
- if(storage.Load(dbc_filename.c_str()))
- {
- bar.step();
- for(uint8 i = 0; i < MAX_LOCALE; ++i)
- {
- if(!(availableDbcLocales & (1 << i)))
- continue;
-
- std::string dbc_filename_loc = dbc_path + localeNames[i] + "/" + filename;
- if(!storage.LoadStringsFrom(dbc_filename_loc.c_str()))
- availableDbcLocales &= ~(1<<i); // mark as not available for speedup next checks
- }
- }
- else
- {
- // sort problematic dbc to (1) non compatible and (2) non-existed
- FILE * f=fopen(dbc_filename.c_str(),"rb");
- if(f)
- {
- char buf[100];
- snprintf(buf,100," (exist, but have %d fields instead %d) Wrong client version DBC file?",storage.GetFieldCount(),strlen(storage.GetFormat()));
- errlist.push_back(dbc_filename + buf);
- fclose(f);
- }
- else
- errlist.push_back(dbc_filename);
- }
-}
-
-void LoadDBCStores(const std::string& dataPath)
-{
- std::string dbcPath = dataPath+"dbc/";
-
- const uint32 DBCFilesCount = 57;
-
- barGoLink bar( DBCFilesCount );
-
- StoreProblemList bad_dbc_files;
- uint32 availableDbcLocales = 0xFFFFFFFF;
-
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sAreaStore, dbcPath,"AreaTable.dbc");
-
- // must be after sAreaStore loading
- for(uint32 i = 0; i < sAreaStore.GetNumRows(); ++i) // areaflag numbered from 0
- {
- if(AreaTableEntry const* area = sAreaStore.LookupEntry(i))
- {
- // fill AreaId->DBC records
- sAreaFlagByAreaID.insert(AreaFlagByAreaID::value_type(uint16(area->ID),area->exploreFlag));
-
- // fill MapId->DBC records ( skip sub zones and continents )
- if(area->zone==0 && area->mapid != 0 && area->mapid != 1 && area->mapid != 530 )
- sAreaFlagByMapID.insert(AreaFlagByMapID::value_type(area->mapid,area->exploreFlag));
- }
- }
-
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sAreaTriggerStore, dbcPath,"AreaTrigger.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sAuctionHouseStore, dbcPath,"AuctionHouse.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sBankBagSlotPricesStore, dbcPath,"BankBagSlotPrices.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sBattlemasterListStore, dbcPath,"BattlemasterList.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sCharStartOutfitStore, dbcPath,"CharStartOutfit.dbc");
-
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sCharTitlesStore, dbcPath,"CharTitles.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sChatChannelsStore, dbcPath,"ChatChannels.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sChrClassesStore, dbcPath,"ChrClasses.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sChrRacesStore, dbcPath,"ChrRaces.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sCreatureDisplayInfoStore, dbcPath,"CreatureDisplayInfo.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sCreatureFamilyStore, dbcPath,"CreatureFamily.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sCreatureSpellDataStore, dbcPath,"CreatureSpellData.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sDurabilityCostsStore, dbcPath,"DurabilityCosts.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sDurabilityQualityStore, dbcPath,"DurabilityQuality.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sEmotesTextStore, dbcPath,"EmotesText.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sFactionStore, dbcPath,"Faction.dbc");
- for (uint32 i=0;i<sFactionStore.GetNumRows(); ++i)
- {
- FactionEntry const * faction = sFactionStore.LookupEntry(i);
- if (faction && faction->team)
- {
- SimpleFactionsList &flist = sFactionTeamMap[faction->team];
- flist.push_back(i);
- }
- }
-
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sFactionTemplateStore, dbcPath,"FactionTemplate.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sGemPropertiesStore, dbcPath,"GemProperties.dbc");
-
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sGtCombatRatingsStore, dbcPath,"gtCombatRatings.dbc");
-
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sGtChanceToMeleeCritBaseStore, dbcPath,"gtChanceToMeleeCritBase.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sGtChanceToMeleeCritStore, dbcPath,"gtChanceToMeleeCrit.dbc");
-
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sGtChanceToSpellCritBaseStore, dbcPath,"gtChanceToSpellCritBase.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sGtChanceToSpellCritStore, dbcPath,"gtChanceToSpellCrit.dbc");
-
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sGtOCTRegenHPStore, dbcPath,"gtOCTRegenHP.dbc");
- //LoadDBC(availableDbcLocales,bar,bad_dbc_files,sGtOCTRegenMPStore, dbcPath,"gtOCTRegenMP.dbc"); -- not used currently
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sGtRegenHPPerSptStore, dbcPath,"gtRegenHPPerSpt.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sGtRegenMPPerSptStore, dbcPath,"gtRegenMPPerSpt.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sItemStore, dbcPath,"Item.dbc");
- //LoadDBC(availableDbcLocales,bar,bad_dbc_files,sItemDisplayInfoStore, dbcPath,"ItemDisplayInfo.dbc"); -- not used currently
- //LoadDBC(availableDbcLocales,bar,bad_dbc_files,sItemCondExtCostsStore, dbcPath,"ItemCondExtCosts.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sItemExtendedCostStore, dbcPath,"ItemExtendedCost.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sItemRandomPropertiesStore,dbcPath,"ItemRandomProperties.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sItemRandomSuffixStore, dbcPath,"ItemRandomSuffix.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sItemSetStore, dbcPath,"ItemSet.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sLockStore, dbcPath,"Lock.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sMailTemplateStore, dbcPath,"MailTemplate.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sMapStore, dbcPath,"Map.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sQuestSortStore, dbcPath,"QuestSort.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sRandomPropertiesPointsStore, dbcPath,"RandPropPoints.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sSkillLineStore, dbcPath,"SkillLine.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sSkillLineAbilityStore, dbcPath,"SkillLineAbility.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sSoundEntriesStore, dbcPath,"SoundEntries.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sSpellStore, dbcPath,"Spell.dbc");
- for(uint32 i = 1; i < sSpellStore.GetNumRows(); ++i)
- {
- SpellEntry const * spell = sSpellStore.LookupEntry(i);
- if(spell && spell->Category)
- sSpellCategoryStore[spell->Category].insert(i);
-
- // DBC not support uint64 fields but SpellEntry have SpellFamilyFlags mapped at 2 uint32 fields
- // uint32 field already converted to bigendian if need, but must be swapped for correct uint64 bigendian view
- #if TRINITY_ENDIAN == TRINITY_BIGENDIAN
- std::swap(*((uint32*)(&spell->SpellFamilyFlags)),*(((uint32*)(&spell->SpellFamilyFlags))+1));
- #endif
- }
-
- for (uint32 j = 0; j < sSkillLineAbilityStore.GetNumRows(); ++j)
- {
- SkillLineAbilityEntry const *skillLine = sSkillLineAbilityStore.LookupEntry(j);
-
- if(!skillLine)
- continue;
-
- SpellEntry const* spellInfo = sSpellStore.LookupEntry(skillLine->spellId);
-
- if(spellInfo && (spellInfo->Attributes & 0x1D0) == 0x1D0)
- {
- for (unsigned int i = 1; i < sCreatureFamilyStore.GetNumRows(); ++i)
- {
- CreatureFamilyEntry const* cFamily = sCreatureFamilyStore.LookupEntry(i);
- if(!cFamily)
- continue;
-
- if(skillLine->skillId != cFamily->skillLine[0] && skillLine->skillId != cFamily->skillLine[1])
- continue;
-
- sPetFamilySpellsStore[i].insert(spellInfo->Id);
- }
- }
- }
-
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sSpellCastTimesStore, dbcPath,"SpellCastTimes.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sSpellDurationStore, dbcPath,"SpellDuration.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sSpellFocusObjectStore, dbcPath,"SpellFocusObject.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sSpellItemEnchantmentStore,dbcPath,"SpellItemEnchantment.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sSpellItemEnchantmentConditionStore,dbcPath,"SpellItemEnchantmentCondition.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sSpellRadiusStore, dbcPath,"SpellRadius.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sSpellRangeStore, dbcPath,"SpellRange.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sSpellShapeshiftStore, dbcPath,"SpellShapeshiftForm.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sStableSlotPricesStore, dbcPath,"StableSlotPrices.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sTalentStore, dbcPath,"Talent.dbc");
-
- // create talent spells set
- for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
- {
- TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
- if (!talentInfo) continue;
- for (int j = 0; j < 5; j++)
- if(talentInfo->RankID[j])
- sTalentSpellPosMap[talentInfo->RankID[j]] = TalentSpellPos(i,j);
- }
-
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sTalentTabStore, dbcPath,"TalentTab.dbc");
-
- // prepare fast data access to bit pos of talent ranks for use at inspecting
- {
- // fill table by amount of talent ranks and fill sTalentTabBitSizeInInspect
- // store in with (row,col,talent)->size key for correct sorting by (row,col)
- typedef std::map<uint32,uint32> TalentBitSize;
- TalentBitSize sTalentBitSize;
- for(uint32 i = 1; i < sTalentStore.GetNumRows(); ++i)
- {
- TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
- if (!talentInfo) continue;
-
- TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
- if(!talentTabInfo)
- continue;
-
- // find talent rank
- uint32 curtalent_maxrank = 0;
- for(uint32 k = 5; k > 0; --k)
- {
- if(talentInfo->RankID[k-1])
- {
- curtalent_maxrank = k;
- break;
- }
- }
-
- sTalentBitSize[(talentInfo->Row<<24) + (talentInfo->Col<<16)+talentInfo->TalentID] = curtalent_maxrank;
- sTalentTabSizeInInspect[talentInfo->TalentTab] += curtalent_maxrank;
- }
-
- // now have all max ranks (and then bit amount used for store talent ranks in inspect)
- for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
- {
- TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
- if(!talentTabInfo)
- continue;
-
- // store class talent tab pages
- uint32 cls = 1;
- for(uint32 m=1;!(m & talentTabInfo->ClassMask) && cls < 12 /*MAX_CLASSES*/;m <<=1, ++cls) {}
-
- sTalentTabPages[cls][talentTabInfo->tabpage]=talentTabId;
-
- // add total amount bits for first rank starting from talent tab first talent rank pos.
- uint32 pos = 0;
- for(TalentBitSize::iterator itr = sTalentBitSize.begin(); itr != sTalentBitSize.end(); ++itr)
- {
- uint32 talentId = itr->first & 0xFFFF;
- TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
- if(!talentInfo)
- continue;
-
- if(talentInfo->TalentTab != talentTabId)
- continue;
-
- sTalentPosInInspect[talentId] = pos;
- pos+= itr->second;
- }
- }
- }
-
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sTaxiNodesStore, dbcPath,"TaxiNodes.dbc");
-
- // Initialize global taxinodes mask
- memset(sTaxiNodesMask,0,sizeof(sTaxiNodesMask));
- for(uint32 i = 1; i < sTaxiNodesStore.GetNumRows(); ++i)
- {
- if(sTaxiNodesStore.LookupEntry(i))
- {
- uint8 field = (uint8)((i - 1) / 32);
- uint32 submask = 1<<((i-1)%32);
- sTaxiNodesMask[field] |= submask;
- }
- }
-
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sTaxiPathStore, dbcPath,"TaxiPath.dbc");
- for(uint32 i = 1; i < sTaxiPathStore.GetNumRows(); ++i)
- if(TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(i))
- sTaxiPathSetBySource[entry->from][entry->to] = TaxiPathBySourceAndDestination(entry->ID,entry->price);
- uint32 pathCount = sTaxiPathStore.GetNumRows();
-
- //## TaxiPathNode.dbc ## Loaded only for initialization different structures
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sTaxiPathNodeStore, dbcPath,"TaxiPathNode.dbc");
- // Calculate path nodes count
- std::vector<uint32> pathLength;
- pathLength.resize(pathCount); // 0 and some other indexes not used
- for(uint32 i = 1; i < sTaxiPathNodeStore.GetNumRows(); ++i)
- if(TaxiPathNodeEntry const* entry = sTaxiPathNodeStore.LookupEntry(i))
- ++pathLength[entry->path];
- // Set path length
- sTaxiPathNodesByPath.resize(pathCount); // 0 and some other indexes not used
- for(uint32 i = 1; i < sTaxiPathNodesByPath.size(); ++i)
- sTaxiPathNodesByPath[i].resize(pathLength[i]);
- // fill data
- for(uint32 i = 1; i < sTaxiPathNodeStore.GetNumRows(); ++i)
- if(TaxiPathNodeEntry const* entry = sTaxiPathNodeStore.LookupEntry(i))
- sTaxiPathNodesByPath[entry->path][entry->index] = TaxiPathNode(entry->mapid,entry->x,entry->y,entry->z,entry->actionFlag,entry->delay);
- sTaxiPathNodeStore.Clear();
-
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sTotemCategoryStore, dbcPath,"TotemCategory.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sWorldMapAreaStore, dbcPath,"WorldMapArea.dbc");
- LoadDBC(availableDbcLocales,bar,bad_dbc_files,sWorldSafeLocsStore, dbcPath,"WorldSafeLocs.dbc");
-
- // error checks
- if(bad_dbc_files.size() >= DBCFilesCount )
- {
- sLog.outError("\nIncorrect DataDir value in Trinityd.conf or ALL required *.dbc files (%d) not found by path: %sdbc",DBCFilesCount,dataPath.c_str());
- exit(1);
- }
- else if(!bad_dbc_files.empty() )
- {
- std::string str;
- for(std::list<std::string>::iterator i = bad_dbc_files.begin(); i != bad_dbc_files.end(); ++i)
- str += *i + "\n";
-
- sLog.outError("\nSome required *.dbc files (%u from %d) not found or not compatible:\n%s",bad_dbc_files.size(),DBCFilesCount,str.c_str());
- exit(1);
- }
-
- // check at up-to-date DBC files (53085 is last added spell in 2.4.3)
- // check at up-to-date DBC files (17514 is last ID in SkillLineAbilities in 2.4.3)
- // check at up-to-date DBC files (598 is last map added in 2.4.3)
- // check at up-to-date DBC files (1127 is last gem property added in 2.4.3)
- // check at up-to-date DBC files (2425 is last item extended cost added in 2.4.3)
- // check at up-to-date DBC files (71 is last char title added in 2.4.3)
- // check at up-to-date DBC files (1768 is last area added in 2.4.3)
- if( !sSpellStore.LookupEntry(53085) ||
- !sSkillLineAbilityStore.LookupEntry(17514) ||
- !sMapStore.LookupEntry(598) ||
- !sGemPropertiesStore.LookupEntry(1127) ||
- !sItemExtendedCostStore.LookupEntry(2425) ||
- !sCharTitlesStore.LookupEntry(71) ||
- !sAreaStore.LookupEntry(1768) )
- {
- sLog.outError("\nYou have _outdated_ DBC files. Please extract correct versions from current using client.");
- exit(1);
- }
-
- sLog.outString();
- sLog.outString( ">> Loaded %d data stores", DBCFilesCount );
- sLog.outString();
-}
-
-SimpleFactionsList const* GetFactionTeamList(uint32 faction)
-{
- FactionTeamMap::const_iterator itr = sFactionTeamMap.find(faction);
- if(itr==sFactionTeamMap.end())
- return NULL;
- return &itr->second;
-}
-
-char* GetPetName(uint32 petfamily, uint32 dbclang)
-{
- if(!petfamily)
- return NULL;
- CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(petfamily);
- if(!pet_family)
- return NULL;
- return pet_family->Name[dbclang]?pet_family->Name[dbclang]:NULL;
-}
-
-TalentSpellPos const* GetTalentSpellPos(uint32 spellId)
-{
- TalentSpellPosMap::const_iterator itr = sTalentSpellPosMap.find(spellId);
- if(itr==sTalentSpellPosMap.end())
- return NULL;
-
- return &itr->second;
-}
-
-uint32 GetTalentSpellCost(uint32 spellId)
-{
- if(TalentSpellPos const* pos = GetTalentSpellPos(spellId))
- return pos->rank+1;
-
- return 0;
-}
-
-int32 GetAreaFlagByAreaID(uint32 area_id)
-{
- AreaFlagByAreaID::iterator i = sAreaFlagByAreaID.find(area_id);
- if(i == sAreaFlagByAreaID.end())
- return -1;
-
- return i->second;
-}
-
-AreaTableEntry const* GetAreaEntryByAreaID(uint32 area_id)
-{
- int32 areaflag = GetAreaFlagByAreaID(area_id);
- if(areaflag < 0)
- return NULL;
-
- return sAreaStore.LookupEntry(areaflag );
-}
-
-AreaTableEntry const* GetAreaEntryByAreaFlagAndMap(uint32 area_flag,uint32 map_id)
-{
- if(area_flag)
- return sAreaStore.LookupEntry(area_flag);
-
- if(MapEntry const* mapEntry = sMapStore.LookupEntry(map_id))
- return GetAreaEntryByAreaID(mapEntry->linked_zone);
-
- return NULL;
-}
-
-uint32 GetAreaFlagByMapId(uint32 mapid)
-{
- AreaFlagByMapID::iterator i = sAreaFlagByMapID.find(mapid);
- if(i == sAreaFlagByMapID.end())
- return 0;
- else
- return i->second;
-}
-
-uint32 GetVirtualMapForMapAndZone(uint32 mapid, uint32 zoneId)
-{
- if(mapid != 530) // speed for most cases
- return mapid;
-
- if(WorldMapAreaEntry const* wma = sWorldMapAreaStore.LookupEntry(zoneId))
- return wma->virtual_map_id >= 0 ? wma->virtual_map_id : wma->map_id;
-
- return mapid;
-}
-
-ContentLevels GetContentLevelsForMapAndZone(uint32 mapid, uint32 zoneId)
-{
- mapid = GetVirtualMapForMapAndZone(mapid,zoneId);
- if(mapid < 2)
- return CONTENT_1_60;
-
- MapEntry const* mapEntry = sMapStore.LookupEntry(mapid);
- if(!mapEntry)
- return CONTENT_1_60;
-
- switch(mapEntry->Expansion())
- {
- default: return CONTENT_1_60;
- case 1: return CONTENT_61_70;
- case 2: return CONTENT_71_80;
- }
-}
-
-ChatChannelsEntry const* GetChannelEntryFor(uint32 channel_id)
-{
- // not sorted, numbering index from 0
- for(uint32 i = 0; i < sChatChannelsStore.GetNumRows(); ++i)
- {
- ChatChannelsEntry const* ch = sChatChannelsStore.LookupEntry(i);
- if(ch && ch->ChannelID == channel_id)
- return ch;
- }
- return NULL;
-}
-
-bool IsTotemCategoryCompatiableWith(uint32 itemTotemCategoryId, uint32 requiredTotemCategoryId)
-{
- if(requiredTotemCategoryId==0)
- return true;
- if(itemTotemCategoryId==0)
- return false;
-
- TotemCategoryEntry const* itemEntry = sTotemCategoryStore.LookupEntry(itemTotemCategoryId);
- if(!itemEntry)
- return false;
- TotemCategoryEntry const* reqEntry = sTotemCategoryStore.LookupEntry(requiredTotemCategoryId);
- if(!reqEntry)
- return false;
-
- if(itemEntry->categoryType!=reqEntry->categoryType)
- return false;
-
- return (itemEntry->categoryMask & reqEntry->categoryMask)==reqEntry->categoryMask;
-}
-
-void Zone2MapCoordinates(float& x,float& y,uint32 zone)
-{
- WorldMapAreaEntry const* maEntry = sWorldMapAreaStore.LookupEntry(zone);
-
- // if not listed then map coordinates (instance)
- if(!maEntry)
- return;
-
- std::swap(x,y); // at client map coords swapped
- x = x*((maEntry->x2-maEntry->x1)/100)+maEntry->x1;
- y = y*((maEntry->y2-maEntry->y1)/100)+maEntry->y1; // client y coord from top to down
-}
-
-void Map2ZoneCoordinates(float& x,float& y,uint32 zone)
-{
- WorldMapAreaEntry const* maEntry = sWorldMapAreaStore.LookupEntry(zone);
-
- // if not listed then map coordinates (instance)
- if(!maEntry)
- return;
-
- x = (x-maEntry->x1)/((maEntry->x2-maEntry->x1)/100);
- y = (y-maEntry->y1)/((maEntry->y2-maEntry->y1)/100); // client y coord from top to down
- std::swap(x,y); // client have map coords swapped
-}
-
-uint32 GetTalentInspectBitPosInTab(uint32 talentId)
-{
- TalentInspectMap::const_iterator itr = sTalentPosInInspect.find(talentId);
- if(itr == sTalentPosInInspect.end())
- return 0;
-
- return itr->second;
-}
-
-uint32 GetTalentTabInspectBitSize(uint32 talentTabId)
-{
- TalentInspectMap::const_iterator itr = sTalentTabSizeInInspect.find(talentTabId);
- if(itr == sTalentTabSizeInInspect.end())
- return 0;
-
- return itr->second;
-}
-
-uint32 const* GetTalentTabPages(uint32 cls)
-{
- return sTalentTabPages[cls];
-}
-
-// script support functions
-TRINITY_DLL_SPEC DBCStorage <SoundEntriesEntry> const* GetSoundEntriesStore() { return &sSoundEntriesStore; }
-TRINITY_DLL_SPEC DBCStorage <SpellEntry> const* GetSpellStore() { return &sSpellStore; }
-TRINITY_DLL_SPEC DBCStorage <SpellRangeEntry> const* GetSpellRangeStore() { return &sSpellRangeStore; }
-
diff --git a/src/shared/Database/DBCStores.h b/src/shared/Database/DBCStores.h
deleted file mode 100644
index 4ad275653e7..00000000000
--- a/src/shared/Database/DBCStores.h
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
- *
- * Copyright (C) 2008 Trinity <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, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-#ifndef DBCSTORES_H
-#define DBCSTORES_H
-
-#include "Common.h"
-//#include "DataStore.h"
-#include "dbcfile.h"
-#include "DBCStructure.h"
-
-#include <list>
-
-typedef std::list<uint32> SimpleFactionsList;
-
-SimpleFactionsList const* GetFactionTeamList(uint32 faction);
-char* GetPetName(uint32 petfamily, uint32 dbclang);
-uint32 GetTalentSpellCost(uint32 spellId);
-TalentSpellPos const* GetTalentSpellPos(uint32 spellId);
-
-int32 GetAreaFlagByAreaID(uint32 area_id); // -1 if not found
-AreaTableEntry const* GetAreaEntryByAreaID(uint32 area_id);
-AreaTableEntry const* GetAreaEntryByAreaFlagAndMap(uint32 area_flag,uint32 map_id);
-uint32 GetAreaFlagByMapId(uint32 mapid);
-
-uint32 GetVirtualMapForMapAndZone(uint32 mapid, uint32 zoneId);
-
-enum ContentLevels
-{
- CONTENT_1_60 = 0,
- CONTENT_61_70,
- CONTENT_71_80
-};
-ContentLevels GetContentLevelsForMapAndZone(uint32 mapid, uint32 zoneId);
-
-ChatChannelsEntry const* GetChannelEntryFor(uint32 channel_id);
-
-bool IsTotemCategoryCompatiableWith(uint32 itemTotemCategoryId, uint32 requiredTotemCategoryId);
-
-void Zone2MapCoordinates(float& x,float& y,uint32 zone);
-void Map2ZoneCoordinates(float& x,float& y,uint32 zone);
-
-uint32 GetTalentInspectBitPosInTab(uint32 talentId);
-uint32 GetTalentTabInspectBitSize(uint32 talentTabId);
-uint32 const* /*[3]*/ GetTalentTabPages(uint32 cls);
-
-template<class T>
-class DBCStorage
-{
- typedef std::list<char*> StringPoolList;
- public:
- explicit DBCStorage(const char *f) : nCount(0), fieldCount(0), fmt(f), indexTable(NULL), m_dataTable(NULL) { }
- ~DBCStorage() { Clear(); }
-
- T const* LookupEntry(uint32 id) const { return (id>=nCount)?NULL:indexTable[id]; }
- uint32 GetNumRows() const { return nCount; }
- char const* GetFormat() const { return fmt; }
- uint32 GetFieldCount() const { return fieldCount; }
-
- bool Load(char const* fn)
- {
- DBCFile dbc;
- // Check if load was sucessful, only then continue
- if(!dbc.Load(fn, fmt))
- return false;
-
- fieldCount = dbc.GetCols();
- m_dataTable = (T*)dbc.AutoProduceData(fmt,nCount,(char**&)indexTable);
- m_stringPoolList.push_back(dbc.AutoProduceStrings(fmt,(char*)m_dataTable));
-
- // error in dbc file at loading if NULL
- return indexTable!=NULL;
- }
-
- bool LoadStringsFrom(char const* fn)
- {
- // DBC must be already loaded using Load
- if(!indexTable)
- return false;
-
- DBCFile dbc;
- // Check if load was successful, only then continue
- if(!dbc.Load(fn, fmt))
- return false;
-
- m_stringPoolList.push_back(dbc.AutoProduceStrings(fmt,(char*)m_dataTable));
-
- return true;
- }
-
- void Clear()
- {
- if (!indexTable)
- return;
-
- delete[] ((char*)indexTable);
- indexTable = NULL;
- delete[] ((char*)m_dataTable);
- m_dataTable = NULL;
-
- while(!m_stringPoolList.empty())
- {
- delete[] m_stringPoolList.front();
- m_stringPoolList.pop_front();
- }
- nCount = 0;
- }
-
- private:
- uint32 nCount;
- uint32 fieldCount;
- char const* fmt;
- T** indexTable;
- T* m_dataTable;
- StringPoolList m_stringPoolList;
-};
-
-extern DBCStorage <AreaTableEntry> sAreaStore;// recommend access using functions
-extern DBCStorage <AreaTriggerEntry> sAreaTriggerStore;
-extern DBCStorage <AuctionHouseEntry> sAuctionHouseStore;
-extern DBCStorage <BankBagSlotPricesEntry> sBankBagSlotPricesStore;
-extern DBCStorage <BattlemasterListEntry> sBattlemasterListStore;
-//extern DBCStorage <ChatChannelsEntry> sChatChannelsStore; -- accessed using function, no usable index
-extern DBCStorage <CharStartOutfitEntry> sCharStartOutfitStore;
-extern DBCStorage <CharTitlesEntry> sCharTitlesStore;
-extern DBCStorage <ChrClassesEntry> sChrClassesStore;
-extern DBCStorage <ChrRacesEntry> sChrRacesStore;
-extern DBCStorage <CreatureDisplayInfoEntry> sCreatureDisplayInfoStore;
-extern DBCStorage <CreatureFamilyEntry> sCreatureFamilyStore;
-extern DBCStorage <CreatureSpellDataEntry> sCreatureSpellDataStore;
-extern DBCStorage <DurabilityCostsEntry> sDurabilityCostsStore;
-extern DBCStorage <DurabilityQualityEntry> sDurabilityQualityStore;
-extern DBCStorage <EmotesTextEntry> sEmotesTextStore;
-extern DBCStorage <FactionEntry> sFactionStore;
-extern DBCStorage <FactionTemplateEntry> sFactionTemplateStore;
-extern DBCStorage <GemPropertiesEntry> sGemPropertiesStore;
-
-extern DBCStorage <GtCombatRatingsEntry> sGtCombatRatingsStore;
-extern DBCStorage <GtChanceToMeleeCritBaseEntry> sGtChanceToMeleeCritBaseStore;
-extern DBCStorage <GtChanceToMeleeCritEntry> sGtChanceToMeleeCritStore;
-extern DBCStorage <GtChanceToSpellCritBaseEntry> sGtChanceToSpellCritBaseStore;
-extern DBCStorage <GtChanceToSpellCritEntry> sGtChanceToSpellCritStore;
-extern DBCStorage <GtOCTRegenHPEntry> sGtOCTRegenHPStore;
-//extern DBCStorage <GtOCTRegenMPEntry> sGtOCTRegenMPStore; -- not used currently
-extern DBCStorage <GtRegenHPPerSptEntry> sGtRegenHPPerSptStore;
-extern DBCStorage <GtRegenMPPerSptEntry> sGtRegenMPPerSptStore;
-extern DBCStorage <ItemEntry> sItemStore;
-//extern DBCStorage <ItemDisplayInfoEntry> sItemDisplayInfoStore; -- not used currently
-extern DBCStorage <ItemExtendedCostEntry> sItemExtendedCostStore;
-extern DBCStorage <ItemRandomPropertiesEntry> sItemRandomPropertiesStore;
-extern DBCStorage <ItemRandomSuffixEntry> sItemRandomSuffixStore;
-extern DBCStorage <ItemSetEntry> sItemSetStore;
-extern DBCStorage <LockEntry> sLockStore;
-extern DBCStorage <MailTemplateEntry> sMailTemplateStore;
-extern DBCStorage <MapEntry> sMapStore;
-extern DBCStorage <QuestSortEntry> sQuestSortStore;
-extern DBCStorage <RandomPropertiesPointsEntry> sRandomPropertiesPointsStore;
-extern DBCStorage <SkillLineEntry> sSkillLineStore;
-extern DBCStorage <SkillLineAbilityEntry> sSkillLineAbilityStore;
-extern DBCStorage <SoundEntriesEntry> sSoundEntriesStore;
-extern DBCStorage <SpellCastTimesEntry> sSpellCastTimesStore;
-extern DBCStorage <SpellDurationEntry> sSpellDurationStore;
-extern DBCStorage <SpellFocusObjectEntry> sSpellFocusObjectStore;
-extern DBCStorage <SpellItemEnchantmentEntry> sSpellItemEnchantmentStore;
-extern DBCStorage <SpellItemEnchantmentConditionEntry> sSpellItemEnchantmentConditionStore;
-extern SpellCategoryStore sSpellCategoryStore;
-extern PetFamilySpellsStore sPetFamilySpellsStore;
-extern DBCStorage <SpellRadiusEntry> sSpellRadiusStore;
-extern DBCStorage <SpellRangeEntry> sSpellRangeStore;
-extern DBCStorage <SpellShapeshiftEntry> sSpellShapeshiftStore;
-extern DBCStorage <SpellEntry> sSpellStore;
-extern DBCStorage <StableSlotPricesEntry> sStableSlotPricesStore;
-extern DBCStorage <TalentEntry> sTalentStore;
-extern DBCStorage <TalentTabEntry> sTalentTabStore;
-extern DBCStorage <TaxiNodesEntry> sTaxiNodesStore;
-extern DBCStorage <TaxiPathEntry> sTaxiPathStore;
-extern TaxiMask sTaxiNodesMask;
-extern TaxiPathSetBySource sTaxiPathSetBySource;
-extern TaxiPathNodesByPath sTaxiPathNodesByPath;
-extern DBCStorage <TotemCategoryEntry> sTotemCategoryStore;
-//extern DBCStorage <WorldMapAreaEntry> sWorldMapAreaStore; -- use Zone2MapCoordinates and Map2ZoneCoordinates
-extern DBCStorage <WorldSafeLocsEntry> sWorldSafeLocsStore;
-
-void LoadDBCStores(const std::string& dataPath);
-
-// script support functions
-TRINITY_DLL_SPEC DBCStorage <SoundEntriesEntry> const* GetSoundEntriesStore();
-TRINITY_DLL_SPEC DBCStorage <SpellEntry> const* GetSpellStore();
-TRINITY_DLL_SPEC DBCStorage <SpellRangeEntry> const* GetSpellRangeStore();
-#endif
-
diff --git a/src/shared/Database/DBCStructure.h b/src/shared/Database/DBCStructure.h
deleted file mode 100644
index 8e8aa8bfba8..00000000000
--- a/src/shared/Database/DBCStructure.h
+++ /dev/null
@@ -1,904 +0,0 @@
-/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
- *
- * Copyright (C) 2008 Trinity <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, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-#ifndef DBCSTRUCTURE_H
-#define DBCSTRUCTURE_H
-
-#include "DBCEnums.h"
-#include "Platform/Define.h"
-
-#include <map>
-#include <set>
-#include <vector>
-
-// Structures using to access raw DBC data and required packing to portability
-
-// GCC have alternative #pragma pack(N) syntax and old gcc version not support pack(push,N), also any gcc version not support it at some platform
-#if defined( __GNUC__ )
-#pragma pack(1)
-#else
-#pragma pack(push,1)
-#endif
-
-struct AreaTableEntry
-{
- uint32 ID; // 0
- uint32 mapid; // 1
- uint32 zone; // 2 if 0 then it's zone, else it's zone id of this area
- uint32 exploreFlag; // 3, main index
- uint32 flags; // 4, unknown value but 312 for all cities
- // 5-9 unused
- int32 area_level; // 10
- char* area_name[16]; // 11-26
- // 27, string flags, unused
- uint32 team; // 28
-};
-
-struct AreaTriggerEntry
-{
- uint32 id; // 0
- uint32 mapid; // 1
- float x; // 2
- float y; // 3
- float z; // 4
- float radius; // 5
- float box_x; // 6 extent x edge
- float box_y; // 7 extent y edge
- float box_z; // 8 extent z edge
- float box_orientation; // 9 extent rotation by about z axis
-};
-
-struct AuctionHouseEntry
-{
- uint32 houseId; // 0 index
- uint32 faction; // 1 id of faction.dbc for player factions associated with city
- uint32 depositPercent; // 2 1/3 from real
- uint32 cutPercent; // 3
- //char* name[16]; // 4-19
- // 20 string flag, unused
-};
-
-struct BankBagSlotPricesEntry
-{
- uint32 ID;
- uint32 price;
-};
-
-struct BattlemasterListEntry
-{
- uint32 id; // 0
- uint32 mapid[3]; // 1-3 mapid
- // 4-8 unused
- uint32 type; // 9 (3 - BG, 4 - arena)
- uint32 minlvl; // 10
- uint32 maxlvl; // 11
- uint32 maxplayersperteam; // 12
- // 13-14 unused
- char* name[16]; // 15-30
- // 31 string flag, unused
- // 32 unused
-};
-
-#define MAX_OUTFIT_ITEMS 12
-// #define MAX_OUTFIT_ITEMS 24 // 12->24 in 3.0.x
-
-struct CharStartOutfitEntry
-{
- //uint32 Id; // 0
- uint32 RaceClassGender; // 1 (UNIT_FIELD_BYTES_0 & 0x00FFFFFF) comparable (0 byte = race, 1 byte = class, 2 byte = gender)
- int32 ItemId[MAX_OUTFIT_ITEMS]; // 2-13
- //int32 ItemDisplayId[MAX_OUTFIT_ITEMS]; // 14-25 not required at server side
- //int32 ItemInventorySlot[MAX_OUTFIT_ITEMS]; // 26-37 not required at server side
- //uint32 Unknown1; // 38, unique values (index-like with gaps ordered in other way as ids)
- //uint32 Unknown2; // 39
- //uint32 Unknown3; // 40
-};
-
-struct CharTitlesEntry
-{
- uint32 ID; // 0, title ids, for example in Quest::GetCharTitleId()
- //uint32 unk1; // 1 flags?
- //char* name[16]; // 2-17, unused
- // 18 string flag, unused
- //char* name2[16]; // 19-34, unused
- // 35 string flag, unused
- uint32 bit_index; // 36 used in PLAYER_CHOSEN_TITLE and 1<<index in PLAYER__FIELD_KNOWN_TITLES
-};
-
-struct ChatChannelsEntry
-{
- uint32 ChannelID; // 0
- uint32 flags; // 1
- char* pattern[16]; // 3-18
- // 19 string flags, unused
- //char* name[16]; // 20-35 unused
- // 36 string flag, unused
-};
-
-struct ChrClassesEntry
-{
- uint32 ClassID; // 0
- // 1-2, unused
- uint32 powerType; // 3
- // 4, unused
- //char* name[16]; // 5-20 unused
- char* name[16]; // 5-20 unused
- // 21 string flag, unused
- //char* nameFemale[16]; // 21-36 unused, if different from base (male) case
- // 37 string flag, unused
- //char* nameNeutralGender[16]; // 38-53 unused, if different from base (male) case
- // 54 string flag, unused
- // 55, unused
- uint32 spellfamily; // 56
- // 57, unused
-};
-
-struct ChrRacesEntry
-{
- uint32 RaceID; // 0
- // 1 unused
- uint32 FactionID; // 2 facton template id
- // 3 unused
- uint32 model_m; // 4
- uint32 model_f; // 5
- // 6-7 unused
- uint32 TeamID; // 8 (7-Alliance 1-Horde)
- // 9-12 unused
- uint32 startmovie; // 13 id from CinematicCamera.dbc
- char* name[16]; // 14-29 used for DBC language detection/selection
- // 30 string flags, unused
- //char* nameFemale[16]; // 31-46, if different from base (male) case
- // 47 string flags, unused
- //char* nameNeutralGender[16]; // 48-63, if different from base (male) case
- // 64 string flags, unused
- // 65-67 unused
- uint32 addon; // 68 (0 - original race, 1 - tbc addon, ...)
-};
-
-struct CreatureDisplayInfoEntry
-{
- uint32 Displayid; // 0
- // 1-3,unused
- float scale; // 4
- // 5-13,unused
-};
-
-struct CreatureFamilyEntry
-{
- uint32 ID; // 0
- float minScale; // 1
- uint32 minScaleLevel; // 2 0/1
- float maxScale; // 3
- uint32 maxScaleLevel; // 4 0/60
- uint32 skillLine[2]; // 5-6
- uint32 petFoodMask; // 7
- char* Name[16]; // 8-23
- // 24 string flags, unused
- // 25 icon, unused
-};
-
-struct CreatureSpellDataEntry
-{
- uint32 ID; // 0
- //uint32 spellId[4]; // 1-4 hunter pet learned spell (for later use)
-};
-
-struct DurabilityCostsEntry
-{
- uint32 Itemlvl; // 0
- uint32 multiplier[29]; // 1-29
-};
-
-struct DurabilityQualityEntry
-{
- uint32 Id; // 0
- float quality_mod; // 1
-};
-
-struct EmotesTextEntry
-{
- uint32 Id;
- uint32 textid;
-};
-
-struct FactionEntry
-{
- uint32 ID; // 0
- int32 reputationListID; // 1
- uint32 BaseRepRaceMask[4]; // 2-5 Base reputation race masks (see enum Races)
- uint32 BaseRepClassMask[4]; // 6-9 Base reputation class masks (see enum Classes)
- int32 BaseRepValue[4]; // 10-13 Base reputation values
- uint32 ReputationFlags[4]; // 14-17 Default flags to apply
- uint32 team; // 18 enum Team
- char* name[16]; // 19-34
- // 35 string flags, unused
- //char* description[16]; // 36-51 unused
- // 52 string flags, unused
-};
-
-struct FactionTemplateEntry
-{
- uint32 ID; // 0
- uint32 faction; // 1
- uint32 factionFlags; // 2 specific flags for that faction
- uint32 ourMask; // 3 if mask set (see FactionMasks) then faction included in masked team
- uint32 friendlyMask; // 4 if mask set (see FactionMasks) then faction friendly to masked team
- uint32 hostileMask; // 5 if mask set (see FactionMasks) then faction hostile to masked team
- uint32 enemyFaction1; // 6
- uint32 enemyFaction2; // 7
- uint32 enemyFaction3; // 8
- uint32 enemyFaction4; // 9
- uint32 friendFaction1; // 10
- uint32 friendFaction2; // 11
- uint32 friendFaction3; // 12
- uint32 friendFaction4; // 13
- //------------------------------------------------------- end structure
-
- // helpers
- bool IsFriendlyTo(FactionTemplateEntry const& entry) const
- {
- if(ID == entry.ID)
- return true;
- if(enemyFaction1 == entry.faction || enemyFaction2 == entry.faction || enemyFaction3 == entry.faction || enemyFaction4 == entry.faction )
- return false;
- if(friendFaction1 == entry.faction || friendFaction2 == entry.faction || friendFaction3 == entry.faction || friendFaction4 == entry.faction )
- return true;
- return (friendlyMask & entry.ourMask) || (ourMask & entry.friendlyMask);
- }
- bool IsHostileTo(FactionTemplateEntry const& entry) const
- {
- if(ID == entry.ID)
- return false;
- if(enemyFaction1 == entry.faction || enemyFaction2 == entry.faction || enemyFaction3 == entry.faction || enemyFaction4 == entry.faction )
- return true;
- if(friendFaction1 == entry.faction || friendFaction2 == entry.faction || friendFaction3 == entry.faction || friendFaction4 == entry.faction )
- return false;
- return (hostileMask & entry.ourMask) != 0;
- }
- bool IsHostileToPlayers() const { return (hostileMask & FACTION_MASK_PLAYER) !=0; }
- bool IsNeutralToAll() const { return hostileMask == 0 && friendlyMask == 0 && enemyFaction1==0 && enemyFaction2==0 && enemyFaction3==0 && enemyFaction4==0; }
- bool IsContestedGuardFaction() const { return (factionFlags & FACTION_TEMPLATE_FLAG_CONTESTED_GUARD)!=0; }
-};
-
-struct GemPropertiesEntry
-{
- uint32 ID;
- uint32 spellitemenchantement;
- uint32 color;
-};
-
-// All Gt* DBC store data for 100 levels, some by 100 per class/race
-#define GT_MAX_LEVEL 100
-
-struct GtCombatRatingsEntry
-{
- float ratio;
-};
-
-struct GtChanceToMeleeCritBaseEntry
-{
- float base;
-};
-
-struct GtChanceToMeleeCritEntry
-{
- float ratio;
-};
-
-struct GtChanceToSpellCritBaseEntry
-{
- float base;
-};
-
-struct GtChanceToSpellCritEntry
-{
- float ratio;
-};
-
-struct GtOCTRegenHPEntry
-{
- float ratio;
-};
-
-//struct GtOCTRegenMPEntry
-//{
-// float ratio;
-//};
-
-struct GtRegenHPPerSptEntry
-{
- float ratio;
-};
-
-struct GtRegenMPPerSptEntry
-{
- float ratio;
-};
-
-struct ItemEntry
-{
- uint32 ID;
- uint32 DisplayId;
- uint32 InventoryType;
- uint32 Sheath;
-};
-
-struct ItemDisplayInfoEntry
-{
- uint32 ID;
- uint32 randomPropertyChance;
-};
-
-//struct ItemCondExtCostsEntry
-//{
-// uint32 ID;
-// uint32 condExtendedCost; // ItemPrototype::CondExtendedCost
-// uint32 itemextendedcostentry; // ItemPrototype::ExtendedCost
-// uint32 arenaseason; // arena season number(1-4)
-//};
-
-struct ItemExtendedCostEntry
-{
- uint32 ID; // 0 extended-cost entry id
- uint32 reqhonorpoints; // 1 required honor points
- uint32 reqarenapoints; // 2 required arena points
- uint32 reqitem[5]; // 3-7 required item id
- uint32 reqitemcount[5]; // 8-12 required count of 1st item
- uint32 reqpersonalarenarating; // 13 required personal arena rating
-};
-
-struct ItemRandomPropertiesEntry
-{
- uint32 ID; // 0
- //char* internalName // 1 unused
- uint32 enchant_id[3]; // 2-4
- // 5-6 unused, 0 only values, reserved for additional enchantments?
- //char* nameSuffix[16] // 7-22, unused
- // 23 nameSufix flags, unused
-};
-
-struct ItemRandomSuffixEntry
-{
- uint32 ID; // 0
- //char* name[16] // 1-16 unused
- // 17, name flags, unused
- // 18 unused
- uint32 enchant_id[3]; // 19-21
- uint32 prefix[3]; // 22-24
-};
-
-struct ItemSetEntry
-{
- //uint32 id // 0 item set ID
- char* name[16]; // 1-16
- // 17 string flags, unused
- // 18-28 items from set, but not have all items listed, use ItemPrototype::ItemSet instead
- // 29-34 unused
- uint32 spells[8]; // 35-42
- uint32 items_to_triggerspell[8]; // 43-50
- uint32 required_skill_id; // 51
- uint32 required_skill_value; // 52
-};
-
-struct LockEntry
-{
- uint32 ID; // 0
- uint32 keytype[5]; // 1-5
- // 6-8, not used
- uint32 key[5]; // 9-13
- // 14-16, not used
- uint32 requiredminingskill; // 17
- uint32 requiredlockskill; // 18
- // 19-32, not used
-};
-
-struct MailTemplateEntry
-{
- uint32 ID; // 0
- //char* subject[16]; // 1-16
- // 17 name flags, unused
- //char* content[16]; // 18-33
-};
-
-struct MapEntry
-{
- uint32 MapID; // 0
- //char* internalname; // 1 unused
- uint32 map_type; // 2
- // 3 unused
- char* name[16]; // 4-19
- // 20 name flags, unused
- // 21-23 unused (something PvPZone related - levels?)
- // 24-26
- uint32 linked_zone; // 27 common zone for instance and continent map
- //char* hordeIntro // 28-43 text for PvP Zones
- // 44 intro text flags
- //char* allianceIntro // 45-60 text for PvP Zones
- // 46 intro text flags
- // 47-61 not used
- uint32 multimap_id; // 62
- // 63-65 not used
- //chat* unknownText1 // 66-81 unknown empty text fields, possible normal Intro text.
- // 82 text flags
- //chat* heroicIntroText // 83-98 heroic mode requirement text
- // 99 text flags
- //chat* unknownText2 // 100-115 unknown empty text fields
- // 116 text flags
- int32 entrance_map; // 117 map_id of entrance map
- float entrance_x; // 118 entrance x coordinate (if exist single entry)
- float entrance_y; // 119 entrance y coordinate (if exist single entry)
- uint32 resetTimeRaid; // 120
- uint32 resetTimeHeroic; // 121
- // 122-123
- uint32 addon; // 124 (0-original maps,1-tbc addon)
-
- // Helpers
- uint32 Expansion() const { return addon; }
-
-
- bool IsDungeon() const { return map_type == MAP_INSTANCE || map_type == MAP_RAID; }
- bool Instanceable() const { return map_type == MAP_INSTANCE || map_type == MAP_RAID || map_type == MAP_BATTLEGROUND || map_type == MAP_ARENA; }
- bool IsRaid() const { return map_type == MAP_RAID; }
- bool IsBattleGround() const { return map_type == MAP_BATTLEGROUND; }
- bool IsBattleArena() const { return map_type == MAP_ARENA; }
- bool IsBattleGroundOrArena() const { return map_type == MAP_BATTLEGROUND || map_type == MAP_ARENA; }
- bool SupportsHeroicMode() const { return resetTimeHeroic && !resetTimeRaid; }
- bool HasResetTime() const { return resetTimeHeroic || resetTimeRaid; }
-
- bool IsMountAllowed() const
- {
- return !IsDungeon() ||
- MapID==568 || MapID==309 || MapID==209 || MapID==534 ||
- MapID==560 || MapID==509 || MapID==269;
- }
-};
-
-struct QuestSortEntry
-{
- uint32 id; // 0, sort id
- //char* name[16]; // 1-16, unused
- // 17 name flags, unused
-};
-
-struct RandomPropertiesPointsEntry
-{
- //uint32 Id; // 0 hidden key
- uint32 itemLevel; // 1
- uint32 EpicPropertiesPoints[5]; // 2-6
- uint32 RarePropertiesPoints[5]; // 7-11
- uint32 UncommonPropertiesPoints[5]; // 12-16
-};
-
-//struct SkillLineCategoryEntry{
-// uint32 id; // 0 hidden key
-// char* name[16]; // 1 - 17 Category name
-// // 18 string flag
-// uint32 displayOrder; // Display order in character tab
-//};
-
-//struct SkillRaceClassInfoEntry{
-// uint32 id; // 0
-// uint32 skillId; // 1 present some refrences to unknown skill
-// uint32 raceMask; // 2
-// uint32 classMask; // 3
-// uint32 flags; // 4 mask for some thing
-// uint32 reqLevel; // 5
-// uint32 skillTierId; // 6
-// uint32 skillCostID; // 7
-//};
-
-//struct SkillTiersEntry{
-// uint32 id; // 0
-// uint32 skillValue[16]; // 1-17 unknown possibly add value on learn?
-// uint32 maxSkillValue[16]; // Max value for rank
-//};
-
-struct SkillLineEntry
-{
- uint32 id; // 0
- uint32 categoryId; // 1 (index from SkillLineCategory.dbc)
- //uint32 skillCostID; // 2 not used
- char* name[16]; // 3-18
- // 19 string flags, not used
- //char* description[16]; // 20-35, not used
- // 36 string flags, not used
- uint32 spellIcon; // 37
-};
-
-struct SkillLineAbilityEntry
-{
- uint32 id; // 0, INDEX
- uint32 skillId; // 1
- uint32 spellId; // 2
- uint32 racemask; // 3
- uint32 classmask; // 4
- //uint32 racemaskNot; // 5 always 0 in 2.4.2
- //uint32 classmaskNot; // 6 always 0 in 2.4.2
- uint32 req_skill_value; // 7 for trade skill.not for training.
- uint32 forward_spellid; // 8
- uint32 learnOnGetSkill; // 9 can be 1 or 2 for spells learned on get skill
- uint32 max_value; // 10
- uint32 min_value; // 11
- // 12-13, unknown, always 0
- uint32 reqtrainpoints; // 14
-};
-
-struct SoundEntriesEntry
-{
- uint32 Id; // 0, sound id
- //uint32 Type; // 1, sound type (10 generally for creature, etc)
- //char* InternalName; // 2, internal name, for use in lookup command for example
- //char* FileName[10]; // 3-12, file names
- //uint32 Unk13[10]; // 13-22, linked with file names?
- //char* Path; // 23
- // 24-28, unknown
-};
-
-struct SpellEntry
-{
- uint32 Id; // 0 normally counted from 0 field (but some tools start counting from 1, check this before tool use for data view!)
- uint32 Category; // 1
- //uint32 castUI // 2 not used
- uint32 Dispel; // 3
- uint32 Mechanic; // 4
- uint32 Attributes; // 5
- uint32 AttributesEx; // 6
- uint32 AttributesEx2; // 7
- uint32 AttributesEx3; // 8
- uint32 AttributesEx4; // 9
- uint32 AttributesEx5; // 10
- //uint32 AttributesEx6; // 11 not used
- uint32 Stances; // 12
- uint32 StancesNot; // 13
- uint32 Targets; // 14
- uint32 TargetCreatureType; // 15
- uint32 RequiresSpellFocus; // 16
- uint32 FacingCasterFlags; // 17
- uint32 CasterAuraState; // 18
- uint32 TargetAuraState; // 19
- uint32 CasterAuraStateNot; // 20
- uint32 TargetAuraStateNot; // 21
- uint32 CastingTimeIndex; // 22
- uint32 RecoveryTime; // 23
- uint32 CategoryRecoveryTime; // 24
- uint32 InterruptFlags; // 25
- uint32 AuraInterruptFlags; // 26
- uint32 ChannelInterruptFlags; // 27
- uint32 procFlags; // 28
- uint32 procChance; // 29
- uint32 procCharges; // 30
- uint32 maxLevel; // 31
- uint32 baseLevel; // 32
- uint32 spellLevel; // 33
- uint32 DurationIndex; // 34
- uint32 powerType; // 35
- uint32 manaCost; // 36
- uint32 manaCostPerlevel; // 37
- uint32 manaPerSecond; // 38
- uint32 manaPerSecondPerLevel; // 39
- uint32 rangeIndex; // 40
- float speed; // 41
- //uint32 modalNextSpell; // 42
- uint32 StackAmount; // 43
- uint32 Totem[2]; // 44-45
- int32 Reagent[8]; // 46-53
- uint32 ReagentCount[8]; // 54-61
- int32 EquippedItemClass; // 62 (value)
- int32 EquippedItemSubClassMask; // 63 (mask)
- int32 EquippedItemInventoryTypeMask; // 64 (mask)
- uint32 Effect[3]; // 65-67
- int32 EffectDieSides[3]; // 68-70
- int32 EffectBaseDice[3]; // 71-73
- float EffectDicePerLevel[3]; // 74-76
- float EffectRealPointsPerLevel[3]; // 77-79
- int32 EffectBasePoints[3]; // 80-82 (don't must be used in spell/auras explicitly, must be used cached Spell::m_currentBasePoints)
- uint32 EffectMechanic[3]; // 83-85
- uint32 EffectImplicitTargetA[3]; // 86-88
- uint32 EffectImplicitTargetB[3]; // 89-91
- uint32 EffectRadiusIndex[3]; // 92-94 - spellradius.dbc
- uint32 EffectApplyAuraName[3]; // 95-97
- uint32 EffectAmplitude[3]; // 98-100
- float EffectMultipleValue[3]; // 101-103
- uint32 EffectChainTarget[3]; // 104-106
- uint32 EffectItemType[3]; // 107-109
- int32 EffectMiscValue[3]; // 110-112
- int32 EffectMiscValueB[3]; // 113-115
- uint32 EffectTriggerSpell[3]; // 116-118
- float EffectPointsPerComboPoint[3]; // 119-121
- uint32 SpellVisual; // 122
- // 123 not used
- uint32 SpellIconID; // 124
- uint32 activeIconID; // 125
- //uint32 spellPriority; // 126
- char* SpellName[16]; // 127-142
- //uint32 SpellNameFlag; // 143
- char* Rank[16]; // 144-159
- //uint32 RankFlags; // 160
- //char* Description[16]; // 161-176 not used
- //uint32 DescriptionFlags; // 177 not used
- //char* ToolTip[16]; // 178-193 not used
- //uint32 ToolTipFlags; // 194 not used
- uint32 ManaCostPercentage; // 195
- uint32 StartRecoveryCategory; // 196
- uint32 StartRecoveryTime; // 197
- uint32 MaxTargetLevel; // 198
- uint32 SpellFamilyName; // 199
- uint64 SpellFamilyFlags; // 200+201
- uint32 MaxAffectedTargets; // 202
- uint32 DmgClass; // 203 defenseType
- uint32 PreventionType; // 204
- //uint32 StanceBarOrder; // 205 not used
- float DmgMultiplier[3]; // 206-208
- //uint32 MinFactionId; // 209 not used, and 0 in 2.4.2
- //uint32 MinReputation; // 210 not used, and 0 in 2.4.2
- //uint32 RequiredAuraVision; // 211 not used
- uint32 TotemCategory[2]; // 212-213
- uint32 AreaId; // 214
- uint32 SchoolMask; // 215 school mask
-
- private:
- // prevent creating custom entries (copy data from original in fact)
- SpellEntry(SpellEntry const&); // DON'T must have implementation
-};
-
-typedef std::set<uint32> SpellCategorySet;
-typedef std::map<uint32,SpellCategorySet > SpellCategoryStore;
-typedef std::set<uint32> PetFamilySpellsSet;
-typedef std::map<uint32,PetFamilySpellsSet > PetFamilySpellsStore;
-
-struct SpellCastTimesEntry
-{
- uint32 ID; // 0
- int32 CastTime; // 1
- //float CastTimePerLevel; // 2 unsure / per skill?
- //int32 MinCastTime; // 3 unsure
-};
-
-struct SpellFocusObjectEntry
-{
- uint32 ID; // 0
- //char* Name[16]; // 1-15 unused
- // 16 string flags, unused
-};
-
-// stored in SQL table
-struct SpellThreatEntry
-{
- uint32 spellId;
- int32 threat;
-};
-
-struct SpellRadiusEntry
-{
- uint32 ID;
- float Radius;
- float Radius2;
-};
-
-struct SpellRangeEntry
-{
- uint32 ID;
- float minRange;
- float maxRange;
- uint32 type;
-};
-
-struct SpellShapeshiftEntry
-{
- uint32 ID; // 0
- //uint32 buttonPosition; // 1 unused
- //char* Name[16]; // 2-17 unused
- //uint32 NameFlags; // 18 unused
- uint32 flags1; // 19
- int32 creatureType; // 20 <=0 humanoid, other normal creature types
- //uint32 unk1; // 21 unused
- uint32 attackSpeed; // 22
- //uint32 modelID; // 23 unused, alliance modelid (where horde case?)
- //uint32 unk2; // 24 unused
- //uint32 unk3; // 25 unused
- //uint32 unk4; // 26 unused
- //uint32 unk5; // 27 unused
- //uint32 unk6; // 28 unused
- //uint32 unk7; // 29 unused
- //uint32 unk8; // 30 unused
- //uint32 unk9; // 31 unused
- //uint32 unk10; // 32 unused
- //uint32 unk11; // 33 unused
- //uint32 unk12; // 34 unused
-};
-
-struct SpellDurationEntry
-{
- uint32 ID;
- int32 Duration[3];
-};
-
-struct SpellItemEnchantmentEntry
-{
- uint32 ID; // 0
- uint32 type[3]; // 1-3
- uint32 amount[3]; // 4-6
- //uint32 amount2[3] // 7-9 always same as similar `amount` value
- uint32 spellid[3]; // 10-12
- char* description[16]; // 13-29
- // 30 description flags
- uint32 aura_id; // 31
- uint32 slot; // 32
- uint32 GemID; // 33
- uint32 EnchantmentCondition; // 34
-};
-
-struct SpellItemEnchantmentConditionEntry
-{
- uint32 ID;
- uint8 Color[5];
- uint8 Comparator[5];
- uint8 CompareColor[5];
- uint32 Value[5];
-};
-
-struct StableSlotPricesEntry
-{
- uint32 Slot;
- uint32 Price;
-};
-
-struct TalentEntry
-{
- uint32 TalentID; // 0
- uint32 TalentTab; // 1 index in TalentTab.dbc (TalentTabEntry)
- uint32 Row; // 2
- uint32 Col; // 3
- uint32 RankID[5]; // 4-8
- // 9-12 not used, always 0, maybe not used high ranks
- uint32 DependsOn; // 13 index in Talent.dbc (TalentEntry)
- // 14-15 not used
- uint32 DependsOnRank; // 16
- // 17-19 not used
- uint32 DependsOnSpell; // 20 req.spell
-};
-
-struct TalentTabEntry
-{
- uint32 TalentTabID; // 0
- //char* name[16]; // 1-16, unused
- //uint32 nameFlags; // 17, unused
- //unit32 spellicon; // 18
- // 19 not used
- uint32 ClassMask; // 20
- uint32 tabpage; // 21
- //char* internalname; // 22
-};
-
-struct TaxiNodesEntry
-{
- uint32 ID; // 0
- uint32 map_id; // 1
- float x; // 2
- float y; // 3
- float z; // 4
- //char* name[16]; // 5-21
- // 22 string flags, unused
- uint32 horde_mount_type; // 23
- uint32 alliance_mount_type; // 24
-};
-
-struct TaxiPathEntry
-{
- uint32 ID;
- uint32 from;
- uint32 to;
- uint32 price;
-};
-
-struct TaxiPathNodeEntry
-{
- uint32 path;
- uint32 index;
- uint32 mapid;
- float x;
- float y;
- float z;
- uint32 actionFlag;
- uint32 delay;
-};
-
-struct TotemCategoryEntry
-{
- uint32 ID; // 0
- //char* name[16]; // 1-16
- // 17 string flags, unused
- uint32 categoryType; // 18 (one for specialization)
- uint32 categoryMask; // 19 (compatibility mask for same type: different for totems, compatible from high to low for rods)
-};
-
-struct WorldMapAreaEntry
-{
- //uint32 ID; // 0
- uint32 map_id; // 1
- uint32 area_id; // 2 index (continent 0 areas ignored)
- //char* internal_name // 3
- float y1; // 4
- float y2; // 5
- float x1; // 6
- float x2; // 7
- int32 virtual_map_id; // 8 -1 (map_id have correct map) other: virtual map where zone show (map_id - where zone in fact internally)
-};
-
-struct WorldSafeLocsEntry
-{
- uint32 ID; // 0
- uint32 map_id; // 1
- float x; // 2
- float y; // 3
- float z; // 4
- //char* name[16] // 5-20 name, unused
- // 21 name flags, unused
-};
-
-// GCC have alternative #pragma pack() syntax and old gcc version not support pack(pop), also any gcc version not support it at some platform
-#if defined( __GNUC__ )
-#pragma pack()
-#else
-#pragma pack(pop)
-#endif
-
-// Structures not used for casting to loaded DBC data and not required then packing
-struct TalentSpellPos
-{
- TalentSpellPos() : talent_id(0), rank(0) {}
- TalentSpellPos(uint16 _talent_id, uint8 _rank) : talent_id(_talent_id), rank(_rank) {}
-
- uint16 talent_id;
- uint8 rank;
-};
-
-typedef std::map<uint32,TalentSpellPos> TalentSpellPosMap;
-
-struct TaxiPathBySourceAndDestination
-{
- TaxiPathBySourceAndDestination() : ID(0),price(0) {}
- TaxiPathBySourceAndDestination(uint32 _id,uint32 _price) : ID(_id),price(_price) {}
-
- uint32 ID;
- uint32 price;
-};
-typedef std::map<uint32,TaxiPathBySourceAndDestination> TaxiPathSetForSource;
-typedef std::map<uint32,TaxiPathSetForSource> TaxiPathSetBySource;
-
-struct TaxiPathNode
-{
- TaxiPathNode() : mapid(0), x(0),y(0),z(0),actionFlag(0),delay(0) {}
- TaxiPathNode(uint32 _mapid, float _x, float _y, float _z, uint32 _actionFlag, uint32 _delay) : mapid(_mapid), x(_x),y(_y),z(_z),actionFlag(_actionFlag),delay(_delay) {}
-
- uint32 mapid;
- float x;
- float y;
- float z;
- uint32 actionFlag;
- uint32 delay;
-};
-typedef std::vector<TaxiPathNode> TaxiPathNodeList;
-typedef std::vector<TaxiPathNodeList> TaxiPathNodesByPath;
-
-#define TaxiMaskSize 16
-typedef uint32 TaxiMask[TaxiMaskSize];
-#endif
-
diff --git a/src/shared/Database/DBCfmt.cpp b/src/shared/Database/DBCfmt.cpp
deleted file mode 100644
index 14cf6486933..00000000000
--- a/src/shared/Database/DBCfmt.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
- *
- * Copyright (C) 2008 Trinity <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, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-const char AreaTableEntryfmt[]="iiinixxxxxissssssssssssssssxixxxxxx";
-const char AuctionHouseEntryfmt[]="niiixxxxxxxxxxxxxxxxx";
-const char AreaTriggerEntryfmt[]="niffffffff";
-const char BankBagSlotPricesEntryfmt[]="ni";
-const char BattlemasterListEntryfmt[]="niiixxxxxiiiixxssssssssssssssssxx";
-const char CharStartOutfitEntryfmt[]="diiiiiiiiiiiiixxxxxxxxxxxxxxxxxxxxxxxxxxx";
-// 3*12 new item fields in 3.0.x
-//const char CharStartOutfitEntryfmt[]="diiiiiiiiiiiiiiiiiiiiiiiiixxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
-const char CharTitlesEntryfmt[]="nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxi";
-const char ChatChannelsEntryfmt[]="iixssssssssssssssssxxxxxxxxxxxxxxxxxx";
- // ChatChannelsEntryfmt, index not used (more compact store)
-//const char ChrClassesEntryfmt[]="nxixxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxix";
-const char ChrClassesEntryfmt[]="nxixssssssssssssssssxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxix";
-const char ChrRacesEntryfmt[]="nxixiixxixxxxissssssssssssssssxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxi";
-const char CreatureDisplayInfofmt[]="nxxxfxxxxxxxxx";
-const char CreatureFamilyfmt[]="nfifiiiissssssssssssssssxx";
-const char CreatureSpellDatafmt[]="nxxxxxxxx";
-const char DurabilityCostsfmt[]="niiiiiiiiiiiiiiiiiiiiiiiiiiiii";
-const char DurabilityQualityfmt[]="nf";
-const char EmoteEntryfmt[]="nxixxxxxxxxxxxxxxxx";
-const char FactionEntryfmt[]="niiiiiiiiiiiiiiiiiissssssssssssssssxxxxxxxxxxxxxxxxxx";
-const char FactionTemplateEntryfmt[]="niiiiiiiiiiiii";
-const char GemPropertiesEntryfmt[]="nixxi";
-const char GtCombatRatingsfmt[]="f";
-const char GtChanceToMeleeCritBasefmt[]="f";
-const char GtChanceToMeleeCritfmt[]="f";
-const char GtChanceToSpellCritBasefmt[]="f";
-const char GtChanceToSpellCritfmt[]="f";
-const char GtOCTRegenHPfmt[]="f";
-//const char GtOCTRegenMPfmt[]="f";
-const char GtRegenHPPerSptfmt[]="f";
-const char GtRegenMPPerSptfmt[]="f";
-const char Itemfmt[]="niii";
-//const char ItemDisplayTemplateEntryfmt[]="nxxxxxxxxxxixxxxxxxxxxx";
-//const char ItemCondExtCostsEntryfmt[]="xiii";
-const char ItemExtendedCostEntryfmt[]="niiiiiiiiiiiii";
-const char ItemRandomPropertiesfmt[]="nxiiixxxxxxxxxxxxxxxxxxx";
-const char ItemRandomSuffixfmt[]="nxxxxxxxxxxxxxxxxxxiiiiii";
-const char ItemSetEntryfmt[]="dssssssssssssssssxxxxxxxxxxxxxxxxxxiiiiiiiiiiiiiiiiii";
-const char LockEntryfmt[]="niiiiixxxiiiiixxxiixxxxxxxxxxxxxx";
-const char MailTemplateEntryfmt[]="nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
-const char MapEntryfmt[]="nxixssssssssssssssssxxxxxxxixxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxixxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxiffiixxi";
-const char QuestSortEntryfmt[]="nxxxxxxxxxxxxxxxxx";
-const char RandomPropertiesPointsfmt[]="niiiiiiiiiiiiiii";
-const char SkillLinefmt[]="nixssssssssssssssssxxxxxxxxxxxxxxxxxxi";
-const char SkillLineAbilityfmt[]="niiiixxiiiiixxi";
-const char SoundEntriesfmt[]="nxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
-const char SpellCastTimefmt[]="nixx";
-const char SpellDurationfmt[]="niii";
-const char SpellEntryfmt[]="nixiiiiiiiixiiiiiiiiiiiiiiiiiiiiiiiiiiiiifxiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiffffffiiiiiiiiiiiiiiiiiiiiifffiiiiiiiiiiiiiiifffixiixssssssssssssssssxssssssssssssssssxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxiiiiiiiiiixfffxxxiiii";
-const char SpellFocusObjectfmt[]="nxxxxxxxxxxxxxxxxx";
-const char SpellItemEnchantmentfmt[]="niiiiiixxxiiissssssssssssssssxiiii";
-const char SpellItemEnchantmentConditionfmt[]="nbbbbbxxxxxbbbbbbbbbbiiiiiXXXXX";
-const char SpellRadiusfmt[]="nfxf";
-const char SpellRangefmt[]="nffixxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
-const char SpellShapeshiftfmt[]="nxxxxxxxxxxxxxxxxxxiixixxxxxxxxxxxx";
-const char StableSlotPricesfmt[] = "ni";
-const char TalentEntryfmt[]="niiiiiiiixxxxixxixxxi";
-const char TalentTabEntryfmt[]="nxxxxxxxxxxxxxxxxxxxiix";
-const char TaxiNodesEntryfmt[]="nifffxxxxxxxxxxxxxxxxxii";
-const char TaxiPathEntryfmt[]="niii";
-const char TaxiPathNodeEntryfmt[]="diiifffiixx";
-const char TotemCategoryEntryfmt[]="nxxxxxxxxxxxxxxxxxii";
-const char WorldMapAreaEntryfmt[]="xinxffffi";
-const char WorldSafeLocsEntryfmt[]="nifffxxxxxxxxxxxxxxxxx";
-
diff --git a/src/shared/Database/Database.cpp b/src/shared/Database/Database.cpp
index 7110fe44c54..651ea7f41fb 100644
--- a/src/shared/Database/Database.cpp
+++ b/src/shared/Database/Database.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -110,7 +110,8 @@ bool Database::PExecuteLog(const char * format,...)
void Database::SetResultQueue(SqlResultQueue * queue)
{
- m_queryQueues[ZThread::ThreadImpl::current()] = queue;
+ m_queryQueues[ACE_Based::Thread::current()] = queue;
+
}
QueryResult* Database::PQuery(const char *format,...)
@@ -132,6 +133,25 @@ QueryResult* Database::PQuery(const char *format,...)
return Query(szQuery);
}
+QueryNamedResult* Database::PQueryNamed(const char *format,...)
+{
+ if(!format) return NULL;
+
+ va_list ap;
+ char szQuery [MAX_QUERY_LEN];
+ va_start(ap, format);
+ int res = vsnprintf( szQuery, MAX_QUERY_LEN, format, ap );
+ va_end(ap);
+
+ if(res==-1)
+ {
+ sLog.outError("SQL Query truncated (and not execute) for format: %s",format);
+ return false;
+ }
+
+ return QueryNamed(szQuery);
+}
+
bool Database::PExecute(const char * format,...)
{
if (!format)
diff --git a/src/shared/Database/Database.h b/src/shared/Database/Database.h
index c2ee9349979..7f2bdaefdb7 100644
--- a/src/shared/Database/Database.h
+++ b/src/shared/Database/Database.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -21,8 +21,7 @@
#ifndef DATABASE_H
#define DATABASE_H
-#include "zthread/Thread.h"
-#include "../src/zthread/ThreadImpl.h"
+#include "Threading.h"
#include "Utilities/UnorderedMap.h"
#include "Database/SqlDelayThread.h"
@@ -30,10 +29,10 @@ class SqlTransaction;
class SqlResultQueue;
class SqlQueryHolder;
-typedef UNORDERED_MAP<ZThread::ThreadImpl*, SqlTransaction*> TransactionQueues;
-typedef UNORDERED_MAP<ZThread::ThreadImpl*, SqlResultQueue*> QueryQueues;
+typedef UNORDERED_MAP<ACE_Based::Thread* , SqlTransaction*> TransactionQueues;
+typedef UNORDERED_MAP<ACE_Based::Thread* , SqlResultQueue*> QueryQueues;
-#define MAX_QUERY_LEN 1024
+#define MAX_QUERY_LEN 32*1024
class TRINITY_DLL_SPEC Database
{
@@ -43,7 +42,7 @@ class TRINITY_DLL_SPEC Database
TransactionQueues m_tranQueues; ///< Transaction queues from diff. threads
QueryQueues m_queryQueues; ///< Query queues from diff threads
SqlDelayThread* m_threadBody; ///< Pointer to delay sql executer
- ZThread::Thread* m_delayThread; ///< Pointer to executer thread
+ ACE_Based::Thread* m_delayThread; ///< Pointer to executer thread
public:
@@ -55,6 +54,8 @@ class TRINITY_DLL_SPEC Database
virtual QueryResult* Query(const char *sql) = 0;
QueryResult* PQuery(const char *format,...) ATTR_PRINTF(2,3);
+ virtual QueryNamedResult* QueryNamed(const char *sql) = 0;
+ QueryNamedResult* PQueryNamed(const char *format,...) ATTR_PRINTF(2,3);
/// Async queries and query holders, implemented in DatabaseImpl.h
@@ -80,16 +81,16 @@ class TRINITY_DLL_SPEC Database
template<class Class, typename ParamType1>
bool AsyncPQuery(Class *object, void (Class::*method)(QueryResult*, ParamType1), ParamType1 param1, const char *format,...) ATTR_PRINTF(5,6);
template<class Class, typename ParamType1, typename ParamType2>
- bool AsyncPQuery(Class *object, void (Class::*method)(QueryResult*, ParamType1, ParamType2), ParamType1 param1, ParamType2 param2, const char *format,...) ATTR_PRINTF(5,6);
+ bool AsyncPQuery(Class *object, void (Class::*method)(QueryResult*, ParamType1, ParamType2), ParamType1 param1, ParamType2 param2, const char *format,...) ATTR_PRINTF(6,7);
template<class Class, typename ParamType1, typename ParamType2, typename ParamType3>
- bool AsyncPQuery(Class *object, void (Class::*method)(QueryResult*, ParamType1, ParamType2, ParamType3), ParamType1 param1, ParamType2 param2, ParamType3 param3, const char *format,...) ATTR_PRINTF(5,6);
+ bool AsyncPQuery(Class *object, void (Class::*method)(QueryResult*, ParamType1, ParamType2, ParamType3), ParamType1 param1, ParamType2 param2, ParamType3 param3, const char *format,...) ATTR_PRINTF(7,8);
// PQuery / static
template<typename ParamType1>
- bool AsyncPQuery(void (*method)(QueryResult*, ParamType1), ParamType1 param1, const char *format,...) ATTR_PRINTF(5,6);
+ bool AsyncPQuery(void (*method)(QueryResult*, ParamType1), ParamType1 param1, const char *format,...) ATTR_PRINTF(4,5);
template<typename ParamType1, typename ParamType2>
bool AsyncPQuery(void (*method)(QueryResult*, ParamType1, ParamType2), ParamType1 param1, ParamType2 param2, const char *format,...) ATTR_PRINTF(5,6);
template<typename ParamType1, typename ParamType2, typename ParamType3>
- bool AsyncPQuery(void (*method)(QueryResult*, ParamType1, ParamType2, ParamType3), ParamType1 param1, ParamType2 param2, ParamType3 param3, const char *format,...) ATTR_PRINTF(5,6);
+ bool AsyncPQuery(void (*method)(QueryResult*, ParamType1, ParamType2, ParamType3), ParamType1 param1, ParamType2 param2, ParamType3 param3, const char *format,...) ATTR_PRINTF(6,7);
template<class Class>
// QueryHolder
bool DelayQueryHolder(Class *object, void (Class::*method)(QueryResult*, SqlQueryHolder*), SqlQueryHolder *holder);
diff --git a/src/shared/Database/DatabaseEnv.h b/src/shared/Database/DatabaseEnv.h
index 664459473af..1d3d735881c 100644
--- a/src/shared/Database/DatabaseEnv.h
+++ b/src/shared/Database/DatabaseEnv.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -25,7 +25,6 @@
#include "Log.h"
#include "Errors.h"
-#include "Database/DBCStores.h"
#include "Database/Field.h"
#include "Database/QueryResult.h"
@@ -40,10 +39,8 @@ typedef DatabasePostgre DatabaseType;
#define _OFFSET_ "LIMIT 1 OFFSET %d"
#else
#include "Database/QueryResultMysql.h"
-#include "Database/QueryResultSqlite.h"
#include "Database/Database.h"
#include "Database/DatabaseMysql.h"
-#include "Database/DatabaseSqlite.h"
typedef DatabaseMysql DatabaseType;
#define _LIKE_ "LIKE"
#define _TABLE_SIM_ "`"
diff --git a/src/shared/Database/DatabaseImpl.h b/src/shared/Database/DatabaseImpl.h
index 5ab4ec04a65..7cbd0ed8ba5 100644
--- a/src/shared/Database/DatabaseImpl.h
+++ b/src/shared/Database/DatabaseImpl.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -29,7 +29,7 @@
QueryQueues::iterator queue_itr; \
\
{ \
- ZThread::ThreadImpl * queryThread = ZThread::ThreadImpl::current(); \
+ ACE_Based::Thread * queryThread = ACE_Based::Thread::current(); \
queue_itr = m_queryQueues.find(queryThread); \
if (queue_itr == m_queryQueues.end()) return false; \
}
@@ -59,7 +59,7 @@
QueryQueues::iterator queue_itr; \
\
{ \
- ZThread::ThreadImpl * queryThread = ZThread::ThreadImpl::current(); \
+ ACE_Based::Thread * queryThread = ACE_Based::Thread::current(); \
queue_itr = m_queryQueues.find(queryThread); \
if (queue_itr == m_queryQueues.end()) return false; \
}
diff --git a/src/shared/Database/DatabaseMysql.cpp b/src/shared/Database/DatabaseMysql.cpp
index 77a59a69c57..0189b5883f7 100644
--- a/src/shared/Database/DatabaseMysql.cpp
+++ b/src/shared/Database/DatabaseMysql.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -23,7 +23,7 @@
#include "Util.h"
#include "Policies/SingletonImp.h"
#include "Platform/Define.h"
-#include "../src/zthread/ThreadImpl.h"
+#include "Threading.h"
#include "DatabaseEnv.h"
#include "Database/MySQLDelayThread.h"
#include "Database/SqlOperations.h"
@@ -192,26 +192,22 @@ bool DatabaseMysql::Initialize(const char *infoString)
}
}
-QueryResult* DatabaseMysql::Query(const char *sql)
+bool DatabaseMysql::_Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount)
{
if (!mMysql)
return 0;
- MYSQL_RES *result = 0;
- uint64 rowCount = 0;
- uint32 fieldCount = 0;
-
{
// guarded block for thread-safe mySQL request
- ZThread::Guard<ZThread::FastMutex> query_connection_guard(mMutex);
- #ifdef TRINITY_DEBUG
+ ACE_Guard<ACE_Thread_Mutex> query_connection_guard(mMutex);
+ #ifdef MANGOS_DEBUG
uint32 _s = getMSTime();
#endif
if(mysql_query(mMysql, sql))
{
sLog.outErrorDb( "SQL: %s", sql );
sLog.outErrorDb("query ERROR: %s", mysql_error(mMysql));
- return NULL;
+ return false;
}
else
{
@@ -220,29 +216,63 @@ QueryResult* DatabaseMysql::Query(const char *sql)
#endif
}
- result = mysql_store_result(mMysql);
-
- rowCount = mysql_affected_rows(mMysql);
- fieldCount = mysql_field_count(mMysql);
+ *pResult = mysql_store_result(mMysql);
+ *pRowCount = mysql_affected_rows(mMysql);
+ *pFieldCount = mysql_field_count(mMysql);
// end guarded block
}
- if (!result )
- return NULL;
+ if (!*pResult )
+ return false;
- if (!rowCount)
+ if (!*pRowCount)
{
- mysql_free_result(result);
- return NULL;
+ mysql_free_result(*pResult);
+ return false;
}
- QueryResultMysql *queryResult = new QueryResultMysql(result, rowCount, fieldCount);
+ *pFields = mysql_fetch_fields(*pResult);
+ return true;
+}
+
+QueryResult* DatabaseMysql::Query(const char *sql)
+{
+ MYSQL_RES *result = NULL;
+ MYSQL_FIELD *fields = NULL;
+ uint64 rowCount = 0;
+ uint32 fieldCount = 0;
+
+ if(!_Query(sql,&result,&fields,&rowCount,&fieldCount))
+ return NULL;
+
+ QueryResultMysql *queryResult = new QueryResultMysql(result, fields, rowCount, fieldCount);
queryResult->NextRow();
return queryResult;
}
+QueryNamedResult* DatabaseMysql::QueryNamed(const char *sql)
+{
+ MYSQL_RES *result = NULL;
+ MYSQL_FIELD *fields = NULL;
+ uint64 rowCount = 0;
+ uint32 fieldCount = 0;
+
+ if(!_Query(sql,&result,&fields,&rowCount,&fieldCount))
+ return NULL;
+
+ QueryFieldNames names(fieldCount);
+ for (uint32 i = 0; i < fieldCount; i++)
+ names[i] = fields[i].name;
+
+ QueryResultMysql *queryResult = new QueryResultMysql(result, fields, rowCount, fieldCount);
+
+ queryResult->NextRow();
+
+ return new QueryNamedResult(queryResult,names);
+}
+
bool DatabaseMysql::Execute(const char *sql)
{
if (!mMysql)
@@ -251,7 +281,7 @@ bool DatabaseMysql::Execute(const char *sql)
// don't use queued execution if it has not been initialized
if (!m_threadBody) return DirectExecute(sql);
- tranThread = ZThread::ThreadImpl::current(); // owner of this transaction
+ tranThread = ACE_Based::Thread::current(); // owner of this transaction
TransactionQueues::iterator i = m_tranQueues.find(tranThread);
if (i != m_tranQueues.end() && i->second != NULL)
{ // Statement for transaction
@@ -273,8 +303,9 @@ bool DatabaseMysql::DirectExecute(const char* sql)
{
// guarded block for thread-safe mySQL request
- ZThread::Guard<ZThread::FastMutex> query_connection_guard(mMutex);
- #ifdef TRINITY_DEBUG
+ ACE_Guard<ACE_Thread_Mutex> query_connection_guard(mMutex);
+
+ #ifdef MANGOS_DEBUG
uint32 _s = getMSTime();
#endif
if(mysql_query(mMysql, sql))
@@ -318,8 +349,9 @@ bool DatabaseMysql::BeginTransaction()
// don't use queued execution if it has not been initialized
if (!m_threadBody)
{
- if (tranThread==ZThread::ThreadImpl::current())
+ if (tranThread == ACE_Based::Thread::current())
return false; // huh? this thread already started transaction
+
mMutex.acquire();
if (!_TransactionCmd("START TRANSACTION"))
{
@@ -329,7 +361,7 @@ bool DatabaseMysql::BeginTransaction()
return true; // transaction started
}
- tranThread = ZThread::ThreadImpl::current(); // owner of this transaction
+ tranThread = ACE_Based::Thread::current(); // owner of this transaction
TransactionQueues::iterator i = m_tranQueues.find(tranThread);
if (i != m_tranQueues.end() && i->second != NULL)
// If for thread exists queue and also contains transaction
@@ -349,7 +381,7 @@ bool DatabaseMysql::CommitTransaction()
// don't use queued execution if it has not been initialized
if (!m_threadBody)
{
- if (tranThread!=ZThread::ThreadImpl::current())
+ if (tranThread != ACE_Based::Thread::current())
return false;
bool _res = _TransactionCmd("COMMIT");
tranThread = NULL;
@@ -357,7 +389,7 @@ bool DatabaseMysql::CommitTransaction()
return _res;
}
- tranThread = ZThread::ThreadImpl::current();
+ tranThread = ACE_Based::Thread::current();
TransactionQueues::iterator i = m_tranQueues.find(tranThread);
if (i != m_tranQueues.end() && i->second != NULL)
{
@@ -377,7 +409,7 @@ bool DatabaseMysql::RollbackTransaction()
// don't use queued execution if it has not been initialized
if (!m_threadBody)
{
- if (tranThread!=ZThread::ThreadImpl::current())
+ if (tranThread != ACE_Based::Thread::current())
return false;
bool _res = _TransactionCmd("ROLLBACK");
tranThread = NULL;
@@ -385,7 +417,7 @@ bool DatabaseMysql::RollbackTransaction()
return _res;
}
- tranThread = ZThread::ThreadImpl::current();
+ tranThread = ACE_Based::Thread::current();
TransactionQueues::iterator i = m_tranQueues.find(tranThread);
if (i != m_tranQueues.end() && i->second != NULL)
{
@@ -408,7 +440,8 @@ void DatabaseMysql::InitDelayThread()
assert(!m_delayThread);
//New delay thread for delay execute
- m_delayThread = new ZThread::Thread(m_threadBody = new MySQLDelayThread(this));
+ m_threadBody = new MySQLDelayThread(this);
+ m_delayThread = new ACE_Based::Thread(*m_threadBody);
}
void DatabaseMysql::HaltDelayThread()
diff --git a/src/shared/Database/DatabaseMysql.h b/src/shared/Database/DatabaseMysql.h
index 1826a08f2aa..4612ebfc462 100644
--- a/src/shared/Database/DatabaseMysql.h
+++ b/src/shared/Database/DatabaseMysql.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -25,7 +25,8 @@
#include "Database.h"
#include "Policies/Singleton.h"
-#include "zthread/FastMutex.h"
+#include "ace/Thread_Mutex.h"
+#include "ace/Guard_T.h"
#ifdef WIN32
#define FD_SETSIZE 1024
@@ -49,6 +50,7 @@ class TRINITY_DLL_SPEC DatabaseMysql : public Database
void InitDelayThread();
void HaltDelayThread();
QueryResult* Query(const char *sql);
+ QueryNamedResult* QueryNamed(const char *sql);
bool Execute(const char *sql);
bool DirectExecute(const char* sql);
bool BeginTransaction();
@@ -65,15 +67,16 @@ class TRINITY_DLL_SPEC DatabaseMysql : public Database
// must be call before finish thread run
void ThreadEnd();
private:
- ZThread::FastMutex mMutex;
+ ACE_Thread_Mutex mMutex;
- ZThread::ThreadImpl* tranThread;
+ ACE_Based::Thread * tranThread;
MYSQL *mMysql;
static size_t db_count;
bool _TransactionCmd(const char *sql);
+ bool _Query(const char *sql, MYSQL_RES **pResult, MYSQL_FIELD **pFields, uint64* pRowCount, uint32* pFieldCount);
};
#endif
#endif
diff --git a/src/shared/Database/DatabasePostgre.cpp b/src/shared/Database/DatabasePostgre.cpp
index 25b5a58b863..c70067dfdba 100644
--- a/src/shared/Database/DatabasePostgre.cpp
+++ b/src/shared/Database/DatabasePostgre.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -23,7 +23,7 @@
#include "Util.h"
#include "Policies/SingletonImp.h"
#include "Platform/Define.h"
-#include "../src/zthread/ThreadImpl.h"
+#include "Threading.h"
#include "DatabaseEnv.h"
#include "Database/PGSQLDelayThread.h"
#include "Database/SqlOperations.h"
@@ -79,14 +79,14 @@ bool DatabasePostgre::Initialize(const char *infoString)
Tokens::iterator iter;
- std::string host, port_or_socket, user, password, database;
+ std::string host, port_or_socket_dir, user, password, database;
iter = tokens.begin();
if(iter != tokens.end())
host = *iter++;
if(iter != tokens.end())
- port_or_socket = *iter++;
+ port_or_socket_dir = *iter++;
if(iter != tokens.end())
user = *iter++;
if(iter != tokens.end())
@@ -94,7 +94,10 @@ bool DatabasePostgre::Initialize(const char *infoString)
if(iter != tokens.end())
database = *iter++;
- mPGconn = PQsetdbLogin(host.c_str(), port_or_socket.c_str(), NULL, NULL, database.c_str(), user.c_str(), password.c_str());
+ if (host == ".")
+ mPGconn = PQsetdbLogin(NULL, port_or_socket_dir == "." ? NULL : port_or_socket_dir.c_str(), NULL, NULL, database.c_str(), user.c_str(), password.c_str());
+ else
+ mPGconn = PQsetdbLogin(host.c_str(), port_or_socket_dir.c_str(), NULL, NULL, database.c_str(), user.c_str(), password.c_str());
/* check to see that the backend connection was successfully made */
if (PQstatus(mPGconn) != CONNECTION_OK)
@@ -114,32 +117,27 @@ bool DatabasePostgre::Initialize(const char *infoString)
}
-QueryResult* DatabasePostgre::Query(const char *sql)
+bool DatabasePostgre::_Query(const char *sql, PGresult** pResult, uint64* pRowCount, uint32* pFieldCount)
{
if (!mPGconn)
return 0;
- uint64 rowCount = 0;
- uint32 fieldCount = 0;
-
// guarded block for thread-safe request
- ZThread::Guard<ZThread::FastMutex> query_connection_guard(mMutex);
- #ifdef TRINITY_DEBUG
+ ACE_Guard<ACE_Thread_Mutex> query_connection_guard(mMutex);
+ #ifdef MANGOS_DEBUG
uint32 _s = getMSTime();
#endif
// Send the query
- PGresult * result = PQexec(mPGconn, sql);
- if (!result )
- {
- return NULL;
- }
+ *pResult = PQexec(mPGconn, sql);
+ if(!*pResult )
+ return false;
- if (PQresultStatus(result) != PGRES_TUPLES_OK)
+ if (PQresultStatus(*pResult) != PGRES_TUPLES_OK)
{
sLog.outErrorDb( "SQL : %s", sql );
sLog.outErrorDb( "SQL %s", PQerrorMessage(mPGconn));
- PQclear(result);
- return NULL;
+ PQclear(*pResult);
+ return false;
}
else
{
@@ -148,15 +146,29 @@ QueryResult* DatabasePostgre::Query(const char *sql)
#endif
}
- rowCount = PQntuples(result);
- fieldCount = PQnfields(result);
+ *pRowCount = PQntuples(*pResult);
+ *pFieldCount = PQnfields(*pResult);
// end guarded block
- if (!rowCount)
+ if (!*pRowCount)
{
- PQclear(result);
- return NULL;
+ PQclear(*pResult);
+ return false;
}
+ return true;
+}
+
+QueryResult* DatabasePostgre::Query(const char *sql)
+{
+ if (!mPGconn)
+ return 0;
+
+ PGresult* result = NULL;
+ uint64 rowCount = 0;
+ uint32 fieldCount = 0;
+
+ if(!_Query(sql,&result,&rowCount,&fieldCount))
+ return NULL;
QueryResultPostgre * queryResult = new QueryResultPostgre(result, rowCount, fieldCount);
queryResult->NextRow();
@@ -164,6 +176,28 @@ QueryResult* DatabasePostgre::Query(const char *sql)
return queryResult;
}
+QueryNamedResult* DatabasePostgre::QueryNamed(const char *sql)
+{
+ if (!mPGconn)
+ return 0;
+
+ PGresult* result = NULL;
+ uint64 rowCount = 0;
+ uint32 fieldCount = 0;
+
+ if(!_Query(sql,&result,&rowCount,&fieldCount))
+ return NULL;
+
+ QueryFieldNames names(fieldCount);
+ for (uint32 i = 0; i < fieldCount; i++)
+ names[i] = PQfname(result, i);
+
+ QueryResultPostgre * queryResult = new QueryResultPostgre(result, rowCount, fieldCount);
+ queryResult->NextRow();
+
+ return new QueryNamedResult(queryResult,names);
+}
+
bool DatabasePostgre::Execute(const char *sql)
{
@@ -171,9 +205,10 @@ bool DatabasePostgre::Execute(const char *sql)
return false;
// don't use queued execution if it has not been initialized
- if (!m_threadBody) return DirectExecute(sql);
+ if (!m_threadBody)
+ return DirectExecute(sql);
- tranThread = ZThread::ThreadImpl::current(); // owner of this transaction
+ tranThread = ACE_Based::Thread::current(); // owner of this transaction
TransactionQueues::iterator i = m_tranQueues.find(tranThread);
if (i != m_tranQueues.end() && i->second != NULL)
{ // Statement for transaction
@@ -194,8 +229,8 @@ bool DatabasePostgre::DirectExecute(const char* sql)
return false;
{
// guarded block for thread-safe request
- ZThread::Guard<ZThread::FastMutex> query_connection_guard(mMutex);
- #ifdef TRINITY_DEBUG
+ ACE_Guard<ACE_Thread_Mutex> query_connection_guard(mMutex);
+ #ifdef MANGOS_DEBUG
uint32 _s = getMSTime();
#endif
PGresult *res = PQexec(mPGconn, sql);
@@ -244,7 +279,7 @@ bool DatabasePostgre::BeginTransaction()
// don't use queued execution if it has not been initialized
if (!m_threadBody)
{
- if (tranThread==ZThread::ThreadImpl::current())
+ if (tranThread == ACE_Based::Thread::current())
return false; // huh? this thread already started transaction
mMutex.acquire();
if (!_TransactionCmd("START TRANSACTION"))
@@ -255,7 +290,7 @@ bool DatabasePostgre::BeginTransaction()
return true;
}
// transaction started
- tranThread = ZThread::ThreadImpl::current(); // owner of this transaction
+ tranThread = ACE_Based::Thread::current(); // owner of this transaction
TransactionQueues::iterator i = m_tranQueues.find(tranThread);
if (i != m_tranQueues.end() && i->second != NULL)
// If for thread exists queue and also contains transaction
@@ -275,14 +310,14 @@ bool DatabasePostgre::CommitTransaction()
// don't use queued execution if it has not been initialized
if (!m_threadBody)
{
- if (tranThread!=ZThread::ThreadImpl::current())
+ if (tranThread != ACE_Based::Thread::current())
return false;
bool _res = _TransactionCmd("COMMIT");
tranThread = NULL;
mMutex.release();
return _res;
}
- tranThread = ZThread::ThreadImpl::current();
+ tranThread = ACE_Based::Thread::current();
TransactionQueues::iterator i = m_tranQueues.find(tranThread);
if (i != m_tranQueues.end() && i->second != NULL)
{
@@ -301,14 +336,14 @@ bool DatabasePostgre::RollbackTransaction()
// don't use queued execution if it has not been initialized
if (!m_threadBody)
{
- if (tranThread!=ZThread::ThreadImpl::current())
+ if (tranThread != ACE_Based::Thread::current())
return false;
bool _res = _TransactionCmd("ROLLBACK");
tranThread = NULL;
mMutex.release();
return _res;
}
- tranThread = ZThread::ThreadImpl::current();
+ tranThread = ACE_Based::Thread::current();
TransactionQueues::iterator i = m_tranQueues.find(tranThread);
if (i != m_tranQueues.end() && i->second != NULL)
{
@@ -331,7 +366,8 @@ void DatabasePostgre::InitDelayThread()
assert(!m_delayThread);
//New delay thread for delay execute
- m_delayThread = new ZThread::Thread(m_threadBody = new PGSQLDelayThread(this));
+ m_threadBody = new PGSQLDelayThread(this);
+ m_delayThread = new ACE_Based::Thread(*m_threadBody);
}
void DatabasePostgre::HaltDelayThread()
diff --git a/src/shared/Database/DatabasePostgre.h b/src/shared/Database/DatabasePostgre.h
index 6dc0c509869..92a8dff045a 100644
--- a/src/shared/Database/DatabasePostgre.h
+++ b/src/shared/Database/DatabasePostgre.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -22,7 +22,6 @@
#define _DatabasePostgre_H
#include "Policies/Singleton.h"
-#include "zthread/FastMutex.h"
#include <stdarg.h>
#ifdef WIN32
@@ -47,6 +46,7 @@ class DatabasePostgre : public Database
void InitDelayThread();
void HaltDelayThread();
QueryResult* Query(const char *sql);
+ QueryNamedResult* QueryNamed(const char *sql);
bool Execute(const char *sql);
bool DirectExecute(const char* sql);
bool BeginTransaction();
@@ -63,16 +63,15 @@ class DatabasePostgre : public Database
// must be call before finish thread run
void ThreadEnd();
private:
- ZThread::FastMutex mMutex;
- ZThread::FastMutex tranMutex;
-
- ZThread::ThreadImpl* tranThread;
+ ACE_Thread_Mutex mMutex;
+ ACE_Based::Thread * tranThread;
PGconn *mPGconn;
static size_t db_count;
bool _TransactionCmd(const char *sql);
+ bool _Query(const char *sql, PGresult **pResult, uint64* pRowCount, uint32* pFieldCount);
};
#endif
diff --git a/src/shared/Database/DatabaseSqlite.cpp b/src/shared/Database/DatabaseSqlite.cpp
deleted file mode 100644
index a7a4a2a9847..00000000000
--- a/src/shared/Database/DatabaseSqlite.cpp
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
- *
- * Copyright (C) 2008 Trinity <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, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-#ifndef DO_POSTGRESQL
-
-#include "DatabaseEnv.h"
-
-DatabaseSqlite::DatabaseSqlite() : Database(), mSqlite(0)
-{
-}
-
-DatabaseSqlite::~DatabaseSqlite()
-{
- if (mSqlite)
- sqlite_close(mSqlite);
-}
-
-bool DatabaseSqlite::Initialize(const char *infoString)
-{
- if(!Database::Initialize(infoString))
- return false;
-
- char *errmsg;
-
- mSqlite = sqlite_open(infoString, 0, &errmsg);
-
- if (!mSqlite)
- {
-
- if (errmsg)
- sqlite_freemem(errmsg);
- return false;
- }
-
- return true;
-}
-
-QueryResult* DatabaseSqlite::Query(const char *sql)
-{
- char *errmsg;
-
- if (!mSqlite)
- return 0;
-
- char **tableData;
- int rowCount;
- int fieldCount;
-
- sqlite_get_table(mSqlite, sql, &tableData, &rowCount, &fieldCount, &errmsg);
-
- if (!rowCount)
- return 0;
-
- if (!tableData)
- {
-
- if (errmsg)
- sqlite_freemem(errmsg);
- return 0;
- }
-
- QueryResultSqlite *queryResult = new QueryResultSqlite(tableData, rowCount, fieldCount);
- if(!queryResult)
- {
-
- return 0;
- }
-
- queryResult->NextRow();
-
- return queryResult;
-}
-
-bool DatabaseSqlite::Execute(const char *sql)
-{
- char *errmsg;
-
- if (!mSqlite)
- return false;
-
- if(sqlite_exec(mSqlite, sql, NULL, NULL, &errmsg) != SQLITE_OK)
- return false;
-
- return true;
-}
-#endif
-
diff --git a/src/shared/Database/DatabaseSqlite.h b/src/shared/Database/DatabaseSqlite.h
deleted file mode 100644
index 32d49d0124b..00000000000
--- a/src/shared/Database/DatabaseSqlite.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
- *
- * Copyright (C) 2008 Trinity <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, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-#ifndef DO_POSTGRESQL
-
-#ifndef _DATABASESQLITE_H
-#define _DATABASESQLITE_H
-
-#include <sqlite/sqlite.h>
-
-class DatabaseSqlite : public Database
-{
- public:
- DatabaseSqlite();
- ~DatabaseSqlite();
-
- bool Initialize(const char *infoString);
-
- QueryResult* Query(const char *sql);
- bool Execute(const char *sql);
-
- operator bool () const { return mSqlite != NULL; }
-
- private:
- sqlite *mSqlite;
-};
-#endif
-#endif
-
diff --git a/src/shared/Database/Field.cpp b/src/shared/Database/Field.cpp
index a7817d9a630..9a1fbfa5178 100644
--- a/src/shared/Database/Field.cpp
+++ b/src/shared/Database/Field.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/Database/Field.h b/src/shared/Database/Field.h
index 3e5f26376bb..f365a96df64 100644
--- a/src/shared/Database/Field.h
+++ b/src/shared/Database/Field.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -59,7 +59,7 @@ class Field
if(mValue)
{
uint64 value;
- sscanf(mValue,I64FMTD,&value);
+ sscanf(mValue,UI64FMTD,&value);
return value;
}
else
diff --git a/src/shared/Database/Makefile.am b/src/shared/Database/Makefile.am
new file mode 100644
index 00000000000..518ea4c98a3
--- /dev/null
+++ b/src/shared/Database/Makefile.am
@@ -0,0 +1,59 @@
+# Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+#
+# Copyright (C) 2008-2009 Trinity <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, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+## Process this file with automake to produce Makefile.in
+
+## Sub-directories to parse
+
+## CPP flags for includes, defines, etc.
+AM_CPPFLAGS = $(TRINI_INCLUDES) -I$(top_builddir)/src/shared -I$(srcdir) -I$(srcdir)/../../../dep/include -I$(srcdir)/../../framework -I$(srcdir)/../../shared -I$(srcdir)/../../../dep/include/g3dlite
+
+## Build MaNGOS shared library and its parts as convenience library.
+# All libraries will be convenience libraries. Might be changed to shared
+# later.
+noinst_LIBRARIES = libmangosdatabase.a
+
+libmangosdatabase_a_SOURCES = \
+ DBCFileLoader.cpp \
+ DBCFileLoader.h \
+ DBCStore.h \
+ Database.cpp \
+ Database.h \
+ DatabaseEnv.h \
+ DatabaseImpl.h \
+ DatabaseMysql.cpp \
+ DatabasePostgre.cpp \
+ DatabaseMysql.h \
+ DatabasePostgre.h \
+ DBCEnums.h \
+ Field.cpp \
+ Field.h \
+ MySQLDelayThread.h \
+ PGSQLDelayThread.h \
+ QueryResult.h \
+ QueryResultMysql.cpp \
+ QueryResultMysql.h \
+ QueryResultPostgre.cpp \
+ QueryResultPostgre.h \
+ SQLStorage.cpp \
+ SQLStorage.h \
+ SQLStorageImpl.h \
+ SqlDelayThread.cpp \
+ SqlDelayThread.h \
+ SqlOperations.cpp \
+ SqlOperations.h
diff --git a/src/shared/Database/MySQLDelayThread.h b/src/shared/Database/MySQLDelayThread.h
index 14cf1a64617..fcebe3fbd35 100644
--- a/src/shared/Database/MySQLDelayThread.h
+++ b/src/shared/Database/MySQLDelayThread.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/Database/PGSQLDelayThread.h b/src/shared/Database/PGSQLDelayThread.h
index 19941464cca..8d219bd9c1e 100644
--- a/src/shared/Database/PGSQLDelayThread.h
+++ b/src/shared/Database/PGSQLDelayThread.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/Database/QueryResult.h b/src/shared/Database/QueryResult.h
index 32e47c0959f..f9f1a009833 100644
--- a/src/shared/Database/QueryResult.h
+++ b/src/shared/Database/QueryResult.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -31,37 +31,53 @@ class TRINITY_DLL_SPEC QueryResult
virtual bool NextRow() = 0;
- typedef std::map<uint32, std::string> FieldNames;
-
- uint32 GetField_idx(const std::string &name) const
- {
- for(FieldNames::const_iterator iter = GetFieldNames().begin(); iter != GetFieldNames().end(); ++iter)
- {
- if(iter->second == name)
- return iter->first;
- }
- assert(false && "unknown field name");
- return uint32(-1);
- }
-
Field *Fetch() const { return mCurrentRow; }
const Field & operator [] (int index) const { return mCurrentRow[index]; }
- const Field & operator [] (const std::string &name) const
- {
- return mCurrentRow[GetField_idx(name)];
- }
-
uint32 GetFieldCount() const { return mFieldCount; }
uint64 GetRowCount() const { return mRowCount; }
- FieldNames const& GetFieldNames() const {return mFieldNames; }
protected:
Field *mCurrentRow;
uint32 mFieldCount;
uint64 mRowCount;
- FieldNames mFieldNames;
};
+
+typedef std::vector<std::string> QueryFieldNames;
+
+class MANGOS_DLL_SPEC QueryNamedResult
+{
+ public:
+ explicit QueryNamedResult(QueryResult* query, QueryFieldNames const& names) : mQuery(query), mFieldNames(names) {}
+ ~QueryNamedResult() { delete mQuery; }
+
+ // compatible interface with QueryResult
+ bool NextRow() { return mQuery->NextRow(); }
+ Field *Fetch() const { return mQuery->Fetch(); }
+ uint32 GetFieldCount() const { return mQuery->GetFieldCount(); }
+ uint64 GetRowCount() const { return mQuery->GetRowCount(); }
+ Field const& operator[] (int index) const { return (*mQuery)[index]; }
+
+ // named access
+ Field const& operator[] (const std::string &name) const { return mQuery->Fetch()[GetField_idx(name)]; }
+ QueryFieldNames const& GetFieldNames() const { return mFieldNames; }
+
+ uint32 GetField_idx(const std::string &name) const
+ {
+ for(size_t idx = 0; idx < mFieldNames.size(); ++idx)
+ {
+ if(mFieldNames[idx] == name)
+ return idx;
+ }
+ ASSERT(false && "unknown field name");
+ return uint32(-1);
+ }
+
+ protected:
+ QueryResult *mQuery;
+ QueryFieldNames mFieldNames;
+};
+
#endif
diff --git a/src/shared/Database/QueryResultMysql.cpp b/src/shared/Database/QueryResultMysql.cpp
index d995b9f2473..2e4738469c9 100644
--- a/src/shared/Database/QueryResultMysql.cpp
+++ b/src/shared/Database/QueryResultMysql.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -22,20 +22,15 @@
#include "DatabaseEnv.h"
-QueryResultMysql::QueryResultMysql(MYSQL_RES *result, uint64 rowCount, uint32 fieldCount) :
-QueryResult(rowCount, fieldCount), mResult(result)
+QueryResultMysql::QueryResultMysql(MYSQL_RES *result, MYSQL_FIELD *fields, uint64 rowCount, uint32 fieldCount) :
+ QueryResult(rowCount, fieldCount), mResult(result)
{
mCurrentRow = new Field[mFieldCount];
ASSERT(mCurrentRow);
- MYSQL_FIELD *fields = mysql_fetch_fields(mResult);
-
for (uint32 i = 0; i < mFieldCount; i++)
- {
- mFieldNames[i] = fields[i].name;
mCurrentRow[i].SetType(ConvertNativeType(fields[i].type));
- }
}
QueryResultMysql::~QueryResultMysql()
diff --git a/src/shared/Database/QueryResultMysql.h b/src/shared/Database/QueryResultMysql.h
index 3131bd4bbe4..89aceb12b13 100644
--- a/src/shared/Database/QueryResultMysql.h
+++ b/src/shared/Database/QueryResultMysql.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -34,7 +34,7 @@
class QueryResultMysql : public QueryResult
{
public:
- QueryResultMysql(MYSQL_RES *result, uint64 rowCount, uint32 fieldCount);
+ QueryResultMysql(MYSQL_RES *result, MYSQL_FIELD *fields, uint64 rowCount, uint32 fieldCount);
~QueryResultMysql();
diff --git a/src/shared/Database/QueryResultPostgre.cpp b/src/shared/Database/QueryResultPostgre.cpp
index def1b0061e5..915b0fba253 100644
--- a/src/shared/Database/QueryResultPostgre.cpp
+++ b/src/shared/Database/QueryResultPostgre.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -23,17 +23,14 @@
#include "DatabaseEnv.h"
QueryResultPostgre::QueryResultPostgre(PGresult *result, uint64 rowCount, uint32 fieldCount) :
-QueryResult(rowCount, fieldCount), mResult(result), mTableIndex(0)
+ QueryResult(rowCount, fieldCount), mResult(result), mTableIndex(0)
{
mCurrentRow = new Field[mFieldCount];
ASSERT(mCurrentRow);
for (uint32 i = 0; i < mFieldCount; i++)
- {
- mFieldNames[i] = PQfname(result, i);
mCurrentRow[i].SetType(ConvertNativeType(PQftype( result, i )));
- }
}
QueryResultPostgre::~QueryResultPostgre()
diff --git a/src/shared/Database/QueryResultPostgre.h b/src/shared/Database/QueryResultPostgre.h
index 61311728f2d..30d69114dc6 100644
--- a/src/shared/Database/QueryResultPostgre.h
+++ b/src/shared/Database/QueryResultPostgre.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/Database/QueryResultSqlite.cpp b/src/shared/Database/QueryResultSqlite.cpp
deleted file mode 100644
index a041232f600..00000000000
--- a/src/shared/Database/QueryResultSqlite.cpp
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
- *
- * Copyright (C) 2008 Trinity <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, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-#ifndef DO_POSTGRESQL
-
-#include "DatabaseEnv.h"
-
-QueryResultSqlite::QueryResultSqlite(char **tableData, uint32 rowCount, uint32 fieldCount) :
-QueryResult(rowCount, fieldCount), mTableData(tableData), mTableIndex(0)
-{
- mCurrentRow = new Field[mFieldCount];
-
- for (uint32 i = 0; i < mFieldCount; i++)
- {
- mFieldNames[i] = mTableData[i];
- mCurrentRow[i].SetType(Field::DB_TYPE_UNKNOWN);
- }
-}
-
-QueryResultSqlite::~QueryResultSqlite()
-{
- EndQuery();
-}
-
-bool QueryResultSqlite::NextRow()
-{
- int startIndex;
- uint32 i;
-
- if (!mTableData)
- return false;
-
- if (mTableIndex >= mRowCount)
- {
- EndQuery();
- return false;
- }
-
- startIndex = (mTableIndex + 1) * mFieldCount;
- for (i = 0; i < mFieldCount; i++)
- {
- mCurrentRow[i].SetValue(mTableData[startIndex + i]);
- }
-
- ++mTableIndex;
- return true;
-}
-
-void QueryResultSqlite::EndQuery()
-{
- if (mCurrentRow)
- {
- delete [] mCurrentRow;
- mCurrentRow = NULL;
- }
- if (mTableData)
- {
- sqlite_free_table(mTableData);
- mTableData = NULL;
- }
-}
-
-enum Field::DataTypes QueryResultSqlite::ConvertNativeType(const char* sqliteType) const
-{
- if (sqliteType)
- {
- switch (*sqliteType)
- {
- case 'S':
- return Field::DB_TYPE_STRING;
- case 'I':
- return Field::DB_TYPE_INTEGER;
- case 'F':
- return Field::DB_TYPE_FLOAT;
- default:
- return Field::DB_TYPE_UNKNOWN;
- };
- }
- return Field::DB_TYPE_UNKNOWN;
-}
-#endif
-
diff --git a/src/shared/Database/QueryResultSqlite.h b/src/shared/Database/QueryResultSqlite.h
deleted file mode 100644
index b2622f96707..00000000000
--- a/src/shared/Database/QueryResultSqlite.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
- *
- * Copyright (C) 2008 Trinity <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, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-#ifndef DO_POSTGRESQL
-
-#if !defined(QUERYRESULTSQLITE_H)
-#define QUERYRESULTSQLITE_H
-
-#include <sqlite/sqlite.h>
-
-class QueryResultSqlite : public QueryResult
-{
- public:
- QueryResultSqlite(char **tableData, uint32 rowCount, uint32 fieldCount);
-
- ~QueryResultSqlite();
-
- bool NextRow();
-
- private:
- enum Field::DataTypes ConvertNativeType(const char* sqliteType) const;
- void EndQuery();
-
- char **mTableData;
- uint32 mTableIndex;
-};
-#endif
-#endif
-
diff --git a/src/shared/Database/SQLStorage.cpp b/src/shared/Database/SQLStorage.cpp
index 0eeefbf10ca..50fd484bff5 100644
--- a/src/shared/Database/SQLStorage.cpp
+++ b/src/shared/Database/SQLStorage.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -27,20 +27,20 @@ extern DatabasePostgre WorldDatabase;
extern DatabaseMysql WorldDatabase;
#endif
-const char CreatureInfosrcfmt[]="iiiiiisssiiiiiiiiiiffiffiiiiiiiiiiiffiiiiiiiiiiiiiiiiiiisiilliiis";
-const char CreatureInfodstfmt[]="iiiiiisssiiiiiiiiiiffiffiiiiiiiiiiiffiiiiiiiiiiiiiiiiiiisiilliiii";
-const char CreatureDataAddonInfofmt[]="iiiiiiiis";
+const char CreatureInfosrcfmt[]="iiiiiiiisssiiiiiiiiiiffiffiifiiiiiiiiiiffiiiiiiiiiiiiiiiiiiiiiiiisiiffliiiiiliiis";
+const char CreatureInfodstfmt[]="iiiiiiiisssiiiiiiiiiiffiffiifiiiiiiiiiiffiiiiiiiiiiiiiiiiiiiiiiiisiiffliiiiiliiii";
+const char CreatureDataAddonInfofmt[]="iiiiiis";
const char CreatureModelfmt[]="iffbi";
-const char CreatureInfoAddonInfofmt[]="iiiiiiiis";
-const char EquipmentInfofmt[]="iiiiiiiiii";
-const char GameObjectInfosrcfmt[]="iiissiifiiiiiiiiiiiiiiiiiiiiiiiis";
-const char GameObjectInfodstfmt[]="iiissiifiiiiiiiiiiiiiiiiiiiiiiiii";
-const char ItemPrototypesrcfmt[]="iiiisiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiffiffiffiffiffiiiiiiiiiifiiifiiiiiifiiiiiifiiiiiifiiiiiifiiiisiiiiiiiiiiiiiiiiiiiiiiiiifsiiiii";
-const char ItemPrototypedstfmt[]="iiiisiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiffiffiffiffiffiiiiiiiiiifiiifiiiiiifiiiiiifiiiiiifiiiiiifiiiisiiiiiiiiiiiiiiiiiiiiiiiiifiiiiii";
+const char CreatureInfoAddonInfofmt[]="iiiiiis";
+const char EquipmentInfofmt[]="iiii";
+const char GameObjectInfosrcfmt[]="iiissssiifiiiiiiiiiiiiiiiiiiiiiiiiiiiis";
+const char GameObjectInfodstfmt[]="iiissssiifiiiiiiiiiiiiiiiiiiiiiiiiiiiii";
+const char ItemPrototypesrcfmt[]="iiiisiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiffiffiiiiiiiiiifiiifiiiiiifiiiiiifiiiiiifiiiiiifiiiisiiiiiiiiiiiiiiiiiiiiiiiiifiiisiiii";
+const char ItemPrototypedstfmt[]="iiiisiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiffiffiiiiiiiiiifiiifiiiiiifiiiiiifiiiiiifiiiiiifiiiisiiiiiiiiiiiiiiiiiiiiiiiiifiiiiiiii";
const char PageTextfmt[]="isi";
const char SpellThreatfmt[]="ii";
-const char InstanceTemplatesrcfmt[]="iiiiiffffs";
-const char InstanceTemplatedstfmt[]="iiiiiffffi";
+const char InstanceTemplatesrcfmt[]="iiiiiiffffs";
+const char InstanceTemplatedstfmt[]="iiiiiiffffi";
SQLStorage sCreatureStorage(CreatureInfosrcfmt, CreatureInfodstfmt, "entry","creature_template");
SQLStorage sCreatureDataAddonStorage(CreatureDataAddonInfofmt,"guid","creature_addon");
diff --git a/src/shared/Database/SQLStorage.h b/src/shared/Database/SQLStorage.h
index 43e34532607..1b5b9d5dcf1 100644
--- a/src/shared/Database/SQLStorage.h
+++ b/src/shared/Database/SQLStorage.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/Database/SQLStorageImpl.h b/src/shared/Database/SQLStorageImpl.h
index 82ff0beb60e..b511bdad68c 100644
--- a/src/shared/Database/SQLStorageImpl.h
+++ b/src/shared/Database/SQLStorageImpl.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -18,17 +18,17 @@
#include "ProgressBar.h"
#include "Log.h"
-#include "dbcfile.h"
+#include "DBCFileLoader.h"
template<class T>
template<class S, class D>
-void SQLStorageLoaderBase<T>::convert(uint32 field_pos, S src, D &dst)
+void SQLStorageLoaderBase<T>::convert(uint32 /*field_pos*/, S src, D &dst)
{
dst = D(src);
}
template<class T>
-void SQLStorageLoaderBase<T>::convert_str_to_str(uint32 field_pos, char *src, char *&dst)
+void SQLStorageLoaderBase<T>::convert_str_to_str(uint32 /*field_pos*/, char *src, char *&dst)
{
if(!src)
{
@@ -45,7 +45,7 @@ void SQLStorageLoaderBase<T>::convert_str_to_str(uint32 field_pos, char *src, ch
template<class T>
template<class S>
-void SQLStorageLoaderBase<T>::convert_to_str(uint32 field_pos, S src, char * & dst)
+void SQLStorageLoaderBase<T>::convert_to_str(uint32 /*field_pos*/, S /*src*/, char * & dst)
{
dst = new char[1];
*dst = 0;
@@ -53,7 +53,7 @@ void SQLStorageLoaderBase<T>::convert_to_str(uint32 field_pos, S src, char * & d
template<class T>
template<class D>
-void SQLStorageLoaderBase<T>::convert_from_str(uint32 field_pos, char * src, D& dst)
+void SQLStorageLoaderBase<T>::convert_from_str(uint32 /*field_pos*/, char * /*src*/, D& dst)
{
dst = 0;
}
diff --git a/src/shared/Database/SqlDelayThread.cpp b/src/shared/Database/SqlDelayThread.cpp
index 16d5146fc53..9a92fd5dd63 100644
--- a/src/shared/Database/SqlDelayThread.cpp
+++ b/src/shared/Database/SqlDelayThread.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -37,7 +37,7 @@ void SqlDelayThread::run()
{
// if the running state gets turned off while sleeping
// empty the queue before exiting
- ZThread::Thread::sleep(10);
+ ACE_Based::Thread::Sleep(10);
while (!m_sqlQueue.empty())
{
s = m_sqlQueue.next();
diff --git a/src/shared/Database/SqlDelayThread.h b/src/shared/Database/SqlDelayThread.h
index 4c77c122f1e..3c24d3525b7 100644
--- a/src/shared/Database/SqlDelayThread.h
+++ b/src/shared/Database/SqlDelayThread.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -21,28 +21,29 @@
#ifndef __SQLDELAYTHREAD_H
#define __SQLDELAYTHREAD_H
-#include "zthread/Thread.h"
-#include "zthread/Runnable.h"
-#include "zthread/FastMutex.h"
-#include "zthread/LockedQueue.h"
+#include "ace/Thread_Mutex.h"
+#include "LockedQueue.h"
+#include "Threading.h"
+
class Database;
class SqlOperation;
-class SqlDelayThread : public ZThread::Runnable
+class SqlDelayThread : public ACE_Based::Runnable
{
- typedef ZThread::LockedQueue<SqlOperation*, ZThread::FastMutex> SqlQueue;
+ typedef ACE_Based::LockedQueue<SqlOperation*, ACE_Thread_Mutex> SqlQueue;
+
private:
SqlQueue m_sqlQueue; ///< Queue of SQL statements
Database* m_dbEngine; ///< Pointer to used Database engine
- bool m_running;
+ volatile bool m_running;
SqlDelayThread();
public:
SqlDelayThread(Database* db);
///< Put sql statement to delay queue
- inline bool Delay(SqlOperation* sql) { m_sqlQueue.add(sql); return true; }
+ bool Delay(SqlOperation* sql) { m_sqlQueue.add(sql); return true; }
virtual void Stop(); ///< Stop event
virtual void run(); ///< Main Thread loop
diff --git a/src/shared/Database/SqlOperations.cpp b/src/shared/Database/SqlOperations.cpp
index c11c5b9269d..53b99359c09 100644
--- a/src/shared/Database/SqlOperations.cpp
+++ b/src/shared/Database/SqlOperations.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -97,7 +97,7 @@ bool SqlQueryHolder::SetQuery(size_t index, const char *sql)
{
if(m_queries.size() <= index)
{
- sLog.outError("Query index (%u) out of range (size: %u) for query: %s",index,m_queries.size(),sql);
+ sLog.outError("Query index (%u) out of range (size: %u) for query: %s",index,(uint32)m_queries.size(),sql);
return false;
}
diff --git a/src/shared/Database/SqlOperations.h b/src/shared/Database/SqlOperations.h
index 1a0d3c78d1b..e91d83b6611 100644
--- a/src/shared/Database/SqlOperations.h
+++ b/src/shared/Database/SqlOperations.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -23,9 +23,8 @@
#include "Common.h"
-#include "zthread/LockedQueue.h"
-#include "zthread/FastMutex.h"
-#include "zthread/Thread.h"
+#include "ace/Thread_Mutex.h"
+#include "LockedQueue.h"
#include <queue>
#include "Utilities/Callback.h"
@@ -72,7 +71,7 @@ class SqlResultQueue; /// queue for thread
class SqlQueryHolder; /// groups several async quries
class SqlQueryHolderEx; /// points to a holder, added to the delay thread
-class SqlResultQueue : public ZThread::LockedQueue<Trinity::IQueryCallback*, ZThread::FastMutex>
+class SqlResultQueue : public ACE_Based::LockedQueue<MaNGOS::IQueryCallback* , ACE_Thread_Mutex>
{
public:
SqlResultQueue() {}
diff --git a/src/shared/Errors.h b/src/shared/Errors.h
index 7203f1c5420..218ab561c12 100644
--- a/src/shared/Errors.h
+++ b/src/shared/Errors.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -21,11 +21,14 @@
#ifndef TRINITYCORE_ERRORS_H
#define TRINITYCORE_ERRORS_H
-#define WPAssert( assertion ) { if( !(assertion) ) { fprintf( stderr, "\n%s:%i ASSERTION FAILED:\n %s\n", __FILE__, __LINE__, #assertion ); assert( #assertion &&0 ); } }
-#define WPError( assertion, errmsg ) if( ! (assertion) ) { sLog.outError( "%s:%i ERROR:\n %s\n", __FILE__, __LINE__, (char *)errmsg ); assert( false ); }
-#define WPWarning( assertion, errmsg ) if( ! (assertion) ) { sLog.outError( "%s:%i WARNING:\n %s\n", __FILE__, __LINE__, (char *)errmsg ); }
+//#include <ace/Stack_Trace.h>
-#define WPFatal( assertion, errmsg ) if( ! (assertion) ) { sLog.outError( "%s:%i FATAL ERROR:\n %s\n", __FILE__, __LINE__, (char *)errmsg ); assert( #assertion &&0 ); abort(); }
+//#define WPAssert( assertion ) { if (!(assertion)) { ACE_Stack_Trace st; fprintf( stderr, "\n%s:%i in %s ASSERTION FAILED:\n %s\n%s\n", __FILE__, __LINE__,__FUNCTION__, #assertion, st.c_str()); assert( #assertion &&0 ); } }
+#define WPAssert( assertion ) { if( !(assertion) ) { fprintf( stderr, "\n%s:%i in %s ASSERTION FAILED:\n %s\n", __FILE__, __LINE__,__FUNCTION__, #assertion ); assert( #assertion &&0 ); } }
+#define WPError( assertion, errmsg ) if( ! (assertion) ) { sLog.outError( "%\n%s:%i in %s ERROR:\n %s\n", __FILE__, __LINE__, __FUNCTION__, (char *)errmsg ); assert( false ); }
+#define WPWarning( assertion, errmsg ) if( ! (assertion) ) { sLog.outError( "\n%s:%i in %s WARNING:\n %s\n", __FILE__, __LINE__, __FUNCTION__, (char *)errmsg ); }
+
+#define WPFatal( assertion, errmsg ) if( ! (assertion) ) { sLog.outError( "\n%s:%i in %s FATAL ERROR:\n %s\n", __FILE__, __LINE__, __FUNCTION__, (char *)errmsg ); assert( #assertion &&0 ); abort(); }
#define ASSERT WPAssert
#endif
diff --git a/src/shared/LockedQueue.h b/src/shared/LockedQueue.h
new file mode 100644
index 00000000000..b085dd09b83
--- /dev/null
+++ b/src/shared/LockedQueue.h
@@ -0,0 +1,144 @@
+/*
+ * Copyright (C) 2009 MaNGOS <http://getmangos.com/>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef LOCKEDQUEUE_H
+#define LOCKEDQUEUE_H
+
+#include <ace/Guard_T.h>
+#include <ace/Thread_Mutex.h>
+#include <deque>
+#include <assert.h>
+#include "Errors.h"
+
+namespace ACE_Based
+{
+
+ template <class T, class LockType, typename StorageType=std::deque<T> >
+ class LockedQueue
+ {
+
+ //! Serialize access to the Queue
+ LockType _lock;
+
+ //! Storage backing the queue
+ StorageType _queue;
+
+ //! Cancellation flag
+ volatile bool _canceled;
+
+ public:
+
+ //! Create a LockedQueue
+ LockedQueue() : _canceled(false) {}
+
+ //! Destroy a LockedQueue
+ virtual ~LockedQueue() { }
+
+ /**
+ * @see Queue::add(const T& item)
+ */
+ void add(const T& item)
+ {
+
+ ACE_Guard<LockType> g(_lock);
+
+ ASSERT(!_canceled);
+ // throw Cancellation_Exception();
+
+ _queue.push_back(item);
+
+ }
+
+ /**
+ * @see Queue::next()
+ */
+ T next()
+ {
+
+ ACE_Guard<LockType> g(_lock);
+
+ ASSERT (!_queue.empty() || !_canceled);
+ // throw Cancellation_Exception();
+
+ T item = _queue.front();
+ _queue.pop_front();
+
+ return item;
+
+ }
+
+ T front()
+ {
+ ACE_Guard<LockType> g(_lock);
+
+ ASSERT (!_queue.empty());
+ // throw NoSuchElement_Exception();
+
+ return _queue.front();
+ }
+
+ /**
+ * @see Queue::cancel()
+ */
+ void cancel()
+ {
+
+ ACE_Guard<LockType> g(_lock);
+
+ _canceled = true;
+
+ }
+
+ /**
+ * @see Queue::isCanceled()
+ */
+ bool isCanceled()
+ {
+
+ // Faster check since the queue will not become un-canceled
+ if(_canceled)
+ return true;
+
+ ACE_Guard<LockType> g(_lock);
+
+ return _canceled;
+
+ }
+
+ /**
+ * @see Queue::size()
+ */
+ size_t size()
+ {
+
+ ACE_Guard<LockType> g(_lock);
+ return _queue.size();
+
+ }
+
+ bool empty()
+ {
+
+ ACE_Guard<LockType> g(_lock);
+ return _queue.empty();
+ }
+
+ };
+
+}
+#endif
diff --git a/src/shared/Log.cpp b/src/shared/Log.cpp
index 46bef6b469b..0f1138279ff 100644
--- a/src/shared/Log.cpp
+++ b/src/shared/Log.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -25,139 +25,47 @@
#include "Util.h"
#include <stdarg.h>
+#include <stdio.h>
INSTANTIATE_SINGLETON_1( Log );
-enum LogType
-{
- LogNormal = 0,
- LogDetails,
- LogDebug,
- LogError
-};
-
-const int LogType_count = int(LogError) +1;
-
Log::Log() :
raLogfile(NULL), logfile(NULL), gmLogfile(NULL), charLogfile(NULL),
- dberLogfile(NULL), arenaLogFile(NULL), m_colored(false), m_includeTime(false), m_gmlog_per_account(false)
+ dberLogfile(NULL), chatLogfile(NULL), m_gmlog_per_account(false), m_colored(false)
+ , arenaLogFile(NULL)
{
Initialize();
}
-void Log::InitColors(const std::string& str)
-{
- if(str.empty())
- {
- m_colored = false;
- return;
- }
-
- int color[4];
-
- std::istringstream ss(str);
-
- for(int i = 0; i < LogType_count; ++i)
- {
- ss >> color[i];
-
- if(!ss)
- return;
-
- if(color[i] < 0 || color[i] >= Color_count)
- return;
- }
-
- for(int i = 0; i < LogType_count; ++i)
- m_colors[i] = Color(color[i]);
-
- m_colored = true;
-}
-
-void Log::SetColor(bool stdout_stream, Color color)
+Log::~Log()
{
- #if PLATFORM == PLATFORM_WINDOWS
-
- static WORD WinColorFG[Color_count] =
- {
- 0, // BLACK
- FOREGROUND_RED, // RED
- FOREGROUND_GREEN, // GREEN
- FOREGROUND_RED | FOREGROUND_GREEN, // BROWN
- FOREGROUND_BLUE, // BLUE
- FOREGROUND_RED | FOREGROUND_BLUE,// MAGENTA
- FOREGROUND_GREEN | FOREGROUND_BLUE, // CYAN
- FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,// WHITE
- // YELLOW
- FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY,
- // RED_BOLD
- FOREGROUND_RED | FOREGROUND_INTENSITY,
- // GREEN_BOLD
- FOREGROUND_GREEN | FOREGROUND_INTENSITY,
- FOREGROUND_BLUE | FOREGROUND_INTENSITY, // BLUE_BOLD
- // MAGENTA_BOLD
- FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY,
- // CYAN_BOLD
- FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY,
- // WHITE_BOLD
- FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY
- };
+ if( logfile != NULL )
+ fclose(logfile);
+ logfile = NULL;
- HANDLE hConsole = GetStdHandle(stdout_stream ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE );
- SetConsoleTextAttribute(hConsole, WinColorFG[color]);
- #else
-
- enum ANSITextAttr
- {
- TA_NORMAL=0,
- TA_BOLD=1,
- TA_BLINK=5,
- TA_REVERSE=7
- };
+ if( gmLogfile != NULL )
+ fclose(gmLogfile);
+ gmLogfile = NULL;
- enum ANSIFgTextAttr
- {
- FG_BLACK=30, FG_RED, FG_GREEN, FG_BROWN, FG_BLUE,
- FG_MAGENTA, FG_CYAN, FG_WHITE, FG_YELLOW
- };
+ if (charLogfile != NULL)
+ fclose(charLogfile);
+ charLogfile = NULL;
- enum ANSIBgTextAttr
- {
- BG_BLACK=40, BG_RED, BG_GREEN, BG_BROWN, BG_BLUE,
- BG_MAGENTA, BG_CYAN, BG_WHITE
- };
+ if( dberLogfile != NULL )
+ fclose(dberLogfile);
+ dberLogfile = NULL;
- static uint8 UnixColorFG[Color_count] =
- {
- FG_BLACK, // BLACK
- FG_RED, // RED
- FG_GREEN, // GREEN
- FG_BROWN, // BROWN
- FG_BLUE, // BLUE
- FG_MAGENTA, // MAGENTA
- FG_CYAN, // CYAN
- FG_WHITE, // WHITE
- FG_YELLOW, // YELLOW
- FG_RED, // LRED
- FG_GREEN, // LGREEN
- FG_BLUE, // LBLUE
- FG_MAGENTA, // LMAGENTA
- FG_CYAN, // LCYAN
- FG_WHITE // LWHITE
- };
+ if (raLogfile != NULL)
+ fclose(raLogfile);
+ raLogfile = NULL;
- fprintf((stdout_stream? stdout : stderr), "\x1b[%d%sm",UnixColorFG[color],(color>=YELLOW&&color<Color_count ?";1":""));
- #endif
-}
+ if (chatLogfile != NULL)
+ fclose(chatLogfile);
+ chatLogfile = NULL;
-void Log::ResetColor(bool stdout_stream)
-{
- #if PLATFORM == PLATFORM_WINDOWS
- HANDLE hConsole = GetStdHandle(stdout_stream ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE );
- SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED );
- #else
- fprintf(( stdout_stream ? stdout : stderr ), "\x1b[0m");
- #endif
+ if (arenaLogFile != NULL)
+ fclose(arenaLogFile);
+ arenaLogFile = NULL;
}
void Log::SetLogLevel(char *Level)
@@ -167,7 +75,7 @@ void Log::SetLogLevel(char *Level)
NewLevel = 0;
m_logLevel = NewLevel;
- printf( "LogLevel is %u\n",m_logLevel );
+ outString( "LogLevel is %u",m_logLevel );
}
void Log::SetLogFileLevel(char *Level)
@@ -177,11 +85,30 @@ void Log::SetLogFileLevel(char *Level)
NewLevel = 0;
m_logFileLevel = NewLevel;
- printf( "LogFileLevel is %u\n",m_logFileLevel );
+ outString( "LogFileLevel is %u",m_logFileLevel );
+}
+
+void Log::SetDBLogLevel(char *Level)
+{
+ int32 NewLevel = atoi((char*)Level);
+ if ( NewLevel < 0 )
+ NewLevel = 0;
+ m_dbLogLevel = NewLevel;
+
+ outString( "DBLogLevel is %u",m_dbLogLevel );
}
void Log::Initialize()
{
+ /// Check whether we'll log GM commands/RA events/character outputs/chat stuffs
+ m_dbChar = sConfig.GetBoolDefault("LogDB.Char", false);
+ m_dbRA = sConfig.GetBoolDefault("LogDB.RA", false);
+ m_dbGM = sConfig.GetBoolDefault("LogDB.GM", false);
+ m_dbChat = sConfig.GetBoolDefault("LogDB.Chat", false);
+
+ /// Realm must be 0 by default
+ SetRealmID(0);
+
/// Common log files data
m_logsDir = sConfig.GetStringDefault("LogsDir","");
if(!m_logsDir.empty())
@@ -194,6 +121,7 @@ void Log::Initialize()
/// Open specific log files
logfile = openLogFile("LogFile","LogTimestamp","w");
+ InitColors(sConfig.GetStringDefault("LogColors", ""));
m_gmlog_per_account = sConfig.GetBoolDefault("GmLogPerAccount",false);
if(!m_gmlog_per_account)
@@ -230,14 +158,13 @@ void Log::Initialize()
dberLogfile = openLogFile("DBErrorLogFile",NULL,"a");
raLogfile = openLogFile("RaLogFile",NULL,"a");
-
+ chatLogfile = openLogFile("ChatLogFile","ChatLogTimestamp","a");
arenaLogFile = openLogFile("ArenaLogFile",NULL,"a");
// Main log file settings
- m_includeTime = sConfig.GetBoolDefault("LogTime", false);
- m_logLevel = sConfig.GetIntDefault("LogLevel", 0);
- m_logFileLevel = sConfig.GetIntDefault("LogFileLevel", 0);
- InitColors(sConfig.GetStringDefault("LogColors", ""));
+ m_logLevel = sConfig.GetIntDefault("LogLevel", LOGL_NORMAL);
+ m_logFileLevel = sConfig.GetIntDefault("LogFileLevel", LOGL_NORMAL);
+ m_dbLogLevel = sConfig.GetIntDefault("DBLogLevel", LOGL_NORMAL);
m_logFilter = 0;
@@ -247,6 +174,8 @@ void Log::Initialize()
m_logFilter |= LOG_FILTER_CREATURE_MOVES;
if(sConfig.GetBoolDefault("LogFilter_VisibilityChanges", true))
m_logFilter |= LOG_FILTER_VISIBILITY_CHANGES;
+ if(sConfig.GetBoolDefault("LogFilter_AchievementUpdates", true))
+ m_logFilter |= LOG_FILTER_ACHIEVEMENT_UPDATES;
// Char log settings
m_charLog_Dump = sConfig.GetBoolDefault("CharLogDump", false);
@@ -294,17 +223,117 @@ void Log::outTimestamp(FILE* file)
fprintf(file,"%-4d-%02d-%02d %02d:%02d:%02d ",aTm->tm_year+1900,aTm->tm_mon+1,aTm->tm_mday,aTm->tm_hour,aTm->tm_min,aTm->tm_sec);
}
-void Log::outTime()
+void Log::InitColors(const std::string& str)
{
- time_t t = time(NULL);
- tm* aTm = localtime(&t);
- // YYYY year
- // MM month (2 digits 01-12)
- // DD day (2 digits 01-31)
- // HH hour (2 digits 00-23)
- // MM minutes (2 digits 00-59)
- // SS seconds (2 digits 00-59)
- printf("%02d:%02d:%02d ",aTm->tm_hour,aTm->tm_min,aTm->tm_sec);
+ if(str.empty())
+ {
+ m_colored = false;
+ return;
+ }
+
+ int color[4];
+
+ std::istringstream ss(str);
+
+ for(uint8 i = 0; i < LogLevels; ++i)
+ {
+ ss >> color[i];
+
+ if(!ss)
+ return;
+
+ if(color[i] < 0 || color[i] >= Colors)
+ return;
+ }
+
+ for(uint8 i = 0; i < LogLevels; ++i)
+ m_colors[i] = ColorTypes(color[i]);
+
+ m_colored = true;
+}
+
+void Log::SetColor(bool stdout_stream, ColorTypes color)
+{
+ #if PLATFORM == PLATFORM_WINDOWS
+ static WORD WinColorFG[Colors] =
+ {
+ 0, // BLACK
+ FOREGROUND_RED, // RED
+ FOREGROUND_GREEN, // GREEN
+ FOREGROUND_RED | FOREGROUND_GREEN, // BROWN
+ FOREGROUND_BLUE, // BLUE
+ FOREGROUND_RED | FOREGROUND_BLUE,// MAGENTA
+ FOREGROUND_GREEN | FOREGROUND_BLUE, // CYAN
+ FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE,// WHITE
+ // YELLOW
+ FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY,
+ // RED_BOLD
+ FOREGROUND_RED | FOREGROUND_INTENSITY,
+ // GREEN_BOLD
+ FOREGROUND_GREEN | FOREGROUND_INTENSITY,
+ FOREGROUND_BLUE | FOREGROUND_INTENSITY, // BLUE_BOLD
+ // MAGENTA_BOLD
+ FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY,
+ // CYAN_BOLD
+ FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY,
+ // WHITE_BOLD
+ FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY
+ };
+
+ HANDLE hConsole = GetStdHandle(stdout_stream ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE );
+ SetConsoleTextAttribute(hConsole, WinColorFG[color]);
+ #else
+ enum ANSITextAttr
+ {
+ TA_NORMAL=0,
+ TA_BOLD=1,
+ TA_BLINK=5,
+ TA_REVERSE=7
+ };
+
+ enum ANSIFgTextAttr
+ {
+ FG_BLACK=30, FG_RED, FG_GREEN, FG_BROWN, FG_BLUE,
+ FG_MAGENTA, FG_CYAN, FG_WHITE, FG_YELLOW
+ };
+
+ enum ANSIBgTextAttr
+ {
+ BG_BLACK=40, BG_RED, BG_GREEN, BG_BROWN, BG_BLUE,
+ BG_MAGENTA, BG_CYAN, BG_WHITE
+ };
+
+ static uint8 UnixColorFG[Colors] =
+ {
+ FG_BLACK, // BLACK
+ FG_RED, // RED
+ FG_GREEN, // GREEN
+ FG_BROWN, // BROWN
+ FG_BLUE, // BLUE
+ FG_MAGENTA, // MAGENTA
+ FG_CYAN, // CYAN
+ FG_WHITE, // WHITE
+ FG_YELLOW, // YELLOW
+ FG_RED, // LRED
+ FG_GREEN, // LGREEN
+ FG_BLUE, // LBLUE
+ FG_MAGENTA, // LMAGENTA
+ FG_CYAN, // LCYAN
+ FG_WHITE // LWHITE
+ };
+
+ fprintf((stdout_stream? stdout : stderr), "\x1b[%d%sm", UnixColorFG[color], (color >= YELLOW && color < Colors ? ";1" : ""));
+ #endif
+}
+
+void Log::ResetColor(bool stdout_stream)
+{
+ #if PLATFORM == PLATFORM_WINDOWS
+ HANDLE hConsole = GetStdHandle(stdout_stream ? STD_OUTPUT_HANDLE : STD_ERROR_HANDLE );
+ SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED );
+ #else
+ fprintf(( stdout_stream ? stdout : stderr ), "\x1b[0m");
+ #endif
}
std::string Log::GetTimestampStr()
@@ -322,16 +351,42 @@ std::string Log::GetTimestampStr()
return std::string(buf);
}
-void Log::outTitle( const char * str)
+void Log::outDB( LogTypes type, const char * str )
+{
+ if(!str || std::string(str).empty() || type >= MAX_LOG_TYPES)
+ return;
+
+ std::string new_str(str);
+ LoginDatabase.escape_string(new_str);
+
+ LoginDatabase.PExecute("INSERT INTO logs (time, realm, type, string) "
+ "VALUES (" UI64FMTD ", %u, %u, '%s');", uint64(time(0)), realm, (uint32)type, new_str.c_str());
+}
+
+void Log::outString( const char * str, ... )
{
if( !str )
return;
+ if (m_enableLogDB)
+ {
+ // we don't want empty strings in the DB
+ std::string s(str);
+ if(s.empty() || s == " ")
+ return;
+
+ va_list ap2;
+ va_start(ap2, str);
+ char nnew_str[MAX_QUERY_LEN];
+ vsnprintf(nnew_str, MAX_QUERY_LEN, str, ap2);
+ outDB(LOG_TYPE_STRING, nnew_str);
+ va_end(ap2);
+ }
+
if(m_colored)
- SetColor(true,WHITE);
+ SetColor(true,m_colors[LOGL_NORMAL]);
- // not expected utf8 and then send as-is
- printf( str );
+ UTF8PRINTF(stdout,str,);
if(m_colored)
ResetColor(true);
@@ -339,18 +394,20 @@ void Log::outTitle( const char * str)
printf( "\n" );
if(logfile)
{
- fprintf(logfile, str);
+ outTimestamp(logfile);
+ va_list ap;
+ va_start(ap, str);
+ vfprintf(logfile, str, ap);
fprintf(logfile, "\n" );
+ va_end(ap);
+
fflush(logfile);
}
-
fflush(stdout);
}
-void Log::outString()
+void Log::outString( )
{
- if(m_includeTime)
- outTime();
printf( "\n" );
if(logfile)
{
@@ -361,36 +418,44 @@ void Log::outString()
fflush(stdout);
}
-void Log::outString( const char * str, ... )
+void Log::outCrash( const char * err, ... )
{
- if( !str )
+ if( !err )
return;
- if(m_colored)
- SetColor(true,m_colors[LogNormal]);
+ if (m_enableLogDB)
+ {
+ va_list ap2;
+ va_start(ap2, err);
+ char nnew_str[MAX_QUERY_LEN];
+ vsnprintf(nnew_str, MAX_QUERY_LEN, err, ap2);
+ outDB(LOG_TYPE_CRASH, nnew_str);
+ va_end(ap2);
+ }
- if(m_includeTime)
- outTime();
+ if(m_colored)
+ SetColor(false,RED);
- UTF8PRINTF(stdout,str,);
+ UTF8PRINTF(stderr,err,);
if(m_colored)
- ResetColor(true);
+ ResetColor(false);
- printf( "\n" );
+ fprintf( stderr, "\n" );
if(logfile)
{
outTimestamp(logfile);
+ fprintf(logfile, "CRASH ALERT: " );
va_list ap;
- va_start(ap, str);
- vfprintf(logfile, str, ap);
- fprintf(logfile, "\n" );
+ va_start(ap, err);
+ vfprintf(logfile, err, ap);
va_end(ap);
+ fprintf(logfile, "\n" );
fflush(logfile);
}
- fflush(stdout);
+ fflush(stderr);
}
void Log::outError( const char * err, ... )
@@ -398,11 +463,18 @@ void Log::outError( const char * err, ... )
if( !err )
return;
- if(m_colored)
- SetColor(false,m_colors[LogError]);
+ if (m_enableLogDB)
+ {
+ va_list ap2;
+ va_start(ap2, err);
+ char nnew_str[MAX_QUERY_LEN];
+ vsnprintf(nnew_str, MAX_QUERY_LEN, err, ap2);
+ outDB(LOG_TYPE_ERROR, nnew_str);
+ va_end(ap2);
+ }
- if(m_includeTime)
- outTime();
+ if(m_colored)
+ SetColor(false,RED);
UTF8PRINTF(stderr,err,);
@@ -413,7 +485,7 @@ void Log::outError( const char * err, ... )
if(logfile)
{
outTimestamp(logfile);
- fprintf(logfile, "ERROR:" );
+ fprintf(logfile, "ERROR: " );
va_list ap;
va_start(ap, err);
@@ -450,10 +522,7 @@ void Log::outErrorDb( const char * err, ... )
return;
if(m_colored)
- SetColor(false,m_colors[LogError]);
-
- if(m_includeTime)
- outTime();
+ SetColor(false,RED);
UTF8PRINTF(stderr,err,);
@@ -465,7 +534,7 @@ void Log::outErrorDb( const char * err, ... )
if(logfile)
{
outTimestamp(logfile);
- fprintf(logfile, "ERROR:" );
+ fprintf(logfile, "ERROR: " );
va_list ap;
va_start(ap, err);
@@ -479,7 +548,6 @@ void Log::outErrorDb( const char * err, ... )
if(dberLogfile)
{
outTimestamp(dberLogfile);
-
va_list ap;
va_start(ap, err);
vfprintf(dberLogfile, err, ap);
@@ -496,13 +564,20 @@ void Log::outBasic( const char * str, ... )
if( !str )
return;
- if( m_logLevel > 0 )
+ if (m_enableLogDB && m_dbLogLevel > LOGL_NORMAL)
{
- if(m_colored)
- SetColor(true,m_colors[LogDetails]);
+ va_list ap2;
+ va_start(ap2, str);
+ char nnew_str[MAX_QUERY_LEN];
+ vsnprintf(nnew_str, MAX_QUERY_LEN, str, ap2);
+ outDB(LOG_TYPE_BASIC, nnew_str);
+ va_end(ap2);
+ }
- if(m_includeTime)
- outTime();
+ if( m_logLevel > LOGL_NORMAL )
+ {
+ if(m_colored)
+ SetColor(true,m_colors[LOGL_BASIC]);
UTF8PRINTF(stdout,str,);
@@ -512,10 +587,10 @@ void Log::outBasic( const char * str, ... )
printf( "\n" );
}
- if(logfile && m_logFileLevel > 0)
+ if(logfile && m_logFileLevel > LOGL_NORMAL)
{
- va_list ap;
outTimestamp(logfile);
+ va_list ap;
va_start(ap, str);
vfprintf(logfile, str, ap);
fprintf(logfile, "\n" );
@@ -530,14 +605,20 @@ void Log::outDetail( const char * str, ... )
if( !str )
return;
- if( m_logLevel > 1 )
+ if (m_enableLogDB && m_dbLogLevel > LOGL_BASIC)
{
+ va_list ap2;
+ va_start(ap2, str);
+ char nnew_str[MAX_QUERY_LEN];
+ vsnprintf(nnew_str, MAX_QUERY_LEN, str, ap2);
+ outDB(LOG_TYPE_DETAIL, nnew_str);
+ va_end(ap2);
+ }
+ if( m_logLevel > LOGL_BASIC )
+ {
if(m_colored)
- SetColor(true,m_colors[LogDetails]);
-
- if(m_includeTime)
- outTime();
+ SetColor(true,m_colors[LOGL_DETAIL]);
UTF8PRINTF(stdout,str,);
@@ -546,10 +627,10 @@ void Log::outDetail( const char * str, ... )
printf( "\n" );
}
- if(logfile && m_logFileLevel > 1)
+ if(logfile && m_logFileLevel > LOGL_BASIC)
{
- va_list ap;
outTimestamp(logfile);
+ va_list ap;
va_start(ap, str);
vfprintf(logfile, str, ap);
fprintf(logfile, "\n" );
@@ -564,17 +645,12 @@ void Log::outDebugInLine( const char * str, ... )
{
if( !str )
return;
- if( m_logLevel > 2 )
- {
- if(m_colored)
- SetColor(true,m_colors[LogDebug]);
+ if( m_logLevel > LOGL_DETAIL )
+ {
UTF8PRINTF(stdout,str,);
-
- if(m_colored)
- ResetColor(true);
}
- if(logfile && m_logFileLevel > 2)
+ if(logfile && m_logFileLevel > LOGL_DETAIL)
{
va_list ap;
va_start(ap, str);
@@ -587,13 +663,21 @@ void Log::outDebug( const char * str, ... )
{
if( !str )
return;
- if( m_logLevel > 2 )
+
+ if (m_enableLogDB && m_dbLogLevel > LOGL_DETAIL)
{
- if(m_colored)
- SetColor(true,m_colors[LogDebug]);
+ va_list ap2;
+ va_start(ap2, str);
+ char nnew_str[MAX_QUERY_LEN];
+ vsnprintf(nnew_str, MAX_QUERY_LEN, str, ap2);
+ outDB(LOG_TYPE_DEBUG, nnew_str);
+ va_end(ap2);
+ }
- if(m_includeTime)
- outTime();
+ if( m_logLevel > LOGL_DETAIL )
+ {
+ if(m_colored)
+ SetColor(true,m_colors[LOGL_DEBUG]);
UTF8PRINTF(stdout,str,);
@@ -602,10 +686,9 @@ void Log::outDebug( const char * str, ... )
printf( "\n" );
}
- if(logfile && m_logFileLevel > 2)
+ if(logfile && m_logFileLevel > LOGL_DETAIL)
{
outTimestamp(logfile);
-
va_list ap;
va_start(ap, str);
vfprintf(logfile, str, ap);
@@ -622,13 +705,21 @@ void Log::outCommand( uint32 account, const char * str, ... )
if( !str )
return;
- if( m_logLevel > 1 )
+ // TODO: support accountid
+ if (m_enableLogDB && m_dbGM)
{
- if(m_colored)
- SetColor(true,m_colors[LogDetails]);
+ va_list ap2;
+ va_start(ap2, str);
+ char nnew_str[MAX_QUERY_LEN];
+ vsnprintf(nnew_str, MAX_QUERY_LEN, str, ap2);
+ outDB(LOG_TYPE_GM, nnew_str);
+ va_end(ap2);
+ }
- if(m_includeTime)
- outTime();
+ if( m_logLevel > LOGL_NORMAL )
+ {
+ if(m_colored)
+ SetColor(true,m_colors[LOGL_BASIC]);
UTF8PRINTF(stdout,str,);
@@ -637,10 +728,10 @@ void Log::outCommand( uint32 account, const char * str, ... )
printf( "\n" );
}
- if(logfile && m_logFileLevel > 1)
+ if(logfile && m_logFileLevel > LOGL_NORMAL)
{
- va_list ap;
outTimestamp(logfile);
+ va_list ap;
va_start(ap, str);
vfprintf(logfile, str, ap);
fprintf(logfile, "\n" );
@@ -652,8 +743,8 @@ void Log::outCommand( uint32 account, const char * str, ... )
{
if (FILE* per_file = openGmlogPerAccount (account))
{
- va_list ap;
outTimestamp(per_file);
+ va_list ap;
va_start(ap, str);
vfprintf(per_file, str, ap);
fprintf(per_file, "\n" );
@@ -663,8 +754,8 @@ void Log::outCommand( uint32 account, const char * str, ... )
}
else if (gmLogfile)
{
- va_list ap;
outTimestamp(gmLogfile);
+ va_list ap;
va_start(ap, str);
vfprintf(gmLogfile, str, ap);
fprintf(gmLogfile, "\n" );
@@ -677,14 +768,23 @@ void Log::outCommand( uint32 account, const char * str, ... )
void Log::outChar(const char * str, ... )
{
-
if (!str)
return;
+ if (m_enableLogDB && m_dbChar)
+ {
+ va_list ap2;
+ va_start(ap2, str);
+ char nnew_str[MAX_QUERY_LEN];
+ vsnprintf(nnew_str, MAX_QUERY_LEN, str, ap2);
+ outDB(LOG_TYPE_CHAR, nnew_str);
+ va_end(ap2);
+ }
+
if(charLogfile)
{
- va_list ap;
outTimestamp(charLogfile);
+ va_list ap;
va_start(ap, str);
vfprintf(charLogfile, str, ap);
fprintf(charLogfile, "\n" );
@@ -702,48 +802,58 @@ void Log::outCharDump( const char * str, uint32 account_id, uint32 guid, const c
}
}
-void Log::outMenu( const char * str, ... )
+void Log::outRemote( const char * str, ... )
{
if( !str )
return;
- SetColor(true,m_colors[LogNormal]);
-
- if(m_includeTime)
- outTime();
-
- UTF8PRINTF(stdout,str,);
-
- ResetColor(true);
-
- if(logfile)
+ if (m_enableLogDB && m_dbRA)
{
- outTimestamp(logfile);
+ va_list ap2;
+ va_start(ap2, str);
+ char nnew_str[MAX_QUERY_LEN];
+ vsnprintf(nnew_str, MAX_QUERY_LEN, str, ap2);
+ outDB(LOG_TYPE_RA, nnew_str);
+ va_end(ap2);
+ }
+ if (raLogfile)
+ {
+ outTimestamp(raLogfile);
va_list ap;
va_start(ap, str);
- vfprintf(logfile, str, ap);
+ vfprintf(raLogfile, str, ap);
+ fprintf(raLogfile, "\n" );
va_end(ap);
-
- fprintf(logfile, "\n" );
- fflush(logfile);
+ fflush(raLogfile);
}
fflush(stdout);
}
-void Log::outRALog( const char * str, ... )
+void Log::outChat( const char * str, ... )
{
if( !str )
return;
- va_list ap;
- if (raLogfile)
+
+ if (m_enableLogDB && m_dbChat)
{
- outTimestamp(raLogfile);
+ va_list ap2;
+ va_start(ap2, str);
+ char nnew_str[MAX_QUERY_LEN];
+ vsnprintf(nnew_str, MAX_QUERY_LEN, str, ap2);
+ outDB(LOG_TYPE_CHAT, nnew_str);
+ va_end(ap2);
+ }
+
+ if (chatLogfile)
+ {
+ outTimestamp(chatLogfile);
+ va_list ap;
va_start(ap, str);
- vfprintf(raLogfile, str, ap);
- fprintf(raLogfile, "\n" );
+ vfprintf(chatLogfile, str, ap);
+ fprintf(chatLogfile, "\n" );
+ fflush(chatLogfile);
va_end(ap);
- fflush(raLogfile);
}
fflush(stdout);
}
diff --git a/src/shared/Log.h b/src/shared/Log.h
index f81a95661d5..b3fb9f00b2e 100644
--- a/src/shared/Log.h
+++ b/src/shared/Log.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -23,18 +23,45 @@
#include "Common.h"
#include "Policies/Singleton.h"
+#include "Database/DatabaseEnv.h"
class Config;
-// bitmask
enum LogFilters
{
- LOG_FILTER_TRANSPORT_MOVES = 1,
- LOG_FILTER_CREATURE_MOVES = 2,
- LOG_FILTER_VISIBILITY_CHANGES = 4
+ LOG_FILTER_TRANSPORT_MOVES = 1,
+ LOG_FILTER_CREATURE_MOVES = 2,
+ LOG_FILTER_VISIBILITY_CHANGES = 4,
+ LOG_FILTER_ACHIEVEMENT_UPDATES = 8
};
-enum Color
+enum LogTypes
+{
+ LOG_TYPE_STRING = 0,
+ LOG_TYPE_ERROR = 1,
+ LOG_TYPE_BASIC = 2,
+ LOG_TYPE_DETAIL = 3,
+ LOG_TYPE_DEBUG = 4,
+ LOG_TYPE_CHAR = 5,
+ LOG_TYPE_WORLD = 6,
+ LOG_TYPE_RA = 7,
+ LOG_TYPE_GM = 8,
+ LOG_TYPE_CRASH = 9,
+ LOG_TYPE_CHAT = 10,
+ MAX_LOG_TYPES
+};
+
+enum LogLevel
+{
+ LOGL_NORMAL = 0,
+ LOGL_BASIC,
+ LOGL_DETAIL,
+ LOGL_DEBUG
+};
+
+const int LogLevels = int(LOGL_DEBUG)+1;
+
+enum ColorTypes
{
BLACK,
RED,
@@ -53,78 +80,54 @@ enum Color
WHITE
};
-const int Color_count = int(WHITE)+1;
+const int Colors = int(WHITE)+1;
-class Log : public Trinity::Singleton<Log, Trinity::ClassLevelLockable<Log, ZThread::FastMutex> >
+class Log : public Trinity::Singleton<Log, Trinity::ClassLevelLockable<Log, ACE_Thread_Mutex> >
{
friend class Trinity::OperatorNew<Log>;
Log();
+ ~Log();
- ~Log()
- {
- if( logfile != NULL )
- fclose(logfile);
- logfile = NULL;
-
- if( gmLogfile != NULL )
- fclose(gmLogfile);
- gmLogfile = NULL;
-
- if (charLogfile != NULL)
- fclose(charLogfile);
- charLogfile = NULL;
-
- if( dberLogfile != NULL )
- fclose(dberLogfile);
- dberLogfile = NULL;
-
- if (raLogfile != NULL)
- fclose(raLogfile);
- raLogfile = NULL;
-
- if (arenaLogFile != NULL)
- fclose(arenaLogFile);
- arenaLogFile = NULL;
- }
public:
void Initialize();
+
void InitColors(const std::string& init_str);
- void outTitle( const char * str);
+ void SetColor(bool stdout_stream, ColorTypes color);
+ void ResetColor(bool stdout_stream);
+
+ void outDB( LogTypes type, const char * str );
+ void outString( const char * str, ... ) ATTR_PRINTF(2,3);
+ void outString( );
+ void outError( const char * err, ... ) ATTR_PRINTF(2,3);
+ void outCrash( const char * err, ... ) ATTR_PRINTF(2,3);
+ void outBasic( const char * str, ... ) ATTR_PRINTF(2,3);
+ void outDetail( const char * str, ... ) ATTR_PRINTF(2,3);
+ void outDebug( const char * str, ... ) ATTR_PRINTF(2,3);
+ void outDebugInLine( const char * str, ... ) ATTR_PRINTF(2,3);
+ void outErrorDb( const char * str, ... ) ATTR_PRINTF(2,3);
+ void outChar( const char * str, ... ) ATTR_PRINTF(2,3);
void outCommand( uint32 account, const char * str, ...) ATTR_PRINTF(3,4);
- void outString(); // any log level
- // any log level
- void outString( const char * str, ... ) ATTR_PRINTF(2,3);
- // any log level
- void outError( const char * err, ... ) ATTR_PRINTF(2,3);
- // log level >= 1
- void outBasic( const char * str, ... ) ATTR_PRINTF(2,3);
- // log level >= 2
- void outDetail( const char * str, ... ) ATTR_PRINTF(2,3);
- // log level >= 3
- void outDebugInLine( const char * str, ... ) ATTR_PRINTF(2,3);
- // log level >= 3
- void outDebug( const char * str, ... ) ATTR_PRINTF(2,3);
- // any log level
- void outMenu( const char * str, ... ) ATTR_PRINTF(2,3);
- // any log level
- void outErrorDb( const char * str, ... ) ATTR_PRINTF(2,3);
- // any log level
- void outChar( const char * str, ... ) ATTR_PRINTF(2,3);
- // any log level
+ void outRemote( const char * str, ... ) ATTR_PRINTF(2,3);
+ void outChat( const char * str, ... ) ATTR_PRINTF(2,3);
+ void outArena( const char * str, ... ) ATTR_PRINTF(2,3);
void outCharDump( const char * str, uint32 account_id, uint32 guid, const char * name );
- void outRALog( const char * str, ... ) ATTR_PRINTF(2,3);
- void outArena( const char * str, ... ) ATTR_PRINTF(2,3);
- void SetLogLevel(char * Level);
- void SetLogFileLevel(char * Level);
- void SetColor(bool stdout_stream, Color color);
- void ResetColor(bool stdout_stream);
- void outTime();
+
static void outTimestamp(FILE* file);
static std::string GetTimestampStr();
+
+ void SetLogLevel(char * Level);
+ void SetLogFileLevel(char * Level);
+ void SetDBLogLevel(char * Level);
+ void SetRealmID(uint32 id) { realm = id; }
+
uint32 getLogFilter() const { return m_logFilter; }
bool IsOutDebug() const { return m_logLevel > 2 || (m_logFileLevel > 2 && logfile); }
bool IsOutCharDump() const { return m_charLog_Dump; }
- bool IsIncludeTime() const { return m_includeTime; }
+
+ bool GetLogDB() { return m_enableLogDB; }
+ bool GetLogDBLater() { return m_enableLogDBLater; }
+ void SetLogDB(bool enable) { m_enableLogDB = enable; }
+ void SetLogDBLater(bool value) { m_enableLogDBLater = value; }
private:
FILE* openLogFile(char const* configFileName,char const* configTimeStampFlag, char const* mode);
FILE* openGmlogPerAccount(uint32 account);
@@ -134,27 +137,36 @@ class Log : public Trinity::Singleton<Log, Trinity::ClassLevelLockable<Log, ZThr
FILE* gmLogfile;
FILE* charLogfile;
FILE* dberLogfile;
+ FILE* chatLogfile;
FILE* arenaLogFile;
- // log/console control
- uint32 m_logLevel;
- uint32 m_logFileLevel;
- bool m_colored;
- bool m_includeTime;
- Color m_colors[4];
- uint32 m_logFilter;
-
// cache values for after initilization use (like gm log per account case)
std::string m_logsDir;
std::string m_logsTimestamp;
- // char log control
- bool m_charLog_Dump;
-
// gm log control
bool m_gmlog_per_account;
-
std::string m_gmlog_filename_format;
+
+ bool m_enableLogDBLater;
+ bool m_enableLogDB;
+ uint32 realm;
+
+ // log coloring
+ bool m_colored;
+ ColorTypes m_colors[4];
+
+ // log levels:
+ // 0 minimum/string, 1 basic/error, 2 detail, 3 full/debug
+ uint8 m_dbLogLevel;
+ uint8 m_logLevel;
+ uint8 m_logFileLevel;
+ uint8 m_logFilter;
+ bool m_dbChar;
+ bool m_dbRA;
+ bool m_dbGM;
+ bool m_dbChat;
+ bool m_charLog_Dump;
};
#define sLog Trinity::Singleton<Log>::Instance()
diff --git a/src/shared/Makefile.am b/src/shared/Makefile.am
new file mode 100644
index 00000000000..60af5b8a4b5
--- /dev/null
+++ b/src/shared/Makefile.am
@@ -0,0 +1,85 @@
+# Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+#
+# Copyright (C) 2008-2009 Trinity <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, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+## Process this file with automake to produce Makefile.in
+
+## Sub-directories to parse
+SUBDIRS = Auth Config Database vmap
+
+## CPP flags for includes, defines, etc.
+AM_CPPFLAGS = $(TRINI_INCLUDES) -I$(top_builddir)/src/shared -I$(srcdir) -I$(srcdir)/../../dep/include -I$(srcdir)/../framework -I$(srcdir)/../shared -I$(srcdir)/../../dep/include/g3dlite -DSYSCONFDIR=\"$(sysconfdir)/\"
+## AM_CPPFLAGS += -I$(srcdir)/../game -I$(srcdir)/../realmd
+
+## Build MaNGOS shared library and its parts as convenience library.
+# All libraries will be convenience libraries. Might be changed to shared
+# later.
+noinst_LIBRARIES = libmangosshared.a
+
+# libmangosshared library will later be reused by ...
+libmangosshared_a_SOURCES = \
+ Base.cpp \
+ Base.h \
+ ByteBuffer.h \
+ Common.cpp \
+ Common.h \
+ Errors.h \
+ LockedQueue.h \
+ Log.cpp \
+ Log.h \
+ MemoryLeaks.cpp \
+ MemoryLeaks.h \
+ ProgressBar.cpp \
+ ProgressBar.h \
+ Timer.h \
+ Threading.cpp \
+ Threading.h \
+ Util.cpp \
+ Util.h \
+ WorldPacket.h \
+ revision_nr.h \
+ revision.h
+
+# Get revision (git or svn)
+# Get HG revision
+REVISION_FILE = revision.h
+
+BUILT_SOURCES = $(REVISION_FILE)
+CLEANFILES = $(REVISION_FILE)
+
+FORCE:
+
+$(REVISION_FILE) : $(top_builddir)/src/tools/genrevision/genrevision FORCE
+ $(top_builddir)/src/tools/genrevision/genrevision $(top_srcdir)
+ cp $(top_builddir)/src/shared/revision.h $(top_srcdir)/src/shared
+
+## Additional files to include when running 'make dist'
+# Disabled packet logger
+EXTRA_DIST = \
+ PacketLog.cpp \
+ PacketLog.h
+
+# System configuration
+EXTRA_DIST += \
+ SystemConfig.h
+
+# System Win32 files
+EXTRA_DIST += \
+ ServiceWin32.cpp \
+ ServiceWin32.h \
+ WheatyExceptionReport.cpp \
+ WheatyExceptionReport.h
diff --git a/src/shared/MemoryLeaks.cpp b/src/shared/MemoryLeaks.cpp
new file mode 100644
index 00000000000..ef7e36c3b57
--- /dev/null
+++ b/src/shared/MemoryLeaks.cpp
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "MemoryLeaks.h"
+#include "Policies/SingletonImp.h"
+
+INSTANTIATE_SINGLETON_1( MemoryManager ) ;
+
+MemoryManager::MemoryManager( )
+{
+ #if COMPILER == MICROSOFT
+ // standard leak check initialization
+ //_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
+ // uncomment to disable Visual Leak Detector from code
+ //VLDDisable();
+ #endif
+}
diff --git a/src/shared/MemoryLeaks.h b/src/shared/MemoryLeaks.h
new file mode 100644
index 00000000000..c8b8fb8e1b1
--- /dev/null
+++ b/src/shared/MemoryLeaks.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef TRINITYSERVER_MEMORY_H
+#define TRINITYSERVER_MEMORY_H
+
+#include "Platform/CompilerDefs.h"
+
+#if COMPILER == COMPILER_MICROSOFT
+
+#ifndef _WIN64
+// Visual Leak Detector support enabled
+//#include <vld/vld.h>
+// standard Visual Studio leak check disabled,
+//# define _CRTDBG_MAP_ALLOC
+//# include <stdlib.h>
+//# include <crtdbg.h>
+#else
+//# define _CRTDBG_MAP_ALLOC
+//# include <stdlib.h>
+//# include <crtdbg.h>
+#endif
+
+#endif
+
+
+#include "Policies/Singleton.h"
+
+struct MemoryManager : public Trinity::Singleton < MemoryManager >
+{
+ MemoryManager();
+};
+#endif
diff --git a/src/shared/Mthread.cpp b/src/shared/Mthread.cpp
deleted file mode 100644
index fbbeeb5a620..00000000000
--- a/src/shared/Mthread.cpp
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
- Cross-platform thread handling
- Copyright (C) 2005 Andrew Zabolotny
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library 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
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public
- License along with this library; if not, write to the Free
- Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-*/
-
-#include "Mthread.h"
-
-#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE_CC__)
-# define TRINITY_PTHREAD_MUTEX_RECURSIVE PTHREAD_MUTEX_RECURSIVE
-#else
-# define TRINITY_PTHREAD_MUTEX_RECURSIVE PTHREAD_MUTEX_RECURSIVE_NP
-#endif
-
-#if PLATFORM != PLATFORM_WINDOWS
-
-MThread::MThread ()
-{
- tid = 0;
-}
-
-MThread::~MThread ()
-{
- /* Kill thread if this is not the current thread */
- if (tid && (pthread_self () != tid))
- {
- pthread_cancel (tid);
- pthread_join (tid, NULL);
- }
-}
-
-static void *thread_start_routine (void *arg)
-{
- MThread *newthr = (MThread *)arg;
- pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
- newthr->routine (newthr->arg);
- return NULL;
-}
-
-MThread *MThread::Start (void (*routine) (void *arg), void *arg)
-{
- MThread *newthr = new MThread ();
- newthr->routine = routine;
- newthr->arg = arg;
- int rc = pthread_create (&newthr->tid, NULL, thread_start_routine, newthr);
- if (rc)
- {
- newthr->DecRef ();
- return NULL;
- }
-
- return newthr;
-}
-
-pthread_mutexattr_t MMutex::attr;
-int MMutex::attr_refcount = 0;
-
-MMutex::MMutex ()
-{
- if (!attr_refcount++)
- {
- pthread_mutexattr_init (&attr);
- pthread_mutexattr_settype (&attr, TRINITY_PTHREAD_MUTEX_RECURSIVE);
- }
-
- pthread_mutex_init (&mutex, &attr);
-}
-
-MMutex::~MMutex ()
-{
- pthread_mutex_destroy (&mutex);
- if (!--attr_refcount)
- pthread_mutexattr_destroy (&attr);
-}
-
-bool MMutex::Lock ()
-{
- return (pthread_mutex_lock (&mutex) == 0);
-}
-
-bool MMutex::TryLock ()
-{
- return (pthread_mutex_trylock (&mutex) == 0);
-}
-
-void MMutex::Unlock ()
-{
- pthread_mutex_unlock (&mutex);
-}
-
-MMutex *MMutex::Create ()
-{
- return new MMutex ();
-}
-
-#else //windows
-
-MThread::MThread()
-{
- th = NULL;
-}
-
-MThread::~MThread ()
-{
- /* Kill thread if this is not current thread */
- if (th && (GetCurrentThreadId () != id))
- {
- TerminateThread (th, 0);
- WaitForSingleObject (th, INFINITE);
- CloseHandle (th);
- }
-}
-
-bool MThread::SetPriority (ThreadPriority prio)
-{
- int p;
- switch (prio)
- {
- case IDLE: p = THREAD_PRIORITY_IDLE; break;
- case LOWER: p = THREAD_PRIORITY_LOWEST; break;
- case LOW: p = THREAD_PRIORITY_BELOW_NORMAL; break;
- case NORMAL: p = THREAD_PRIORITY_NORMAL; break;
- case HIGH: p = THREAD_PRIORITY_ABOVE_NORMAL; break;
- case HIGHER: p = THREAD_PRIORITY_HIGHEST; break;
- case REALTIME: p = THREAD_PRIORITY_TIME_CRITICAL; break;
- default: p = THREAD_PRIORITY_NORMAL; break;
- }
- return SetThreadPriority (th, p);
-}
-
-static DWORD WINAPI thread_start_routine (void *arg)
-//static void thread_start_routine (void *arg)
-{
- MThread *newthr = (MThread *)arg;
- newthr->id = GetCurrentThreadId ();
- newthr->routine (newthr->arg);
- return 0;
-}
-
-MThread *MThread::Start (void (*routine) (void *arg), void *arg)
-{
- DWORD dwtid;
- MThread *newthr = new MThread ();
- newthr->routine = routine;
- newthr->arg = arg;
- newthr->th = CreateThread (NULL, WIN32_THREAD_STACK_SIZE, thread_start_routine, newthr, 0, &dwtid);
- //newthr->th = (HANDLE)_beginthread(thread_start_routine, 0, newthr);
- if (!newthr->th)
- {
- newthr->DecRef ();
- return NULL;
- }
- return newthr;
-}
-
-MMutex::MMutex ()
-{
- sem = CreateMutex (NULL, FALSE, NULL);
-}
-
-MMutex::~MMutex ()
-{
- CloseHandle (sem);
-}
-
-bool MMutex::Lock ()
-{
- return (WaitForSingleObject (sem, INFINITE) != WAIT_FAILED);
-}
-
-bool MMutex::TryLock ()
-{
- DWORD state = WaitForSingleObject (sem, 0);
- return (state == WAIT_OBJECT_0) && (state != WAIT_ABANDONED);
-}
-
-void MMutex::Unlock ()
-{
- ReleaseMutex (sem);
-}
-
-MMutex *MMutex::Create ()
-{
- MMutex *mutex = new MMutex ();
- if (!mutex->sem)
- {
- mutex->DecRef ();
- return NULL;
- }
- return mutex;
-}
-#endif
-
diff --git a/src/shared/Mthread.h b/src/shared/Mthread.h
deleted file mode 100644
index d0ac6deb43c..00000000000
--- a/src/shared/Mthread.h
+++ /dev/null
@@ -1,63 +0,0 @@
-#ifndef MTHREAD_H
-#define MTHREAD_H
-
-#include "Base.h"
-#ifndef WIN32
-#include <pthread.h>
-#else
-#include <windows.h>
-//#include "Process.h"
-#define WIN32_THREAD_STACK_SIZE 0x10000
-#endif
-
-enum ThreadPriority
-{
- IDLE,
- LOWER,
- LOW,
- NORMAL,
- HIGH,
- HIGHER,
- REALTIME
-};
-
-class MThread: public Base
-{
- public:
- static MThread *Start (void (*routine) (void *arg), void *arg);
- MThread ();
- ~MThread ();
- bool SetPriority (ThreadPriority prio);
-
- void (*routine) (void *arg);
- void *arg;
-
- #ifdef WIN32
- HANDLE th;
- ULONG id;
- #else
- pthread_t tid;
- #endif
-
-};
-
-class MMutex : public Base
-{
- public:
-
- #ifdef WIN32
- HANDLE sem;
- #else
- pthread_mutex_t mutex;
- static pthread_mutexattr_t attr;
- static int attr_refcount;
- #endif
- static MMutex *Create ();
- MMutex ();
- virtual ~MMutex ();
- virtual bool Lock ();
- virtual bool TryLock ();
- virtual void Unlock ();
-};
-#endif // MTHREAD_H
-
diff --git a/src/shared/PacketLog.cpp b/src/shared/PacketLog.cpp
index aa9fd2dc348..96c9727e7fa 100644
--- a/src/shared/PacketLog.cpp
+++ b/src/shared/PacketLog.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/PacketLog.h b/src/shared/PacketLog.h
index 30fb7da15b9..49ac72ebc4b 100644
--- a/src/shared/PacketLog.h
+++ b/src/shared/PacketLog.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/ProgressBar.cpp b/src/shared/ProgressBar.cpp
index f5a45b9d862..b72118ad804 100644
--- a/src/shared/ProgressBar.cpp
+++ b/src/shared/ProgressBar.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/ProgressBar.h b/src/shared/ProgressBar.h
index 3f217f228fe..50c5c7d11e5 100644
--- a/src/shared/ProgressBar.h
+++ b/src/shared/ProgressBar.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/ServiceWin32.cpp b/src/shared/ServiceWin32.cpp
index d384884529a..5c68ba31954 100644
--- a/src/shared/ServiceWin32.cpp
+++ b/src/shared/ServiceWin32.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -131,10 +131,10 @@ bool WinServiceUninstall()
serviceName, SERVICE_QUERY_STATUS | DELETE);
if (service)
{
- SERVICE_STATUS serviceStatus;
- if (QueryServiceStatus(service, &serviceStatus))
+ SERVICE_STATUS serviceStatus2;
+ if (QueryServiceStatus(service, &serviceStatus2))
{
- if (serviceStatus.dwCurrentState == SERVICE_STOPPED)
+ if (serviceStatus2.dwCurrentState == SERVICE_STOPPED)
DeleteService(service);
}
CloseServiceHandle(service);
diff --git a/src/shared/ServiceWin32.h b/src/shared/ServiceWin32.h
index d046acdcef4..18a52c396ea 100644
--- a/src/shared/ServiceWin32.h
+++ b/src/shared/ServiceWin32.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/SystemConfig.h b/src/shared/SystemConfig.h
index 6b4471e792d..9d154b863d0 100644
--- a/src/shared/SystemConfig.h
+++ b/src/shared/SystemConfig.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <http://www.trinitycore.org/>
*
*
* This program is free software; you can redistribute it and/or modify
@@ -28,7 +28,7 @@
#include "revision.h"
-#define _PACKAGENAME "TrinityCore "
+#define _PACKAGENAME "TrinityCore2 "
#define _CODENAME "YUME"
#if TRINITY_ENDIAN == TRINITY_BIGENDIAN
diff --git a/src/shared/SystemConfig.h.in b/src/shared/SystemConfig.h.in
new file mode 100644
index 00000000000..233403b77de
--- /dev/null
+++ b/src/shared/SystemConfig.h.in
@@ -0,0 +1,103 @@
+/*
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+ *
+ * Copyright (C) 2008-2009 Trinity <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, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef TRINITY_SYSTEMCONFIG_H
+#define TRINITY_SYSTEMCONFIG_H
+
+#ifndef _PACKAGENAME
+#define _PACKAGENAME "TrinityCore2 "
+#endif
+
+#include "Platform/Define.h"
+#include "revision.h" //-----here u are ------ _REVISION is the magic key
+
+#ifndef _VERSION
+#if PLATFORM == PLATFORM_WINDOWS
+# define _VERSION(REVD,REVT,REVN,REVH) "0.14.0-DEV" " (" REVD " " REVT " Revision " REVN " - " REVH ")"
+#else
+# define _VERSION(REVD,REVT,REVN,REVH) "@VERSION@" " (" REVD " " REVT " Revision " REVN " - " REVH ")"
+#endif
+#endif
+
+// Format is YYYYMMDDRR where RR is the change in the conf file
+// for that day.
+#ifndef _MANGOSDCONFVERSION
+# define _MANGOSDCONFVERSION 2008022901
+#endif
+#ifndef _REALMDCONFVERSION
+# define _REALMDCONFVERSION 2007062001
+#endif
+
+#if MANGOS_ENDIAN == MANGOS_BIGENDIAN
+# define _ENDIAN_STRING "big-endian"
+#else
+# define _ENDIAN_STRING "little-endian"
+#endif
+
+#if defined(i386) || defined(__i386) || defined(__i386__) || defined(_M_IX86)
+# define ARCHITECTURE "x32"
+#elif defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(_M_X64)
+# define ARCHITECTURE "x64"
+#elif defined(__ia64) || defined(__IA64__) || defined(_M_IA64)
+# define ARCHITECTURE "IA64"
+#else
+# define ARCHITECTURE "x32"
+#endif
+
+// The path to config files
+#ifndef SYSCONFDIR
+# define SYSCONFDIR ""
+#endif
+
+#if PLATFORM == PLATFORM_WINDOWS
+# ifdef _WIN64
+# define _ENDIAN_PLATFORM "Win64 (" _ENDIAN_STRING ")"
+# else
+# define _ENDIAN_PLATFORM "Win32 (" _ENDIAN_STRING ")"
+# endif
+# define _MANGOSD_CONFIG SYSCONFDIR"mangosd.conf"
+# define _REALMD_CONFIG SYSCONFDIR"realmd.conf"
+#else
+# if defined (__FreeBSD__)
+# define _ENDIAN_PLATFORM "FreeBSD_"ARCHITECTURE" (" _ENDIAN_STRING ")"
+# elif defined(__NetBSD__)
+# define _ENDIAN_PLATFORM "NetBSD_"ARCHITECTURE" (" _ENDIAN_STRING ")"
+# elif defined(__OpenBSD__)
+# define _ENDIAN_PLATFORM "OpenBSD_"ARCHITECTURE" (" _ENDIAN_STRING ")"
+# elif defined(__DragonFly__)
+# define _ENDIAN_PLATFORM "DragonFlyBSD_"ARCHITECTURE" (" _ENDIAN_STRING ")"
+# elif defined(__APPLE__)
+# define _ENDIAN_PLATFORM "MacOSX_"ARCHITECTURE" (" _ENDIAN_STRING ")"
+# elif defined(__linux) || defined(__linux__)
+# define _ENDIAN_PLATFORM "Linux_"ARCHITECTURE" (" _ENDIAN_STRING ")"
+# else
+# define _ENDIAN_PLATFORM "Unix_"ARCHITECTURE" (" _ENDIAN_STRING ")"
+# endif
+# define _MANGOSD_CONFIG SYSCONFDIR"mangosd.conf"
+# define _REALMD_CONFIG SYSCONFDIR"realmd.conf"
+#endif
+
+
+#define DEFAULT_PLAYER_LIMIT 100
+#define DEFAULT_WORLDSERVER_PORT 8085 //8129
+#define DEFAULT_REALMSERVER_PORT 3724
+#define DEFAULT_SOCKET_SELECT_TIME 10000
+#endif
diff --git a/src/shared/Threading.cpp b/src/shared/Threading.cpp
new file mode 100644
index 00000000000..496e86353ca
--- /dev/null
+++ b/src/shared/Threading.cpp
@@ -0,0 +1,205 @@
+/*
+ * Copyright (C) 2009 MaNGOS <http://getmangos.com/>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#include "Threading.h"
+#include <ace/OS_NS_unistd.h>
+#include <ace/Sched_Params.h>
+#include <vector>
+
+using namespace ACE_Based;
+
+ThreadPriority::ThreadPriority()
+{
+ for (int i = Idle; i < MAXPRIORITYNUM; ++i)
+ m_priority[i] = ACE_THR_PRI_OTHER_DEF;
+
+ m_priority[Idle] = ACE_Sched_Params::priority_min(ACE_SCHED_OTHER);
+ m_priority[Realtime] = ACE_Sched_Params::priority_max(ACE_SCHED_OTHER);
+
+ std::vector<int> _tmp;
+
+ ACE_Sched_Params::Policy _policy = ACE_SCHED_OTHER;
+ ACE_Sched_Priority_Iterator pr_iter(_policy);
+
+ while (pr_iter.more())
+ {
+ _tmp.push_back(pr_iter.priority());
+ pr_iter.next();
+ }
+
+ ASSERT (!_tmp.empty());
+
+ if(_tmp.size() >= MAXPRIORITYNUM)
+ {
+ const size_t max_pos = _tmp.size();
+ size_t min_pos = 1;
+ size_t norm_pos = 0;
+ for (size_t i = 0; i < max_pos; ++i)
+ {
+ if(_tmp[i] == ACE_THR_PRI_OTHER_DEF)
+ {
+ norm_pos = i + 1;
+ break;
+ }
+ }
+
+ //since we have only 7(seven) values in enum Priority
+ //and 3 we know already (Idle, Normal, Realtime) so
+ //we need to split each list [Idle...Normal] and [Normal...Realtime]
+ //into ¹ piesces
+ const size_t _divider = 4;
+ size_t _div = (norm_pos - min_pos) / _divider;
+ if(_div == 0)
+ _div = 1;
+
+ min_pos = (norm_pos - 1);
+
+ m_priority[Low] = _tmp[min_pos -= _div];
+ m_priority[Lowest] = _tmp[min_pos -= _div ];
+
+ _div = (max_pos - norm_pos) / _divider;
+ if(_div == 0)
+ _div = 1;
+
+ min_pos = norm_pos - 1;
+
+ m_priority[High] = _tmp[min_pos += _div];
+ m_priority[Highest] = _tmp[min_pos += _div];
+ }
+}
+
+int ThreadPriority::getPriority(Priority p) const
+{
+ if(p < Idle)
+ p = Idle;
+
+ if(p > Realtime)
+ p = Realtime;
+
+ return m_priority[p];
+}
+
+#define THREADFLAG (THR_NEW_LWP | THR_SCHED_DEFAULT| THR_JOINABLE)
+
+Thread::Thread() : m_task(0), m_iThreadId(0), m_hThreadHandle(0)
+{
+
+}
+
+Thread::Thread(Runnable& instance) : m_task(&instance), m_iThreadId(0), m_hThreadHandle(0)
+{
+ bool _start = start();
+ ASSERT (_start);
+}
+
+Thread::~Thread()
+{
+ //Wait();
+}
+
+//initialize Thread's class static member
+Thread::ThreadStorage Thread::m_ThreadStorage;
+ThreadPriority Thread::m_TpEnum;
+
+bool Thread::start()
+{
+ if(m_task == 0 || m_iThreadId != 0)
+ return false;
+
+ return (ACE_Thread::spawn(&Thread::ThreadTask, (void*)m_task, THREADFLAG, &m_iThreadId, &m_hThreadHandle) == 0);
+}
+
+bool Thread::wait()
+{
+ if(!m_hThreadHandle || !m_task)
+ return false;
+
+ ACE_THR_FUNC_RETURN _value = ACE_THR_FUNC_RETURN(-1);
+ int _res = ACE_Thread::join(m_hThreadHandle, &_value);
+
+ m_iThreadId = 0;
+ m_hThreadHandle = 0;
+
+ return (_res == 0);
+}
+
+void Thread::destroy()
+{
+ ACE_Thread::kill(m_iThreadId, -1);
+}
+
+void Thread::suspend()
+{
+ ACE_Thread::suspend(m_hThreadHandle);
+}
+
+void Thread::resume()
+{
+ ACE_Thread::resume(m_hThreadHandle);
+}
+
+ACE_THR_FUNC_RETURN Thread::ThreadTask(void * param)
+{
+ Runnable * _task = (Runnable*)param;
+ _task->run();
+
+ return (ACE_THR_FUNC_RETURN)0;
+}
+
+ACE_thread_t Thread::currentId()
+{
+ return ACE_Thread::self();
+}
+
+ACE_hthread_t Thread::currentHandle()
+{
+ ACE_hthread_t _handle;
+ ACE_Thread::self(_handle);
+
+ return _handle;
+}
+
+Thread * Thread::current()
+{
+ Thread * _thread = m_ThreadStorage.ts_object();
+ if(!_thread)
+ {
+ _thread = new Thread();
+ _thread->m_iThreadId = Thread::currentId();
+ _thread->m_hThreadHandle = Thread::currentHandle();
+
+ Thread * _oldValue = m_ThreadStorage.ts_object(_thread);
+ if(_oldValue)
+ delete _oldValue;
+ }
+
+ return _thread;
+}
+
+void Thread::setPriority(Priority type)
+{
+ int _priority = m_TpEnum.getPriority(type);
+ int _ok = ACE_Thread::setprio(m_hThreadHandle, _priority);
+ //remove this ASSERT in case you don't want to know is thread priority change was successful or not
+ ASSERT (_ok == 0);
+}
+
+void Thread::Sleep(unsigned long msecs)
+{
+ ACE_OS::sleep(ACE_Time_Value(0, 1000 * msecs));
+}
diff --git a/src/shared/Threading.h b/src/shared/Threading.h
new file mode 100644
index 00000000000..eac3c0e8efb
--- /dev/null
+++ b/src/shared/Threading.h
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2009 MaNGOS <http://getmangos.com/>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef THREADING_H
+#define THREADING_H
+
+#include <ace/Thread.h>
+#include <ace/TSS_T.h>
+#include <assert.h>
+#include "Errors.h"
+
+namespace ACE_Based
+{
+
+ class Runnable
+ {
+ public:
+ virtual ~Runnable() {}
+ virtual void run() = 0;
+ };
+
+ enum Priority
+ {
+ Idle,
+ Lowest,
+ Low,
+ Normal,
+ High,
+ Highest,
+ Realtime,
+ };
+
+#define MAXPRIORITYNUM (Realtime + 1)
+
+ class ThreadPriority
+ {
+ public:
+ ThreadPriority();
+ int getPriority(Priority p) const;
+
+ private:
+ int m_priority[MAXPRIORITYNUM];
+ };
+
+ class Thread
+ {
+ public:
+ Thread();
+ Thread(Runnable& instance);
+ ~Thread();
+
+ bool start();
+ bool wait();
+ void destroy();
+
+ void suspend();
+ void resume();
+
+ void setPriority(Priority type);
+
+ static void Sleep(unsigned long msecs);
+ static ACE_thread_t currentId();
+ static ACE_hthread_t currentHandle();
+ static Thread * current();
+
+ private:
+ Thread(const Thread&);
+ Thread& operator=(const Thread&);
+
+ static ACE_THR_FUNC_RETURN ThreadTask(void * param);
+
+ ACE_thread_t m_iThreadId;
+ ACE_hthread_t m_hThreadHandle;
+ Runnable * m_task;
+
+ typedef ACE_TSS<Thread> ThreadStorage;
+ //global object - container for Thread class representation of every thread
+ static ThreadStorage m_ThreadStorage;
+ //use this object to determine current OS thread priority values mapped to enum Priority{}
+ static ThreadPriority m_TpEnum;
+ };
+
+}
+#endif
diff --git a/src/shared/Timer.h b/src/shared/Timer.h
index 81b6bb58465..82f5be161d9 100644
--- a/src/shared/Timer.h
+++ b/src/shared/Timer.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/Util.cpp b/src/shared/Util.cpp
index 4624cacfde7..354568c778f 100644
--- a/src/shared/Util.cpp
+++ b/src/shared/Util.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -23,67 +23,92 @@
#include "sockets/socket_include.h"
#include "utf8cpp/utf8.h"
#include "mersennetwister/MersenneTwister.h"
-#include "zthread/ThreadLocal.h"
+#include <ace/TSS_T.h>
-typedef ZThread::ThreadLocal<MTRand> MTRandTSS;
-
-/* NOTE: Not sure if static initialization is ok for TSS objects ,
- * as I see zthread uses custom implementation of the TSS
- * ,and in the consturctor there is no code ,so I suppose its ok
- * If its not ok ,change it to use singleton.
- */
+typedef ACE_TSS<MTRand> MTRandTSS;
static MTRandTSS mtRand;
+#ifdef MULTI_THREAD_MAP
+
int32 irand (int32 min, int32 max)
{
- int32 result;
+ int32 result;
#pragma omp critical (mtrand)
{
- result = mtRand.get ().randInt (max-min) + min;
+ result = int32 (mtRand->randInt (max - min)) + min;
}
return result;
}
uint32 urand (uint32 min, uint32 max)
{
- uint32 result;
+ uint32 result;
#pragma omp critical (mtrand)
{
- result = mtRand.get ().randInt (max - min) + min;
+ result = mtRand->randInt (max - min) + min;
}
return result;
}
int32 rand32 ()
{
- int32 result;
+ int32 result;
#pragma omp critical (mtrand)
{
- result = mtRand.get ().randInt ();
+ result = mtRand->randInt ();
}
return result;
}
double rand_norm(void)
{
- double result;
+ double result;
#pragma omp critical (mtrand)
{
- result = mtRand.get ().randExc ();
+ result = mtRand->randExc ();
}
return result;
}
double rand_chance (void)
{
- double result;
+ double result;
#pragma omp critical (mtrand)
{
- result = mtRand.get ().randExc (100.0);
+ result = mtRand->randExc (100.0);
}
return result;
}
+#else
+
+int32 irand (int32 min, int32 max)
+{
+ return int32 (mtRand->randInt (max - min)) + min;
+}
+
+uint32 urand (uint32 min, uint32 max)
+{
+ return mtRand->randInt (max - min) + min;
+}
+
+int32 rand32 ()
+{
+ return mtRand->randInt ();
+}
+
+double rand_norm(void)
+{
+ return mtRand->randExc ();
+}
+
+double rand_chance (void)
+{
+ return mtRand->randExc (100.0);
+}
+
+#endif
+
Tokens StrSplit(const std::string &src, const std::string &sep)
{
Tokens r;
@@ -279,8 +304,9 @@ bool Utf8toWStr(char const* utf8str, size_t csize, wchar_t* wstr, size_t& wsize)
size_t len = utf8::distance(utf8str,utf8str+csize);
if(len > wsize)
{
+ if(wsize > 0)
+ wstr[0] = L'\0';
wsize = 0;
- wstr = L"";
return false;
}
@@ -290,8 +316,9 @@ bool Utf8toWStr(char const* utf8str, size_t csize, wchar_t* wstr, size_t& wsize)
}
catch(std::exception)
{
+ if(wsize > 0)
+ wstr[0] = L'\0';
wsize = 0;
- wstr = L"";
return false;
}
diff --git a/src/shared/Util.h b/src/shared/Util.h
index 98e60f83319..ddbf968b2c2 100644
--- a/src/shared/Util.h
+++ b/src/shared/Util.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -92,7 +92,7 @@ inline void ApplyModFloatVar(float& var, float val, bool apply)
inline void ApplyPercentModFloatVar(float& var, float val, bool apply)
{
- if (!apply && val == -100.0f)
+ if (val == -100.0f) // prevent set var to zero
val = -99.99f;
var *= (apply?(100.0f+val)/100.0f : 100.0f / (100.0f+val));
}
@@ -287,20 +287,20 @@ bool consoleToUtf8(const std::string& conStr,std::string& utf8str);
bool Utf8FitTo(const std::string& str, std::wstring search);
#if PLATFORM == PLATFORM_WINDOWS
-#define UTF8PRINTF(OUT,FRM,RESERR) \
-{ \
- char temp_buf[6000]; \
- va_list ap; \
- va_start(ap, FRM); \
- size_t temp_len = vsnprintf(temp_buf,6000,FRM,ap); \
- va_end(ap); \
- \
- wchar_t wtemp_buf[6000]; \
- size_t wtemp_len = 6000-1; \
+#define UTF8PRINTF(OUT,FRM,RESERR) \
+{ \
+ char temp_buf[32*1024]; \
+ va_list ap; \
+ va_start(ap, FRM); \
+ size_t temp_len = vsnprintf(temp_buf,32*1024,FRM,ap); \
+ va_end(ap); \
+ \
+ wchar_t wtemp_buf[32*1024]; \
+ size_t wtemp_len = 32*1024-1; \
if(!Utf8toWStr(temp_buf,temp_len,wtemp_buf,wtemp_len)) \
- return RESERR; \
+ return RESERR; \
CharToOemBuffW(&wtemp_buf[0],&temp_buf[0],wtemp_len+1);\
- fprintf(OUT,temp_buf); \
+ fprintf(OUT,temp_buf); \
}
#else
#define UTF8PRINTF(OUT,FRM,RESERR) \
@@ -317,3 +317,231 @@ uint32 CreatePIDFile(const std::string& filename);
#endif
+//handler for operations on large flags
+#ifndef _FLAG96
+#define _FLAG96
+
+class flag96
+{
+private:
+ uint32 part[3];
+public:
+ flag96(uint32 p1=0,uint32 p2=0,uint32 p3=0)
+ {
+ part[0]=p1;
+ part[1]=p2;
+ part[2]=p3;
+ }
+
+ inline bool IsEqual(uint32 p1=0, uint32 p2=0, uint32 p3=0) const
+ {
+ return (
+ part[0]==p1 &&
+ part[1]==p2 &&
+ part[2]==p3);
+ };
+
+ inline bool HasFlag(uint32 p1=0, uint32 p2=0, uint32 p3=0) const
+ {
+ return (
+ part[0]&p1 ||
+ part[1]&p2 ||
+ part[2]&p3);
+ };
+
+ inline void Set(uint32 p1=0, uint32 p2=0, uint32 p3=0)
+ {
+ part[0]=p1;
+ part[1]=p2;
+ part[2]=p3;
+ };
+
+ template<class type>
+ inline bool operator < (type & right)
+ {
+ for (uint8 i=3;i>0;i--)
+ {
+ if (part[i-1]<right.part[i-1])
+ return 1;
+ else if (part[i-1]>right.part[i-1])
+ return 0;
+ }
+ return 0;
+ };
+
+ template<class type>
+ inline bool operator < (type & right) const
+ {
+ for (uint8 i=3;i>0;i--)
+ {
+ if (part[i-1]<right.part[i-1])
+ return 1;
+ else if (part[i-1]>right.part[i-1])
+ return 0;
+ }
+ return 0;
+ };
+
+ template<class type>
+ inline bool operator != (type & right)
+ {
+ if (part[0]!=right.part[0]
+ || part[1]!=right.part[1]
+ || part[2]!=right.part[2])
+ return true;
+ return false;
+ }
+
+ template<class type>
+ inline bool operator != (type & right) const
+ {
+ if (part[0]!=right.part[0]
+ || part[1]!=right.part[1]
+ || part[2]!=right.part[2])
+ return true;
+ return false;
+ };
+
+ template<class type>
+ inline bool operator == (type & right)
+ {
+ if (part[0]!=right.part[0]
+ || part[1]!=right.part[1]
+ || part[2]!=right.part[2])
+ return false;
+ return true;
+ };
+
+ template<class type>
+ inline bool operator == (type & right) const
+ {
+ if (part[0]!=right.part[0]
+ || part[1]!=right.part[1]
+ || part[2]!=right.part[2])
+ return false;
+ return true;
+ };
+
+ template<class type>
+ inline void operator = (type & right)
+ {
+ part[0]=right.part[0];
+ part[1]=right.part[1];
+ part[2]=right.part[2];
+ };
+
+ template<class type>
+ inline flag96 operator & (type & right)
+ {
+ flag96 ret(part[0] & right.part[0],part[1] & right.part[1],part[2] & right.part[2]);
+ return
+ ret;
+ };
+ template<class type>
+ inline flag96 operator & (type & right) const
+ {
+ flag96 ret(part[0] & right.part[0],part[1] & right.part[1],part[2] & right.part[2]);
+ return
+ ret;
+ };
+
+ template<class type>
+ inline void operator &= (type & right)
+ {
+ *this=*this & right;
+ };
+
+ template<class type>
+ inline flag96 operator | (type & right)
+ {
+ flag96 ret(part[0] | right.part[0],part[1] | right.part[1],part[2] | right.part[2]);
+ return
+ ret;
+ };
+
+ template<class type>
+ inline flag96 operator | (type & right) const
+ {
+ flag96 ret(part[0] | right.part[0],part[1] | right.part[1],part[2] | right.part[2]);
+ return
+ ret;
+ };
+
+ template<class type>
+ inline void operator |= (type & right)
+ {
+ *this=*this | right;
+ };
+
+ inline void operator ~ ()
+ {
+ part[2]=~part[2];
+ part[1]=~part[1];
+ part[0]=~part[0];
+ };
+
+ template<class type>
+ inline flag96 operator ^ (type & right)
+ {
+ flag96 ret(part[0] ^ right.part[0],part[1] ^ right.part[1],part[2] ^ right.part[2]);
+ return
+ ret;
+ };
+
+ template<class type>
+ inline flag96 operator ^ (type & right) const
+ {
+ flag96 ret(part[0] ^ right.part[0],part[1] ^ right.part[1],part[2] ^ right.part[2]);
+ return
+ ret;
+ };
+
+ template<class type>
+ inline void operator ^= (type & right)
+ {
+ *this=*this^right;
+ };
+
+ inline operator bool() const
+ {
+ return(
+ part[0] != 0 ||
+ part[1] != 0 ||
+ part[2] != 0);
+ };
+
+ inline operator bool()
+ {
+ return(
+ part[0] != 0 ||
+ part[1] != 0 ||
+ part[2] != 0);
+ };
+
+ inline bool operator ! () const
+ {
+ return(
+ part[0] == 0 &&
+ part[1] == 0 &&
+ part[2] == 0);
+ };
+
+ inline bool operator ! ()
+ {
+ return(
+ part[0] == 0 &&
+ part[1] == 0 &&
+ part[2] == 0);
+ };
+
+ inline uint32 & operator[](uint8 el)
+ {
+ return (part[el]);
+ };
+
+ inline const uint32 & operator[](uint8 el) const
+ {
+ return (part[el]);
+ };
+};
+#endif
diff --git a/src/shared/WorldPacket.h b/src/shared/WorldPacket.h
index 8849b790f01..1eb3f12dd86 100644
--- a/src/shared/WorldPacket.h
+++ b/src/shared/WorldPacket.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/BaseModel.cpp b/src/shared/vmap/BaseModel.cpp
index f4bf13bc558..2ffd5672218 100644
--- a/src/shared/vmap/BaseModel.cpp
+++ b/src/shared/vmap/BaseModel.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/BaseModel.h b/src/shared/vmap/BaseModel.h
index 6c17f704692..098e1d9381b 100644
--- a/src/shared/vmap/BaseModel.h
+++ b/src/shared/vmap/BaseModel.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/CoordModelMapping.cpp b/src/shared/vmap/CoordModelMapping.cpp
index 319e7bb8c31..86e3347a614 100644
--- a/src/shared/vmap/CoordModelMapping.cpp
+++ b/src/shared/vmap/CoordModelMapping.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -21,6 +21,7 @@
#include "CoordModelMapping.h"
#include <string.h>
+#include <cstdio>
using namespace G3D;
@@ -87,63 +88,65 @@ namespace VMAP
bool CoordModelMapping::readCoordinateMapping(const std::string& pDirectoryFileName)
{
FILE *f = fopen(pDirectoryFileName.c_str(), "rb");
- bool result = false;
+ if(!f)
+ {
+ printf("ERROR: Can't open file: %s\n",pDirectoryFileName.c_str());
+ return false;
+ }
+
char buffer[500+1];
- if(f)
+ CMappingEntry* cMappingEntry;
+ while(fgets(buffer, 500, f))
{
- result = true;
- CMappingEntry* cMappingEntry;
- while(fgets(buffer, 500, f))
- {
- //char namebuffer[500];
- char positionbuffer[500];
- int xpos, ypos, noVec;
- float scale;
- xpos = ypos = noVec = 0;
+ //char namebuffer[500];
+ char positionbuffer[500];
+ int xpos, ypos, noVec;
+ float scale;
+ xpos = ypos = noVec = 0;
- //sscanf(buffer, "%d %d %s %s %f %d", &xpos, &ypos, namebuffer,positionbuffer, &scale, &noVec);
+ //sscanf(buffer, "%d %d %s %s %f %d", &xpos, &ypos, namebuffer,positionbuffer, &scale, &noVec);
- // this is ugly, but the format has no read delimiter and a space could be in the first part of the name
- int nameStart = findPosChar(buffer, ' ', 2);// find the 2. space
- if(nameStart > -1 && (iFilterMethod == NULL || (*iFilterMethod)(buffer)))
+ // this is ugly, but the format has no read delimiter and a space could be in the first part of the name
+ int nameStart = findPosChar(buffer, ' ', 2);// find the 2. space
+ if(nameStart > -1 && (iFilterMethod == NULL || (*iFilterMethod)(buffer)))
+ {
+ ++nameStart;
+ // find the 1. / (now a space only can be found at the end of the name)
+ int nameEnd = nameStart + findPosChar(&buffer[nameStart], '/', 1);
+ // find the 1. space (after the name)
+ nameEnd += findPosChar(&buffer[nameEnd], ' ', 1);
+ buffer[nameEnd] = 0; // terminate the name
+
+ sscanf(buffer, "%d %d", &xpos, &ypos);
+ sscanf(&buffer[nameEnd+1], "%s %f %d", positionbuffer, &scale, &noVec);
+ unsigned int mapId = getMapIdFromFilename(std::string(&buffer[nameStart]));
+ if(!iMapIds.contains(mapId))
{
- ++nameStart;
- // find the 1. / (now a space only can be found at the end of the name)
- int nameEnd = nameStart + findPosChar(&buffer[nameStart], '/', 1);
- // find the 1. space (after the name)
- nameEnd += findPosChar(&buffer[nameEnd], ' ', 1);
- buffer[nameEnd] = 0; // terminate the name
-
- sscanf(buffer, "%d %d", &xpos, &ypos);
- sscanf(&buffer[nameEnd+1], "%s %f %d", positionbuffer, &scale, &noVec);
- unsigned int mapId = getMapIdFromFilename(std::string(&buffer[nameStart]));
- if(!iMapIds.contains(mapId))
- {
- iMapIds.append(mapId);
- }
- if(!isWorldAreaMap(mapId))
- {
- xpos = 0; // store all files under the groupKey
- ypos = 0;
- }
-
- std::string key = CMappingEntry::getKeyString(mapId, xpos, ypos);
- cMappingEntry = getCMappingEntry(key);
- if(cMappingEntry == 0)
- {
- cMappingEntry = new CMappingEntry(mapId, xpos, ypos);
- addCMappingEntry(cMappingEntry);
- }
- char namebuffer2[500];
- sprintf(namebuffer2, "%d %s#%s_%f", noVec, &buffer[nameStart], positionbuffer, scale);
- cMappingEntry->addFilename(namebuffer2);
- //break;
+ iMapIds.append(mapId);
+ printf("Coords for map %u...\n",mapId);
}
+ if(!isWorldAreaMap(mapId))
+ {
+ xpos = 0; // store all files under the groupKey
+ ypos = 0;
+ }
+
+ std::string key = CMappingEntry::getKeyString(mapId, xpos, ypos);
+ cMappingEntry = getCMappingEntry(key);
+ if(cMappingEntry == 0)
+ {
+ cMappingEntry = new CMappingEntry(mapId, xpos, ypos);
+ addCMappingEntry(cMappingEntry);
+ }
+ char namebuffer2[500];
+ sprintf(namebuffer2, "%d %s#%s_%f", noVec, &buffer[nameStart], positionbuffer, scale);
+ cMappingEntry->addFilename(namebuffer2);
+ //break;
}
- fclose(f);
}
- return result;
+ fclose(f);
+ return true;
}
//============================================================
diff --git a/src/shared/vmap/CoordModelMapping.h b/src/shared/vmap/CoordModelMapping.h
index cfaa600ee81..c1f49462962 100644
--- a/src/shared/vmap/CoordModelMapping.h
+++ b/src/shared/vmap/CoordModelMapping.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -21,6 +21,7 @@
#ifndef _COORDMODELMAPPING_H_
#define _COORDMODELMAPPING_H_
+#include <cstdio>
#include <G3D/Table.h>
#include <G3D/Array.h>
diff --git a/src/shared/vmap/DebugCmdLogger.cpp b/src/shared/vmap/DebugCmdLogger.cpp
index 2552a16acc2..e6b36572c45 100644
--- a/src/shared/vmap/DebugCmdLogger.cpp
+++ b/src/shared/vmap/DebugCmdLogger.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -18,6 +18,8 @@
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
+#include <cstdio>
+
#include "DebugCmdLogger.h"
using namespace G3D;
diff --git a/src/shared/vmap/DebugCmdLogger.h b/src/shared/vmap/DebugCmdLogger.h
index a194d335381..5493ab6f332 100644
--- a/src/shared/vmap/DebugCmdLogger.h
+++ b/src/shared/vmap/DebugCmdLogger.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/IVMapManager.h b/src/shared/vmap/IVMapManager.h
index 01aef4b9d4c..243a15aef73 100644
--- a/src/shared/vmap/IVMapManager.h
+++ b/src/shared/vmap/IVMapManager.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/Makefile.am b/src/shared/vmap/Makefile.am
new file mode 100644
index 00000000000..483a926c907
--- /dev/null
+++ b/src/shared/vmap/Makefile.am
@@ -0,0 +1,58 @@
+# Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
+#
+# Copyright (C) 2008-2009 Trinity <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, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+## Process this file with automake to produce Makefile.in
+
+## Sub-directories to parse
+
+## CPP flags for includes, defines, etc.
+AM_CPPFLAGS = $(TRINI_INCLUDES) -I$(top_builddir)/src/shared -I$(srcdir) -I$(srcdir)/../../../dep/include -I$(srcdir)/../../framework -I$(srcdir)/../../shared -I$(srcdir)/../../../dep/include/g3dlite
+
+## Build MaNGOS shared library and its parts as convenience library.
+# All libraries will be convenience libraries. Might be changed to shared
+# later.
+noinst_LIBRARIES = libmangosvmaps.a
+
+libmangosvmaps_a_SOURCES = \
+ AABSPTree.h \
+ BaseModel.cpp \
+ BaseModel.h \
+ CoordModelMapping.cpp \
+ CoordModelMapping.h \
+ DebugCmdLogger.cpp \
+ DebugCmdLogger.h \
+ IVMapManager.h \
+ ManagedModelContainer.cpp \
+ ManagedModelContainer.h \
+ ModelContainer.cpp \
+ ModelContainer.h \
+ NodeValueAccess.h \
+ ShortBox.h \
+ ShortVector.h \
+ SubModel.cpp \
+ SubModel.h \
+ TileAssembler.cpp \
+ TileAssembler.h \
+ TreeNode.cpp \
+ TreeNode.h \
+ VMapDefinitions.h \
+ VMapFactory.cpp \
+ VMapFactory.h \
+ VMapManager.cpp \
+ VMapManager.h \
+ VMapTools.h
diff --git a/src/shared/vmap/ManagedModelContainer.cpp b/src/shared/vmap/ManagedModelContainer.cpp
index 1362002bafd..c7bfefe7179 100644
--- a/src/shared/vmap/ManagedModelContainer.cpp
+++ b/src/shared/vmap/ManagedModelContainer.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/ManagedModelContainer.h b/src/shared/vmap/ManagedModelContainer.h
index 33c675d0806..e6862f915c7 100644
--- a/src/shared/vmap/ManagedModelContainer.h
+++ b/src/shared/vmap/ManagedModelContainer.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/ModelContainer.cpp b/src/shared/vmap/ModelContainer.cpp
index 9eb100161d8..4a722d2585b 100644
--- a/src/shared/vmap/ModelContainer.cpp
+++ b/src/shared/vmap/ModelContainer.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/ModelContainer.h b/src/shared/vmap/ModelContainer.h
index 9613bf53d96..abc96261050 100644
--- a/src/shared/vmap/ModelContainer.h
+++ b/src/shared/vmap/ModelContainer.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/NodeValueAccess.h b/src/shared/vmap/NodeValueAccess.h
index e14a6dba676..54fc5ee99b6 100644
--- a/src/shared/vmap/NodeValueAccess.h
+++ b/src/shared/vmap/NodeValueAccess.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/ShortBox.h b/src/shared/vmap/ShortBox.h
index bffca0d806d..0e98677aa9e 100644
--- a/src/shared/vmap/ShortBox.h
+++ b/src/shared/vmap/ShortBox.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/ShortVector.h b/src/shared/vmap/ShortVector.h
index f7dd0f74859..5f0fb7d9fd8 100644
--- a/src/shared/vmap/ShortVector.h
+++ b/src/shared/vmap/ShortVector.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/SubModel.cpp b/src/shared/vmap/SubModel.cpp
index c6022d2ed69..370c80062d6 100644
--- a/src/shared/vmap/SubModel.cpp
+++ b/src/shared/vmap/SubModel.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/SubModel.h b/src/shared/vmap/SubModel.h
index c52dc7f5c51..89ea9b91d7b 100644
--- a/src/shared/vmap/SubModel.h
+++ b/src/shared/vmap/SubModel.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/TileAssembler.cpp b/src/shared/vmap/TileAssembler.cpp
index bb73a2ba241..cbaa4e58108 100644
--- a/src/shared/vmap/TileAssembler.cpp
+++ b/src/shared/vmap/TileAssembler.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
@@ -75,12 +75,12 @@ namespace VMAP
addWorldAreaMapId(0); //Azeroth
addWorldAreaMapId(1); //Kalimdor
addWorldAreaMapId(530); //Expansion01
+ addWorldAreaMapId(571); //Expansion02
}
//=================================================================
std::string getModNameFromModPosName(const std::string& pModPosName)
{
-
size_t spos = pModPosName.find_first_of('#');
std::string modelFileName = pModPosName.substr(0,spos);
return(modelFileName);
@@ -142,7 +142,6 @@ namespace VMAP
//=================================================================
bool TileAssembler::convertWorld()
{
-
#ifdef _ASSEMBLER_DEBUG
# ifdef _DEBUG
::g_df = fopen("../TileAssembler_debug.txt", "wb");
@@ -151,424 +150,454 @@ namespace VMAP
# endif
#endif
- bool result = true;
std::string fname = iSrcDir;
fname.append("/");
fname.append("dir");
iCoordModelMapping->setModelNameFilterMethod(iFilterMethod);
- iCoordModelMapping->readCoordinateMapping(fname);
+
+ printf("Read coordinate mapping...\n");
+ if(!iCoordModelMapping->readCoordinateMapping(fname))
+ return false;
Array<unsigned int> mapIds = iCoordModelMapping->getMaps();
if(mapIds.size() == 0)
{
- result = false;
+ printf("Fatal error: empty map list!\n");
+ return false;
}
- for(int i=0; i<mapIds.size() && result; ++i)
+
+ for(int i=0; i<mapIds.size(); ++i)
{
unsigned int mapId = mapIds[i];
#ifdef _ASSEMBLER_DEBUG
if(mapId == 0) // "Azeroth" just for debug
{
- for(int x=28; x<29 && result; ++x) //debug
+ for(int x=28; x<29; ++x) //debug
{
- for(int y=28; y<29 && result; ++y)
+ for(int y=28; y<29; ++y)
{
- #else
- // ignore DeeprunTram (369) it is too large for short vector and not important
- // ignore test (13), Test (29) , development (451)
- if(mapId != 369 && mapId != 13 && mapId != 29 && mapId != 451)
+ #else
+ // ignore DeeprunTram (369) it is too large for short vector and not important
+ // ignore test (13), Test (29) , development (451)
+ if(mapId != 369 && mapId != 13 && mapId != 29 && mapId != 451)
+ {
+ for(int x=0; x<66; ++x)
+ {
+ for(int y=0; y<66; ++y)
+ {
+ #endif
+ Array<ModelContainer*> mc;
+ std::string dirname;
+ char buffer[100];
+ if(iCoordModelMapping->isWorldAreaMap(mapId) && x<65 && y<65)
{
- for(int x=0; x<66 && result; ++x)
- {
- for(int y=0; y<66 && result; ++y)
- {
- #endif
- Array<ModelContainer*> mc;
- std::string dirname;
- char buffer[100];
- if(iCoordModelMapping->isWorldAreaMap(mapId) && x<65 && y<65)
- {
- sprintf(buffer, "%03u_%d_%d",mapId,y,x); // Let's flip x and y here
- dirname = std::string(buffer);
- }
- else
- {
- sprintf(buffer, "%03u",mapId);
- dirname = std::string(buffer);
- }
- result = fillModelContainerArray(dirname, mapId, x, y, mc);
- emptyArray(mc);
- }
- }
+ sprintf(buffer, "%03u_%d_%d",mapId,y,x); // Let's flip x and y here
+ dirname = std::string(buffer);
+ printf("%s...\n",dirname.c_str());
}
- }
- #ifdef _ASSEMBLER_DEBUG
- if(::g_df) fclose(::g_df);
- #endif
-
- return result;
- }
+ else
+ {
+ sprintf(buffer, "%03u",mapId);
+ dirname = std::string(buffer);
- //=================================================================
+ // prevent spam for small maps
+ if(x==0 && y==0)
+ printf("%s...\n",dirname.c_str());
+ }
- bool TileAssembler::fillModelContainerArray(const std::string& pDirFileName, unsigned int pMapId, int pXPos, int pYPos, Array<ModelContainer*>& pMC)
- {
- bool result = true;
- ModelContainer* modelContainer;
+ bool result = fillModelContainerArray(dirname, mapId, x, y, mc);
+ emptyArray(mc);
- NameCollection nameCollection = iCoordModelMapping->getFilenamesForCoordinate(pMapId, pXPos, pYPos);
- if(nameCollection.size() > 0)
- {
- result = false;
- char dirfilename[500];
- sprintf(dirfilename,"%s/%s.vmdir",iDestDir.c_str(),pDirFileName.c_str());
- FILE *dirfile = fopen(dirfilename, "ab");
- if(dirfile)
- {
- result = true;
- char destnamebuffer[500];
- char fullnamedestnamebuffer[500];
- if(nameCollection.iMainFiles.size() >0)
- {
- sprintf(destnamebuffer,"%03u_%i_%i.vmap",pMapId, pYPos, pXPos); // flip it here too
- std::string checkDoubleStr = std::string(dirfilename);
- checkDoubleStr.append("##");
- checkDoubleStr.append(std::string(destnamebuffer));
- // Check, if same file already is in the same dir file
- if(!iCoordModelMapping->isAlreadyProcessedSingleFile(checkDoubleStr))
- {
- iCoordModelMapping->addAlreadyProcessedSingleFile(checkDoubleStr);
- fprintf(dirfile, "%s\n",destnamebuffer);
- sprintf(fullnamedestnamebuffer,"%s/%s",iDestDir.c_str(),destnamebuffer);
- modelContainer = processNames(nameCollection.iMainFiles, fullnamedestnamebuffer);
- if(modelContainer)
- {
- pMC.append(modelContainer);
- }
- else
- {
- result = false;
- }
- }
- }
- // process the large singe files
- int pos = 0;
- while(result && (pos < nameCollection.iSingeFiles.size()))
- {
- std::string destFileName = iDestDir;
- destFileName.append("/");
- std::string dirEntryName = getDirEntryNameFromModName(pMapId,nameCollection.iSingeFiles[pos]);
- std::string checkDoubleStr = std::string(dirfilename);
- checkDoubleStr.append("##");
- checkDoubleStr.append(nameCollection.iSingeFiles[pos]);
- // Check, if same file already is in the same dir file
- if(!iCoordModelMapping->isAlreadyProcessedSingleFile(checkDoubleStr))
- {
- iCoordModelMapping->addAlreadyProcessedSingleFile(checkDoubleStr);
- fprintf(dirfile, "%s\n",dirEntryName.c_str());
- destFileName.append(dirEntryName);
-
- Array<std::string> positionarray;
- positionarray.append(nameCollection.iSingeFiles[pos]);
-
- if(!iCoordModelMapping->isAlreadyProcessedSingleFile(nameCollection.iSingeFiles[pos]))
- {
- modelContainer = processNames(positionarray, destFileName.c_str());
- iCoordModelMapping->addAlreadyProcessedSingleFile(nameCollection.iSingeFiles[pos]);
- if(modelContainer)
- {
- pMC.append(modelContainer);
- }
- else
- {
- result = false;
- }
- }
- }
- ++pos;
- }
- fclose(dirfile);
- }
+ if(!result)
+ return false;
}
- return(result);
}
+ }
+ }
+ #ifdef _ASSEMBLER_DEBUG
+ if(::g_df) fclose(::g_df);
+ #endif
- //=================================================================
+ return true;
+ }
+
+ //=================================================================
+
+ bool TileAssembler::fillModelContainerArray(const std::string& pDirFileName, unsigned int pMapId, int pXPos, int pYPos, Array<ModelContainer*>& pMC)
+ {
+ ModelContainer* modelContainer;
- void removeEntriesFromTree(AABSPTree<SubModel *>* pTree)
+ NameCollection nameCollection = iCoordModelMapping->getFilenamesForCoordinate(pMapId, pXPos, pYPos);
+ if(nameCollection.size() == 0)
+ return true; // no data...
+
+ char dirfilename[500];
+ sprintf(dirfilename,"%s/%s.vmdir",iDestDir.c_str(),pDirFileName.c_str());
+ FILE *dirfile = fopen(dirfilename, "ab");
+ if(!dirfile)
+ {
+ printf("ERROR: Can't create file %s",dirfilename);
+ return false;
+ }
+
+ char destnamebuffer[500];
+ char fullnamedestnamebuffer[500];
+
+ if(nameCollection.iMainFiles.size() >0)
+ {
+ sprintf(destnamebuffer,"%03u_%i_%i.vmap",pMapId, pYPos, pXPos); // flip it here too
+ std::string checkDoubleStr = std::string(dirfilename);
+ checkDoubleStr.append("##");
+ checkDoubleStr.append(std::string(destnamebuffer));
+ // Check, if same file already is in the same dir file
+ if(!iCoordModelMapping->isAlreadyProcessedSingleFile(checkDoubleStr))
+ {
+ iCoordModelMapping->addAlreadyProcessedSingleFile(checkDoubleStr);
+ fprintf(dirfile, "%s\n",destnamebuffer);
+ sprintf(fullnamedestnamebuffer,"%s/%s",iDestDir.c_str(),destnamebuffer);
+ modelContainer = processNames(nameCollection.iMainFiles, fullnamedestnamebuffer);
+ if(modelContainer)
+ pMC.append(modelContainer);
+ else
+ printf("warning: (if) problems in processing data for %s\n",destnamebuffer);
+ }
+ }
+ // process the large singe files
+ int pos = 0;
+ while(pos < nameCollection.iSingeFiles.size())
+ {
+ std::string destFileName = iDestDir;
+ destFileName.append("/");
+ std::string dirEntryName = getDirEntryNameFromModName(pMapId,nameCollection.iSingeFiles[pos]);
+ std::string checkDoubleStr = std::string(dirfilename);
+ checkDoubleStr.append("##");
+ checkDoubleStr.append(nameCollection.iSingeFiles[pos]);
+ // Check, if same file already is in the same dir file
+ if(!iCoordModelMapping->isAlreadyProcessedSingleFile(checkDoubleStr))
+ {
+ iCoordModelMapping->addAlreadyProcessedSingleFile(checkDoubleStr);
+ fprintf(dirfile, "%s\n",dirEntryName.c_str());
+ destFileName.append(dirEntryName);
+
+ Array<std::string> positionarray;
+ positionarray.append(nameCollection.iSingeFiles[pos]);
+
+ if(!iCoordModelMapping->isAlreadyProcessedSingleFile(nameCollection.iSingeFiles[pos]))
{
- Array<SubModel *> submodelArray;
- pTree->getMembers(submodelArray);
- int no = submodelArray.size();
- while(no > 0)
- {
- --no;
- delete submodelArray[no];
- }
+ modelContainer = processNames(positionarray, destFileName.c_str());
+ iCoordModelMapping->addAlreadyProcessedSingleFile(nameCollection.iSingeFiles[pos]);
+ if(modelContainer)
+ pMC.append(modelContainer);
+ else
+ printf("warning: (while) problems in processing data for %s\n",destFileName.c_str());
}
+ }
+ ++pos;
+ }
- //=================================================================
+ fclose(dirfile);
+ return true;
+ }
- ModelContainer* TileAssembler::processNames(const Array<std::string>& pPositions, const char* pDestFileName)
- {
- ModelContainer *modelContainer = 0;
+ //=================================================================
- Vector3 basepos = Vector3(0,0,0);
- AABSPTree<SubModel *>* mainTree = new AABSPTree<SubModel *>();
+ void removeEntriesFromTree(AABSPTree<SubModel *>* pTree)
+ {
+ Array<SubModel *> submodelArray;
+ pTree->getMembers(submodelArray);
+ int no = submodelArray.size();
+ while(no > 0)
+ {
+ --no;
+ delete submodelArray[no];
+ }
+ }
- int pos = 0;
+ //=================================================================
- bool result = true;
- while(result && (pos < pPositions.size()))
- {
- std::string modelPosString = pPositions[pos];
- std::string modelFileName = getModNameFromModPosName(modelPosString);
+ ModelContainer* TileAssembler::processNames(const Array<std::string>& pPositions, const char* pDestFileName)
+ {
+ ModelContainer *modelContainer = 0;
- if(!fillModelIntoTree(mainTree, basepos, modelPosString, modelFileName))
- {
- result = false;
- break;
- }
- ++pos;
- }
- if(result && mainTree->size() > 0)
- {
- mainTree->balance();
- modelContainer = new ModelContainer(mainTree);
- modelContainer->writeFile(pDestFileName);
- }
- removeEntriesFromTree(mainTree);
+ Vector3 basepos = Vector3(0,0,0);
+ AABSPTree<SubModel *>* mainTree = new AABSPTree<SubModel *>();
- delete mainTree;
+ int pos = 0;
- return(modelContainer);
- }
+ bool result = true;
+ while(result && (pos < pPositions.size()))
+ {
+ std::string modelPosString = pPositions[pos];
+ std::string modelFileName = getModNameFromModPosName(modelPosString);
- //=================================================================
- bool TileAssembler::readRawFile(std::string& pModelFilename, ModelPosition& pModelPosition, AABSPTree<SubModel *> *pMainTree)
- {
- bool result = false;
-
- std::string filename = iSrcDir;
- if(filename.length() >0)
- filename.append("/");
- filename.append(pModelFilename);
- FILE *rf = fopen(filename.c_str(), "rb");
- if(!rf)
- {
- // depending on the extractor version, the data could be located in the root dir
- std::string baseModelFilename = pModelFilename.substr((pModelFilename.find_first_of("/")+1),pModelFilename.length());
- filename = iSrcDir;
- if(filename.length() >0)
- filename.append("/");
- filename.append(baseModelFilename);
- rf = fopen(filename.c_str(), "rb");
- }
- char ident[8];
-
- int trianglecount =0;
-
- #ifdef _ASSEMBLER_DEBUG
- int startgroup = 0; //2;
- int endgroup = INT_MAX; //2;
- fprintf(::g_df,"-------------------------------------------------\n");
- fprintf(::g_df,"%s\n", pModelFilename.c_str());
- fprintf(::g_df,"-------------------------------------------------\n");
- #else
- int startgroup = 0;
- int endgroup = INT_MAX;
- #endif
-
- if(rf)
- {
- if(fread(&ident, 8, 1, rf) != 1) { fclose(rf); return(false); }
- if(strcmp(ident, "VMAP001") == 0)
- {
- // OK, do nothing
- }
- else if(strcmp(ident, "VMAP002") == 0)
- {
- // we have to read one int. This is needed during the export and we have to skip it here
- int tempNVectors;
- if(fread(&tempNVectors, sizeof(int), 1, rf) != 1) { fclose(rf); return(false); }
+ if(!fillModelIntoTree(mainTree, basepos, modelPosString, modelFileName))
+ {
+ result = false;
+ break;
+ }
+ ++pos;
+ }
+ if(result && mainTree->size() > 0)
+ {
+ mainTree->balance();
+ modelContainer = new ModelContainer(mainTree);
+ modelContainer->writeFile(pDestFileName);
+ }
+ removeEntriesFromTree(mainTree);
- }
- else
- {
- // wrong version
- fclose(rf);
- return(false);
- }
- G3D::uint32 groups;
- char blockId[5];
- blockId[4] = 0;
- int blocksize;
+ delete mainTree;
- if(fread(&groups, sizeof(G3D::uint32), 1, rf) != 1) { fclose(rf); return(false); }
+ return(modelContainer);
+ }
- for(int g=0;g<(int)groups;g++)
- {
- // group MUST NOT have more then 65536 indexes !! Array will have a problem with that !! (strange ...)
- Array<int> tempIndexArray;
- Array<Vector3> tempVertexArray;
-
- AABSPTree<Triangle> *gtree = new AABSPTree<Triangle>();
-
- G3D::uint32 flags;
- if(fread(&flags, sizeof(G3D::uint32), 1, rf) != 1) { fclose(rf); delete gtree; return(false); }
-
- G3D::uint32 branches;
- if(fread(&blockId, 4, 1, rf) != 1) { fclose(rf); delete gtree; return(false); }
- if(strcmp(blockId, "GRP ") != 0) { fclose(rf); delete gtree; return(false); }
- if(fread(&blocksize, sizeof(int), 1, rf) != 1) { fclose(rf); delete gtree; return(false); }
- if(fread(&branches, sizeof(G3D::uint32), 1, rf) != 1) { fclose(rf); delete gtree; return(false); }
- for(int b=0;b<(int)branches; b++)
- {
- G3D::uint32 indexes;
- // indexes for each branch (not used jet)
- if(fread(&indexes, sizeof(G3D::uint32), 1, rf) != 1) { fclose(rf); delete gtree; return(false); }
- }
-
- // ---- indexes
- if(fread(&blockId, 4, 1, rf) != 1) { fclose(rf); delete gtree; return(false); }
- if(strcmp(blockId, "INDX") != 0) { fclose(rf); delete gtree; return(false); }
- if(fread(&blocksize, sizeof(int), 1, rf) != 1) { fclose(rf); delete gtree; return(false); }
- unsigned int nindexes;
- if(fread(&nindexes, sizeof(G3D::uint32), 1, rf) != 1) { fclose(rf); return(false); }
- if(nindexes >0)
- {
- unsigned short *indexarray = new unsigned short[nindexes*sizeof(unsigned short)];
- if(fread(indexarray, sizeof(unsigned short), nindexes, rf) != nindexes) { fclose(rf); delete gtree; delete[] indexarray; return(false); }
- for(int i=0;i<(int)nindexes; i++)
- {
- unsigned short val = indexarray[i];
- tempIndexArray.append(val);
- }
- delete[] indexarray;
- }
-
- // ---- vectors
- if(fread(&blockId, 4, 1, rf) != 1) {fclose(rf); delete gtree; return(false); }
- if(strcmp(blockId, "VERT") != 0) { fclose(rf); delete gtree; return(false); }
- if(fread(&blocksize, sizeof(int), 1, rf) != 1) { fclose(rf); delete gtree; return(false); }
- unsigned int nvectors;
- if(fread(&nvectors, sizeof(int), 1, rf) != 1) { fclose(rf); delete gtree; return(false); }
- float *vectorarray = 0;
- if(nvectors >0)
- {
- vectorarray = new float[nvectors*sizeof(float)*3];
- if(fread(vectorarray, sizeof(float)*3, nvectors, rf) != nvectors) { fclose(rf); delete gtree; delete[] vectorarray; return(false); }
- }
- // ----- liquit
- if(flags & 1)
- {
- // we have liquit -> not handled yet ... skip
- if(fread(&blockId, 4, 1, rf) != 1) { fclose(rf); delete gtree; delete[] vectorarray; return(false); }
- if(strcmp(blockId, "LIQU") != 0) { fclose(rf); delete gtree; delete[] vectorarray; return(false); }
- if(fread(&blocksize, sizeof(int), 1, rf) != 1) { fclose(rf); delete gtree; delete[] vectorarray; return(false); }
- fseek(rf, blocksize, SEEK_CUR);
- }
-
- for(unsigned int i=0, indexNo=0; indexNo<nvectors; indexNo++)
- {
- Vector3 v = Vector3(vectorarray[i+2], vectorarray[i+1], vectorarray[i+0]);
- i+=3;
- v = pModelPosition.transform(v);
-
- float swapy = v.y;
- v.y = v.x;
- v.x = swapy;
-
- tempVertexArray.append(v);
- }
-
- // ---- calculate triangles
- int rest = nindexes%3;
- if(rest != 0)
- {
- nindexes -= rest;
- }
-
- for(unsigned int i=0;i<(nindexes);)
- {
- Triangle t = Triangle(tempVertexArray[tempIndexArray[i+2]], tempVertexArray[tempIndexArray[i+1]], tempVertexArray[tempIndexArray[i+0]] );
- i+=3;
- ++trianglecount;
- if(g>= startgroup && g <= endgroup)
- {
- gtree->insert(t);
- }
- }
-
- if(vectorarray != 0)
- {
- delete vectorarray;
- }
-
- if(gtree->size() >0)
- {
- gtree->balance();
- SubModel *sm = new SubModel(gtree);
- #ifdef _ASSEMBLER_DEBUG
- if(::g_df) fprintf(::g_df,"group trianglies: %d, Tris: %d, Nodes: %d, gtree.triangles: %d\n", g, sm->getNTriangles(), sm->getNNodes(), gtree->memberTable.size());
- if(sm->getNTriangles() != gtree->memberTable.size())
- {
- if(::g_df) fprintf(::g_df,"ERROR !!!! group trianglies: %d, Tris: %d, Nodes: %d, gtree.triangles: %d\n", g, sm->getNTriangles(), sm->getNNodes(), gtree->memberTable.size());
- }
- #endif
- sm->setBasePosition(pModelPosition.iPos);
- pMainTree->insert(sm);
- }
- delete gtree;
- }
- fclose(rf);
- result = true;
- }
- return(result);
- }
+ //=================================================================
+ bool TileAssembler::readRawFile(std::string& pModelFilename, ModelPosition& pModelPosition, AABSPTree<SubModel *> *pMainTree)
+ {
+ std::string filename = iSrcDir;
+ if(filename.length() >0)
+ filename.append("/");
+ filename.append(pModelFilename);
+ FILE *rf = fopen(filename.c_str(), "rb");
+ if(!rf)
+ {
+ // depending on the extractor version, the data could be located in the root dir
+ std::string baseModelFilename = pModelFilename.substr((pModelFilename.find_first_of("/")+1),pModelFilename.length());
+ filename = iSrcDir;
+ if(filename.length() >0)
+ filename.append("/");
+ filename.append(baseModelFilename);
+ rf = fopen(filename.c_str(), "rb");
+ }
+
+ if(!rf)
+ {
+ printf("ERROR: Can't open model file in form: %s",pModelFilename.c_str());
+ printf("... or form: %s",filename.c_str() );
+ return false;
+ }
+
+ char ident[8];
+
+ int trianglecount =0;
+
+ #ifdef _ASSEMBLER_DEBUG
+ int startgroup = 0; //2;
+ int endgroup = INT_MAX; //2;
+ fprintf(::g_df,"-------------------------------------------------\n");
+ fprintf(::g_df,"%s\n", pModelFilename.c_str());
+ fprintf(::g_df,"-------------------------------------------------\n");
+ #else
+ int startgroup = 0;
+ int endgroup = INT_MAX;
+ #endif
+
+ // temporary use defines to simplify read/check code (close file and return at fail)
+ #define READ_OR_RETURN(V,S) if(fread((V), (S), 1, rf) != 1) { \
+ fclose(rf); return(false); }
+ #define CMP_OR_RETURN(V,S) if(strcmp((V),(S)) != 0) { \
+ fclose(rf); return(false); }
+
+ READ_OR_RETURN(&ident, 8);
+ if(strcmp(ident, "VMAP001") == 0)
+ {
+ // OK, do nothing
+ }
+ else if(strcmp(ident, "VMAP002") == 0)
+ {
+ // we have to read one int. This is needed during the export and we have to skip it here
+ int tempNVectors;
+ READ_OR_RETURN(&tempNVectors, sizeof(int));
+
+ }
+ else
+ {
+ // wrong version
+ fclose(rf);
+ return(false);
+ }
+ G3D::uint32 groups;
+ char blockId[5];
+ blockId[4] = 0;
+ int blocksize;
- //=================================================================
+ READ_OR_RETURN(&groups, sizeof(G3D::uint32));
- bool TileAssembler::fillModelIntoTree(AABSPTree<SubModel *> *pMainTree, const Vector3& pBasePos, std::string& pPos, std::string& pModelFilename)
+ for(int g=0;g<(int)groups;g++)
+ {
+ // group MUST NOT have more then 65536 indexes !! Array will have a problem with that !! (strange ...)
+ Array<int> tempIndexArray;
+ Array<Vector3> tempVertexArray;
+
+ AABSPTree<Triangle> *gtree = new AABSPTree<Triangle>();
+
+ // add free gtree at fail
+ #undef READ_OR_RETURN
+ #undef CMP_OR_RETURN
+ #define READ_OR_RETURN(V,S) if(fread((V), (S), 1, rf) != 1) { \
+ fclose(rf); delete gtree; return(false); }
+ #define CMP_OR_RETURN(V,S) if(strcmp((V),(S)) != 0) { \
+ fclose(rf); delete gtree; return(false); }
+
+ G3D::uint32 flags;
+ READ_OR_RETURN(&flags, sizeof(G3D::uint32));
+
+ G3D::uint32 branches;
+ READ_OR_RETURN(&blockId, 4);
+ CMP_OR_RETURN(blockId, "GRP ");
+ READ_OR_RETURN(&blocksize, sizeof(int));
+ READ_OR_RETURN(&branches, sizeof(G3D::uint32));
+ for(int b=0;b<(int)branches; b++)
+ {
+ G3D::uint32 indexes;
+ // indexes for each branch (not used jet)
+ READ_OR_RETURN(&indexes, sizeof(G3D::uint32));
+ }
+
+ // ---- indexes
+ READ_OR_RETURN(&blockId, 4);
+ CMP_OR_RETURN(blockId, "INDX");
+ READ_OR_RETURN(&blocksize, sizeof(int));
+ unsigned int nindexes;
+ READ_OR_RETURN(&nindexes, sizeof(G3D::uint32));
+ if(nindexes >0)
+ {
+ unsigned short *indexarray = new unsigned short[nindexes*sizeof(unsigned short)];
+ READ_OR_RETURN(indexarray, nindexes*sizeof(unsigned short));
+ for(int i=0;i<(int)nindexes; i++)
{
- bool result = false;
- ModelPosition modelPosition;
- getModelPosition(pPos, modelPosition);
- // all should be relative to object base position
- modelPosition.moveToBasePos(pBasePos);
+ unsigned short val = indexarray[i];
+ tempIndexArray.append(val);
+ }
+ delete[] indexarray;
+ }
+
+ // ---- vectors
+ READ_OR_RETURN(&blockId, 4);
+ CMP_OR_RETURN(blockId, "VERT");
+ READ_OR_RETURN(&blocksize, sizeof(int));
+ unsigned int nvectors;
+ READ_OR_RETURN(&nvectors, sizeof(int));
+
+ float *vectorarray = 0;
+
+ // add vectorarray free
+ #undef READ_OR_RETURN
+ #undef CMP_OR_RETURN
+ #define READ_OR_RETURN(V,S) if(fread((V), (S), 1, rf) != 1) { \
+ fclose(rf); delete gtree; delete[] vectorarray; return(false); }
+ #define CMP_OR_RETURN(V,S) if(strcmp((V),(S)) != 0) { \
+ fclose(rf); delete gtree; delete[] vectorarray; return(false); }
+
+ if(nvectors >0)
+ {
+ vectorarray = new float[nvectors*sizeof(float)*3];
+ READ_OR_RETURN(vectorarray, nvectors*sizeof(float)*3);
+ }
+ // ----- liquit
+ if(flags & 1)
+ {
+ // we have liquit -> not handled yet ... skip
+ READ_OR_RETURN(&blockId, 4);
+ CMP_OR_RETURN(blockId, "LIQU");
+ READ_OR_RETURN(&blocksize, sizeof(int));
+ fseek(rf, blocksize, SEEK_CUR);
+ }
- modelPosition.init();
- if(readRawFile(pModelFilename, modelPosition, pMainTree))
- {
- result = true;
- }
+ for(unsigned int i=0, indexNo=0; indexNo<nvectors; indexNo++)
+ {
+ Vector3 v = Vector3(vectorarray[i+2], vectorarray[i+1], vectorarray[i+0]);
+ i+=3;
+ v = pModelPosition.transform(v);
+
+ float swapy = v.y;
+ v.y = v.x;
+ v.x = swapy;
+
+ tempVertexArray.append(v);
+ }
+
+ // ---- calculate triangles
+ int rest = nindexes%3;
+ if(rest != 0)
+ {
+ nindexes -= rest;
+ }
- return result;
+ for(unsigned int i=0;i<(nindexes);)
+ {
+ Triangle t = Triangle(tempVertexArray[tempIndexArray[i+2]], tempVertexArray[tempIndexArray[i+1]], tempVertexArray[tempIndexArray[i+0]] );
+ i+=3;
+ ++trianglecount;
+ if(g>= startgroup && g <= endgroup)
+ {
+ gtree->insert(t);
}
+ }
+
+ // drop of temporary use defines
+ #undef READ_OR_RETURN
+ #undef CMP_OR_RETURN
- //=================================================================
- void TileAssembler::getModelPosition(std::string& pPosString, ModelPosition& pModelPosition)
+ if(vectorarray != 0)
+ {
+ delete vectorarray;
+ }
+
+ if(gtree->size() >0)
+ {
+ gtree->balance();
+ SubModel *sm = new SubModel(gtree);
+ #ifdef _ASSEMBLER_DEBUG
+ if(::g_df) fprintf(::g_df,"group trianglies: %d, Tris: %d, Nodes: %d, gtree.triangles: %d\n", g, sm->getNTriangles(), sm->getNNodes(), gtree->memberTable.size());
+ if(sm->getNTriangles() != gtree->memberTable.size())
{
- float vposarray[3];
- float vdirarray[3];
- float scale;
+ if(::g_df) fprintf(::g_df,"ERROR !!!! group trianglies: %d, Tris: %d, Nodes: %d, gtree.triangles: %d\n", g, sm->getNTriangles(), sm->getNNodes(), gtree->memberTable.size());
+ }
+ #endif
+ sm->setBasePosition(pModelPosition.iPos);
+ pMainTree->insert(sm);
+ }
+ delete gtree;
+ }
+ fclose(rf);
+ return true;
+ }
+
+ //=================================================================
- size_t spos = pPosString.find_first_of('#');
- std::string stripedPosString = pPosString.substr(spos+1,pPosString.length());
+ bool TileAssembler::fillModelIntoTree(AABSPTree<SubModel *> *pMainTree, const Vector3& pBasePos, std::string& pPos, std::string& pModelFilename)
+ {
+ ModelPosition modelPosition;
+ getModelPosition(pPos, modelPosition);
+ // all should be relative to object base position
+ modelPosition.moveToBasePos(pBasePos);
- sscanf(stripedPosString.c_str(), "%f,%f,%f_%f,%f,%f_%f",
- &vposarray[0],&vposarray[1],&vposarray[2],
- &vdirarray[0],&vdirarray[1],&vdirarray[2],
- &scale);
+ modelPosition.init();
- pModelPosition.iPos = Vector3(vposarray[0], vposarray[1], vposarray[2]);
- pModelPosition.iDir = Vector3(vdirarray[0], vdirarray[1], vdirarray[2]);
- pModelPosition.iScale = scale;
+ return readRawFile(pModelFilename, modelPosition, pMainTree);
+ }
- }
- //==========================================
+ //=================================================================
+ void TileAssembler::getModelPosition(std::string& pPosString, ModelPosition& pModelPosition)
+ {
+ float vposarray[3];
+ float vdirarray[3];
+ float scale;
+
+ size_t spos = pPosString.find_first_of('#');
+ std::string stripedPosString = pPosString.substr(spos+1,pPosString.length());
- } // VMAP
+ sscanf(stripedPosString.c_str(), "%f,%f,%f_%f,%f,%f_%f",
+ &vposarray[0],&vposarray[1],&vposarray[2],
+ &vdirarray[0],&vdirarray[1],&vdirarray[2],
+ &scale);
+ pModelPosition.iPos = Vector3(vposarray[0], vposarray[1], vposarray[2]);
+ pModelPosition.iDir = Vector3(vdirarray[0], vdirarray[1], vdirarray[2]);
+ pModelPosition.iScale = scale;
+
+ }
+ //==========================================
+} // VMAP
diff --git a/src/shared/vmap/TileAssembler.h b/src/shared/vmap/TileAssembler.h
index a2fe8055fcf..d2183794a9e 100644
--- a/src/shared/vmap/TileAssembler.h
+++ b/src/shared/vmap/TileAssembler.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/TreeNode.cpp b/src/shared/vmap/TreeNode.cpp
index 113199235bf..c884f9b3b1d 100644
--- a/src/shared/vmap/TreeNode.cpp
+++ b/src/shared/vmap/TreeNode.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/TreeNode.h b/src/shared/vmap/TreeNode.h
index d71396487b9..1b9532001e5 100644
--- a/src/shared/vmap/TreeNode.h
+++ b/src/shared/vmap/TreeNode.h
@@ -1,7 +1,7 @@
/*
-* Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
-* Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+* Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/VMapDefinitions.h b/src/shared/vmap/VMapDefinitions.h
index 0800bfbda88..fd28a91d515 100644
--- a/src/shared/vmap/VMapDefinitions.h
+++ b/src/shared/vmap/VMapDefinitions.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/VMapFactory.cpp b/src/shared/vmap/VMapFactory.cpp
index 2dad2047189..5189f79daba 100644
--- a/src/shared/vmap/VMapFactory.cpp
+++ b/src/shared/vmap/VMapFactory.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/VMapFactory.h b/src/shared/vmap/VMapFactory.h
index 9a4493d8817..f3375d723c1 100644
--- a/src/shared/vmap/VMapFactory.h
+++ b/src/shared/vmap/VMapFactory.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/VMapManager.cpp b/src/shared/vmap/VMapManager.cpp
index 3b93b63086b..f5c2640be70 100644
--- a/src/shared/vmap/VMapManager.cpp
+++ b/src/shared/vmap/VMapManager.cpp
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/VMapManager.h b/src/shared/vmap/VMapManager.h
index 8ece6de4652..bfeba3cfe67 100644
--- a/src/shared/vmap/VMapManager.h
+++ b/src/shared/vmap/VMapManager.h
@@ -1,7 +1,7 @@
/*
- * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+ * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
- * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+ * Copyright (C) 2008-2009 Trinity <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
diff --git a/src/shared/vmap/VMapTools.h b/src/shared/vmap/VMapTools.h
index 4961064d188..3af3a29310d 100644
--- a/src/shared/vmap/VMapTools.h
+++ b/src/shared/vmap/VMapTools.h
@@ -1,7 +1,7 @@
/*
-* Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
+* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
-* Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
+* Copyright (C) 2008-2009 Trinity <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