[6862] Some additional mangosd.conf options for player startup and gameplay customizing.
[getmangos.git] / src / game / World.cpp
blob8ee55172b8f1330e27d8c97cea1258121b0b60f6
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 VMAP::VMapFactory::clear();
130 if(m_resultQueue) delete m_resultQueue;
132 //TODO free addSessQueue
135 /// Find a player in a specified zone
136 Player* World::FindPlayerInZone(uint32 zone)
138 ///- circle through active sessions and return the first player found in the zone
139 SessionMap::iterator itr;
140 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
142 if(!itr->second)
143 continue;
144 Player *player = itr->second->GetPlayer();
145 if(!player)
146 continue;
147 if( player->IsInWorld() && player->GetZoneId() == zone )
149 // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone.
150 return player;
153 return NULL;
156 /// Find a session by its id
157 WorldSession* World::FindSession(uint32 id) const
159 SessionMap::const_iterator itr = m_sessions.find(id);
161 if(itr != m_sessions.end())
162 return itr->second; // also can return NULL for kicked session
163 else
164 return NULL;
167 /// Remove a given session
168 bool World::RemoveSession(uint32 id)
170 ///- Find the session, kick the user, but we can't delete session at this moment to prevent iterator invalidation
171 SessionMap::iterator itr = m_sessions.find(id);
173 if(itr != m_sessions.end() && itr->second)
175 if (itr->second->PlayerLoading())
176 return false;
177 itr->second->KickPlayer();
180 return true;
183 void World::AddSession(WorldSession* s)
185 addSessQueue.add(s);
188 void
189 World::AddSession_ (WorldSession* s)
191 ASSERT (s);
193 //NOTE - Still there is race condition in WorldSession* being used in the Sockets
195 ///- kick already loaded player with same account (if any) and remove session
196 ///- if player is in loading and want to load again, return
197 if (!RemoveSession (s->GetAccountId ()))
199 s->KickPlayer ();
200 delete s; // session not added yet in session list, so not listed in queue
201 return;
204 // decrease session counts only at not reconnection case
205 bool decrease_session = true;
207 // if session already exist, prepare to it deleting at next world update
208 // NOTE - KickPlayer() should be called on "old" in RemoveSession()
210 SessionMap::const_iterator old = m_sessions.find(s->GetAccountId ());
212 if(old != m_sessions.end())
214 // prevent decrease sessions count if session queued
215 if(RemoveQueuedPlayer(old->second))
216 decrease_session = false;
217 // not remove replaced session form queue if listed
218 delete old->second;
222 m_sessions[s->GetAccountId ()] = s;
224 uint32 Sessions = GetActiveAndQueuedSessionCount ();
225 uint32 pLimit = GetPlayerAmountLimit ();
226 uint32 QueueSize = GetQueueSize (); //number of players in the queue
228 //so we don't count the user trying to
229 //login as a session and queue the socket that we are using
230 if(decrease_session)
231 --Sessions;
233 if (pLimit > 0 && Sessions >= pLimit && s->GetSecurity () == SEC_PLAYER )
235 AddQueuedPlayer (s);
236 UpdateMaxSessionCounters ();
237 sLog.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s->GetAccountId (), ++QueueSize);
238 return;
241 WorldPacket packet(SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
242 packet << uint8 (AUTH_OK);
243 packet << uint32 (0); // unknown random value...
244 packet << uint8 (0);
245 packet << uint32 (0);
246 packet << uint8 (s->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
247 s->SendPacket (&packet);
249 UpdateMaxSessionCounters ();
251 // Updates the population
252 if (pLimit > 0)
254 float popu = GetActiveSessionCount (); //updated number of users on the server
255 popu /= pLimit;
256 popu *= 2;
257 loginDatabase.PExecute ("UPDATE realmlist SET population = '%f' WHERE id = '%d'", popu, realmID);
258 sLog.outDetail ("Server Population (%f).", popu);
262 int32 World::GetQueuePos(WorldSession* sess)
264 uint32 position = 1;
266 for(Queue::iterator iter = m_QueuedPlayer.begin(); iter != m_QueuedPlayer.end(); ++iter, ++position)
267 if((*iter) == sess)
268 return position;
270 return 0;
273 void World::AddQueuedPlayer(WorldSession* sess)
275 sess->SetInQueue(true);
276 m_QueuedPlayer.push_back (sess);
278 // The 1st SMSG_AUTH_RESPONSE needs to contain other info too.
279 WorldPacket packet (SMSG_AUTH_RESPONSE, 1 + 4 + 1 + 4 + 1);
280 packet << uint8 (AUTH_WAIT_QUEUE);
281 packet << uint32 (0); // unknown random value...
282 packet << uint8 (0);
283 packet << uint32 (0);
284 packet << uint8 (sess->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
285 packet << uint32(GetQueuePos (sess));
286 sess->SendPacket (&packet);
288 //sess->SendAuthWaitQue (GetQueuePos (sess));
291 bool World::RemoveQueuedPlayer(WorldSession* sess)
293 // sessions count including queued to remove (if removed_session set)
294 uint32 sessions = GetActiveSessionCount();
296 uint32 position = 1;
297 Queue::iterator iter = m_QueuedPlayer.begin();
299 // search to remove and count skipped positions
300 bool found = false;
302 for(;iter != m_QueuedPlayer.end(); ++iter, ++position)
304 if(*iter==sess)
306 sess->SetInQueue(false);
307 iter = m_QueuedPlayer.erase(iter);
308 found = true; // removing queued session
309 break;
313 // iter point to next socked after removed or end()
314 // position store position of removed socket and then new position next socket after removed
316 // if session not queued then we need decrease sessions count
317 if(!found && sessions)
318 --sessions;
320 // accept first in queue
321 if( (!m_playerLimit || sessions < m_playerLimit) && !m_QueuedPlayer.empty() )
323 WorldSession* pop_sess = m_QueuedPlayer.front();
324 pop_sess->SetInQueue(false);
325 pop_sess->SendAuthWaitQue(0);
326 m_QueuedPlayer.pop_front();
328 // update iter to point first queued socket or end() if queue is empty now
329 iter = m_QueuedPlayer.begin();
330 position = 1;
333 // update position from iter to end()
334 // iter point to first not updated socket, position store new position
335 for(; iter != m_QueuedPlayer.end(); ++iter, ++position)
336 (*iter)->SendAuthWaitQue(position);
338 return found;
341 /// Find a Weather object by the given zoneid
342 Weather* World::FindWeather(uint32 id) const
344 WeatherMap::const_iterator itr = m_weathers.find(id);
346 if(itr != m_weathers.end())
347 return itr->second;
348 else
349 return 0;
352 /// Remove a Weather object for the given zoneid
353 void World::RemoveWeather(uint32 id)
355 // not called at the moment. Kept for completeness
356 WeatherMap::iterator itr = m_weathers.find(id);
358 if(itr != m_weathers.end())
360 delete itr->second;
361 m_weathers.erase(itr);
365 /// Add a Weather object to the list
366 Weather* World::AddWeather(uint32 zone_id)
368 WeatherZoneChances const* weatherChances = objmgr.GetWeatherChances(zone_id);
370 // zone not have weather, ignore
371 if(!weatherChances)
372 return NULL;
374 Weather* w = new Weather(zone_id,weatherChances);
375 m_weathers[w->GetZone()] = w;
376 w->ReGenerate();
377 w->UpdateWeather();
378 return w;
381 /// Initialize config values
382 void World::LoadConfigSettings(bool reload)
384 if(reload)
386 if(!sConfig.Reload())
388 sLog.outError("World settings reload fail: can't read settings from %s.",sConfig.GetFilename().c_str());
389 return;
393 ///- Read the version of the configuration file and warn the user in case of emptiness or mismatch
394 uint32 confVersion = sConfig.GetIntDefault("ConfVersion", 0);
395 if(!confVersion)
397 sLog.outError("*****************************************************************************");
398 sLog.outError(" WARNING: mangosd.conf does not include a ConfVersion variable.");
399 sLog.outError(" Your configuration file may be out of date!");
400 sLog.outError("*****************************************************************************");
401 clock_t pause = 3000 + clock();
402 while (pause > clock());
404 else
406 if (confVersion < _MANGOSDCONFVERSION)
408 sLog.outError("*****************************************************************************");
409 sLog.outError(" WARNING: Your mangosd.conf version indicates your conf file is out of date!");
410 sLog.outError(" Please check for updates, as your current default values may cause");
411 sLog.outError(" unexpected behavior.");
412 sLog.outError("*****************************************************************************");
413 clock_t pause = 3000 + clock();
414 while (pause > clock());
418 ///- Read the player limit and the Message of the day from the config file
419 SetPlayerLimit( sConfig.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT), true );
420 SetMotd( sConfig.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
422 ///- Read all rates from the config file
423 rate_values[RATE_HEALTH] = sConfig.GetFloatDefault("Rate.Health", 1);
424 if(rate_values[RATE_HEALTH] < 0)
426 sLog.outError("Rate.Health (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_HEALTH]);
427 rate_values[RATE_HEALTH] = 1;
429 rate_values[RATE_POWER_MANA] = sConfig.GetFloatDefault("Rate.Mana", 1);
430 if(rate_values[RATE_POWER_MANA] < 0)
432 sLog.outError("Rate.Mana (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_POWER_MANA]);
433 rate_values[RATE_POWER_MANA] = 1;
435 rate_values[RATE_POWER_RAGE_INCOME] = sConfig.GetFloatDefault("Rate.Rage.Income", 1);
436 rate_values[RATE_POWER_RAGE_LOSS] = sConfig.GetFloatDefault("Rate.Rage.Loss", 1);
437 if(rate_values[RATE_POWER_RAGE_LOSS] < 0)
439 sLog.outError("Rate.Rage.Loss (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_POWER_RAGE_LOSS]);
440 rate_values[RATE_POWER_RAGE_LOSS] = 1;
442 rate_values[RATE_POWER_FOCUS] = sConfig.GetFloatDefault("Rate.Focus", 1.0f);
443 rate_values[RATE_LOYALTY] = sConfig.GetFloatDefault("Rate.Loyalty", 1.0f);
444 rate_values[RATE_SKILL_DISCOVERY] = sConfig.GetFloatDefault("Rate.Skill.Discovery", 1.0f);
445 rate_values[RATE_DROP_ITEM_POOR] = sConfig.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f);
446 rate_values[RATE_DROP_ITEM_NORMAL] = sConfig.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f);
447 rate_values[RATE_DROP_ITEM_UNCOMMON] = sConfig.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f);
448 rate_values[RATE_DROP_ITEM_RARE] = sConfig.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f);
449 rate_values[RATE_DROP_ITEM_EPIC] = sConfig.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f);
450 rate_values[RATE_DROP_ITEM_LEGENDARY] = sConfig.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f);
451 rate_values[RATE_DROP_ITEM_ARTIFACT] = sConfig.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f);
452 rate_values[RATE_DROP_ITEM_REFERENCED] = sConfig.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f);
453 rate_values[RATE_DROP_MONEY] = sConfig.GetFloatDefault("Rate.Drop.Money", 1.0f);
454 rate_values[RATE_XP_KILL] = sConfig.GetFloatDefault("Rate.XP.Kill", 1.0f);
455 rate_values[RATE_XP_QUEST] = sConfig.GetFloatDefault("Rate.XP.Quest", 1.0f);
456 rate_values[RATE_XP_EXPLORE] = sConfig.GetFloatDefault("Rate.XP.Explore", 1.0f);
457 rate_values[RATE_XP_PAST_70] = sConfig.GetFloatDefault("Rate.XP.PastLevel70", 1.0f);
458 rate_values[RATE_REPUTATION_GAIN] = sConfig.GetFloatDefault("Rate.Reputation.Gain", 1.0f);
459 rate_values[RATE_CREATURE_NORMAL_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f);
460 rate_values[RATE_CREATURE_ELITE_ELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f);
461 rate_values[RATE_CREATURE_ELITE_RAREELITE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f);
462 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f);
463 rate_values[RATE_CREATURE_ELITE_RARE_DAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f);
464 rate_values[RATE_CREATURE_NORMAL_HP] = sConfig.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f);
465 rate_values[RATE_CREATURE_ELITE_ELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f);
466 rate_values[RATE_CREATURE_ELITE_RAREELITE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f);
467 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f);
468 rate_values[RATE_CREATURE_ELITE_RARE_HP] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f);
469 rate_values[RATE_CREATURE_NORMAL_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f);
470 rate_values[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f);
471 rate_values[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f);
472 rate_values[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f);
473 rate_values[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE] = sConfig.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f);
474 rate_values[RATE_CREATURE_AGGRO] = sConfig.GetFloatDefault("Rate.Creature.Aggro", 1.0f);
475 rate_values[RATE_REST_INGAME] = sConfig.GetFloatDefault("Rate.Rest.InGame", 1.0f);
476 rate_values[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY] = sConfig.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f);
477 rate_values[RATE_REST_OFFLINE_IN_WILDERNESS] = sConfig.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f);
478 rate_values[RATE_DAMAGE_FALL] = sConfig.GetFloatDefault("Rate.Damage.Fall", 1.0f);
479 rate_values[RATE_AUCTION_TIME] = sConfig.GetFloatDefault("Rate.Auction.Time", 1.0f);
480 rate_values[RATE_AUCTION_DEPOSIT] = sConfig.GetFloatDefault("Rate.Auction.Deposit", 1.0f);
481 rate_values[RATE_AUCTION_CUT] = sConfig.GetFloatDefault("Rate.Auction.Cut", 1.0f);
482 rate_values[RATE_HONOR] = sConfig.GetFloatDefault("Rate.Honor",1.0f);
483 rate_values[RATE_MINING_AMOUNT] = sConfig.GetFloatDefault("Rate.Mining.Amount",1.0f);
484 rate_values[RATE_MINING_NEXT] = sConfig.GetFloatDefault("Rate.Mining.Next",1.0f);
485 rate_values[RATE_INSTANCE_RESET_TIME] = sConfig.GetFloatDefault("Rate.InstanceResetTime",1.0f);
486 rate_values[RATE_TALENT] = sConfig.GetFloatDefault("Rate.Talent",1.0f);
487 if(rate_values[RATE_TALENT] < 0.0f)
489 sLog.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values[RATE_TALENT]);
490 rate_values[RATE_TALENT] = 1.0f;
492 rate_values[RATE_CORPSE_DECAY_LOOTED] = sConfig.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f);
494 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = sConfig.GetFloatDefault("TargetPosRecalculateRange",1.5f);
495 if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] < CONTACT_DISTANCE)
497 sLog.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],CONTACT_DISTANCE,CONTACT_DISTANCE);
498 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = CONTACT_DISTANCE;
500 else if(rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] > ATTACK_DISTANCE)
502 sLog.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",
503 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE],ATTACK_DISTANCE,ATTACK_DISTANCE);
504 rate_values[RATE_TARGET_POS_RECALCULATION_RANGE] = ATTACK_DISTANCE;
507 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = sConfig.GetFloatDefault("DurabilityLossChance.Damage",0.5f);
508 if(rate_values[RATE_DURABILITY_LOSS_DAMAGE] < 0.0f)
510 sLog.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_DAMAGE]);
511 rate_values[RATE_DURABILITY_LOSS_DAMAGE] = 0.0f;
513 rate_values[RATE_DURABILITY_LOSS_ABSORB] = sConfig.GetFloatDefault("DurabilityLossChance.Absorb",0.5f);
514 if(rate_values[RATE_DURABILITY_LOSS_ABSORB] < 0.0f)
516 sLog.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_ABSORB]);
517 rate_values[RATE_DURABILITY_LOSS_ABSORB] = 0.0f;
519 rate_values[RATE_DURABILITY_LOSS_PARRY] = sConfig.GetFloatDefault("DurabilityLossChance.Parry",0.05f);
520 if(rate_values[RATE_DURABILITY_LOSS_PARRY] < 0.0f)
522 sLog.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_PARRY]);
523 rate_values[RATE_DURABILITY_LOSS_PARRY] = 0.0f;
525 rate_values[RATE_DURABILITY_LOSS_BLOCK] = sConfig.GetFloatDefault("DurabilityLossChance.Block",0.05f);
526 if(rate_values[RATE_DURABILITY_LOSS_BLOCK] < 0.0f)
528 sLog.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values[RATE_DURABILITY_LOSS_BLOCK]);
529 rate_values[RATE_DURABILITY_LOSS_BLOCK] = 0.0f;
532 ///- Read other configuration items from the config file
534 m_configs[CONFIG_COMPRESSION] = sConfig.GetIntDefault("Compression", 1);
535 if(m_configs[CONFIG_COMPRESSION] < 1 || m_configs[CONFIG_COMPRESSION] > 9)
537 sLog.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs[CONFIG_COMPRESSION]);
538 m_configs[CONFIG_COMPRESSION] = 1;
540 m_configs[CONFIG_ADDON_CHANNEL] = sConfig.GetBoolDefault("AddonChannel", true);
541 m_configs[CONFIG_GRID_UNLOAD] = sConfig.GetBoolDefault("GridUnload", true);
542 m_configs[CONFIG_INTERVAL_SAVE] = sConfig.GetIntDefault("PlayerSaveInterval", 900000);
544 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = sConfig.GetIntDefault("GridCleanUpDelay", 300000);
545 if(m_configs[CONFIG_INTERVAL_GRIDCLEAN] < MIN_GRID_DELAY)
547 sLog.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_GRIDCLEAN],MIN_GRID_DELAY);
548 m_configs[CONFIG_INTERVAL_GRIDCLEAN] = MIN_GRID_DELAY;
550 if(reload)
551 MapManager::Instance().SetGridCleanUpDelay(m_configs[CONFIG_INTERVAL_GRIDCLEAN]);
553 m_configs[CONFIG_INTERVAL_MAPUPDATE] = sConfig.GetIntDefault("MapUpdateInterval", 100);
554 if(m_configs[CONFIG_INTERVAL_MAPUPDATE] < MIN_MAP_UPDATE_DELAY)
556 sLog.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs[CONFIG_INTERVAL_MAPUPDATE],MIN_MAP_UPDATE_DELAY);
557 m_configs[CONFIG_INTERVAL_MAPUPDATE] = MIN_MAP_UPDATE_DELAY;
559 if(reload)
560 MapManager::Instance().SetMapUpdateInterval(m_configs[CONFIG_INTERVAL_MAPUPDATE]);
562 m_configs[CONFIG_INTERVAL_CHANGEWEATHER] = sConfig.GetIntDefault("ChangeWeatherInterval", 600000);
564 if(reload)
566 uint32 val = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
567 if(val!=m_configs[CONFIG_PORT_WORLD])
568 sLog.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_PORT_WORLD]);
570 else
571 m_configs[CONFIG_PORT_WORLD] = sConfig.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT);
573 if(reload)
575 uint32 val = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
576 if(val!=m_configs[CONFIG_SOCKET_SELECTTIME])
577 sLog.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[DEFAULT_SOCKET_SELECT_TIME]);
579 else
580 m_configs[CONFIG_SOCKET_SELECTTIME] = sConfig.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME);
582 m_configs[CONFIG_GROUP_XP_DISTANCE] = sConfig.GetIntDefault("MaxGroupXPDistance", 74);
583 /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
584 m_configs[CONFIG_SIGHT_MONSTER] = sConfig.GetIntDefault("MonsterSight", 50);
585 m_configs[CONFIG_SIGHT_GUARDER] = sConfig.GetIntDefault("GuarderSight", 50);
587 if(reload)
589 uint32 val = sConfig.GetIntDefault("GameType", 0);
590 if(val!=m_configs[CONFIG_GAME_TYPE])
591 sLog.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_GAME_TYPE]);
593 else
594 m_configs[CONFIG_GAME_TYPE] = sConfig.GetIntDefault("GameType", 0);
596 if(reload)
598 uint32 val = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
599 if(val!=m_configs[CONFIG_REALM_ZONE])
600 sLog.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_REALM_ZONE]);
602 else
603 m_configs[CONFIG_REALM_ZONE] = sConfig.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT);
605 m_configs[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS] = sConfig.GetBoolDefault("AllowTwoSide.Accounts", false);
606 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
607 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
608 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
609 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
610 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
611 m_configs[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL] = sConfig.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
612 m_configs[CONFIG_ALLOW_TWO_SIDE_WHO_LIST] = sConfig.GetBoolDefault("AllowTwoSide.WhoList", false);
613 m_configs[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND] = sConfig.GetBoolDefault("AllowTwoSide.AddFriend", false);
614 m_configs[CONFIG_STRICT_PLAYER_NAMES] = sConfig.GetIntDefault("StrictPlayerNames", 0);
615 m_configs[CONFIG_STRICT_CHARTER_NAMES] = sConfig.GetIntDefault("StrictCharterNames", 0);
616 m_configs[CONFIG_STRICT_PET_NAMES] = sConfig.GetIntDefault("StrictPetNames", 0);
618 m_configs[CONFIG_CHARACTERS_CREATING_DISABLED] = sConfig.GetIntDefault("CharactersCreatingDisabled", 0);
620 m_configs[CONFIG_CHARACTERS_PER_REALM] = sConfig.GetIntDefault("CharactersPerRealm", 10);
621 if(m_configs[CONFIG_CHARACTERS_PER_REALM] < 1 || m_configs[CONFIG_CHARACTERS_PER_REALM] > 10)
623 sLog.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs[CONFIG_CHARACTERS_PER_REALM]);
624 m_configs[CONFIG_CHARACTERS_PER_REALM] = 10;
627 // must be after CONFIG_CHARACTERS_PER_REALM
628 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = sConfig.GetIntDefault("CharactersPerAccount", 50);
629 if(m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] < m_configs[CONFIG_CHARACTERS_PER_REALM])
631 sLog.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs[CONFIG_CHARACTERS_PER_ACCOUNT],m_configs[CONFIG_CHARACTERS_PER_REALM]);
632 m_configs[CONFIG_CHARACTERS_PER_ACCOUNT] = m_configs[CONFIG_CHARACTERS_PER_REALM];
635 m_configs[CONFIG_SKIP_CINEMATICS] = sConfig.GetIntDefault("SkipCinematics", 0);
636 if(m_configs[CONFIG_SKIP_CINEMATICS] < 0 || m_configs[CONFIG_SKIP_CINEMATICS] > 2)
638 sLog.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs[CONFIG_SKIP_CINEMATICS]);
639 m_configs[CONFIG_SKIP_CINEMATICS] = 0;
642 if(reload)
644 uint32 val = sConfig.GetIntDefault("MaxPlayerLevel", 60);
645 if(val!=m_configs[CONFIG_MAX_PLAYER_LEVEL])
646 sLog.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
648 else
649 m_configs[CONFIG_MAX_PLAYER_LEVEL] = sConfig.GetIntDefault("MaxPlayerLevel", 60);
650 if(m_configs[CONFIG_MAX_PLAYER_LEVEL] > 255)
652 sLog.outError("MaxPlayerLevel (%i) must be in range 1..255. Set to 255.",m_configs[CONFIG_MAX_PLAYER_LEVEL]);
653 m_configs[CONFIG_MAX_PLAYER_LEVEL] = 255;
656 m_configs[CONFIG_START_PLAYER_LEVEL] = sConfig.GetIntDefault("StartPlayerLevel", 1);
657 if(m_configs[CONFIG_START_PLAYER_LEVEL] < 1)
659 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]);
660 m_configs[CONFIG_START_PLAYER_LEVEL] = 1;
662 else if(m_configs[CONFIG_START_PLAYER_LEVEL] > m_configs[CONFIG_MAX_PLAYER_LEVEL])
664 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]);
665 m_configs[CONFIG_START_PLAYER_LEVEL] = m_configs[CONFIG_MAX_PLAYER_LEVEL];
668 m_configs[CONFIG_START_PLAYER_MONEY] = sConfig.GetIntDefault("StartPlayerMoney", 0);
669 if(m_configs[CONFIG_START_PLAYER_MONEY] < 0)
671 sLog.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",m_configs[CONFIG_START_PLAYER_MONEY],MAX_MONEY_AMOUNT,0);
672 m_configs[CONFIG_START_PLAYER_MONEY] = 0;
674 else if(m_configs[CONFIG_START_PLAYER_MONEY] > MAX_MONEY_AMOUNT)
676 sLog.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",
677 m_configs[CONFIG_START_PLAYER_MONEY],MAX_MONEY_AMOUNT,MAX_MONEY_AMOUNT);
678 m_configs[CONFIG_START_PLAYER_MONEY] = MAX_MONEY_AMOUNT;
681 m_configs[CONFIG_MAX_HONOR_POINTS] = sConfig.GetIntDefault("MaxHonorPoints", 75000);
682 if(m_configs[CONFIG_MAX_HONOR_POINTS] < 0)
684 sLog.outError("MaxHonorPoints (%i) can't be negative. Set to 0.",m_configs[CONFIG_MAX_HONOR_POINTS]);
685 m_configs[CONFIG_MAX_HONOR_POINTS] = 0;
688 m_configs[CONFIG_START_HONOR_POINTS] = sConfig.GetIntDefault("StartHonorPoints", 0);
689 if(m_configs[CONFIG_START_HONOR_POINTS] < 0)
691 sLog.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
692 m_configs[CONFIG_START_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS],0);
693 m_configs[CONFIG_MAX_HONOR_POINTS] = 0;
695 else if(m_configs[CONFIG_START_HONOR_POINTS] > m_configs[CONFIG_MAX_HONOR_POINTS])
697 sLog.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
698 m_configs[CONFIG_START_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS],m_configs[CONFIG_MAX_HONOR_POINTS]);
699 m_configs[CONFIG_START_HONOR_POINTS] = m_configs[CONFIG_MAX_HONOR_POINTS];
702 m_configs[CONFIG_MAX_ARENA_POINTS] = sConfig.GetIntDefault("MaxArenaPoints", 5000);
703 if(m_configs[CONFIG_MAX_ARENA_POINTS] < 0)
705 sLog.outError("MaxArenaPoints (%i) can't be negative. Set to 0.",m_configs[CONFIG_MAX_ARENA_POINTS]);
706 m_configs[CONFIG_MAX_ARENA_POINTS] = 0;
709 m_configs[CONFIG_START_ARENA_POINTS] = sConfig.GetIntDefault("StartArenaPoints", 0);
710 if(m_configs[CONFIG_START_ARENA_POINTS] < 0)
712 sLog.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
713 m_configs[CONFIG_START_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS],0);
714 m_configs[CONFIG_MAX_ARENA_POINTS] = 0;
716 else if(m_configs[CONFIG_START_ARENA_POINTS] > m_configs[CONFIG_MAX_ARENA_POINTS])
718 sLog.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
719 m_configs[CONFIG_START_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS],m_configs[CONFIG_MAX_ARENA_POINTS]);
720 m_configs[CONFIG_START_ARENA_POINTS] = m_configs[CONFIG_MAX_ARENA_POINTS];
723 m_configs[CONFIG_ALL_TAXI_PATHS] = sConfig.GetBoolDefault("AllFlightPaths", false);
725 m_configs[CONFIG_INSTANCE_IGNORE_LEVEL] = sConfig.GetBoolDefault("Instance.IgnoreLevel", false);
726 m_configs[CONFIG_INSTANCE_IGNORE_RAID] = sConfig.GetBoolDefault("Instance.IgnoreRaid", false);
728 m_configs[CONFIG_BATTLEGROUND_CAST_DESERTER] = sConfig.GetBoolDefault("Battleground.CastDeserter", true);
729 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.Enable", true);
730 m_configs[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY] = sConfig.GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false);
732 m_configs[CONFIG_CAST_UNSTUCK] = sConfig.GetBoolDefault("CastUnstuck", true);
733 m_configs[CONFIG_INSTANCE_RESET_TIME_HOUR] = sConfig.GetIntDefault("Instance.ResetTimeHour", 4);
734 m_configs[CONFIG_INSTANCE_UNLOAD_DELAY] = sConfig.GetIntDefault("Instance.UnloadDelay", 1800000);
736 m_configs[CONFIG_MAX_PRIMARY_TRADE_SKILL] = sConfig.GetIntDefault("MaxPrimaryTradeSkill", 2);
737 m_configs[CONFIG_MIN_PETITION_SIGNS] = sConfig.GetIntDefault("MinPetitionSigns", 9);
738 if(m_configs[CONFIG_MIN_PETITION_SIGNS] > 9)
740 sLog.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.",m_configs[CONFIG_MIN_PETITION_SIGNS]);
741 m_configs[CONFIG_MIN_PETITION_SIGNS] = 9;
744 m_configs[CONFIG_GM_LOGIN_STATE] = sConfig.GetIntDefault("GM.LoginState",2);
745 m_configs[CONFIG_GM_ACCEPT_TICKETS] = sConfig.GetIntDefault("GM.AcceptTickets",2);
746 m_configs[CONFIG_GM_CHAT] = sConfig.GetIntDefault("GM.Chat",2);
747 m_configs[CONFIG_GM_WISPERING_TO] = sConfig.GetIntDefault("GM.WhisperingTo",2);
749 m_configs[CONFIG_GM_IN_GM_LIST] = sConfig.GetBoolDefault("GM.InGMList",false);
750 m_configs[CONFIG_GM_IN_WHO_LIST] = sConfig.GetBoolDefault("GM.InWhoList",false);
751 m_configs[CONFIG_GM_LOG_TRADE] = sConfig.GetBoolDefault("GM.LogTrade", false);
753 m_configs[CONFIG_START_GM_LEVEL] = sConfig.GetIntDefault("GM.StartLevel", 1);
754 if(m_configs[CONFIG_START_GM_LEVEL] < m_configs[CONFIG_START_PLAYER_LEVEL])
756 sLog.outError("GM.StartLevel (%i) must be in range StartPlayerLevel(%u)..255. Set to %u.",
757 m_configs[CONFIG_START_GM_LEVEL],m_configs[CONFIG_START_PLAYER_LEVEL],m_configs[CONFIG_START_PLAYER_LEVEL]);
758 m_configs[CONFIG_START_GM_LEVEL] = m_configs[CONFIG_START_PLAYER_LEVEL];
760 else if(m_configs[CONFIG_START_GM_LEVEL] > 255)
762 sLog.outError("GM.StartLevel (%i) must be in range 1..255. Set to %u.",m_configs[CONFIG_START_GM_LEVEL],255);
763 m_configs[CONFIG_START_GM_LEVEL] = 255;
766 m_configs[CONFIG_GROUP_VISIBILITY] = sConfig.GetIntDefault("Visibility.GroupMode",0);
768 m_configs[CONFIG_MAIL_DELIVERY_DELAY] = sConfig.GetIntDefault("MailDeliveryDelay",HOUR);
770 m_configs[CONFIG_UPTIME_UPDATE] = sConfig.GetIntDefault("UpdateUptimeInterval", 10);
771 if(m_configs[CONFIG_UPTIME_UPDATE]<=0)
773 sLog.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs[CONFIG_UPTIME_UPDATE]);
774 m_configs[CONFIG_UPTIME_UPDATE] = 10;
776 if(reload)
778 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
779 m_timers[WUPDATE_UPTIME].Reset();
782 m_configs[CONFIG_SKILL_CHANCE_ORANGE] = sConfig.GetIntDefault("SkillChance.Orange",100);
783 m_configs[CONFIG_SKILL_CHANCE_YELLOW] = sConfig.GetIntDefault("SkillChance.Yellow",75);
784 m_configs[CONFIG_SKILL_CHANCE_GREEN] = sConfig.GetIntDefault("SkillChance.Green",25);
785 m_configs[CONFIG_SKILL_CHANCE_GREY] = sConfig.GetIntDefault("SkillChance.Grey",0);
787 m_configs[CONFIG_SKILL_CHANCE_MINING_STEPS] = sConfig.GetIntDefault("SkillChance.MiningSteps",75);
788 m_configs[CONFIG_SKILL_CHANCE_SKINNING_STEPS] = sConfig.GetIntDefault("SkillChance.SkinningSteps",75);
790 m_configs[CONFIG_SKILL_PROSPECTING] = sConfig.GetBoolDefault("SkillChance.Prospecting",false);
792 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = sConfig.GetIntDefault("SkillGain.Crafting", 1);
793 if(m_configs[CONFIG_SKILL_GAIN_CRAFTING] < 0)
795 sLog.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_CRAFTING]);
796 m_configs[CONFIG_SKILL_GAIN_CRAFTING] = 1;
799 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = sConfig.GetIntDefault("SkillGain.Defense", 1);
800 if(m_configs[CONFIG_SKILL_GAIN_DEFENSE] < 0)
802 sLog.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_DEFENSE]);
803 m_configs[CONFIG_SKILL_GAIN_DEFENSE] = 1;
806 m_configs[CONFIG_SKILL_GAIN_GATHERING] = sConfig.GetIntDefault("SkillGain.Gathering", 1);
807 if(m_configs[CONFIG_SKILL_GAIN_GATHERING] < 0)
809 sLog.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_GATHERING]);
810 m_configs[CONFIG_SKILL_GAIN_GATHERING] = 1;
813 m_configs[CONFIG_SKILL_GAIN_WEAPON] = sConfig.GetIntDefault("SkillGain.Weapon", 1);
814 if(m_configs[CONFIG_SKILL_GAIN_WEAPON] < 0)
816 sLog.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs[CONFIG_SKILL_GAIN_WEAPON]);
817 m_configs[CONFIG_SKILL_GAIN_WEAPON] = 1;
820 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = sConfig.GetIntDefault("MaxOverspeedPings",2);
821 if(m_configs[CONFIG_MAX_OVERSPEED_PINGS] != 0 && m_configs[CONFIG_MAX_OVERSPEED_PINGS] < 2)
823 sLog.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs[CONFIG_MAX_OVERSPEED_PINGS]);
824 m_configs[CONFIG_MAX_OVERSPEED_PINGS] = 2;
827 m_configs[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY] = sConfig.GetBoolDefault("SaveRespawnTimeImmediately",true);
828 m_configs[CONFIG_WEATHER] = sConfig.GetBoolDefault("ActivateWeather",true);
830 m_configs[CONFIG_DISABLE_BREATHING] = sConfig.GetIntDefault("DisableWaterBreath", SEC_CONSOLE);
832 m_configs[CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL] = sConfig.GetBoolDefault("AlwaysMaxSkillForLevel", false);
834 if(reload)
836 uint32 val = sConfig.GetIntDefault("Expansion",1);
837 if(val!=m_configs[CONFIG_EXPANSION])
838 sLog.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs[CONFIG_EXPANSION]);
840 else
841 m_configs[CONFIG_EXPANSION] = sConfig.GetIntDefault("Expansion",1);
843 m_configs[CONFIG_CHATFLOOD_MESSAGE_COUNT] = sConfig.GetIntDefault("ChatFlood.MessageCount",10);
844 m_configs[CONFIG_CHATFLOOD_MESSAGE_DELAY] = sConfig.GetIntDefault("ChatFlood.MessageDelay",1);
845 m_configs[CONFIG_CHATFLOOD_MUTE_TIME] = sConfig.GetIntDefault("ChatFlood.MuteTime",10);
847 m_configs[CONFIG_EVENT_ANNOUNCE] = sConfig.GetIntDefault("Event.Announce",0);
849 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS] = sConfig.GetIntDefault("CreatureFamilyAssistanceRadius",10);
850 m_configs[CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY] = sConfig.GetIntDefault("CreatureFamilyAssistanceDelay",1500);
852 m_configs[CONFIG_WORLD_BOSS_LEVEL_DIFF] = sConfig.GetIntDefault("WorldBossLevelDiff",3);
854 // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level (255)
855 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.LowLevelHideDiff",4);
856 if(m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] > 255)
857 m_configs[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF] = 255;
858 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = sConfig.GetIntDefault("Quests.HighLevelHideDiff",7);
859 if(m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] > 255)
860 m_configs[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF] = 255;
862 m_configs[CONFIG_DETECT_POS_COLLISION] = sConfig.GetBoolDefault("DetectPosCollision", true);
864 m_configs[CONFIG_RESTRICTED_LFG_CHANNEL] = sConfig.GetBoolDefault("Channel.RestrictedLfg", true);
865 m_configs[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL] = sConfig.GetBoolDefault("Channel.SilentlyGMJoin", false);
867 m_configs[CONFIG_TALENTS_INSPECTING] = sConfig.GetBoolDefault("TalentsInspecting", true);
868 m_configs[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING] = sConfig.GetBoolDefault("ChatFakeMessagePreventing", false);
870 m_configs[CONFIG_CORPSE_DECAY_NORMAL] = sConfig.GetIntDefault("Corpse.Decay.NORMAL", 60);
871 m_configs[CONFIG_CORPSE_DECAY_RARE] = sConfig.GetIntDefault("Corpse.Decay.RARE", 300);
872 m_configs[CONFIG_CORPSE_DECAY_ELITE] = sConfig.GetIntDefault("Corpse.Decay.ELITE", 300);
873 m_configs[CONFIG_CORPSE_DECAY_RAREELITE] = sConfig.GetIntDefault("Corpse.Decay.RAREELITE", 300);
874 m_configs[CONFIG_CORPSE_DECAY_WORLDBOSS] = sConfig.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
876 m_configs[CONFIG_DEATH_SICKNESS_LEVEL] = sConfig.GetIntDefault("Death.SicknessLevel", 11);
877 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
878 m_configs[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE] = sConfig.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
880 m_configs[CONFIG_THREAT_RADIUS] = sConfig.GetIntDefault("ThreatRadius", 100);
882 // always use declined names in the russian client
883 m_configs[CONFIG_DECLINED_NAMES_USED] =
884 (m_configs[CONFIG_REALM_ZONE] == REALM_ZONE_RUSSIAN) ? true : sConfig.GetBoolDefault("DeclinedNames", false);
886 m_configs[CONFIG_LISTEN_RANGE_SAY] = sConfig.GetIntDefault("ListenRange.Say", 25);
887 m_configs[CONFIG_LISTEN_RANGE_TEXTEMOTE] = sConfig.GetIntDefault("ListenRange.TextEmote", 25);
888 m_configs[CONFIG_LISTEN_RANGE_YELL] = sConfig.GetIntDefault("ListenRange.Yell", 300);
890 m_configs[CONFIG_INSTANT_LOGOUT] = sConfig.GetIntDefault("InstantLogout", SEC_MODERATOR);
892 m_VisibleUnitGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
893 if(m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
895 sLog.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE);
896 m_VisibleUnitGreyDistance = MAX_VISIBILITY_DISTANCE;
898 m_VisibleObjectGreyDistance = sConfig.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
899 if(m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
901 sLog.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE);
902 m_VisibleObjectGreyDistance = MAX_VISIBILITY_DISTANCE;
905 m_MaxVisibleDistanceForCreature = sConfig.GetFloatDefault("Visibility.Distance.Creature", DEFAULT_VISIBILITY_DISTANCE);
906 if(m_MaxVisibleDistanceForCreature < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
908 sLog.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
909 m_MaxVisibleDistanceForCreature = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
911 else if(m_MaxVisibleDistanceForCreature + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
913 sLog.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
914 m_MaxVisibleDistanceForCreature = MAX_VISIBILITY_DISTANCE-m_VisibleUnitGreyDistance;
916 m_MaxVisibleDistanceForPlayer = sConfig.GetFloatDefault("Visibility.Distance.Player", DEFAULT_VISIBILITY_DISTANCE);
917 if(m_MaxVisibleDistanceForPlayer < 45*sWorld.getRate(RATE_CREATURE_AGGRO))
919 sLog.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld.getRate(RATE_CREATURE_AGGRO));
920 m_MaxVisibleDistanceForPlayer = 45*sWorld.getRate(RATE_CREATURE_AGGRO);
922 else if(m_MaxVisibleDistanceForPlayer + m_VisibleUnitGreyDistance > MAX_VISIBILITY_DISTANCE)
924 sLog.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance);
925 m_MaxVisibleDistanceForPlayer = MAX_VISIBILITY_DISTANCE - m_VisibleUnitGreyDistance;
927 m_MaxVisibleDistanceForObject = sConfig.GetFloatDefault("Visibility.Distance.Gameobject", DEFAULT_VISIBILITY_DISTANCE);
928 if(m_MaxVisibleDistanceForObject < INTERACTION_DISTANCE)
930 sLog.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE));
931 m_MaxVisibleDistanceForObject = INTERACTION_DISTANCE;
933 else if(m_MaxVisibleDistanceForObject + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
935 sLog.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
936 m_MaxVisibleDistanceForObject = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
938 m_MaxVisibleDistanceInFlight = sConfig.GetFloatDefault("Visibility.Distance.InFlight", DEFAULT_VISIBILITY_DISTANCE);
939 if(m_MaxVisibleDistanceInFlight + m_VisibleObjectGreyDistance > MAX_VISIBILITY_DISTANCE)
941 sLog.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE-m_VisibleObjectGreyDistance);
942 m_MaxVisibleDistanceInFlight = MAX_VISIBILITY_DISTANCE - m_VisibleObjectGreyDistance;
945 ///- Read the "Data" directory from the config file
946 std::string dataPath = sConfig.GetStringDefault("DataDir","./");
947 if( dataPath.at(dataPath.length()-1)!='/' && dataPath.at(dataPath.length()-1)!='\\' )
948 dataPath.append("/");
950 if(reload)
952 if(dataPath!=m_dataPath)
953 sLog.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath.c_str());
955 else
957 m_dataPath = dataPath;
958 sLog.outString("Using DataDir %s",m_dataPath.c_str());
961 bool enableLOS = sConfig.GetBoolDefault("vmap.enableLOS", false);
962 bool enableHeight = sConfig.GetBoolDefault("vmap.enableHeight", false);
963 std::string ignoreMapIds = sConfig.GetStringDefault("vmap.ignoreMapIds", "");
964 std::string ignoreSpellIds = sConfig.GetStringDefault("vmap.ignoreSpellIds", "");
965 VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS);
966 VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight);
967 VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds.c_str());
968 VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds.c_str());
969 sLog.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS, enableHeight);
970 sLog.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath.c_str());
971 sLog.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
974 /// Initialize the World
975 void World::SetInitialWorldSettings()
977 ///- Initialize the random number generator
978 srand((unsigned int)time(NULL));
980 ///- Initialize config settings
981 LoadConfigSettings();
983 ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
984 objmgr.SetHighestGuids();
986 ///- Check the existence of the map files for all races' startup areas.
987 if( !MapManager::ExistMapAndVMap(0,-6240.32f, 331.033f)
988 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
989 ||!MapManager::ExistMapAndVMap(0,-8949.95f,-132.493f)
990 ||!MapManager::ExistMapAndVMap(1,-618.518f,-4251.67f)
991 ||!MapManager::ExistMapAndVMap(0, 1676.35f, 1677.45f)
992 ||!MapManager::ExistMapAndVMap(1, 10311.3f, 832.463f)
993 ||!MapManager::ExistMapAndVMap(1,-2917.58f,-257.98f)
994 ||m_configs[CONFIG_EXPANSION] && (
995 !MapManager::ExistMapAndVMap(530,10349.6f,-6357.29f) || !MapManager::ExistMapAndVMap(530,-3961.64f,-13931.2f) ) )
997 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());
998 exit(1);
1001 ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
1002 sLog.outString( "" );
1003 sLog.outString( "Loading MaNGOS strings..." );
1004 if (!objmgr.LoadMangosStrings())
1005 exit(1); // Error message displayed in function already
1007 ///- Update the realm entry in the database with the realm type from the config file
1008 //No SQL injection as values are treated as integers
1010 // not send custom type REALM_FFA_PVP to realm list
1011 uint32 server_type = IsFFAPvPRealm() ? REALM_TYPE_PVP : getConfig(CONFIG_GAME_TYPE);
1012 uint32 realm_zone = getConfig(CONFIG_REALM_ZONE);
1013 loginDatabase.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type, realm_zone, realmID);
1015 ///- Remove the bones after a restart
1016 CharacterDatabase.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
1018 ///- Load the DBC files
1019 sLog.outString("Initialize data stores...");
1020 LoadDBCStores(m_dataPath);
1021 DetectDBCLang();
1023 sLog.outString( "Loading Script Names...");
1024 objmgr.LoadScriptNames();
1026 sLog.outString( "Loading InstanceTemplate" );
1027 objmgr.LoadInstanceTemplate();
1029 sLog.outString( "Loading SkillLineAbilityMultiMap Data..." );
1030 spellmgr.LoadSkillLineAbilityMap();
1032 ///- Clean up and pack instances
1033 sLog.outString( "Cleaning up instances..." );
1034 sInstanceSaveManager.CleanupInstances(); // must be called before `creature_respawn`/`gameobject_respawn` tables
1036 sLog.outString( "Packing instances..." );
1037 sInstanceSaveManager.PackInstances();
1039 sLog.outString( "Loading Localization strings..." );
1040 objmgr.LoadCreatureLocales();
1041 objmgr.LoadGameObjectLocales();
1042 objmgr.LoadItemLocales();
1043 objmgr.LoadQuestLocales();
1044 objmgr.LoadNpcTextLocales();
1045 objmgr.LoadPageTextLocales();
1046 objmgr.LoadNpcOptionLocales();
1047 objmgr.SetDBCLocaleIndex(GetDefaultDbcLocale()); // Get once for all the locale index of DBC language (console/broadcasts)
1049 sLog.outString( "Loading Page Texts..." );
1050 objmgr.LoadPageTexts();
1052 sLog.outString( "Loading Game Object Templates..." ); // must be after LoadPageTexts
1053 objmgr.LoadGameobjectInfo();
1055 sLog.outString( "Loading Spell Chain Data..." );
1056 spellmgr.LoadSpellChains();
1058 sLog.outString( "Loading Spell Elixir types..." );
1059 spellmgr.LoadSpellElixirs();
1061 sLog.outString( "Loading Spell Learn Skills..." );
1062 spellmgr.LoadSpellLearnSkills(); // must be after LoadSpellChains
1064 sLog.outString( "Loading Spell Learn Spells..." );
1065 spellmgr.LoadSpellLearnSpells();
1067 sLog.outString( "Loading Spell Proc Event conditions..." );
1068 spellmgr.LoadSpellProcEvents();
1070 sLog.outString( "Loading Aggro Spells Definitions...");
1071 spellmgr.LoadSpellThreats();
1073 sLog.outString( "Loading NPC Texts..." );
1074 objmgr.LoadGossipText();
1076 sLog.outString( "Loading Item Random Enchantments Table..." );
1077 LoadRandomEnchantmentsTable();
1079 sLog.outString( "Loading Items..." ); // must be after LoadRandomEnchantmentsTable and LoadPageTexts
1080 objmgr.LoadItemPrototypes();
1082 sLog.outString( "Loading Item Texts..." );
1083 objmgr.LoadItemTexts();
1085 sLog.outString( "Loading Creature Model Based Info Data..." );
1086 objmgr.LoadCreatureModelInfo();
1088 sLog.outString( "Loading Equipment templates...");
1089 objmgr.LoadEquipmentTemplates();
1091 sLog.outString( "Loading Creature templates..." );
1092 objmgr.LoadCreatureTemplates();
1094 sLog.outString( "Loading SpellsScriptTarget...");
1095 spellmgr.LoadSpellScriptTarget(); // must be after LoadCreatureTemplates and LoadGameobjectInfo
1097 sLog.outString( "Loading Creature Reputation OnKill Data..." );
1098 objmgr.LoadReputationOnKill();
1100 sLog.outString( "Loading Pet Create Spells..." );
1101 objmgr.LoadPetCreateSpells();
1103 sLog.outString( "Loading Creature Data..." );
1104 objmgr.LoadCreatures();
1106 sLog.outString( "Loading Creature Addon Data..." );
1107 objmgr.LoadCreatureAddons(); // must be after LoadCreatureTemplates() and LoadCreatures()
1109 sLog.outString( "Loading Creature Respawn Data..." ); // must be after PackInstances()
1110 objmgr.LoadCreatureRespawnTimes();
1112 sLog.outString( "Loading Gameobject Data..." );
1113 objmgr.LoadGameobjects();
1115 sLog.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1116 objmgr.LoadGameobjectRespawnTimes();
1118 sLog.outString( "Loading Game Event Data...");
1119 gameeventmgr.LoadFromDB();
1121 sLog.outString( "Loading Weather Data..." );
1122 objmgr.LoadWeatherZoneChances();
1124 sLog.outString( "Loading Quests..." );
1125 objmgr.LoadQuests(); // must be loaded after DBCs, creature_template, item_template, gameobject tables
1127 sLog.outString( "Loading Quests Relations..." );
1128 objmgr.LoadQuestRelations(); // must be after quest load
1130 sLog.outString( "Loading AreaTrigger definitions..." );
1131 objmgr.LoadAreaTriggerTeleports(); // must be after item template load
1133 sLog.outString( "Loading Quest Area Triggers..." );
1134 objmgr.LoadQuestAreaTriggers(); // must be after LoadQuests
1136 sLog.outString( "Loading Tavern Area Triggers..." );
1137 objmgr.LoadTavernAreaTriggers();
1139 sLog.outString( "Loading AreaTrigger script names..." );
1140 objmgr.LoadAreaTriggerScripts();
1142 sLog.outString( "Loading Graveyard-zone links...");
1143 objmgr.LoadGraveyardZones();
1145 sLog.outString( "Loading Spell target coordinates..." );
1146 spellmgr.LoadSpellTargetPositions();
1148 sLog.outString( "Loading SpellAffect definitions..." );
1149 spellmgr.LoadSpellAffects();
1151 sLog.outString( "Loading spell pet auras..." );
1152 spellmgr.LoadSpellPetAuras();
1154 sLog.outString( "Loading player Create Info & Level Stats..." );
1155 objmgr.LoadPlayerInfo();
1157 sLog.outString( "Loading Exploration BaseXP Data..." );
1158 objmgr.LoadExplorationBaseXP();
1160 sLog.outString( "Loading Pet Name Parts..." );
1161 objmgr.LoadPetNames();
1163 sLog.outString( "Loading the max pet number..." );
1164 objmgr.LoadPetNumber();
1166 sLog.outString( "Loading pet level stats..." );
1167 objmgr.LoadPetLevelInfo();
1169 sLog.outString( "Loading Player Corpses..." );
1170 objmgr.LoadCorpses();
1172 sLog.outString( "Loading Loot Tables..." );
1173 LoadLootTables();
1175 sLog.outString( "Loading Skill Discovery Table..." );
1176 LoadSkillDiscoveryTable();
1178 sLog.outString( "Loading Skill Extra Item Table..." );
1179 LoadSkillExtraItemTable();
1181 sLog.outString( "Loading Skill Fishing base level requirements..." );
1182 objmgr.LoadFishingBaseSkillLevel();
1184 ///- Load dynamic data tables from the database
1185 sLog.outString( "Loading Auctions..." );
1186 objmgr.LoadAuctionItems();
1187 objmgr.LoadAuctions();
1189 sLog.outString( "Loading Guilds..." );
1190 objmgr.LoadGuilds();
1192 sLog.outString( "Loading ArenaTeams..." );
1193 objmgr.LoadArenaTeams();
1195 sLog.outString( "Loading Groups..." );
1196 objmgr.LoadGroups();
1198 sLog.outString( "Loading ReservedNames..." );
1199 objmgr.LoadReservedPlayersNames();
1201 sLog.outString( "Loading GameObject for quests..." );
1202 objmgr.LoadGameObjectForQuests();
1204 sLog.outString( "Loading BattleMasters..." );
1205 objmgr.LoadBattleMastersEntry();
1207 sLog.outString( "Loading GameTeleports..." );
1208 objmgr.LoadGameTele();
1210 sLog.outString( "Loading Npc Text Id..." );
1211 objmgr.LoadNpcTextId(); // must be after load Creature and NpcText
1213 sLog.outString( "Loading Npc Options..." );
1214 objmgr.LoadNpcOptions();
1216 sLog.outString( "Loading vendors..." );
1217 objmgr.LoadVendors(); // must be after load CreatureTemplate and ItemTemplate
1219 sLog.outString( "Loading trainers..." );
1220 objmgr.LoadTrainerSpell(); // must be after load CreatureTemplate
1222 sLog.outString( "Loading Waypoints..." );
1223 WaypointMgr.Load();
1225 sLog.outString( "Loading GM tickets...");
1226 ticketmgr.LoadGMTickets();
1228 ///- Handle outdated emails (delete/return)
1229 sLog.outString( "Returning old mails..." );
1230 objmgr.ReturnOrDeleteOldMails(false);
1232 ///- Load and initialize scripts
1233 sLog.outString( "Loading Scripts..." );
1234 objmgr.LoadQuestStartScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1235 objmgr.LoadQuestEndScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1236 objmgr.LoadSpellScripts(); // must be after load Creature/Gameobject(Template/Data)
1237 objmgr.LoadGameObjectScripts(); // must be after load Creature/Gameobject(Template/Data)
1238 objmgr.LoadEventScripts(); // must be after load Creature/Gameobject(Template/Data)
1240 sLog.outString( "Loading Scripts text locales..." ); // must be after Load*Scripts calls
1241 objmgr.LoadDbScriptStrings();
1243 sLog.outString( "Initializing Scripts..." );
1244 if(!LoadScriptingModule())
1245 exit(1);
1247 ///- Initialize game time and timers
1248 sLog.outString( "DEBUG:: Initialize game time and timers" );
1249 m_gameTime = time(NULL);
1250 m_startTime=m_gameTime;
1252 tm local;
1253 time_t curr;
1254 time(&curr);
1255 local=*(localtime(&curr)); // dereference and assign
1256 char isoDate[128];
1257 sprintf( isoDate, "%04d-%02d-%02d %02d:%02d:%02d",
1258 local.tm_year+1900, local.tm_mon+1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec);
1260 WorldDatabase.PExecute("INSERT INTO uptime (startstring, starttime, uptime) VALUES('%s', " I64FMTD ", 0)",
1261 isoDate, uint64(m_startTime));
1263 m_timers[WUPDATE_OBJECTS].SetInterval(0);
1264 m_timers[WUPDATE_SESSIONS].SetInterval(0);
1265 m_timers[WUPDATE_WEATHERS].SetInterval(1000);
1266 m_timers[WUPDATE_AUCTIONS].SetInterval(MINUTE*1000); //set auction update interval to 1 minute
1267 m_timers[WUPDATE_UPTIME].SetInterval(m_configs[CONFIG_UPTIME_UPDATE]*MINUTE*1000);
1268 //Update "uptime" table based on configuration entry in minutes.
1269 m_timers[WUPDATE_CORPSES].SetInterval(20*MINUTE*1000); //erase corpses every 20 minutes
1271 //to set mailtimer to return mails every day between 4 and 5 am
1272 //mailtimer is increased when updating auctions
1273 //one second is 1000 -(tested on win system)
1274 mail_timer = ((((localtime( &m_gameTime )->tm_hour + 20) % 24)* HOUR * 1000) / m_timers[WUPDATE_AUCTIONS].GetInterval() );
1275 //1440
1276 mail_timer_expires = ( (DAY * 1000) / (m_timers[WUPDATE_AUCTIONS].GetInterval()));
1277 sLog.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer, mail_timer_expires);
1279 ///- Initilize static helper structures
1280 AIRegistry::Initialize();
1281 WaypointMovementGenerator<Creature>::Initialize();
1282 Player::InitVisibleBits();
1284 ///- Initialize MapManager
1285 sLog.outString( "Starting Map System" );
1286 MapManager::Instance().Initialize();
1288 ///- Initialize Battlegrounds
1289 sLog.outString( "Starting BattleGround System" );
1290 sBattleGroundMgr.CreateInitialBattleGrounds();
1292 //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1293 sLog.outString( "Loading Transports..." );
1294 MapManager::Instance().LoadTransports();
1296 sLog.outString("Deleting expired bans..." );
1297 loginDatabase.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1299 sLog.outString("Calculate next daily quest reset time..." );
1300 InitDailyQuestResetTime();
1302 sLog.outString("Starting Game Event system..." );
1303 uint32 nextGameEvent = gameeventmgr.Initialize();
1304 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent); //depend on next event
1306 sLog.outString( "WORLD: World initialized" );
1309 void World::DetectDBCLang()
1311 uint32 m_lang_confid = sConfig.GetIntDefault("DBC.Locale", 255);
1313 if(m_lang_confid != 255 && m_lang_confid >= MAX_LOCALE)
1315 sLog.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE);
1316 m_lang_confid = LOCALE_enUS;
1319 ChrRacesEntry const* race = sChrRacesStore.LookupEntry(1);
1321 std::string availableLocalsStr;
1323 int default_locale = MAX_LOCALE;
1324 for (int i = MAX_LOCALE-1; i >= 0; --i)
1326 if ( strlen(race->name[i]) > 0) // check by race names
1328 default_locale = i;
1329 m_availableDbcLocaleMask |= (1 << i);
1330 availableLocalsStr += localeNames[i];
1331 availableLocalsStr += " ";
1335 if( default_locale != m_lang_confid && m_lang_confid < MAX_LOCALE &&
1336 (m_availableDbcLocaleMask & (1 << m_lang_confid)) )
1338 default_locale = m_lang_confid;
1341 if(default_locale >= MAX_LOCALE)
1343 sLog.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1344 exit(1);
1347 m_defaultDbcLocale = LocaleConstant(default_locale);
1349 sLog.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames[m_defaultDbcLocale],availableLocalsStr.empty() ? "<none>" : availableLocalsStr.c_str());
1352 /// Update the World !
1353 void World::Update(time_t diff)
1355 ///- Update the different timers
1356 for(int i = 0; i < WUPDATE_COUNT; i++)
1357 if(m_timers[i].GetCurrent()>=0)
1358 m_timers[i].Update(diff);
1359 else m_timers[i].SetCurrent(0);
1361 ///- Update the game time and check for shutdown time
1362 _UpdateGameTime();
1364 /// Handle daily quests reset time
1365 if(m_gameTime > m_NextDailyQuestReset)
1367 ResetDailyQuests();
1368 m_NextDailyQuestReset += DAY;
1371 /// <ul><li> Handle auctions when the timer has passed
1372 if (m_timers[WUPDATE_AUCTIONS].Passed())
1374 m_timers[WUPDATE_AUCTIONS].Reset();
1376 ///- Update mails (return old mails with item, or delete them)
1377 //(tested... works on win)
1378 if (++mail_timer > mail_timer_expires)
1380 mail_timer = 0;
1381 objmgr.ReturnOrDeleteOldMails(true);
1384 AuctionHouseObject* AuctionMap;
1385 for (int i = 0; i < 3; i++)
1387 switch (i)
1389 case 0:
1390 AuctionMap = objmgr.GetAuctionsMap( 6 );//horde
1391 break;
1392 case 1:
1393 AuctionMap = objmgr.GetAuctionsMap( 2 );//alliance
1394 break;
1395 case 2:
1396 AuctionMap = objmgr.GetAuctionsMap( 7 );//neutral
1397 break;
1400 ///- Handle expired auctions
1401 AuctionHouseObject::AuctionEntryMap::iterator itr,next;
1402 for (itr = AuctionMap->GetAuctionsBegin(); itr != AuctionMap->GetAuctionsEnd();itr = next)
1404 next = itr;
1405 ++next;
1406 if (m_gameTime > (itr->second->time))
1408 ///- Either cancel the auction if there was no bidder
1409 if (itr->second->bidder == 0)
1411 objmgr.SendAuctionExpiredMail( itr->second );
1413 ///- Or perform the transaction
1414 else
1416 //we should send an "item sold" message if the seller is online
1417 //we send the item to the winner
1418 //we send the money to the seller
1419 objmgr.SendAuctionSuccessfulMail( itr->second );
1420 objmgr.SendAuctionWonMail( itr->second );
1423 ///- In any case clear the auction
1424 //No SQL injection (Id is integer)
1425 CharacterDatabase.PExecute("DELETE FROM auctionhouse WHERE id = '%u'",itr->second->Id);
1426 objmgr.RemoveAItem(itr->second->item_guidlow);
1427 delete itr->second;
1428 AuctionMap->RemoveAuction(itr->first);
1434 /// <li> Handle session updates when the timer has passed
1435 if (m_timers[WUPDATE_SESSIONS].Passed())
1437 m_timers[WUPDATE_SESSIONS].Reset();
1439 UpdateSessions(diff);
1442 /// <li> Handle weather updates when the timer has passed
1443 if (m_timers[WUPDATE_WEATHERS].Passed())
1445 m_timers[WUPDATE_WEATHERS].Reset();
1447 ///- Send an update signal to Weather objects
1448 WeatherMap::iterator itr, next;
1449 for (itr = m_weathers.begin(); itr != m_weathers.end(); itr = next)
1451 next = itr;
1452 ++next;
1454 ///- and remove Weather objects for zones with no player
1455 //As interval > WorldTick
1456 if(!itr->second->Update(m_timers[WUPDATE_WEATHERS].GetInterval()))
1458 delete itr->second;
1459 m_weathers.erase(itr);
1463 /// <li> Update uptime table
1464 if (m_timers[WUPDATE_UPTIME].Passed())
1466 uint32 tmpDiff = (m_gameTime - m_startTime);
1467 uint32 maxClientsNum = sWorld.GetMaxActiveSessionCount();
1469 m_timers[WUPDATE_UPTIME].Reset();
1470 WorldDatabase.PExecute("UPDATE uptime SET uptime = %d, maxplayers = %d WHERE starttime = " I64FMTD, tmpDiff, maxClientsNum, uint64(m_startTime));
1473 /// <li> Handle all other objects
1474 if (m_timers[WUPDATE_OBJECTS].Passed())
1476 m_timers[WUPDATE_OBJECTS].Reset();
1477 ///- Update objects when the timer has passed (maps, transport, creatures,...)
1478 MapManager::Instance().Update(diff); // As interval = 0
1480 ///- Process necessary scripts
1481 if (!m_scriptSchedule.empty())
1482 ScriptsProcess();
1484 sBattleGroundMgr.Update(diff);
1487 // execute callbacks from sql queries that were queued recently
1488 UpdateResultQueue();
1490 ///- Erase corpses once every 20 minutes
1491 if (m_timers[WUPDATE_CORPSES].Passed())
1493 m_timers[WUPDATE_CORPSES].Reset();
1495 CorpsesErase();
1498 ///- Process Game events when necessary
1499 if (m_timers[WUPDATE_EVENTS].Passed())
1501 m_timers[WUPDATE_EVENTS].Reset(); // to give time for Update() to be processed
1502 uint32 nextGameEvent = gameeventmgr.Update();
1503 m_timers[WUPDATE_EVENTS].SetInterval(nextGameEvent);
1504 m_timers[WUPDATE_EVENTS].Reset();
1507 /// </ul>
1508 ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1509 MapManager::Instance().DoDelayedMovesAndRemoves();
1511 // update the instance reset times
1512 sInstanceSaveManager.Update();
1514 // And last, but not least handle the issued cli commands
1515 ProcessCliCommands();
1518 /// Put scripts in the execution queue
1519 void World::ScriptsStart(ScriptMapMap const& scripts, uint32 id, Object* source, Object* target)
1521 ///- Find the script map
1522 ScriptMapMap::const_iterator s = scripts.find(id);
1523 if (s == scripts.end())
1524 return;
1526 // prepare static data
1527 uint64 sourceGUID = source->GetGUID();
1528 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1529 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1531 ///- Schedule script execution for all scripts in the script map
1532 ScriptMap const *s2 = &(s->second);
1533 bool immedScript = false;
1534 for (ScriptMap::const_iterator iter = s2->begin(); iter != s2->end(); ++iter)
1536 ScriptAction sa;
1537 sa.sourceGUID = sourceGUID;
1538 sa.targetGUID = targetGUID;
1539 sa.ownerGUID = ownerGUID;
1541 sa.script = &iter->second;
1542 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + iter->first, sa));
1543 if (iter->first == 0)
1544 immedScript = true;
1546 ///- If one of the effects should be immediate, launch the script execution
1547 if (immedScript)
1548 ScriptsProcess();
1551 void World::ScriptCommandStart(ScriptInfo const& script, uint32 delay, Object* source, Object* target)
1553 // NOTE: script record _must_ exist until command executed
1555 // prepare static data
1556 uint64 sourceGUID = source->GetGUID();
1557 uint64 targetGUID = target ? target->GetGUID() : (uint64)0;
1558 uint64 ownerGUID = (source->GetTypeId()==TYPEID_ITEM) ? ((Item*)source)->GetOwnerGUID() : (uint64)0;
1560 ScriptAction sa;
1561 sa.sourceGUID = sourceGUID;
1562 sa.targetGUID = targetGUID;
1563 sa.ownerGUID = ownerGUID;
1565 sa.script = &script;
1566 m_scriptSchedule.insert(std::pair<time_t, ScriptAction>(m_gameTime + delay, sa));
1568 ///- If effects should be immediate, launch the script execution
1569 if(delay == 0)
1570 ScriptsProcess();
1573 /// Process queued scripts
1574 void World::ScriptsProcess()
1576 if (m_scriptSchedule.empty())
1577 return;
1579 ///- Process overdue queued scripts
1580 std::multimap<time_t, ScriptAction>::iterator iter = m_scriptSchedule.begin();
1581 // ok as multimap is a *sorted* associative container
1582 while (!m_scriptSchedule.empty() && (iter->first <= m_gameTime))
1584 ScriptAction const& step = iter->second;
1586 Object* source = NULL;
1588 if(step.sourceGUID)
1590 switch(GUID_HIPART(step.sourceGUID))
1592 case HIGHGUID_ITEM:
1593 // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1595 Player* player = HashMapHolder<Player>::Find(step.ownerGUID);
1596 if(player)
1597 source = player->GetItemByGuid(step.sourceGUID);
1598 break;
1600 case HIGHGUID_UNIT:
1601 source = HashMapHolder<Creature>::Find(step.sourceGUID);
1602 break;
1603 case HIGHGUID_PET:
1604 source = HashMapHolder<Pet>::Find(step.sourceGUID);
1605 break;
1606 case HIGHGUID_PLAYER:
1607 source = HashMapHolder<Player>::Find(step.sourceGUID);
1608 break;
1609 case HIGHGUID_GAMEOBJECT:
1610 source = HashMapHolder<GameObject>::Find(step.sourceGUID);
1611 break;
1612 case HIGHGUID_CORPSE:
1613 source = HashMapHolder<Corpse>::Find(step.sourceGUID);
1614 break;
1615 default:
1616 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.sourceGUID));
1617 break;
1621 if(source && !source->IsInWorld()) source = NULL;
1623 Object* target = NULL;
1625 if(step.targetGUID)
1627 switch(GUID_HIPART(step.targetGUID))
1629 case HIGHGUID_UNIT:
1630 target = HashMapHolder<Creature>::Find(step.targetGUID);
1631 break;
1632 case HIGHGUID_PET:
1633 target = HashMapHolder<Pet>::Find(step.targetGUID);
1634 break;
1635 case HIGHGUID_PLAYER: // empty GUID case also
1636 target = HashMapHolder<Player>::Find(step.targetGUID);
1637 break;
1638 case HIGHGUID_GAMEOBJECT:
1639 target = HashMapHolder<GameObject>::Find(step.targetGUID);
1640 break;
1641 case HIGHGUID_CORPSE:
1642 target = HashMapHolder<Corpse>::Find(step.targetGUID);
1643 break;
1644 default:
1645 sLog.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step.targetGUID));
1646 break;
1650 if(target && !target->IsInWorld()) target = NULL;
1652 switch (step.script->command)
1654 case SCRIPT_COMMAND_TALK:
1656 if(!source)
1658 sLog.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1659 break;
1662 if(source->GetTypeId()!=TYPEID_UNIT)
1664 sLog.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1665 break;
1668 uint64 unit_target = target ? target->GetGUID() : 0;
1670 //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1671 switch(step.script->datalong)
1673 case 0: // Say
1674 ((Creature *)source)->Say(step.script->dataint, LANG_UNIVERSAL, unit_target);
1675 break;
1676 case 1: // Whisper
1677 if(!unit_target)
1679 sLog.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step.script->datalong);
1680 break;
1682 ((Creature *)source)->Whisper(step.script->dataint,unit_target);
1683 break;
1684 case 2: // Yell
1685 ((Creature *)source)->Yell(step.script->dataint, LANG_UNIVERSAL, unit_target);
1686 break;
1687 case 3: // Emote text
1688 ((Creature *)source)->TextEmote(step.script->dataint, unit_target);
1689 break;
1690 default:
1691 break; // must be already checked at load
1693 break;
1696 case SCRIPT_COMMAND_EMOTE:
1697 if(!source)
1699 sLog.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1700 break;
1703 if(source->GetTypeId()!=TYPEID_UNIT)
1705 sLog.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1706 break;
1709 ((Creature *)source)->HandleEmoteCommand(step.script->datalong);
1710 break;
1711 case SCRIPT_COMMAND_FIELD_SET:
1712 if(!source)
1714 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1715 break;
1717 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1719 sLog.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1720 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1721 break;
1724 source->SetUInt32Value(step.script->datalong, step.script->datalong2);
1725 break;
1726 case SCRIPT_COMMAND_MOVE_TO:
1727 if(!source)
1729 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1730 break;
1733 if(source->GetTypeId()!=TYPEID_UNIT)
1735 sLog.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source->GetTypeId());
1736 break;
1738 ((Unit *)source)->SendMonsterMoveWithSpeed(step.script->x, step.script->y, step.script->z, ((Unit *)source)->GetUnitMovementFlags(), step.script->datalong2 );
1739 ((Unit *)source)->GetMap()->CreatureRelocation(((Creature *)source), step.script->x, step.script->y, step.script->z, 0);
1740 break;
1741 case SCRIPT_COMMAND_FLAG_SET:
1742 if(!source)
1744 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1745 break;
1747 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1749 sLog.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1750 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1751 break;
1754 source->SetFlag(step.script->datalong, step.script->datalong2);
1755 break;
1756 case SCRIPT_COMMAND_FLAG_REMOVE:
1757 if(!source)
1759 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1760 break;
1762 if(step.script->datalong <= OBJECT_FIELD_ENTRY || step.script->datalong >= source->GetValuesCount())
1764 sLog.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1765 step.script->datalong,source->GetValuesCount(),source->GetTypeId());
1766 break;
1769 source->RemoveFlag(step.script->datalong, step.script->datalong2);
1770 break;
1772 case SCRIPT_COMMAND_TELEPORT_TO:
1774 // accept player in any one from target/source arg
1775 if (!target && !source)
1777 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1778 break;
1781 // must be only Player
1782 if((!target || target->GetTypeId() != TYPEID_PLAYER) && (!source || source->GetTypeId() != TYPEID_PLAYER))
1784 sLog.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source ? source->GetTypeId() : 0, target ? target->GetTypeId() : 0);
1785 break;
1788 Player* pSource = target && target->GetTypeId() == TYPEID_PLAYER ? (Player*)target : (Player*)source;
1790 pSource->TeleportTo(step.script->datalong, step.script->x, step.script->y, step.script->z, step.script->o);
1791 break;
1794 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE:
1796 if(!step.script->datalong) // creature not specified
1798 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1799 break;
1802 if(!source)
1804 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1805 break;
1808 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1810 if(!summoner)
1812 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1813 break;
1816 float x = step.script->x;
1817 float y = step.script->y;
1818 float z = step.script->z;
1819 float o = step.script->o;
1821 Creature* pCreature = summoner->SummonCreature(step.script->datalong, x, y, z, o,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN,step.script->datalong2);
1822 if (!pCreature)
1824 sLog.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step.script->datalong);
1825 break;
1828 break;
1831 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT:
1833 if(!step.script->datalong) // gameobject not specified
1835 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1836 break;
1839 if(!source)
1841 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1842 break;
1845 WorldObject* summoner = dynamic_cast<WorldObject*>(source);
1847 if(!summoner)
1849 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source->GetTypeId());
1850 break;
1853 GameObject *go = NULL;
1854 int32 time_to_despawn = step.script->datalong2<5 ? 5 : (int32)step.script->datalong2;
1856 CellPair p(MaNGOS::ComputeCellPair(summoner->GetPositionX(), summoner->GetPositionY()));
1857 Cell cell(p);
1858 cell.data.Part.reserved = ALL_DISTRICT;
1860 MaNGOS::GameObjectWithDbGUIDCheck go_check(*summoner,step.script->datalong);
1861 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(go,go_check);
1863 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1864 CellLock<GridReadGuard> cell_lock(cell, p);
1865 cell_lock->Visit(cell_lock, object_checker, *summoner->GetMap());
1867 if ( !go )
1869 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step.script->datalong);
1870 break;
1873 if( go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1874 go->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE ||
1875 go->GetGoType()==GAMEOBJECT_TYPE_DOOR ||
1876 go->GetGoType()==GAMEOBJECT_TYPE_BUTTON ||
1877 go->GetGoType()==GAMEOBJECT_TYPE_TRAP )
1879 sLog.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go->GetGoType()), step.script->datalong);
1880 break;
1883 if( go->isSpawned() )
1884 break; //gameobject already spawned
1886 go->SetLootState(GO_READY);
1887 go->SetRespawnTime(time_to_despawn); //despawn object in ? seconds
1889 go->GetMap()->Add(go);
1890 break;
1892 case SCRIPT_COMMAND_OPEN_DOOR:
1894 if(!step.script->datalong) // door not specified
1896 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1897 break;
1900 if(!source)
1902 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1903 break;
1906 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
1908 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1909 break;
1912 Unit* caster = (Unit*)source;
1914 GameObject *door = NULL;
1915 int32 time_to_close = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1917 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1918 Cell cell(p);
1919 cell.data.Part.reserved = ALL_DISTRICT;
1921 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1922 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1924 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1925 CellLock<GridReadGuard> cell_lock(cell, p);
1926 cell_lock->Visit(cell_lock, object_checker, *caster->GetMap());
1928 if ( !door )
1930 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1931 break;
1933 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1935 sLog.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1936 break;
1939 if( !door->GetGoState() )
1940 break; //door already open
1942 door->UseDoorOrButton(time_to_close);
1944 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
1945 ((GameObject*)target)->UseDoorOrButton(time_to_close);
1946 break;
1948 case SCRIPT_COMMAND_CLOSE_DOOR:
1950 if(!step.script->datalong) // guid for door not specified
1952 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
1953 break;
1956 if(!source)
1958 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
1959 break;
1962 if(!source->isType(TYPEMASK_UNIT)) // must be any Unit (creature or player)
1964 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source->GetTypeId());
1965 break;
1968 Unit* caster = (Unit*)source;
1970 GameObject *door = NULL;
1971 int32 time_to_open = step.script->datalong2 < 15 ? 15 : (int32)step.script->datalong2;
1973 CellPair p(MaNGOS::ComputeCellPair(caster->GetPositionX(), caster->GetPositionY()));
1974 Cell cell(p);
1975 cell.data.Part.reserved = ALL_DISTRICT;
1977 MaNGOS::GameObjectWithDbGUIDCheck go_check(*caster,step.script->datalong);
1978 MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck> checker(door,go_check);
1980 TypeContainerVisitor<MaNGOS::GameObjectSearcher<MaNGOS::GameObjectWithDbGUIDCheck>, GridTypeMapContainer > object_checker(checker);
1981 CellLock<GridReadGuard> cell_lock(cell, p);
1982 cell_lock->Visit(cell_lock, object_checker, *caster->GetMap());
1984 if ( !door )
1986 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step.script->datalong);
1987 break;
1989 if ( door->GetGoType() != GAMEOBJECT_TYPE_DOOR )
1991 sLog.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door->GetGoType());
1992 break;
1995 if( door->GetGoState() )
1996 break; //door already closed
1998 door->UseDoorOrButton(time_to_open);
2000 if(target && target->isType(TYPEMASK_GAMEOBJECT) && ((GameObject*)target)->GetGoType()==GAMEOBJECT_TYPE_BUTTON)
2001 ((GameObject*)target)->UseDoorOrButton(time_to_open);
2003 break;
2005 case SCRIPT_COMMAND_QUEST_EXPLORED:
2007 if(!source)
2009 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
2010 break;
2013 if(!target)
2015 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
2016 break;
2019 // when script called for item spell casting then target == (unit or GO) and source is player
2020 WorldObject* worldObject;
2021 Player* player;
2023 if(target->GetTypeId()==TYPEID_PLAYER)
2025 if(source->GetTypeId()!=TYPEID_UNIT && source->GetTypeId()!=TYPEID_GAMEOBJECT)
2027 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source->GetTypeId());
2028 break;
2031 worldObject = (WorldObject*)source;
2032 player = (Player*)target;
2034 else
2036 if(target->GetTypeId()!=TYPEID_UNIT && target->GetTypeId()!=TYPEID_GAMEOBJECT)
2038 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
2039 break;
2042 if(source->GetTypeId()!=TYPEID_PLAYER)
2044 sLog.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source->GetTypeId());
2045 break;
2048 worldObject = (WorldObject*)target;
2049 player = (Player*)source;
2052 // quest id and flags checked at script loading
2053 if( (worldObject->GetTypeId()!=TYPEID_UNIT || ((Unit*)worldObject)->isAlive()) &&
2054 (step.script->datalong2==0 || worldObject->IsWithinDistInMap(player,float(step.script->datalong2))) )
2055 player->AreaExploredOrEventHappens(step.script->datalong);
2056 else
2057 player->FailQuest(step.script->datalong);
2059 break;
2062 case SCRIPT_COMMAND_ACTIVATE_OBJECT:
2064 if(!source)
2066 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
2067 break;
2070 if(!source->isType(TYPEMASK_UNIT))
2072 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2073 break;
2076 if(!target)
2078 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
2079 break;
2082 if(target->GetTypeId()!=TYPEID_GAMEOBJECT)
2084 sLog.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target->GetTypeId());
2085 break;
2088 Unit* caster = (Unit*)source;
2090 GameObject *go = (GameObject*)target;
2092 go->Use(caster);
2093 break;
2096 case SCRIPT_COMMAND_REMOVE_AURA:
2098 Object* cmdTarget = step.script->datalong2 ? source : target;
2100 if(!cmdTarget)
2102 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step.script->datalong2 ? "source" : "target");
2103 break;
2106 if(!cmdTarget->isType(TYPEMASK_UNIT))
2108 sLog.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2109 break;
2112 ((Unit*)cmdTarget)->RemoveAurasDueToSpell(step.script->datalong);
2113 break;
2116 case SCRIPT_COMMAND_CAST_SPELL:
2118 if(!source)
2120 sLog.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
2121 break;
2124 if(!source->isType(TYPEMASK_UNIT))
2126 sLog.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source->GetTypeId());
2127 break;
2130 Object* cmdTarget = step.script->datalong2 ? source : target;
2132 if(!cmdTarget)
2134 sLog.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step.script->datalong2 ? "source" : "target");
2135 break;
2138 if(!cmdTarget->isType(TYPEMASK_UNIT))
2140 sLog.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step.script->datalong2 ? "source" : "target",cmdTarget->GetTypeId());
2141 break;
2144 Unit* spellTarget = (Unit*)cmdTarget;
2146 //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2147 ((Unit*)source)->CastSpell(spellTarget,step.script->datalong,false);
2149 break;
2152 default:
2153 sLog.outError("Unknown script command %u called.",step.script->command);
2154 break;
2157 m_scriptSchedule.erase(iter);
2159 iter = m_scriptSchedule.begin();
2161 return;
2164 /// Send a packet to all players (except self if mentioned)
2165 void World::SendGlobalMessage(WorldPacket *packet, WorldSession *self, uint32 team)
2167 SessionMap::iterator itr;
2168 for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2170 if (itr->second &&
2171 itr->second->GetPlayer() &&
2172 itr->second->GetPlayer()->IsInWorld() &&
2173 itr->second != self &&
2174 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2176 itr->second->SendPacket(packet);
2181 /// Send a System Message to all players (except self if mentioned)
2182 void World::SendWorldText(int32 string_id, ...)
2184 std::vector<std::vector<WorldPacket*> > data_cache; // 0 = default, i => i-1 locale index
2186 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2188 if(!itr->second || !itr->second->GetPlayer() || !itr->second->GetPlayer()->IsInWorld() )
2189 continue;
2191 uint32 loc_idx = itr->second->GetSessionDbLocaleIndex();
2192 uint32 cache_idx = loc_idx+1;
2194 std::vector<WorldPacket*>* data_list;
2196 // create if not cached yet
2197 if(data_cache.size() < cache_idx+1 || data_cache[cache_idx].empty())
2199 if(data_cache.size() < cache_idx+1)
2200 data_cache.resize(cache_idx+1);
2202 data_list = &data_cache[cache_idx];
2204 char const* text = objmgr.GetMangosString(string_id,loc_idx);
2206 char buf[1000];
2208 va_list argptr;
2209 va_start( argptr, string_id );
2210 vsnprintf( buf,1000, text, argptr );
2211 va_end( argptr );
2213 char* pos = &buf[0];
2215 while(char* line = ChatHandler::LineFromMessage(pos))
2217 WorldPacket* data = new WorldPacket();
2218 ChatHandler::FillMessageData(data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, line, NULL);
2219 data_list->push_back(data);
2222 else
2223 data_list = &data_cache[cache_idx];
2225 for(int i = 0; i < data_list->size(); ++i)
2226 itr->second->SendPacket((*data_list)[i]);
2229 // free memory
2230 for(int i = 0; i < data_cache.size(); ++i)
2231 for(int j = 0; j < data_cache[i].size(); ++j)
2232 delete data_cache[i][j];
2235 /// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2236 void World::SendZoneMessage(uint32 zone, WorldPacket *packet, WorldSession *self, uint32 team)
2238 SessionMap::iterator itr;
2239 for (itr = m_sessions.begin(); itr != m_sessions.end(); itr++)
2241 if (itr->second &&
2242 itr->second->GetPlayer() &&
2243 itr->second->GetPlayer()->IsInWorld() &&
2244 itr->second->GetPlayer()->GetZoneId() == zone &&
2245 itr->second != self &&
2246 (team == 0 || itr->second->GetPlayer()->GetTeam() == team) )
2248 itr->second->SendPacket(packet);
2253 /// Send a System Message to all players in the zone (except self if mentioned)
2254 void World::SendZoneText(uint32 zone, const char* text, WorldSession *self, uint32 team)
2256 WorldPacket data;
2257 ChatHandler::FillMessageData(&data, NULL, CHAT_MSG_SYSTEM, LANG_UNIVERSAL, NULL, 0, text, NULL);
2258 SendZoneMessage(zone, &data, self,team);
2261 /// Kick (and save) all players
2262 void World::KickAll()
2264 m_QueuedPlayer.clear(); // prevent send queue update packet and login queued sessions
2266 // session not removed at kick and will removed in next update tick
2267 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2268 itr->second->KickPlayer();
2271 /// Kick (and save) all players with security level less `sec`
2272 void World::KickAllLess(AccountTypes sec)
2274 // session not removed at kick and will removed in next update tick
2275 for (SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2276 if(itr->second->GetSecurity() < sec)
2277 itr->second->KickPlayer();
2280 /// Kick (and save) the designated player
2281 bool World::KickPlayer(std::string playerName)
2283 SessionMap::iterator itr;
2285 // session not removed at kick and will removed in next update tick
2286 for (itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2288 if(!itr->second)
2289 continue;
2290 Player *player = itr->second->GetPlayer();
2291 if(!player)
2292 continue;
2293 if( player->IsInWorld() )
2295 if (playerName == player->GetName())
2297 itr->second->KickPlayer();
2298 return true;
2302 return false;
2305 /// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2306 BanReturn World::BanAccount(BanMode mode, std::string nameOrIP, std::string duration, std::string reason, std::string author)
2308 loginDatabase.escape_string(nameOrIP);
2309 loginDatabase.escape_string(reason);
2310 std::string safe_author=author;
2311 loginDatabase.escape_string(safe_author);
2313 uint32 duration_secs = TimeStringToSecs(duration);
2314 QueryResult *resultAccounts = NULL; //used for kicking
2316 ///- Update the database with ban information
2317 switch(mode)
2319 case BAN_IP:
2320 //No SQL injection as strings are escaped
2321 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP.c_str());
2322 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());
2323 break;
2324 case BAN_ACCOUNT:
2325 //No SQL injection as string is escaped
2326 resultAccounts = loginDatabase.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP.c_str());
2327 break;
2328 case BAN_CHARACTER:
2329 //No SQL injection as string is escaped
2330 resultAccounts = CharacterDatabase.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP.c_str());
2331 break;
2332 default:
2333 return BAN_SYNTAX_ERROR;
2336 if(!resultAccounts)
2338 if(mode==BAN_IP)
2339 return BAN_SUCCESS; // ip correctly banned but nobody affected (yet)
2340 else
2341 return BAN_NOTFOUND; // Nobody to ban
2344 ///- Disconnect all affected players (for IP it can be several)
2347 Field* fieldsAccount = resultAccounts->Fetch();
2348 uint32 account = fieldsAccount->GetUInt32();
2350 if(mode!=BAN_IP)
2352 //No SQL injection as strings are escaped
2353 loginDatabase.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2354 account,duration_secs,safe_author.c_str(),reason.c_str());
2357 if (WorldSession* sess = FindSession(account))
2358 if(std::string(sess->GetPlayerName()) != author)
2359 sess->KickPlayer();
2361 while( resultAccounts->NextRow() );
2363 delete resultAccounts;
2364 return BAN_SUCCESS;
2367 /// Remove a ban from an account or IP address
2368 bool World::RemoveBanAccount(BanMode mode, std::string nameOrIP)
2370 if (mode == BAN_IP)
2372 loginDatabase.escape_string(nameOrIP);
2373 loginDatabase.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP.c_str());
2375 else
2377 uint32 account = 0;
2378 if (mode == BAN_ACCOUNT)
2379 account = accmgr.GetId (nameOrIP);
2380 else if (mode == BAN_CHARACTER)
2381 account = objmgr.GetPlayerAccountIdByPlayerName (nameOrIP);
2383 if (!account)
2384 return false;
2386 //NO SQL injection as account is uint32
2387 loginDatabase.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account);
2389 return true;
2392 /// Update the game time
2393 void World::_UpdateGameTime()
2395 ///- update the time
2396 time_t thisTime = time(NULL);
2397 uint32 elapsed = uint32(thisTime - m_gameTime);
2398 m_gameTime = thisTime;
2400 ///- if there is a shutdown timer
2401 if(!m_stopEvent && m_ShutdownTimer > 0 && elapsed > 0)
2403 ///- ... and it is overdue, stop the world (set m_stopEvent)
2404 if( m_ShutdownTimer <= elapsed )
2406 if(!(m_ShutdownMask & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2407 m_stopEvent = true; // exist code already set
2408 else
2409 m_ShutdownTimer = 1; // minimum timer value to wait idle state
2411 ///- ... else decrease it and if necessary display a shutdown countdown to the users
2412 else
2414 m_ShutdownTimer -= elapsed;
2416 ShutdownMsg();
2421 /// Shutdown the server
2422 void World::ShutdownServ(uint32 time, uint32 options, uint8 exitcode)
2424 // ignore if server shutdown at next tick
2425 if(m_stopEvent)
2426 return;
2428 m_ShutdownMask = options;
2429 m_ExitCode = exitcode;
2431 ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2432 if(time==0)
2434 if(!(options & SHUTDOWN_MASK_IDLE) || GetActiveAndQueuedSessionCount()==0)
2435 m_stopEvent = true; // exist code already set
2436 else
2437 m_ShutdownTimer = 1; //So that the session count is re-evaluated at next world tick
2439 ///- Else set the shutdown timer and warn users
2440 else
2442 m_ShutdownTimer = time;
2443 ShutdownMsg(true);
2447 /// Display a shutdown message to the user(s)
2448 void World::ShutdownMsg(bool show, Player* player)
2450 // not show messages for idle shutdown mode
2451 if(m_ShutdownMask & SHUTDOWN_MASK_IDLE)
2452 return;
2454 ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2455 if ( show ||
2456 (m_ShutdownTimer < 10) ||
2457 // < 30 sec; every 5 sec
2458 (m_ShutdownTimer<30 && (m_ShutdownTimer % 5 )==0) ||
2459 // < 5 min ; every 1 min
2460 (m_ShutdownTimer<5*MINUTE && (m_ShutdownTimer % MINUTE )==0) ||
2461 // < 30 min ; every 5 min
2462 (m_ShutdownTimer<30*MINUTE && (m_ShutdownTimer % (5*MINUTE))==0) ||
2463 // < 12 h ; every 1 h
2464 (m_ShutdownTimer<12*HOUR && (m_ShutdownTimer % HOUR )==0) ||
2465 // > 12 h ; every 12 h
2466 (m_ShutdownTimer>12*HOUR && (m_ShutdownTimer % (12*HOUR) )==0))
2468 std::string str = secsToTimeString(m_ShutdownTimer);
2470 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_TIME : SERVER_MSG_SHUTDOWN_TIME;
2472 SendServerMessage(msgid,str.c_str(),player);
2473 DEBUG_LOG("Server is %s in %s",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"),str.c_str());
2477 /// Cancel a planned server shutdown
2478 void World::ShutdownCancel()
2480 // nothing cancel or too later
2481 if(!m_ShutdownTimer || m_stopEvent)
2482 return;
2484 uint32 msgid = (m_ShutdownMask & SHUTDOWN_MASK_RESTART) ? SERVER_MSG_RESTART_CANCELLED : SERVER_MSG_SHUTDOWN_CANCELLED;
2486 m_ShutdownMask = 0;
2487 m_ShutdownTimer = 0;
2488 m_ExitCode = SHUTDOWN_EXIT_CODE; // to default value
2489 SendServerMessage(msgid);
2491 DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask & SHUTDOWN_MASK_RESTART ? "restart" : "shuttingdown"));
2494 /// Send a server message to the user(s)
2495 void World::SendServerMessage(uint32 type, const char *text, Player* player)
2497 WorldPacket data(SMSG_SERVER_MESSAGE, 50); // guess size
2498 data << uint32(type);
2499 if(type <= SERVER_MSG_STRING)
2500 data << text;
2502 if(player)
2503 player->GetSession()->SendPacket(&data);
2504 else
2505 SendGlobalMessage( &data );
2508 void World::UpdateSessions( time_t diff )
2510 ///- Add new sessions
2511 while(!addSessQueue.empty())
2513 WorldSession* sess = addSessQueue.next ();
2514 AddSession_ (sess);
2517 ///- Then send an update signal to remaining ones
2518 for (SessionMap::iterator itr = m_sessions.begin(), next; itr != m_sessions.end(); itr = next)
2520 next = itr;
2521 ++next;
2523 if(!itr->second)
2524 continue;
2526 ///- and remove not active sessions from the list
2527 if(!itr->second->Update(diff)) // As interval = 0
2529 RemoveQueuedPlayer (itr->second);
2530 delete itr->second;
2531 m_sessions.erase(itr);
2536 // This handles the issued and queued CLI commands
2537 void World::ProcessCliCommands()
2539 if (cliCmdQueue.empty())
2540 return;
2542 CliCommandHolder::Print* zprint;
2544 while (!cliCmdQueue.empty())
2546 sLog.outDebug("CLI command under processing...");
2547 CliCommandHolder *command = cliCmdQueue.next();
2549 zprint = command->m_print;
2551 CliHandler(zprint).ParseCommands(command->m_command);
2553 delete command;
2556 // print the console message here so it looks right
2557 zprint("mangos>");
2560 void World::InitResultQueue()
2562 m_resultQueue = new SqlResultQueue;
2563 CharacterDatabase.SetResultQueue(m_resultQueue);
2566 void World::UpdateResultQueue()
2568 m_resultQueue->Update();
2571 void World::UpdateRealmCharCount(uint32 accountId)
2573 CharacterDatabase.AsyncPQuery(this, &World::_UpdateRealmCharCount, accountId,
2574 "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId);
2577 void World::_UpdateRealmCharCount(QueryResult *resultCharCount, uint32 accountId)
2579 if (resultCharCount)
2581 Field *fields = resultCharCount->Fetch();
2582 uint32 charCount = fields[0].GetUInt32();
2583 delete resultCharCount;
2584 loginDatabase.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId, realmID);
2585 loginDatabase.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount, accountId, realmID);
2589 void World::InitDailyQuestResetTime()
2591 time_t mostRecentQuestTime;
2593 QueryResult* result = CharacterDatabase.Query("SELECT MAX(time) FROM character_queststatus_daily");
2594 if(result)
2596 Field *fields = result->Fetch();
2598 mostRecentQuestTime = (time_t)fields[0].GetUInt64();
2599 delete result;
2601 else
2602 mostRecentQuestTime = 0;
2604 // client built-in time for reset is 6:00 AM
2605 // FIX ME: client not show day start time
2606 time_t curTime = time(NULL);
2607 tm localTm = *localtime(&curTime);
2608 localTm.tm_hour = 6;
2609 localTm.tm_min = 0;
2610 localTm.tm_sec = 0;
2612 // current day reset time
2613 time_t curDayResetTime = mktime(&localTm);
2615 // last reset time before current moment
2616 time_t resetTime = (curTime < curDayResetTime) ? curDayResetTime - DAY : curDayResetTime;
2618 // need reset (if we have quest time before last reset time (not processed by some reason)
2619 if(mostRecentQuestTime && mostRecentQuestTime <= resetTime)
2620 m_NextDailyQuestReset = mostRecentQuestTime;
2621 else
2623 // plan next reset time
2624 m_NextDailyQuestReset = (curTime >= curDayResetTime) ? curDayResetTime + DAY : curDayResetTime;
2628 void World::ResetDailyQuests()
2630 sLog.outDetail("Daily quests reset for all characters.");
2631 CharacterDatabase.Execute("DELETE FROM character_queststatus_daily");
2632 for(SessionMap::iterator itr = m_sessions.begin(); itr != m_sessions.end(); ++itr)
2633 if(itr->second->GetPlayer())
2634 itr->second->GetPlayer()->ResetDailyQuestStatus();
2637 void World::SetPlayerLimit( int32 limit, bool needUpdate )
2639 if(limit < -SEC_ADMINISTRATOR)
2640 limit = -SEC_ADMINISTRATOR;
2642 // lock update need
2643 bool db_update_need = needUpdate || (limit < 0) != (m_playerLimit < 0) || (limit < 0 && m_playerLimit < 0 && limit != m_playerLimit);
2645 m_playerLimit = limit;
2647 if(db_update_need)
2648 loginDatabase.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID);
2651 void World::UpdateMaxSessionCounters()
2653 m_maxActiveSessionCount = std::max(m_maxActiveSessionCount,uint32(m_sessions.size()-m_QueuedPlayer.size()));
2654 m_maxQueuedSessionCount = std::max(m_maxQueuedSessionCount,uint32(m_QueuedPlayer.size()));
2657 void World::LoadDBVersion()
2659 QueryResult* result = WorldDatabase.Query("SELECT version FROM db_version LIMIT 1");
2660 if(result)
2662 Field* fields = result->Fetch();
2664 m_DBVersion = fields[0].GetString();
2665 delete result;
2667 else
2668 m_DBVersion = "unknown world database";