[6830] Implement custom exit codes on server shutdown/restart
[getmangos.git] / src / game / World.cpp
blob546cdbbf647b19e05b4c602c4d26c6f18de6115d
1 /*
2 * Copyright (C) 2005-2008 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 "WorldSocket.h"
25 #include "Database/DatabaseEnv.h"
26 #include "Config/ConfigEnv.h"
27 #include "SystemConfig.h"
28 #include "Log.h"
29 #include "Opcodes.h"
30 #include "WorldSession.h"
31 #include "WorldPacket.h"
32 #include "Weather.h"
33 #include "Player.h"
34 #include "SkillExtraItems.h"
35 #include "SkillDiscovery.h"
36 #include "World.h"
37 #include "AccountMgr.h"
38 #include "ObjectMgr.h"
39 #include "SpellMgr.h"
40 #include "Chat.h"
41 #include "Database/DBCStores.h"
42 #include "LootMgr.h"
43 #include "ItemEnchantmentMgr.h"
44 #include "MapManager.h"
45 #include "ScriptCalls.h"
46 #include "CreatureAIRegistry.h"
47 #include "Policies/SingletonImp.h"
48 #include "BattleGroundMgr.h"
49 #include "TemporarySummon.h"
50 #include "WaypointMovementGenerator.h"
51 #include "VMapFactory.h"
52 #include "GlobalEvents.h"
53 #include "GameEvent.h"
54 #include "Database/DatabaseImpl.h"
55 #include "GridNotifiersImpl.h"
56 #include "CellImpl.h"
57 #include "InstanceSaveMgr.h"
58 #include "WaypointManager.h"
59 #include "GMTicketMgr.h"
60 #include "Util.h"
62 INSTANTIATE_SINGLETON_1( World );
64 volatile bool World::m_stopEvent = false;
65 uint8 World::m_ExitCode = SHUTDOWN_EXIT_CODE;
66 volatile uint32 World::m_worldLoopCounter = 0;
68 float World::m_MaxVisibleDistanceForCreature = DEFAULT_VISIBILITY_DISTANCE;
69 float World::m_MaxVisibleDistanceForPlayer = DEFAULT_VISIBILITY_DISTANCE;
70 float World::m_MaxVisibleDistanceForObject = DEFAULT_VISIBILITY_DISTANCE;
71 float World::m_MaxVisibleDistanceInFlight = DEFAULT_VISIBILITY_DISTANCE;
72 float World::m_VisibleUnitGreyDistance = 0;
73 float World::m_VisibleObjectGreyDistance = 0;
75 // ServerMessages.dbc
76 enum ServerMessageType
78 SERVER_MSG_SHUTDOWN_TIME = 1,
79 SERVER_MSG_RESTART_TIME = 2,
80 SERVER_MSG_STRING = 3,
81 SERVER_MSG_SHUTDOWN_CANCELLED = 4,
82 SERVER_MSG_RESTART_CANCELLED = 5
85 struct ScriptAction
87 uint64 sourceGUID;
88 uint64 targetGUID;
89 uint64 ownerGUID; // owner of source if source is item
90 ScriptInfo const* script; // pointer to static script data
93 /// World constructor
94 World::World()
96 m_playerLimit = 0;
97 m_allowMovement = true;
98 m_ShutdownMask = 0;
99 m_ShutdownTimer = 0;
100 m_gameTime=time(NULL);
101 m_startTime=m_gameTime;
102 m_maxActiveSessionCount = 0;
103 m_maxQueuedSessionCount = 0;
104 m_resultQueue = NULL;
105 m_NextDailyQuestReset = 0;
107 m_defaultDbcLocale = LOCALE_enUS;
108 m_availableDbcLocaleMask = 0;
111 /// World destructor
112 World::~World()
114 ///- Empty the kicked session set
115 for (std::set<WorldSession*>::iterator itr = m_kicked_sessions.begin(); itr != m_kicked_sessions.end(); ++itr)
116 delete *itr;
118 m_kicked_sessions.clear();
120 ///- Empty the WeatherMap
121 for (WeatherMap::iterator itr = m_weathers.begin(); itr != m_weathers.end(); ++itr)
122 delete itr->second;
124 m_weathers.clear();
126 VMAP::VMapFactory::clear();
128 if(m_resultQueue) delete m_resultQueue;
130 //TODO free addSessQueue
133 /// Find a player in a specified zone
134 Player* World::FindPlayerInZone(uint32 zone)
136 ///- circle through active sessions and return the first player found in the zone
137 SessionMap::iterator itr;
138 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
140 if(!itr->second)
141 continue;
142 Player *player = itr->second->GetPlayer();
143 if(!player)
144 continue;
145 if( player->IsInWorld() && player->GetZoneId() == zone )
147 // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone.
148 return player;
151 return NULL;
154 /// Find a session by its id
155 WorldSession* World::FindSession(uint32 id) const
157 SessionMap::const_iterator itr = m_sessions.find(id);
159 if(itr != m_sessions.end())
160 return itr->second; // also can return NULL for kicked session
161 else
162 return NULL;
165 /// Remove a given session
166 bool World::RemoveSession(uint32 id)
168 ///- Find the session, kick the user, but we can't delete session at this moment to prevent iterator invalidation
169 SessionMap::iterator itr = m_sessions.find(id);
171 if(itr != m_sessions.end() && itr->second)
173 if (itr->second->PlayerLoading())
174 return false;
175 itr->second->KickPlayer();
178 return true;
181 void World::AddSession(WorldSession* s)
183 addSessQueue.add(s);
186 void
187 World::AddSession_ (WorldSession* s)
189 ASSERT (s);
191 //NOTE - Still there is race condition in WorldSession* being used in the Sockets
193 ///- kick already loaded player with same account (if any) and remove session
194 ///- if player is in loading and want to load again, return
195 if (!RemoveSession (s->GetAccountId ()))
197 s->KickPlayer ();
198 m_kicked_sessions.insert (s);
199 return;
202 // if session already exist, prepare to it deleting at next world update
203 // NOTE - KickPlayer() should be called on "old" in RemoveSession()
205 SessionMap::const_iterator old = m_sessions.find(s->GetAccountId ());
207 if(old != m_sessions.end())
208 m_kicked_sessions.insert (old->second);
211 m_sessions[s->GetAccountId ()] = s;
213 uint32 Sessions = GetActiveAndQueuedSessionCount ();
214 uint32 pLimit = GetPlayerAmountLimit ();
215 uint32 QueueSize = GetQueueSize (); //number of players in the queue
216 //so we don't count the user trying to
217 //login as a session and queue the socket that we are using
218 --Sessions;
220 if (pLimit > 0 && Sessions >= pLimit && s->GetSecurity () == SEC_PLAYER )
222 AddQueuedPlayer (s);
223 UpdateMaxSessionCounters ();
224 sLog.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s->GetAccountId (), ++QueueSize);
225 return;
228 WorldPacket packet(SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
229 packet << uint8 (AUTH_OK);
230 packet << uint32 (0); // unknown random value...
231 packet << uint8 (0);
232 packet << uint32 (0);
233 packet << uint8 (s->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
234 s->SendPacket (&packet);
236 UpdateMaxSessionCounters ();
238 // Updates the population
239 if (pLimit > 0)
241 float popu = GetActiveSessionCount (); //updated number of users on the server
242 popu /= pLimit;
243 popu *= 2;
244 loginDatabase.PExecute ("UPDATE realmlist SET population = '%f' WHERE id = '%d'", popu, realmID);
245 sLog.outDetail ("Server Population (%f).", popu);
249 int32 World::GetQueuePos(WorldSession* sess)
251 uint32 position = 1;
253 for(Queue::iterator iter = m_QueuedPlayer.begin(); iter != m_QueuedPlayer.end(); ++iter, ++position)
254 if((*iter) == sess)
255 return position;
257 return 0;
260 void World::AddQueuedPlayer(WorldSession* sess)
262 m_QueuedPlayer.push_back (sess);
264 // The 1st SMSG_AUTH_RESPONSE needs to contain other info too.
265 WorldPacket packet (SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
266 packet << uint8 (AUTH_WAIT_QUEUE);
267 packet << uint32 (0); // unknown random value...
268 packet << uint8 (0);
269 packet << uint32 (0);
270 packet << uint8 (sess->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
271 packet << uint32(GetQueuePos (sess));
272 sess->SendPacket (&packet);
274 //sess->SendAuthWaitQue (GetQueuePos (sess));
277 void World::RemoveQueuedPlayer(WorldSession* sess)
279 // sessions count including queued to remove (if removed_session set)
280 uint32 sessions = GetActiveSessionCount();
282 uint32 position = 1;
283 Queue::iterator iter = m_QueuedPlayer.begin();
285 // if session not queued then we need decrease sessions count (Remove socked callet before session removing from session list)
286 bool decrease_session = true;
288 // search to remove and count skipped positions
289 for(;iter != m_QueuedPlayer.end(); ++iter, ++position)
291 if(*iter==sess)
293 iter = m_QueuedPlayer.erase(iter);
294 decrease_session = false; // removing queued session
295 break;
299 // iter point to next socked after removed or end()
300 // position store position of removed socket and then new position next socket after removed
302 // decrease for case session queued for removing
303 if(decrease_session && sessions)
304 --sessions;
306 // accept first in queue
307 if( (!m_playerLimit || sessions < m_playerLimit) && !m_QueuedPlayer.empty() )
309 WorldSession * socket = m_QueuedPlayer.front();
310 socket->SendAuthWaitQue(0);
311 m_QueuedPlayer.pop_front();
313 // update iter to point first queued socket or end() if queue is empty now
314 iter = m_QueuedPlayer.begin();
315 position = 1;
318 // update position from iter to end()
319 // iter point to first not updated socket, position store new position
320 for(; iter != m_QueuedPlayer.end(); ++iter, ++position)
321 (*iter)->SendAuthWaitQue(position);
324 /// Find a Weather object by the given zoneid
325 Weather* World::FindWeather(uint32 id) const
327 WeatherMap::const_iterator itr = m_weathers.find(id);
329 if(itr != m_weathers.end())
330 return itr->second;
331 else
332 return 0;
335 /// Remove a Weather object for the given zoneid
336 void World::RemoveWeather(uint32 id)
338 // not called at the moment. Kept for completeness
339 WeatherMap::iterator itr = m_weathers.find(id);
341 if(itr != m_weathers.end())
343 delete itr->second;
344 m_weathers.erase(itr);
348 /// Add a Weather object to the list
349 Weather* World::AddWeather(uint32 zone_id)
351 WeatherZoneChances const* weatherChances = objmgr.GetWeatherChances(zone_id);
353 // zone not have weather, ignore
354 if(!weatherChances)
355 return NULL;
357 Weather* w = new Weather(zone_id,weatherChances);
358 m_weathers[w->GetZone()] = w;
359 w->ReGenerate();
360 w->UpdateWeather();
361 return w;
364 /// Initialize config values
365 void World::LoadConfigSettings(bool reload)
367 if(reload)
369 if(!sConfig.Reload())
371 sLog.outError("World settings reload fail: can't read settings from %s.",sConfig.GetFilename().c_str());
372 return;
376 ///- Read the version of the configuration file and warn the user in case of emptiness or mismatch
377 uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
378 if(!confVersion)
380 sLog.outError("*****************************************************************************");
381 sLog.outError(" WARNING: mangosd.conf does not include a ConfVersion variable.");
382 sLog.outError(" Your configuration file may be out of date!");
383 sLog.outError("*****************************************************************************");
384 clock_t pause = 3000 + clock();
385 while (pause > clock());
387 else
389 if (confVersion < _MANGOSDCONFVERSION)
391 sLog.outError("*****************************************************************************");
392 sLog.outError(" WARNING: Your mangosd.conf version indicates your conf file is out of date!");
393 sLog.outError(" Please check for updates, as your current default values may cause");
394 sLog.outError(" unexpected behavior.");
395 sLog.outError("*****************************************************************************");
396 clock_t pause = 3000 + clock();
397 while (pause > clock());
401 ///- Read the player limit and the Message of the day from the config file
402 SetPlayerLimit( sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT), true );
403 SetMotd( sConfig.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
405 ///- Read all rates from the config file
406 rate_values[RATE_HEALTH] = sConfig.GetFloatDefault("Rate.Health", 1);
407 if(rate_values[RATE_HEALTH] < 0)
409 sLog.outError("Rate.Health (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_HEALTH]);
410 rate_values[RATE_HEALTH] = 1;
412 rate_values[RATE_POWER_MANA] = sConfig.GetFloatDefault("Rate.Mana", 1);
413 if(rate_values[RATE_POWER_MANA] < 0)
415 sLog.outError("Rate.Mana (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_POWER_MANA]);
416 rate_values[RATE_POWER_MANA] = 1;
418 rate_values[RATE_POWER_RAGE_INCOME] = sConfig.GetFloatDefault("Rate.Rage.Income", 1);
419 rate_values[RATE_POWER_RAGE_LOSS] = sConfig.GetFloatDefault("Rate.Rage.Loss", 1);
420 if(rate_values[RATE_POWER_RAGE_LOSS] < 0)
422 sLog.outError("Rate.Rage.Loss (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_POWER_RAGE_LOSS]);
423 rate_values[RATE_POWER_RAGE_LOSS] = 1;
425 rate_values[RATE_POWER_FOCUS] = sConfig.GetFloatDefault("Rate.Focus", 1.0f);
426 rate_values[RATE_LOYALTY] = sConfig.GetFloatDefault("Rate.Loyalty", 1.0f);
427 rate_values[RATE_SKILL_DISCOVERY] = sConfig.GetFloatDefault("Rate.Skill.Discovery", 1.0f);
428 rate_values[RATE_DROP_ITEM_POOR] = sConfig.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f);
429 rate_values[RATE_DROP_ITEM_NORMAL] = sConfig.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f);
430 rate_values[RATE_DROP_ITEM_UNCOMMON] = sConfig.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f);
431 rate_values[RATE_DROP_ITEM_RARE] = sConfig.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f);
432 rate_values[RATE_DROP_ITEM_EPIC] = sConfig.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f);
433 rate_values[RATE_DROP_ITEM_LEGENDARY] = sConfig.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f);
434 rate_values[RATE_DROP_ITEM_ARTIFACT] = sConfig.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f);
435 rate_values[RATE_DROP_ITEM_REFERENCED] = sConfig.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f);
436 rate_values[RATE_DROP_MONEY] = sConfig.GetFloatDefault("Rate.Drop.Money", 1.0f);
437 rate_values[RATE_XP_KILL] = sConfig.GetFloatDefault("Rate.XP.Kill", 1.0f);
438 rate_values[RATE_XP_QUEST] = sConfig.GetFloatDefault("Rate.XP.Quest", 1.0f);
439 rate_values[RATE_XP_EXPLORE] = sConfig.GetFloatDefault("Rate.XP.Explore", 1.0f);
440 rate_values[RATE_XP_PAST_70] = sConfig.GetFloatDefault("Rate.XP.PastLevel70", 1.0f);
441 rate_values[RATE_REPUTATION_GAIN] = sConfig.GetFloatDefault("Rate.Reputation.Gain", 1.0f);
442 rate_values[RATE_CREATURE_NORMAL_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f);
443 rate_values[RATE_CREATURE_ELITE_ELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f);
444 rate_values[RATE_CREATURE_ELITE_RAREELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f);
445 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f);
446 rate_values[RATE_CREATURE_ELITE_RARE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f);
447 rate_values[RATE_CREATURE_NORMAL_HP] = sConfig.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f);
448 rate_values[RATE_CREATURE_ELITE_ELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f);
449 rate_values[RATE_CREATURE_ELITE_RAREELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f);
450 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f);
451 rate_values[RATE_CREATURE_ELITE_RARE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f);
452 rate_values[RATE_CREATURE_NORMAL_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f);
453 rate_values[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f);
454 rate_values[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f);
455 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f);
456 rate_values[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f);
457 rate_values[RATE_CREATURE_AGGRO] = sConfig.GetFloatDefault("Rate.Creature.Aggro", 1.0f);
458 rate_values[RATE_REST_INGAME] = sConfig.GetFloatDefault("Rate.Rest.InGame", 1.0f);
459 rate_values[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY] = sConfig.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f);
460 rate_values[RATE_REST_OFFLINE_IN_WILDERNESS] = sConfig.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f);
461 rate_values[RATE_DAMAGE_FALL] = sConfig.GetFloatDefault("Rate.Damage.Fall", 1.0f);
462 rate_values[RATE_AUCTION_TIME] = sConfig.GetFloatDefault("Rate.Auction.Time", 1.0f);
463 rate_values[RATE_AUCTION_DEPOSIT] = sConfig.GetFloatDefault("Rate.Auction.Deposit", 1.0f);
464 rate_values[RATE_AUCTION_CUT] = sConfig.GetFloatDefault("Rate.Auction.Cut", 1.0f);
465 rate_values[RATE_HONOR] = sConfig.GetFloatDefault("Rate.Honor",1.0f);
466 rate_values[RATE_MINING_AMOUNT] = sConfig.GetFloatDefault("Rate.Mining.Amount",1.0f);
467 rate_values[RATE_MINING_NEXT] = sConfig.GetFloatDefault("Rate.Mining.Next",1.0f);
468 rate_values[RATE_INSTANCE_RESET_TIME] = sConfig.GetFloatDefault("Rate.InstanceResetTime",1.0f);
469 rate_values[RATE_TALENT] = sConfig.GetFloatDefault("Rate.Talent",1.0f);
470 if(rate_values[RATE_TALENT] < 0.0f)
472 sLog.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_TALENT]);
473 rate_values[RATE_TALENT] = 1.0f;
475 rate_values[RATE_CORPSE_DECAY_LOOTED] = sConfig.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f);
477 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = sConfig.GetFloatDefault("TargetPosRecalculateRange",1.5f);
478 if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] < CONTACT_DISTANCE)
480 sLog.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],CONTACT_DISTANCE,CONTACT_DISTANCE);
481 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = CONTACT_DISTANCE;
483 else if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] > ATTACK_DISTANCE)
485 sLog.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",
486 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],ATTACK_DISTANCE,ATTACK_DISTANCE);
487 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = ATTACK_DISTANCE;
490 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = sConfig.GetFloatDefault("DurabilityLossChance.Damage",0.5f);
491 if(rate_values[RATE_DURABILITY_LOSS_DAMAGE] < 0.0f)
493 sLog.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_DAMAGE]);
494 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = 0.0f;
496 rate_values[RATE_DURABILITY_LOSS_ABSORB] = sConfig.GetFloatDefault("DurabilityLossChance.Absorb",0.5f);
497 if(rate_values[RATE_DURABILITY_LOSS_ABSORB] < 0.0f)
499 sLog.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_ABSORB]);
500 rate_values[RATE_DURABILITY_LOSS_ABSORB] = 0.0f;
502 rate_values[RATE_DURABILITY_LOSS_PARRY] = sConfig.GetFloatDefault("DurabilityLossChance.Parry",0.05f);
503 if(rate_values[RATE_DURABILITY_LOSS_PARRY] < 0.0f)
505 sLog.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_PARRY]);
506 rate_values[RATE_DURABILITY_LOSS_PARRY] = 0.0f;
508 rate_values[RATE_DURABILITY_LOSS_BLOCK] = sConfig.GetFloatDefault("DurabilityLossChance.Block",0.05f);
509 if(rate_values[RATE_DURABILITY_LOSS_BLOCK] < 0.0f)
511 sLog.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_BLOCK]);
512 rate_values[RATE_DURABILITY_LOSS_BLOCK] = 0.0f;
515 ///- Read other configuration items from the config file
517 m_configs[CONFIG_COMPRESSION] = sConfig.GetIntDefault("Compression", 1);
518 if(m_configs[CONFIG_COMPRESSION] < 1 || m_configs[CONFIG_COMPRESSION] > 9)
520 sLog.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs[CONFIG_COMPRESSION]);
521 m_configs[CONFIG_COMPRESSION] = 1;
523 m_configs[CONFIG_ADDON_CHANNEL] = sConfig.GetBoolDefault("AddonChannel", true);
524 m_configs[CONFIG_GRID_UNLOAD] = sConfig.GetBoolDefault("GridUnload", true);
525 m_configs[CONFIG_INTERVAL_SAVE] = sConfig.GetIntDefault("PlayerSaveInterval", 900000);
527 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = sConfig.GetIntDefault("GridCleanUpDelay", 300000);
528 if(m_configs[CONFIG_INTERVAL_GRIDCLEAN] < MIN_GRID_DELAY)
530 sLog.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_GRIDCLEAN],MIN_GRID_DELAY);
531 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = MIN_GRID_DELAY;
533 if(reload)
534 MapManager::Instance().SetGridCleanUpDelay(m_configs[CONFIG_INTERVAL_GRIDCLEAN]);
536 m_configs[CONFIG_INTERVAL_MAPUPDATE] = sConfig.GetIntDefault("MapUpdateInterval", 100);
537 if(m_configs[CONFIG_INTERVAL_MAPUPDATE] < MIN_MAP_UPDATE_DELAY)
539 sLog.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_MAPUPDATE],MIN_MAP_UPDATE_DELAY);
540 m_configs[CONFIG_INTERVAL_MAPUPDATE] = MIN_MAP_UPDATE_DELAY;
542 if(reload)
543 MapManager::Instance().SetMapUpdateInterval(m_configs[CONFIG_INTERVAL_MAPUPDATE]);
545 m_configs[CONFIG_INTERVAL_CHANGEWEATHER] = sConfig.GetIntDefault("ChangeWeatherInterval", 600000);
547 if(reload)
549 uint32 val = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
550 if(val!=m_configs[CONFIG_PORT_WORLD])
551 sLog.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_PORT_WORLD]);
553 else
554 m_configs[CONFIG_PORT_WORLD] = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
556 if(reload)
558 uint32 val = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
559 if(val!=m_configs[CONFIG_SOCKET_SELECTTIME])
560 sLog.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[DEFAULT_SOCKET_SELECT_TIME]);
562 else
563 m_configs[CONFIG_SOCKET_SELECTTIME] = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
565 m_configs[CONFIG_GROUP_XP_DISTANCE] = sConfig.GetIntDefault("MaxGroupXPDistance", 74);
566 /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
567 m_configs[CONFIG_SIGHT_MONSTER] = sConfig.GetIntDefault("MonsterSight", 50);
568 m_configs[CONFIG_SIGHT_GUARDER] = sConfig.GetIntDefault("GuarderSight", 50);
570 if(reload)
572 uint32 val = sConfig.GetIntDefault("GameType", 0);
573 if(val!=m_configs[CONFIG_GAME_TYPE])
574 sLog.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_GAME_TYPE]);
576 else
577 m_configs[CONFIG_GAME_TYPE] = sConfig.GetIntDefault("GameType", 0);
579 if(reload)
581 uint32 val = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
582 if(val!=m_configs[CONFIG_REALM_ZONE])
583 sLog.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_REALM_ZONE]);
585 else
586 m_configs[CONFIG_REALM_ZONE] = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
588 m_configs[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS] = sConfig.GetBoolDefault("AllowTwoSide.Accounts", false);
589 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
590 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
591 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
592 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
593 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
594 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
595 m_configs[CONFIG_ALLOW_TWO_SIDE_WHO_LIST] = sConfig.GetBoolDefault("AllowTwoSide.WhoList", false);
596 m_configs[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND] = sConfig.GetBoolDefault("AllowTwoSide.AddFriend", false);
597 m_configs[CONFIG_STRICT_PLAYER_NAMES] = sConfig.GetIntDefault("StrictPlayerNames", 0);
598 m_configs[CONFIG_STRICT_CHARTER_NAMES] = sConfig.GetIntDefault("StrictCharterNames", 0);
599 m_configs[CONFIG_STRICT_PET_NAMES] = sConfig.GetIntDefault("StrictPetNames", 0);
601 m_configs[CONFIG_CHARACTERS_CREATING_DISABLED] = sConfig.GetIntDefault("CharactersCreatingDisabled", 0);
603 m_configs[CONFIG_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("CharactersPerRealm", 10);
604 if(m_configs[CONFIG_CHARACTERS_PER_REALM] < 1 || m_configs[CONFIG_CHARACTERS_PER_REALM] > 10)
606 sLog.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs[CONFIG_CHARACTERS_PER_REALM]);
607 m_configs[CONFIG_CHARACTERS_PER_REALM] = 10;
610 // must be after CONFIG_CHARACTERS_PER_REALM
611 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = sConfig.GetIntDefault("CharactersPerAccount", 50);
612 if(m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] < m_configs[CONFIG_CHARACTERS_PER_REALM])
614 sLog.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs[CONFIG_CHARACTERS_PER_ACCOUNT],m_configs[CONFIG_CHARACTERS_PER_REALM]);
615 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = m_configs[CONFIG_CHARACTERS_PER_REALM];
618 m_configs[CONFIG_SKIP_CINEMATICS] = sConfig.GetIntDefault("SkipCinematics", 0);
619 if(m_configs[CONFIG_SKIP_CINEMATICS] < 0 || m_configs[CONFIG_SKIP_CINEMATICS] > 2)
621 sLog.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs[CONFIG_SKIP_CINEMATICS]);
622 m_configs[CONFIG_SKIP_CINEMATICS] = 0;
625 if(reload)
627 uint32 val = sConfig.GetIntDefault("MaxPlayerLevel", 60);
628 if(val!=m_configs[CONFIG_MAX_PLAYER_LEVEL])
629 sLog.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
631 else
632 m_configs[CONFIG_MAX_PLAYER_LEVEL] = sConfig.GetIntDefault("MaxPlayerLevel", 60);
633 if(m_configs[CONFIG_MAX_PLAYER_LEVEL] > 255)
635 sLog.outError("MaxPlayerLevel (%i) must be in range 1..255. Set to 255.",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
636 m_configs[CONFIG_MAX_PLAYER_LEVEL] = 255;
639 m_configs[CONFIG_START_PLAYER_LEVEL] = sConfig.GetIntDefault("StartPlayerLevel", 1);
640 if(m_configs[CONFIG_START_PLAYER_LEVEL] < 1)
642 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]);
643 m_configs[CONFIG_START_PLAYER_LEVEL] = 1;
645 else if(m_configs[CONFIG_START_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
647 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]);
648 m_configs[CONFIG_START_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
650 m_configs[CONFIG_MAX_HONOR_POINTS] = sConfig.GetIntDefault("MaxHonorPoints", 75000);
651 m_configs[CONFIG_MAX_ARENA_POINTS] = sConfig.GetIntDefault("MaxArenaPoints", 5000);
653 m_configs[CONFIG_INSTANCE_IGNORE_LEVEL] = sConfig.GetBoolDefault("Instance.IgnoreLevel", false);
654 m_configs[CONFIG_INSTANCE_IGNORE_RAID] = sConfig.GetBoolDefault("Instance.IgnoreRaid", false);
656 m_configs[CONFIG_BATTLEGROUND_CAST_DESERTER] = sConfig.GetBoolDefault("Battleground.CastDeserter", true);
657 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.Enable", true);
658 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false);
660 m_configs[CONFIG_CAST_UNSTUCK] = sConfig.GetBoolDefault("CastUnstuck", true);
661 m_configs[CONFIG_INSTANCE_RESET_TIME_HOUR] = sConfig.GetIntDefault("Instance.ResetTimeHour", 4);
662 m_configs[CONFIG_INSTANCE_UNLOAD_DELAY] = sConfig.GetIntDefault("Instance.UnloadDelay", 1800000);
664 m_configs[CONFIG_MAX_PRIMARY_TRADE_SKILL] = sConfig.GetIntDefault("MaxPrimaryTradeSkill", 2);
665 m_configs[CONFIG_MIN_PETITION_SIGNS] = sConfig.GetIntDefault("MinPetitionSigns", 9);
666 if(m_configs[CONFIG_MIN_PETITION_SIGNS] > 9)
668 sLog.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.",m_configs[CONFIG_MIN_PETITION_SIGNS]);
669 m_configs[CONFIG_MIN_PETITION_SIGNS] = 9;
672 m_configs[CONFIG_GM_LOGIN_STATE] = sConfig.GetIntDefault("GM.LoginState",2);
673 m_configs[CONFIG_GM_ACCEPT_TICKETS] = sConfig.GetIntDefault("GM.AcceptTickets",2);
674 m_configs[CONFIG_GM_CHAT] = sConfig.GetIntDefault("GM.Chat",2);
675 m_configs[CONFIG_GM_WISPERING_TO] = sConfig.GetIntDefault("GM.WhisperingTo",2);
677 m_configs[CONFIG_GM_IN_GM_LIST] = sConfig.GetBoolDefault("GM.InGMList",false);
678 m_configs[CONFIG_GM_IN_WHO_LIST] = sConfig.GetBoolDefault("GM.InWhoList",false);
679 m_configs[CONFIG_GM_LOG_TRADE] = sConfig.GetBoolDefault("GM.LogTrade", false);
681 m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
683 m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
685 m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
686 if(m_configs[CONFIG_UPTIME_UPDATE]<=0)
688 sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
689 m_configs[CONFIG_UPTIME_UPDATE] = 10;
691 if(reload)
693 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
694 m_timers[WUPDATE_UPTIME].Reset();
697 m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
698 m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
699 m_configs[CONFIG_SKILL_CHANCE_GREEN] = sConfig.GetIntDefault("SkillChance.Green",25);
700 m_configs[CONFIG_SKILL_CHANCE_GREY] = sConfig.GetIntDefault("SkillChance.Grey",0);
702 m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS] = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
703 m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS] = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
705 m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
707 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = sConfig.GetIntDefault("SkillGain.Crafting", 1);
708 if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
710 sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
711 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
714 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = sConfig.GetIntDefault("SkillGain.Defense", 1);
715 if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
717 sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
718 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
721 m_configs[CONFIG_SKILL_GAIN_GATHERING] = sConfig.GetIntDefault("SkillGain.Gathering", 1);
722 if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
724 sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
725 m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
728 m_configs[CONFIG_SKILL_GAIN_WEAPON] = sConfig.GetIntDefault("SkillGain.Weapon", 1);
729 if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
731 sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
732 m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
735 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
736 if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
738 sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
739 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
742 m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
743 m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
745 if(reload)
747 uint32 val = sConfig.GetIntDefault("Expansion",1);
748 if(val!=m_configs[CONFIG_EXPANSION])
749 sLog.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
751 else
752 m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",1);
754 m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
755 m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
756 m_configs[CONFIG_CHATFLOOD_MUTE_TIME] = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
758 m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
760 m_configs[CONFIG_CREATURE_FAMILY_ASSISTEMCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistenceRadius",10);
762 m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
764 // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level (255)
765 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff",4);
766 if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > 255)
767 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = 255;
768 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff",7);
769 if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > 255)
770 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = 255;
772 m_configs[CONFIG_DETECT_POS_COLLISION] = sConfig.GetBoolDefault("DetectPosCollision", true);
774 m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
775 m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
777 m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
778 m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
780 m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
781 m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
782 m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
783 m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
784 m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
786 m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault("Death.SicknessLevel", 11);
787 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
788 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
790 m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
792 // always use declined names in the russian client
793 m_configs[CONFIG_DECLINED_NAMES_USED] =
794 (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
796 m_configs[CONFIG_LISTEN_RANGE_SAY] = sConfig.GetIntDefault("ListenRange.Say", 25);
797 m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
798 m_configs[CONFIG_LISTEN_RANGE_YELL] = sConfig.GetIntDefault("ListenRange.Yell", 300);
800 m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
801 if(m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
803 sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
804 m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
806 m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
807 if(m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
809 sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
810 m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
813 m_MaxVisibleDistanceForCreature = sConfig.GetFloatDefault("Visibility.Distance.Creature", DEFAULT_VISIBILITY_DISTANCE);
814 if(m_MaxVisibleDistanceForCreature < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
816 sLog.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
817 m_MaxVisibleDistanceForCreature = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
819 else if(m_MaxVisibleDistanceForCreature + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
821 sLog.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
822 m_MaxVisibleDistanceForCreature = MAX_VISIBILITY_DISTANCE-m_VisibleUnitGreyDistance;
824 m_MaxVisibleDistanceForPlayer = sConfig.GetFloatDefault("Visibility.Distance.Player", DEFAULT_VISIBILITY_DISTANCE);
825 if(m_MaxVisibleDistanceForPlayer < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
827 sLog.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
828 m_MaxVisibleDistanceForPlayer = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
830 else if(m_MaxVisibleDistanceForPlayer + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
832 sLog.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
833 m_MaxVisibleDistanceForPlayer = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
835 m_MaxVisibleDistanceForObject = sConfig.GetFloatDefault("Visibility.Distance.Gameobject", DEFAULT_VISIBILITY_DISTANCE);
836 if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
838 sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
839 m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
841 else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
843 sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
844 m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
846 m_MaxVisibleDistanceInFlight = sConfig.GetFloatDefault("Visibility.Distance.InFlight", DEFAULT_VISIBILITY_DISTANCE);
847 if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
849 sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
850 m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
853 ///- Read the "Data" directory from the config file
854 std::string dataPath = sConfig.GetStringDefault("DataDir","./");
855 if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
856 dataPath.append("/");
858 if(reload)
860 if(dataPath!=m_dataPath)
861 sLog.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath.c_str());
863 else
865 m_dataPath = dataPath;
866 sLog.outString("Using DataDir %s",m_dataPath.c_str());
869 bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
870 bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
871 std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
872 std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
873 VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
874 VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
875 VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
876 VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
877 sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
878 sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
879 sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
882 /// Initialize the World
883 void World::SetInitialWorldSettings()
885 ///- Initialize the random number generator
886 srand((unsigned int)time(NULL));
888 ///- Initialize config settings
889 LoadConfigSettings();
891 ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
892 objmgr.SetHighestGuids();
894 ///- Check the existence of the map files for all races' startup areas.
895 if( !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
896 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
897 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
898 ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
899 ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
900 ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
901 ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
902 ||m_configs[CONFIG_EXPANSION] && (
903 !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
905 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());
906 exit(1);
909 ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
910 sLog.outString( "" );
911 sLog.outString( "Loading MaNGOS strings..." );
912 if (!objmgr.LoadMangosStrings())
913 exit(1); // Error message displayed in function already
915 ///- Update the realm entry in the database with the realm type from the config file
916 //No SQL injection as values are treated as integers
918 // not send custom type REALM_FFA_PVP to realm list
919 uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
920 uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
921 loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
923 ///- Remove the bones after a restart
924 CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
926 ///- Load the DBC files
927 sLog.outString("Initialize data stores...");
928 LoadDBCStores(m_dataPath);
929 DetectDBCLang();
931 sLog.outString( "Loading Script Names...");
932 objmgr.LoadScriptNames();
934 sLog.outString( "Loading InstanceTemplate" );
935 objmgr.LoadInstanceTemplate();
937 sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
938 spellmgr.LoadSkillLineAbilityMap();
940 ///- Clean up and pack instances
941 sLog.outString( "Cleaning up instances..." );
942 sInstanceSaveManager.CleanupInstances(); // must be called before `creature_respawn`/`gameobject_respawn` tables
944 sLog.outString( "Packing instances..." );
945 sInstanceSaveManager.PackInstances();
947 sLog.outString( "Loading Localization strings..." );
948 objmgr.LoadCreatureLocales();
949 objmgr.LoadGameObjectLocales();
950 objmgr.LoadItemLocales();
951 objmgr.LoadQuestLocales();
952 objmgr.LoadNpcTextLocales();
953 objmgr.LoadPageTextLocales();
954 objmgr.LoadNpcOptionLocales();
955 objmgr.SetDBCLocaleIndex(GetDefaultDbcLocale()); // Get once for all the locale index of DBC language (console/broadcasts)
957 sLog.outString( "Loading Page Texts..." );
958 objmgr.LoadPageTexts();
960 sLog.outString( "Loading Game Object Templates..." ); // must be after LoadPageTexts
961 objmgr.LoadGameobjectInfo();
963 sLog.outString( "Loading Spell Chain Data..." );
964 spellmgr.LoadSpellChains();
966 sLog.outString( "Loading Spell Elixir types..." );
967 spellmgr.LoadSpellElixirs();
969 sLog.outString( "Loading Spell Learn Skills..." );
970 spellmgr.LoadSpellLearnSkills(); // must be after LoadSpellChains
972 sLog.outString( "Loading Spell Learn Spells..." );
973 spellmgr.LoadSpellLearnSpells();
975 sLog.outString( "Loading Spell Proc Event conditions..." );
976 spellmgr.LoadSpellProcEvents();
978 sLog.outString( "Loading Aggro Spells Definitions...");
979 spellmgr.LoadSpellThreats();
981 sLog.outString( "Loading NPC Texts..." );
982 objmgr.LoadGossipText();
984 sLog.outString( "Loading Item Random Enchantments Table..." );
985 LoadRandomEnchantmentsTable();
987 sLog.outString( "Loading Items..." ); // must be after LoadRandomEnchantmentsTable and LoadPageTexts
988 objmgr.LoadItemPrototypes();
990 sLog.outString( "Loading Item Texts..." );
991 objmgr.LoadItemTexts();
993 sLog.outString( "Loading Creature Model Based Info Data..." );
994 objmgr.LoadCreatureModelInfo();
996 sLog.outString( "Loading Equipment templates...");
997 objmgr.LoadEquipmentTemplates();
999 sLog.outString( "Loading Creature templates..." );
1000 objmgr.LoadCreatureTemplates();
1002 sLog.outString( "Loading SpellsScriptTarget...");
1003 spellmgr.LoadSpellScriptTarget(); // must be after LoadCreatureTemplates and LoadGameobjectInfo
1005 sLog.outString( "Loading Creature Reputation OnKill Data..." );
1006 objmgr.LoadReputationOnKill();
1008 sLog.outString( "Loading Pet Create Spells..." );
1009 objmgr.LoadPetCreateSpells();
1011 sLog.outString( "Loading Creature Data..." );
1012 objmgr.LoadCreatures();
1014 sLog.outString( "Loading Creature Addon Data..." );
1015 objmgr.LoadCreatureAddons(); // must be after LoadCreatureTemplates() and LoadCreatures()
1017 sLog.outString( "Loading Creature Respawn Data..." ); // must be after PackInstances()
1018 objmgr.LoadCreatureRespawnTimes();
1020 sLog.outString( "Loading Gameobject Data..." );
1021 objmgr.LoadGameobjects();
1023 sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1024 objmgr.LoadGameobjectRespawnTimes();
1026 sLog.outString( "Loading Game Event Data...");
1027 gameeventmgr.LoadFromDB();
1029 sLog.outString( "Loading Weather Data..." );
1030 objmgr.LoadWeatherZoneChances();
1032 sLog.outString( "Loading Quests..." );
1033 objmgr.LoadQuests(); // must be loaded after DBCs, creature_template, item_template, gameobject tables
1035 sLog.outString( "Loading Quests Relations..." );
1036 objmgr.LoadQuestRelations(); // must be after quest load
1038 sLog.outString( "Loading AreaTrigger definitions..." );
1039 objmgr.LoadAreaTriggerTeleports(); // must be after item template load
1041 sLog.outString( "Loading Quest Area Triggers..." );
1042 objmgr.LoadQuestAreaTriggers(); // must be after LoadQuests
1044 sLog.outString( "Loading Tavern Area Triggers..." );
1045 objmgr.LoadTavernAreaTriggers();
1047 sLog.outString( "Loading AreaTrigger script names..." );
1048 objmgr.LoadAreaTriggerScripts();
1050 sLog.outString( "Loading Graveyard-zone links...");
1051 objmgr.LoadGraveyardZones();
1053 sLog.outString( "Loading Spell target coordinates..." );
1054 spellmgr.LoadSpellTargetPositions();
1056 sLog.outString( "Loading SpellAffect definitions..." );
1057 spellmgr.LoadSpellAffects();
1059 sLog.outString( "Loading spell pet auras..." );
1060 spellmgr.LoadSpellPetAuras();
1062 sLog.outString( "Loading player Create Info & Level Stats..." );
1063 objmgr.LoadPlayerInfo();
1065 sLog.outString( "Loading Exploration BaseXP Data..." );
1066 objmgr.LoadExplorationBaseXP();
1068 sLog.outString( "Loading Pet Name Parts..." );
1069 objmgr.LoadPetNames();
1071 sLog.outString( "Loading the max pet number..." );
1072 objmgr.LoadPetNumber();
1074 sLog.outString( "Loading pet level stats..." );
1075 objmgr.LoadPetLevelInfo();
1077 sLog.outString( "Loading Player Corpses..." );
1078 objmgr.LoadCorpses();
1080 sLog.outString( "Loading Loot Tables..." );
1081 LoadLootTables();
1083 sLog.outString( "Loading Skill Discovery Table..." );
1084 LoadSkillDiscoveryTable();
1086 sLog.outString( "Loading Skill Extra Item Table..." );
1087 LoadSkillExtraItemTable();
1089 sLog.outString( "Loading Skill Fishing base level requirements..." );
1090 objmgr.LoadFishingBaseSkillLevel();
1092 ///- Load dynamic data tables from the database
1093 sLog.outString( "Loading Auctions..." );
1094 objmgr.LoadAuctionItems();
1095 objmgr.LoadAuctions();
1097 sLog.outString( "Loading Guilds..." );
1098 objmgr.LoadGuilds();
1100 sLog.outString( "Loading ArenaTeams..." );
1101 objmgr.LoadArenaTeams();
1103 sLog.outString( "Loading Groups..." );
1104 objmgr.LoadGroups();
1106 sLog.outString( "Loading ReservedNames..." );
1107 objmgr.LoadReservedPlayersNames();
1109 sLog.outString( "Loading GameObject for quests..." );
1110 objmgr.LoadGameObjectForQuests();
1112 sLog.outString( "Loading BattleMasters..." );
1113 objmgr.LoadBattleMastersEntry();
1115 sLog.outString( "Loading GameTeleports..." );
1116 objmgr.LoadGameTele();
1118 sLog.outString( "Loading Npc Text Id..." );
1119 objmgr.LoadNpcTextId(); // must be after load Creature and NpcText
1121 sLog.outString( "Loading Npc Options..." );
1122 objmgr.LoadNpcOptions();
1124 sLog.outString( "Loading vendors..." );
1125 objmgr.LoadVendors(); // must be after load CreatureTemplate and ItemTemplate
1127 sLog.outString( "Loading trainers..." );
1128 objmgr.LoadTrainerSpell(); // must be after load CreatureTemplate
1130 sLog.outString( "Loading Waypoints..." );
1131 WaypointMgr.Load();
1133 sLog.outString( "Loading GM tickets...");
1134 ticketmgr.LoadGMTickets();
1136 ///- Handle outdated emails (delete/return)
1137 sLog.outString( "Returning old mails..." );
1138 objmgr.ReturnOrDeleteOldMails(false);
1140 ///- Load and initialize scripts
1141 sLog.outString( "Loading Scripts..." );
1142 objmgr.LoadQuestStartScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1143 objmgr.LoadQuestEndScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1144 objmgr.LoadSpellScripts(); // must be after load Creature/Gameobject(Template/Data)
1145 objmgr.LoadGameObjectScripts(); // must be after load Creature/Gameobject(Template/Data)
1146 objmgr.LoadEventScripts(); // must be after load Creature/Gameobject(Template/Data)
1148 sLog.outString( "Loading Scripts text locales..." ); // must be after Load*Scripts calls
1149 objmgr.LoadDbScriptStrings();
1151 sLog.outString( "Initializing Scripts..." );
1152 if(!LoadScriptingModule())
1153 exit(1);
1155 ///- Initialize game time and timers
1156 sLog.outString( "DEBUG:: Initialize game time and timers" );
1157 m_gameTime = time(NULL);
1158 m_startTime=m_gameTime;
1160 tm local;
1161 time_t curr;
1162 time(&curr);
1163 local=*(localtime(&curr)); // dereference and assign
1164 char isoDate[128];
1165 sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1166 local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1168 WorldDatabase.PExecute("INSERT INTO uptime (startstring, starttime, uptime) VALUES('%s', " I64FMTD ", 0)",
1169 isoDate, uint64(m_startTime));
1171 m_timers[WUPDATE_OBJECTS].SetInterval(0);
1172 m_timers[WUPDATE_SESSIONS].SetInterval(0);
1173 m_timers[WUPDATE_WEATHERS].SetInterval(1000);
1174 m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*1000); //set auction update interval to 1 minute
1175 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
1176 //Update "uptime" table based on configuration entry in minutes.
1177 m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*1000); //erase corpses every 20 minutes
1179 //to set mailtimer to return mails every day between 4 and 5 am
1180 //mailtimer is increased when updating auctions
1181 //one second is 1000 -(tested on win system)
1182 mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * 1000) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1183 //1440
1184 mail_timer_expires = ( (DAY * 1000) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1185 sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1187 ///- Initilize static helper structures
1188 AIRegistry::Initialize();
1189 WaypointMovementGenerator<Creature>::Initialize();
1190 Player::InitVisibleBits();
1192 ///- Initialize MapManager
1193 sLog.outString( "Starting Map System" );
1194 MapManager::Instance().Initialize();
1196 ///- Initialize Battlegrounds
1197 sLog.outString( "Starting BattleGround System" );
1198 sBattleGroundMgr.CreateInitialBattleGrounds();
1200 //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1201 sLog.outString( "Loading Transports..." );
1202 MapManager::Instance().LoadTransports();
1204 sLog.outString("Deleting expired bans..." );
1205 loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1207 sLog.outString("Calculate next daily quest reset time..." );
1208 InitDailyQuestResetTime();
1210 sLog.outString("Starting Game Event system..." );
1211 uint32 nextGameEvent = gameeventmgr.Initialize();
1212 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent); //depend on next event
1214 sLog.outString( "WORLD: World initialized" );
1217 void World::DetectDBCLang()
1219 uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1221 if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1223 sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1224 m_lang_confid = LOCALE_enUS;
1227 ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1229 std::string availableLocalsStr;
1231 int default_locale = MAX_LOCALE;
1232 for (int i = MAX_LOCALE-1; i >= 0; --i)
1234 if ( strlen(race->name[i]) > 0) // check by race names
1236 default_locale = i;
1237 m_availableDbcLocaleMask |= (1 << i);
1238 availableLocalsStr += localeNames[i];
1239 availableLocalsStr += " ";
1243 if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1244 (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1246 default_locale = m_lang_confid;
1249 if(default_locale >= MAX_LOCALE)
1251 sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1252 exit(1);
1255 m_defaultDbcLocale = LocaleConstant(default_locale);
1257 sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1260 /// Update the World !
1261 void World::Update(time_t diff)
1263 ///- Update the different timers
1264 for(int i = 0; i < WUPDATE_COUNT; i++)
1265 if(m_timers[i].GetCurrent()>=0)
1266 m_timers[i].Update(diff);
1267 else m_timers[i].SetCurrent(0);
1269 ///- Update the game time and check for shutdown time
1270 _UpdateGameTime();
1272 /// Handle daily quests reset time
1273 if(m_gameTime > m_NextDailyQuestReset)
1275 ResetDailyQuests();
1276 m_NextDailyQuestReset += DAY;
1279 /// <ul><li> Handle auctions when the timer has passed
1280 if (m_timers[WUPDATE_AUCTIONS].Passed())
1282 m_timers[WUPDATE_AUCTIONS].Reset();
1284 ///- Update mails (return old mails with item, or delete them)
1285 //(tested... works on win)
1286 if (++mail_timer > mail_timer_expires)
1288 mail_timer = 0;
1289 objmgr.ReturnOrDeleteOldMails(true);
1292 AuctionHouseObject* AuctionMap;
1293 for (int i = 0; i < 3; i++)
1295 switch (i)
1297 case 0:
1298 AuctionMap = objmgr.GetAuctionsMap( 6 );//horde
1299 break;
1300 case 1:
1301 AuctionMap = objmgr.GetAuctionsMap( 2 );//alliance
1302 break;
1303 case 2:
1304 AuctionMap = objmgr.GetAuctionsMap( 7 );//neutral
1305 break;
1308 ///- Handle expired auctions
1309 AuctionHouseObject::AuctionEntryMap::iterator itr,next;
1310 for (itr = AuctionMap->GetAuctionsBegin(); itr != AuctionMap->GetAuctionsEnd();itr = next)
1312 next = itr;
1313 ++next;
1314 if (m_gameTime > (itr->second->time))
1316 ///- Either cancel the auction if there was no bidder
1317 if (itr->second->bidder == 0)
1319 objmgr.SendAuctionExpiredMail( itr->second );
1321 ///- Or perform the transaction
1322 else
1324 //we should send an "item sold" message if the seller is online
1325 //we send the item to the winner
1326 //we send the money to the seller
1327 objmgr.SendAuctionSuccessfulMail( itr->second );
1328 objmgr.SendAuctionWonMail( itr->second );
1331 ///- In any case clear the auction
1332 //No SQL injection (Id is integer)
1333 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",itr->second->Id);
1334 objmgr.RemoveAItem(itr->second->item_guidlow);
1335 delete itr->second;
1336 AuctionMap->RemoveAuction(itr->first);
1342 /// <li> Handle session updates when the timer has passed
1343 if (m_timers[WUPDATE_SESSIONS].Passed())
1345 m_timers[WUPDATE_SESSIONS].Reset();
1347 UpdateSessions(diff);
1350 /// <li> Handle weather updates when the timer has passed
1351 if (m_timers[WUPDATE_WEATHERS].Passed())
1353 m_timers[WUPDATE_WEATHERS].Reset();
1355 ///- Send an update signal to Weather objects
1356 WeatherMap::iterator itr, next;
1357 for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1359 next = itr;
1360 ++next;
1362 ///- and remove Weather objects for zones with no player
1363 //As interval > WorldTick
1364 if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1366 delete itr->second;
1367 m_weathers.erase(itr);
1371 /// <li> Update uptime table
1372 if (m_timers[WUPDATE_UPTIME].Passed())
1374 uint32 tmpDiff = (m_gameTime - m_startTime);
1375 uint32 maxClientsNum = sWorld.GetMaxActiveSessionCount();
1377 m_timers[WUPDATE_UPTIME].Reset();
1378 WorldDatabase.PExecute("UPDATE uptime SET uptime = %d, maxplayers = %d WHERE starttime = " I64FMTD, tmpDiff, maxClientsNum, uint64(m_startTime));
1381 /// <li> Handle all other objects
1382 if (m_timers[WUPDATE_OBJECTS].Passed())
1384 m_timers[WUPDATE_OBJECTS].Reset();
1385 ///- Update objects when the timer has passed (maps, transport, creatures,...)
1386 MapManager::Instance().Update(diff); // As interval = 0
1388 ///- Process necessary scripts
1389 if (!m_scriptSchedule.empty())
1390 ScriptsProcess();
1392 sBattleGroundMgr.Update(diff);
1395 // execute callbacks from sql queries that were queued recently
1396 UpdateResultQueue();
1398 ///- Erase corpses once every 20 minutes
1399 if (m_timers[WUPDATE_CORPSES].Passed())
1401 m_timers[WUPDATE_CORPSES].Reset();
1403 CorpsesErase();
1406 ///- Process Game events when necessary
1407 if (m_timers[WUPDATE_EVENTS].Passed())
1409 m_timers[WUPDATE_EVENTS].Reset(); // to give time for Update() to be processed
1410 uint32 nextGameEvent = gameeventmgr.Update();
1411 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1412 m_timers[WUPDATE_EVENTS].Reset();
1415 /// </ul>
1416 ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1417 MapManager::Instance().DoDelayedMovesAndRemoves();
1419 // update the instance reset times
1420 sInstanceSaveManager.Update();
1422 // And last, but not least handle the issued cli commands
1423 ProcessCliCommands();
1426 /// Put scripts in the execution queue
1427 void World::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
1429 ///- Find the script map
1430 ScriptMapMap::const_iterator s = scripts.find(id);
1431 if (s == scripts.end())
1432 return;
1434 // prepare static data
1435 uint64 sourceGUID = source->GetGUID();
1436 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1437 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1439 ///- Schedule script execution for all scripts in the script map
1440 ScriptMap const *s2 = &(s->second);
1441 bool immedScript = false;
1442 for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
1444 ScriptAction sa;
1445 sa.sourceGUID = sourceGUID;
1446 sa.targetGUID = targetGUID;
1447 sa.ownerGUID = ownerGUID;
1449 sa.script = &iter->second;
1450 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + iter->first, sa));
1451 if (iter->first == 0)
1452 immedScript = true;
1454 ///- If one of the effects should be immediate, launch the script execution
1455 if (immedScript)
1456 ScriptsProcess();
1459 void World::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
1461 // NOTE: script record _must_ exist until command executed
1463 // prepare static data
1464 uint64 sourceGUID = source->GetGUID();
1465 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1466 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1468 ScriptAction sa;
1469 sa.sourceGUID = sourceGUID;
1470 sa.targetGUID = targetGUID;
1471 sa.ownerGUID = ownerGUID;
1473 sa.script = &script;
1474 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + delay, sa));
1476 ///- If effects should be immediate, launch the script execution
1477 if(delay == 0)
1478 ScriptsProcess();
1481 /// Process queued scripts
1482 void World::ScriptsProcess()
1484 if (m_scriptSchedule.empty())
1485 return;
1487 ///- Process overdue queued scripts
1488 std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
1489 // ok as multimap is a *sorted* associative container
1490 while (!m_scriptSchedule.empty() && (iter->first <= m_gameTime))
1492 ScriptAction const& step = iter->second;
1494 Object* source = NULL;
1496 if(step.sourceGUID)
1498 switch(GUID_HIPART(step.sourceGUID))
1500 case HIGHGUID_ITEM:
1501 // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1503 Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
1504 if(player)
1505 source = player->GetItemByGuid(step.sourceGUID);
1506 break;
1508 case HIGHGUID_UNIT:
1509 source = HashMapHolder<Creature>::Find(step.sourceGUID);
1510 break;
1511 case HIGHGUID_PET:
1512 source = HashMapHolder<Pet>::Find(step.sourceGUID);
1513 break;
1514 case HIGHGUID_PLAYER:
1515 source = HashMapHolder<Player>::Find(step.sourceGUID);
1516 break;
1517 case HIGHGUID_GAMEOBJECT:
1518 source = HashMapHolder<GameObject>::Find(step.sourceGUID);
1519 break;
1520 case HIGHGUID_CORPSE:
1521 source = HashMapHolder<Corpse>::Find(step.sourceGUID);
1522 break;
1523 default:
1524 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
1525 break;
1529 if(source && !source->IsInWorld()) source = NULL;
1531 Object* target = NULL;
1533 if(step.targetGUID)
1535 switch(GUID_HIPART(step.targetGUID))
1537 case HIGHGUID_UNIT:
1538 target = HashMapHolder<Creature>::Find(step.targetGUID);
1539 break;
1540 case HIGHGUID_PET:
1541 target = HashMapHolder<Pet>::Find(step.targetGUID);
1542 break;
1543 case HIGHGUID_PLAYER: // empty GUID case also
1544 target = HashMapHolder<Player>::Find(step.targetGUID);
1545 break;
1546 case HIGHGUID_GAMEOBJECT:
1547 target = HashMapHolder<GameObject>::Find(step.targetGUID);
1548 break;
1549 case HIGHGUID_CORPSE:
1550 target = HashMapHolder<Corpse>::Find(step.targetGUID);
1551 break;
1552 default:
1553 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
1554 break;
1558 if(target && !target->IsInWorld()) target = NULL;
1560 switch (step.script->command)
1562 case SCRIPT_COMMAND_TALK:
1564 if(!source)
1566 sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1567 break;
1570 if(source->GetTypeId()!=TYPEID_UNIT)
1572 sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1573 break;
1576 uint64 unit_target = target ? target->GetGUID() : 0;
1578 //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1579 switch(step.script->datalong)
1581 case 0: // Say
1582 ((Creature *)source)->Say(step.script->dataint, LANG_UNIVERSAL, unit_target);
1583 break;
1584 case 1: // Whisper
1585 if(!unit_target)
1587 sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
1588 break;
1590 ((Creature *)source)->Whisper(step.script->dataint,unit_target);
1591 break;
1592 case 2: // Yell
1593 ((Creature *)source)->Yell(step.script->dataint, LANG_UNIVERSAL, unit_target);
1594 break;
1595 case 3: // Emote text
1596 ((Creature *)source)->TextEmote(step.script->dataint, unit_target);
1597 break;
1598 default:
1599 break; // must be already checked at load
1601 break;
1604 case SCRIPT_COMMAND_EMOTE:
1605 if(!source)
1607 sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1608 break;
1611 if(source->GetTypeId()!=TYPEID_UNIT)
1613 sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1614 break;
1617 ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
1618 break;
1619 case SCRIPT_COMMAND_FIELD_SET:
1620 if(!source)
1622 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1623 break;
1625 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1627 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1628 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1629 break;
1632 source->SetUInt32Value(step.script->datalong, step.script->datalong2);
1633 break;
1634 case SCRIPT_COMMAND_MOVE_TO:
1635 if(!source)
1637 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1638 break;
1641 if(source->GetTypeId()!=TYPEID_UNIT)
1643 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1644 break;
1646 ((Unit *)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, ((Unit *)source)->GetUnitMovementFlags(), step.script->datalong2 );
1647 MapManager::Instance().GetMap(((Unit *)source)->GetMapId(), ((Unit *)source))->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
1648 break;
1649 case SCRIPT_COMMAND_FLAG_SET:
1650 if(!source)
1652 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1653 break;
1655 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1657 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1658 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1659 break;
1662 source->SetFlag(step.script->datalong, step.script->datalong2);
1663 break;
1664 case SCRIPT_COMMAND_FLAG_REMOVE:
1665 if(!source)
1667 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1668 break;
1670 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1672 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1673 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1674 break;
1677 source->RemoveFlag(step.script->datalong, step.script->datalong2);
1678 break;
1680 case SCRIPT_COMMAND_TELEPORT_TO:
1682 // accept player in any one from target/source arg
1683 if (!target && !source)
1685 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1686 break;
1689 // must be only Player
1690 if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
1692 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
1693 break;
1696 Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
1698 pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
1699 break;
1702 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
1704 if(!step.script->datalong) // creature not specified
1706 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1707 break;
1710 if(!source)
1712 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1713 break;
1716 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1718 if(!summoner)
1720 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1721 break;
1724 float x = step.script->x;
1725 float y = step.script->y;
1726 float z = step.script->z;
1727 float o = step.script->o;
1729 Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
1730 if (!pCreature)
1732 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
1733 break;
1736 break;
1739 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
1741 if(!step.script->datalong) // gameobject not specified
1743 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1744 break;
1747 if(!source)
1749 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1750 break;
1753 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1755 if(!summoner)
1757 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1758 break;
1761 GameObject *go = NULL;
1762 int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
1764 CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
1765 Cell cell(p);
1766 cell.data.Part.reserved = ALL_DISTRICT;
1768 MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
1769 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(go,go_check);
1771 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1772 CellLock<GridReadGuard> cell_lock(cell, p);
1773 cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(summoner->GetMapId(), summoner));
1775 if ( !go )
1777 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
1778 break;
1781 if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1782 go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1783 go->GetGoType()==GAMEOBJECT_TYPE_DOOR ||
1784 go->GetGoType()==GAMEOBJECT_TYPE_BUTTON ||
1785 go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
1787 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
1788 break;
1791 if( go->isSpawned() )
1792 break; //gameobject already spawned
1794 go->SetLootState(GO_READY);
1795 go->SetRespawnTime(time_to_despawn); //despawn object in ? seconds
1797 MapManager::Instance().GetMap(go->GetMapId(), go)->Add(go);
1798 break;
1800 case SCRIPT_COMMAND_OPEN_DOOR:
1802 if(!step.script->datalong) // door not specified
1804 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1805 break;
1808 if(!source)
1810 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1811 break;
1814 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
1816 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1817 break;
1820 Unit* caster = (Unit*)source;
1822 GameObject *door = NULL;
1823 int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1825 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1826 Cell cell(p);
1827 cell.data.Part.reserved = ALL_DISTRICT;
1829 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1830 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1832 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1833 CellLock<GridReadGuard> cell_lock(cell, p);
1834 cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1836 if ( !door )
1838 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1839 break;
1841 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1843 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1844 break;
1847 if( !door->GetGoState() )
1848 break; //door already open
1850 door->UseDoorOrButton(time_to_close);
1852 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1853 ((GameObject*)target)->UseDoorOrButton(time_to_close);
1854 break;
1856 case SCRIPT_COMMAND_CLOSE_DOOR:
1858 if(!step.script->datalong) // guid for door not specified
1860 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
1861 break;
1864 if(!source)
1866 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
1867 break;
1870 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
1872 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1873 break;
1876 Unit* caster = (Unit*)source;
1878 GameObject *door = NULL;
1879 int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1881 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1882 Cell cell(p);
1883 cell.data.Part.reserved = ALL_DISTRICT;
1885 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1886 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1888 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1889 CellLock<GridReadGuard> cell_lock(cell, p);
1890 cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1892 if ( !door )
1894 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1895 break;
1897 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1899 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1900 break;
1903 if( door->GetGoState() )
1904 break; //door already closed
1906 door->UseDoorOrButton(time_to_open);
1908 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1909 ((GameObject*)target)->UseDoorOrButton(time_to_open);
1911 break;
1913 case SCRIPT_COMMAND_QUEST_EXPLORED:
1915 if(!source)
1917 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
1918 break;
1921 if(!target)
1923 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
1924 break;
1927 // when script called for item spell casting then target == (unit or GO) and source is player
1928 WorldObject* worldObject;
1929 Player* player;
1931 if(target->GetTypeId()==TYPEID_PLAYER)
1933 if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
1935 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
1936 break;
1939 worldObject = (WorldObject*)source;
1940 player = (Player*)target;
1942 else
1944 if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
1946 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
1947 break;
1950 if(source->GetTypeId()!=TYPEID_PLAYER)
1952 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
1953 break;
1956 worldObject = (WorldObject*)target;
1957 player = (Player*)source;
1960 // quest id and flags checked at script loading
1961 if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
1962 (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
1963 player->AreaExploredOrEventHappens(step.script->datalong);
1964 else
1965 player->FailQuest(step.script->datalong);
1967 break;
1970 case SCRIPT_COMMAND_ACTIVATE_OBJECT:
1972 if(!source)
1974 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
1975 break;
1978 if(!source->isType(TYPEMASK_UNIT))
1980 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
1981 break;
1984 if(!target)
1986 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
1987 break;
1990 if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
1992 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
1993 break;
1996 Unit* caster = (Unit*)source;
1998 GameObject *go = (GameObject*)target;
2000 go->Use(caster);
2001 break;
2004 case SCRIPT_COMMAND_REMOVE_AURA:
2006 Object* cmdTarget = step.script->datalong2 ? source : target;
2008 if(!cmdTarget)
2010 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
2011 break;
2014 if(!cmdTarget->isType(TYPEMASK_UNIT))
2016 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2017 break;
2020 ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
2021 break;
2024 case SCRIPT_COMMAND_CAST_SPELL:
2026 if(!source)
2028 sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
2029 break;
2032 if(!source->isType(TYPEMASK_UNIT))
2034 sLog.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2035 break;
2038 Object* cmdTarget = step.script->datalong2 ? source : target;
2040 if(!cmdTarget)
2042 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 ? "source" : "target");
2043 break;
2046 if(!cmdTarget->isType(TYPEMASK_UNIT))
2048 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2049 break;
2052 Unit* spellTarget = (Unit*)cmdTarget;
2054 //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2055 ((Unit*)source)->CastSpell(spellTarget,step.script->datalong,false);
2057 break;
2060 default:
2061 sLog.outError("Unknown script command %u called.",step.script->command);
2062 break;
2065 m_scriptSchedule.erase(iter);
2067 iter = m_scriptSchedule.begin();
2069 return;
2072 /// Send a packet to all players (except self if mentioned)
2073 void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
2075 SessionMap::iterator itr;
2076 for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2078 if (itr->second &&
2079 itr->second->GetPlayer() &&
2080 itr->second->GetPlayer()->IsInWorld() &&
2081 itr->second != self &&
2082 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2084 itr->second->SendPacket(packet);
2089 /// Send a System Message to all players (except self if mentioned)
2090 void World::SendWorldText(int32 string_id, ...)
2092 std::vector<std::vector<WorldPacket*> > data_cache; // 0 = default, i => i-1 locale index
2094 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2096 if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
2097 continue;
2099 uint32 loc_idx = itr->second->GetSessionDbLocaleIndex();
2100 uint32 cache_idx = loc_idx+1;
2102 std::vector<WorldPacket*>* data_list;
2104 // create if not cached yet
2105 if(data_cache.size() < cache_idx+1 || data_cache[cache_idx].empty())
2107 if(data_cache.size() < cache_idx+1)
2108 data_cache.resize(cache_idx+1);
2110 data_list = &data_cache[cache_idx];
2112 char const* text = objmgr.GetMangosString(string_id,loc_idx);
2114 char buf[1000];
2116 va_list argptr;
2117 va_start( argptr, string_id );
2118 vsnprintf( buf,1000, text, argptr );
2119 va_end( argptr );
2121 char* pos = &buf[0];
2123 while(char* line = ChatHandler::LineFromMessage(pos))
2125 WorldPacket* data = new WorldPacket();
2126 ChatHandler::FillMessageData(data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2127 data_list->push_back(data);
2130 else
2131 data_list = &data_cache[cache_idx];
2133 for(int i = 0; i < data_list->size(); ++i)
2134 itr->second->SendPacket((*data_list)[i]);
2137 // free memory
2138 for(int i = 0; i < data_cache.size(); ++i)
2139 for(int j = 0; j < data_cache[i].size(); ++j)
2140 delete data_cache[i][j];
2143 /// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2144 void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
2146 SessionMap::iterator itr;
2147 for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2149 if (itr->second &&
2150 itr->second->GetPlayer() &&
2151 itr->second->GetPlayer()->IsInWorld() &&
2152 itr->second->GetPlayer()->GetZoneId() == zone &&
2153 itr->second != self &&
2154 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2156 itr->second->SendPacket(packet);
2161 /// Send a System Message to all players in the zone (except self if mentioned)
2162 void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
2164 WorldPacket data;
2165 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
2166 SendZoneMessage(zone, &data, self,team);
2169 /// Kick (and save) all players
2170 void World::KickAll()
2172 // session not removed at kick and will removed in next update tick
2173 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2174 itr->second->KickPlayer();
2177 /// Kick (and save) all players with security level less `sec`
2178 void World::KickAllLess(AccountTypes sec)
2180 // session not removed at kick and will removed in next update tick
2181 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2182 if(itr->second->GetSecurity() < sec)
2183 itr->second->KickPlayer();
2186 /// Kick all queued players
2187 void World::KickAllQueued()
2189 // session not removed at kick and will removed in next update tick
2190 //TODO here
2191 // for (Queue::iterator itr = m_QueuedPlayer.begin(); itr != m_QueuedPlayer.end(); ++itr)
2192 // if(WorldSession* session = (*itr)->GetSession())
2193 // session->KickPlayer();
2195 m_QueuedPlayer.empty();
2198 /// Kick (and save) the designated player
2199 bool World::KickPlayer(std::string playerName)
2201 SessionMap::iterator itr;
2203 // session not removed at kick and will removed in next update tick
2204 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2206 if(!itr->second)
2207 continue;
2208 Player *player = itr->second->GetPlayer();
2209 if(!player)
2210 continue;
2211 if( player->IsInWorld() )
2213 if (playerName == player->GetName())
2215 itr->second->KickPlayer();
2216 return true;
2220 return false;
2223 /// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2224 BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, std::string duration, std::string reason, std::string author)
2226 loginDatabase.escape_string(nameOrIP);
2227 loginDatabase.escape_string(reason);
2228 std::string safe_author=author;
2229 loginDatabase.escape_string(safe_author);
2231 uint32 duration_secs = TimeStringToSecs(duration);
2232 QueryResult *resultAccounts = NULL; //used for kicking
2234 ///- Update the database with ban information
2235 switch(mode)
2237 case BAN_IP:
2238 //No SQL injection as strings are escaped
2239 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
2240 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());
2241 break;
2242 case BAN_ACCOUNT:
2243 //No SQL injection as string is escaped
2244 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2245 break;
2246 case BAN_CHARACTER:
2247 //No SQL injection as string is escaped
2248 resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2249 break;
2250 default:
2251 return BAN_SYNTAX_ERROR;
2254 if(!resultAccounts)
2256 if(mode==BAN_IP)
2257 return BAN_SUCCESS; // ip correctly banned but nobody affected (yet)
2258 else
2259 return BAN_NOTFOUND; // Nobody to ban
2262 ///- Disconnect all affected players (for IP it can be several)
2265 Field* fieldsAccount = resultAccounts->Fetch();
2266 uint32 account = fieldsAccount->GetUInt32();
2268 if(mode!=BAN_IP)
2270 //No SQL injection as strings are escaped
2271 loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2272 account,duration_secs,safe_author.c_str(),reason.c_str());
2275 if (WorldSession* sess = FindSession(account))
2276 if(std::string(sess->GetPlayerName()) != author)
2277 sess->KickPlayer();
2279 while( resultAccounts->NextRow() );
2281 delete resultAccounts;
2282 return BAN_SUCCESS;
2285 /// Remove a ban from an account or IP address
2286 bool World::RemoveBanAccount(BanMode mode, std::string nameOrIP)
2288 if (mode == BAN_IP)
2290 loginDatabase.escape_string(nameOrIP);
2291 loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
2293 else
2295 uint32 account = 0;
2296 if (mode == BAN_ACCOUNT)
2297 account = accmgr.GetId (nameOrIP);
2298 else if (mode == BAN_CHARACTER)
2299 account = objmgr.GetPlayerAccountIdByPlayerName (nameOrIP);
2301 if (!account)
2302 return false;
2304 //NO SQL injection as account is uint32
2305 loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
2307 return true;
2310 /// Update the game time
2311 void World::_UpdateGameTime()
2313 ///- update the time
2314 time_t thisTime = time(NULL);
2315 uint32 elapsed = uint32(thisTime - m_gameTime);
2316 m_gameTime = thisTime;
2318 ///- if there is a shutdown timer
2319 if(!m_stopEvent && m_ShutdownTimer > 0 && elapsed > 0)
2321 ///- ... and it is overdue, stop the world (set m_stopEvent)
2322 if( m_ShutdownTimer <= elapsed )
2324 if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2325 m_stopEvent = true; // exist code already set
2326 else
2327 m_ShutdownTimer = 1; // minimum timer value to wait idle state
2329 ///- ... else decrease it and if necessary display a shutdown countdown to the users
2330 else
2332 m_ShutdownTimer -= elapsed;
2334 ShutdownMsg();
2339 /// Shutdown the server
2340 void World::ShutdownServ(uint32 time, uint32 options, uint8 exitcode)
2342 // ignore if server shutdown at next tick
2343 if(m_stopEvent)
2344 return;
2346 m_ShutdownMask = options;
2347 m_ExitCode = exitcode;
2349 ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2350 if(time==0)
2352 if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2353 m_stopEvent = true; // exist code already set
2354 else
2355 m_ShutdownTimer = 1; //So that the session count is re-evaluated at next world tick
2357 ///- Else set the shutdown timer and warn users
2358 else
2360 m_ShutdownTimer = time;
2361 ShutdownMsg(true);
2365 /// Display a shutdown message to the user(s)
2366 void World::ShutdownMsg(bool show, Player* player)
2368 // not show messages for idle shutdown mode
2369 if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
2370 return;
2372 ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2373 if ( show ||
2374 (m_ShutdownTimer < 10) ||
2375 // < 30 sec; every 5 sec
2376 (m_ShutdownTimer<30 && (m_ShutdownTimer % 5 )==0) ||
2377 // < 5 min ; every 1 min
2378 (m_ShutdownTimer<5*MINUTE && (m_ShutdownTimer % MINUTE )==0) ||
2379 // < 30 min ; every 5 min
2380 (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
2381 // < 12 h ; every 1 h
2382 (m_ShutdownTimer<12*HOUR && (m_ShutdownTimer % HOUR )==0) ||
2383 // > 12 h ; every 12 h
2384 (m_ShutdownTimer>12*HOUR && (m_ShutdownTimer % (12*HOUR) )==0))
2386 std::string str = secsToTimeString(m_ShutdownTimer);
2388 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
2390 SendServerMessage(msgid,str.c_str(),player);
2391 DEBUG_LOG("Server is %s in %s",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"),str.c_str());
2395 /// Cancel a planned server shutdown
2396 void World::ShutdownCancel()
2398 // nothing cancel or too later
2399 if(!m_ShutdownTimer || m_stopEvent)
2400 return;
2402 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2404 m_ShutdownMask = 0;
2405 m_ShutdownTimer = 0;
2406 m_ExitCode = SHUTDOWN_EXIT_CODE; // to default value
2407 SendServerMessage(msgid);
2409 DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2412 /// Send a server message to the user(s)
2413 void World::SendServerMessage(uint32 type, const char *text, Player* player)
2415 WorldPacket data(SMSG_SERVER_MESSAGE, 50); // guess size
2416 data << uint32(type);
2417 if(type <= SERVER_MSG_STRING)
2418 data << text;
2420 if(player)
2421 player->GetSession()->SendPacket(&data);
2422 else
2423 SendGlobalMessage( &data );
2426 void World::UpdateSessions( time_t diff )
2428 while(!addSessQueue.empty())
2430 WorldSession* sess = addSessQueue.next ();
2431 AddSession_ (sess);
2434 ///- Delete kicked sessions at add new session
2435 for (std::set<WorldSession*>::iterator itr = m_kicked_sessions.begin(); itr != m_kicked_sessions.end(); ++itr)
2437 RemoveQueuedPlayer (*itr);
2438 delete *itr;
2440 m_kicked_sessions.clear();
2442 ///- Then send an update signal to remaining ones
2443 for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2445 next = itr;
2446 ++next;
2448 if(!itr->second)
2449 continue;
2451 ///- and remove not active sessions from the list
2452 if(!itr->second->Update(diff)) // As interval = 0
2454 RemoveQueuedPlayer (itr->second);
2455 delete itr->second;
2456 m_sessions.erase(itr);
2461 // This handles the issued and queued CLI commands
2462 void World::ProcessCliCommands()
2464 if (cliCmdQueue.empty())
2465 return;
2467 CliCommandHolder::Print* zprint;
2469 while (!cliCmdQueue.empty())
2471 sLog.outDebug("CLI command under processing...");
2472 CliCommandHolder *command = cliCmdQueue.next();
2474 zprint = command->m_print;
2476 CliHandler(zprint).ParseCommands(command->m_command);
2478 delete command;
2481 // print the console message here so it looks right
2482 zprint("mangos>");
2485 void World::InitResultQueue()
2487 m_resultQueue = new SqlResultQueue;
2488 CharacterDatabase.SetResultQueue(m_resultQueue);
2491 void World::UpdateResultQueue()
2493 m_resultQueue->Update();
2496 void World::UpdateRealmCharCount(uint32 accountId)
2498 CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2499 "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2502 void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2504 if (resultCharCount)
2506 Field *fields = resultCharCount->Fetch();
2507 uint32 charCount = fields[0].GetUInt32();
2508 delete resultCharCount;
2509 loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2510 loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2514 void World::InitDailyQuestResetTime()
2516 time_t mostRecentQuestTime;
2518 QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2519 if(result)
2521 Field *fields = result->Fetch();
2523 mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2524 delete result;
2526 else
2527 mostRecentQuestTime = 0;
2529 // client built-in time for reset is 6:00 AM
2530 // FIX ME: client not show day start time
2531 time_t curTime = time(NULL);
2532 tm localTm = *localtime(&curTime);
2533 localTm.tm_hour = 6;
2534 localTm.tm_min = 0;
2535 localTm.tm_sec = 0;
2537 // current day reset time
2538 time_t curDayResetTime = mktime(&localTm);
2540 // last reset time before current moment
2541 time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2543 // need reset (if we have quest time before last reset time (not processed by some reason)
2544 if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2545 m_NextDailyQuestReset = mostRecentQuestTime;
2546 else
2548 // plan next reset time
2549 m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2553 void World::ResetDailyQuests()
2555 sLog.outDetail("Daily quests reset for all characters.");
2556 CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2557 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2558 if(itr->second->GetPlayer())
2559 itr->second->GetPlayer()->ResetDailyQuestStatus();
2562 void World::SetPlayerLimit( int32 limit, bool needUpdate )
2564 if(limit < -SEC_ADMINISTRATOR)
2565 limit = -SEC_ADMINISTRATOR;
2567 // lock update need
2568 bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2570 m_playerLimit = limit;
2572 if(db_update_need)
2573 loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2576 void World::UpdateMaxSessionCounters()
2578 m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2579 m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2582 void World::LoadDBVersion()
2584 QueryResult* result = WorldDatabase.Query("SELECT version FROM db_version LIMIT 1");
2585 if(result)
2587 Field* fields = result->Fetch();
2589 m_DBVersion = fields[0].GetString();
2590 delete result;
2592 else
2593 m_DBVersion = "unknown world database";