Merge branch 'master' into 303
[getmangos.git] / src / game / World.cpp
blob1e29ffc55c281fdea383a67c952e276e6feab653
1 /*
2 * Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 /** \file
20 \ingroup world
23 #include "Common.h"
24 //#include "WorldSocket.h"
25 #include "Database/DatabaseEnv.h"
26 #include "Config/ConfigEnv.h"
27 #include "SystemConfig.h"
28 #include "Log.h"
29 #include "Opcodes.h"
30 #include "WorldSession.h"
31 #include "WorldPacket.h"
32 #include "Weather.h"
33 #include "Player.h"
34 #include "SkillExtraItems.h"
35 #include "SkillDiscovery.h"
36 #include "World.h"
37 #include "AccountMgr.h"
38 #include "ObjectMgr.h"
39 #include "SpellMgr.h"
40 #include "Chat.h"
41 #include "Database/DBCStores.h"
42 #include "LootMgr.h"
43 #include "ItemEnchantmentMgr.h"
44 #include "MapManager.h"
45 #include "ScriptCalls.h"
46 #include "CreatureAIRegistry.h"
47 #include "Policies/SingletonImp.h"
48 #include "BattleGroundMgr.h"
49 #include "TemporarySummon.h"
50 #include "WaypointMovementGenerator.h"
51 #include "VMapFactory.h"
52 #include "GlobalEvents.h"
53 #include "GameEvent.h"
54 #include "Database/DatabaseImpl.h"
55 #include "GridNotifiersImpl.h"
56 #include "CellImpl.h"
57 #include "InstanceSaveMgr.h"
58 #include "WaypointManager.h"
59 #include "Util.h"
61 INSTANTIATE_SINGLETON_1( World );
63 volatile bool World::m_stopEvent = false;
64 volatile uint32 World::m_worldLoopCounter = 0;
66 float World::m_MaxVisibleDistanceForCreature = DEFAULT_VISIBILITY_DISTANCE;
67 float World::m_MaxVisibleDistanceForPlayer = DEFAULT_VISIBILITY_DISTANCE;
68 float World::m_MaxVisibleDistanceForObject = DEFAULT_VISIBILITY_DISTANCE;
69 float World::m_MaxVisibleDistanceInFlight = DEFAULT_VISIBILITY_DISTANCE;
70 float World::m_VisibleUnitGreyDistance = 0;
71 float World::m_VisibleObjectGreyDistance = 0;
73 // ServerMessages.dbc
74 enum ServerMessageType
76 SERVER_MSG_SHUTDOWN_TIME = 1,
77 SERVER_MSG_RESTART_TIME = 2,
78 SERVER_MSG_STRING = 3,
79 SERVER_MSG_SHUTDOWN_CANCELLED = 4,
80 SERVER_MSG_RESTART_CANCELLED = 5
83 struct ScriptAction
85 uint64 sourceGUID;
86 uint64 targetGUID;
87 uint64 ownerGUID; // owner of source if source is item
88 ScriptInfo const* script; // pointer to static script data
91 /// World constructor
92 World::World()
94 m_playerLimit = 0;
95 m_allowMovement = true;
96 m_ShutdownMask = 0;
97 m_ShutdownTimer = 0;
98 m_gameTime=time(NULL);
99 m_startTime=m_gameTime;
100 m_maxActiveSessionCount = 0;
101 m_maxQueuedSessionCount = 0;
102 m_resultQueue = NULL;
103 m_NextDailyQuestReset = 0;
105 m_defaultDbcLocale = LOCALE_enUS;
106 m_availableDbcLocaleMask = 0;
109 /// World destructor
110 World::~World()
112 ///- Empty the kicked session set
113 for (std::set<WorldSession*>::iterator itr = m_kicked_sessions.begin(); itr != m_kicked_sessions.end(); ++itr)
114 delete *itr;
116 m_kicked_sessions.clear();
118 ///- Empty the WeatherMap
119 for (WeatherMap::iterator itr = m_weathers.begin(); itr != m_weathers.end(); ++itr)
120 delete itr->second;
122 m_weathers.clear();
124 VMAP::VMapFactory::clear();
126 if(m_resultQueue) delete m_resultQueue;
128 //TODO free addSessQueue
131 /// Find a player in a specified zone
132 Player* World::FindPlayerInZone(uint32 zone)
134 ///- circle through active sessions and return the first player found in the zone
135 SessionMap::iterator itr;
136 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
138 if(!itr->second)
139 continue;
140 Player *player = itr->second->GetPlayer();
141 if(!player)
142 continue;
143 if( player->IsInWorld() && player->GetZoneId() == zone )
145 // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone.
146 return player;
149 return NULL;
152 /// Find a session by its id
153 WorldSession* World::FindSession(uint32 id) const
155 SessionMap::const_iterator itr = m_sessions.find(id);
157 if(itr != m_sessions.end())
158 return itr->second; // also can return NULL for kicked session
159 else
160 return NULL;
163 /// Remove a given session
164 bool World::RemoveSession(uint32 id)
166 ///- Find the session, kick the user, but we can't delete session at this moment to prevent iterator invalidation
167 SessionMap::iterator itr = m_sessions.find(id);
169 if(itr != m_sessions.end() && itr->second)
171 if (itr->second->PlayerLoading())
172 return false;
173 itr->second->KickPlayer();
176 return true;
179 void World::AddSession(WorldSession* s)
181 addSessQueue.add(s);
184 void
185 World::AddSession_ (WorldSession* s)
187 ASSERT (s);
189 //NOTE - Still there is race condition in WorldSession* being used in the Sockets
191 ///- kick already loaded player with same account (if any) and remove session
192 ///- if player is in loading and want to load again, return
193 if (!RemoveSession (s->GetAccountId ()))
195 s->KickPlayer ();
196 m_kicked_sessions.insert (s);
197 return;
200 WorldSession* old = m_sessions[s->GetAccountId ()];
201 m_sessions[s->GetAccountId ()] = s;
203 // if session already exist, prepare to it deleting at next world update
204 // NOTE - KickPlayer() should be called on "old" in RemoveSession()
205 if (old)
206 m_kicked_sessions.insert (old);
208 uint32 Sessions = GetActiveAndQueuedSessionCount ();
209 uint32 pLimit = GetPlayerAmountLimit ();
210 uint32 QueueSize = GetQueueSize (); //number of players in the queue
211 bool inQueue = false;
212 //so we don't count the user trying to
213 //login as a session and queue the socket that we are using
214 --Sessions;
216 if (pLimit > 0 && Sessions >= pLimit && s->GetSecurity () == SEC_PLAYER )
218 AddQueuedPlayer (s);
219 UpdateMaxSessionCounters ();
220 sLog.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s->GetAccountId (), ++QueueSize);
221 return;
224 WorldPacket packet(SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
225 packet << uint8 (AUTH_OK);
226 packet << uint32 (0); // unknown random value...
227 packet << uint8 (0);
228 packet << uint32 (0);
229 packet << uint8 (s->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
230 s->SendPacket (&packet);
232 UpdateMaxSessionCounters ();
234 // Updates the population
235 if (pLimit > 0)
237 float popu = GetActiveSessionCount (); //updated number of users on the server
238 popu /= pLimit;
239 popu *= 2;
240 loginDatabase.PExecute ("UPDATE realmlist SET population = '%f' WHERE id = '%d'", popu, realmID);
241 sLog.outDetail ("Server Population (%f).", popu);
245 int32 World::GetQueuePos(WorldSession* sess)
247 uint32 position = 1;
249 for(Queue::iterator iter = m_QueuedPlayer.begin(); iter != m_QueuedPlayer.end(); ++iter, ++position)
250 if((*iter) == sess)
251 return position;
253 return 0;
256 void World::AddQueuedPlayer(WorldSession* sess)
258 m_QueuedPlayer.push_back (sess);
260 // The 1st SMSG_AUTH_RESPONSE needs to contain other info too.
261 WorldPacket packet (SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
262 packet << uint8 (AUTH_WAIT_QUEUE);
263 packet << uint32 (0); // unknown random value...
264 packet << uint8 (0);
265 packet << uint32 (0);
266 packet << uint8 (sess->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
267 packet << uint32(GetQueuePos (sess));
268 sess->SendPacket (&packet);
270 //sess->SendAuthWaitQue (GetQueuePos (sess));
273 void World::RemoveQueuedPlayer(WorldSession* sess)
275 // sessions count including queued to remove (if removed_session set)
276 uint32 sessions = GetActiveSessionCount();
278 uint32 position = 1;
279 Queue::iterator iter = m_QueuedPlayer.begin();
281 // if session not queued then we need decrease sessions count (Remove socked callet before session removing from session list)
282 bool decrease_session = true;
284 // search to remove and count skipped positions
285 for(;iter != m_QueuedPlayer.end(); ++iter, ++position)
287 if(*iter==sess)
289 Queue::iterator iter2 = iter;
290 ++iter;
291 m_QueuedPlayer.erase(iter2);
292 decrease_session = false; // removing queued session
293 break;
297 // iter point to next socked after removed or end()
298 // position store position of removed socket and then new position next socket after removed
300 // decrease for case session queued for removing
301 if(decrease_session && sessions)
302 --sessions;
304 // accept first in queue
305 if( (!m_playerLimit || sessions < m_playerLimit) && !m_QueuedPlayer.empty() )
307 WorldSession * socket = m_QueuedPlayer.front();
308 socket->SendAuthWaitQue(0);
309 m_QueuedPlayer.pop_front();
311 // update iter to point first queued socket or end() if queue is empty now
312 iter = m_QueuedPlayer.begin();
313 position = 1;
316 // update position from iter to end()
317 // iter point to first not updated socket, position store new position
318 for(; iter != m_QueuedPlayer.end(); ++iter, ++position)
319 (*iter)->SendAuthWaitQue(position);
322 /// Find a Weather object by the given zoneid
323 Weather* World::FindWeather(uint32 id) const
325 WeatherMap::const_iterator itr = m_weathers.find(id);
327 if(itr != m_weathers.end())
328 return itr->second;
329 else
330 return 0;
333 /// Remove a Weather object for the given zoneid
334 void World::RemoveWeather(uint32 id)
336 // not called at the moment. Kept for completeness
337 WeatherMap::iterator itr = m_weathers.find(id);
339 if(itr != m_weathers.end())
341 delete itr->second;
342 m_weathers.erase(itr);
346 /// Add a Weather object to the list
347 Weather* World::AddWeather(uint32 zone_id)
349 WeatherZoneChances const* weatherChances = objmgr.GetWeatherChances(zone_id);
351 // zone not have weather, ignore
352 if(!weatherChances)
353 return NULL;
355 Weather* w = new Weather(zone_id,weatherChances);
356 m_weathers[w->GetZone()] = w;
357 w->ReGenerate();
358 w->UpdateWeather();
359 return w;
362 /// Initialize config values
363 void World::LoadConfigSettings(bool reload)
365 if(reload)
367 if(!sConfig.Reload())
369 sLog.outError("World settings reload fail: can't read settings from %s.",sConfig.GetFilename().c_str());
370 return;
374 ///- Read the version of the configuration file and warn the user in case of emptiness or mismatch
375 uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
376 if(!confVersion)
378 sLog.outError("*****************************************************************************");
379 sLog.outError(" WARNING: mangosd.conf does not include a ConfVersion variable.");
380 sLog.outError(" Your configuration file may be out of date!");
381 sLog.outError("*****************************************************************************");
382 clock_t pause = 3000 + clock();
383 while (pause > clock());
385 else
387 if (confVersion < _MANGOSDCONFVERSION)
389 sLog.outError("*****************************************************************************");
390 sLog.outError(" WARNING: Your mangosd.conf version indicates your conf file is out of date!");
391 sLog.outError(" Please check for updates, as your current default values may cause");
392 sLog.outError(" unexpected behavior.");
393 sLog.outError("*****************************************************************************");
394 clock_t pause = 3000 + clock();
395 while (pause > clock());
399 ///- Read the player limit and the Message of the day from the config file
400 SetPlayerLimit( sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT), true );
401 SetMotd( sConfig.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
403 ///- Read all rates from the config file
404 rate_values[RATE_HEALTH] = sConfig.GetFloatDefault("Rate.Health", 1);
405 if(rate_values[RATE_HEALTH] < 0)
407 sLog.outError("Rate.Health (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_HEALTH]);
408 rate_values[RATE_HEALTH] = 1;
410 rate_values[RATE_POWER_MANA] = sConfig.GetFloatDefault("Rate.Mana", 1);
411 if(rate_values[RATE_POWER_MANA] < 0)
413 sLog.outError("Rate.Mana (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_POWER_MANA]);
414 rate_values[RATE_POWER_MANA] = 1;
416 rate_values[RATE_POWER_RAGE_INCOME] = sConfig.GetFloatDefault("Rate.Rage.Income", 1);
417 rate_values[RATE_POWER_RAGE_LOSS] = sConfig.GetFloatDefault("Rate.Rage.Loss", 1);
418 if(rate_values[RATE_POWER_RAGE_LOSS] < 0)
420 sLog.outError("Rate.Rage.Loss (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_POWER_RAGE_LOSS]);
421 rate_values[RATE_POWER_RAGE_LOSS] = 1;
423 rate_values[RATE_POWER_FOCUS] = sConfig.GetFloatDefault("Rate.Focus", 1.0f);
424 rate_values[RATE_LOYALTY] = sConfig.GetFloatDefault("Rate.Loyalty", 1.0f);
425 rate_values[RATE_SKILL_DISCOVERY] = sConfig.GetFloatDefault("Rate.Skill.Discovery", 1.0f);
426 rate_values[RATE_DROP_ITEM_POOR] = sConfig.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f);
427 rate_values[RATE_DROP_ITEM_NORMAL] = sConfig.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f);
428 rate_values[RATE_DROP_ITEM_UNCOMMON] = sConfig.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f);
429 rate_values[RATE_DROP_ITEM_RARE] = sConfig.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f);
430 rate_values[RATE_DROP_ITEM_EPIC] = sConfig.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f);
431 rate_values[RATE_DROP_ITEM_LEGENDARY] = sConfig.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f);
432 rate_values[RATE_DROP_ITEM_ARTIFACT] = sConfig.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f);
433 rate_values[RATE_DROP_ITEM_REFERENCED] = sConfig.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f);
434 rate_values[RATE_DROP_MONEY] = sConfig.GetFloatDefault("Rate.Drop.Money", 1.0f);
435 rate_values[RATE_XP_KILL] = sConfig.GetFloatDefault("Rate.XP.Kill", 1.0f);
436 rate_values[RATE_XP_QUEST] = sConfig.GetFloatDefault("Rate.XP.Quest", 1.0f);
437 rate_values[RATE_XP_EXPLORE] = sConfig.GetFloatDefault("Rate.XP.Explore", 1.0f);
438 rate_values[RATE_XP_PAST_70] = sConfig.GetFloatDefault("Rate.XP.PastLevel70", 1.0f);
439 rate_values[RATE_REPUTATION_GAIN] = sConfig.GetFloatDefault("Rate.Reputation.Gain", 1.0f);
440 rate_values[RATE_CREATURE_NORMAL_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f);
441 rate_values[RATE_CREATURE_ELITE_ELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f);
442 rate_values[RATE_CREATURE_ELITE_RAREELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f);
443 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f);
444 rate_values[RATE_CREATURE_ELITE_RARE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f);
445 rate_values[RATE_CREATURE_NORMAL_HP] = sConfig.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f);
446 rate_values[RATE_CREATURE_ELITE_ELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f);
447 rate_values[RATE_CREATURE_ELITE_RAREELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f);
448 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f);
449 rate_values[RATE_CREATURE_ELITE_RARE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f);
450 rate_values[RATE_CREATURE_NORMAL_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f);
451 rate_values[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f);
452 rate_values[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f);
453 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f);
454 rate_values[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f);
455 rate_values[RATE_CREATURE_AGGRO] = sConfig.GetFloatDefault("Rate.Creature.Aggro", 1.0f);
456 rate_values[RATE_REST_INGAME] = sConfig.GetFloatDefault("Rate.Rest.InGame", 1.0f);
457 rate_values[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY] = sConfig.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f);
458 rate_values[RATE_REST_OFFLINE_IN_WILDERNESS] = sConfig.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f);
459 rate_values[RATE_DAMAGE_FALL] = sConfig.GetFloatDefault("Rate.Damage.Fall", 1.0f);
460 rate_values[RATE_AUCTION_TIME] = sConfig.GetFloatDefault("Rate.Auction.Time", 1.0f);
461 rate_values[RATE_AUCTION_DEPOSIT] = sConfig.GetFloatDefault("Rate.Auction.Deposit", 1.0f);
462 rate_values[RATE_AUCTION_CUT] = sConfig.GetFloatDefault("Rate.Auction.Cut", 1.0f);
463 rate_values[RATE_HONOR] = sConfig.GetFloatDefault("Rate.Honor",1.0f);
464 rate_values[RATE_MINING_AMOUNT] = sConfig.GetFloatDefault("Rate.Mining.Amount",1.0f);
465 rate_values[RATE_MINING_NEXT] = sConfig.GetFloatDefault("Rate.Mining.Next",1.0f);
466 rate_values[RATE_INSTANCE_RESET_TIME] = sConfig.GetFloatDefault("Rate.InstanceResetTime",1.0f);
467 rate_values[RATE_TALENT] = sConfig.GetFloatDefault("Rate.Talent",1.0f);
468 if(rate_values[RATE_TALENT] < 0.0f)
470 sLog.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_TALENT]);
471 rate_values[RATE_TALENT] = 1.0f;
473 rate_values[RATE_CORPSE_DECAY_LOOTED] = sConfig.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f);
475 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = sConfig.GetFloatDefault("TargetPosRecalculateRange",1.5f);
476 if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] < CONTACT_DISTANCE)
478 sLog.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],CONTACT_DISTANCE,CONTACT_DISTANCE);
479 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = CONTACT_DISTANCE;
481 else if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] > ATTACK_DISTANCE)
483 sLog.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",
484 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],ATTACK_DISTANCE,ATTACK_DISTANCE);
485 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = ATTACK_DISTANCE;
488 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = sConfig.GetFloatDefault("DurabilityLossChance.Damage",0.5f);
489 if(rate_values[RATE_DURABILITY_LOSS_DAMAGE] < 0.0f)
491 sLog.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_DAMAGE]);
492 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = 0.0f;
494 rate_values[RATE_DURABILITY_LOSS_ABSORB] = sConfig.GetFloatDefault("DurabilityLossChance.Absorb",0.5f);
495 if(rate_values[RATE_DURABILITY_LOSS_ABSORB] < 0.0f)
497 sLog.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_ABSORB]);
498 rate_values[RATE_DURABILITY_LOSS_ABSORB] = 0.0f;
500 rate_values[RATE_DURABILITY_LOSS_PARRY] = sConfig.GetFloatDefault("DurabilityLossChance.Parry",0.05f);
501 if(rate_values[RATE_DURABILITY_LOSS_PARRY] < 0.0f)
503 sLog.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_PARRY]);
504 rate_values[RATE_DURABILITY_LOSS_PARRY] = 0.0f;
506 rate_values[RATE_DURABILITY_LOSS_BLOCK] = sConfig.GetFloatDefault("DurabilityLossChance.Block",0.05f);
507 if(rate_values[RATE_DURABILITY_LOSS_BLOCK] < 0.0f)
509 sLog.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_BLOCK]);
510 rate_values[RATE_DURABILITY_LOSS_BLOCK] = 0.0f;
513 ///- Read other configuration items from the config file
515 m_configs[CONFIG_COMPRESSION] = sConfig.GetIntDefault("Compression", 1);
516 if(m_configs[CONFIG_COMPRESSION] < 1 || m_configs[CONFIG_COMPRESSION] > 9)
518 sLog.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs[CONFIG_COMPRESSION]);
519 m_configs[CONFIG_COMPRESSION] = 1;
521 m_configs[CONFIG_ADDON_CHANNEL] = sConfig.GetBoolDefault("AddonChannel", true);
522 m_configs[CONFIG_GRID_UNLOAD] = sConfig.GetBoolDefault("GridUnload", true);
523 m_configs[CONFIG_INTERVAL_SAVE] = sConfig.GetIntDefault("PlayerSaveInterval", 900000);
525 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = sConfig.GetIntDefault("GridCleanUpDelay", 300000);
526 if(m_configs[CONFIG_INTERVAL_GRIDCLEAN] < MIN_GRID_DELAY)
528 sLog.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_GRIDCLEAN],MIN_GRID_DELAY);
529 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = MIN_GRID_DELAY;
531 if(reload)
532 MapManager::Instance().SetGridCleanUpDelay(m_configs[CONFIG_INTERVAL_GRIDCLEAN]);
534 m_configs[CONFIG_INTERVAL_MAPUPDATE] = sConfig.GetIntDefault("MapUpdateInterval", 100);
535 if(m_configs[CONFIG_INTERVAL_MAPUPDATE] < MIN_MAP_UPDATE_DELAY)
537 sLog.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_MAPUPDATE],MIN_MAP_UPDATE_DELAY);
538 m_configs[CONFIG_INTERVAL_MAPUPDATE] = MIN_MAP_UPDATE_DELAY;
540 if(reload)
541 MapManager::Instance().SetMapUpdateInterval(m_configs[CONFIG_INTERVAL_MAPUPDATE]);
543 m_configs[CONFIG_INTERVAL_CHANGEWEATHER] = sConfig.GetIntDefault("ChangeWeatherInterval", 600000);
545 if(reload)
547 uint32 val = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
548 if(val!=m_configs[CONFIG_PORT_WORLD])
549 sLog.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_PORT_WORLD]);
551 else
552 m_configs[CONFIG_PORT_WORLD] = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
554 if(reload)
556 uint32 val = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
557 if(val!=m_configs[CONFIG_SOCKET_SELECTTIME])
558 sLog.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[DEFAULT_SOCKET_SELECT_TIME]);
560 else
561 m_configs[CONFIG_SOCKET_SELECTTIME] = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
563 m_configs[CONFIG_GROUP_XP_DISTANCE] = sConfig.GetIntDefault("MaxGroupXPDistance", 74);
564 /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
565 m_configs[CONFIG_SIGHT_MONSTER] = sConfig.GetIntDefault("MonsterSight", 50);
566 m_configs[CONFIG_SIGHT_GUARDER] = sConfig.GetIntDefault("GuarderSight", 50);
568 if(reload)
570 uint32 val = sConfig.GetIntDefault("GameType", 0);
571 if(val!=m_configs[CONFIG_GAME_TYPE])
572 sLog.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_GAME_TYPE]);
574 else
575 m_configs[CONFIG_GAME_TYPE] = sConfig.GetIntDefault("GameType", 0);
577 if(reload)
579 uint32 val = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
580 if(val!=m_configs[CONFIG_REALM_ZONE])
581 sLog.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_REALM_ZONE]);
583 else
584 m_configs[CONFIG_REALM_ZONE] = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
586 m_configs[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS] = sConfig.GetBoolDefault("AllowTwoSide.Accounts", false);
587 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
588 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
589 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
590 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
591 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
592 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
593 m_configs[CONFIG_ALLOW_TWO_SIDE_WHO_LIST] = sConfig.GetBoolDefault("AllowTwoSide.WhoList", false);
594 m_configs[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND] = sConfig.GetBoolDefault("AllowTwoSide.AddFriend", false);
595 m_configs[CONFIG_STRICT_PLAYER_NAMES] = sConfig.GetIntDefault("StrictPlayerNames", 0);
596 m_configs[CONFIG_STRICT_CHARTER_NAMES] = sConfig.GetIntDefault("StrictCharterNames", 0);
597 m_configs[CONFIG_STRICT_PET_NAMES] = sConfig.GetIntDefault("StrictPetNames", 0);
599 m_configs[CONFIG_CHARACTERS_CREATING_DISABLED] = sConfig.GetIntDefault("CharactersCreatingDisabled", 0);
601 m_configs[CONFIG_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("CharactersPerRealm", 10);
602 if(m_configs[CONFIG_CHARACTERS_PER_REALM] < 1 || m_configs[CONFIG_CHARACTERS_PER_REALM] > 10)
604 sLog.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs[CONFIG_CHARACTERS_PER_REALM]);
605 m_configs[CONFIG_CHARACTERS_PER_REALM] = 10;
608 // must be after CONFIG_CHARACTERS_PER_REALM
609 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = sConfig.GetIntDefault("CharactersPerAccount", 50);
610 if(m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] < m_configs[CONFIG_CHARACTERS_PER_REALM])
612 sLog.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs[CONFIG_CHARACTERS_PER_ACCOUNT],m_configs[CONFIG_CHARACTERS_PER_REALM]);
613 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = m_configs[CONFIG_CHARACTERS_PER_REALM];
616 m_configs[CONFIG_SKIP_CINEMATICS] = sConfig.GetIntDefault("SkipCinematics", 0);
617 if(m_configs[CONFIG_SKIP_CINEMATICS] < 0 || m_configs[CONFIG_SKIP_CINEMATICS] > 2)
619 sLog.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs[CONFIG_SKIP_CINEMATICS]);
620 m_configs[CONFIG_SKIP_CINEMATICS] = 0;
623 if(reload)
625 uint32 val = sConfig.GetIntDefault("MaxPlayerLevel", 60);
626 if(val!=m_configs[CONFIG_MAX_PLAYER_LEVEL])
627 sLog.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
629 else
630 m_configs[CONFIG_MAX_PLAYER_LEVEL] = sConfig.GetIntDefault("MaxPlayerLevel", 60);
631 if(m_configs[CONFIG_MAX_PLAYER_LEVEL] > 255)
633 sLog.outError("MaxPlayerLevel (%i) must be in range 1..255. Set to 255.",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
634 m_configs[CONFIG_MAX_PLAYER_LEVEL] = 255;
637 m_configs[CONFIG_START_PLAYER_LEVEL] = sConfig.GetIntDefault("StartPlayerLevel", 1);
638 if(m_configs[CONFIG_START_PLAYER_LEVEL] < 1)
640 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]);
641 m_configs[CONFIG_START_PLAYER_LEVEL] = 1;
643 else if(m_configs[CONFIG_START_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
645 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]);
646 m_configs[CONFIG_START_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
648 m_configs[CONFIG_MAX_HONOR_POINTS] = sConfig.GetIntDefault("MaxHonorPoints", 75000);
649 m_configs[CONFIG_MAX_ARENA_POINTS] = sConfig.GetIntDefault("MaxArenaPoints", 5000);
651 m_configs[CONFIG_INSTANCE_IGNORE_LEVEL] = sConfig.GetBoolDefault("Instance.IgnoreLevel", false);
652 m_configs[CONFIG_INSTANCE_IGNORE_RAID] = sConfig.GetBoolDefault("Instance.IgnoreRaid", false);
654 m_configs[CONFIG_BATTLEGROUND_CAST_DESERTER] = sConfig.GetBoolDefault("Battleground.CastDeserter", true);
655 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.Enable", true);
656 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false);
658 m_configs[CONFIG_CAST_UNSTUCK] = sConfig.GetBoolDefault("CastUnstuck", true);
659 m_configs[CONFIG_INSTANCE_RESET_TIME_HOUR] = sConfig.GetIntDefault("Instance.ResetTimeHour", 4);
660 m_configs[CONFIG_INSTANCE_UNLOAD_DELAY] = sConfig.GetIntDefault("Instance.UnloadDelay", 1800000);
662 m_configs[CONFIG_MAX_PRIMARY_TRADE_SKILL] = sConfig.GetIntDefault("MaxPrimaryTradeSkill", 2);
663 m_configs[CONFIG_MIN_PETITION_SIGNS] = sConfig.GetIntDefault("MinPetitionSigns", 9);
664 if(m_configs[CONFIG_MIN_PETITION_SIGNS] > 9)
666 sLog.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.",m_configs[CONFIG_MIN_PETITION_SIGNS]);
667 m_configs[CONFIG_MIN_PETITION_SIGNS] = 9;
670 m_configs[CONFIG_GM_LOGIN_STATE] = sConfig.GetIntDefault("GM.LoginState",2);
671 m_configs[CONFIG_GM_ACCEPT_TICKETS] = sConfig.GetIntDefault("GM.AcceptTickets",2);
672 m_configs[CONFIG_GM_CHAT] = sConfig.GetIntDefault("GM.Chat",2);
673 m_configs[CONFIG_GM_WISPERING_TO] = sConfig.GetIntDefault("GM.WhisperingTo",2);
675 m_configs[CONFIG_GM_IN_GM_LIST] = sConfig.GetBoolDefault("GM.InGMList",false);
676 m_configs[CONFIG_GM_IN_WHO_LIST] = sConfig.GetBoolDefault("GM.InWhoList",false);
677 m_configs[CONFIG_GM_LOG_TRADE] = sConfig.GetBoolDefault("GM.LogTrade", false);
679 m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
681 m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
683 m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
684 if(m_configs[CONFIG_UPTIME_UPDATE]<=0)
686 sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
687 m_configs[CONFIG_UPTIME_UPDATE] = 10;
689 if(reload)
691 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
692 m_timers[WUPDATE_UPTIME].Reset();
695 m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
696 m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
697 m_configs[CONFIG_SKILL_CHANCE_GREEN] = sConfig.GetIntDefault("SkillChance.Green",25);
698 m_configs[CONFIG_SKILL_CHANCE_GREY] = sConfig.GetIntDefault("SkillChance.Grey",0);
700 m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS] = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
701 m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS] = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
703 m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
705 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = sConfig.GetIntDefault("SkillGain.Crafting", 1);
706 if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
708 sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
709 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
712 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = sConfig.GetIntDefault("SkillGain.Defense", 1);
713 if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
715 sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
716 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
719 m_configs[CONFIG_SKILL_GAIN_GATHERING] = sConfig.GetIntDefault("SkillGain.Gathering", 1);
720 if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
722 sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
723 m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
726 m_configs[CONFIG_SKILL_GAIN_WEAPON] = sConfig.GetIntDefault("SkillGain.Weapon", 1);
727 if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
729 sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
730 m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
733 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
734 if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
736 sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
737 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
740 m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
741 m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
743 if(reload)
745 uint32 val = sConfig.GetIntDefault("Expansion",1);
746 if(val!=m_configs[CONFIG_EXPANSION])
747 sLog.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
749 else
750 m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",1);
752 m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
753 m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
754 m_configs[CONFIG_CHATFLOOD_MUTE_TIME] = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
756 m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
758 m_configs[CONFIG_CREATURE_FAMILY_ASSISTEMCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistenceRadius",10);
760 m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
762 // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level (255)
763 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff",4);
764 if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > 255)
765 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = 255;
766 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff",7);
767 if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > 255)
768 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = 255;
770 m_configs[CONFIG_DETECT_POS_COLLISION] = sConfig.GetBoolDefault("DetectPosCollision", true);
772 m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
773 m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
775 m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
776 m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
778 m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
779 m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
780 m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
781 m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
782 m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
784 m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault("Death.SicknessLevel", 11);
785 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
786 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
788 m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
790 // always use declined names in the russian client
791 m_configs[CONFIG_DECLINED_NAMES_USED] =
792 (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
794 m_configs[CONFIG_LISTEN_RANGE_SAY] = sConfig.GetIntDefault("ListenRange.Say", 25);
795 m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
796 m_configs[CONFIG_LISTEN_RANGE_YELL] = sConfig.GetIntDefault("ListenRange.Yell", 300);
798 m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
799 if(m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
801 sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
802 m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
804 m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
805 if(m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
807 sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
808 m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
811 m_MaxVisibleDistanceForCreature = sConfig.GetFloatDefault("Visibility.Distance.Creature", DEFAULT_VISIBILITY_DISTANCE);
812 if(m_MaxVisibleDistanceForCreature < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
814 sLog.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
815 m_MaxVisibleDistanceForCreature = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
817 else if(m_MaxVisibleDistanceForCreature + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
819 sLog.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
820 m_MaxVisibleDistanceForCreature = MAX_VISIBILITY_DISTANCE-m_VisibleUnitGreyDistance;
822 m_MaxVisibleDistanceForPlayer = sConfig.GetFloatDefault("Visibility.Distance.Player", DEFAULT_VISIBILITY_DISTANCE);
823 if(m_MaxVisibleDistanceForPlayer < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
825 sLog.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
826 m_MaxVisibleDistanceForPlayer = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
828 else if(m_MaxVisibleDistanceForPlayer + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
830 sLog.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
831 m_MaxVisibleDistanceForPlayer = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
833 m_MaxVisibleDistanceForObject = sConfig.GetFloatDefault("Visibility.Distance.Gameobject", DEFAULT_VISIBILITY_DISTANCE);
834 if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
836 sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
837 m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
839 else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
841 sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
842 m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
844 m_MaxVisibleDistanceInFlight = sConfig.GetFloatDefault("Visibility.Distance.InFlight", DEFAULT_VISIBILITY_DISTANCE);
845 if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
847 sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
848 m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
851 ///- Read the "Data" directory from the config file
852 std::string dataPath = sConfig.GetStringDefault("DataDir","./");
853 if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
854 dataPath.append("/");
856 if(reload)
858 if(dataPath!=m_dataPath)
859 sLog.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath.c_str());
861 else
863 m_dataPath = dataPath;
864 sLog.outString("Using DataDir %s",m_dataPath.c_str());
867 bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
868 bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
869 std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
870 std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
871 VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
872 VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
873 VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
874 VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
875 sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
876 sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
877 sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
880 /// Initialize the World
881 void World::SetInitialWorldSettings()
883 ///- Initialize the random number generator
884 srand((unsigned int)time(NULL));
886 ///- Initialize config settings
887 LoadConfigSettings();
889 ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
890 objmgr.SetHighestGuids();
892 ///- Check the existence of the map files for all races' startup areas.
893 if( !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
894 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
895 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
896 ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
897 ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
898 ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
899 ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
900 ||m_configs[CONFIG_EXPANSION] && (
901 !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
903 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());
904 exit(1);
907 ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
908 sLog.outString( "" );
909 sLog.outString( "Loading MaNGOS strings..." );
910 if (!objmgr.LoadMangosStrings())
911 exit(1); // Error message displayed in function already
913 ///- Update the realm entry in the database with the realm type from the config file
914 //No SQL injection as values are treated as integers
916 // not send custom type REALM_FFA_PVP to realm list
917 uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
918 uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
919 loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
921 ///- Remove the bones after a restart
922 CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
924 ///- Load the DBC files
925 sLog.outString("Initialize data stores...");
926 LoadDBCStores(m_dataPath);
927 DetectDBCLang();
929 sLog.outString( "Loading InstanceTemplate" );
930 objmgr.LoadInstanceTemplate();
932 sLog.outString( "Loading AchievementCriteriaList..." );
933 objmgr.LoadAchievementCriteriaList();
935 sLog.outString( "Loading completed achievements..." );
936 objmgr.LoadCompletedAchievements();
938 sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
939 spellmgr.LoadSkillLineAbilityMap();
941 ///- Clean up and pack instances
942 sLog.outString( "Cleaning up instances..." );
943 sInstanceSaveManager.CleanupInstances(); // must be called before `creature_respawn`/`gameobject_respawn` tables
945 sLog.outString( "Packing instances..." );
946 sInstanceSaveManager.PackInstances();
948 sLog.outString( "Loading Localization strings..." );
949 objmgr.LoadCreatureLocales();
950 objmgr.LoadGameObjectLocales();
951 objmgr.LoadItemLocales();
952 objmgr.LoadQuestLocales();
953 objmgr.LoadNpcTextLocales();
954 objmgr.LoadPageTextLocales();
955 objmgr.LoadNpcOptionLocales();
956 objmgr.SetDBCLocaleIndex(GetDefaultDbcLocale()); // Get once for all the locale index of DBC language (console/broadcasts)
958 sLog.outString( "Loading Page Texts..." );
959 objmgr.LoadPageTexts();
961 sLog.outString( "Loading Game Object Templates..." ); // must be after LoadPageTexts
962 objmgr.LoadGameobjectInfo();
964 sLog.outString( "Loading Spell Chain Data..." );
965 spellmgr.LoadSpellChains();
967 sLog.outString( "Loading Spell Elixir types..." );
968 spellmgr.LoadSpellElixirs();
970 sLog.outString( "Loading Spell Learn Skills..." );
971 spellmgr.LoadSpellLearnSkills(); // must be after LoadSpellChains
973 sLog.outString( "Loading Spell Learn Spells..." );
974 spellmgr.LoadSpellLearnSpells();
976 sLog.outString( "Loading Spell Proc Event conditions..." );
977 spellmgr.LoadSpellProcEvents();
979 sLog.outString( "Loading Aggro Spells Definitions...");
980 spellmgr.LoadSpellThreats();
982 sLog.outString( "Loading NPC Texts..." );
983 objmgr.LoadGossipText();
985 sLog.outString( "Loading Item Random Enchantments Table..." );
986 LoadRandomEnchantmentsTable();
988 sLog.outString( "Loading Items..." ); // must be after LoadRandomEnchantmentsTable and LoadPageTexts
989 objmgr.LoadItemPrototypes();
991 sLog.outString( "Loading Item Texts..." );
992 objmgr.LoadItemTexts();
994 sLog.outString( "Loading Creature Model Based Info Data..." );
995 objmgr.LoadCreatureModelInfo();
997 sLog.outString( "Loading Equipment templates...");
998 objmgr.LoadEquipmentTemplates();
1000 sLog.outString( "Loading Creature templates..." );
1001 objmgr.LoadCreatureTemplates();
1003 sLog.outString( "Loading SpellsScriptTarget...");
1004 spellmgr.LoadSpellScriptTarget(); // must be after LoadCreatureTemplates and LoadGameobjectInfo
1006 sLog.outString( "Loading Creature Reputation OnKill Data..." );
1007 objmgr.LoadReputationOnKill();
1009 sLog.outString( "Loading Pet Create Spells..." );
1010 objmgr.LoadPetCreateSpells();
1012 sLog.outString( "Loading Creature Data..." );
1013 objmgr.LoadCreatures();
1015 sLog.outString( "Loading Creature Addon Data..." );
1016 objmgr.LoadCreatureAddons(); // must be after LoadCreatureTemplates() and LoadCreatures()
1018 sLog.outString( "Loading Creature Respawn Data..." ); // must be after PackInstances()
1019 objmgr.LoadCreatureRespawnTimes();
1021 sLog.outString( "Loading Gameobject Data..." );
1022 objmgr.LoadGameobjects();
1024 sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1025 objmgr.LoadGameobjectRespawnTimes();
1027 sLog.outString( "Loading Game Event Data...");
1028 gameeventmgr.LoadFromDB();
1030 sLog.outString( "Loading Weather Data..." );
1031 objmgr.LoadWeatherZoneChances();
1033 sLog.outString( "Loading Quests..." );
1034 objmgr.LoadQuests(); // must be loaded after DBCs, creature_template, item_template, gameobject tables
1036 sLog.outString( "Loading Quests Relations..." );
1037 objmgr.LoadQuestRelations(); // must be after quest load
1039 sLog.outString( "Loading AreaTrigger definitions..." );
1040 objmgr.LoadAreaTriggerTeleports(); // must be after item template load
1042 sLog.outString( "Loading Quest Area Triggers..." );
1043 objmgr.LoadQuestAreaTriggers(); // must be after LoadQuests
1045 sLog.outString( "Loading Tavern Area Triggers..." );
1046 objmgr.LoadTavernAreaTriggers();
1048 sLog.outString( "Loading AreaTrigger script names..." );
1049 objmgr.LoadAreaTriggerScripts();
1051 sLog.outString( "Loading Graveyard-zone links...");
1052 objmgr.LoadGraveyardZones();
1054 sLog.outString( "Loading Spell target coordinates..." );
1055 spellmgr.LoadSpellTargetPositions();
1057 sLog.outString( "Loading SpellAffect definitions..." );
1058 spellmgr.LoadSpellAffects();
1060 sLog.outString( "Loading spell pet auras..." );
1061 spellmgr.LoadSpellPetAuras();
1063 sLog.outString( "Loading player Create Info & Level Stats..." );
1064 objmgr.LoadPlayerInfo();
1066 sLog.outString( "Loading Exploration BaseXP Data..." );
1067 objmgr.LoadExplorationBaseXP();
1069 sLog.outString( "Loading Pet Name Parts..." );
1070 objmgr.LoadPetNames();
1072 sLog.outString( "Loading the max pet number..." );
1073 objmgr.LoadPetNumber();
1075 sLog.outString( "Loading pet level stats..." );
1076 objmgr.LoadPetLevelInfo();
1078 sLog.outString( "Loading Player Corpses..." );
1079 objmgr.LoadCorpses();
1081 sLog.outString( "Loading Loot Tables..." );
1082 LoadLootTables();
1084 sLog.outString( "Loading Skill Discovery Table..." );
1085 LoadSkillDiscoveryTable();
1087 sLog.outString( "Loading Skill Extra Item Table..." );
1088 LoadSkillExtraItemTable();
1090 sLog.outString( "Loading Skill Fishing base level requirements..." );
1091 objmgr.LoadFishingBaseSkillLevel();
1093 ///- Load dynamic data tables from the database
1094 sLog.outString( "Loading Auctions..." );
1095 objmgr.LoadAuctionItems();
1096 objmgr.LoadAuctions();
1098 sLog.outString( "Loading Guilds..." );
1099 objmgr.LoadGuilds();
1101 sLog.outString( "Loading ArenaTeams..." );
1102 objmgr.LoadArenaTeams();
1104 sLog.outString( "Loading Groups..." );
1105 objmgr.LoadGroups();
1107 sLog.outString( "Loading ReservedNames..." );
1108 objmgr.LoadReservedPlayersNames();
1110 sLog.outString( "Loading GameObject for quests..." );
1111 objmgr.LoadGameObjectForQuests();
1113 sLog.outString( "Loading BattleMasters..." );
1114 objmgr.LoadBattleMastersEntry();
1116 sLog.outString( "Loading GameTeleports..." );
1117 objmgr.LoadGameTele();
1119 sLog.outString( "Loading Npc Text Id..." );
1120 objmgr.LoadNpcTextId(); // must be after load Creature and NpcText
1122 sLog.outString( "Loading Npc Options..." );
1123 objmgr.LoadNpcOptions();
1125 sLog.outString( "Loading vendors..." );
1126 objmgr.LoadVendors(); // must be after load CreatureTemplate and ItemTemplate
1128 sLog.outString( "Loading trainers..." );
1129 objmgr.LoadTrainerSpell(); // must be after load CreatureTemplate
1131 sLog.outString( "Loading Waypoints..." );
1132 WaypointMgr.Load();
1134 ///- Handle outdated emails (delete/return)
1135 sLog.outString( "Returning old mails..." );
1136 objmgr.ReturnOrDeleteOldMails(false);
1138 ///- Load and initialize scripts
1139 sLog.outString( "Loading Scripts..." );
1140 objmgr.LoadQuestStartScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1141 objmgr.LoadQuestEndScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1142 objmgr.LoadSpellScripts(); // must be after load Creature/Gameobject(Template/Data)
1143 objmgr.LoadGameObjectScripts(); // must be after load Creature/Gameobject(Template/Data)
1144 objmgr.LoadEventScripts(); // must be after load Creature/Gameobject(Template/Data)
1146 sLog.outString( "Initializing Scripts..." );
1147 if(!LoadScriptingModule())
1148 exit(1);
1150 ///- Initialize game time and timers
1151 sLog.outString( "DEBUG:: Initialize game time and timers" );
1152 m_gameTime = time(NULL);
1153 m_startTime=m_gameTime;
1155 tm local;
1156 time_t curr;
1157 time(&curr);
1158 local=*(localtime(&curr)); // dereference and assign
1159 char isoDate[128];
1160 sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1161 local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1163 WorldDatabase.PExecute("INSERT INTO uptime (startstring, starttime, uptime) VALUES('%s', " I64FMTD ", 0)",
1164 isoDate, uint64(m_startTime));
1166 m_timers[WUPDATE_OBJECTS].SetInterval(0);
1167 m_timers[WUPDATE_SESSIONS].SetInterval(0);
1168 m_timers[WUPDATE_WEATHERS].SetInterval(1000);
1169 m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*1000); //set auction update interval to 1 minute
1170 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
1171 //Update "uptime" table based on configuration entry in minutes.
1172 m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*1000); //erase corpses every 20 minutes
1174 //to set mailtimer to return mails every day between 4 and 5 am
1175 //mailtimer is increased when updating auctions
1176 //one second is 1000 -(tested on win system)
1177 mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * 1000) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1178 //1440
1179 mail_timer_expires = ( (DAY * 1000) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1180 sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1182 ///- Initilize static helper structures
1183 AIRegistry::Initialize();
1184 WaypointMovementGenerator<Creature>::Initialize();
1185 Player::InitVisibleBits();
1187 ///- Initialize MapManager
1188 sLog.outString( "Starting Map System" );
1189 MapManager::Instance().Initialize();
1191 ///- Initialize Battlegrounds
1192 sLog.outString( "Starting BattleGround System" );
1193 sBattleGroundMgr.CreateInitialBattleGrounds();
1195 //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1196 sLog.outString( "Loading Transports..." );
1197 MapManager::Instance().LoadTransports();
1199 sLog.outString("Deleting expired bans..." );
1200 loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1202 sLog.outString("Calculate next daily quest reset time..." );
1203 InitDailyQuestResetTime();
1205 sLog.outString("Starting Game Event system..." );
1206 uint32 nextGameEvent = gameeventmgr.Initialize();
1207 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent); //depend on next event
1209 sLog.outString( "WORLD: World initialized" );
1212 void World::DetectDBCLang()
1214 uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1216 if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1218 sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1219 m_lang_confid = LOCALE_enUS;
1222 ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1224 std::string availableLocalsStr;
1226 int default_locale = MAX_LOCALE;
1227 for (int i = MAX_LOCALE-1; i >= 0; --i)
1229 if ( strlen(race->name[i]) > 0) // check by race names
1231 default_locale = i;
1232 m_availableDbcLocaleMask |= (1 << i);
1233 availableLocalsStr += localeNames[i];
1234 availableLocalsStr += " ";
1238 if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1239 (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1241 default_locale = m_lang_confid;
1244 if(default_locale >= MAX_LOCALE)
1246 sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1247 exit(1);
1250 m_defaultDbcLocale = LocaleConstant(default_locale);
1252 sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1255 /// Update the World !
1256 void World::Update(time_t diff)
1258 ///- Update the different timers
1259 for(int i = 0; i < WUPDATE_COUNT; i++)
1260 if(m_timers[i].GetCurrent()>=0)
1261 m_timers[i].Update(diff);
1262 else m_timers[i].SetCurrent(0);
1264 ///- Update the game time and check for shutdown time
1265 _UpdateGameTime();
1267 /// Handle daily quests reset time
1268 if(m_gameTime > m_NextDailyQuestReset)
1270 ResetDailyQuests();
1271 m_NextDailyQuestReset += DAY;
1274 /// <ul><li> Handle auctions when the timer has passed
1275 if (m_timers[WUPDATE_AUCTIONS].Passed())
1277 m_timers[WUPDATE_AUCTIONS].Reset();
1279 ///- Update mails (return old mails with item, or delete them)
1280 //(tested... works on win)
1281 if (++mail_timer > mail_timer_expires)
1283 mail_timer = 0;
1284 objmgr.ReturnOrDeleteOldMails(true);
1287 AuctionHouseObject* AuctionMap;
1288 for (int i = 0; i < 3; i++)
1290 switch (i)
1292 case 0:
1293 AuctionMap = objmgr.GetAuctionsMap( 6 );//horde
1294 break;
1295 case 1:
1296 AuctionMap = objmgr.GetAuctionsMap( 2 );//alliance
1297 break;
1298 case 2:
1299 AuctionMap = objmgr.GetAuctionsMap( 7 );//neutral
1300 break;
1303 ///- Handle expired auctions
1304 AuctionHouseObject::AuctionEntryMap::iterator itr,next;
1305 for (itr = AuctionMap->GetAuctionsBegin(); itr != AuctionMap->GetAuctionsEnd();itr = next)
1307 next = itr;
1308 ++next;
1309 if (m_gameTime > (itr->second->time))
1311 ///- Either cancel the auction if there was no bidder
1312 if (itr->second->bidder == 0)
1314 objmgr.SendAuctionExpiredMail( itr->second );
1316 ///- Or perform the transaction
1317 else
1319 //we should send an "item sold" message if the seller is online
1320 //we send the item to the winner
1321 //we send the money to the seller
1322 objmgr.SendAuctionSuccessfulMail( itr->second );
1323 objmgr.SendAuctionWonMail( itr->second );
1326 ///- In any case clear the auction
1327 //No SQL injection (Id is integer)
1328 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",itr->second->Id);
1329 objmgr.RemoveAItem(itr->second->item_guidlow);
1330 delete itr->second;
1331 AuctionMap->RemoveAuction(itr->first);
1337 /// <li> Handle session updates when the timer has passed
1338 if (m_timers[WUPDATE_SESSIONS].Passed())
1340 m_timers[WUPDATE_SESSIONS].Reset();
1342 UpdateSessions(diff);
1345 /// <li> Handle weather updates when the timer has passed
1346 if (m_timers[WUPDATE_WEATHERS].Passed())
1348 m_timers[WUPDATE_WEATHERS].Reset();
1350 ///- Send an update signal to Weather objects
1351 WeatherMap::iterator itr, next;
1352 for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1354 next = itr;
1355 ++next;
1357 ///- and remove Weather objects for zones with no player
1358 //As interval > WorldTick
1359 if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1361 delete itr->second;
1362 m_weathers.erase(itr);
1366 /// <li> Update uptime table
1367 if (m_timers[WUPDATE_UPTIME].Passed())
1369 uint32 tmpDiff = (m_gameTime - m_startTime);
1370 uint32 maxClientsNum = sWorld.GetMaxActiveSessionCount();
1372 m_timers[WUPDATE_UPTIME].Reset();
1373 WorldDatabase.PExecute("UPDATE uptime SET uptime = %d, maxplayers = %d WHERE starttime = " I64FMTD, tmpDiff, maxClientsNum, uint64(m_startTime));
1376 /// <li> Handle all other objects
1377 if (m_timers[WUPDATE_OBJECTS].Passed())
1379 m_timers[WUPDATE_OBJECTS].Reset();
1380 ///- Update objects when the timer has passed (maps, transport, creatures,...)
1381 MapManager::Instance().Update(diff); // As interval = 0
1383 ///- Process necessary scripts
1384 if (!m_scriptSchedule.empty())
1385 ScriptsProcess();
1387 sBattleGroundMgr.Update(diff);
1390 // execute callbacks from sql queries that were queued recently
1391 UpdateResultQueue();
1393 ///- Erase corpses once every 20 minutes
1394 if (m_timers[WUPDATE_CORPSES].Passed())
1396 m_timers[WUPDATE_CORPSES].Reset();
1398 CorpsesErase();
1401 ///- Process Game events when necessary
1402 if (m_timers[WUPDATE_EVENTS].Passed())
1404 m_timers[WUPDATE_EVENTS].Reset(); // to give time for Update() to be processed
1405 uint32 nextGameEvent = gameeventmgr.Update();
1406 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1407 m_timers[WUPDATE_EVENTS].Reset();
1410 /// </ul>
1411 ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1412 MapManager::Instance().DoDelayedMovesAndRemoves();
1414 // update the instance reset times
1415 sInstanceSaveManager.Update();
1417 // And last, but not least handle the issued cli commands
1418 ProcessCliCommands();
1421 /// Put scripts in the execution queue
1422 void World::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
1424 ///- Find the script map
1425 ScriptMapMap::const_iterator s = scripts.find(id);
1426 if (s == scripts.end())
1427 return;
1429 // prepare static data
1430 uint64 sourceGUID = source->GetGUID();
1431 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1432 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1434 ///- Schedule script execution for all scripts in the script map
1435 ScriptMap const *s2 = &(s->second);
1436 bool immedScript = false;
1437 for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
1439 ScriptAction sa;
1440 sa.sourceGUID = sourceGUID;
1441 sa.targetGUID = targetGUID;
1442 sa.ownerGUID = ownerGUID;
1444 sa.script = &iter->second;
1445 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + iter->first, sa));
1446 if (iter->first == 0)
1447 immedScript = true;
1449 ///- If one of the effects should be immediate, launch the script execution
1450 if (immedScript)
1451 ScriptsProcess();
1454 void World::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
1456 // NOTE: script record _must_ exist until command executed
1458 // prepare static data
1459 uint64 sourceGUID = source->GetGUID();
1460 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1461 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1463 ScriptAction sa;
1464 sa.sourceGUID = sourceGUID;
1465 sa.targetGUID = targetGUID;
1466 sa.ownerGUID = ownerGUID;
1468 sa.script = &script;
1469 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + delay, sa));
1471 ///- If effects should be immediate, launch the script execution
1472 if(delay == 0)
1473 ScriptsProcess();
1476 /// Process queued scripts
1477 void World::ScriptsProcess()
1479 if (m_scriptSchedule.empty())
1480 return;
1482 ///- Process overdue queued scripts
1483 std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
1484 // ok as multimap is a *sorted* associative container
1485 while (!m_scriptSchedule.empty() && (iter->first <= m_gameTime))
1487 ScriptAction const& step = iter->second;
1489 Object* source = NULL;
1491 if(step.sourceGUID)
1493 switch(GUID_HIPART(step.sourceGUID))
1495 case HIGHGUID_ITEM:
1496 // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1498 Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
1499 if(player)
1500 source = player->GetItemByGuid(step.sourceGUID);
1501 break;
1503 case HIGHGUID_UNIT:
1504 source = HashMapHolder<Creature>::Find(step.sourceGUID);
1505 break;
1506 case HIGHGUID_PET:
1507 source = HashMapHolder<Pet>::Find(step.sourceGUID);
1508 break;
1509 case HIGHGUID_PLAYER:
1510 source = HashMapHolder<Player>::Find(step.sourceGUID);
1511 break;
1512 case HIGHGUID_GAMEOBJECT:
1513 source = HashMapHolder<GameObject>::Find(step.sourceGUID);
1514 break;
1515 case HIGHGUID_CORPSE:
1516 source = HashMapHolder<Corpse>::Find(step.sourceGUID);
1517 break;
1518 default:
1519 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
1520 break;
1524 Object* target = NULL;
1526 if(step.targetGUID)
1528 switch(GUID_HIPART(step.targetGUID))
1530 case HIGHGUID_UNIT:
1531 target = HashMapHolder<Creature>::Find(step.targetGUID);
1532 break;
1533 case HIGHGUID_PET:
1534 target = HashMapHolder<Pet>::Find(step.targetGUID);
1535 break;
1536 case HIGHGUID_PLAYER: // empty GUID case also
1537 target = HashMapHolder<Player>::Find(step.targetGUID);
1538 break;
1539 case HIGHGUID_GAMEOBJECT:
1540 target = HashMapHolder<GameObject>::Find(step.targetGUID);
1541 break;
1542 case HIGHGUID_CORPSE:
1543 target = HashMapHolder<Corpse>::Find(step.targetGUID);
1544 break;
1545 default:
1546 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
1547 break;
1551 switch (step.script->command)
1553 case SCRIPT_COMMAND_TALK:
1555 if(!source)
1557 sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1558 break;
1561 if(source->GetTypeId()!=TYPEID_UNIT)
1563 sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1564 break;
1566 if(step.script->datalong > 3)
1568 sLog.outError("SCRIPT_COMMAND_TALK invalid chat type (%u), skipping.",step.script->datalong);
1569 break;
1572 uint64 unit_target = target ? target->GetGUID() : 0;
1574 //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1575 switch(step.script->datalong)
1577 case 0: // Say
1578 ((Creature *)source)->Say(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
1579 break;
1580 case 1: // Whisper
1581 if(!unit_target)
1583 sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
1584 break;
1586 ((Creature *)source)->Whisper(step.script->datatext.c_str(),unit_target);
1587 break;
1588 case 2: // Yell
1589 ((Creature *)source)->Yell(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
1590 break;
1591 case 3: // Emote text
1592 ((Creature *)source)->TextEmote(step.script->datatext.c_str(), unit_target);
1593 break;
1594 default:
1595 break; // must be already checked at load
1597 break;
1600 case SCRIPT_COMMAND_EMOTE:
1601 if(!source)
1603 sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1604 break;
1607 if(source->GetTypeId()!=TYPEID_UNIT)
1609 sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1610 break;
1613 ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
1614 break;
1615 case SCRIPT_COMMAND_FIELD_SET:
1616 if(!source)
1618 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1619 break;
1621 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1623 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1624 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1625 break;
1628 source->SetUInt32Value(step.script->datalong, step.script->datalong2);
1629 break;
1630 case SCRIPT_COMMAND_MOVE_TO:
1631 if(!source)
1633 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1634 break;
1637 if(source->GetTypeId()!=TYPEID_UNIT)
1639 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1640 break;
1642 ((Unit *)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, ((Unit *)source)->GetUnitMovementFlags(), step.script->datalong2 );
1643 MapManager::Instance().GetMap(((Unit *)source)->GetMapId(), ((Unit *)source))->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
1644 break;
1645 case SCRIPT_COMMAND_FLAG_SET:
1646 if(!source)
1648 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1649 break;
1651 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1653 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1654 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1655 break;
1658 source->SetFlag(step.script->datalong, step.script->datalong2);
1659 break;
1660 case SCRIPT_COMMAND_FLAG_REMOVE:
1661 if(!source)
1663 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1664 break;
1666 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1668 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1669 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1670 break;
1673 source->RemoveFlag(step.script->datalong, step.script->datalong2);
1674 break;
1676 case SCRIPT_COMMAND_TELEPORT_TO:
1678 // accept player in any one from target/source arg
1679 if (!target && !source)
1681 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1682 break;
1685 // must be only Player
1686 if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
1688 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
1689 break;
1692 Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
1694 pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
1695 break;
1698 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
1700 if(!step.script->datalong) // creature not specified
1702 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1703 break;
1706 if(!source)
1708 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1709 break;
1712 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1714 if(!summoner)
1716 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1717 break;
1720 float x = step.script->x;
1721 float y = step.script->y;
1722 float z = step.script->z;
1723 float o = step.script->o;
1725 Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
1726 if (!pCreature)
1728 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
1729 break;
1732 break;
1735 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
1737 if(!step.script->datalong) // gameobject not specified
1739 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1740 break;
1743 if(!source)
1745 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1746 break;
1749 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1751 if(!summoner)
1753 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1754 break;
1757 GameObject *go = NULL;
1758 int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
1760 CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
1761 Cell cell(p);
1762 cell.data.Part.reserved = ALL_DISTRICT;
1764 MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
1765 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(go,go_check);
1767 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1768 CellLock<GridReadGuard> cell_lock(cell, p);
1769 cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(summoner->GetMapId(), summoner));
1771 if ( !go )
1773 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
1774 break;
1777 if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1778 go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1779 go->GetGoType()==GAMEOBJECT_TYPE_DOOR ||
1780 go->GetGoType()==GAMEOBJECT_TYPE_BUTTON ||
1781 go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
1783 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
1784 break;
1787 if( go->isSpawned() )
1788 break; //gameobject already spawned
1790 go->SetLootState(GO_READY);
1791 go->SetRespawnTime(time_to_despawn); //despawn object in ? seconds
1793 MapManager::Instance().GetMap(go->GetMapId(), go)->Add(go);
1794 break;
1796 case SCRIPT_COMMAND_OPEN_DOOR:
1798 if(!step.script->datalong) // door not specified
1800 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1801 break;
1804 if(!source)
1806 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1807 break;
1810 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
1812 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1813 break;
1816 Unit* caster = (Unit*)source;
1818 GameObject *door = NULL;
1819 int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1821 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1822 Cell cell(p);
1823 cell.data.Part.reserved = ALL_DISTRICT;
1825 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1826 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1828 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1829 CellLock<GridReadGuard> cell_lock(cell, p);
1830 cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1832 if ( !door )
1834 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1835 break;
1837 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1839 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1840 break;
1843 if( !door->GetGoState() )
1844 break; //door already open
1846 door->UseDoorOrButton(time_to_close);
1848 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1849 ((GameObject*)target)->UseDoorOrButton(time_to_close);
1850 break;
1852 case SCRIPT_COMMAND_CLOSE_DOOR:
1854 if(!step.script->datalong) // guid for door not specified
1856 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
1857 break;
1860 if(!source)
1862 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
1863 break;
1866 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
1868 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1869 break;
1872 Unit* caster = (Unit*)source;
1874 GameObject *door = NULL;
1875 int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1877 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1878 Cell cell(p);
1879 cell.data.Part.reserved = ALL_DISTRICT;
1881 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1882 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1884 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1885 CellLock<GridReadGuard> cell_lock(cell, p);
1886 cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1888 if ( !door )
1890 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1891 break;
1893 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1895 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1896 break;
1899 if( door->GetGoState() )
1900 break; //door already closed
1902 door->UseDoorOrButton(time_to_open);
1904 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1905 ((GameObject*)target)->UseDoorOrButton(time_to_open);
1907 break;
1909 case SCRIPT_COMMAND_QUEST_EXPLORED:
1911 if(!source)
1913 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
1914 break;
1917 if(!target)
1919 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
1920 break;
1923 // when script called for item spell casting then target == (unit or GO) and source is player
1924 WorldObject* worldObject;
1925 Player* player;
1927 if(target->GetTypeId()==TYPEID_PLAYER)
1929 if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
1931 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
1932 break;
1935 worldObject = (WorldObject*)source;
1936 player = (Player*)target;
1938 else
1940 if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
1942 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
1943 break;
1946 if(source->GetTypeId()!=TYPEID_PLAYER)
1948 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
1949 break;
1952 worldObject = (WorldObject*)target;
1953 player = (Player*)source;
1956 // quest id and flags checked at script loading
1957 if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
1958 (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
1959 player->AreaExploredOrEventHappens(step.script->datalong);
1960 else
1961 player->FailQuest(step.script->datalong);
1963 break;
1966 case SCRIPT_COMMAND_ACTIVATE_OBJECT:
1968 if(!source)
1970 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
1971 break;
1974 if(!source->isType(TYPEMASK_UNIT))
1976 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
1977 break;
1980 if(!target)
1982 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
1983 break;
1986 if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
1988 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
1989 break;
1992 Unit* caster = (Unit*)source;
1994 GameObject *go = (GameObject*)target;
1996 go->Use(caster);
1997 break;
2000 case SCRIPT_COMMAND_REMOVE_AURA:
2002 Object* cmdTarget = step.script->datalong2 ? source : target;
2004 if(!cmdTarget)
2006 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
2007 break;
2010 if(!cmdTarget->isType(TYPEMASK_UNIT))
2012 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2013 break;
2016 ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
2017 break;
2020 case SCRIPT_COMMAND_CAST_SPELL:
2022 if(!source)
2024 sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
2025 break;
2028 if(!source->isType(TYPEMASK_UNIT))
2030 sLog.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2031 break;
2034 Object* cmdTarget = step.script->datalong2 ? source : target;
2036 if(!cmdTarget)
2038 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 ? "source" : "target");
2039 break;
2042 if(!cmdTarget->isType(TYPEMASK_UNIT))
2044 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2045 break;
2048 Unit* spellTarget = (Unit*)cmdTarget;
2050 //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2051 ((Unit*)source)->CastSpell(spellTarget,step.script->datalong,false);
2053 break;
2056 default:
2057 sLog.outError("Unknown script command %u called.",step.script->command);
2058 break;
2061 m_scriptSchedule.erase(iter);
2063 iter = m_scriptSchedule.begin();
2065 return;
2068 /// Send a packet to all players (except self if mentioned)
2069 void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
2071 SessionMap::iterator itr;
2072 for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2074 if (itr->second &&
2075 itr->second->GetPlayer() &&
2076 itr->second->GetPlayer()->IsInWorld() &&
2077 itr->second != self &&
2078 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2080 itr->second->SendPacket(packet);
2085 /// Send a System Message to all players (except self if mentioned)
2086 void World::SendWorldText(int32 string_id, ...)
2088 std::vector<std::vector<WorldPacket*> > data_cache; // 0 = default, i => i-1 locale index
2090 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2092 if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
2093 continue;
2095 uint32 loc_idx = itr->second->GetSessionDbLocaleIndex();
2096 uint32 cache_idx = loc_idx+1;
2098 std::vector<WorldPacket*>* data_list;
2100 // create if not cached yet
2101 if(data_cache.size() < cache_idx+1 || data_cache[cache_idx].empty())
2103 if(data_cache.size() < cache_idx+1)
2104 data_cache.resize(cache_idx+1);
2106 data_list = &data_cache[cache_idx];
2108 char const* text = objmgr.GetMangosString(string_id,loc_idx);
2110 char buf[1000];
2112 va_list argptr;
2113 va_start( argptr, string_id );
2114 vsnprintf( buf,1000, text, argptr );
2115 va_end( argptr );
2117 char* pos = &buf[0];
2119 while(char* line = ChatHandler::LineFromMessage(pos))
2121 WorldPacket* data = new WorldPacket();
2122 ChatHandler::FillMessageData(data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2123 data_list->push_back(data);
2126 else
2127 data_list = &data_cache[cache_idx];
2129 for(int i = 0; i < data_list->size(); ++i)
2130 itr->second->SendPacket((*data_list)[i]);
2133 // free memory
2134 for(int i = 0; i < data_cache.size(); ++i)
2135 for(int j = 0; j < data_cache[i].size(); ++j)
2136 delete data_cache[i][j];
2139 /// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2140 void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
2142 SessionMap::iterator itr;
2143 for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2145 if (itr->second &&
2146 itr->second->GetPlayer() &&
2147 itr->second->GetPlayer()->IsInWorld() &&
2148 itr->second->GetPlayer()->GetZoneId() == zone &&
2149 itr->second != self &&
2150 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2152 itr->second->SendPacket(packet);
2157 /// Send a System Message to all players in the zone (except self if mentioned)
2158 void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
2160 WorldPacket data;
2161 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
2162 SendZoneMessage(zone, &data, self,team);
2165 /// Kick (and save) all players
2166 void World::KickAll()
2168 // session not removed at kick and will removed in next update tick
2169 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2170 itr->second->KickPlayer();
2173 /// Kick (and save) all players with security level less `sec`
2174 void World::KickAllLess(AccountTypes sec)
2176 // session not removed at kick and will removed in next update tick
2177 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2178 if(itr->second->GetSecurity() < sec)
2179 itr->second->KickPlayer();
2182 /// Kick all queued players
2183 void World::KickAllQueued()
2185 // session not removed at kick and will removed in next update tick
2186 //TODO here
2187 // for (Queue::iterator itr = m_QueuedPlayer.begin(); itr != m_QueuedPlayer.end(); ++itr)
2188 // if(WorldSession* session = (*itr)->GetSession())
2189 // session->KickPlayer();
2191 m_QueuedPlayer.empty();
2194 /// Kick (and save) the designated player
2195 bool World::KickPlayer(std::string playerName)
2197 SessionMap::iterator itr;
2199 // session not removed at kick and will removed in next update tick
2200 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2202 if(!itr->second)
2203 continue;
2204 Player *player = itr->second->GetPlayer();
2205 if(!player)
2206 continue;
2207 if( player->IsInWorld() )
2209 if (playerName == player->GetName())
2211 itr->second->KickPlayer();
2212 return true;
2216 return false;
2219 /// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2220 BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, std::string duration, std::string reason, std::string author)
2222 loginDatabase.escape_string(nameOrIP);
2223 loginDatabase.escape_string(reason);
2224 std::string safe_author=author;
2225 loginDatabase.escape_string(safe_author);
2227 uint32 duration_secs = TimeStringToSecs(duration);
2228 QueryResult *resultAccounts = NULL; //used for kicking
2230 ///- Update the database with ban information
2231 switch(mode)
2233 case BAN_IP:
2234 //No SQL injection as strings are escaped
2235 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
2236 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());
2237 break;
2238 case BAN_ACCOUNT:
2239 //No SQL injection as string is escaped
2240 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2241 break;
2242 case BAN_CHARACTER:
2243 //No SQL injection as string is escaped
2244 resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2245 break;
2246 default:
2247 return BAN_SYNTAX_ERROR;
2250 if(!resultAccounts)
2252 if(mode==BAN_IP)
2253 return BAN_SUCCESS; // ip correctly banned but nobody affected (yet)
2254 else
2255 return BAN_NOTFOUND; // Nobody to ban
2258 ///- Disconnect all affected players (for IP it can be several)
2261 Field* fieldsAccount = resultAccounts->Fetch();
2262 uint32 account = fieldsAccount->GetUInt32();
2264 if(mode!=BAN_IP)
2266 //No SQL injection as strings are escaped
2267 loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2268 account,duration_secs,safe_author.c_str(),reason.c_str());
2271 if (WorldSession* sess = FindSession(account))
2272 if(std::string(sess->GetPlayerName()) != author)
2273 sess->KickPlayer();
2275 while( resultAccounts->NextRow() );
2277 delete resultAccounts;
2278 return BAN_SUCCESS;
2281 /// Remove a ban from an account or IP address
2282 bool World::RemoveBanAccount(BanMode mode, std::string nameOrIP)
2284 if (mode == BAN_IP)
2286 loginDatabase.escape_string(nameOrIP);
2287 loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
2289 else
2291 uint32 account = 0;
2292 if (mode == BAN_ACCOUNT)
2293 account = accmgr.GetId (nameOrIP);
2294 else if (mode == BAN_CHARACTER)
2295 account = objmgr.GetPlayerAccountIdByPlayerName (nameOrIP);
2297 if (!account)
2298 return false;
2300 //NO SQL injection as account is uint32
2301 loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
2303 return true;
2306 /// Update the game time
2307 void World::_UpdateGameTime()
2309 ///- update the time
2310 time_t thisTime = time(NULL);
2311 uint32 elapsed = uint32(thisTime - m_gameTime);
2312 m_gameTime = thisTime;
2314 ///- if there is a shutdown timer
2315 if(m_ShutdownTimer > 0 && elapsed > 0)
2317 ///- ... and it is overdue, stop the world (set m_stopEvent)
2318 if( m_ShutdownTimer <= elapsed )
2320 if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2321 m_stopEvent = true;
2322 else
2323 m_ShutdownTimer = 1; // minimum timer value to wait idle state
2325 ///- ... else decrease it and if necessary display a shutdown countdown to the users
2326 else
2328 m_ShutdownTimer -= elapsed;
2330 ShutdownMsg();
2335 /// Shutdown the server
2336 void World::ShutdownServ(uint32 time, uint32 options)
2338 m_ShutdownMask = options;
2340 ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2341 if(time==0)
2343 if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2344 m_stopEvent = true;
2345 else
2346 m_ShutdownTimer = 1; //So that the session count is re-evaluated at next world tick
2348 ///- Else set the shutdown timer and warn users
2349 else
2351 m_ShutdownTimer = time;
2352 ShutdownMsg(true);
2356 /// Display a shutdown message to the user(s)
2357 void World::ShutdownMsg(bool show, Player* player)
2359 // not show messages for idle shutdown mode
2360 if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
2361 return;
2363 ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2364 if ( show ||
2365 (m_ShutdownTimer < 10) ||
2366 // < 30 sec; every 5 sec
2367 (m_ShutdownTimer<30 && (m_ShutdownTimer % 5 )==0) ||
2368 // < 5 min ; every 1 min
2369 (m_ShutdownTimer<5*MINUTE && (m_ShutdownTimer % MINUTE )==0) ||
2370 // < 30 min ; every 5 min
2371 (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
2372 // < 12 h ; every 1 h
2373 (m_ShutdownTimer<12*HOUR && (m_ShutdownTimer % HOUR )==0) ||
2374 // > 12 h ; every 12 h
2375 (m_ShutdownTimer>12*HOUR && (m_ShutdownTimer % (12*HOUR) )==0))
2377 std::string str = secsToTimeString(m_ShutdownTimer);
2379 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
2381 SendServerMessage(msgid,str.c_str(),player);
2382 DEBUG_LOG("Server is %s in %s",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"),str.c_str());
2386 /// Cancel a planned server shutdown
2387 void World::ShutdownCancel()
2389 if(!m_ShutdownTimer)
2390 return;
2392 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2394 m_ShutdownMask = 0;
2395 m_ShutdownTimer = 0;
2396 SendServerMessage(msgid);
2398 DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2401 /// Send a server message to the user(s)
2402 void World::SendServerMessage(uint32 type, const char *text, Player* player)
2404 WorldPacket data(SMSG_SERVER_MESSAGE, 50); // guess size
2405 data << uint32(type);
2406 if(type <= SERVER_MSG_STRING)
2407 data << text;
2409 if(player)
2410 player->GetSession()->SendPacket(&data);
2411 else
2412 SendGlobalMessage( &data );
2415 void World::UpdateSessions( time_t diff )
2417 while(!addSessQueue.empty())
2419 WorldSession* sess = addSessQueue.next ();
2420 AddSession_ (sess);
2423 ///- Delete kicked sessions at add new session
2424 for (std::set<WorldSession*>::iterator itr = m_kicked_sessions.begin(); itr != m_kicked_sessions.end(); ++itr)
2426 RemoveQueuedPlayer (*itr);
2427 delete *itr;
2429 m_kicked_sessions.clear();
2431 ///- Then send an update signal to remaining ones
2432 for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2434 next = itr;
2435 ++next;
2437 if(!itr->second)
2438 continue;
2440 ///- and remove not active sessions from the list
2441 if(!itr->second->Update(diff)) // As interval = 0
2443 delete itr->second;
2444 m_sessions.erase(itr);
2449 // This handles the issued and queued CLI commands
2450 void World::ProcessCliCommands()
2452 if (cliCmdQueue.empty())
2453 return;
2455 CliCommandHolder::Print* zprint;
2457 while (!cliCmdQueue.empty())
2459 sLog.outDebug("CLI command under processing...");
2460 CliCommandHolder *command = cliCmdQueue.next();
2462 zprint = command->m_print;
2464 CliHandler(zprint).ParseCommands(command->m_command);
2466 delete command;
2469 // print the console message here so it looks right
2470 zprint("mangos>");
2473 void World::InitResultQueue()
2475 m_resultQueue = new SqlResultQueue;
2476 CharacterDatabase.SetResultQueue(m_resultQueue);
2479 void World::UpdateResultQueue()
2481 m_resultQueue->Update();
2484 void World::UpdateRealmCharCount(uint32 accountId)
2486 CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2487 "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2490 void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2492 if (resultCharCount)
2494 Field *fields = resultCharCount->Fetch();
2495 uint32 charCount = fields[0].GetUInt32();
2496 delete resultCharCount;
2497 loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2498 loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2502 void World::InitDailyQuestResetTime()
2504 time_t mostRecentQuestTime;
2506 QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2507 if(result)
2509 Field *fields = result->Fetch();
2511 mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2512 delete result;
2514 else
2515 mostRecentQuestTime = 0;
2517 // client built-in time for reset is 6:00 AM
2518 // FIX ME: client not show day start time
2519 time_t curTime = time(NULL);
2520 tm localTm = *localtime(&curTime);
2521 localTm.tm_hour = 6;
2522 localTm.tm_min = 0;
2523 localTm.tm_sec = 0;
2525 // current day reset time
2526 time_t curDayResetTime = mktime(&localTm);
2528 // last reset time before current moment
2529 time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2531 // need reset (if we have quest time before last reset time (not processed by some reason)
2532 if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2533 m_NextDailyQuestReset = mostRecentQuestTime;
2534 else
2536 // plan next reset time
2537 m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2541 void World::ResetDailyQuests()
2543 sLog.outDetail("Daily quests reset for all characters.");
2544 CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2545 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2546 if(itr->second->GetPlayer())
2547 itr->second->GetPlayer()->ResetDailyQuestStatus();
2550 void World::SetPlayerLimit( int32 limit, bool needUpdate )
2552 if(limit < -SEC_ADMINISTRATOR)
2553 limit = -SEC_ADMINISTRATOR;
2555 // lock update need
2556 bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2558 m_playerLimit = limit;
2560 if(db_update_need)
2561 loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2564 void World::UpdateMaxSessionCounters()
2566 m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2567 m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2570 void World::LoadDBVersion()
2572 QueryResult* result = WorldDatabase.Query("SELECT version FROM db_version LIMIT 1");
2573 if(result)
2575 Field* fields = result->Fetch();
2577 m_DBVersion = fields[0].GetString();
2578 delete result;
2580 else
2581 m_DBVersion = "unknown world database";