Phase system development continue.
[getmangos.git] / src / game / World.cpp
blob621239791c81c00352b65742fe5e90b30bc367e3
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 /** \file
20 \ingroup world
23 #include "Common.h"
24 //#include "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 "AchievementMgr.h"
39 #include "ObjectMgr.h"
40 #include "SpellMgr.h"
41 #include "Chat.h"
42 #include "Database/DBCStores.h"
43 #include "LootMgr.h"
44 #include "ItemEnchantmentMgr.h"
45 #include "MapManager.h"
46 #include "ScriptCalls.h"
47 #include "CreatureAIRegistry.h"
48 #include "Policies/SingletonImp.h"
49 #include "BattleGroundMgr.h"
50 #include "TemporarySummon.h"
51 #include "WaypointMovementGenerator.h"
52 #include "VMapFactory.h"
53 #include "GlobalEvents.h"
54 #include "GameEvent.h"
55 #include "Database/DatabaseImpl.h"
56 #include "GridNotifiersImpl.h"
57 #include "CellImpl.h"
58 #include "InstanceSaveMgr.h"
59 #include "WaypointManager.h"
60 #include "GMTicketMgr.h"
61 #include "Util.h"
63 INSTANTIATE_SINGLETON_1( World );
65 volatile bool World::m_stopEvent = false;
66 uint8 World::m_ExitCode = SHUTDOWN_EXIT_CODE;
67 volatile uint32 World::m_worldLoopCounter = 0;
69 float World::m_MaxVisibleDistanceForCreature = DEFAULT_VISIBILITY_DISTANCE;
70 float World::m_MaxVisibleDistanceForPlayer = DEFAULT_VISIBILITY_DISTANCE;
71 float World::m_MaxVisibleDistanceForObject = DEFAULT_VISIBILITY_DISTANCE;
72 float World::m_MaxVisibleDistanceInFlight = DEFAULT_VISIBILITY_DISTANCE;
73 float World::m_VisibleUnitGreyDistance = 0;
74 float World::m_VisibleObjectGreyDistance = 0;
76 // ServerMessages.dbc
77 enum ServerMessageType
79 SERVER_MSG_SHUTDOWN_TIME = 1,
80 SERVER_MSG_RESTART_TIME = 2,
81 SERVER_MSG_STRING = 3,
82 SERVER_MSG_SHUTDOWN_CANCELLED = 4,
83 SERVER_MSG_RESTART_CANCELLED = 5
86 struct ScriptAction
88 uint64 sourceGUID;
89 uint64 targetGUID;
90 uint64 ownerGUID; // owner of source if source is item
91 ScriptInfo const* script; // pointer to static script data
94 /// World constructor
95 World::World()
97 m_playerLimit = 0;
98 m_allowMovement = true;
99 m_ShutdownMask = 0;
100 m_ShutdownTimer = 0;
101 m_gameTime=time(NULL);
102 m_startTime=m_gameTime;
103 m_maxActiveSessionCount = 0;
104 m_maxQueuedSessionCount = 0;
105 m_resultQueue = NULL;
106 m_NextDailyQuestReset = 0;
108 m_defaultDbcLocale = LOCALE_enUS;
109 m_availableDbcLocaleMask = 0;
112 /// World destructor
113 World::~World()
115 ///- Empty the kicked session set
116 while (!m_sessions.empty())
118 // not remove from queue, prevent loading new sessions
119 delete m_sessions.begin()->second;
120 m_sessions.erase(m_sessions.begin());
123 ///- Empty the WeatherMap
124 for (WeatherMap::iterator itr = m_weathers.begin(); itr != m_weathers.end(); ++itr)
125 delete itr->second;
127 m_weathers.clear();
129 while (!cliCmdQueue.empty())
130 delete cliCmdQueue.next();
132 VMAP::VMapFactory::clear();
134 if(m_resultQueue) delete m_resultQueue;
136 //TODO free addSessQueue
139 /// Find a player in a specified zone
140 Player* World::FindPlayerInZone(uint32 zone)
142 ///- circle through active sessions and return the first player found in the zone
143 SessionMap::iterator itr;
144 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
146 if(!itr->second)
147 continue;
148 Player *player = itr->second->GetPlayer();
149 if(!player)
150 continue;
151 if( player->IsInWorld() && player->GetZoneId() == zone )
153 // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone.
154 return player;
157 return NULL;
160 /// Find a session by its id
161 WorldSession* World::FindSession(uint32 id) const
163 SessionMap::const_iterator itr = m_sessions.find(id);
165 if(itr != m_sessions.end())
166 return itr->second; // also can return NULL for kicked session
167 else
168 return NULL;
171 /// Remove a given session
172 bool World::RemoveSession(uint32 id)
174 ///- Find the session, kick the user, but we can't delete session at this moment to prevent iterator invalidation
175 SessionMap::iterator itr = m_sessions.find(id);
177 if(itr != m_sessions.end() && itr->second)
179 if (itr->second->PlayerLoading())
180 return false;
181 itr->second->KickPlayer();
184 return true;
187 void World::AddSession(WorldSession* s)
189 addSessQueue.add(s);
192 void
193 World::AddSession_ (WorldSession* s)
195 ASSERT (s);
197 //NOTE - Still there is race condition in WorldSession* being used in the Sockets
199 ///- kick already loaded player with same account (if any) and remove session
200 ///- if player is in loading and want to load again, return
201 if (!RemoveSession (s->GetAccountId ()))
203 s->KickPlayer ();
204 delete s; // session not added yet in session list, so not listed in queue
205 return;
208 // decrease session counts only at not reconnection case
209 bool decrease_session = true;
211 // if session already exist, prepare to it deleting at next world update
212 // NOTE - KickPlayer() should be called on "old" in RemoveSession()
214 SessionMap::const_iterator old = m_sessions.find(s->GetAccountId ());
216 if(old != m_sessions.end())
218 // prevent decrease sessions count if session queued
219 if(RemoveQueuedPlayer(old->second))
220 decrease_session = false;
221 // not remove replaced session form queue if listed
222 delete old->second;
226 m_sessions[s->GetAccountId ()] = s;
228 uint32 Sessions = GetActiveAndQueuedSessionCount ();
229 uint32 pLimit = GetPlayerAmountLimit ();
230 uint32 QueueSize = GetQueueSize (); //number of players in the queue
232 //so we don't count the user trying to
233 //login as a session and queue the socket that we are using
234 if(decrease_session)
235 --Sessions;
237 if (pLimit > 0 && Sessions >= pLimit && s->GetSecurity () == SEC_PLAYER )
239 AddQueuedPlayer (s);
240 UpdateMaxSessionCounters ();
241 sLog.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s->GetAccountId (), ++QueueSize);
242 return;
245 WorldPacket packet(SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
246 packet << uint8 (AUTH_OK);
247 packet << uint32 (0); // BillingTimeRemaining
248 packet << uint8 (0); // BillingPlanFlags
249 packet << uint32 (0); // BillingTimeRested
250 packet << uint8 (s->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
251 s->SendPacket (&packet);
253 UpdateMaxSessionCounters ();
255 // Updates the population
256 if (pLimit > 0)
258 float popu = GetActiveSessionCount (); //updated number of users on the server
259 popu /= pLimit;
260 popu *= 2;
261 loginDatabase.PExecute ("UPDATE realmlist SET population = '%f' WHERE id = '%d'", popu, realmID);
262 sLog.outDetail ("Server Population (%f).", popu);
266 int32 World::GetQueuePos(WorldSession* sess)
268 uint32 position = 1;
270 for(Queue::iterator iter = m_QueuedPlayer.begin(); iter != m_QueuedPlayer.end(); ++iter, ++position)
271 if((*iter) == sess)
272 return position;
274 return 0;
277 void World::AddQueuedPlayer(WorldSession* sess)
279 sess->SetInQueue(true);
280 m_QueuedPlayer.push_back (sess);
282 // The 1st SMSG_AUTH_RESPONSE needs to contain other info too.
283 WorldPacket packet (SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
284 packet << uint8 (AUTH_WAIT_QUEUE);
285 packet << uint32 (0); // BillingTimeRemaining
286 packet << uint8 (0); // BillingPlanFlags
287 packet << uint32 (0); // BillingTimeRested
288 packet << uint8 (sess->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
289 packet << uint32(GetQueuePos (sess));
290 sess->SendPacket (&packet);
292 //sess->SendAuthWaitQue (GetQueuePos (sess));
295 bool World::RemoveQueuedPlayer(WorldSession* sess)
297 // sessions count including queued to remove (if removed_session set)
298 uint32 sessions = GetActiveSessionCount();
300 uint32 position = 1;
301 Queue::iterator iter = m_QueuedPlayer.begin();
303 // search to remove and count skipped positions
304 bool found = false;
306 for(;iter != m_QueuedPlayer.end(); ++iter, ++position)
308 if(*iter==sess)
310 sess->SetInQueue(false);
311 iter = m_QueuedPlayer.erase(iter);
312 found = true; // removing queued session
313 break;
317 // iter point to next socked after removed or end()
318 // position store position of removed socket and then new position next socket after removed
320 // if session not queued then we need decrease sessions count
321 if(!found && sessions)
322 --sessions;
324 // accept first in queue
325 if( (!m_playerLimit || sessions < m_playerLimit) && !m_QueuedPlayer.empty() )
327 WorldSession* pop_sess = m_QueuedPlayer.front();
328 pop_sess->SetInQueue(false);
329 pop_sess->SendAuthWaitQue(0);
330 m_QueuedPlayer.pop_front();
332 // update iter to point first queued socket or end() if queue is empty now
333 iter = m_QueuedPlayer.begin();
334 position = 1;
337 // update position from iter to end()
338 // iter point to first not updated socket, position store new position
339 for(; iter != m_QueuedPlayer.end(); ++iter, ++position)
340 (*iter)->SendAuthWaitQue(position);
342 return found;
345 /// Find a Weather object by the given zoneid
346 Weather* World::FindWeather(uint32 id) const
348 WeatherMap::const_iterator itr = m_weathers.find(id);
350 if(itr != m_weathers.end())
351 return itr->second;
352 else
353 return 0;
356 /// Remove a Weather object for the given zoneid
357 void World::RemoveWeather(uint32 id)
359 // not called at the moment. Kept for completeness
360 WeatherMap::iterator itr = m_weathers.find(id);
362 if(itr != m_weathers.end())
364 delete itr->second;
365 m_weathers.erase(itr);
369 /// Add a Weather object to the list
370 Weather* World::AddWeather(uint32 zone_id)
372 WeatherZoneChances const* weatherChances = objmgr.GetWeatherChances(zone_id);
374 // zone not have weather, ignore
375 if(!weatherChances)
376 return NULL;
378 Weather* w = new Weather(zone_id,weatherChances);
379 m_weathers[w->GetZone()] = w;
380 w->ReGenerate();
381 w->UpdateWeather();
382 return w;
385 /// Initialize config values
386 void World::LoadConfigSettings(bool reload)
388 if(reload)
390 if(!sConfig.Reload())
392 sLog.outError("World settings reload fail: can't read settings from %s.",sConfig.GetFilename().c_str());
393 return;
397 ///- Read the version of the configuration file and warn the user in case of emptiness or mismatch
398 uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
399 if(!confVersion)
401 sLog.outError("*****************************************************************************");
402 sLog.outError(" WARNING: mangosd.conf does not include a ConfVersion variable.");
403 sLog.outError(" Your configuration file may be out of date!");
404 sLog.outError("*****************************************************************************");
405 clock_t pause = 3000 + clock();
406 while (pause > clock());
408 else
410 if (confVersion < _MANGOSDCONFVERSION)
412 sLog.outError("*****************************************************************************");
413 sLog.outError(" WARNING: Your mangosd.conf version indicates your conf file is out of date!");
414 sLog.outError(" Please check for updates, as your current default values may cause");
415 sLog.outError(" unexpected behavior.");
416 sLog.outError("*****************************************************************************");
417 clock_t pause = 3000 + clock();
418 while (pause > clock());
422 ///- Read the player limit and the Message of the day from the config file
423 SetPlayerLimit( sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT), true );
424 SetMotd( sConfig.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
426 ///- Read all rates from the config file
427 rate_values[RATE_HEALTH] = sConfig.GetFloatDefault("Rate.Health", 1);
428 if(rate_values[RATE_HEALTH] < 0)
430 sLog.outError("Rate.Health (%f) must be > 0. Using 1 instead.",rate_values[RATE_HEALTH]);
431 rate_values[RATE_HEALTH] = 1;
433 rate_values[RATE_POWER_MANA] = sConfig.GetFloatDefault("Rate.Mana", 1);
434 if(rate_values[RATE_POWER_MANA] < 0)
436 sLog.outError("Rate.Mana (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_MANA]);
437 rate_values[RATE_POWER_MANA] = 1;
439 rate_values[RATE_POWER_RAGE_INCOME] = sConfig.GetFloatDefault("Rate.Rage.Income", 1);
440 rate_values[RATE_POWER_RAGE_LOSS] = sConfig.GetFloatDefault("Rate.Rage.Loss", 1);
441 if(rate_values[RATE_POWER_RAGE_LOSS] < 0)
443 sLog.outError("Rate.Rage.Loss (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_RAGE_LOSS]);
444 rate_values[RATE_POWER_RAGE_LOSS] = 1;
446 rate_values[RATE_POWER_RUNICPOWER_INCOME] = sConfig.GetFloatDefault("Rate.RunicPower.Income", 1);
447 rate_values[RATE_POWER_RUNICPOWER_LOSS] = sConfig.GetFloatDefault("Rate.RunicPower.Loss", 1);
448 if(rate_values[RATE_POWER_RUNICPOWER_LOSS] < 0)
450 sLog.outError("Rate.RunicPower.Loss (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_RUNICPOWER_LOSS]);
451 rate_values[RATE_POWER_RUNICPOWER_LOSS] = 1;
453 rate_values[RATE_POWER_FOCUS] = sConfig.GetFloatDefault("Rate.Focus", 1.0f);
454 rate_values[RATE_SKILL_DISCOVERY] = sConfig.GetFloatDefault("Rate.Skill.Discovery", 1.0f);
455 rate_values[RATE_DROP_ITEM_POOR] = sConfig.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f);
456 rate_values[RATE_DROP_ITEM_NORMAL] = sConfig.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f);
457 rate_values[RATE_DROP_ITEM_UNCOMMON] = sConfig.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f);
458 rate_values[RATE_DROP_ITEM_RARE] = sConfig.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f);
459 rate_values[RATE_DROP_ITEM_EPIC] = sConfig.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f);
460 rate_values[RATE_DROP_ITEM_LEGENDARY] = sConfig.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f);
461 rate_values[RATE_DROP_ITEM_ARTIFACT] = sConfig.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f);
462 rate_values[RATE_DROP_ITEM_REFERENCED] = sConfig.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f);
463 rate_values[RATE_DROP_MONEY] = sConfig.GetFloatDefault("Rate.Drop.Money", 1.0f);
464 rate_values[RATE_XP_KILL] = sConfig.GetFloatDefault("Rate.XP.Kill", 1.0f);
465 rate_values[RATE_XP_QUEST] = sConfig.GetFloatDefault("Rate.XP.Quest", 1.0f);
466 rate_values[RATE_XP_EXPLORE] = sConfig.GetFloatDefault("Rate.XP.Explore", 1.0f);
467 rate_values[RATE_REPUTATION_GAIN] = sConfig.GetFloatDefault("Rate.Reputation.Gain", 1.0f);
468 rate_values[RATE_CREATURE_NORMAL_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f);
469 rate_values[RATE_CREATURE_ELITE_ELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f);
470 rate_values[RATE_CREATURE_ELITE_RAREELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f);
471 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f);
472 rate_values[RATE_CREATURE_ELITE_RARE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f);
473 rate_values[RATE_CREATURE_NORMAL_HP] = sConfig.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f);
474 rate_values[RATE_CREATURE_ELITE_ELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f);
475 rate_values[RATE_CREATURE_ELITE_RAREELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f);
476 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f);
477 rate_values[RATE_CREATURE_ELITE_RARE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f);
478 rate_values[RATE_CREATURE_NORMAL_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f);
479 rate_values[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f);
480 rate_values[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f);
481 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f);
482 rate_values[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f);
483 rate_values[RATE_CREATURE_AGGRO] = sConfig.GetFloatDefault("Rate.Creature.Aggro", 1.0f);
484 rate_values[RATE_REST_INGAME] = sConfig.GetFloatDefault("Rate.Rest.InGame", 1.0f);
485 rate_values[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY] = sConfig.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f);
486 rate_values[RATE_REST_OFFLINE_IN_WILDERNESS] = sConfig.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f);
487 rate_values[RATE_DAMAGE_FALL] = sConfig.GetFloatDefault("Rate.Damage.Fall", 1.0f);
488 rate_values[RATE_AUCTION_TIME] = sConfig.GetFloatDefault("Rate.Auction.Time", 1.0f);
489 rate_values[RATE_AUCTION_DEPOSIT] = sConfig.GetFloatDefault("Rate.Auction.Deposit", 1.0f);
490 rate_values[RATE_AUCTION_CUT] = sConfig.GetFloatDefault("Rate.Auction.Cut", 1.0f);
491 rate_values[RATE_HONOR] = sConfig.GetFloatDefault("Rate.Honor",1.0f);
492 rate_values[RATE_MINING_AMOUNT] = sConfig.GetFloatDefault("Rate.Mining.Amount",1.0f);
493 rate_values[RATE_MINING_NEXT] = sConfig.GetFloatDefault("Rate.Mining.Next",1.0f);
494 rate_values[RATE_INSTANCE_RESET_TIME] = sConfig.GetFloatDefault("Rate.InstanceResetTime",1.0f);
495 rate_values[RATE_TALENT] = sConfig.GetFloatDefault("Rate.Talent",1.0f);
496 if(rate_values[RATE_TALENT] < 0.0f)
498 sLog.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_TALENT]);
499 rate_values[RATE_TALENT] = 1.0f;
501 rate_values[RATE_CORPSE_DECAY_LOOTED] = sConfig.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f);
503 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = sConfig.GetFloatDefault("TargetPosRecalculateRange",1.5f);
504 if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] < CONTACT_DISTANCE)
506 sLog.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],CONTACT_DISTANCE,CONTACT_DISTANCE);
507 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = CONTACT_DISTANCE;
509 else if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] > ATTACK_DISTANCE)
511 sLog.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",
512 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],ATTACK_DISTANCE,ATTACK_DISTANCE);
513 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = ATTACK_DISTANCE;
516 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = sConfig.GetFloatDefault("DurabilityLossChance.Damage",0.5f);
517 if(rate_values[RATE_DURABILITY_LOSS_DAMAGE] < 0.0f)
519 sLog.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_DAMAGE]);
520 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = 0.0f;
522 rate_values[RATE_DURABILITY_LOSS_ABSORB] = sConfig.GetFloatDefault("DurabilityLossChance.Absorb",0.5f);
523 if(rate_values[RATE_DURABILITY_LOSS_ABSORB] < 0.0f)
525 sLog.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_ABSORB]);
526 rate_values[RATE_DURABILITY_LOSS_ABSORB] = 0.0f;
528 rate_values[RATE_DURABILITY_LOSS_PARRY] = sConfig.GetFloatDefault("DurabilityLossChance.Parry",0.05f);
529 if(rate_values[RATE_DURABILITY_LOSS_PARRY] < 0.0f)
531 sLog.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_PARRY]);
532 rate_values[RATE_DURABILITY_LOSS_PARRY] = 0.0f;
534 rate_values[RATE_DURABILITY_LOSS_BLOCK] = sConfig.GetFloatDefault("DurabilityLossChance.Block",0.05f);
535 if(rate_values[RATE_DURABILITY_LOSS_BLOCK] < 0.0f)
537 sLog.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_BLOCK]);
538 rate_values[RATE_DURABILITY_LOSS_BLOCK] = 0.0f;
541 ///- Read other configuration items from the config file
543 m_configs[CONFIG_COMPRESSION] = sConfig.GetIntDefault("Compression", 1);
544 if(m_configs[CONFIG_COMPRESSION] < 1 || m_configs[CONFIG_COMPRESSION] > 9)
546 sLog.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs[CONFIG_COMPRESSION]);
547 m_configs[CONFIG_COMPRESSION] = 1;
549 m_configs[CONFIG_ADDON_CHANNEL] = sConfig.GetBoolDefault("AddonChannel", true);
550 m_configs[CONFIG_GRID_UNLOAD] = sConfig.GetBoolDefault("GridUnload", true);
551 m_configs[CONFIG_INTERVAL_SAVE] = sConfig.GetIntDefault("PlayerSaveInterval", 900000);
553 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = sConfig.GetIntDefault("GridCleanUpDelay", 300000);
554 if(m_configs[CONFIG_INTERVAL_GRIDCLEAN] < MIN_GRID_DELAY)
556 sLog.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_GRIDCLEAN],MIN_GRID_DELAY);
557 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = MIN_GRID_DELAY;
559 if(reload)
560 MapManager::Instance().SetGridCleanUpDelay(m_configs[CONFIG_INTERVAL_GRIDCLEAN]);
562 m_configs[CONFIG_INTERVAL_MAPUPDATE] = sConfig.GetIntDefault("MapUpdateInterval", 100);
563 if(m_configs[CONFIG_INTERVAL_MAPUPDATE] < MIN_MAP_UPDATE_DELAY)
565 sLog.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_MAPUPDATE],MIN_MAP_UPDATE_DELAY);
566 m_configs[CONFIG_INTERVAL_MAPUPDATE] = MIN_MAP_UPDATE_DELAY;
568 if(reload)
569 MapManager::Instance().SetMapUpdateInterval(m_configs[CONFIG_INTERVAL_MAPUPDATE]);
571 m_configs[CONFIG_INTERVAL_CHANGEWEATHER] = sConfig.GetIntDefault("ChangeWeatherInterval", 600000);
573 if(reload)
575 uint32 val = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
576 if(val!=m_configs[CONFIG_PORT_WORLD])
577 sLog.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_PORT_WORLD]);
579 else
580 m_configs[CONFIG_PORT_WORLD] = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
582 if(reload)
584 uint32 val = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
585 if(val!=m_configs[CONFIG_SOCKET_SELECTTIME])
586 sLog.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[DEFAULT_SOCKET_SELECT_TIME]);
588 else
589 m_configs[CONFIG_SOCKET_SELECTTIME] = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
591 m_configs[CONFIG_GROUP_XP_DISTANCE] = sConfig.GetIntDefault("MaxGroupXPDistance", 74);
592 /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
593 m_configs[CONFIG_SIGHT_MONSTER] = sConfig.GetIntDefault("MonsterSight", 50);
594 m_configs[CONFIG_SIGHT_GUARDER] = sConfig.GetIntDefault("GuarderSight", 50);
596 if(reload)
598 uint32 val = sConfig.GetIntDefault("GameType", 0);
599 if(val!=m_configs[CONFIG_GAME_TYPE])
600 sLog.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_GAME_TYPE]);
602 else
603 m_configs[CONFIG_GAME_TYPE] = sConfig.GetIntDefault("GameType", 0);
605 if(reload)
607 uint32 val = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
608 if(val!=m_configs[CONFIG_REALM_ZONE])
609 sLog.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_REALM_ZONE]);
611 else
612 m_configs[CONFIG_REALM_ZONE] = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
614 m_configs[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS] = sConfig.GetBoolDefault("AllowTwoSide.Accounts", false);
615 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
616 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
617 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
618 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
619 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
620 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
621 m_configs[CONFIG_ALLOW_TWO_SIDE_WHO_LIST] = sConfig.GetBoolDefault("AllowTwoSide.WhoList", false);
622 m_configs[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND] = sConfig.GetBoolDefault("AllowTwoSide.AddFriend", false);
623 m_configs[CONFIG_STRICT_PLAYER_NAMES] = sConfig.GetIntDefault("StrictPlayerNames", 0);
624 m_configs[CONFIG_STRICT_CHARTER_NAMES] = sConfig.GetIntDefault("StrictCharterNames", 0);
625 m_configs[CONFIG_STRICT_PET_NAMES] = sConfig.GetIntDefault("StrictPetNames", 0);
627 m_configs[CONFIG_CHARACTERS_CREATING_DISABLED] = sConfig.GetIntDefault("CharactersCreatingDisabled", 0);
629 m_configs[CONFIG_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("CharactersPerRealm", 10);
630 if(m_configs[CONFIG_CHARACTERS_PER_REALM] < 1 || m_configs[CONFIG_CHARACTERS_PER_REALM] > 10)
632 sLog.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs[CONFIG_CHARACTERS_PER_REALM]);
633 m_configs[CONFIG_CHARACTERS_PER_REALM] = 10;
636 // must be after CONFIG_CHARACTERS_PER_REALM
637 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = sConfig.GetIntDefault("CharactersPerAccount", 50);
638 if(m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] < m_configs[CONFIG_CHARACTERS_PER_REALM])
640 sLog.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs[CONFIG_CHARACTERS_PER_ACCOUNT],m_configs[CONFIG_CHARACTERS_PER_REALM]);
641 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = m_configs[CONFIG_CHARACTERS_PER_REALM];
644 m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("HeroicCharactersPerRealm", 1);
645 if(m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] < 0 || m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] > 10)
647 sLog.outError("HeroicCharactersPerRealm (%i) must be in range 0..10. Set to 1.",m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM]);
648 m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] = 1;
651 m_configs[CONFIG_MIN_LEVEL_FOR_HEROIC_CHARACTER_CREATING] = sConfig.GetIntDefault("MinLevelForHeroicCharacterCreating", 55);
653 m_configs[CONFIG_SKIP_CINEMATICS] = sConfig.GetIntDefault("SkipCinematics", 0);
654 if(m_configs[CONFIG_SKIP_CINEMATICS] < 0 || m_configs[CONFIG_SKIP_CINEMATICS] > 2)
656 sLog.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs[CONFIG_SKIP_CINEMATICS]);
657 m_configs[CONFIG_SKIP_CINEMATICS] = 0;
660 if(reload)
662 uint32 val = sConfig.GetIntDefault("MaxPlayerLevel", 60);
663 if(val!=m_configs[CONFIG_MAX_PLAYER_LEVEL])
664 sLog.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
666 else
667 m_configs[CONFIG_MAX_PLAYER_LEVEL] = sConfig.GetIntDefault("MaxPlayerLevel", 60);
669 if(m_configs[CONFIG_MAX_PLAYER_LEVEL] > MAX_LEVEL)
671 sLog.outError("MaxPlayerLevel (%i) must be in range 1..%u. Set to %u.",m_configs[CONFIG_MAX_PLAYER_LEVEL],MAX_LEVEL,MAX_LEVEL);
672 m_configs[CONFIG_MAX_PLAYER_LEVEL] = MAX_LEVEL;
675 m_configs[CONFIG_START_PLAYER_LEVEL] = sConfig.GetIntDefault("StartPlayerLevel", 1);
676 if(m_configs[CONFIG_START_PLAYER_LEVEL] < 1)
678 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]);
679 m_configs[CONFIG_START_PLAYER_LEVEL] = 1;
681 else if(m_configs[CONFIG_START_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
683 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]);
684 m_configs[CONFIG_START_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
687 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = sConfig.GetIntDefault("StartHeroicPlayerLevel", 55);
688 if(m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] < 1)
690 sLog.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to 55.",
691 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
692 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = 55;
694 else if(m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
696 sLog.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to %u.",
697 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
698 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
701 m_configs[CONFIG_START_PLAYER_MONEY] = sConfig.GetIntDefault("StartPlayerMoney", 0);
702 if(m_configs[CONFIG_START_PLAYER_MONEY] < 0)
704 sLog.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",m_configs[CONFIG_START_PLAYER_MONEY],MAX_MONEY_AMOUNT,0);
705 m_configs[CONFIG_START_PLAYER_MONEY] = 0;
707 else if(m_configs[CONFIG_START_PLAYER_MONEY] > MAX_MONEY_AMOUNT)
709 sLog.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",
710 m_configs[CONFIG_START_PLAYER_MONEY],MAX_MONEY_AMOUNT,MAX_MONEY_AMOUNT);
711 m_configs[CONFIG_START_PLAYER_MONEY] = MAX_MONEY_AMOUNT;
714 m_configs[CONFIG_MAX_HONOR_POINTS] = sConfig.GetIntDefault("MaxHonorPoints", 75000);
715 if(m_configs[CONFIG_MAX_HONOR_POINTS] < 0)
717 sLog.outError("MaxHonorPoints (%i) can't be negative. Set to 0.",m_configs[CONFIG_MAX_HONOR_POINTS]);
718 m_configs[CONFIG_MAX_HONOR_POINTS] = 0;
721 m_configs[CONFIG_START_HONOR_POINTS] = sConfig.GetIntDefault("StartHonorPoints", 0);
722 if(m_configs[CONFIG_START_HONOR_POINTS] < 0)
724 sLog.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
725 m_configs[CONFIG_START_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS],0);
726 m_configs[CONFIG_MAX_HONOR_POINTS] = 0;
728 else if(m_configs[CONFIG_START_HONOR_POINTS] > m_configs[CONFIG_MAX_HONOR_POINTS])
730 sLog.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
731 m_configs[CONFIG_START_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS]);
732 m_configs[CONFIG_START_HONOR_POINTS] = m_configs[CONFIG_MAX_HONOR_POINTS];
735 m_configs[CONFIG_MAX_ARENA_POINTS] = sConfig.GetIntDefault("MaxArenaPoints", 5000);
736 if(m_configs[CONFIG_MAX_ARENA_POINTS] < 0)
738 sLog.outError("MaxArenaPoints (%i) can't be negative. Set to 0.",m_configs[CONFIG_MAX_ARENA_POINTS]);
739 m_configs[CONFIG_MAX_ARENA_POINTS] = 0;
742 m_configs[CONFIG_START_ARENA_POINTS] = sConfig.GetIntDefault("StartArenaPoints", 0);
743 if(m_configs[CONFIG_START_ARENA_POINTS] < 0)
745 sLog.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
746 m_configs[CONFIG_START_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS],0);
747 m_configs[CONFIG_MAX_ARENA_POINTS] = 0;
749 else if(m_configs[CONFIG_START_ARENA_POINTS] > m_configs[CONFIG_MAX_ARENA_POINTS])
751 sLog.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
752 m_configs[CONFIG_START_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS]);
753 m_configs[CONFIG_START_ARENA_POINTS] = m_configs[CONFIG_MAX_ARENA_POINTS];
756 m_configs[CONFIG_ALL_TAXI_PATHS] = sConfig.GetBoolDefault("AllFlightPaths", false);
758 m_configs[CONFIG_INSTANCE_IGNORE_LEVEL] = sConfig.GetBoolDefault("Instance.IgnoreLevel", false);
759 m_configs[CONFIG_INSTANCE_IGNORE_RAID] = sConfig.GetBoolDefault("Instance.IgnoreRaid", false);
761 m_configs[CONFIG_BATTLEGROUND_CAST_DESERTER] = sConfig.GetBoolDefault("Battleground.CastDeserter", true);
762 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.Enable", false);
763 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false);
764 m_configs[CONFIG_ARENA_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Arena.QueueAnnouncer.Enable", false);
765 m_configs[CONFIG_ARENA_SEASON_ID] = sConfig.GetIntDefault ("Arena.ArenaSeason.ID", 1);
766 m_configs[CONFIG_ARENA_SEASON_IN_PROGRESS] = sConfig.GetBoolDefault("Arena.ArenaSeason.InProgress", true);
768 m_configs[CONFIG_CAST_UNSTUCK] = sConfig.GetBoolDefault("CastUnstuck", true);
769 m_configs[CONFIG_INSTANCE_RESET_TIME_HOUR] = sConfig.GetIntDefault("Instance.ResetTimeHour", 4);
770 m_configs[CONFIG_INSTANCE_UNLOAD_DELAY] = sConfig.GetIntDefault("Instance.UnloadDelay", 1800000);
772 m_configs[CONFIG_MAX_PRIMARY_TRADE_SKILL] = sConfig.GetIntDefault("MaxPrimaryTradeSkill", 2);
773 m_configs[CONFIG_MIN_PETITION_SIGNS] = sConfig.GetIntDefault("MinPetitionSigns", 9);
774 if(m_configs[CONFIG_MIN_PETITION_SIGNS] > 9)
776 sLog.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.", m_configs[CONFIG_MIN_PETITION_SIGNS]);
777 m_configs[CONFIG_MIN_PETITION_SIGNS] = 9;
780 m_configs[CONFIG_GM_LOGIN_STATE] = sConfig.GetIntDefault("GM.LoginState", 2);
781 m_configs[CONFIG_GM_VISIBLE_STATE] = sConfig.GetIntDefault("GM.Visible", 2);
782 m_configs[CONFIG_GM_ACCEPT_TICKETS] = sConfig.GetIntDefault("GM.AcceptTickets", 2);
783 m_configs[CONFIG_GM_CHAT] = sConfig.GetIntDefault("GM.Chat", 2);
784 m_configs[CONFIG_GM_WISPERING_TO] = sConfig.GetIntDefault("GM.WhisperingTo", 2);
786 m_configs[CONFIG_GM_IN_GM_LIST] = sConfig.GetBoolDefault("GM.InGMList", false);
787 m_configs[CONFIG_GM_IN_WHO_LIST] = sConfig.GetBoolDefault("GM.InWhoList", false);
788 m_configs[CONFIG_GM_LOG_TRADE] = sConfig.GetBoolDefault("GM.LogTrade", false);
790 m_configs[CONFIG_START_GM_LEVEL] = sConfig.GetIntDefault("GM.StartLevel", 1);
791 if(m_configs[CONFIG_START_GM_LEVEL] < m_configs[CONFIG_START_PLAYER_LEVEL])
793 sLog.outError("GM.StartLevel (%i) must be in range StartPlayerLevel(%u)..%u. Set to %u.",
794 m_configs[CONFIG_START_GM_LEVEL],m_configs[CONFIG_START_PLAYER_LEVEL], MAX_LEVEL, m_configs[CONFIG_START_PLAYER_LEVEL]);
795 m_configs[CONFIG_START_GM_LEVEL] = m_configs[CONFIG_START_PLAYER_LEVEL];
797 else if(m_configs[CONFIG_START_GM_LEVEL] > MAX_LEVEL)
799 sLog.outError("GM.StartLevel (%i) must be in range 1..%u. Set to %u.", m_configs[CONFIG_START_GM_LEVEL], MAX_LEVEL, MAX_LEVEL);
800 m_configs[CONFIG_START_GM_LEVEL] = MAX_LEVEL;
802 m_configs[CONFIG_GM_LOWER_SECURITY] = sConfig.GetBoolDefault("GM.LowerSecurity", false);
803 m_configs[CONFIG_GM_ALLOW_ACHIEVEMENT_GAINS] = sConfig.GetBoolDefault("GM.AllowAchievementGain", true);
805 m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
807 m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
809 m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
810 if(m_configs[CONFIG_UPTIME_UPDATE]<=0)
812 sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
813 m_configs[CONFIG_UPTIME_UPDATE] = 10;
815 if(reload)
817 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
818 m_timers[WUPDATE_UPTIME].Reset();
821 m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
822 m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
823 m_configs[CONFIG_SKILL_CHANCE_GREEN] = sConfig.GetIntDefault("SkillChance.Green",25);
824 m_configs[CONFIG_SKILL_CHANCE_GREY] = sConfig.GetIntDefault("SkillChance.Grey",0);
826 m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS] = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
827 m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS] = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
829 m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
830 m_configs[CONFIG_SKILL_MILLING] = sConfig.GetBoolDefault("SkillChance.Milling",false);
832 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = sConfig.GetIntDefault("SkillGain.Crafting", 1);
833 if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
835 sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
836 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
839 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = sConfig.GetIntDefault("SkillGain.Defense", 1);
840 if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
842 sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
843 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
846 m_configs[CONFIG_SKILL_GAIN_GATHERING] = sConfig.GetIntDefault("SkillGain.Gathering", 1);
847 if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
849 sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
850 m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
853 m_configs[CONFIG_SKILL_GAIN_WEAPON] = sConfig.GetIntDefault("SkillGain.Weapon", 1);
854 if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
856 sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
857 m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
860 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
861 if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
863 sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
864 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
867 m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
868 m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
870 m_configs[CONFIG_DISABLE_BREATHING] = sConfig.GetIntDefault("DisableWaterBreath", SEC_CONSOLE);
872 m_configs[CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL] = sConfig.GetBoolDefault("AlwaysMaxSkillForLevel", false);
874 if(reload)
876 uint32 val = sConfig.GetIntDefault("Expansion",1);
877 if(val!=m_configs[CONFIG_EXPANSION])
878 sLog.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
880 else
881 m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",1);
883 m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
884 m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
885 m_configs[CONFIG_CHATFLOOD_MUTE_TIME] = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
887 m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
889 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistanceRadius",10);
890 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY] = sConfig.GetIntDefault("CreatureFamilyAssistanceDelay",1500);
892 m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
894 // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level MAX_LEVEL(100)
895 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff", 4);
896 if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > MAX_LEVEL)
897 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = MAX_LEVEL;
898 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff", 7);
899 if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > MAX_LEVEL)
900 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = MAX_LEVEL;
902 m_configs[CONFIG_DETECT_POS_COLLISION] = sConfig.GetBoolDefault("DetectPosCollision", true);
904 m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
905 m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
907 m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
908 m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
910 m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
911 m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
912 m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
913 m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
914 m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
916 m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault("Death.SicknessLevel", 11);
917 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
918 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
919 m_configs[CONFIG_DEATH_BONES_WORLD] = sConfig.GetBoolDefault("Death.Bones.World", true);
920 m_configs[CONFIG_DEATH_BONES_BG_OR_ARENA] = sConfig.GetBoolDefault("Death.Bones.BattlegroundOrArena", true);
922 m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
924 // always use declined names in the russian client
925 m_configs[CONFIG_DECLINED_NAMES_USED] =
926 (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
928 m_configs[CONFIG_LISTEN_RANGE_SAY] = sConfig.GetIntDefault("ListenRange.Say", 25);
929 m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
930 m_configs[CONFIG_LISTEN_RANGE_YELL] = sConfig.GetIntDefault("ListenRange.Yell", 300);
932 m_configs[CONFIG_ARENA_MAX_RATING_DIFFERENCE] = sConfig.GetIntDefault("Arena.MaxRatingDifference", 0);
933 m_configs[CONFIG_ARENA_RATING_DISCARD_TIMER] = sConfig.GetIntDefault("Arena.RatingDiscardTimer",300000);
934 m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_POINTS] = sConfig.GetBoolDefault("Arena.AutoDistributePoints", false);
935 m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS] = sConfig.GetIntDefault("Arena.AutoDistributeInterval", 7);
937 m_configs[CONFIG_BATTLEGROUND_PREMATURE_FINISH_TIMER] = sConfig.GetIntDefault("BattleGround.PrematureFinishTimer", 0);
938 m_configs[CONFIG_INSTANT_LOGOUT] = sConfig.GetIntDefault("InstantLogout", SEC_MODERATOR);
940 m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
941 if(m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
943 sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
944 m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
946 m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
947 if(m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
949 sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
950 m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
953 m_MaxVisibleDistanceForCreature = sConfig.GetFloatDefault("Visibility.Distance.Creature", DEFAULT_VISIBILITY_DISTANCE);
954 if(m_MaxVisibleDistanceForCreature < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
956 sLog.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
957 m_MaxVisibleDistanceForCreature = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
959 else if(m_MaxVisibleDistanceForCreature + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
961 sLog.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
962 m_MaxVisibleDistanceForCreature = MAX_VISIBILITY_DISTANCE-m_VisibleUnitGreyDistance;
964 m_MaxVisibleDistanceForPlayer = sConfig.GetFloatDefault("Visibility.Distance.Player", DEFAULT_VISIBILITY_DISTANCE);
965 if(m_MaxVisibleDistanceForPlayer < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
967 sLog.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
968 m_MaxVisibleDistanceForPlayer = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
970 else if(m_MaxVisibleDistanceForPlayer + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
972 sLog.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
973 m_MaxVisibleDistanceForPlayer = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
975 m_MaxVisibleDistanceForObject = sConfig.GetFloatDefault("Visibility.Distance.Gameobject", DEFAULT_VISIBILITY_DISTANCE);
976 if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
978 sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
979 m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
981 else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
983 sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
984 m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
986 m_MaxVisibleDistanceInFlight = sConfig.GetFloatDefault("Visibility.Distance.InFlight", DEFAULT_VISIBILITY_DISTANCE);
987 if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
989 sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
990 m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
993 ///- Read the "Data" directory from the config file
994 std::string dataPath = sConfig.GetStringDefault("DataDir","./");
995 if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
996 dataPath.append("/");
998 if(reload)
1000 if(dataPath!=m_dataPath)
1001 sLog.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath.c_str());
1003 else
1005 m_dataPath = dataPath;
1006 sLog.outString("Using DataDir %s",m_dataPath.c_str());
1009 bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
1010 bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
1011 std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
1012 std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
1013 VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
1014 VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
1015 VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
1016 VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
1017 sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
1018 sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
1019 sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
1022 /// Initialize the World
1023 void World::SetInitialWorldSettings()
1025 ///- Initialize the random number generator
1026 srand((unsigned int)time(NULL));
1028 ///- Initialize config settings
1029 LoadConfigSettings();
1031 ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
1032 objmgr.SetHighestGuids();
1034 ///- Check the existence of the map files for all races' startup areas.
1035 if( !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
1036 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
1037 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
1038 ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
1039 ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
1040 ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
1041 ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
1042 ||m_configs[CONFIG_EXPANSION] && (
1043 !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
1045 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());
1046 exit(1);
1049 ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
1050 sLog.outString( "" );
1051 sLog.outString( "Loading MaNGOS strings..." );
1052 if (!objmgr.LoadMangosStrings())
1053 exit(1); // Error message displayed in function already
1055 ///- Update the realm entry in the database with the realm type from the config file
1056 //No SQL injection as values are treated as integers
1058 // not send custom type REALM_FFA_PVP to realm list
1059 uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
1060 uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
1061 loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
1063 ///- Remove the bones after a restart
1064 CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
1066 ///- Load the DBC files
1067 sLog.outString("Initialize data stores...");
1068 LoadDBCStores(m_dataPath);
1069 DetectDBCLang();
1071 sLog.outString( "Loading Script Names...");
1072 objmgr.LoadScriptNames();
1074 sLog.outString( "Loading InstanceTemplate..." );
1075 objmgr.LoadInstanceTemplate();
1077 sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
1078 spellmgr.LoadSkillLineAbilityMap();
1080 ///- Clean up and pack instances
1081 sLog.outString( "Cleaning up instances..." );
1082 sInstanceSaveManager.CleanupInstances(); // must be called before `creature_respawn`/`gameobject_respawn` tables
1084 sLog.outString( "Packing instances..." );
1085 sInstanceSaveManager.PackInstances();
1087 sLog.outString();
1088 sLog.outString( "Loading Localization strings..." );
1089 objmgr.LoadCreatureLocales();
1090 objmgr.LoadGameObjectLocales();
1091 objmgr.LoadItemLocales();
1092 objmgr.LoadQuestLocales();
1093 objmgr.LoadNpcTextLocales();
1094 objmgr.LoadPageTextLocales();
1095 objmgr.LoadNpcOptionLocales();
1096 objmgr.SetDBCLocaleIndex(GetDefaultDbcLocale()); // Get once for all the locale index of DBC language (console/broadcasts)
1097 sLog.outString( ">>> Localization strings loaded" );
1098 sLog.outString();
1100 sLog.outString( "Loading Page Texts..." );
1101 objmgr.LoadPageTexts();
1103 sLog.outString( "Loading Game Object Templates..." ); // must be after LoadPageTexts
1104 objmgr.LoadGameobjectInfo();
1106 sLog.outString( "Loading Spell Chain Data..." );
1107 spellmgr.LoadSpellChains();
1109 sLog.outString( "Loading Spell Elixir types..." );
1110 spellmgr.LoadSpellElixirs();
1112 sLog.outString( "Loading Spell Learn Skills..." );
1113 spellmgr.LoadSpellLearnSkills(); // must be after LoadSpellChains
1115 sLog.outString( "Loading Spell Learn Spells..." );
1116 spellmgr.LoadSpellLearnSpells();
1118 sLog.outString( "Loading Spell Proc Event conditions..." );
1119 spellmgr.LoadSpellProcEvents();
1121 sLog.outString( "Loading Spell Bonus Data..." );
1122 spellmgr.LoadSpellBonusess();
1124 sLog.outString( "Loading Aggro Spells Definitions...");
1125 spellmgr.LoadSpellThreats();
1127 sLog.outString( "Loading NPC Texts..." );
1128 objmgr.LoadGossipText();
1130 sLog.outString( "Loading Item Random Enchantments Table..." );
1131 LoadRandomEnchantmentsTable();
1133 sLog.outString( "Loading Items..." ); // must be after LoadRandomEnchantmentsTable and LoadPageTexts
1134 objmgr.LoadItemPrototypes();
1136 sLog.outString( "Loading Item Texts..." );
1137 objmgr.LoadItemTexts();
1139 sLog.outString( "Loading Creature Model Based Info Data..." );
1140 objmgr.LoadCreatureModelInfo();
1142 sLog.outString( "Loading Equipment templates...");
1143 objmgr.LoadEquipmentTemplates();
1145 sLog.outString( "Loading Creature templates..." );
1146 objmgr.LoadCreatureTemplates();
1148 sLog.outString( "Loading SpellsScriptTarget...");
1149 spellmgr.LoadSpellScriptTarget(); // must be after LoadCreatureTemplates and LoadGameobjectInfo
1151 sLog.outString( "Loading Creature Reputation OnKill Data..." );
1152 objmgr.LoadReputationOnKill();
1154 sLog.outString( "Loading Pet Create Spells..." );
1155 objmgr.LoadPetCreateSpells();
1157 sLog.outString( "Loading Creature Data..." );
1158 objmgr.LoadCreatures();
1160 sLog.outString( "Loading Creature Addon Data..." );
1161 sLog.outString();
1162 objmgr.LoadCreatureAddons(); // must be after LoadCreatureTemplates() and LoadCreatures()
1163 sLog.outString( ">>> Creature Addon Data loaded" );
1164 sLog.outString();
1166 sLog.outString( "Loading Creature Respawn Data..." ); // must be after PackInstances()
1167 objmgr.LoadCreatureRespawnTimes();
1169 sLog.outString( "Loading Gameobject Data..." );
1170 objmgr.LoadGameobjects();
1172 sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1173 objmgr.LoadGameobjectRespawnTimes();
1175 sLog.outString( "Loading Game Event Data...");
1176 sLog.outString();
1177 gameeventmgr.LoadFromDB();
1178 sLog.outString( ">>> Game Event Data loaded" );
1179 sLog.outString();
1181 sLog.outString( "Loading Weather Data..." );
1182 objmgr.LoadWeatherZoneChances();
1184 sLog.outString( "Loading Quests..." );
1185 objmgr.LoadQuests(); // must be loaded after DBCs, creature_template, item_template, gameobject tables
1187 sLog.outString( "Loading Quests Relations..." );
1188 sLog.outString();
1189 objmgr.LoadQuestRelations(); // must be after quest load
1190 sLog.outString( ">>> Quests Relations loaded" );
1191 sLog.outString();
1193 sLog.outString( "Loading AreaTrigger definitions..." );
1194 objmgr.LoadAreaTriggerTeleports(); // must be after item template load
1196 sLog.outString( "Loading Quest Area Triggers..." );
1197 objmgr.LoadQuestAreaTriggers(); // must be after LoadQuests
1199 sLog.outString( "Loading Tavern Area Triggers..." );
1200 objmgr.LoadTavernAreaTriggers();
1202 sLog.outString( "Loading AreaTrigger script names..." );
1203 objmgr.LoadAreaTriggerScripts();
1205 sLog.outString( "Loading Graveyard-zone links...");
1206 objmgr.LoadGraveyardZones();
1208 sLog.outString( "Loading Spell target coordinates..." );
1209 spellmgr.LoadSpellTargetPositions();
1211 sLog.outString( "Loading SpellAffect definitions..." );
1212 spellmgr.LoadSpellAffects();
1214 sLog.outString( "Loading spell pet auras..." );
1215 spellmgr.LoadSpellPetAuras();
1217 sLog.outString( "Loading pet levelup spells..." );
1218 spellmgr.LoadPetLevelupSpellMap();
1220 sLog.outString( "Loading Player Create Info & Level Stats..." );
1221 sLog.outString();
1222 objmgr.LoadPlayerInfo();
1223 sLog.outString( ">>> Player Create Info & Level Stats loaded" );
1224 sLog.outString();
1226 sLog.outString( "Loading Exploration BaseXP Data..." );
1227 objmgr.LoadExplorationBaseXP();
1229 sLog.outString( "Loading Pet Name Parts..." );
1230 objmgr.LoadPetNames();
1232 sLog.outString( "Loading the max pet number..." );
1233 objmgr.LoadPetNumber();
1235 sLog.outString( "Loading pet level stats..." );
1236 objmgr.LoadPetLevelInfo();
1238 sLog.outString( "Loading Player Corpses..." );
1239 objmgr.LoadCorpses();
1241 sLog.outString( "Loading Loot Tables..." );
1242 sLog.outString();
1243 LoadLootTables();
1244 sLog.outString( ">>> Loot Tables loaded" );
1245 sLog.outString();
1247 sLog.outString( "Loading Skill Discovery Table..." );
1248 LoadSkillDiscoveryTable();
1250 sLog.outString( "Loading Skill Extra Item Table..." );
1251 LoadSkillExtraItemTable();
1253 sLog.outString( "Loading Skill Fishing base level requirements..." );
1254 objmgr.LoadFishingBaseSkillLevel();
1256 sLog.outString( "Loading Achievements..." );
1257 sLog.outString();
1258 achievementmgr.LoadAchievementCriteriaList();
1259 achievementmgr.LoadRewards();
1260 achievementmgr.LoadRewardLocales();
1261 achievementmgr.LoadCompletedAchievements();
1262 sLog.outString( ">>> Achievements loaded" );
1263 sLog.outString();
1265 ///- Load dynamic data tables from the database
1266 sLog.outString( "Loading Auctions..." );
1267 sLog.outString();
1268 objmgr.LoadAuctionItems();
1269 objmgr.LoadAuctions();
1270 sLog.outString( ">>> Auctions loaded" );
1271 sLog.outString();
1273 sLog.outString( "Loading Guilds..." );
1274 objmgr.LoadGuilds();
1276 sLog.outString( "Loading ArenaTeams..." );
1277 objmgr.LoadArenaTeams();
1279 sLog.outString( "Loading Groups..." );
1280 objmgr.LoadGroups();
1282 sLog.outString( "Loading ReservedNames..." );
1283 objmgr.LoadReservedPlayersNames();
1285 sLog.outString( "Loading GameObjects for quests..." );
1286 objmgr.LoadGameObjectForQuests();
1288 sLog.outString( "Loading BattleMasters..." );
1289 objmgr.LoadBattleMastersEntry();
1291 sLog.outString( "Loading GameTeleports..." );
1292 objmgr.LoadGameTele();
1294 sLog.outString( "Loading Npc Text Id..." );
1295 objmgr.LoadNpcTextId(); // must be after load Creature and NpcText
1297 sLog.outString( "Loading Npc Options..." );
1298 objmgr.LoadNpcOptions();
1300 sLog.outString( "Loading Vendors..." );
1301 objmgr.LoadVendors(); // must be after load CreatureTemplate and ItemTemplate
1303 sLog.outString( "Loading Trainers..." );
1304 objmgr.LoadTrainerSpell(); // must be after load CreatureTemplate
1306 sLog.outString( "Loading Waypoints..." );
1307 sLog.outString();
1308 WaypointMgr.Load();
1310 sLog.outString( "Loading GM tickets...");
1311 ticketmgr.LoadGMTickets();
1313 ///- Handle outdated emails (delete/return)
1314 sLog.outString( "Returning old mails..." );
1315 objmgr.ReturnOrDeleteOldMails(false);
1317 ///- Load and initialize scripts
1318 sLog.outString( "Loading Scripts..." );
1319 sLog.outString();
1320 objmgr.LoadQuestStartScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1321 objmgr.LoadQuestEndScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1322 objmgr.LoadSpellScripts(); // must be after load Creature/Gameobject(Template/Data)
1323 objmgr.LoadGameObjectScripts(); // must be after load Creature/Gameobject(Template/Data)
1324 objmgr.LoadEventScripts(); // must be after load Creature/Gameobject(Template/Data)
1325 sLog.outString( ">>> Scripts loaded" );
1326 sLog.outString();
1328 sLog.outString( "Loading Scripts text locales..." ); // must be after Load*Scripts calls
1329 objmgr.LoadDbScriptStrings();
1331 sLog.outString( "Initializing Scripts..." );
1332 if(!LoadScriptingModule())
1333 exit(1);
1335 ///- Initialize game time and timers
1336 sLog.outString( "DEBUG:: Initialize game time and timers" );
1337 m_gameTime = time(NULL);
1338 m_startTime=m_gameTime;
1340 tm local;
1341 time_t curr;
1342 time(&curr);
1343 local=*(localtime(&curr)); // dereference and assign
1344 char isoDate[128];
1345 sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1346 local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1348 WorldDatabase.PExecute("INSERT INTO uptime (startstring, starttime, uptime) VALUES('%s', " I64FMTD ", 0)",
1349 isoDate, uint64(m_startTime));
1351 m_timers[WUPDATE_OBJECTS].SetInterval(0);
1352 m_timers[WUPDATE_SESSIONS].SetInterval(0);
1353 m_timers[WUPDATE_WEATHERS].SetInterval(1000);
1354 m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*1000); //set auction update interval to 1 minute
1355 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
1356 //Update "uptime" table based on configuration entry in minutes.
1357 m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*1000); //erase corpses every 20 minutes
1359 //to set mailtimer to return mails every day between 4 and 5 am
1360 //mailtimer is increased when updating auctions
1361 //one second is 1000 -(tested on win system)
1362 mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * 1000) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1363 //1440
1364 mail_timer_expires = ( (DAY * 1000) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1365 sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1367 ///- Initilize static helper structures
1368 AIRegistry::Initialize();
1369 WaypointMovementGenerator<Creature>::Initialize();
1370 Player::InitVisibleBits();
1372 ///- Initialize MapManager
1373 sLog.outString( "Starting Map System" );
1374 MapManager::Instance().Initialize();
1376 ///- Initialize Battlegrounds
1377 sLog.outString( "Starting BattleGround System" );
1378 sBattleGroundMgr.CreateInitialBattleGrounds();
1379 sBattleGroundMgr.InitAutomaticArenaPointDistribution();
1381 //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1382 sLog.outString( "Loading Transports..." );
1383 MapManager::Instance().LoadTransports();
1385 sLog.outString("Deleting expired bans..." );
1386 loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1388 sLog.outString("Calculate next daily quest reset time..." );
1389 InitDailyQuestResetTime();
1391 sLog.outString("Starting Game Event system..." );
1392 uint32 nextGameEvent = gameeventmgr.Initialize();
1393 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent); //depend on next event
1395 sLog.outString( "WORLD: World initialized" );
1398 void World::DetectDBCLang()
1400 uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1402 if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1404 sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1405 m_lang_confid = LOCALE_enUS;
1408 ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1410 std::string availableLocalsStr;
1412 int default_locale = MAX_LOCALE;
1413 for (int i = MAX_LOCALE-1; i >= 0; --i)
1415 if ( strlen(race->name[i]) > 0) // check by race names
1417 default_locale = i;
1418 m_availableDbcLocaleMask |= (1 << i);
1419 availableLocalsStr += localeNames[i];
1420 availableLocalsStr += " ";
1424 if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1425 (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1427 default_locale = m_lang_confid;
1430 if(default_locale >= MAX_LOCALE)
1432 sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1433 exit(1);
1436 m_defaultDbcLocale = LocaleConstant(default_locale);
1438 sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1439 sLog.outString();
1442 /// Update the World !
1443 void World::Update(uint32 diff)
1445 ///- Update the different timers
1446 for(int i = 0; i < WUPDATE_COUNT; i++)
1447 if(m_timers[i].GetCurrent()>=0)
1448 m_timers[i].Update(diff);
1449 else m_timers[i].SetCurrent(0);
1451 ///- Update the game time and check for shutdown time
1452 _UpdateGameTime();
1454 /// Handle daily quests reset time
1455 if(m_gameTime > m_NextDailyQuestReset)
1457 ResetDailyQuests();
1458 m_NextDailyQuestReset += DAY;
1461 /// <ul><li> Handle auctions when the timer has passed
1462 if (m_timers[WUPDATE_AUCTIONS].Passed())
1464 m_timers[WUPDATE_AUCTIONS].Reset();
1466 ///- Update mails (return old mails with item, or delete them)
1467 //(tested... works on win)
1468 if (++mail_timer > mail_timer_expires)
1470 mail_timer = 0;
1471 objmgr.ReturnOrDeleteOldMails(true);
1474 AuctionHouseObject* AuctionMap;
1475 for (int i = 0; i < 3; i++)
1477 switch (i)
1479 case 0:
1480 AuctionMap = objmgr.GetAuctionsMap( 6 );//horde
1481 break;
1482 case 1:
1483 AuctionMap = objmgr.GetAuctionsMap( 2 );//alliance
1484 break;
1485 case 2:
1486 AuctionMap = objmgr.GetAuctionsMap( 7 );//neutral
1487 break;
1490 ///- Handle expired auctions
1491 AuctionHouseObject::AuctionEntryMap::iterator itr,next;
1492 for (itr = AuctionMap->GetAuctionsBegin(); itr != AuctionMap->GetAuctionsEnd();itr = next)
1494 next = itr;
1495 ++next;
1496 if (m_gameTime > (itr->second->time))
1498 ///- Either cancel the auction if there was no bidder
1499 if (itr->second->bidder == 0)
1501 objmgr.SendAuctionExpiredMail( itr->second );
1503 ///- Or perform the transaction
1504 else
1506 //we should send an "item sold" message if the seller is online
1507 //we send the item to the winner
1508 //we send the money to the seller
1509 objmgr.SendAuctionSuccessfulMail( itr->second );
1510 objmgr.SendAuctionWonMail( itr->second );
1513 ///- In any case clear the auction
1514 //No SQL injection (Id is integer)
1515 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",itr->second->Id);
1516 objmgr.RemoveAItem(itr->second->item_guidlow);
1517 delete itr->second;
1518 AuctionMap->RemoveAuction(itr->first);
1524 /// <li> Handle session updates when the timer has passed
1525 if (m_timers[WUPDATE_SESSIONS].Passed())
1527 m_timers[WUPDATE_SESSIONS].Reset();
1529 UpdateSessions(diff);
1532 /// <li> Handle weather updates when the timer has passed
1533 if (m_timers[WUPDATE_WEATHERS].Passed())
1535 m_timers[WUPDATE_WEATHERS].Reset();
1537 ///- Send an update signal to Weather objects
1538 WeatherMap::iterator itr, next;
1539 for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1541 next = itr;
1542 ++next;
1544 ///- and remove Weather objects for zones with no player
1545 //As interval > WorldTick
1546 if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1548 delete itr->second;
1549 m_weathers.erase(itr);
1553 /// <li> Update uptime table
1554 if (m_timers[WUPDATE_UPTIME].Passed())
1556 uint32 tmpDiff = (m_gameTime - m_startTime);
1557 uint32 maxClientsNum = sWorld.GetMaxActiveSessionCount();
1559 m_timers[WUPDATE_UPTIME].Reset();
1560 WorldDatabase.PExecute("UPDATE uptime SET uptime = %d, maxplayers = %d WHERE starttime = " I64FMTD, tmpDiff, maxClientsNum, uint64(m_startTime));
1563 /// <li> Handle all other objects
1564 if (m_timers[WUPDATE_OBJECTS].Passed())
1566 m_timers[WUPDATE_OBJECTS].Reset();
1567 ///- Update objects when the timer has passed (maps, transport, creatures,...)
1568 MapManager::Instance().Update(diff); // As interval = 0
1570 ///- Process necessary scripts
1571 if (!m_scriptSchedule.empty())
1572 ScriptsProcess();
1574 sBattleGroundMgr.Update(diff);
1577 // execute callbacks from sql queries that were queued recently
1578 UpdateResultQueue();
1580 ///- Erase corpses once every 20 minutes
1581 if (m_timers[WUPDATE_CORPSES].Passed())
1583 m_timers[WUPDATE_CORPSES].Reset();
1585 CorpsesErase();
1588 ///- Process Game events when necessary
1589 if (m_timers[WUPDATE_EVENTS].Passed())
1591 m_timers[WUPDATE_EVENTS].Reset(); // to give time for Update() to be processed
1592 uint32 nextGameEvent = gameeventmgr.Update();
1593 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1594 m_timers[WUPDATE_EVENTS].Reset();
1597 /// </ul>
1598 ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1599 MapManager::Instance().DoDelayedMovesAndRemoves();
1601 // update the instance reset times
1602 sInstanceSaveManager.Update();
1604 // And last, but not least handle the issued cli commands
1605 ProcessCliCommands();
1608 /// Put scripts in the execution queue
1609 void World::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
1611 ///- Find the script map
1612 ScriptMapMap::const_iterator s = scripts.find(id);
1613 if (s == scripts.end())
1614 return;
1616 // prepare static data
1617 uint64 sourceGUID = source->GetGUID();
1618 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1619 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1621 ///- Schedule script execution for all scripts in the script map
1622 ScriptMap const *s2 = &(s->second);
1623 bool immedScript = false;
1624 for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
1626 ScriptAction sa;
1627 sa.sourceGUID = sourceGUID;
1628 sa.targetGUID = targetGUID;
1629 sa.ownerGUID = ownerGUID;
1631 sa.script = &iter->second;
1632 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + iter->first, sa));
1633 if (iter->first == 0)
1634 immedScript = true;
1636 ///- If one of the effects should be immediate, launch the script execution
1637 if (immedScript)
1638 ScriptsProcess();
1641 void World::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
1643 // NOTE: script record _must_ exist until command executed
1645 // prepare static data
1646 uint64 sourceGUID = source->GetGUID();
1647 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1648 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1650 ScriptAction sa;
1651 sa.sourceGUID = sourceGUID;
1652 sa.targetGUID = targetGUID;
1653 sa.ownerGUID = ownerGUID;
1655 sa.script = &script;
1656 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + delay, sa));
1658 ///- If effects should be immediate, launch the script execution
1659 if(delay == 0)
1660 ScriptsProcess();
1663 /// Process queued scripts
1664 void World::ScriptsProcess()
1666 if (m_scriptSchedule.empty())
1667 return;
1669 ///- Process overdue queued scripts
1670 std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
1671 // ok as multimap is a *sorted* associative container
1672 while (!m_scriptSchedule.empty() && (iter->first <= m_gameTime))
1674 ScriptAction const& step = iter->second;
1676 Object* source = NULL;
1678 if(step.sourceGUID)
1680 switch(GUID_HIPART(step.sourceGUID))
1682 case HIGHGUID_ITEM:
1683 // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1685 Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
1686 if(player)
1687 source = player->GetItemByGuid(step.sourceGUID);
1688 break;
1690 case HIGHGUID_UNIT:
1691 source = HashMapHolder<Creature>::Find(step.sourceGUID);
1692 break;
1693 case HIGHGUID_PET:
1694 source = HashMapHolder<Pet>::Find(step.sourceGUID);
1695 break;
1696 case HIGHGUID_VEHICLE:
1697 source = HashMapHolder<Vehicle>::Find(step.sourceGUID);
1698 break;
1699 case HIGHGUID_PLAYER:
1700 source = HashMapHolder<Player>::Find(step.sourceGUID);
1701 break;
1702 case HIGHGUID_GAMEOBJECT:
1703 source = HashMapHolder<GameObject>::Find(step.sourceGUID);
1704 break;
1705 case HIGHGUID_CORPSE:
1706 source = HashMapHolder<Corpse>::Find(step.sourceGUID);
1707 break;
1708 default:
1709 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
1710 break;
1714 if(source && !source->IsInWorld()) source = NULL;
1716 Object* target = NULL;
1718 if(step.targetGUID)
1720 switch(GUID_HIPART(step.targetGUID))
1722 case HIGHGUID_UNIT:
1723 target = HashMapHolder<Creature>::Find(step.targetGUID);
1724 break;
1725 case HIGHGUID_PET:
1726 target = HashMapHolder<Pet>::Find(step.targetGUID);
1727 break;
1728 case HIGHGUID_VEHICLE:
1729 target = HashMapHolder<Vehicle>::Find(step.targetGUID);
1730 break;
1731 case HIGHGUID_PLAYER: // empty GUID case also
1732 target = HashMapHolder<Player>::Find(step.targetGUID);
1733 break;
1734 case HIGHGUID_GAMEOBJECT:
1735 target = HashMapHolder<GameObject>::Find(step.targetGUID);
1736 break;
1737 case HIGHGUID_CORPSE:
1738 target = HashMapHolder<Corpse>::Find(step.targetGUID);
1739 break;
1740 default:
1741 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
1742 break;
1746 if(target && !target->IsInWorld()) target = NULL;
1748 switch (step.script->command)
1750 case SCRIPT_COMMAND_TALK:
1752 if(!source)
1754 sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1755 break;
1758 if(source->GetTypeId()!=TYPEID_UNIT)
1760 sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1761 break;
1764 uint64 unit_target = target ? target->GetGUID() : 0;
1766 //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1767 switch(step.script->datalong)
1769 case 0: // Say
1770 ((Creature *)source)->Say(step.script->dataint, LANG_UNIVERSAL, unit_target);
1771 break;
1772 case 1: // Whisper
1773 if(!unit_target)
1775 sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
1776 break;
1778 ((Creature *)source)->Whisper(step.script->dataint,unit_target);
1779 break;
1780 case 2: // Yell
1781 ((Creature *)source)->Yell(step.script->dataint, LANG_UNIVERSAL, unit_target);
1782 break;
1783 case 3: // Emote text
1784 ((Creature *)source)->TextEmote(step.script->dataint, unit_target);
1785 break;
1786 default:
1787 break; // must be already checked at load
1789 break;
1792 case SCRIPT_COMMAND_EMOTE:
1793 if(!source)
1795 sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1796 break;
1799 if(source->GetTypeId()!=TYPEID_UNIT)
1801 sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1802 break;
1805 ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
1806 break;
1807 case SCRIPT_COMMAND_FIELD_SET:
1808 if(!source)
1810 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1811 break;
1813 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1815 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1816 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1817 break;
1820 source->SetUInt32Value(step.script->datalong, step.script->datalong2);
1821 break;
1822 case SCRIPT_COMMAND_MOVE_TO:
1823 if(!source)
1825 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1826 break;
1829 if(source->GetTypeId()!=TYPEID_UNIT)
1831 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1832 break;
1834 ((Unit *)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, ((Unit *)source)->GetUnitMovementFlags(), step.script->datalong2 );
1835 ((Unit *)source)->GetMap()->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
1836 break;
1837 case SCRIPT_COMMAND_FLAG_SET:
1838 if(!source)
1840 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1841 break;
1843 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1845 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1846 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1847 break;
1850 source->SetFlag(step.script->datalong, step.script->datalong2);
1851 break;
1852 case SCRIPT_COMMAND_FLAG_REMOVE:
1853 if(!source)
1855 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1856 break;
1858 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1860 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1861 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1862 break;
1865 source->RemoveFlag(step.script->datalong, step.script->datalong2);
1866 break;
1868 case SCRIPT_COMMAND_TELEPORT_TO:
1870 // accept player in any one from target/source arg
1871 if (!target && !source)
1873 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1874 break;
1877 // must be only Player
1878 if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
1880 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
1881 break;
1884 Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
1886 pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
1887 break;
1890 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
1892 if(!step.script->datalong) // creature not specified
1894 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1895 break;
1898 if(!source)
1900 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1901 break;
1904 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1906 if(!summoner)
1908 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1909 break;
1912 float x = step.script->x;
1913 float y = step.script->y;
1914 float z = step.script->z;
1915 float o = step.script->o;
1917 Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
1918 if (!pCreature)
1920 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
1921 break;
1924 break;
1927 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
1929 if(!step.script->datalong) // gameobject not specified
1931 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1932 break;
1935 if(!source)
1937 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1938 break;
1941 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1943 if(!summoner)
1945 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1946 break;
1949 GameObject *go = NULL;
1950 int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
1952 CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
1953 Cell cell(p);
1954 cell.data.Part.reserved = ALL_DISTRICT;
1956 MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
1957 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(summoner, go,go_check);
1959 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1960 CellLock<GridReadGuard> cell_lock(cell, p);
1961 cell_lock->Visit(cell_lock, object_checker, *summoner->GetMap());
1963 if ( !go )
1965 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
1966 break;
1969 if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1970 go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1971 go->GetGoType()==GAMEOBJECT_TYPE_DOOR ||
1972 go->GetGoType()==GAMEOBJECT_TYPE_BUTTON ||
1973 go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
1975 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
1976 break;
1979 if( go->isSpawned() )
1980 break; //gameobject already spawned
1982 go->SetLootState(GO_READY);
1983 go->SetRespawnTime(time_to_despawn); //despawn object in ? seconds
1985 go->GetMap()->Add(go);
1986 break;
1988 case SCRIPT_COMMAND_OPEN_DOOR:
1990 if(!step.script->datalong) // door not specified
1992 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1993 break;
1996 if(!source)
1998 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1999 break;
2002 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
2004 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
2005 break;
2008 Unit* caster = (Unit*)source;
2010 GameObject *door = NULL;
2011 int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
2013 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
2014 Cell cell(p);
2015 cell.data.Part.reserved = ALL_DISTRICT;
2017 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
2018 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(caster,door,go_check);
2020 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
2021 CellLock<GridReadGuard> cell_lock(cell, p);
2022 cell_lock->Visit(cell_lock, object_checker, *caster->GetMap());
2024 if ( !door )
2026 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
2027 break;
2029 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
2031 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
2032 break;
2035 if( !door->GetGoState() )
2036 break; //door already open
2038 door->UseDoorOrButton(time_to_close);
2040 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
2041 ((GameObject*)target)->UseDoorOrButton(time_to_close);
2042 break;
2044 case SCRIPT_COMMAND_CLOSE_DOOR:
2046 if(!step.script->datalong) // guid for door not specified
2048 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
2049 break;
2052 if(!source)
2054 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
2055 break;
2058 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
2060 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
2061 break;
2064 Unit* caster = (Unit*)source;
2066 GameObject *door = NULL;
2067 int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
2069 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
2070 Cell cell(p);
2071 cell.data.Part.reserved = ALL_DISTRICT;
2073 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
2074 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(caster,door,go_check);
2076 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
2077 CellLock<GridReadGuard> cell_lock(cell, p);
2078 cell_lock->Visit(cell_lock, object_checker, *caster->GetMap());
2080 if ( !door )
2082 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
2083 break;
2085 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
2087 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
2088 break;
2091 if( door->GetGoState() )
2092 break; //door already closed
2094 door->UseDoorOrButton(time_to_open);
2096 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
2097 ((GameObject*)target)->UseDoorOrButton(time_to_open);
2099 break;
2101 case SCRIPT_COMMAND_QUEST_EXPLORED:
2103 if(!source)
2105 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
2106 break;
2109 if(!target)
2111 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
2112 break;
2115 // when script called for item spell casting then target == (unit or GO) and source is player
2116 WorldObject* worldObject;
2117 Player* player;
2119 if(target->GetTypeId()==TYPEID_PLAYER)
2121 if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
2123 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
2124 break;
2127 worldObject = (WorldObject*)source;
2128 player = (Player*)target;
2130 else
2132 if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
2134 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
2135 break;
2138 if(source->GetTypeId()!=TYPEID_PLAYER)
2140 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
2141 break;
2144 worldObject = (WorldObject*)target;
2145 player = (Player*)source;
2148 // quest id and flags checked at script loading
2149 if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
2150 (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
2151 player->AreaExploredOrEventHappens(step.script->datalong);
2152 else
2153 player->FailQuest(step.script->datalong);
2155 break;
2158 case SCRIPT_COMMAND_ACTIVATE_OBJECT:
2160 if(!source)
2162 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
2163 break;
2166 if(!source->isType(TYPEMASK_UNIT))
2168 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2169 break;
2172 if(!target)
2174 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
2175 break;
2178 if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
2180 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
2181 break;
2184 Unit* caster = (Unit*)source;
2186 GameObject *go = (GameObject*)target;
2188 go->Use(caster);
2189 break;
2192 case SCRIPT_COMMAND_REMOVE_AURA:
2194 Object* cmdTarget = step.script->datalong2 ? source : target;
2196 if(!cmdTarget)
2198 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
2199 break;
2202 if(!cmdTarget->isType(TYPEMASK_UNIT))
2204 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2205 break;
2208 ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
2209 break;
2212 case SCRIPT_COMMAND_CAST_SPELL:
2214 if(!source)
2216 sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
2217 break;
2220 if(!source->isType(TYPEMASK_UNIT))
2222 sLog.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2223 break;
2226 Object* cmdTarget = step.script->datalong2 ? source : target;
2228 if(!cmdTarget)
2230 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 ? "source" : "target");
2231 break;
2234 if(!cmdTarget->isType(TYPEMASK_UNIT))
2236 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2237 break;
2240 Unit* spellTarget = (Unit*)cmdTarget;
2242 //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2243 ((Unit*)source)->CastSpell(spellTarget,step.script->datalong,false);
2245 break;
2248 default:
2249 sLog.outError("Unknown script command %u called.",step.script->command);
2250 break;
2253 m_scriptSchedule.erase(iter);
2255 iter = m_scriptSchedule.begin();
2257 return;
2260 /// Send a packet to all players (except self if mentioned)
2261 void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
2263 SessionMap::iterator itr;
2264 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2266 if (itr->second &&
2267 itr->second->GetPlayer() &&
2268 itr->second->GetPlayer()->IsInWorld() &&
2269 itr->second != self &&
2270 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2272 itr->second->SendPacket(packet);
2277 /// Send a System Message to all players (except self if mentioned)
2278 void World::SendWorldText(int32 string_id, ...)
2280 std::vector<std::vector<WorldPacket*> > data_cache; // 0 = default, i => i-1 locale index
2282 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2284 if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
2285 continue;
2287 uint32 loc_idx = itr->second->GetSessionDbLocaleIndex();
2288 uint32 cache_idx = loc_idx+1;
2290 std::vector<WorldPacket*>* data_list;
2292 // create if not cached yet
2293 if(data_cache.size() < cache_idx+1 || data_cache[cache_idx].empty())
2295 if(data_cache.size() < cache_idx+1)
2296 data_cache.resize(cache_idx+1);
2298 data_list = &data_cache[cache_idx];
2300 char const* text = objmgr.GetMangosString(string_id,loc_idx);
2302 char buf[1000];
2304 va_list argptr;
2305 va_start( argptr, string_id );
2306 vsnprintf( buf,1000, text, argptr );
2307 va_end( argptr );
2309 char* pos = &buf[0];
2311 while(char* line = ChatHandler::LineFromMessage(pos))
2313 WorldPacket* data = new WorldPacket();
2314 ChatHandler::FillMessageData(data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2315 data_list->push_back(data);
2318 else
2319 data_list = &data_cache[cache_idx];
2321 for(int i = 0; i < data_list->size(); ++i)
2322 itr->second->SendPacket((*data_list)[i]);
2325 // free memory
2326 for(int i = 0; i < data_cache.size(); ++i)
2327 for(int j = 0; j < data_cache[i].size(); ++j)
2328 delete data_cache[i][j];
2331 /// Send a System Message to all players (except self if mentioned)
2332 void World::SendGlobalText(const char* text, WorldSession *self)
2334 WorldPacket data;
2336 // need copy to prevent corruption by strtok call in LineFromMessage original string
2337 char* buf = strdup(text);
2338 char* pos = buf;
2340 while(char* line = ChatHandler::LineFromMessage(pos))
2342 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2343 SendGlobalMessage(&data, self);
2346 free(buf);
2349 /// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2350 void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
2352 SessionMap::iterator itr;
2353 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2355 if (itr->second &&
2356 itr->second->GetPlayer() &&
2357 itr->second->GetPlayer()->IsInWorld() &&
2358 itr->second->GetPlayer()->GetZoneId() == zone &&
2359 itr->second != self &&
2360 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2362 itr->second->SendPacket(packet);
2367 /// Send a System Message to all players in the zone (except self if mentioned)
2368 void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
2370 WorldPacket data;
2371 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
2372 SendZoneMessage(zone, &data, self,team);
2375 /// Kick (and save) all players
2376 void World::KickAll()
2378 m_QueuedPlayer.clear(); // prevent send queue update packet and login queued sessions
2380 // session not removed at kick and will removed in next update tick
2381 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2382 itr->second->KickPlayer();
2385 /// Kick (and save) all players with security level less `sec`
2386 void World::KickAllLess(AccountTypes sec)
2388 // session not removed at kick and will removed in next update tick
2389 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2390 if(itr->second->GetSecurity() < sec)
2391 itr->second->KickPlayer();
2394 /// Kick (and save) the designated player
2395 bool World::KickPlayer(const std::string& playerName)
2397 SessionMap::iterator itr;
2399 // session not removed at kick and will removed in next update tick
2400 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2402 if(!itr->second)
2403 continue;
2404 Player *player = itr->second->GetPlayer();
2405 if(!player)
2406 continue;
2407 if( player->IsInWorld() )
2409 if (playerName == player->GetName())
2411 itr->second->KickPlayer();
2412 return true;
2416 return false;
2419 /// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2420 BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, std::string duration, std::string reason, std::string author)
2422 loginDatabase.escape_string(nameOrIP);
2423 loginDatabase.escape_string(reason);
2424 std::string safe_author=author;
2425 loginDatabase.escape_string(safe_author);
2427 uint32 duration_secs = TimeStringToSecs(duration);
2428 QueryResult *resultAccounts = NULL; //used for kicking
2430 ///- Update the database with ban information
2431 switch(mode)
2433 case BAN_IP:
2434 //No SQL injection as strings are escaped
2435 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
2436 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());
2437 break;
2438 case BAN_ACCOUNT:
2439 //No SQL injection as string is escaped
2440 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2441 break;
2442 case BAN_CHARACTER:
2443 //No SQL injection as string is escaped
2444 resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2445 break;
2446 default:
2447 return BAN_SYNTAX_ERROR;
2450 if(!resultAccounts)
2452 if(mode==BAN_IP)
2453 return BAN_SUCCESS; // ip correctly banned but nobody affected (yet)
2454 else
2455 return BAN_NOTFOUND; // Nobody to ban
2458 ///- Disconnect all affected players (for IP it can be several)
2461 Field* fieldsAccount = resultAccounts->Fetch();
2462 uint32 account = fieldsAccount->GetUInt32();
2464 if(mode!=BAN_IP)
2466 //No SQL injection as strings are escaped
2467 loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2468 account,duration_secs,safe_author.c_str(),reason.c_str());
2471 if (WorldSession* sess = FindSession(account))
2472 if(std::string(sess->GetPlayerName()) != author)
2473 sess->KickPlayer();
2475 while( resultAccounts->NextRow() );
2477 delete resultAccounts;
2478 return BAN_SUCCESS;
2481 /// Remove a ban from an account or IP address
2482 bool World::RemoveBanAccount(BanMode mode, std::string nameOrIP)
2484 if (mode == BAN_IP)
2486 loginDatabase.escape_string(nameOrIP);
2487 loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
2489 else
2491 uint32 account = 0;
2492 if (mode == BAN_ACCOUNT)
2493 account = accmgr.GetId (nameOrIP);
2494 else if (mode == BAN_CHARACTER)
2495 account = objmgr.GetPlayerAccountIdByPlayerName (nameOrIP);
2497 if (!account)
2498 return false;
2500 //NO SQL injection as account is uint32
2501 loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
2503 return true;
2506 /// Update the game time
2507 void World::_UpdateGameTime()
2509 ///- update the time
2510 time_t thisTime = time(NULL);
2511 uint32 elapsed = uint32(thisTime - m_gameTime);
2512 m_gameTime = thisTime;
2514 ///- if there is a shutdown timer
2515 if(!m_stopEvent && m_ShutdownTimer > 0 && elapsed > 0)
2517 ///- ... and it is overdue, stop the world (set m_stopEvent)
2518 if( m_ShutdownTimer <= elapsed )
2520 if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2521 m_stopEvent = true; // exist code already set
2522 else
2523 m_ShutdownTimer = 1; // minimum timer value to wait idle state
2525 ///- ... else decrease it and if necessary display a shutdown countdown to the users
2526 else
2528 m_ShutdownTimer -= elapsed;
2530 ShutdownMsg();
2535 /// Shutdown the server
2536 void World::ShutdownServ(uint32 time, uint32 options, uint8 exitcode)
2538 // ignore if server shutdown at next tick
2539 if(m_stopEvent)
2540 return;
2542 m_ShutdownMask = options;
2543 m_ExitCode = exitcode;
2545 ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2546 if(time==0)
2548 if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2549 m_stopEvent = true; // exist code already set
2550 else
2551 m_ShutdownTimer = 1; //So that the session count is re-evaluated at next world tick
2553 ///- Else set the shutdown timer and warn users
2554 else
2556 m_ShutdownTimer = time;
2557 ShutdownMsg(true);
2561 /// Display a shutdown message to the user(s)
2562 void World::ShutdownMsg(bool show, Player* player)
2564 // not show messages for idle shutdown mode
2565 if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
2566 return;
2568 ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2569 if ( show ||
2570 (m_ShutdownTimer < 10) ||
2571 // < 30 sec; every 5 sec
2572 (m_ShutdownTimer<30 && (m_ShutdownTimer % 5 )==0) ||
2573 // < 5 min ; every 1 min
2574 (m_ShutdownTimer<5*MINUTE && (m_ShutdownTimer % MINUTE )==0) ||
2575 // < 30 min ; every 5 min
2576 (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
2577 // < 12 h ; every 1 h
2578 (m_ShutdownTimer<12*HOUR && (m_ShutdownTimer % HOUR )==0) ||
2579 // > 12 h ; every 12 h
2580 (m_ShutdownTimer>12*HOUR && (m_ShutdownTimer % (12*HOUR) )==0))
2582 std::string str = secsToTimeString(m_ShutdownTimer);
2584 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
2586 SendServerMessage(msgid,str.c_str(),player);
2587 DEBUG_LOG("Server is %s in %s",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"),str.c_str());
2591 /// Cancel a planned server shutdown
2592 void World::ShutdownCancel()
2594 // nothing cancel or too later
2595 if(!m_ShutdownTimer || m_stopEvent)
2596 return;
2598 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2600 m_ShutdownMask = 0;
2601 m_ShutdownTimer = 0;
2602 m_ExitCode = SHUTDOWN_EXIT_CODE; // to default value
2603 SendServerMessage(msgid);
2605 DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2608 /// Send a server message to the user(s)
2609 void World::SendServerMessage(uint32 type, const char *text, Player* player)
2611 WorldPacket data(SMSG_SERVER_MESSAGE, 50); // guess size
2612 data << uint32(type);
2613 if(type <= SERVER_MSG_STRING)
2614 data << text;
2616 if(player)
2617 player->GetSession()->SendPacket(&data);
2618 else
2619 SendGlobalMessage( &data );
2622 void World::UpdateSessions( uint32 diff )
2624 ///- Add new sessions
2625 while(!addSessQueue.empty())
2627 WorldSession* sess = addSessQueue.next ();
2628 AddSession_ (sess);
2631 ///- Then send an update signal to remaining ones
2632 for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2634 next = itr;
2635 ++next;
2637 if(!itr->second)
2638 continue;
2640 ///- and remove not active sessions from the list
2641 if(!itr->second->Update(diff)) // As interval = 0
2643 RemoveQueuedPlayer (itr->second);
2644 delete itr->second;
2645 m_sessions.erase(itr);
2650 // This handles the issued and queued CLI commands
2651 void World::ProcessCliCommands()
2653 if (cliCmdQueue.empty())
2654 return;
2656 CliCommandHolder::Print* zprint;
2658 while (!cliCmdQueue.empty())
2660 sLog.outDebug("CLI command under processing...");
2661 CliCommandHolder *command = cliCmdQueue.next();
2663 zprint = command->m_print;
2665 CliHandler(zprint).ParseCommands(command->m_command);
2667 delete command;
2670 // print the console message here so it looks right
2671 zprint("mangos>");
2674 void World::InitResultQueue()
2676 m_resultQueue = new SqlResultQueue;
2677 CharacterDatabase.SetResultQueue(m_resultQueue);
2680 void World::UpdateResultQueue()
2682 m_resultQueue->Update();
2685 void World::UpdateRealmCharCount(uint32 accountId)
2687 CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2688 "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2691 void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2693 if (resultCharCount)
2695 Field *fields = resultCharCount->Fetch();
2696 uint32 charCount = fields[0].GetUInt32();
2697 delete resultCharCount;
2698 loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2699 loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2703 void World::InitDailyQuestResetTime()
2705 time_t mostRecentQuestTime;
2707 QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2708 if(result)
2710 Field *fields = result->Fetch();
2712 mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2713 delete result;
2715 else
2716 mostRecentQuestTime = 0;
2718 // client built-in time for reset is 6:00 AM
2719 // FIX ME: client not show day start time
2720 time_t curTime = time(NULL);
2721 tm localTm = *localtime(&curTime);
2722 localTm.tm_hour = 6;
2723 localTm.tm_min = 0;
2724 localTm.tm_sec = 0;
2726 // current day reset time
2727 time_t curDayResetTime = mktime(&localTm);
2729 // last reset time before current moment
2730 time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2732 // need reset (if we have quest time before last reset time (not processed by some reason)
2733 if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2734 m_NextDailyQuestReset = mostRecentQuestTime;
2735 else
2737 // plan next reset time
2738 m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2742 void World::ResetDailyQuests()
2744 sLog.outDetail("Daily quests reset for all characters.");
2745 CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2746 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2747 if(itr->second->GetPlayer())
2748 itr->second->GetPlayer()->ResetDailyQuestStatus();
2751 void World::SetPlayerLimit( int32 limit, bool needUpdate )
2753 if(limit < -SEC_ADMINISTRATOR)
2754 limit = -SEC_ADMINISTRATOR;
2756 // lock update need
2757 bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2759 m_playerLimit = limit;
2761 if(db_update_need)
2762 loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2765 void World::UpdateMaxSessionCounters()
2767 m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2768 m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2771 void World::LoadDBVersion()
2773 QueryResult* result = WorldDatabase.Query("SELECT version FROM db_version LIMIT 1");
2774 if(result)
2776 Field* fields = result->Fetch();
2778 m_DBVersion = fields[0].GetString();
2779 delete result;
2781 else
2782 m_DBVersion = "unknown world database";