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

Revision 9, 106.0 kB (checked in by yumileroy, 17 years ago)

[svn] -enabled instantiated battlegrounds
-enabled arena matches
-rewritten battleground queuing to support joining as group
-removed queue announcements

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