[9033] Fixed percent mana regneration from spell 53228 and ranks buff.
[getmangos.git] / src / game / World.cpp
blobad772bdf757f2f3682ee7fbbbc2453d6065e1403
1 /*
2 * Copyright (C) 2005-2009 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 "WaypointMovementGenerator.h"
54 #include "VMapFactory.h"
55 #include "GlobalEvents.h"
56 #include "GameEventMgr.h"
57 #include "PoolManager.h"
58 #include "Database/DatabaseImpl.h"
59 #include "GridNotifiersImpl.h"
60 #include "CellImpl.h"
61 #include "InstanceSaveMgr.h"
62 #include "WaypointManager.h"
63 #include "GMTicketMgr.h"
64 #include "Util.h"
66 INSTANTIATE_SINGLETON_1( World );
68 volatile bool World::m_stopEvent = false;
69 uint8 World::m_ExitCode = SHUTDOWN_EXIT_CODE;
70 volatile uint32 World::m_worldLoopCounter = 0;
72 float World::m_MaxVisibleDistanceOnContinents = DEFAULT_VISIBILITY_DISTANCE;
73 float World::m_MaxVisibleDistanceInInctances = DEFAULT_VISIBILITY_INSTANCE;
74 float World::m_MaxVisibleDistanceInBGArenas = DEFAULT_VISIBILITY_BGARENAS;
75 float World::m_MaxVisibleDistanceForObject = DEFAULT_VISIBILITY_DISTANCE;
77 float World::m_MaxVisibleDistanceInFlight = DEFAULT_VISIBILITY_DISTANCE;
78 float World::m_VisibleUnitGreyDistance = 0;
79 float World::m_VisibleObjectGreyDistance = 0;
81 /// World constructor
82 World::World()
84 m_playerLimit = 0;
85 m_allowMovement = true;
86 m_ShutdownMask = 0;
87 m_ShutdownTimer = 0;
88 m_gameTime=time(NULL);
89 m_startTime=m_gameTime;
90 m_maxActiveSessionCount = 0;
91 m_maxQueuedSessionCount = 0;
92 m_resultQueue = NULL;
93 m_NextDailyQuestReset = 0;
94 m_scheduledScripts = 0;
96 m_defaultDbcLocale = LOCALE_enUS;
97 m_availableDbcLocaleMask = 0;
100 /// World destructor
101 World::~World()
103 ///- Empty the kicked session set
104 while (!m_sessions.empty())
106 // not remove from queue, prevent loading new sessions
107 delete m_sessions.begin()->second;
108 m_sessions.erase(m_sessions.begin());
111 ///- Empty the WeatherMap
112 for (WeatherMap::const_iterator itr = m_weathers.begin(); itr != m_weathers.end(); ++itr)
113 delete itr->second;
115 m_weathers.clear();
117 CliCommandHolder* command;
118 while (cliCmdQueue.next(command))
119 delete command;
121 VMAP::VMapFactory::clear();
123 if(m_resultQueue) delete m_resultQueue;
125 //TODO free addSessQueue
128 /// Find a player in a specified zone
129 Player* World::FindPlayerInZone(uint32 zone)
131 ///- circle through active sessions and return the first player found in the zone
132 SessionMap::const_iterator itr;
133 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
135 if(!itr->second)
136 continue;
137 Player *player = itr->second->GetPlayer();
138 if(!player)
139 continue;
140 if( player->IsInWorld() && player->GetZoneId() == zone )
142 // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone.
143 return player;
146 return NULL;
149 /// Find a session by its id
150 WorldSession* World::FindSession(uint32 id) const
152 SessionMap::const_iterator itr = m_sessions.find(id);
154 if(itr != m_sessions.end())
155 return itr->second; // also can return NULL for kicked session
156 else
157 return NULL;
160 /// Remove a given session
161 bool World::RemoveSession(uint32 id)
163 ///- Find the session, kick the user, but we can't delete session at this moment to prevent iterator invalidation
164 SessionMap::const_iterator itr = m_sessions.find(id);
166 if(itr != m_sessions.end() && itr->second)
168 if (itr->second->PlayerLoading())
169 return false;
170 itr->second->KickPlayer();
173 return true;
176 void World::AddSession(WorldSession* s)
178 addSessQueue.add(s);
181 void
182 World::AddSession_ (WorldSession* s)
184 ASSERT (s);
186 //NOTE - Still there is race condition in WorldSession* being used in the Sockets
188 ///- kick already loaded player with same account (if any) and remove session
189 ///- if player is in loading and want to load again, return
190 if (!RemoveSession (s->GetAccountId ()))
192 s->KickPlayer ();
193 delete s; // session not added yet in session list, so not listed in queue
194 return;
197 // decrease session counts only at not reconnection case
198 bool decrease_session = true;
200 // if session already exist, prepare to it deleting at next world update
201 // NOTE - KickPlayer() should be called on "old" in RemoveSession()
203 SessionMap::const_iterator old = m_sessions.find(s->GetAccountId ());
205 if(old != m_sessions.end())
207 // prevent decrease sessions count if session queued
208 if(RemoveQueuedPlayer(old->second))
209 decrease_session = false;
210 // not remove replaced session form queue if listed
211 delete old->second;
215 m_sessions[s->GetAccountId ()] = s;
217 uint32 Sessions = GetActiveAndQueuedSessionCount ();
218 uint32 pLimit = GetPlayerAmountLimit ();
219 uint32 QueueSize = GetQueueSize (); //number of players in the queue
221 //so we don't count the user trying to
222 //login as a session and queue the socket that we are using
223 if(decrease_session)
224 --Sessions;
226 if (pLimit > 0 && Sessions >= pLimit && s->GetSecurity () == SEC_PLAYER )
228 AddQueuedPlayer (s);
229 UpdateMaxSessionCounters ();
230 sLog.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s->GetAccountId (), ++QueueSize);
231 return;
234 WorldPacket packet(SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
235 packet << uint8 (AUTH_OK);
236 packet << uint32 (0); // BillingTimeRemaining
237 packet << uint8 (0); // BillingPlanFlags
238 packet << uint32 (0); // BillingTimeRested
239 packet << uint8 (s->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
240 s->SendPacket (&packet);
242 s->SendAddonsInfo();
244 WorldPacket pkt(SMSG_CLIENTCACHE_VERSION, 4);
245 pkt << uint32(getConfig(CONFIG_CLIENTCACHE_VERSION));
246 s->SendPacket(&pkt);
248 s->SendAccountDataTimes(GLOBAL_CACHE_MASK);
250 s->SendTutorialsData();
252 UpdateMaxSessionCounters ();
254 // Updates the population
255 if (pLimit > 0)
257 float popu = GetActiveSessionCount (); // updated number of users on the server
258 popu /= pLimit;
259 popu *= 2;
260 loginDatabase.PExecute ("UPDATE realmlist SET population = '%f' WHERE id = '%d'", popu, realmID);
261 sLog.outDetail ("Server Population (%f).", popu);
265 int32 World::GetQueuePos(WorldSession* sess)
267 uint32 position = 1;
269 for(Queue::const_iterator iter = m_QueuedPlayer.begin(); iter != m_QueuedPlayer.end(); ++iter, ++position)
270 if((*iter) == sess)
271 return position;
273 return 0;
276 void World::AddQueuedPlayer(WorldSession* sess)
278 sess->SetInQueue(true);
279 m_QueuedPlayer.push_back (sess);
281 // The 1st SMSG_AUTH_RESPONSE needs to contain other info too.
282 WorldPacket packet (SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
283 packet << uint8 (AUTH_WAIT_QUEUE);
284 packet << uint32 (0); // BillingTimeRemaining
285 packet << uint8 (0); // BillingPlanFlags
286 packet << uint32 (0); // BillingTimeRested
287 packet << uint8 (sess->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
288 packet << uint32(GetQueuePos (sess));
289 sess->SendPacket (&packet);
291 //sess->SendAuthWaitQue (GetQueuePos (sess));
294 bool World::RemoveQueuedPlayer(WorldSession* sess)
296 // sessions count including queued to remove (if removed_session set)
297 uint32 sessions = GetActiveSessionCount();
299 uint32 position = 1;
300 Queue::iterator iter = m_QueuedPlayer.begin();
302 // search to remove and count skipped positions
303 bool found = false;
305 for(;iter != m_QueuedPlayer.end(); ++iter, ++position)
307 if(*iter==sess)
309 sess->SetInQueue(false);
310 iter = m_QueuedPlayer.erase(iter);
311 found = true; // removing queued session
312 break;
316 // iter point to next socked after removed or end()
317 // position store position of removed socket and then new position next socket after removed
319 // if session not queued then we need decrease sessions count
320 if(!found && sessions)
321 --sessions;
323 // accept first in queue
324 if( (!m_playerLimit || sessions < m_playerLimit) && !m_QueuedPlayer.empty() )
326 WorldSession* pop_sess = m_QueuedPlayer.front();
327 pop_sess->SetInQueue(false);
328 pop_sess->SendAuthWaitQue(0);
329 pop_sess->SendAddonsInfo();
331 WorldPacket pkt(SMSG_CLIENTCACHE_VERSION, 4);
332 pkt << uint32(getConfig(CONFIG_CLIENTCACHE_VERSION));
333 pop_sess->SendPacket(&pkt);
335 pop_sess->SendAccountDataTimes(GLOBAL_CACHE_MASK);
336 pop_sess->SendTutorialsData();
338 m_QueuedPlayer.pop_front();
340 // update iter to point first queued socket or end() if queue is empty now
341 iter = m_QueuedPlayer.begin();
342 position = 1;
345 // update position from iter to end()
346 // iter point to first not updated socket, position store new position
347 for(; iter != m_QueuedPlayer.end(); ++iter, ++position)
348 (*iter)->SendAuthWaitQue(position);
350 return found;
353 /// Find a Weather object by the given zoneid
354 Weather* World::FindWeather(uint32 id) const
356 WeatherMap::const_iterator itr = m_weathers.find(id);
358 if(itr != m_weathers.end())
359 return itr->second;
360 else
361 return 0;
364 /// Remove a Weather object for the given zoneid
365 void World::RemoveWeather(uint32 id)
367 // not called at the moment. Kept for completeness
368 WeatherMap::iterator itr = m_weathers.find(id);
370 if(itr != m_weathers.end())
372 delete itr->second;
373 m_weathers.erase(itr);
377 /// Add a Weather object to the list
378 Weather* World::AddWeather(uint32 zone_id)
380 WeatherZoneChances const* weatherChances = sObjectMgr.GetWeatherChances(zone_id);
382 // zone not have weather, ignore
383 if(!weatherChances)
384 return NULL;
386 Weather* w = new Weather(zone_id,weatherChances);
387 m_weathers[w->GetZone()] = w;
388 w->ReGenerate();
389 w->UpdateWeather();
390 return w;
393 /// Initialize config values
394 void World::LoadConfigSettings(bool reload)
396 if(reload)
398 if(!sConfig.Reload())
400 sLog.outError("World settings reload fail: can't read settings from %s.",sConfig.GetFilename().c_str());
401 return;
405 ///- Read the version of the configuration file and warn the user in case of emptiness or mismatch
406 uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
407 if(!confVersion)
409 sLog.outError("*****************************************************************************");
410 sLog.outError(" WARNING: mangosd.conf does not include a ConfVersion variable.");
411 sLog.outError(" Your configuration file may be out of date!");
412 sLog.outError("*****************************************************************************");
413 clock_t pause = 3000 + clock();
414 while (pause > clock())
415 ; // empty body
417 else
419 if (confVersion < _MANGOSDCONFVERSION)
421 sLog.outError("*****************************************************************************");
422 sLog.outError(" WARNING: Your mangosd.conf version indicates your conf file is out of date!");
423 sLog.outError(" Please check for updates, as your current default values may cause");
424 sLog.outError(" unexpected behavior.");
425 sLog.outError("*****************************************************************************");
426 clock_t pause = 3000 + clock();
427 while (pause > clock())
428 ; // empty body
432 ///- Read the player limit and the Message of the day from the config file
433 SetPlayerLimit( sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT), true );
434 SetMotd( sConfig.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
436 ///- Read all rates from the config file
437 rate_values[RATE_HEALTH] = sConfig.GetFloatDefault("Rate.Health", 1);
438 if(rate_values[RATE_HEALTH] < 0)
440 sLog.outError("Rate.Health (%f) must be > 0. Using 1 instead.",rate_values[RATE_HEALTH]);
441 rate_values[RATE_HEALTH] = 1;
443 rate_values[RATE_POWER_MANA] = sConfig.GetFloatDefault("Rate.Mana", 1);
444 if(rate_values[RATE_POWER_MANA] < 0)
446 sLog.outError("Rate.Mana (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_MANA]);
447 rate_values[RATE_POWER_MANA] = 1;
449 rate_values[RATE_POWER_RAGE_INCOME] = sConfig.GetFloatDefault("Rate.Rage.Income", 1);
450 rate_values[RATE_POWER_RAGE_LOSS] = sConfig.GetFloatDefault("Rate.Rage.Loss", 1);
451 if(rate_values[RATE_POWER_RAGE_LOSS] < 0)
453 sLog.outError("Rate.Rage.Loss (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_RAGE_LOSS]);
454 rate_values[RATE_POWER_RAGE_LOSS] = 1;
456 rate_values[RATE_POWER_RUNICPOWER_INCOME] = sConfig.GetFloatDefault("Rate.RunicPower.Income", 1);
457 rate_values[RATE_POWER_RUNICPOWER_LOSS] = sConfig.GetFloatDefault("Rate.RunicPower.Loss", 1);
458 if(rate_values[RATE_POWER_RUNICPOWER_LOSS] < 0)
460 sLog.outError("Rate.RunicPower.Loss (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_RUNICPOWER_LOSS]);
461 rate_values[RATE_POWER_RUNICPOWER_LOSS] = 1;
463 rate_values[RATE_POWER_FOCUS] = sConfig.GetFloatDefault("Rate.Focus", 1.0f);
464 rate_values[RATE_SKILL_DISCOVERY] = sConfig.GetFloatDefault("Rate.Skill.Discovery", 1.0f);
465 rate_values[RATE_DROP_ITEM_POOR] = sConfig.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f);
466 rate_values[RATE_DROP_ITEM_NORMAL] = sConfig.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f);
467 rate_values[RATE_DROP_ITEM_UNCOMMON] = sConfig.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f);
468 rate_values[RATE_DROP_ITEM_RARE] = sConfig.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f);
469 rate_values[RATE_DROP_ITEM_EPIC] = sConfig.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f);
470 rate_values[RATE_DROP_ITEM_LEGENDARY] = sConfig.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f);
471 rate_values[RATE_DROP_ITEM_ARTIFACT] = sConfig.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f);
472 rate_values[RATE_DROP_ITEM_REFERENCED] = sConfig.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f);
473 rate_values[RATE_DROP_MONEY] = sConfig.GetFloatDefault("Rate.Drop.Money", 1.0f);
474 rate_values[RATE_XP_KILL] = sConfig.GetFloatDefault("Rate.XP.Kill", 1.0f);
475 rate_values[RATE_XP_QUEST] = sConfig.GetFloatDefault("Rate.XP.Quest", 1.0f);
476 rate_values[RATE_XP_EXPLORE] = sConfig.GetFloatDefault("Rate.XP.Explore", 1.0f);
477 rate_values[RATE_REPUTATION_GAIN] = sConfig.GetFloatDefault("Rate.Reputation.Gain", 1.0f);
478 rate_values[RATE_REPUTATION_LOWLEVEL_KILL] = sConfig.GetFloatDefault("Rate.Reputation.LowLevel.Kill", 1.0f);
479 rate_values[RATE_REPUTATION_LOWLEVEL_QUEST] = sConfig.GetFloatDefault("Rate.Reputation.LowLevel.Quest", 1.0f);
480 rate_values[RATE_CREATURE_NORMAL_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f);
481 rate_values[RATE_CREATURE_ELITE_ELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f);
482 rate_values[RATE_CREATURE_ELITE_RAREELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f);
483 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f);
484 rate_values[RATE_CREATURE_ELITE_RARE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f);
485 rate_values[RATE_CREATURE_NORMAL_HP] = sConfig.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f);
486 rate_values[RATE_CREATURE_ELITE_ELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f);
487 rate_values[RATE_CREATURE_ELITE_RAREELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f);
488 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f);
489 rate_values[RATE_CREATURE_ELITE_RARE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f);
490 rate_values[RATE_CREATURE_NORMAL_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f);
491 rate_values[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f);
492 rate_values[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f);
493 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f);
494 rate_values[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f);
495 rate_values[RATE_CREATURE_AGGRO] = sConfig.GetFloatDefault("Rate.Creature.Aggro", 1.0f);
496 rate_values[RATE_REST_INGAME] = sConfig.GetFloatDefault("Rate.Rest.InGame", 1.0f);
497 rate_values[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY] = sConfig.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f);
498 rate_values[RATE_REST_OFFLINE_IN_WILDERNESS] = sConfig.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f);
499 rate_values[RATE_DAMAGE_FALL] = sConfig.GetFloatDefault("Rate.Damage.Fall", 1.0f);
500 rate_values[RATE_AUCTION_TIME] = sConfig.GetFloatDefault("Rate.Auction.Time", 1.0f);
501 rate_values[RATE_AUCTION_DEPOSIT] = sConfig.GetFloatDefault("Rate.Auction.Deposit", 1.0f);
502 rate_values[RATE_AUCTION_CUT] = sConfig.GetFloatDefault("Rate.Auction.Cut", 1.0f);
503 rate_values[RATE_HONOR] = sConfig.GetFloatDefault("Rate.Honor",1.0f);
504 rate_values[RATE_MINING_AMOUNT] = sConfig.GetFloatDefault("Rate.Mining.Amount",1.0f);
505 rate_values[RATE_MINING_NEXT] = sConfig.GetFloatDefault("Rate.Mining.Next",1.0f);
506 rate_values[RATE_INSTANCE_RESET_TIME] = sConfig.GetFloatDefault("Rate.InstanceResetTime",1.0f);
507 rate_values[RATE_TALENT] = sConfig.GetFloatDefault("Rate.Talent",1.0f);
508 if(rate_values[RATE_TALENT] < 0.0f)
510 sLog.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_TALENT]);
511 rate_values[RATE_TALENT] = 1.0f;
513 rate_values[RATE_CORPSE_DECAY_LOOTED] = sConfig.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f);
515 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = sConfig.GetFloatDefault("TargetPosRecalculateRange",1.5f);
516 if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] < CONTACT_DISTANCE)
518 sLog.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],CONTACT_DISTANCE,CONTACT_DISTANCE);
519 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = CONTACT_DISTANCE;
521 else if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] > ATTACK_DISTANCE)
523 sLog.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",
524 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],ATTACK_DISTANCE,ATTACK_DISTANCE);
525 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = ATTACK_DISTANCE;
528 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = sConfig.GetFloatDefault("DurabilityLossChance.Damage",0.5f);
529 if(rate_values[RATE_DURABILITY_LOSS_DAMAGE] < 0.0f)
531 sLog.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_DAMAGE]);
532 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = 0.0f;
534 rate_values[RATE_DURABILITY_LOSS_ABSORB] = sConfig.GetFloatDefault("DurabilityLossChance.Absorb",0.5f);
535 if(rate_values[RATE_DURABILITY_LOSS_ABSORB] < 0.0f)
537 sLog.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_ABSORB]);
538 rate_values[RATE_DURABILITY_LOSS_ABSORB] = 0.0f;
540 rate_values[RATE_DURABILITY_LOSS_PARRY] = sConfig.GetFloatDefault("DurabilityLossChance.Parry",0.05f);
541 if(rate_values[RATE_DURABILITY_LOSS_PARRY] < 0.0f)
543 sLog.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_PARRY]);
544 rate_values[RATE_DURABILITY_LOSS_PARRY] = 0.0f;
546 rate_values[RATE_DURABILITY_LOSS_BLOCK] = sConfig.GetFloatDefault("DurabilityLossChance.Block",0.05f);
547 if(rate_values[RATE_DURABILITY_LOSS_BLOCK] < 0.0f)
549 sLog.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_BLOCK]);
550 rate_values[RATE_DURABILITY_LOSS_BLOCK] = 0.0f;
553 ///- Read other configuration items from the config file
555 m_configs[CONFIG_COMPRESSION] = sConfig.GetIntDefault("Compression", 1);
556 if(m_configs[CONFIG_COMPRESSION] < 1 || m_configs[CONFIG_COMPRESSION] > 9)
558 sLog.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs[CONFIG_COMPRESSION]);
559 m_configs[CONFIG_COMPRESSION] = 1;
561 m_configs[CONFIG_ADDON_CHANNEL] = sConfig.GetBoolDefault("AddonChannel", true);
562 m_configs[CONFIG_GRID_UNLOAD] = sConfig.GetBoolDefault("GridUnload", true);
563 m_configs[CONFIG_INTERVAL_SAVE] = sConfig.GetIntDefault("PlayerSaveInterval", 15 * MINUTE * IN_MILISECONDS);
565 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = sConfig.GetIntDefault("GridCleanUpDelay", 5 * MINUTE * IN_MILISECONDS);
566 if(m_configs[CONFIG_INTERVAL_GRIDCLEAN] < MIN_GRID_DELAY)
568 sLog.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_GRIDCLEAN],MIN_GRID_DELAY);
569 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = MIN_GRID_DELAY;
571 if(reload)
572 sMapMgr.SetGridCleanUpDelay(m_configs[CONFIG_INTERVAL_GRIDCLEAN]);
574 m_configs[CONFIG_INTERVAL_MAPUPDATE] = sConfig.GetIntDefault("MapUpdateInterval", 100);
575 if(m_configs[CONFIG_INTERVAL_MAPUPDATE] < MIN_MAP_UPDATE_DELAY)
577 sLog.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_MAPUPDATE],MIN_MAP_UPDATE_DELAY);
578 m_configs[CONFIG_INTERVAL_MAPUPDATE] = MIN_MAP_UPDATE_DELAY;
580 if(reload)
581 sMapMgr.SetMapUpdateInterval(m_configs[CONFIG_INTERVAL_MAPUPDATE]);
583 m_configs[CONFIG_INTERVAL_CHANGEWEATHER] = sConfig.GetIntDefault("ChangeWeatherInterval", 10 * MINUTE * IN_MILISECONDS);
585 if(reload)
587 uint32 val = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
588 if(val!=m_configs[CONFIG_PORT_WORLD])
589 sLog.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_PORT_WORLD]);
591 else
592 m_configs[CONFIG_PORT_WORLD] = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
594 if(reload)
596 uint32 val = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
597 if(val!=m_configs[CONFIG_SOCKET_SELECTTIME])
598 sLog.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_SOCKET_SELECTTIME]);
600 else
601 m_configs[CONFIG_SOCKET_SELECTTIME] = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
603 m_configs[CONFIG_GROUP_XP_DISTANCE] = sConfig.GetIntDefault("MaxGroupXPDistance", 74);
604 /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
605 m_configs[CONFIG_SIGHT_MONSTER] = sConfig.GetIntDefault("MonsterSight", 50);
606 m_configs[CONFIG_SIGHT_GUARDER] = sConfig.GetIntDefault("GuarderSight", 50);
608 if(reload)
610 uint32 val = sConfig.GetIntDefault("GameType", 0);
611 if(val!=m_configs[CONFIG_GAME_TYPE])
612 sLog.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_GAME_TYPE]);
614 else
615 m_configs[CONFIG_GAME_TYPE] = sConfig.GetIntDefault("GameType", 0);
617 if(reload)
619 uint32 val = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
620 if(val!=m_configs[CONFIG_REALM_ZONE])
621 sLog.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_REALM_ZONE]);
623 else
624 m_configs[CONFIG_REALM_ZONE] = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
626 m_configs[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS] = sConfig.GetBoolDefault("AllowTwoSide.Accounts", false);
627 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
628 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
629 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
630 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
631 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
632 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
633 m_configs[CONFIG_ALLOW_TWO_SIDE_WHO_LIST] = sConfig.GetBoolDefault("AllowTwoSide.WhoList", false);
634 m_configs[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND] = sConfig.GetBoolDefault("AllowTwoSide.AddFriend", false);
635 m_configs[CONFIG_STRICT_PLAYER_NAMES] = sConfig.GetIntDefault ("StrictPlayerNames", 0);
636 m_configs[CONFIG_STRICT_CHARTER_NAMES] = sConfig.GetIntDefault ("StrictCharterNames", 0);
637 m_configs[CONFIG_STRICT_PET_NAMES] = sConfig.GetIntDefault ("StrictPetNames", 0);
639 m_configs[CONFIG_MIN_PLAYER_NAME] = sConfig.GetIntDefault ("MinPlayerName", 2);
640 if(m_configs[CONFIG_MIN_PLAYER_NAME] < 1 || m_configs[CONFIG_MIN_PLAYER_NAME] > MAX_PLAYER_NAME)
642 sLog.outError("MinPlayerName (%i) must be in range 1..%u. Set to 2.",m_configs[CONFIG_MIN_PLAYER_NAME],MAX_PLAYER_NAME);
643 m_configs[CONFIG_MIN_PLAYER_NAME] = 2;
646 m_configs[CONFIG_MIN_CHARTER_NAME] = sConfig.GetIntDefault ("MinCharterName", 2);
647 if(m_configs[CONFIG_MIN_CHARTER_NAME] < 1 || m_configs[CONFIG_MIN_CHARTER_NAME] > MAX_CHARTER_NAME)
649 sLog.outError("MinCharterName (%i) must be in range 1..%u. Set to 2.",m_configs[CONFIG_MIN_CHARTER_NAME],MAX_CHARTER_NAME);
650 m_configs[CONFIG_MIN_CHARTER_NAME] = 2;
653 m_configs[CONFIG_MIN_PET_NAME] = sConfig.GetIntDefault ("MinPetName", 2);
654 if(m_configs[CONFIG_MIN_PET_NAME] < 1 || m_configs[CONFIG_MIN_PET_NAME] > MAX_PET_NAME)
656 sLog.outError("MinPetName (%i) must be in range 1..%u. Set to 2.",m_configs[CONFIG_MIN_PET_NAME],MAX_PET_NAME);
657 m_configs[CONFIG_MIN_PET_NAME] = 2;
660 m_configs[CONFIG_CHARACTERS_CREATING_DISABLED] = sConfig.GetIntDefault ("CharactersCreatingDisabled", 0);
662 m_configs[CONFIG_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("CharactersPerRealm", 10);
663 if(m_configs[CONFIG_CHARACTERS_PER_REALM] < 1 || m_configs[CONFIG_CHARACTERS_PER_REALM] > 10)
665 sLog.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs[CONFIG_CHARACTERS_PER_REALM]);
666 m_configs[CONFIG_CHARACTERS_PER_REALM] = 10;
669 // must be after CONFIG_CHARACTERS_PER_REALM
670 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = sConfig.GetIntDefault("CharactersPerAccount", 50);
671 if(m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] < m_configs[CONFIG_CHARACTERS_PER_REALM])
673 sLog.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs[CONFIG_CHARACTERS_PER_ACCOUNT],m_configs[CONFIG_CHARACTERS_PER_REALM]);
674 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = m_configs[CONFIG_CHARACTERS_PER_REALM];
677 m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("HeroicCharactersPerRealm", 1);
678 if(int32(m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM]) < 0 || m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] > 10)
680 sLog.outError("HeroicCharactersPerRealm (%i) must be in range 0..10. Set to 1.",m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM]);
681 m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] = 1;
684 m_configs[CONFIG_MIN_LEVEL_FOR_HEROIC_CHARACTER_CREATING] = sConfig.GetIntDefault("MinLevelForHeroicCharacterCreating", 55);
686 m_configs[CONFIG_SKIP_CINEMATICS] = sConfig.GetIntDefault("SkipCinematics", 0);
687 if(int32(m_configs[CONFIG_SKIP_CINEMATICS]) < 0 || m_configs[CONFIG_SKIP_CINEMATICS] > 2)
689 sLog.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs[CONFIG_SKIP_CINEMATICS]);
690 m_configs[CONFIG_SKIP_CINEMATICS] = 0;
693 if(reload)
695 uint32 val = sConfig.GetIntDefault("MaxPlayerLevel", DEFAULT_MAX_LEVEL);
696 if(val!=m_configs[CONFIG_MAX_PLAYER_LEVEL])
697 sLog.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
699 else
700 m_configs[CONFIG_MAX_PLAYER_LEVEL] = sConfig.GetIntDefault("MaxPlayerLevel", DEFAULT_MAX_LEVEL);
702 if(m_configs[CONFIG_MAX_PLAYER_LEVEL] > MAX_LEVEL)
704 sLog.outError("MaxPlayerLevel (%i) must be in range 1..%u. Set to %u.",m_configs[CONFIG_MAX_PLAYER_LEVEL],MAX_LEVEL,MAX_LEVEL);
705 m_configs[CONFIG_MAX_PLAYER_LEVEL] = MAX_LEVEL;
708 m_configs[CONFIG_START_PLAYER_LEVEL] = sConfig.GetIntDefault("StartPlayerLevel", 1);
709 if(m_configs[CONFIG_START_PLAYER_LEVEL] < 1)
711 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]);
712 m_configs[CONFIG_START_PLAYER_LEVEL] = 1;
714 else if(m_configs[CONFIG_START_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
716 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]);
717 m_configs[CONFIG_START_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
720 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = sConfig.GetIntDefault("StartHeroicPlayerLevel", 55);
721 if(m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] < 1)
723 sLog.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to 55.",
724 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
725 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = 55;
727 else if(m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
729 sLog.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to %u.",
730 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
731 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
734 m_configs[CONFIG_START_PLAYER_MONEY] = sConfig.GetIntDefault("StartPlayerMoney", 0);
735 if(int32(m_configs[CONFIG_START_PLAYER_MONEY]) < 0)
737 sLog.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",m_configs[CONFIG_START_PLAYER_MONEY],MAX_MONEY_AMOUNT,0);
738 m_configs[CONFIG_START_PLAYER_MONEY] = 0;
740 else if(m_configs[CONFIG_START_PLAYER_MONEY] > MAX_MONEY_AMOUNT)
742 sLog.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",
743 m_configs[CONFIG_START_PLAYER_MONEY],MAX_MONEY_AMOUNT,MAX_MONEY_AMOUNT);
744 m_configs[CONFIG_START_PLAYER_MONEY] = MAX_MONEY_AMOUNT;
747 m_configs[CONFIG_MAX_HONOR_POINTS] = sConfig.GetIntDefault("MaxHonorPoints", 75000);
748 if(int32(m_configs[CONFIG_MAX_HONOR_POINTS]) < 0)
750 sLog.outError("MaxHonorPoints (%i) can't be negative. Set to 0.",m_configs[CONFIG_MAX_HONOR_POINTS]);
751 m_configs[CONFIG_MAX_HONOR_POINTS] = 0;
754 m_configs[CONFIG_START_HONOR_POINTS] = sConfig.GetIntDefault("StartHonorPoints", 0);
755 if(int32(m_configs[CONFIG_START_HONOR_POINTS]) < 0)
757 sLog.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
758 m_configs[CONFIG_START_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS],0);
759 m_configs[CONFIG_START_HONOR_POINTS] = 0;
761 else if(m_configs[CONFIG_START_HONOR_POINTS] > m_configs[CONFIG_MAX_HONOR_POINTS])
763 sLog.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
764 m_configs[CONFIG_START_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS]);
765 m_configs[CONFIG_START_HONOR_POINTS] = m_configs[CONFIG_MAX_HONOR_POINTS];
768 m_configs[CONFIG_MAX_ARENA_POINTS] = sConfig.GetIntDefault("MaxArenaPoints", 5000);
769 if(int32(m_configs[CONFIG_MAX_ARENA_POINTS]) < 0)
771 sLog.outError("MaxArenaPoints (%i) can't be negative. Set to 0.",m_configs[CONFIG_MAX_ARENA_POINTS]);
772 m_configs[CONFIG_MAX_ARENA_POINTS] = 0;
775 m_configs[CONFIG_START_ARENA_POINTS] = sConfig.GetIntDefault("StartArenaPoints", 0);
776 if(int32(m_configs[CONFIG_START_ARENA_POINTS]) < 0)
778 sLog.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
779 m_configs[CONFIG_START_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS],0);
780 m_configs[CONFIG_MAX_ARENA_POINTS] = 0;
782 else if(m_configs[CONFIG_START_ARENA_POINTS] > m_configs[CONFIG_MAX_ARENA_POINTS])
784 sLog.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
785 m_configs[CONFIG_START_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS]);
786 m_configs[CONFIG_START_ARENA_POINTS] = m_configs[CONFIG_MAX_ARENA_POINTS];
789 m_configs[CONFIG_ALL_TAXI_PATHS] = sConfig.GetBoolDefault("AllFlightPaths", false);
791 m_configs[CONFIG_INSTANCE_IGNORE_LEVEL] = sConfig.GetBoolDefault("Instance.IgnoreLevel", false);
792 m_configs[CONFIG_INSTANCE_IGNORE_RAID] = sConfig.GetBoolDefault("Instance.IgnoreRaid", false);
794 m_configs[CONFIG_CAST_UNSTUCK] = sConfig.GetBoolDefault("CastUnstuck", true);
795 m_configs[CONFIG_INSTANCE_RESET_TIME_HOUR] = sConfig.GetIntDefault("Instance.ResetTimeHour", 4);
796 m_configs[CONFIG_INSTANCE_UNLOAD_DELAY] = sConfig.GetIntDefault("Instance.UnloadDelay", 30 * MINUTE * IN_MILISECONDS);
798 m_configs[CONFIG_MAX_PRIMARY_TRADE_SKILL] = sConfig.GetIntDefault("MaxPrimaryTradeSkill", 2);
799 m_configs[CONFIG_MIN_PETITION_SIGNS] = sConfig.GetIntDefault("MinPetitionSigns", 9);
800 if(m_configs[CONFIG_MIN_PETITION_SIGNS] > 9)
802 sLog.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.", m_configs[CONFIG_MIN_PETITION_SIGNS]);
803 m_configs[CONFIG_MIN_PETITION_SIGNS] = 9;
806 m_configs[CONFIG_GM_LOGIN_STATE] = sConfig.GetIntDefault("GM.LoginState", 2);
807 m_configs[CONFIG_GM_VISIBLE_STATE] = sConfig.GetIntDefault("GM.Visible", 2);
808 m_configs[CONFIG_GM_ACCEPT_TICKETS] = sConfig.GetIntDefault("GM.AcceptTickets", 2);
809 m_configs[CONFIG_GM_CHAT] = sConfig.GetIntDefault("GM.Chat", 2);
810 m_configs[CONFIG_GM_WISPERING_TO] = sConfig.GetIntDefault("GM.WhisperingTo", 2);
812 m_configs[CONFIG_GM_LEVEL_IN_GM_LIST] = sConfig.GetIntDefault("GM.InGMList.Level", SEC_ADMINISTRATOR);
813 m_configs[CONFIG_GM_LEVEL_IN_WHO_LIST] = sConfig.GetIntDefault("GM.InWhoList.Level", SEC_ADMINISTRATOR);
814 m_configs[CONFIG_GM_LOG_TRADE] = sConfig.GetBoolDefault("GM.LogTrade", false);
816 m_configs[CONFIG_START_GM_LEVEL] = sConfig.GetIntDefault("GM.StartLevel", 1);
817 if(m_configs[CONFIG_START_GM_LEVEL] < m_configs[CONFIG_START_PLAYER_LEVEL])
819 sLog.outError("GM.StartLevel (%i) must be in range StartPlayerLevel(%u)..%u. Set to %u.",
820 m_configs[CONFIG_START_GM_LEVEL],m_configs[CONFIG_START_PLAYER_LEVEL], MAX_LEVEL, m_configs[CONFIG_START_PLAYER_LEVEL]);
821 m_configs[CONFIG_START_GM_LEVEL] = m_configs[CONFIG_START_PLAYER_LEVEL];
823 else if(m_configs[CONFIG_START_GM_LEVEL] > MAX_LEVEL)
825 sLog.outError("GM.StartLevel (%i) must be in range 1..%u. Set to %u.", m_configs[CONFIG_START_GM_LEVEL], MAX_LEVEL, MAX_LEVEL);
826 m_configs[CONFIG_START_GM_LEVEL] = MAX_LEVEL;
828 m_configs[CONFIG_GM_LOWER_SECURITY] = sConfig.GetBoolDefault("GM.LowerSecurity", false);
829 m_configs[CONFIG_GM_ALLOW_ACHIEVEMENT_GAINS] = sConfig.GetBoolDefault("GM.AllowAchievementGain", true);
831 m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
833 m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
835 m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
836 if(int32(m_configs[CONFIG_UPTIME_UPDATE])<=0)
838 sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
839 m_configs[CONFIG_UPTIME_UPDATE] = 10;
841 if(reload)
843 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*IN_MILISECONDS);
844 m_timers[WUPDATE_UPTIME].Reset();
847 m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
848 m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
849 m_configs[CONFIG_SKILL_CHANCE_GREEN] = sConfig.GetIntDefault("SkillChance.Green",25);
850 m_configs[CONFIG_SKILL_CHANCE_GREY] = sConfig.GetIntDefault("SkillChance.Grey",0);
852 m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS] = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
853 m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS] = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
855 m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
856 m_configs[CONFIG_SKILL_MILLING] = sConfig.GetBoolDefault("SkillChance.Milling",false);
858 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = sConfig.GetIntDefault("SkillGain.Crafting", 1);
859 if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
861 sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
862 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
865 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = sConfig.GetIntDefault("SkillGain.Defense", 1);
866 if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
868 sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
869 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
872 m_configs[CONFIG_SKILL_GAIN_GATHERING] = sConfig.GetIntDefault("SkillGain.Gathering", 1);
873 if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
875 sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
876 m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
879 m_configs[CONFIG_SKILL_GAIN_WEAPON] = sConfig.GetIntDefault("SkillGain.Weapon", 1);
880 if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
882 sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
883 m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
886 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
887 if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
889 sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check). Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
890 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
893 m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
894 m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
896 m_configs[CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL] = sConfig.GetBoolDefault("AlwaysMaxSkillForLevel", false);
898 if(reload)
900 uint32 val = sConfig.GetIntDefault("Expansion",1);
901 if(val!=m_configs[CONFIG_EXPANSION])
902 sLog.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
904 else
905 m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",1);
907 m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
908 m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
909 m_configs[CONFIG_CHATFLOOD_MUTE_TIME] = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
911 m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
913 m_configs[CONFIG_CREATURE_FAMILY_FLEE_ASSISTANCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyFleeAssistanceRadius",30);
914 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistanceRadius",10);
915 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY] = sConfig.GetIntDefault("CreatureFamilyAssistanceDelay",1500);
916 m_configs[CONFIG_CREATURE_FAMILY_FLEE_DELAY] = sConfig.GetIntDefault("CreatureFamilyFleeDelay",7000);
918 m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
920 // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level MAX_LEVEL(100)
921 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff", 4);
922 if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > MAX_LEVEL)
923 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = MAX_LEVEL;
924 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff", 7);
925 if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > MAX_LEVEL)
926 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = MAX_LEVEL;
928 m_configs[CONFIG_DETECT_POS_COLLISION] = sConfig.GetBoolDefault("DetectPosCollision", true);
930 m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
931 m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
933 m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
934 m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
935 m_configs[CONFIG_CHAT_STRICT_LINK_CHECKING_SEVERITY] = sConfig.GetIntDefault("ChatStrictLinkChecking.Severity", 0);
936 m_configs[CONFIG_CHAT_STRICT_LINK_CHECKING_KICK] = sConfig.GetIntDefault("ChatStrictLinkChecking.Kick", 0);
938 m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
939 m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
940 m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
941 m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
942 m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
944 m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault ("Death.SicknessLevel", 11);
945 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
946 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
947 m_configs[CONFIG_DEATH_BONES_WORLD] = sConfig.GetBoolDefault("Death.Bones.World", true);
948 m_configs[CONFIG_DEATH_BONES_BG_OR_ARENA] = sConfig.GetBoolDefault("Death.Bones.BattlegroundOrArena", true);
950 m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
952 // always use declined names in the russian client
953 m_configs[CONFIG_DECLINED_NAMES_USED] =
954 (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
956 m_configs[CONFIG_LISTEN_RANGE_SAY] = sConfig.GetIntDefault("ListenRange.Say", 25);
957 m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
958 m_configs[CONFIG_LISTEN_RANGE_YELL] = sConfig.GetIntDefault("ListenRange.Yell", 300);
960 m_configs[CONFIG_BATTLEGROUND_CAST_DESERTER] = sConfig.GetBoolDefault("Battleground.CastDeserter", true);
961 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.Enable", false);
962 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false);
963 m_configs[CONFIG_BATTLEGROUND_INVITATION_TYPE] = sConfig.GetIntDefault ("Battleground.InvitationType", 0);
964 m_configs[CONFIG_BATTLEGROUND_PREMATURE_FINISH_TIMER] = sConfig.GetIntDefault ("BattleGround.PrematureFinishTimer", 5 * MINUTE * IN_MILISECONDS);
965 m_configs[CONFIG_BATTLEGROUND_PREMADE_GROUP_WAIT_FOR_MATCH] = sConfig.GetIntDefault ("BattleGround.PremadeGroupWaitForMatch", 30 * MINUTE * IN_MILISECONDS);
966 m_configs[CONFIG_ARENA_MAX_RATING_DIFFERENCE] = sConfig.GetIntDefault ("Arena.MaxRatingDifference", 150);
967 m_configs[CONFIG_ARENA_RATING_DISCARD_TIMER] = sConfig.GetIntDefault ("Arena.RatingDiscardTimer", 10 * MINUTE * IN_MILISECONDS);
968 m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_POINTS] = sConfig.GetBoolDefault("Arena.AutoDistributePoints", false);
969 m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS] = sConfig.GetIntDefault ("Arena.AutoDistributeInterval", 7);
970 m_configs[CONFIG_ARENA_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Arena.QueueAnnouncer.Enable", false);
971 m_configs[CONFIG_ARENA_SEASON_ID] = sConfig.GetIntDefault ("Arena.ArenaSeason.ID", 1);
972 m_configs[CONFIG_ARENA_SEASON_IN_PROGRESS] = sConfig.GetBoolDefault("Arena.ArenaSeason.InProgress", true);
974 m_configs[CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET] = sConfig.GetBoolDefault("OffhandCheckAtTalentsReset", false);
976 if(int clientCacheId = sConfig.GetIntDefault("ClientCacheVersion", 0))
978 // overwrite DB/old value
979 if(clientCacheId > 0)
981 m_configs[CONFIG_CLIENTCACHE_VERSION] = clientCacheId;
982 sLog.outString("Client cache version set to: %u", clientCacheId);
984 else
985 sLog.outError("ClientCacheVersion can't be negative %d, ignored.", clientCacheId);
988 m_configs[CONFIG_INSTANT_LOGOUT] = sConfig.GetIntDefault("InstantLogout", SEC_MODERATOR);
990 m_configs[CONFIG_GUILD_EVENT_LOG_COUNT] = sConfig.GetIntDefault("Guild.EventLogRecordsCount", GUILD_EVENTLOG_MAX_RECORDS);
991 if (m_configs[CONFIG_GUILD_EVENT_LOG_COUNT] < GUILD_EVENTLOG_MAX_RECORDS)
992 m_configs[CONFIG_GUILD_EVENT_LOG_COUNT] = GUILD_EVENTLOG_MAX_RECORDS;
993 m_configs[CONFIG_GUILD_BANK_EVENT_LOG_COUNT] = sConfig.GetIntDefault("Guild.BankEventLogRecordsCount", GUILD_BANK_MAX_LOGS);
994 if (m_configs[CONFIG_GUILD_BANK_EVENT_LOG_COUNT] < GUILD_BANK_MAX_LOGS)
995 m_configs[CONFIG_GUILD_BANK_EVENT_LOG_COUNT] = GUILD_BANK_MAX_LOGS;
997 m_configs[CONFIG_TIMERBAR_FATIGUE_GMLEVEL] = sConfig.GetIntDefault("TimerBar.Fatigue.GMLevel", SEC_CONSOLE);
998 m_configs[CONFIG_TIMERBAR_FATIGUE_MAX] = sConfig.GetIntDefault("TimerBar.Fatigue.Max", 60);
999 m_configs[CONFIG_TIMERBAR_BREATH_GMLEVEL] = sConfig.GetIntDefault("TimerBar.Breath.GMLevel", SEC_CONSOLE);
1000 m_configs[CONFIG_TIMERBAR_BREATH_MAX] = sConfig.GetIntDefault("TimerBar.Breath.Max", 180);
1001 m_configs[CONFIG_TIMERBAR_FIRE_GMLEVEL] = sConfig.GetIntDefault("TimerBar.Fire.GMLevel", SEC_CONSOLE);
1002 m_configs[CONFIG_TIMERBAR_FIRE_MAX] = sConfig.GetIntDefault("TimerBar.Fire.Max", 1);
1004 m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
1005 if(m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
1007 sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
1008 m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
1010 m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
1011 if(m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
1013 sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
1014 m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
1017 //visibility on continents
1018 m_MaxVisibleDistanceOnContinents = sConfig.GetFloatDefault("Visibility.Distance.Continents", DEFAULT_VISIBILITY_DISTANCE);
1019 if(m_MaxVisibleDistanceOnContinents < 45*getRate(RATE_CREATURE_AGGRO))
1021 sLog.outError("Visibility.Distance.Continents can't be less max aggro radius %f", 45*getRate(RATE_CREATURE_AGGRO));
1022 m_MaxVisibleDistanceOnContinents = 45*getRate(RATE_CREATURE_AGGRO);
1024 else if(m_MaxVisibleDistanceOnContinents + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
1026 sLog.outError("Visibility.Distance.Continents can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
1027 m_MaxVisibleDistanceOnContinents = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
1030 //visibility in instances
1031 m_MaxVisibleDistanceInInctances = sConfig.GetFloatDefault("Visibility.Distance.Instances", DEFAULT_VISIBILITY_INSTANCE);
1032 if(m_MaxVisibleDistanceInInctances < 45*getRate(RATE_CREATURE_AGGRO))
1034 sLog.outError("Visibility.Distance.Instances can't be less max aggro radius %f",45*getRate(RATE_CREATURE_AGGRO));
1035 m_MaxVisibleDistanceInInctances = 45*getRate(RATE_CREATURE_AGGRO);
1037 else if(m_MaxVisibleDistanceInInctances + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
1039 sLog.outError("Visibility.Distance.Instances can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
1040 m_MaxVisibleDistanceInInctances = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
1043 //visibility in BG/Arenas
1044 m_MaxVisibleDistanceInBGArenas = sConfig.GetFloatDefault("Visibility.Distance.BGArenas", DEFAULT_VISIBILITY_BGARENAS);
1045 if(m_MaxVisibleDistanceInBGArenas < 45*getRate(RATE_CREATURE_AGGRO))
1047 sLog.outError("Visibility.Distance.BGArenas can't be less max aggro radius %f",45*getRate(RATE_CREATURE_AGGRO));
1048 m_MaxVisibleDistanceInBGArenas = 45*getRate(RATE_CREATURE_AGGRO);
1050 else if(m_MaxVisibleDistanceInBGArenas + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
1052 sLog.outError("Visibility.Distance.BGArenas can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
1053 m_MaxVisibleDistanceInBGArenas = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
1056 m_MaxVisibleDistanceForObject = sConfig.GetFloatDefault("Visibility.Distance.Object", DEFAULT_VISIBILITY_DISTANCE);
1057 if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
1059 sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
1060 m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
1062 else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
1064 sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
1065 m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
1067 m_MaxVisibleDistanceInFlight = sConfig.GetFloatDefault("Visibility.Distance.InFlight", DEFAULT_VISIBILITY_DISTANCE);
1068 if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
1070 sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
1071 m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
1074 ///- Read the "Data" directory from the config file
1075 std::string dataPath = sConfig.GetStringDefault("DataDir","./");
1076 if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
1077 dataPath.append("/");
1079 if(reload)
1081 if(dataPath!=m_dataPath)
1082 sLog.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath.c_str());
1084 else
1086 m_dataPath = dataPath;
1087 sLog.outString("Using DataDir %s",m_dataPath.c_str());
1090 bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
1091 bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
1092 std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
1093 std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
1094 VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
1095 VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
1096 VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
1097 VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
1098 sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
1099 sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
1100 sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
1103 /// Initialize the World
1104 void World::SetInitialWorldSettings()
1106 ///- Initialize the random number generator
1107 srand((unsigned int)time(NULL));
1109 ///- Time server startup
1110 uint32 uStartTime = getMSTime();
1112 ///- Initialize config settings
1113 LoadConfigSettings();
1115 ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
1116 sObjectMgr.SetHighestGuids();
1118 ///- Check the existence of the map files for all races' startup areas.
1119 if( !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
1120 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
1121 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
1122 ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
1123 ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
1124 ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
1125 ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
1126 ||m_configs[CONFIG_EXPANSION] && (
1127 !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
1129 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());
1130 exit(1);
1133 ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
1134 sLog.outString();
1135 sLog.outString("Loading MaNGOS strings...");
1136 if (!sObjectMgr.LoadMangosStrings())
1137 exit(1); // Error message displayed in function already
1139 ///- Update the realm entry in the database with the realm type from the config file
1140 //No SQL injection as values are treated as integers
1142 // not send custom type REALM_FFA_PVP to realm list
1143 uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
1144 uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
1145 loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
1147 ///- Remove the bones after a restart
1148 CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
1150 ///- Load the DBC files
1151 sLog.outString("Initialize data stores...");
1152 LoadDBCStores(m_dataPath);
1153 DetectDBCLang();
1155 sLog.outString( "Loading Script Names...");
1156 sObjectMgr.LoadScriptNames();
1158 sLog.outString( "Loading InstanceTemplate..." );
1159 sObjectMgr.LoadInstanceTemplate();
1161 sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
1162 sSpellMgr.LoadSkillLineAbilityMap();
1164 ///- Clean up and pack instances
1165 sLog.outString( "Cleaning up instances..." );
1166 sInstanceSaveMgr.CleanupInstances(); // must be called before `creature_respawn`/`gameobject_respawn` tables
1168 sLog.outString( "Packing instances..." );
1169 sInstanceSaveMgr.PackInstances();
1171 sLog.outString();
1172 sLog.outString( "Loading Localization strings..." );
1173 sObjectMgr.LoadCreatureLocales();
1174 sObjectMgr.LoadGameObjectLocales();
1175 sObjectMgr.LoadItemLocales();
1176 sObjectMgr.LoadQuestLocales();
1177 sObjectMgr.LoadNpcTextLocales();
1178 sObjectMgr.LoadPageTextLocales();
1179 sObjectMgr.LoadGossipMenuItemsLocales();
1180 sObjectMgr.LoadPointOfInterestLocales();
1181 sObjectMgr.SetDBCLocaleIndex(GetDefaultDbcLocale()); // Get once for all the locale index of DBC language (console/broadcasts)
1182 sLog.outString( ">>> Localization strings loaded" );
1183 sLog.outString();
1185 sLog.outString( "Loading Page Texts..." );
1186 sObjectMgr.LoadPageTexts();
1188 sLog.outString( "Loading Game Object Templates..." ); // must be after LoadPageTexts
1189 sObjectMgr.LoadGameobjectInfo();
1191 sLog.outString( "Loading Spell Chain Data..." );
1192 sSpellMgr.LoadSpellChains();
1194 sLog.outString( "Loading Spell Elixir types..." );
1195 sSpellMgr.LoadSpellElixirs();
1197 sLog.outString( "Loading Spell Learn Skills..." );
1198 sSpellMgr.LoadSpellLearnSkills(); // must be after LoadSpellChains
1200 sLog.outString( "Loading Spell Learn Spells..." );
1201 sSpellMgr.LoadSpellLearnSpells();
1203 sLog.outString( "Loading Spell Proc Event conditions..." );
1204 sSpellMgr.LoadSpellProcEvents();
1206 sLog.outString( "Loading Spell Bonus Data..." );
1207 sSpellMgr.LoadSpellBonusess();
1209 sLog.outString( "Loading Spell Proc Item Enchant..." );
1210 sSpellMgr.LoadSpellProcItemEnchant(); // must be after LoadSpellChains
1212 sLog.outString( "Loading Aggro Spells Definitions...");
1213 sSpellMgr.LoadSpellThreats();
1215 sLog.outString( "Loading NPC Texts..." );
1216 sObjectMgr.LoadGossipText();
1218 sLog.outString( "Loading Item Random Enchantments Table..." );
1219 LoadRandomEnchantmentsTable();
1221 sLog.outString( "Loading Items..." ); // must be after LoadRandomEnchantmentsTable and LoadPageTexts
1222 sObjectMgr.LoadItemPrototypes();
1224 sLog.outString( "Loading Item Texts..." );
1225 sObjectMgr.LoadItemTexts();
1227 sLog.outString( "Loading Creature Model Based Info Data..." );
1228 sObjectMgr.LoadCreatureModelInfo();
1230 sLog.outString( "Loading Equipment templates...");
1231 sObjectMgr.LoadEquipmentTemplates();
1233 sLog.outString( "Loading Creature templates..." );
1234 sObjectMgr.LoadCreatureTemplates();
1236 sLog.outString( "Loading SpellsScriptTarget...");
1237 sSpellMgr.LoadSpellScriptTarget(); // must be after LoadCreatureTemplates and LoadGameobjectInfo
1239 sLog.outString( "Loading ItemRequiredTarget...");
1240 sObjectMgr.LoadItemRequiredTarget();
1242 sLog.outString( "Loading Creature Reputation OnKill Data..." );
1243 sObjectMgr.LoadReputationOnKill();
1245 sLog.outString( "Loading Points Of Interest Data..." );
1246 sObjectMgr.LoadPointsOfInterest();
1248 sLog.outString( "Loading Creature Data..." );
1249 sObjectMgr.LoadCreatures();
1251 sLog.outString( "Loading pet levelup spells..." );
1252 sSpellMgr.LoadPetLevelupSpellMap();
1254 sLog.outString( "Loading pet default spell additional to levelup spells..." );
1255 sSpellMgr.LoadPetDefaultSpells();
1257 sLog.outString( "Loading Creature Addon Data..." );
1258 sLog.outString();
1259 sObjectMgr.LoadCreatureAddons(); // must be after LoadCreatureTemplates() and LoadCreatures()
1260 sLog.outString( ">>> Creature Addon Data loaded" );
1261 sLog.outString();
1263 sLog.outString( "Loading Creature Respawn Data..." ); // must be after PackInstances()
1264 sObjectMgr.LoadCreatureRespawnTimes();
1266 sLog.outString( "Loading Gameobject Data..." );
1267 sObjectMgr.LoadGameobjects();
1269 sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1270 sObjectMgr.LoadGameobjectRespawnTimes();
1272 sLog.outString( "Loading Objects Pooling Data...");
1273 sPoolMgr.LoadFromDB();
1275 sLog.outString( "Loading Game Event Data...");
1276 sLog.outString();
1277 sGameEventMgr.LoadFromDB();
1278 sLog.outString( ">>> Game Event Data loaded" );
1279 sLog.outString();
1281 sLog.outString( "Loading Weather Data..." );
1282 sObjectMgr.LoadWeatherZoneChances();
1284 sLog.outString( "Loading Quests..." );
1285 sObjectMgr.LoadQuests(); // must be loaded after DBCs, creature_template, item_template, gameobject tables
1287 sLog.outString( "Loading Quests Relations..." );
1288 sLog.outString();
1289 sObjectMgr.LoadQuestRelations(); // must be after quest load
1290 sLog.outString( ">>> Quests Relations loaded" );
1291 sLog.outString();
1293 sLog.outString( "Loading UNIT_NPC_FLAG_SPELLCLICK Data..." );
1294 sObjectMgr.LoadNPCSpellClickSpells();
1296 sLog.outString( "Loading SpellArea Data..." ); // must be after quest load
1297 sSpellMgr.LoadSpellAreas();
1299 sLog.outString( "Loading AreaTrigger definitions..." );
1300 sObjectMgr.LoadAreaTriggerTeleports(); // must be after item template load
1302 sLog.outString( "Loading Quest Area Triggers..." );
1303 sObjectMgr.LoadQuestAreaTriggers(); // must be after LoadQuests
1305 sLog.outString( "Loading Tavern Area Triggers..." );
1306 sObjectMgr.LoadTavernAreaTriggers();
1308 sLog.outString( "Loading AreaTrigger script names..." );
1309 sObjectMgr.LoadAreaTriggerScripts();
1311 sLog.outString( "Loading Graveyard-zone links...");
1312 sObjectMgr.LoadGraveyardZones();
1314 sLog.outString( "Loading Spell target coordinates..." );
1315 sSpellMgr.LoadSpellTargetPositions();
1317 sLog.outString( "Loading spell pet auras..." );
1318 sSpellMgr.LoadSpellPetAuras();
1320 sLog.outString( "Loading Player Create Info & Level Stats..." );
1321 sLog.outString();
1322 sObjectMgr.LoadPlayerInfo();
1323 sLog.outString( ">>> Player Create Info & Level Stats loaded" );
1324 sLog.outString();
1326 sLog.outString( "Loading Exploration BaseXP Data..." );
1327 sObjectMgr.LoadExplorationBaseXP();
1329 sLog.outString( "Loading Pet Name Parts..." );
1330 sObjectMgr.LoadPetNames();
1332 sLog.outString( "Loading the max pet number..." );
1333 sObjectMgr.LoadPetNumber();
1335 sLog.outString( "Loading pet level stats..." );
1336 sObjectMgr.LoadPetLevelInfo();
1338 sLog.outString( "Loading Player Corpses..." );
1339 sObjectMgr.LoadCorpses();
1341 sLog.outString( "Loading Player level dependent mail rewards..." );
1342 sObjectMgr.LoadMailLevelRewards();
1344 sLog.outString( "Loading Loot Tables..." );
1345 sLog.outString();
1346 LoadLootTables();
1347 sLog.outString( ">>> Loot Tables loaded" );
1348 sLog.outString();
1350 sLog.outString( "Loading Skill Discovery Table..." );
1351 LoadSkillDiscoveryTable();
1353 sLog.outString( "Loading Skill Extra Item Table..." );
1354 LoadSkillExtraItemTable();
1356 sLog.outString( "Loading Skill Fishing base level requirements..." );
1357 sObjectMgr.LoadFishingBaseSkillLevel();
1359 sLog.outString( "Loading Achievements..." );
1360 sLog.outString();
1361 sAchievementMgr.LoadAchievementReferenceList();
1362 sAchievementMgr.LoadAchievementCriteriaList();
1363 sAchievementMgr.LoadAchievementCriteriaRequirements();
1364 sAchievementMgr.LoadRewards();
1365 sAchievementMgr.LoadRewardLocales();
1366 sAchievementMgr.LoadCompletedAchievements();
1367 sLog.outString( ">>> Achievements loaded" );
1368 sLog.outString();
1370 ///- Load dynamic data tables from the database
1371 sLog.outString( "Loading Auctions..." );
1372 sLog.outString();
1373 sAuctionMgr.LoadAuctionItems();
1374 sAuctionMgr.LoadAuctions();
1375 sLog.outString( ">>> Auctions loaded" );
1376 sLog.outString();
1378 sLog.outString( "Loading Guilds..." );
1379 sObjectMgr.LoadGuilds();
1381 sLog.outString( "Loading ArenaTeams..." );
1382 sObjectMgr.LoadArenaTeams();
1384 sLog.outString( "Loading Groups..." );
1385 sObjectMgr.LoadGroups();
1387 sLog.outString( "Loading ReservedNames..." );
1388 sObjectMgr.LoadReservedPlayersNames();
1390 sLog.outString( "Loading GameObjects for quests..." );
1391 sObjectMgr.LoadGameObjectForQuests();
1393 sLog.outString( "Loading BattleMasters..." );
1394 sBattleGroundMgr.LoadBattleMastersEntry();
1396 sLog.outString( "Loading BattleGround event indexes..." );
1397 sBattleGroundMgr.LoadBattleEventIndexes();
1399 sLog.outString( "Loading GameTeleports..." );
1400 sObjectMgr.LoadGameTele();
1402 sLog.outString( "Loading Npc Text Id..." );
1403 sObjectMgr.LoadNpcTextId(); // must be after load Creature and NpcText
1405 sLog.outString( "Loading Gossip scripts..." );
1406 sObjectMgr.LoadGossipScripts(); // must be before gossip menu options
1408 sLog.outString( "Loading Gossip menus..." );
1409 sObjectMgr.LoadGossipMenu();
1411 sLog.outString( "Loading Gossip menu options..." );
1412 sObjectMgr.LoadGossipMenuItems();
1414 sLog.outString( "Loading Vendors..." );
1415 sObjectMgr.LoadVendors(); // must be after load CreatureTemplate and ItemTemplate
1417 sLog.outString( "Loading Trainers..." );
1418 sObjectMgr.LoadTrainerSpell(); // must be after load CreatureTemplate
1420 sLog.outString( "Loading Waypoints..." );
1421 sLog.outString();
1422 sWaypointMgr.Load();
1424 sLog.outString( "Loading GM tickets...");
1425 sTicketMgr.LoadGMTickets();
1427 ///- Handle outdated emails (delete/return)
1428 sLog.outString( "Returning old mails..." );
1429 sObjectMgr.ReturnOrDeleteOldMails(false);
1431 ///- Load and initialize scripts
1432 sLog.outString( "Loading Scripts..." );
1433 sLog.outString();
1434 sObjectMgr.LoadQuestStartScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1435 sObjectMgr.LoadQuestEndScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1436 sObjectMgr.LoadSpellScripts(); // must be after load Creature/Gameobject(Template/Data)
1437 sObjectMgr.LoadGameObjectScripts(); // must be after load Creature/Gameobject(Template/Data)
1438 sObjectMgr.LoadEventScripts(); // must be after load Creature/Gameobject(Template/Data)
1439 sLog.outString( ">>> Scripts loaded" );
1440 sLog.outString();
1442 sLog.outString( "Loading Scripts text locales..." ); // must be after Load*Scripts calls
1443 sObjectMgr.LoadDbScriptStrings();
1445 sLog.outString( "Loading CreatureEventAI Texts...");
1446 sEventAIMgr.LoadCreatureEventAI_Texts(false); // false, will checked in LoadCreatureEventAI_Scripts
1448 sLog.outString( "Loading CreatureEventAI Summons...");
1449 sEventAIMgr.LoadCreatureEventAI_Summons(false); // false, will checked in LoadCreatureEventAI_Scripts
1451 sLog.outString( "Loading CreatureEventAI Scripts...");
1452 sEventAIMgr.LoadCreatureEventAI_Scripts();
1454 sLog.outString( "Initializing Scripts..." );
1455 if(!LoadScriptingModule())
1456 exit(1);
1458 ///- Initialize game time and timers
1459 sLog.outString( "DEBUG:: Initialize game time and timers" );
1460 m_gameTime = time(NULL);
1461 m_startTime=m_gameTime;
1463 tm local;
1464 time_t curr;
1465 time(&curr);
1466 local=*(localtime(&curr)); // dereference and assign
1467 char isoDate[128];
1468 sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1469 local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1471 loginDatabase.PExecute("INSERT INTO uptime (realmid, starttime, startstring, uptime) VALUES('%u', " UI64FMTD ", '%s', 0)",
1472 realmID, uint64(m_startTime), isoDate);
1474 m_timers[WUPDATE_OBJECTS].SetInterval(0);
1475 m_timers[WUPDATE_SESSIONS].SetInterval(0);
1476 m_timers[WUPDATE_WEATHERS].SetInterval(1*IN_MILISECONDS);
1477 m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*IN_MILISECONDS);
1478 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*IN_MILISECONDS);
1479 //Update "uptime" table based on configuration entry in minutes.
1480 m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*IN_MILISECONDS);
1481 //erase corpses every 20 minutes
1483 //to set mailtimer to return mails every day between 4 and 5 am
1484 //mailtimer is increased when updating auctions
1485 //one second is 1000 -(tested on win system)
1486 mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * IN_MILISECONDS) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1487 //1440
1488 mail_timer_expires = ( (DAY * IN_MILISECONDS) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1489 sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1491 ///- Initilize static helper structures
1492 AIRegistry::Initialize();
1493 WaypointMovementGenerator<Creature>::Initialize();
1494 Player::InitVisibleBits();
1496 ///- Initialize MapManager
1497 sLog.outString( "Starting Map System" );
1498 sMapMgr.Initialize();
1500 ///- Initialize Battlegrounds
1501 sLog.outString( "Starting BattleGround System" );
1502 sBattleGroundMgr.CreateInitialBattleGrounds();
1503 sBattleGroundMgr.InitAutomaticArenaPointDistribution();
1505 //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1506 sLog.outString( "Loading Transports..." );
1507 sMapMgr.LoadTransports();
1509 sLog.outString("Deleting expired bans..." );
1510 loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1512 sLog.outString("Calculate next daily quest reset time..." );
1513 InitDailyQuestResetTime();
1515 sLog.outString("Starting objects Pooling system..." );
1516 sPoolMgr.Initialize();
1518 sLog.outString("Starting Game Event system..." );
1519 uint32 nextGameEvent = sGameEventMgr.Initialize();
1520 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent); //depend on next event
1522 sLog.outString( "WORLD: World initialized" );
1524 uint32 uStartInterval = getMSTimeDiff(uStartTime, getMSTime());
1525 sLog.outString( "SERVER STARTUP TIME: %i minutes %i seconds", uStartInterval / 60000, (uStartInterval % 60000) / 1000 );
1528 void World::DetectDBCLang()
1530 uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1532 if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1534 sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1535 m_lang_confid = LOCALE_enUS;
1538 ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1540 std::string availableLocalsStr;
1542 int default_locale = MAX_LOCALE;
1543 for (int i = MAX_LOCALE-1; i >= 0; --i)
1545 if ( strlen(race->name[i]) > 0) // check by race names
1547 default_locale = i;
1548 m_availableDbcLocaleMask |= (1 << i);
1549 availableLocalsStr += localeNames[i];
1550 availableLocalsStr += " ";
1554 if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1555 (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1557 default_locale = m_lang_confid;
1560 if(default_locale >= MAX_LOCALE)
1562 sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1563 exit(1);
1566 m_defaultDbcLocale = LocaleConstant(default_locale);
1568 sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1569 sLog.outString();
1572 /// Update the World !
1573 void World::Update(uint32 diff)
1575 ///- Update the different timers
1576 for(int i = 0; i < WUPDATE_COUNT; ++i)
1577 if(m_timers[i].GetCurrent()>=0)
1578 m_timers[i].Update(diff);
1579 else m_timers[i].SetCurrent(0);
1581 ///- Update the game time and check for shutdown time
1582 _UpdateGameTime();
1584 /// Handle daily quests reset time
1585 if(m_gameTime > m_NextDailyQuestReset)
1587 ResetDailyQuests();
1588 m_NextDailyQuestReset += DAY;
1591 /// <ul><li> Handle auctions when the timer has passed
1592 if (m_timers[WUPDATE_AUCTIONS].Passed())
1594 m_timers[WUPDATE_AUCTIONS].Reset();
1596 ///- Update mails (return old mails with item, or delete them)
1597 //(tested... works on win)
1598 if (++mail_timer > mail_timer_expires)
1600 mail_timer = 0;
1601 sObjectMgr.ReturnOrDeleteOldMails(true);
1604 ///- Handle expired auctions
1605 sAuctionMgr.Update();
1608 /// <li> Handle session updates when the timer has passed
1609 if (m_timers[WUPDATE_SESSIONS].Passed())
1611 m_timers[WUPDATE_SESSIONS].Reset();
1613 UpdateSessions(diff);
1616 /// <li> Handle weather updates when the timer has passed
1617 if (m_timers[WUPDATE_WEATHERS].Passed())
1619 m_timers[WUPDATE_WEATHERS].Reset();
1621 ///- Send an update signal to Weather objects
1622 WeatherMap::iterator itr, next;
1623 for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1625 next = itr;
1626 ++next;
1628 ///- and remove Weather objects for zones with no player
1629 //As interval > WorldTick
1630 if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1632 delete itr->second;
1633 m_weathers.erase(itr);
1637 /// <li> Update uptime table
1638 if (m_timers[WUPDATE_UPTIME].Passed())
1640 uint32 tmpDiff = (m_gameTime - m_startTime);
1641 uint32 maxClientsNum = GetMaxActiveSessionCount();
1643 m_timers[WUPDATE_UPTIME].Reset();
1644 loginDatabase.PExecute("UPDATE uptime SET uptime = %u, maxplayers = %u WHERE realmid = %u AND starttime = " UI64FMTD, tmpDiff, maxClientsNum, realmID, uint64(m_startTime));
1647 /// <li> Handle all other objects
1648 if (m_timers[WUPDATE_OBJECTS].Passed())
1650 m_timers[WUPDATE_OBJECTS].Reset();
1651 ///- Update objects when the timer has passed (maps, transport, creatures,...)
1652 sMapMgr.Update(diff); // As interval = 0
1654 sBattleGroundMgr.Update(diff);
1657 // execute callbacks from sql queries that were queued recently
1658 UpdateResultQueue();
1660 ///- Erase corpses once every 20 minutes
1661 if (m_timers[WUPDATE_CORPSES].Passed())
1663 m_timers[WUPDATE_CORPSES].Reset();
1665 CorpsesErase();
1668 ///- Process Game events when necessary
1669 if (m_timers[WUPDATE_EVENTS].Passed())
1671 m_timers[WUPDATE_EVENTS].Reset(); // to give time for Update() to be processed
1672 uint32 nextGameEvent = sGameEventMgr.Update();
1673 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1674 m_timers[WUPDATE_EVENTS].Reset();
1677 /// </ul>
1678 ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1679 sMapMgr.DoDelayedMovesAndRemoves();
1681 // update the instance reset times
1682 sInstanceSaveMgr.Update();
1684 // And last, but not least handle the issued cli commands
1685 ProcessCliCommands();
1688 /// Send a packet to all players (except self if mentioned)
1689 void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
1691 SessionMap::const_iterator itr;
1692 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
1694 if (itr->second &&
1695 itr->second->GetPlayer() &&
1696 itr->second->GetPlayer()->IsInWorld() &&
1697 itr->second != self &&
1698 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
1700 itr->second->SendPacket(packet);
1705 namespace MaNGOS
1707 class WorldWorldTextBuilder
1709 public:
1710 typedef std::vector<WorldPacket*> WorldPacketList;
1711 explicit WorldWorldTextBuilder(int32 textId, va_list* args = NULL) : i_textId(textId), i_args(args) {}
1712 void operator()(WorldPacketList& data_list, int32 loc_idx)
1714 char const* text = sObjectMgr.GetMangosString(i_textId,loc_idx);
1716 if(i_args)
1718 // we need copy va_list before use or original va_list will corrupted
1719 va_list ap;
1720 va_copy(ap,*i_args);
1722 char str [2048];
1723 vsnprintf(str,2048,text, ap );
1724 va_end(ap);
1726 do_helper(data_list,&str[0]);
1728 else
1729 do_helper(data_list,(char*)text);
1731 private:
1732 char* lineFromMessage(char*& pos) { char* start = strtok(pos,"\n"); pos = NULL; return start; }
1733 void do_helper(WorldPacketList& data_list, char* text)
1735 char* pos = text;
1737 while(char* line = lineFromMessage(pos))
1739 WorldPacket* data = new WorldPacket();
1741 uint32 lineLength = (line ? strlen(line) : 0) + 1;
1743 data->Initialize(SMSG_MESSAGECHAT, 100); // guess size
1744 *data << uint8(CHAT_MSG_SYSTEM);
1745 *data << uint32(LANG_UNIVERSAL);
1746 *data << uint64(0);
1747 *data << uint32(0); // can be chat msg group or something
1748 *data << uint64(0);
1749 *data << uint32(lineLength);
1750 *data << line;
1751 *data << uint8(0);
1753 data_list.push_back(data);
1757 int32 i_textId;
1758 va_list* i_args;
1760 } // namespace MaNGOS
1762 /// Send a System Message to all players (except self if mentioned)
1763 void World::SendWorldText(int32 string_id, ...)
1765 va_list ap;
1766 va_start(ap, string_id);
1768 MaNGOS::WorldWorldTextBuilder wt_builder(string_id, &ap);
1769 MaNGOS::LocalizedPacketListDo<MaNGOS::WorldWorldTextBuilder> wt_do(wt_builder);
1770 for(SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
1772 if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
1773 continue;
1775 wt_do(itr->second->GetPlayer());
1778 va_end(ap);
1781 /// DEPRICATED, only for debug purpose. Send a System Message to all players (except self if mentioned)
1782 void World::SendGlobalText(const char* text, WorldSession *self)
1784 WorldPacket data;
1786 // need copy to prevent corruption by strtok call in LineFromMessage original string
1787 char* buf = mangos_strdup(text);
1788 char* pos = buf;
1790 while(char* line = ChatHandler::LineFromMessage(pos))
1792 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
1793 SendGlobalMessage(&data, self);
1796 delete [] buf;
1799 /// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
1800 void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
1802 SessionMap::const_iterator itr;
1803 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
1805 if (itr->second &&
1806 itr->second->GetPlayer() &&
1807 itr->second->GetPlayer()->IsInWorld() &&
1808 itr->second->GetPlayer()->GetZoneId() == zone &&
1809 itr->second != self &&
1810 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
1812 itr->second->SendPacket(packet);
1817 /// Send a System Message to all players in the zone (except self if mentioned)
1818 void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
1820 WorldPacket data;
1821 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
1822 SendZoneMessage(zone, &data, self,team);
1825 /// Kick (and save) all players
1826 void World::KickAll()
1828 m_QueuedPlayer.clear(); // prevent send queue update packet and login queued sessions
1830 // session not removed at kick and will removed in next update tick
1831 for (SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
1832 itr->second->KickPlayer();
1835 /// Kick (and save) all players with security level less `sec`
1836 void World::KickAllLess(AccountTypes sec)
1838 // session not removed at kick and will removed in next update tick
1839 for (SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
1840 if(itr->second->GetSecurity() < sec)
1841 itr->second->KickPlayer();
1844 /// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
1845 BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, std::string duration, std::string reason, std::string author)
1847 loginDatabase.escape_string(nameOrIP);
1848 loginDatabase.escape_string(reason);
1849 std::string safe_author=author;
1850 loginDatabase.escape_string(safe_author);
1852 uint32 duration_secs = TimeStringToSecs(duration);
1853 QueryResult *resultAccounts = NULL; //used for kicking
1855 ///- Update the database with ban information
1856 switch(mode)
1858 case BAN_IP:
1859 //No SQL injection as strings are escaped
1860 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
1861 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());
1862 break;
1863 case BAN_ACCOUNT:
1864 //No SQL injection as string is escaped
1865 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
1866 break;
1867 case BAN_CHARACTER:
1868 //No SQL injection as string is escaped
1869 resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
1870 break;
1871 default:
1872 return BAN_SYNTAX_ERROR;
1875 if(!resultAccounts)
1877 if(mode==BAN_IP)
1878 return BAN_SUCCESS; // ip correctly banned but nobody affected (yet)
1879 else
1880 return BAN_NOTFOUND; // Nobody to ban
1883 ///- Disconnect all affected players (for IP it can be several)
1886 Field* fieldsAccount = resultAccounts->Fetch();
1887 uint32 account = fieldsAccount->GetUInt32();
1889 if(mode!=BAN_IP)
1891 //No SQL injection as strings are escaped
1892 loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
1893 account,duration_secs,safe_author.c_str(),reason.c_str());
1896 if (WorldSession* sess = FindSession(account))
1897 if(std::string(sess->GetPlayerName()) != author)
1898 sess->KickPlayer();
1900 while( resultAccounts->NextRow() );
1902 delete resultAccounts;
1903 return BAN_SUCCESS;
1906 /// Remove a ban from an account or IP address
1907 bool World::RemoveBanAccount(BanMode mode, std::string nameOrIP)
1909 if (mode == BAN_IP)
1911 loginDatabase.escape_string(nameOrIP);
1912 loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
1914 else
1916 uint32 account = 0;
1917 if (mode == BAN_ACCOUNT)
1918 account = sAccountMgr.GetId (nameOrIP);
1919 else if (mode == BAN_CHARACTER)
1920 account = sObjectMgr.GetPlayerAccountIdByPlayerName (nameOrIP);
1922 if (!account)
1923 return false;
1925 //NO SQL injection as account is uint32
1926 loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
1928 return true;
1931 /// Update the game time
1932 void World::_UpdateGameTime()
1934 ///- update the time
1935 time_t thisTime = time(NULL);
1936 uint32 elapsed = uint32(thisTime - m_gameTime);
1937 m_gameTime = thisTime;
1939 ///- if there is a shutdown timer
1940 if(!m_stopEvent && m_ShutdownTimer > 0 && elapsed > 0)
1942 ///- ... and it is overdue, stop the world (set m_stopEvent)
1943 if( m_ShutdownTimer <= elapsed )
1945 if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
1946 m_stopEvent = true; // exist code already set
1947 else
1948 m_ShutdownTimer = 1; // minimum timer value to wait idle state
1950 ///- ... else decrease it and if necessary display a shutdown countdown to the users
1951 else
1953 m_ShutdownTimer -= elapsed;
1955 ShutdownMsg();
1960 /// Shutdown the server
1961 void World::ShutdownServ(uint32 time, uint32 options, uint8 exitcode)
1963 // ignore if server shutdown at next tick
1964 if(m_stopEvent)
1965 return;
1967 m_ShutdownMask = options;
1968 m_ExitCode = exitcode;
1970 ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
1971 if(time==0)
1973 if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
1974 m_stopEvent = true; // exist code already set
1975 else
1976 m_ShutdownTimer = 1; //So that the session count is re-evaluated at next world tick
1978 ///- Else set the shutdown timer and warn users
1979 else
1981 m_ShutdownTimer = time;
1982 ShutdownMsg(true);
1986 /// Display a shutdown message to the user(s)
1987 void World::ShutdownMsg(bool show, Player* player)
1989 // not show messages for idle shutdown mode
1990 if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
1991 return;
1993 ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
1994 if ( show ||
1995 (m_ShutdownTimer < 10) ||
1996 // < 30 sec; every 5 sec
1997 (m_ShutdownTimer<30 && (m_ShutdownTimer % 5 )==0) ||
1998 // < 5 min ; every 1 min
1999 (m_ShutdownTimer<5*MINUTE && (m_ShutdownTimer % MINUTE )==0) ||
2000 // < 30 min ; every 5 min
2001 (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
2002 // < 12 h ; every 1 h
2003 (m_ShutdownTimer<12*HOUR && (m_ShutdownTimer % HOUR )==0) ||
2004 // > 12 h ; every 12 h
2005 (m_ShutdownTimer>12*HOUR && (m_ShutdownTimer % (12*HOUR) )==0))
2007 std::string str = secsToTimeString(m_ShutdownTimer);
2009 ServerMessageType msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
2011 SendServerMessage(msgid,str.c_str(),player);
2012 DEBUG_LOG("Server is %s in %s",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"),str.c_str());
2016 /// Cancel a planned server shutdown
2017 void World::ShutdownCancel()
2019 // nothing cancel or too later
2020 if(!m_ShutdownTimer || m_stopEvent)
2021 return;
2023 ServerMessageType msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2025 m_ShutdownMask = 0;
2026 m_ShutdownTimer = 0;
2027 m_ExitCode = SHUTDOWN_EXIT_CODE; // to default value
2028 SendServerMessage(msgid);
2030 DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2033 /// Send a server message to the user(s)
2034 void World::SendServerMessage(ServerMessageType type, const char *text, Player* player)
2036 WorldPacket data(SMSG_SERVER_MESSAGE, 50); // guess size
2037 data << uint32(type);
2038 if(type <= SERVER_MSG_STRING)
2039 data << text;
2041 if(player)
2042 player->GetSession()->SendPacket(&data);
2043 else
2044 SendGlobalMessage( &data );
2047 void World::UpdateSessions( uint32 diff )
2049 ///- Add new sessions
2050 WorldSession* sess;
2051 while(addSessQueue.next(sess))
2052 AddSession_ (sess);
2054 ///- Then send an update signal to remaining ones
2055 for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2057 next = itr;
2058 ++next;
2059 ///- and remove not active sessions from the list
2060 if(!itr->second->Update(diff)) // As interval = 0
2062 RemoveQueuedPlayer (itr->second);
2063 delete itr->second;
2064 m_sessions.erase(itr);
2069 // This handles the issued and queued CLI commands
2070 void World::ProcessCliCommands()
2072 CliCommandHolder::Print* zprint = NULL;
2074 CliCommandHolder* command;
2075 while (cliCmdQueue.next(command))
2077 sLog.outDebug("CLI command under processing...");
2078 zprint = command->m_print;
2079 CliHandler(zprint).ParseCommands(command->m_command);
2080 delete command;
2083 // print the console message here so it looks right
2084 if (zprint)
2085 zprint("mangos>");
2088 void World::InitResultQueue()
2090 m_resultQueue = new SqlResultQueue;
2091 CharacterDatabase.SetResultQueue(m_resultQueue);
2094 void World::UpdateResultQueue()
2096 m_resultQueue->Update();
2099 void World::UpdateRealmCharCount(uint32 accountId)
2101 CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2102 "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2105 void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2107 if (resultCharCount)
2109 Field *fields = resultCharCount->Fetch();
2110 uint32 charCount = fields[0].GetUInt32();
2111 delete resultCharCount;
2112 loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2113 loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2117 void World::InitDailyQuestResetTime()
2119 time_t mostRecentQuestTime;
2121 QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2122 if(result)
2124 Field *fields = result->Fetch();
2126 mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2127 delete result;
2129 else
2130 mostRecentQuestTime = 0;
2132 // client built-in time for reset is 6:00 AM
2133 // FIX ME: client not show day start time
2134 time_t curTime = time(NULL);
2135 tm localTm = *localtime(&curTime);
2136 localTm.tm_hour = 6;
2137 localTm.tm_min = 0;
2138 localTm.tm_sec = 0;
2140 // current day reset time
2141 time_t curDayResetTime = mktime(&localTm);
2143 // last reset time before current moment
2144 time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2146 // need reset (if we have quest time before last reset time (not processed by some reason)
2147 if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2148 m_NextDailyQuestReset = mostRecentQuestTime;
2149 else
2151 // plan next reset time
2152 m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2156 void World::ResetDailyQuests()
2158 sLog.outDetail("Daily quests reset for all characters.");
2159 CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2160 for(SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2161 if(itr->second->GetPlayer())
2162 itr->second->GetPlayer()->ResetDailyQuestStatus();
2165 void World::SetPlayerLimit( int32 limit, bool needUpdate )
2167 if(limit < -SEC_ADMINISTRATOR)
2168 limit = -SEC_ADMINISTRATOR;
2170 // lock update need
2171 bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2173 m_playerLimit = limit;
2175 if(db_update_need)
2176 loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2179 void World::UpdateMaxSessionCounters()
2181 m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2182 m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2185 void World::LoadDBVersion()
2187 QueryResult* result = WorldDatabase.Query("SELECT version, creature_ai_version, cache_id FROM db_version LIMIT 1");
2188 if(result)
2190 Field* fields = result->Fetch();
2192 m_DBVersion = fields[0].GetCppString();
2193 m_CreatureEventAIVersion = fields[1].GetCppString();
2195 // will be overwrite by config values if different and non-0
2196 m_configs[CONFIG_CLIENTCACHE_VERSION] = fields[2].GetUInt32();
2197 delete result;
2200 if(m_DBVersion.empty())
2201 m_DBVersion = "Unknown world database.";
2203 if(m_CreatureEventAIVersion.empty())
2204 m_CreatureEventAIVersion = "Unknown creature EventAI.";