[9290] Some cleanups in realmd, no functional changes
[getmangos.git] / src / game / World.cpp
bloba9e6f4b8631b86a519f9790262f3b7b7b784716a
1 /*
2 * Copyright (C) 2005-2010 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 /** \file
20 \ingroup world
23 #include "Common.h"
24 #include "Database/DatabaseEnv.h"
25 #include "Config/ConfigEnv.h"
26 #include "SystemConfig.h"
27 #include "Log.h"
28 #include "Opcodes.h"
29 #include "WorldSession.h"
30 #include "WorldPacket.h"
31 #include "Weather.h"
32 #include "Player.h"
33 #include "Vehicle.h"
34 #include "SkillExtraItems.h"
35 #include "SkillDiscovery.h"
36 #include "World.h"
37 #include "AccountMgr.h"
38 #include "AchievementMgr.h"
39 #include "AuctionHouseMgr.h"
40 #include "ObjectMgr.h"
41 #include "CreatureEventAIMgr.h"
42 #include "SpellMgr.h"
43 #include "Chat.h"
44 #include "DBCStores.h"
45 #include "LootMgr.h"
46 #include "ItemEnchantmentMgr.h"
47 #include "MapManager.h"
48 #include "ScriptCalls.h"
49 #include "CreatureAIRegistry.h"
50 #include "Policies/SingletonImp.h"
51 #include "BattleGroundMgr.h"
52 #include "TemporarySummon.h"
53 #include "VMapFactory.h"
54 #include "GlobalEvents.h"
55 #include "GameEventMgr.h"
56 #include "PoolManager.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"
65 INSTANTIATE_SINGLETON_1( World );
67 volatile bool World::m_stopEvent = false;
68 uint8 World::m_ExitCode = SHUTDOWN_EXIT_CODE;
69 volatile uint32 World::m_worldLoopCounter = 0;
71 float World::m_MaxVisibleDistanceOnContinents = DEFAULT_VISIBILITY_DISTANCE;
72 float World::m_MaxVisibleDistanceInInctances = DEFAULT_VISIBILITY_INSTANCE;
73 float World::m_MaxVisibleDistanceInBGArenas = DEFAULT_VISIBILITY_BGARENAS;
74 float World::m_MaxVisibleDistanceForObject = DEFAULT_VISIBILITY_DISTANCE;
76 float World::m_MaxVisibleDistanceInFlight = DEFAULT_VISIBILITY_DISTANCE;
77 float World::m_VisibleUnitGreyDistance = 0;
78 float World::m_VisibleObjectGreyDistance = 0;
80 /// World constructor
81 World::World()
83 m_playerLimit = 0;
84 m_allowMovement = true;
85 m_ShutdownMask = 0;
86 m_ShutdownTimer = 0;
87 m_gameTime=time(NULL);
88 m_startTime=m_gameTime;
89 m_maxActiveSessionCount = 0;
90 m_maxQueuedSessionCount = 0;
91 m_resultQueue = NULL;
92 m_NextDailyQuestReset = 0;
93 m_scheduledScripts = 0;
95 m_defaultDbcLocale = LOCALE_enUS;
96 m_availableDbcLocaleMask = 0;
99 /// World destructor
100 World::~World()
102 ///- Empty the kicked session set
103 while (!m_sessions.empty())
105 // not remove from queue, prevent loading new sessions
106 delete m_sessions.begin()->second;
107 m_sessions.erase(m_sessions.begin());
110 ///- Empty the WeatherMap
111 for (WeatherMap::const_iterator itr = m_weathers.begin(); itr != m_weathers.end(); ++itr)
112 delete itr->second;
114 m_weathers.clear();
116 CliCommandHolder* command;
117 while (cliCmdQueue.next(command))
118 delete command;
120 VMAP::VMapFactory::clear();
122 if(m_resultQueue) delete m_resultQueue;
124 //TODO free addSessQueue
127 /// Find a player in a specified zone
128 Player* World::FindPlayerInZone(uint32 zone)
130 ///- circle through active sessions and return the first player found in the zone
131 SessionMap::const_iterator itr;
132 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
134 if(!itr->second)
135 continue;
136 Player *player = itr->second->GetPlayer();
137 if(!player)
138 continue;
139 if( player->IsInWorld() && player->GetZoneId() == zone )
141 // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone.
142 return player;
145 return NULL;
148 /// Find a session by its id
149 WorldSession* World::FindSession(uint32 id) const
151 SessionMap::const_iterator itr = m_sessions.find(id);
153 if(itr != m_sessions.end())
154 return itr->second; // also can return NULL for kicked session
155 else
156 return NULL;
159 /// Remove a given session
160 bool World::RemoveSession(uint32 id)
162 ///- Find the session, kick the user, but we can't delete session at this moment to prevent iterator invalidation
163 SessionMap::const_iterator itr = m_sessions.find(id);
165 if(itr != m_sessions.end() && itr->second)
167 if (itr->second->PlayerLoading())
168 return false;
169 itr->second->KickPlayer();
172 return true;
175 void World::AddSession(WorldSession* s)
177 addSessQueue.add(s);
180 void
181 World::AddSession_ (WorldSession* s)
183 ASSERT (s);
185 //NOTE - Still there is race condition in WorldSession* being used in the Sockets
187 ///- kick already loaded player with same account (if any) and remove session
188 ///- if player is in loading and want to load again, return
189 if (!RemoveSession (s->GetAccountId ()))
191 s->KickPlayer ();
192 delete s; // session not added yet in session list, so not listed in queue
193 return;
196 // decrease session counts only at not reconnection case
197 bool decrease_session = true;
199 // if session already exist, prepare to it deleting at next world update
200 // NOTE - KickPlayer() should be called on "old" in RemoveSession()
202 SessionMap::const_iterator old = m_sessions.find(s->GetAccountId ());
204 if(old != m_sessions.end())
206 // prevent decrease sessions count if session queued
207 if(RemoveQueuedPlayer(old->second))
208 decrease_session = false;
209 // not remove replaced session form queue if listed
210 delete old->second;
214 m_sessions[s->GetAccountId ()] = s;
216 uint32 Sessions = GetActiveAndQueuedSessionCount ();
217 uint32 pLimit = GetPlayerAmountLimit ();
218 uint32 QueueSize = GetQueueSize (); //number of players in the queue
220 //so we don't count the user trying to
221 //login as a session and queue the socket that we are using
222 if(decrease_session)
223 --Sessions;
225 if (pLimit > 0 && Sessions >= pLimit && s->GetSecurity () == SEC_PLAYER )
227 AddQueuedPlayer (s);
228 UpdateMaxSessionCounters ();
229 sLog.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s->GetAccountId (), ++QueueSize);
230 return;
233 WorldPacket packet(SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
234 packet << uint8 (AUTH_OK);
235 packet << uint32 (0); // BillingTimeRemaining
236 packet << uint8 (0); // BillingPlanFlags
237 packet << uint32 (0); // BillingTimeRested
238 packet << uint8 (s->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
239 s->SendPacket (&packet);
241 s->SendAddonsInfo();
243 WorldPacket pkt(SMSG_CLIENTCACHE_VERSION, 4);
244 pkt << uint32(getConfig(CONFIG_CLIENTCACHE_VERSION));
245 s->SendPacket(&pkt);
247 s->SendTutorialsData();
249 UpdateMaxSessionCounters ();
251 // Updates the population
252 if (pLimit > 0)
254 float popu = GetActiveSessionCount (); // updated number of users on the server
255 popu /= pLimit;
256 popu *= 2;
257 loginDatabase.PExecute ("UPDATE realmlist SET population = '%f' WHERE id = '%d'", popu, realmID);
258 sLog.outDetail ("Server Population (%f).", popu);
262 int32 World::GetQueuePos(WorldSession* sess)
264 uint32 position = 1;
266 for(Queue::const_iterator iter = m_QueuedPlayer.begin(); iter != m_QueuedPlayer.end(); ++iter, ++position)
267 if((*iter) == sess)
268 return position;
270 return 0;
273 void World::AddQueuedPlayer(WorldSession* sess)
275 sess->SetInQueue(true);
276 m_QueuedPlayer.push_back (sess);
278 // The 1st SMSG_AUTH_RESPONSE needs to contain other info too.
279 WorldPacket packet (SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1 + 4 + 1);
280 packet << uint8 (AUTH_WAIT_QUEUE);
281 packet << uint32 (0); // BillingTimeRemaining
282 packet << uint8 (0); // BillingPlanFlags
283 packet << uint32 (0); // BillingTimeRested
284 packet << uint8 (sess->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
285 packet << uint32(GetQueuePos (sess)); // position in queue
286 packet << uint8(0); // unk 3.3.0
287 sess->SendPacket (&packet);
290 bool World::RemoveQueuedPlayer(WorldSession* sess)
292 // sessions count including queued to remove (if removed_session set)
293 uint32 sessions = GetActiveSessionCount();
295 uint32 position = 1;
296 Queue::iterator iter = m_QueuedPlayer.begin();
298 // search to remove and count skipped positions
299 bool found = false;
301 for(;iter != m_QueuedPlayer.end(); ++iter, ++position)
303 if(*iter==sess)
305 sess->SetInQueue(false);
306 iter = m_QueuedPlayer.erase(iter);
307 found = true; // removing queued session
308 break;
312 // iter point to next socked after removed or end()
313 // position store position of removed socket and then new position next socket after removed
315 // if session not queued then we need decrease sessions count
316 if(!found && sessions)
317 --sessions;
319 // accept first in queue
320 if( (!m_playerLimit || sessions < m_playerLimit) && !m_QueuedPlayer.empty() )
322 WorldSession* pop_sess = m_QueuedPlayer.front();
323 pop_sess->SetInQueue(false);
324 pop_sess->SendAuthWaitQue(0);
325 pop_sess->SendAddonsInfo();
327 WorldPacket pkt(SMSG_CLIENTCACHE_VERSION, 4);
328 pkt << uint32(getConfig(CONFIG_CLIENTCACHE_VERSION));
329 pop_sess->SendPacket(&pkt);
331 pop_sess->SendAccountDataTimes(GLOBAL_CACHE_MASK);
332 pop_sess->SendTutorialsData();
334 m_QueuedPlayer.pop_front();
336 // update iter to point first queued socket or end() if queue is empty now
337 iter = m_QueuedPlayer.begin();
338 position = 1;
341 // update position from iter to end()
342 // iter point to first not updated socket, position store new position
343 for(; iter != m_QueuedPlayer.end(); ++iter, ++position)
344 (*iter)->SendAuthWaitQue(position);
346 return found;
349 /// Find a Weather object by the given zoneid
350 Weather* World::FindWeather(uint32 id) const
352 WeatherMap::const_iterator itr = m_weathers.find(id);
354 if(itr != m_weathers.end())
355 return itr->second;
356 else
357 return 0;
360 /// Remove a Weather object for the given zoneid
361 void World::RemoveWeather(uint32 id)
363 // not called at the moment. Kept for completeness
364 WeatherMap::iterator itr = m_weathers.find(id);
366 if(itr != m_weathers.end())
368 delete itr->second;
369 m_weathers.erase(itr);
373 /// Add a Weather object to the list
374 Weather* World::AddWeather(uint32 zone_id)
376 WeatherZoneChances const* weatherChances = sObjectMgr.GetWeatherChances(zone_id);
378 // zone not have weather, ignore
379 if(!weatherChances)
380 return NULL;
382 Weather* w = new Weather(zone_id,weatherChances);
383 m_weathers[w->GetZone()] = w;
384 w->ReGenerate();
385 w->UpdateWeather();
386 return w;
389 /// Initialize config values
390 void World::LoadConfigSettings(bool reload)
392 if(reload)
394 if(!sConfig.Reload())
396 sLog.outError("World settings reload fail: can't read settings from %s.",sConfig.GetFilename().c_str());
397 return;
401 ///- Read the version of the configuration file and warn the user in case of emptiness or mismatch
402 uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
403 if(!confVersion)
405 sLog.outError("*****************************************************************************");
406 sLog.outError(" WARNING: mangosd.conf does not include a ConfVersion variable.");
407 sLog.outError(" Your configuration file may be out of date!");
408 sLog.outError("*****************************************************************************");
409 clock_t pause = 3000 + clock();
410 while (pause > clock())
411 ; // empty body
413 else
415 if (confVersion < _MANGOSDCONFVERSION)
417 sLog.outError("*****************************************************************************");
418 sLog.outError(" WARNING: Your mangosd.conf version indicates your conf file is out of date!");
419 sLog.outError(" Please check for updates, as your current default values may cause");
420 sLog.outError(" unexpected behavior.");
421 sLog.outError("*****************************************************************************");
422 clock_t pause = 3000 + clock();
423 while (pause > clock())
424 ; // empty body
428 ///- Read the player limit and the Message of the day from the config file
429 SetPlayerLimit( sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT), true );
430 SetMotd( sConfig.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
432 ///- Read all rates from the config file
433 rate_values[RATE_HEALTH] = sConfig.GetFloatDefault("Rate.Health", 1);
434 if(rate_values[RATE_HEALTH] < 0)
436 sLog.outError("Rate.Health (%f) must be > 0. Using 1 instead.",rate_values[RATE_HEALTH]);
437 rate_values[RATE_HEALTH] = 1;
439 rate_values[RATE_POWER_MANA] = sConfig.GetFloatDefault("Rate.Mana", 1);
440 if(rate_values[RATE_POWER_MANA] < 0)
442 sLog.outError("Rate.Mana (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_MANA]);
443 rate_values[RATE_POWER_MANA] = 1;
445 rate_values[RATE_POWER_RAGE_INCOME] = sConfig.GetFloatDefault("Rate.Rage.Income", 1);
446 rate_values[RATE_POWER_RAGE_LOSS] = sConfig.GetFloatDefault("Rate.Rage.Loss", 1);
447 if(rate_values[RATE_POWER_RAGE_LOSS] < 0)
449 sLog.outError("Rate.Rage.Loss (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_RAGE_LOSS]);
450 rate_values[RATE_POWER_RAGE_LOSS] = 1;
452 rate_values[RATE_POWER_RUNICPOWER_INCOME] = sConfig.GetFloatDefault("Rate.RunicPower.Income", 1);
453 rate_values[RATE_POWER_RUNICPOWER_LOSS] = sConfig.GetFloatDefault("Rate.RunicPower.Loss", 1);
454 if(rate_values[RATE_POWER_RUNICPOWER_LOSS] < 0)
456 sLog.outError("Rate.RunicPower.Loss (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_RUNICPOWER_LOSS]);
457 rate_values[RATE_POWER_RUNICPOWER_LOSS] = 1;
459 rate_values[RATE_POWER_FOCUS] = sConfig.GetFloatDefault("Rate.Focus", 1.0f);
460 rate_values[RATE_SKILL_DISCOVERY] = sConfig.GetFloatDefault("Rate.Skill.Discovery", 1.0f);
461 rate_values[RATE_DROP_ITEM_POOR] = sConfig.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f);
462 rate_values[RATE_DROP_ITEM_NORMAL] = sConfig.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f);
463 rate_values[RATE_DROP_ITEM_UNCOMMON] = sConfig.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f);
464 rate_values[RATE_DROP_ITEM_RARE] = sConfig.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f);
465 rate_values[RATE_DROP_ITEM_EPIC] = sConfig.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f);
466 rate_values[RATE_DROP_ITEM_LEGENDARY] = sConfig.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f);
467 rate_values[RATE_DROP_ITEM_ARTIFACT] = sConfig.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f);
468 rate_values[RATE_DROP_ITEM_REFERENCED] = sConfig.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f);
469 rate_values[RATE_DROP_MONEY] = sConfig.GetFloatDefault("Rate.Drop.Money", 1.0f);
470 rate_values[RATE_XP_KILL] = sConfig.GetFloatDefault("Rate.XP.Kill", 1.0f);
471 rate_values[RATE_XP_QUEST] = sConfig.GetFloatDefault("Rate.XP.Quest", 1.0f);
472 rate_values[RATE_XP_EXPLORE] = sConfig.GetFloatDefault("Rate.XP.Explore", 1.0f);
473 rate_values[RATE_REPUTATION_GAIN] = sConfig.GetFloatDefault("Rate.Reputation.Gain", 1.0f);
474 rate_values[RATE_REPUTATION_LOWLEVEL_KILL] = sConfig.GetFloatDefault("Rate.Reputation.LowLevel.Kill", 1.0f);
475 rate_values[RATE_REPUTATION_LOWLEVEL_QUEST] = sConfig.GetFloatDefault("Rate.Reputation.LowLevel.Quest", 1.0f);
476 rate_values[RATE_CREATURE_NORMAL_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f);
477 rate_values[RATE_CREATURE_ELITE_ELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f);
478 rate_values[RATE_CREATURE_ELITE_RAREELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f);
479 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f);
480 rate_values[RATE_CREATURE_ELITE_RARE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f);
481 rate_values[RATE_CREATURE_NORMAL_HP] = sConfig.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f);
482 rate_values[RATE_CREATURE_ELITE_ELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f);
483 rate_values[RATE_CREATURE_ELITE_RAREELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f);
484 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f);
485 rate_values[RATE_CREATURE_ELITE_RARE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f);
486 rate_values[RATE_CREATURE_NORMAL_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f);
487 rate_values[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f);
488 rate_values[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f);
489 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f);
490 rate_values[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f);
491 rate_values[RATE_CREATURE_AGGRO] = sConfig.GetFloatDefault("Rate.Creature.Aggro", 1.0f);
492 rate_values[RATE_REST_INGAME] = sConfig.GetFloatDefault("Rate.Rest.InGame", 1.0f);
493 rate_values[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY] = sConfig.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f);
494 rate_values[RATE_REST_OFFLINE_IN_WILDERNESS] = sConfig.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f);
495 rate_values[RATE_DAMAGE_FALL] = sConfig.GetFloatDefault("Rate.Damage.Fall", 1.0f);
496 rate_values[RATE_AUCTION_TIME] = sConfig.GetFloatDefault("Rate.Auction.Time", 1.0f);
497 rate_values[RATE_AUCTION_DEPOSIT] = sConfig.GetFloatDefault("Rate.Auction.Deposit", 1.0f);
498 rate_values[RATE_AUCTION_CUT] = sConfig.GetFloatDefault("Rate.Auction.Cut", 1.0f);
499 rate_values[RATE_HONOR] = sConfig.GetFloatDefault("Rate.Honor",1.0f);
500 rate_values[RATE_MINING_AMOUNT] = sConfig.GetFloatDefault("Rate.Mining.Amount",1.0f);
501 rate_values[RATE_MINING_NEXT] = sConfig.GetFloatDefault("Rate.Mining.Next",1.0f);
502 rate_values[RATE_INSTANCE_RESET_TIME] = sConfig.GetFloatDefault("Rate.InstanceResetTime",1.0f);
503 rate_values[RATE_TALENT] = sConfig.GetFloatDefault("Rate.Talent",1.0f);
504 if(rate_values[RATE_TALENT] < 0.0f)
506 sLog.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_TALENT]);
507 rate_values[RATE_TALENT] = 1.0f;
509 rate_values[RATE_CORPSE_DECAY_LOOTED] = sConfig.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f);
511 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = sConfig.GetFloatDefault("TargetPosRecalculateRange",1.5f);
512 if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] < CONTACT_DISTANCE)
514 sLog.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],CONTACT_DISTANCE,CONTACT_DISTANCE);
515 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = CONTACT_DISTANCE;
517 else if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] > ATTACK_DISTANCE)
519 sLog.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",
520 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],ATTACK_DISTANCE,ATTACK_DISTANCE);
521 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = ATTACK_DISTANCE;
524 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = sConfig.GetFloatDefault("DurabilityLossChance.Damage",0.5f);
525 if(rate_values[RATE_DURABILITY_LOSS_DAMAGE] < 0.0f)
527 sLog.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_DAMAGE]);
528 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = 0.0f;
530 rate_values[RATE_DURABILITY_LOSS_ABSORB] = sConfig.GetFloatDefault("DurabilityLossChance.Absorb",0.5f);
531 if(rate_values[RATE_DURABILITY_LOSS_ABSORB] < 0.0f)
533 sLog.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_ABSORB]);
534 rate_values[RATE_DURABILITY_LOSS_ABSORB] = 0.0f;
536 rate_values[RATE_DURABILITY_LOSS_PARRY] = sConfig.GetFloatDefault("DurabilityLossChance.Parry",0.05f);
537 if(rate_values[RATE_DURABILITY_LOSS_PARRY] < 0.0f)
539 sLog.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_PARRY]);
540 rate_values[RATE_DURABILITY_LOSS_PARRY] = 0.0f;
542 rate_values[RATE_DURABILITY_LOSS_BLOCK] = sConfig.GetFloatDefault("DurabilityLossChance.Block",0.05f);
543 if(rate_values[RATE_DURABILITY_LOSS_BLOCK] < 0.0f)
545 sLog.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_BLOCK]);
546 rate_values[RATE_DURABILITY_LOSS_BLOCK] = 0.0f;
549 ///- Read other configuration items from the config file
551 m_configs[CONFIG_COMPRESSION] = sConfig.GetIntDefault("Compression", 1);
552 if(m_configs[CONFIG_COMPRESSION] < 1 || m_configs[CONFIG_COMPRESSION] > 9)
554 sLog.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs[CONFIG_COMPRESSION]);
555 m_configs[CONFIG_COMPRESSION] = 1;
557 m_configs[CONFIG_ADDON_CHANNEL] = sConfig.GetBoolDefault("AddonChannel", true);
558 m_configs[CONFIG_GRID_UNLOAD] = sConfig.GetBoolDefault("GridUnload", true);
559 m_configs[CONFIG_INTERVAL_SAVE] = sConfig.GetIntDefault("PlayerSaveInterval", 15 * MINUTE * IN_MILISECONDS);
561 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = sConfig.GetIntDefault("GridCleanUpDelay", 5 * MINUTE * IN_MILISECONDS);
562 if(m_configs[CONFIG_INTERVAL_GRIDCLEAN] < MIN_GRID_DELAY)
564 sLog.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_GRIDCLEAN],MIN_GRID_DELAY);
565 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = MIN_GRID_DELAY;
567 if(reload)
568 sMapMgr.SetGridCleanUpDelay(m_configs[CONFIG_INTERVAL_GRIDCLEAN]);
570 m_configs[CONFIG_INTERVAL_MAPUPDATE] = sConfig.GetIntDefault("MapUpdateInterval", 100);
571 if(m_configs[CONFIG_INTERVAL_MAPUPDATE] < MIN_MAP_UPDATE_DELAY)
573 sLog.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_MAPUPDATE],MIN_MAP_UPDATE_DELAY);
574 m_configs[CONFIG_INTERVAL_MAPUPDATE] = MIN_MAP_UPDATE_DELAY;
576 if(reload)
577 sMapMgr.SetMapUpdateInterval(m_configs[CONFIG_INTERVAL_MAPUPDATE]);
579 m_configs[CONFIG_INTERVAL_CHANGEWEATHER] = sConfig.GetIntDefault("ChangeWeatherInterval", 10 * MINUTE * IN_MILISECONDS);
581 if(reload)
583 uint32 val = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
584 if(val!=m_configs[CONFIG_PORT_WORLD])
585 sLog.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_PORT_WORLD]);
587 else
588 m_configs[CONFIG_PORT_WORLD] = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
590 if(reload)
592 uint32 val = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
593 if(val!=m_configs[CONFIG_SOCKET_SELECTTIME])
594 sLog.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_SOCKET_SELECTTIME]);
596 else
597 m_configs[CONFIG_SOCKET_SELECTTIME] = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
599 m_configs[CONFIG_GROUP_XP_DISTANCE] = sConfig.GetIntDefault("MaxGroupXPDistance", 74);
600 /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
601 m_configs[CONFIG_SIGHT_MONSTER] = sConfig.GetIntDefault("MonsterSight", 50);
602 m_configs[CONFIG_SIGHT_GUARDER] = sConfig.GetIntDefault("GuarderSight", 50);
604 if(reload)
606 uint32 val = sConfig.GetIntDefault("GameType", 0);
607 if(val!=m_configs[CONFIG_GAME_TYPE])
608 sLog.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_GAME_TYPE]);
610 else
611 m_configs[CONFIG_GAME_TYPE] = sConfig.GetIntDefault("GameType", 0);
613 if(reload)
615 uint32 val = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
616 if(val!=m_configs[CONFIG_REALM_ZONE])
617 sLog.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_REALM_ZONE]);
619 else
620 m_configs[CONFIG_REALM_ZONE] = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
622 m_configs[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS] = sConfig.GetBoolDefault("AllowTwoSide.Accounts", false);
623 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
624 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
625 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
626 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
627 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
628 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
629 m_configs[CONFIG_ALLOW_TWO_SIDE_WHO_LIST] = sConfig.GetBoolDefault("AllowTwoSide.WhoList", false);
630 m_configs[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND] = sConfig.GetBoolDefault("AllowTwoSide.AddFriend", false);
631 m_configs[CONFIG_STRICT_PLAYER_NAMES] = sConfig.GetIntDefault ("StrictPlayerNames", 0);
632 m_configs[CONFIG_STRICT_CHARTER_NAMES] = sConfig.GetIntDefault ("StrictCharterNames", 0);
633 m_configs[CONFIG_STRICT_PET_NAMES] = sConfig.GetIntDefault ("StrictPetNames", 0);
635 m_configs[CONFIG_MIN_PLAYER_NAME] = sConfig.GetIntDefault ("MinPlayerName", 2);
636 if(m_configs[CONFIG_MIN_PLAYER_NAME] < 1 || m_configs[CONFIG_MIN_PLAYER_NAME] > MAX_PLAYER_NAME)
638 sLog.outError("MinPlayerName (%i) must be in range 1..%u. Set to 2.",m_configs[CONFIG_MIN_PLAYER_NAME],MAX_PLAYER_NAME);
639 m_configs[CONFIG_MIN_PLAYER_NAME] = 2;
642 m_configs[CONFIG_MIN_CHARTER_NAME] = sConfig.GetIntDefault ("MinCharterName", 2);
643 if(m_configs[CONFIG_MIN_CHARTER_NAME] < 1 || m_configs[CONFIG_MIN_CHARTER_NAME] > MAX_CHARTER_NAME)
645 sLog.outError("MinCharterName (%i) must be in range 1..%u. Set to 2.",m_configs[CONFIG_MIN_CHARTER_NAME],MAX_CHARTER_NAME);
646 m_configs[CONFIG_MIN_CHARTER_NAME] = 2;
649 m_configs[CONFIG_MIN_PET_NAME] = sConfig.GetIntDefault ("MinPetName", 2);
650 if(m_configs[CONFIG_MIN_PET_NAME] < 1 || m_configs[CONFIG_MIN_PET_NAME] > MAX_PET_NAME)
652 sLog.outError("MinPetName (%i) must be in range 1..%u. Set to 2.",m_configs[CONFIG_MIN_PET_NAME],MAX_PET_NAME);
653 m_configs[CONFIG_MIN_PET_NAME] = 2;
656 m_configs[CONFIG_CHARACTERS_CREATING_DISABLED] = sConfig.GetIntDefault ("CharactersCreatingDisabled", 0);
658 m_configs[CONFIG_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("CharactersPerRealm", 10);
659 if(m_configs[CONFIG_CHARACTERS_PER_REALM] < 1 || m_configs[CONFIG_CHARACTERS_PER_REALM] > 10)
661 sLog.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs[CONFIG_CHARACTERS_PER_REALM]);
662 m_configs[CONFIG_CHARACTERS_PER_REALM] = 10;
665 // must be after CONFIG_CHARACTERS_PER_REALM
666 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = sConfig.GetIntDefault("CharactersPerAccount", 50);
667 if(m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] < m_configs[CONFIG_CHARACTERS_PER_REALM])
669 sLog.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs[CONFIG_CHARACTERS_PER_ACCOUNT],m_configs[CONFIG_CHARACTERS_PER_REALM]);
670 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = m_configs[CONFIG_CHARACTERS_PER_REALM];
673 m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("HeroicCharactersPerRealm", 1);
674 if(int32(m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM]) < 0 || m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] > 10)
676 sLog.outError("HeroicCharactersPerRealm (%i) must be in range 0..10. Set to 1.",m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM]);
677 m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] = 1;
680 m_configs[CONFIG_MIN_LEVEL_FOR_HEROIC_CHARACTER_CREATING] = sConfig.GetIntDefault("MinLevelForHeroicCharacterCreating", 55);
682 m_configs[CONFIG_SKIP_CINEMATICS] = sConfig.GetIntDefault("SkipCinematics", 0);
683 if(int32(m_configs[CONFIG_SKIP_CINEMATICS]) < 0 || m_configs[CONFIG_SKIP_CINEMATICS] > 2)
685 sLog.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs[CONFIG_SKIP_CINEMATICS]);
686 m_configs[CONFIG_SKIP_CINEMATICS] = 0;
689 if(reload)
691 uint32 val = sConfig.GetIntDefault("MaxPlayerLevel", DEFAULT_MAX_LEVEL);
692 if(val!=m_configs[CONFIG_MAX_PLAYER_LEVEL])
693 sLog.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
695 else
696 m_configs[CONFIG_MAX_PLAYER_LEVEL] = sConfig.GetIntDefault("MaxPlayerLevel", DEFAULT_MAX_LEVEL);
698 if(m_configs[CONFIG_MAX_PLAYER_LEVEL] > MAX_LEVEL)
700 sLog.outError("MaxPlayerLevel (%i) must be in range 1..%u. Set to %u.",m_configs[CONFIG_MAX_PLAYER_LEVEL],MAX_LEVEL,MAX_LEVEL);
701 m_configs[CONFIG_MAX_PLAYER_LEVEL] = MAX_LEVEL;
704 m_configs[CONFIG_START_PLAYER_LEVEL] = sConfig.GetIntDefault("StartPlayerLevel", 1);
705 if(m_configs[CONFIG_START_PLAYER_LEVEL] < 1)
707 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]);
708 m_configs[CONFIG_START_PLAYER_LEVEL] = 1;
710 else if(m_configs[CONFIG_START_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
712 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]);
713 m_configs[CONFIG_START_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
716 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = sConfig.GetIntDefault("StartHeroicPlayerLevel", 55);
717 if(m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] < 1)
719 sLog.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to 55.",
720 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
721 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = 55;
723 else if(m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
725 sLog.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to %u.",
726 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
727 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
730 m_configs[CONFIG_START_PLAYER_MONEY] = sConfig.GetIntDefault("StartPlayerMoney", 0);
731 if(int32(m_configs[CONFIG_START_PLAYER_MONEY]) < 0)
733 sLog.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",m_configs[CONFIG_START_PLAYER_MONEY],MAX_MONEY_AMOUNT,0);
734 m_configs[CONFIG_START_PLAYER_MONEY] = 0;
736 else if(m_configs[CONFIG_START_PLAYER_MONEY] > MAX_MONEY_AMOUNT)
738 sLog.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",
739 m_configs[CONFIG_START_PLAYER_MONEY],MAX_MONEY_AMOUNT,MAX_MONEY_AMOUNT);
740 m_configs[CONFIG_START_PLAYER_MONEY] = MAX_MONEY_AMOUNT;
743 m_configs[CONFIG_MAX_HONOR_POINTS] = sConfig.GetIntDefault("MaxHonorPoints", 75000);
744 if(int32(m_configs[CONFIG_MAX_HONOR_POINTS]) < 0)
746 sLog.outError("MaxHonorPoints (%i) can't be negative. Set to 0.",m_configs[CONFIG_MAX_HONOR_POINTS]);
747 m_configs[CONFIG_MAX_HONOR_POINTS] = 0;
750 m_configs[CONFIG_START_HONOR_POINTS] = sConfig.GetIntDefault("StartHonorPoints", 0);
751 if(int32(m_configs[CONFIG_START_HONOR_POINTS]) < 0)
753 sLog.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
754 m_configs[CONFIG_START_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS],0);
755 m_configs[CONFIG_START_HONOR_POINTS] = 0;
757 else if(m_configs[CONFIG_START_HONOR_POINTS] > m_configs[CONFIG_MAX_HONOR_POINTS])
759 sLog.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
760 m_configs[CONFIG_START_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS]);
761 m_configs[CONFIG_START_HONOR_POINTS] = m_configs[CONFIG_MAX_HONOR_POINTS];
764 m_configs[CONFIG_MAX_ARENA_POINTS] = sConfig.GetIntDefault("MaxArenaPoints", 5000);
765 if(int32(m_configs[CONFIG_MAX_ARENA_POINTS]) < 0)
767 sLog.outError("MaxArenaPoints (%i) can't be negative. Set to 0.",m_configs[CONFIG_MAX_ARENA_POINTS]);
768 m_configs[CONFIG_MAX_ARENA_POINTS] = 0;
771 m_configs[CONFIG_START_ARENA_POINTS] = sConfig.GetIntDefault("StartArenaPoints", 0);
772 if(int32(m_configs[CONFIG_START_ARENA_POINTS]) < 0)
774 sLog.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
775 m_configs[CONFIG_START_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS],0);
776 m_configs[CONFIG_MAX_ARENA_POINTS] = 0;
778 else if(m_configs[CONFIG_START_ARENA_POINTS] > m_configs[CONFIG_MAX_ARENA_POINTS])
780 sLog.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
781 m_configs[CONFIG_START_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS]);
782 m_configs[CONFIG_START_ARENA_POINTS] = m_configs[CONFIG_MAX_ARENA_POINTS];
785 m_configs[CONFIG_ALL_TAXI_PATHS] = sConfig.GetBoolDefault("AllFlightPaths", false);
787 m_configs[CONFIG_INSTANCE_IGNORE_LEVEL] = sConfig.GetBoolDefault("Instance.IgnoreLevel", false);
788 m_configs[CONFIG_INSTANCE_IGNORE_RAID] = sConfig.GetBoolDefault("Instance.IgnoreRaid", false);
790 m_configs[CONFIG_CAST_UNSTUCK] = sConfig.GetBoolDefault("CastUnstuck", true);
791 m_configs[CONFIG_INSTANCE_RESET_TIME_HOUR] = sConfig.GetIntDefault("Instance.ResetTimeHour", 4);
792 m_configs[CONFIG_INSTANCE_UNLOAD_DELAY] = sConfig.GetIntDefault("Instance.UnloadDelay", 30 * MINUTE * IN_MILISECONDS);
794 m_configs[CONFIG_MAX_PRIMARY_TRADE_SKILL] = sConfig.GetIntDefault("MaxPrimaryTradeSkill", 2);
795 m_configs[CONFIG_MIN_PETITION_SIGNS] = sConfig.GetIntDefault("MinPetitionSigns", 9);
796 if(m_configs[CONFIG_MIN_PETITION_SIGNS] > 9)
798 sLog.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.", m_configs[CONFIG_MIN_PETITION_SIGNS]);
799 m_configs[CONFIG_MIN_PETITION_SIGNS] = 9;
802 m_configs[CONFIG_GM_LOGIN_STATE] = sConfig.GetIntDefault("GM.LoginState", 2);
803 m_configs[CONFIG_GM_VISIBLE_STATE] = sConfig.GetIntDefault("GM.Visible", 2);
804 m_configs[CONFIG_GM_ACCEPT_TICKETS] = sConfig.GetIntDefault("GM.AcceptTickets", 2);
805 m_configs[CONFIG_GM_CHAT] = sConfig.GetIntDefault("GM.Chat", 2);
806 m_configs[CONFIG_GM_WISPERING_TO] = sConfig.GetIntDefault("GM.WhisperingTo", 2);
808 m_configs[CONFIG_GM_LEVEL_IN_GM_LIST] = sConfig.GetIntDefault("GM.InGMList.Level", SEC_ADMINISTRATOR);
809 m_configs[CONFIG_GM_LEVEL_IN_WHO_LIST] = sConfig.GetIntDefault("GM.InWhoList.Level", SEC_ADMINISTRATOR);
810 m_configs[CONFIG_GM_LOG_TRADE] = sConfig.GetBoolDefault("GM.LogTrade", false);
812 m_configs[CONFIG_START_GM_LEVEL] = sConfig.GetIntDefault("GM.StartLevel", 1);
813 if(m_configs[CONFIG_START_GM_LEVEL] < m_configs[CONFIG_START_PLAYER_LEVEL])
815 sLog.outError("GM.StartLevel (%i) must be in range StartPlayerLevel(%u)..%u. Set to %u.",
816 m_configs[CONFIG_START_GM_LEVEL],m_configs[CONFIG_START_PLAYER_LEVEL], MAX_LEVEL, m_configs[CONFIG_START_PLAYER_LEVEL]);
817 m_configs[CONFIG_START_GM_LEVEL] = m_configs[CONFIG_START_PLAYER_LEVEL];
819 else if(m_configs[CONFIG_START_GM_LEVEL] > MAX_LEVEL)
821 sLog.outError("GM.StartLevel (%i) must be in range 1..%u. Set to %u.", m_configs[CONFIG_START_GM_LEVEL], MAX_LEVEL, MAX_LEVEL);
822 m_configs[CONFIG_START_GM_LEVEL] = MAX_LEVEL;
824 m_configs[CONFIG_GM_LOWER_SECURITY] = sConfig.GetBoolDefault("GM.LowerSecurity", false);
825 m_configs[CONFIG_GM_ALLOW_ACHIEVEMENT_GAINS] = sConfig.GetBoolDefault("GM.AllowAchievementGain", true);
827 m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
829 m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
831 m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
832 if(int32(m_configs[CONFIG_UPTIME_UPDATE])<=0)
834 sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
835 m_configs[CONFIG_UPTIME_UPDATE] = 10;
837 if(reload)
839 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*IN_MILISECONDS);
840 m_timers[WUPDATE_UPTIME].Reset();
843 m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
844 m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
845 m_configs[CONFIG_SKILL_CHANCE_GREEN] = sConfig.GetIntDefault("SkillChance.Green",25);
846 m_configs[CONFIG_SKILL_CHANCE_GREY] = sConfig.GetIntDefault("SkillChance.Grey",0);
848 m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS] = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
849 m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS] = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
851 m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
852 m_configs[CONFIG_SKILL_MILLING] = sConfig.GetBoolDefault("SkillChance.Milling",false);
854 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = sConfig.GetIntDefault("SkillGain.Crafting", 1);
855 if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
857 sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
858 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
861 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = sConfig.GetIntDefault("SkillGain.Defense", 1);
862 if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
864 sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
865 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
868 m_configs[CONFIG_SKILL_GAIN_GATHERING] = sConfig.GetIntDefault("SkillGain.Gathering", 1);
869 if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
871 sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
872 m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
875 m_configs[CONFIG_SKILL_GAIN_WEAPON] = sConfig.GetIntDefault("SkillGain.Weapon", 1);
876 if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
878 sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
879 m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
882 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
883 if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
885 sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check). Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
886 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
889 m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
890 m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
892 m_configs[CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL] = sConfig.GetBoolDefault("AlwaysMaxSkillForLevel", false);
894 if(reload)
896 uint32 val = sConfig.GetIntDefault("Expansion",MAX_EXPANSION);
897 if(val!=m_configs[CONFIG_EXPANSION])
898 sLog.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
900 else
901 m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",MAX_EXPANSION);
903 if(m_configs[CONFIG_EXPANSION] > MAX_EXPANSION)
905 sLog.outError("Expansion option can't be greater %u but set to %u, used %u",MAX_EXPANSION,m_configs[CONFIG_EXPANSION],MAX_EXPANSION);
906 m_configs[CONFIG_EXPANSION] = MAX_EXPANSION;
909 m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
910 m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
911 m_configs[CONFIG_CHATFLOOD_MUTE_TIME] = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
913 m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
915 m_configs[CONFIG_CREATURE_FAMILY_FLEE_ASSISTANCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyFleeAssistanceRadius",30);
916 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistanceRadius",10);
917 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY] = sConfig.GetIntDefault("CreatureFamilyAssistanceDelay",1500);
918 m_configs[CONFIG_CREATURE_FAMILY_FLEE_DELAY] = sConfig.GetIntDefault("CreatureFamilyFleeDelay",7000);
920 m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
922 // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level MAX_LEVEL(100)
923 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff", 4);
924 if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > MAX_LEVEL)
925 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = MAX_LEVEL;
926 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff", 7);
927 if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > MAX_LEVEL)
928 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = MAX_LEVEL;
930 m_configs[CONFIG_DETECT_POS_COLLISION] = sConfig.GetBoolDefault("DetectPosCollision", true);
932 m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
933 m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
935 m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
936 m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
937 m_configs[CONFIG_CHAT_STRICT_LINK_CHECKING_SEVERITY] = sConfig.GetIntDefault("ChatStrictLinkChecking.Severity", 0);
938 m_configs[CONFIG_CHAT_STRICT_LINK_CHECKING_KICK] = sConfig.GetIntDefault("ChatStrictLinkChecking.Kick", 0);
940 m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
941 m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
942 m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
943 m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
944 m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
946 m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault ("Death.SicknessLevel", 11);
947 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
948 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
949 m_configs[CONFIG_DEATH_BONES_WORLD] = sConfig.GetBoolDefault("Death.Bones.World", true);
950 m_configs[CONFIG_DEATH_BONES_BG_OR_ARENA] = sConfig.GetBoolDefault("Death.Bones.BattlegroundOrArena", true);
952 m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
954 // always use declined names in the russian client
955 m_configs[CONFIG_DECLINED_NAMES_USED] =
956 (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
958 m_configs[CONFIG_LISTEN_RANGE_SAY] = sConfig.GetIntDefault("ListenRange.Say", 25);
959 m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
960 m_configs[CONFIG_LISTEN_RANGE_YELL] = sConfig.GetIntDefault("ListenRange.Yell", 300);
962 m_configs[CONFIG_BATTLEGROUND_CAST_DESERTER] = sConfig.GetBoolDefault("Battleground.CastDeserter", true);
963 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.Enable", false);
964 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false);
965 m_configs[CONFIG_BATTLEGROUND_INVITATION_TYPE] = sConfig.GetIntDefault ("Battleground.InvitationType", 0);
966 m_configs[CONFIG_BATTLEGROUND_PREMATURE_FINISH_TIMER] = sConfig.GetIntDefault ("BattleGround.PrematureFinishTimer", 5 * MINUTE * IN_MILISECONDS);
967 m_configs[CONFIG_BATTLEGROUND_PREMADE_GROUP_WAIT_FOR_MATCH] = sConfig.GetIntDefault ("BattleGround.PremadeGroupWaitForMatch", 30 * MINUTE * IN_MILISECONDS);
968 m_configs[CONFIG_ARENA_MAX_RATING_DIFFERENCE] = sConfig.GetIntDefault ("Arena.MaxRatingDifference", 150);
969 m_configs[CONFIG_ARENA_RATING_DISCARD_TIMER] = sConfig.GetIntDefault ("Arena.RatingDiscardTimer", 10 * MINUTE * IN_MILISECONDS);
970 m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_POINTS] = sConfig.GetBoolDefault("Arena.AutoDistributePoints", false);
971 m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS] = sConfig.GetIntDefault ("Arena.AutoDistributeInterval", 7);
972 m_configs[CONFIG_ARENA_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Arena.QueueAnnouncer.Enable", false);
973 m_configs[CONFIG_ARENA_SEASON_ID] = sConfig.GetIntDefault ("Arena.ArenaSeason.ID", 1);
974 m_configs[CONFIG_ARENA_SEASON_IN_PROGRESS] = sConfig.GetBoolDefault("Arena.ArenaSeason.InProgress", true);
976 m_configs[CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET] = sConfig.GetBoolDefault("OffhandCheckAtTalentsReset", false);
978 if(int clientCacheId = sConfig.GetIntDefault("ClientCacheVersion", 0))
980 // overwrite DB/old value
981 if(clientCacheId > 0)
983 m_configs[CONFIG_CLIENTCACHE_VERSION] = clientCacheId;
984 sLog.outString("Client cache version set to: %u", clientCacheId);
986 else
987 sLog.outError("ClientCacheVersion can't be negative %d, ignored.", clientCacheId);
990 m_configs[CONFIG_INSTANT_LOGOUT] = sConfig.GetIntDefault("InstantLogout", SEC_MODERATOR);
992 m_configs[CONFIG_GUILD_EVENT_LOG_COUNT] = sConfig.GetIntDefault("Guild.EventLogRecordsCount", GUILD_EVENTLOG_MAX_RECORDS);
993 if (m_configs[CONFIG_GUILD_EVENT_LOG_COUNT] < GUILD_EVENTLOG_MAX_RECORDS)
994 m_configs[CONFIG_GUILD_EVENT_LOG_COUNT] = GUILD_EVENTLOG_MAX_RECORDS;
995 m_configs[CONFIG_GUILD_BANK_EVENT_LOG_COUNT] = sConfig.GetIntDefault("Guild.BankEventLogRecordsCount", GUILD_BANK_MAX_LOGS);
996 if (m_configs[CONFIG_GUILD_BANK_EVENT_LOG_COUNT] < GUILD_BANK_MAX_LOGS)
997 m_configs[CONFIG_GUILD_BANK_EVENT_LOG_COUNT] = GUILD_BANK_MAX_LOGS;
999 m_configs[CONFIG_TIMERBAR_FATIGUE_GMLEVEL] = sConfig.GetIntDefault("TimerBar.Fatigue.GMLevel", SEC_CONSOLE);
1000 m_configs[CONFIG_TIMERBAR_FATIGUE_MAX] = sConfig.GetIntDefault("TimerBar.Fatigue.Max", 60);
1001 m_configs[CONFIG_TIMERBAR_BREATH_GMLEVEL] = sConfig.GetIntDefault("TimerBar.Breath.GMLevel", SEC_CONSOLE);
1002 m_configs[CONFIG_TIMERBAR_BREATH_MAX] = sConfig.GetIntDefault("TimerBar.Breath.Max", 180);
1003 m_configs[CONFIG_TIMERBAR_FIRE_GMLEVEL] = sConfig.GetIntDefault("TimerBar.Fire.GMLevel", SEC_CONSOLE);
1004 m_configs[CONFIG_TIMERBAR_FIRE_MAX] = sConfig.GetIntDefault("TimerBar.Fire.Max", 1);
1006 m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
1007 if(m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
1009 sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
1010 m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
1012 m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
1013 if(m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
1015 sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
1016 m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
1019 //visibility on continents
1020 m_MaxVisibleDistanceOnContinents = sConfig.GetFloatDefault("Visibility.Distance.Continents", DEFAULT_VISIBILITY_DISTANCE);
1021 if(m_MaxVisibleDistanceOnContinents < 45*getRate(RATE_CREATURE_AGGRO))
1023 sLog.outError("Visibility.Distance.Continents can't be less max aggro radius %f", 45*getRate(RATE_CREATURE_AGGRO));
1024 m_MaxVisibleDistanceOnContinents = 45*getRate(RATE_CREATURE_AGGRO);
1026 else if(m_MaxVisibleDistanceOnContinents + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
1028 sLog.outError("Visibility.Distance.Continents can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
1029 m_MaxVisibleDistanceOnContinents = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
1032 //visibility in instances
1033 m_MaxVisibleDistanceInInctances = sConfig.GetFloatDefault("Visibility.Distance.Instances", DEFAULT_VISIBILITY_INSTANCE);
1034 if(m_MaxVisibleDistanceInInctances < 45*getRate(RATE_CREATURE_AGGRO))
1036 sLog.outError("Visibility.Distance.Instances can't be less max aggro radius %f",45*getRate(RATE_CREATURE_AGGRO));
1037 m_MaxVisibleDistanceInInctances = 45*getRate(RATE_CREATURE_AGGRO);
1039 else if(m_MaxVisibleDistanceInInctances + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
1041 sLog.outError("Visibility.Distance.Instances can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
1042 m_MaxVisibleDistanceInInctances = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
1045 //visibility in BG/Arenas
1046 m_MaxVisibleDistanceInBGArenas = sConfig.GetFloatDefault("Visibility.Distance.BGArenas", DEFAULT_VISIBILITY_BGARENAS);
1047 if(m_MaxVisibleDistanceInBGArenas < 45*getRate(RATE_CREATURE_AGGRO))
1049 sLog.outError("Visibility.Distance.BGArenas can't be less max aggro radius %f",45*getRate(RATE_CREATURE_AGGRO));
1050 m_MaxVisibleDistanceInBGArenas = 45*getRate(RATE_CREATURE_AGGRO);
1052 else if(m_MaxVisibleDistanceInBGArenas + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
1054 sLog.outError("Visibility.Distance.BGArenas can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
1055 m_MaxVisibleDistanceInBGArenas = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
1058 m_MaxVisibleDistanceForObject = sConfig.GetFloatDefault("Visibility.Distance.Object", DEFAULT_VISIBILITY_DISTANCE);
1059 if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
1061 sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
1062 m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
1064 else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
1066 sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
1067 m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
1069 m_MaxVisibleDistanceInFlight = sConfig.GetFloatDefault("Visibility.Distance.InFlight", DEFAULT_VISIBILITY_DISTANCE);
1070 if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
1072 sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
1073 m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
1076 ///- Read the "Data" directory from the config file
1077 std::string dataPath = sConfig.GetStringDefault("DataDir","./");
1078 if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
1079 dataPath.append("/");
1081 if(reload)
1083 if(dataPath!=m_dataPath)
1084 sLog.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath.c_str());
1086 else
1088 m_dataPath = dataPath;
1089 sLog.outString("Using DataDir %s",m_dataPath.c_str());
1092 bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
1093 bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
1094 std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
1095 std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
1096 VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
1097 VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
1098 VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
1099 VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
1100 sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
1101 sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
1102 sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
1105 /// Initialize the World
1106 void World::SetInitialWorldSettings()
1108 ///- Initialize the random number generator
1109 srand((unsigned int)time(NULL));
1111 ///- Time server startup
1112 uint32 uStartTime = getMSTime();
1114 ///- Initialize config settings
1115 LoadConfigSettings();
1117 ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
1118 sObjectMgr.SetHighestGuids();
1120 ///- Check the existence of the map files for all races' startup areas.
1121 if( !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
1122 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
1123 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
1124 ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
1125 ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
1126 ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
1127 ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
1128 ||m_configs[CONFIG_EXPANSION] && (
1129 !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
1131 sLog.outError("Correct *.map files not found in path '%smaps' or *.vmap/*vmdir files in '%svmaps'. Please place *.map/*.vmap/*.vmdir files in appropriate directories or correct the DataDir value in the mangosd.conf file.",m_dataPath.c_str(),m_dataPath.c_str());
1132 exit(1);
1135 ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
1136 sLog.outString();
1137 sLog.outString("Loading MaNGOS strings...");
1138 if (!sObjectMgr.LoadMangosStrings())
1139 exit(1); // Error message displayed in function already
1141 ///- Update the realm entry in the database with the realm type from the config file
1142 //No SQL injection as values are treated as integers
1144 // not send custom type REALM_FFA_PVP to realm list
1145 uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
1146 uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
1147 loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
1149 ///- Remove the bones after a restart
1150 CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
1152 ///- Load the DBC files
1153 sLog.outString("Initialize data stores...");
1154 LoadDBCStores(m_dataPath);
1155 DetectDBCLang();
1157 sLog.outString( "Loading Script Names...");
1158 sObjectMgr.LoadScriptNames();
1160 sLog.outString( "Loading InstanceTemplate..." );
1161 sObjectMgr.LoadInstanceTemplate();
1163 sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
1164 sSpellMgr.LoadSkillLineAbilityMap();
1166 ///- Clean up and pack instances
1167 sLog.outString( "Cleaning up instances..." );
1168 sInstanceSaveMgr.CleanupInstances(); // must be called before `creature_respawn`/`gameobject_respawn` tables
1170 sLog.outString( "Packing instances..." );
1171 sInstanceSaveMgr.PackInstances();
1173 sLog.outString();
1174 sLog.outString( "Loading Localization strings..." );
1175 sObjectMgr.LoadCreatureLocales();
1176 sObjectMgr.LoadGameObjectLocales();
1177 sObjectMgr.LoadItemLocales();
1178 sObjectMgr.LoadQuestLocales();
1179 sObjectMgr.LoadNpcTextLocales();
1180 sObjectMgr.LoadPageTextLocales();
1181 sObjectMgr.LoadGossipMenuItemsLocales();
1182 sObjectMgr.LoadPointOfInterestLocales();
1183 sObjectMgr.SetDBCLocaleIndex(GetDefaultDbcLocale()); // Get once for all the locale index of DBC language (console/broadcasts)
1184 sLog.outString( ">>> Localization strings loaded" );
1185 sLog.outString();
1187 sLog.outString( "Loading Page Texts..." );
1188 sObjectMgr.LoadPageTexts();
1190 sLog.outString( "Loading Game Object Templates..." ); // must be after LoadPageTexts
1191 sObjectMgr.LoadGameobjectInfo();
1193 sLog.outString( "Loading Spell Chain Data..." );
1194 sSpellMgr.LoadSpellChains();
1196 sLog.outString( "Loading Spell Elixir types..." );
1197 sSpellMgr.LoadSpellElixirs();
1199 sLog.outString( "Loading Spell Learn Skills..." );
1200 sSpellMgr.LoadSpellLearnSkills(); // must be after LoadSpellChains
1202 sLog.outString( "Loading Spell Learn Spells..." );
1203 sSpellMgr.LoadSpellLearnSpells();
1205 sLog.outString( "Loading Spell Proc Event conditions..." );
1206 sSpellMgr.LoadSpellProcEvents();
1208 sLog.outString( "Loading Spell Bonus Data..." );
1209 sSpellMgr.LoadSpellBonusess();
1211 sLog.outString( "Loading Spell Proc Item Enchant..." );
1212 sSpellMgr.LoadSpellProcItemEnchant(); // must be after LoadSpellChains
1214 sLog.outString( "Loading Aggro Spells Definitions...");
1215 sSpellMgr.LoadSpellThreats();
1217 sLog.outString( "Loading NPC Texts..." );
1218 sObjectMgr.LoadGossipText();
1220 sLog.outString( "Loading Item Random Enchantments Table..." );
1221 LoadRandomEnchantmentsTable();
1223 sLog.outString( "Loading Items..." ); // must be after LoadRandomEnchantmentsTable and LoadPageTexts
1224 sObjectMgr.LoadItemPrototypes();
1226 sLog.outString( "Loading Item Texts..." );
1227 sObjectMgr.LoadItemTexts();
1229 sLog.outString( "Loading Creature Model Based Info Data..." );
1230 sObjectMgr.LoadCreatureModelInfo();
1232 sLog.outString( "Loading Equipment templates...");
1233 sObjectMgr.LoadEquipmentTemplates();
1235 sLog.outString( "Loading Creature templates..." );
1236 sObjectMgr.LoadCreatureTemplates();
1238 sLog.outString( "Loading SpellsScriptTarget...");
1239 sSpellMgr.LoadSpellScriptTarget(); // must be after LoadCreatureTemplates and LoadGameobjectInfo
1241 sLog.outString( "Loading ItemRequiredTarget...");
1242 sObjectMgr.LoadItemRequiredTarget();
1244 sLog.outString( "Loading Creature Reputation OnKill Data..." );
1245 sObjectMgr.LoadReputationOnKill();
1247 sLog.outString( "Loading Points Of Interest Data..." );
1248 sObjectMgr.LoadPointsOfInterest();
1250 sLog.outString( "Loading Creature Data..." );
1251 sObjectMgr.LoadCreatures();
1253 sLog.outString( "Loading pet levelup spells..." );
1254 sSpellMgr.LoadPetLevelupSpellMap();
1256 sLog.outString( "Loading pet default spell additional to levelup spells..." );
1257 sSpellMgr.LoadPetDefaultSpells();
1259 sLog.outString( "Loading Creature Addon Data..." );
1260 sLog.outString();
1261 sObjectMgr.LoadCreatureAddons(); // must be after LoadCreatureTemplates() and LoadCreatures()
1262 sLog.outString( ">>> Creature Addon Data loaded" );
1263 sLog.outString();
1265 sLog.outString( "Loading Creature Respawn Data..." ); // must be after PackInstances()
1266 sObjectMgr.LoadCreatureRespawnTimes();
1268 sLog.outString( "Loading Gameobject Data..." );
1269 sObjectMgr.LoadGameobjects();
1271 sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1272 sObjectMgr.LoadGameobjectRespawnTimes();
1274 sLog.outString( "Loading Objects Pooling Data...");
1275 sPoolMgr.LoadFromDB();
1277 sLog.outString( "Loading Game Event Data...");
1278 sLog.outString();
1279 sGameEventMgr.LoadFromDB();
1280 sLog.outString( ">>> Game Event Data loaded" );
1281 sLog.outString();
1283 sLog.outString( "Loading Weather Data..." );
1284 sObjectMgr.LoadWeatherZoneChances();
1286 sLog.outString( "Loading Quests..." );
1287 sObjectMgr.LoadQuests(); // must be loaded after DBCs, creature_template, item_template, gameobject tables
1289 sLog.outString( "Loading Quest POI" );
1290 sObjectMgr.LoadQuestPOI();
1292 sLog.outString( "Loading Quests Relations..." );
1293 sLog.outString();
1294 sObjectMgr.LoadQuestRelations(); // must be after quest load
1295 sLog.outString( ">>> Quests Relations loaded" );
1296 sLog.outString();
1298 sLog.outString( "Loading UNIT_NPC_FLAG_SPELLCLICK Data..." );
1299 sObjectMgr.LoadNPCSpellClickSpells();
1301 sLog.outString( "Loading SpellArea Data..." ); // must be after quest load
1302 sSpellMgr.LoadSpellAreas();
1304 sLog.outString( "Loading AreaTrigger definitions..." );
1305 sObjectMgr.LoadAreaTriggerTeleports(); // must be after item template load
1307 sLog.outString( "Loading Quest Area Triggers..." );
1308 sObjectMgr.LoadQuestAreaTriggers(); // must be after LoadQuests
1310 sLog.outString( "Loading Tavern Area Triggers..." );
1311 sObjectMgr.LoadTavernAreaTriggers();
1313 sLog.outString( "Loading AreaTrigger script names..." );
1314 sObjectMgr.LoadAreaTriggerScripts();
1316 sLog.outString( "Loading Graveyard-zone links...");
1317 sObjectMgr.LoadGraveyardZones();
1319 sLog.outString( "Loading Spell target coordinates..." );
1320 sSpellMgr.LoadSpellTargetPositions();
1322 sLog.outString( "Loading spell pet auras..." );
1323 sSpellMgr.LoadSpellPetAuras();
1325 sLog.outString( "Loading Player Create Info & Level Stats..." );
1326 sLog.outString();
1327 sObjectMgr.LoadPlayerInfo();
1328 sLog.outString( ">>> Player Create Info & Level Stats loaded" );
1329 sLog.outString();
1331 sLog.outString( "Loading Exploration BaseXP Data..." );
1332 sObjectMgr.LoadExplorationBaseXP();
1334 sLog.outString( "Loading Pet Name Parts..." );
1335 sObjectMgr.LoadPetNames();
1337 sLog.outString( "Loading the max pet number..." );
1338 sObjectMgr.LoadPetNumber();
1340 sLog.outString( "Loading pet level stats..." );
1341 sObjectMgr.LoadPetLevelInfo();
1343 sLog.outString( "Loading Player Corpses..." );
1344 sObjectMgr.LoadCorpses();
1346 sLog.outString( "Loading Player level dependent mail rewards..." );
1347 sObjectMgr.LoadMailLevelRewards();
1349 sLog.outString( "Loading Loot Tables..." );
1350 sLog.outString();
1351 LoadLootTables();
1352 sLog.outString( ">>> Loot Tables loaded" );
1353 sLog.outString();
1355 sLog.outString( "Loading Skill Discovery Table..." );
1356 LoadSkillDiscoveryTable();
1358 sLog.outString( "Loading Skill Extra Item Table..." );
1359 LoadSkillExtraItemTable();
1361 sLog.outString( "Loading Skill Fishing base level requirements..." );
1362 sObjectMgr.LoadFishingBaseSkillLevel();
1364 sLog.outString( "Loading Achievements..." );
1365 sLog.outString();
1366 sAchievementMgr.LoadAchievementReferenceList();
1367 sAchievementMgr.LoadAchievementCriteriaList();
1368 sAchievementMgr.LoadAchievementCriteriaRequirements();
1369 sAchievementMgr.LoadRewards();
1370 sAchievementMgr.LoadRewardLocales();
1371 sAchievementMgr.LoadCompletedAchievements();
1372 sLog.outString( ">>> Achievements loaded" );
1373 sLog.outString();
1375 ///- Load dynamic data tables from the database
1376 sLog.outString( "Loading Auctions..." );
1377 sLog.outString();
1378 sAuctionMgr.LoadAuctionItems();
1379 sAuctionMgr.LoadAuctions();
1380 sLog.outString( ">>> Auctions loaded" );
1381 sLog.outString();
1383 sLog.outString( "Loading Guilds..." );
1384 sObjectMgr.LoadGuilds();
1386 sLog.outString( "Loading ArenaTeams..." );
1387 sObjectMgr.LoadArenaTeams();
1389 sLog.outString( "Loading Groups..." );
1390 sObjectMgr.LoadGroups();
1392 sLog.outString( "Loading ReservedNames..." );
1393 sObjectMgr.LoadReservedPlayersNames();
1395 sLog.outString( "Loading GameObjects for quests..." );
1396 sObjectMgr.LoadGameObjectForQuests();
1398 sLog.outString( "Loading BattleMasters..." );
1399 sBattleGroundMgr.LoadBattleMastersEntry();
1401 sLog.outString( "Loading BattleGround event indexes..." );
1402 sBattleGroundMgr.LoadBattleEventIndexes();
1404 sLog.outString( "Loading GameTeleports..." );
1405 sObjectMgr.LoadGameTele();
1407 sLog.outString( "Loading Npc Text Id..." );
1408 sObjectMgr.LoadNpcTextId(); // must be after load Creature and NpcText
1410 sLog.outString( "Loading Gossip scripts..." );
1411 sObjectMgr.LoadGossipScripts(); // must be before gossip menu options
1413 sLog.outString( "Loading Gossip menus..." );
1414 sObjectMgr.LoadGossipMenu();
1416 sLog.outString( "Loading Gossip menu options..." );
1417 sObjectMgr.LoadGossipMenuItems();
1419 sLog.outString( "Loading Vendors..." );
1420 sObjectMgr.LoadVendors(); // must be after load CreatureTemplate and ItemTemplate
1422 sLog.outString( "Loading Trainers..." );
1423 sObjectMgr.LoadTrainerSpell(); // must be after load CreatureTemplate
1425 sLog.outString( "Loading Waypoints..." );
1426 sLog.outString();
1427 sWaypointMgr.Load();
1429 sLog.outString( "Loading GM tickets...");
1430 sTicketMgr.LoadGMTickets();
1432 ///- Handle outdated emails (delete/return)
1433 sLog.outString( "Returning old mails..." );
1434 sObjectMgr.ReturnOrDeleteOldMails(false);
1436 ///- Load and initialize scripts
1437 sLog.outString( "Loading Scripts..." );
1438 sLog.outString();
1439 sObjectMgr.LoadQuestStartScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1440 sObjectMgr.LoadQuestEndScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1441 sObjectMgr.LoadSpellScripts(); // must be after load Creature/Gameobject(Template/Data)
1442 sObjectMgr.LoadGameObjectScripts(); // must be after load Creature/Gameobject(Template/Data)
1443 sObjectMgr.LoadEventScripts(); // must be after load Creature/Gameobject(Template/Data)
1444 sLog.outString( ">>> Scripts loaded" );
1445 sLog.outString();
1447 sLog.outString( "Loading Scripts text locales..." ); // must be after Load*Scripts calls
1448 sObjectMgr.LoadDbScriptStrings();
1450 sLog.outString( "Loading CreatureEventAI Texts...");
1451 sEventAIMgr.LoadCreatureEventAI_Texts(false); // false, will checked in LoadCreatureEventAI_Scripts
1453 sLog.outString( "Loading CreatureEventAI Summons...");
1454 sEventAIMgr.LoadCreatureEventAI_Summons(false); // false, will checked in LoadCreatureEventAI_Scripts
1456 sLog.outString( "Loading CreatureEventAI Scripts...");
1457 sEventAIMgr.LoadCreatureEventAI_Scripts();
1459 sLog.outString( "Initializing Scripts..." );
1460 if(!LoadScriptingModule())
1461 exit(1);
1463 ///- Initialize game time and timers
1464 sLog.outString( "DEBUG:: Initialize game time and timers" );
1465 m_gameTime = time(NULL);
1466 m_startTime=m_gameTime;
1468 tm local;
1469 time_t curr;
1470 time(&curr);
1471 local=*(localtime(&curr)); // dereference and assign
1472 char isoDate[128];
1473 sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1474 local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1476 loginDatabase.PExecute("INSERT INTO uptime (realmid, starttime, startstring, uptime) VALUES('%u', " UI64FMTD ", '%s', 0)",
1477 realmID, uint64(m_startTime), isoDate);
1479 m_timers[WUPDATE_OBJECTS].SetInterval(0);
1480 m_timers[WUPDATE_SESSIONS].SetInterval(0);
1481 m_timers[WUPDATE_WEATHERS].SetInterval(1*IN_MILISECONDS);
1482 m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*IN_MILISECONDS);
1483 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*IN_MILISECONDS);
1484 //Update "uptime" table based on configuration entry in minutes.
1485 m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*IN_MILISECONDS);
1486 //erase corpses every 20 minutes
1488 //to set mailtimer to return mails every day between 4 and 5 am
1489 //mailtimer is increased when updating auctions
1490 //one second is 1000 -(tested on win system)
1491 mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * IN_MILISECONDS) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1492 //1440
1493 mail_timer_expires = ( (DAY * IN_MILISECONDS) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1494 sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1496 ///- Initilize static helper structures
1497 AIRegistry::Initialize();
1498 Player::InitVisibleBits();
1500 ///- Initialize MapManager
1501 sLog.outString( "Starting Map System" );
1502 sMapMgr.Initialize();
1504 ///- Initialize Battlegrounds
1505 sLog.outString( "Starting BattleGround System" );
1506 sBattleGroundMgr.CreateInitialBattleGrounds();
1507 sBattleGroundMgr.InitAutomaticArenaPointDistribution();
1509 //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1510 sLog.outString( "Loading Transports..." );
1511 sMapMgr.LoadTransports();
1513 sLog.outString("Deleting expired bans..." );
1514 loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1516 sLog.outString("Calculate next daily quest reset time..." );
1517 InitDailyQuestResetTime();
1519 sLog.outString("Starting objects Pooling system..." );
1520 sPoolMgr.Initialize();
1522 sLog.outString("Starting Game Event system..." );
1523 uint32 nextGameEvent = sGameEventMgr.Initialize();
1524 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent); //depend on next event
1526 sLog.outString( "WORLD: World initialized" );
1528 uint32 uStartInterval = getMSTimeDiff(uStartTime, getMSTime());
1529 sLog.outString( "SERVER STARTUP TIME: %i minutes %i seconds", uStartInterval / 60000, (uStartInterval % 60000) / 1000 );
1532 void World::DetectDBCLang()
1534 uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1536 if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1538 sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1539 m_lang_confid = LOCALE_enUS;
1542 ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1544 std::string availableLocalsStr;
1546 int default_locale = MAX_LOCALE;
1547 for (int i = MAX_LOCALE-1; i >= 0; --i)
1549 if ( strlen(race->name[i]) > 0) // check by race names
1551 default_locale = i;
1552 m_availableDbcLocaleMask |= (1 << i);
1553 availableLocalsStr += localeNames[i];
1554 availableLocalsStr += " ";
1558 if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1559 (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1561 default_locale = m_lang_confid;
1564 if(default_locale >= MAX_LOCALE)
1566 sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1567 exit(1);
1570 m_defaultDbcLocale = LocaleConstant(default_locale);
1572 sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1573 sLog.outString();
1576 /// Update the World !
1577 void World::Update(uint32 diff)
1579 ///- Update the different timers
1580 for(int i = 0; i < WUPDATE_COUNT; ++i)
1581 if(m_timers[i].GetCurrent()>=0)
1582 m_timers[i].Update(diff);
1583 else m_timers[i].SetCurrent(0);
1585 ///- Update the game time and check for shutdown time
1586 _UpdateGameTime();
1588 /// Handle daily quests reset time
1589 if(m_gameTime > m_NextDailyQuestReset)
1591 ResetDailyQuests();
1592 m_NextDailyQuestReset += DAY;
1595 /// <ul><li> Handle auctions when the timer has passed
1596 if (m_timers[WUPDATE_AUCTIONS].Passed())
1598 m_timers[WUPDATE_AUCTIONS].Reset();
1600 ///- Update mails (return old mails with item, or delete them)
1601 //(tested... works on win)
1602 if (++mail_timer > mail_timer_expires)
1604 mail_timer = 0;
1605 sObjectMgr.ReturnOrDeleteOldMails(true);
1608 ///- Handle expired auctions
1609 sAuctionMgr.Update();
1612 /// <li> Handle session updates when the timer has passed
1613 if (m_timers[WUPDATE_SESSIONS].Passed())
1615 m_timers[WUPDATE_SESSIONS].Reset();
1617 UpdateSessions(diff);
1620 /// <li> Handle weather updates when the timer has passed
1621 if (m_timers[WUPDATE_WEATHERS].Passed())
1623 m_timers[WUPDATE_WEATHERS].Reset();
1625 ///- Send an update signal to Weather objects
1626 WeatherMap::iterator itr, next;
1627 for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1629 next = itr;
1630 ++next;
1632 ///- and remove Weather objects for zones with no player
1633 //As interval > WorldTick
1634 if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1636 delete itr->second;
1637 m_weathers.erase(itr);
1641 /// <li> Update uptime table
1642 if (m_timers[WUPDATE_UPTIME].Passed())
1644 uint32 tmpDiff = (m_gameTime - m_startTime);
1645 uint32 maxClientsNum = GetMaxActiveSessionCount();
1647 m_timers[WUPDATE_UPTIME].Reset();
1648 loginDatabase.PExecute("UPDATE uptime SET uptime = %u, maxplayers = %u WHERE realmid = %u AND starttime = " UI64FMTD, tmpDiff, maxClientsNum, realmID, uint64(m_startTime));
1651 /// <li> Handle all other objects
1652 if (m_timers[WUPDATE_OBJECTS].Passed())
1654 m_timers[WUPDATE_OBJECTS].Reset();
1655 ///- Update objects when the timer has passed (maps, transport, creatures,...)
1656 sMapMgr.Update(diff); // As interval = 0
1658 sBattleGroundMgr.Update(diff);
1661 // execute callbacks from sql queries that were queued recently
1662 UpdateResultQueue();
1664 ///- Erase corpses once every 20 minutes
1665 if (m_timers[WUPDATE_CORPSES].Passed())
1667 m_timers[WUPDATE_CORPSES].Reset();
1669 CorpsesErase();
1672 ///- Process Game events when necessary
1673 if (m_timers[WUPDATE_EVENTS].Passed())
1675 m_timers[WUPDATE_EVENTS].Reset(); // to give time for Update() to be processed
1676 uint32 nextGameEvent = sGameEventMgr.Update();
1677 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1678 m_timers[WUPDATE_EVENTS].Reset();
1681 /// </ul>
1682 ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1683 sMapMgr.DoDelayedMovesAndRemoves();
1685 // update the instance reset times
1686 sInstanceSaveMgr.Update();
1688 // And last, but not least handle the issued cli commands
1689 ProcessCliCommands();
1692 /// Send a packet to all players (except self if mentioned)
1693 void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
1695 SessionMap::const_iterator itr;
1696 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
1698 if (itr->second &&
1699 itr->second->GetPlayer() &&
1700 itr->second->GetPlayer()->IsInWorld() &&
1701 itr->second != self &&
1702 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
1704 itr->second->SendPacket(packet);
1709 namespace MaNGOS
1711 class WorldWorldTextBuilder
1713 public:
1714 typedef std::vector<WorldPacket*> WorldPacketList;
1715 explicit WorldWorldTextBuilder(int32 textId, va_list* args = NULL) : i_textId(textId), i_args(args) {}
1716 void operator()(WorldPacketList& data_list, int32 loc_idx)
1718 char const* text = sObjectMgr.GetMangosString(i_textId,loc_idx);
1720 if(i_args)
1722 // we need copy va_list before use or original va_list will corrupted
1723 va_list ap;
1724 va_copy(ap,*i_args);
1726 char str [2048];
1727 vsnprintf(str,2048,text, ap );
1728 va_end(ap);
1730 do_helper(data_list,&str[0]);
1732 else
1733 do_helper(data_list,(char*)text);
1735 private:
1736 char* lineFromMessage(char*& pos) { char* start = strtok(pos,"\n"); pos = NULL; return start; }
1737 void do_helper(WorldPacketList& data_list, char* text)
1739 char* pos = text;
1741 while(char* line = lineFromMessage(pos))
1743 WorldPacket* data = new WorldPacket();
1745 uint32 lineLength = (line ? strlen(line) : 0) + 1;
1747 data->Initialize(SMSG_MESSAGECHAT, 100); // guess size
1748 *data << uint8(CHAT_MSG_SYSTEM);
1749 *data << uint32(LANG_UNIVERSAL);
1750 *data << uint64(0);
1751 *data << uint32(0); // can be chat msg group or something
1752 *data << uint64(0);
1753 *data << uint32(lineLength);
1754 *data << line;
1755 *data << uint8(0);
1757 data_list.push_back(data);
1761 int32 i_textId;
1762 va_list* i_args;
1764 } // namespace MaNGOS
1766 /// Send a System Message to all players (except self if mentioned)
1767 void World::SendWorldText(int32 string_id, ...)
1769 va_list ap;
1770 va_start(ap, string_id);
1772 MaNGOS::WorldWorldTextBuilder wt_builder(string_id, &ap);
1773 MaNGOS::LocalizedPacketListDo<MaNGOS::WorldWorldTextBuilder> wt_do(wt_builder);
1774 for(SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
1776 if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
1777 continue;
1779 wt_do(itr->second->GetPlayer());
1782 va_end(ap);
1785 /// DEPRICATED, only for debug purpose. Send a System Message to all players (except self if mentioned)
1786 void World::SendGlobalText(const char* text, WorldSession *self)
1788 WorldPacket data;
1790 // need copy to prevent corruption by strtok call in LineFromMessage original string
1791 char* buf = mangos_strdup(text);
1792 char* pos = buf;
1794 while(char* line = ChatHandler::LineFromMessage(pos))
1796 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
1797 SendGlobalMessage(&data, self);
1800 delete [] buf;
1803 /// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
1804 void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
1806 SessionMap::const_iterator itr;
1807 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
1809 if (itr->second &&
1810 itr->second->GetPlayer() &&
1811 itr->second->GetPlayer()->IsInWorld() &&
1812 itr->second->GetPlayer()->GetZoneId() == zone &&
1813 itr->second != self &&
1814 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
1816 itr->second->SendPacket(packet);
1821 /// Send a System Message to all players in the zone (except self if mentioned)
1822 void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
1824 WorldPacket data;
1825 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
1826 SendZoneMessage(zone, &data, self,team);
1829 /// Kick (and save) all players
1830 void World::KickAll()
1832 m_QueuedPlayer.clear(); // prevent send queue update packet and login queued sessions
1834 // session not removed at kick and will removed in next update tick
1835 for (SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
1836 itr->second->KickPlayer();
1839 /// Kick (and save) all players with security level less `sec`
1840 void World::KickAllLess(AccountTypes sec)
1842 // session not removed at kick and will removed in next update tick
1843 for (SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
1844 if(itr->second->GetSecurity() < sec)
1845 itr->second->KickPlayer();
1848 /// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
1849 BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, std::string duration, std::string reason, std::string author)
1851 loginDatabase.escape_string(nameOrIP);
1852 loginDatabase.escape_string(reason);
1853 std::string safe_author=author;
1854 loginDatabase.escape_string(safe_author);
1856 uint32 duration_secs = TimeStringToSecs(duration);
1857 QueryResult *resultAccounts = NULL; //used for kicking
1859 ///- Update the database with ban information
1860 switch(mode)
1862 case BAN_IP:
1863 //No SQL injection as strings are escaped
1864 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
1865 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());
1866 break;
1867 case BAN_ACCOUNT:
1868 //No SQL injection as string is escaped
1869 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
1870 break;
1871 case BAN_CHARACTER:
1872 //No SQL injection as string is escaped
1873 resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
1874 break;
1875 default:
1876 return BAN_SYNTAX_ERROR;
1879 if(!resultAccounts)
1881 if(mode==BAN_IP)
1882 return BAN_SUCCESS; // ip correctly banned but nobody affected (yet)
1883 else
1884 return BAN_NOTFOUND; // Nobody to ban
1887 ///- Disconnect all affected players (for IP it can be several)
1890 Field* fieldsAccount = resultAccounts->Fetch();
1891 uint32 account = fieldsAccount->GetUInt32();
1893 if(mode!=BAN_IP)
1895 //No SQL injection as strings are escaped
1896 loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
1897 account,duration_secs,safe_author.c_str(),reason.c_str());
1900 if (WorldSession* sess = FindSession(account))
1901 if(std::string(sess->GetPlayerName()) != author)
1902 sess->KickPlayer();
1904 while( resultAccounts->NextRow() );
1906 delete resultAccounts;
1907 return BAN_SUCCESS;
1910 /// Remove a ban from an account or IP address
1911 bool World::RemoveBanAccount(BanMode mode, std::string nameOrIP)
1913 if (mode == BAN_IP)
1915 loginDatabase.escape_string(nameOrIP);
1916 loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
1918 else
1920 uint32 account = 0;
1921 if (mode == BAN_ACCOUNT)
1922 account = sAccountMgr.GetId (nameOrIP);
1923 else if (mode == BAN_CHARACTER)
1924 account = sObjectMgr.GetPlayerAccountIdByPlayerName (nameOrIP);
1926 if (!account)
1927 return false;
1929 //NO SQL injection as account is uint32
1930 loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
1932 return true;
1935 /// Update the game time
1936 void World::_UpdateGameTime()
1938 ///- update the time
1939 time_t thisTime = time(NULL);
1940 uint32 elapsed = uint32(thisTime - m_gameTime);
1941 m_gameTime = thisTime;
1943 ///- if there is a shutdown timer
1944 if(!m_stopEvent && m_ShutdownTimer > 0 && elapsed > 0)
1946 ///- ... and it is overdue, stop the world (set m_stopEvent)
1947 if( m_ShutdownTimer <= elapsed )
1949 if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
1950 m_stopEvent = true; // exist code already set
1951 else
1952 m_ShutdownTimer = 1; // minimum timer value to wait idle state
1954 ///- ... else decrease it and if necessary display a shutdown countdown to the users
1955 else
1957 m_ShutdownTimer -= elapsed;
1959 ShutdownMsg();
1964 /// Shutdown the server
1965 void World::ShutdownServ(uint32 time, uint32 options, uint8 exitcode)
1967 // ignore if server shutdown at next tick
1968 if(m_stopEvent)
1969 return;
1971 m_ShutdownMask = options;
1972 m_ExitCode = exitcode;
1974 ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
1975 if(time==0)
1977 if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
1978 m_stopEvent = true; // exist code already set
1979 else
1980 m_ShutdownTimer = 1; //So that the session count is re-evaluated at next world tick
1982 ///- Else set the shutdown timer and warn users
1983 else
1985 m_ShutdownTimer = time;
1986 ShutdownMsg(true);
1990 /// Display a shutdown message to the user(s)
1991 void World::ShutdownMsg(bool show, Player* player)
1993 // not show messages for idle shutdown mode
1994 if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
1995 return;
1997 ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
1998 if ( show ||
1999 (m_ShutdownTimer < 10) ||
2000 // < 30 sec; every 5 sec
2001 (m_ShutdownTimer<30 && (m_ShutdownTimer % 5 )==0) ||
2002 // < 5 min ; every 1 min
2003 (m_ShutdownTimer<5*MINUTE && (m_ShutdownTimer % MINUTE )==0) ||
2004 // < 30 min ; every 5 min
2005 (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
2006 // < 12 h ; every 1 h
2007 (m_ShutdownTimer<12*HOUR && (m_ShutdownTimer % HOUR )==0) ||
2008 // > 12 h ; every 12 h
2009 (m_ShutdownTimer>12*HOUR && (m_ShutdownTimer % (12*HOUR) )==0))
2011 std::string str = secsToTimeString(m_ShutdownTimer);
2013 ServerMessageType msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
2015 SendServerMessage(msgid,str.c_str(),player);
2016 DEBUG_LOG("Server is %s in %s",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"),str.c_str());
2020 /// Cancel a planned server shutdown
2021 void World::ShutdownCancel()
2023 // nothing cancel or too later
2024 if(!m_ShutdownTimer || m_stopEvent)
2025 return;
2027 ServerMessageType msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2029 m_ShutdownMask = 0;
2030 m_ShutdownTimer = 0;
2031 m_ExitCode = SHUTDOWN_EXIT_CODE; // to default value
2032 SendServerMessage(msgid);
2034 DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2037 /// Send a server message to the user(s)
2038 void World::SendServerMessage(ServerMessageType type, const char *text, Player* player)
2040 WorldPacket data(SMSG_SERVER_MESSAGE, 50); // guess size
2041 data << uint32(type);
2042 if(type <= SERVER_MSG_STRING)
2043 data << text;
2045 if(player)
2046 player->GetSession()->SendPacket(&data);
2047 else
2048 SendGlobalMessage( &data );
2051 void World::UpdateSessions( uint32 diff )
2053 ///- Add new sessions
2054 WorldSession* sess;
2055 while(addSessQueue.next(sess))
2056 AddSession_ (sess);
2058 ///- Then send an update signal to remaining ones
2059 for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2061 next = itr;
2062 ++next;
2063 ///- and remove not active sessions from the list
2064 if(!itr->second->Update(diff)) // As interval = 0
2066 RemoveQueuedPlayer (itr->second);
2067 delete itr->second;
2068 m_sessions.erase(itr);
2073 // This handles the issued and queued CLI commands
2074 void World::ProcessCliCommands()
2076 CliCommandHolder::Print* zprint = NULL;
2078 CliCommandHolder* command;
2079 while (cliCmdQueue.next(command))
2081 sLog.outDebug("CLI command under processing...");
2082 zprint = command->m_print;
2083 CliHandler(zprint).ParseCommands(command->m_command);
2084 delete command;
2087 // print the console message here so it looks right
2088 if (zprint)
2089 zprint("mangos>");
2092 void World::InitResultQueue()
2094 m_resultQueue = new SqlResultQueue;
2095 CharacterDatabase.SetResultQueue(m_resultQueue);
2098 void World::UpdateResultQueue()
2100 m_resultQueue->Update();
2103 void World::UpdateRealmCharCount(uint32 accountId)
2105 CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2106 "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2109 void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2111 if (resultCharCount)
2113 Field *fields = resultCharCount->Fetch();
2114 uint32 charCount = fields[0].GetUInt32();
2115 delete resultCharCount;
2116 loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2117 loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2121 void World::InitDailyQuestResetTime()
2123 time_t mostRecentQuestTime;
2125 QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2126 if(result)
2128 Field *fields = result->Fetch();
2130 mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2131 delete result;
2133 else
2134 mostRecentQuestTime = 0;
2136 // client built-in time for reset is 6:00 AM
2137 // FIX ME: client not show day start time
2138 time_t curTime = time(NULL);
2139 tm localTm = *localtime(&curTime);
2140 localTm.tm_hour = 6;
2141 localTm.tm_min = 0;
2142 localTm.tm_sec = 0;
2144 // current day reset time
2145 time_t curDayResetTime = mktime(&localTm);
2147 // last reset time before current moment
2148 time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2150 // need reset (if we have quest time before last reset time (not processed by some reason)
2151 if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2152 m_NextDailyQuestReset = mostRecentQuestTime;
2153 else
2155 // plan next reset time
2156 m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2160 void World::ResetDailyQuests()
2162 sLog.outDetail("Daily quests reset for all characters.");
2163 CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2164 for(SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2165 if(itr->second->GetPlayer())
2166 itr->second->GetPlayer()->ResetDailyQuestStatus();
2169 void World::SetPlayerLimit( int32 limit, bool needUpdate )
2171 if(limit < -SEC_ADMINISTRATOR)
2172 limit = -SEC_ADMINISTRATOR;
2174 // lock update need
2175 bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2177 m_playerLimit = limit;
2179 if(db_update_need)
2180 loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2183 void World::UpdateMaxSessionCounters()
2185 m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2186 m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2189 void World::LoadDBVersion()
2191 QueryResult* result = WorldDatabase.Query("SELECT version, creature_ai_version, cache_id FROM db_version LIMIT 1");
2192 if(result)
2194 Field* fields = result->Fetch();
2196 m_DBVersion = fields[0].GetCppString();
2197 m_CreatureEventAIVersion = fields[1].GetCppString();
2199 // will be overwrite by config values if different and non-0
2200 m_configs[CONFIG_CLIENTCACHE_VERSION] = fields[2].GetUInt32();
2201 delete result;
2204 if(m_DBVersion.empty())
2205 m_DBVersion = "Unknown world database.";
2207 if(m_CreatureEventAIVersion.empty())
2208 m_CreatureEventAIVersion = "Unknown creature EventAI.";