Implemented ACHIEVEMENT_FLAG_REALM_FIRST_REACH
[AHbot.git] / src / game / World.cpp
blob7647abbff699d4d540115de0e80526c2757d1e18
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.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],ATTACK_DISTANCE,ATTACK_DISTANCE);
484 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = ATTACK_DISTANCE;
487 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = sConfig.GetFloatDefault("DurabilityLossChance.Damage",0.5f);
488 if(rate_values[RATE_DURABILITY_LOSS_DAMAGE] < 0.0f)
490 sLog.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_DAMAGE]);
491 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = 0.0f;
493 rate_values[RATE_DURABILITY_LOSS_ABSORB] = sConfig.GetFloatDefault("DurabilityLossChance.Absorb",0.5f);
494 if(rate_values[RATE_DURABILITY_LOSS_ABSORB] < 0.0f)
496 sLog.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_ABSORB]);
497 rate_values[RATE_DURABILITY_LOSS_ABSORB] = 0.0f;
499 rate_values[RATE_DURABILITY_LOSS_PARRY] = sConfig.GetFloatDefault("DurabilityLossChance.Parry",0.05f);
500 if(rate_values[RATE_DURABILITY_LOSS_PARRY] < 0.0f)
502 sLog.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_PARRY]);
503 rate_values[RATE_DURABILITY_LOSS_PARRY] = 0.0f;
505 rate_values[RATE_DURABILITY_LOSS_BLOCK] = sConfig.GetFloatDefault("DurabilityLossChance.Block",0.05f);
506 if(rate_values[RATE_DURABILITY_LOSS_BLOCK] < 0.0f)
508 sLog.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_BLOCK]);
509 rate_values[RATE_DURABILITY_LOSS_BLOCK] = 0.0f;
512 ///- Read other configuration items from the config file
514 m_configs[CONFIG_COMPRESSION] = sConfig.GetIntDefault("Compression", 1);
515 if(m_configs[CONFIG_COMPRESSION] < 1 || m_configs[CONFIG_COMPRESSION] > 9)
517 sLog.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs[CONFIG_COMPRESSION]);
518 m_configs[CONFIG_COMPRESSION] = 1;
520 m_configs[CONFIG_ADDON_CHANNEL] = sConfig.GetBoolDefault("AddonChannel", true);
521 m_configs[CONFIG_GRID_UNLOAD] = sConfig.GetBoolDefault("GridUnload", true);
522 m_configs[CONFIG_INTERVAL_SAVE] = sConfig.GetIntDefault("PlayerSaveInterval", 900000);
524 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = sConfig.GetIntDefault("GridCleanUpDelay", 300000);
525 if(m_configs[CONFIG_INTERVAL_GRIDCLEAN] < MIN_GRID_DELAY)
527 sLog.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_GRIDCLEAN],MIN_GRID_DELAY);
528 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = MIN_GRID_DELAY;
530 if(reload)
531 MapManager::Instance().SetGridCleanUpDelay(m_configs[CONFIG_INTERVAL_GRIDCLEAN]);
533 m_configs[CONFIG_INTERVAL_MAPUPDATE] = sConfig.GetIntDefault("MapUpdateInterval", 100);
534 if(m_configs[CONFIG_INTERVAL_MAPUPDATE] < MIN_MAP_UPDATE_DELAY)
536 sLog.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_MAPUPDATE],MIN_MAP_UPDATE_DELAY);
537 m_configs[CONFIG_INTERVAL_MAPUPDATE] = MIN_MAP_UPDATE_DELAY;
539 if(reload)
540 MapManager::Instance().SetMapUpdateInterval(m_configs[CONFIG_INTERVAL_MAPUPDATE]);
542 m_configs[CONFIG_INTERVAL_CHANGEWEATHER] = sConfig.GetIntDefault("ChangeWeatherInterval", 600000);
544 if(reload)
546 uint32 val = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
547 if(val!=m_configs[CONFIG_PORT_WORLD])
548 sLog.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_PORT_WORLD]);
550 else
551 m_configs[CONFIG_PORT_WORLD] = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
553 if(reload)
555 uint32 val = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
556 if(val!=m_configs[CONFIG_SOCKET_SELECTTIME])
557 sLog.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[DEFAULT_SOCKET_SELECT_TIME]);
559 else
560 m_configs[CONFIG_SOCKET_SELECTTIME] = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
562 m_configs[CONFIG_GROUP_XP_DISTANCE] = sConfig.GetIntDefault("MaxGroupXPDistance", 74);
563 /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
564 m_configs[CONFIG_SIGHT_MONSTER] = sConfig.GetIntDefault("MonsterSight", 50);
565 m_configs[CONFIG_SIGHT_GUARDER] = sConfig.GetIntDefault("GuarderSight", 50);
567 if(reload)
569 uint32 val = sConfig.GetIntDefault("GameType", 0);
570 if(val!=m_configs[CONFIG_GAME_TYPE])
571 sLog.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_GAME_TYPE]);
573 else
574 m_configs[CONFIG_GAME_TYPE] = sConfig.GetIntDefault("GameType", 0);
576 if(reload)
578 uint32 val = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
579 if(val!=m_configs[CONFIG_REALM_ZONE])
580 sLog.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_REALM_ZONE]);
582 else
583 m_configs[CONFIG_REALM_ZONE] = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
585 m_configs[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS] = sConfig.GetBoolDefault("AllowTwoSide.Accounts", false);
586 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
587 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
588 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
589 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
590 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
591 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
592 m_configs[CONFIG_ALLOW_TWO_SIDE_WHO_LIST] = sConfig.GetBoolDefault("AllowTwoSide.WhoList", false);
593 m_configs[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND] = sConfig.GetBoolDefault("AllowTwoSide.AddFriend", false);
594 m_configs[CONFIG_STRICT_PLAYER_NAMES] = sConfig.GetIntDefault("StrictPlayerNames", 0);
595 m_configs[CONFIG_STRICT_CHARTER_NAMES] = sConfig.GetIntDefault("StrictCharterNames", 0);
596 m_configs[CONFIG_STRICT_PET_NAMES] = sConfig.GetIntDefault("StrictPetNames", 0);
598 m_configs[CONFIG_CHARACTERS_CREATING_DISABLED] = sConfig.GetIntDefault("CharactersCreatingDisabled", 0);
600 m_configs[CONFIG_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("CharactersPerRealm", 10);
601 if(m_configs[CONFIG_CHARACTERS_PER_REALM] < 1 || m_configs[CONFIG_CHARACTERS_PER_REALM] > 10)
603 sLog.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs[CONFIG_CHARACTERS_PER_REALM]);
604 m_configs[CONFIG_CHARACTERS_PER_REALM] = 10;
607 // must be after CONFIG_CHARACTERS_PER_REALM
608 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = sConfig.GetIntDefault("CharactersPerAccount", 50);
609 if(m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] < m_configs[CONFIG_CHARACTERS_PER_REALM])
611 sLog.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs[CONFIG_CHARACTERS_PER_ACCOUNT],m_configs[CONFIG_CHARACTERS_PER_REALM]);
612 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = m_configs[CONFIG_CHARACTERS_PER_REALM];
615 m_configs[CONFIG_SKIP_CINEMATICS] = sConfig.GetIntDefault("SkipCinematics", 0);
616 if(m_configs[CONFIG_SKIP_CINEMATICS] < 0 || m_configs[CONFIG_SKIP_CINEMATICS] > 2)
618 sLog.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs[CONFIG_SKIP_CINEMATICS]);
619 m_configs[CONFIG_SKIP_CINEMATICS] = 0;
622 if(reload)
624 uint32 val = sConfig.GetIntDefault("MaxPlayerLevel", 60);
625 if(val!=m_configs[CONFIG_MAX_PLAYER_LEVEL])
626 sLog.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
628 else
629 m_configs[CONFIG_MAX_PLAYER_LEVEL] = sConfig.GetIntDefault("MaxPlayerLevel", 60);
630 if(m_configs[CONFIG_MAX_PLAYER_LEVEL] > 255)
632 sLog.outError("MaxPlayerLevel (%i) must be in range 1..255. Set to 255.",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
633 m_configs[CONFIG_MAX_PLAYER_LEVEL] = 255;
636 m_configs[CONFIG_START_PLAYER_LEVEL] = sConfig.GetIntDefault("StartPlayerLevel", 1);
637 if(m_configs[CONFIG_START_PLAYER_LEVEL] < 1)
639 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]);
640 m_configs[CONFIG_START_PLAYER_LEVEL] = 1;
642 else if(m_configs[CONFIG_START_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
644 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]);
645 m_configs[CONFIG_START_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
647 m_configs[CONFIG_MAX_HONOR_POINTS] = sConfig.GetIntDefault("MaxHonorPoints", 75000);
648 m_configs[CONFIG_MAX_ARENA_POINTS] = sConfig.GetIntDefault("MaxArenaPoints", 5000);
650 m_configs[CONFIG_INSTANCE_IGNORE_LEVEL] = sConfig.GetBoolDefault("Instance.IgnoreLevel", false);
651 m_configs[CONFIG_INSTANCE_IGNORE_RAID] = sConfig.GetBoolDefault("Instance.IgnoreRaid", false);
653 m_configs[CONFIG_BATTLEGROUND_CAST_DESERTER] = sConfig.GetBoolDefault("Battleground.CastDeserter", true);
654 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.Enable", true);
655 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false);
657 m_configs[CONFIG_CAST_UNSTUCK] = sConfig.GetBoolDefault("CastUnstuck", true);
658 m_configs[CONFIG_INSTANCE_RESET_TIME_HOUR] = sConfig.GetIntDefault("Instance.ResetTimeHour", 4);
659 m_configs[CONFIG_INSTANCE_UNLOAD_DELAY] = sConfig.GetIntDefault("Instance.UnloadDelay", 1800000);
661 m_configs[CONFIG_MAX_PRIMARY_TRADE_SKILL] = sConfig.GetIntDefault("MaxPrimaryTradeSkill", 2);
662 m_configs[CONFIG_MIN_PETITION_SIGNS] = sConfig.GetIntDefault("MinPetitionSigns", 9);
663 if(m_configs[CONFIG_MIN_PETITION_SIGNS] > 9)
665 sLog.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.",m_configs[CONFIG_MIN_PETITION_SIGNS]);
666 m_configs[CONFIG_MIN_PETITION_SIGNS] = 9;
669 m_configs[CONFIG_GM_LOGIN_STATE] = sConfig.GetIntDefault("GM.LoginState",2);
670 m_configs[CONFIG_GM_ACCEPT_TICKETS] = sConfig.GetIntDefault("GM.AcceptTickets",2);
671 m_configs[CONFIG_GM_CHAT] = sConfig.GetIntDefault("GM.Chat",2);
672 m_configs[CONFIG_GM_WISPERING_TO] = sConfig.GetIntDefault("GM.WhisperingTo",2);
674 m_configs[CONFIG_GM_IN_GM_LIST] = sConfig.GetBoolDefault("GM.InGMList",false);
675 m_configs[CONFIG_GM_IN_WHO_LIST] = sConfig.GetBoolDefault("GM.InWhoList",false);
676 m_configs[CONFIG_GM_LOG_TRADE] = sConfig.GetBoolDefault("GM.LogTrade", false);
678 m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
680 m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
682 m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
683 if(m_configs[CONFIG_UPTIME_UPDATE]<=0)
685 sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
686 m_configs[CONFIG_UPTIME_UPDATE] = 10;
688 if(reload)
690 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
691 m_timers[WUPDATE_UPTIME].Reset();
694 m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
695 m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
696 m_configs[CONFIG_SKILL_CHANCE_GREEN] = sConfig.GetIntDefault("SkillChance.Green",25);
697 m_configs[CONFIG_SKILL_CHANCE_GREY] = sConfig.GetIntDefault("SkillChance.Grey",0);
699 m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS] = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
700 m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS] = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
702 m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
704 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = sConfig.GetIntDefault("SkillGain.Crafting", 1);
705 if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
707 sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
708 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
711 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = sConfig.GetIntDefault("SkillGain.Defense", 1);
712 if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
714 sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
715 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
718 m_configs[CONFIG_SKILL_GAIN_GATHERING] = sConfig.GetIntDefault("SkillGain.Gathering", 1);
719 if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
721 sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
722 m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
725 m_configs[CONFIG_SKILL_GAIN_WEAPON] = sConfig.GetIntDefault("SkillGain.Weapon", 1);
726 if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
728 sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
729 m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
732 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
733 if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
735 sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
736 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
739 m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
740 m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
742 if(reload)
744 uint32 val = sConfig.GetIntDefault("Expansion",1);
745 if(val!=m_configs[CONFIG_EXPANSION])
746 sLog.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
748 else
749 m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",1);
751 m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
752 m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
753 m_configs[CONFIG_CHATFLOOD_MUTE_TIME] = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
755 m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
757 m_configs[CONFIG_CREATURE_FAMILY_ASSISTEMCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistenceRadius",10);
759 m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
761 // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level (255)
762 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff",4);
763 if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > 255)
764 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = 255;
765 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff",7);
766 if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > 255)
767 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = 255;
769 m_configs[CONFIG_DETECT_POS_COLLISION] = sConfig.GetBoolDefault("DetectPosCollision", true);
771 m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
772 m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
774 m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
775 m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
777 m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
778 m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
779 m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
780 m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
781 m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
783 m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault("Death.SicknessLevel", 11);
784 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
785 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
787 m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
789 // always use declined names in the russian client
790 m_configs[CONFIG_DECLINED_NAMES_USED] =
791 (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
793 m_configs[CONFIG_LISTEN_RANGE_SAY] = sConfig.GetIntDefault("ListenRange.Say", 25);
794 m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
795 m_configs[CONFIG_LISTEN_RANGE_YELL] = sConfig.GetIntDefault("ListenRange.Yell", 300);
797 m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
798 if(m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
800 sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
801 m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
803 m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
804 if(m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
806 sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
807 m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
810 m_MaxVisibleDistanceForCreature = sConfig.GetFloatDefault("Visibility.Distance.Creature", DEFAULT_VISIBILITY_DISTANCE);
811 if(m_MaxVisibleDistanceForCreature < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
813 sLog.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
814 m_MaxVisibleDistanceForCreature = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
816 else if(m_MaxVisibleDistanceForCreature + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
818 sLog.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
819 m_MaxVisibleDistanceForCreature = MAX_VISIBILITY_DISTANCE-m_VisibleUnitGreyDistance;
821 m_MaxVisibleDistanceForPlayer = sConfig.GetFloatDefault("Visibility.Distance.Player", DEFAULT_VISIBILITY_DISTANCE);
822 if(m_MaxVisibleDistanceForPlayer < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
824 sLog.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
825 m_MaxVisibleDistanceForPlayer = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
827 else if(m_MaxVisibleDistanceForPlayer + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
829 sLog.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
830 m_MaxVisibleDistanceForPlayer = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
832 m_MaxVisibleDistanceForObject = sConfig.GetFloatDefault("Visibility.Distance.Gameobject", DEFAULT_VISIBILITY_DISTANCE);
833 if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
835 sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
836 m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
838 else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
840 sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
841 m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
843 m_MaxVisibleDistanceInFlight = sConfig.GetFloatDefault("Visibility.Distance.InFlight", DEFAULT_VISIBILITY_DISTANCE);
844 if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
846 sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
847 m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
850 ///- Read the "Data" directory from the config file
851 std::string dataPath = sConfig.GetStringDefault("DataDir","./");
852 if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
853 dataPath.append("/");
855 if(reload)
857 if(dataPath!=m_dataPath)
858 sLog.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath.c_str());
860 else
862 m_dataPath = dataPath;
863 sLog.outString("Using DataDir %s",m_dataPath.c_str());
866 bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
867 bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
868 std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
869 std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
870 VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
871 VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
872 VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
873 VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
874 sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
875 sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
876 sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
879 /// Initialize the World
880 void World::SetInitialWorldSettings()
882 ///- Initialize the random number generator
883 srand((unsigned int)time(NULL));
885 ///- Initialize config settings
886 LoadConfigSettings();
888 ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
889 objmgr.SetHighestGuids();
891 ///- Check the existence of the map files for all races' startup areas.
892 if( !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
893 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
894 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
895 ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
896 ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
897 ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
898 ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
899 ||m_configs[CONFIG_EXPANSION] && (
900 !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
902 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());
903 exit(1);
906 ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
907 sLog.outString( "" );
908 sLog.outString( "Loading MaNGOS strings..." );
909 if (!objmgr.LoadMangosStrings())
910 exit(1); // Error message displayed in function already
912 ///- Update the realm entry in the database with the realm type from the config file
913 //No SQL injection as values are treated as integers
915 // not send custom type REALM_FFA_PVP to realm list
916 uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
917 uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
918 loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
920 ///- Remove the bones after a restart
921 CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
923 ///- Load the DBC files
924 sLog.outString("Initialize data stores...");
925 LoadDBCStores(m_dataPath);
926 DetectDBCLang();
928 sLog.outString( "Loading InstanceTemplate" );
929 objmgr.LoadInstanceTemplate();
931 sLog.outString( "Loading AchievementCriteriaList..." );
932 objmgr.LoadAchievementCriteriaList();
934 sLog.outString( "Loading completed achievements..." );
935 objmgr.LoadCompletedAchievements();
937 sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
938 spellmgr.LoadSkillLineAbilityMap();
940 ///- Clean up and pack instances
941 sLog.outString( "Cleaning up instances..." );
942 sInstanceSaveManager.CleanupInstances(); // must be called before `creature_respawn`/`gameobject_respawn` tables
944 sLog.outString( "Packing instances..." );
945 sInstanceSaveManager.PackInstances();
947 sLog.outString( "Loading Localization strings..." );
948 objmgr.LoadCreatureLocales();
949 objmgr.LoadGameObjectLocales();
950 objmgr.LoadItemLocales();
951 objmgr.LoadQuestLocales();
952 objmgr.LoadNpcTextLocales();
953 objmgr.LoadPageTextLocales();
954 objmgr.LoadNpcOptionLocales();
955 objmgr.SetDBCLocaleIndex(GetDefaultDbcLocale()); // Get once for all the locale index of DBC language (console/broadcasts)
957 sLog.outString( "Loading Page Texts..." );
958 objmgr.LoadPageTexts();
960 sLog.outString( "Loading Game Object Templates..." ); // must be after LoadPageTexts
961 objmgr.LoadGameobjectInfo();
963 sLog.outString( "Loading Spell Chain Data..." );
964 spellmgr.LoadSpellChains();
966 sLog.outString( "Loading Spell Elixir types..." );
967 spellmgr.LoadSpellElixirs();
969 sLog.outString( "Loading Spell Learn Skills..." );
970 spellmgr.LoadSpellLearnSkills(); // must be after LoadSpellChains
972 sLog.outString( "Loading Spell Learn Spells..." );
973 spellmgr.LoadSpellLearnSpells();
975 sLog.outString( "Loading Spell Proc Event conditions..." );
976 spellmgr.LoadSpellProcEvents();
978 sLog.outString( "Loading Aggro Spells Definitions...");
979 spellmgr.LoadSpellThreats();
981 sLog.outString( "Loading NPC Texts..." );
982 objmgr.LoadGossipText();
984 sLog.outString( "Loading Item Random Enchantments Table..." );
985 LoadRandomEnchantmentsTable();
987 sLog.outString( "Loading Items..." ); // must be after LoadRandomEnchantmentsTable and LoadPageTexts
988 objmgr.LoadItemPrototypes();
990 sLog.outString( "Loading Item Texts..." );
991 objmgr.LoadItemTexts();
993 sLog.outString( "Loading Creature Model Based Info Data..." );
994 objmgr.LoadCreatureModelInfo();
996 sLog.outString( "Loading Equipment templates...");
997 objmgr.LoadEquipmentTemplates();
999 sLog.outString( "Loading Creature templates..." );
1000 objmgr.LoadCreatureTemplates();
1002 sLog.outString( "Loading SpellsScriptTarget...");
1003 spellmgr.LoadSpellScriptTarget(); // must be after LoadCreatureTemplates and LoadGameobjectInfo
1005 sLog.outString( "Loading Creature Reputation OnKill Data..." );
1006 objmgr.LoadReputationOnKill();
1008 sLog.outString( "Loading Pet Create Spells..." );
1009 objmgr.LoadPetCreateSpells();
1011 sLog.outString( "Loading Creature Data..." );
1012 objmgr.LoadCreatures();
1014 sLog.outString( "Loading Creature Addon Data..." );
1015 objmgr.LoadCreatureAddons(); // must be after LoadCreatureTemplates() and LoadCreatures()
1017 sLog.outString( "Loading Creature Respawn Data..." ); // must be after PackInstances()
1018 objmgr.LoadCreatureRespawnTimes();
1020 sLog.outString( "Loading Gameobject Data..." );
1021 objmgr.LoadGameobjects();
1023 sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1024 objmgr.LoadGameobjectRespawnTimes();
1026 sLog.outString( "Loading Game Event Data...");
1027 gameeventmgr.LoadFromDB();
1029 sLog.outString( "Loading Weather Data..." );
1030 objmgr.LoadWeatherZoneChances();
1032 sLog.outString( "Loading Quests..." );
1033 objmgr.LoadQuests(); // must be loaded after DBCs, creature_template, item_template, gameobject tables
1035 sLog.outString( "Loading Quests Relations..." );
1036 objmgr.LoadQuestRelations(); // must be after quest load
1038 sLog.outString( "Loading AreaTrigger definitions..." );
1039 objmgr.LoadAreaTriggerTeleports(); // must be after item template load
1041 sLog.outString( "Loading Quest Area Triggers..." );
1042 objmgr.LoadQuestAreaTriggers(); // must be after LoadQuests
1044 sLog.outString( "Loading Tavern Area Triggers..." );
1045 objmgr.LoadTavernAreaTriggers();
1047 sLog.outString( "Loading AreaTrigger script names..." );
1048 objmgr.LoadAreaTriggerScripts();
1050 sLog.outString( "Loading Graveyard-zone links...");
1051 objmgr.LoadGraveyardZones();
1053 sLog.outString( "Loading Spell target coordinates..." );
1054 spellmgr.LoadSpellTargetPositions();
1056 sLog.outString( "Loading SpellAffect definitions..." );
1057 spellmgr.LoadSpellAffects();
1059 sLog.outString( "Loading spell pet auras..." );
1060 spellmgr.LoadSpellPetAuras();
1062 sLog.outString( "Loading player Create Info & Level Stats..." );
1063 objmgr.LoadPlayerInfo();
1065 sLog.outString( "Loading Exploration BaseXP Data..." );
1066 objmgr.LoadExplorationBaseXP();
1068 sLog.outString( "Loading Pet Name Parts..." );
1069 objmgr.LoadPetNames();
1071 sLog.outString( "Loading the max pet number..." );
1072 objmgr.LoadPetNumber();
1074 sLog.outString( "Loading pet level stats..." );
1075 objmgr.LoadPetLevelInfo();
1077 sLog.outString( "Loading Player Corpses..." );
1078 objmgr.LoadCorpses();
1080 sLog.outString( "Loading Loot Tables..." );
1081 LoadLootTables();
1083 sLog.outString( "Loading Skill Discovery Table..." );
1084 LoadSkillDiscoveryTable();
1086 sLog.outString( "Loading Skill Extra Item Table..." );
1087 LoadSkillExtraItemTable();
1089 sLog.outString( "Loading Skill Fishing base level requirements..." );
1090 objmgr.LoadFishingBaseSkillLevel();
1092 ///- Load dynamic data tables from the database
1093 sLog.outString( "Loading Auctions..." );
1094 objmgr.LoadAuctionItems();
1095 objmgr.LoadAuctions();
1097 sLog.outString( "Loading Guilds..." );
1098 objmgr.LoadGuilds();
1100 sLog.outString( "Loading ArenaTeams..." );
1101 objmgr.LoadArenaTeams();
1103 sLog.outString( "Loading Groups..." );
1104 objmgr.LoadGroups();
1106 sLog.outString( "Loading ReservedNames..." );
1107 objmgr.LoadReservedPlayersNames();
1109 sLog.outString( "Loading GameObject for quests..." );
1110 objmgr.LoadGameObjectForQuests();
1112 sLog.outString( "Loading BattleMasters..." );
1113 objmgr.LoadBattleMastersEntry();
1115 sLog.outString( "Loading GameTeleports..." );
1116 objmgr.LoadGameTele();
1118 sLog.outString( "Loading Npc Text Id..." );
1119 objmgr.LoadNpcTextId(); // must be after load Creature and NpcText
1121 sLog.outString( "Loading Npc Options..." );
1122 objmgr.LoadNpcOptions();
1124 sLog.outString( "Loading vendors..." );
1125 objmgr.LoadVendors(); // must be after load CreatureTemplate and ItemTemplate
1127 sLog.outString( "Loading trainers..." );
1128 objmgr.LoadTrainerSpell(); // must be after load CreatureTemplate
1130 sLog.outString( "Loading Waypoints..." );
1131 WaypointMgr.Load();
1133 ///- Handle outdated emails (delete/return)
1134 sLog.outString( "Returning old mails..." );
1135 objmgr.ReturnOrDeleteOldMails(false);
1137 ///- Load and initialize scripts
1138 sLog.outString( "Loading Scripts..." );
1139 objmgr.LoadQuestStartScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1140 objmgr.LoadQuestEndScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1141 objmgr.LoadSpellScripts(); // must be after load Creature/Gameobject(Template/Data)
1142 objmgr.LoadGameObjectScripts(); // must be after load Creature/Gameobject(Template/Data)
1143 objmgr.LoadEventScripts(); // must be after load Creature/Gameobject(Template/Data)
1145 sLog.outString( "Initializing Scripts..." );
1146 if(!LoadScriptingModule())
1147 exit(1);
1149 ///- Initialize game time and timers
1150 sLog.outString( "DEBUG:: Initialize game time and timers" );
1151 m_gameTime = time(NULL);
1152 m_startTime=m_gameTime;
1154 tm local;
1155 time_t curr;
1156 time(&curr);
1157 local=*(localtime(&curr)); // dereference and assign
1158 char isoDate[128];
1159 sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1160 local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1162 WorldDatabase.PExecute("INSERT INTO uptime (startstring, starttime, uptime) VALUES('%s', %ld, 0)", isoDate, m_startTime );
1164 m_timers[WUPDATE_OBJECTS].SetInterval(0);
1165 m_timers[WUPDATE_SESSIONS].SetInterval(0);
1166 m_timers[WUPDATE_WEATHERS].SetInterval(1000);
1167 m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*1000); //set auction update interval to 1 minute
1168 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
1169 //Update "uptime" table based on configuration entry in minutes.
1170 m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*1000); //erase corpses every 20 minutes
1172 //to set mailtimer to return mails every day between 4 and 5 am
1173 //mailtimer is increased when updating auctions
1174 //one second is 1000 -(tested on win system)
1175 mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * 1000) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1176 //1440
1177 mail_timer_expires = ( (DAY * 1000) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1178 sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1180 ///- Initilize static helper structures
1181 AIRegistry::Initialize();
1182 WaypointMovementGenerator<Creature>::Initialize();
1183 Player::InitVisibleBits();
1185 ///- Initialize MapManager
1186 sLog.outString( "Starting Map System" );
1187 MapManager::Instance().Initialize();
1189 ///- Initialize Battlegrounds
1190 sLog.outString( "Starting BattleGround System" );
1191 sBattleGroundMgr.CreateInitialBattleGrounds();
1193 //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1194 sLog.outString( "Loading Transports..." );
1195 MapManager::Instance().LoadTransports();
1197 sLog.outString("Deleting expired bans..." );
1198 loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1200 sLog.outString("Calculate next daily quest reset time..." );
1201 InitDailyQuestResetTime();
1203 sLog.outString("Starting Game Event system..." );
1204 uint32 nextGameEvent = gameeventmgr.Initialize();
1205 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent); //depend on next event
1207 sLog.outString( "WORLD: World initialized" );
1210 void World::DetectDBCLang()
1212 uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1214 if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1216 sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1217 m_lang_confid = LOCALE_enUS;
1220 ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1222 std::string availableLocalsStr;
1224 int default_locale = MAX_LOCALE;
1225 for (int i = MAX_LOCALE-1; i >= 0; --i)
1227 if ( strlen(race->name[i]) > 0) // check by race names
1229 default_locale = i;
1230 m_availableDbcLocaleMask |= (1 << i);
1231 availableLocalsStr += localeNames[i];
1232 availableLocalsStr += " ";
1236 if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1237 (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1239 default_locale = m_lang_confid;
1242 if(default_locale >= MAX_LOCALE)
1244 sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1245 exit(1);
1248 m_defaultDbcLocale = LocaleConstant(default_locale);
1250 sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1253 /// Update the World !
1254 void World::Update(time_t diff)
1256 ///- Update the different timers
1257 for(int i = 0; i < WUPDATE_COUNT; i++)
1258 if(m_timers[i].GetCurrent()>=0)
1259 m_timers[i].Update(diff);
1260 else m_timers[i].SetCurrent(0);
1262 ///- Update the game time and check for shutdown time
1263 _UpdateGameTime();
1265 /// Handle daily quests reset time
1266 if(m_gameTime > m_NextDailyQuestReset)
1268 ResetDailyQuests();
1269 m_NextDailyQuestReset += DAY;
1272 /// <ul><li> Handle auctions when the timer has passed
1273 if (m_timers[WUPDATE_AUCTIONS].Passed())
1275 m_timers[WUPDATE_AUCTIONS].Reset();
1277 ///- Update mails (return old mails with item, or delete them)
1278 //(tested... works on win)
1279 if (++mail_timer > mail_timer_expires)
1281 mail_timer = 0;
1282 objmgr.ReturnOrDeleteOldMails(true);
1285 AuctionHouseObject* AuctionMap;
1286 for (int i = 0; i < 3; i++)
1288 switch (i)
1290 case 0:
1291 AuctionMap = objmgr.GetAuctionsMap( 6 );//horde
1292 break;
1293 case 1:
1294 AuctionMap = objmgr.GetAuctionsMap( 2 );//alliance
1295 break;
1296 case 2:
1297 AuctionMap = objmgr.GetAuctionsMap( 7 );//neutral
1298 break;
1301 ///- Handle expired auctions
1302 AuctionHouseObject::AuctionEntryMap::iterator itr,next;
1303 for (itr = AuctionMap->GetAuctionsBegin(); itr != AuctionMap->GetAuctionsEnd();itr = next)
1305 next = itr;
1306 ++next;
1307 if (m_gameTime > (itr->second->time))
1309 ///- Either cancel the auction if there was no bidder
1310 if (itr->second->bidder == 0)
1312 objmgr.SendAuctionExpiredMail( itr->second );
1314 ///- Or perform the transaction
1315 else
1317 //we should send an "item sold" message if the seller is online
1318 //we send the item to the winner
1319 //we send the money to the seller
1320 objmgr.SendAuctionSuccessfulMail( itr->second );
1321 objmgr.SendAuctionWonMail( itr->second );
1324 ///- In any case clear the auction
1325 //No SQL injection (Id is integer)
1326 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",itr->second->Id);
1327 objmgr.RemoveAItem(itr->second->item_guidlow);
1328 delete itr->second;
1329 AuctionMap->RemoveAuction(itr->first);
1335 /// <li> Handle session updates when the timer has passed
1336 if (m_timers[WUPDATE_SESSIONS].Passed())
1338 m_timers[WUPDATE_SESSIONS].Reset();
1340 UpdateSessions(diff);
1343 /// <li> Handle weather updates when the timer has passed
1344 if (m_timers[WUPDATE_WEATHERS].Passed())
1346 m_timers[WUPDATE_WEATHERS].Reset();
1348 ///- Send an update signal to Weather objects
1349 WeatherMap::iterator itr, next;
1350 for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1352 next = itr;
1353 ++next;
1355 ///- and remove Weather objects for zones with no player
1356 //As interval > WorldTick
1357 if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1359 delete itr->second;
1360 m_weathers.erase(itr);
1364 /// <li> Update uptime table
1365 if (m_timers[WUPDATE_UPTIME].Passed())
1367 uint32 tmpDiff = (m_gameTime - m_startTime);
1368 uint32 maxClientsNum = sWorld.GetMaxActiveSessionCount();
1370 m_timers[WUPDATE_UPTIME].Reset();
1371 WorldDatabase.PExecute("UPDATE uptime SET uptime = %d, maxplayers = %d WHERE starttime = " I64FMTD, tmpDiff, maxClientsNum, uint64(m_startTime));
1374 /// <li> Handle all other objects
1375 if (m_timers[WUPDATE_OBJECTS].Passed())
1377 m_timers[WUPDATE_OBJECTS].Reset();
1378 ///- Update objects when the timer has passed (maps, transport, creatures,...)
1379 MapManager::Instance().Update(diff); // As interval = 0
1381 ///- Process necessary scripts
1382 if (!m_scriptSchedule.empty())
1383 ScriptsProcess();
1385 sBattleGroundMgr.Update(diff);
1388 // execute callbacks from sql queries that were queued recently
1389 UpdateResultQueue();
1391 ///- Erase corpses once every 20 minutes
1392 if (m_timers[WUPDATE_CORPSES].Passed())
1394 m_timers[WUPDATE_CORPSES].Reset();
1396 CorpsesErase();
1399 ///- Process Game events when necessary
1400 if (m_timers[WUPDATE_EVENTS].Passed())
1402 m_timers[WUPDATE_EVENTS].Reset(); // to give time for Update() to be processed
1403 uint32 nextGameEvent = gameeventmgr.Update();
1404 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1405 m_timers[WUPDATE_EVENTS].Reset();
1408 /// </ul>
1409 ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1410 MapManager::Instance().DoDelayedMovesAndRemoves();
1412 // update the instance reset times
1413 sInstanceSaveManager.Update();
1415 // And last, but not least handle the issued cli commands
1416 ProcessCliCommands();
1419 /// Put scripts in the execution queue
1420 void World::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
1422 ///- Find the script map
1423 ScriptMapMap::const_iterator s = scripts.find(id);
1424 if (s == scripts.end())
1425 return;
1427 // prepare static data
1428 uint64 sourceGUID = source->GetGUID();
1429 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1430 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1432 ///- Schedule script execution for all scripts in the script map
1433 ScriptMap const *s2 = &(s->second);
1434 bool immedScript = false;
1435 for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
1437 ScriptAction sa;
1438 sa.sourceGUID = sourceGUID;
1439 sa.targetGUID = targetGUID;
1440 sa.ownerGUID = ownerGUID;
1442 sa.script = &iter->second;
1443 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + iter->first, sa));
1444 if (iter->first == 0)
1445 immedScript = true;
1447 ///- If one of the effects should be immediate, launch the script execution
1448 if (immedScript)
1449 ScriptsProcess();
1452 void World::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
1454 // NOTE: script record _must_ exist until command executed
1456 // prepare static data
1457 uint64 sourceGUID = source->GetGUID();
1458 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1459 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1461 ScriptAction sa;
1462 sa.sourceGUID = sourceGUID;
1463 sa.targetGUID = targetGUID;
1464 sa.ownerGUID = ownerGUID;
1466 sa.script = &script;
1467 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + delay, sa));
1469 ///- If effects should be immediate, launch the script execution
1470 if(delay == 0)
1471 ScriptsProcess();
1474 /// Process queued scripts
1475 void World::ScriptsProcess()
1477 if (m_scriptSchedule.empty())
1478 return;
1480 ///- Process overdue queued scripts
1481 std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
1482 // ok as multimap is a *sorted* associative container
1483 while (!m_scriptSchedule.empty() && (iter->first <= m_gameTime))
1485 ScriptAction const& step = iter->second;
1487 Object* source = NULL;
1489 if(step.sourceGUID)
1491 switch(GUID_HIPART(step.sourceGUID))
1493 case HIGHGUID_ITEM:
1494 // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1496 Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
1497 if(player)
1498 source = player->GetItemByGuid(step.sourceGUID);
1499 break;
1501 case HIGHGUID_UNIT:
1502 source = HashMapHolder<Creature>::Find(step.sourceGUID);
1503 break;
1504 case HIGHGUID_PET:
1505 source = HashMapHolder<Pet>::Find(step.sourceGUID);
1506 break;
1507 case HIGHGUID_PLAYER:
1508 source = HashMapHolder<Player>::Find(step.sourceGUID);
1509 break;
1510 case HIGHGUID_GAMEOBJECT:
1511 source = HashMapHolder<GameObject>::Find(step.sourceGUID);
1512 break;
1513 case HIGHGUID_CORPSE:
1514 source = HashMapHolder<Corpse>::Find(step.sourceGUID);
1515 break;
1516 default:
1517 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
1518 break;
1522 Object* target = NULL;
1524 if(step.targetGUID)
1526 switch(GUID_HIPART(step.targetGUID))
1528 case HIGHGUID_UNIT:
1529 target = HashMapHolder<Creature>::Find(step.targetGUID);
1530 break;
1531 case HIGHGUID_PET:
1532 target = HashMapHolder<Pet>::Find(step.targetGUID);
1533 break;
1534 case HIGHGUID_PLAYER: // empty GUID case also
1535 target = HashMapHolder<Player>::Find(step.targetGUID);
1536 break;
1537 case HIGHGUID_GAMEOBJECT:
1538 target = HashMapHolder<GameObject>::Find(step.targetGUID);
1539 break;
1540 case HIGHGUID_CORPSE:
1541 target = HashMapHolder<Corpse>::Find(step.targetGUID);
1542 break;
1543 default:
1544 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
1545 break;
1549 switch (step.script->command)
1551 case SCRIPT_COMMAND_TALK:
1553 if(!source)
1555 sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1556 break;
1559 if(source->GetTypeId()!=TYPEID_UNIT)
1561 sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1562 break;
1564 if(step.script->datalong > 3)
1566 sLog.outError("SCRIPT_COMMAND_TALK invalid chat type (%u), skipping.",step.script->datalong);
1567 break;
1570 uint64 unit_target = target ? target->GetGUID() : 0;
1572 //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1573 switch(step.script->datalong)
1575 case 0: // Say
1576 ((Creature *)source)->Say(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
1577 break;
1578 case 1: // Whisper
1579 if(!unit_target)
1581 sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
1582 break;
1584 ((Creature *)source)->Whisper(step.script->datatext.c_str(),unit_target);
1585 break;
1586 case 2: // Yell
1587 ((Creature *)source)->Yell(step.script->datatext.c_str(), LANG_UNIVERSAL, unit_target);
1588 break;
1589 case 3: // Emote text
1590 ((Creature *)source)->TextEmote(step.script->datatext.c_str(), unit_target);
1591 break;
1592 default:
1593 break; // must be already checked at load
1595 break;
1598 case SCRIPT_COMMAND_EMOTE:
1599 if(!source)
1601 sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1602 break;
1605 if(source->GetTypeId()!=TYPEID_UNIT)
1607 sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1608 break;
1611 ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
1612 break;
1613 case SCRIPT_COMMAND_FIELD_SET:
1614 if(!source)
1616 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1617 break;
1619 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1621 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1622 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1623 break;
1626 source->SetUInt32Value(step.script->datalong, step.script->datalong2);
1627 break;
1628 case SCRIPT_COMMAND_MOVE_TO:
1629 if(!source)
1631 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1632 break;
1635 if(source->GetTypeId()!=TYPEID_UNIT)
1637 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1638 break;
1640 ((Unit *)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, ((Unit *)source)->GetUnitMovementFlags(), step.script->datalong2 );
1641 MapManager::Instance().GetMap(((Unit *)source)->GetMapId(), ((Unit *)source))->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
1642 break;
1643 case SCRIPT_COMMAND_FLAG_SET:
1644 if(!source)
1646 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1647 break;
1649 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1651 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1652 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1653 break;
1656 source->SetFlag(step.script->datalong, step.script->datalong2);
1657 break;
1658 case SCRIPT_COMMAND_FLAG_REMOVE:
1659 if(!source)
1661 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1662 break;
1664 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1666 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1667 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1668 break;
1671 source->RemoveFlag(step.script->datalong, step.script->datalong2);
1672 break;
1674 case SCRIPT_COMMAND_TELEPORT_TO:
1676 // accept player in any one from target/source arg
1677 if (!target && !source)
1679 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1680 break;
1683 // must be only Player
1684 if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
1686 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
1687 break;
1690 Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
1692 pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
1693 break;
1696 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
1698 if(!step.script->datalong) // creature not specified
1700 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1701 break;
1704 if(!source)
1706 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1707 break;
1710 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1712 if(!summoner)
1714 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1715 break;
1718 float x = step.script->x;
1719 float y = step.script->y;
1720 float z = step.script->z;
1721 float o = step.script->o;
1723 Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
1724 if (!pCreature)
1726 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
1727 break;
1730 break;
1733 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
1735 if(!step.script->datalong) // gameobject not specified
1737 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1738 break;
1741 if(!source)
1743 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1744 break;
1747 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1749 if(!summoner)
1751 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1752 break;
1755 GameObject *go = NULL;
1756 int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
1758 CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
1759 Cell cell(p);
1760 cell.data.Part.reserved = ALL_DISTRICT;
1762 MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
1763 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(go,go_check);
1765 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1766 CellLock<GridReadGuard> cell_lock(cell, p);
1767 cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(summoner->GetMapId(), summoner));
1769 if ( !go )
1771 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
1772 break;
1775 if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1776 go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1777 go->GetGoType()==GAMEOBJECT_TYPE_DOOR ||
1778 go->GetGoType()==GAMEOBJECT_TYPE_BUTTON ||
1779 go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
1781 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
1782 break;
1785 if( go->isSpawned() )
1786 break; //gameobject already spawned
1788 go->SetLootState(GO_READY);
1789 go->SetRespawnTime(time_to_despawn); //despawn object in ? seconds
1791 MapManager::Instance().GetMap(go->GetMapId(), go)->Add(go);
1792 break;
1794 case SCRIPT_COMMAND_OPEN_DOOR:
1796 if(!step.script->datalong) // door not specified
1798 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1799 break;
1802 if(!source)
1804 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1805 break;
1808 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
1810 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1811 break;
1814 Unit* caster = (Unit*)source;
1816 GameObject *door = NULL;
1817 int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1819 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1820 Cell cell(p);
1821 cell.data.Part.reserved = ALL_DISTRICT;
1823 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1824 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1826 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1827 CellLock<GridReadGuard> cell_lock(cell, p);
1828 cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1830 if ( !door )
1832 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1833 break;
1835 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1837 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1838 break;
1841 if( !door->GetGoState() )
1842 break; //door already open
1844 door->UseDoorOrButton(time_to_close);
1846 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1847 ((GameObject*)target)->UseDoorOrButton(time_to_close);
1848 break;
1850 case SCRIPT_COMMAND_CLOSE_DOOR:
1852 if(!step.script->datalong) // guid for door not specified
1854 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
1855 break;
1858 if(!source)
1860 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
1861 break;
1864 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
1866 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1867 break;
1870 Unit* caster = (Unit*)source;
1872 GameObject *door = NULL;
1873 int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1875 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1876 Cell cell(p);
1877 cell.data.Part.reserved = ALL_DISTRICT;
1879 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1880 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1882 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1883 CellLock<GridReadGuard> cell_lock(cell, p);
1884 cell_lock->Visit(cell_lock, object_checker, *MapManager::Instance().GetMap(caster->GetMapId(), (Unit*)source));
1886 if ( !door )
1888 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1889 break;
1891 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1893 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1894 break;
1897 if( door->GetGoState() )
1898 break; //door already closed
1900 door->UseDoorOrButton(time_to_open);
1902 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1903 ((GameObject*)target)->UseDoorOrButton(time_to_open);
1905 break;
1907 case SCRIPT_COMMAND_QUEST_EXPLORED:
1909 if(!source)
1911 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
1912 break;
1915 if(!target)
1917 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
1918 break;
1921 // when script called for item spell casting then target == (unit or GO) and source is player
1922 WorldObject* worldObject;
1923 Player* player;
1925 if(target->GetTypeId()==TYPEID_PLAYER)
1927 if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
1929 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
1930 break;
1933 worldObject = (WorldObject*)source;
1934 player = (Player*)target;
1936 else
1938 if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
1940 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
1941 break;
1944 if(source->GetTypeId()!=TYPEID_PLAYER)
1946 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
1947 break;
1950 worldObject = (WorldObject*)target;
1951 player = (Player*)source;
1954 // quest id and flags checked at script loading
1955 if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
1956 (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
1957 player->AreaExploredOrEventHappens(step.script->datalong);
1958 else
1959 player->FailQuest(step.script->datalong);
1961 break;
1964 case SCRIPT_COMMAND_ACTIVATE_OBJECT:
1966 if(!source)
1968 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
1969 break;
1972 if(!source->isType(TYPEMASK_UNIT))
1974 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
1975 break;
1978 if(!target)
1980 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
1981 break;
1984 if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
1986 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
1987 break;
1990 Unit* caster = (Unit*)source;
1992 GameObject *go = (GameObject*)target;
1994 go->Use(caster);
1995 break;
1998 case SCRIPT_COMMAND_REMOVE_AURA:
2000 Object* cmdTarget = step.script->datalong2 ? source : target;
2002 if(!cmdTarget)
2004 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
2005 break;
2008 if(!cmdTarget->isType(TYPEMASK_UNIT))
2010 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2011 break;
2014 ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
2015 break;
2018 case SCRIPT_COMMAND_CAST_SPELL:
2020 if(!source)
2022 sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
2023 break;
2026 if(!source->isType(TYPEMASK_UNIT))
2028 sLog.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2029 break;
2032 Object* cmdTarget = step.script->datalong2 ? source : target;
2034 if(!cmdTarget)
2036 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 ? "source" : "target");
2037 break;
2040 if(!cmdTarget->isType(TYPEMASK_UNIT))
2042 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2043 break;
2046 Unit* spellTarget = (Unit*)cmdTarget;
2048 //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2049 ((Unit*)source)->CastSpell(spellTarget,step.script->datalong,false);
2051 break;
2054 default:
2055 sLog.outError("Unknown script command %u called.",step.script->command);
2056 break;
2059 m_scriptSchedule.erase(iter);
2061 iter = m_scriptSchedule.begin();
2063 return;
2066 /// Send a packet to all players (except self if mentioned)
2067 void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
2069 SessionMap::iterator itr;
2070 for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2072 if (itr->second &&
2073 itr->second->GetPlayer() &&
2074 itr->second->GetPlayer()->IsInWorld() &&
2075 itr->second != self &&
2076 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2078 itr->second->SendPacket(packet);
2083 /// Send a System Message to all players (except self if mentioned)
2084 void World::SendWorldText(int32 string_id, ...)
2086 std::vector<std::vector<WorldPacket*> > data_cache; // 0 = default, i => i-1 locale index
2088 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2090 if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
2091 continue;
2093 uint32 loc_idx = itr->second->GetSessionDbLocaleIndex();
2094 uint32 cache_idx = loc_idx+1;
2096 std::vector<WorldPacket*>* data_list;
2098 // create if not cached yet
2099 if(data_cache.size() < cache_idx+1 || data_cache[cache_idx].empty())
2101 if(data_cache.size() < cache_idx+1)
2102 data_cache.resize(cache_idx+1);
2104 data_list = &data_cache[cache_idx];
2106 char const* text = objmgr.GetMangosString(string_id,loc_idx);
2108 char buf[1000];
2110 va_list argptr;
2111 va_start( argptr, string_id );
2112 vsnprintf( buf,1000, text, argptr );
2113 va_end( argptr );
2115 char* pos = &buf[0];
2117 while(char* line = ChatHandler::LineFromMessage(pos))
2119 WorldPacket* data = new WorldPacket();
2120 ChatHandler::FillMessageData(data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2121 data_list->push_back(data);
2124 else
2125 data_list = &data_cache[cache_idx];
2127 for(int i = 0; i < data_list->size(); ++i)
2128 itr->second->SendPacket((*data_list)[i]);
2131 // free memory
2132 for(int i = 0; i < data_cache.size(); ++i)
2133 for(int j = 0; j < data_cache[i].size(); ++j)
2134 delete data_cache[i][j];
2137 /// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2138 void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
2140 SessionMap::iterator itr;
2141 for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2143 if (itr->second &&
2144 itr->second->GetPlayer() &&
2145 itr->second->GetPlayer()->IsInWorld() &&
2146 itr->second->GetPlayer()->GetZoneId() == zone &&
2147 itr->second != self &&
2148 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2150 itr->second->SendPacket(packet);
2155 /// Send a System Message to all players in the zone (except self if mentioned)
2156 void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
2158 WorldPacket data;
2159 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
2160 SendZoneMessage(zone, &data, self,team);
2163 /// Kick (and save) all players
2164 void World::KickAll()
2166 // session not removed at kick and will removed in next update tick
2167 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2168 itr->second->KickPlayer();
2171 /// Kick (and save) all players with security level less `sec`
2172 void World::KickAllLess(AccountTypes sec)
2174 // session not removed at kick and will removed in next update tick
2175 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2176 if(itr->second->GetSecurity() < sec)
2177 itr->second->KickPlayer();
2180 /// Kick all queued players
2181 void World::KickAllQueued()
2183 // session not removed at kick and will removed in next update tick
2184 //TODO here
2185 // for (Queue::iterator itr = m_QueuedPlayer.begin(); itr != m_QueuedPlayer.end(); ++itr)
2186 // if(WorldSession* session = (*itr)->GetSession())
2187 // session->KickPlayer();
2189 m_QueuedPlayer.empty();
2192 /// Kick (and save) the designated player
2193 bool World::KickPlayer(std::string playerName)
2195 SessionMap::iterator itr;
2197 // session not removed at kick and will removed in next update tick
2198 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2200 if(!itr->second)
2201 continue;
2202 Player *player = itr->second->GetPlayer();
2203 if(!player)
2204 continue;
2205 if( player->IsInWorld() )
2207 if (playerName == player->GetName())
2209 itr->second->KickPlayer();
2210 return true;
2214 return false;
2217 /// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2218 BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, std::string duration, std::string reason, std::string author)
2220 loginDatabase.escape_string(nameOrIP);
2221 loginDatabase.escape_string(reason);
2222 std::string safe_author=author;
2223 loginDatabase.escape_string(safe_author);
2225 uint32 duration_secs = TimeStringToSecs(duration);
2226 QueryResult *resultAccounts = NULL; //used for kicking
2228 ///- Update the database with ban information
2229 switch(mode)
2231 case BAN_IP:
2232 //No SQL injection as strings are escaped
2233 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
2234 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());
2235 break;
2236 case BAN_ACCOUNT:
2237 //No SQL injection as string is escaped
2238 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2239 break;
2240 case BAN_CHARACTER:
2241 //No SQL injection as string is escaped
2242 resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2243 break;
2244 default:
2245 return BAN_SYNTAX_ERROR;
2248 if(!resultAccounts)
2250 if(mode==BAN_IP)
2251 return BAN_SUCCESS; // ip correctly banned but nobody affected (yet)
2252 else
2253 return BAN_NOTFOUND; // Nobody to ban
2256 ///- Disconnect all affected players (for IP it can be several)
2259 Field* fieldsAccount = resultAccounts->Fetch();
2260 uint32 account = fieldsAccount->GetUInt32();
2262 if(mode!=BAN_IP)
2264 //No SQL injection as strings are escaped
2265 loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2266 account,duration_secs,safe_author.c_str(),reason.c_str());
2269 if (WorldSession* sess = FindSession(account))
2270 if(std::string(sess->GetPlayerName()) != author)
2271 sess->KickPlayer();
2273 while( resultAccounts->NextRow() );
2275 delete resultAccounts;
2276 return BAN_SUCCESS;
2279 /// Remove a ban from an account or IP address
2280 bool World::RemoveBanAccount(BanMode mode, std::string nameOrIP)
2282 if (mode == BAN_IP)
2284 loginDatabase.escape_string(nameOrIP);
2285 loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
2287 else
2289 uint32 account = 0;
2290 if (mode == BAN_ACCOUNT)
2291 account = accmgr.GetId (nameOrIP);
2292 else if (mode == BAN_CHARACTER)
2293 account = objmgr.GetPlayerAccountIdByPlayerName (nameOrIP);
2295 if (!account)
2296 return false;
2298 //NO SQL injection as account is uint32
2299 loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
2301 return true;
2304 /// Update the game time
2305 void World::_UpdateGameTime()
2307 ///- update the time
2308 time_t thisTime = time(NULL);
2309 uint32 elapsed = uint32(thisTime - m_gameTime);
2310 m_gameTime = thisTime;
2312 ///- if there is a shutdown timer
2313 if(m_ShutdownTimer > 0 && elapsed > 0)
2315 ///- ... and it is overdue, stop the world (set m_stopEvent)
2316 if( m_ShutdownTimer <= elapsed )
2318 if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2319 m_stopEvent = true;
2320 else
2321 m_ShutdownTimer = 1; // minimum timer value to wait idle state
2323 ///- ... else decrease it and if necessary display a shutdown countdown to the users
2324 else
2326 m_ShutdownTimer -= elapsed;
2328 ShutdownMsg();
2333 /// Shutdown the server
2334 void World::ShutdownServ(uint32 time, uint32 options)
2336 m_ShutdownMask = options;
2338 ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2339 if(time==0)
2341 if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2342 m_stopEvent = true;
2343 else
2344 m_ShutdownTimer = 1; //So that the session count is re-evaluated at next world tick
2346 ///- Else set the shutdown timer and warn users
2347 else
2349 m_ShutdownTimer = time;
2350 ShutdownMsg(true);
2354 /// Display a shutdown message to the user(s)
2355 void World::ShutdownMsg(bool show, Player* player)
2357 // not show messages for idle shutdown mode
2358 if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
2359 return;
2361 ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2362 if ( show ||
2363 (m_ShutdownTimer < 10) ||
2364 // < 30 sec; every 5 sec
2365 (m_ShutdownTimer<30 && (m_ShutdownTimer % 5 )==0) ||
2366 // < 5 min ; every 1 min
2367 (m_ShutdownTimer<5*MINUTE && (m_ShutdownTimer % MINUTE )==0) ||
2368 // < 30 min ; every 5 min
2369 (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
2370 // < 12 h ; every 1 h
2371 (m_ShutdownTimer<12*HOUR && (m_ShutdownTimer % HOUR )==0) ||
2372 // > 12 h ; every 12 h
2373 (m_ShutdownTimer>12*HOUR && (m_ShutdownTimer % (12*HOUR) )==0))
2375 std::string str = secsToTimeString(m_ShutdownTimer);
2377 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
2379 SendServerMessage(msgid,str.c_str(),player);
2380 DEBUG_LOG("Server is %s in %s",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"),str.c_str());
2384 /// Cancel a planned server shutdown
2385 void World::ShutdownCancel()
2387 if(!m_ShutdownTimer)
2388 return;
2390 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2392 m_ShutdownMask = 0;
2393 m_ShutdownTimer = 0;
2394 SendServerMessage(msgid);
2396 DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2399 /// Send a server message to the user(s)
2400 void World::SendServerMessage(uint32 type, const char *text, Player* player)
2402 WorldPacket data(SMSG_SERVER_MESSAGE, 50); // guess size
2403 data << uint32(type);
2404 if(type <= SERVER_MSG_STRING)
2405 data << text;
2407 if(player)
2408 player->GetSession()->SendPacket(&data);
2409 else
2410 SendGlobalMessage( &data );
2413 void World::UpdateSessions( time_t diff )
2415 while(!addSessQueue.empty())
2417 WorldSession* sess = addSessQueue.next ();
2418 AddSession_ (sess);
2421 ///- Delete kicked sessions at add new session
2422 for (std::set<WorldSession*>::iterator itr = m_kicked_sessions.begin(); itr != m_kicked_sessions.end(); ++itr)
2423 delete *itr;
2424 m_kicked_sessions.clear();
2426 ///- Then send an update signal to remaining ones
2427 for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2429 next = itr;
2430 ++next;
2432 if(!itr->second)
2433 continue;
2435 ///- and remove not active sessions from the list
2436 if(!itr->second->Update(diff)) // As interval = 0
2438 delete itr->second;
2439 m_sessions.erase(itr);
2444 // This handles the issued and queued CLI commands
2445 void World::ProcessCliCommands()
2447 if (cliCmdQueue.empty())
2448 return;
2450 CliCommandHolder::Print* zprint;
2452 while (!cliCmdQueue.empty())
2454 sLog.outDebug("CLI command under processing...");
2455 CliCommandHolder *command = cliCmdQueue.next();
2457 zprint = command->m_print;
2459 CliHandler(zprint).ParseCommands(command->m_command);
2461 delete command;
2464 // print the console message here so it looks right
2465 zprint("mangos>");
2468 void World::InitResultQueue()
2470 m_resultQueue = new SqlResultQueue;
2471 CharacterDatabase.SetResultQueue(m_resultQueue);
2474 void World::UpdateResultQueue()
2476 m_resultQueue->Update();
2479 void World::UpdateRealmCharCount(uint32 accountId)
2481 CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2482 "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2485 void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2487 if (resultCharCount)
2489 Field *fields = resultCharCount->Fetch();
2490 uint32 charCount = fields[0].GetUInt32();
2491 delete resultCharCount;
2492 loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2493 loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2497 void World::InitDailyQuestResetTime()
2499 time_t mostRecentQuestTime;
2501 QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2502 if(result)
2504 Field *fields = result->Fetch();
2506 mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2507 delete result;
2509 else
2510 mostRecentQuestTime = 0;
2512 // client built-in time for reset is 6:00 AM
2513 // FIX ME: client not show day start time
2514 time_t curTime = time(NULL);
2515 tm localTm = *localtime(&curTime);
2516 localTm.tm_hour = 6;
2517 localTm.tm_min = 0;
2518 localTm.tm_sec = 0;
2520 // current day reset time
2521 time_t curDayResetTime = mktime(&localTm);
2523 // last reset time before current moment
2524 time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2526 // need reset (if we have quest time before last reset time (not processed by some reason)
2527 if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2528 m_NextDailyQuestReset = mostRecentQuestTime;
2529 else
2531 // plan next reset time
2532 m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2536 void World::ResetDailyQuests()
2538 sLog.outDetail("Daily quests reset for all characters.");
2539 CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2540 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2541 if(itr->second->GetPlayer())
2542 itr->second->GetPlayer()->ResetDailyQuestStatus();
2545 void World::SetPlayerLimit( int32 limit, bool needUpdate )
2547 if(limit < -SEC_ADMINISTRATOR)
2548 limit = -SEC_ADMINISTRATOR;
2550 // lock update need
2551 bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2553 m_playerLimit = limit;
2555 if(db_update_need)
2556 loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2559 void World::UpdateMaxSessionCounters()
2561 m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2562 m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2565 void World::LoadDBVersion()
2567 QueryResult* result = WorldDatabase.Query("SELECT version FROM db_version LIMIT 1");
2568 if(result)
2570 Field* fields = result->Fetch();
2572 m_DBVersion = fields[0].GetString();
2573 delete result;
2575 else
2576 m_DBVersion = "unknown world database";