* Remove unused now TcpNoDelay config option. Patch provided by TonyMontana5000.
[getmangos.git] / src / game / World.cpp
blob2badcae6b7461b6868db46f25b6d00d964a6d302
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 "ObjectMgr.h"
38 #include "SpellMgr.h"
39 #include "Chat.h"
40 #include "Database/DBCStores.h"
41 #include "LootMgr.h"
42 #include "ItemEnchantmentMgr.h"
43 #include "MapManager.h"
44 #include "ScriptCalls.h"
45 #include "CreatureAIRegistry.h"
46 #include "Policies/SingletonImp.h"
47 #include "BattleGroundMgr.h"
48 #include "TemporarySummon.h"
49 #include "WaypointMovementGenerator.h"
50 #include "VMapFactory.h"
51 #include "GlobalEvents.h"
52 #include "GameEvent.h"
53 #include "Database/DatabaseImpl.h"
54 #include "GridNotifiersImpl.h"
55 #include "CellImpl.h"
56 #include "InstanceSaveMgr.h"
57 #include "WaypointManager.h"
58 #include "Util.h"
60 INSTANTIATE_SINGLETON_1( World );
62 volatile bool World::m_stopEvent = false;
63 volatile uint32 World::m_worldLoopCounter = 0;
65 float World::m_MaxVisibleDistanceForCreature = DEFAULT_VISIBILITY_DISTANCE;
66 float World::m_MaxVisibleDistanceForPlayer = DEFAULT_VISIBILITY_DISTANCE;
67 float World::m_MaxVisibleDistanceForObject = DEFAULT_VISIBILITY_DISTANCE;
68 float World::m_MaxVisibleDistanceInFlight = DEFAULT_VISIBILITY_DISTANCE;
69 float World::m_VisibleUnitGreyDistance = 0;
70 float World::m_VisibleObjectGreyDistance = 0;
72 // ServerMessages.dbc
73 enum ServerMessageType
75 SERVER_MSG_SHUTDOWN_TIME = 1,
76 SERVER_MSG_RESTART_TIME = 2,
77 SERVER_MSG_STRING = 3,
78 SERVER_MSG_SHUTDOWN_CANCELLED = 4,
79 SERVER_MSG_RESTART_CANCELLED = 5
82 struct ScriptAction
84 uint64 sourceGUID;
85 uint64 targetGUID;
86 uint64 ownerGUID; // owner of source if source is item
87 ScriptInfo const* script; // pointer to static script data
90 /// World constructor
91 World::World()
93 m_playerLimit = 0;
94 m_allowMovement = true;
95 m_ShutdownMask = 0;
96 m_ShutdownTimer = 0;
97 m_gameTime=time(NULL);
98 m_startTime=m_gameTime;
99 m_maxActiveSessionCount = 0;
100 m_maxQueuedSessionCount = 0;
101 m_resultQueue = NULL;
102 m_NextDailyQuestReset = 0;
104 m_defaultDbcLocale = LOCALE_enUS;
105 m_availableDbcLocaleMask = 0;
108 /// World destructor
109 World::~World()
111 ///- Empty the kicked session set
112 for (std::set<WorldSession*>::iterator itr = m_kicked_sessions.begin(); itr != m_kicked_sessions.end(); ++itr)
113 delete *itr;
115 m_kicked_sessions.clear();
117 ///- Empty the WeatherMap
118 for (WeatherMap::iterator itr = m_weathers.begin(); itr != m_weathers.end(); ++itr)
119 delete itr->second;
121 m_weathers.clear();
123 VMAP::VMapFactory::clear();
125 if(m_resultQueue) delete m_resultQueue;
127 //TODO free addSessQueue
130 /// Find a player in a specified zone
131 Player* World::FindPlayerInZone(uint32 zone)
133 ///- circle through active sessions and return the first player found in the zone
134 SessionMap::iterator itr;
135 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
137 if(!itr->second)
138 continue;
139 Player *player = itr->second->GetPlayer();
140 if(!player)
141 continue;
142 if( player->IsInWorld() && player->GetZoneId() == zone )
144 // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone.
145 return player;
148 return NULL;
151 /// Find a session by its id
152 WorldSession* World::FindSession(uint32 id) const
154 SessionMap::const_iterator itr = m_sessions.find(id);
156 if(itr != m_sessions.end())
157 return itr->second; // also can return NULL for kicked session
158 else
159 return NULL;
162 /// Remove a given session
163 bool World::RemoveSession(uint32 id)
165 ///- Find the session, kick the user, but we can't delete session at this moment to prevent iterator invalidation
166 SessionMap::iterator itr = m_sessions.find(id);
168 if(itr != m_sessions.end() && itr->second)
170 if (itr->second->PlayerLoading())
171 return false;
172 itr->second->KickPlayer();
175 return true;
178 void World::AddSession(WorldSession* s)
180 addSessQueue.add(s);
183 void
184 World::AddSession_ (WorldSession* s)
186 ASSERT (s);
188 //NOTE - Still there is race condition in WorldSession* being used in the Sockets
190 ///- kick already loaded player with same account (if any) and remove session
191 ///- if player is in loading and want to load again, return
192 if (!RemoveSession (s->GetAccountId ()))
194 s->KickPlayer ();
195 m_kicked_sessions.insert (s);
196 return;
199 WorldSession* old = m_sessions[s->GetAccountId ()];
200 m_sessions[s->GetAccountId ()] = s;
202 // if session already exist, prepare to it deleting at next world update
203 // NOTE - KickPlayer() should be called on "old" in RemoveSession()
204 if (old)
205 m_kicked_sessions.insert (old);
207 uint32 Sessions = GetActiveAndQueuedSessionCount ();
208 uint32 pLimit = GetPlayerAmountLimit ();
209 uint32 QueueSize = GetQueueSize (); //number of players in the queue
210 bool inQueue = false;
211 //so we don't count the user trying to
212 //login as a session and queue the socket that we are using
213 --Sessions;
215 if (pLimit > 0 && Sessions >= pLimit && s->GetSecurity () == SEC_PLAYER )
217 AddQueuedPlayer (s);
218 UpdateMaxSessionCounters ();
219 sLog.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s->GetAccountId (), ++QueueSize);
220 return;
223 WorldPacket packet(SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
224 packet << uint8 (AUTH_OK);
225 packet << uint32 (0); // unknown random value...
226 packet << uint8 (0);
227 packet << uint32 (0);
228 packet << uint8 (s->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
229 s->SendPacket (&packet);
231 UpdateMaxSessionCounters ();
233 // Updates the population
234 if (pLimit > 0)
236 float popu = GetActiveSessionCount (); //updated number of users on the server
237 popu /= pLimit;
238 popu *= 2;
239 loginDatabase.PExecute ("UPDATE realmlist SET population = '%f' WHERE id = '%d'", popu, realmID);
240 sLog.outDetail ("Server Population (%f).", popu);
244 int32 World::GetQueuePos(WorldSession* sess)
246 uint32 position = 1;
248 for(Queue::iterator iter = m_QueuedPlayer.begin(); iter != m_QueuedPlayer.end(); ++iter, ++position)
249 if((*iter) == sess)
250 return position;
252 return 0;
255 void World::AddQueuedPlayer(WorldSession* sess)
257 m_QueuedPlayer.push_back (sess);
259 // The 1st SMSG_AUTH_RESPONSE needs to contain other info too.
260 WorldPacket packet (SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
261 packet << uint8 (AUTH_WAIT_QUEUE);
262 packet << uint32 (0); // unknown random value...
263 packet << uint8 (0);
264 packet << uint32 (0);
265 packet << uint8 (sess->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
266 packet << uint32(GetQueuePos (sess));
267 sess->SendPacket (&packet);
269 //sess->SendAuthWaitQue (GetQueuePos (sess));
272 void World::RemoveQueuedPlayer(WorldSession* sess)
274 // sessions count including queued to remove (if removed_session set)
275 uint32 sessions = GetActiveSessionCount();
277 uint32 position = 1;
278 Queue::iterator iter = m_QueuedPlayer.begin();
280 // if session not queued then we need decrease sessions count (Remove socked callet before session removing from session list)
281 bool decrease_session = true;
283 // search to remove and count skipped positions
284 for(;iter != m_QueuedPlayer.end(); ++iter, ++position)
286 if(*iter==sess)
288 Queue::iterator iter2 = iter;
289 ++iter;
290 m_QueuedPlayer.erase(iter2);
291 decrease_session = false; // removing queued session
292 break;
296 // iter point to next socked after removed or end()
297 // position store position of removed socket and then new position next socket after removed
299 // decrease for case session queued for removing
300 if(decrease_session && sessions)
301 --sessions;
303 // accept first in queue
304 if( (!m_playerLimit || sessions < m_playerLimit) && !m_QueuedPlayer.empty() )
306 WorldSession * socket = m_QueuedPlayer.front();
307 socket->SendAuthWaitQue(0);
308 m_QueuedPlayer.pop_front();
310 // update iter to point first queued socket or end() if queue is empty now
311 iter = m_QueuedPlayer.begin();
312 position = 1;
315 // update position from iter to end()
316 // iter point to first not updated socket, position store new position
317 for(; iter != m_QueuedPlayer.end(); ++iter, ++position)
318 (*iter)->SendAuthWaitQue(position);
321 /// Find a Weather object by the given zoneid
322 Weather* World::FindWeather(uint32 id) const
324 WeatherMap::const_iterator itr = m_weathers.find(id);
326 if(itr != m_weathers.end())
327 return itr->second;
328 else
329 return 0;
332 /// Remove a Weather object for the given zoneid
333 void World::RemoveWeather(uint32 id)
335 // not called at the moment. Kept for completeness
336 WeatherMap::iterator itr = m_weathers.find(id);
338 if(itr != m_weathers.end())
340 delete itr->second;
341 m_weathers.erase(itr);
345 /// Add a Weather object to the list
346 Weather* World::AddWeather(uint32 zone_id)
348 WeatherZoneChances const* weatherChances = objmgr.GetWeatherChances(zone_id);
350 // zone not have weather, ignore
351 if(!weatherChances)
352 return NULL;
354 Weather* w = new Weather(zone_id,weatherChances);
355 m_weathers[w->GetZone()] = w;
356 w->ReGenerate();
357 w->UpdateWeather();
358 return w;
361 /// Initialize config values
362 void World::LoadConfigSettings(bool reload)
364 if(reload)
366 if(!sConfig.Reload())
368 sLog.outError("World settings reload fail: can't read settings from %s.",sConfig.GetFilename().c_str());
369 return;
373 ///- Read the version of the configuration file and warn the user in case of emptiness or mismatch
374 uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
375 if(!confVersion)
377 sLog.outError("*****************************************************************************");
378 sLog.outError(" WARNING: mangosd.conf does not include a ConfVersion variable.");
379 sLog.outError(" Your configuration file may be out of date!");
380 sLog.outError("*****************************************************************************");
381 clock_t pause = 3000 + clock();
382 while (pause > clock());
384 else
386 if (confVersion < _MANGOSDCONFVERSION)
388 sLog.outError("*****************************************************************************");
389 sLog.outError(" WARNING: Your mangosd.conf version indicates your conf file is out of date!");
390 sLog.outError(" Please check for updates, as your current default values may cause");
391 sLog.outError(" unexpected behavior.");
392 sLog.outError("*****************************************************************************");
393 clock_t pause = 3000 + clock();
394 while (pause > clock());
398 ///- Read the player limit and the Message of the day from the config file
399 SetPlayerLimit( sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT), true );
400 SetMotd( sConfig.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
402 ///- Read all rates from the config file
403 rate_values[RATE_HEALTH] = sConfig.GetFloatDefault("Rate.Health", 1);
404 if(rate_values[RATE_HEALTH] < 0)
406 sLog.outError("Rate.Health (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_HEALTH]);
407 rate_values[RATE_HEALTH] = 1;
409 rate_values[RATE_POWER_MANA] = sConfig.GetFloatDefault("Rate.Mana", 1);
410 if(rate_values[RATE_POWER_MANA] < 0)
412 sLog.outError("Rate.Mana (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_POWER_MANA]);
413 rate_values[RATE_POWER_MANA] = 1;
415 rate_values[RATE_POWER_RAGE_INCOME] = sConfig.GetFloatDefault("Rate.Rage.Income", 1);
416 rate_values[RATE_POWER_RAGE_LOSS] = sConfig.GetFloatDefault("Rate.Rage.Loss", 1);
417 if(rate_values[RATE_POWER_RAGE_LOSS] < 0)
419 sLog.outError("Rate.Rage.Loss (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_POWER_RAGE_LOSS]);
420 rate_values[RATE_POWER_RAGE_LOSS] = 1;
422 rate_values[RATE_POWER_FOCUS] = sConfig.GetFloatDefault("Rate.Focus", 1.0f);
423 rate_values[RATE_LOYALTY] = sConfig.GetFloatDefault("Rate.Loyalty", 1.0f);
424 rate_values[RATE_SKILL_DISCOVERY] = sConfig.GetFloatDefault("Rate.Skill.Discovery", 1.0f);
425 rate_values[RATE_DROP_ITEM_POOR] = sConfig.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f);
426 rate_values[RATE_DROP_ITEM_NORMAL] = sConfig.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f);
427 rate_values[RATE_DROP_ITEM_UNCOMMON] = sConfig.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f);
428 rate_values[RATE_DROP_ITEM_RARE] = sConfig.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f);
429 rate_values[RATE_DROP_ITEM_EPIC] = sConfig.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f);
430 rate_values[RATE_DROP_ITEM_LEGENDARY] = sConfig.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f);
431 rate_values[RATE_DROP_ITEM_ARTIFACT] = sConfig.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f);
432 rate_values[RATE_DROP_ITEM_REFERENCED] = sConfig.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f);
433 rate_values[RATE_DROP_MONEY] = sConfig.GetFloatDefault("Rate.Drop.Money", 1.0f);
434 rate_values[RATE_XP_KILL] = sConfig.GetFloatDefault("Rate.XP.Kill", 1.0f);
435 rate_values[RATE_XP_QUEST] = sConfig.GetFloatDefault("Rate.XP.Quest", 1.0f);
436 rate_values[RATE_XP_EXPLORE] = sConfig.GetFloatDefault("Rate.XP.Explore", 1.0f);
437 rate_values[RATE_XP_PAST_70] = sConfig.GetFloatDefault("Rate.XP.PastLevel70", 1.0f);
438 rate_values[RATE_REPUTATION_GAIN] = sConfig.GetFloatDefault("Rate.Reputation.Gain", 1.0f);
439 rate_values[RATE_CREATURE_NORMAL_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f);
440 rate_values[RATE_CREATURE_ELITE_ELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f);
441 rate_values[RATE_CREATURE_ELITE_RAREELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f);
442 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f);
443 rate_values[RATE_CREATURE_ELITE_RARE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f);
444 rate_values[RATE_CREATURE_NORMAL_HP] = sConfig.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f);
445 rate_values[RATE_CREATURE_ELITE_ELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f);
446 rate_values[RATE_CREATURE_ELITE_RAREELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f);
447 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f);
448 rate_values[RATE_CREATURE_ELITE_RARE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f);
449 rate_values[RATE_CREATURE_NORMAL_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f);
450 rate_values[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f);
451 rate_values[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f);
452 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f);
453 rate_values[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f);
454 rate_values[RATE_CREATURE_AGGRO] = sConfig.GetFloatDefault("Rate.Creature.Aggro", 1.0f);
455 rate_values[RATE_REST_INGAME] = sConfig.GetFloatDefault("Rate.Rest.InGame", 1.0f);
456 rate_values[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY] = sConfig.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f);
457 rate_values[RATE_REST_OFFLINE_IN_WILDERNESS] = sConfig.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f);
458 rate_values[RATE_DAMAGE_FALL] = sConfig.GetFloatDefault("Rate.Damage.Fall", 1.0f);
459 rate_values[RATE_AUCTION_TIME] = sConfig.GetFloatDefault("Rate.Auction.Time", 1.0f);
460 rate_values[RATE_AUCTION_DEPOSIT] = sConfig.GetFloatDefault("Rate.Auction.Deposit", 1.0f);
461 rate_values[RATE_AUCTION_CUT] = sConfig.GetFloatDefault("Rate.Auction.Cut", 1.0f);
462 rate_values[RATE_HONOR] = sConfig.GetFloatDefault("Rate.Honor",1.0f);
463 rate_values[RATE_MINING_AMOUNT] = sConfig.GetFloatDefault("Rate.Mining.Amount",1.0f);
464 rate_values[RATE_MINING_NEXT] = sConfig.GetFloatDefault("Rate.Mining.Next",1.0f);
465 rate_values[RATE_INSTANCE_RESET_TIME] = sConfig.GetFloatDefault("Rate.InstanceResetTime",1.0f);
466 rate_values[RATE_TALENT] = sConfig.GetFloatDefault("Rate.Talent",1.0f);
467 if(rate_values[RATE_TALENT] < 0.0f)
469 sLog.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_TALENT]);
470 rate_values[RATE_TALENT] = 1.0f;
472 rate_values[RATE_CORPSE_DECAY_LOOTED] = sConfig.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f);
474 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = sConfig.GetFloatDefault("TargetPosRecalculateRange",1.5f);
475 if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] < CONTACT_DISTANCE)
477 sLog.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],CONTACT_DISTANCE,CONTACT_DISTANCE);
478 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = CONTACT_DISTANCE;
480 else if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] > ATTACK_DISTANCE)
482 sLog.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],ATTACK_DISTANCE,ATTACK_DISTANCE);
483 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = ATTACK_DISTANCE;
486 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = sConfig.GetFloatDefault("DurabilityLossChance.Damage",0.5f);
487 if(rate_values[RATE_DURABILITY_LOSS_DAMAGE] < 0.0f)
489 sLog.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_DAMAGE]);
490 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = 0.0f;
492 rate_values[RATE_DURABILITY_LOSS_ABSORB] = sConfig.GetFloatDefault("DurabilityLossChance.Absorb",0.5f);
493 if(rate_values[RATE_DURABILITY_LOSS_ABSORB] < 0.0f)
495 sLog.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_ABSORB]);
496 rate_values[RATE_DURABILITY_LOSS_ABSORB] = 0.0f;
498 rate_values[RATE_DURABILITY_LOSS_PARRY] = sConfig.GetFloatDefault("DurabilityLossChance.Parry",0.05f);
499 if(rate_values[RATE_DURABILITY_LOSS_PARRY] < 0.0f)
501 sLog.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_PARRY]);
502 rate_values[RATE_DURABILITY_LOSS_PARRY] = 0.0f;
504 rate_values[RATE_DURABILITY_LOSS_BLOCK] = sConfig.GetFloatDefault("DurabilityLossChance.Block",0.05f);
505 if(rate_values[RATE_DURABILITY_LOSS_BLOCK] < 0.0f)
507 sLog.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_BLOCK]);
508 rate_values[RATE_DURABILITY_LOSS_BLOCK] = 0.0f;
511 ///- Read other configuration items from the config file
513 m_configs[CONFIG_COMPRESSION] = sConfig.GetIntDefault("Compression", 1);
514 if(m_configs[CONFIG_COMPRESSION] < 1 || m_configs[CONFIG_COMPRESSION] > 9)
516 sLog.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs[CONFIG_COMPRESSION]);
517 m_configs[CONFIG_COMPRESSION] = 1;
519 m_configs[CONFIG_ADDON_CHANNEL] = sConfig.GetBoolDefault("AddonChannel", true);
520 m_configs[CONFIG_GRID_UNLOAD] = sConfig.GetBoolDefault("GridUnload", true);
521 m_configs[CONFIG_INTERVAL_SAVE] = sConfig.GetIntDefault("PlayerSaveInterval", 900000);
523 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = sConfig.GetIntDefault("GridCleanUpDelay", 300000);
524 if(m_configs[CONFIG_INTERVAL_GRIDCLEAN] < MIN_GRID_DELAY)
526 sLog.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_GRIDCLEAN],MIN_GRID_DELAY);
527 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = MIN_GRID_DELAY;
529 if(reload)
530 MapManager::Instance().SetGridCleanUpDelay(m_configs[CONFIG_INTERVAL_GRIDCLEAN]);
532 m_configs[CONFIG_INTERVAL_MAPUPDATE] = sConfig.GetIntDefault("MapUpdateInterval", 100);
533 if(m_configs[CONFIG_INTERVAL_MAPUPDATE] < MIN_MAP_UPDATE_DELAY)
535 sLog.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_MAPUPDATE],MIN_MAP_UPDATE_DELAY);
536 m_configs[CONFIG_INTERVAL_MAPUPDATE] = MIN_MAP_UPDATE_DELAY;
538 if(reload)
539 MapManager::Instance().SetMapUpdateInterval(m_configs[CONFIG_INTERVAL_MAPUPDATE]);
541 m_configs[CONFIG_INTERVAL_CHANGEWEATHER] = sConfig.GetIntDefault("ChangeWeatherInterval", 600000);
543 if(reload)
545 uint32 val = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
546 if(val!=m_configs[CONFIG_PORT_WORLD])
547 sLog.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_PORT_WORLD]);
549 else
550 m_configs[CONFIG_PORT_WORLD] = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
552 if(reload)
554 uint32 val = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
555 if(val!=m_configs[CONFIG_SOCKET_SELECTTIME])
556 sLog.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[DEFAULT_SOCKET_SELECT_TIME]);
558 else
559 m_configs[CONFIG_SOCKET_SELECTTIME] = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
561 m_configs[CONFIG_GROUP_XP_DISTANCE] = sConfig.GetIntDefault("MaxGroupXPDistance", 74);
562 /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
563 m_configs[CONFIG_SIGHT_MONSTER] = sConfig.GetIntDefault("MonsterSight", 50);
564 m_configs[CONFIG_SIGHT_GUARDER] = sConfig.GetIntDefault("GuarderSight", 50);
566 if(reload)
568 uint32 val = sConfig.GetIntDefault("GameType", 0);
569 if(val!=m_configs[CONFIG_GAME_TYPE])
570 sLog.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_GAME_TYPE]);
572 else
573 m_configs[CONFIG_GAME_TYPE] = sConfig.GetIntDefault("GameType", 0);
575 if(reload)
577 uint32 val = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
578 if(val!=m_configs[CONFIG_REALM_ZONE])
579 sLog.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_REALM_ZONE]);
581 else
582 m_configs[CONFIG_REALM_ZONE] = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
584 m_configs[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS] = sConfig.GetBoolDefault("AllowTwoSide.Accounts", false);
585 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
586 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
587 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
588 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
589 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
590 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
591 m_configs[CONFIG_ALLOW_TWO_SIDE_WHO_LIST] = sConfig.GetBoolDefault("AllowTwoSide.WhoList", false);
592 m_configs[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND] = sConfig.GetBoolDefault("AllowTwoSide.AddFriend", false);
593 m_configs[CONFIG_STRICT_PLAYER_NAMES] = sConfig.GetIntDefault("StrictPlayerNames", 0);
594 m_configs[CONFIG_STRICT_CHARTER_NAMES] = sConfig.GetIntDefault("StrictCharterNames", 0);
595 m_configs[CONFIG_STRICT_PET_NAMES] = sConfig.GetIntDefault("StrictPetNames", 0);
597 m_configs[CONFIG_CHARACTERS_CREATING_DISABLED] = sConfig.GetIntDefault("CharactersCreatingDisabled", 0);
599 m_configs[CONFIG_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("CharactersPerRealm", 10);
600 if(m_configs[CONFIG_CHARACTERS_PER_REALM] < 1 || m_configs[CONFIG_CHARACTERS_PER_REALM] > 10)
602 sLog.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs[CONFIG_CHARACTERS_PER_REALM]);
603 m_configs[CONFIG_CHARACTERS_PER_REALM] = 10;
606 // must be after CONFIG_CHARACTERS_PER_REALM
607 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = sConfig.GetIntDefault("CharactersPerAccount", 50);
608 if(m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] < m_configs[CONFIG_CHARACTERS_PER_REALM])
610 sLog.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs[CONFIG_CHARACTERS_PER_ACCOUNT],m_configs[CONFIG_CHARACTERS_PER_REALM]);
611 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = m_configs[CONFIG_CHARACTERS_PER_REALM];
614 m_configs[CONFIG_SKIP_CINEMATICS] = sConfig.GetIntDefault("SkipCinematics", 0);
615 if(m_configs[CONFIG_SKIP_CINEMATICS] < 0 || m_configs[CONFIG_SKIP_CINEMATICS] > 2)
617 sLog.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs[CONFIG_SKIP_CINEMATICS]);
618 m_configs[CONFIG_SKIP_CINEMATICS] = 0;
621 if(reload)
623 uint32 val = sConfig.GetIntDefault("MaxPlayerLevel", 60);
624 if(val!=m_configs[CONFIG_MAX_PLAYER_LEVEL])
625 sLog.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
627 else
628 m_configs[CONFIG_MAX_PLAYER_LEVEL] = sConfig.GetIntDefault("MaxPlayerLevel", 60);
629 if(m_configs[CONFIG_MAX_PLAYER_LEVEL] > 255)
631 sLog.outError("MaxPlayerLevel (%i) must be in range 1..255. Set to 255.",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
632 m_configs[CONFIG_MAX_PLAYER_LEVEL] = 255;
635 m_configs[CONFIG_START_PLAYER_LEVEL] = sConfig.GetIntDefault("StartPlayerLevel", 1);
636 if(m_configs[CONFIG_START_PLAYER_LEVEL] < 1)
638 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]);
639 m_configs[CONFIG_START_PLAYER_LEVEL] = 1;
641 else if(m_configs[CONFIG_START_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
643 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]);
644 m_configs[CONFIG_START_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
646 m_configs[CONFIG_MAX_HONOR_POINTS] = sConfig.GetIntDefault("MaxHonorPoints", 75000);
647 m_configs[CONFIG_MAX_ARENA_POINTS] = sConfig.GetIntDefault("MaxArenaPoints", 5000);
649 m_configs[CONFIG_INSTANCE_IGNORE_LEVEL] = sConfig.GetBoolDefault("Instance.IgnoreLevel", false);
650 m_configs[CONFIG_INSTANCE_IGNORE_RAID] = sConfig.GetBoolDefault("Instance.IgnoreRaid", false);
652 m_configs[CONFIG_BATTLEGROUND_CAST_DESERTER] = sConfig.GetBoolDefault("Battleground.CastDeserter", true);
653 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.Enable", true);
654 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false);
656 m_configs[CONFIG_CAST_UNSTUCK] = sConfig.GetBoolDefault("CastUnstuck", true);
657 m_configs[CONFIG_INSTANCE_RESET_TIME_HOUR] = sConfig.GetIntDefault("Instance.ResetTimeHour", 4);
658 m_configs[CONFIG_INSTANCE_UNLOAD_DELAY] = sConfig.GetIntDefault("Instance.UnloadDelay", 1800000);
660 m_configs[CONFIG_MAX_PRIMARY_TRADE_SKILL] = sConfig.GetIntDefault("MaxPrimaryTradeSkill", 2);
661 m_configs[CONFIG_MIN_PETITION_SIGNS] = sConfig.GetIntDefault("MinPetitionSigns", 9);
662 if(m_configs[CONFIG_MIN_PETITION_SIGNS] > 9)
664 sLog.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.",m_configs[CONFIG_MIN_PETITION_SIGNS]);
665 m_configs[CONFIG_MIN_PETITION_SIGNS] = 9;
668 m_configs[CONFIG_GM_LOGIN_STATE] = sConfig.GetIntDefault("GM.LoginState",2);
669 m_configs[CONFIG_GM_ACCEPT_TICKETS] = sConfig.GetIntDefault("GM.AcceptTickets",2);
670 m_configs[CONFIG_GM_CHAT] = sConfig.GetIntDefault("GM.Chat",2);
671 m_configs[CONFIG_GM_WISPERING_TO] = sConfig.GetIntDefault("GM.WhisperingTo",2);
673 m_configs[CONFIG_GM_IN_GM_LIST] = sConfig.GetBoolDefault("GM.InGMList",false);
674 m_configs[CONFIG_GM_IN_WHO_LIST] = sConfig.GetBoolDefault("GM.InWhoList",false);
675 m_configs[CONFIG_GM_LOG_TRADE] = sConfig.GetBoolDefault("GM.LogTrade", false);
677 m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
679 m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
681 m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
682 if(m_configs[CONFIG_UPTIME_UPDATE]<=0)
684 sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
685 m_configs[CONFIG_UPTIME_UPDATE] = 10;
687 if(reload)
689 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
690 m_timers[WUPDATE_UPTIME].Reset();
693 m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
694 m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
695 m_configs[CONFIG_SKILL_CHANCE_GREEN] = sConfig.GetIntDefault("SkillChance.Green",25);
696 m_configs[CONFIG_SKILL_CHANCE_GREY] = sConfig.GetIntDefault("SkillChance.Grey",0);
698 m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS] = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
699 m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS] = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
701 m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
703 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = sConfig.GetIntDefault("SkillGain.Crafting", 1);
704 if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
706 sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
707 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
710 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = sConfig.GetIntDefault("SkillGain.Defense", 1);
711 if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
713 sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
714 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
717 m_configs[CONFIG_SKILL_GAIN_GATHERING] = sConfig.GetIntDefault("SkillGain.Gathering", 1);
718 if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
720 sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
721 m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
724 m_configs[CONFIG_SKILL_GAIN_WEAPON] = sConfig.GetIntDefault("SkillGain.Weapon", 1);
725 if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
727 sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
728 m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
731 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
732 if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
734 sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
735 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
738 m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
739 m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
741 if(reload)
743 uint32 val = sConfig.GetIntDefault("Expansion",1);
744 if(val!=m_configs[CONFIG_EXPANSION])
745 sLog.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
747 else
748 m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",1);
750 m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
751 m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
752 m_configs[CONFIG_CHATFLOOD_MUTE_TIME] = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
754 m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
756 m_configs[CONFIG_CREATURE_FAMILY_ASSISTEMCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistenceRadius",10);
758 m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
760 // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level (255)
761 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff",4);
762 if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > 255)
763 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = 255;
764 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff",7);
765 if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > 255)
766 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = 255;
768 m_configs[CONFIG_DETECT_POS_COLLISION] = sConfig.GetBoolDefault("DetectPosCollision", true);
770 m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
771 m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
773 m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
774 m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
776 m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
777 m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
778 m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
779 m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
780 m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
782 m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault("Death.SicknessLevel", 11);
783 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
784 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
786 m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
788 // always use declined names in the russian client
789 m_configs[CONFIG_DECLINED_NAMES_USED] =
790 (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
792 m_configs[CONFIG_LISTEN_RANGE_SAY] = sConfig.GetIntDefault("ListenRange.Say", 25);
793 m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
794 m_configs[CONFIG_LISTEN_RANGE_YELL] = sConfig.GetIntDefault("ListenRange.Yell", 300);
796 m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
797 if(m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
799 sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
800 m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
802 m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
803 if(m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
805 sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
806 m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
809 m_MaxVisibleDistanceForCreature = sConfig.GetFloatDefault("Visibility.Distance.Creature", DEFAULT_VISIBILITY_DISTANCE);
810 if(m_MaxVisibleDistanceForCreature < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
812 sLog.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
813 m_MaxVisibleDistanceForCreature = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
815 else if(m_MaxVisibleDistanceForCreature + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
817 sLog.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
818 m_MaxVisibleDistanceForCreature = MAX_VISIBILITY_DISTANCE-m_VisibleUnitGreyDistance;
820 m_MaxVisibleDistanceForPlayer = sConfig.GetFloatDefault("Visibility.Distance.Player", DEFAULT_VISIBILITY_DISTANCE);
821 if(m_MaxVisibleDistanceForPlayer < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
823 sLog.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
824 m_MaxVisibleDistanceForPlayer = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
826 else if(m_MaxVisibleDistanceForPlayer + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
828 sLog.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
829 m_MaxVisibleDistanceForPlayer = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
831 m_MaxVisibleDistanceForObject = sConfig.GetFloatDefault("Visibility.Distance.Gameobject", DEFAULT_VISIBILITY_DISTANCE);
832 if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
834 sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
835 m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
837 else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
839 sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
840 m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
842 m_MaxVisibleDistanceInFlight = sConfig.GetFloatDefault("Visibility.Distance.InFlight", DEFAULT_VISIBILITY_DISTANCE);
843 if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
845 sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
846 m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
849 ///- Read the "Data" directory from the config file
850 std::string dataPath = sConfig.GetStringDefault("DataDir","./");
851 if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
852 dataPath.append("/");
854 if(reload)
856 if(dataPath!=m_dataPath)
857 sLog.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath.c_str());
859 else
861 m_dataPath = dataPath;
862 sLog.outString("Using DataDir %s",m_dataPath.c_str());
865 bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
866 bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
867 std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
868 std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
869 VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
870 VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
871 VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
872 VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
873 sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
874 sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
875 sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
878 /// Initialize the World
879 void World::SetInitialWorldSettings()
881 ///- Initialize the random number generator
882 srand((unsigned int)time(NULL));
884 ///- Initialize config settings
885 LoadConfigSettings();
887 ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
888 objmgr.SetHighestGuids();
890 ///- Check the existence of the map files for all races' startup areas.
891 if( !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
892 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
893 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
894 ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
895 ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
896 ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
897 ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
898 ||m_configs[CONFIG_EXPANSION] && (
899 !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
901 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());
902 exit(1);
905 ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
906 sLog.outString( "" );
907 sLog.outString( "Loading MaNGOS strings..." );
908 if (!objmgr.LoadMangosStrings())
909 exit(1); // Error message displayed in function already
911 ///- Update the realm entry in the database with the realm type from the config file
912 //No SQL injection as values are treated as integers
914 // not send custom type REALM_FFA_PVP to realm list
915 uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
916 uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
917 loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
919 ///- Remove the bones after a restart
920 CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
922 ///- Load the DBC files
923 sLog.outString("Initialize data stores...");
924 LoadDBCStores(m_dataPath);
925 DetectDBCLang();
927 sLog.outString( "Loading InstanceTemplate" );
928 objmgr.LoadInstanceTemplate();
930 sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
931 spellmgr.LoadSkillLineAbilityMap();
933 ///- Clean up and pack instances
934 sLog.outString( "Cleaning up instances..." );
935 sInstanceSaveManager.CleanupInstances(); // must be called before `creature_respawn`/`gameobject_respawn` tables
937 sLog.outString( "Packing instances..." );
938 sInstanceSaveManager.PackInstances();
940 sLog.outString( "Loading Localization strings..." );
941 objmgr.LoadCreatureLocales();
942 objmgr.LoadGameObjectLocales();
943 objmgr.LoadItemLocales();
944 objmgr.LoadQuestLocales();
945 objmgr.LoadNpcTextLocales();
946 objmgr.LoadPageTextLocales();
947 objmgr.SetDBCLocaleIndex(GetDefaultDbcLocale()); // Get once for all the locale index of DBC language (console/broadcasts)
949 sLog.outString( "Loading Page Texts..." );
950 objmgr.LoadPageTexts();
952 sLog.outString( "Loading Game Object Templates..." ); // must be after LoadPageTexts
953 objmgr.LoadGameobjectInfo();
955 sLog.outString( "Loading Spell Chain Data..." );
956 spellmgr.LoadSpellChains();
958 sLog.outString( "Loading Spell Elixir types..." );
959 spellmgr.LoadSpellElixirs();
961 sLog.outString( "Loading Spell Learn Skills..." );
962 spellmgr.LoadSpellLearnSkills(); // must be after LoadSpellChains
964 sLog.outString( "Loading Spell Learn Spells..." );
965 spellmgr.LoadSpellLearnSpells();
967 sLog.outString( "Loading Spell Proc Event conditions..." );
968 spellmgr.LoadSpellProcEvents();
970 sLog.outString( "Loading Aggro Spells Definitions...");
971 spellmgr.LoadSpellThreats();
973 sLog.outString( "Loading NPC Texts..." );
974 objmgr.LoadGossipText();
976 sLog.outString( "Loading Item Random Enchantments Table..." );
977 LoadRandomEnchantmentsTable();
979 sLog.outString( "Loading Items..." ); // must be after LoadRandomEnchantmentsTable and LoadPageTexts
980 objmgr.LoadItemPrototypes();
982 sLog.outString( "Loading Item Texts..." );
983 objmgr.LoadItemTexts();
985 sLog.outString( "Loading Creature Model Based Info Data..." );
986 objmgr.LoadCreatureModelInfo();
988 sLog.outString( "Loading Equipment templates...");
989 objmgr.LoadEquipmentTemplates();
991 sLog.outString( "Loading Creature templates..." );
992 objmgr.LoadCreatureTemplates();
994 sLog.outString( "Loading SpellsScriptTarget...");
995 spellmgr.LoadSpellScriptTarget(); // must be after LoadCreatureTemplates and LoadGameobjectInfo
997 sLog.outString( "Loading Creature Reputation OnKill Data..." );
998 objmgr.LoadReputationOnKill();
1000 sLog.outString( "Loading Pet Create Spells..." );
1001 objmgr.LoadPetCreateSpells();
1003 sLog.outString( "Loading Creature Data..." );
1004 objmgr.LoadCreatures();
1006 sLog.outString( "Loading Creature Addon Data..." );
1007 objmgr.LoadCreatureAddons(); // must be after LoadCreatureTemplates() and LoadCreatures()
1009 sLog.outString( "Loading Creature Respawn Data..." ); // must be after PackInstances()
1010 objmgr.LoadCreatureRespawnTimes();
1012 sLog.outString( "Loading Gameobject Data..." );
1013 objmgr.LoadGameobjects();
1015 sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1016 objmgr.LoadGameobjectRespawnTimes();
1018 sLog.outString( "Loading Game Event Data...");
1019 gameeventmgr.LoadFromDB();
1021 sLog.outString( "Loading Weather Data..." );
1022 objmgr.LoadWeatherZoneChances();
1024 sLog.outString( "Loading Quests..." );
1025 objmgr.LoadQuests(); // must be loaded after DBCs, creature_template, item_template, gameobject tables
1027 sLog.outString( "Loading Quests Relations..." );
1028 objmgr.LoadQuestRelations(); // must be after quest load
1030 sLog.outString( "Loading AreaTrigger definitions..." );
1031 objmgr.LoadAreaTriggerTeleports(); // must be after item template load
1033 sLog.outString( "Loading Quest Area Triggers..." );
1034 objmgr.LoadQuestAreaTriggers(); // must be after LoadQuests
1036 sLog.outString( "Loading Tavern Area Triggers..." );
1037 objmgr.LoadTavernAreaTriggers();
1039 sLog.outString( "Loading AreaTrigger script names..." );
1040 objmgr.LoadAreaTriggerScripts();
1042 sLog.outString( "Loading Graveyard-zone links...");
1043 objmgr.LoadGraveyardZones();
1045 sLog.outString( "Loading Spell target coordinates..." );
1046 spellmgr.LoadSpellTargetPositions();
1048 sLog.outString( "Loading SpellAffect definitions..." );
1049 spellmgr.LoadSpellAffects();
1051 sLog.outString( "Loading spell pet auras..." );
1052 spellmgr.LoadSpellPetAuras();
1054 sLog.outString( "Loading player Create Info & Level Stats..." );
1055 objmgr.LoadPlayerInfo();
1057 sLog.outString( "Loading Exploration BaseXP Data..." );
1058 objmgr.LoadExplorationBaseXP();
1060 sLog.outString( "Loading Pet Name Parts..." );
1061 objmgr.LoadPetNames();
1063 sLog.outString( "Loading the max pet number..." );
1064 objmgr.LoadPetNumber();
1066 sLog.outString( "Loading pet level stats..." );
1067 objmgr.LoadPetLevelInfo();
1069 sLog.outString( "Loading Player Corpses..." );
1070 objmgr.LoadCorpses();
1072 sLog.outString( "Loading Loot Tables..." );
1073 LoadLootTables();
1075 sLog.outString( "Loading Skill Discovery Table..." );
1076 LoadSkillDiscoveryTable();
1078 sLog.outString( "Loading Skill Extra Item Table..." );
1079 LoadSkillExtraItemTable();
1081 sLog.outString( "Loading Skill Fishing base level requirements..." );
1082 objmgr.LoadFishingBaseSkillLevel();
1084 ///- Load dynamic data tables from the database
1085 sLog.outString( "Loading Auctions..." );
1086 objmgr.LoadAuctionItems();
1087 objmgr.LoadAuctions();
1089 sLog.outString( "Loading Guilds..." );
1090 objmgr.LoadGuilds();
1092 sLog.outString( "Loading ArenaTeams..." );
1093 objmgr.LoadArenaTeams();
1095 sLog.outString( "Loading Groups..." );
1096 objmgr.LoadGroups();
1098 sLog.outString( "Loading ReservedNames..." );
1099 objmgr.LoadReservedPlayersNames();
1101 sLog.outString( "Loading GameObject for quests..." );
1102 objmgr.LoadGameObjectForQuests();
1104 sLog.outString( "Loading BattleMasters..." );
1105 objmgr.LoadBattleMastersEntry();
1107 sLog.outString( "Loading GameTeleports..." );
1108 objmgr.LoadGameTele();
1110 sLog.outString( "Loading Npc Text Id..." );
1111 objmgr.LoadNpcTextId(); // must be after load Creature and NpcText
1113 sLog.outString( "Loading vendors..." );
1114 objmgr.LoadVendors(); // must be after load CreatureTemplate and ItemTemplate
1116 sLog.outString( "Loading trainers..." );
1117 objmgr.LoadTrainerSpell(); // must be after load CreatureTemplate
1119 sLog.outString( "Loading Waypoints..." );
1120 WaypointMgr.Load();
1122 ///- Handle outdated emails (delete/return)
1123 sLog.outString( "Returning old mails..." );
1124 objmgr.ReturnOrDeleteOldMails(false);
1126 ///- Load and initialize scripts
1127 sLog.outString( "Loading Scripts..." );
1128 objmgr.LoadQuestStartScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1129 objmgr.LoadQuestEndScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1130 objmgr.LoadSpellScripts(); // must be after load Creature/Gameobject(Template/Data)
1131 objmgr.LoadGameObjectScripts(); // must be after load Creature/Gameobject(Template/Data)
1132 objmgr.LoadEventScripts(); // must be after load Creature/Gameobject(Template/Data)
1134 sLog.outString( "Initializing Scripts..." );
1135 if(!LoadScriptingModule())
1136 exit(1);
1138 ///- Initialize game time and timers
1139 sLog.outString( "DEBUG:: Initialize game time and timers" );
1140 m_gameTime = time(NULL);
1141 m_startTime=m_gameTime;
1143 tm local;
1144 time_t curr;
1145 time(&curr);
1146 local=*(localtime(&curr)); // dereference and assign
1147 char isoDate[128];
1148 sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1149 local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1151 WorldDatabase.PExecute("INSERT INTO uptime (startstring, starttime, uptime) VALUES('%s', %ld, 0)", isoDate, m_startTime );
1153 m_timers[WUPDATE_OBJECTS].SetInterval(0);
1154 m_timers[WUPDATE_SESSIONS].SetInterval(0);
1155 m_timers[WUPDATE_WEATHERS].SetInterval(1000);
1156 m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*1000); //set auction update interval to 1 minute
1157 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
1158 //Update "uptime" table based on configuration entry in minutes.
1159 m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*1000); //erase corpses every 20 minutes
1161 //to set mailtimer to return mails every day between 4 and 5 am
1162 //mailtimer is increased when updating auctions
1163 //one second is 1000 -(tested on win system)
1164 mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * 1000) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1165 //1440
1166 mail_timer_expires = ( (DAY * 1000) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1167 sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1169 ///- Initilize static helper structures
1170 AIRegistry::Initialize();
1171 WaypointMovementGenerator<Creature>::Initialize();
1172 Player::InitVisibleBits();
1174 ///- Initialize MapManager
1175 sLog.outString( "Starting Map System" );
1176 MapManager::Instance().Initialize();
1178 ///- Initialize Battlegrounds
1179 sLog.outString( "Starting BattleGround System" );
1180 sBattleGroundMgr.CreateInitialBattleGrounds();
1182 //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1183 sLog.outString( "Loading Transports..." );
1184 MapManager::Instance().LoadTransports();
1186 sLog.outString("Deleting expired bans..." );
1187 loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1189 sLog.outString("Calculate next daily quest reset time..." );
1190 InitDailyQuestResetTime();
1192 sLog.outString("Starting Game Event system..." );
1193 uint32 nextGameEvent = gameeventmgr.Initialize();
1194 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent); //depend on next event
1196 sLog.outString( "WORLD: World initialized" );
1199 void World::DetectDBCLang()
1201 uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1203 if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1205 sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1206 m_lang_confid = LOCALE_enUS;
1209 ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1211 std::string availableLocalsStr;
1213 int default_locale = MAX_LOCALE;
1214 for (int i = MAX_LOCALE-1; i >= 0; --i)
1216 if ( strlen(race->name[i]) > 0) // check by race names
1218 default_locale = i;
1219 m_availableDbcLocaleMask |= (1 << i);
1220 availableLocalsStr += localeNames[i];
1221 availableLocalsStr += " ";
1225 if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1226 (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1228 default_locale = m_lang_confid;
1231 if(default_locale >= MAX_LOCALE)
1233 sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1234 exit(1);
1237 m_defaultDbcLocale = LocaleConstant(default_locale);
1239 sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1242 /// Update the World !
1243 void World::Update(time_t diff)
1245 ///- Update the different timers
1246 for(int i = 0; i < WUPDATE_COUNT; i++)
1247 if(m_timers[i].GetCurrent()>=0)
1248 m_timers[i].Update(diff);
1249 else m_timers[i].SetCurrent(0);
1251 ///- Update the game time and check for shutdown time
1252 _UpdateGameTime();
1254 /// Handle daily quests reset time
1255 if(m_gameTime > m_NextDailyQuestReset)
1257 ResetDailyQuests();
1258 m_NextDailyQuestReset += DAY;
1261 /// <ul><li> Handle auctions when the timer has passed
1262 if (m_timers[WUPDATE_AUCTIONS].Passed())
1264 m_timers[WUPDATE_AUCTIONS].Reset();
1266 ///- Update mails (return old mails with item, or delete them)
1267 //(tested... works on win)
1268 if (++mail_timer > mail_timer_expires)
1270 mail_timer = 0;
1271 objmgr.ReturnOrDeleteOldMails(true);
1274 AuctionHouseObject* AuctionMap;
1275 for (int i = 0; i < 3; i++)
1277 switch (i)
1279 case 0:
1280 AuctionMap = objmgr.GetAuctionsMap( 6 );//horde
1281 break;
1282 case 1:
1283 AuctionMap = objmgr.GetAuctionsMap( 2 );//alliance
1284 break;
1285 case 2:
1286 AuctionMap = objmgr.GetAuctionsMap( 7 );//neutral
1287 break;
1290 ///- Handle expired auctions
1291 AuctionHouseObject::AuctionEntryMap::iterator itr,next;
1292 for (itr = AuctionMap->GetAuctionsBegin(); itr != AuctionMap->GetAuctionsEnd();itr = next)
1294 next = itr;
1295 ++next;
1296 if (m_gameTime > (itr->second->time))
1298 ///- Either cancel the auction if there was no bidder
1299 if (itr->second->bidder == 0)
1301 objmgr.SendAuctionExpiredMail( itr->second );
1303 ///- Or perform the transaction
1304 else
1306 //we should send an "item sold" message if the seller is online
1307 //we send the item to the winner
1308 //we send the money to the seller
1309 objmgr.SendAuctionSuccessfulMail( itr->second );
1310 objmgr.SendAuctionWonMail( itr->second );
1313 ///- In any case clear the auction
1314 //No SQL injection (Id is integer)
1315 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",itr->second->Id);
1316 objmgr.RemoveAItem(itr->second->item_guidlow);
1317 delete itr->second;
1318 AuctionMap->RemoveAuction(itr->first);
1324 /// <li> Handle session updates when the timer has passed
1325 if (m_timers[WUPDATE_SESSIONS].Passed())
1327 m_timers[WUPDATE_SESSIONS].Reset();
1329 UpdateSessions(diff);
1332 /// <li> Handle weather updates when the timer has passed
1333 if (m_timers[WUPDATE_WEATHERS].Passed())
1335 m_timers[WUPDATE_WEATHERS].Reset();
1337 ///- Send an update signal to Weather objects
1338 WeatherMap::iterator itr, next;
1339 for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1341 next = itr;
1342 ++next;
1344 ///- and remove Weather objects for zones with no player
1345 //As interval > WorldTick
1346 if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1348 delete itr->second;
1349 m_weathers.erase(itr);
1353 /// <li> Update uptime table
1354 if (m_timers[WUPDATE_UPTIME].Passed())
1356 uint32 tmpDiff = (m_gameTime - m_startTime);
1357 uint32 maxClientsNum = sWorld.GetMaxActiveSessionCount();
1359 m_timers[WUPDATE_UPTIME].Reset();
1360 WorldDatabase.PExecute("UPDATE uptime SET uptime = %d, maxplayers = %d WHERE starttime = " I64FMTD, tmpDiff, maxClientsNum, uint64(m_startTime));
1363 /// <li> Handle all other objects
1364 if (m_timers[WUPDATE_OBJECTS].Passed())
1366 m_timers[WUPDATE_OBJECTS].Reset();
1367 ///- Update objects when the timer has passed (maps, transport, creatures,...)
1368 MapManager::Instance().Update(diff); // As interval = 0
1370 ///- Process necessary scripts
1371 if (!m_scriptSchedule.empty())
1372 ScriptsProcess();
1374 sBattleGroundMgr.Update(diff);
1377 // execute callbacks from sql queries that were queued recently
1378 UpdateResultQueue();
1380 ///- Erase corpses once every 20 minutes
1381 if (m_timers[WUPDATE_CORPSES].Passed())
1383 m_timers[WUPDATE_CORPSES].Reset();
1385 CorpsesErase();
1388 ///- Process Game events when necessary
1389 if (m_timers[WUPDATE_EVENTS].Passed())
1391 m_timers[WUPDATE_EVENTS].Reset(); // to give time for Update() to be processed
1392 uint32 nextGameEvent = gameeventmgr.Update();
1393 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1394 m_timers[WUPDATE_EVENTS].Reset();
1397 /// </ul>
1398 ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1399 MapManager::Instance().DoDelayedMovesAndRemoves();
1401 // update the instance reset times
1402 sInstanceSaveManager.Update();
1404 // And last, but not least handle the issued cli commands
1405 ProcessCliCommands();
1408 /// Put scripts in the execution queue
1409 void World::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
1411 ///- Find the script map
1412 ScriptMapMap::const_iterator s = scripts.find(id);
1413 if (s == scripts.end())
1414 return;
1416 // prepare static data
1417 uint64 sourceGUID = source->GetGUID();
1418 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1419 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1421 ///- Schedule script execution for all scripts in the script map
1422 ScriptMap const *s2 = &(s->second);
1423 bool immedScript = false;
1424 for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
1426 ScriptAction sa;
1427 sa.sourceGUID = sourceGUID;
1428 sa.targetGUID = targetGUID;
1429 sa.ownerGUID = ownerGUID;
1431 sa.script = &iter->second;
1432 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + iter->first, sa));
1433 if (iter->first == 0)
1434 immedScript = true;
1436 ///- If one of the effects should be immediate, launch the script execution
1437 if (immedScript)
1438 ScriptsProcess();
1441 void World::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
1443 // NOTE: script record _must_ exist until command executed
1445 // prepare static data
1446 uint64 sourceGUID = source->GetGUID();
1447 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1448 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1450 ScriptAction sa;
1451 sa.sourceGUID = sourceGUID;
1452 sa.targetGUID = targetGUID;
1453 sa.ownerGUID = ownerGUID;
1455 sa.script = &script;
1456 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + delay, sa));
1458 ///- If effects should be immediate, launch the script execution
1459 if(delay == 0)
1460 ScriptsProcess();
1463 /// Process queued scripts
1464 void World::ScriptsProcess()
1466 if (m_scriptSchedule.empty())
1467 return;
1469 ///- Process overdue queued scripts
1470 std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
1471 // ok as multimap is a *sorted* associative container
1472 while (!m_scriptSchedule.empty() && (iter->first <= m_gameTime))
1474 ScriptAction const& step = iter->second;
1476 Object* source = NULL;
1478 if(step.sourceGUID)
1480 switch(GUID_HIPART(step.sourceGUID))
1482 case HIGHGUID_ITEM:
1483 // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1485 Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
1486 if(player)
1487 source = player->GetItemByGuid(step.sourceGUID);
1488 break;
1490 case HIGHGUID_UNIT:
1491 source = HashMapHolder<Creature>::Find(step.sourceGUID);
1492 break;
1493 case HIGHGUID_PET:
1494 source = HashMapHolder<Pet>::Find(step.sourceGUID);
1495 break;
1496 case HIGHGUID_PLAYER:
1497 source = HashMapHolder<Player>::Find(step.sourceGUID);
1498 break;
1499 case HIGHGUID_GAMEOBJECT:
1500 source = HashMapHolder<GameObject>::Find(step.sourceGUID);
1501 break;
1502 case HIGHGUID_CORPSE:
1503 source = HashMapHolder<Corpse>::Find(step.sourceGUID);
1504 break;
1505 default:
1506 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
1507 break;
1511 Object* target = NULL;
1513 if(step.targetGUID)
1515 switch(GUID_HIPART(step.targetGUID))
1517 case HIGHGUID_UNIT:
1518 target = HashMapHolder<Creature>::Find(step.targetGUID);
1519 break;
1520 case HIGHGUID_PET:
1521 target = HashMapHolder<Pet>::Find(step.targetGUID);
1522 break;
1523 case HIGHGUID_PLAYER: // empty GUID case also
1524 target = HashMapHolder<Player>::Find(step.targetGUID);
1525 break;
1526 case HIGHGUID_GAMEOBJECT:
1527 target = HashMapHolder<GameObject>::Find(step.targetGUID);
1528 break;
1529 case HIGHGUID_CORPSE:
1530 target = HashMapHolder<Corpse>::Find(step.targetGUID);
1531 break;
1532 default:
1533 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
1534 break;
1538 switch (step.script->command)
1540 case SCRIPT_COMMAND_TALK:
1542 if(!source)
1544 sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1545 break;
1548 if(source->GetTypeId()!=TYPEID_UNIT)
1550 sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1551 break;
1553 if(step.script->datalong > 3)
1555 sLog.outError("SCRIPT_COMMAND_TALK invalid chat type (%u), skipping.",step.script->datalong);
1556 break;
1559 uint64 unit_target = target ? target->GetGUID() : 0;
1561 //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1562 switch(step.script->datalong)
1564 case 0: // Say
1565 ((Creature *)source)->Say(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
1566 break;
1567 case 1: // Whisper
1568 if(!unit_target)
1570 sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
1571 break;
1573 ((Creature *)source)->Whisper(step.script->datatext.c_str(),unit_target);
1574 break;
1575 case 2: // Yell
1576 ((Creature *)source)->Yell(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
1577 break;
1578 case 3: // Emote text
1579 ((Creature *)source)->TextEmote(step.script->datatext.c_str(), unit_target);
1580 break;
1581 default:
1582 break; // must be already checked at load
1584 break;
1587 case SCRIPT_COMMAND_EMOTE:
1588 if(!source)
1590 sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1591 break;
1594 if(source->GetTypeId()!=TYPEID_UNIT)
1596 sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1597 break;
1600 ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
1601 break;
1602 case SCRIPT_COMMAND_FIELD_SET:
1603 if(!source)
1605 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1606 break;
1608 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1610 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1611 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1612 break;
1615 source->SetUInt32Value(step.script->datalong, step.script->datalong2);
1616 break;
1617 case SCRIPT_COMMAND_MOVE_TO:
1618 if(!source)
1620 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1621 break;
1624 if(source->GetTypeId()!=TYPEID_UNIT)
1626 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1627 break;
1629 ((Unit *)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, ((Unit *)source)->GetUnitMovementFlags(), step.script->datalong2 );
1630 MapManager::Instance().GetMap(((Unit *)source)->GetMapId(), ((Unit *)source))->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
1631 break;
1632 case SCRIPT_COMMAND_FLAG_SET:
1633 if(!source)
1635 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1636 break;
1638 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1640 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1641 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1642 break;
1645 source->SetFlag(step.script->datalong, step.script->datalong2);
1646 break;
1647 case SCRIPT_COMMAND_FLAG_REMOVE:
1648 if(!source)
1650 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1651 break;
1653 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1655 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1656 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1657 break;
1660 source->RemoveFlag(step.script->datalong, step.script->datalong2);
1661 break;
1663 case SCRIPT_COMMAND_TELEPORT_TO:
1665 // accept player in any one from target/source arg
1666 if (!target && !source)
1668 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1669 break;
1672 // must be only Player
1673 if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
1675 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
1676 break;
1679 Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
1681 pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
1682 break;
1685 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
1687 if(!step.script->datalong) // creature not specified
1689 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1690 break;
1693 if(!source)
1695 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1696 break;
1699 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1701 if(!summoner)
1703 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1704 break;
1707 float x = step.script->x;
1708 float y = step.script->y;
1709 float z = step.script->z;
1710 float o = step.script->o;
1712 Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
1713 if (!pCreature)
1715 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
1716 break;
1719 break;
1722 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
1724 if(!step.script->datalong) // gameobject not specified
1726 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1727 break;
1730 if(!source)
1732 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1733 break;
1736 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1738 if(!summoner)
1740 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1741 break;
1744 GameObject *go = NULL;
1745 int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
1747 CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
1748 Cell cell(p);
1749 cell.data.Part.reserved = ALL_DISTRICT;
1751 MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
1752 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(go,go_check);
1754 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1755 CellLock<GridReadGuard> cell_lock(cell, p);
1756 cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(summoner->GetMapId(), summoner));
1758 if ( !go )
1760 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
1761 break;
1764 if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1765 go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1766 go->GetGoType()==GAMEOBJECT_TYPE_DOOR ||
1767 go->GetGoType()==GAMEOBJECT_TYPE_BUTTON ||
1768 go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
1770 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
1771 break;
1774 if( go->isSpawned() )
1775 break; //gameobject already spawned
1777 go->SetLootState(GO_READY);
1778 go->SetRespawnTime(time_to_despawn); //despawn object in ? seconds
1780 MapManager::Instance().GetMap(go->GetMapId(), go)->Add(go);
1781 break;
1783 case SCRIPT_COMMAND_OPEN_DOOR:
1785 if(!step.script->datalong) // door not specified
1787 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1788 break;
1791 if(!source)
1793 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1794 break;
1797 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
1799 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1800 break;
1803 Unit* caster = (Unit*)source;
1805 GameObject *door = NULL;
1806 int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1808 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1809 Cell cell(p);
1810 cell.data.Part.reserved = ALL_DISTRICT;
1812 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1813 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1815 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1816 CellLock<GridReadGuard> cell_lock(cell, p);
1817 cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1819 if ( !door )
1821 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1822 break;
1824 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1826 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1827 break;
1830 if( !door->GetGoState() )
1831 break; //door already open
1833 door->UseDoorOrButton(time_to_close);
1835 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1836 ((GameObject*)target)->UseDoorOrButton(time_to_close);
1837 break;
1839 case SCRIPT_COMMAND_CLOSE_DOOR:
1841 if(!step.script->datalong) // guid for door not specified
1843 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
1844 break;
1847 if(!source)
1849 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
1850 break;
1853 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
1855 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1856 break;
1859 Unit* caster = (Unit*)source;
1861 GameObject *door = NULL;
1862 int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1864 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1865 Cell cell(p);
1866 cell.data.Part.reserved = ALL_DISTRICT;
1868 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1869 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1871 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1872 CellLock<GridReadGuard> cell_lock(cell, p);
1873 cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1875 if ( !door )
1877 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1878 break;
1880 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1882 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1883 break;
1886 if( door->GetGoState() )
1887 break; //door already closed
1889 door->UseDoorOrButton(time_to_open);
1891 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1892 ((GameObject*)target)->UseDoorOrButton(time_to_open);
1894 break;
1896 case SCRIPT_COMMAND_QUEST_EXPLORED:
1898 if(!source)
1900 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
1901 break;
1904 if(!target)
1906 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
1907 break;
1910 // when script called for item spell casting then target == (unit or GO) and source is player
1911 WorldObject* worldObject;
1912 Player* player;
1914 if(target->GetTypeId()==TYPEID_PLAYER)
1916 if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
1918 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
1919 break;
1922 worldObject = (WorldObject*)source;
1923 player = (Player*)target;
1925 else
1927 if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
1929 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
1930 break;
1933 if(source->GetTypeId()!=TYPEID_PLAYER)
1935 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
1936 break;
1939 worldObject = (WorldObject*)target;
1940 player = (Player*)source;
1943 // quest id and flags checked at script loading
1944 if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
1945 (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
1946 player->AreaExploredOrEventHappens(step.script->datalong);
1947 else
1948 player->FailQuest(step.script->datalong);
1950 break;
1953 case SCRIPT_COMMAND_ACTIVATE_OBJECT:
1955 if(!source)
1957 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
1958 break;
1961 if(!source->isType(TYPEMASK_UNIT))
1963 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
1964 break;
1967 if(!target)
1969 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
1970 break;
1973 if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
1975 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
1976 break;
1979 Unit* caster = (Unit*)source;
1981 GameObject *go = (GameObject*)target;
1983 go->Use(caster);
1984 break;
1987 case SCRIPT_COMMAND_REMOVE_AURA:
1989 Object* cmdTarget = step.script->datalong2 ? source : target;
1991 if(!cmdTarget)
1993 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
1994 break;
1997 if(!cmdTarget->isType(TYPEMASK_UNIT))
1999 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2000 break;
2003 ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
2004 break;
2007 case SCRIPT_COMMAND_CAST_SPELL:
2009 if(!source)
2011 sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
2012 break;
2015 if(!source->isType(TYPEMASK_UNIT))
2017 sLog.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2018 break;
2021 Object* cmdTarget = step.script->datalong2 ? source : target;
2023 if(!cmdTarget)
2025 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 ? "source" : "target");
2026 break;
2029 if(!cmdTarget->isType(TYPEMASK_UNIT))
2031 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2032 break;
2035 Unit* spellTarget = (Unit*)cmdTarget;
2037 //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2038 ((Unit*)source)->CastSpell(spellTarget,step.script->datalong,false);
2040 break;
2043 default:
2044 sLog.outError("Unknown script command %u called.",step.script->command);
2045 break;
2048 m_scriptSchedule.erase(iter);
2050 iter = m_scriptSchedule.begin();
2052 return;
2055 /// Send a packet to all players (except self if mentioned)
2056 void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
2058 SessionMap::iterator itr;
2059 for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2061 if (itr->second &&
2062 itr->second->GetPlayer() &&
2063 itr->second->GetPlayer()->IsInWorld() &&
2064 itr->second != self &&
2065 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2067 itr->second->SendPacket(packet);
2072 /// Send a System Message to all players (except self if mentioned)
2073 void World::SendWorldText(int32 string_id, ...)
2075 std::vector<std::vector<WorldPacket*> > data_cache; // 0 = default, i => i-1 locale index
2077 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2079 if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
2080 continue;
2082 uint32 loc_idx = itr->second->GetSessionDbLocaleIndex();
2083 uint32 cache_idx = loc_idx+1;
2085 std::vector<WorldPacket*>* data_list;
2087 // create if not cached yet
2088 if(data_cache.size() < cache_idx+1 || data_cache[cache_idx].empty())
2090 if(data_cache.size() < cache_idx+1)
2091 data_cache.resize(cache_idx+1);
2093 data_list = &data_cache[cache_idx];
2095 char const* text = objmgr.GetMangosString(string_id,loc_idx);
2097 char buf[1000];
2099 va_list argptr;
2100 va_start( argptr, string_id );
2101 vsnprintf( buf,1000, text, argptr );
2102 va_end( argptr );
2104 char* pos = &buf[0];
2106 while(char* line = ChatHandler::LineFromMessage(pos))
2108 WorldPacket* data = new WorldPacket();
2109 ChatHandler::FillMessageData(data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2110 data_list->push_back(data);
2113 else
2114 data_list = &data_cache[cache_idx];
2116 for(int i = 0; i < data_list->size(); ++i)
2117 itr->second->SendPacket((*data_list)[i]);
2120 // free memory
2121 for(int i = 0; i < data_cache.size(); ++i)
2122 for(int j = 0; j < data_cache[i].size(); ++j)
2123 delete data_cache[i][j];
2126 /// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2127 void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
2129 SessionMap::iterator itr;
2130 for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2132 if (itr->second &&
2133 itr->second->GetPlayer() &&
2134 itr->second->GetPlayer()->IsInWorld() &&
2135 itr->second->GetPlayer()->GetZoneId() == zone &&
2136 itr->second != self &&
2137 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2139 itr->second->SendPacket(packet);
2144 /// Send a System Message to all players in the zone (except self if mentioned)
2145 void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
2147 WorldPacket data;
2148 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
2149 SendZoneMessage(zone, &data, self,team);
2152 /// Kick (and save) all players
2153 void World::KickAll()
2155 // session not removed at kick and will removed in next update tick
2156 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2157 itr->second->KickPlayer();
2160 /// Kick (and save) all players with security level less `sec`
2161 void World::KickAllLess(AccountTypes sec)
2163 // session not removed at kick and will removed in next update tick
2164 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2165 if(itr->second->GetSecurity() < sec)
2166 itr->second->KickPlayer();
2169 /// Kick all queued players
2170 void World::KickAllQueued()
2172 // session not removed at kick and will removed in next update tick
2173 //TODO here
2174 // for (Queue::iterator itr = m_QueuedPlayer.begin(); itr != m_QueuedPlayer.end(); ++itr)
2175 // if(WorldSession* session = (*itr)->GetSession())
2176 // session->KickPlayer();
2178 m_QueuedPlayer.empty();
2181 /// Kick (and save) the designated player
2182 bool World::KickPlayer(std::string playerName)
2184 SessionMap::iterator itr;
2186 // session not removed at kick and will removed in next update tick
2187 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2189 if(!itr->second)
2190 continue;
2191 Player *player = itr->second->GetPlayer();
2192 if(!player)
2193 continue;
2194 if( player->IsInWorld() )
2196 if (playerName == player->GetName())
2198 itr->second->KickPlayer();
2199 return true;
2203 return false;
2206 /// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2207 uint8 World::BanAccount(std::string type, std::string nameOrIP, std::string duration, std::string reason, std::string author)
2209 loginDatabase.escape_string(nameOrIP);
2210 loginDatabase.escape_string(reason);
2211 std::string safe_author=author;
2212 loginDatabase.escape_string(safe_author);
2214 if(type != "ip" && !normalizePlayerName(nameOrIP))
2215 return BAN_NOTFOUND; // Nobody to ban
2217 uint32 duration_secs = TimeStringToSecs(duration);
2218 QueryResult *resultAccounts = NULL; //used for kicking
2220 ///- Update the database with ban information
2222 if(type=="ip")
2224 //No SQL injection as strings are escaped
2225 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
2226 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());
2228 else if(type=="account")
2230 //No SQL injection as string is escaped
2231 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2233 else if(type=="character")
2235 //No SQL injection as string is escaped
2236 resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2238 else
2239 return BAN_SYNTAX_ERROR; //Syntax problem
2241 if(!resultAccounts)
2242 if(type=="ip")
2243 return BAN_SUCCESS; // ip correctly banned but nobody affected (yet)
2244 else
2245 return BAN_NOTFOUND; // Nobody to ban
2247 ///- Disconnect all affected players (for IP it can be several)
2250 Field* fieldsAccount = resultAccounts->Fetch();
2251 uint32 account = fieldsAccount->GetUInt32();
2253 if(type != "ip")
2254 //No SQL injection as strings are escaped
2255 loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2256 account,duration_secs,safe_author.c_str(),reason.c_str());
2258 WorldSession* sess = FindSession(account);
2259 if( sess )
2260 if(std::string(sess->GetPlayerName()) != author)
2261 sess->KickPlayer();
2263 while( resultAccounts->NextRow() );
2265 delete resultAccounts;
2266 return BAN_SUCCESS;
2269 /// Remove a ban from an account or IP address
2270 bool World::RemoveBanAccount(std::string type, std::string nameOrIP)
2272 if(type == "ip")
2274 loginDatabase.escape_string(nameOrIP);
2275 loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
2277 else
2279 uint32 account=0;
2280 if(type == "account")
2282 //NO SQL injection as name is escaped
2283 loginDatabase.escape_string(nameOrIP);
2284 QueryResult *resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2285 if(!resultAccounts)
2286 return false;
2287 Field* fieldsAccount = resultAccounts->Fetch();
2288 account = fieldsAccount->GetUInt32();
2290 delete resultAccounts;
2292 else if(type == "character")
2294 if(!normalizePlayerName(nameOrIP))
2295 return false;
2297 //NO SQL injection as name is escaped
2298 loginDatabase.escape_string(nameOrIP);
2299 QueryResult *resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2300 if(!resultAccounts)
2301 return false;
2302 Field* fieldsAccount = resultAccounts->Fetch();
2303 account = fieldsAccount->GetUInt32();
2305 delete resultAccounts;
2307 if(!account)
2308 return false;
2309 //NO SQL injection as account is uint32
2310 loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
2312 return true;
2315 /// Update the game time
2316 void World::_UpdateGameTime()
2318 ///- update the time
2319 time_t thisTime = time(NULL);
2320 uint32 elapsed = uint32(thisTime - m_gameTime);
2321 m_gameTime = thisTime;
2323 ///- if there is a shutdown timer
2324 if(m_ShutdownTimer > 0 && elapsed > 0)
2326 ///- ... and it is overdue, stop the world (set m_stopEvent)
2327 if( m_ShutdownTimer <= elapsed )
2329 if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2330 m_stopEvent = true;
2331 else
2332 m_ShutdownTimer = 1; // minimum timer value to wait idle state
2334 ///- ... else decrease it and if necessary display a shutdown countdown to the users
2335 else
2337 m_ShutdownTimer -= elapsed;
2339 ShutdownMsg();
2344 /// Shutdown the server
2345 void World::ShutdownServ(uint32 time, uint32 options)
2347 m_ShutdownMask = options;
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;
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 if(!m_ShutdownTimer)
2399 return;
2401 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2403 m_ShutdownMask = 0;
2404 m_ShutdownTimer = 0;
2405 SendServerMessage(msgid);
2407 DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2410 /// Send a server message to the user(s)
2411 void World::SendServerMessage(uint32 type, const char *text, Player* player)
2413 WorldPacket data(SMSG_SERVER_MESSAGE, 50); // guess size
2414 data << uint32(type);
2415 if(type <= SERVER_MSG_STRING)
2416 data << text;
2418 if(player)
2419 player->GetSession()->SendPacket(&data);
2420 else
2421 SendGlobalMessage( &data );
2424 void World::UpdateSessions( time_t diff )
2426 while(!addSessQueue.empty())
2428 WorldSession* sess = addSessQueue.next ();
2429 AddSession_ (sess);
2432 ///- Delete kicked sessions at add new session
2433 for (std::set<WorldSession*>::iterator itr = m_kicked_sessions.begin(); itr != m_kicked_sessions.end(); ++itr)
2434 delete *itr;
2435 m_kicked_sessions.clear();
2437 ///- Then send an update signal to remaining ones
2438 for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2440 next = itr;
2441 ++next;
2443 if(!itr->second)
2444 continue;
2446 ///- and remove not active sessions from the list
2447 if(!itr->second->Update(diff)) // As interval = 0
2449 delete itr->second;
2450 m_sessions.erase(itr);
2455 // This handles the issued and queued CLI commands
2456 void World::ProcessCliCommands()
2458 if (cliCmdQueue.empty()) return;
2460 CliCommandHolder *command;
2461 pPrintf p_zprintf;
2462 while (!cliCmdQueue.empty())
2464 sLog.outDebug("CLI command under processing...");
2465 command = cliCmdQueue.next();
2466 command->Execute();
2467 p_zprintf=command->GetOutputMethod();
2468 delete command;
2470 // print the console message here so it looks right
2471 p_zprintf("mangos>");
2474 void World::InitResultQueue()
2476 m_resultQueue = new SqlResultQueue;
2477 CharacterDatabase.SetResultQueue(m_resultQueue);
2480 void World::UpdateResultQueue()
2482 m_resultQueue->Update();
2485 void World::UpdateRealmCharCount(uint32 accountId)
2487 CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2488 "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2491 void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2493 if (resultCharCount)
2495 Field *fields = resultCharCount->Fetch();
2496 uint32 charCount = fields[0].GetUInt32();
2497 delete resultCharCount;
2498 loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2499 loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2503 void World::InitDailyQuestResetTime()
2505 time_t mostRecentQuestTime;
2507 QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2508 if(result)
2510 Field *fields = result->Fetch();
2512 mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2513 delete result;
2515 else
2516 mostRecentQuestTime = 0;
2518 // client built-in time for reset is 6:00 AM
2519 // FIX ME: client not show day start time
2520 time_t curTime = time(NULL);
2521 tm localTm = *localtime(&curTime);
2522 localTm.tm_hour = 6;
2523 localTm.tm_min = 0;
2524 localTm.tm_sec = 0;
2526 // current day reset time
2527 time_t curDayResetTime = mktime(&localTm);
2529 // last reset time before current moment
2530 time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2532 // need reset (if we have quest time before last reset time (not processed by some reason)
2533 if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2534 m_NextDailyQuestReset = mostRecentQuestTime;
2535 else
2537 // plan next reset time
2538 m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2542 void World::ResetDailyQuests()
2544 sLog.outDetail("Daily quests reset for all characters.");
2545 CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2546 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2547 if(itr->second->GetPlayer())
2548 itr->second->GetPlayer()->ResetDailyQuestStatus();
2551 void World::SetPlayerLimit( int32 limit, bool needUpdate )
2553 if(limit < -SEC_ADMINISTRATOR)
2554 limit = -SEC_ADMINISTRATOR;
2556 // lock update need
2557 bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2559 m_playerLimit = limit;
2561 if(db_update_need)
2562 loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2565 void World::UpdateMaxSessionCounters()
2567 m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2568 m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));