Replace hardcoded client(100) and server side (255) level limtation values by defines.
[getmangos.git] / src / game / World.cpp
blobe6623a29a1dc6a977c3c5307e50d99be51bd8529
1 /*
2 * Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 /** \file
20 \ingroup world
23 #include "Common.h"
24 //#include "WorldSocket.h"
25 #include "Database/DatabaseEnv.h"
26 #include "Config/ConfigEnv.h"
27 #include "SystemConfig.h"
28 #include "Log.h"
29 #include "Opcodes.h"
30 #include "WorldSession.h"
31 #include "WorldPacket.h"
32 #include "Weather.h"
33 #include "Player.h"
34 #include "SkillExtraItems.h"
35 #include "SkillDiscovery.h"
36 #include "World.h"
37 #include "AccountMgr.h"
38 #include "ObjectMgr.h"
39 #include "SpellMgr.h"
40 #include "Chat.h"
41 #include "Database/DBCStores.h"
42 #include "LootMgr.h"
43 #include "ItemEnchantmentMgr.h"
44 #include "MapManager.h"
45 #include "ScriptCalls.h"
46 #include "CreatureAIRegistry.h"
47 #include "Policies/SingletonImp.h"
48 #include "BattleGroundMgr.h"
49 #include "TemporarySummon.h"
50 #include "WaypointMovementGenerator.h"
51 #include "VMapFactory.h"
52 #include "GlobalEvents.h"
53 #include "GameEvent.h"
54 #include "Database/DatabaseImpl.h"
55 #include "GridNotifiersImpl.h"
56 #include "CellImpl.h"
57 #include "InstanceSaveMgr.h"
58 #include "WaypointManager.h"
59 #include "GMTicketMgr.h"
60 #include "Util.h"
62 INSTANTIATE_SINGLETON_1( World );
64 volatile bool World::m_stopEvent = false;
65 uint8 World::m_ExitCode = SHUTDOWN_EXIT_CODE;
66 volatile uint32 World::m_worldLoopCounter = 0;
68 float World::m_MaxVisibleDistanceForCreature = DEFAULT_VISIBILITY_DISTANCE;
69 float World::m_MaxVisibleDistanceForPlayer = DEFAULT_VISIBILITY_DISTANCE;
70 float World::m_MaxVisibleDistanceForObject = DEFAULT_VISIBILITY_DISTANCE;
71 float World::m_MaxVisibleDistanceInFlight = DEFAULT_VISIBILITY_DISTANCE;
72 float World::m_VisibleUnitGreyDistance = 0;
73 float World::m_VisibleObjectGreyDistance = 0;
75 // ServerMessages.dbc
76 enum ServerMessageType
78 SERVER_MSG_SHUTDOWN_TIME = 1,
79 SERVER_MSG_RESTART_TIME = 2,
80 SERVER_MSG_STRING = 3,
81 SERVER_MSG_SHUTDOWN_CANCELLED = 4,
82 SERVER_MSG_RESTART_CANCELLED = 5
85 struct ScriptAction
87 uint64 sourceGUID;
88 uint64 targetGUID;
89 uint64 ownerGUID; // owner of source if source is item
90 ScriptInfo const* script; // pointer to static script data
93 /// World constructor
94 World::World()
96 m_playerLimit = 0;
97 m_allowMovement = true;
98 m_ShutdownMask = 0;
99 m_ShutdownTimer = 0;
100 m_gameTime=time(NULL);
101 m_startTime=m_gameTime;
102 m_maxActiveSessionCount = 0;
103 m_maxQueuedSessionCount = 0;
104 m_resultQueue = NULL;
105 m_NextDailyQuestReset = 0;
107 m_defaultDbcLocale = LOCALE_enUS;
108 m_availableDbcLocaleMask = 0;
111 /// World destructor
112 World::~World()
114 ///- Empty the kicked session set
115 while (!m_sessions.empty())
117 // not remove from queue, prevent loading new sessions
118 delete m_sessions.begin()->second;
119 m_sessions.erase(m_sessions.begin());
122 ///- Empty the WeatherMap
123 for (WeatherMap::iterator itr = m_weathers.begin(); itr != m_weathers.end(); ++itr)
124 delete itr->second;
126 m_weathers.clear();
128 while (!cliCmdQueue.empty())
129 delete cliCmdQueue.next();
131 VMAP::VMapFactory::clear();
133 if(m_resultQueue) delete m_resultQueue;
135 //TODO free addSessQueue
138 /// Find a player in a specified zone
139 Player* World::FindPlayerInZone(uint32 zone)
141 ///- circle through active sessions and return the first player found in the zone
142 SessionMap::iterator itr;
143 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
145 if(!itr->second)
146 continue;
147 Player *player = itr->second->GetPlayer();
148 if(!player)
149 continue;
150 if( player->IsInWorld() && player->GetZoneId() == zone )
152 // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone.
153 return player;
156 return NULL;
159 /// Find a session by its id
160 WorldSession* World::FindSession(uint32 id) const
162 SessionMap::const_iterator itr = m_sessions.find(id);
164 if(itr != m_sessions.end())
165 return itr->second; // also can return NULL for kicked session
166 else
167 return NULL;
170 /// Remove a given session
171 bool World::RemoveSession(uint32 id)
173 ///- Find the session, kick the user, but we can't delete session at this moment to prevent iterator invalidation
174 SessionMap::iterator itr = m_sessions.find(id);
176 if(itr != m_sessions.end() && itr->second)
178 if (itr->second->PlayerLoading())
179 return false;
180 itr->second->KickPlayer();
183 return true;
186 void World::AddSession(WorldSession* s)
188 addSessQueue.add(s);
191 void
192 World::AddSession_ (WorldSession* s)
194 ASSERT (s);
196 //NOTE - Still there is race condition in WorldSession* being used in the Sockets
198 ///- kick already loaded player with same account (if any) and remove session
199 ///- if player is in loading and want to load again, return
200 if (!RemoveSession (s->GetAccountId ()))
202 s->KickPlayer ();
203 delete s; // session not added yet in session list, so not listed in queue
204 return;
207 // decrease session counts only at not reconnection case
208 bool decrease_session = true;
210 // if session already exist, prepare to it deleting at next world update
211 // NOTE - KickPlayer() should be called on "old" in RemoveSession()
213 SessionMap::const_iterator old = m_sessions.find(s->GetAccountId ());
215 if(old != m_sessions.end())
217 // prevent decrease sessions count if session queued
218 if(RemoveQueuedPlayer(old->second))
219 decrease_session = false;
220 // not remove replaced session form queue if listed
221 delete old->second;
225 m_sessions[s->GetAccountId ()] = s;
227 uint32 Sessions = GetActiveAndQueuedSessionCount ();
228 uint32 pLimit = GetPlayerAmountLimit ();
229 uint32 QueueSize = GetQueueSize (); //number of players in the queue
231 //so we don't count the user trying to
232 //login as a session and queue the socket that we are using
233 if(decrease_session)
234 --Sessions;
236 if (pLimit > 0 && Sessions >= pLimit && s->GetSecurity () == SEC_PLAYER )
238 AddQueuedPlayer (s);
239 UpdateMaxSessionCounters ();
240 sLog.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s->GetAccountId (), ++QueueSize);
241 return;
244 WorldPacket packet(SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
245 packet << uint8 (AUTH_OK);
246 packet << uint32 (0); // unknown random value...
247 packet << uint8 (0);
248 packet << uint32 (0);
249 packet << uint8 (s->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
250 s->SendPacket (&packet);
252 UpdateMaxSessionCounters ();
254 // Updates the population
255 if (pLimit > 0)
257 float popu = GetActiveSessionCount (); //updated number of users on the server
258 popu /= pLimit;
259 popu *= 2;
260 loginDatabase.PExecute ("UPDATE realmlist SET population = '%f' WHERE id = '%d'", popu, realmID);
261 sLog.outDetail ("Server Population (%f).", popu);
265 int32 World::GetQueuePos(WorldSession* sess)
267 uint32 position = 1;
269 for(Queue::iterator iter = m_QueuedPlayer.begin(); iter != m_QueuedPlayer.end(); ++iter, ++position)
270 if((*iter) == sess)
271 return position;
273 return 0;
276 void World::AddQueuedPlayer(WorldSession* sess)
278 sess->SetInQueue(true);
279 m_QueuedPlayer.push_back (sess);
281 // The 1st SMSG_AUTH_RESPONSE needs to contain other info too.
282 WorldPacket packet (SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
283 packet << uint8 (AUTH_WAIT_QUEUE);
284 packet << uint32 (0); // unknown random value...
285 packet << uint8 (0);
286 packet << uint32 (0);
287 packet << uint8 (sess->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
288 packet << uint32(GetQueuePos (sess));
289 sess->SendPacket (&packet);
291 //sess->SendAuthWaitQue (GetQueuePos (sess));
294 bool World::RemoveQueuedPlayer(WorldSession* sess)
296 // sessions count including queued to remove (if removed_session set)
297 uint32 sessions = GetActiveSessionCount();
299 uint32 position = 1;
300 Queue::iterator iter = m_QueuedPlayer.begin();
302 // search to remove and count skipped positions
303 bool found = false;
305 for(;iter != m_QueuedPlayer.end(); ++iter, ++position)
307 if(*iter==sess)
309 sess->SetInQueue(false);
310 iter = m_QueuedPlayer.erase(iter);
311 found = true; // removing queued session
312 break;
316 // iter point to next socked after removed or end()
317 // position store position of removed socket and then new position next socket after removed
319 // if session not queued then we need decrease sessions count
320 if(!found && sessions)
321 --sessions;
323 // accept first in queue
324 if( (!m_playerLimit || sessions < m_playerLimit) && !m_QueuedPlayer.empty() )
326 WorldSession* pop_sess = m_QueuedPlayer.front();
327 pop_sess->SetInQueue(false);
328 pop_sess->SendAuthWaitQue(0);
329 m_QueuedPlayer.pop_front();
331 // update iter to point first queued socket or end() if queue is empty now
332 iter = m_QueuedPlayer.begin();
333 position = 1;
336 // update position from iter to end()
337 // iter point to first not updated socket, position store new position
338 for(; iter != m_QueuedPlayer.end(); ++iter, ++position)
339 (*iter)->SendAuthWaitQue(position);
341 return found;
344 /// Find a Weather object by the given zoneid
345 Weather* World::FindWeather(uint32 id) const
347 WeatherMap::const_iterator itr = m_weathers.find(id);
349 if(itr != m_weathers.end())
350 return itr->second;
351 else
352 return 0;
355 /// Remove a Weather object for the given zoneid
356 void World::RemoveWeather(uint32 id)
358 // not called at the moment. Kept for completeness
359 WeatherMap::iterator itr = m_weathers.find(id);
361 if(itr != m_weathers.end())
363 delete itr->second;
364 m_weathers.erase(itr);
368 /// Add a Weather object to the list
369 Weather* World::AddWeather(uint32 zone_id)
371 WeatherZoneChances const* weatherChances = objmgr.GetWeatherChances(zone_id);
373 // zone not have weather, ignore
374 if(!weatherChances)
375 return NULL;
377 Weather* w = new Weather(zone_id,weatherChances);
378 m_weathers[w->GetZone()] = w;
379 w->ReGenerate();
380 w->UpdateWeather();
381 return w;
384 /// Initialize config values
385 void World::LoadConfigSettings(bool reload)
387 if(reload)
389 if(!sConfig.Reload())
391 sLog.outError("World settings reload fail: can't read settings from %s.",sConfig.GetFilename().c_str());
392 return;
396 ///- Read the version of the configuration file and warn the user in case of emptiness or mismatch
397 uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
398 if(!confVersion)
400 sLog.outError("*****************************************************************************");
401 sLog.outError(" WARNING: mangosd.conf does not include a ConfVersion variable.");
402 sLog.outError(" Your configuration file may be out of date!");
403 sLog.outError("*****************************************************************************");
404 clock_t pause = 3000 + clock();
405 while (pause > clock());
407 else
409 if (confVersion < _MANGOSDCONFVERSION)
411 sLog.outError("*****************************************************************************");
412 sLog.outError(" WARNING: Your mangosd.conf version indicates your conf file is out of date!");
413 sLog.outError(" Please check for updates, as your current default values may cause");
414 sLog.outError(" unexpected behavior.");
415 sLog.outError("*****************************************************************************");
416 clock_t pause = 3000 + clock();
417 while (pause > clock());
421 ///- Read the player limit and the Message of the day from the config file
422 SetPlayerLimit( sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT), true );
423 SetMotd( sConfig.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
425 ///- Read all rates from the config file
426 rate_values[RATE_HEALTH] = sConfig.GetFloatDefault("Rate.Health", 1);
427 if(rate_values[RATE_HEALTH] < 0)
429 sLog.outError("Rate.Health (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_HEALTH]);
430 rate_values[RATE_HEALTH] = 1;
432 rate_values[RATE_POWER_MANA] = sConfig.GetFloatDefault("Rate.Mana", 1);
433 if(rate_values[RATE_POWER_MANA] < 0)
435 sLog.outError("Rate.Mana (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_POWER_MANA]);
436 rate_values[RATE_POWER_MANA] = 1;
438 rate_values[RATE_POWER_RAGE_INCOME] = sConfig.GetFloatDefault("Rate.Rage.Income", 1);
439 rate_values[RATE_POWER_RAGE_LOSS] = sConfig.GetFloatDefault("Rate.Rage.Loss", 1);
440 if(rate_values[RATE_POWER_RAGE_LOSS] < 0)
442 sLog.outError("Rate.Rage.Loss (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_POWER_RAGE_LOSS]);
443 rate_values[RATE_POWER_RAGE_LOSS] = 1;
445 rate_values[RATE_POWER_FOCUS] = sConfig.GetFloatDefault("Rate.Focus", 1.0f);
446 rate_values[RATE_LOYALTY] = sConfig.GetFloatDefault("Rate.Loyalty", 1.0f);
447 rate_values[RATE_SKILL_DISCOVERY] = sConfig.GetFloatDefault("Rate.Skill.Discovery", 1.0f);
448 rate_values[RATE_DROP_ITEM_POOR] = sConfig.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f);
449 rate_values[RATE_DROP_ITEM_NORMAL] = sConfig.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f);
450 rate_values[RATE_DROP_ITEM_UNCOMMON] = sConfig.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f);
451 rate_values[RATE_DROP_ITEM_RARE] = sConfig.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f);
452 rate_values[RATE_DROP_ITEM_EPIC] = sConfig.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f);
453 rate_values[RATE_DROP_ITEM_LEGENDARY] = sConfig.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f);
454 rate_values[RATE_DROP_ITEM_ARTIFACT] = sConfig.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f);
455 rate_values[RATE_DROP_ITEM_REFERENCED] = sConfig.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f);
456 rate_values[RATE_DROP_MONEY] = sConfig.GetFloatDefault("Rate.Drop.Money", 1.0f);
457 rate_values[RATE_XP_KILL] = sConfig.GetFloatDefault("Rate.XP.Kill", 1.0f);
458 rate_values[RATE_XP_QUEST] = sConfig.GetFloatDefault("Rate.XP.Quest", 1.0f);
459 rate_values[RATE_XP_EXPLORE] = sConfig.GetFloatDefault("Rate.XP.Explore", 1.0f);
460 rate_values[RATE_XP_PAST_70] = sConfig.GetFloatDefault("Rate.XP.PastLevel70", 1.0f);
461 rate_values[RATE_REPUTATION_GAIN] = sConfig.GetFloatDefault("Rate.Reputation.Gain", 1.0f);
462 rate_values[RATE_CREATURE_NORMAL_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f);
463 rate_values[RATE_CREATURE_ELITE_ELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f);
464 rate_values[RATE_CREATURE_ELITE_RAREELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f);
465 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f);
466 rate_values[RATE_CREATURE_ELITE_RARE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f);
467 rate_values[RATE_CREATURE_NORMAL_HP] = sConfig.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f);
468 rate_values[RATE_CREATURE_ELITE_ELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f);
469 rate_values[RATE_CREATURE_ELITE_RAREELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f);
470 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f);
471 rate_values[RATE_CREATURE_ELITE_RARE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f);
472 rate_values[RATE_CREATURE_NORMAL_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f);
473 rate_values[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f);
474 rate_values[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f);
475 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f);
476 rate_values[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f);
477 rate_values[RATE_CREATURE_AGGRO] = sConfig.GetFloatDefault("Rate.Creature.Aggro", 1.0f);
478 rate_values[RATE_REST_INGAME] = sConfig.GetFloatDefault("Rate.Rest.InGame", 1.0f);
479 rate_values[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY] = sConfig.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f);
480 rate_values[RATE_REST_OFFLINE_IN_WILDERNESS] = sConfig.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f);
481 rate_values[RATE_DAMAGE_FALL] = sConfig.GetFloatDefault("Rate.Damage.Fall", 1.0f);
482 rate_values[RATE_AUCTION_TIME] = sConfig.GetFloatDefault("Rate.Auction.Time", 1.0f);
483 rate_values[RATE_AUCTION_DEPOSIT] = sConfig.GetFloatDefault("Rate.Auction.Deposit", 1.0f);
484 rate_values[RATE_AUCTION_CUT] = sConfig.GetFloatDefault("Rate.Auction.Cut", 1.0f);
485 rate_values[RATE_HONOR] = sConfig.GetFloatDefault("Rate.Honor",1.0f);
486 rate_values[RATE_MINING_AMOUNT] = sConfig.GetFloatDefault("Rate.Mining.Amount",1.0f);
487 rate_values[RATE_MINING_NEXT] = sConfig.GetFloatDefault("Rate.Mining.Next",1.0f);
488 rate_values[RATE_INSTANCE_RESET_TIME] = sConfig.GetFloatDefault("Rate.InstanceResetTime",1.0f);
489 rate_values[RATE_TALENT] = sConfig.GetFloatDefault("Rate.Talent",1.0f);
490 if(rate_values[RATE_TALENT] < 0.0f)
492 sLog.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_TALENT]);
493 rate_values[RATE_TALENT] = 1.0f;
495 rate_values[RATE_CORPSE_DECAY_LOOTED] = sConfig.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f);
497 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = sConfig.GetFloatDefault("TargetPosRecalculateRange",1.5f);
498 if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] < CONTACT_DISTANCE)
500 sLog.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],CONTACT_DISTANCE,CONTACT_DISTANCE);
501 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = CONTACT_DISTANCE;
503 else if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] > ATTACK_DISTANCE)
505 sLog.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",
506 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],ATTACK_DISTANCE,ATTACK_DISTANCE);
507 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = ATTACK_DISTANCE;
510 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = sConfig.GetFloatDefault("DurabilityLossChance.Damage",0.5f);
511 if(rate_values[RATE_DURABILITY_LOSS_DAMAGE] < 0.0f)
513 sLog.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_DAMAGE]);
514 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = 0.0f;
516 rate_values[RATE_DURABILITY_LOSS_ABSORB] = sConfig.GetFloatDefault("DurabilityLossChance.Absorb",0.5f);
517 if(rate_values[RATE_DURABILITY_LOSS_ABSORB] < 0.0f)
519 sLog.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_ABSORB]);
520 rate_values[RATE_DURABILITY_LOSS_ABSORB] = 0.0f;
522 rate_values[RATE_DURABILITY_LOSS_PARRY] = sConfig.GetFloatDefault("DurabilityLossChance.Parry",0.05f);
523 if(rate_values[RATE_DURABILITY_LOSS_PARRY] < 0.0f)
525 sLog.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_PARRY]);
526 rate_values[RATE_DURABILITY_LOSS_PARRY] = 0.0f;
528 rate_values[RATE_DURABILITY_LOSS_BLOCK] = sConfig.GetFloatDefault("DurabilityLossChance.Block",0.05f);
529 if(rate_values[RATE_DURABILITY_LOSS_BLOCK] < 0.0f)
531 sLog.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_BLOCK]);
532 rate_values[RATE_DURABILITY_LOSS_BLOCK] = 0.0f;
535 ///- Read other configuration items from the config file
537 m_configs[CONFIG_COMPRESSION] = sConfig.GetIntDefault("Compression", 1);
538 if(m_configs[CONFIG_COMPRESSION] < 1 || m_configs[CONFIG_COMPRESSION] > 9)
540 sLog.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs[CONFIG_COMPRESSION]);
541 m_configs[CONFIG_COMPRESSION] = 1;
543 m_configs[CONFIG_ADDON_CHANNEL] = sConfig.GetBoolDefault("AddonChannel", true);
544 m_configs[CONFIG_GRID_UNLOAD] = sConfig.GetBoolDefault("GridUnload", true);
545 m_configs[CONFIG_INTERVAL_SAVE] = sConfig.GetIntDefault("PlayerSaveInterval", 900000);
547 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = sConfig.GetIntDefault("GridCleanUpDelay", 300000);
548 if(m_configs[CONFIG_INTERVAL_GRIDCLEAN] < MIN_GRID_DELAY)
550 sLog.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_GRIDCLEAN],MIN_GRID_DELAY);
551 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = MIN_GRID_DELAY;
553 if(reload)
554 MapManager::Instance().SetGridCleanUpDelay(m_configs[CONFIG_INTERVAL_GRIDCLEAN]);
556 m_configs[CONFIG_INTERVAL_MAPUPDATE] = sConfig.GetIntDefault("MapUpdateInterval", 100);
557 if(m_configs[CONFIG_INTERVAL_MAPUPDATE] < MIN_MAP_UPDATE_DELAY)
559 sLog.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_MAPUPDATE],MIN_MAP_UPDATE_DELAY);
560 m_configs[CONFIG_INTERVAL_MAPUPDATE] = MIN_MAP_UPDATE_DELAY;
562 if(reload)
563 MapManager::Instance().SetMapUpdateInterval(m_configs[CONFIG_INTERVAL_MAPUPDATE]);
565 m_configs[CONFIG_INTERVAL_CHANGEWEATHER] = sConfig.GetIntDefault("ChangeWeatherInterval", 600000);
567 if(reload)
569 uint32 val = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
570 if(val!=m_configs[CONFIG_PORT_WORLD])
571 sLog.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_PORT_WORLD]);
573 else
574 m_configs[CONFIG_PORT_WORLD] = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
576 if(reload)
578 uint32 val = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
579 if(val!=m_configs[CONFIG_SOCKET_SELECTTIME])
580 sLog.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[DEFAULT_SOCKET_SELECT_TIME]);
582 else
583 m_configs[CONFIG_SOCKET_SELECTTIME] = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
585 m_configs[CONFIG_GROUP_XP_DISTANCE] = sConfig.GetIntDefault("MaxGroupXPDistance", 74);
586 /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
587 m_configs[CONFIG_SIGHT_MONSTER] = sConfig.GetIntDefault("MonsterSight", 50);
588 m_configs[CONFIG_SIGHT_GUARDER] = sConfig.GetIntDefault("GuarderSight", 50);
590 if(reload)
592 uint32 val = sConfig.GetIntDefault("GameType", 0);
593 if(val!=m_configs[CONFIG_GAME_TYPE])
594 sLog.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_GAME_TYPE]);
596 else
597 m_configs[CONFIG_GAME_TYPE] = sConfig.GetIntDefault("GameType", 0);
599 if(reload)
601 uint32 val = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
602 if(val!=m_configs[CONFIG_REALM_ZONE])
603 sLog.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_REALM_ZONE]);
605 else
606 m_configs[CONFIG_REALM_ZONE] = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
608 m_configs[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS] = sConfig.GetBoolDefault("AllowTwoSide.Accounts", false);
609 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
610 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
611 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
612 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
613 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
614 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
615 m_configs[CONFIG_ALLOW_TWO_SIDE_WHO_LIST] = sConfig.GetBoolDefault("AllowTwoSide.WhoList", false);
616 m_configs[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND] = sConfig.GetBoolDefault("AllowTwoSide.AddFriend", false);
617 m_configs[CONFIG_STRICT_PLAYER_NAMES] = sConfig.GetIntDefault("StrictPlayerNames", 0);
618 m_configs[CONFIG_STRICT_CHARTER_NAMES] = sConfig.GetIntDefault("StrictCharterNames", 0);
619 m_configs[CONFIG_STRICT_PET_NAMES] = sConfig.GetIntDefault("StrictPetNames", 0);
621 m_configs[CONFIG_CHARACTERS_CREATING_DISABLED] = sConfig.GetIntDefault("CharactersCreatingDisabled", 0);
623 m_configs[CONFIG_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("CharactersPerRealm", 10);
624 if(m_configs[CONFIG_CHARACTERS_PER_REALM] < 1 || m_configs[CONFIG_CHARACTERS_PER_REALM] > 10)
626 sLog.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs[CONFIG_CHARACTERS_PER_REALM]);
627 m_configs[CONFIG_CHARACTERS_PER_REALM] = 10;
630 // must be after CONFIG_CHARACTERS_PER_REALM
631 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = sConfig.GetIntDefault("CharactersPerAccount", 50);
632 if(m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] < m_configs[CONFIG_CHARACTERS_PER_REALM])
634 sLog.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs[CONFIG_CHARACTERS_PER_ACCOUNT],m_configs[CONFIG_CHARACTERS_PER_REALM]);
635 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = m_configs[CONFIG_CHARACTERS_PER_REALM];
638 m_configs[CONFIG_SKIP_CINEMATICS] = sConfig.GetIntDefault("SkipCinematics", 0);
639 if(m_configs[CONFIG_SKIP_CINEMATICS] < 0 || m_configs[CONFIG_SKIP_CINEMATICS] > 2)
641 sLog.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs[CONFIG_SKIP_CINEMATICS]);
642 m_configs[CONFIG_SKIP_CINEMATICS] = 0;
645 if(reload)
647 uint32 val = sConfig.GetIntDefault("MaxPlayerLevel", 60);
648 if(val!=m_configs[CONFIG_MAX_PLAYER_LEVEL])
649 sLog.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
651 else
652 m_configs[CONFIG_MAX_PLAYER_LEVEL] = sConfig.GetIntDefault("MaxPlayerLevel", 60);
654 if(m_configs[CONFIG_MAX_PLAYER_LEVEL] > MAX_LEVEL)
656 sLog.outError("MaxPlayerLevel (%i) must be in range 1..%u. Set to %u.",m_configs[CONFIG_MAX_PLAYER_LEVEL],MAX_LEVEL,MAX_LEVEL);
657 m_configs[CONFIG_MAX_PLAYER_LEVEL] = MAX_LEVEL;
660 m_configs[CONFIG_START_PLAYER_LEVEL] = sConfig.GetIntDefault("StartPlayerLevel", 1);
661 if(m_configs[CONFIG_START_PLAYER_LEVEL] < 1)
663 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]);
664 m_configs[CONFIG_START_PLAYER_LEVEL] = 1;
666 else if(m_configs[CONFIG_START_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
668 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]);
669 m_configs[CONFIG_START_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
672 m_configs[CONFIG_START_PLAYER_MONEY] = sConfig.GetIntDefault("StartPlayerMoney", 0);
673 if(m_configs[CONFIG_START_PLAYER_MONEY] < 0)
675 sLog.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",m_configs[CONFIG_START_PLAYER_MONEY],MAX_MONEY_AMOUNT,0);
676 m_configs[CONFIG_START_PLAYER_MONEY] = 0;
678 else if(m_configs[CONFIG_START_PLAYER_MONEY] > MAX_MONEY_AMOUNT)
680 sLog.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",
681 m_configs[CONFIG_START_PLAYER_MONEY],MAX_MONEY_AMOUNT,MAX_MONEY_AMOUNT);
682 m_configs[CONFIG_START_PLAYER_MONEY] = MAX_MONEY_AMOUNT;
685 m_configs[CONFIG_MAX_HONOR_POINTS] = sConfig.GetIntDefault("MaxHonorPoints", 75000);
686 if(m_configs[CONFIG_MAX_HONOR_POINTS] < 0)
688 sLog.outError("MaxHonorPoints (%i) can't be negative. Set to 0.",m_configs[CONFIG_MAX_HONOR_POINTS]);
689 m_configs[CONFIG_MAX_HONOR_POINTS] = 0;
692 m_configs[CONFIG_START_HONOR_POINTS] = sConfig.GetIntDefault("StartHonorPoints", 0);
693 if(m_configs[CONFIG_START_HONOR_POINTS] < 0)
695 sLog.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
696 m_configs[CONFIG_START_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS],0);
697 m_configs[CONFIG_MAX_HONOR_POINTS] = 0;
699 else if(m_configs[CONFIG_START_HONOR_POINTS] > m_configs[CONFIG_MAX_HONOR_POINTS])
701 sLog.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
702 m_configs[CONFIG_START_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS]);
703 m_configs[CONFIG_START_HONOR_POINTS] = m_configs[CONFIG_MAX_HONOR_POINTS];
706 m_configs[CONFIG_MAX_ARENA_POINTS] = sConfig.GetIntDefault("MaxArenaPoints", 5000);
707 if(m_configs[CONFIG_MAX_ARENA_POINTS] < 0)
709 sLog.outError("MaxArenaPoints (%i) can't be negative. Set to 0.",m_configs[CONFIG_MAX_ARENA_POINTS]);
710 m_configs[CONFIG_MAX_ARENA_POINTS] = 0;
713 m_configs[CONFIG_START_ARENA_POINTS] = sConfig.GetIntDefault("StartArenaPoints", 0);
714 if(m_configs[CONFIG_START_ARENA_POINTS] < 0)
716 sLog.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
717 m_configs[CONFIG_START_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS],0);
718 m_configs[CONFIG_MAX_ARENA_POINTS] = 0;
720 else if(m_configs[CONFIG_START_ARENA_POINTS] > m_configs[CONFIG_MAX_ARENA_POINTS])
722 sLog.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
723 m_configs[CONFIG_START_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS]);
724 m_configs[CONFIG_START_ARENA_POINTS] = m_configs[CONFIG_MAX_ARENA_POINTS];
727 m_configs[CONFIG_ALL_TAXI_PATHS] = sConfig.GetBoolDefault("AllFlightPaths", false);
729 m_configs[CONFIG_INSTANCE_IGNORE_LEVEL] = sConfig.GetBoolDefault("Instance.IgnoreLevel", false);
730 m_configs[CONFIG_INSTANCE_IGNORE_RAID] = sConfig.GetBoolDefault("Instance.IgnoreRaid", false);
732 m_configs[CONFIG_BATTLEGROUND_CAST_DESERTER] = sConfig.GetBoolDefault("Battleground.CastDeserter", true);
733 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.Enable", true);
734 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false);
736 m_configs[CONFIG_CAST_UNSTUCK] = sConfig.GetBoolDefault("CastUnstuck", true);
737 m_configs[CONFIG_INSTANCE_RESET_TIME_HOUR] = sConfig.GetIntDefault("Instance.ResetTimeHour", 4);
738 m_configs[CONFIG_INSTANCE_UNLOAD_DELAY] = sConfig.GetIntDefault("Instance.UnloadDelay", 1800000);
740 m_configs[CONFIG_MAX_PRIMARY_TRADE_SKILL] = sConfig.GetIntDefault("MaxPrimaryTradeSkill", 2);
741 m_configs[CONFIG_MIN_PETITION_SIGNS] = sConfig.GetIntDefault("MinPetitionSigns", 9);
742 if(m_configs[CONFIG_MIN_PETITION_SIGNS] > 9)
744 sLog.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.",m_configs[CONFIG_MIN_PETITION_SIGNS]);
745 m_configs[CONFIG_MIN_PETITION_SIGNS] = 9;
748 m_configs[CONFIG_GM_LOGIN_STATE] = sConfig.GetIntDefault("GM.LoginState",2);
749 m_configs[CONFIG_GM_ACCEPT_TICKETS] = sConfig.GetIntDefault("GM.AcceptTickets",2);
750 m_configs[CONFIG_GM_CHAT] = sConfig.GetIntDefault("GM.Chat",2);
751 m_configs[CONFIG_GM_WISPERING_TO] = sConfig.GetIntDefault("GM.WhisperingTo",2);
753 m_configs[CONFIG_GM_IN_GM_LIST] = sConfig.GetBoolDefault("GM.InGMList",false);
754 m_configs[CONFIG_GM_IN_WHO_LIST] = sConfig.GetBoolDefault("GM.InWhoList",false);
755 m_configs[CONFIG_GM_LOG_TRADE] = sConfig.GetBoolDefault("GM.LogTrade", false);
757 m_configs[CONFIG_START_GM_LEVEL] = sConfig.GetIntDefault("GM.StartLevel", 1);
758 if(m_configs[CONFIG_START_GM_LEVEL] < m_configs[CONFIG_START_PLAYER_LEVEL])
760 sLog.outError("GM.StartLevel (%i) must be in range StartPlayerLevel(%u)..%u. Set to %u.",
761 m_configs[CONFIG_START_GM_LEVEL],m_configs[CONFIG_START_PLAYER_LEVEL], MAX_LEVEL, m_configs[CONFIG_START_PLAYER_LEVEL]);
762 m_configs[CONFIG_START_GM_LEVEL] = m_configs[CONFIG_START_PLAYER_LEVEL];
764 else if(m_configs[CONFIG_START_GM_LEVEL] > MAX_LEVEL)
766 sLog.outError("GM.StartLevel (%i) must be in range 1..%u. Set to %u.", m_configs[CONFIG_START_GM_LEVEL], MAX_LEVEL, MAX_LEVEL);
767 m_configs[CONFIG_START_GM_LEVEL] = MAX_LEVEL;
770 m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
772 m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
774 m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
775 if(m_configs[CONFIG_UPTIME_UPDATE]<=0)
777 sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
778 m_configs[CONFIG_UPTIME_UPDATE] = 10;
780 if(reload)
782 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
783 m_timers[WUPDATE_UPTIME].Reset();
786 m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
787 m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
788 m_configs[CONFIG_SKILL_CHANCE_GREEN] = sConfig.GetIntDefault("SkillChance.Green",25);
789 m_configs[CONFIG_SKILL_CHANCE_GREY] = sConfig.GetIntDefault("SkillChance.Grey",0);
791 m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS] = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
792 m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS] = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
794 m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
796 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = sConfig.GetIntDefault("SkillGain.Crafting", 1);
797 if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
799 sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
800 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
803 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = sConfig.GetIntDefault("SkillGain.Defense", 1);
804 if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
806 sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
807 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
810 m_configs[CONFIG_SKILL_GAIN_GATHERING] = sConfig.GetIntDefault("SkillGain.Gathering", 1);
811 if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
813 sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
814 m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
817 m_configs[CONFIG_SKILL_GAIN_WEAPON] = sConfig.GetIntDefault("SkillGain.Weapon", 1);
818 if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
820 sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
821 m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
824 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
825 if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
827 sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
828 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
831 m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
832 m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
834 m_configs[CONFIG_DISABLE_BREATHING] = sConfig.GetIntDefault("DisableWaterBreath", SEC_CONSOLE);
836 m_configs[CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL] = sConfig.GetBoolDefault("AlwaysMaxSkillForLevel", false);
838 if(reload)
840 uint32 val = sConfig.GetIntDefault("Expansion",1);
841 if(val!=m_configs[CONFIG_EXPANSION])
842 sLog.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
844 else
845 m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",1);
847 m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
848 m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
849 m_configs[CONFIG_CHATFLOOD_MUTE_TIME] = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
851 m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
853 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistanceRadius",10);
854 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY] = sConfig.GetIntDefault("CreatureFamilyAssistanceDelay",1500);
856 m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
858 // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level MAX_LEVEL(100)
859 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff", 4);
860 if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > MAX_LEVEL)
861 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = MAX_LEVEL;
862 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff", 7);
863 if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > MAX_LEVEL)
864 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = MAX_LEVEL;
866 m_configs[CONFIG_DETECT_POS_COLLISION] = sConfig.GetBoolDefault("DetectPosCollision", true);
868 m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
869 m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
871 m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
872 m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
874 m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
875 m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
876 m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
877 m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
878 m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
880 m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault("Death.SicknessLevel", 11);
881 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
882 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
884 m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
886 // always use declined names in the russian client
887 m_configs[CONFIG_DECLINED_NAMES_USED] =
888 (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
890 m_configs[CONFIG_LISTEN_RANGE_SAY] = sConfig.GetIntDefault("ListenRange.Say", 25);
891 m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
892 m_configs[CONFIG_LISTEN_RANGE_YELL] = sConfig.GetIntDefault("ListenRange.Yell", 300);
894 m_configs[CONFIG_INSTANT_LOGOUT] = sConfig.GetIntDefault("InstantLogout", SEC_MODERATOR);
896 m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
897 if(m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
899 sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
900 m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
902 m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
903 if(m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
905 sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
906 m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
909 m_MaxVisibleDistanceForCreature = sConfig.GetFloatDefault("Visibility.Distance.Creature", DEFAULT_VISIBILITY_DISTANCE);
910 if(m_MaxVisibleDistanceForCreature < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
912 sLog.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
913 m_MaxVisibleDistanceForCreature = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
915 else if(m_MaxVisibleDistanceForCreature + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
917 sLog.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
918 m_MaxVisibleDistanceForCreature = MAX_VISIBILITY_DISTANCE-m_VisibleUnitGreyDistance;
920 m_MaxVisibleDistanceForPlayer = sConfig.GetFloatDefault("Visibility.Distance.Player", DEFAULT_VISIBILITY_DISTANCE);
921 if(m_MaxVisibleDistanceForPlayer < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
923 sLog.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
924 m_MaxVisibleDistanceForPlayer = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
926 else if(m_MaxVisibleDistanceForPlayer + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
928 sLog.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
929 m_MaxVisibleDistanceForPlayer = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
931 m_MaxVisibleDistanceForObject = sConfig.GetFloatDefault("Visibility.Distance.Gameobject", DEFAULT_VISIBILITY_DISTANCE);
932 if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
934 sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
935 m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
937 else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
939 sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
940 m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
942 m_MaxVisibleDistanceInFlight = sConfig.GetFloatDefault("Visibility.Distance.InFlight", DEFAULT_VISIBILITY_DISTANCE);
943 if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
945 sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
946 m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
949 ///- Read the "Data" directory from the config file
950 std::string dataPath = sConfig.GetStringDefault("DataDir","./");
951 if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
952 dataPath.append("/");
954 if(reload)
956 if(dataPath!=m_dataPath)
957 sLog.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath.c_str());
959 else
961 m_dataPath = dataPath;
962 sLog.outString("Using DataDir %s",m_dataPath.c_str());
965 bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
966 bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
967 std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
968 std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
969 VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
970 VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
971 VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
972 VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
973 sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
974 sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
975 sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
978 /// Initialize the World
979 void World::SetInitialWorldSettings()
981 ///- Initialize the random number generator
982 srand((unsigned int)time(NULL));
984 ///- Initialize config settings
985 LoadConfigSettings();
987 ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
988 objmgr.SetHighestGuids();
990 ///- Check the existence of the map files for all races' startup areas.
991 if( !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
992 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
993 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
994 ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
995 ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
996 ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
997 ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
998 ||m_configs[CONFIG_EXPANSION] && (
999 !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
1001 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());
1002 exit(1);
1005 ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
1006 sLog.outString( "" );
1007 sLog.outString( "Loading MaNGOS strings..." );
1008 if (!objmgr.LoadMangosStrings())
1009 exit(1); // Error message displayed in function already
1011 ///- Update the realm entry in the database with the realm type from the config file
1012 //No SQL injection as values are treated as integers
1014 // not send custom type REALM_FFA_PVP to realm list
1015 uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
1016 uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
1017 loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
1019 ///- Remove the bones after a restart
1020 CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
1022 ///- Load the DBC files
1023 sLog.outString("Initialize data stores...");
1024 LoadDBCStores(m_dataPath);
1025 DetectDBCLang();
1027 sLog.outString( "Loading Script Names...");
1028 objmgr.LoadScriptNames();
1030 sLog.outString( "Loading InstanceTemplate" );
1031 objmgr.LoadInstanceTemplate();
1033 sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
1034 spellmgr.LoadSkillLineAbilityMap();
1036 ///- Clean up and pack instances
1037 sLog.outString( "Cleaning up instances..." );
1038 sInstanceSaveManager.CleanupInstances(); // must be called before `creature_respawn`/`gameobject_respawn` tables
1040 sLog.outString( "Packing instances..." );
1041 sInstanceSaveManager.PackInstances();
1043 sLog.outString( "Loading Localization strings..." );
1044 objmgr.LoadCreatureLocales();
1045 objmgr.LoadGameObjectLocales();
1046 objmgr.LoadItemLocales();
1047 objmgr.LoadQuestLocales();
1048 objmgr.LoadNpcTextLocales();
1049 objmgr.LoadPageTextLocales();
1050 objmgr.LoadNpcOptionLocales();
1051 objmgr.SetDBCLocaleIndex(GetDefaultDbcLocale()); // Get once for all the locale index of DBC language (console/broadcasts)
1053 sLog.outString( "Loading Page Texts..." );
1054 objmgr.LoadPageTexts();
1056 sLog.outString( "Loading Game Object Templates..." ); // must be after LoadPageTexts
1057 objmgr.LoadGameobjectInfo();
1059 sLog.outString( "Loading Spell Chain Data..." );
1060 spellmgr.LoadSpellChains();
1062 sLog.outString( "Loading Spell Elixir types..." );
1063 spellmgr.LoadSpellElixirs();
1065 sLog.outString( "Loading Spell Learn Skills..." );
1066 spellmgr.LoadSpellLearnSkills(); // must be after LoadSpellChains
1068 sLog.outString( "Loading Spell Learn Spells..." );
1069 spellmgr.LoadSpellLearnSpells();
1071 sLog.outString( "Loading Spell Proc Event conditions..." );
1072 spellmgr.LoadSpellProcEvents();
1074 sLog.outString( "Loading Aggro Spells Definitions...");
1075 spellmgr.LoadSpellThreats();
1077 sLog.outString( "Loading NPC Texts..." );
1078 objmgr.LoadGossipText();
1080 sLog.outString( "Loading Item Random Enchantments Table..." );
1081 LoadRandomEnchantmentsTable();
1083 sLog.outString( "Loading Items..." ); // must be after LoadRandomEnchantmentsTable and LoadPageTexts
1084 objmgr.LoadItemPrototypes();
1086 sLog.outString( "Loading Item Texts..." );
1087 objmgr.LoadItemTexts();
1089 sLog.outString( "Loading Creature Model Based Info Data..." );
1090 objmgr.LoadCreatureModelInfo();
1092 sLog.outString( "Loading Equipment templates...");
1093 objmgr.LoadEquipmentTemplates();
1095 sLog.outString( "Loading Creature templates..." );
1096 objmgr.LoadCreatureTemplates();
1098 sLog.outString( "Loading SpellsScriptTarget...");
1099 spellmgr.LoadSpellScriptTarget(); // must be after LoadCreatureTemplates and LoadGameobjectInfo
1101 sLog.outString( "Loading Creature Reputation OnKill Data..." );
1102 objmgr.LoadReputationOnKill();
1104 sLog.outString( "Loading Pet Create Spells..." );
1105 objmgr.LoadPetCreateSpells();
1107 sLog.outString( "Loading Creature Data..." );
1108 objmgr.LoadCreatures();
1110 sLog.outString( "Loading Creature Addon Data..." );
1111 objmgr.LoadCreatureAddons(); // must be after LoadCreatureTemplates() and LoadCreatures()
1113 sLog.outString( "Loading Creature Respawn Data..." ); // must be after PackInstances()
1114 objmgr.LoadCreatureRespawnTimes();
1116 sLog.outString( "Loading Gameobject Data..." );
1117 objmgr.LoadGameobjects();
1119 sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1120 objmgr.LoadGameobjectRespawnTimes();
1122 sLog.outString( "Loading Game Event Data...");
1123 gameeventmgr.LoadFromDB();
1125 sLog.outString( "Loading Weather Data..." );
1126 objmgr.LoadWeatherZoneChances();
1128 sLog.outString( "Loading Quests..." );
1129 objmgr.LoadQuests(); // must be loaded after DBCs, creature_template, item_template, gameobject tables
1131 sLog.outString( "Loading Quests Relations..." );
1132 objmgr.LoadQuestRelations(); // must be after quest load
1134 sLog.outString( "Loading AreaTrigger definitions..." );
1135 objmgr.LoadAreaTriggerTeleports(); // must be after item template load
1137 sLog.outString( "Loading Quest Area Triggers..." );
1138 objmgr.LoadQuestAreaTriggers(); // must be after LoadQuests
1140 sLog.outString( "Loading Tavern Area Triggers..." );
1141 objmgr.LoadTavernAreaTriggers();
1143 sLog.outString( "Loading AreaTrigger script names..." );
1144 objmgr.LoadAreaTriggerScripts();
1146 sLog.outString( "Loading Graveyard-zone links...");
1147 objmgr.LoadGraveyardZones();
1149 sLog.outString( "Loading Spell target coordinates..." );
1150 spellmgr.LoadSpellTargetPositions();
1152 sLog.outString( "Loading SpellAffect definitions..." );
1153 spellmgr.LoadSpellAffects();
1155 sLog.outString( "Loading spell pet auras..." );
1156 spellmgr.LoadSpellPetAuras();
1158 sLog.outString( "Loading player Create Info & Level Stats..." );
1159 objmgr.LoadPlayerInfo();
1161 sLog.outString( "Loading Exploration BaseXP Data..." );
1162 objmgr.LoadExplorationBaseXP();
1164 sLog.outString( "Loading Pet Name Parts..." );
1165 objmgr.LoadPetNames();
1167 sLog.outString( "Loading the max pet number..." );
1168 objmgr.LoadPetNumber();
1170 sLog.outString( "Loading pet level stats..." );
1171 objmgr.LoadPetLevelInfo();
1173 sLog.outString( "Loading Player Corpses..." );
1174 objmgr.LoadCorpses();
1176 sLog.outString( "Loading Loot Tables..." );
1177 LoadLootTables();
1179 sLog.outString( "Loading Skill Discovery Table..." );
1180 LoadSkillDiscoveryTable();
1182 sLog.outString( "Loading Skill Extra Item Table..." );
1183 LoadSkillExtraItemTable();
1185 sLog.outString( "Loading Skill Fishing base level requirements..." );
1186 objmgr.LoadFishingBaseSkillLevel();
1188 ///- Load dynamic data tables from the database
1189 sLog.outString( "Loading Auctions..." );
1190 objmgr.LoadAuctionItems();
1191 objmgr.LoadAuctions();
1193 sLog.outString( "Loading Guilds..." );
1194 objmgr.LoadGuilds();
1196 sLog.outString( "Loading ArenaTeams..." );
1197 objmgr.LoadArenaTeams();
1199 sLog.outString( "Loading Groups..." );
1200 objmgr.LoadGroups();
1202 sLog.outString( "Loading ReservedNames..." );
1203 objmgr.LoadReservedPlayersNames();
1205 sLog.outString( "Loading GameObject for quests..." );
1206 objmgr.LoadGameObjectForQuests();
1208 sLog.outString( "Loading BattleMasters..." );
1209 objmgr.LoadBattleMastersEntry();
1211 sLog.outString( "Loading GameTeleports..." );
1212 objmgr.LoadGameTele();
1214 sLog.outString( "Loading Npc Text Id..." );
1215 objmgr.LoadNpcTextId(); // must be after load Creature and NpcText
1217 sLog.outString( "Loading Npc Options..." );
1218 objmgr.LoadNpcOptions();
1220 sLog.outString( "Loading vendors..." );
1221 objmgr.LoadVendors(); // must be after load CreatureTemplate and ItemTemplate
1223 sLog.outString( "Loading trainers..." );
1224 objmgr.LoadTrainerSpell(); // must be after load CreatureTemplate
1226 sLog.outString( "Loading Waypoints..." );
1227 WaypointMgr.Load();
1229 sLog.outString( "Loading GM tickets...");
1230 ticketmgr.LoadGMTickets();
1232 ///- Handle outdated emails (delete/return)
1233 sLog.outString( "Returning old mails..." );
1234 objmgr.ReturnOrDeleteOldMails(false);
1236 ///- Load and initialize scripts
1237 sLog.outString( "Loading Scripts..." );
1238 objmgr.LoadQuestStartScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1239 objmgr.LoadQuestEndScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1240 objmgr.LoadSpellScripts(); // must be after load Creature/Gameobject(Template/Data)
1241 objmgr.LoadGameObjectScripts(); // must be after load Creature/Gameobject(Template/Data)
1242 objmgr.LoadEventScripts(); // must be after load Creature/Gameobject(Template/Data)
1244 sLog.outString( "Loading Scripts text locales..." ); // must be after Load*Scripts calls
1245 objmgr.LoadDbScriptStrings();
1247 sLog.outString( "Initializing Scripts..." );
1248 if(!LoadScriptingModule())
1249 exit(1);
1251 ///- Initialize game time and timers
1252 sLog.outString( "DEBUG:: Initialize game time and timers" );
1253 m_gameTime = time(NULL);
1254 m_startTime=m_gameTime;
1256 tm local;
1257 time_t curr;
1258 time(&curr);
1259 local=*(localtime(&curr)); // dereference and assign
1260 char isoDate[128];
1261 sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1262 local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1264 WorldDatabase.PExecute("INSERT INTO uptime (startstring, starttime, uptime) VALUES('%s', " I64FMTD ", 0)",
1265 isoDate, uint64(m_startTime));
1267 m_timers[WUPDATE_OBJECTS].SetInterval(0);
1268 m_timers[WUPDATE_SESSIONS].SetInterval(0);
1269 m_timers[WUPDATE_WEATHERS].SetInterval(1000);
1270 m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*1000); //set auction update interval to 1 minute
1271 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
1272 //Update "uptime" table based on configuration entry in minutes.
1273 m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*1000); //erase corpses every 20 minutes
1275 //to set mailtimer to return mails every day between 4 and 5 am
1276 //mailtimer is increased when updating auctions
1277 //one second is 1000 -(tested on win system)
1278 mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * 1000) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1279 //1440
1280 mail_timer_expires = ( (DAY * 1000) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1281 sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1283 ///- Initilize static helper structures
1284 AIRegistry::Initialize();
1285 WaypointMovementGenerator<Creature>::Initialize();
1286 Player::InitVisibleBits();
1288 ///- Initialize MapManager
1289 sLog.outString( "Starting Map System" );
1290 MapManager::Instance().Initialize();
1292 ///- Initialize Battlegrounds
1293 sLog.outString( "Starting BattleGround System" );
1294 sBattleGroundMgr.CreateInitialBattleGrounds();
1296 //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1297 sLog.outString( "Loading Transports..." );
1298 MapManager::Instance().LoadTransports();
1300 sLog.outString("Deleting expired bans..." );
1301 loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1303 sLog.outString("Calculate next daily quest reset time..." );
1304 InitDailyQuestResetTime();
1306 sLog.outString("Starting Game Event system..." );
1307 uint32 nextGameEvent = gameeventmgr.Initialize();
1308 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent); //depend on next event
1310 sLog.outString( "WORLD: World initialized" );
1313 void World::DetectDBCLang()
1315 uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1317 if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1319 sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1320 m_lang_confid = LOCALE_enUS;
1323 ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1325 std::string availableLocalsStr;
1327 int default_locale = MAX_LOCALE;
1328 for (int i = MAX_LOCALE-1; i >= 0; --i)
1330 if ( strlen(race->name[i]) > 0) // check by race names
1332 default_locale = i;
1333 m_availableDbcLocaleMask |= (1 << i);
1334 availableLocalsStr += localeNames[i];
1335 availableLocalsStr += " ";
1339 if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1340 (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1342 default_locale = m_lang_confid;
1345 if(default_locale >= MAX_LOCALE)
1347 sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1348 exit(1);
1351 m_defaultDbcLocale = LocaleConstant(default_locale);
1353 sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1356 /// Update the World !
1357 void World::Update(time_t diff)
1359 ///- Update the different timers
1360 for(int i = 0; i < WUPDATE_COUNT; i++)
1361 if(m_timers[i].GetCurrent()>=0)
1362 m_timers[i].Update(diff);
1363 else m_timers[i].SetCurrent(0);
1365 ///- Update the game time and check for shutdown time
1366 _UpdateGameTime();
1368 /// Handle daily quests reset time
1369 if(m_gameTime > m_NextDailyQuestReset)
1371 ResetDailyQuests();
1372 m_NextDailyQuestReset += DAY;
1375 /// <ul><li> Handle auctions when the timer has passed
1376 if (m_timers[WUPDATE_AUCTIONS].Passed())
1378 m_timers[WUPDATE_AUCTIONS].Reset();
1380 ///- Update mails (return old mails with item, or delete them)
1381 //(tested... works on win)
1382 if (++mail_timer > mail_timer_expires)
1384 mail_timer = 0;
1385 objmgr.ReturnOrDeleteOldMails(true);
1388 AuctionHouseObject* AuctionMap;
1389 for (int i = 0; i < 3; i++)
1391 switch (i)
1393 case 0:
1394 AuctionMap = objmgr.GetAuctionsMap( 6 );//horde
1395 break;
1396 case 1:
1397 AuctionMap = objmgr.GetAuctionsMap( 2 );//alliance
1398 break;
1399 case 2:
1400 AuctionMap = objmgr.GetAuctionsMap( 7 );//neutral
1401 break;
1404 ///- Handle expired auctions
1405 AuctionHouseObject::AuctionEntryMap::iterator itr,next;
1406 for (itr = AuctionMap->GetAuctionsBegin(); itr != AuctionMap->GetAuctionsEnd();itr = next)
1408 next = itr;
1409 ++next;
1410 if (m_gameTime > (itr->second->time))
1412 ///- Either cancel the auction if there was no bidder
1413 if (itr->second->bidder == 0)
1415 objmgr.SendAuctionExpiredMail( itr->second );
1417 ///- Or perform the transaction
1418 else
1420 //we should send an "item sold" message if the seller is online
1421 //we send the item to the winner
1422 //we send the money to the seller
1423 objmgr.SendAuctionSuccessfulMail( itr->second );
1424 objmgr.SendAuctionWonMail( itr->second );
1427 ///- In any case clear the auction
1428 //No SQL injection (Id is integer)
1429 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",itr->second->Id);
1430 objmgr.RemoveAItem(itr->second->item_guidlow);
1431 delete itr->second;
1432 AuctionMap->RemoveAuction(itr->first);
1438 /// <li> Handle session updates when the timer has passed
1439 if (m_timers[WUPDATE_SESSIONS].Passed())
1441 m_timers[WUPDATE_SESSIONS].Reset();
1443 UpdateSessions(diff);
1446 /// <li> Handle weather updates when the timer has passed
1447 if (m_timers[WUPDATE_WEATHERS].Passed())
1449 m_timers[WUPDATE_WEATHERS].Reset();
1451 ///- Send an update signal to Weather objects
1452 WeatherMap::iterator itr, next;
1453 for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1455 next = itr;
1456 ++next;
1458 ///- and remove Weather objects for zones with no player
1459 //As interval > WorldTick
1460 if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1462 delete itr->second;
1463 m_weathers.erase(itr);
1467 /// <li> Update uptime table
1468 if (m_timers[WUPDATE_UPTIME].Passed())
1470 uint32 tmpDiff = (m_gameTime - m_startTime);
1471 uint32 maxClientsNum = sWorld.GetMaxActiveSessionCount();
1473 m_timers[WUPDATE_UPTIME].Reset();
1474 WorldDatabase.PExecute("UPDATE uptime SET uptime = %d, maxplayers = %d WHERE starttime = " I64FMTD, tmpDiff, maxClientsNum, uint64(m_startTime));
1477 /// <li> Handle all other objects
1478 if (m_timers[WUPDATE_OBJECTS].Passed())
1480 m_timers[WUPDATE_OBJECTS].Reset();
1481 ///- Update objects when the timer has passed (maps, transport, creatures,...)
1482 MapManager::Instance().Update(diff); // As interval = 0
1484 ///- Process necessary scripts
1485 if (!m_scriptSchedule.empty())
1486 ScriptsProcess();
1488 sBattleGroundMgr.Update(diff);
1491 // execute callbacks from sql queries that were queued recently
1492 UpdateResultQueue();
1494 ///- Erase corpses once every 20 minutes
1495 if (m_timers[WUPDATE_CORPSES].Passed())
1497 m_timers[WUPDATE_CORPSES].Reset();
1499 CorpsesErase();
1502 ///- Process Game events when necessary
1503 if (m_timers[WUPDATE_EVENTS].Passed())
1505 m_timers[WUPDATE_EVENTS].Reset(); // to give time for Update() to be processed
1506 uint32 nextGameEvent = gameeventmgr.Update();
1507 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1508 m_timers[WUPDATE_EVENTS].Reset();
1511 /// </ul>
1512 ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1513 MapManager::Instance().DoDelayedMovesAndRemoves();
1515 // update the instance reset times
1516 sInstanceSaveManager.Update();
1518 // And last, but not least handle the issued cli commands
1519 ProcessCliCommands();
1522 /// Put scripts in the execution queue
1523 void World::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
1525 ///- Find the script map
1526 ScriptMapMap::const_iterator s = scripts.find(id);
1527 if (s == scripts.end())
1528 return;
1530 // prepare static data
1531 uint64 sourceGUID = source->GetGUID();
1532 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1533 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1535 ///- Schedule script execution for all scripts in the script map
1536 ScriptMap const *s2 = &(s->second);
1537 bool immedScript = false;
1538 for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
1540 ScriptAction sa;
1541 sa.sourceGUID = sourceGUID;
1542 sa.targetGUID = targetGUID;
1543 sa.ownerGUID = ownerGUID;
1545 sa.script = &iter->second;
1546 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + iter->first, sa));
1547 if (iter->first == 0)
1548 immedScript = true;
1550 ///- If one of the effects should be immediate, launch the script execution
1551 if (immedScript)
1552 ScriptsProcess();
1555 void World::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
1557 // NOTE: script record _must_ exist until command executed
1559 // prepare static data
1560 uint64 sourceGUID = source->GetGUID();
1561 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1562 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1564 ScriptAction sa;
1565 sa.sourceGUID = sourceGUID;
1566 sa.targetGUID = targetGUID;
1567 sa.ownerGUID = ownerGUID;
1569 sa.script = &script;
1570 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + delay, sa));
1572 ///- If effects should be immediate, launch the script execution
1573 if(delay == 0)
1574 ScriptsProcess();
1577 /// Process queued scripts
1578 void World::ScriptsProcess()
1580 if (m_scriptSchedule.empty())
1581 return;
1583 ///- Process overdue queued scripts
1584 std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
1585 // ok as multimap is a *sorted* associative container
1586 while (!m_scriptSchedule.empty() && (iter->first <= m_gameTime))
1588 ScriptAction const& step = iter->second;
1590 Object* source = NULL;
1592 if(step.sourceGUID)
1594 switch(GUID_HIPART(step.sourceGUID))
1596 case HIGHGUID_ITEM:
1597 // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1599 Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
1600 if(player)
1601 source = player->GetItemByGuid(step.sourceGUID);
1602 break;
1604 case HIGHGUID_UNIT:
1605 source = HashMapHolder<Creature>::Find(step.sourceGUID);
1606 break;
1607 case HIGHGUID_PET:
1608 source = HashMapHolder<Pet>::Find(step.sourceGUID);
1609 break;
1610 case HIGHGUID_PLAYER:
1611 source = HashMapHolder<Player>::Find(step.sourceGUID);
1612 break;
1613 case HIGHGUID_GAMEOBJECT:
1614 source = HashMapHolder<GameObject>::Find(step.sourceGUID);
1615 break;
1616 case HIGHGUID_CORPSE:
1617 source = HashMapHolder<Corpse>::Find(step.sourceGUID);
1618 break;
1619 default:
1620 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
1621 break;
1625 if(source && !source->IsInWorld()) source = NULL;
1627 Object* target = NULL;
1629 if(step.targetGUID)
1631 switch(GUID_HIPART(step.targetGUID))
1633 case HIGHGUID_UNIT:
1634 target = HashMapHolder<Creature>::Find(step.targetGUID);
1635 break;
1636 case HIGHGUID_PET:
1637 target = HashMapHolder<Pet>::Find(step.targetGUID);
1638 break;
1639 case HIGHGUID_PLAYER: // empty GUID case also
1640 target = HashMapHolder<Player>::Find(step.targetGUID);
1641 break;
1642 case HIGHGUID_GAMEOBJECT:
1643 target = HashMapHolder<GameObject>::Find(step.targetGUID);
1644 break;
1645 case HIGHGUID_CORPSE:
1646 target = HashMapHolder<Corpse>::Find(step.targetGUID);
1647 break;
1648 default:
1649 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
1650 break;
1654 if(target && !target->IsInWorld()) target = NULL;
1656 switch (step.script->command)
1658 case SCRIPT_COMMAND_TALK:
1660 if(!source)
1662 sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1663 break;
1666 if(source->GetTypeId()!=TYPEID_UNIT)
1668 sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1669 break;
1672 uint64 unit_target = target ? target->GetGUID() : 0;
1674 //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1675 switch(step.script->datalong)
1677 case 0: // Say
1678 ((Creature *)source)->Say(step.script->dataint, LANG_UNIVERSAL, unit_target);
1679 break;
1680 case 1: // Whisper
1681 if(!unit_target)
1683 sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
1684 break;
1686 ((Creature *)source)->Whisper(step.script->dataint,unit_target);
1687 break;
1688 case 2: // Yell
1689 ((Creature *)source)->Yell(step.script->dataint, LANG_UNIVERSAL, unit_target);
1690 break;
1691 case 3: // Emote text
1692 ((Creature *)source)->TextEmote(step.script->dataint, unit_target);
1693 break;
1694 default:
1695 break; // must be already checked at load
1697 break;
1700 case SCRIPT_COMMAND_EMOTE:
1701 if(!source)
1703 sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1704 break;
1707 if(source->GetTypeId()!=TYPEID_UNIT)
1709 sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1710 break;
1713 ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
1714 break;
1715 case SCRIPT_COMMAND_FIELD_SET:
1716 if(!source)
1718 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1719 break;
1721 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1723 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1724 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1725 break;
1728 source->SetUInt32Value(step.script->datalong, step.script->datalong2);
1729 break;
1730 case SCRIPT_COMMAND_MOVE_TO:
1731 if(!source)
1733 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1734 break;
1737 if(source->GetTypeId()!=TYPEID_UNIT)
1739 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1740 break;
1742 ((Unit *)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, ((Unit *)source)->GetUnitMovementFlags(), step.script->datalong2 );
1743 ((Unit *)source)->GetMap()->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
1744 break;
1745 case SCRIPT_COMMAND_FLAG_SET:
1746 if(!source)
1748 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1749 break;
1751 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1753 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1754 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1755 break;
1758 source->SetFlag(step.script->datalong, step.script->datalong2);
1759 break;
1760 case SCRIPT_COMMAND_FLAG_REMOVE:
1761 if(!source)
1763 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1764 break;
1766 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1768 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1769 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1770 break;
1773 source->RemoveFlag(step.script->datalong, step.script->datalong2);
1774 break;
1776 case SCRIPT_COMMAND_TELEPORT_TO:
1778 // accept player in any one from target/source arg
1779 if (!target && !source)
1781 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1782 break;
1785 // must be only Player
1786 if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
1788 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
1789 break;
1792 Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
1794 pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
1795 break;
1798 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
1800 if(!step.script->datalong) // creature not specified
1802 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1803 break;
1806 if(!source)
1808 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1809 break;
1812 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1814 if(!summoner)
1816 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1817 break;
1820 float x = step.script->x;
1821 float y = step.script->y;
1822 float z = step.script->z;
1823 float o = step.script->o;
1825 Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
1826 if (!pCreature)
1828 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
1829 break;
1832 break;
1835 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
1837 if(!step.script->datalong) // gameobject not specified
1839 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1840 break;
1843 if(!source)
1845 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1846 break;
1849 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1851 if(!summoner)
1853 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1854 break;
1857 GameObject *go = NULL;
1858 int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
1860 CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
1861 Cell cell(p);
1862 cell.data.Part.reserved = ALL_DISTRICT;
1864 MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
1865 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(go,go_check);
1867 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1868 CellLock<GridReadGuard> cell_lock(cell, p);
1869 cell_lock->Visit(cell_lock, object_checker, *summoner->GetMap());
1871 if ( !go )
1873 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
1874 break;
1877 if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1878 go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1879 go->GetGoType()==GAMEOBJECT_TYPE_DOOR ||
1880 go->GetGoType()==GAMEOBJECT_TYPE_BUTTON ||
1881 go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
1883 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
1884 break;
1887 if( go->isSpawned() )
1888 break; //gameobject already spawned
1890 go->SetLootState(GO_READY);
1891 go->SetRespawnTime(time_to_despawn); //despawn object in ? seconds
1893 go->GetMap()->Add(go);
1894 break;
1896 case SCRIPT_COMMAND_OPEN_DOOR:
1898 if(!step.script->datalong) // door not specified
1900 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1901 break;
1904 if(!source)
1906 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1907 break;
1910 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
1912 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1913 break;
1916 Unit* caster = (Unit*)source;
1918 GameObject *door = NULL;
1919 int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1921 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1922 Cell cell(p);
1923 cell.data.Part.reserved = ALL_DISTRICT;
1925 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1926 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1928 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1929 CellLock<GridReadGuard> cell_lock(cell, p);
1930 cell_lock->Visit(cell_lock, object_checker, *caster->GetMap());
1932 if ( !door )
1934 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1935 break;
1937 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1939 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1940 break;
1943 if( !door->GetGoState() )
1944 break; //door already open
1946 door->UseDoorOrButton(time_to_close);
1948 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1949 ((GameObject*)target)->UseDoorOrButton(time_to_close);
1950 break;
1952 case SCRIPT_COMMAND_CLOSE_DOOR:
1954 if(!step.script->datalong) // guid for door not specified
1956 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
1957 break;
1960 if(!source)
1962 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
1963 break;
1966 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
1968 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1969 break;
1972 Unit* caster = (Unit*)source;
1974 GameObject *door = NULL;
1975 int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1977 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1978 Cell cell(p);
1979 cell.data.Part.reserved = ALL_DISTRICT;
1981 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1982 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1984 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1985 CellLock<GridReadGuard> cell_lock(cell, p);
1986 cell_lock->Visit(cell_lock, object_checker, *caster->GetMap());
1988 if ( !door )
1990 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1991 break;
1993 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1995 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1996 break;
1999 if( door->GetGoState() )
2000 break; //door already closed
2002 door->UseDoorOrButton(time_to_open);
2004 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
2005 ((GameObject*)target)->UseDoorOrButton(time_to_open);
2007 break;
2009 case SCRIPT_COMMAND_QUEST_EXPLORED:
2011 if(!source)
2013 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
2014 break;
2017 if(!target)
2019 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
2020 break;
2023 // when script called for item spell casting then target == (unit or GO) and source is player
2024 WorldObject* worldObject;
2025 Player* player;
2027 if(target->GetTypeId()==TYPEID_PLAYER)
2029 if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
2031 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
2032 break;
2035 worldObject = (WorldObject*)source;
2036 player = (Player*)target;
2038 else
2040 if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
2042 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
2043 break;
2046 if(source->GetTypeId()!=TYPEID_PLAYER)
2048 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
2049 break;
2052 worldObject = (WorldObject*)target;
2053 player = (Player*)source;
2056 // quest id and flags checked at script loading
2057 if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
2058 (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
2059 player->AreaExploredOrEventHappens(step.script->datalong);
2060 else
2061 player->FailQuest(step.script->datalong);
2063 break;
2066 case SCRIPT_COMMAND_ACTIVATE_OBJECT:
2068 if(!source)
2070 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
2071 break;
2074 if(!source->isType(TYPEMASK_UNIT))
2076 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2077 break;
2080 if(!target)
2082 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
2083 break;
2086 if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
2088 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
2089 break;
2092 Unit* caster = (Unit*)source;
2094 GameObject *go = (GameObject*)target;
2096 go->Use(caster);
2097 break;
2100 case SCRIPT_COMMAND_REMOVE_AURA:
2102 Object* cmdTarget = step.script->datalong2 ? source : target;
2104 if(!cmdTarget)
2106 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
2107 break;
2110 if(!cmdTarget->isType(TYPEMASK_UNIT))
2112 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2113 break;
2116 ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
2117 break;
2120 case SCRIPT_COMMAND_CAST_SPELL:
2122 if(!source)
2124 sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
2125 break;
2128 if(!source->isType(TYPEMASK_UNIT))
2130 sLog.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2131 break;
2134 Object* cmdTarget = step.script->datalong2 ? source : target;
2136 if(!cmdTarget)
2138 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 ? "source" : "target");
2139 break;
2142 if(!cmdTarget->isType(TYPEMASK_UNIT))
2144 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2145 break;
2148 Unit* spellTarget = (Unit*)cmdTarget;
2150 //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2151 ((Unit*)source)->CastSpell(spellTarget,step.script->datalong,false);
2153 break;
2156 default:
2157 sLog.outError("Unknown script command %u called.",step.script->command);
2158 break;
2161 m_scriptSchedule.erase(iter);
2163 iter = m_scriptSchedule.begin();
2165 return;
2168 /// Send a packet to all players (except self if mentioned)
2169 void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
2171 SessionMap::iterator itr;
2172 for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2174 if (itr->second &&
2175 itr->second->GetPlayer() &&
2176 itr->second->GetPlayer()->IsInWorld() &&
2177 itr->second != self &&
2178 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2180 itr->second->SendPacket(packet);
2185 /// Send a System Message to all players (except self if mentioned)
2186 void World::SendWorldText(int32 string_id, ...)
2188 std::vector<std::vector<WorldPacket*> > data_cache; // 0 = default, i => i-1 locale index
2190 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2192 if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
2193 continue;
2195 uint32 loc_idx = itr->second->GetSessionDbLocaleIndex();
2196 uint32 cache_idx = loc_idx+1;
2198 std::vector<WorldPacket*>* data_list;
2200 // create if not cached yet
2201 if(data_cache.size() < cache_idx+1 || data_cache[cache_idx].empty())
2203 if(data_cache.size() < cache_idx+1)
2204 data_cache.resize(cache_idx+1);
2206 data_list = &data_cache[cache_idx];
2208 char const* text = objmgr.GetMangosString(string_id,loc_idx);
2210 char buf[1000];
2212 va_list argptr;
2213 va_start( argptr, string_id );
2214 vsnprintf( buf,1000, text, argptr );
2215 va_end( argptr );
2217 char* pos = &buf[0];
2219 while(char* line = ChatHandler::LineFromMessage(pos))
2221 WorldPacket* data = new WorldPacket();
2222 ChatHandler::FillMessageData(data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2223 data_list->push_back(data);
2226 else
2227 data_list = &data_cache[cache_idx];
2229 for(int i = 0; i < data_list->size(); ++i)
2230 itr->second->SendPacket((*data_list)[i]);
2233 // free memory
2234 for(int i = 0; i < data_cache.size(); ++i)
2235 for(int j = 0; j < data_cache[i].size(); ++j)
2236 delete data_cache[i][j];
2239 /// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2240 void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
2242 SessionMap::iterator itr;
2243 for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2245 if (itr->second &&
2246 itr->second->GetPlayer() &&
2247 itr->second->GetPlayer()->IsInWorld() &&
2248 itr->second->GetPlayer()->GetZoneId() == zone &&
2249 itr->second != self &&
2250 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2252 itr->second->SendPacket(packet);
2257 /// Send a System Message to all players in the zone (except self if mentioned)
2258 void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
2260 WorldPacket data;
2261 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
2262 SendZoneMessage(zone, &data, self,team);
2265 /// Kick (and save) all players
2266 void World::KickAll()
2268 m_QueuedPlayer.clear(); // prevent send queue update packet and login queued sessions
2270 // session not removed at kick and will removed in next update tick
2271 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2272 itr->second->KickPlayer();
2275 /// Kick (and save) all players with security level less `sec`
2276 void World::KickAllLess(AccountTypes sec)
2278 // session not removed at kick and will removed in next update tick
2279 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2280 if(itr->second->GetSecurity() < sec)
2281 itr->second->KickPlayer();
2284 /// Kick (and save) the designated player
2285 bool World::KickPlayer(const std::string& playerName)
2287 SessionMap::iterator itr;
2289 // session not removed at kick and will removed in next update tick
2290 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2292 if(!itr->second)
2293 continue;
2294 Player *player = itr->second->GetPlayer();
2295 if(!player)
2296 continue;
2297 if( player->IsInWorld() )
2299 if (playerName == player->GetName())
2301 itr->second->KickPlayer();
2302 return true;
2306 return false;
2309 /// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2310 BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, std::string duration, std::string reason, std::string author)
2312 loginDatabase.escape_string(nameOrIP);
2313 loginDatabase.escape_string(reason);
2314 std::string safe_author=author;
2315 loginDatabase.escape_string(safe_author);
2317 uint32 duration_secs = TimeStringToSecs(duration);
2318 QueryResult *resultAccounts = NULL; //used for kicking
2320 ///- Update the database with ban information
2321 switch(mode)
2323 case BAN_IP:
2324 //No SQL injection as strings are escaped
2325 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
2326 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());
2327 break;
2328 case BAN_ACCOUNT:
2329 //No SQL injection as string is escaped
2330 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2331 break;
2332 case BAN_CHARACTER:
2333 //No SQL injection as string is escaped
2334 resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2335 break;
2336 default:
2337 return BAN_SYNTAX_ERROR;
2340 if(!resultAccounts)
2342 if(mode==BAN_IP)
2343 return BAN_SUCCESS; // ip correctly banned but nobody affected (yet)
2344 else
2345 return BAN_NOTFOUND; // Nobody to ban
2348 ///- Disconnect all affected players (for IP it can be several)
2351 Field* fieldsAccount = resultAccounts->Fetch();
2352 uint32 account = fieldsAccount->GetUInt32();
2354 if(mode!=BAN_IP)
2356 //No SQL injection as strings are escaped
2357 loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2358 account,duration_secs,safe_author.c_str(),reason.c_str());
2361 if (WorldSession* sess = FindSession(account))
2362 if(std::string(sess->GetPlayerName()) != author)
2363 sess->KickPlayer();
2365 while( resultAccounts->NextRow() );
2367 delete resultAccounts;
2368 return BAN_SUCCESS;
2371 /// Remove a ban from an account or IP address
2372 bool World::RemoveBanAccount(BanMode mode, std::string nameOrIP)
2374 if (mode == BAN_IP)
2376 loginDatabase.escape_string(nameOrIP);
2377 loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
2379 else
2381 uint32 account = 0;
2382 if (mode == BAN_ACCOUNT)
2383 account = accmgr.GetId (nameOrIP);
2384 else if (mode == BAN_CHARACTER)
2385 account = objmgr.GetPlayerAccountIdByPlayerName (nameOrIP);
2387 if (!account)
2388 return false;
2390 //NO SQL injection as account is uint32
2391 loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
2393 return true;
2396 /// Update the game time
2397 void World::_UpdateGameTime()
2399 ///- update the time
2400 time_t thisTime = time(NULL);
2401 uint32 elapsed = uint32(thisTime - m_gameTime);
2402 m_gameTime = thisTime;
2404 ///- if there is a shutdown timer
2405 if(!m_stopEvent && m_ShutdownTimer > 0 && elapsed > 0)
2407 ///- ... and it is overdue, stop the world (set m_stopEvent)
2408 if( m_ShutdownTimer <= elapsed )
2410 if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2411 m_stopEvent = true; // exist code already set
2412 else
2413 m_ShutdownTimer = 1; // minimum timer value to wait idle state
2415 ///- ... else decrease it and if necessary display a shutdown countdown to the users
2416 else
2418 m_ShutdownTimer -= elapsed;
2420 ShutdownMsg();
2425 /// Shutdown the server
2426 void World::ShutdownServ(uint32 time, uint32 options, uint8 exitcode)
2428 // ignore if server shutdown at next tick
2429 if(m_stopEvent)
2430 return;
2432 m_ShutdownMask = options;
2433 m_ExitCode = exitcode;
2435 ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2436 if(time==0)
2438 if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2439 m_stopEvent = true; // exist code already set
2440 else
2441 m_ShutdownTimer = 1; //So that the session count is re-evaluated at next world tick
2443 ///- Else set the shutdown timer and warn users
2444 else
2446 m_ShutdownTimer = time;
2447 ShutdownMsg(true);
2451 /// Display a shutdown message to the user(s)
2452 void World::ShutdownMsg(bool show, Player* player)
2454 // not show messages for idle shutdown mode
2455 if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
2456 return;
2458 ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2459 if ( show ||
2460 (m_ShutdownTimer < 10) ||
2461 // < 30 sec; every 5 sec
2462 (m_ShutdownTimer<30 && (m_ShutdownTimer % 5 )==0) ||
2463 // < 5 min ; every 1 min
2464 (m_ShutdownTimer<5*MINUTE && (m_ShutdownTimer % MINUTE )==0) ||
2465 // < 30 min ; every 5 min
2466 (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
2467 // < 12 h ; every 1 h
2468 (m_ShutdownTimer<12*HOUR && (m_ShutdownTimer % HOUR )==0) ||
2469 // > 12 h ; every 12 h
2470 (m_ShutdownTimer>12*HOUR && (m_ShutdownTimer % (12*HOUR) )==0))
2472 std::string str = secsToTimeString(m_ShutdownTimer);
2474 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
2476 SendServerMessage(msgid,str.c_str(),player);
2477 DEBUG_LOG("Server is %s in %s",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"),str.c_str());
2481 /// Cancel a planned server shutdown
2482 void World::ShutdownCancel()
2484 // nothing cancel or too later
2485 if(!m_ShutdownTimer || m_stopEvent)
2486 return;
2488 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2490 m_ShutdownMask = 0;
2491 m_ShutdownTimer = 0;
2492 m_ExitCode = SHUTDOWN_EXIT_CODE; // to default value
2493 SendServerMessage(msgid);
2495 DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2498 /// Send a server message to the user(s)
2499 void World::SendServerMessage(uint32 type, const char *text, Player* player)
2501 WorldPacket data(SMSG_SERVER_MESSAGE, 50); // guess size
2502 data << uint32(type);
2503 if(type <= SERVER_MSG_STRING)
2504 data << text;
2506 if(player)
2507 player->GetSession()->SendPacket(&data);
2508 else
2509 SendGlobalMessage( &data );
2512 void World::UpdateSessions( time_t diff )
2514 ///- Add new sessions
2515 while(!addSessQueue.empty())
2517 WorldSession* sess = addSessQueue.next ();
2518 AddSession_ (sess);
2521 ///- Then send an update signal to remaining ones
2522 for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2524 next = itr;
2525 ++next;
2527 if(!itr->second)
2528 continue;
2530 ///- and remove not active sessions from the list
2531 if(!itr->second->Update(diff)) // As interval = 0
2533 RemoveQueuedPlayer (itr->second);
2534 delete itr->second;
2535 m_sessions.erase(itr);
2540 // This handles the issued and queued CLI commands
2541 void World::ProcessCliCommands()
2543 if (cliCmdQueue.empty())
2544 return;
2546 CliCommandHolder::Print* zprint;
2548 while (!cliCmdQueue.empty())
2550 sLog.outDebug("CLI command under processing...");
2551 CliCommandHolder *command = cliCmdQueue.next();
2553 zprint = command->m_print;
2555 CliHandler(zprint).ParseCommands(command->m_command);
2557 delete command;
2560 // print the console message here so it looks right
2561 zprint("mangos>");
2564 void World::InitResultQueue()
2566 m_resultQueue = new SqlResultQueue;
2567 CharacterDatabase.SetResultQueue(m_resultQueue);
2570 void World::UpdateResultQueue()
2572 m_resultQueue->Update();
2575 void World::UpdateRealmCharCount(uint32 accountId)
2577 CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2578 "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2581 void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2583 if (resultCharCount)
2585 Field *fields = resultCharCount->Fetch();
2586 uint32 charCount = fields[0].GetUInt32();
2587 delete resultCharCount;
2588 loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2589 loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2593 void World::InitDailyQuestResetTime()
2595 time_t mostRecentQuestTime;
2597 QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2598 if(result)
2600 Field *fields = result->Fetch();
2602 mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2603 delete result;
2605 else
2606 mostRecentQuestTime = 0;
2608 // client built-in time for reset is 6:00 AM
2609 // FIX ME: client not show day start time
2610 time_t curTime = time(NULL);
2611 tm localTm = *localtime(&curTime);
2612 localTm.tm_hour = 6;
2613 localTm.tm_min = 0;
2614 localTm.tm_sec = 0;
2616 // current day reset time
2617 time_t curDayResetTime = mktime(&localTm);
2619 // last reset time before current moment
2620 time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2622 // need reset (if we have quest time before last reset time (not processed by some reason)
2623 if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2624 m_NextDailyQuestReset = mostRecentQuestTime;
2625 else
2627 // plan next reset time
2628 m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2632 void World::ResetDailyQuests()
2634 sLog.outDetail("Daily quests reset for all characters.");
2635 CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2636 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2637 if(itr->second->GetPlayer())
2638 itr->second->GetPlayer()->ResetDailyQuestStatus();
2641 void World::SetPlayerLimit( int32 limit, bool needUpdate )
2643 if(limit < -SEC_ADMINISTRATOR)
2644 limit = -SEC_ADMINISTRATOR;
2646 // lock update need
2647 bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2649 m_playerLimit = limit;
2651 if(db_update_need)
2652 loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2655 void World::UpdateMaxSessionCounters()
2657 m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2658 m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2661 void World::LoadDBVersion()
2663 QueryResult* result = WorldDatabase.Query("SELECT version FROM db_version LIMIT 1");
2664 if(result)
2666 Field* fields = result->Fetch();
2668 m_DBVersion = fields[0].GetString();
2669 delete result;
2671 else
2672 m_DBVersion = "unknown world database";