root/trunk/src/game/World.cpp @ 2

Revision 2, 100.2 kB (checked in by yumileroy, 17 years ago)

[svn] * Proper SVN structure

Original author: Neo2003
Date: 2008-10-02 16:23:55-05:00

Line 
1/*
2 * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17 */
18
19/** \file
20    \ingroup world
21*/
22
23#include "Common.h"
24#include "Database/DatabaseEnv.h"
25#include "Config/ConfigEnv.h"
26#include "SystemConfig.h"
27#include "Log.h"
28#include "Opcodes.h"
29#include "WorldSession.h"
30#include "WorldPacket.h"
31#include "Weather.h"
32#include "Player.h"
33#include "SkillExtraItems.h"
34#include "SkillDiscovery.h"
35#include "World.h"
36#include "ObjectMgr.h"
37#include "SpellMgr.h"
38#include "Chat.h"
39#include "Database/DBCStores.h"
40#include "LootMgr.h"
41#include "ItemEnchantmentMgr.h"
42#include "MapManager.h"
43#include "ScriptCalls.h"
44#include "CreatureAIRegistry.h"
45#include "Policies/SingletonImp.h"
46#include "BattleGroundMgr.h"
47#include "TemporarySummon.h"
48#include "WaypointMovementGenerator.h"
49#include "VMapFactory.h"
50#include "GlobalEvents.h"
51#include "GameEvent.h"
52#include "Database/DatabaseImpl.h"
53#include "WorldSocket.h"
54#include "GridNotifiersImpl.h"
55#include "CellImpl.h"
56#include "InstanceSaveMgr.h"
57#include "WaypointManager.h"
58#include "Util.h"
59
60INSTANTIATE_SINGLETON_1( World );
61
62volatile bool World::m_stopEvent = false;
63volatile uint32 World::m_worldLoopCounter = 0;
64
65float World::m_MaxVisibleDistanceForCreature  = DEFAULT_VISIBILITY_DISTANCE;
66float World::m_MaxVisibleDistanceForPlayer    = DEFAULT_VISIBILITY_DISTANCE;
67float World::m_MaxVisibleDistanceForObject    = DEFAULT_VISIBILITY_DISTANCE;
68float World::m_MaxVisibleDistanceInFlight     = DEFAULT_VISIBILITY_DISTANCE;
69float World::m_VisibleUnitGreyDistance        = 0;
70float World::m_VisibleObjectGreyDistance      = 0;
71
72// ServerMessages.dbc
73enum ServerMessageType
74{
75    SERVER_MSG_SHUTDOWN_TIME      = 1,
76    SERVER_MSG_RESTART_TIME       = 2,
77    SERVER_MSG_STRING             = 3,
78    SERVER_MSG_SHUTDOWN_CANCELLED = 4,
79    SERVER_MSG_RESTART_CANCELLED  = 5
80};
81
82struct ScriptAction
83{
84    uint64 sourceGUID;
85    uint64 targetGUID;
86    uint64 ownerGUID;                                       // owner of source if source is item
87    ScriptInfo const* script;                               // pointer to static script data
88};
89
90/// World constructor
91World::World()
92{
93    m_playerLimit = 0;
94    m_allowMovement = true;
95    m_ShutdownMask = 0;
96    m_ShutdownTimer = 0;
97    m_gameTime=time(NULL);
98    m_startTime=m_gameTime;
99    m_maxActiveSessionCount = 0;
100    m_maxQueuedSessionCount = 0;
101    m_resultQueue = NULL;
102    m_NextDailyQuestReset = 0;
103
104    m_defaultDbcLocale = LOCALE_enUS;
105    m_availableDbcLocaleMask = 0;
106}
107
108/// World destructor
109World::~World()
110{
111    ///- Empty the kicked session set
112    for (std::set<WorldSession*>::iterator itr = m_kicked_sessions.begin(); itr != m_kicked_sessions.end(); ++itr)
113        delete *itr;
114
115    m_kicked_sessions.clear();
116
117    ///- Empty the WeatherMap
118    for (WeatherMap::iterator itr = m_weathers.begin(); itr != m_weathers.end(); ++itr)
119        delete itr->second;
120
121    m_weathers.clear();
122
123    VMAP::VMapFactory::clear();
124
125    if(m_resultQueue) delete m_resultQueue;
126}
127
128/// Find a player in a specified zone
129Player* World::FindPlayerInZone(uint32 zone)
130{
131    ///- circle through active sessions and return the first player found in the zone
132    SessionMap::iterator itr;
133    for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
134    {
135        if(!itr->second)
136            continue;
137        Player *player = itr->second->GetPlayer();
138        if(!player)
139            continue;
140        if( player->IsInWorld() && player->GetZoneId() == zone )
141        {
142            // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone.
143            return player;
144        }
145    }
146    return NULL;
147}
148
149/// Find a session by its id
150WorldSession* World::FindSession(uint32 id) const
151{
152    SessionMap::const_iterator itr = m_sessions.find(id);
153
154    if(itr != m_sessions.end())
155        return itr->second;                                 // also can return NULL for kicked session
156    else
157        return NULL;
158}
159
160/// Remove a given session
161bool World::RemoveSession(uint32 id)
162{
163    ///- Find the session, kick the user, but we can't delete session at this moment to prevent iterator invalidation
164    SessionMap::iterator itr = m_sessions.find(id);
165
166    if(itr != m_sessions.end() && itr->second)
167    {
168        if (itr->second->PlayerLoading())
169            return false;
170        itr->second->KickPlayer();
171    }
172
173    return true;
174}
175
176/// Add a session to the session list
177void World::AddSession(WorldSession* s)
178{
179    ASSERT(s);
180
181    WorldSession* old = m_sessions[s->GetAccountId()];
182    m_sessions[s->GetAccountId()] = s;
183
184    // if session already exist, prepare to it deleting at next world update
185    if(old)
186        m_kicked_sessions.insert(old);
187}
188
189int32 World::GetQueuePos(WorldSocket* socket)
190{
191    uint32 position = 1;
192
193    for(Queue::iterator iter = m_QueuedPlayer.begin(); iter != m_QueuedPlayer.end(); ++iter, ++position)
194        if((*iter) == socket)
195            return position;
196
197    return 0;
198}
199
200void World::AddQueuedPlayer(WorldSocket* socket)
201{
202    m_QueuedPlayer.push_back(socket);
203}
204
205void World::RemoveQueuedPlayer(WorldSocket* socket)
206{
207    // sessions count including queued to remove (if removed_session set)
208    uint32 sessions = GetActiveSessionCount();
209
210    uint32 position = 1;
211    Queue::iterator iter = m_QueuedPlayer.begin();
212
213    // if session not queued then we need decrease sessions count (Remove socked callet before session removing from session list)
214    bool decrease_session = true;
215
216    // search socket to remove and count skipped positions
217    for(;iter != m_QueuedPlayer.end(); ++iter, ++position)
218    {
219        if(*iter==socket)
220        {
221            Queue::iterator iter2 = iter;
222            ++iter;
223            m_QueuedPlayer.erase(iter2);
224            decrease_session = false;                       // removing queued session
225            break;
226        }
227    }
228
229    // iter point to next socked after removed or end()
230    // position store position of removed socket and then new position next socket after removed
231
232    // decrease for case session queued for removing
233    if(decrease_session && sessions)
234        --sessions;
235
236    // accept first in queue
237    if( (!m_playerLimit || sessions < m_playerLimit) && !m_QueuedPlayer.empty() )
238    {
239        WorldSocket * socket = m_QueuedPlayer.front();
240        socket->SendAuthWaitQue(0);
241        m_QueuedPlayer.pop_front();
242
243        // update iter to point first queued socket or end() if queue is empty now
244        iter = m_QueuedPlayer.begin();
245        position = 1;
246    }
247
248    // update position from iter to end()
249    // iter point to first not updated socket, position store new position
250    for(; iter != m_QueuedPlayer.end(); ++iter, ++position)
251        (*iter)->SendAuthWaitQue(position);
252}
253
254/// Find a Weather object by the given zoneid
255Weather* World::FindWeather(uint32 id) const
256{
257    WeatherMap::const_iterator itr = m_weathers.find(id);
258
259    if(itr != m_weathers.end())
260        return itr->second;
261    else
262        return 0;
263}
264
265/// Remove a Weather object for the given zoneid
266void World::RemoveWeather(uint32 id)
267{
268    // not called at the moment. Kept for completeness
269    WeatherMap::iterator itr = m_weathers.find(id);
270
271    if(itr != m_weathers.end())
272    {
273        delete itr->second;
274        m_weathers.erase(itr);
275    }
276}
277
278/// Add a Weather object to the list
279Weather* World::AddWeather(uint32 zone_id)
280{
281    WeatherZoneChances const* weatherChances = objmgr.GetWeatherChances(zone_id);
282
283    // zone not have weather, ignore
284    if(!weatherChances)
285        return NULL;
286
287    Weather* w = new Weather(zone_id,weatherChances);
288    m_weathers[w->GetZone()] = w;
289    w->ReGenerate();
290    w->UpdateWeather();
291    return w;
292}
293
294/// Initialize config values
295void World::LoadConfigSettings(bool reload)
296{
297    if(reload)
298    {
299        if(!sConfig.Reload())
300        {
301            sLog.outError("World settings reload fail: can't read settings from %s.",sConfig.GetFilename().c_str());
302            return;
303        }
304        //TODO Check if config is outdated
305    }
306
307    ///- Read the player limit and the Message of the day from the config file
308    SetPlayerLimit( sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT), true );
309    SetMotd( sConfig.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
310
311    ///- Read all rates from the config file
312    rate_values[RATE_HEALTH]      = sConfig.GetFloatDefault("Rate.Health", 1);
313    if(rate_values[RATE_HEALTH] < 0)
314    {
315        sLog.outError("Rate.Health (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_HEALTH]);
316        rate_values[RATE_HEALTH] = 1;
317    }
318    rate_values[RATE_POWER_MANA]  = sConfig.GetFloatDefault("Rate.Mana", 1);
319    if(rate_values[RATE_POWER_MANA] < 0)
320    {
321        sLog.outError("Rate.Mana (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_POWER_MANA]);
322        rate_values[RATE_POWER_MANA] = 1;
323    }
324    rate_values[RATE_POWER_RAGE_INCOME] = sConfig.GetFloatDefault("Rate.Rage.Income", 1);
325    rate_values[RATE_POWER_RAGE_LOSS]   = sConfig.GetFloatDefault("Rate.Rage.Loss", 1);
326    if(rate_values[RATE_POWER_RAGE_LOSS] < 0)
327    {
328        sLog.outError("Rate.Rage.Loss (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_POWER_RAGE_LOSS]);
329        rate_values[RATE_POWER_RAGE_LOSS] = 1;
330    }
331    rate_values[RATE_POWER_FOCUS] = sConfig.GetFloatDefault("Rate.Focus", 1.0f);
332    rate_values[RATE_LOYALTY]     = sConfig.GetFloatDefault("Rate.Loyalty", 1.0f);
333    rate_values[RATE_SKILL_DISCOVERY] = sConfig.GetFloatDefault("Rate.Skill.Discovery", 1.0f);
334    rate_values[RATE_DROP_ITEM_POOR]       = sConfig.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f);
335    rate_values[RATE_DROP_ITEM_NORMAL]     = sConfig.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f);
336    rate_values[RATE_DROP_ITEM_UNCOMMON]   = sConfig.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f);
337    rate_values[RATE_DROP_ITEM_RARE]       = sConfig.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f);
338    rate_values[RATE_DROP_ITEM_EPIC]       = sConfig.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f);
339    rate_values[RATE_DROP_ITEM_LEGENDARY]  = sConfig.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f);
340    rate_values[RATE_DROP_ITEM_ARTIFACT]   = sConfig.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f);
341    rate_values[RATE_DROP_ITEM_REFERENCED] = sConfig.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f);
342    rate_values[RATE_DROP_MONEY]  = sConfig.GetFloatDefault("Rate.Drop.Money", 1.0f);
343    rate_values[RATE_XP_KILL]     = sConfig.GetFloatDefault("Rate.XP.Kill", 1.0f);
344    rate_values[RATE_XP_QUEST]    = sConfig.GetFloatDefault("Rate.XP.Quest", 1.0f);
345    rate_values[RATE_XP_EXPLORE]  = sConfig.GetFloatDefault("Rate.XP.Explore", 1.0f);
346    rate_values[RATE_XP_PAST_70]  = sConfig.GetFloatDefault("Rate.XP.PastLevel70", 1.0f);
347    rate_values[RATE_REPUTATION_GAIN]  = sConfig.GetFloatDefault("Rate.Reputation.Gain", 1.0f);
348    rate_values[RATE_CREATURE_NORMAL_DAMAGE]          = sConfig.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f);
349    rate_values[RATE_CREATURE_ELITE_ELITE_DAMAGE]     = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f);
350    rate_values[RATE_CREATURE_ELITE_RAREELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f);
351    rate_values[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f);
352    rate_values[RATE_CREATURE_ELITE_RARE_DAMAGE]      = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f);
353    rate_values[RATE_CREATURE_NORMAL_HP]          = sConfig.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f);
354    rate_values[RATE_CREATURE_ELITE_ELITE_HP]     = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f);
355    rate_values[RATE_CREATURE_ELITE_RAREELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f);
356    rate_values[RATE_CREATURE_ELITE_WORLDBOSS_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f);
357    rate_values[RATE_CREATURE_ELITE_RARE_HP]      = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f);
358    rate_values[RATE_CREATURE_NORMAL_SPELLDAMAGE]          = sConfig.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f);
359    rate_values[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE]     = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f);
360    rate_values[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f);
361    rate_values[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f);
362    rate_values[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE]      = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f);
363    rate_values[RATE_CREATURE_AGGRO]  = sConfig.GetFloatDefault("Rate.Creature.Aggro", 1.0f);
364    rate_values[RATE_REST_INGAME]                    = sConfig.GetFloatDefault("Rate.Rest.InGame", 1.0f);
365    rate_values[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY] = sConfig.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f);
366    rate_values[RATE_REST_OFFLINE_IN_WILDERNESS]     = sConfig.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f);
367    rate_values[RATE_DAMAGE_FALL]  = sConfig.GetFloatDefault("Rate.Damage.Fall", 1.0f);
368    rate_values[RATE_AUCTION_TIME]  = sConfig.GetFloatDefault("Rate.Auction.Time", 1.0f);
369    rate_values[RATE_AUCTION_DEPOSIT] = sConfig.GetFloatDefault("Rate.Auction.Deposit", 1.0f);
370    rate_values[RATE_AUCTION_CUT] = sConfig.GetFloatDefault("Rate.Auction.Cut", 1.0f);
371    rate_values[RATE_HONOR] = sConfig.GetFloatDefault("Rate.Honor",1.0f);
372    rate_values[RATE_MINING_AMOUNT] = sConfig.GetFloatDefault("Rate.Mining.Amount",1.0f);
373    rate_values[RATE_MINING_NEXT]   = sConfig.GetFloatDefault("Rate.Mining.Next",1.0f);
374    rate_values[RATE_INSTANCE_RESET_TIME] = sConfig.GetFloatDefault("Rate.InstanceResetTime",1.0f);
375    rate_values[RATE_TALENT] = sConfig.GetFloatDefault("Rate.Talent",1.0f);
376    if(rate_values[RATE_TALENT] < 0.0f)
377    {
378        sLog.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_TALENT]);
379        rate_values[RATE_TALENT] = 1.0f;
380    }
381    rate_values[RATE_CORPSE_DECAY_LOOTED] = sConfig.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f);
382
383    rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = sConfig.GetFloatDefault("TargetPosRecalculateRange",1.5f);
384    if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] < CONTACT_DISTANCE)
385    {
386        sLog.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],CONTACT_DISTANCE,CONTACT_DISTANCE);
387        rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = CONTACT_DISTANCE;
388    }
389    else if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] > ATTACK_DISTANCE)
390    {
391        sLog.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],ATTACK_DISTANCE,ATTACK_DISTANCE);
392        rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = ATTACK_DISTANCE;
393    }
394
395    rate_values[RATE_DURABILITY_LOSS_DAMAGE] = sConfig.GetFloatDefault("DurabilityLossChance.Damage",0.5f);
396    if(rate_values[RATE_DURABILITY_LOSS_DAMAGE] < 0.0f)
397    {
398        sLog.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_DAMAGE]);
399        rate_values[RATE_DURABILITY_LOSS_DAMAGE] = 0.0f;
400    }
401    rate_values[RATE_DURABILITY_LOSS_ABSORB] = sConfig.GetFloatDefault("DurabilityLossChance.Absorb",0.5f);
402    if(rate_values[RATE_DURABILITY_LOSS_ABSORB] < 0.0f)
403    {
404        sLog.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_ABSORB]);
405        rate_values[RATE_DURABILITY_LOSS_ABSORB] = 0.0f;
406    }
407    rate_values[RATE_DURABILITY_LOSS_PARRY] = sConfig.GetFloatDefault("DurabilityLossChance.Parry",0.05f);
408    if(rate_values[RATE_DURABILITY_LOSS_PARRY] < 0.0f)
409    {
410        sLog.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_PARRY]);
411        rate_values[RATE_DURABILITY_LOSS_PARRY] = 0.0f;
412    }
413    rate_values[RATE_DURABILITY_LOSS_BLOCK] = sConfig.GetFloatDefault("DurabilityLossChance.Block",0.05f);
414    if(rate_values[RATE_DURABILITY_LOSS_BLOCK] < 0.0f)
415    {
416        sLog.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_BLOCK]);
417        rate_values[RATE_DURABILITY_LOSS_BLOCK] = 0.0f;
418    }
419
420    ///- Read other configuration items from the config file
421
422    m_configs[CONFIG_COMPRESSION] = sConfig.GetIntDefault("Compression", 1);
423    if(m_configs[CONFIG_COMPRESSION] < 1 || m_configs[CONFIG_COMPRESSION] > 9)
424    {
425        sLog.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs[CONFIG_COMPRESSION]);
426        m_configs[CONFIG_COMPRESSION] = 1;
427    }
428    m_configs[CONFIG_ADDON_CHANNEL] = sConfig.GetBoolDefault("AddonChannel", true);
429    m_configs[CONFIG_GRID_UNLOAD] = sConfig.GetBoolDefault("GridUnload", true);
430    m_configs[CONFIG_INTERVAL_SAVE] = sConfig.GetIntDefault("PlayerSaveInterval", 900000);
431
432    m_configs[CONFIG_INTERVAL_GRIDCLEAN] = sConfig.GetIntDefault("GridCleanUpDelay", 300000);
433    if(m_configs[CONFIG_INTERVAL_GRIDCLEAN] < MIN_GRID_DELAY)
434    {
435        sLog.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_GRIDCLEAN],MIN_GRID_DELAY);
436        m_configs[CONFIG_INTERVAL_GRIDCLEAN] = MIN_GRID_DELAY;
437    }
438    if(reload)
439        MapManager::Instance().SetGridCleanUpDelay(m_configs[CONFIG_INTERVAL_GRIDCLEAN]);
440
441    m_configs[CONFIG_INTERVAL_MAPUPDATE] = sConfig.GetIntDefault("MapUpdateInterval", 100);
442    if(m_configs[CONFIG_INTERVAL_MAPUPDATE] < MIN_MAP_UPDATE_DELAY)
443    {
444        sLog.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_MAPUPDATE],MIN_MAP_UPDATE_DELAY);
445        m_configs[CONFIG_INTERVAL_MAPUPDATE] = MIN_MAP_UPDATE_DELAY;
446    }
447    if(reload)
448        MapManager::Instance().SetMapUpdateInterval(m_configs[CONFIG_INTERVAL_MAPUPDATE]);
449
450    m_configs[CONFIG_INTERVAL_CHANGEWEATHER] = sConfig.GetIntDefault("ChangeWeatherInterval", 600000);
451
452    if(reload)
453    {
454        uint32 val = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
455        if(val!=m_configs[CONFIG_PORT_WORLD])
456            sLog.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_PORT_WORLD]);
457    }
458    else
459        m_configs[CONFIG_PORT_WORLD] = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
460
461    if(reload)
462    {
463        uint32 val = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
464        if(val!=m_configs[CONFIG_SOCKET_SELECTTIME])
465            sLog.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[DEFAULT_SOCKET_SELECT_TIME]);
466    }
467    else
468        m_configs[CONFIG_SOCKET_SELECTTIME] = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
469
470
471    m_configs[CONFIG_TCP_NO_DELAY] = sConfig.GetBoolDefault("TcpNoDelay", false);
472    m_configs[CONFIG_GROUP_XP_DISTANCE] = sConfig.GetIntDefault("MaxGroupXPDistance", 74);
473    /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
474    m_configs[CONFIG_SIGHT_MONSTER] = sConfig.GetIntDefault("MonsterSight", 50);
475    m_configs[CONFIG_SIGHT_GUARDER] = sConfig.GetIntDefault("GuarderSight", 50);
476
477    if(reload)
478    {
479        uint32 val = sConfig.GetIntDefault("GameType", 0);
480        if(val!=m_configs[CONFIG_GAME_TYPE])
481            sLog.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_GAME_TYPE]);
482    }
483    else
484        m_configs[CONFIG_GAME_TYPE] = sConfig.GetIntDefault("GameType", 0);
485
486    if(reload)
487    {
488        uint32 val = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
489        if(val!=m_configs[CONFIG_REALM_ZONE])
490            sLog.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_REALM_ZONE]);
491    }
492    else
493        m_configs[CONFIG_REALM_ZONE] = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
494
495    m_configs[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS] = sConfig.GetBoolDefault("AllowTwoSide.Accounts", false);
496    m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT]    = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
497    m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
498    m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP]   = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
499    m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD]   = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
500    m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION]   = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
501    m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL]    = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
502    m_configs[CONFIG_ALLOW_TWO_SIDE_WHO_LIST] = sConfig.GetBoolDefault("AllowTwoSide.WhoList", false);
503    m_configs[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND] = sConfig.GetBoolDefault("AllowTwoSide.AddFriend", false);
504    m_configs[CONFIG_STRICT_PLAYER_NAMES]  = sConfig.GetIntDefault("StrictPlayerNames",  0);
505    m_configs[CONFIG_STRICT_CHARTER_NAMES] = sConfig.GetIntDefault("StrictCharterNames", 0);
506    m_configs[CONFIG_STRICT_PET_NAMES]     = sConfig.GetIntDefault("StrictPetNames",     0);
507
508    m_configs[CONFIG_CHARACTERS_CREATING_DISABLED] = sConfig.GetIntDefault("CharactersCreatingDisabled", 0);
509
510    m_configs[CONFIG_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("CharactersPerRealm", 10);
511    if(m_configs[CONFIG_CHARACTERS_PER_REALM] < 1 || m_configs[CONFIG_CHARACTERS_PER_REALM] > 10)
512    {
513        sLog.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs[CONFIG_CHARACTERS_PER_REALM]);
514        m_configs[CONFIG_CHARACTERS_PER_REALM] = 10;
515    }
516
517    // must be after CONFIG_CHARACTERS_PER_REALM
518    m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = sConfig.GetIntDefault("CharactersPerAccount", 50);
519    if(m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] < m_configs[CONFIG_CHARACTERS_PER_REALM])
520    {
521        sLog.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs[CONFIG_CHARACTERS_PER_ACCOUNT],m_configs[CONFIG_CHARACTERS_PER_REALM]);
522        m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = m_configs[CONFIG_CHARACTERS_PER_REALM];
523    }
524
525    m_configs[CONFIG_SKIP_CINEMATICS] = sConfig.GetIntDefault("SkipCinematics", 0);
526    if(m_configs[CONFIG_SKIP_CINEMATICS] < 0 || m_configs[CONFIG_SKIP_CINEMATICS] > 2)
527    {
528        sLog.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs[CONFIG_SKIP_CINEMATICS]);
529        m_configs[CONFIG_SKIP_CINEMATICS] = 0;
530    }
531
532
533    if(reload)
534    {
535        uint32 val = sConfig.GetIntDefault("MaxPlayerLevel", 60);
536        if(val!=m_configs[CONFIG_MAX_PLAYER_LEVEL])
537            sLog.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
538    }
539    else
540        m_configs[CONFIG_MAX_PLAYER_LEVEL] = sConfig.GetIntDefault("MaxPlayerLevel", 60);
541    if(m_configs[CONFIG_MAX_PLAYER_LEVEL] > 255)
542    {
543        sLog.outError("MaxPlayerLevel (%i) must be in range 1..255. Set to 255.",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
544        m_configs[CONFIG_MAX_PLAYER_LEVEL] = 255;
545    }
546
547    m_configs[CONFIG_START_PLAYER_LEVEL] = sConfig.GetIntDefault("StartPlayerLevel", 1);
548    if(m_configs[CONFIG_START_PLAYER_LEVEL] < 1)
549    {
550        sLog.outError("StartPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to 1.",m_configs[CONFIG_START_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
551        m_configs[CONFIG_START_PLAYER_LEVEL] = 1;
552    }
553    else if(m_configs[CONFIG_START_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
554    {
555        sLog.outError("StartPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to %u.",m_configs[CONFIG_START_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
556        m_configs[CONFIG_START_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
557    }
558    m_configs[CONFIG_MAX_HONOR_POINTS] = sConfig.GetIntDefault("MaxHonorPoints", 75000);
559    m_configs[CONFIG_MAX_ARENA_POINTS] = sConfig.GetIntDefault("MaxArenaPoints", 5000);
560
561    m_configs[CONFIG_INSTANCE_IGNORE_LEVEL] = sConfig.GetBoolDefault("Instance.IgnoreLevel", false);
562    m_configs[CONFIG_INSTANCE_IGNORE_RAID]  = sConfig.GetBoolDefault("Instance.IgnoreRaid", false);
563
564    m_configs[CONFIG_BATTLEGROUND_CAST_DESERTER]              = sConfig.GetBoolDefault("Battleground.CastDeserter", true);
565    m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE]     = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.Enable", true);
566    m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false);
567
568    m_configs[CONFIG_CAST_UNSTUCK] = sConfig.GetBoolDefault("CastUnstuck", true);
569    m_configs[CONFIG_INSTANCE_RESET_TIME_HOUR]  = sConfig.GetIntDefault("Instance.ResetTimeHour", 4);
570    m_configs[CONFIG_INSTANCE_UNLOAD_DELAY] = sConfig.GetIntDefault("Instance.UnloadDelay", 1800000);
571
572    m_configs[CONFIG_MAX_PRIMARY_TRADE_SKILL] = sConfig.GetIntDefault("MaxPrimaryTradeSkill", 2);
573    m_configs[CONFIG_MIN_PETITION_SIGNS] = sConfig.GetIntDefault("MinPetitionSigns", 9);
574    if(m_configs[CONFIG_MIN_PETITION_SIGNS] > 9)
575    {
576        sLog.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.",m_configs[CONFIG_MIN_PETITION_SIGNS]);
577        m_configs[CONFIG_MIN_PETITION_SIGNS] = 9;
578    }
579
580    m_configs[CONFIG_GM_WISPERING_TO] = sConfig.GetBoolDefault("GM.WhisperingTo",false);
581    m_configs[CONFIG_GM_IN_GM_LIST]  = sConfig.GetBoolDefault("GM.InGMList",false);
582    m_configs[CONFIG_GM_IN_WHO_LIST]  = sConfig.GetBoolDefault("GM.InWhoList",false);
583    m_configs[CONFIG_GM_LOGIN_STATE]  = sConfig.GetIntDefault("GM.LoginState",2);
584    m_configs[CONFIG_GM_LOG_TRADE] = sConfig.GetBoolDefault("GM.LogTrade", false);
585
586    m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
587
588    m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
589
590    m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
591    if(m_configs[CONFIG_UPTIME_UPDATE]<=0)
592    {
593        sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
594        m_configs[CONFIG_UPTIME_UPDATE] = 10;
595    }
596    if(reload)
597    {
598        m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
599        m_timers[WUPDATE_UPTIME].Reset();
600    }
601
602    m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
603    m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
604    m_configs[CONFIG_SKILL_CHANCE_GREEN]  = sConfig.GetIntDefault("SkillChance.Green",25);
605    m_configs[CONFIG_SKILL_CHANCE_GREY]   = sConfig.GetIntDefault("SkillChance.Grey",0);
606
607    m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS]  = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
608    m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS]   = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
609
610    m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
611
612    m_configs[CONFIG_SKILL_GAIN_CRAFTING]  = sConfig.GetIntDefault("SkillGain.Crafting", 1);
613    if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
614    {
615        sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
616        m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
617    }
618
619    m_configs[CONFIG_SKILL_GAIN_DEFENSE]  = sConfig.GetIntDefault("SkillGain.Defense", 1);
620    if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
621    {
622        sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
623        m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
624    }
625
626    m_configs[CONFIG_SKILL_GAIN_GATHERING]  = sConfig.GetIntDefault("SkillGain.Gathering", 1);
627    if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
628    {
629        sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
630        m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
631    }
632
633    m_configs[CONFIG_SKILL_GAIN_WEAPON]  = sConfig.GetIntDefault("SkillGain.Weapon", 1);
634    if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
635    {
636        sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
637        m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
638    }
639
640    m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
641    if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
642    {
643        sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
644        m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
645    }
646
647    m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
648    m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
649
650    if(reload)
651    {
652        uint32 val = sConfig.GetIntDefault("Expansion",1);
653        if(val!=m_configs[CONFIG_EXPANSION])
654            sLog.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
655    }
656    else
657        m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",1);
658
659    m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
660    m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
661    m_configs[CONFIG_CHATFLOOD_MUTE_TIME]     = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
662
663    m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
664
665    m_configs[CONFIG_CREATURE_FAMILY_ASSISTEMCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistenceRadius",10);
666
667    m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
668
669    // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level (255)
670    m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff",4);
671    if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > 255)
672        m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = 255;
673    m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff",7);
674    if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > 255)
675        m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = 255;
676
677    m_configs[CONFIG_DETECT_POS_COLLISION] = sConfig.GetBoolDefault("DetectPosCollision", true);
678
679    m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
680    m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
681
682    m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
683    m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
684
685    m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
686    m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
687    m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
688    m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
689    m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
690
691    m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault("Death.SicknessLevel", 11);
692    m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
693    m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
694
695    m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
696
697    // always use declined names in the russian client
698    m_configs[CONFIG_DECLINED_NAMES_USED] = 
699        (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
700
701    m_configs[CONFIG_LISTEN_RANGE_SAY]       = sConfig.GetIntDefault("ListenRange.Say", 25);
702    m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
703    m_configs[CONFIG_LISTEN_RANGE_YELL]      = sConfig.GetIntDefault("ListenRange.Yell", 300);
704
705
706    m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
707    if(m_VisibleUnitGreyDistance >  MAX_VISIBILITY_DISTANCE)
708    {
709        sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
710        m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
711    }
712    m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
713    if(m_VisibleObjectGreyDistance >  MAX_VISIBILITY_DISTANCE)
714    {
715        sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
716        m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
717    }
718
719    m_MaxVisibleDistanceForCreature      = sConfig.GetFloatDefault("Visibility.Distance.Creature",     DEFAULT_VISIBILITY_DISTANCE);
720    if(m_MaxVisibleDistanceForCreature < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
721    {
722        sLog.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
723        m_MaxVisibleDistanceForCreature = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
724    }
725    else if(m_MaxVisibleDistanceForCreature + m_VisibleUnitGreyDistance >  MAX_VISIBILITY_DISTANCE)
726    {
727        sLog.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
728        m_MaxVisibleDistanceForCreature = MAX_VISIBILITY_DISTANCE-m_VisibleUnitGreyDistance;
729    }
730    m_MaxVisibleDistanceForPlayer        = sConfig.GetFloatDefault("Visibility.Distance.Player",       DEFAULT_VISIBILITY_DISTANCE);
731    if(m_MaxVisibleDistanceForPlayer < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
732    {
733        sLog.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
734        m_MaxVisibleDistanceForPlayer = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
735    }
736    else if(m_MaxVisibleDistanceForPlayer + m_VisibleUnitGreyDistance >  MAX_VISIBILITY_DISTANCE)
737    {
738        sLog.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
739        m_MaxVisibleDistanceForPlayer = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
740    }
741    m_MaxVisibleDistanceForObject    = sConfig.GetFloatDefault("Visibility.Distance.Gameobject",   DEFAULT_VISIBILITY_DISTANCE);
742    if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
743    {
744        sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
745        m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
746    }
747    else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance >  MAX_VISIBILITY_DISTANCE)
748    {
749        sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
750        m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
751    }
752    m_MaxVisibleDistanceInFlight    = sConfig.GetFloatDefault("Visibility.Distance.InFlight",      DEFAULT_VISIBILITY_DISTANCE);
753    if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
754    {
755        sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
756        m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
757    }
758
759    ///- Read the "Data" directory from the config file
760    std::string dataPath = sConfig.GetStringDefault("DataDir","./");
761    if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
762        dataPath.append("/");
763
764    if(reload)
765    {
766        if(dataPath!=m_dataPath)
767            sLog.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath.c_str());
768    }
769    else
770    {
771        m_dataPath = dataPath;
772        sLog.outString("Using DataDir %s",m_dataPath.c_str());
773    }
774
775    bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
776    bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
777    std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
778    std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
779    VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
780    VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
781    VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
782    VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
783    sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
784    sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
785    sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
786}
787
788/// Initialize the World
789void World::SetInitialWorldSettings()
790{
791    ///- Initialize the random number generator
792    srand((unsigned int)time(NULL));
793
794    ///- Initialize config settings
795    LoadConfigSettings();
796
797    ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
798    objmgr.SetHighestGuids();
799
800    ///- Check the existence of the map files for all races' startup areas.
801    if(   !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
802        ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
803        ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
804        ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
805        ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
806        ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
807        ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
808        ||m_configs[CONFIG_EXPANSION] && (
809        !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
810    {
811        sLog.outError("Correct *.map files not found in path '%smaps' or *.vmap/*vmdir files in '%svmaps'. Please place *.map/*.vmap/*.vmdir files in appropriate directories or correct the DataDir value in the mangosd.conf file.",m_dataPath.c_str(),m_dataPath.c_str());
812        exit(1);
813    }
814
815    ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
816    sLog.outString( "" );
817    sLog.outString( "Loading MaNGOS strings..." );
818    if (!objmgr.LoadMangosStrings())
819        exit(1);                                            // Error message displayed in function already
820
821    ///- Update the realm entry in the database with the realm type from the config file
822    //No SQL injection as values are treated as integers
823
824    // not send custom type REALM_FFA_PVP to realm list
825    uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
826    uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
827    loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
828
829    ///- Remove the bones after a restart
830    CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
831
832    ///- Load the DBC files
833    sLog.outString("Initialize data stores...");
834    LoadDBCStores(m_dataPath);
835    DetectDBCLang();
836
837    sLog.outString( "Loading InstanceTemplate" );
838    objmgr.LoadInstanceTemplate();
839
840    sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
841    spellmgr.LoadSkillLineAbilityMap();
842
843    ///- Clean up and pack instances
844    sLog.outString( "Cleaning up instances..." );
845    sInstanceSaveManager.CleanupInstances();                              // must be called before `creature_respawn`/`gameobject_respawn` tables
846
847    sLog.outString( "Packing instances..." );
848    sInstanceSaveManager.PackInstances();
849
850    sLog.outString( "Loading Localization strings..." );
851    objmgr.LoadCreatureLocales();
852    objmgr.LoadGameObjectLocales();
853    objmgr.LoadItemLocales();
854    objmgr.LoadQuestLocales();
855    objmgr.LoadNpcTextLocales();
856    objmgr.LoadPageTextLocales();
857    objmgr.SetDBCLocaleIndex(GetDefaultDbcLocale());        // Get once for all the locale index of DBC language (console/broadcasts)
858
859    sLog.outString( "Loading Page Texts..." );
860    objmgr.LoadPageTexts();
861
862    sLog.outString( "Loading Game Object Templates..." );   // must be after LoadPageTexts
863    objmgr.LoadGameobjectInfo();
864
865    sLog.outString( "Loading Spell Chain Data..." );
866    spellmgr.LoadSpellChains();
867
868    sLog.outString( "Loading Spell Elixir types..." );
869    spellmgr.LoadSpellElixirs();
870
871    sLog.outString( "Loading Spell Learn Skills..." );
872    spellmgr.LoadSpellLearnSkills();                        // must be after LoadSpellChains
873
874    sLog.outString( "Loading Spell Learn Spells..." );
875    spellmgr.LoadSpellLearnSpells();
876
877    sLog.outString( "Loading Spell Proc Event conditions..." );
878    spellmgr.LoadSpellProcEvents();
879
880    sLog.outString( "Loading Aggro Spells Definitions...");
881    spellmgr.LoadSpellThreats();
882
883    sLog.outString( "Loading NPC Texts..." );
884    objmgr.LoadGossipText();
885
886    sLog.outString( "Loading Item Random Enchantments Table..." );
887    LoadRandomEnchantmentsTable();
888
889    sLog.outString( "Loading Items..." );                   // must be after LoadRandomEnchantmentsTable and LoadPageTexts
890    objmgr.LoadItemPrototypes();
891
892    sLog.outString( "Loading Item Texts..." );
893    objmgr.LoadItemTexts();
894
895    sLog.outString( "Loading Creature Model Based Info Data..." );
896    objmgr.LoadCreatureModelInfo();
897
898    sLog.outString( "Loading Equipment templates...");
899    objmgr.LoadEquipmentTemplates();
900
901    sLog.outString( "Loading Creature templates..." );
902    objmgr.LoadCreatureTemplates();
903
904    sLog.outString( "Loading SpellsScriptTarget...");
905    spellmgr.LoadSpellScriptTarget();                       // must be after LoadCreatureTemplates and LoadGameobjectInfo
906
907    sLog.outString( "Loading Creature Reputation OnKill Data..." );
908    objmgr.LoadReputationOnKill();
909
910    sLog.outString( "Loading Pet Create Spells..." );
911    objmgr.LoadPetCreateSpells();
912
913    sLog.outString( "Loading Creature Data..." );
914    objmgr.LoadCreatures();
915
916    sLog.outString( "Loading Creature Addon Data..." );
917    objmgr.LoadCreatureAddons();                            // must be after LoadCreatureTemplates() and LoadCreatures()
918
919    sLog.outString( "Loading Creature Respawn Data..." );   // must be after PackInstances()
920    objmgr.LoadCreatureRespawnTimes();
921
922    sLog.outString( "Loading Gameobject Data..." );
923    objmgr.LoadGameobjects();
924
925    sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
926    objmgr.LoadGameobjectRespawnTimes();
927
928    sLog.outString( "Loading Game Event Data...");
929    gameeventmgr.LoadFromDB();
930
931    sLog.outString( "Loading Weather Data..." );
932    objmgr.LoadWeatherZoneChances();
933
934    sLog.outString( "Loading Quests..." );
935    objmgr.LoadQuests();                                    // must be loaded after DBCs, creature_template, item_template, gameobject tables
936
937    sLog.outString( "Loading Quests Relations..." );
938    objmgr.LoadQuestRelations();                            // must be after quest load
939
940    sLog.outString( "Loading AreaTrigger definitions..." );
941    objmgr.LoadAreaTriggerTeleports();                      // must be after item template load
942
943    sLog.outString( "Loading Quest Area Triggers..." );
944    objmgr.LoadQuestAreaTriggers();                         // must be after LoadQuests
945
946    sLog.outString( "Loading Tavern Area Triggers..." );
947    objmgr.LoadTavernAreaTriggers();
948   
949    sLog.outString( "Loading AreaTrigger script names..." );
950    objmgr.LoadAreaTriggerScripts();
951
952
953    sLog.outString( "Loading Graveyard-zone links...");
954    objmgr.LoadGraveyardZones();
955
956    sLog.outString( "Loading Spell target coordinates..." );
957    spellmgr.LoadSpellTargetPositions();
958
959    sLog.outString( "Loading SpellAffect definitions..." );
960    spellmgr.LoadSpellAffects();
961
962    sLog.outString( "Loading spell pet auras..." );
963    spellmgr.LoadSpellPetAuras();
964
965    sLog.outString( "Loading player Create Info & Level Stats..." );
966    objmgr.LoadPlayerInfo();
967
968    sLog.outString( "Loading Exploration BaseXP Data..." );
969    objmgr.LoadExplorationBaseXP();
970
971    sLog.outString( "Loading Pet Name Parts..." );
972    objmgr.LoadPetNames();
973
974    sLog.outString( "Loading the max pet number..." );
975    objmgr.LoadPetNumber();
976
977    sLog.outString( "Loading pet level stats..." );
978    objmgr.LoadPetLevelInfo();
979
980    sLog.outString( "Loading Player Corpses..." );
981    objmgr.LoadCorpses();
982
983    sLog.outString( "Loading Loot Tables..." );
984    LoadLootTables();
985
986    sLog.outString( "Loading Skill Discovery Table..." );
987    LoadSkillDiscoveryTable();
988
989    sLog.outString( "Loading Skill Extra Item Table..." );
990    LoadSkillExtraItemTable();
991
992    sLog.outString( "Loading Skill Fishing base level requirements..." );
993    objmgr.LoadFishingBaseSkillLevel();
994
995    ///- Load dynamic data tables from the database
996    sLog.outString( "Loading Auctions..." );
997    objmgr.LoadAuctionItems();
998    objmgr.LoadAuctions();
999
1000    sLog.outString( "Loading Guilds..." );
1001    objmgr.LoadGuilds();
1002
1003    sLog.outString( "Loading ArenaTeams..." );
1004    objmgr.LoadArenaTeams();
1005
1006    sLog.outString( "Loading Groups..." );
1007    objmgr.LoadGroups();
1008
1009    sLog.outString( "Loading ReservedNames..." );
1010    objmgr.LoadReservedPlayersNames();
1011
1012    sLog.outString( "Loading GameObject for quests..." );
1013    objmgr.LoadGameObjectForQuests();
1014
1015    sLog.outString( "Loading BattleMasters..." );
1016    objmgr.LoadBattleMastersEntry();
1017
1018    sLog.outString( "Loading Waypoints..." );
1019    WaypointMgr.Load();
1020
1021    ///- Handle outdated emails (delete/return)
1022    sLog.outString( "Returning old mails..." );
1023    objmgr.ReturnOrDeleteOldMails(false);
1024
1025    ///- Load and initialize scripts
1026    sLog.outString( "Loading Scripts..." );
1027    objmgr.LoadQuestStartScripts();                         // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1028    objmgr.LoadQuestEndScripts();                           // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1029    objmgr.LoadSpellScripts();                              // must be after load Creature/Gameobject(Template/Data)
1030    objmgr.LoadGameObjectScripts();                         // must be after load Creature/Gameobject(Template/Data)
1031    objmgr.LoadEventScripts();                              // must be after load Creature/Gameobject(Template/Data)
1032
1033    sLog.outString( "Initializing Scripts..." );
1034    if(!LoadScriptingModule())
1035        exit(1);
1036
1037    ///- Initialize game time and timers
1038    sLog.outString( "DEBUG:: Initialize game time and timers" );
1039    m_gameTime = time(NULL);
1040    m_startTime=m_gameTime;
1041
1042    tm local;
1043    time_t curr;
1044    time(&curr);
1045    local=*(localtime(&curr));                              // dereference and assign
1046    char isoDate[128];
1047    sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1048        local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1049
1050    WorldDatabase.PExecute("INSERT INTO uptime (startstring, starttime, uptime) VALUES('%s', %ld, 0)", isoDate, m_startTime );
1051
1052    m_timers[WUPDATE_OBJECTS].SetInterval(0);
1053    m_timers[WUPDATE_SESSIONS].SetInterval(0);
1054    m_timers[WUPDATE_WEATHERS].SetInterval(1000);
1055    m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*1000);    //set auction update interval to 1 minute
1056    m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
1057                                                            //Update "uptime" table based on configuration entry in minutes.
1058    m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*1000);  //erase corpses every 20 minutes
1059
1060    //to set mailtimer to return mails every day between 4 and 5 am
1061    //mailtimer is increased when updating auctions
1062    //one second is 1000 -(tested on win system)
1063    mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * 1000) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1064                                                            //1440
1065    mail_timer_expires = ( (DAY * 1000) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1066    sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1067
1068    ///- Initilize static helper structures
1069    AIRegistry::Initialize();
1070    WaypointMovementGenerator<Creature>::Initialize();
1071    Player::InitVisibleBits();
1072
1073    ///- Initialize MapManager
1074    sLog.outString( "Starting Map System" );
1075    MapManager::Instance().Initialize();
1076
1077    ///- Initialize Battlegrounds
1078    sLog.outString( "Starting BattleGround System" );
1079    sBattleGroundMgr.CreateInitialBattleGrounds();
1080
1081    //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1082    sLog.outString( "Loading Transports..." );
1083    MapManager::Instance().LoadTransports();
1084
1085    sLog.outString("Deleting expired bans..." );
1086    loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1087
1088    sLog.outString("Calculate next daily quest reset time..." );
1089    InitDailyQuestResetTime();
1090
1091    sLog.outString("Starting Game Event system..." );
1092    uint32 nextGameEvent = gameeventmgr.Initialize();
1093    m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);    //depend on next event
1094
1095    sLog.outString( "WORLD: World initialized" );
1096}
1097void World::DetectDBCLang()
1098{
1099    uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1100
1101    if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1102    {
1103        sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1104        m_lang_confid = LOCALE_enUS;
1105    }
1106
1107    ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1108
1109    std::string availableLocalsStr;
1110
1111    int default_locale = MAX_LOCALE;
1112    for (int i = MAX_LOCALE-1; i >= 0; --i)
1113    {
1114        if ( strlen(race->name[i]) > 0)                     // check by race names
1115        {
1116            default_locale = i;
1117            m_availableDbcLocaleMask |= (1 << i);
1118            availableLocalsStr += localeNames[i];
1119            availableLocalsStr += " ";
1120        }
1121    }
1122
1123    if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1124        (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1125    {
1126        default_locale = m_lang_confid;
1127    }
1128
1129    if(default_locale >= MAX_LOCALE)
1130    {
1131        sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1132        exit(1);
1133    }
1134
1135    m_defaultDbcLocale = LocaleConstant(default_locale);
1136
1137    sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1138}
1139
1140/// Update the World !
1141void World::Update(time_t diff)
1142{
1143    ///- Update the different timers
1144    for(int i = 0; i < WUPDATE_COUNT; i++)
1145        if(m_timers[i].GetCurrent()>=0)
1146            m_timers[i].Update(diff);
1147    else m_timers[i].SetCurrent(0);
1148
1149    ///- Update the game time and check for shutdown time
1150    _UpdateGameTime();
1151
1152    /// Handle daily quests reset time
1153    if(m_gameTime > m_NextDailyQuestReset)
1154    {
1155        ResetDailyQuests();
1156        m_NextDailyQuestReset += DAY;
1157    }
1158
1159    /// <ul><li> Handle auctions when the timer has passed
1160    if (m_timers[WUPDATE_AUCTIONS].Passed())
1161    {
1162        m_timers[WUPDATE_AUCTIONS].Reset();
1163
1164        ///- Update mails (return old mails with item, or delete them)
1165        //(tested... works on win)
1166        if (++mail_timer > mail_timer_expires)
1167        {
1168            mail_timer = 0;
1169            objmgr.ReturnOrDeleteOldMails(true);
1170        }
1171
1172        AuctionHouseObject* AuctionMap;
1173        for (int i = 0; i < 3; i++)
1174        {
1175            switch (i)
1176            {
1177                case 0:
1178                    AuctionMap = objmgr.GetAuctionsMap( 6 );//horde
1179                    break;
1180                case 1:
1181                    AuctionMap = objmgr.GetAuctionsMap( 2 );//alliance
1182                    break;
1183                case 2:
1184                    AuctionMap = objmgr.GetAuctionsMap( 7 );//neutral
1185                    break;
1186            }
1187
1188            ///- Handle expired auctions
1189            AuctionHouseObject::AuctionEntryMap::iterator itr,next;
1190            for (itr = AuctionMap->GetAuctionsBegin(); itr != AuctionMap->GetAuctionsEnd();itr = next)
1191            {
1192                next = itr;
1193                ++next;
1194                if (m_gameTime > (itr->second->time))
1195                {
1196                    ///- Either cancel the auction if there was no bidder
1197                    if (itr->second->bidder == 0)
1198                    {
1199                        objmgr.SendAuctionExpiredMail( itr->second );
1200                    }
1201                    ///- Or perform the transaction
1202                    else
1203                    {
1204                        //we should send an "item sold" message if the seller is online
1205                        //we send the item to the winner
1206                        //we send the money to the seller
1207                        objmgr.SendAuctionSuccessfulMail( itr->second );
1208                        objmgr.SendAuctionWonMail( itr->second );
1209                    }
1210
1211                    ///- In any case clear the auction
1212                    //No SQL injection (Id is integer)
1213                    CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",itr->second->Id);
1214                    objmgr.RemoveAItem(itr->second->item_guidlow);
1215                    delete itr->second;
1216                    AuctionMap->RemoveAuction(itr->first);
1217                }
1218            }
1219        }
1220    }
1221
1222    /// <li> Handle session updates when the timer has passed
1223    if (m_timers[WUPDATE_SESSIONS].Passed())
1224    {
1225        m_timers[WUPDATE_SESSIONS].Reset();
1226
1227        UpdateSessions(diff);
1228    }
1229
1230    /// <li> Handle weather updates when the timer has passed
1231    if (m_timers[WUPDATE_WEATHERS].Passed())
1232    {
1233        m_timers[WUPDATE_WEATHERS].Reset();
1234
1235        ///- Send an update signal to Weather objects
1236        WeatherMap::iterator itr, next;
1237        for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1238        {
1239            next = itr;
1240            ++next;
1241
1242            ///- and remove Weather objects for zones with no player
1243                                                            //As interval > WorldTick
1244            if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1245            {
1246                delete itr->second;
1247                m_weathers.erase(itr);
1248            }
1249        }
1250    }
1251    /// <li> Update uptime table
1252    if (m_timers[WUPDATE_UPTIME].Passed())
1253    {
1254        uint32 tmpDiff = (m_gameTime - m_startTime);
1255        uint32 maxClientsNum = sWorld.GetMaxActiveSessionCount();
1256
1257        m_timers[WUPDATE_UPTIME].Reset();
1258        WorldDatabase.PExecute("UPDATE uptime SET uptime = %d, maxplayers = %d WHERE starttime = " I64FMTD, tmpDiff, maxClientsNum, uint64(m_startTime));
1259    }
1260
1261    /// <li> Handle all other objects
1262    if (m_timers[WUPDATE_OBJECTS].Passed())
1263    {
1264        m_timers[WUPDATE_OBJECTS].Reset();
1265        ///- Update objects when the timer has passed (maps, transport, creatures,...)
1266        MapManager::Instance().Update(diff);                // As interval = 0
1267
1268        ///- Process necessary scripts
1269        if (!m_scriptSchedule.empty())
1270            ScriptsProcess();
1271
1272        sBattleGroundMgr.Update(diff);
1273    }
1274
1275    // execute callbacks from sql queries that were queued recently
1276    UpdateResultQueue();
1277
1278    ///- Erase corpses once every 20 minutes
1279    if (m_timers[WUPDATE_CORPSES].Passed())
1280    {
1281        m_timers[WUPDATE_CORPSES].Reset();
1282
1283        CorpsesErase();
1284    }
1285
1286    ///- Process Game events when necessary
1287    if (m_timers[WUPDATE_EVENTS].Passed())
1288    {
1289        m_timers[WUPDATE_EVENTS].Reset();                   // to give time for Update() to be processed
1290        uint32 nextGameEvent = gameeventmgr.Update();
1291        m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1292        m_timers[WUPDATE_EVENTS].Reset();
1293    }
1294
1295    /// </ul>
1296    ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1297    MapManager::Instance().DoDelayedMovesAndRemoves();
1298
1299    // update the instance reset times
1300    sInstanceSaveManager.Update();
1301
1302    // And last, but not least handle the issued cli commands
1303    ProcessCliCommands();
1304}
1305
1306/// Put scripts in the execution queue
1307void World::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
1308{
1309    ///- Find the script map
1310    ScriptMapMap::const_iterator s = scripts.find(id);
1311    if (s == scripts.end())
1312        return;
1313
1314    // prepare static data
1315    uint64 sourceGUID = source->GetGUID();
1316    uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1317    uint64 ownerGUID  = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1318
1319    ///- Schedule script execution for all scripts in the script map
1320    ScriptMap const *s2 = &(s->second);
1321    bool immedScript = false;
1322    for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
1323    {
1324        ScriptAction sa;
1325        sa.sourceGUID = sourceGUID;
1326        sa.targetGUID = targetGUID;
1327        sa.ownerGUID  = ownerGUID;
1328
1329        sa.script = &iter->second;
1330        m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + iter->first, sa));
1331        if (iter->first == 0)
1332            immedScript = true;
1333    }
1334    ///- If one of the effects should be immediate, launch the script execution
1335    if (immedScript)
1336        ScriptsProcess();
1337}
1338
1339void World::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
1340{
1341    // NOTE: script record _must_ exist until command executed
1342
1343    // prepare static data
1344    uint64 sourceGUID = source->GetGUID();
1345    uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1346    uint64 ownerGUID  = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1347
1348    ScriptAction sa;
1349    sa.sourceGUID = sourceGUID;
1350    sa.targetGUID = targetGUID;
1351    sa.ownerGUID  = ownerGUID;
1352
1353    sa.script = &script;
1354    m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + delay, sa));
1355
1356    ///- If effects should be immediate, launch the script execution
1357    if(delay == 0)
1358        ScriptsProcess();
1359}
1360
1361/// Process queued scripts
1362void World::ScriptsProcess()
1363{
1364    if (m_scriptSchedule.empty())
1365        return;
1366
1367    ///- Process overdue queued scripts
1368    std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
1369                                                            // ok as multimap is a *sorted* associative container
1370    while (!m_scriptSchedule.empty() && (iter->first <= m_gameTime))
1371    {
1372        ScriptAction const& step = iter->second;
1373
1374        Object* source = NULL;
1375
1376        if(step.sourceGUID)
1377        {
1378            switch(GUID_HIPART(step.sourceGUID))
1379            {
1380                case HIGHGUID_ITEM:
1381                    // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1382                    {
1383                        Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
1384                        if(player)
1385                            source = player->GetItemByGuid(step.sourceGUID);
1386                        break;
1387                    }
1388                case HIGHGUID_UNIT:
1389                    source = HashMapHolder<Creature>::Find(step.sourceGUID);
1390                    break;
1391                case HIGHGUID_PET:
1392                    source = HashMapHolder<Pet>::Find(step.sourceGUID);
1393                    break;
1394                case HIGHGUID_PLAYER:
1395                    source = HashMapHolder<Player>::Find(step.sourceGUID);
1396                    break;
1397                case HIGHGUID_GAMEOBJECT:
1398                    source = HashMapHolder<GameObject>::Find(step.sourceGUID);
1399                    break;
1400                case HIGHGUID_CORPSE:
1401                    source = HashMapHolder<Corpse>::Find(step.sourceGUID);
1402                    break;
1403                default:
1404                    sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
1405                    break;
1406            }
1407        }
1408
1409        Object* target = NULL;
1410
1411        if(step.targetGUID)
1412        {
1413            switch(GUID_HIPART(step.targetGUID))
1414            {
1415                case HIGHGUID_UNIT:
1416                    target = HashMapHolder<Creature>::Find(step.targetGUID);
1417                    break;
1418                case HIGHGUID_PET:
1419                    target = HashMapHolder<Pet>::Find(step.targetGUID);
1420                    break;
1421                case HIGHGUID_PLAYER:                       // empty GUID case also
1422                    target = HashMapHolder<Player>::Find(step.targetGUID);
1423                    break;
1424                case HIGHGUID_GAMEOBJECT:
1425                    target = HashMapHolder<GameObject>::Find(step.targetGUID);
1426                    break;
1427                case HIGHGUID_CORPSE:
1428                    target = HashMapHolder<Corpse>::Find(step.targetGUID);
1429                    break;
1430                default:
1431                    sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
1432                    break;
1433            }
1434        }
1435
1436        switch (step.script->command)
1437        {
1438            case SCRIPT_COMMAND_TALK:
1439            {
1440                if(!source)
1441                {
1442                    sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1443                    break;
1444                }
1445
1446                if(source->GetTypeId()!=TYPEID_UNIT)
1447                {
1448                    sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1449                    break;
1450                }
1451                if(step.script->datalong > 3)
1452                {
1453                    sLog.outError("SCRIPT_COMMAND_TALK invalid chat type (%u), skipping.",step.script->datalong);
1454                    break;
1455                }
1456
1457                uint64 unit_target = target ? target->GetGUID() : 0;
1458
1459                //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1460                switch(step.script->datalong)
1461                {
1462                    case 0:                                 // Say
1463                        ((Creature *)source)->Say(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
1464                        break;
1465                    case 1:                                 // Whisper
1466                        if(!unit_target)
1467                        {
1468                            sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
1469                            break;
1470                        }
1471                        ((Creature *)source)->Whisper(step.script->datatext.c_str(),unit_target);
1472                        break;
1473                    case 2:                                 // Yell
1474                        ((Creature *)source)->Yell(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
1475                        break;
1476                    case 3:                                 // Emote text
1477                        ((Creature *)source)->TextEmote(step.script->datatext.c_str(), unit_target);
1478                        break;
1479                    default:
1480                        break;                              // must be already checked at load
1481                }
1482                break;
1483            }
1484
1485            case SCRIPT_COMMAND_EMOTE:
1486                if(!source)
1487                {
1488                    sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1489                    break;
1490                }
1491
1492                if(source->GetTypeId()!=TYPEID_UNIT)
1493                {
1494                    sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1495                    break;
1496                }
1497
1498                ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
1499                break;
1500            case SCRIPT_COMMAND_FIELD_SET:
1501                if(!source)
1502                {
1503                    sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1504                    break;
1505                }
1506                if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1507                {
1508                    sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1509                        step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1510                    break;
1511                }
1512
1513                source->SetUInt32Value(step.script->datalong, step.script->datalong2);
1514                break;
1515            case SCRIPT_COMMAND_MOVE_TO:
1516                if(!source)
1517                {
1518                    sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1519                    break;
1520                }
1521
1522                if(source->GetTypeId()!=TYPEID_UNIT)
1523                {
1524                    sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1525                    break;
1526                }
1527                ((Unit *)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, ((Unit *)source)->GetUnitMovementFlags(), step.script->datalong2 );
1528                MapManager::Instance().GetMap(((Unit *)source)->GetMapId(), ((Unit *)source))->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
1529                break;
1530            case SCRIPT_COMMAND_FLAG_SET:
1531                if(!source)
1532                {
1533                    sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1534                    break;
1535                }
1536                if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1537                {
1538                    sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1539                        step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1540                    break;
1541                }
1542
1543                source->SetFlag(step.script->datalong, step.script->datalong2);
1544                break;
1545            case SCRIPT_COMMAND_FLAG_REMOVE:
1546                if(!source)
1547                {
1548                    sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1549                    break;
1550                }
1551                if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1552                {
1553                    sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1554                        step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1555                    break;
1556                }
1557
1558                source->RemoveFlag(step.script->datalong, step.script->datalong2);
1559                break;
1560
1561            case SCRIPT_COMMAND_TELEPORT_TO:
1562            {
1563                // accept player in any one from target/source arg
1564                if (!target && !source)
1565                {
1566                    sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1567                    break;
1568                }
1569
1570                                                            // must be only Player
1571                if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
1572                {
1573                    sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
1574                    break;
1575                }
1576
1577                Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
1578
1579                pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
1580                break;
1581            }
1582
1583            case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
1584            {
1585                if(!step.script->datalong)                  // creature not specified
1586                {
1587                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1588                    break;
1589                }
1590
1591                if(!source)
1592                {
1593                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1594                    break;
1595                }
1596
1597                WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1598
1599                if(!summoner)
1600                {
1601                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1602                    break;
1603                }
1604
1605                float x = step.script->x;
1606                float y = step.script->y;
1607                float z = step.script->z;
1608                float o = step.script->o;
1609
1610                Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
1611                if (!pCreature)
1612                {
1613                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
1614                    break;
1615                }
1616
1617                break;
1618            }
1619
1620            case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
1621            {
1622                if(!step.script->datalong)                  // gameobject not specified
1623                {
1624                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1625                    break;
1626                }
1627
1628                if(!source)
1629                {
1630                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1631                    break;
1632                }
1633
1634                WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1635
1636                if(!summoner)
1637                {
1638                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1639                    break;
1640                }
1641
1642                GameObject *go = NULL;
1643                int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
1644
1645                CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
1646                Cell cell(p);
1647                cell.data.Part.reserved = ALL_DISTRICT;
1648
1649                MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
1650                MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(go,go_check);
1651
1652                TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1653                CellLock<GridReadGuard> cell_lock(cell, p);
1654                cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(summoner->GetMapId(), summoner));
1655
1656                if ( !go )
1657                {
1658                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
1659                    break;
1660                }
1661
1662                if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1663                    go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1664                    go->GetGoType()==GAMEOBJECT_TYPE_DOOR        ||
1665                    go->GetGoType()==GAMEOBJECT_TYPE_BUTTON      ||
1666                    go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
1667                {
1668                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
1669                    break;
1670                }
1671
1672                if( go->isSpawned() )
1673                    break;                                  //gameobject already spawned
1674
1675                go->SetLootState(GO_READY);
1676                go->SetRespawnTime(time_to_despawn);        //despawn object in ? seconds
1677
1678                MapManager::Instance().GetMap(go->GetMapId(), go)->Add(go);
1679                break;
1680            }
1681            case SCRIPT_COMMAND_OPEN_DOOR:
1682            {
1683                if(!step.script->datalong)                  // door not specified
1684                {
1685                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1686                    break;
1687                }
1688
1689                if(!source)
1690                {
1691                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1692                    break;
1693                }
1694
1695                if(!source->isType(TYPEMASK_UNIT))          // must be any Unit (creature or player)
1696                {
1697                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1698                    break;
1699                }
1700
1701                Unit* caster = (Unit*)source;
1702
1703                GameObject *door = NULL;
1704                int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1705
1706                CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1707                Cell cell(p);
1708                cell.data.Part.reserved = ALL_DISTRICT;
1709
1710                MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1711                MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1712
1713                TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1714                CellLock<GridReadGuard> cell_lock(cell, p);
1715                cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1716
1717                if ( !door )
1718                {
1719                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1720                    break;
1721                }
1722                if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1723                {
1724                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1725                    break;
1726                }
1727
1728                if( !door->GetGoState() )
1729                    break;                                  //door already  open
1730
1731                door->UseDoorOrButton(time_to_close);
1732
1733                if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1734                    ((GameObject*)target)->UseDoorOrButton(time_to_close);
1735                break;
1736            }
1737            case SCRIPT_COMMAND_CLOSE_DOOR:
1738            {
1739                if(!step.script->datalong)                  // guid for door not specified
1740                {
1741                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
1742                    break;
1743                }
1744
1745                if(!source)
1746                {
1747                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
1748                    break;
1749                }
1750
1751                if(!source->isType(TYPEMASK_UNIT))          // must be any Unit (creature or player)
1752                {
1753                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1754                    break;
1755                }
1756
1757                Unit* caster = (Unit*)source;
1758
1759                GameObject *door = NULL;
1760                int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1761
1762                CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1763                Cell cell(p);
1764                cell.data.Part.reserved = ALL_DISTRICT;
1765
1766                MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1767                MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1768
1769                TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1770                CellLock<GridReadGuard> cell_lock(cell, p);
1771                cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1772
1773                if ( !door )
1774                {
1775                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1776                    break;
1777                }
1778                if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1779                {
1780                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1781                    break;
1782                }
1783
1784                if( door->GetGoState() )
1785                    break;                                  //door already closed
1786
1787                door->UseDoorOrButton(time_to_open);
1788
1789                if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1790                    ((GameObject*)target)->UseDoorOrButton(time_to_open);
1791
1792                break;
1793            }
1794            case SCRIPT_COMMAND_QUEST_EXPLORED:
1795            {
1796                if(!source)
1797                {
1798                    sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
1799                    break;
1800                }
1801
1802                if(!target)
1803                {
1804                    sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
1805                    break;
1806                }
1807
1808                // when script called for item spell casting then target == (unit or GO) and source is player
1809                WorldObject* worldObject;
1810                Player* player;
1811
1812                if(target->GetTypeId()==TYPEID_PLAYER)
1813                {
1814                    if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
1815                    {
1816                        sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
1817                        break;
1818                    }
1819
1820                    worldObject = (WorldObject*)source;
1821                    player = (Player*)target;
1822                }
1823                else
1824                {
1825                    if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
1826                    {
1827                        sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
1828                        break;
1829                    }
1830
1831                    if(source->GetTypeId()!=TYPEID_PLAYER)
1832                    {
1833                        sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
1834                        break;
1835                    }
1836
1837                    worldObject = (WorldObject*)target;
1838                    player = (Player*)source;
1839                }
1840
1841                // quest id and flags checked at script loading
1842                if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
1843                    (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
1844                    player->AreaExploredOrEventHappens(step.script->datalong);
1845                else
1846                    player->FailQuest(step.script->datalong);
1847
1848                break;
1849            }
1850
1851            case SCRIPT_COMMAND_ACTIVATE_OBJECT:
1852            {
1853                if(!source)
1854                {
1855                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
1856                    break;
1857                }
1858
1859                if(!source->isType(TYPEMASK_UNIT))
1860                {
1861                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
1862                    break;
1863                }
1864
1865                if(!target)
1866                {
1867                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
1868                    break;
1869                }
1870
1871                if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
1872                {
1873                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
1874                    break;
1875                }
1876
1877                Unit* caster = (Unit*)source;
1878
1879                GameObject *go = (GameObject*)target;
1880
1881                go->Use(caster);
1882                break;
1883            }
1884
1885            case SCRIPT_COMMAND_REMOVE_AURA:
1886            {
1887                Object* cmdTarget = step.script->datalong2 ? source : target;
1888
1889                if(!cmdTarget)
1890                {
1891                    sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
1892                    break;
1893                }
1894
1895                if(!cmdTarget->isType(TYPEMASK_UNIT))
1896                {
1897                    sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
1898                    break;
1899                }
1900
1901                ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
1902                break;
1903            }
1904
1905            case SCRIPT_COMMAND_CAST_SPELL:
1906            {
1907                if(!source)
1908                {
1909                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
1910                    break;
1911                }
1912
1913                if(!source->isType(TYPEMASK_UNIT))
1914                {
1915                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
1916                    break;
1917                }
1918
1919                Object* cmdTarget = step.script->datalong2 ? source : target;
1920
1921                if(!cmdTarget)
1922                {
1923                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 ? "source" : "target");
1924                    break;
1925                }
1926
1927                if(!cmdTarget->isType(TYPEMASK_UNIT))
1928                {
1929                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
1930                    break;
1931                }
1932
1933                Unit* spellTarget = (Unit*)cmdTarget;
1934
1935                //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
1936                ((Unit*)source)->CastSpell(spellTarget,step.script->datalong,false);
1937
1938                break;
1939            }
1940
1941            default:
1942                sLog.outError("Unknown script command %u called.",step.script->command);
1943                break;
1944        }
1945
1946        m_scriptSchedule.erase(iter);
1947
1948        iter = m_scriptSchedule.begin();
1949    }
1950    return;
1951}
1952
1953/// Send a packet to all players (except self if mentioned)
1954void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
1955{
1956    SessionMap::iterator itr;
1957    for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
1958    {
1959        if (itr->second &&
1960            itr->second->GetPlayer() &&
1961            itr->second->GetPlayer()->IsInWorld() &&
1962            itr->second != self &&
1963            (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
1964        {
1965            itr->second->SendPacket(packet);
1966        }
1967    }
1968}
1969
1970/// Send a System Message to all players (except self if mentioned)
1971void World::SendWorldText(int32 string_id, ...)
1972{
1973    std::vector<std::vector<WorldPacket*> > data_cache;     // 0 = default, i => i-1 locale index
1974
1975    for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
1976    {
1977        if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
1978            continue;
1979
1980        uint32 loc_idx = itr->second->GetSessionDbLocaleIndex();
1981        uint32 cache_idx = loc_idx+1;
1982
1983        std::vector<WorldPacket*>* data_list;
1984
1985        // create if not cached yet
1986        if(data_cache.size() < cache_idx+1 || data_cache[cache_idx].empty())
1987        {
1988            if(data_cache.size() < cache_idx+1)
1989                data_cache.resize(cache_idx+1);
1990
1991            data_list = &data_cache[cache_idx];
1992
1993            char const* text = objmgr.GetMangosString(string_id,loc_idx);
1994
1995            char buf[1000];
1996
1997            va_list argptr;
1998            va_start( argptr, string_id );
1999            vsnprintf( buf,1000, text, argptr );
2000            va_end( argptr );
2001
2002            char* pos = &buf[0];
2003
2004            while(char* line = ChatHandler::LineFromMessage(pos))
2005            {
2006                WorldPacket* data = new WorldPacket();
2007                ChatHandler::FillMessageData(data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2008                data_list->push_back(data);
2009            }
2010        }
2011        else
2012            data_list = &data_cache[cache_idx];
2013
2014        for(int i = 0; i < data_list->size(); ++i)
2015            itr->second->SendPacket((*data_list)[i]);
2016    }
2017
2018    // free memory
2019    for(int i = 0; i < data_cache.size(); ++i)
2020        for(int j = 0; j < data_cache[i].size(); ++j)
2021            delete data_cache[i][j];
2022}
2023
2024/// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2025void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
2026{
2027    SessionMap::iterator itr;
2028    for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2029    {
2030        if (itr->second &&
2031            itr->second->GetPlayer() &&
2032            itr->second->GetPlayer()->IsInWorld() &&
2033            itr->second->GetPlayer()->GetZoneId() == zone &&
2034            itr->second != self &&
2035            (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2036        {
2037            itr->second->SendPacket(packet);
2038        }
2039    }
2040}
2041
2042/// Send a System Message to all players in the zone (except self if mentioned)
2043void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
2044{
2045    WorldPacket data;
2046    ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
2047    SendZoneMessage(zone, &data, self,team);
2048}
2049
2050/// Kick (and save) all players
2051void World::KickAll()
2052{
2053    // session not removed at kick and will removed in next update tick
2054    for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2055        itr->second->KickPlayer();
2056}
2057
2058/// Kick (and save) all players with security level less `sec`
2059void World::KickAllLess(AccountTypes sec)
2060{
2061    // session not removed at kick and will removed in next update tick
2062    for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2063        if(itr->second->GetSecurity() < sec)
2064            itr->second->KickPlayer();
2065}
2066
2067/// Kick all queued players
2068void World::KickAllQueued()
2069{
2070    // session not removed at kick and will removed in next update tick
2071    for (Queue::iterator itr = m_QueuedPlayer.begin(); itr != m_QueuedPlayer.end(); ++itr)
2072        if(WorldSession* session = (*itr)->GetSession())
2073            session->KickPlayer();
2074
2075    m_QueuedPlayer.empty();
2076}
2077
2078/// Kick (and save) the designated player
2079bool World::KickPlayer(std::string playerName)
2080{
2081    SessionMap::iterator itr;
2082
2083    // session not removed at kick and will removed in next update tick
2084    for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2085    {
2086        if(!itr->second)
2087            continue;
2088        Player *player = itr->second->GetPlayer();
2089        if(!player)
2090            continue;
2091        if( player->IsInWorld() )
2092        {
2093            if (playerName == player->GetName())
2094            {
2095                itr->second->KickPlayer();
2096                return true;
2097            }
2098        }
2099    }
2100    return false;
2101}
2102
2103/// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2104uint8 World::BanAccount(std::string type, std::string nameOrIP, std::string duration, std::string reason, std::string author)
2105{
2106    loginDatabase.escape_string(nameOrIP);
2107    loginDatabase.escape_string(reason);
2108    std::string safe_author=author;
2109    loginDatabase.escape_string(safe_author);
2110
2111    if(type != "ip" && !normalizePlayerName(nameOrIP))
2112        return BAN_NOTFOUND;                                // Nobody to ban
2113
2114    uint32 duration_secs = TimeStringToSecs(duration);
2115    QueryResult *resultAccounts = NULL;                     //used for kicking
2116
2117    ///- Update the database with ban information
2118
2119    if(type=="ip")
2120    {
2121        //No SQL injection as strings are escaped
2122        resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
2123        loginDatabase.PExecute("INSERT INTO ip_banned VALUES ('%s',UNIX_TIMESTAMP(),UNIX_TIMESTAMP()+%u,'%s','%s')",nameOrIP.c_str(),duration_secs,safe_author.c_str(),reason.c_str());
2124    }
2125    else if(type=="account")
2126    {
2127        //No SQL injection as string is escaped
2128        resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2129    }
2130    else if(type=="character")
2131    {
2132        //No SQL injection as string is escaped
2133        resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2134    }
2135    else
2136        return BAN_SYNTAX_ERROR;                            //Syntax problem
2137
2138    if(!resultAccounts)
2139        if(type=="ip")
2140            return BAN_SUCCESS;                             // ip correctly banned but nobody affected (yet)
2141    else
2142        return BAN_NOTFOUND;                                // Nobody to ban
2143
2144    ///- Disconnect all affected players (for IP it can be several)
2145    do
2146    {
2147        Field* fieldsAccount = resultAccounts->Fetch();
2148        uint32 account = fieldsAccount->GetUInt32();
2149
2150        if(type != "ip")
2151            //No SQL injection as strings are escaped
2152            loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2153                account,duration_secs,safe_author.c_str(),reason.c_str());
2154
2155        WorldSession* sess = FindSession(account);
2156        if( sess )
2157            if(std::string(sess->GetPlayerName()) != author)
2158                sess->KickPlayer();
2159    }
2160    while( resultAccounts->NextRow() );
2161
2162    delete resultAccounts;
2163    return BAN_SUCCESS;
2164}
2165
2166/// Remove a ban from an account or IP address
2167bool World::RemoveBanAccount(std::string type, std::string nameOrIP)
2168{
2169    if(type == "ip")
2170    {
2171        loginDatabase.escape_string(nameOrIP);
2172        loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
2173    }
2174    else
2175    {
2176        uint32 account=0;
2177        if(type == "account")
2178        {
2179            //NO SQL injection as name is escaped
2180            loginDatabase.escape_string(nameOrIP);
2181            QueryResult *resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2182            if(!resultAccounts)
2183                return false;
2184            Field* fieldsAccount = resultAccounts->Fetch();
2185            account = fieldsAccount->GetUInt32();
2186
2187            delete resultAccounts;
2188        }
2189        else if(type == "character")
2190        {
2191            if(!normalizePlayerName(nameOrIP))
2192                return false;
2193
2194            //NO SQL injection as name is escaped
2195            loginDatabase.escape_string(nameOrIP);
2196            QueryResult *resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2197            if(!resultAccounts)
2198                return false;
2199            Field* fieldsAccount = resultAccounts->Fetch();
2200            account = fieldsAccount->GetUInt32();
2201
2202            delete resultAccounts;
2203        }
2204        if(!account)
2205            return false;
2206        //NO SQL injection as account is uint32
2207        loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
2208    }
2209    return true;
2210}
2211
2212/// Update the game time
2213void World::_UpdateGameTime()
2214{
2215    ///- update the time
2216    time_t thisTime = time(NULL);
2217    uint32 elapsed = uint32(thisTime - m_gameTime);
2218    m_gameTime = thisTime;
2219
2220    ///- if there is a shutdown timer
2221    if(m_ShutdownTimer > 0 && elapsed > 0)
2222    {
2223        ///- ... and it is overdue, stop the world (set m_stopEvent)
2224        if( m_ShutdownTimer <= elapsed )
2225        {
2226            if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2227                m_stopEvent = true;
2228            else
2229                m_ShutdownTimer = 1;                        // minimum timer value to wait idle state
2230        }
2231        ///- ... else decrease it and if necessary display a shutdown countdown to the users
2232        else
2233        {
2234            m_ShutdownTimer -= elapsed;
2235
2236            ShutdownMsg();
2237        }
2238    }
2239}
2240
2241/// Shutdown the server
2242void World::ShutdownServ(uint32 time, uint32 options)
2243{
2244    m_ShutdownMask = options;
2245
2246    ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2247    if(time==0)
2248    {
2249        if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2250            m_stopEvent = true;
2251        else
2252            m_ShutdownTimer = 1;                            //So that the session count is re-evaluated at next world tick
2253    }
2254    ///- Else set the shutdown timer and warn users
2255    else
2256    {
2257        m_ShutdownTimer = time;
2258        ShutdownMsg(true);
2259    }
2260}
2261
2262/// Display a shutdown message to the user(s)
2263void World::ShutdownMsg(bool show, Player* player)
2264{
2265    // not show messages for idle shutdown mode
2266    if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
2267        return;
2268
2269    ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2270    if ( show ||
2271        (m_ShutdownTimer < 10) ||
2272                                                            // < 30 sec; every 5 sec
2273        (m_ShutdownTimer<30        && (m_ShutdownTimer % 5         )==0) ||
2274                                                            // < 5 min ; every 1 min
2275        (m_ShutdownTimer<5*MINUTE  && (m_ShutdownTimer % MINUTE    )==0) ||
2276                                                            // < 30 min ; every 5 min
2277        (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
2278                                                            // < 12 h ; every 1 h
2279        (m_ShutdownTimer<12*HOUR   && (m_ShutdownTimer % HOUR      )==0) ||
2280                                                            // > 12 h ; every 12 h
2281        (m_ShutdownTimer>12*HOUR   && (m_ShutdownTimer % (12*HOUR) )==0))
2282    {
2283        std::string str = secsToTimeString(m_ShutdownTimer);
2284
2285        uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
2286
2287        SendServerMessage(msgid,str.c_str(),player);
2288        DEBUG_LOG("Server is %s in %s",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"),str.c_str());
2289    }
2290}
2291
2292/// Cancel a planned server shutdown
2293void World::ShutdownCancel()
2294{
2295    if(!m_ShutdownTimer)
2296        return;
2297
2298    uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2299
2300    m_ShutdownMask = 0;
2301    m_ShutdownTimer = 0;
2302    SendServerMessage(msgid);
2303
2304    DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2305}
2306
2307/// Send a server message to the user(s)
2308void World::SendServerMessage(uint32 type, const char *text, Player* player)
2309{
2310    WorldPacket data(SMSG_SERVER_MESSAGE, 50);              // guess size
2311    data << uint32(type);
2312    if(type <= SERVER_MSG_STRING)
2313        data << text;
2314
2315    if(player)
2316        player->GetSession()->SendPacket(&data);
2317    else
2318        SendGlobalMessage( &data );
2319}
2320
2321void World::UpdateSessions( time_t diff )
2322{
2323    ///- Delete kicked sessions at add new session
2324    for (std::set<WorldSession*>::iterator itr = m_kicked_sessions.begin(); itr != m_kicked_sessions.end(); ++itr)
2325        delete *itr;
2326    m_kicked_sessions.clear();
2327
2328    ///- Then send an update signal to remaining ones
2329    for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2330    {
2331        next = itr;
2332        ++next;
2333
2334        if(!itr->second)
2335            continue;
2336
2337        ///- and remove not active sessions from the list
2338        if(!itr->second->Update(diff))                      // As interval = 0
2339        {
2340            delete itr->second;
2341            m_sessions.erase(itr);
2342        }
2343    }
2344}
2345
2346// This handles the issued and queued CLI commands
2347void World::ProcessCliCommands()
2348{
2349    if (cliCmdQueue.empty()) return;
2350
2351    CliCommandHolder *command;
2352    pPrintf p_zprintf;
2353    while (!cliCmdQueue.empty())
2354    {
2355        sLog.outDebug("CLI command under processing...");
2356        command = cliCmdQueue.next();
2357        command->Execute();
2358        p_zprintf=command->GetOutputMethod();
2359        delete command;
2360    }
2361    // print the console message here so it looks right
2362    p_zprintf("mangos>");
2363}
2364
2365void World::InitResultQueue()
2366{
2367    m_resultQueue = new SqlResultQueue;
2368    CharacterDatabase.SetResultQueue(m_resultQueue);
2369}
2370
2371void World::UpdateResultQueue()
2372{
2373    m_resultQueue->Update();
2374}
2375
2376void World::UpdateRealmCharCount(uint32 accountId)
2377{
2378    CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2379        "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2380}
2381
2382void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2383{
2384    if (resultCharCount)
2385    {
2386        Field *fields = resultCharCount->Fetch();
2387        uint32 charCount = fields[0].GetUInt32();
2388        delete resultCharCount;
2389        loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2390        loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2391    }
2392}
2393
2394void World::InitDailyQuestResetTime()
2395{
2396    time_t mostRecentQuestTime;
2397
2398    QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2399    if(result)
2400    {
2401        Field *fields = result->Fetch();
2402
2403        mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2404        delete result;
2405    }
2406    else
2407        mostRecentQuestTime = 0;
2408
2409    // client built-in time for reset is 6:00 AM
2410    // FIX ME: client not show day start time
2411    time_t curTime = time(NULL);
2412    tm localTm = *localtime(&curTime);
2413    localTm.tm_hour = 6;
2414    localTm.tm_min  = 0;
2415    localTm.tm_sec  = 0;
2416
2417    // current day reset time
2418    time_t curDayResetTime = mktime(&localTm);
2419
2420    // last reset time before current moment
2421    time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2422
2423    // need reset (if we have quest time before last reset time (not processed by some reason)
2424    if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2425        m_NextDailyQuestReset = mostRecentQuestTime;
2426    else
2427    {
2428        // plan next reset time
2429        m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2430    }
2431}
2432
2433void World::ResetDailyQuests()
2434{
2435    sLog.outDetail("Daily quests reset for all characters.");
2436    CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2437    for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2438        if(itr->second->GetPlayer())
2439            itr->second->GetPlayer()->ResetDailyQuestStatus();
2440}
2441
2442void World::SetPlayerLimit( int32 limit, bool needUpdate )
2443{
2444    if(limit < -SEC_ADMINISTRATOR)
2445        limit = -SEC_ADMINISTRATOR;
2446
2447    // lock update need
2448    bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2449
2450    m_playerLimit = limit;
2451
2452    if(db_update_need)
2453        loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2454}
2455
2456void World::UpdateMaxSessionCounters()
2457{
2458    m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2459    m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2460}
Note: See TracBrowser for help on using the browser.