Implemented gameobjects and creatures grouping (pools of them)
[getmangos.git] / src / game / World.cpp
blob9ccdf1378ee78bf93485e537d2b00e454a1890e5
1 /*
2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 /** \file
20 \ingroup world
23 #include "Common.h"
24 //#include "WorldSocket.h"
25 #include "Database/DatabaseEnv.h"
26 #include "Config/ConfigEnv.h"
27 #include "SystemConfig.h"
28 #include "Log.h"
29 #include "Opcodes.h"
30 #include "WorldSession.h"
31 #include "WorldPacket.h"
32 #include "Weather.h"
33 #include "Player.h"
34 #include "SkillExtraItems.h"
35 #include "SkillDiscovery.h"
36 #include "World.h"
37 #include "AccountMgr.h"
38 #include "AchievementMgr.h"
39 #include "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 "GameEvent.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());
410 else
412 if (confVersion < _MANGOSDCONFVERSION)
414 sLog.outError("*****************************************************************************");
415 sLog.outError(" WARNING: Your mangosd.conf version indicates your conf file is out of date!");
416 sLog.outError(" Please check for updates, as your current default values may cause");
417 sLog.outError(" unexpected behavior.");
418 sLog.outError("*****************************************************************************");
419 clock_t pause = 3000 + clock();
420 while (pause > clock());
424 ///- Read the player limit and the Message of the day from the config file
425 SetPlayerLimit( sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT), true );
426 SetMotd( sConfig.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
428 ///- Read all rates from the config file
429 rate_values[RATE_HEALTH] = sConfig.GetFloatDefault("Rate.Health", 1);
430 if(rate_values[RATE_HEALTH] < 0)
432 sLog.outError("Rate.Health (%f) must be > 0. Using 1 instead.",rate_values[RATE_HEALTH]);
433 rate_values[RATE_HEALTH] = 1;
435 rate_values[RATE_POWER_MANA] = sConfig.GetFloatDefault("Rate.Mana", 1);
436 if(rate_values[RATE_POWER_MANA] < 0)
438 sLog.outError("Rate.Mana (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_MANA]);
439 rate_values[RATE_POWER_MANA] = 1;
441 rate_values[RATE_POWER_RAGE_INCOME] = sConfig.GetFloatDefault("Rate.Rage.Income", 1);
442 rate_values[RATE_POWER_RAGE_LOSS] = sConfig.GetFloatDefault("Rate.Rage.Loss", 1);
443 if(rate_values[RATE_POWER_RAGE_LOSS] < 0)
445 sLog.outError("Rate.Rage.Loss (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_RAGE_LOSS]);
446 rate_values[RATE_POWER_RAGE_LOSS] = 1;
448 rate_values[RATE_POWER_RUNICPOWER_INCOME] = sConfig.GetFloatDefault("Rate.RunicPower.Income", 1);
449 rate_values[RATE_POWER_RUNICPOWER_LOSS] = sConfig.GetFloatDefault("Rate.RunicPower.Loss", 1);
450 if(rate_values[RATE_POWER_RUNICPOWER_LOSS] < 0)
452 sLog.outError("Rate.RunicPower.Loss (%f) must be > 0. Using 1 instead.",rate_values[RATE_POWER_RUNICPOWER_LOSS]);
453 rate_values[RATE_POWER_RUNICPOWER_LOSS] = 1;
455 rate_values[RATE_POWER_FOCUS] = sConfig.GetFloatDefault("Rate.Focus", 1.0f);
456 rate_values[RATE_SKILL_DISCOVERY] = sConfig.GetFloatDefault("Rate.Skill.Discovery", 1.0f);
457 rate_values[RATE_DROP_ITEM_POOR] = sConfig.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f);
458 rate_values[RATE_DROP_ITEM_NORMAL] = sConfig.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f);
459 rate_values[RATE_DROP_ITEM_UNCOMMON] = sConfig.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f);
460 rate_values[RATE_DROP_ITEM_RARE] = sConfig.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f);
461 rate_values[RATE_DROP_ITEM_EPIC] = sConfig.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f);
462 rate_values[RATE_DROP_ITEM_LEGENDARY] = sConfig.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f);
463 rate_values[RATE_DROP_ITEM_ARTIFACT] = sConfig.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f);
464 rate_values[RATE_DROP_ITEM_REFERENCED] = sConfig.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f);
465 rate_values[RATE_DROP_MONEY] = sConfig.GetFloatDefault("Rate.Drop.Money", 1.0f);
466 rate_values[RATE_XP_KILL] = sConfig.GetFloatDefault("Rate.XP.Kill", 1.0f);
467 rate_values[RATE_XP_QUEST] = sConfig.GetFloatDefault("Rate.XP.Quest", 1.0f);
468 rate_values[RATE_XP_EXPLORE] = sConfig.GetFloatDefault("Rate.XP.Explore", 1.0f);
469 rate_values[RATE_REPUTATION_GAIN] = sConfig.GetFloatDefault("Rate.Reputation.Gain", 1.0f);
470 rate_values[RATE_CREATURE_NORMAL_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f);
471 rate_values[RATE_CREATURE_ELITE_ELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f);
472 rate_values[RATE_CREATURE_ELITE_RAREELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f);
473 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f);
474 rate_values[RATE_CREATURE_ELITE_RARE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f);
475 rate_values[RATE_CREATURE_NORMAL_HP] = sConfig.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f);
476 rate_values[RATE_CREATURE_ELITE_ELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f);
477 rate_values[RATE_CREATURE_ELITE_RAREELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f);
478 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f);
479 rate_values[RATE_CREATURE_ELITE_RARE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f);
480 rate_values[RATE_CREATURE_NORMAL_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f);
481 rate_values[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f);
482 rate_values[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f);
483 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f);
484 rate_values[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f);
485 rate_values[RATE_CREATURE_AGGRO] = sConfig.GetFloatDefault("Rate.Creature.Aggro", 1.0f);
486 rate_values[RATE_REST_INGAME] = sConfig.GetFloatDefault("Rate.Rest.InGame", 1.0f);
487 rate_values[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY] = sConfig.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f);
488 rate_values[RATE_REST_OFFLINE_IN_WILDERNESS] = sConfig.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f);
489 rate_values[RATE_DAMAGE_FALL] = sConfig.GetFloatDefault("Rate.Damage.Fall", 1.0f);
490 rate_values[RATE_AUCTION_TIME] = sConfig.GetFloatDefault("Rate.Auction.Time", 1.0f);
491 rate_values[RATE_AUCTION_DEPOSIT] = sConfig.GetFloatDefault("Rate.Auction.Deposit", 1.0f);
492 rate_values[RATE_AUCTION_CUT] = sConfig.GetFloatDefault("Rate.Auction.Cut", 1.0f);
493 rate_values[RATE_HONOR] = sConfig.GetFloatDefault("Rate.Honor",1.0f);
494 rate_values[RATE_MINING_AMOUNT] = sConfig.GetFloatDefault("Rate.Mining.Amount",1.0f);
495 rate_values[RATE_MINING_NEXT] = sConfig.GetFloatDefault("Rate.Mining.Next",1.0f);
496 rate_values[RATE_INSTANCE_RESET_TIME] = sConfig.GetFloatDefault("Rate.InstanceResetTime",1.0f);
497 rate_values[RATE_TALENT] = sConfig.GetFloatDefault("Rate.Talent",1.0f);
498 if(rate_values[RATE_TALENT] < 0.0f)
500 sLog.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_TALENT]);
501 rate_values[RATE_TALENT] = 1.0f;
503 rate_values[RATE_CORPSE_DECAY_LOOTED] = sConfig.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f);
505 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = sConfig.GetFloatDefault("TargetPosRecalculateRange",1.5f);
506 if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] < CONTACT_DISTANCE)
508 sLog.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],CONTACT_DISTANCE,CONTACT_DISTANCE);
509 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = CONTACT_DISTANCE;
511 else if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] > ATTACK_DISTANCE)
513 sLog.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",
514 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],ATTACK_DISTANCE,ATTACK_DISTANCE);
515 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = ATTACK_DISTANCE;
518 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = sConfig.GetFloatDefault("DurabilityLossChance.Damage",0.5f);
519 if(rate_values[RATE_DURABILITY_LOSS_DAMAGE] < 0.0f)
521 sLog.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_DAMAGE]);
522 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = 0.0f;
524 rate_values[RATE_DURABILITY_LOSS_ABSORB] = sConfig.GetFloatDefault("DurabilityLossChance.Absorb",0.5f);
525 if(rate_values[RATE_DURABILITY_LOSS_ABSORB] < 0.0f)
527 sLog.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_ABSORB]);
528 rate_values[RATE_DURABILITY_LOSS_ABSORB] = 0.0f;
530 rate_values[RATE_DURABILITY_LOSS_PARRY] = sConfig.GetFloatDefault("DurabilityLossChance.Parry",0.05f);
531 if(rate_values[RATE_DURABILITY_LOSS_PARRY] < 0.0f)
533 sLog.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_PARRY]);
534 rate_values[RATE_DURABILITY_LOSS_PARRY] = 0.0f;
536 rate_values[RATE_DURABILITY_LOSS_BLOCK] = sConfig.GetFloatDefault("DurabilityLossChance.Block",0.05f);
537 if(rate_values[RATE_DURABILITY_LOSS_BLOCK] < 0.0f)
539 sLog.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_BLOCK]);
540 rate_values[RATE_DURABILITY_LOSS_BLOCK] = 0.0f;
543 ///- Read other configuration items from the config file
545 m_configs[CONFIG_COMPRESSION] = sConfig.GetIntDefault("Compression", 1);
546 if(m_configs[CONFIG_COMPRESSION] < 1 || m_configs[CONFIG_COMPRESSION] > 9)
548 sLog.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs[CONFIG_COMPRESSION]);
549 m_configs[CONFIG_COMPRESSION] = 1;
551 m_configs[CONFIG_ADDON_CHANNEL] = sConfig.GetBoolDefault("AddonChannel", true);
552 m_configs[CONFIG_GRID_UNLOAD] = sConfig.GetBoolDefault("GridUnload", true);
553 m_configs[CONFIG_INTERVAL_SAVE] = sConfig.GetIntDefault("PlayerSaveInterval", 900000);
555 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = sConfig.GetIntDefault("GridCleanUpDelay", 300000);
556 if(m_configs[CONFIG_INTERVAL_GRIDCLEAN] < MIN_GRID_DELAY)
558 sLog.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_GRIDCLEAN],MIN_GRID_DELAY);
559 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = MIN_GRID_DELAY;
561 if(reload)
562 MapManager::Instance().SetGridCleanUpDelay(m_configs[CONFIG_INTERVAL_GRIDCLEAN]);
564 m_configs[CONFIG_INTERVAL_MAPUPDATE] = sConfig.GetIntDefault("MapUpdateInterval", 100);
565 if(m_configs[CONFIG_INTERVAL_MAPUPDATE] < MIN_MAP_UPDATE_DELAY)
567 sLog.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_MAPUPDATE],MIN_MAP_UPDATE_DELAY);
568 m_configs[CONFIG_INTERVAL_MAPUPDATE] = MIN_MAP_UPDATE_DELAY;
570 if(reload)
571 MapManager::Instance().SetMapUpdateInterval(m_configs[CONFIG_INTERVAL_MAPUPDATE]);
573 m_configs[CONFIG_INTERVAL_CHANGEWEATHER] = sConfig.GetIntDefault("ChangeWeatherInterval", 600000);
575 if(reload)
577 uint32 val = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
578 if(val!=m_configs[CONFIG_PORT_WORLD])
579 sLog.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_PORT_WORLD]);
581 else
582 m_configs[CONFIG_PORT_WORLD] = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
584 if(reload)
586 uint32 val = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
587 if(val!=m_configs[CONFIG_SOCKET_SELECTTIME])
588 sLog.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[DEFAULT_SOCKET_SELECT_TIME]);
590 else
591 m_configs[CONFIG_SOCKET_SELECTTIME] = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
593 m_configs[CONFIG_GROUP_XP_DISTANCE] = sConfig.GetIntDefault("MaxGroupXPDistance", 74);
594 /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
595 m_configs[CONFIG_SIGHT_MONSTER] = sConfig.GetIntDefault("MonsterSight", 50);
596 m_configs[CONFIG_SIGHT_GUARDER] = sConfig.GetIntDefault("GuarderSight", 50);
598 if(reload)
600 uint32 val = sConfig.GetIntDefault("GameType", 0);
601 if(val!=m_configs[CONFIG_GAME_TYPE])
602 sLog.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_GAME_TYPE]);
604 else
605 m_configs[CONFIG_GAME_TYPE] = sConfig.GetIntDefault("GameType", 0);
607 if(reload)
609 uint32 val = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
610 if(val!=m_configs[CONFIG_REALM_ZONE])
611 sLog.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_REALM_ZONE]);
613 else
614 m_configs[CONFIG_REALM_ZONE] = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
616 m_configs[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS] = sConfig.GetBoolDefault("AllowTwoSide.Accounts", false);
617 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
618 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
619 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
620 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
621 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
622 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
623 m_configs[CONFIG_ALLOW_TWO_SIDE_WHO_LIST] = sConfig.GetBoolDefault("AllowTwoSide.WhoList", false);
624 m_configs[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND] = sConfig.GetBoolDefault("AllowTwoSide.AddFriend", false);
625 m_configs[CONFIG_STRICT_PLAYER_NAMES] = sConfig.GetIntDefault("StrictPlayerNames", 0);
626 m_configs[CONFIG_STRICT_CHARTER_NAMES] = sConfig.GetIntDefault("StrictCharterNames", 0);
627 m_configs[CONFIG_STRICT_PET_NAMES] = sConfig.GetIntDefault("StrictPetNames", 0);
629 m_configs[CONFIG_CHARACTERS_CREATING_DISABLED] = sConfig.GetIntDefault("CharactersCreatingDisabled", 0);
631 m_configs[CONFIG_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("CharactersPerRealm", 10);
632 if(m_configs[CONFIG_CHARACTERS_PER_REALM] < 1 || m_configs[CONFIG_CHARACTERS_PER_REALM] > 10)
634 sLog.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs[CONFIG_CHARACTERS_PER_REALM]);
635 m_configs[CONFIG_CHARACTERS_PER_REALM] = 10;
638 // must be after CONFIG_CHARACTERS_PER_REALM
639 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = sConfig.GetIntDefault("CharactersPerAccount", 50);
640 if(m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] < m_configs[CONFIG_CHARACTERS_PER_REALM])
642 sLog.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs[CONFIG_CHARACTERS_PER_ACCOUNT],m_configs[CONFIG_CHARACTERS_PER_REALM]);
643 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = m_configs[CONFIG_CHARACTERS_PER_REALM];
646 m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("HeroicCharactersPerRealm", 1);
647 if(m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] < 0 || m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] > 10)
649 sLog.outError("HeroicCharactersPerRealm (%i) must be in range 0..10. Set to 1.",m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM]);
650 m_configs[CONFIG_HEROIC_CHARACTERS_PER_REALM] = 1;
653 m_configs[CONFIG_MIN_LEVEL_FOR_HEROIC_CHARACTER_CREATING] = sConfig.GetIntDefault("MinLevelForHeroicCharacterCreating", 55);
655 m_configs[CONFIG_SKIP_CINEMATICS] = sConfig.GetIntDefault("SkipCinematics", 0);
656 if(m_configs[CONFIG_SKIP_CINEMATICS] < 0 || m_configs[CONFIG_SKIP_CINEMATICS] > 2)
658 sLog.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs[CONFIG_SKIP_CINEMATICS]);
659 m_configs[CONFIG_SKIP_CINEMATICS] = 0;
662 if(reload)
664 uint32 val = sConfig.GetIntDefault("MaxPlayerLevel", 60);
665 if(val!=m_configs[CONFIG_MAX_PLAYER_LEVEL])
666 sLog.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
668 else
669 m_configs[CONFIG_MAX_PLAYER_LEVEL] = sConfig.GetIntDefault("MaxPlayerLevel", 60);
671 if(m_configs[CONFIG_MAX_PLAYER_LEVEL] > MAX_LEVEL)
673 sLog.outError("MaxPlayerLevel (%i) must be in range 1..%u. Set to %u.",m_configs[CONFIG_MAX_PLAYER_LEVEL],MAX_LEVEL,MAX_LEVEL);
674 m_configs[CONFIG_MAX_PLAYER_LEVEL] = MAX_LEVEL;
677 m_configs[CONFIG_START_PLAYER_LEVEL] = sConfig.GetIntDefault("StartPlayerLevel", 1);
678 if(m_configs[CONFIG_START_PLAYER_LEVEL] < 1)
680 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]);
681 m_configs[CONFIG_START_PLAYER_LEVEL] = 1;
683 else if(m_configs[CONFIG_START_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
685 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]);
686 m_configs[CONFIG_START_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
689 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = sConfig.GetIntDefault("StartHeroicPlayerLevel", 55);
690 if(m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] < 1)
692 sLog.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to 55.",
693 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
694 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = 55;
696 else if(m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
698 sLog.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to %u.",
699 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL],m_configs[CONFIG_MAX_PLAYER_LEVEL]);
700 m_configs[CONFIG_START_HEROIC_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
703 m_configs[CONFIG_START_PLAYER_MONEY] = sConfig.GetIntDefault("StartPlayerMoney", 0);
704 if(m_configs[CONFIG_START_PLAYER_MONEY] < 0)
706 sLog.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",m_configs[CONFIG_START_PLAYER_MONEY],MAX_MONEY_AMOUNT,0);
707 m_configs[CONFIG_START_PLAYER_MONEY] = 0;
709 else if(m_configs[CONFIG_START_PLAYER_MONEY] > MAX_MONEY_AMOUNT)
711 sLog.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",
712 m_configs[CONFIG_START_PLAYER_MONEY],MAX_MONEY_AMOUNT,MAX_MONEY_AMOUNT);
713 m_configs[CONFIG_START_PLAYER_MONEY] = MAX_MONEY_AMOUNT;
716 m_configs[CONFIG_MAX_HONOR_POINTS] = sConfig.GetIntDefault("MaxHonorPoints", 75000);
717 if(m_configs[CONFIG_MAX_HONOR_POINTS] < 0)
719 sLog.outError("MaxHonorPoints (%i) can't be negative. Set to 0.",m_configs[CONFIG_MAX_HONOR_POINTS]);
720 m_configs[CONFIG_MAX_HONOR_POINTS] = 0;
723 m_configs[CONFIG_START_HONOR_POINTS] = sConfig.GetIntDefault("StartHonorPoints", 0);
724 if(m_configs[CONFIG_START_HONOR_POINTS] < 0)
726 sLog.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
727 m_configs[CONFIG_START_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS],0);
728 m_configs[CONFIG_MAX_HONOR_POINTS] = 0;
730 else if(m_configs[CONFIG_START_HONOR_POINTS] > m_configs[CONFIG_MAX_HONOR_POINTS])
732 sLog.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
733 m_configs[CONFIG_START_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS]);
734 m_configs[CONFIG_START_HONOR_POINTS] = m_configs[CONFIG_MAX_HONOR_POINTS];
737 m_configs[CONFIG_MAX_ARENA_POINTS] = sConfig.GetIntDefault("MaxArenaPoints", 5000);
738 if(m_configs[CONFIG_MAX_ARENA_POINTS] < 0)
740 sLog.outError("MaxArenaPoints (%i) can't be negative. Set to 0.",m_configs[CONFIG_MAX_ARENA_POINTS]);
741 m_configs[CONFIG_MAX_ARENA_POINTS] = 0;
744 m_configs[CONFIG_START_ARENA_POINTS] = sConfig.GetIntDefault("StartArenaPoints", 0);
745 if(m_configs[CONFIG_START_ARENA_POINTS] < 0)
747 sLog.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
748 m_configs[CONFIG_START_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS],0);
749 m_configs[CONFIG_MAX_ARENA_POINTS] = 0;
751 else if(m_configs[CONFIG_START_ARENA_POINTS] > m_configs[CONFIG_MAX_ARENA_POINTS])
753 sLog.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
754 m_configs[CONFIG_START_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS]);
755 m_configs[CONFIG_START_ARENA_POINTS] = m_configs[CONFIG_MAX_ARENA_POINTS];
758 m_configs[CONFIG_ALL_TAXI_PATHS] = sConfig.GetBoolDefault("AllFlightPaths", false);
760 m_configs[CONFIG_INSTANCE_IGNORE_LEVEL] = sConfig.GetBoolDefault("Instance.IgnoreLevel", false);
761 m_configs[CONFIG_INSTANCE_IGNORE_RAID] = sConfig.GetBoolDefault("Instance.IgnoreRaid", false);
763 m_configs[CONFIG_BATTLEGROUND_CAST_DESERTER] = sConfig.GetBoolDefault("Battleground.CastDeserter", true);
764 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.Enable", false);
765 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false);
766 m_configs[CONFIG_ARENA_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Arena.QueueAnnouncer.Enable", false);
767 m_configs[CONFIG_ARENA_SEASON_ID] = sConfig.GetIntDefault ("Arena.ArenaSeason.ID", 1);
768 m_configs[CONFIG_ARENA_SEASON_IN_PROGRESS] = sConfig.GetBoolDefault("Arena.ArenaSeason.InProgress", true);
770 m_configs[CONFIG_CAST_UNSTUCK] = sConfig.GetBoolDefault("CastUnstuck", true);
771 m_configs[CONFIG_INSTANCE_RESET_TIME_HOUR] = sConfig.GetIntDefault("Instance.ResetTimeHour", 4);
772 m_configs[CONFIG_INSTANCE_UNLOAD_DELAY] = sConfig.GetIntDefault("Instance.UnloadDelay", 1800000);
774 m_configs[CONFIG_MAX_PRIMARY_TRADE_SKILL] = sConfig.GetIntDefault("MaxPrimaryTradeSkill", 2);
775 m_configs[CONFIG_MIN_PETITION_SIGNS] = sConfig.GetIntDefault("MinPetitionSigns", 9);
776 if(m_configs[CONFIG_MIN_PETITION_SIGNS] > 9)
778 sLog.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.", m_configs[CONFIG_MIN_PETITION_SIGNS]);
779 m_configs[CONFIG_MIN_PETITION_SIGNS] = 9;
782 m_configs[CONFIG_GM_LOGIN_STATE] = sConfig.GetIntDefault("GM.LoginState", 2);
783 m_configs[CONFIG_GM_VISIBLE_STATE] = sConfig.GetIntDefault("GM.Visible", 2);
784 m_configs[CONFIG_GM_ACCEPT_TICKETS] = sConfig.GetIntDefault("GM.AcceptTickets", 2);
785 m_configs[CONFIG_GM_CHAT] = sConfig.GetIntDefault("GM.Chat", 2);
786 m_configs[CONFIG_GM_WISPERING_TO] = sConfig.GetIntDefault("GM.WhisperingTo", 2);
788 m_configs[CONFIG_GM_IN_GM_LIST] = sConfig.GetBoolDefault("GM.InGMList", false);
789 m_configs[CONFIG_GM_IN_WHO_LIST] = sConfig.GetBoolDefault("GM.InWhoList", false);
790 m_configs[CONFIG_GM_LOG_TRADE] = sConfig.GetBoolDefault("GM.LogTrade", false);
792 m_configs[CONFIG_START_GM_LEVEL] = sConfig.GetIntDefault("GM.StartLevel", 1);
793 if(m_configs[CONFIG_START_GM_LEVEL] < m_configs[CONFIG_START_PLAYER_LEVEL])
795 sLog.outError("GM.StartLevel (%i) must be in range StartPlayerLevel(%u)..%u. Set to %u.",
796 m_configs[CONFIG_START_GM_LEVEL],m_configs[CONFIG_START_PLAYER_LEVEL], MAX_LEVEL, m_configs[CONFIG_START_PLAYER_LEVEL]);
797 m_configs[CONFIG_START_GM_LEVEL] = m_configs[CONFIG_START_PLAYER_LEVEL];
799 else if(m_configs[CONFIG_START_GM_LEVEL] > MAX_LEVEL)
801 sLog.outError("GM.StartLevel (%i) must be in range 1..%u. Set to %u.", m_configs[CONFIG_START_GM_LEVEL], MAX_LEVEL, MAX_LEVEL);
802 m_configs[CONFIG_START_GM_LEVEL] = MAX_LEVEL;
804 m_configs[CONFIG_GM_LOWER_SECURITY] = sConfig.GetBoolDefault("GM.LowerSecurity", false);
805 m_configs[CONFIG_GM_ALLOW_ACHIEVEMENT_GAINS] = sConfig.GetBoolDefault("GM.AllowAchievementGain", true);
807 m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
809 m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
811 m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
812 if(m_configs[CONFIG_UPTIME_UPDATE]<=0)
814 sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
815 m_configs[CONFIG_UPTIME_UPDATE] = 10;
817 if(reload)
819 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
820 m_timers[WUPDATE_UPTIME].Reset();
823 m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
824 m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
825 m_configs[CONFIG_SKILL_CHANCE_GREEN] = sConfig.GetIntDefault("SkillChance.Green",25);
826 m_configs[CONFIG_SKILL_CHANCE_GREY] = sConfig.GetIntDefault("SkillChance.Grey",0);
828 m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS] = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
829 m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS] = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
831 m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
832 m_configs[CONFIG_SKILL_MILLING] = sConfig.GetBoolDefault("SkillChance.Milling",false);
834 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = sConfig.GetIntDefault("SkillGain.Crafting", 1);
835 if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
837 sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
838 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
841 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = sConfig.GetIntDefault("SkillGain.Defense", 1);
842 if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
844 sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
845 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
848 m_configs[CONFIG_SKILL_GAIN_GATHERING] = sConfig.GetIntDefault("SkillGain.Gathering", 1);
849 if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
851 sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
852 m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
855 m_configs[CONFIG_SKILL_GAIN_WEAPON] = sConfig.GetIntDefault("SkillGain.Weapon", 1);
856 if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
858 sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
859 m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
862 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
863 if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
865 sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
866 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
869 m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
870 m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
872 m_configs[CONFIG_DISABLE_BREATHING] = sConfig.GetIntDefault("DisableWaterBreath", SEC_CONSOLE);
874 m_configs[CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL] = sConfig.GetBoolDefault("AlwaysMaxSkillForLevel", false);
876 if(reload)
878 uint32 val = sConfig.GetIntDefault("Expansion",1);
879 if(val!=m_configs[CONFIG_EXPANSION])
880 sLog.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
882 else
883 m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",1);
885 m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
886 m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
887 m_configs[CONFIG_CHATFLOOD_MUTE_TIME] = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
889 m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
891 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistanceRadius",10);
892 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY] = sConfig.GetIntDefault("CreatureFamilyAssistanceDelay",1500);
894 m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
896 // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level MAX_LEVEL(100)
897 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff", 4);
898 if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > MAX_LEVEL)
899 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = MAX_LEVEL;
900 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff", 7);
901 if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > MAX_LEVEL)
902 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = MAX_LEVEL;
904 m_configs[CONFIG_DETECT_POS_COLLISION] = sConfig.GetBoolDefault("DetectPosCollision", true);
906 m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
907 m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
909 m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
910 m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
912 m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
913 m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
914 m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
915 m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
916 m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
918 m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault("Death.SicknessLevel", 11);
919 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
920 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
921 m_configs[CONFIG_DEATH_BONES_WORLD] = sConfig.GetBoolDefault("Death.Bones.World", true);
922 m_configs[CONFIG_DEATH_BONES_BG_OR_ARENA] = sConfig.GetBoolDefault("Death.Bones.BattlegroundOrArena", true);
924 m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
926 // always use declined names in the russian client
927 m_configs[CONFIG_DECLINED_NAMES_USED] =
928 (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
930 m_configs[CONFIG_LISTEN_RANGE_SAY] = sConfig.GetIntDefault("ListenRange.Say", 25);
931 m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
932 m_configs[CONFIG_LISTEN_RANGE_YELL] = sConfig.GetIntDefault("ListenRange.Yell", 300);
934 m_configs[CONFIG_ARENA_MAX_RATING_DIFFERENCE] = sConfig.GetIntDefault("Arena.MaxRatingDifference", 0);
935 m_configs[CONFIG_ARENA_RATING_DISCARD_TIMER] = sConfig.GetIntDefault("Arena.RatingDiscardTimer",300000);
936 m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_POINTS] = sConfig.GetBoolDefault("Arena.AutoDistributePoints", false);
937 m_configs[CONFIG_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS] = sConfig.GetIntDefault("Arena.AutoDistributeInterval", 7);
939 m_configs[CONFIG_BATTLEGROUND_PREMATURE_FINISH_TIMER] = sConfig.GetIntDefault("BattleGround.PrematureFinishTimer", 0);
940 m_configs[CONFIG_INSTANT_LOGOUT] = sConfig.GetIntDefault("InstantLogout", SEC_MODERATOR);
942 m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
943 if(m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
945 sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
946 m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
948 m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
949 if(m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
951 sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
952 m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
955 m_MaxVisibleDistanceForCreature = sConfig.GetFloatDefault("Visibility.Distance.Creature", DEFAULT_VISIBILITY_DISTANCE);
956 if(m_MaxVisibleDistanceForCreature < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
958 sLog.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
959 m_MaxVisibleDistanceForCreature = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
961 else if(m_MaxVisibleDistanceForCreature + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
963 sLog.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
964 m_MaxVisibleDistanceForCreature = MAX_VISIBILITY_DISTANCE-m_VisibleUnitGreyDistance;
966 m_MaxVisibleDistanceForPlayer = sConfig.GetFloatDefault("Visibility.Distance.Player", DEFAULT_VISIBILITY_DISTANCE);
967 if(m_MaxVisibleDistanceForPlayer < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
969 sLog.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
970 m_MaxVisibleDistanceForPlayer = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
972 else if(m_MaxVisibleDistanceForPlayer + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
974 sLog.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
975 m_MaxVisibleDistanceForPlayer = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
977 m_MaxVisibleDistanceForObject = sConfig.GetFloatDefault("Visibility.Distance.Gameobject", DEFAULT_VISIBILITY_DISTANCE);
978 if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
980 sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
981 m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
983 else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
985 sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
986 m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
988 m_MaxVisibleDistanceInFlight = sConfig.GetFloatDefault("Visibility.Distance.InFlight", DEFAULT_VISIBILITY_DISTANCE);
989 if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
991 sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
992 m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
995 ///- Read the "Data" directory from the config file
996 std::string dataPath = sConfig.GetStringDefault("DataDir","./");
997 if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
998 dataPath.append("/");
1000 if(reload)
1002 if(dataPath!=m_dataPath)
1003 sLog.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath.c_str());
1005 else
1007 m_dataPath = dataPath;
1008 sLog.outString("Using DataDir %s",m_dataPath.c_str());
1011 bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
1012 bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
1013 std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
1014 std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
1015 VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
1016 VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
1017 VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
1018 VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
1019 sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
1020 sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
1021 sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
1024 /// Initialize the World
1025 void World::SetInitialWorldSettings()
1027 ///- Initialize the random number generator
1028 srand((unsigned int)time(NULL));
1030 ///- Initialize config settings
1031 LoadConfigSettings();
1033 ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
1034 objmgr.SetHighestGuids();
1036 ///- Check the existence of the map files for all races' startup areas.
1037 if( !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
1038 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
1039 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
1040 ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
1041 ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
1042 ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
1043 ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
1044 ||m_configs[CONFIG_EXPANSION] && (
1045 !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
1047 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());
1048 exit(1);
1051 ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
1052 sLog.outString( "" );
1053 sLog.outString( "Loading MaNGOS strings..." );
1054 if (!objmgr.LoadMangosStrings())
1055 exit(1); // Error message displayed in function already
1057 ///- Update the realm entry in the database with the realm type from the config file
1058 //No SQL injection as values are treated as integers
1060 // not send custom type REALM_FFA_PVP to realm list
1061 uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
1062 uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
1063 loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
1065 ///- Remove the bones after a restart
1066 CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
1068 ///- Load the DBC files
1069 sLog.outString("Initialize data stores...");
1070 LoadDBCStores(m_dataPath);
1071 DetectDBCLang();
1073 sLog.outString( "Loading Script Names...");
1074 objmgr.LoadScriptNames();
1076 sLog.outString( "Loading InstanceTemplate..." );
1077 objmgr.LoadInstanceTemplate();
1079 sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
1080 spellmgr.LoadSkillLineAbilityMap();
1082 ///- Clean up and pack instances
1083 sLog.outString( "Cleaning up instances..." );
1084 sInstanceSaveManager.CleanupInstances(); // must be called before `creature_respawn`/`gameobject_respawn` tables
1086 sLog.outString( "Packing instances..." );
1087 sInstanceSaveManager.PackInstances();
1089 sLog.outString();
1090 sLog.outString( "Loading Localization strings..." );
1091 objmgr.LoadCreatureLocales();
1092 objmgr.LoadGameObjectLocales();
1093 objmgr.LoadItemLocales();
1094 objmgr.LoadQuestLocales();
1095 objmgr.LoadNpcTextLocales();
1096 objmgr.LoadPageTextLocales();
1097 objmgr.LoadNpcOptionLocales();
1098 objmgr.LoadPointOfInterestLocales();
1099 objmgr.SetDBCLocaleIndex(GetDefaultDbcLocale()); // Get once for all the locale index of DBC language (console/broadcasts)
1100 sLog.outString( ">>> Localization strings loaded" );
1101 sLog.outString();
1103 sLog.outString( "Loading Page Texts..." );
1104 objmgr.LoadPageTexts();
1106 sLog.outString( "Loading Game Object Templates..." ); // must be after LoadPageTexts
1107 objmgr.LoadGameobjectInfo();
1109 sLog.outString( "Loading Spell Chain Data..." );
1110 spellmgr.LoadSpellChains();
1112 sLog.outString( "Loading Spell Elixir types..." );
1113 spellmgr.LoadSpellElixirs();
1115 sLog.outString( "Loading Spell Learn Skills..." );
1116 spellmgr.LoadSpellLearnSkills(); // must be after LoadSpellChains
1118 sLog.outString( "Loading Spell Learn Spells..." );
1119 spellmgr.LoadSpellLearnSpells();
1121 sLog.outString( "Loading Spell Proc Event conditions..." );
1122 spellmgr.LoadSpellProcEvents();
1124 sLog.outString( "Loading Spell Bonus Data..." );
1125 spellmgr.LoadSpellBonusess();
1127 sLog.outString( "Loading Aggro Spells Definitions...");
1128 spellmgr.LoadSpellThreats();
1130 sLog.outString( "Loading NPC Texts..." );
1131 objmgr.LoadGossipText();
1133 sLog.outString( "Loading Item Random Enchantments Table..." );
1134 LoadRandomEnchantmentsTable();
1136 sLog.outString( "Loading Items..." ); // must be after LoadRandomEnchantmentsTable and LoadPageTexts
1137 objmgr.LoadItemPrototypes();
1139 sLog.outString( "Loading Item Texts..." );
1140 objmgr.LoadItemTexts();
1142 sLog.outString( "Loading Creature Model Based Info Data..." );
1143 objmgr.LoadCreatureModelInfo();
1145 sLog.outString( "Loading Equipment templates...");
1146 objmgr.LoadEquipmentTemplates();
1148 sLog.outString( "Loading Creature templates..." );
1149 objmgr.LoadCreatureTemplates();
1151 sLog.outString( "Loading SpellsScriptTarget...");
1152 spellmgr.LoadSpellScriptTarget(); // must be after LoadCreatureTemplates and LoadGameobjectInfo
1154 sLog.outString( "Loading Creature Reputation OnKill Data..." );
1155 objmgr.LoadReputationOnKill();
1157 sLog.outString( "Loading Points Of Interest Data..." );
1158 objmgr.LoadPointsOfInterest();
1160 sLog.outString( "Loading Pet Create Spells..." );
1161 objmgr.LoadPetCreateSpells();
1163 sLog.outString( "Loading Creature Data..." );
1164 objmgr.LoadCreatures();
1166 sLog.outString( "Loading Creature Addon Data..." );
1167 sLog.outString();
1168 objmgr.LoadCreatureAddons(); // must be after LoadCreatureTemplates() and LoadCreatures()
1169 sLog.outString( ">>> Creature Addon Data loaded" );
1170 sLog.outString();
1172 sLog.outString( "Loading Creature Respawn Data..." ); // must be after PackInstances()
1173 objmgr.LoadCreatureRespawnTimes();
1175 sLog.outString( "Loading Gameobject Data..." );
1176 objmgr.LoadGameobjects();
1178 sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1179 objmgr.LoadGameobjectRespawnTimes();
1181 sLog.outString( "Loading Objects Pooling Data...");
1182 poolhandler.LoadFromDB();
1184 sLog.outString( "Loading Game Event Data...");
1185 sLog.outString();
1186 gameeventmgr.LoadFromDB();
1187 sLog.outString( ">>> Game Event Data loaded" );
1188 sLog.outString();
1190 sLog.outString( "Loading Weather Data..." );
1191 objmgr.LoadWeatherZoneChances();
1193 sLog.outString( "Loading Quests..." );
1194 objmgr.LoadQuests(); // must be loaded after DBCs, creature_template, item_template, gameobject tables
1196 sLog.outString( "Loading Quests Relations..." );
1197 sLog.outString();
1198 objmgr.LoadQuestRelations(); // must be after quest load
1199 sLog.outString( ">>> Quests Relations loaded" );
1200 sLog.outString();
1202 sLog.outString( "Loading AreaTrigger definitions..." );
1203 objmgr.LoadAreaTriggerTeleports(); // must be after item template load
1205 sLog.outString( "Loading Quest Area Triggers..." );
1206 objmgr.LoadQuestAreaTriggers(); // must be after LoadQuests
1208 sLog.outString( "Loading Tavern Area Triggers..." );
1209 objmgr.LoadTavernAreaTriggers();
1211 sLog.outString( "Loading AreaTrigger script names..." );
1212 objmgr.LoadAreaTriggerScripts();
1214 sLog.outString( "Loading Graveyard-zone links...");
1215 objmgr.LoadGraveyardZones();
1217 sLog.outString( "Loading Spell target coordinates..." );
1218 spellmgr.LoadSpellTargetPositions();
1220 sLog.outString( "Loading SpellAffect definitions..." );
1221 spellmgr.LoadSpellAffects();
1223 sLog.outString( "Loading spell pet auras..." );
1224 spellmgr.LoadSpellPetAuras();
1226 sLog.outString( "Loading pet levelup spells..." );
1227 spellmgr.LoadPetLevelupSpellMap();
1229 sLog.outString( "Loading Player Create Info & Level Stats..." );
1230 sLog.outString();
1231 objmgr.LoadPlayerInfo();
1232 sLog.outString( ">>> Player Create Info & Level Stats loaded" );
1233 sLog.outString();
1235 sLog.outString( "Loading Exploration BaseXP Data..." );
1236 objmgr.LoadExplorationBaseXP();
1238 sLog.outString( "Loading Pet Name Parts..." );
1239 objmgr.LoadPetNames();
1241 sLog.outString( "Loading the max pet number..." );
1242 objmgr.LoadPetNumber();
1244 sLog.outString( "Loading pet level stats..." );
1245 objmgr.LoadPetLevelInfo();
1247 sLog.outString( "Loading Player Corpses..." );
1248 objmgr.LoadCorpses();
1250 sLog.outString( "Loading Loot Tables..." );
1251 sLog.outString();
1252 LoadLootTables();
1253 sLog.outString( ">>> Loot Tables loaded" );
1254 sLog.outString();
1256 sLog.outString( "Loading Skill Discovery Table..." );
1257 LoadSkillDiscoveryTable();
1259 sLog.outString( "Loading Skill Extra Item Table..." );
1260 LoadSkillExtraItemTable();
1262 sLog.outString( "Loading Skill Fishing base level requirements..." );
1263 objmgr.LoadFishingBaseSkillLevel();
1265 sLog.outString( "Loading Achievements..." );
1266 sLog.outString();
1267 achievementmgr.LoadAchievementCriteriaList();
1268 achievementmgr.LoadRewards();
1269 achievementmgr.LoadRewardLocales();
1270 achievementmgr.LoadCompletedAchievements();
1271 sLog.outString( ">>> Achievements loaded" );
1272 sLog.outString();
1274 ///- Load dynamic data tables from the database
1275 sLog.outString( "Loading Auctions..." );
1276 sLog.outString();
1277 auctionmgr.LoadAuctionItems();
1278 auctionmgr.LoadAuctions();
1279 sLog.outString( ">>> Auctions loaded" );
1280 sLog.outString();
1282 sLog.outString( "Loading Guilds..." );
1283 objmgr.LoadGuilds();
1285 sLog.outString( "Loading ArenaTeams..." );
1286 objmgr.LoadArenaTeams();
1288 sLog.outString( "Loading Groups..." );
1289 objmgr.LoadGroups();
1291 sLog.outString( "Loading ReservedNames..." );
1292 objmgr.LoadReservedPlayersNames();
1294 sLog.outString( "Loading GameObjects for quests..." );
1295 objmgr.LoadGameObjectForQuests();
1297 sLog.outString( "Loading BattleMasters..." );
1298 sBattleGroundMgr.LoadBattleMastersEntry();
1300 sLog.outString( "Loading GameTeleports..." );
1301 objmgr.LoadGameTele();
1303 sLog.outString( "Loading Npc Text Id..." );
1304 objmgr.LoadNpcTextId(); // must be after load Creature and NpcText
1306 sLog.outString( "Loading Npc Options..." );
1307 objmgr.LoadNpcOptions();
1309 sLog.outString( "Loading Vendors..." );
1310 objmgr.LoadVendors(); // must be after load CreatureTemplate and ItemTemplate
1312 sLog.outString( "Loading Trainers..." );
1313 objmgr.LoadTrainerSpell(); // must be after load CreatureTemplate
1315 sLog.outString( "Loading Waypoints..." );
1316 sLog.outString();
1317 WaypointMgr.Load();
1319 sLog.outString( "Loading GM tickets...");
1320 ticketmgr.LoadGMTickets();
1322 ///- Handle outdated emails (delete/return)
1323 sLog.outString( "Returning old mails..." );
1324 objmgr.ReturnOrDeleteOldMails(false);
1326 ///- Load and initialize scripts
1327 sLog.outString( "Loading Scripts..." );
1328 sLog.outString();
1329 objmgr.LoadQuestStartScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1330 objmgr.LoadQuestEndScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1331 objmgr.LoadSpellScripts(); // must be after load Creature/Gameobject(Template/Data)
1332 objmgr.LoadGameObjectScripts(); // must be after load Creature/Gameobject(Template/Data)
1333 objmgr.LoadEventScripts(); // must be after load Creature/Gameobject(Template/Data)
1334 sLog.outString( ">>> Scripts loaded" );
1335 sLog.outString();
1337 sLog.outString( "Loading Scripts text locales..." ); // must be after Load*Scripts calls
1338 objmgr.LoadDbScriptStrings();
1340 sLog.outString( "Initializing Scripts..." );
1341 if(!LoadScriptingModule())
1342 exit(1);
1344 ///- Initialize game time and timers
1345 sLog.outString( "DEBUG:: Initialize game time and timers" );
1346 m_gameTime = time(NULL);
1347 m_startTime=m_gameTime;
1349 tm local;
1350 time_t curr;
1351 time(&curr);
1352 local=*(localtime(&curr)); // dereference and assign
1353 char isoDate[128];
1354 sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1355 local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1357 WorldDatabase.PExecute("INSERT INTO uptime (startstring, starttime, uptime) VALUES('%s', " I64FMTD ", 0)",
1358 isoDate, uint64(m_startTime));
1360 m_timers[WUPDATE_OBJECTS].SetInterval(0);
1361 m_timers[WUPDATE_SESSIONS].SetInterval(0);
1362 m_timers[WUPDATE_WEATHERS].SetInterval(1000);
1363 m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*1000); //set auction update interval to 1 minute
1364 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
1365 //Update "uptime" table based on configuration entry in minutes.
1366 m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*1000); //erase corpses every 20 minutes
1368 //to set mailtimer to return mails every day between 4 and 5 am
1369 //mailtimer is increased when updating auctions
1370 //one second is 1000 -(tested on win system)
1371 mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * 1000) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1372 //1440
1373 mail_timer_expires = ( (DAY * 1000) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1374 sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1376 ///- Initilize static helper structures
1377 AIRegistry::Initialize();
1378 WaypointMovementGenerator<Creature>::Initialize();
1379 Player::InitVisibleBits();
1381 ///- Initialize MapManager
1382 sLog.outString( "Starting Map System" );
1383 MapManager::Instance().Initialize();
1385 ///- Initialize Battlegrounds
1386 sLog.outString( "Starting BattleGround System" );
1387 sBattleGroundMgr.CreateInitialBattleGrounds();
1388 sBattleGroundMgr.InitAutomaticArenaPointDistribution();
1390 //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1391 sLog.outString( "Loading Transports..." );
1392 MapManager::Instance().LoadTransports();
1394 sLog.outString("Deleting expired bans..." );
1395 loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1397 sLog.outString("Calculate next daily quest reset time..." );
1398 InitDailyQuestResetTime();
1400 sLog.outString("Starting objects Pooling system..." );
1401 poolhandler.Initialize();
1403 sLog.outString("Starting Game Event system..." );
1404 uint32 nextGameEvent = gameeventmgr.Initialize();
1405 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent); //depend on next event
1407 sLog.outString( "WORLD: World initialized" );
1410 void World::DetectDBCLang()
1412 uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1414 if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1416 sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1417 m_lang_confid = LOCALE_enUS;
1420 ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1422 std::string availableLocalsStr;
1424 int default_locale = MAX_LOCALE;
1425 for (int i = MAX_LOCALE-1; i >= 0; --i)
1427 if ( strlen(race->name[i]) > 0) // check by race names
1429 default_locale = i;
1430 m_availableDbcLocaleMask |= (1 << i);
1431 availableLocalsStr += localeNames[i];
1432 availableLocalsStr += " ";
1436 if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1437 (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1439 default_locale = m_lang_confid;
1442 if(default_locale >= MAX_LOCALE)
1444 sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1445 exit(1);
1448 m_defaultDbcLocale = LocaleConstant(default_locale);
1450 sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1451 sLog.outString();
1454 /// Update the World !
1455 void World::Update(uint32 diff)
1457 ///- Update the different timers
1458 for(int i = 0; i < WUPDATE_COUNT; i++)
1459 if(m_timers[i].GetCurrent()>=0)
1460 m_timers[i].Update(diff);
1461 else m_timers[i].SetCurrent(0);
1463 ///- Update the game time and check for shutdown time
1464 _UpdateGameTime();
1466 /// Handle daily quests reset time
1467 if(m_gameTime > m_NextDailyQuestReset)
1469 ResetDailyQuests();
1470 m_NextDailyQuestReset += DAY;
1473 /// <ul><li> Handle auctions when the timer has passed
1474 if (m_timers[WUPDATE_AUCTIONS].Passed())
1476 m_timers[WUPDATE_AUCTIONS].Reset();
1478 ///- Update mails (return old mails with item, or delete them)
1479 //(tested... works on win)
1480 if (++mail_timer > mail_timer_expires)
1482 mail_timer = 0;
1483 objmgr.ReturnOrDeleteOldMails(true);
1486 ///- Handle expired auctions
1487 auctionmgr.Update();
1490 /// <li> Handle session updates when the timer has passed
1491 if (m_timers[WUPDATE_SESSIONS].Passed())
1493 m_timers[WUPDATE_SESSIONS].Reset();
1495 UpdateSessions(diff);
1498 /// <li> Handle weather updates when the timer has passed
1499 if (m_timers[WUPDATE_WEATHERS].Passed())
1501 m_timers[WUPDATE_WEATHERS].Reset();
1503 ///- Send an update signal to Weather objects
1504 WeatherMap::iterator itr, next;
1505 for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1507 next = itr;
1508 ++next;
1510 ///- and remove Weather objects for zones with no player
1511 //As interval > WorldTick
1512 if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1514 delete itr->second;
1515 m_weathers.erase(itr);
1519 /// <li> Update uptime table
1520 if (m_timers[WUPDATE_UPTIME].Passed())
1522 uint32 tmpDiff = (m_gameTime - m_startTime);
1523 uint32 maxClientsNum = sWorld.GetMaxActiveSessionCount();
1525 m_timers[WUPDATE_UPTIME].Reset();
1526 WorldDatabase.PExecute("UPDATE uptime SET uptime = %d, maxplayers = %d WHERE starttime = " I64FMTD, tmpDiff, maxClientsNum, uint64(m_startTime));
1529 /// <li> Handle all other objects
1530 if (m_timers[WUPDATE_OBJECTS].Passed())
1532 m_timers[WUPDATE_OBJECTS].Reset();
1533 ///- Update objects when the timer has passed (maps, transport, creatures,...)
1534 MapManager::Instance().Update(diff); // As interval = 0
1536 ///- Process necessary scripts
1537 if (!m_scriptSchedule.empty())
1538 ScriptsProcess();
1540 sBattleGroundMgr.Update(diff);
1543 // execute callbacks from sql queries that were queued recently
1544 UpdateResultQueue();
1546 ///- Erase corpses once every 20 minutes
1547 if (m_timers[WUPDATE_CORPSES].Passed())
1549 m_timers[WUPDATE_CORPSES].Reset();
1551 CorpsesErase();
1554 ///- Process Game events when necessary
1555 if (m_timers[WUPDATE_EVENTS].Passed())
1557 m_timers[WUPDATE_EVENTS].Reset(); // to give time for Update() to be processed
1558 uint32 nextGameEvent = gameeventmgr.Update();
1559 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1560 m_timers[WUPDATE_EVENTS].Reset();
1563 /// </ul>
1564 ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1565 MapManager::Instance().DoDelayedMovesAndRemoves();
1567 // update the instance reset times
1568 sInstanceSaveManager.Update();
1570 // And last, but not least handle the issued cli commands
1571 ProcessCliCommands();
1574 /// Put scripts in the execution queue
1575 void World::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
1577 ///- Find the script map
1578 ScriptMapMap::const_iterator s = scripts.find(id);
1579 if (s == scripts.end())
1580 return;
1582 // prepare static data
1583 uint64 sourceGUID = source->GetGUID();
1584 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1585 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1587 ///- Schedule script execution for all scripts in the script map
1588 ScriptMap const *s2 = &(s->second);
1589 bool immedScript = false;
1590 for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
1592 ScriptAction sa;
1593 sa.sourceGUID = sourceGUID;
1594 sa.targetGUID = targetGUID;
1595 sa.ownerGUID = ownerGUID;
1597 sa.script = &iter->second;
1598 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + iter->first, sa));
1599 if (iter->first == 0)
1600 immedScript = true;
1602 ///- If one of the effects should be immediate, launch the script execution
1603 if (immedScript)
1604 ScriptsProcess();
1607 void World::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
1609 // NOTE: script record _must_ exist until command executed
1611 // prepare static data
1612 uint64 sourceGUID = source->GetGUID();
1613 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1614 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1616 ScriptAction sa;
1617 sa.sourceGUID = sourceGUID;
1618 sa.targetGUID = targetGUID;
1619 sa.ownerGUID = ownerGUID;
1621 sa.script = &script;
1622 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + delay, sa));
1624 ///- If effects should be immediate, launch the script execution
1625 if(delay == 0)
1626 ScriptsProcess();
1629 /// Process queued scripts
1630 void World::ScriptsProcess()
1632 if (m_scriptSchedule.empty())
1633 return;
1635 ///- Process overdue queued scripts
1636 std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
1637 // ok as multimap is a *sorted* associative container
1638 while (!m_scriptSchedule.empty() && (iter->first <= m_gameTime))
1640 ScriptAction const& step = iter->second;
1642 Object* source = NULL;
1644 if(step.sourceGUID)
1646 switch(GUID_HIPART(step.sourceGUID))
1648 case HIGHGUID_ITEM:
1649 // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1651 Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
1652 if(player)
1653 source = player->GetItemByGuid(step.sourceGUID);
1654 break;
1656 case HIGHGUID_UNIT:
1657 source = HashMapHolder<Creature>::Find(step.sourceGUID);
1658 break;
1659 case HIGHGUID_PET:
1660 source = HashMapHolder<Pet>::Find(step.sourceGUID);
1661 break;
1662 case HIGHGUID_VEHICLE:
1663 source = HashMapHolder<Vehicle>::Find(step.sourceGUID);
1664 break;
1665 case HIGHGUID_PLAYER:
1666 source = HashMapHolder<Player>::Find(step.sourceGUID);
1667 break;
1668 case HIGHGUID_GAMEOBJECT:
1669 source = HashMapHolder<GameObject>::Find(step.sourceGUID);
1670 break;
1671 case HIGHGUID_CORPSE:
1672 source = HashMapHolder<Corpse>::Find(step.sourceGUID);
1673 break;
1674 default:
1675 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
1676 break;
1680 if(source && !source->IsInWorld()) source = NULL;
1682 Object* target = NULL;
1684 if(step.targetGUID)
1686 switch(GUID_HIPART(step.targetGUID))
1688 case HIGHGUID_UNIT:
1689 target = HashMapHolder<Creature>::Find(step.targetGUID);
1690 break;
1691 case HIGHGUID_PET:
1692 target = HashMapHolder<Pet>::Find(step.targetGUID);
1693 break;
1694 case HIGHGUID_VEHICLE:
1695 target = HashMapHolder<Vehicle>::Find(step.targetGUID);
1696 break;
1697 case HIGHGUID_PLAYER: // empty GUID case also
1698 target = HashMapHolder<Player>::Find(step.targetGUID);
1699 break;
1700 case HIGHGUID_GAMEOBJECT:
1701 target = HashMapHolder<GameObject>::Find(step.targetGUID);
1702 break;
1703 case HIGHGUID_CORPSE:
1704 target = HashMapHolder<Corpse>::Find(step.targetGUID);
1705 break;
1706 default:
1707 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
1708 break;
1712 if(target && !target->IsInWorld()) target = NULL;
1714 switch (step.script->command)
1716 case SCRIPT_COMMAND_TALK:
1718 if(!source)
1720 sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1721 break;
1724 if(source->GetTypeId()!=TYPEID_UNIT)
1726 sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1727 break;
1730 uint64 unit_target = target ? target->GetGUID() : 0;
1732 //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1733 switch(step.script->datalong)
1735 case 0: // Say
1736 ((Creature *)source)->Say(step.script->dataint, LANG_UNIVERSAL, unit_target);
1737 break;
1738 case 1: // Whisper
1739 if(!unit_target)
1741 sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
1742 break;
1744 ((Creature *)source)->Whisper(step.script->dataint,unit_target);
1745 break;
1746 case 2: // Yell
1747 ((Creature *)source)->Yell(step.script->dataint, LANG_UNIVERSAL, unit_target);
1748 break;
1749 case 3: // Emote text
1750 ((Creature *)source)->TextEmote(step.script->dataint, unit_target);
1751 break;
1752 default:
1753 break; // must be already checked at load
1755 break;
1758 case SCRIPT_COMMAND_EMOTE:
1759 if(!source)
1761 sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1762 break;
1765 if(source->GetTypeId()!=TYPEID_UNIT)
1767 sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1768 break;
1771 ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
1772 break;
1773 case SCRIPT_COMMAND_FIELD_SET:
1774 if(!source)
1776 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1777 break;
1779 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1781 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1782 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1783 break;
1786 source->SetUInt32Value(step.script->datalong, step.script->datalong2);
1787 break;
1788 case SCRIPT_COMMAND_MOVE_TO:
1789 if(!source)
1791 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1792 break;
1795 if(source->GetTypeId()!=TYPEID_UNIT)
1797 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1798 break;
1800 ((Unit *)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, ((Unit *)source)->GetUnitMovementFlags(), step.script->datalong2 );
1801 ((Unit *)source)->GetMap()->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
1802 break;
1803 case SCRIPT_COMMAND_FLAG_SET:
1804 if(!source)
1806 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1807 break;
1809 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1811 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1812 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1813 break;
1816 source->SetFlag(step.script->datalong, step.script->datalong2);
1817 break;
1818 case SCRIPT_COMMAND_FLAG_REMOVE:
1819 if(!source)
1821 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1822 break;
1824 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1826 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1827 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1828 break;
1831 source->RemoveFlag(step.script->datalong, step.script->datalong2);
1832 break;
1834 case SCRIPT_COMMAND_TELEPORT_TO:
1836 // accept player in any one from target/source arg
1837 if (!target && !source)
1839 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1840 break;
1843 // must be only Player
1844 if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
1846 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
1847 break;
1850 Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
1852 pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
1853 break;
1856 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
1858 if(!step.script->datalong) // creature not specified
1860 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1861 break;
1864 if(!source)
1866 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1867 break;
1870 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1872 if(!summoner)
1874 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1875 break;
1878 float x = step.script->x;
1879 float y = step.script->y;
1880 float z = step.script->z;
1881 float o = step.script->o;
1883 Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
1884 if (!pCreature)
1886 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
1887 break;
1890 break;
1893 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
1895 if(!step.script->datalong) // gameobject not specified
1897 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1898 break;
1901 if(!source)
1903 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1904 break;
1907 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1909 if(!summoner)
1911 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1912 break;
1915 GameObject *go = NULL;
1916 int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
1918 CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
1919 Cell cell(p);
1920 cell.data.Part.reserved = ALL_DISTRICT;
1922 MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
1923 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(summoner, go,go_check);
1925 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1926 CellLock<GridReadGuard> cell_lock(cell, p);
1927 cell_lock->Visit(cell_lock, object_checker, *summoner->GetMap());
1929 if ( !go )
1931 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
1932 break;
1935 if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1936 go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1937 go->GetGoType()==GAMEOBJECT_TYPE_DOOR ||
1938 go->GetGoType()==GAMEOBJECT_TYPE_BUTTON ||
1939 go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
1941 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
1942 break;
1945 if( go->isSpawned() )
1946 break; //gameobject already spawned
1948 go->SetLootState(GO_READY);
1949 go->SetRespawnTime(time_to_despawn); //despawn object in ? seconds
1951 go->GetMap()->Add(go);
1952 break;
1954 case SCRIPT_COMMAND_OPEN_DOOR:
1956 if(!step.script->datalong) // door not specified
1958 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1959 break;
1962 if(!source)
1964 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1965 break;
1968 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
1970 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1971 break;
1974 Unit* caster = (Unit*)source;
1976 GameObject *door = NULL;
1977 int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1979 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1980 Cell cell(p);
1981 cell.data.Part.reserved = ALL_DISTRICT;
1983 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1984 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(caster,door,go_check);
1986 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1987 CellLock<GridReadGuard> cell_lock(cell, p);
1988 cell_lock->Visit(cell_lock, object_checker, *caster->GetMap());
1990 if ( !door )
1992 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1993 break;
1995 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1997 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1998 break;
2001 if( !door->GetGoState() )
2002 break; //door already open
2004 door->UseDoorOrButton(time_to_close);
2006 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
2007 ((GameObject*)target)->UseDoorOrButton(time_to_close);
2008 break;
2010 case SCRIPT_COMMAND_CLOSE_DOOR:
2012 if(!step.script->datalong) // guid for door not specified
2014 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
2015 break;
2018 if(!source)
2020 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
2021 break;
2024 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
2026 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
2027 break;
2030 Unit* caster = (Unit*)source;
2032 GameObject *door = NULL;
2033 int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
2035 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
2036 Cell cell(p);
2037 cell.data.Part.reserved = ALL_DISTRICT;
2039 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
2040 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(caster,door,go_check);
2042 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
2043 CellLock<GridReadGuard> cell_lock(cell, p);
2044 cell_lock->Visit(cell_lock, object_checker, *caster->GetMap());
2046 if ( !door )
2048 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
2049 break;
2051 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
2053 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
2054 break;
2057 if( door->GetGoState() )
2058 break; //door already closed
2060 door->UseDoorOrButton(time_to_open);
2062 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
2063 ((GameObject*)target)->UseDoorOrButton(time_to_open);
2065 break;
2067 case SCRIPT_COMMAND_QUEST_EXPLORED:
2069 if(!source)
2071 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
2072 break;
2075 if(!target)
2077 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
2078 break;
2081 // when script called for item spell casting then target == (unit or GO) and source is player
2082 WorldObject* worldObject;
2083 Player* player;
2085 if(target->GetTypeId()==TYPEID_PLAYER)
2087 if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
2089 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
2090 break;
2093 worldObject = (WorldObject*)source;
2094 player = (Player*)target;
2096 else
2098 if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
2100 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
2101 break;
2104 if(source->GetTypeId()!=TYPEID_PLAYER)
2106 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
2107 break;
2110 worldObject = (WorldObject*)target;
2111 player = (Player*)source;
2114 // quest id and flags checked at script loading
2115 if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
2116 (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
2117 player->AreaExploredOrEventHappens(step.script->datalong);
2118 else
2119 player->FailQuest(step.script->datalong);
2121 break;
2124 case SCRIPT_COMMAND_ACTIVATE_OBJECT:
2126 if(!source)
2128 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
2129 break;
2132 if(!source->isType(TYPEMASK_UNIT))
2134 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2135 break;
2138 if(!target)
2140 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
2141 break;
2144 if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
2146 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
2147 break;
2150 Unit* caster = (Unit*)source;
2152 GameObject *go = (GameObject*)target;
2154 go->Use(caster);
2155 break;
2158 case SCRIPT_COMMAND_REMOVE_AURA:
2160 Object* cmdTarget = step.script->datalong2 ? source : target;
2162 if(!cmdTarget)
2164 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
2165 break;
2168 if(!cmdTarget->isType(TYPEMASK_UNIT))
2170 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2171 break;
2174 ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
2175 break;
2178 case SCRIPT_COMMAND_CAST_SPELL:
2180 if(!source)
2182 sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
2183 break;
2186 if(!source->isType(TYPEMASK_UNIT))
2188 sLog.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2189 break;
2192 Object* cmdTarget = step.script->datalong2 ? source : target;
2194 if(!cmdTarget)
2196 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 ? "source" : "target");
2197 break;
2200 if(!cmdTarget->isType(TYPEMASK_UNIT))
2202 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2203 break;
2206 Unit* spellTarget = (Unit*)cmdTarget;
2208 //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2209 ((Unit*)source)->CastSpell(spellTarget,step.script->datalong,false);
2211 break;
2214 default:
2215 sLog.outError("Unknown script command %u called.",step.script->command);
2216 break;
2219 m_scriptSchedule.erase(iter);
2221 iter = m_scriptSchedule.begin();
2223 return;
2226 /// Send a packet to all players (except self if mentioned)
2227 void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
2229 SessionMap::iterator itr;
2230 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2232 if (itr->second &&
2233 itr->second->GetPlayer() &&
2234 itr->second->GetPlayer()->IsInWorld() &&
2235 itr->second != self &&
2236 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2238 itr->second->SendPacket(packet);
2243 /// Send a System Message to all players (except self if mentioned)
2244 void World::SendWorldText(int32 string_id, ...)
2246 std::vector<std::vector<WorldPacket*> > data_cache; // 0 = default, i => i-1 locale index
2248 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2250 if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
2251 continue;
2253 uint32 loc_idx = itr->second->GetSessionDbLocaleIndex();
2254 uint32 cache_idx = loc_idx+1;
2256 std::vector<WorldPacket*>* data_list;
2258 // create if not cached yet
2259 if(data_cache.size() < cache_idx+1 || data_cache[cache_idx].empty())
2261 if(data_cache.size() < cache_idx+1)
2262 data_cache.resize(cache_idx+1);
2264 data_list = &data_cache[cache_idx];
2266 char const* text = objmgr.GetMangosString(string_id,loc_idx);
2268 char buf[1000];
2270 va_list argptr;
2271 va_start( argptr, string_id );
2272 vsnprintf( buf,1000, text, argptr );
2273 va_end( argptr );
2275 char* pos = &buf[0];
2277 while(char* line = ChatHandler::LineFromMessage(pos))
2279 WorldPacket* data = new WorldPacket();
2280 ChatHandler::FillMessageData(data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2281 data_list->push_back(data);
2284 else
2285 data_list = &data_cache[cache_idx];
2287 for(int i = 0; i < data_list->size(); ++i)
2288 itr->second->SendPacket((*data_list)[i]);
2291 // free memory
2292 for(int i = 0; i < data_cache.size(); ++i)
2293 for(int j = 0; j < data_cache[i].size(); ++j)
2294 delete data_cache[i][j];
2297 /// DEPRICATED, only for debug purpose. Send a System Message to all players (except self if mentioned)
2298 void World::SendGlobalText(const char* text, WorldSession *self)
2300 WorldPacket data;
2302 // need copy to prevent corruption by strtok call in LineFromMessage original string
2303 char* buf = strdup(text);
2304 char* pos = buf;
2306 while(char* line = ChatHandler::LineFromMessage(pos))
2308 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2309 SendGlobalMessage(&data, self);
2312 free(buf);
2315 /// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2316 void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
2318 SessionMap::iterator itr;
2319 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2321 if (itr->second &&
2322 itr->second->GetPlayer() &&
2323 itr->second->GetPlayer()->IsInWorld() &&
2324 itr->second->GetPlayer()->GetZoneId() == zone &&
2325 itr->second != self &&
2326 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2328 itr->second->SendPacket(packet);
2333 /// Send a System Message to all players in the zone (except self if mentioned)
2334 void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
2336 WorldPacket data;
2337 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
2338 SendZoneMessage(zone, &data, self,team);
2341 /// Kick (and save) all players
2342 void World::KickAll()
2344 m_QueuedPlayer.clear(); // prevent send queue update packet and login queued sessions
2346 // session not removed at kick and will removed in next update tick
2347 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2348 itr->second->KickPlayer();
2351 /// Kick (and save) all players with security level less `sec`
2352 void World::KickAllLess(AccountTypes sec)
2354 // session not removed at kick and will removed in next update tick
2355 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2356 if(itr->second->GetSecurity() < sec)
2357 itr->second->KickPlayer();
2360 /// Kick (and save) the designated player
2361 bool World::KickPlayer(const std::string& playerName)
2363 SessionMap::iterator itr;
2365 // session not removed at kick and will removed in next update tick
2366 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2368 if(!itr->second)
2369 continue;
2370 Player *player = itr->second->GetPlayer();
2371 if(!player)
2372 continue;
2373 if( player->IsInWorld() )
2375 if (playerName == player->GetName())
2377 itr->second->KickPlayer();
2378 return true;
2382 return false;
2385 /// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2386 BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, std::string duration, std::string reason, std::string author)
2388 loginDatabase.escape_string(nameOrIP);
2389 loginDatabase.escape_string(reason);
2390 std::string safe_author=author;
2391 loginDatabase.escape_string(safe_author);
2393 uint32 duration_secs = TimeStringToSecs(duration);
2394 QueryResult *resultAccounts = NULL; //used for kicking
2396 ///- Update the database with ban information
2397 switch(mode)
2399 case BAN_IP:
2400 //No SQL injection as strings are escaped
2401 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
2402 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());
2403 break;
2404 case BAN_ACCOUNT:
2405 //No SQL injection as string is escaped
2406 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2407 break;
2408 case BAN_CHARACTER:
2409 //No SQL injection as string is escaped
2410 resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2411 break;
2412 default:
2413 return BAN_SYNTAX_ERROR;
2416 if(!resultAccounts)
2418 if(mode==BAN_IP)
2419 return BAN_SUCCESS; // ip correctly banned but nobody affected (yet)
2420 else
2421 return BAN_NOTFOUND; // Nobody to ban
2424 ///- Disconnect all affected players (for IP it can be several)
2427 Field* fieldsAccount = resultAccounts->Fetch();
2428 uint32 account = fieldsAccount->GetUInt32();
2430 if(mode!=BAN_IP)
2432 //No SQL injection as strings are escaped
2433 loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2434 account,duration_secs,safe_author.c_str(),reason.c_str());
2437 if (WorldSession* sess = FindSession(account))
2438 if(std::string(sess->GetPlayerName()) != author)
2439 sess->KickPlayer();
2441 while( resultAccounts->NextRow() );
2443 delete resultAccounts;
2444 return BAN_SUCCESS;
2447 /// Remove a ban from an account or IP address
2448 bool World::RemoveBanAccount(BanMode mode, std::string nameOrIP)
2450 if (mode == BAN_IP)
2452 loginDatabase.escape_string(nameOrIP);
2453 loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
2455 else
2457 uint32 account = 0;
2458 if (mode == BAN_ACCOUNT)
2459 account = accmgr.GetId (nameOrIP);
2460 else if (mode == BAN_CHARACTER)
2461 account = objmgr.GetPlayerAccountIdByPlayerName (nameOrIP);
2463 if (!account)
2464 return false;
2466 //NO SQL injection as account is uint32
2467 loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
2469 return true;
2472 /// Update the game time
2473 void World::_UpdateGameTime()
2475 ///- update the time
2476 time_t thisTime = time(NULL);
2477 uint32 elapsed = uint32(thisTime - m_gameTime);
2478 m_gameTime = thisTime;
2480 ///- if there is a shutdown timer
2481 if(!m_stopEvent && m_ShutdownTimer > 0 && elapsed > 0)
2483 ///- ... and it is overdue, stop the world (set m_stopEvent)
2484 if( m_ShutdownTimer <= elapsed )
2486 if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2487 m_stopEvent = true; // exist code already set
2488 else
2489 m_ShutdownTimer = 1; // minimum timer value to wait idle state
2491 ///- ... else decrease it and if necessary display a shutdown countdown to the users
2492 else
2494 m_ShutdownTimer -= elapsed;
2496 ShutdownMsg();
2501 /// Shutdown the server
2502 void World::ShutdownServ(uint32 time, uint32 options, uint8 exitcode)
2504 // ignore if server shutdown at next tick
2505 if(m_stopEvent)
2506 return;
2508 m_ShutdownMask = options;
2509 m_ExitCode = exitcode;
2511 ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2512 if(time==0)
2514 if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2515 m_stopEvent = true; // exist code already set
2516 else
2517 m_ShutdownTimer = 1; //So that the session count is re-evaluated at next world tick
2519 ///- Else set the shutdown timer and warn users
2520 else
2522 m_ShutdownTimer = time;
2523 ShutdownMsg(true);
2527 /// Display a shutdown message to the user(s)
2528 void World::ShutdownMsg(bool show, Player* player)
2530 // not show messages for idle shutdown mode
2531 if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
2532 return;
2534 ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2535 if ( show ||
2536 (m_ShutdownTimer < 10) ||
2537 // < 30 sec; every 5 sec
2538 (m_ShutdownTimer<30 && (m_ShutdownTimer % 5 )==0) ||
2539 // < 5 min ; every 1 min
2540 (m_ShutdownTimer<5*MINUTE && (m_ShutdownTimer % MINUTE )==0) ||
2541 // < 30 min ; every 5 min
2542 (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
2543 // < 12 h ; every 1 h
2544 (m_ShutdownTimer<12*HOUR && (m_ShutdownTimer % HOUR )==0) ||
2545 // > 12 h ; every 12 h
2546 (m_ShutdownTimer>12*HOUR && (m_ShutdownTimer % (12*HOUR) )==0))
2548 std::string str = secsToTimeString(m_ShutdownTimer);
2550 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
2552 SendServerMessage(msgid,str.c_str(),player);
2553 DEBUG_LOG("Server is %s in %s",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"),str.c_str());
2557 /// Cancel a planned server shutdown
2558 void World::ShutdownCancel()
2560 // nothing cancel or too later
2561 if(!m_ShutdownTimer || m_stopEvent)
2562 return;
2564 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2566 m_ShutdownMask = 0;
2567 m_ShutdownTimer = 0;
2568 m_ExitCode = SHUTDOWN_EXIT_CODE; // to default value
2569 SendServerMessage(msgid);
2571 DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2574 /// Send a server message to the user(s)
2575 void World::SendServerMessage(uint32 type, const char *text, Player* player)
2577 WorldPacket data(SMSG_SERVER_MESSAGE, 50); // guess size
2578 data << uint32(type);
2579 if(type <= SERVER_MSG_STRING)
2580 data << text;
2582 if(player)
2583 player->GetSession()->SendPacket(&data);
2584 else
2585 SendGlobalMessage( &data );
2588 void World::UpdateSessions( uint32 diff )
2590 ///- Add new sessions
2591 while(!addSessQueue.empty())
2593 WorldSession* sess = addSessQueue.next ();
2594 AddSession_ (sess);
2597 ///- Then send an update signal to remaining ones
2598 for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2600 next = itr;
2601 ++next;
2603 if(!itr->second)
2604 continue;
2606 ///- and remove not active sessions from the list
2607 if(!itr->second->Update(diff)) // As interval = 0
2609 RemoveQueuedPlayer (itr->second);
2610 delete itr->second;
2611 m_sessions.erase(itr);
2616 // This handles the issued and queued CLI commands
2617 void World::ProcessCliCommands()
2619 if (cliCmdQueue.empty())
2620 return;
2622 CliCommandHolder::Print* zprint;
2624 while (!cliCmdQueue.empty())
2626 sLog.outDebug("CLI command under processing...");
2627 CliCommandHolder *command = cliCmdQueue.next();
2629 zprint = command->m_print;
2631 CliHandler(zprint).ParseCommands(command->m_command);
2633 delete command;
2636 // print the console message here so it looks right
2637 zprint("mangos>");
2640 void World::InitResultQueue()
2642 m_resultQueue = new SqlResultQueue;
2643 CharacterDatabase.SetResultQueue(m_resultQueue);
2646 void World::UpdateResultQueue()
2648 m_resultQueue->Update();
2651 void World::UpdateRealmCharCount(uint32 accountId)
2653 CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2654 "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2657 void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2659 if (resultCharCount)
2661 Field *fields = resultCharCount->Fetch();
2662 uint32 charCount = fields[0].GetUInt32();
2663 delete resultCharCount;
2664 loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2665 loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2669 void World::InitDailyQuestResetTime()
2671 time_t mostRecentQuestTime;
2673 QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2674 if(result)
2676 Field *fields = result->Fetch();
2678 mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2679 delete result;
2681 else
2682 mostRecentQuestTime = 0;
2684 // client built-in time for reset is 6:00 AM
2685 // FIX ME: client not show day start time
2686 time_t curTime = time(NULL);
2687 tm localTm = *localtime(&curTime);
2688 localTm.tm_hour = 6;
2689 localTm.tm_min = 0;
2690 localTm.tm_sec = 0;
2692 // current day reset time
2693 time_t curDayResetTime = mktime(&localTm);
2695 // last reset time before current moment
2696 time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2698 // need reset (if we have quest time before last reset time (not processed by some reason)
2699 if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2700 m_NextDailyQuestReset = mostRecentQuestTime;
2701 else
2703 // plan next reset time
2704 m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2708 void World::ResetDailyQuests()
2710 sLog.outDetail("Daily quests reset for all characters.");
2711 CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2712 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2713 if(itr->second->GetPlayer())
2714 itr->second->GetPlayer()->ResetDailyQuestStatus();
2717 void World::SetPlayerLimit( int32 limit, bool needUpdate )
2719 if(limit < -SEC_ADMINISTRATOR)
2720 limit = -SEC_ADMINISTRATOR;
2722 // lock update need
2723 bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2725 m_playerLimit = limit;
2727 if(db_update_need)
2728 loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2731 void World::UpdateMaxSessionCounters()
2733 m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2734 m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2737 void World::LoadDBVersion()
2739 QueryResult* result = WorldDatabase.Query("SELECT version FROM db_version LIMIT 1");
2740 if(result)
2742 Field* fields = result->Fetch();
2744 m_DBVersion = fields[0].GetString();
2745 delete result;
2747 else
2748 m_DBVersion = "unknown world database";