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

Revision 28, 106.1 kB (checked in by yumileroy, 17 years ago)

[svn] * Updated to 6743 and 685

Moved language id used by Arena to a higher place to solve conflicts
Added the empty script folders

Original author: Neo2003
Date: 2008-10-09 08:42:22-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_LOGIN_STATE]       = sConfig.GetIntDefault("GM.LoginState",2);
646    m_configs[CONFIG_GM_ACCEPT_TICKETS]    = sConfig.GetIntDefault("GM.AcceptTickets",2);
647    m_configs[CONFIG_GM_CHAT]              = sConfig.GetIntDefault("GM.Chat",2);
648    m_configs[CONFIG_GM_WISPERING_TO]      = sConfig.GetIntDefault("GM.WhisperingTo",2);
649
650    m_configs[CONFIG_GM_IN_GM_LIST]        = sConfig.GetBoolDefault("GM.InGMList",false);
651    m_configs[CONFIG_GM_IN_WHO_LIST]       = sConfig.GetBoolDefault("GM.InWhoList",false);
652    m_configs[CONFIG_GM_LOG_TRADE]         = sConfig.GetBoolDefault("GM.LogTrade", false);
653
654    m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
655
656    m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
657
658    m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
659    if(m_configs[CONFIG_UPTIME_UPDATE]<=0)
660    {
661        sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
662        m_configs[CONFIG_UPTIME_UPDATE] = 10;
663    }
664    if(reload)
665    {
666        m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
667        m_timers[WUPDATE_UPTIME].Reset();
668    }
669
670    m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
671    m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
672    m_configs[CONFIG_SKILL_CHANCE_GREEN]  = sConfig.GetIntDefault("SkillChance.Green",25);
673    m_configs[CONFIG_SKILL_CHANCE_GREY]   = sConfig.GetIntDefault("SkillChance.Grey",0);
674
675    m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS]  = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
676    m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS]   = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
677
678    m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
679
680    m_configs[CONFIG_SKILL_GAIN_CRAFTING]  = sConfig.GetIntDefault("SkillGain.Crafting", 1);
681    if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
682    {
683        sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
684        m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
685    }
686
687    m_configs[CONFIG_SKILL_GAIN_DEFENSE]  = sConfig.GetIntDefault("SkillGain.Defense", 1);
688    if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
689    {
690        sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
691        m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
692    }
693
694    m_configs[CONFIG_SKILL_GAIN_GATHERING]  = sConfig.GetIntDefault("SkillGain.Gathering", 1);
695    if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
696    {
697        sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
698        m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
699    }
700
701    m_configs[CONFIG_SKILL_GAIN_WEAPON]  = sConfig.GetIntDefault("SkillGain.Weapon", 1);
702    if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
703    {
704        sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
705        m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
706    }
707
708    m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
709    if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
710    {
711        sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
712        m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
713    }
714
715    m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
716    m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
717
718    if(reload)
719    {
720        uint32 val = sConfig.GetIntDefault("Expansion",1);
721        if(val!=m_configs[CONFIG_EXPANSION])
722            sLog.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
723    }
724    else
725        m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",1);
726
727    m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
728    m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
729    m_configs[CONFIG_CHATFLOOD_MUTE_TIME]     = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
730
731    m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
732
733    m_configs[CONFIG_CREATURE_FAMILY_ASSISTEMCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistenceRadius",10);
734
735    m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
736
737    // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level (255)
738    m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff",4);
739    if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > 255)
740        m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = 255;
741    m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff",7);
742    if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > 255)
743        m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = 255;
744
745    m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
746    m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
747
748    m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
749    m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
750
751    m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
752    m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
753    m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
754    m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
755    m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
756
757    m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault("Death.SicknessLevel", 11);
758    m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
759    m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
760
761    m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
762
763    // always use declined names in the russian client
764    m_configs[CONFIG_DECLINED_NAMES_USED] = 
765        (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
766
767    m_configs[CONFIG_LISTEN_RANGE_SAY]       = sConfig.GetIntDefault("ListenRange.Say", 25);
768    m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
769    m_configs[CONFIG_LISTEN_RANGE_YELL]      = sConfig.GetIntDefault("ListenRange.Yell", 300);
770
771
772    m_configs[CONFIG_ARENA_MAX_RATING_DIFFERENCE] = sConfig.GetIntDefault("Arena.MaxRatingDifference", 0);
773    m_configs[CONFIG_ARENA_RATING_DISCARD_TIMER] = sConfig.GetIntDefault("Arena.RatingDiscardTimer",300000);
774    m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_POINTS] = sConfig.GetBoolDefault("Arena.AutoDistributePoints", false);
775    m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS] = sConfig.GetIntDefault("Arena.AutoDistributeInterval", 7);
776
777    m_configs[CONFIG_BATTLEGROUND_PREMATURE_FINISH_TIMER] = sConfig.GetIntDefault("BattleGround.PrematureFinishTimer", 0);
778
779    m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
780    if(m_VisibleUnitGreyDistance >  MAX_VISIBILITY_DISTANCE)
781    {
782        sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
783        m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
784    }
785    m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
786    if(m_VisibleObjectGreyDistance >  MAX_VISIBILITY_DISTANCE)
787    {
788        sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
789        m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
790    }
791
792    m_MaxVisibleDistanceForCreature      = sConfig.GetFloatDefault("Visibility.Distance.Creature",     DEFAULT_VISIBILITY_DISTANCE);
793    if(m_MaxVisibleDistanceForCreature < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
794    {
795        sLog.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
796        m_MaxVisibleDistanceForCreature = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
797    }
798    else if(m_MaxVisibleDistanceForCreature + m_VisibleUnitGreyDistance >  MAX_VISIBILITY_DISTANCE)
799    {
800        sLog.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
801        m_MaxVisibleDistanceForCreature = MAX_VISIBILITY_DISTANCE-m_VisibleUnitGreyDistance;
802    }
803    m_MaxVisibleDistanceForPlayer        = sConfig.GetFloatDefault("Visibility.Distance.Player",       DEFAULT_VISIBILITY_DISTANCE);
804    if(m_MaxVisibleDistanceForPlayer < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
805    {
806        sLog.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
807        m_MaxVisibleDistanceForPlayer = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
808    }
809    else if(m_MaxVisibleDistanceForPlayer + m_VisibleUnitGreyDistance >  MAX_VISIBILITY_DISTANCE)
810    {
811        sLog.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
812        m_MaxVisibleDistanceForPlayer = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
813    }
814    m_MaxVisibleDistanceForObject    = sConfig.GetFloatDefault("Visibility.Distance.Gameobject",   DEFAULT_VISIBILITY_DISTANCE);
815    if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
816    {
817        sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
818        m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
819    }
820    else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance >  MAX_VISIBILITY_DISTANCE)
821    {
822        sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
823        m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
824    }
825    m_MaxVisibleDistanceInFlight    = sConfig.GetFloatDefault("Visibility.Distance.InFlight",      DEFAULT_VISIBILITY_DISTANCE);
826    if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
827    {
828        sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
829        m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
830    }
831
832    ///- Read the "Data" directory from the config file
833    std::string dataPath = sConfig.GetStringDefault("DataDir","./");
834    if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
835        dataPath.append("/");
836
837    if(reload)
838    {
839        if(dataPath!=m_dataPath)
840            sLog.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath.c_str());
841    }
842    else
843    {
844        m_dataPath = dataPath;
845        sLog.outString("Using DataDir %s",m_dataPath.c_str());
846    }
847
848    bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
849    bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
850    std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
851    std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
852    VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
853    VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
854    VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
855    VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
856    sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
857    sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
858    sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
859}
860
861/// Initialize the World
862void World::SetInitialWorldSettings()
863{
864    ///- Initialize the random number generator
865    srand((unsigned int)time(NULL));
866
867    ///- Initialize config settings
868    LoadConfigSettings();
869
870    ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
871    objmgr.SetHighestGuids();
872
873    ///- Check the existence of the map files for all races' startup areas.
874    if(   !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
875        ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
876        ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
877        ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
878        ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
879        ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
880        ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
881        ||m_configs[CONFIG_EXPANSION] && (
882        !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
883    {
884        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());
885        exit(1);
886    }
887
888    ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
889    sLog.outString( "" );
890    sLog.outString( "Loading MaNGOS strings..." );
891    if (!objmgr.LoadMangosStrings())
892        exit(1);                                            // Error message displayed in function already
893
894    ///- Update the realm entry in the database with the realm type from the config file
895    //No SQL injection as values are treated as integers
896
897    // not send custom type REALM_FFA_PVP to realm list
898    uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
899    uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
900    loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
901
902    ///- Remove the bones after a restart
903    CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
904
905    ///- Load the DBC files
906    sLog.outString("Initialize data stores...");
907    LoadDBCStores(m_dataPath);
908    DetectDBCLang();
909
910    sLog.outString( "Loading InstanceTemplate" );
911    objmgr.LoadInstanceTemplate();
912
913    sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
914    spellmgr.LoadSkillLineAbilityMap();
915
916    ///- Clean up and pack instances
917    sLog.outString( "Cleaning up instances..." );
918    sInstanceSaveManager.CleanupInstances();                              // must be called before `creature_respawn`/`gameobject_respawn` tables
919
920    sLog.outString( "Packing instances..." );
921    sInstanceSaveManager.PackInstances();
922
923    sLog.outString( "Loading Localization strings..." );
924    objmgr.LoadCreatureLocales();
925    objmgr.LoadGameObjectLocales();
926    objmgr.LoadItemLocales();
927    objmgr.LoadQuestLocales();
928    objmgr.LoadNpcTextLocales();
929    objmgr.LoadPageTextLocales();
930    objmgr.SetDBCLocaleIndex(GetDefaultDbcLocale());        // Get once for all the locale index of DBC language (console/broadcasts)
931
932    sLog.outString( "Loading Page Texts..." );
933    objmgr.LoadPageTexts();
934
935    sLog.outString( "Loading Game Object Templates..." );   // must be after LoadPageTexts
936    objmgr.LoadGameobjectInfo();
937
938    sLog.outString( "Loading Spell Chain Data..." );
939    spellmgr.LoadSpellChains();
940
941    sLog.outString( "Loading Spell Elixir types..." );
942    spellmgr.LoadSpellElixirs();
943
944    sLog.outString( "Loading Spell Learn Skills..." );
945    spellmgr.LoadSpellLearnSkills();                        // must be after LoadSpellChains
946
947    sLog.outString( "Loading Spell Learn Spells..." );
948    spellmgr.LoadSpellLearnSpells();
949
950    sLog.outString( "Loading Spell Proc Event conditions..." );
951    spellmgr.LoadSpellProcEvents();
952
953    sLog.outString( "Loading Aggro Spells Definitions...");
954    spellmgr.LoadSpellThreats();
955
956    sLog.outString( "Loading NPC Texts..." );
957    objmgr.LoadGossipText();
958
959    sLog.outString( "Loading Item Random Enchantments Table..." );
960    LoadRandomEnchantmentsTable();
961
962    sLog.outString( "Loading Items..." );                   // must be after LoadRandomEnchantmentsTable and LoadPageTexts
963    objmgr.LoadItemPrototypes();
964
965    sLog.outString( "Loading Item Texts..." );
966    objmgr.LoadItemTexts();
967
968    sLog.outString( "Loading Creature Model Based Info Data..." );
969    objmgr.LoadCreatureModelInfo();
970
971    sLog.outString( "Loading Equipment templates...");
972    objmgr.LoadEquipmentTemplates();
973
974    sLog.outString( "Loading Creature templates..." );
975    objmgr.LoadCreatureTemplates();
976
977    sLog.outString( "Loading SpellsScriptTarget...");
978    spellmgr.LoadSpellScriptTarget();                       // must be after LoadCreatureTemplates and LoadGameobjectInfo
979
980    sLog.outString( "Loading Creature Reputation OnKill Data..." );
981    objmgr.LoadReputationOnKill();
982
983    sLog.outString( "Loading Pet Create Spells..." );
984    objmgr.LoadPetCreateSpells();
985
986    sLog.outString( "Loading Creature Data..." );
987    objmgr.LoadCreatures();
988
989    sLog.outString( "Loading Creature Addon Data..." );
990    objmgr.LoadCreatureAddons();                            // must be after LoadCreatureTemplates() and LoadCreatures()
991
992    sLog.outString( "Loading Creature Respawn Data..." );   // must be after PackInstances()
993    objmgr.LoadCreatureRespawnTimes();
994
995    sLog.outString( "Loading Gameobject Data..." );
996    objmgr.LoadGameobjects();
997
998    sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
999    objmgr.LoadGameobjectRespawnTimes();
1000
1001    sLog.outString( "Loading Game Event Data...");
1002    gameeventmgr.LoadFromDB();
1003
1004    sLog.outString( "Loading Weather Data..." );
1005    objmgr.LoadWeatherZoneChances();
1006
1007    sLog.outString( "Loading Quests..." );
1008    objmgr.LoadQuests();                                    // must be loaded after DBCs, creature_template, item_template, gameobject tables
1009
1010    sLog.outString( "Loading Quests Relations..." );
1011    objmgr.LoadQuestRelations();                            // must be after quest load
1012
1013    sLog.outString( "Loading AreaTrigger definitions..." );
1014    objmgr.LoadAreaTriggerTeleports();                      // must be after item template load
1015
1016    sLog.outString( "Loading Quest Area Triggers..." );
1017    objmgr.LoadQuestAreaTriggers();                         // must be after LoadQuests
1018
1019    sLog.outString( "Loading Tavern Area Triggers..." );
1020    objmgr.LoadTavernAreaTriggers();
1021   
1022    sLog.outString( "Loading AreaTrigger script names..." );
1023    objmgr.LoadAreaTriggerScripts();
1024
1025
1026    sLog.outString( "Loading Graveyard-zone links...");
1027    objmgr.LoadGraveyardZones();
1028
1029    sLog.outString( "Loading Spell target coordinates..." );
1030    spellmgr.LoadSpellTargetPositions();
1031
1032    sLog.outString( "Loading SpellAffect definitions..." );
1033    spellmgr.LoadSpellAffects();
1034
1035    sLog.outString( "Loading spell pet auras..." );
1036    spellmgr.LoadSpellPetAuras();
1037
1038    sLog.outString( "Loading player Create Info & Level Stats..." );
1039    objmgr.LoadPlayerInfo();
1040
1041    sLog.outString( "Loading Exploration BaseXP Data..." );
1042    objmgr.LoadExplorationBaseXP();
1043
1044    sLog.outString( "Loading Pet Name Parts..." );
1045    objmgr.LoadPetNames();
1046
1047    sLog.outString( "Loading the max pet number..." );
1048    objmgr.LoadPetNumber();
1049
1050    sLog.outString( "Loading pet level stats..." );
1051    objmgr.LoadPetLevelInfo();
1052
1053    sLog.outString( "Loading Player Corpses..." );
1054    objmgr.LoadCorpses();
1055
1056    sLog.outString( "Loading Loot Tables..." );
1057    LoadLootTables();
1058
1059    sLog.outString( "Loading Skill Discovery Table..." );
1060    LoadSkillDiscoveryTable();
1061
1062    sLog.outString( "Loading Skill Extra Item Table..." );
1063    LoadSkillExtraItemTable();
1064
1065    sLog.outString( "Loading Skill Fishing base level requirements..." );
1066    objmgr.LoadFishingBaseSkillLevel();
1067
1068    ///- Load dynamic data tables from the database
1069    sLog.outString( "Loading Auctions..." );
1070    objmgr.LoadAuctionItems();
1071    objmgr.LoadAuctions();
1072
1073    sLog.outString( "Loading Guilds..." );
1074    objmgr.LoadGuilds();
1075
1076    sLog.outString( "Loading ArenaTeams..." );
1077    objmgr.LoadArenaTeams();
1078
1079    sLog.outString( "Loading Groups..." );
1080    objmgr.LoadGroups();
1081
1082    sLog.outString( "Loading ReservedNames..." );
1083    objmgr.LoadReservedPlayersNames();
1084
1085    sLog.outString( "Loading GameObject for quests..." );
1086    objmgr.LoadGameObjectForQuests();
1087
1088    sLog.outString( "Loading BattleMasters..." );
1089    objmgr.LoadBattleMastersEntry();
1090
1091    sLog.outString( "Loading GameTeleports..." );
1092    objmgr.LoadGameTele();
1093
1094    sLog.outString( "Loading Npc Text Id..." );
1095    objmgr.LoadNpcTextId();                                 // must be after load Creature and NpcText
1096
1097    sLog.outString( "Loading vendors..." );
1098    objmgr.LoadVendors();                                   // must be after load CreatureTemplate and ItemTemplate
1099
1100    sLog.outString( "Loading trainers..." );
1101    objmgr.LoadTrainerSpell();                              // must be after load CreatureTemplate
1102
1103    sLog.outString( "Loading Waypoints..." );
1104    WaypointMgr.Load();
1105
1106    ///- Handle outdated emails (delete/return)
1107    sLog.outString( "Returning old mails..." );
1108    objmgr.ReturnOrDeleteOldMails(false);
1109
1110    ///- Load and initialize scripts
1111    sLog.outString( "Loading Scripts..." );
1112    objmgr.LoadQuestStartScripts();                         // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1113    objmgr.LoadQuestEndScripts();                           // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1114    objmgr.LoadSpellScripts();                              // must be after load Creature/Gameobject(Template/Data)
1115    objmgr.LoadGameObjectScripts();                         // must be after load Creature/Gameobject(Template/Data)
1116    objmgr.LoadEventScripts();                              // must be after load Creature/Gameobject(Template/Data)
1117
1118    sLog.outString( "Initializing Scripts..." );
1119    if(!LoadScriptingModule())
1120        exit(1);
1121
1122    ///- Initialize game time and timers
1123    sLog.outString( "DEBUG:: Initialize game time and timers" );
1124    m_gameTime = time(NULL);
1125    m_startTime=m_gameTime;
1126
1127    tm local;
1128    time_t curr;
1129    time(&curr);
1130    local=*(localtime(&curr));                              // dereference and assign
1131    char isoDate[128];
1132    sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1133        local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1134
1135    WorldDatabase.PExecute("INSERT INTO uptime (startstring, starttime, uptime) VALUES('%s', %ld, 0)", isoDate, m_startTime );
1136
1137    m_timers[WUPDATE_OBJECTS].SetInterval(0);
1138    m_timers[WUPDATE_SESSIONS].SetInterval(0);
1139    m_timers[WUPDATE_WEATHERS].SetInterval(1000);
1140    m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*1000);    //set auction update interval to 1 minute
1141    m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
1142                                                            //Update "uptime" table based on configuration entry in minutes.
1143    m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*1000);  //erase corpses every 20 minutes
1144
1145    //to set mailtimer to return mails every day between 4 and 5 am
1146    //mailtimer is increased when updating auctions
1147    //one second is 1000 -(tested on win system)
1148    mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * 1000) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1149                                                            //1440
1150    mail_timer_expires = ( (DAY * 1000) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1151    sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1152
1153    ///- Initilize static helper structures
1154    AIRegistry::Initialize();
1155    WaypointMovementGenerator<Creature>::Initialize();
1156    Player::InitVisibleBits();
1157
1158    ///- Initialize MapManager
1159    sLog.outString( "Starting Map System" );
1160    MapManager::Instance().Initialize();
1161
1162    ///- Initialize Battlegrounds
1163    sLog.outString( "Starting BattleGround System" );
1164    sBattleGroundMgr.CreateInitialBattleGrounds();
1165    sBattleGroundMgr.InitAutomaticArenaPointDistribution();
1166
1167    //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1168    sLog.outString( "Loading Transports..." );
1169    MapManager::Instance().LoadTransports();
1170
1171    sLog.outString("Deleting expired bans..." );
1172    loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1173
1174    sLog.outString("Calculate next daily quest reset time..." );
1175    InitDailyQuestResetTime();
1176
1177    sLog.outString("Starting Game Event system..." );
1178    uint32 nextGameEvent = gameeventmgr.Initialize();
1179    m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);    //depend on next event
1180
1181    sLog.outString( "WORLD: World initialized" );
1182}
1183void World::DetectDBCLang()
1184{
1185    uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1186
1187    if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1188    {
1189        sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1190        m_lang_confid = LOCALE_enUS;
1191    }
1192
1193    ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1194
1195    std::string availableLocalsStr;
1196
1197    int default_locale = MAX_LOCALE;
1198    for (int i = MAX_LOCALE-1; i >= 0; --i)
1199    {
1200        if ( strlen(race->name[i]) > 0)                     // check by race names
1201        {
1202            default_locale = i;
1203            m_availableDbcLocaleMask |= (1 << i);
1204            availableLocalsStr += localeNames[i];
1205            availableLocalsStr += " ";
1206        }
1207    }
1208
1209    if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1210        (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1211    {
1212        default_locale = m_lang_confid;
1213    }
1214
1215    if(default_locale >= MAX_LOCALE)
1216    {
1217        sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1218        exit(1);
1219    }
1220
1221    m_defaultDbcLocale = LocaleConstant(default_locale);
1222
1223    sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1224}
1225
1226/// Update the World !
1227void World::Update(time_t diff)
1228{
1229    ///- Update the different timers
1230    for(int i = 0; i < WUPDATE_COUNT; i++)
1231        if(m_timers[i].GetCurrent()>=0)
1232            m_timers[i].Update(diff);
1233    else m_timers[i].SetCurrent(0);
1234
1235    ///- Update the game time and check for shutdown time
1236    _UpdateGameTime();
1237
1238    /// Handle daily quests reset time
1239    if(m_gameTime > m_NextDailyQuestReset)
1240    {
1241        ResetDailyQuests();
1242        m_NextDailyQuestReset += DAY;
1243    }
1244
1245    /// <ul><li> Handle auctions when the timer has passed
1246    if (m_timers[WUPDATE_AUCTIONS].Passed())
1247    {
1248        m_timers[WUPDATE_AUCTIONS].Reset();
1249
1250        ///- Update mails (return old mails with item, or delete them)
1251        //(tested... works on win)
1252        if (++mail_timer > mail_timer_expires)
1253        {
1254            mail_timer = 0;
1255            objmgr.ReturnOrDeleteOldMails(true);
1256        }
1257
1258        AuctionHouseObject* AuctionMap;
1259        for (int i = 0; i < 3; i++)
1260        {
1261            switch (i)
1262            {
1263                case 0:
1264                    AuctionMap = objmgr.GetAuctionsMap( 6 );//horde
1265                    break;
1266                case 1:
1267                    AuctionMap = objmgr.GetAuctionsMap( 2 );//alliance
1268                    break;
1269                case 2:
1270                    AuctionMap = objmgr.GetAuctionsMap( 7 );//neutral
1271                    break;
1272            }
1273
1274            ///- Handle expired auctions
1275            AuctionHouseObject::AuctionEntryMap::iterator itr,next;
1276            for (itr = AuctionMap->GetAuctionsBegin(); itr != AuctionMap->GetAuctionsEnd();itr = next)
1277            {
1278                next = itr;
1279                ++next;
1280                if (m_gameTime > (itr->second->time))
1281                {
1282                    ///- Either cancel the auction if there was no bidder
1283                    if (itr->second->bidder == 0)
1284                    {
1285                        objmgr.SendAuctionExpiredMail( itr->second );
1286                    }
1287                    ///- Or perform the transaction
1288                    else
1289                    {
1290                        //we should send an "item sold" message if the seller is online
1291                        //we send the item to the winner
1292                        //we send the money to the seller
1293                        objmgr.SendAuctionSuccessfulMail( itr->second );
1294                        objmgr.SendAuctionWonMail( itr->second );
1295                    }
1296
1297                    ///- In any case clear the auction
1298                    //No SQL injection (Id is integer)
1299                    CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",itr->second->Id);
1300                    objmgr.RemoveAItem(itr->second->item_guidlow);
1301                    delete itr->second;
1302                    AuctionMap->RemoveAuction(itr->first);
1303                }
1304            }
1305        }
1306    }
1307
1308    /// <li> Handle session updates when the timer has passed
1309    if (m_timers[WUPDATE_SESSIONS].Passed())
1310    {
1311        m_timers[WUPDATE_SESSIONS].Reset();
1312
1313        UpdateSessions(diff);
1314    }
1315
1316    /// <li> Handle weather updates when the timer has passed
1317    if (m_timers[WUPDATE_WEATHERS].Passed())
1318    {
1319        m_timers[WUPDATE_WEATHERS].Reset();
1320
1321        ///- Send an update signal to Weather objects
1322        WeatherMap::iterator itr, next;
1323        for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1324        {
1325            next = itr;
1326            ++next;
1327
1328            ///- and remove Weather objects for zones with no player
1329                                                            //As interval > WorldTick
1330            if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1331            {
1332                delete itr->second;
1333                m_weathers.erase(itr);
1334            }
1335        }
1336    }
1337    /// <li> Update uptime table
1338    if (m_timers[WUPDATE_UPTIME].Passed())
1339    {
1340        uint32 tmpDiff = (m_gameTime - m_startTime);
1341        uint32 maxClientsNum = sWorld.GetMaxActiveSessionCount();
1342
1343        m_timers[WUPDATE_UPTIME].Reset();
1344        WorldDatabase.PExecute("UPDATE uptime SET uptime = %d, maxplayers = %d WHERE starttime = " I64FMTD, tmpDiff, maxClientsNum, uint64(m_startTime));
1345    }
1346
1347    /// <li> Handle all other objects
1348    if (m_timers[WUPDATE_OBJECTS].Passed())
1349    {
1350        m_timers[WUPDATE_OBJECTS].Reset();
1351        ///- Update objects when the timer has passed (maps, transport, creatures,...)
1352        MapManager::Instance().Update(diff);                // As interval = 0
1353
1354        ///- Process necessary scripts
1355        if (!m_scriptSchedule.empty())
1356            ScriptsProcess();
1357
1358        sBattleGroundMgr.Update(diff);
1359    }
1360
1361    // execute callbacks from sql queries that were queued recently
1362    UpdateResultQueue();
1363
1364    ///- Erase corpses once every 20 minutes
1365    if (m_timers[WUPDATE_CORPSES].Passed())
1366    {
1367        m_timers[WUPDATE_CORPSES].Reset();
1368
1369        CorpsesErase();
1370    }
1371
1372    ///- Process Game events when necessary
1373    if (m_timers[WUPDATE_EVENTS].Passed())
1374    {
1375        m_timers[WUPDATE_EVENTS].Reset();                   // to give time for Update() to be processed
1376        uint32 nextGameEvent = gameeventmgr.Update();
1377        m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1378        m_timers[WUPDATE_EVENTS].Reset();
1379    }
1380
1381    /// </ul>
1382    ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1383    MapManager::Instance().DoDelayedMovesAndRemoves();
1384
1385    // update the instance reset times
1386    sInstanceSaveManager.Update();
1387
1388    // And last, but not least handle the issued cli commands
1389    ProcessCliCommands();
1390}
1391
1392/// Put scripts in the execution queue
1393void World::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
1394{
1395    ///- Find the script map
1396    ScriptMapMap::const_iterator s = scripts.find(id);
1397    if (s == scripts.end())
1398        return;
1399
1400    // prepare static data
1401    uint64 sourceGUID = source->GetGUID();
1402    uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1403    uint64 ownerGUID  = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1404
1405    ///- Schedule script execution for all scripts in the script map
1406    ScriptMap const *s2 = &(s->second);
1407    bool immedScript = false;
1408    for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
1409    {
1410        ScriptAction sa;
1411        sa.sourceGUID = sourceGUID;
1412        sa.targetGUID = targetGUID;
1413        sa.ownerGUID  = ownerGUID;
1414
1415        sa.script = &iter->second;
1416        m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + iter->first, sa));
1417        if (iter->first == 0)
1418            immedScript = true;
1419    }
1420    ///- If one of the effects should be immediate, launch the script execution
1421    if (immedScript)
1422        ScriptsProcess();
1423}
1424
1425void World::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
1426{
1427    // NOTE: script record _must_ exist until command executed
1428
1429    // prepare static data
1430    uint64 sourceGUID = source->GetGUID();
1431    uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1432    uint64 ownerGUID  = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1433
1434    ScriptAction sa;
1435    sa.sourceGUID = sourceGUID;
1436    sa.targetGUID = targetGUID;
1437    sa.ownerGUID  = ownerGUID;
1438
1439    sa.script = &script;
1440    m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + delay, sa));
1441
1442    ///- If effects should be immediate, launch the script execution
1443    if(delay == 0)
1444        ScriptsProcess();
1445}
1446
1447/// Process queued scripts
1448void World::ScriptsProcess()
1449{
1450    if (m_scriptSchedule.empty())
1451        return;
1452
1453    ///- Process overdue queued scripts
1454    std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
1455                                                            // ok as multimap is a *sorted* associative container
1456    while (!m_scriptSchedule.empty() && (iter->first <= m_gameTime))
1457    {
1458        ScriptAction const& step = iter->second;
1459
1460        Object* source = NULL;
1461
1462        if(step.sourceGUID)
1463        {
1464            switch(GUID_HIPART(step.sourceGUID))
1465            {
1466                case HIGHGUID_ITEM:
1467                    // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1468                    {
1469                        Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
1470                        if(player)
1471                            source = player->GetItemByGuid(step.sourceGUID);
1472                        break;
1473                    }
1474                case HIGHGUID_UNIT:
1475                    source = HashMapHolder<Creature>::Find(step.sourceGUID);
1476                    break;
1477                case HIGHGUID_PET:
1478                    source = HashMapHolder<Pet>::Find(step.sourceGUID);
1479                    break;
1480                case HIGHGUID_PLAYER:
1481                    source = HashMapHolder<Player>::Find(step.sourceGUID);
1482                    break;
1483                case HIGHGUID_GAMEOBJECT:
1484                    source = HashMapHolder<GameObject>::Find(step.sourceGUID);
1485                    break;
1486                case HIGHGUID_CORPSE:
1487                    source = HashMapHolder<Corpse>::Find(step.sourceGUID);
1488                    break;
1489                default:
1490                    sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
1491                    break;
1492            }
1493        }
1494
1495        Object* target = NULL;
1496
1497        if(step.targetGUID)
1498        {
1499            switch(GUID_HIPART(step.targetGUID))
1500            {
1501                case HIGHGUID_UNIT:
1502                    target = HashMapHolder<Creature>::Find(step.targetGUID);
1503                    break;
1504                case HIGHGUID_PET:
1505                    target = HashMapHolder<Pet>::Find(step.targetGUID);
1506                    break;
1507                case HIGHGUID_PLAYER:                       // empty GUID case also
1508                    target = HashMapHolder<Player>::Find(step.targetGUID);
1509                    break;
1510                case HIGHGUID_GAMEOBJECT:
1511                    target = HashMapHolder<GameObject>::Find(step.targetGUID);
1512                    break;
1513                case HIGHGUID_CORPSE:
1514                    target = HashMapHolder<Corpse>::Find(step.targetGUID);
1515                    break;
1516                default:
1517                    sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
1518                    break;
1519            }
1520        }
1521
1522        switch (step.script->command)
1523        {
1524            case SCRIPT_COMMAND_TALK:
1525            {
1526                if(!source)
1527                {
1528                    sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1529                    break;
1530                }
1531
1532                if(source->GetTypeId()!=TYPEID_UNIT)
1533                {
1534                    sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1535                    break;
1536                }
1537                if(step.script->datalong > 3)
1538                {
1539                    sLog.outError("SCRIPT_COMMAND_TALK invalid chat type (%u), skipping.",step.script->datalong);
1540                    break;
1541                }
1542
1543                uint64 unit_target = target ? target->GetGUID() : 0;
1544
1545                //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1546                switch(step.script->datalong)
1547                {
1548                    case 0:                                 // Say
1549                        ((Creature *)source)->Say(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
1550                        break;
1551                    case 1:                                 // Whisper
1552                        if(!unit_target)
1553                        {
1554                            sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
1555                            break;
1556                        }
1557                        ((Creature *)source)->Whisper(step.script->datatext.c_str(),unit_target);
1558                        break;
1559                    case 2:                                 // Yell
1560                        ((Creature *)source)->Yell(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
1561                        break;
1562                    case 3:                                 // Emote text
1563                        ((Creature *)source)->TextEmote(step.script->datatext.c_str(), unit_target);
1564                        break;
1565                    default:
1566                        break;                              // must be already checked at load
1567                }
1568                break;
1569            }
1570
1571            case SCRIPT_COMMAND_EMOTE:
1572                if(!source)
1573                {
1574                    sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1575                    break;
1576                }
1577
1578                if(source->GetTypeId()!=TYPEID_UNIT)
1579                {
1580                    sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1581                    break;
1582                }
1583
1584                ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
1585                break;
1586            case SCRIPT_COMMAND_FIELD_SET:
1587                if(!source)
1588                {
1589                    sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1590                    break;
1591                }
1592                if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1593                {
1594                    sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1595                        step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1596                    break;
1597                }
1598
1599                source->SetUInt32Value(step.script->datalong, step.script->datalong2);
1600                break;
1601            case SCRIPT_COMMAND_MOVE_TO:
1602                if(!source)
1603                {
1604                    sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1605                    break;
1606                }
1607
1608                if(source->GetTypeId()!=TYPEID_UNIT)
1609                {
1610                    sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1611                    break;
1612                }
1613                ((Unit *)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, ((Unit *)source)->GetUnitMovementFlags(), step.script->datalong2 );
1614                MapManager::Instance().GetMap(((Unit *)source)->GetMapId(), ((Unit *)source))->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
1615                break;
1616            case SCRIPT_COMMAND_FLAG_SET:
1617                if(!source)
1618                {
1619                    sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1620                    break;
1621                }
1622                if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1623                {
1624                    sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1625                        step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1626                    break;
1627                }
1628
1629                source->SetFlag(step.script->datalong, step.script->datalong2);
1630                break;
1631            case SCRIPT_COMMAND_FLAG_REMOVE:
1632                if(!source)
1633                {
1634                    sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1635                    break;
1636                }
1637                if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1638                {
1639                    sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1640                        step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1641                    break;
1642                }
1643
1644                source->RemoveFlag(step.script->datalong, step.script->datalong2);
1645                break;
1646
1647            case SCRIPT_COMMAND_TELEPORT_TO:
1648            {
1649                // accept player in any one from target/source arg
1650                if (!target && !source)
1651                {
1652                    sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1653                    break;
1654                }
1655
1656                                                            // must be only Player
1657                if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
1658                {
1659                    sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
1660                    break;
1661                }
1662
1663                Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
1664
1665                pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
1666                break;
1667            }
1668
1669            case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
1670            {
1671                if(!step.script->datalong)                  // creature not specified
1672                {
1673                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1674                    break;
1675                }
1676
1677                if(!source)
1678                {
1679                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1680                    break;
1681                }
1682
1683                WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1684
1685                if(!summoner)
1686                {
1687                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1688                    break;
1689                }
1690
1691                float x = step.script->x;
1692                float y = step.script->y;
1693                float z = step.script->z;
1694                float o = step.script->o;
1695
1696                Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
1697                if (!pCreature)
1698                {
1699                    sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
1700                    break;
1701                }
1702
1703                break;
1704            }
1705
1706            case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
1707            {
1708                if(!step.script->datalong)                  // gameobject not specified
1709                {
1710                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1711                    break;
1712                }
1713
1714                if(!source)
1715                {
1716                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1717                    break;
1718                }
1719
1720                WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1721
1722                if(!summoner)
1723                {
1724                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1725                    break;
1726                }
1727
1728                GameObject *go = NULL;
1729                int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
1730
1731                CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
1732                Cell cell(p);
1733                cell.data.Part.reserved = ALL_DISTRICT;
1734
1735                MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
1736                MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(go,go_check);
1737
1738                TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1739                CellLock<GridReadGuard> cell_lock(cell, p);
1740                cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(summoner->GetMapId(), summoner));
1741
1742                if ( !go )
1743                {
1744                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
1745                    break;
1746                }
1747
1748                if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1749                    go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1750                    go->GetGoType()==GAMEOBJECT_TYPE_DOOR        ||
1751                    go->GetGoType()==GAMEOBJECT_TYPE_BUTTON      ||
1752                    go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
1753                {
1754                    sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
1755                    break;
1756                }
1757
1758                if( go->isSpawned() )
1759                    break;                                  //gameobject already spawned
1760
1761                go->SetLootState(GO_READY);
1762                go->SetRespawnTime(time_to_despawn);        //despawn object in ? seconds
1763
1764                MapManager::Instance().GetMap(go->GetMapId(), go)->Add(go);
1765                break;
1766            }
1767            case SCRIPT_COMMAND_OPEN_DOOR:
1768            {
1769                if(!step.script->datalong)                  // door not specified
1770                {
1771                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1772                    break;
1773                }
1774
1775                if(!source)
1776                {
1777                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1778                    break;
1779                }
1780
1781                if(!source->isType(TYPEMASK_UNIT))          // must be any Unit (creature or player)
1782                {
1783                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1784                    break;
1785                }
1786
1787                Unit* caster = (Unit*)source;
1788
1789                GameObject *door = NULL;
1790                int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1791
1792                CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1793                Cell cell(p);
1794                cell.data.Part.reserved = ALL_DISTRICT;
1795
1796                MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1797                MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1798
1799                TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1800                CellLock<GridReadGuard> cell_lock(cell, p);
1801                cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1802
1803                if ( !door )
1804                {
1805                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1806                    break;
1807                }
1808                if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1809                {
1810                    sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1811                    break;
1812                }
1813
1814                if( !door->GetGoState() )
1815                    break;                                  //door already  open
1816
1817                door->UseDoorOrButton(time_to_close);
1818
1819                if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1820                    ((GameObject*)target)->UseDoorOrButton(time_to_close);
1821                break;
1822            }
1823            case SCRIPT_COMMAND_CLOSE_DOOR:
1824            {
1825                if(!step.script->datalong)                  // guid for door not specified
1826                {
1827                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
1828                    break;
1829                }
1830
1831                if(!source)
1832                {
1833                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
1834                    break;
1835                }
1836
1837                if(!source->isType(TYPEMASK_UNIT))          // must be any Unit (creature or player)
1838                {
1839                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1840                    break;
1841                }
1842
1843                Unit* caster = (Unit*)source;
1844
1845                GameObject *door = NULL;
1846                int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1847
1848                CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1849                Cell cell(p);
1850                cell.data.Part.reserved = ALL_DISTRICT;
1851
1852                MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1853                MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1854
1855                TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1856                CellLock<GridReadGuard> cell_lock(cell, p);
1857                cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1858
1859                if ( !door )
1860                {
1861                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1862                    break;
1863                }
1864                if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1865                {
1866                    sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1867                    break;
1868                }
1869
1870                if( door->GetGoState() )
1871                    break;                                  //door already closed
1872
1873                door->UseDoorOrButton(time_to_open);
1874
1875                if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1876                    ((GameObject*)target)->UseDoorOrButton(time_to_open);
1877
1878                break;
1879            }
1880            case SCRIPT_COMMAND_QUEST_EXPLORED:
1881            {
1882                if(!source)
1883                {
1884                    sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
1885                    break;
1886                }
1887
1888                if(!target)
1889                {
1890                    sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
1891                    break;
1892                }
1893
1894                // when script called for item spell casting then target == (unit or GO) and source is player
1895                WorldObject* worldObject;
1896                Player* player;
1897
1898                if(target->GetTypeId()==TYPEID_PLAYER)
1899                {
1900                    if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
1901                    {
1902                        sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
1903                        break;
1904                    }
1905
1906                    worldObject = (WorldObject*)source;
1907                    player = (Player*)target;
1908                }
1909                else
1910                {
1911                    if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
1912                    {
1913                        sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
1914                        break;
1915                    }
1916
1917                    if(source->GetTypeId()!=TYPEID_PLAYER)
1918                    {
1919                        sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
1920                        break;
1921                    }
1922
1923                    worldObject = (WorldObject*)target;
1924                    player = (Player*)source;
1925                }
1926
1927                // quest id and flags checked at script loading
1928                if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
1929                    (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
1930                    player->AreaExploredOrEventHappens(step.script->datalong);
1931                else
1932                    player->FailQuest(step.script->datalong);
1933
1934                break;
1935            }
1936
1937            case SCRIPT_COMMAND_ACTIVATE_OBJECT:
1938            {
1939                if(!source)
1940                {
1941                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
1942                    break;
1943                }
1944
1945                if(!source->isType(TYPEMASK_UNIT))
1946                {
1947                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
1948                    break;
1949                }
1950
1951                if(!target)
1952                {
1953                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
1954                    break;
1955                }
1956
1957                if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
1958                {
1959                    sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
1960                    break;
1961                }
1962
1963                Unit* caster = (Unit*)source;
1964
1965                GameObject *go = (GameObject*)target;
1966
1967                go->Use(caster);
1968                break;
1969            }
1970
1971            case SCRIPT_COMMAND_REMOVE_AURA:
1972            {
1973                Object* cmdTarget = step.script->datalong2 ? source : target;
1974
1975                if(!cmdTarget)
1976                {
1977                    sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
1978                    break;
1979                }
1980
1981                if(!cmdTarget->isType(TYPEMASK_UNIT))
1982                {
1983                    sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
1984                    break;
1985                }
1986
1987                ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
1988                break;
1989            }
1990
1991            case SCRIPT_COMMAND_CAST_SPELL:
1992            {
1993                if(!source)
1994                {
1995                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
1996                    break;
1997                }
1998
1999                if(!source->isType(TYPEMASK_UNIT))
2000                {
2001                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2002                    break;
2003                }
2004
2005                Object* cmdTarget = step.script->datalong2 ? source : target;
2006
2007                if(!cmdTarget)
2008                {
2009                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 ? "source" : "target");
2010                    break;
2011                }
2012
2013                if(!cmdTarget->isType(TYPEMASK_UNIT))
2014                {
2015                    sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2016                    break;
2017                }
2018
2019                Unit* spellTarget = (Unit*)cmdTarget;
2020
2021                //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2022                ((Unit*)source)->CastSpell(spellTarget,step.script->datalong,false);
2023
2024                break;
2025            }
2026
2027            default:
2028                sLog.outError("Unknown script command %u called.",step.script->command);
2029                break;
2030        }
2031
2032        m_scriptSchedule.erase(iter);
2033
2034        iter = m_scriptSchedule.begin();
2035    }
2036    return;
2037}
2038
2039/// Send a packet to all players (except self if mentioned)
2040void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
2041{
2042    SessionMap::iterator itr;
2043    for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2044    {
2045        if (itr->second &&
2046            itr->second->GetPlayer() &&
2047            itr->second->GetPlayer()->IsInWorld() &&
2048            itr->second != self &&
2049            (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2050        {
2051            itr->second->SendPacket(packet);
2052        }
2053    }
2054}
2055
2056/// Send a System Message to all players (except self if mentioned)
2057void World::SendWorldText(int32 string_id, ...)
2058{
2059    std::vector<std::vector<WorldPacket*> > data_cache;     // 0 = default, i => i-1 locale index
2060
2061    for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2062    {
2063        if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
2064            continue;
2065
2066        uint32 loc_idx = itr->second->GetSessionDbLocaleIndex();
2067        uint32 cache_idx = loc_idx+1;
2068
2069        std::vector<WorldPacket*>* data_list;
2070
2071        // create if not cached yet
2072        if(data_cache.size() < cache_idx+1 || data_cache[cache_idx].empty())
2073        {
2074            if(data_cache.size() < cache_idx+1)
2075                data_cache.resize(cache_idx+1);
2076
2077            data_list = &data_cache[cache_idx];
2078
2079            char const* text = objmgr.GetMangosString(string_id,loc_idx);
2080
2081            char buf[1000];
2082
2083            va_list argptr;
2084            va_start( argptr, string_id );
2085            vsnprintf( buf,1000, text, argptr );
2086            va_end( argptr );
2087
2088            char* pos = &buf[0];
2089
2090            while(char* line = ChatHandler::LineFromMessage(pos))
2091            {
2092                WorldPacket* data = new WorldPacket();
2093                ChatHandler::FillMessageData(data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2094                data_list->push_back(data);
2095            }
2096        }
2097        else
2098            data_list = &data_cache[cache_idx];
2099
2100        for(int i = 0; i < data_list->size(); ++i)
2101            itr->second->SendPacket((*data_list)[i]);
2102    }
2103
2104    // free memory
2105    for(int i = 0; i < data_cache.size(); ++i)
2106        for(int j = 0; j < data_cache[i].size(); ++j)
2107            delete data_cache[i][j];
2108}
2109
2110/// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2111void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
2112{
2113    SessionMap::iterator itr;
2114    for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2115    {
2116        if (itr->second &&
2117            itr->second->GetPlayer() &&
2118            itr->second->GetPlayer()->IsInWorld() &&
2119            itr->second->GetPlayer()->GetZoneId() == zone &&
2120            itr->second != self &&
2121            (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2122        {
2123            itr->second->SendPacket(packet);
2124        }
2125    }
2126}
2127
2128/// Send a System Message to all players in the zone (except self if mentioned)
2129void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
2130{
2131    WorldPacket data;
2132    ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
2133    SendZoneMessage(zone, &data, self,team);
2134}
2135
2136/// Kick (and save) all players
2137void World::KickAll()
2138{
2139    // session not removed at kick and will removed in next update tick
2140    for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2141        itr->second->KickPlayer();
2142}
2143
2144/// Kick (and save) all players with security level less `sec`
2145void World::KickAllLess(AccountTypes sec)
2146{
2147    // session not removed at kick and will removed in next update tick
2148    for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2149        if(itr->second->GetSecurity() < sec)
2150            itr->second->KickPlayer();
2151}
2152
2153/// Kick all queued players
2154void World::KickAllQueued()
2155{
2156    // session not removed at kick and will removed in next update tick
2157  //TODO here
2158//    for (Queue::iterator itr = m_QueuedPlayer.begin(); itr != m_QueuedPlayer.end(); ++itr)
2159//        if(WorldSession* session = (*itr)->GetSession())
2160//            session->KickPlayer();
2161
2162    m_QueuedPlayer.empty();
2163}
2164
2165/// Kick (and save) the designated player
2166bool World::KickPlayer(std::string playerName)
2167{
2168    SessionMap::iterator itr;
2169
2170    // session not removed at kick and will removed in next update tick
2171    for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2172    {
2173        if(!itr->second)
2174            continue;
2175        Player *player = itr->second->GetPlayer();
2176        if(!player)
2177            continue;
2178        if( player->IsInWorld() )
2179        {
2180            if (playerName == player->GetName())
2181            {
2182                itr->second->KickPlayer();
2183                return true;
2184            }
2185        }
2186    }
2187    return false;
2188}
2189
2190/// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2191uint8 World::BanAccount(std::string type, std::string nameOrIP, std::string duration, std::string reason, std::string author)
2192{
2193    loginDatabase.escape_string(nameOrIP);
2194    loginDatabase.escape_string(reason);
2195    std::string safe_author=author;
2196    loginDatabase.escape_string(safe_author);
2197
2198    if(type != "ip" && !normalizePlayerName(nameOrIP))
2199        return BAN_NOTFOUND;                                // Nobody to ban
2200
2201    uint32 duration_secs = TimeStringToSecs(duration);
2202    QueryResult *resultAccounts = NULL;                     //used for kicking
2203
2204    ///- Update the database with ban information
2205
2206    if(type=="ip")
2207    {
2208        //No SQL injection as strings are escaped
2209        resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
2210        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());
2211    }
2212    else if(type=="account")
2213    {
2214        //No SQL injection as string is escaped
2215        resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2216    }
2217    else if(type=="character")
2218    {
2219        //No SQL injection as string is escaped
2220        resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2221    }
2222    else
2223        return BAN_SYNTAX_ERROR;                            //Syntax problem
2224
2225    if(!resultAccounts)
2226        if(type=="ip")
2227            return BAN_SUCCESS;                             // ip correctly banned but nobody affected (yet)
2228    else
2229        return BAN_NOTFOUND;                                // Nobody to ban
2230
2231    ///- Disconnect all affected players (for IP it can be several)
2232    do
2233    {
2234        Field* fieldsAccount = resultAccounts->Fetch();
2235        uint32 account = fieldsAccount->GetUInt32();
2236
2237        if(type != "ip")
2238            //No SQL injection as strings are escaped
2239            loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2240                account,duration_secs,safe_author.c_str(),reason.c_str());
2241
2242        WorldSession* sess = FindSession(account);
2243        if( sess )
2244            if(std::string(sess->GetPlayerName()) != author)
2245                sess->KickPlayer();
2246    }
2247    while( resultAccounts->NextRow() );
2248
2249    delete resultAccounts;
2250    return BAN_SUCCESS;
2251}
2252
2253/// Remove a ban from an account or IP address
2254bool World::RemoveBanAccount(std::string type, std::string nameOrIP)
2255{
2256    if(type == "ip")
2257    {
2258        loginDatabase.escape_string(nameOrIP);
2259        loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
2260    }
2261    else
2262    {
2263        uint32 account=0;
2264        if(type == "account")
2265        {
2266            //NO SQL injection as name is escaped
2267            loginDatabase.escape_string(nameOrIP);
2268            QueryResult *resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2269            if(!resultAccounts)
2270                return false;
2271            Field* fieldsAccount = resultAccounts->Fetch();
2272            account = fieldsAccount->GetUInt32();
2273
2274            delete resultAccounts;
2275        }
2276        else if(type == "character")
2277        {
2278            if(!normalizePlayerName(nameOrIP))
2279                return false;
2280
2281            //NO SQL injection as name is escaped
2282            loginDatabase.escape_string(nameOrIP);
2283            QueryResult *resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2284            if(!resultAccounts)
2285                return false;
2286            Field* fieldsAccount = resultAccounts->Fetch();
2287            account = fieldsAccount->GetUInt32();
2288
2289            delete resultAccounts;
2290        }
2291        if(!account)
2292            return false;
2293        //NO SQL injection as account is uint32
2294        loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
2295    }
2296    return true;
2297}
2298
2299/// Update the game time
2300void World::_UpdateGameTime()
2301{
2302    ///- update the time
2303    time_t thisTime = time(NULL);
2304    uint32 elapsed = uint32(thisTime - m_gameTime);
2305    m_gameTime = thisTime;
2306
2307    ///- if there is a shutdown timer
2308    if(m_ShutdownTimer > 0 && elapsed > 0)
2309    {
2310        ///- ... and it is overdue, stop the world (set m_stopEvent)
2311        if( m_ShutdownTimer <= elapsed )
2312        {
2313            if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2314                m_stopEvent = true;
2315            else
2316                m_ShutdownTimer = 1;                        // minimum timer value to wait idle state
2317        }
2318        ///- ... else decrease it and if necessary display a shutdown countdown to the users
2319        else
2320        {
2321            m_ShutdownTimer -= elapsed;
2322
2323            ShutdownMsg();
2324        }
2325    }
2326}
2327
2328/// Shutdown the server
2329void World::ShutdownServ(uint32 time, uint32 options)
2330{
2331    m_ShutdownMask = options;
2332
2333    ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2334    if(time==0)
2335    {
2336        if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2337            m_stopEvent = true;
2338        else
2339            m_ShutdownTimer = 1;                            //So that the session count is re-evaluated at next world tick
2340    }
2341    ///- Else set the shutdown timer and warn users
2342    else
2343    {
2344        m_ShutdownTimer = time;
2345        ShutdownMsg(true);
2346    }
2347}
2348
2349/// Display a shutdown message to the user(s)
2350void World::ShutdownMsg(bool show, Player* player)
2351{
2352    // not show messages for idle shutdown mode
2353    if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
2354        return;
2355
2356    ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2357    if ( show ||
2358        (m_ShutdownTimer < 10) ||
2359                                                            // < 30 sec; every 5 sec
2360        (m_ShutdownTimer<30        && (m_ShutdownTimer % 5         )==0) ||
2361                                                            // < 5 min ; every 1 min
2362        (m_ShutdownTimer<5*MINUTE  && (m_ShutdownTimer % MINUTE    )==0) ||
2363                                                            // < 30 min ; every 5 min
2364        (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
2365                                                            // < 12 h ; every 1 h
2366        (m_ShutdownTimer<12*HOUR   && (m_ShutdownTimer % HOUR      )==0) ||
2367                                                            // > 12 h ; every 12 h
2368        (m_ShutdownTimer>12*HOUR   && (m_ShutdownTimer % (12*HOUR) )==0))
2369    {
2370        std::string str = secsToTimeString(m_ShutdownTimer);
2371
2372        uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
2373
2374        SendServerMessage(msgid,str.c_str(),player);
2375        DEBUG_LOG("Server is %s in %s",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"),str.c_str());
2376    }
2377}
2378
2379/// Cancel a planned server shutdown
2380void World::ShutdownCancel()
2381{
2382    if(!m_ShutdownTimer)
2383        return;
2384
2385    uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2386
2387    m_ShutdownMask = 0;
2388    m_ShutdownTimer = 0;
2389    SendServerMessage(msgid);
2390
2391    DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2392}
2393
2394/// Send a server message to the user(s)
2395void World::SendServerMessage(uint32 type, const char *text, Player* player)
2396{
2397    WorldPacket data(SMSG_SERVER_MESSAGE, 50);              // guess size
2398    data << uint32(type);
2399    if(type <= SERVER_MSG_STRING)
2400        data << text;
2401
2402    if(player)
2403        player->GetSession()->SendPacket(&data);
2404    else
2405        SendGlobalMessage( &data );
2406}
2407
2408void World::UpdateSessions( time_t diff )
2409{
2410    while(!addSessQueue.empty())
2411    {
2412      WorldSession* sess = addSessQueue.next ();
2413      AddSession_ (sess);
2414    }
2415       
2416    ///- Delete kicked sessions at add new session
2417    for (std::set<WorldSession*>::iterator itr = m_kicked_sessions.begin(); itr != m_kicked_sessions.end(); ++itr)
2418        delete *itr;
2419    m_kicked_sessions.clear();
2420
2421    ///- Then send an update signal to remaining ones
2422    for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2423    {
2424        next = itr;
2425        ++next;
2426
2427        if(!itr->second)
2428            continue;
2429
2430        ///- and remove not active sessions from the list
2431        if(!itr->second->Update(diff))                      // As interval = 0
2432        {
2433            delete itr->second;
2434            m_sessions.erase(itr);
2435        }
2436    }
2437}
2438
2439// This handles the issued and queued CLI commands
2440void World::ProcessCliCommands()
2441{
2442    if (cliCmdQueue.empty()) return;
2443
2444    CliCommandHolder *command;
2445    pPrintf p_zprintf;
2446    while (!cliCmdQueue.empty())
2447    {
2448        sLog.outDebug("CLI command under processing...");
2449        command = cliCmdQueue.next();
2450        command->Execute();
2451        p_zprintf=command->GetOutputMethod();
2452        delete command;
2453    }
2454    // print the console message here so it looks right
2455    p_zprintf("mangos>");
2456}
2457
2458void World::InitResultQueue()
2459{
2460    m_resultQueue = new SqlResultQueue;
2461    CharacterDatabase.SetResultQueue(m_resultQueue);
2462}
2463
2464void World::UpdateResultQueue()
2465{
2466    m_resultQueue->Update();
2467}
2468
2469void World::UpdateRealmCharCount(uint32 accountId)
2470{
2471    CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2472        "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2473}
2474
2475void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2476{
2477    if (resultCharCount)
2478    {
2479        Field *fields = resultCharCount->Fetch();
2480        uint32 charCount = fields[0].GetUInt32();
2481        delete resultCharCount;
2482        loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2483        loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2484    }
2485}
2486
2487void World::InitDailyQuestResetTime()
2488{
2489    time_t mostRecentQuestTime;
2490
2491    QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2492    if(result)
2493    {
2494        Field *fields = result->Fetch();
2495
2496        mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2497        delete result;
2498    }
2499    else
2500        mostRecentQuestTime = 0;
2501
2502    // client built-in time for reset is 6:00 AM
2503    // FIX ME: client not show day start time
2504    time_t curTime = time(NULL);
2505    tm localTm = *localtime(&curTime);
2506    localTm.tm_hour = 6;
2507    localTm.tm_min  = 0;
2508    localTm.tm_sec  = 0;
2509
2510    // current day reset time
2511    time_t curDayResetTime = mktime(&localTm);
2512
2513    // last reset time before current moment
2514    time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2515
2516    // need reset (if we have quest time before last reset time (not processed by some reason)
2517    if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2518        m_NextDailyQuestReset = mostRecentQuestTime;
2519    else
2520    {
2521        // plan next reset time
2522        m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2523    }
2524}
2525
2526void World::ResetDailyQuests()
2527{
2528    sLog.outDetail("Daily quests reset for all characters.");
2529    CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2530    for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2531        if(itr->second->GetPlayer())
2532            itr->second->GetPlayer()->ResetDailyQuestStatus();
2533}
2534
2535void World::SetPlayerLimit( int32 limit, bool needUpdate )
2536{
2537    if(limit < -SEC_ADMINISTRATOR)
2538        limit = -SEC_ADMINISTRATOR;
2539
2540    // lock update need
2541    bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2542
2543    m_playerLimit = limit;
2544
2545    if(db_update_need)
2546        loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2547}
2548
2549void World::UpdateMaxSessionCounters()
2550{
2551    m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2552    m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2553}
Note: See TracBrowser for help on using the browser.