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

Revision 279, 107.8 kB (checked in by yumileroy, 17 years ago)

Merged commit 269 (5f0e38da128a).

Original author: gvcoman
Date: 2008-11-21 14:34:05-05:00

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