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

Revision 94, 106.6 kB (checked in by yumileroy, 17 years ago)

[svn] * Use ObjectMgr/AccountMgr? functions rather than DB queries. Source mangos

Original author: KingPin?
Date: 2008-10-21 19:07:16-05:00

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