[7474] Set correct value/maxvalue for skill with fixed skill value at skill loading.
[AHbot.git] / src / game / World.cpp
blobc3c2f94ea0765508873bd95b405f87fef3d39eb1
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 "Database/DatabaseEnv.h"
25 #include "Config/ConfigEnv.h"
26 #include "SystemConfig.h"
27 #include "Log.h"
28 #include "Opcodes.h"
29 #include "WorldSession.h"
30 #include "WorldPacket.h"
31 #include "Weather.h"
32 #include "Player.h"
33 #include "Vehicle.h"
34 #include "SkillExtraItems.h"
35 #include "SkillDiscovery.h"
36 #include "World.h"
37 #include "AccountMgr.h"
38 #include "AchievementMgr.h"
39 #include "AuctionHouseMgr.h"
40 #include "ObjectMgr.h"
41 #include "SpellMgr.h"
42 #include "Chat.h"
43 #include "Database/DBCStores.h"
44 #include "LootMgr.h"
45 #include "ItemEnchantmentMgr.h"
46 #include "MapManager.h"
47 #include "ScriptCalls.h"
48 #include "CreatureAIRegistry.h"
49 #include "Policies/SingletonImp.h"
50 #include "BattleGroundMgr.h"
51 #include "TemporarySummon.h"
52 #include "WaypointMovementGenerator.h"
53 #include "VMapFactory.h"
54 #include "GlobalEvents.h"
55 #include "GameEventMgr.h"
56 #include "PoolHandler.h"
57 #include "Database/DatabaseImpl.h"
58 #include "GridNotifiersImpl.h"
59 #include "CellImpl.h"
60 #include "InstanceSaveMgr.h"
61 #include "WaypointManager.h"
62 #include "GMTicketMgr.h"
63 #include "Util.h"
65 INSTANTIATE_SINGLETON_1( World );
67 volatile bool World::m_stopEvent = false;
68 uint8 World::m_ExitCode = SHUTDOWN_EXIT_CODE;
69 volatile uint32 World::m_worldLoopCounter = 0;
71 float World::m_MaxVisibleDistanceForCreature = DEFAULT_VISIBILITY_DISTANCE;
72 float World::m_MaxVisibleDistanceForPlayer = DEFAULT_VISIBILITY_DISTANCE;
73 float World::m_MaxVisibleDistanceForObject = DEFAULT_VISIBILITY_DISTANCE;
74 float World::m_MaxVisibleDistanceInFlight = DEFAULT_VISIBILITY_DISTANCE;
75 float World::m_VisibleUnitGreyDistance = 0;
76 float World::m_VisibleObjectGreyDistance = 0;
78 // ServerMessages.dbc
79 enum ServerMessageType
81 SERVER_MSG_SHUTDOWN_TIME = 1,
82 SERVER_MSG_RESTART_TIME = 2,
83 SERVER_MSG_STRING = 3,
84 SERVER_MSG_SHUTDOWN_CANCELLED = 4,
85 SERVER_MSG_RESTART_CANCELLED = 5
88 struct ScriptAction
90 uint64 sourceGUID;
91 uint64 targetGUID;
92 uint64 ownerGUID; // owner of source if source is item
93 ScriptInfo const* script; // pointer to static script data
96 /// World constructor
97 World::World()
99 m_playerLimit = 0;
100 m_allowMovement = true;
101 m_ShutdownMask = 0;
102 m_ShutdownTimer = 0;
103 m_gameTime=time(NULL);
104 m_startTime=m_gameTime;
105 m_maxActiveSessionCount = 0;
106 m_maxQueuedSessionCount = 0;
107 m_resultQueue = NULL;
108 m_NextDailyQuestReset = 0;
110 m_defaultDbcLocale = LOCALE_enUS;
111 m_availableDbcLocaleMask = 0;
114 /// World destructor
115 World::~World()
117 ///- Empty the kicked session set
118 while (!m_sessions.empty())
120 // not remove from queue, prevent loading new sessions
121 delete m_sessions.begin()->second;
122 m_sessions.erase(m_sessions.begin());
125 ///- Empty the WeatherMap
126 for (WeatherMap::iterator itr = m_weathers.begin(); itr != m_weathers.end(); ++itr)
127 delete itr->second;
129 m_weathers.clear();
131 while (!cliCmdQueue.empty())
132 delete cliCmdQueue.next();
134 VMAP::VMapFactory::clear();
136 if(m_resultQueue) delete m_resultQueue;
138 //TODO free addSessQueue
141 /// Find a player in a specified zone
142 Player* World::FindPlayerInZone(uint32 zone)
144 ///- circle through active sessions and return the first player found in the zone
145 SessionMap::iterator itr;
146 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
148 if(!itr->second)
149 continue;
150 Player *player = itr->second->GetPlayer();
151 if(!player)
152 continue;
153 if( player->IsInWorld() && player->GetZoneId() == zone )
155 // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone.
156 return player;
159 return NULL;
162 /// Find a session by its id
163 WorldSession* World::FindSession(uint32 id) const
165 SessionMap::const_iterator itr = m_sessions.find(id);
167 if(itr != m_sessions.end())
168 return itr->second; // also can return NULL for kicked session
169 else
170 return NULL;
173 /// Remove a given session
174 bool World::RemoveSession(uint32 id)
176 ///- Find the session, kick the user, but we can't delete session at this moment to prevent iterator invalidation
177 SessionMap::iterator itr = m_sessions.find(id);
179 if(itr != m_sessions.end() && itr->second)
181 if (itr->second->PlayerLoading())
182 return false;
183 itr->second->KickPlayer();
186 return true;
189 void World::AddSession(WorldSession* s)
191 addSessQueue.add(s);
194 void
195 World::AddSession_ (WorldSession* s)
197 ASSERT (s);
199 //NOTE - Still there is race condition in WorldSession* being used in the Sockets
201 ///- kick already loaded player with same account (if any) and remove session
202 ///- if player is in loading and want to load again, return
203 if (!RemoveSession (s->GetAccountId ()))
205 s->KickPlayer ();
206 delete s; // session not added yet in session list, so not listed in queue
207 return;
210 // decrease session counts only at not reconnection case
211 bool decrease_session = true;
213 // if session already exist, prepare to it deleting at next world update
214 // NOTE - KickPlayer() should be called on "old" in RemoveSession()
216 SessionMap::const_iterator old = m_sessions.find(s->GetAccountId ());
218 if(old != m_sessions.end())
220 // prevent decrease sessions count if session queued
221 if(RemoveQueuedPlayer(old->second))
222 decrease_session = false;
223 // not remove replaced session form queue if listed
224 delete old->second;
228 m_sessions[s->GetAccountId ()] = s;
230 uint32 Sessions = GetActiveAndQueuedSessionCount ();
231 uint32 pLimit = GetPlayerAmountLimit ();
232 uint32 QueueSize = GetQueueSize (); //number of players in the queue
234 //so we don't count the user trying to
235 //login as a session and queue the socket that we are using
236 if(decrease_session)
237 --Sessions;
239 if (pLimit > 0 && Sessions >= pLimit && s->GetSecurity () == SEC_PLAYER )
241 AddQueuedPlayer (s);
242 UpdateMaxSessionCounters ();
243 sLog.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s->GetAccountId (), ++QueueSize);
244 return;
247 WorldPacket packet(SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
248 packet << uint8 (AUTH_OK);
249 packet << uint32 (0); // BillingTimeRemaining
250 packet << uint8 (0); // BillingPlanFlags
251 packet << uint32 (0); // BillingTimeRested
252 packet << uint8 (s->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
253 s->SendPacket (&packet);
255 UpdateMaxSessionCounters ();
257 // Updates the population
258 if (pLimit > 0)
260 float popu = GetActiveSessionCount (); //updated number of users on the server
261 popu /= pLimit;
262 popu *= 2;
263 loginDatabase.PExecute ("UPDATE realmlist SET population = '%f' WHERE id = '%d'", popu, realmID);
264 sLog.outDetail ("Server Population (%f).", popu);
268 int32 World::GetQueuePos(WorldSession* sess)
270 uint32 position = 1;
272 for(Queue::iterator iter = m_QueuedPlayer.begin(); iter != m_QueuedPlayer.end(); ++iter, ++position)
273 if((*iter) == sess)
274 return position;
276 return 0;
279 void World::AddQueuedPlayer(WorldSession* sess)
281 sess->SetInQueue(true);
282 m_QueuedPlayer.push_back (sess);
284 // The 1st SMSG_AUTH_RESPONSE needs to contain other info too.
285 WorldPacket packet (SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
286 packet << uint8 (AUTH_WAIT_QUEUE);
287 packet << uint32 (0); // BillingTimeRemaining
288 packet << uint8 (0); // BillingPlanFlags
289 packet << uint32 (0); // BillingTimeRested
290 packet << uint8 (sess->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
291 packet << uint32(GetQueuePos (sess));
292 sess->SendPacket (&packet);
294 //sess->SendAuthWaitQue (GetQueuePos (sess));
297 bool World::RemoveQueuedPlayer(WorldSession* sess)
299 // sessions count including queued to remove (if removed_session set)
300 uint32 sessions = GetActiveSessionCount();
302 uint32 position = 1;
303 Queue::iterator iter = m_QueuedPlayer.begin();
305 // search to remove and count skipped positions
306 bool found = false;
308 for(;iter != m_QueuedPlayer.end(); ++iter, ++position)
310 if(*iter==sess)
312 sess->SetInQueue(false);
313 iter = m_QueuedPlayer.erase(iter);
314 found = true; // removing queued session
315 break;
319 // iter point to next socked after removed or end()
320 // position store position of removed socket and then new position next socket after removed
322 // if session not queued then we need decrease sessions count
323 if(!found && sessions)
324 --sessions;
326 // accept first in queue
327 if( (!m_playerLimit || sessions < m_playerLimit) && !m_QueuedPlayer.empty() )
329 WorldSession* pop_sess = m_QueuedPlayer.front();
330 pop_sess->SetInQueue(false);
331 pop_sess->SendAuthWaitQue(0);
332 m_QueuedPlayer.pop_front();
334 // update iter to point first queued socket or end() if queue is empty now
335 iter = m_QueuedPlayer.begin();
336 position = 1;
339 // update position from iter to end()
340 // iter point to first not updated socket, position store new position
341 for(; iter != m_QueuedPlayer.end(); ++iter, ++position)
342 (*iter)->SendAuthWaitQue(position);
344 return found;
347 /// Find a Weather object by the given zoneid
348 Weather* World::FindWeather(uint32 id) const
350 WeatherMap::const_iterator itr = m_weathers.find(id);
352 if(itr != m_weathers.end())
353 return itr->second;
354 else
355 return 0;
358 /// Remove a Weather object for the given zoneid
359 void World::RemoveWeather(uint32 id)
361 // not called at the moment. Kept for completeness
362 WeatherMap::iterator itr = m_weathers.find(id);
364 if(itr != m_weathers.end())
366 delete itr->second;
367 m_weathers.erase(itr);
371 /// Add a Weather object to the list
372 Weather* World::AddWeather(uint32 zone_id)
374 WeatherZoneChances const* weatherChances = objmgr.GetWeatherChances(zone_id);
376 // zone not have weather, ignore
377 if(!weatherChances)
378 return NULL;
380 Weather* w = new Weather(zone_id,weatherChances);
381 m_weathers[w->GetZone()] = w;
382 w->ReGenerate();
383 w->UpdateWeather();
384 return w;
387 /// Initialize config values
388 void World::LoadConfigSettings(bool reload)
390 if(reload)
392 if(!sConfig.Reload())
394 sLog.outError("World settings reload fail: can't read settings from %s.",sConfig.GetFilename().c_str());
395 return;
399 ///- Read the version of the configuration file and warn the user in case of emptiness or mismatch
400 uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
401 if(!confVersion)
403 sLog.outError("*****************************************************************************");
404 sLog.outError(" WARNING: mangosd.conf does not include a ConfVersion variable.");
405 sLog.outError(" Your configuration file may be out of date!");
406 sLog.outError("*****************************************************************************");
407 clock_t pause = 3000 + clock();
408 while (pause > clock())
409 ; // empty body
411 else
413 if (confVersion < _MANGOSDCONFVERSION)
415 sLog.outError("*****************************************************************************");
416 sLog.outError(" WARNING: Your mangosd.conf version indicates your conf file is out of date!");
417 sLog.outError(" Please check for updates, as your current default values may cause");
418 sLog.outError(" unexpected behavior.");
419 sLog.outError("*****************************************************************************");
420 clock_t pause = 3000 + clock();
421 while (pause > clock())
422 ; // empty body
426 ///- Read the player limit and the Message of the day from the config file
427 SetPlayerLimit( sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT), true );
428 SetMotd( sConfig.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
430 ///- Read all rates from the config file
431 rate_values[RATE_HEALTH] = sConfig.GetFloatDefault("Rate.Health", 1);
432 if(rate_values[RATE_HEALTH] < 0)
434 sLog.outError("Rate.Health (%f) must be > 0. Using 1 instead.",rate_values[RATE_HEALTH]);
435 rate_values[RATE_HEALTH] = 1;
437 rate_values[RATE_POWER_MANA] = sConfig.GetFloatDefault("Rate.Mana", 1);
438 if(rate_values[RATE_POWER_MANA] < 0)
440 sLog.outError("Rate.Mana (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_MANA]);
441 rate_values[RATE_POWER_MANA] = 1;
443 rate_values[RATE_POWER_RAGE_INCOME] = sConfig.GetFloatDefault("Rate.Rage.Income", 1);
444 rate_values[RATE_POWER_RAGE_LOSS] = sConfig.GetFloatDefault("Rate.Rage.Loss", 1);
445 if(rate_values[RATE_POWER_RAGE_LOSS] < 0)
447 sLog.outError("Rate.Rage.Loss (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_RAGE_LOSS]);
448 rate_values[RATE_POWER_RAGE_LOSS] = 1;
450 rate_values[RATE_POWER_RUNICPOWER_INCOME] = sConfig.GetFloatDefault("Rate.RunicPower.Income", 1);
451 rate_values[RATE_POWER_RUNICPOWER_LOSS] = sConfig.GetFloatDefault("Rate.RunicPower.Loss", 1);
452 if(rate_values[RATE_POWER_RUNICPOWER_LOSS] < 0)
454 sLog.outError("Rate.RunicPower.Loss (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_RUNICPOWER_LOSS]);
455 rate_values[RATE_POWER_RUNICPOWER_LOSS] = 1;
457 rate_values[RATE_POWER_FOCUS] = sConfig.GetFloatDefault("Rate.Focus", 1.0f);
458 rate_values[RATE_SKILL_DISCOVERY] = sConfig.GetFloatDefault("Rate.Skill.Discovery", 1.0f);
459 rate_values[RATE_DROP_ITEM_POOR] = sConfig.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f);
460 rate_values[RATE_DROP_ITEM_NORMAL] = sConfig.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f);
461 rate_values[RATE_DROP_ITEM_UNCOMMON] = sConfig.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f);
462 rate_values[RATE_DROP_ITEM_RARE] = sConfig.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f);
463 rate_values[RATE_DROP_ITEM_EPIC] = sConfig.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f);
464 rate_values[RATE_DROP_ITEM_LEGENDARY] = sConfig.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f);
465 rate_values[RATE_DROP_ITEM_ARTIFACT] = sConfig.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f);
466 rate_values[RATE_DROP_ITEM_REFERENCED] = sConfig.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f);
467 rate_values[RATE_DROP_MONEY] = sConfig.GetFloatDefault("Rate.Drop.Money", 1.0f);
468 rate_values[RATE_XP_KILL] = sConfig.GetFloatDefault("Rate.XP.Kill", 1.0f);
469 rate_values[RATE_XP_QUEST] = sConfig.GetFloatDefault("Rate.XP.Quest", 1.0f);
470 rate_values[RATE_XP_EXPLORE] = sConfig.GetFloatDefault("Rate.XP.Explore", 1.0f);
471 rate_values[RATE_REPUTATION_GAIN] = sConfig.GetFloatDefault("Rate.Reputation.Gain", 1.0f);
472 rate_values[RATE_CREATURE_NORMAL_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f);
473 rate_values[RATE_CREATURE_ELITE_ELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f);
474 rate_values[RATE_CREATURE_ELITE_RAREELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f);
475 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f);
476 rate_values[RATE_CREATURE_ELITE_RARE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f);
477 rate_values[RATE_CREATURE_NORMAL_HP] = sConfig.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f);
478 rate_values[RATE_CREATURE_ELITE_ELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f);
479 rate_values[RATE_CREATURE_ELITE_RAREELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f);
480 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f);
481 rate_values[RATE_CREATURE_ELITE_RARE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f);
482 rate_values[RATE_CREATURE_NORMAL_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f);
483 rate_values[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f);
484 rate_values[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f);
485 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f);
486 rate_values[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f);
487 rate_values[RATE_CREATURE_AGGRO] = sConfig.GetFloatDefault("Rate.Creature.Aggro", 1.0f);
488 rate_values[RATE_REST_INGAME] = sConfig.GetFloatDefault("Rate.Rest.InGame", 1.0f);
489 rate_values[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY] = sConfig.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f);
490 rate_values[RATE_REST_OFFLINE_IN_WILDERNESS] = sConfig.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f);
491 rate_values[RATE_DAMAGE_FALL] = sConfig.GetFloatDefault("Rate.Damage.Fall", 1.0f);
492 rate_values[RATE_AUCTION_TIME] = sConfig.GetFloatDefault("Rate.Auction.Time", 1.0f);
493 rate_values[RATE_AUCTION_DEPOSIT] = sConfig.GetFloatDefault("Rate.Auction.Deposit", 1.0f);
494 rate_values[RATE_AUCTION_CUT] = sConfig.GetFloatDefault("Rate.Auction.Cut", 1.0f);
495 rate_values[RATE_HONOR] = sConfig.GetFloatDefault("Rate.Honor",1.0f);
496 rate_values[RATE_MINING_AMOUNT] = sConfig.GetFloatDefault("Rate.Mining.Amount",1.0f);
497 rate_values[RATE_MINING_NEXT] = sConfig.GetFloatDefault("Rate.Mining.Next",1.0f);
498 rate_values[RATE_INSTANCE_RESET_TIME] = sConfig.GetFloatDefault("Rate.InstanceResetTime",1.0f);
499 rate_values[RATE_TALENT] = sConfig.GetFloatDefault("Rate.Talent",1.0f);
500 if(rate_values[RATE_TALENT] < 0.0f)
502 sLog.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_TALENT]);
503 rate_values[RATE_TALENT] = 1.0f;
505 rate_values[RATE_CORPSE_DECAY_LOOTED] = sConfig.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f);
507 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = sConfig.GetFloatDefault("TargetPosRecalculateRange",1.5f);
508 if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] < CONTACT_DISTANCE)
510 sLog.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],CONTACT_DISTANCE,CONTACT_DISTANCE);
511 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = CONTACT_DISTANCE;
513 else if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] > ATTACK_DISTANCE)
515 sLog.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",
516 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],ATTACK_DISTANCE,ATTACK_DISTANCE);
517 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = ATTACK_DISTANCE;
520 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = sConfig.GetFloatDefault("DurabilityLossChance.Damage",0.5f);
521 if(rate_values[RATE_DURABILITY_LOSS_DAMAGE] < 0.0f)
523 sLog.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_DAMAGE]);
524 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = 0.0f;
526 rate_values[RATE_DURABILITY_LOSS_ABSORB] = sConfig.GetFloatDefault("DurabilityLossChance.Absorb",0.5f);
527 if(rate_values[RATE_DURABILITY_LOSS_ABSORB] < 0.0f)
529 sLog.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_ABSORB]);
530 rate_values[RATE_DURABILITY_LOSS_ABSORB] = 0.0f;
532 rate_values[RATE_DURABILITY_LOSS_PARRY] = sConfig.GetFloatDefault("DurabilityLossChance.Parry",0.05f);
533 if(rate_values[RATE_DURABILITY_LOSS_PARRY] < 0.0f)
535 sLog.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_PARRY]);
536 rate_values[RATE_DURABILITY_LOSS_PARRY] = 0.0f;
538 rate_values[RATE_DURABILITY_LOSS_BLOCK] = sConfig.GetFloatDefault("DurabilityLossChance.Block",0.05f);
539 if(rate_values[RATE_DURABILITY_LOSS_BLOCK] < 0.0f)
541 sLog.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_BLOCK]);
542 rate_values[RATE_DURABILITY_LOSS_BLOCK] = 0.0f;
545 ///- Read other configuration items from the config file
547 m_configs[CONFIG_COMPRESSION] = sConfig.GetIntDefault("Compression", 1);
548 if(m_configs[CONFIG_COMPRESSION] < 1 || m_configs[CONFIG_COMPRESSION] > 9)
550 sLog.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs[CONFIG_COMPRESSION]);
551 m_configs[CONFIG_COMPRESSION] = 1;
553 m_configs[CONFIG_ADDON_CHANNEL] = sConfig.GetBoolDefault("AddonChannel", true);
554 m_configs[CONFIG_GRID_UNLOAD] = sConfig.GetBoolDefault("GridUnload", true);
555 m_configs[CONFIG_INTERVAL_SAVE] = sConfig.GetIntDefault("PlayerSaveInterval", 15 * MINUTE * IN_MILISECONDS);
557 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = sConfig.GetIntDefault("GridCleanUpDelay", 5 * MINUTE * IN_MILISECONDS);
558 if(m_configs[CONFIG_INTERVAL_GRIDCLEAN] < MIN_GRID_DELAY)
560 sLog.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_GRIDCLEAN],MIN_GRID_DELAY);
561 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = MIN_GRID_DELAY;
563 if(reload)
564 MapManager::Instance().SetGridCleanUpDelay(m_configs[CONFIG_INTERVAL_GRIDCLEAN]);
566 m_configs[CONFIG_INTERVAL_MAPUPDATE] = sConfig.GetIntDefault("MapUpdateInterval", 100);
567 if(m_configs[CONFIG_INTERVAL_MAPUPDATE] < MIN_MAP_UPDATE_DELAY)
569 sLog.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_MAPUPDATE],MIN_MAP_UPDATE_DELAY);
570 m_configs[CONFIG_INTERVAL_MAPUPDATE] = MIN_MAP_UPDATE_DELAY;
572 if(reload)
573 MapManager::Instance().SetMapUpdateInterval(m_configs[CONFIG_INTERVAL_MAPUPDATE]);
575 m_configs[CONFIG_INTERVAL_CHANGEWEATHER] = sConfig.GetIntDefault("ChangeWeatherInterval", 10 * MINUTE * IN_MILISECONDS);
577 if(reload)
579 uint32 val = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
580 if(val!=m_configs[CONFIG_PORT_WORLD])
581 sLog.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_PORT_WORLD]);
583 else
584 m_configs[CONFIG_PORT_WORLD] = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
586 if(reload)
588 uint32 val = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
589 if(val!=m_configs[CONFIG_SOCKET_SELECTTIME])
590 sLog.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_SOCKET_SELECTTIME]);
592 else
593 m_configs[CONFIG_SOCKET_SELECTTIME] = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
595 m_configs[CONFIG_GROUP_XP_DISTANCE] = sConfig.GetIntDefault("MaxGroupXPDistance", 74);
596 /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
597 m_configs[CONFIG_SIGHT_MONSTER] = sConfig.GetIntDefault("MonsterSight", 50);
598 m_configs[CONFIG_SIGHT_GUARDER] = sConfig.GetIntDefault("GuarderSight", 50);
600 if(reload)
602 uint32 val = sConfig.GetIntDefault("GameType", 0);
603 if(val!=m_configs[CONFIG_GAME_TYPE])
604 sLog.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_GAME_TYPE]);
606 else
607 m_configs[CONFIG_GAME_TYPE] = sConfig.GetIntDefault("GameType", 0);
609 if(reload)
611 uint32 val = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
612 if(val!=m_configs[CONFIG_REALM_ZONE])
613 sLog.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_REALM_ZONE]);
615 else
616 m_configs[CONFIG_REALM_ZONE] = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
618 m_configs[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS] = sConfig.GetBoolDefault("AllowTwoSide.Accounts", false);
619 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
620 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
621 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
622 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
623 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
624 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
625 m_configs[CONFIG_ALLOW_TWO_SIDE_WHO_LIST] = sConfig.GetBoolDefault("AllowTwoSide.WhoList", false);
626 m_configs[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND] = sConfig.GetBoolDefault("AllowTwoSide.AddFriend", false);
627 m_configs[CONFIG_STRICT_PLAYER_NAMES] = sConfig.GetIntDefault ("StrictPlayerNames", 0);
628 m_configs[CONFIG_STRICT_CHARTER_NAMES] = sConfig.GetIntDefault ("StrictCharterNames", 0);
629 m_configs[CONFIG_STRICT_PET_NAMES] = sConfig.GetIntDefault ("StrictPetNames", 0);
631 m_configs[CONFIG_CHARACTERS_CREATING_DISABLED] = sConfig.GetIntDefault ("CharactersCreatingDisabled", 0);
633 m_configs[CONFIG_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("CharactersPerRealm", 10);
634 if(m_configs[CONFIG_CHARACTERS_PER_REALM] < 1 || m_configs[CONFIG_CHARACTERS_PER_REALM] > 10)
636 sLog.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs[CONFIG_CHARACTERS_PER_REALM]);
637 m_configs[CONFIG_CHARACTERS_PER_REALM] = 10;
640 // must be after CONFIG_CHARACTERS_PER_REALM
641 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = sConfig.GetIntDefault("CharactersPerAccount", 50);
642 if(m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] < m_configs[CONFIG_CHARACTERS_PER_REALM])
644 sLog.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs[CONFIG_CHARACTERS_PER_ACCOUNT],m_configs[CONFIG_CHARACTERS_PER_REALM]);
645 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = m_configs[CONFIG_CHARACTERS_PER_REALM];
648 m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("HeroicCharactersPerRealm", 1);
649 if(int32(m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM]) < 0 || m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] > 10)
651 sLog.outError("HeroicCharactersPerRealm (%i) must be in range 0..10. Set to 1.",m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM]);
652 m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] = 1;
655 m_configs[CONFIG_MIN_LEVEL_FOR_HEROIC_CHARACTER_CREATING] = sConfig.GetIntDefault("MinLevelForHeroicCharacterCreating", 55);
657 m_configs[CONFIG_SKIP_CINEMATICS] = sConfig.GetIntDefault("SkipCinematics", 0);
658 if(int32(m_configs[CONFIG_SKIP_CINEMATICS]) < 0 || m_configs[CONFIG_SKIP_CINEMATICS] > 2)
660 sLog.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs[CONFIG_SKIP_CINEMATICS]);
661 m_configs[CONFIG_SKIP_CINEMATICS] = 0;
664 if(reload)
666 uint32 val = sConfig.GetIntDefault("MaxPlayerLevel", 80);
667 if(val!=m_configs[CONFIG_MAX_PLAYER_LEVEL])
668 sLog.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
670 else
671 m_configs[CONFIG_MAX_PLAYER_LEVEL] = sConfig.GetIntDefault("MaxPlayerLevel", 80);
673 if(m_configs[CONFIG_MAX_PLAYER_LEVEL] > MAX_LEVEL)
675 sLog.outError("MaxPlayerLevel (%i) must be in range 1..%u. Set to %u.",m_configs[CONFIG_MAX_PLAYER_LEVEL],MAX_LEVEL,MAX_LEVEL);
676 m_configs[CONFIG_MAX_PLAYER_LEVEL] = MAX_LEVEL;
679 m_configs[CONFIG_START_PLAYER_LEVEL] = sConfig.GetIntDefault("StartPlayerLevel", 1);
680 if(m_configs[CONFIG_START_PLAYER_LEVEL] < 1)
682 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]);
683 m_configs[CONFIG_START_PLAYER_LEVEL] = 1;
685 else if(m_configs[CONFIG_START_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
687 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]);
688 m_configs[CONFIG_START_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
691 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = sConfig.GetIntDefault("StartHeroicPlayerLevel", 55);
692 if(m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] < 1)
694 sLog.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to 55.",
695 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
696 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = 55;
698 else if(m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
700 sLog.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to %u.",
701 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
702 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
705 m_configs[CONFIG_START_PLAYER_MONEY] = sConfig.GetIntDefault("StartPlayerMoney", 0);
706 if(int32(m_configs[CONFIG_START_PLAYER_MONEY]) < 0)
708 sLog.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",m_configs[CONFIG_START_PLAYER_MONEY],MAX_MONEY_AMOUNT,0);
709 m_configs[CONFIG_START_PLAYER_MONEY] = 0;
711 else if(m_configs[CONFIG_START_PLAYER_MONEY] > MAX_MONEY_AMOUNT)
713 sLog.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",
714 m_configs[CONFIG_START_PLAYER_MONEY],MAX_MONEY_AMOUNT,MAX_MONEY_AMOUNT);
715 m_configs[CONFIG_START_PLAYER_MONEY] = MAX_MONEY_AMOUNT;
718 m_configs[CONFIG_MAX_HONOR_POINTS] = sConfig.GetIntDefault("MaxHonorPoints", 75000);
719 if(int32(m_configs[CONFIG_MAX_HONOR_POINTS]) < 0)
721 sLog.outError("MaxHonorPoints (%i) can't be negative. Set to 0.",m_configs[CONFIG_MAX_HONOR_POINTS]);
722 m_configs[CONFIG_MAX_HONOR_POINTS] = 0;
725 m_configs[CONFIG_START_HONOR_POINTS] = sConfig.GetIntDefault("StartHonorPoints", 0);
726 if(int32(m_configs[CONFIG_START_HONOR_POINTS]) < 0)
728 sLog.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
729 m_configs[CONFIG_START_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS],0);
730 m_configs[CONFIG_MAX_HONOR_POINTS] = 0;
732 else if(m_configs[CONFIG_START_HONOR_POINTS] > m_configs[CONFIG_MAX_HONOR_POINTS])
734 sLog.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
735 m_configs[CONFIG_START_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS]);
736 m_configs[CONFIG_START_HONOR_POINTS] = m_configs[CONFIG_MAX_HONOR_POINTS];
739 m_configs[CONFIG_MAX_ARENA_POINTS] = sConfig.GetIntDefault("MaxArenaPoints", 5000);
740 if(int32(m_configs[CONFIG_MAX_ARENA_POINTS]) < 0)
742 sLog.outError("MaxArenaPoints (%i) can't be negative. Set to 0.",m_configs[CONFIG_MAX_ARENA_POINTS]);
743 m_configs[CONFIG_MAX_ARENA_POINTS] = 0;
746 m_configs[CONFIG_START_ARENA_POINTS] = sConfig.GetIntDefault("StartArenaPoints", 0);
747 if(int32(m_configs[CONFIG_START_ARENA_POINTS]) < 0)
749 sLog.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
750 m_configs[CONFIG_START_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS],0);
751 m_configs[CONFIG_MAX_ARENA_POINTS] = 0;
753 else if(m_configs[CONFIG_START_ARENA_POINTS] > m_configs[CONFIG_MAX_ARENA_POINTS])
755 sLog.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
756 m_configs[CONFIG_START_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS]);
757 m_configs[CONFIG_START_ARENA_POINTS] = m_configs[CONFIG_MAX_ARENA_POINTS];
760 m_configs[CONFIG_ALL_TAXI_PATHS] = sConfig.GetBoolDefault("AllFlightPaths", false);
762 m_configs[CONFIG_INSTANCE_IGNORE_LEVEL] = sConfig.GetBoolDefault("Instance.IgnoreLevel", false);
763 m_configs[CONFIG_INSTANCE_IGNORE_RAID] = sConfig.GetBoolDefault("Instance.IgnoreRaid", false);
765 m_configs[CONFIG_CAST_UNSTUCK] = sConfig.GetBoolDefault("CastUnstuck", true);
766 m_configs[CONFIG_INSTANCE_RESET_TIME_HOUR] = sConfig.GetIntDefault("Instance.ResetTimeHour", 4);
767 m_configs[CONFIG_INSTANCE_UNLOAD_DELAY] = sConfig.GetIntDefault("Instance.UnloadDelay", 30 * MINUTE * IN_MILISECONDS);
769 m_configs[CONFIG_MAX_PRIMARY_TRADE_SKILL] = sConfig.GetIntDefault("MaxPrimaryTradeSkill", 2);
770 m_configs[CONFIG_MIN_PETITION_SIGNS] = sConfig.GetIntDefault("MinPetitionSigns", 9);
771 if(m_configs[CONFIG_MIN_PETITION_SIGNS] > 9)
773 sLog.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.", m_configs[CONFIG_MIN_PETITION_SIGNS]);
774 m_configs[CONFIG_MIN_PETITION_SIGNS] = 9;
777 m_configs[CONFIG_GM_LOGIN_STATE] = sConfig.GetIntDefault("GM.LoginState", 2);
778 m_configs[CONFIG_GM_VISIBLE_STATE] = sConfig.GetIntDefault("GM.Visible", 2);
779 m_configs[CONFIG_GM_ACCEPT_TICKETS] = sConfig.GetIntDefault("GM.AcceptTickets", 2);
780 m_configs[CONFIG_GM_CHAT] = sConfig.GetIntDefault("GM.Chat", 2);
781 m_configs[CONFIG_GM_WISPERING_TO] = sConfig.GetIntDefault("GM.WhisperingTo", 2);
783 m_configs[CONFIG_GM_IN_GM_LIST] = sConfig.GetBoolDefault("GM.InGMList", false);
784 m_configs[CONFIG_GM_IN_WHO_LIST] = sConfig.GetBoolDefault("GM.InWhoList", false);
785 m_configs[CONFIG_GM_LOG_TRADE] = sConfig.GetBoolDefault("GM.LogTrade", false);
787 m_configs[CONFIG_START_GM_LEVEL] = sConfig.GetIntDefault("GM.StartLevel", 1);
788 if(m_configs[CONFIG_START_GM_LEVEL] < m_configs[CONFIG_START_PLAYER_LEVEL])
790 sLog.outError("GM.StartLevel (%i) must be in range StartPlayerLevel(%u)..%u. Set to %u.",
791 m_configs[CONFIG_START_GM_LEVEL],m_configs[CONFIG_START_PLAYER_LEVEL], MAX_LEVEL, m_configs[CONFIG_START_PLAYER_LEVEL]);
792 m_configs[CONFIG_START_GM_LEVEL] = m_configs[CONFIG_START_PLAYER_LEVEL];
794 else if(m_configs[CONFIG_START_GM_LEVEL] > MAX_LEVEL)
796 sLog.outError("GM.StartLevel (%i) must be in range 1..%u. Set to %u.", m_configs[CONFIG_START_GM_LEVEL], MAX_LEVEL, MAX_LEVEL);
797 m_configs[CONFIG_START_GM_LEVEL] = MAX_LEVEL;
799 m_configs[CONFIG_GM_LOWER_SECURITY] = sConfig.GetBoolDefault("GM.LowerSecurity", false);
800 m_configs[CONFIG_GM_ALLOW_ACHIEVEMENT_GAINS] = sConfig.GetBoolDefault("GM.AllowAchievementGain", true);
802 m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
804 m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
806 m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
807 if(int32(m_configs[CONFIG_UPTIME_UPDATE])<=0)
809 sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
810 m_configs[CONFIG_UPTIME_UPDATE] = 10;
812 if(reload)
814 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*IN_MILISECONDS);
815 m_timers[WUPDATE_UPTIME].Reset();
818 m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
819 m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
820 m_configs[CONFIG_SKILL_CHANCE_GREEN] = sConfig.GetIntDefault("SkillChance.Green",25);
821 m_configs[CONFIG_SKILL_CHANCE_GREY] = sConfig.GetIntDefault("SkillChance.Grey",0);
823 m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS] = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
824 m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS] = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
826 m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
827 m_configs[CONFIG_SKILL_MILLING] = sConfig.GetBoolDefault("SkillChance.Milling",false);
829 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = sConfig.GetIntDefault("SkillGain.Crafting", 1);
830 if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
832 sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
833 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
836 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = sConfig.GetIntDefault("SkillGain.Defense", 1);
837 if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
839 sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
840 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
843 m_configs[CONFIG_SKILL_GAIN_GATHERING] = sConfig.GetIntDefault("SkillGain.Gathering", 1);
844 if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
846 sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
847 m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
850 m_configs[CONFIG_SKILL_GAIN_WEAPON] = sConfig.GetIntDefault("SkillGain.Weapon", 1);
851 if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
853 sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
854 m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
857 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
858 if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
860 sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
861 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
864 m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
865 m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
867 m_configs[CONFIG_DISABLE_BREATHING] = sConfig.GetIntDefault("DisableWaterBreath", SEC_CONSOLE);
869 m_configs[CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL] = sConfig.GetBoolDefault("AlwaysMaxSkillForLevel", false);
871 if(reload)
873 uint32 val = sConfig.GetIntDefault("Expansion",1);
874 if(val!=m_configs[CONFIG_EXPANSION])
875 sLog.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
877 else
878 m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",1);
880 m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
881 m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
882 m_configs[CONFIG_CHATFLOOD_MUTE_TIME] = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
884 m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
886 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistanceRadius",10);
887 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY] = sConfig.GetIntDefault("CreatureFamilyAssistanceDelay",1500);
889 m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
891 // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level MAX_LEVEL(100)
892 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff", 4);
893 if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > MAX_LEVEL)
894 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = MAX_LEVEL;
895 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff", 7);
896 if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > MAX_LEVEL)
897 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = MAX_LEVEL;
899 m_configs[CONFIG_DETECT_POS_COLLISION] = sConfig.GetBoolDefault("DetectPosCollision", true);
901 m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
902 m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
904 m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
905 m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
907 m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
908 m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
909 m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
910 m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
911 m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
913 m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault ("Death.SicknessLevel", 11);
914 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
915 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
916 m_configs[CONFIG_DEATH_BONES_WORLD] = sConfig.GetBoolDefault("Death.Bones.World", true);
917 m_configs[CONFIG_DEATH_BONES_BG_OR_ARENA] = sConfig.GetBoolDefault("Death.Bones.BattlegroundOrArena", true);
919 m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
921 // always use declined names in the russian client
922 m_configs[CONFIG_DECLINED_NAMES_USED] =
923 (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
925 m_configs[CONFIG_LISTEN_RANGE_SAY] = sConfig.GetIntDefault("ListenRange.Say", 25);
926 m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
927 m_configs[CONFIG_LISTEN_RANGE_YELL] = sConfig.GetIntDefault("ListenRange.Yell", 300);
929 m_configs[CONFIG_BATTLEGROUND_CAST_DESERTER] = sConfig.GetBoolDefault("Battleground.CastDeserter", true);
930 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.Enable", false);
931 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false);
932 m_configs[CONFIG_BATTLEGROUND_INVITATION_TYPE] = sConfig.GetIntDefault ("Battleground.InvitationType", 0);
933 m_configs[CONFIG_BATTLEGROUND_PREMATURE_FINISH_TIMER] = sConfig.GetIntDefault ("BattleGround.PrematureFinishTimer", 5 * MINUTE * IN_MILISECONDS);
934 m_configs[CONFIG_BATTLEGROUND_PREMADE_GROUP_WAIT_FOR_MATCH] = sConfig.GetIntDefault ("BattleGround.PremadeGroupWaitForMatch", 30 * MINUTE * IN_MILISECONDS);
935 m_configs[CONFIG_ARENA_MAX_RATING_DIFFERENCE] = sConfig.GetIntDefault ("Arena.MaxRatingDifference", 150);
936 m_configs[CONFIG_ARENA_RATING_DISCARD_TIMER] = sConfig.GetIntDefault ("Arena.RatingDiscardTimer", 10 * MINUTE * IN_MILISECONDS);
937 m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_POINTS] = sConfig.GetBoolDefault("Arena.AutoDistributePoints", false);
938 m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS] = sConfig.GetIntDefault ("Arena.AutoDistributeInterval", 7);
939 m_configs[CONFIG_ARENA_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Arena.QueueAnnouncer.Enable", false);
940 m_configs[CONFIG_ARENA_SEASON_ID] = sConfig.GetIntDefault ("Arena.ArenaSeason.ID", 1);
941 m_configs[CONFIG_ARENA_SEASON_IN_PROGRESS] = sConfig.GetBoolDefault("Arena.ArenaSeason.InProgress", true);
943 m_configs[CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET] = sConfig.GetBoolDefault("OffhandCheckAtTalentsReset", false);
945 m_configs[CONFIG_INSTANT_LOGOUT] = sConfig.GetIntDefault("InstantLogout", SEC_MODERATOR);
947 m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
948 if(m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
950 sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
951 m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
953 m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
954 if(m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
956 sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
957 m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
960 m_MaxVisibleDistanceForCreature = sConfig.GetFloatDefault("Visibility.Distance.Creature", DEFAULT_VISIBILITY_DISTANCE);
961 if(m_MaxVisibleDistanceForCreature < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
963 sLog.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
964 m_MaxVisibleDistanceForCreature = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
966 else if(m_MaxVisibleDistanceForCreature + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
968 sLog.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
969 m_MaxVisibleDistanceForCreature = MAX_VISIBILITY_DISTANCE-m_VisibleUnitGreyDistance;
971 m_MaxVisibleDistanceForPlayer = sConfig.GetFloatDefault("Visibility.Distance.Player", DEFAULT_VISIBILITY_DISTANCE);
972 if(m_MaxVisibleDistanceForPlayer < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
974 sLog.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
975 m_MaxVisibleDistanceForPlayer = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
977 else if(m_MaxVisibleDistanceForPlayer + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
979 sLog.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
980 m_MaxVisibleDistanceForPlayer = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
982 m_MaxVisibleDistanceForObject = sConfig.GetFloatDefault("Visibility.Distance.Gameobject", DEFAULT_VISIBILITY_DISTANCE);
983 if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
985 sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
986 m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
988 else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
990 sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
991 m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
993 m_MaxVisibleDistanceInFlight = sConfig.GetFloatDefault("Visibility.Distance.InFlight", DEFAULT_VISIBILITY_DISTANCE);
994 if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
996 sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
997 m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
1000 ///- Read the "Data" directory from the config file
1001 std::string dataPath = sConfig.GetStringDefault("DataDir","./");
1002 if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
1003 dataPath.append("/");
1005 if(reload)
1007 if(dataPath!=m_dataPath)
1008 sLog.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath.c_str());
1010 else
1012 m_dataPath = dataPath;
1013 sLog.outString("Using DataDir %s",m_dataPath.c_str());
1016 bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
1017 bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
1018 std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
1019 std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
1020 VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
1021 VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
1022 VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
1023 VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
1024 sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
1025 sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
1026 sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
1029 /// Initialize the World
1030 void World::SetInitialWorldSettings()
1032 ///- Initialize the random number generator
1033 srand((unsigned int)time(NULL));
1035 ///- Initialize config settings
1036 LoadConfigSettings();
1038 ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
1039 objmgr.SetHighestGuids();
1041 ///- Check the existence of the map files for all races' startup areas.
1042 if( !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
1043 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
1044 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
1045 ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
1046 ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
1047 ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
1048 ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
1049 ||m_configs[CONFIG_EXPANSION] && (
1050 !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
1052 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());
1053 exit(1);
1056 ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
1057 sLog.outString();
1058 sLog.outString("Loading MaNGOS strings...");
1059 if (!objmgr.LoadMangosStrings())
1060 exit(1); // Error message displayed in function already
1062 ///- Update the realm entry in the database with the realm type from the config file
1063 //No SQL injection as values are treated as integers
1065 // not send custom type REALM_FFA_PVP to realm list
1066 uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
1067 uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
1068 loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
1070 ///- Remove the bones after a restart
1071 CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
1073 ///- Load the DBC files
1074 sLog.outString("Initialize data stores...");
1075 LoadDBCStores(m_dataPath);
1076 DetectDBCLang();
1078 sLog.outString( "Loading Script Names...");
1079 objmgr.LoadScriptNames();
1081 sLog.outString( "Loading InstanceTemplate..." );
1082 objmgr.LoadInstanceTemplate();
1084 sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
1085 spellmgr.LoadSkillLineAbilityMap();
1087 ///- Clean up and pack instances
1088 sLog.outString( "Cleaning up instances..." );
1089 sInstanceSaveManager.CleanupInstances(); // must be called before `creature_respawn`/`gameobject_respawn` tables
1091 sLog.outString( "Packing instances..." );
1092 sInstanceSaveManager.PackInstances();
1094 sLog.outString();
1095 sLog.outString( "Loading Localization strings..." );
1096 objmgr.LoadCreatureLocales();
1097 objmgr.LoadGameObjectLocales();
1098 objmgr.LoadItemLocales();
1099 objmgr.LoadQuestLocales();
1100 objmgr.LoadNpcTextLocales();
1101 objmgr.LoadPageTextLocales();
1102 objmgr.LoadNpcOptionLocales();
1103 objmgr.LoadPointOfInterestLocales();
1104 objmgr.SetDBCLocaleIndex(GetDefaultDbcLocale()); // Get once for all the locale index of DBC language (console/broadcasts)
1105 sLog.outString( ">>> Localization strings loaded" );
1106 sLog.outString();
1108 sLog.outString( "Loading Page Texts..." );
1109 objmgr.LoadPageTexts();
1111 sLog.outString( "Loading Game Object Templates..." ); // must be after LoadPageTexts
1112 objmgr.LoadGameobjectInfo();
1114 sLog.outString( "Loading Spell Chain Data..." );
1115 spellmgr.LoadSpellChains();
1117 sLog.outString( "Loading Spell Elixir types..." );
1118 spellmgr.LoadSpellElixirs();
1120 sLog.outString( "Loading Spell Learn Skills..." );
1121 spellmgr.LoadSpellLearnSkills(); // must be after LoadSpellChains
1123 sLog.outString( "Loading Spell Learn Spells..." );
1124 spellmgr.LoadSpellLearnSpells();
1126 sLog.outString( "Loading Spell Proc Event conditions..." );
1127 spellmgr.LoadSpellProcEvents();
1129 sLog.outString( "Loading Spell Bonus Data..." );
1130 spellmgr.LoadSpellBonusess();
1132 sLog.outString( "Loading Aggro Spells Definitions...");
1133 spellmgr.LoadSpellThreats();
1135 sLog.outString( "Loading NPC Texts..." );
1136 objmgr.LoadGossipText();
1138 sLog.outString( "Loading Item Random Enchantments Table..." );
1139 LoadRandomEnchantmentsTable();
1141 sLog.outString( "Loading Items..." ); // must be after LoadRandomEnchantmentsTable and LoadPageTexts
1142 objmgr.LoadItemPrototypes();
1144 sLog.outString( "Loading Item Texts..." );
1145 objmgr.LoadItemTexts();
1147 sLog.outString( "Loading Creature Model Based Info Data..." );
1148 objmgr.LoadCreatureModelInfo();
1150 sLog.outString( "Loading Equipment templates...");
1151 objmgr.LoadEquipmentTemplates();
1153 sLog.outString( "Loading Creature templates..." );
1154 objmgr.LoadCreatureTemplates();
1156 sLog.outString( "Loading SpellsScriptTarget...");
1157 spellmgr.LoadSpellScriptTarget(); // must be after LoadCreatureTemplates and LoadGameobjectInfo
1159 sLog.outString( "Loading Creature Reputation OnKill Data..." );
1160 objmgr.LoadReputationOnKill();
1162 sLog.outString( "Loading Points Of Interest Data..." );
1163 objmgr.LoadPointsOfInterest();
1165 sLog.outString( "Loading Pet Create Spells..." );
1166 objmgr.LoadPetCreateSpells();
1168 sLog.outString( "Loading Creature Data..." );
1169 objmgr.LoadCreatures();
1171 sLog.outString( "Loading Creature Addon Data..." );
1172 sLog.outString();
1173 objmgr.LoadCreatureAddons(); // must be after LoadCreatureTemplates() and LoadCreatures()
1174 sLog.outString( ">>> Creature Addon Data loaded" );
1175 sLog.outString();
1177 sLog.outString( "Loading Creature Respawn Data..." ); // must be after PackInstances()
1178 objmgr.LoadCreatureRespawnTimes();
1180 sLog.outString( "Loading Gameobject Data..." );
1181 objmgr.LoadGameobjects();
1183 sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1184 objmgr.LoadGameobjectRespawnTimes();
1186 sLog.outString( "Loading Objects Pooling Data...");
1187 poolhandler.LoadFromDB();
1189 sLog.outString( "Loading Game Event Data...");
1190 sLog.outString();
1191 gameeventmgr.LoadFromDB();
1192 sLog.outString( ">>> Game Event Data loaded" );
1193 sLog.outString();
1195 sLog.outString( "Loading Weather Data..." );
1196 objmgr.LoadWeatherZoneChances();
1198 sLog.outString( "Loading Quests..." );
1199 objmgr.LoadQuests(); // must be loaded after DBCs, creature_template, item_template, gameobject tables
1201 sLog.outString( "Loading Quests Relations..." );
1202 sLog.outString();
1203 objmgr.LoadQuestRelations(); // must be after quest load
1204 sLog.outString( ">>> Quests Relations loaded" );
1205 sLog.outString();
1207 sLog.outString( "Loading SpellArea Data..." ); // must be after quest load
1208 spellmgr.LoadSpellAreas();
1210 sLog.outString( "Loading AreaTrigger definitions..." );
1211 objmgr.LoadAreaTriggerTeleports(); // must be after item template load
1213 sLog.outString( "Loading Quest Area Triggers..." );
1214 objmgr.LoadQuestAreaTriggers(); // must be after LoadQuests
1216 sLog.outString( "Loading Tavern Area Triggers..." );
1217 objmgr.LoadTavernAreaTriggers();
1219 sLog.outString( "Loading AreaTrigger script names..." );
1220 objmgr.LoadAreaTriggerScripts();
1222 sLog.outString( "Loading Graveyard-zone links...");
1223 objmgr.LoadGraveyardZones();
1225 sLog.outString( "Loading Spell target coordinates..." );
1226 spellmgr.LoadSpellTargetPositions();
1228 sLog.outString( "Loading SpellAffect definitions..." );
1229 spellmgr.LoadSpellAffects();
1231 sLog.outString( "Loading spell pet auras..." );
1232 spellmgr.LoadSpellPetAuras();
1234 sLog.outString( "Loading pet levelup spells..." );
1235 spellmgr.LoadPetLevelupSpellMap();
1237 sLog.outString( "Loading Player Create Info & Level Stats..." );
1238 sLog.outString();
1239 objmgr.LoadPlayerInfo();
1240 sLog.outString( ">>> Player Create Info & Level Stats loaded" );
1241 sLog.outString();
1243 sLog.outString( "Loading Exploration BaseXP Data..." );
1244 objmgr.LoadExplorationBaseXP();
1246 sLog.outString( "Loading Pet Name Parts..." );
1247 objmgr.LoadPetNames();
1249 sLog.outString( "Loading the max pet number..." );
1250 objmgr.LoadPetNumber();
1252 sLog.outString( "Loading pet level stats..." );
1253 objmgr.LoadPetLevelInfo();
1255 sLog.outString( "Loading Player Corpses..." );
1256 objmgr.LoadCorpses();
1258 sLog.outString( "Loading Loot Tables..." );
1259 sLog.outString();
1260 LoadLootTables();
1261 sLog.outString( ">>> Loot Tables loaded" );
1262 sLog.outString();
1264 sLog.outString( "Loading Skill Discovery Table..." );
1265 LoadSkillDiscoveryTable();
1267 sLog.outString( "Loading Skill Extra Item Table..." );
1268 LoadSkillExtraItemTable();
1270 sLog.outString( "Loading Skill Fishing base level requirements..." );
1271 objmgr.LoadFishingBaseSkillLevel();
1273 sLog.outString( "Loading Achievements..." );
1274 sLog.outString();
1275 achievementmgr.LoadAchievementCriteriaList();
1276 achievementmgr.LoadRewards();
1277 achievementmgr.LoadRewardLocales();
1278 achievementmgr.LoadCompletedAchievements();
1279 sLog.outString( ">>> Achievements loaded" );
1280 sLog.outString();
1282 ///- Load dynamic data tables from the database
1283 sLog.outString( "Loading Auctions..." );
1284 sLog.outString();
1285 auctionmgr.LoadAuctionItems();
1286 auctionmgr.LoadAuctions();
1287 sLog.outString( ">>> Auctions loaded" );
1288 sLog.outString();
1290 sLog.outString( "Loading Guilds..." );
1291 objmgr.LoadGuilds();
1293 sLog.outString( "Loading ArenaTeams..." );
1294 objmgr.LoadArenaTeams();
1296 sLog.outString( "Loading Groups..." );
1297 objmgr.LoadGroups();
1299 sLog.outString( "Loading ReservedNames..." );
1300 objmgr.LoadReservedPlayersNames();
1302 sLog.outString( "Loading GameObjects for quests..." );
1303 objmgr.LoadGameObjectForQuests();
1305 sLog.outString( "Loading BattleMasters..." );
1306 sBattleGroundMgr.LoadBattleMastersEntry();
1308 sLog.outString( "Loading GameTeleports..." );
1309 objmgr.LoadGameTele();
1311 sLog.outString( "Loading Npc Text Id..." );
1312 objmgr.LoadNpcTextId(); // must be after load Creature and NpcText
1314 sLog.outString( "Loading Npc Options..." );
1315 objmgr.LoadNpcOptions();
1317 sLog.outString( "Loading Vendors..." );
1318 objmgr.LoadVendors(); // must be after load CreatureTemplate and ItemTemplate
1320 sLog.outString( "Loading Trainers..." );
1321 objmgr.LoadTrainerSpell(); // must be after load CreatureTemplate
1323 sLog.outString( "Loading Waypoints..." );
1324 sLog.outString();
1325 WaypointMgr.Load();
1327 sLog.outString( "Loading GM tickets...");
1328 ticketmgr.LoadGMTickets();
1330 ///- Handle outdated emails (delete/return)
1331 sLog.outString( "Returning old mails..." );
1332 objmgr.ReturnOrDeleteOldMails(false);
1334 ///- Load and initialize scripts
1335 sLog.outString( "Loading Scripts..." );
1336 sLog.outString();
1337 objmgr.LoadQuestStartScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1338 objmgr.LoadQuestEndScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1339 objmgr.LoadSpellScripts(); // must be after load Creature/Gameobject(Template/Data)
1340 objmgr.LoadGameObjectScripts(); // must be after load Creature/Gameobject(Template/Data)
1341 objmgr.LoadEventScripts(); // must be after load Creature/Gameobject(Template/Data)
1342 sLog.outString( ">>> Scripts loaded" );
1343 sLog.outString();
1345 sLog.outString( "Loading Scripts text locales..." ); // must be after Load*Scripts calls
1346 objmgr.LoadDbScriptStrings();
1348 sLog.outString( "Initializing Scripts..." );
1349 if(!LoadScriptingModule())
1350 exit(1);
1352 ///- Initialize game time and timers
1353 sLog.outString( "DEBUG:: Initialize game time and timers" );
1354 m_gameTime = time(NULL);
1355 m_startTime=m_gameTime;
1357 tm local;
1358 time_t curr;
1359 time(&curr);
1360 local=*(localtime(&curr)); // dereference and assign
1361 char isoDate[128];
1362 sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1363 local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1365 WorldDatabase.PExecute("INSERT INTO uptime (startstring, starttime, uptime) VALUES('%s', " I64FMTD ", 0)",
1366 isoDate, uint64(m_startTime));
1368 m_timers[WUPDATE_OBJECTS].SetInterval(0);
1369 m_timers[WUPDATE_SESSIONS].SetInterval(0);
1370 m_timers[WUPDATE_WEATHERS].SetInterval(1*IN_MILISECONDS);
1371 m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*IN_MILISECONDS);
1372 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*IN_MILISECONDS);
1373 //Update "uptime" table based on configuration entry in minutes.
1374 m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*IN_MILISECONDS);
1375 //erase corpses every 20 minutes
1377 //to set mailtimer to return mails every day between 4 and 5 am
1378 //mailtimer is increased when updating auctions
1379 //one second is 1000 -(tested on win system)
1380 mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * IN_MILISECONDS) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1381 //1440
1382 mail_timer_expires = ( (DAY * IN_MILISECONDS) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1383 sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1385 ///- Initilize static helper structures
1386 AIRegistry::Initialize();
1387 WaypointMovementGenerator<Creature>::Initialize();
1388 Player::InitVisibleBits();
1390 ///- Initialize MapManager
1391 sLog.outString( "Starting Map System" );
1392 MapManager::Instance().Initialize();
1394 ///- Initialize Battlegrounds
1395 sLog.outString( "Starting BattleGround System" );
1396 sBattleGroundMgr.CreateInitialBattleGrounds();
1397 sBattleGroundMgr.InitAutomaticArenaPointDistribution();
1399 //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1400 sLog.outString( "Loading Transports..." );
1401 MapManager::Instance().LoadTransports();
1403 sLog.outString("Deleting expired bans..." );
1404 loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1406 sLog.outString("Calculate next daily quest reset time..." );
1407 InitDailyQuestResetTime();
1409 sLog.outString("Starting objects Pooling system..." );
1410 poolhandler.Initialize();
1412 sLog.outString("Starting Game Event system..." );
1413 uint32 nextGameEvent = gameeventmgr.Initialize();
1414 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent); //depend on next event
1416 sLog.outString( "WORLD: World initialized" );
1419 void World::DetectDBCLang()
1421 uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1423 if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1425 sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1426 m_lang_confid = LOCALE_enUS;
1429 ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1431 std::string availableLocalsStr;
1433 int default_locale = MAX_LOCALE;
1434 for (int i = MAX_LOCALE-1; i >= 0; --i)
1436 if ( strlen(race->name[i]) > 0) // check by race names
1438 default_locale = i;
1439 m_availableDbcLocaleMask |= (1 << i);
1440 availableLocalsStr += localeNames[i];
1441 availableLocalsStr += " ";
1445 if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1446 (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1448 default_locale = m_lang_confid;
1451 if(default_locale >= MAX_LOCALE)
1453 sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1454 exit(1);
1457 m_defaultDbcLocale = LocaleConstant(default_locale);
1459 sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1460 sLog.outString();
1463 /// Update the World !
1464 void World::Update(uint32 diff)
1466 ///- Update the different timers
1467 for(int i = 0; i < WUPDATE_COUNT; i++)
1468 if(m_timers[i].GetCurrent()>=0)
1469 m_timers[i].Update(diff);
1470 else m_timers[i].SetCurrent(0);
1472 ///- Update the game time and check for shutdown time
1473 _UpdateGameTime();
1475 /// Handle daily quests reset time
1476 if(m_gameTime > m_NextDailyQuestReset)
1478 ResetDailyQuests();
1479 m_NextDailyQuestReset += DAY;
1482 /// <ul><li> Handle auctions when the timer has passed
1483 if (m_timers[WUPDATE_AUCTIONS].Passed())
1485 m_timers[WUPDATE_AUCTIONS].Reset();
1487 ///- Update mails (return old mails with item, or delete them)
1488 //(tested... works on win)
1489 if (++mail_timer > mail_timer_expires)
1491 mail_timer = 0;
1492 objmgr.ReturnOrDeleteOldMails(true);
1495 ///- Handle expired auctions
1496 auctionmgr.Update();
1499 /// <li> Handle session updates when the timer has passed
1500 if (m_timers[WUPDATE_SESSIONS].Passed())
1502 m_timers[WUPDATE_SESSIONS].Reset();
1504 UpdateSessions(diff);
1507 /// <li> Handle weather updates when the timer has passed
1508 if (m_timers[WUPDATE_WEATHERS].Passed())
1510 m_timers[WUPDATE_WEATHERS].Reset();
1512 ///- Send an update signal to Weather objects
1513 WeatherMap::iterator itr, next;
1514 for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1516 next = itr;
1517 ++next;
1519 ///- and remove Weather objects for zones with no player
1520 //As interval > WorldTick
1521 if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1523 delete itr->second;
1524 m_weathers.erase(itr);
1528 /// <li> Update uptime table
1529 if (m_timers[WUPDATE_UPTIME].Passed())
1531 uint32 tmpDiff = (m_gameTime - m_startTime);
1532 uint32 maxClientsNum = sWorld.GetMaxActiveSessionCount();
1534 m_timers[WUPDATE_UPTIME].Reset();
1535 WorldDatabase.PExecute("UPDATE uptime SET uptime = %d, maxplayers = %d WHERE starttime = " I64FMTD, tmpDiff, maxClientsNum, uint64(m_startTime));
1538 /// <li> Handle all other objects
1539 if (m_timers[WUPDATE_OBJECTS].Passed())
1541 m_timers[WUPDATE_OBJECTS].Reset();
1542 ///- Update objects when the timer has passed (maps, transport, creatures,...)
1543 MapManager::Instance().Update(diff); // As interval = 0
1545 ///- Process necessary scripts
1546 if (!m_scriptSchedule.empty())
1547 ScriptsProcess();
1549 sBattleGroundMgr.Update(diff);
1552 // execute callbacks from sql queries that were queued recently
1553 UpdateResultQueue();
1555 ///- Erase corpses once every 20 minutes
1556 if (m_timers[WUPDATE_CORPSES].Passed())
1558 m_timers[WUPDATE_CORPSES].Reset();
1560 CorpsesErase();
1563 ///- Process Game events when necessary
1564 if (m_timers[WUPDATE_EVENTS].Passed())
1566 m_timers[WUPDATE_EVENTS].Reset(); // to give time for Update() to be processed
1567 uint32 nextGameEvent = gameeventmgr.Update();
1568 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1569 m_timers[WUPDATE_EVENTS].Reset();
1572 /// </ul>
1573 ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1574 MapManager::Instance().DoDelayedMovesAndRemoves();
1576 // update the instance reset times
1577 sInstanceSaveManager.Update();
1579 // And last, but not least handle the issued cli commands
1580 ProcessCliCommands();
1583 /// Put scripts in the execution queue
1584 void World::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
1586 ///- Find the script map
1587 ScriptMapMap::const_iterator s = scripts.find(id);
1588 if (s == scripts.end())
1589 return;
1591 // prepare static data
1592 uint64 sourceGUID = source->GetGUID();
1593 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1594 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1596 ///- Schedule script execution for all scripts in the script map
1597 ScriptMap const *s2 = &(s->second);
1598 bool immedScript = false;
1599 for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
1601 ScriptAction sa;
1602 sa.sourceGUID = sourceGUID;
1603 sa.targetGUID = targetGUID;
1604 sa.ownerGUID = ownerGUID;
1606 sa.script = &iter->second;
1607 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + iter->first, sa));
1608 if (iter->first == 0)
1609 immedScript = true;
1611 ///- If one of the effects should be immediate, launch the script execution
1612 if (immedScript)
1613 ScriptsProcess();
1616 void World::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
1618 // NOTE: script record _must_ exist until command executed
1620 // prepare static data
1621 uint64 sourceGUID = source->GetGUID();
1622 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1623 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1625 ScriptAction sa;
1626 sa.sourceGUID = sourceGUID;
1627 sa.targetGUID = targetGUID;
1628 sa.ownerGUID = ownerGUID;
1630 sa.script = &script;
1631 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + delay, sa));
1633 ///- If effects should be immediate, launch the script execution
1634 if(delay == 0)
1635 ScriptsProcess();
1638 /// Process queued scripts
1639 void World::ScriptsProcess()
1641 if (m_scriptSchedule.empty())
1642 return;
1644 ///- Process overdue queued scripts
1645 std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
1646 // ok as multimap is a *sorted* associative container
1647 while (!m_scriptSchedule.empty() && (iter->first <= m_gameTime))
1649 ScriptAction const& step = iter->second;
1651 Object* source = NULL;
1653 if(step.sourceGUID)
1655 switch(GUID_HIPART(step.sourceGUID))
1657 case HIGHGUID_ITEM:
1658 // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1660 Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
1661 if(player)
1662 source = player->GetItemByGuid(step.sourceGUID);
1663 break;
1665 case HIGHGUID_UNIT:
1666 source = HashMapHolder<Creature>::Find(step.sourceGUID);
1667 break;
1668 case HIGHGUID_PET:
1669 source = HashMapHolder<Pet>::Find(step.sourceGUID);
1670 break;
1671 case HIGHGUID_VEHICLE:
1672 source = HashMapHolder<Vehicle>::Find(step.sourceGUID);
1673 break;
1674 case HIGHGUID_PLAYER:
1675 source = HashMapHolder<Player>::Find(step.sourceGUID);
1676 break;
1677 case HIGHGUID_GAMEOBJECT:
1678 source = HashMapHolder<GameObject>::Find(step.sourceGUID);
1679 break;
1680 case HIGHGUID_CORPSE:
1681 source = HashMapHolder<Corpse>::Find(step.sourceGUID);
1682 break;
1683 default:
1684 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
1685 break;
1689 if(source && !source->IsInWorld()) source = NULL;
1691 Object* target = NULL;
1693 if(step.targetGUID)
1695 switch(GUID_HIPART(step.targetGUID))
1697 case HIGHGUID_UNIT:
1698 target = HashMapHolder<Creature>::Find(step.targetGUID);
1699 break;
1700 case HIGHGUID_PET:
1701 target = HashMapHolder<Pet>::Find(step.targetGUID);
1702 break;
1703 case HIGHGUID_VEHICLE:
1704 target = HashMapHolder<Vehicle>::Find(step.targetGUID);
1705 break;
1706 case HIGHGUID_PLAYER: // empty GUID case also
1707 target = HashMapHolder<Player>::Find(step.targetGUID);
1708 break;
1709 case HIGHGUID_GAMEOBJECT:
1710 target = HashMapHolder<GameObject>::Find(step.targetGUID);
1711 break;
1712 case HIGHGUID_CORPSE:
1713 target = HashMapHolder<Corpse>::Find(step.targetGUID);
1714 break;
1715 default:
1716 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
1717 break;
1721 if(target && !target->IsInWorld()) target = NULL;
1723 switch (step.script->command)
1725 case SCRIPT_COMMAND_TALK:
1727 if(!source)
1729 sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1730 break;
1733 if(source->GetTypeId()!=TYPEID_UNIT)
1735 sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1736 break;
1739 uint64 unit_target = target ? target->GetGUID() : 0;
1741 //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1742 switch(step.script->datalong)
1744 case 0: // Say
1745 ((Creature *)source)->Say(step.script->dataint, LANG_UNIVERSAL, unit_target);
1746 break;
1747 case 1: // Whisper
1748 if(!unit_target)
1750 sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
1751 break;
1753 ((Creature *)source)->Whisper(step.script->dataint,unit_target);
1754 break;
1755 case 2: // Yell
1756 ((Creature *)source)->Yell(step.script->dataint, LANG_UNIVERSAL, unit_target);
1757 break;
1758 case 3: // Emote text
1759 ((Creature *)source)->TextEmote(step.script->dataint, unit_target);
1760 break;
1761 default:
1762 break; // must be already checked at load
1764 break;
1767 case SCRIPT_COMMAND_EMOTE:
1768 if(!source)
1770 sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1771 break;
1774 if(source->GetTypeId()!=TYPEID_UNIT)
1776 sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1777 break;
1780 ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
1781 break;
1782 case SCRIPT_COMMAND_FIELD_SET:
1783 if(!source)
1785 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1786 break;
1788 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1790 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1791 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1792 break;
1795 source->SetUInt32Value(step.script->datalong, step.script->datalong2);
1796 break;
1797 case SCRIPT_COMMAND_MOVE_TO:
1798 if(!source)
1800 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1801 break;
1804 if(source->GetTypeId()!=TYPEID_UNIT)
1806 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1807 break;
1809 ((Unit *)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, step.script->datalong2 );
1810 ((Unit *)source)->GetMap()->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
1811 break;
1812 case SCRIPT_COMMAND_FLAG_SET:
1813 if(!source)
1815 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1816 break;
1818 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1820 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1821 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1822 break;
1825 source->SetFlag(step.script->datalong, step.script->datalong2);
1826 break;
1827 case SCRIPT_COMMAND_FLAG_REMOVE:
1828 if(!source)
1830 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1831 break;
1833 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1835 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1836 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1837 break;
1840 source->RemoveFlag(step.script->datalong, step.script->datalong2);
1841 break;
1843 case SCRIPT_COMMAND_TELEPORT_TO:
1845 // accept player in any one from target/source arg
1846 if (!target && !source)
1848 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1849 break;
1852 // must be only Player
1853 if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
1855 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
1856 break;
1859 Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
1861 pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
1862 break;
1865 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
1867 if(!step.script->datalong) // creature not specified
1869 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1870 break;
1873 if(!source)
1875 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1876 break;
1879 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1881 if(!summoner)
1883 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1884 break;
1887 float x = step.script->x;
1888 float y = step.script->y;
1889 float z = step.script->z;
1890 float o = step.script->o;
1892 Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
1893 if (!pCreature)
1895 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
1896 break;
1899 break;
1902 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
1904 if(!step.script->datalong) // gameobject not specified
1906 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1907 break;
1910 if(!source)
1912 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1913 break;
1916 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1918 if(!summoner)
1920 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1921 break;
1924 GameObject *go = NULL;
1925 int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
1927 CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
1928 Cell cell(p);
1929 cell.data.Part.reserved = ALL_DISTRICT;
1931 MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
1932 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(summoner, go,go_check);
1934 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1935 CellLock<GridReadGuard> cell_lock(cell, p);
1936 cell_lock->Visit(cell_lock, object_checker, *summoner->GetMap());
1938 if ( !go )
1940 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
1941 break;
1944 if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1945 go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1946 go->GetGoType()==GAMEOBJECT_TYPE_DOOR ||
1947 go->GetGoType()==GAMEOBJECT_TYPE_BUTTON ||
1948 go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
1950 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
1951 break;
1954 if( go->isSpawned() )
1955 break; //gameobject already spawned
1957 go->SetLootState(GO_READY);
1958 go->SetRespawnTime(time_to_despawn); //despawn object in ? seconds
1960 go->GetMap()->Add(go);
1961 break;
1963 case SCRIPT_COMMAND_OPEN_DOOR:
1965 if(!step.script->datalong) // door not specified
1967 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1968 break;
1971 if(!source)
1973 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1974 break;
1977 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
1979 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1980 break;
1983 Unit* caster = (Unit*)source;
1985 GameObject *door = NULL;
1986 int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1988 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1989 Cell cell(p);
1990 cell.data.Part.reserved = ALL_DISTRICT;
1992 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1993 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(caster,door,go_check);
1995 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1996 CellLock<GridReadGuard> cell_lock(cell, p);
1997 cell_lock->Visit(cell_lock, object_checker, *caster->GetMap());
1999 if ( !door )
2001 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
2002 break;
2004 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
2006 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
2007 break;
2010 if( !door->GetGoState() )
2011 break; //door already open
2013 door->UseDoorOrButton(time_to_close);
2015 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
2016 ((GameObject*)target)->UseDoorOrButton(time_to_close);
2017 break;
2019 case SCRIPT_COMMAND_CLOSE_DOOR:
2021 if(!step.script->datalong) // guid for door not specified
2023 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
2024 break;
2027 if(!source)
2029 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
2030 break;
2033 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
2035 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
2036 break;
2039 Unit* caster = (Unit*)source;
2041 GameObject *door = NULL;
2042 int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
2044 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
2045 Cell cell(p);
2046 cell.data.Part.reserved = ALL_DISTRICT;
2048 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
2049 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(caster,door,go_check);
2051 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
2052 CellLock<GridReadGuard> cell_lock(cell, p);
2053 cell_lock->Visit(cell_lock, object_checker, *caster->GetMap());
2055 if ( !door )
2057 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
2058 break;
2060 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
2062 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
2063 break;
2066 if( door->GetGoState() )
2067 break; //door already closed
2069 door->UseDoorOrButton(time_to_open);
2071 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
2072 ((GameObject*)target)->UseDoorOrButton(time_to_open);
2074 break;
2076 case SCRIPT_COMMAND_QUEST_EXPLORED:
2078 if(!source)
2080 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
2081 break;
2084 if(!target)
2086 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
2087 break;
2090 // when script called for item spell casting then target == (unit or GO) and source is player
2091 WorldObject* worldObject;
2092 Player* player;
2094 if(target->GetTypeId()==TYPEID_PLAYER)
2096 if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
2098 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
2099 break;
2102 worldObject = (WorldObject*)source;
2103 player = (Player*)target;
2105 else
2107 if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
2109 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
2110 break;
2113 if(source->GetTypeId()!=TYPEID_PLAYER)
2115 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
2116 break;
2119 worldObject = (WorldObject*)target;
2120 player = (Player*)source;
2123 // quest id and flags checked at script loading
2124 if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
2125 (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
2126 player->AreaExploredOrEventHappens(step.script->datalong);
2127 else
2128 player->FailQuest(step.script->datalong);
2130 break;
2133 case SCRIPT_COMMAND_ACTIVATE_OBJECT:
2135 if(!source)
2137 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
2138 break;
2141 if(!source->isType(TYPEMASK_UNIT))
2143 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2144 break;
2147 if(!target)
2149 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
2150 break;
2153 if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
2155 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
2156 break;
2159 Unit* caster = (Unit*)source;
2161 GameObject *go = (GameObject*)target;
2163 go->Use(caster);
2164 break;
2167 case SCRIPT_COMMAND_REMOVE_AURA:
2169 Object* cmdTarget = step.script->datalong2 ? source : target;
2171 if(!cmdTarget)
2173 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
2174 break;
2177 if(!cmdTarget->isType(TYPEMASK_UNIT))
2179 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2180 break;
2183 ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
2184 break;
2187 case SCRIPT_COMMAND_CAST_SPELL:
2189 if(!source)
2191 sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
2192 break;
2195 if(!source->isType(TYPEMASK_UNIT))
2197 sLog.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2198 break;
2201 Object* cmdTarget = step.script->datalong2 & 0x01 ? source : target;
2203 if(!cmdTarget)
2205 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 & 0x01 ? "source" : "target");
2206 break;
2209 if(!cmdTarget->isType(TYPEMASK_UNIT))
2211 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 & 0x01 ? "source" : "target",cmdTarget->GetTypeId());
2212 break;
2215 Unit* spellTarget = (Unit*)cmdTarget;
2217 Object* cmdSource = step.script->datalong2 & 0x02 ? target : source;
2219 if(!cmdSource)
2221 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 & 0x02 ? "target" : "source");
2222 break;
2225 if(!cmdSource->isType(TYPEMASK_UNIT))
2227 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 & 0x02 ? "target" : "source", cmdSource->GetTypeId());
2228 break;
2231 Unit* spellSource = (Unit*)cmdSource;
2233 //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2234 spellSource->CastSpell(spellTarget,step.script->datalong,false);
2236 break;
2239 default:
2240 sLog.outError("Unknown script command %u called.",step.script->command);
2241 break;
2244 m_scriptSchedule.erase(iter);
2246 iter = m_scriptSchedule.begin();
2248 return;
2251 /// Send a packet to all players (except self if mentioned)
2252 void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
2254 SessionMap::iterator itr;
2255 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2257 if (itr->second &&
2258 itr->second->GetPlayer() &&
2259 itr->second->GetPlayer()->IsInWorld() &&
2260 itr->second != self &&
2261 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2263 itr->second->SendPacket(packet);
2268 namespace MaNGOS
2270 class WorldWorldTextBuilder
2272 public:
2273 typedef std::vector<WorldPacket*> WorldPacketList;
2274 explicit WorldWorldTextBuilder(int32 textId, va_list* args = NULL) : i_textId(textId), i_args(args) {}
2275 void operator()(WorldPacketList& data_list, int32 loc_idx)
2277 char const* text = objmgr.GetMangosString(i_textId,loc_idx);
2279 if(i_args)
2281 // we need copy va_list before use or original va_list will corrupted
2282 va_list ap;
2283 va_copy(ap,*i_args);
2285 char str [2048];
2286 vsnprintf(str,2048,text, ap );
2287 va_end(ap);
2289 do_helper(data_list,&str[0]);
2291 else
2292 do_helper(data_list,(char*)text);
2294 private:
2295 char* lineFromMessage(char*& pos) { char* start = strtok(pos,"\n"); pos = NULL; return start; }
2296 void do_helper(WorldPacketList& data_list, char* text)
2298 char* pos = text;
2300 while(char* line = lineFromMessage(pos))
2302 WorldPacket* data = new WorldPacket();
2304 uint32 lineLength = (line ? strlen(line) : 0) + 1;
2306 data->Initialize(SMSG_MESSAGECHAT, 100); // guess size
2307 *data << uint8(CHAT_MSG_SYSTEM);
2308 *data << uint32(LANG_UNIVERSAL);
2309 *data << uint64(0);
2310 *data << uint32(0); // can be chat msg group or something
2311 *data << uint64(0);
2312 *data << uint32(lineLength);
2313 *data << line;
2314 *data << uint8(0);
2316 data_list.push_back(data);
2320 int32 i_textId;
2321 va_list* i_args;
2323 } // namespace MaNGOS
2325 /// Send a System Message to all players (except self if mentioned)
2326 void World::SendWorldText(int32 string_id, ...)
2328 va_list ap;
2329 va_start(ap, string_id);
2331 MaNGOS::WorldWorldTextBuilder wt_builder(string_id, &ap);
2332 MaNGOS::LocalizedPacketListDo<MaNGOS::WorldWorldTextBuilder> wt_do(wt_builder);
2333 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2335 if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
2336 continue;
2338 wt_do(itr->second->GetPlayer());
2341 va_end(ap);
2344 /// DEPRICATED, only for debug purpose. Send a System Message to all players (except self if mentioned)
2345 void World::SendGlobalText(const char* text, WorldSession *self)
2347 WorldPacket data;
2349 // need copy to prevent corruption by strtok call in LineFromMessage original string
2350 char* buf = strdup(text);
2351 char* pos = buf;
2353 while(char* line = ChatHandler::LineFromMessage(pos))
2355 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2356 SendGlobalMessage(&data, self);
2359 free(buf);
2362 /// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2363 void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
2365 SessionMap::iterator itr;
2366 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2368 if (itr->second &&
2369 itr->second->GetPlayer() &&
2370 itr->second->GetPlayer()->IsInWorld() &&
2371 itr->second->GetPlayer()->GetZoneId() == zone &&
2372 itr->second != self &&
2373 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2375 itr->second->SendPacket(packet);
2380 /// Send a System Message to all players in the zone (except self if mentioned)
2381 void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
2383 WorldPacket data;
2384 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
2385 SendZoneMessage(zone, &data, self,team);
2388 /// Kick (and save) all players
2389 void World::KickAll()
2391 m_QueuedPlayer.clear(); // prevent send queue update packet and login queued sessions
2393 // session not removed at kick and will removed in next update tick
2394 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2395 itr->second->KickPlayer();
2398 /// Kick (and save) all players with security level less `sec`
2399 void World::KickAllLess(AccountTypes sec)
2401 // session not removed at kick and will removed in next update tick
2402 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2403 if(itr->second->GetSecurity() < sec)
2404 itr->second->KickPlayer();
2407 /// Kick (and save) the designated player
2408 bool World::KickPlayer(const std::string& playerName)
2410 SessionMap::iterator itr;
2412 // session not removed at kick and will removed in next update tick
2413 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2415 if(!itr->second)
2416 continue;
2417 Player *player = itr->second->GetPlayer();
2418 if(!player)
2419 continue;
2420 if( player->IsInWorld() )
2422 if (playerName == player->GetName())
2424 itr->second->KickPlayer();
2425 return true;
2429 return false;
2432 /// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2433 BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, std::string duration, std::string reason, std::string author)
2435 loginDatabase.escape_string(nameOrIP);
2436 loginDatabase.escape_string(reason);
2437 std::string safe_author=author;
2438 loginDatabase.escape_string(safe_author);
2440 uint32 duration_secs = TimeStringToSecs(duration);
2441 QueryResult *resultAccounts = NULL; //used for kicking
2443 ///- Update the database with ban information
2444 switch(mode)
2446 case BAN_IP:
2447 //No SQL injection as strings are escaped
2448 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
2449 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());
2450 break;
2451 case BAN_ACCOUNT:
2452 //No SQL injection as string is escaped
2453 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2454 break;
2455 case BAN_CHARACTER:
2456 //No SQL injection as string is escaped
2457 resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2458 break;
2459 default:
2460 return BAN_SYNTAX_ERROR;
2463 if(!resultAccounts)
2465 if(mode==BAN_IP)
2466 return BAN_SUCCESS; // ip correctly banned but nobody affected (yet)
2467 else
2468 return BAN_NOTFOUND; // Nobody to ban
2471 ///- Disconnect all affected players (for IP it can be several)
2474 Field* fieldsAccount = resultAccounts->Fetch();
2475 uint32 account = fieldsAccount->GetUInt32();
2477 if(mode!=BAN_IP)
2479 //No SQL injection as strings are escaped
2480 loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2481 account,duration_secs,safe_author.c_str(),reason.c_str());
2484 if (WorldSession* sess = FindSession(account))
2485 if(std::string(sess->GetPlayerName()) != author)
2486 sess->KickPlayer();
2488 while( resultAccounts->NextRow() );
2490 delete resultAccounts;
2491 return BAN_SUCCESS;
2494 /// Remove a ban from an account or IP address
2495 bool World::RemoveBanAccount(BanMode mode, std::string nameOrIP)
2497 if (mode == BAN_IP)
2499 loginDatabase.escape_string(nameOrIP);
2500 loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
2502 else
2504 uint32 account = 0;
2505 if (mode == BAN_ACCOUNT)
2506 account = accmgr.GetId (nameOrIP);
2507 else if (mode == BAN_CHARACTER)
2508 account = objmgr.GetPlayerAccountIdByPlayerName (nameOrIP);
2510 if (!account)
2511 return false;
2513 //NO SQL injection as account is uint32
2514 loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
2516 return true;
2519 /// Update the game time
2520 void World::_UpdateGameTime()
2522 ///- update the time
2523 time_t thisTime = time(NULL);
2524 uint32 elapsed = uint32(thisTime - m_gameTime);
2525 m_gameTime = thisTime;
2527 ///- if there is a shutdown timer
2528 if(!m_stopEvent && m_ShutdownTimer > 0 && elapsed > 0)
2530 ///- ... and it is overdue, stop the world (set m_stopEvent)
2531 if( m_ShutdownTimer <= elapsed )
2533 if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2534 m_stopEvent = true; // exist code already set
2535 else
2536 m_ShutdownTimer = 1; // minimum timer value to wait idle state
2538 ///- ... else decrease it and if necessary display a shutdown countdown to the users
2539 else
2541 m_ShutdownTimer -= elapsed;
2543 ShutdownMsg();
2548 /// Shutdown the server
2549 void World::ShutdownServ(uint32 time, uint32 options, uint8 exitcode)
2551 // ignore if server shutdown at next tick
2552 if(m_stopEvent)
2553 return;
2555 m_ShutdownMask = options;
2556 m_ExitCode = exitcode;
2558 ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2559 if(time==0)
2561 if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2562 m_stopEvent = true; // exist code already set
2563 else
2564 m_ShutdownTimer = 1; //So that the session count is re-evaluated at next world tick
2566 ///- Else set the shutdown timer and warn users
2567 else
2569 m_ShutdownTimer = time;
2570 ShutdownMsg(true);
2574 /// Display a shutdown message to the user(s)
2575 void World::ShutdownMsg(bool show, Player* player)
2577 // not show messages for idle shutdown mode
2578 if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
2579 return;
2581 ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2582 if ( show ||
2583 (m_ShutdownTimer < 10) ||
2584 // < 30 sec; every 5 sec
2585 (m_ShutdownTimer<30 && (m_ShutdownTimer % 5 )==0) ||
2586 // < 5 min ; every 1 min
2587 (m_ShutdownTimer<5*MINUTE && (m_ShutdownTimer % MINUTE )==0) ||
2588 // < 30 min ; every 5 min
2589 (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
2590 // < 12 h ; every 1 h
2591 (m_ShutdownTimer<12*HOUR && (m_ShutdownTimer % HOUR )==0) ||
2592 // > 12 h ; every 12 h
2593 (m_ShutdownTimer>12*HOUR && (m_ShutdownTimer % (12*HOUR) )==0))
2595 std::string str = secsToTimeString(m_ShutdownTimer);
2597 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
2599 SendServerMessage(msgid,str.c_str(),player);
2600 DEBUG_LOG("Server is %s in %s",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"),str.c_str());
2604 /// Cancel a planned server shutdown
2605 void World::ShutdownCancel()
2607 // nothing cancel or too later
2608 if(!m_ShutdownTimer || m_stopEvent)
2609 return;
2611 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2613 m_ShutdownMask = 0;
2614 m_ShutdownTimer = 0;
2615 m_ExitCode = SHUTDOWN_EXIT_CODE; // to default value
2616 SendServerMessage(msgid);
2618 DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2621 /// Send a server message to the user(s)
2622 void World::SendServerMessage(uint32 type, const char *text, Player* player)
2624 WorldPacket data(SMSG_SERVER_MESSAGE, 50); // guess size
2625 data << uint32(type);
2626 if(type <= SERVER_MSG_STRING)
2627 data << text;
2629 if(player)
2630 player->GetSession()->SendPacket(&data);
2631 else
2632 SendGlobalMessage( &data );
2635 void World::UpdateSessions( uint32 diff )
2637 ///- Add new sessions
2638 while(!addSessQueue.empty())
2640 WorldSession* sess = addSessQueue.next ();
2641 AddSession_ (sess);
2644 ///- Then send an update signal to remaining ones
2645 for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2647 next = itr;
2648 ++next;
2650 if(!itr->second)
2651 continue;
2653 ///- and remove not active sessions from the list
2654 if(!itr->second->Update(diff)) // As interval = 0
2656 RemoveQueuedPlayer (itr->second);
2657 delete itr->second;
2658 m_sessions.erase(itr);
2663 // This handles the issued and queued CLI commands
2664 void World::ProcessCliCommands()
2666 if (cliCmdQueue.empty())
2667 return;
2669 CliCommandHolder::Print* zprint;
2671 while (!cliCmdQueue.empty())
2673 sLog.outDebug("CLI command under processing...");
2674 CliCommandHolder *command = cliCmdQueue.next();
2676 zprint = command->m_print;
2678 CliHandler(zprint).ParseCommands(command->m_command);
2680 delete command;
2683 // print the console message here so it looks right
2684 zprint("mangos>");
2687 void World::InitResultQueue()
2689 m_resultQueue = new SqlResultQueue;
2690 CharacterDatabase.SetResultQueue(m_resultQueue);
2693 void World::UpdateResultQueue()
2695 m_resultQueue->Update();
2698 void World::UpdateRealmCharCount(uint32 accountId)
2700 CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2701 "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2704 void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2706 if (resultCharCount)
2708 Field *fields = resultCharCount->Fetch();
2709 uint32 charCount = fields[0].GetUInt32();
2710 delete resultCharCount;
2711 loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2712 loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2716 void World::InitDailyQuestResetTime()
2718 time_t mostRecentQuestTime;
2720 QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2721 if(result)
2723 Field *fields = result->Fetch();
2725 mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2726 delete result;
2728 else
2729 mostRecentQuestTime = 0;
2731 // client built-in time for reset is 6:00 AM
2732 // FIX ME: client not show day start time
2733 time_t curTime = time(NULL);
2734 tm localTm = *localtime(&curTime);
2735 localTm.tm_hour = 6;
2736 localTm.tm_min = 0;
2737 localTm.tm_sec = 0;
2739 // current day reset time
2740 time_t curDayResetTime = mktime(&localTm);
2742 // last reset time before current moment
2743 time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2745 // need reset (if we have quest time before last reset time (not processed by some reason)
2746 if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2747 m_NextDailyQuestReset = mostRecentQuestTime;
2748 else
2750 // plan next reset time
2751 m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2755 void World::ResetDailyQuests()
2757 sLog.outDetail("Daily quests reset for all characters.");
2758 CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2759 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2760 if(itr->second->GetPlayer())
2761 itr->second->GetPlayer()->ResetDailyQuestStatus();
2764 void World::SetPlayerLimit( int32 limit, bool needUpdate )
2766 if(limit < -SEC_ADMINISTRATOR)
2767 limit = -SEC_ADMINISTRATOR;
2769 // lock update need
2770 bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2772 m_playerLimit = limit;
2774 if(db_update_need)
2775 loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2778 void World::UpdateMaxSessionCounters()
2780 m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2781 m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2784 void World::LoadDBVersion()
2786 QueryResult* result = WorldDatabase.Query("SELECT version FROM db_version LIMIT 1");
2787 if(result)
2789 Field* fields = result->Fetch();
2791 m_DBVersion = fields[0].GetString();
2792 delete result;
2794 else
2795 m_DBVersion = "unknown world database";