[8483] Implement glyph 43361.
[getmangos.git] / src / game / World.cpp
bloba8c04e005e13f14a81a2ead86bfe607cbe6139ce
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 "PoolHandler.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_MaxVisibleDistanceForCreature = DEFAULT_VISIBILITY_DISTANCE;
73 float World::m_MaxVisibleDistanceForPlayer = DEFAULT_VISIBILITY_DISTANCE;
74 float World::m_MaxVisibleDistanceForObject = DEFAULT_VISIBILITY_DISTANCE;
75 float World::m_MaxVisibleDistanceInFlight = DEFAULT_VISIBILITY_DISTANCE;
76 float World::m_VisibleUnitGreyDistance = 0;
77 float World::m_VisibleObjectGreyDistance = 0;
79 /// World constructor
80 World::World()
82 m_playerLimit = 0;
83 m_allowMovement = true;
84 m_ShutdownMask = 0;
85 m_ShutdownTimer = 0;
86 m_gameTime=time(NULL);
87 m_startTime=m_gameTime;
88 m_maxActiveSessionCount = 0;
89 m_maxQueuedSessionCount = 0;
90 m_resultQueue = NULL;
91 m_NextDailyQuestReset = 0;
92 m_scheduledScripts = 0;
94 m_defaultDbcLocale = LOCALE_enUS;
95 m_availableDbcLocaleMask = 0;
98 /// World destructor
99 World::~World()
101 ///- Empty the kicked session set
102 while (!m_sessions.empty())
104 // not remove from queue, prevent loading new sessions
105 delete m_sessions.begin()->second;
106 m_sessions.erase(m_sessions.begin());
109 ///- Empty the WeatherMap
110 for (WeatherMap::const_iterator itr = m_weathers.begin(); itr != m_weathers.end(); ++itr)
111 delete itr->second;
113 m_weathers.clear();
115 CliCommandHolder* command;
116 while (cliCmdQueue.next(command))
117 delete command;
119 VMAP::VMapFactory::clear();
121 if(m_resultQueue) delete m_resultQueue;
123 //TODO free addSessQueue
126 /// Find a player in a specified zone
127 Player* World::FindPlayerInZone(uint32 zone)
129 ///- circle through active sessions and return the first player found in the zone
130 SessionMap::const_iterator itr;
131 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
133 if(!itr->second)
134 continue;
135 Player *player = itr->second->GetPlayer();
136 if(!player)
137 continue;
138 if( player->IsInWorld() && player->GetZoneId() == zone )
140 // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone.
141 return player;
144 return NULL;
147 /// Find a session by its id
148 WorldSession* World::FindSession(uint32 id) const
150 SessionMap::const_iterator itr = m_sessions.find(id);
152 if(itr != m_sessions.end())
153 return itr->second; // also can return NULL for kicked session
154 else
155 return NULL;
158 /// Remove a given session
159 bool World::RemoveSession(uint32 id)
161 ///- Find the session, kick the user, but we can't delete session at this moment to prevent iterator invalidation
162 SessionMap::const_iterator itr = m_sessions.find(id);
164 if(itr != m_sessions.end() && itr->second)
166 if (itr->second->PlayerLoading())
167 return false;
168 itr->second->KickPlayer();
171 return true;
174 void World::AddSession(WorldSession* s)
176 addSessQueue.add(s);
179 void
180 World::AddSession_ (WorldSession* s)
182 ASSERT (s);
184 //NOTE - Still there is race condition in WorldSession* being used in the Sockets
186 ///- kick already loaded player with same account (if any) and remove session
187 ///- if player is in loading and want to load again, return
188 if (!RemoveSession (s->GetAccountId ()))
190 s->KickPlayer ();
191 delete s; // session not added yet in session list, so not listed in queue
192 return;
195 // decrease session counts only at not reconnection case
196 bool decrease_session = true;
198 // if session already exist, prepare to it deleting at next world update
199 // NOTE - KickPlayer() should be called on "old" in RemoveSession()
201 SessionMap::const_iterator old = m_sessions.find(s->GetAccountId ());
203 if(old != m_sessions.end())
205 // prevent decrease sessions count if session queued
206 if(RemoveQueuedPlayer(old->second))
207 decrease_session = false;
208 // not remove replaced session form queue if listed
209 delete old->second;
213 m_sessions[s->GetAccountId ()] = s;
215 uint32 Sessions = GetActiveAndQueuedSessionCount ();
216 uint32 pLimit = GetPlayerAmountLimit ();
217 uint32 QueueSize = GetQueueSize (); //number of players in the queue
219 //so we don't count the user trying to
220 //login as a session and queue the socket that we are using
221 if(decrease_session)
222 --Sessions;
224 if (pLimit > 0 && Sessions >= pLimit && s->GetSecurity () == SEC_PLAYER )
226 AddQueuedPlayer (s);
227 UpdateMaxSessionCounters ();
228 sLog.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s->GetAccountId (), ++QueueSize);
229 return;
232 WorldPacket packet(SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
233 packet << uint8 (AUTH_OK);
234 packet << uint32 (0); // BillingTimeRemaining
235 packet << uint8 (0); // BillingPlanFlags
236 packet << uint32 (0); // BillingTimeRested
237 packet << uint8 (s->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
238 s->SendPacket (&packet);
240 s->SendAddonsInfo();
242 WorldPacket pkt(SMSG_CLIENTCACHE_VERSION, 4);
243 pkt << uint32(sWorld.getConfig(CONFIG_CLIENTCACHE_VERSION));
244 s->SendPacket(&pkt);
246 s->SendTutorialsData();
248 UpdateMaxSessionCounters ();
250 // Updates the population
251 if (pLimit > 0)
253 float popu = GetActiveSessionCount (); // updated number of users on the server
254 popu /= pLimit;
255 popu *= 2;
256 loginDatabase.PExecute ("UPDATE realmlist SET population = '%f' WHERE id = '%d'", popu, realmID);
257 sLog.outDetail ("Server Population (%f).", popu);
261 int32 World::GetQueuePos(WorldSession* sess)
263 uint32 position = 1;
265 for(Queue::const_iterator iter = m_QueuedPlayer.begin(); iter != m_QueuedPlayer.end(); ++iter, ++position)
266 if((*iter) == sess)
267 return position;
269 return 0;
272 void World::AddQueuedPlayer(WorldSession* sess)
274 sess->SetInQueue(true);
275 m_QueuedPlayer.push_back (sess);
277 // The 1st SMSG_AUTH_RESPONSE needs to contain other info too.
278 WorldPacket packet (SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
279 packet << uint8 (AUTH_WAIT_QUEUE);
280 packet << uint32 (0); // BillingTimeRemaining
281 packet << uint8 (0); // BillingPlanFlags
282 packet << uint32 (0); // BillingTimeRested
283 packet << uint8 (sess->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
284 packet << uint32(GetQueuePos (sess));
285 sess->SendPacket (&packet);
287 //sess->SendAuthWaitQue (GetQueuePos (sess));
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 m_QueuedPlayer.pop_front();
327 // update iter to point first queued socket or end() if queue is empty now
328 iter = m_QueuedPlayer.begin();
329 position = 1;
332 // update position from iter to end()
333 // iter point to first not updated socket, position store new position
334 for(; iter != m_QueuedPlayer.end(); ++iter, ++position)
335 (*iter)->SendAuthWaitQue(position);
337 return found;
340 /// Find a Weather object by the given zoneid
341 Weather* World::FindWeather(uint32 id) const
343 WeatherMap::const_iterator itr = m_weathers.find(id);
345 if(itr != m_weathers.end())
346 return itr->second;
347 else
348 return 0;
351 /// Remove a Weather object for the given zoneid
352 void World::RemoveWeather(uint32 id)
354 // not called at the moment. Kept for completeness
355 WeatherMap::iterator itr = m_weathers.find(id);
357 if(itr != m_weathers.end())
359 delete itr->second;
360 m_weathers.erase(itr);
364 /// Add a Weather object to the list
365 Weather* World::AddWeather(uint32 zone_id)
367 WeatherZoneChances const* weatherChances = objmgr.GetWeatherChances(zone_id);
369 // zone not have weather, ignore
370 if(!weatherChances)
371 return NULL;
373 Weather* w = new Weather(zone_id,weatherChances);
374 m_weathers[w->GetZone()] = w;
375 w->ReGenerate();
376 w->UpdateWeather();
377 return w;
380 /// Initialize config values
381 void World::LoadConfigSettings(bool reload)
383 if(reload)
385 if(!sConfig.Reload())
387 sLog.outError("World settings reload fail: can't read settings from %s.",sConfig.GetFilename().c_str());
388 return;
392 ///- Read the version of the configuration file and warn the user in case of emptiness or mismatch
393 uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
394 if(!confVersion)
396 sLog.outError("*****************************************************************************");
397 sLog.outError(" WARNING: mangosd.conf does not include a ConfVersion variable.");
398 sLog.outError(" Your configuration file may be out of date!");
399 sLog.outError("*****************************************************************************");
400 clock_t pause = 3000 + clock();
401 while (pause > clock())
402 ; // empty body
404 else
406 if (confVersion < _MANGOSDCONFVERSION)
408 sLog.outError("*****************************************************************************");
409 sLog.outError(" WARNING: Your mangosd.conf version indicates your conf file is out of date!");
410 sLog.outError(" Please check for updates, as your current default values may cause");
411 sLog.outError(" unexpected behavior.");
412 sLog.outError("*****************************************************************************");
413 clock_t pause = 3000 + clock();
414 while (pause > clock())
415 ; // empty body
419 ///- Read the player limit and the Message of the day from the config file
420 SetPlayerLimit( sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT), true );
421 SetMotd( sConfig.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
423 ///- Read all rates from the config file
424 rate_values[RATE_HEALTH] = sConfig.GetFloatDefault("Rate.Health", 1);
425 if(rate_values[RATE_HEALTH] < 0)
427 sLog.outError("Rate.Health (%f) must be > 0. Using 1 instead.",rate_values[RATE_HEALTH]);
428 rate_values[RATE_HEALTH] = 1;
430 rate_values[RATE_POWER_MANA] = sConfig.GetFloatDefault("Rate.Mana", 1);
431 if(rate_values[RATE_POWER_MANA] < 0)
433 sLog.outError("Rate.Mana (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_MANA]);
434 rate_values[RATE_POWER_MANA] = 1;
436 rate_values[RATE_POWER_RAGE_INCOME] = sConfig.GetFloatDefault("Rate.Rage.Income", 1);
437 rate_values[RATE_POWER_RAGE_LOSS] = sConfig.GetFloatDefault("Rate.Rage.Loss", 1);
438 if(rate_values[RATE_POWER_RAGE_LOSS] < 0)
440 sLog.outError("Rate.Rage.Loss (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_RAGE_LOSS]);
441 rate_values[RATE_POWER_RAGE_LOSS] = 1;
443 rate_values[RATE_POWER_RUNICPOWER_INCOME] = sConfig.GetFloatDefault("Rate.RunicPower.Income", 1);
444 rate_values[RATE_POWER_RUNICPOWER_LOSS] = sConfig.GetFloatDefault("Rate.RunicPower.Loss", 1);
445 if(rate_values[RATE_POWER_RUNICPOWER_LOSS] < 0)
447 sLog.outError("Rate.RunicPower.Loss (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_RUNICPOWER_LOSS]);
448 rate_values[RATE_POWER_RUNICPOWER_LOSS] = 1;
450 rate_values[RATE_POWER_FOCUS] = sConfig.GetFloatDefault("Rate.Focus", 1.0f);
451 rate_values[RATE_SKILL_DISCOVERY] = sConfig.GetFloatDefault("Rate.Skill.Discovery", 1.0f);
452 rate_values[RATE_DROP_ITEM_POOR] = sConfig.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f);
453 rate_values[RATE_DROP_ITEM_NORMAL] = sConfig.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f);
454 rate_values[RATE_DROP_ITEM_UNCOMMON] = sConfig.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f);
455 rate_values[RATE_DROP_ITEM_RARE] = sConfig.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f);
456 rate_values[RATE_DROP_ITEM_EPIC] = sConfig.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f);
457 rate_values[RATE_DROP_ITEM_LEGENDARY] = sConfig.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f);
458 rate_values[RATE_DROP_ITEM_ARTIFACT] = sConfig.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f);
459 rate_values[RATE_DROP_ITEM_REFERENCED] = sConfig.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f);
460 rate_values[RATE_DROP_MONEY] = sConfig.GetFloatDefault("Rate.Drop.Money", 1.0f);
461 rate_values[RATE_XP_KILL] = sConfig.GetFloatDefault("Rate.XP.Kill", 1.0f);
462 rate_values[RATE_XP_QUEST] = sConfig.GetFloatDefault("Rate.XP.Quest", 1.0f);
463 rate_values[RATE_XP_EXPLORE] = sConfig.GetFloatDefault("Rate.XP.Explore", 1.0f);
464 rate_values[RATE_REPUTATION_GAIN] = sConfig.GetFloatDefault("Rate.Reputation.Gain", 1.0f);
465 rate_values[RATE_REPUTATION_LOWLEVEL_KILL] = sConfig.GetFloatDefault("Rate.Reputation.LowLevel.Kill", 1.0f);
466 rate_values[RATE_REPUTATION_LOWLEVEL_QUEST] = sConfig.GetFloatDefault("Rate.Reputation.LowLevel.Quest", 1.0f);
467 rate_values[RATE_CREATURE_NORMAL_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f);
468 rate_values[RATE_CREATURE_ELITE_ELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f);
469 rate_values[RATE_CREATURE_ELITE_RAREELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f);
470 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f);
471 rate_values[RATE_CREATURE_ELITE_RARE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f);
472 rate_values[RATE_CREATURE_NORMAL_HP] = sConfig.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f);
473 rate_values[RATE_CREATURE_ELITE_ELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f);
474 rate_values[RATE_CREATURE_ELITE_RAREELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f);
475 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f);
476 rate_values[RATE_CREATURE_ELITE_RARE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f);
477 rate_values[RATE_CREATURE_NORMAL_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f);
478 rate_values[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f);
479 rate_values[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f);
480 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f);
481 rate_values[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f);
482 rate_values[RATE_CREATURE_AGGRO] = sConfig.GetFloatDefault("Rate.Creature.Aggro", 1.0f);
483 rate_values[RATE_REST_INGAME] = sConfig.GetFloatDefault("Rate.Rest.InGame", 1.0f);
484 rate_values[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY] = sConfig.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f);
485 rate_values[RATE_REST_OFFLINE_IN_WILDERNESS] = sConfig.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f);
486 rate_values[RATE_DAMAGE_FALL] = sConfig.GetFloatDefault("Rate.Damage.Fall", 1.0f);
487 rate_values[RATE_AUCTION_TIME] = sConfig.GetFloatDefault("Rate.Auction.Time", 1.0f);
488 rate_values[RATE_AUCTION_DEPOSIT] = sConfig.GetFloatDefault("Rate.Auction.Deposit", 1.0f);
489 rate_values[RATE_AUCTION_CUT] = sConfig.GetFloatDefault("Rate.Auction.Cut", 1.0f);
490 rate_values[RATE_HONOR] = sConfig.GetFloatDefault("Rate.Honor",1.0f);
491 rate_values[RATE_MINING_AMOUNT] = sConfig.GetFloatDefault("Rate.Mining.Amount",1.0f);
492 rate_values[RATE_MINING_NEXT] = sConfig.GetFloatDefault("Rate.Mining.Next",1.0f);
493 rate_values[RATE_INSTANCE_RESET_TIME] = sConfig.GetFloatDefault("Rate.InstanceResetTime",1.0f);
494 rate_values[RATE_TALENT] = sConfig.GetFloatDefault("Rate.Talent",1.0f);
495 if(rate_values[RATE_TALENT] < 0.0f)
497 sLog.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_TALENT]);
498 rate_values[RATE_TALENT] = 1.0f;
500 rate_values[RATE_CORPSE_DECAY_LOOTED] = sConfig.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f);
502 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = sConfig.GetFloatDefault("TargetPosRecalculateRange",1.5f);
503 if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] < CONTACT_DISTANCE)
505 sLog.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],CONTACT_DISTANCE,CONTACT_DISTANCE);
506 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = CONTACT_DISTANCE;
508 else if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] > ATTACK_DISTANCE)
510 sLog.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",
511 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],ATTACK_DISTANCE,ATTACK_DISTANCE);
512 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = ATTACK_DISTANCE;
515 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = sConfig.GetFloatDefault("DurabilityLossChance.Damage",0.5f);
516 if(rate_values[RATE_DURABILITY_LOSS_DAMAGE] < 0.0f)
518 sLog.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_DAMAGE]);
519 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = 0.0f;
521 rate_values[RATE_DURABILITY_LOSS_ABSORB] = sConfig.GetFloatDefault("DurabilityLossChance.Absorb",0.5f);
522 if(rate_values[RATE_DURABILITY_LOSS_ABSORB] < 0.0f)
524 sLog.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_ABSORB]);
525 rate_values[RATE_DURABILITY_LOSS_ABSORB] = 0.0f;
527 rate_values[RATE_DURABILITY_LOSS_PARRY] = sConfig.GetFloatDefault("DurabilityLossChance.Parry",0.05f);
528 if(rate_values[RATE_DURABILITY_LOSS_PARRY] < 0.0f)
530 sLog.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_PARRY]);
531 rate_values[RATE_DURABILITY_LOSS_PARRY] = 0.0f;
533 rate_values[RATE_DURABILITY_LOSS_BLOCK] = sConfig.GetFloatDefault("DurabilityLossChance.Block",0.05f);
534 if(rate_values[RATE_DURABILITY_LOSS_BLOCK] < 0.0f)
536 sLog.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_BLOCK]);
537 rate_values[RATE_DURABILITY_LOSS_BLOCK] = 0.0f;
540 ///- Read other configuration items from the config file
542 m_configs[CONFIG_COMPRESSION] = sConfig.GetIntDefault("Compression", 1);
543 if(m_configs[CONFIG_COMPRESSION] < 1 || m_configs[CONFIG_COMPRESSION] > 9)
545 sLog.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs[CONFIG_COMPRESSION]);
546 m_configs[CONFIG_COMPRESSION] = 1;
548 m_configs[CONFIG_ADDON_CHANNEL] = sConfig.GetBoolDefault("AddonChannel", true);
549 m_configs[CONFIG_GRID_UNLOAD] = sConfig.GetBoolDefault("GridUnload", true);
550 m_configs[CONFIG_INTERVAL_SAVE] = sConfig.GetIntDefault("PlayerSaveInterval", 15 * MINUTE * IN_MILISECONDS);
552 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = sConfig.GetIntDefault("GridCleanUpDelay", 5 * MINUTE * IN_MILISECONDS);
553 if(m_configs[CONFIG_INTERVAL_GRIDCLEAN] < MIN_GRID_DELAY)
555 sLog.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_GRIDCLEAN],MIN_GRID_DELAY);
556 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = MIN_GRID_DELAY;
558 if(reload)
559 MapManager::Instance().SetGridCleanUpDelay(m_configs[CONFIG_INTERVAL_GRIDCLEAN]);
561 m_configs[CONFIG_INTERVAL_MAPUPDATE] = sConfig.GetIntDefault("MapUpdateInterval", 100);
562 if(m_configs[CONFIG_INTERVAL_MAPUPDATE] < MIN_MAP_UPDATE_DELAY)
564 sLog.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_MAPUPDATE],MIN_MAP_UPDATE_DELAY);
565 m_configs[CONFIG_INTERVAL_MAPUPDATE] = MIN_MAP_UPDATE_DELAY;
567 if(reload)
568 MapManager::Instance().SetMapUpdateInterval(m_configs[CONFIG_INTERVAL_MAPUPDATE]);
570 m_configs[CONFIG_INTERVAL_CHANGEWEATHER] = sConfig.GetIntDefault("ChangeWeatherInterval", 10 * MINUTE * IN_MILISECONDS);
572 if(reload)
574 uint32 val = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
575 if(val!=m_configs[CONFIG_PORT_WORLD])
576 sLog.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_PORT_WORLD]);
578 else
579 m_configs[CONFIG_PORT_WORLD] = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
581 if(reload)
583 uint32 val = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
584 if(val!=m_configs[CONFIG_SOCKET_SELECTTIME])
585 sLog.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_SOCKET_SELECTTIME]);
587 else
588 m_configs[CONFIG_SOCKET_SELECTTIME] = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
590 m_configs[CONFIG_GROUP_XP_DISTANCE] = sConfig.GetIntDefault("MaxGroupXPDistance", 74);
591 /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
592 m_configs[CONFIG_SIGHT_MONSTER] = sConfig.GetIntDefault("MonsterSight", 50);
593 m_configs[CONFIG_SIGHT_GUARDER] = sConfig.GetIntDefault("GuarderSight", 50);
595 if(reload)
597 uint32 val = sConfig.GetIntDefault("GameType", 0);
598 if(val!=m_configs[CONFIG_GAME_TYPE])
599 sLog.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_GAME_TYPE]);
601 else
602 m_configs[CONFIG_GAME_TYPE] = sConfig.GetIntDefault("GameType", 0);
604 if(reload)
606 uint32 val = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
607 if(val!=m_configs[CONFIG_REALM_ZONE])
608 sLog.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_REALM_ZONE]);
610 else
611 m_configs[CONFIG_REALM_ZONE] = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
613 m_configs[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS] = sConfig.GetBoolDefault("AllowTwoSide.Accounts", false);
614 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
615 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
616 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
617 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
618 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
619 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
620 m_configs[CONFIG_ALLOW_TWO_SIDE_WHO_LIST] = sConfig.GetBoolDefault("AllowTwoSide.WhoList", false);
621 m_configs[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND] = sConfig.GetBoolDefault("AllowTwoSide.AddFriend", false);
622 m_configs[CONFIG_STRICT_PLAYER_NAMES] = sConfig.GetIntDefault ("StrictPlayerNames", 0);
623 m_configs[CONFIG_STRICT_CHARTER_NAMES] = sConfig.GetIntDefault ("StrictCharterNames", 0);
624 m_configs[CONFIG_STRICT_PET_NAMES] = sConfig.GetIntDefault ("StrictPetNames", 0);
626 m_configs[CONFIG_MIN_PLAYER_NAME] = sConfig.GetIntDefault ("MinPlayerName", 2);
627 if(m_configs[CONFIG_MIN_PLAYER_NAME] < 1 || m_configs[CONFIG_MIN_PLAYER_NAME] > MAX_PLAYER_NAME)
629 sLog.outError("MinPlayerName (%i) must be in range 1..%u. Set to 2.",m_configs[CONFIG_MIN_PLAYER_NAME],MAX_PLAYER_NAME);
630 m_configs[CONFIG_MIN_PLAYER_NAME] = 2;
633 m_configs[CONFIG_MIN_CHARTER_NAME] = sConfig.GetIntDefault ("MinCharterName", 2);
634 if(m_configs[CONFIG_MIN_CHARTER_NAME] < 1 || m_configs[CONFIG_MIN_CHARTER_NAME] > MAX_CHARTER_NAME)
636 sLog.outError("MinCharterName (%i) must be in range 1..%u. Set to 2.",m_configs[CONFIG_MIN_CHARTER_NAME],MAX_CHARTER_NAME);
637 m_configs[CONFIG_MIN_CHARTER_NAME] = 2;
640 m_configs[CONFIG_MIN_PET_NAME] = sConfig.GetIntDefault ("MinPetName", 2);
641 if(m_configs[CONFIG_MIN_PET_NAME] < 1 || m_configs[CONFIG_MIN_PET_NAME] > MAX_PET_NAME)
643 sLog.outError("MinPetName (%i) must be in range 1..%u. Set to 2.",m_configs[CONFIG_MIN_PET_NAME],MAX_PET_NAME);
644 m_configs[CONFIG_MIN_PET_NAME] = 2;
647 m_configs[CONFIG_CHARACTERS_CREATING_DISABLED] = sConfig.GetIntDefault ("CharactersCreatingDisabled", 0);
649 m_configs[CONFIG_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("CharactersPerRealm", 10);
650 if(m_configs[CONFIG_CHARACTERS_PER_REALM] < 1 || m_configs[CONFIG_CHARACTERS_PER_REALM] > 10)
652 sLog.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs[CONFIG_CHARACTERS_PER_REALM]);
653 m_configs[CONFIG_CHARACTERS_PER_REALM] = 10;
656 // must be after CONFIG_CHARACTERS_PER_REALM
657 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = sConfig.GetIntDefault("CharactersPerAccount", 50);
658 if(m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] < m_configs[CONFIG_CHARACTERS_PER_REALM])
660 sLog.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs[CONFIG_CHARACTERS_PER_ACCOUNT],m_configs[CONFIG_CHARACTERS_PER_REALM]);
661 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = m_configs[CONFIG_CHARACTERS_PER_REALM];
664 m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("HeroicCharactersPerRealm", 1);
665 if(int32(m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM]) < 0 || m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] > 10)
667 sLog.outError("HeroicCharactersPerRealm (%i) must be in range 0..10. Set to 1.",m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM]);
668 m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] = 1;
671 m_configs[CONFIG_MIN_LEVEL_FOR_HEROIC_CHARACTER_CREATING] = sConfig.GetIntDefault("MinLevelForHeroicCharacterCreating", 55);
673 m_configs[CONFIG_SKIP_CINEMATICS] = sConfig.GetIntDefault("SkipCinematics", 0);
674 if(int32(m_configs[CONFIG_SKIP_CINEMATICS]) < 0 || m_configs[CONFIG_SKIP_CINEMATICS] > 2)
676 sLog.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs[CONFIG_SKIP_CINEMATICS]);
677 m_configs[CONFIG_SKIP_CINEMATICS] = 0;
680 if(reload)
682 uint32 val = sConfig.GetIntDefault("MaxPlayerLevel", DEFAULT_MAX_LEVEL);
683 if(val!=m_configs[CONFIG_MAX_PLAYER_LEVEL])
684 sLog.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
686 else
687 m_configs[CONFIG_MAX_PLAYER_LEVEL] = sConfig.GetIntDefault("MaxPlayerLevel", DEFAULT_MAX_LEVEL);
689 if(m_configs[CONFIG_MAX_PLAYER_LEVEL] > MAX_LEVEL)
691 sLog.outError("MaxPlayerLevel (%i) must be in range 1..%u. Set to %u.",m_configs[CONFIG_MAX_PLAYER_LEVEL],MAX_LEVEL,MAX_LEVEL);
692 m_configs[CONFIG_MAX_PLAYER_LEVEL] = MAX_LEVEL;
695 m_configs[CONFIG_START_PLAYER_LEVEL] = sConfig.GetIntDefault("StartPlayerLevel", 1);
696 if(m_configs[CONFIG_START_PLAYER_LEVEL] < 1)
698 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]);
699 m_configs[CONFIG_START_PLAYER_LEVEL] = 1;
701 else if(m_configs[CONFIG_START_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
703 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]);
704 m_configs[CONFIG_START_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
707 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = sConfig.GetIntDefault("StartHeroicPlayerLevel", 55);
708 if(m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] < 1)
710 sLog.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to 55.",
711 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
712 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = 55;
714 else if(m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
716 sLog.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to %u.",
717 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
718 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
721 m_configs[CONFIG_START_PLAYER_MONEY] = sConfig.GetIntDefault("StartPlayerMoney", 0);
722 if(int32(m_configs[CONFIG_START_PLAYER_MONEY]) < 0)
724 sLog.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",m_configs[CONFIG_START_PLAYER_MONEY],MAX_MONEY_AMOUNT,0);
725 m_configs[CONFIG_START_PLAYER_MONEY] = 0;
727 else if(m_configs[CONFIG_START_PLAYER_MONEY] > MAX_MONEY_AMOUNT)
729 sLog.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",
730 m_configs[CONFIG_START_PLAYER_MONEY],MAX_MONEY_AMOUNT,MAX_MONEY_AMOUNT);
731 m_configs[CONFIG_START_PLAYER_MONEY] = MAX_MONEY_AMOUNT;
734 m_configs[CONFIG_MAX_HONOR_POINTS] = sConfig.GetIntDefault("MaxHonorPoints", 75000);
735 if(int32(m_configs[CONFIG_MAX_HONOR_POINTS]) < 0)
737 sLog.outError("MaxHonorPoints (%i) can't be negative. Set to 0.",m_configs[CONFIG_MAX_HONOR_POINTS]);
738 m_configs[CONFIG_MAX_HONOR_POINTS] = 0;
741 m_configs[CONFIG_START_HONOR_POINTS] = sConfig.GetIntDefault("StartHonorPoints", 0);
742 if(int32(m_configs[CONFIG_START_HONOR_POINTS]) < 0)
744 sLog.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
745 m_configs[CONFIG_START_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS],0);
746 m_configs[CONFIG_START_HONOR_POINTS] = 0;
748 else if(m_configs[CONFIG_START_HONOR_POINTS] > m_configs[CONFIG_MAX_HONOR_POINTS])
750 sLog.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
751 m_configs[CONFIG_START_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS]);
752 m_configs[CONFIG_START_HONOR_POINTS] = m_configs[CONFIG_MAX_HONOR_POINTS];
755 m_configs[CONFIG_MAX_ARENA_POINTS] = sConfig.GetIntDefault("MaxArenaPoints", 5000);
756 if(int32(m_configs[CONFIG_MAX_ARENA_POINTS]) < 0)
758 sLog.outError("MaxArenaPoints (%i) can't be negative. Set to 0.",m_configs[CONFIG_MAX_ARENA_POINTS]);
759 m_configs[CONFIG_MAX_ARENA_POINTS] = 0;
762 m_configs[CONFIG_START_ARENA_POINTS] = sConfig.GetIntDefault("StartArenaPoints", 0);
763 if(int32(m_configs[CONFIG_START_ARENA_POINTS]) < 0)
765 sLog.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
766 m_configs[CONFIG_START_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS],0);
767 m_configs[CONFIG_MAX_ARENA_POINTS] = 0;
769 else if(m_configs[CONFIG_START_ARENA_POINTS] > m_configs[CONFIG_MAX_ARENA_POINTS])
771 sLog.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
772 m_configs[CONFIG_START_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS]);
773 m_configs[CONFIG_START_ARENA_POINTS] = m_configs[CONFIG_MAX_ARENA_POINTS];
776 m_configs[CONFIG_ALL_TAXI_PATHS] = sConfig.GetBoolDefault("AllFlightPaths", false);
778 m_configs[CONFIG_INSTANCE_IGNORE_LEVEL] = sConfig.GetBoolDefault("Instance.IgnoreLevel", false);
779 m_configs[CONFIG_INSTANCE_IGNORE_RAID] = sConfig.GetBoolDefault("Instance.IgnoreRaid", false);
781 m_configs[CONFIG_CAST_UNSTUCK] = sConfig.GetBoolDefault("CastUnstuck", true);
782 m_configs[CONFIG_INSTANCE_RESET_TIME_HOUR] = sConfig.GetIntDefault("Instance.ResetTimeHour", 4);
783 m_configs[CONFIG_INSTANCE_UNLOAD_DELAY] = sConfig.GetIntDefault("Instance.UnloadDelay", 30 * MINUTE * IN_MILISECONDS);
785 m_configs[CONFIG_MAX_PRIMARY_TRADE_SKILL] = sConfig.GetIntDefault("MaxPrimaryTradeSkill", 2);
786 m_configs[CONFIG_MIN_PETITION_SIGNS] = sConfig.GetIntDefault("MinPetitionSigns", 9);
787 if(m_configs[CONFIG_MIN_PETITION_SIGNS] > 9)
789 sLog.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.", m_configs[CONFIG_MIN_PETITION_SIGNS]);
790 m_configs[CONFIG_MIN_PETITION_SIGNS] = 9;
793 m_configs[CONFIG_GM_LOGIN_STATE] = sConfig.GetIntDefault("GM.LoginState", 2);
794 m_configs[CONFIG_GM_VISIBLE_STATE] = sConfig.GetIntDefault("GM.Visible", 2);
795 m_configs[CONFIG_GM_ACCEPT_TICKETS] = sConfig.GetIntDefault("GM.AcceptTickets", 2);
796 m_configs[CONFIG_GM_CHAT] = sConfig.GetIntDefault("GM.Chat", 2);
797 m_configs[CONFIG_GM_WISPERING_TO] = sConfig.GetIntDefault("GM.WhisperingTo", 2);
799 m_configs[CONFIG_GM_LEVEL_IN_GM_LIST] = sConfig.GetIntDefault("GM.InGMList.Level", SEC_ADMINISTRATOR);
800 m_configs[CONFIG_GM_LEVEL_IN_WHO_LIST] = sConfig.GetIntDefault("GM.InWhoList.Level", SEC_ADMINISTRATOR);
801 m_configs[CONFIG_GM_LOG_TRADE] = sConfig.GetBoolDefault("GM.LogTrade", false);
803 m_configs[CONFIG_START_GM_LEVEL] = sConfig.GetIntDefault("GM.StartLevel", 1);
804 if(m_configs[CONFIG_START_GM_LEVEL] < m_configs[CONFIG_START_PLAYER_LEVEL])
806 sLog.outError("GM.StartLevel (%i) must be in range StartPlayerLevel(%u)..%u. Set to %u.",
807 m_configs[CONFIG_START_GM_LEVEL],m_configs[CONFIG_START_PLAYER_LEVEL], MAX_LEVEL, m_configs[CONFIG_START_PLAYER_LEVEL]);
808 m_configs[CONFIG_START_GM_LEVEL] = m_configs[CONFIG_START_PLAYER_LEVEL];
810 else if(m_configs[CONFIG_START_GM_LEVEL] > MAX_LEVEL)
812 sLog.outError("GM.StartLevel (%i) must be in range 1..%u. Set to %u.", m_configs[CONFIG_START_GM_LEVEL], MAX_LEVEL, MAX_LEVEL);
813 m_configs[CONFIG_START_GM_LEVEL] = MAX_LEVEL;
815 m_configs[CONFIG_GM_LOWER_SECURITY] = sConfig.GetBoolDefault("GM.LowerSecurity", false);
816 m_configs[CONFIG_GM_ALLOW_ACHIEVEMENT_GAINS] = sConfig.GetBoolDefault("GM.AllowAchievementGain", true);
818 m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
820 m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
822 m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
823 if(int32(m_configs[CONFIG_UPTIME_UPDATE])<=0)
825 sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
826 m_configs[CONFIG_UPTIME_UPDATE] = 10;
828 if(reload)
830 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*IN_MILISECONDS);
831 m_timers[WUPDATE_UPTIME].Reset();
834 m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
835 m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
836 m_configs[CONFIG_SKILL_CHANCE_GREEN] = sConfig.GetIntDefault("SkillChance.Green",25);
837 m_configs[CONFIG_SKILL_CHANCE_GREY] = sConfig.GetIntDefault("SkillChance.Grey",0);
839 m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS] = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
840 m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS] = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
842 m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
843 m_configs[CONFIG_SKILL_MILLING] = sConfig.GetBoolDefault("SkillChance.Milling",false);
845 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = sConfig.GetIntDefault("SkillGain.Crafting", 1);
846 if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
848 sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
849 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
852 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = sConfig.GetIntDefault("SkillGain.Defense", 1);
853 if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
855 sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
856 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
859 m_configs[CONFIG_SKILL_GAIN_GATHERING] = sConfig.GetIntDefault("SkillGain.Gathering", 1);
860 if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
862 sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
863 m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
866 m_configs[CONFIG_SKILL_GAIN_WEAPON] = sConfig.GetIntDefault("SkillGain.Weapon", 1);
867 if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
869 sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
870 m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
873 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
874 if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
876 sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check). Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
877 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
880 m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
881 m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
883 m_configs[CONFIG_DISABLE_BREATHING] = sConfig.GetIntDefault("DisableWaterBreath", SEC_CONSOLE);
885 m_configs[CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL] = sConfig.GetBoolDefault("AlwaysMaxSkillForLevel", false);
887 if(reload)
889 uint32 val = sConfig.GetIntDefault("Expansion",1);
890 if(val!=m_configs[CONFIG_EXPANSION])
891 sLog.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
893 else
894 m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",1);
896 m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
897 m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
898 m_configs[CONFIG_CHATFLOOD_MUTE_TIME] = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
900 m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
902 m_configs[CONFIG_CREATURE_FAMILY_FLEE_ASSISTANCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyFleeAssistanceRadius",30);
903 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistanceRadius",10);
904 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY] = sConfig.GetIntDefault("CreatureFamilyAssistanceDelay",1500);
905 m_configs[CONFIG_CREATURE_FAMILY_FLEE_DELAY] = sConfig.GetIntDefault("CreatureFamilyFleeDelay",7000);
907 m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
909 // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level MAX_LEVEL(100)
910 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff", 4);
911 if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > MAX_LEVEL)
912 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = MAX_LEVEL;
913 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff", 7);
914 if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > MAX_LEVEL)
915 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = MAX_LEVEL;
917 m_configs[CONFIG_DETECT_POS_COLLISION] = sConfig.GetBoolDefault("DetectPosCollision", true);
919 m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
920 m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
922 m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
923 m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
924 m_configs[CONFIG_CHAT_STRICT_LINK_CHECKING_SEVERITY] = sConfig.GetIntDefault("ChatStrictLinkChecking.Severity", 0);
925 m_configs[CONFIG_CHAT_STRICT_LINK_CHECKING_KICK] = sConfig.GetIntDefault("ChatStrictLinkChecking.Kick", 0);
927 m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
928 m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
929 m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
930 m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
931 m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
933 m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault ("Death.SicknessLevel", 11);
934 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
935 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
936 m_configs[CONFIG_DEATH_BONES_WORLD] = sConfig.GetBoolDefault("Death.Bones.World", true);
937 m_configs[CONFIG_DEATH_BONES_BG_OR_ARENA] = sConfig.GetBoolDefault("Death.Bones.BattlegroundOrArena", true);
939 m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
941 // always use declined names in the russian client
942 m_configs[CONFIG_DECLINED_NAMES_USED] =
943 (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
945 m_configs[CONFIG_LISTEN_RANGE_SAY] = sConfig.GetIntDefault("ListenRange.Say", 25);
946 m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
947 m_configs[CONFIG_LISTEN_RANGE_YELL] = sConfig.GetIntDefault("ListenRange.Yell", 300);
949 m_configs[CONFIG_BATTLEGROUND_CAST_DESERTER] = sConfig.GetBoolDefault("Battleground.CastDeserter", true);
950 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.Enable", false);
951 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false);
952 m_configs[CONFIG_BATTLEGROUND_INVITATION_TYPE] = sConfig.GetIntDefault ("Battleground.InvitationType", 0);
953 m_configs[CONFIG_BATTLEGROUND_PREMATURE_FINISH_TIMER] = sConfig.GetIntDefault ("BattleGround.PrematureFinishTimer", 5 * MINUTE * IN_MILISECONDS);
954 m_configs[CONFIG_BATTLEGROUND_PREMADE_GROUP_WAIT_FOR_MATCH] = sConfig.GetIntDefault ("BattleGround.PremadeGroupWaitForMatch", 30 * MINUTE * IN_MILISECONDS);
955 m_configs[CONFIG_ARENA_MAX_RATING_DIFFERENCE] = sConfig.GetIntDefault ("Arena.MaxRatingDifference", 150);
956 m_configs[CONFIG_ARENA_RATING_DISCARD_TIMER] = sConfig.GetIntDefault ("Arena.RatingDiscardTimer", 10 * MINUTE * IN_MILISECONDS);
957 m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_POINTS] = sConfig.GetBoolDefault("Arena.AutoDistributePoints", false);
958 m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS] = sConfig.GetIntDefault ("Arena.AutoDistributeInterval", 7);
959 m_configs[CONFIG_ARENA_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Arena.QueueAnnouncer.Enable", false);
960 m_configs[CONFIG_ARENA_SEASON_ID] = sConfig.GetIntDefault ("Arena.ArenaSeason.ID", 1);
961 m_configs[CONFIG_ARENA_SEASON_IN_PROGRESS] = sConfig.GetBoolDefault("Arena.ArenaSeason.InProgress", true);
963 m_configs[CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET] = sConfig.GetBoolDefault("OffhandCheckAtTalentsReset", false);
965 if(int clientCacheId = sConfig.GetIntDefault("ClientCacheVersion", 0))
967 // overwrite DB/old value
968 if(clientCacheId > 0)
970 m_configs[CONFIG_CLIENTCACHE_VERSION] = clientCacheId;
971 sLog.outString("Client cache version set to: %u", clientCacheId);
973 else
974 sLog.outError("ClientCacheVersion can't be negative %d, ignored.", clientCacheId);
977 m_configs[CONFIG_INSTANT_LOGOUT] = sConfig.GetIntDefault("InstantLogout", SEC_MODERATOR);
979 m_configs[CONFIG_GUILD_EVENT_LOG_COUNT] = sConfig.GetIntDefault("Guild.EventLogRecordsCount", GUILD_EVENTLOG_MAX_RECORDS);
980 if (m_configs[CONFIG_GUILD_EVENT_LOG_COUNT] < GUILD_EVENTLOG_MAX_RECORDS)
981 m_configs[CONFIG_GUILD_EVENT_LOG_COUNT] = GUILD_EVENTLOG_MAX_RECORDS;
982 m_configs[CONFIG_GUILD_BANK_EVENT_LOG_COUNT] = sConfig.GetIntDefault("Guild.BankEventLogRecordsCount", GUILD_BANK_MAX_LOGS);
983 if (m_configs[CONFIG_GUILD_BANK_EVENT_LOG_COUNT] < GUILD_BANK_MAX_LOGS)
984 m_configs[CONFIG_GUILD_BANK_EVENT_LOG_COUNT] = GUILD_BANK_MAX_LOGS;
986 m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
987 if(m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
989 sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
990 m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
992 m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
993 if(m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
995 sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
996 m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
999 m_MaxVisibleDistanceForCreature = sConfig.GetFloatDefault("Visibility.Distance.Creature", DEFAULT_VISIBILITY_DISTANCE);
1000 if(m_MaxVisibleDistanceForCreature < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
1002 sLog.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
1003 m_MaxVisibleDistanceForCreature = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
1005 else if(m_MaxVisibleDistanceForCreature + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
1007 sLog.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
1008 m_MaxVisibleDistanceForCreature = MAX_VISIBILITY_DISTANCE-m_VisibleUnitGreyDistance;
1010 m_MaxVisibleDistanceForPlayer = sConfig.GetFloatDefault("Visibility.Distance.Player", DEFAULT_VISIBILITY_DISTANCE);
1011 if(m_MaxVisibleDistanceForPlayer < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
1013 sLog.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
1014 m_MaxVisibleDistanceForPlayer = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
1016 else if(m_MaxVisibleDistanceForPlayer + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
1018 sLog.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
1019 m_MaxVisibleDistanceForPlayer = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
1021 m_MaxVisibleDistanceForObject = sConfig.GetFloatDefault("Visibility.Distance.Object", DEFAULT_VISIBILITY_DISTANCE);
1022 if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
1024 sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
1025 m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
1027 else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
1029 sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
1030 m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
1032 m_MaxVisibleDistanceInFlight = sConfig.GetFloatDefault("Visibility.Distance.InFlight", DEFAULT_VISIBILITY_DISTANCE);
1033 if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
1035 sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
1036 m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
1039 ///- Read the "Data" directory from the config file
1040 std::string dataPath = sConfig.GetStringDefault("DataDir","./");
1041 if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
1042 dataPath.append("/");
1044 if(reload)
1046 if(dataPath!=m_dataPath)
1047 sLog.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath.c_str());
1049 else
1051 m_dataPath = dataPath;
1052 sLog.outString("Using DataDir %s",m_dataPath.c_str());
1055 bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
1056 bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
1057 std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
1058 std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
1059 VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
1060 VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
1061 VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
1062 VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
1063 sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
1064 sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
1065 sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
1068 /// Initialize the World
1069 void World::SetInitialWorldSettings()
1071 ///- Initialize the random number generator
1072 srand((unsigned int)time(NULL));
1074 ///- Initialize config settings
1075 LoadConfigSettings();
1077 ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
1078 objmgr.SetHighestGuids();
1080 ///- Check the existence of the map files for all races' startup areas.
1081 if( !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
1082 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
1083 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
1084 ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
1085 ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
1086 ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
1087 ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
1088 ||m_configs[CONFIG_EXPANSION] && (
1089 !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
1091 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());
1092 exit(1);
1095 ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
1096 sLog.outString();
1097 sLog.outString("Loading MaNGOS strings...");
1098 if (!objmgr.LoadMangosStrings())
1099 exit(1); // Error message displayed in function already
1101 ///- Update the realm entry in the database with the realm type from the config file
1102 //No SQL injection as values are treated as integers
1104 // not send custom type REALM_FFA_PVP to realm list
1105 uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
1106 uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
1107 loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
1109 ///- Remove the bones after a restart
1110 CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
1112 ///- Load the DBC files
1113 sLog.outString("Initialize data stores...");
1114 LoadDBCStores(m_dataPath);
1115 DetectDBCLang();
1117 sLog.outString( "Loading Script Names...");
1118 objmgr.LoadScriptNames();
1120 sLog.outString( "Loading InstanceTemplate..." );
1121 objmgr.LoadInstanceTemplate();
1123 sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
1124 spellmgr.LoadSkillLineAbilityMap();
1126 ///- Clean up and pack instances
1127 sLog.outString( "Cleaning up instances..." );
1128 sInstanceSaveManager.CleanupInstances(); // must be called before `creature_respawn`/`gameobject_respawn` tables
1130 sLog.outString( "Packing instances..." );
1131 sInstanceSaveManager.PackInstances();
1133 sLog.outString();
1134 sLog.outString( "Loading Localization strings..." );
1135 objmgr.LoadCreatureLocales();
1136 objmgr.LoadGameObjectLocales();
1137 objmgr.LoadItemLocales();
1138 objmgr.LoadQuestLocales();
1139 objmgr.LoadNpcTextLocales();
1140 objmgr.LoadPageTextLocales();
1141 objmgr.LoadNpcOptionLocales();
1142 objmgr.LoadPointOfInterestLocales();
1143 objmgr.SetDBCLocaleIndex(GetDefaultDbcLocale()); // Get once for all the locale index of DBC language (console/broadcasts)
1144 sLog.outString( ">>> Localization strings loaded" );
1145 sLog.outString();
1147 sLog.outString( "Loading Page Texts..." );
1148 objmgr.LoadPageTexts();
1150 sLog.outString( "Loading Game Object Templates..." ); // must be after LoadPageTexts
1151 objmgr.LoadGameobjectInfo();
1153 sLog.outString( "Loading Spell Chain Data..." );
1154 spellmgr.LoadSpellChains();
1156 sLog.outString( "Loading Spell Elixir types..." );
1157 spellmgr.LoadSpellElixirs();
1159 sLog.outString( "Loading Spell Learn Skills..." );
1160 spellmgr.LoadSpellLearnSkills(); // must be after LoadSpellChains
1162 sLog.outString( "Loading Spell Learn Spells..." );
1163 spellmgr.LoadSpellLearnSpells();
1165 sLog.outString( "Loading Spell Proc Event conditions..." );
1166 spellmgr.LoadSpellProcEvents();
1168 sLog.outString( "Loading Spell Bonus Data..." );
1169 spellmgr.LoadSpellBonusess();
1171 sLog.outString( "Loading Spell Proc Item Enchant..." );
1172 spellmgr.LoadSpellProcItemEnchant(); // must be after LoadSpellChains
1174 sLog.outString( "Loading Aggro Spells Definitions...");
1175 spellmgr.LoadSpellThreats();
1177 sLog.outString( "Loading NPC Texts..." );
1178 objmgr.LoadGossipText();
1180 sLog.outString( "Loading Item Random Enchantments Table..." );
1181 LoadRandomEnchantmentsTable();
1183 sLog.outString( "Loading Items..." ); // must be after LoadRandomEnchantmentsTable and LoadPageTexts
1184 objmgr.LoadItemPrototypes();
1186 sLog.outString( "Loading Item Texts..." );
1187 objmgr.LoadItemTexts();
1189 sLog.outString( "Loading Creature Model Based Info Data..." );
1190 objmgr.LoadCreatureModelInfo();
1192 sLog.outString( "Loading Equipment templates...");
1193 objmgr.LoadEquipmentTemplates();
1195 sLog.outString( "Loading Creature templates..." );
1196 objmgr.LoadCreatureTemplates();
1198 sLog.outString( "Loading SpellsScriptTarget...");
1199 spellmgr.LoadSpellScriptTarget(); // must be after LoadCreatureTemplates and LoadGameobjectInfo
1201 sLog.outString( "Loading ItemRequiredTarget...");
1202 objmgr.LoadItemRequiredTarget();
1204 sLog.outString( "Loading Creature Reputation OnKill Data..." );
1205 objmgr.LoadReputationOnKill();
1207 sLog.outString( "Loading Points Of Interest Data..." );
1208 objmgr.LoadPointsOfInterest();
1210 sLog.outString( "Loading Creature Data..." );
1211 objmgr.LoadCreatures();
1213 sLog.outString( "Loading pet levelup spells..." );
1214 spellmgr.LoadPetLevelupSpellMap();
1216 sLog.outString( "Loading pet default spell additional to levelup spells..." );
1217 spellmgr.LoadPetDefaultSpells();
1219 sLog.outString( "Loading Creature Addon Data..." );
1220 sLog.outString();
1221 objmgr.LoadCreatureAddons(); // must be after LoadCreatureTemplates() and LoadCreatures()
1222 sLog.outString( ">>> Creature Addon Data loaded" );
1223 sLog.outString();
1225 sLog.outString( "Loading Creature Respawn Data..." ); // must be after PackInstances()
1226 objmgr.LoadCreatureRespawnTimes();
1228 sLog.outString( "Loading Gameobject Data..." );
1229 objmgr.LoadGameobjects();
1231 sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1232 objmgr.LoadGameobjectRespawnTimes();
1234 sLog.outString( "Loading Objects Pooling Data...");
1235 poolhandler.LoadFromDB();
1237 sLog.outString( "Loading Game Event Data...");
1238 sLog.outString();
1239 gameeventmgr.LoadFromDB();
1240 sLog.outString( ">>> Game Event Data loaded" );
1241 sLog.outString();
1243 sLog.outString( "Loading Weather Data..." );
1244 objmgr.LoadWeatherZoneChances();
1246 sLog.outString( "Loading Quests..." );
1247 objmgr.LoadQuests(); // must be loaded after DBCs, creature_template, item_template, gameobject tables
1249 sLog.outString( "Loading Quests Relations..." );
1250 sLog.outString();
1251 objmgr.LoadQuestRelations(); // must be after quest load
1252 sLog.outString( ">>> Quests Relations loaded" );
1253 sLog.outString();
1255 sLog.outString( "Loading UNIT_NPC_FLAG_SPELLCLICK Data..." );
1256 objmgr.LoadNPCSpellClickSpells();
1258 sLog.outString( "Loading SpellArea Data..." ); // must be after quest load
1259 spellmgr.LoadSpellAreas();
1261 sLog.outString( "Loading AreaTrigger definitions..." );
1262 objmgr.LoadAreaTriggerTeleports(); // must be after item template load
1264 sLog.outString( "Loading Quest Area Triggers..." );
1265 objmgr.LoadQuestAreaTriggers(); // must be after LoadQuests
1267 sLog.outString( "Loading Tavern Area Triggers..." );
1268 objmgr.LoadTavernAreaTriggers();
1270 sLog.outString( "Loading AreaTrigger script names..." );
1271 objmgr.LoadAreaTriggerScripts();
1273 sLog.outString( "Loading Graveyard-zone links...");
1274 objmgr.LoadGraveyardZones();
1276 sLog.outString( "Loading Spell target coordinates..." );
1277 spellmgr.LoadSpellTargetPositions();
1279 sLog.outString( "Loading spell pet auras..." );
1280 spellmgr.LoadSpellPetAuras();
1282 sLog.outString( "Loading Player Create Info & Level Stats..." );
1283 sLog.outString();
1284 objmgr.LoadPlayerInfo();
1285 sLog.outString( ">>> Player Create Info & Level Stats loaded" );
1286 sLog.outString();
1288 sLog.outString( "Loading Exploration BaseXP Data..." );
1289 objmgr.LoadExplorationBaseXP();
1291 sLog.outString( "Loading Pet Name Parts..." );
1292 objmgr.LoadPetNames();
1294 sLog.outString( "Loading the max pet number..." );
1295 objmgr.LoadPetNumber();
1297 sLog.outString( "Loading pet level stats..." );
1298 objmgr.LoadPetLevelInfo();
1300 sLog.outString( "Loading Player Corpses..." );
1301 objmgr.LoadCorpses();
1303 sLog.outString( "Loading Loot Tables..." );
1304 sLog.outString();
1305 LoadLootTables();
1306 sLog.outString( ">>> Loot Tables loaded" );
1307 sLog.outString();
1309 sLog.outString( "Loading Skill Discovery Table..." );
1310 LoadSkillDiscoveryTable();
1312 sLog.outString( "Loading Skill Extra Item Table..." );
1313 LoadSkillExtraItemTable();
1315 sLog.outString( "Loading Skill Fishing base level requirements..." );
1316 objmgr.LoadFishingBaseSkillLevel();
1318 sLog.outString( "Loading Achievements..." );
1319 sLog.outString();
1320 achievementmgr.LoadAchievementReferenceList();
1321 achievementmgr.LoadAchievementCriteriaList();
1322 achievementmgr.LoadAchievementCriteriaData();
1323 achievementmgr.LoadRewards();
1324 achievementmgr.LoadRewardLocales();
1325 achievementmgr.LoadCompletedAchievements();
1326 sLog.outString( ">>> Achievements loaded" );
1327 sLog.outString();
1329 ///- Load dynamic data tables from the database
1330 sLog.outString( "Loading Auctions..." );
1331 sLog.outString();
1332 auctionmgr.LoadAuctionItems();
1333 auctionmgr.LoadAuctions();
1334 sLog.outString( ">>> Auctions loaded" );
1335 sLog.outString();
1337 sLog.outString( "Loading Guilds..." );
1338 objmgr.LoadGuilds();
1340 sLog.outString( "Loading ArenaTeams..." );
1341 objmgr.LoadArenaTeams();
1343 sLog.outString( "Loading Groups..." );
1344 objmgr.LoadGroups();
1346 sLog.outString( "Loading ReservedNames..." );
1347 objmgr.LoadReservedPlayersNames();
1349 sLog.outString( "Loading GameObjects for quests..." );
1350 objmgr.LoadGameObjectForQuests();
1352 sLog.outString( "Loading BattleMasters..." );
1353 sBattleGroundMgr.LoadBattleMastersEntry();
1355 sLog.outString( "Loading GameTeleports..." );
1356 objmgr.LoadGameTele();
1358 sLog.outString( "Loading Npc Text Id..." );
1359 objmgr.LoadNpcTextId(); // must be after load Creature and NpcText
1361 sLog.outString( "Loading Npc Options..." );
1362 objmgr.LoadNpcOptions();
1364 sLog.outString( "Loading Vendors..." );
1365 objmgr.LoadVendors(); // must be after load CreatureTemplate and ItemTemplate
1367 sLog.outString( "Loading Trainers..." );
1368 objmgr.LoadTrainerSpell(); // must be after load CreatureTemplate
1370 sLog.outString( "Loading Waypoints..." );
1371 sLog.outString();
1372 WaypointMgr.Load();
1374 sLog.outString( "Loading GM tickets...");
1375 ticketmgr.LoadGMTickets();
1377 ///- Handle outdated emails (delete/return)
1378 sLog.outString( "Returning old mails..." );
1379 objmgr.ReturnOrDeleteOldMails(false);
1381 ///- Load and initialize scripts
1382 sLog.outString( "Loading Scripts..." );
1383 sLog.outString();
1384 objmgr.LoadQuestStartScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1385 objmgr.LoadQuestEndScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1386 objmgr.LoadSpellScripts(); // must be after load Creature/Gameobject(Template/Data)
1387 objmgr.LoadGameObjectScripts(); // must be after load Creature/Gameobject(Template/Data)
1388 objmgr.LoadEventScripts(); // must be after load Creature/Gameobject(Template/Data)
1389 sLog.outString( ">>> Scripts loaded" );
1390 sLog.outString();
1392 sLog.outString( "Loading Scripts text locales..." ); // must be after Load*Scripts calls
1393 objmgr.LoadDbScriptStrings();
1395 sLog.outString( "Loading CreatureEventAI Texts...");
1396 CreatureEAI_Mgr.LoadCreatureEventAI_Texts();
1398 sLog.outString( "Loading CreatureEventAI Summons...");
1399 CreatureEAI_Mgr.LoadCreatureEventAI_Summons();
1401 sLog.outString( "Loading CreatureEventAI Scripts...");
1402 CreatureEAI_Mgr.LoadCreatureEventAI_Scripts();
1404 sLog.outString( "Initializing Scripts..." );
1405 if(!LoadScriptingModule())
1406 exit(1);
1408 ///- Initialize game time and timers
1409 sLog.outString( "DEBUG:: Initialize game time and timers" );
1410 m_gameTime = time(NULL);
1411 m_startTime=m_gameTime;
1413 tm local;
1414 time_t curr;
1415 time(&curr);
1416 local=*(localtime(&curr)); // dereference and assign
1417 char isoDate[128];
1418 sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1419 local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1421 loginDatabase.PExecute("INSERT INTO uptime (realmid, starttime, startstring, uptime) VALUES('%u', " UI64FMTD ", '%s', 0)",
1422 realmID, uint64(m_startTime), isoDate);
1424 m_timers[WUPDATE_OBJECTS].SetInterval(0);
1425 m_timers[WUPDATE_SESSIONS].SetInterval(0);
1426 m_timers[WUPDATE_WEATHERS].SetInterval(1*IN_MILISECONDS);
1427 m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*IN_MILISECONDS);
1428 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*IN_MILISECONDS);
1429 //Update "uptime" table based on configuration entry in minutes.
1430 m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*IN_MILISECONDS);
1431 //erase corpses every 20 minutes
1433 //to set mailtimer to return mails every day between 4 and 5 am
1434 //mailtimer is increased when updating auctions
1435 //one second is 1000 -(tested on win system)
1436 mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * IN_MILISECONDS) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1437 //1440
1438 mail_timer_expires = ( (DAY * IN_MILISECONDS) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1439 sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1441 ///- Initilize static helper structures
1442 AIRegistry::Initialize();
1443 WaypointMovementGenerator<Creature>::Initialize();
1444 Player::InitVisibleBits();
1446 ///- Initialize MapManager
1447 sLog.outString( "Starting Map System" );
1448 MapManager::Instance().Initialize();
1450 ///- Initialize Battlegrounds
1451 sLog.outString( "Starting BattleGround System" );
1452 sBattleGroundMgr.CreateInitialBattleGrounds();
1453 sBattleGroundMgr.InitAutomaticArenaPointDistribution();
1455 //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1456 sLog.outString( "Loading Transports..." );
1457 MapManager::Instance().LoadTransports();
1459 sLog.outString("Deleting expired bans..." );
1460 loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1462 sLog.outString("Calculate next daily quest reset time..." );
1463 InitDailyQuestResetTime();
1465 sLog.outString("Starting objects Pooling system..." );
1466 poolhandler.Initialize();
1468 sLog.outString("Starting Game Event system..." );
1469 uint32 nextGameEvent = gameeventmgr.Initialize();
1470 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent); //depend on next event
1472 sLog.outString( "WORLD: World initialized" );
1475 void World::DetectDBCLang()
1477 uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1479 if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1481 sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1482 m_lang_confid = LOCALE_enUS;
1485 ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1487 std::string availableLocalsStr;
1489 int default_locale = MAX_LOCALE;
1490 for (int i = MAX_LOCALE-1; i >= 0; --i)
1492 if ( strlen(race->name[i]) > 0) // check by race names
1494 default_locale = i;
1495 m_availableDbcLocaleMask |= (1 << i);
1496 availableLocalsStr += localeNames[i];
1497 availableLocalsStr += " ";
1501 if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1502 (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1504 default_locale = m_lang_confid;
1507 if(default_locale >= MAX_LOCALE)
1509 sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1510 exit(1);
1513 m_defaultDbcLocale = LocaleConstant(default_locale);
1515 sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1516 sLog.outString();
1519 /// Update the World !
1520 void World::Update(uint32 diff)
1522 ///- Update the different timers
1523 for(int i = 0; i < WUPDATE_COUNT; ++i)
1524 if(m_timers[i].GetCurrent()>=0)
1525 m_timers[i].Update(diff);
1526 else m_timers[i].SetCurrent(0);
1528 ///- Update the game time and check for shutdown time
1529 _UpdateGameTime();
1531 /// Handle daily quests reset time
1532 if(m_gameTime > m_NextDailyQuestReset)
1534 ResetDailyQuests();
1535 m_NextDailyQuestReset += DAY;
1538 /// <ul><li> Handle auctions when the timer has passed
1539 if (m_timers[WUPDATE_AUCTIONS].Passed())
1541 m_timers[WUPDATE_AUCTIONS].Reset();
1543 ///- Update mails (return old mails with item, or delete them)
1544 //(tested... works on win)
1545 if (++mail_timer > mail_timer_expires)
1547 mail_timer = 0;
1548 objmgr.ReturnOrDeleteOldMails(true);
1551 ///- Handle expired auctions
1552 auctionmgr.Update();
1555 /// <li> Handle session updates when the timer has passed
1556 if (m_timers[WUPDATE_SESSIONS].Passed())
1558 m_timers[WUPDATE_SESSIONS].Reset();
1560 UpdateSessions(diff);
1563 /// <li> Handle weather updates when the timer has passed
1564 if (m_timers[WUPDATE_WEATHERS].Passed())
1566 m_timers[WUPDATE_WEATHERS].Reset();
1568 ///- Send an update signal to Weather objects
1569 WeatherMap::iterator itr, next;
1570 for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1572 next = itr;
1573 ++next;
1575 ///- and remove Weather objects for zones with no player
1576 //As interval > WorldTick
1577 if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1579 delete itr->second;
1580 m_weathers.erase(itr);
1584 /// <li> Update uptime table
1585 if (m_timers[WUPDATE_UPTIME].Passed())
1587 uint32 tmpDiff = (m_gameTime - m_startTime);
1588 uint32 maxClientsNum = GetMaxActiveSessionCount();
1590 m_timers[WUPDATE_UPTIME].Reset();
1591 loginDatabase.PExecute("UPDATE uptime SET uptime = %u, maxplayers = %u WHERE realmid = %u AND starttime = " UI64FMTD, tmpDiff, maxClientsNum, realmID, uint64(m_startTime));
1594 /// <li> Handle all other objects
1595 if (m_timers[WUPDATE_OBJECTS].Passed())
1597 m_timers[WUPDATE_OBJECTS].Reset();
1598 ///- Update objects when the timer has passed (maps, transport, creatures,...)
1599 MapManager::Instance().Update(diff); // As interval = 0
1601 sBattleGroundMgr.Update(diff);
1604 // execute callbacks from sql queries that were queued recently
1605 UpdateResultQueue();
1607 ///- Erase corpses once every 20 minutes
1608 if (m_timers[WUPDATE_CORPSES].Passed())
1610 m_timers[WUPDATE_CORPSES].Reset();
1612 CorpsesErase();
1615 ///- Process Game events when necessary
1616 if (m_timers[WUPDATE_EVENTS].Passed())
1618 m_timers[WUPDATE_EVENTS].Reset(); // to give time for Update() to be processed
1619 uint32 nextGameEvent = gameeventmgr.Update();
1620 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1621 m_timers[WUPDATE_EVENTS].Reset();
1624 /// </ul>
1625 ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1626 MapManager::Instance().DoDelayedMovesAndRemoves();
1628 // update the instance reset times
1629 sInstanceSaveManager.Update();
1631 // And last, but not least handle the issued cli commands
1632 ProcessCliCommands();
1635 /// Send a packet to all players (except self if mentioned)
1636 void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
1638 SessionMap::const_iterator itr;
1639 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
1641 if (itr->second &&
1642 itr->second->GetPlayer() &&
1643 itr->second->GetPlayer()->IsInWorld() &&
1644 itr->second != self &&
1645 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
1647 itr->second->SendPacket(packet);
1652 namespace MaNGOS
1654 class WorldWorldTextBuilder
1656 public:
1657 typedef std::vector<WorldPacket*> WorldPacketList;
1658 explicit WorldWorldTextBuilder(int32 textId, va_list* args = NULL) : i_textId(textId), i_args(args) {}
1659 void operator()(WorldPacketList& data_list, int32 loc_idx)
1661 char const* text = objmgr.GetMangosString(i_textId,loc_idx);
1663 if(i_args)
1665 // we need copy va_list before use or original va_list will corrupted
1666 va_list ap;
1667 va_copy(ap,*i_args);
1669 char str [2048];
1670 vsnprintf(str,2048,text, ap );
1671 va_end(ap);
1673 do_helper(data_list,&str[0]);
1675 else
1676 do_helper(data_list,(char*)text);
1678 private:
1679 char* lineFromMessage(char*& pos) { char* start = strtok(pos,"\n"); pos = NULL; return start; }
1680 void do_helper(WorldPacketList& data_list, char* text)
1682 char* pos = text;
1684 while(char* line = lineFromMessage(pos))
1686 WorldPacket* data = new WorldPacket();
1688 uint32 lineLength = (line ? strlen(line) : 0) + 1;
1690 data->Initialize(SMSG_MESSAGECHAT, 100); // guess size
1691 *data << uint8(CHAT_MSG_SYSTEM);
1692 *data << uint32(LANG_UNIVERSAL);
1693 *data << uint64(0);
1694 *data << uint32(0); // can be chat msg group or something
1695 *data << uint64(0);
1696 *data << uint32(lineLength);
1697 *data << line;
1698 *data << uint8(0);
1700 data_list.push_back(data);
1704 int32 i_textId;
1705 va_list* i_args;
1707 } // namespace MaNGOS
1709 /// Send a System Message to all players (except self if mentioned)
1710 void World::SendWorldText(int32 string_id, ...)
1712 va_list ap;
1713 va_start(ap, string_id);
1715 MaNGOS::WorldWorldTextBuilder wt_builder(string_id, &ap);
1716 MaNGOS::LocalizedPacketListDo<MaNGOS::WorldWorldTextBuilder> wt_do(wt_builder);
1717 for(SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
1719 if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
1720 continue;
1722 wt_do(itr->second->GetPlayer());
1725 va_end(ap);
1728 /// DEPRICATED, only for debug purpose. Send a System Message to all players (except self if mentioned)
1729 void World::SendGlobalText(const char* text, WorldSession *self)
1731 WorldPacket data;
1733 // need copy to prevent corruption by strtok call in LineFromMessage original string
1734 char* buf = strdup(text);
1735 char* pos = buf;
1737 while(char* line = ChatHandler::LineFromMessage(pos))
1739 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
1740 SendGlobalMessage(&data, self);
1743 free(buf);
1746 /// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
1747 void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
1749 SessionMap::const_iterator itr;
1750 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
1752 if (itr->second &&
1753 itr->second->GetPlayer() &&
1754 itr->second->GetPlayer()->IsInWorld() &&
1755 itr->second->GetPlayer()->GetZoneId() == zone &&
1756 itr->second != self &&
1757 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
1759 itr->second->SendPacket(packet);
1764 /// Send a System Message to all players in the zone (except self if mentioned)
1765 void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
1767 WorldPacket data;
1768 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
1769 SendZoneMessage(zone, &data, self,team);
1772 /// Kick (and save) all players
1773 void World::KickAll()
1775 m_QueuedPlayer.clear(); // prevent send queue update packet and login queued sessions
1777 // session not removed at kick and will removed in next update tick
1778 for (SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
1779 itr->second->KickPlayer();
1782 /// Kick (and save) all players with security level less `sec`
1783 void World::KickAllLess(AccountTypes sec)
1785 // session not removed at kick and will removed in next update tick
1786 for (SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
1787 if(itr->second->GetSecurity() < sec)
1788 itr->second->KickPlayer();
1791 /// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
1792 BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, std::string duration, std::string reason, std::string author)
1794 loginDatabase.escape_string(nameOrIP);
1795 loginDatabase.escape_string(reason);
1796 std::string safe_author=author;
1797 loginDatabase.escape_string(safe_author);
1799 uint32 duration_secs = TimeStringToSecs(duration);
1800 QueryResult *resultAccounts = NULL; //used for kicking
1802 ///- Update the database with ban information
1803 switch(mode)
1805 case BAN_IP:
1806 //No SQL injection as strings are escaped
1807 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
1808 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());
1809 break;
1810 case BAN_ACCOUNT:
1811 //No SQL injection as string is escaped
1812 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
1813 break;
1814 case BAN_CHARACTER:
1815 //No SQL injection as string is escaped
1816 resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
1817 break;
1818 default:
1819 return BAN_SYNTAX_ERROR;
1822 if(!resultAccounts)
1824 if(mode==BAN_IP)
1825 return BAN_SUCCESS; // ip correctly banned but nobody affected (yet)
1826 else
1827 return BAN_NOTFOUND; // Nobody to ban
1830 ///- Disconnect all affected players (for IP it can be several)
1833 Field* fieldsAccount = resultAccounts->Fetch();
1834 uint32 account = fieldsAccount->GetUInt32();
1836 if(mode!=BAN_IP)
1838 //No SQL injection as strings are escaped
1839 loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
1840 account,duration_secs,safe_author.c_str(),reason.c_str());
1843 if (WorldSession* sess = FindSession(account))
1844 if(std::string(sess->GetPlayerName()) != author)
1845 sess->KickPlayer();
1847 while( resultAccounts->NextRow() );
1849 delete resultAccounts;
1850 return BAN_SUCCESS;
1853 /// Remove a ban from an account or IP address
1854 bool World::RemoveBanAccount(BanMode mode, std::string nameOrIP)
1856 if (mode == BAN_IP)
1858 loginDatabase.escape_string(nameOrIP);
1859 loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
1861 else
1863 uint32 account = 0;
1864 if (mode == BAN_ACCOUNT)
1865 account = accmgr.GetId (nameOrIP);
1866 else if (mode == BAN_CHARACTER)
1867 account = objmgr.GetPlayerAccountIdByPlayerName (nameOrIP);
1869 if (!account)
1870 return false;
1872 //NO SQL injection as account is uint32
1873 loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
1875 return true;
1878 /// Update the game time
1879 void World::_UpdateGameTime()
1881 ///- update the time
1882 time_t thisTime = time(NULL);
1883 uint32 elapsed = uint32(thisTime - m_gameTime);
1884 m_gameTime = thisTime;
1886 ///- if there is a shutdown timer
1887 if(!m_stopEvent && m_ShutdownTimer > 0 && elapsed > 0)
1889 ///- ... and it is overdue, stop the world (set m_stopEvent)
1890 if( m_ShutdownTimer <= elapsed )
1892 if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
1893 m_stopEvent = true; // exist code already set
1894 else
1895 m_ShutdownTimer = 1; // minimum timer value to wait idle state
1897 ///- ... else decrease it and if necessary display a shutdown countdown to the users
1898 else
1900 m_ShutdownTimer -= elapsed;
1902 ShutdownMsg();
1907 /// Shutdown the server
1908 void World::ShutdownServ(uint32 time, uint32 options, uint8 exitcode)
1910 // ignore if server shutdown at next tick
1911 if(m_stopEvent)
1912 return;
1914 m_ShutdownMask = options;
1915 m_ExitCode = exitcode;
1917 ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
1918 if(time==0)
1920 if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
1921 m_stopEvent = true; // exist code already set
1922 else
1923 m_ShutdownTimer = 1; //So that the session count is re-evaluated at next world tick
1925 ///- Else set the shutdown timer and warn users
1926 else
1928 m_ShutdownTimer = time;
1929 ShutdownMsg(true);
1933 /// Display a shutdown message to the user(s)
1934 void World::ShutdownMsg(bool show, Player* player)
1936 // not show messages for idle shutdown mode
1937 if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
1938 return;
1940 ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
1941 if ( show ||
1942 (m_ShutdownTimer < 10) ||
1943 // < 30 sec; every 5 sec
1944 (m_ShutdownTimer<30 && (m_ShutdownTimer % 5 )==0) ||
1945 // < 5 min ; every 1 min
1946 (m_ShutdownTimer<5*MINUTE && (m_ShutdownTimer % MINUTE )==0) ||
1947 // < 30 min ; every 5 min
1948 (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
1949 // < 12 h ; every 1 h
1950 (m_ShutdownTimer<12*HOUR && (m_ShutdownTimer % HOUR )==0) ||
1951 // > 12 h ; every 12 h
1952 (m_ShutdownTimer>12*HOUR && (m_ShutdownTimer % (12*HOUR) )==0))
1954 std::string str = secsToTimeString(m_ShutdownTimer);
1956 ServerMessageType msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
1958 SendServerMessage(msgid,str.c_str(),player);
1959 DEBUG_LOG("Server is %s in %s",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"),str.c_str());
1963 /// Cancel a planned server shutdown
1964 void World::ShutdownCancel()
1966 // nothing cancel or too later
1967 if(!m_ShutdownTimer || m_stopEvent)
1968 return;
1970 ServerMessageType msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
1972 m_ShutdownMask = 0;
1973 m_ShutdownTimer = 0;
1974 m_ExitCode = SHUTDOWN_EXIT_CODE; // to default value
1975 SendServerMessage(msgid);
1977 DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
1980 /// Send a server message to the user(s)
1981 void World::SendServerMessage(ServerMessageType type, const char *text, Player* player)
1983 WorldPacket data(SMSG_SERVER_MESSAGE, 50); // guess size
1984 data << uint32(type);
1985 if(type <= SERVER_MSG_STRING)
1986 data << text;
1988 if(player)
1989 player->GetSession()->SendPacket(&data);
1990 else
1991 SendGlobalMessage( &data );
1994 void World::UpdateSessions( uint32 diff )
1996 ///- Add new sessions
1997 WorldSession* sess;
1998 while(addSessQueue.next(sess))
1999 AddSession_ (sess);
2001 ///- Then send an update signal to remaining ones
2002 for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2004 next = itr;
2005 ++next;
2007 if(!itr->second)
2008 continue;
2010 ///- and remove not active sessions from the list
2011 if(!itr->second->Update(diff)) // As interval = 0
2013 RemoveQueuedPlayer (itr->second);
2014 delete itr->second;
2015 m_sessions.erase(itr);
2020 // This handles the issued and queued CLI commands
2021 void World::ProcessCliCommands()
2023 CliCommandHolder::Print* zprint = NULL;
2025 CliCommandHolder* command;
2026 while (cliCmdQueue.next(command))
2028 sLog.outDebug("CLI command under processing...");
2029 zprint = command->m_print;
2030 CliHandler(zprint).ParseCommands(command->m_command);
2031 delete command;
2034 // print the console message here so it looks right
2035 if (zprint)
2036 zprint("mangos>");
2039 void World::InitResultQueue()
2041 m_resultQueue = new SqlResultQueue;
2042 CharacterDatabase.SetResultQueue(m_resultQueue);
2045 void World::UpdateResultQueue()
2047 m_resultQueue->Update();
2050 void World::UpdateRealmCharCount(uint32 accountId)
2052 CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2053 "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2056 void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2058 if (resultCharCount)
2060 Field *fields = resultCharCount->Fetch();
2061 uint32 charCount = fields[0].GetUInt32();
2062 delete resultCharCount;
2063 loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2064 loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2068 void World::InitDailyQuestResetTime()
2070 time_t mostRecentQuestTime;
2072 QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2073 if(result)
2075 Field *fields = result->Fetch();
2077 mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2078 delete result;
2080 else
2081 mostRecentQuestTime = 0;
2083 // client built-in time for reset is 6:00 AM
2084 // FIX ME: client not show day start time
2085 time_t curTime = time(NULL);
2086 tm localTm = *localtime(&curTime);
2087 localTm.tm_hour = 6;
2088 localTm.tm_min = 0;
2089 localTm.tm_sec = 0;
2091 // current day reset time
2092 time_t curDayResetTime = mktime(&localTm);
2094 // last reset time before current moment
2095 time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2097 // need reset (if we have quest time before last reset time (not processed by some reason)
2098 if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2099 m_NextDailyQuestReset = mostRecentQuestTime;
2100 else
2102 // plan next reset time
2103 m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2107 void World::ResetDailyQuests()
2109 sLog.outDetail("Daily quests reset for all characters.");
2110 CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2111 for(SessionMap::const_iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2112 if(itr->second->GetPlayer())
2113 itr->second->GetPlayer()->ResetDailyQuestStatus();
2116 void World::SetPlayerLimit( int32 limit, bool needUpdate )
2118 if(limit < -SEC_ADMINISTRATOR)
2119 limit = -SEC_ADMINISTRATOR;
2121 // lock update need
2122 bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2124 m_playerLimit = limit;
2126 if(db_update_need)
2127 loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2130 void World::UpdateMaxSessionCounters()
2132 m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2133 m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2136 void World::LoadDBVersion()
2138 QueryResult* result = WorldDatabase.Query("SELECT version, creature_ai_version, cache_id FROM db_version LIMIT 1");
2139 if(result)
2141 Field* fields = result->Fetch();
2143 m_DBVersion = fields[0].GetCppString();
2144 m_CreatureEventAIVersion = fields[1].GetCppString();
2146 // will be overwrite by config values if different and non-0
2147 m_configs[CONFIG_CLIENTCACHE_VERSION] = fields[2].GetUInt32();
2148 delete result;
2151 if(m_DBVersion.empty())
2152 m_DBVersion = "Unknown world database.";
2154 if(m_CreatureEventAIVersion.empty())
2155 m_CreatureEventAIVersion = "Unknown creature EventAI.";