2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 #include "Database/DatabaseEnv.h"
25 #include "Config/ConfigEnv.h"
26 #include "SystemConfig.h"
29 #include "WorldSession.h"
30 #include "WorldPacket.h"
34 #include "SkillExtraItems.h"
35 #include "SkillDiscovery.h"
37 #include "AccountMgr.h"
38 #include "AchievementMgr.h"
39 #include "AuctionHouseMgr.h"
40 #include "ObjectMgr.h"
43 #include "Database/DBCStores.h"
45 #include "ItemEnchantmentMgr.h"
46 #include "MapManager.h"
47 #include "ScriptCalls.h"
48 #include "CreatureAIRegistry.h"
49 #include "Policies/SingletonImp.h"
50 #include "BattleGroundMgr.h"
51 #include "TemporarySummon.h"
52 #include "WaypointMovementGenerator.h"
53 #include "VMapFactory.h"
54 #include "GlobalEvents.h"
55 #include "GameEventMgr.h"
56 #include "PoolHandler.h"
57 #include "Database/DatabaseImpl.h"
58 #include "GridNotifiersImpl.h"
60 #include "InstanceSaveMgr.h"
61 #include "WaypointManager.h"
62 #include "GMTicketMgr.h"
65 INSTANTIATE_SINGLETON_1( World
);
67 volatile bool World::m_stopEvent
= false;
68 uint8
World::m_ExitCode
= SHUTDOWN_EXIT_CODE
;
69 volatile uint32
World::m_worldLoopCounter
= 0;
71 float World::m_MaxVisibleDistanceForCreature
= DEFAULT_VISIBILITY_DISTANCE
;
72 float World::m_MaxVisibleDistanceForPlayer
= DEFAULT_VISIBILITY_DISTANCE
;
73 float World::m_MaxVisibleDistanceForObject
= DEFAULT_VISIBILITY_DISTANCE
;
74 float World::m_MaxVisibleDistanceInFlight
= DEFAULT_VISIBILITY_DISTANCE
;
75 float World::m_VisibleUnitGreyDistance
= 0;
76 float World::m_VisibleObjectGreyDistance
= 0;
79 enum ServerMessageType
81 SERVER_MSG_SHUTDOWN_TIME
= 1,
82 SERVER_MSG_RESTART_TIME
= 2,
83 SERVER_MSG_STRING
= 3,
84 SERVER_MSG_SHUTDOWN_CANCELLED
= 4,
85 SERVER_MSG_RESTART_CANCELLED
= 5
92 uint64 ownerGUID
; // owner of source if source is item
93 ScriptInfo
const* script
; // pointer to static script data
100 m_allowMovement
= true;
103 m_gameTime
=time(NULL
);
104 m_startTime
=m_gameTime
;
105 m_maxActiveSessionCount
= 0;
106 m_maxQueuedSessionCount
= 0;
107 m_resultQueue
= NULL
;
108 m_NextDailyQuestReset
= 0;
110 m_defaultDbcLocale
= LOCALE_enUS
;
111 m_availableDbcLocaleMask
= 0;
117 ///- Empty the kicked session set
118 while (!m_sessions
.empty())
120 // not remove from queue, prevent loading new sessions
121 delete m_sessions
.begin()->second
;
122 m_sessions
.erase(m_sessions
.begin());
125 ///- Empty the WeatherMap
126 for (WeatherMap::iterator itr
= m_weathers
.begin(); itr
!= m_weathers
.end(); ++itr
)
131 while (!cliCmdQueue
.empty())
132 delete cliCmdQueue
.next();
134 VMAP::VMapFactory::clear();
136 if(m_resultQueue
) delete m_resultQueue
;
138 //TODO free addSessQueue
141 /// Find a player in a specified zone
142 Player
* World::FindPlayerInZone(uint32 zone
)
144 ///- circle through active sessions and return the first player found in the zone
145 SessionMap::iterator itr
;
146 for (itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
150 Player
*player
= itr
->second
->GetPlayer();
153 if( player
->IsInWorld() && player
->GetZoneId() == zone
)
155 // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone.
162 /// Find a session by its id
163 WorldSession
* World::FindSession(uint32 id
) const
165 SessionMap::const_iterator itr
= m_sessions
.find(id
);
167 if(itr
!= m_sessions
.end())
168 return itr
->second
; // also can return NULL for kicked session
173 /// Remove a given session
174 bool World::RemoveSession(uint32 id
)
176 ///- Find the session, kick the user, but we can't delete session at this moment to prevent iterator invalidation
177 SessionMap::iterator itr
= m_sessions
.find(id
);
179 if(itr
!= m_sessions
.end() && itr
->second
)
181 if (itr
->second
->PlayerLoading())
183 itr
->second
->KickPlayer();
189 void World::AddSession(WorldSession
* s
)
195 World::AddSession_ (WorldSession
* s
)
199 //NOTE - Still there is race condition in WorldSession* being used in the Sockets
201 ///- kick already loaded player with same account (if any) and remove session
202 ///- if player is in loading and want to load again, return
203 if (!RemoveSession (s
->GetAccountId ()))
206 delete s
; // session not added yet in session list, so not listed in queue
210 // decrease session counts only at not reconnection case
211 bool decrease_session
= true;
213 // if session already exist, prepare to it deleting at next world update
214 // NOTE - KickPlayer() should be called on "old" in RemoveSession()
216 SessionMap::const_iterator old
= m_sessions
.find(s
->GetAccountId ());
218 if(old
!= m_sessions
.end())
220 // prevent decrease sessions count if session queued
221 if(RemoveQueuedPlayer(old
->second
))
222 decrease_session
= false;
223 // not remove replaced session form queue if listed
228 m_sessions
[s
->GetAccountId ()] = s
;
230 uint32 Sessions
= GetActiveAndQueuedSessionCount ();
231 uint32 pLimit
= GetPlayerAmountLimit ();
232 uint32 QueueSize
= GetQueueSize (); //number of players in the queue
234 //so we don't count the user trying to
235 //login as a session and queue the socket that we are using
239 if (pLimit
> 0 && Sessions
>= pLimit
&& s
->GetSecurity () == SEC_PLAYER
)
242 UpdateMaxSessionCounters ();
243 sLog
.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s
->GetAccountId (), ++QueueSize
);
247 WorldPacket
packet(SMSG_AUTH_RESPONSE
, 1 + 4 + 1 + 4 + 1);
248 packet
<< uint8 (AUTH_OK
);
249 packet
<< uint32 (0); // BillingTimeRemaining
250 packet
<< uint8 (0); // BillingPlanFlags
251 packet
<< uint32 (0); // BillingTimeRested
252 packet
<< uint8 (s
->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
253 s
->SendPacket (&packet
);
256 UpdateMaxSessionCounters ();
258 // Updates the population
261 float popu
= GetActiveSessionCount (); //updated number of users on the server
264 loginDatabase
.PExecute ("UPDATE realmlist SET population = '%f' WHERE id = '%d'", popu
, realmID
);
265 sLog
.outDetail ("Server Population (%f).", popu
);
269 int32
World::GetQueuePos(WorldSession
* sess
)
273 for(Queue::iterator iter
= m_QueuedPlayer
.begin(); iter
!= m_QueuedPlayer
.end(); ++iter
, ++position
)
280 void World::AddQueuedPlayer(WorldSession
* sess
)
282 sess
->SetInQueue(true);
283 m_QueuedPlayer
.push_back (sess
);
285 // The 1st SMSG_AUTH_RESPONSE needs to contain other info too.
286 WorldPacket
packet (SMSG_AUTH_RESPONSE
, 1 + 4 + 1 + 4 + 1);
287 packet
<< uint8 (AUTH_WAIT_QUEUE
);
288 packet
<< uint32 (0); // BillingTimeRemaining
289 packet
<< uint8 (0); // BillingPlanFlags
290 packet
<< uint32 (0); // BillingTimeRested
291 packet
<< uint8 (sess
->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
292 packet
<< uint32(GetQueuePos (sess
));
293 sess
->SendPacket (&packet
);
295 //sess->SendAuthWaitQue (GetQueuePos (sess));
298 bool World::RemoveQueuedPlayer(WorldSession
* sess
)
300 // sessions count including queued to remove (if removed_session set)
301 uint32 sessions
= GetActiveSessionCount();
304 Queue::iterator iter
= m_QueuedPlayer
.begin();
306 // search to remove and count skipped positions
309 for(;iter
!= m_QueuedPlayer
.end(); ++iter
, ++position
)
313 sess
->SetInQueue(false);
314 iter
= m_QueuedPlayer
.erase(iter
);
315 found
= true; // removing queued session
320 // iter point to next socked after removed or end()
321 // position store position of removed socket and then new position next socket after removed
323 // if session not queued then we need decrease sessions count
324 if(!found
&& sessions
)
327 // accept first in queue
328 if( (!m_playerLimit
|| sessions
< m_playerLimit
) && !m_QueuedPlayer
.empty() )
330 WorldSession
* pop_sess
= m_QueuedPlayer
.front();
331 pop_sess
->SetInQueue(false);
332 pop_sess
->SendAuthWaitQue(0);
333 m_QueuedPlayer
.pop_front();
335 // update iter to point first queued socket or end() if queue is empty now
336 iter
= m_QueuedPlayer
.begin();
340 // update position from iter to end()
341 // iter point to first not updated socket, position store new position
342 for(; iter
!= m_QueuedPlayer
.end(); ++iter
, ++position
)
343 (*iter
)->SendAuthWaitQue(position
);
348 /// Find a Weather object by the given zoneid
349 Weather
* World::FindWeather(uint32 id
) const
351 WeatherMap::const_iterator itr
= m_weathers
.find(id
);
353 if(itr
!= m_weathers
.end())
359 /// Remove a Weather object for the given zoneid
360 void World::RemoveWeather(uint32 id
)
362 // not called at the moment. Kept for completeness
363 WeatherMap::iterator itr
= m_weathers
.find(id
);
365 if(itr
!= m_weathers
.end())
368 m_weathers
.erase(itr
);
372 /// Add a Weather object to the list
373 Weather
* World::AddWeather(uint32 zone_id
)
375 WeatherZoneChances
const* weatherChances
= objmgr
.GetWeatherChances(zone_id
);
377 // zone not have weather, ignore
381 Weather
* w
= new Weather(zone_id
,weatherChances
);
382 m_weathers
[w
->GetZone()] = w
;
388 /// Initialize config values
389 void World::LoadConfigSettings(bool reload
)
393 if(!sConfig
.Reload())
395 sLog
.outError("World settings reload fail: can't read settings from %s.",sConfig
.GetFilename().c_str());
400 ///- Read the version of the configuration file and warn the user in case of emptiness or mismatch
401 uint32 confVersion
= sConfig
.GetIntDefault("ConfVersion", 0);
404 sLog
.outError("*****************************************************************************");
405 sLog
.outError(" WARNING: mangosd.conf does not include a ConfVersion variable.");
406 sLog
.outError(" Your configuration file may be out of date!");
407 sLog
.outError("*****************************************************************************");
408 clock_t pause
= 3000 + clock();
409 while (pause
> clock())
414 if (confVersion
< _MANGOSDCONFVERSION
)
416 sLog
.outError("*****************************************************************************");
417 sLog
.outError(" WARNING: Your mangosd.conf version indicates your conf file is out of date!");
418 sLog
.outError(" Please check for updates, as your current default values may cause");
419 sLog
.outError(" unexpected behavior.");
420 sLog
.outError("*****************************************************************************");
421 clock_t pause
= 3000 + clock();
422 while (pause
> clock())
427 ///- Read the player limit and the Message of the day from the config file
428 SetPlayerLimit( sConfig
.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT
), true );
429 SetMotd( sConfig
.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
431 ///- Read all rates from the config file
432 rate_values
[RATE_HEALTH
] = sConfig
.GetFloatDefault("Rate.Health", 1);
433 if(rate_values
[RATE_HEALTH
] < 0)
435 sLog
.outError("Rate.Health (%f) must be > 0. Using 1 instead.",rate_values
[RATE_HEALTH
]);
436 rate_values
[RATE_HEALTH
] = 1;
438 rate_values
[RATE_POWER_MANA
] = sConfig
.GetFloatDefault("Rate.Mana", 1);
439 if(rate_values
[RATE_POWER_MANA
] < 0)
441 sLog
.outError("Rate.Mana (%f) must be > 0. Using 1 instead.",rate_values
[RATE_POWER_MANA
]);
442 rate_values
[RATE_POWER_MANA
] = 1;
444 rate_values
[RATE_POWER_RAGE_INCOME
] = sConfig
.GetFloatDefault("Rate.Rage.Income", 1);
445 rate_values
[RATE_POWER_RAGE_LOSS
] = sConfig
.GetFloatDefault("Rate.Rage.Loss", 1);
446 if(rate_values
[RATE_POWER_RAGE_LOSS
] < 0)
448 sLog
.outError("Rate.Rage.Loss (%f) must be > 0. Using 1 instead.",rate_values
[RATE_POWER_RAGE_LOSS
]);
449 rate_values
[RATE_POWER_RAGE_LOSS
] = 1;
451 rate_values
[RATE_POWER_RUNICPOWER_INCOME
] = sConfig
.GetFloatDefault("Rate.RunicPower.Income", 1);
452 rate_values
[RATE_POWER_RUNICPOWER_LOSS
] = sConfig
.GetFloatDefault("Rate.RunicPower.Loss", 1);
453 if(rate_values
[RATE_POWER_RUNICPOWER_LOSS
] < 0)
455 sLog
.outError("Rate.RunicPower.Loss (%f) must be > 0. Using 1 instead.",rate_values
[RATE_POWER_RUNICPOWER_LOSS
]);
456 rate_values
[RATE_POWER_RUNICPOWER_LOSS
] = 1;
458 rate_values
[RATE_POWER_FOCUS
] = sConfig
.GetFloatDefault("Rate.Focus", 1.0f
);
459 rate_values
[RATE_SKILL_DISCOVERY
] = sConfig
.GetFloatDefault("Rate.Skill.Discovery", 1.0f
);
460 rate_values
[RATE_DROP_ITEM_POOR
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f
);
461 rate_values
[RATE_DROP_ITEM_NORMAL
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f
);
462 rate_values
[RATE_DROP_ITEM_UNCOMMON
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f
);
463 rate_values
[RATE_DROP_ITEM_RARE
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f
);
464 rate_values
[RATE_DROP_ITEM_EPIC
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f
);
465 rate_values
[RATE_DROP_ITEM_LEGENDARY
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f
);
466 rate_values
[RATE_DROP_ITEM_ARTIFACT
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f
);
467 rate_values
[RATE_DROP_ITEM_REFERENCED
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f
);
468 rate_values
[RATE_DROP_MONEY
] = sConfig
.GetFloatDefault("Rate.Drop.Money", 1.0f
);
469 rate_values
[RATE_XP_KILL
] = sConfig
.GetFloatDefault("Rate.XP.Kill", 1.0f
);
470 rate_values
[RATE_XP_QUEST
] = sConfig
.GetFloatDefault("Rate.XP.Quest", 1.0f
);
471 rate_values
[RATE_XP_EXPLORE
] = sConfig
.GetFloatDefault("Rate.XP.Explore", 1.0f
);
472 rate_values
[RATE_REPUTATION_GAIN
] = sConfig
.GetFloatDefault("Rate.Reputation.Gain", 1.0f
);
473 rate_values
[RATE_CREATURE_NORMAL_DAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f
);
474 rate_values
[RATE_CREATURE_ELITE_ELITE_DAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f
);
475 rate_values
[RATE_CREATURE_ELITE_RAREELITE_DAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f
);
476 rate_values
[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f
);
477 rate_values
[RATE_CREATURE_ELITE_RARE_DAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f
);
478 rate_values
[RATE_CREATURE_NORMAL_HP
] = sConfig
.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f
);
479 rate_values
[RATE_CREATURE_ELITE_ELITE_HP
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f
);
480 rate_values
[RATE_CREATURE_ELITE_RAREELITE_HP
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f
);
481 rate_values
[RATE_CREATURE_ELITE_WORLDBOSS_HP
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f
);
482 rate_values
[RATE_CREATURE_ELITE_RARE_HP
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f
);
483 rate_values
[RATE_CREATURE_NORMAL_SPELLDAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f
);
484 rate_values
[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f
);
485 rate_values
[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f
);
486 rate_values
[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f
);
487 rate_values
[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f
);
488 rate_values
[RATE_CREATURE_AGGRO
] = sConfig
.GetFloatDefault("Rate.Creature.Aggro", 1.0f
);
489 rate_values
[RATE_REST_INGAME
] = sConfig
.GetFloatDefault("Rate.Rest.InGame", 1.0f
);
490 rate_values
[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY
] = sConfig
.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f
);
491 rate_values
[RATE_REST_OFFLINE_IN_WILDERNESS
] = sConfig
.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f
);
492 rate_values
[RATE_DAMAGE_FALL
] = sConfig
.GetFloatDefault("Rate.Damage.Fall", 1.0f
);
493 rate_values
[RATE_AUCTION_TIME
] = sConfig
.GetFloatDefault("Rate.Auction.Time", 1.0f
);
494 rate_values
[RATE_AUCTION_DEPOSIT
] = sConfig
.GetFloatDefault("Rate.Auction.Deposit", 1.0f
);
495 rate_values
[RATE_AUCTION_CUT
] = sConfig
.GetFloatDefault("Rate.Auction.Cut", 1.0f
);
496 rate_values
[RATE_HONOR
] = sConfig
.GetFloatDefault("Rate.Honor",1.0f
);
497 rate_values
[RATE_MINING_AMOUNT
] = sConfig
.GetFloatDefault("Rate.Mining.Amount",1.0f
);
498 rate_values
[RATE_MINING_NEXT
] = sConfig
.GetFloatDefault("Rate.Mining.Next",1.0f
);
499 rate_values
[RATE_INSTANCE_RESET_TIME
] = sConfig
.GetFloatDefault("Rate.InstanceResetTime",1.0f
);
500 rate_values
[RATE_TALENT
] = sConfig
.GetFloatDefault("Rate.Talent",1.0f
);
501 if(rate_values
[RATE_TALENT
] < 0.0f
)
503 sLog
.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values
[RATE_TALENT
]);
504 rate_values
[RATE_TALENT
] = 1.0f
;
506 rate_values
[RATE_CORPSE_DECAY_LOOTED
] = sConfig
.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f
);
508 rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
] = sConfig
.GetFloatDefault("TargetPosRecalculateRange",1.5f
);
509 if(rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
] < CONTACT_DISTANCE
)
511 sLog
.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
],CONTACT_DISTANCE
,CONTACT_DISTANCE
);
512 rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
] = CONTACT_DISTANCE
;
514 else if(rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
] > ATTACK_DISTANCE
)
516 sLog
.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",
517 rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
],ATTACK_DISTANCE
,ATTACK_DISTANCE
);
518 rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
] = ATTACK_DISTANCE
;
521 rate_values
[RATE_DURABILITY_LOSS_DAMAGE
] = sConfig
.GetFloatDefault("DurabilityLossChance.Damage",0.5f
);
522 if(rate_values
[RATE_DURABILITY_LOSS_DAMAGE
] < 0.0f
)
524 sLog
.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values
[RATE_DURABILITY_LOSS_DAMAGE
]);
525 rate_values
[RATE_DURABILITY_LOSS_DAMAGE
] = 0.0f
;
527 rate_values
[RATE_DURABILITY_LOSS_ABSORB
] = sConfig
.GetFloatDefault("DurabilityLossChance.Absorb",0.5f
);
528 if(rate_values
[RATE_DURABILITY_LOSS_ABSORB
] < 0.0f
)
530 sLog
.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values
[RATE_DURABILITY_LOSS_ABSORB
]);
531 rate_values
[RATE_DURABILITY_LOSS_ABSORB
] = 0.0f
;
533 rate_values
[RATE_DURABILITY_LOSS_PARRY
] = sConfig
.GetFloatDefault("DurabilityLossChance.Parry",0.05f
);
534 if(rate_values
[RATE_DURABILITY_LOSS_PARRY
] < 0.0f
)
536 sLog
.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values
[RATE_DURABILITY_LOSS_PARRY
]);
537 rate_values
[RATE_DURABILITY_LOSS_PARRY
] = 0.0f
;
539 rate_values
[RATE_DURABILITY_LOSS_BLOCK
] = sConfig
.GetFloatDefault("DurabilityLossChance.Block",0.05f
);
540 if(rate_values
[RATE_DURABILITY_LOSS_BLOCK
] < 0.0f
)
542 sLog
.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values
[RATE_DURABILITY_LOSS_BLOCK
]);
543 rate_values
[RATE_DURABILITY_LOSS_BLOCK
] = 0.0f
;
546 ///- Read other configuration items from the config file
548 m_configs
[CONFIG_COMPRESSION
] = sConfig
.GetIntDefault("Compression", 1);
549 if(m_configs
[CONFIG_COMPRESSION
] < 1 || m_configs
[CONFIG_COMPRESSION
] > 9)
551 sLog
.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs
[CONFIG_COMPRESSION
]);
552 m_configs
[CONFIG_COMPRESSION
] = 1;
554 m_configs
[CONFIG_ADDON_CHANNEL
] = sConfig
.GetBoolDefault("AddonChannel", true);
555 m_configs
[CONFIG_GRID_UNLOAD
] = sConfig
.GetBoolDefault("GridUnload", true);
556 m_configs
[CONFIG_INTERVAL_SAVE
] = sConfig
.GetIntDefault("PlayerSaveInterval", 15 * MINUTE
* IN_MILISECONDS
);
558 m_configs
[CONFIG_INTERVAL_GRIDCLEAN
] = sConfig
.GetIntDefault("GridCleanUpDelay", 5 * MINUTE
* IN_MILISECONDS
);
559 if(m_configs
[CONFIG_INTERVAL_GRIDCLEAN
] < MIN_GRID_DELAY
)
561 sLog
.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs
[CONFIG_INTERVAL_GRIDCLEAN
],MIN_GRID_DELAY
);
562 m_configs
[CONFIG_INTERVAL_GRIDCLEAN
] = MIN_GRID_DELAY
;
565 MapManager::Instance().SetGridCleanUpDelay(m_configs
[CONFIG_INTERVAL_GRIDCLEAN
]);
567 m_configs
[CONFIG_INTERVAL_MAPUPDATE
] = sConfig
.GetIntDefault("MapUpdateInterval", 100);
568 if(m_configs
[CONFIG_INTERVAL_MAPUPDATE
] < MIN_MAP_UPDATE_DELAY
)
570 sLog
.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs
[CONFIG_INTERVAL_MAPUPDATE
],MIN_MAP_UPDATE_DELAY
);
571 m_configs
[CONFIG_INTERVAL_MAPUPDATE
] = MIN_MAP_UPDATE_DELAY
;
574 MapManager::Instance().SetMapUpdateInterval(m_configs
[CONFIG_INTERVAL_MAPUPDATE
]);
576 m_configs
[CONFIG_INTERVAL_CHANGEWEATHER
] = sConfig
.GetIntDefault("ChangeWeatherInterval", 10 * MINUTE
* IN_MILISECONDS
);
580 uint32 val
= sConfig
.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT
);
581 if(val
!=m_configs
[CONFIG_PORT_WORLD
])
582 sLog
.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs
[CONFIG_PORT_WORLD
]);
585 m_configs
[CONFIG_PORT_WORLD
] = sConfig
.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT
);
589 uint32 val
= sConfig
.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME
);
590 if(val
!=m_configs
[CONFIG_SOCKET_SELECTTIME
])
591 sLog
.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs
[CONFIG_SOCKET_SELECTTIME
]);
594 m_configs
[CONFIG_SOCKET_SELECTTIME
] = sConfig
.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME
);
596 m_configs
[CONFIG_GROUP_XP_DISTANCE
] = sConfig
.GetIntDefault("MaxGroupXPDistance", 74);
597 /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
598 m_configs
[CONFIG_SIGHT_MONSTER
] = sConfig
.GetIntDefault("MonsterSight", 50);
599 m_configs
[CONFIG_SIGHT_GUARDER
] = sConfig
.GetIntDefault("GuarderSight", 50);
603 uint32 val
= sConfig
.GetIntDefault("GameType", 0);
604 if(val
!=m_configs
[CONFIG_GAME_TYPE
])
605 sLog
.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs
[CONFIG_GAME_TYPE
]);
608 m_configs
[CONFIG_GAME_TYPE
] = sConfig
.GetIntDefault("GameType", 0);
612 uint32 val
= sConfig
.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT
);
613 if(val
!=m_configs
[CONFIG_REALM_ZONE
])
614 sLog
.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs
[CONFIG_REALM_ZONE
]);
617 m_configs
[CONFIG_REALM_ZONE
] = sConfig
.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT
);
619 m_configs
[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS
] = sConfig
.GetBoolDefault("AllowTwoSide.Accounts", false);
620 m_configs
[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT
] = sConfig
.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
621 m_configs
[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL
] = sConfig
.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
622 m_configs
[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP
] = sConfig
.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
623 m_configs
[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD
] = sConfig
.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
624 m_configs
[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION
] = sConfig
.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
625 m_configs
[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL
] = sConfig
.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
626 m_configs
[CONFIG_ALLOW_TWO_SIDE_WHO_LIST
] = sConfig
.GetBoolDefault("AllowTwoSide.WhoList", false);
627 m_configs
[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND
] = sConfig
.GetBoolDefault("AllowTwoSide.AddFriend", false);
628 m_configs
[CONFIG_STRICT_PLAYER_NAMES
] = sConfig
.GetIntDefault ("StrictPlayerNames", 0);
629 m_configs
[CONFIG_STRICT_CHARTER_NAMES
] = sConfig
.GetIntDefault ("StrictCharterNames", 0);
630 m_configs
[CONFIG_STRICT_PET_NAMES
] = sConfig
.GetIntDefault ("StrictPetNames", 0);
632 m_configs
[CONFIG_CHARACTERS_CREATING_DISABLED
] = sConfig
.GetIntDefault ("CharactersCreatingDisabled", 0);
634 m_configs
[CONFIG_CHARACTERS_PER_REALM
] = sConfig
.GetIntDefault("CharactersPerRealm", 10);
635 if(m_configs
[CONFIG_CHARACTERS_PER_REALM
] < 1 || m_configs
[CONFIG_CHARACTERS_PER_REALM
] > 10)
637 sLog
.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs
[CONFIG_CHARACTERS_PER_REALM
]);
638 m_configs
[CONFIG_CHARACTERS_PER_REALM
] = 10;
641 // must be after CONFIG_CHARACTERS_PER_REALM
642 m_configs
[CONFIG_CHARACTERS_PER_ACCOUNT
] = sConfig
.GetIntDefault("CharactersPerAccount", 50);
643 if(m_configs
[CONFIG_CHARACTERS_PER_ACCOUNT
] < m_configs
[CONFIG_CHARACTERS_PER_REALM
])
645 sLog
.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs
[CONFIG_CHARACTERS_PER_ACCOUNT
],m_configs
[CONFIG_CHARACTERS_PER_REALM
]);
646 m_configs
[CONFIG_CHARACTERS_PER_ACCOUNT
] = m_configs
[CONFIG_CHARACTERS_PER_REALM
];
649 m_configs
[CONFIG_HEROIC_CHARACTERS_PER_REALM
] = sConfig
.GetIntDefault("HeroicCharactersPerRealm", 1);
650 if(int32(m_configs
[CONFIG_HEROIC_CHARACTERS_PER_REALM
]) < 0 || m_configs
[CONFIG_HEROIC_CHARACTERS_PER_REALM
] > 10)
652 sLog
.outError("HeroicCharactersPerRealm (%i) must be in range 0..10. Set to 1.",m_configs
[CONFIG_HEROIC_CHARACTERS_PER_REALM
]);
653 m_configs
[CONFIG_HEROIC_CHARACTERS_PER_REALM
] = 1;
656 m_configs
[CONFIG_MIN_LEVEL_FOR_HEROIC_CHARACTER_CREATING
] = sConfig
.GetIntDefault("MinLevelForHeroicCharacterCreating", 55);
658 m_configs
[CONFIG_SKIP_CINEMATICS
] = sConfig
.GetIntDefault("SkipCinematics", 0);
659 if(int32(m_configs
[CONFIG_SKIP_CINEMATICS
]) < 0 || m_configs
[CONFIG_SKIP_CINEMATICS
] > 2)
661 sLog
.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs
[CONFIG_SKIP_CINEMATICS
]);
662 m_configs
[CONFIG_SKIP_CINEMATICS
] = 0;
667 uint32 val
= sConfig
.GetIntDefault("MaxPlayerLevel", 80);
668 if(val
!=m_configs
[CONFIG_MAX_PLAYER_LEVEL
])
669 sLog
.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs
[CONFIG_MAX_PLAYER_LEVEL
]);
672 m_configs
[CONFIG_MAX_PLAYER_LEVEL
] = sConfig
.GetIntDefault("MaxPlayerLevel", 80);
674 if(m_configs
[CONFIG_MAX_PLAYER_LEVEL
] > MAX_LEVEL
)
676 sLog
.outError("MaxPlayerLevel (%i) must be in range 1..%u. Set to %u.",m_configs
[CONFIG_MAX_PLAYER_LEVEL
],MAX_LEVEL
,MAX_LEVEL
);
677 m_configs
[CONFIG_MAX_PLAYER_LEVEL
] = MAX_LEVEL
;
680 m_configs
[CONFIG_START_PLAYER_LEVEL
] = sConfig
.GetIntDefault("StartPlayerLevel", 1);
681 if(m_configs
[CONFIG_START_PLAYER_LEVEL
] < 1)
683 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
]);
684 m_configs
[CONFIG_START_PLAYER_LEVEL
] = 1;
686 else if(m_configs
[CONFIG_START_PLAYER_LEVEL
] > m_configs
[CONFIG_MAX_PLAYER_LEVEL
])
688 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
]);
689 m_configs
[CONFIG_START_PLAYER_LEVEL
] = m_configs
[CONFIG_MAX_PLAYER_LEVEL
];
692 m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
] = sConfig
.GetIntDefault("StartHeroicPlayerLevel", 55);
693 if(m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
] < 1)
695 sLog
.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to 55.",
696 m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
],m_configs
[CONFIG_MAX_PLAYER_LEVEL
]);
697 m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
] = 55;
699 else if(m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
] > m_configs
[CONFIG_MAX_PLAYER_LEVEL
])
701 sLog
.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to %u.",
702 m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
],m_configs
[CONFIG_MAX_PLAYER_LEVEL
],m_configs
[CONFIG_MAX_PLAYER_LEVEL
]);
703 m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
] = m_configs
[CONFIG_MAX_PLAYER_LEVEL
];
706 m_configs
[CONFIG_START_PLAYER_MONEY
] = sConfig
.GetIntDefault("StartPlayerMoney", 0);
707 if(int32(m_configs
[CONFIG_START_PLAYER_MONEY
]) < 0)
709 sLog
.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",m_configs
[CONFIG_START_PLAYER_MONEY
],MAX_MONEY_AMOUNT
,0);
710 m_configs
[CONFIG_START_PLAYER_MONEY
] = 0;
712 else if(m_configs
[CONFIG_START_PLAYER_MONEY
] > MAX_MONEY_AMOUNT
)
714 sLog
.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",
715 m_configs
[CONFIG_START_PLAYER_MONEY
],MAX_MONEY_AMOUNT
,MAX_MONEY_AMOUNT
);
716 m_configs
[CONFIG_START_PLAYER_MONEY
] = MAX_MONEY_AMOUNT
;
719 m_configs
[CONFIG_MAX_HONOR_POINTS
] = sConfig
.GetIntDefault("MaxHonorPoints", 75000);
720 if(int32(m_configs
[CONFIG_MAX_HONOR_POINTS
]) < 0)
722 sLog
.outError("MaxHonorPoints (%i) can't be negative. Set to 0.",m_configs
[CONFIG_MAX_HONOR_POINTS
]);
723 m_configs
[CONFIG_MAX_HONOR_POINTS
] = 0;
726 m_configs
[CONFIG_START_HONOR_POINTS
] = sConfig
.GetIntDefault("StartHonorPoints", 0);
727 if(int32(m_configs
[CONFIG_START_HONOR_POINTS
]) < 0)
729 sLog
.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
730 m_configs
[CONFIG_START_HONOR_POINTS
],m_configs
[CONFIG_MAX_HONOR_POINTS
],0);
731 m_configs
[CONFIG_MAX_HONOR_POINTS
] = 0;
733 else if(m_configs
[CONFIG_START_HONOR_POINTS
] > m_configs
[CONFIG_MAX_HONOR_POINTS
])
735 sLog
.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
736 m_configs
[CONFIG_START_HONOR_POINTS
],m_configs
[CONFIG_MAX_HONOR_POINTS
],m_configs
[CONFIG_MAX_HONOR_POINTS
]);
737 m_configs
[CONFIG_START_HONOR_POINTS
] = m_configs
[CONFIG_MAX_HONOR_POINTS
];
740 m_configs
[CONFIG_MAX_ARENA_POINTS
] = sConfig
.GetIntDefault("MaxArenaPoints", 5000);
741 if(int32(m_configs
[CONFIG_MAX_ARENA_POINTS
]) < 0)
743 sLog
.outError("MaxArenaPoints (%i) can't be negative. Set to 0.",m_configs
[CONFIG_MAX_ARENA_POINTS
]);
744 m_configs
[CONFIG_MAX_ARENA_POINTS
] = 0;
747 m_configs
[CONFIG_START_ARENA_POINTS
] = sConfig
.GetIntDefault("StartArenaPoints", 0);
748 if(int32(m_configs
[CONFIG_START_ARENA_POINTS
]) < 0)
750 sLog
.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
751 m_configs
[CONFIG_START_ARENA_POINTS
],m_configs
[CONFIG_MAX_ARENA_POINTS
],0);
752 m_configs
[CONFIG_MAX_ARENA_POINTS
] = 0;
754 else if(m_configs
[CONFIG_START_ARENA_POINTS
] > m_configs
[CONFIG_MAX_ARENA_POINTS
])
756 sLog
.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
757 m_configs
[CONFIG_START_ARENA_POINTS
],m_configs
[CONFIG_MAX_ARENA_POINTS
],m_configs
[CONFIG_MAX_ARENA_POINTS
]);
758 m_configs
[CONFIG_START_ARENA_POINTS
] = m_configs
[CONFIG_MAX_ARENA_POINTS
];
761 m_configs
[CONFIG_ALL_TAXI_PATHS
] = sConfig
.GetBoolDefault("AllFlightPaths", false);
763 m_configs
[CONFIG_INSTANCE_IGNORE_LEVEL
] = sConfig
.GetBoolDefault("Instance.IgnoreLevel", false);
764 m_configs
[CONFIG_INSTANCE_IGNORE_RAID
] = sConfig
.GetBoolDefault("Instance.IgnoreRaid", false);
766 m_configs
[CONFIG_CAST_UNSTUCK
] = sConfig
.GetBoolDefault("CastUnstuck", true);
767 m_configs
[CONFIG_INSTANCE_RESET_TIME_HOUR
] = sConfig
.GetIntDefault("Instance.ResetTimeHour", 4);
768 m_configs
[CONFIG_INSTANCE_UNLOAD_DELAY
] = sConfig
.GetIntDefault("Instance.UnloadDelay", 30 * MINUTE
* IN_MILISECONDS
);
770 m_configs
[CONFIG_MAX_PRIMARY_TRADE_SKILL
] = sConfig
.GetIntDefault("MaxPrimaryTradeSkill", 2);
771 m_configs
[CONFIG_MIN_PETITION_SIGNS
] = sConfig
.GetIntDefault("MinPetitionSigns", 9);
772 if(m_configs
[CONFIG_MIN_PETITION_SIGNS
] > 9)
774 sLog
.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.", m_configs
[CONFIG_MIN_PETITION_SIGNS
]);
775 m_configs
[CONFIG_MIN_PETITION_SIGNS
] = 9;
778 m_configs
[CONFIG_GM_LOGIN_STATE
] = sConfig
.GetIntDefault("GM.LoginState", 2);
779 m_configs
[CONFIG_GM_VISIBLE_STATE
] = sConfig
.GetIntDefault("GM.Visible", 2);
780 m_configs
[CONFIG_GM_ACCEPT_TICKETS
] = sConfig
.GetIntDefault("GM.AcceptTickets", 2);
781 m_configs
[CONFIG_GM_CHAT
] = sConfig
.GetIntDefault("GM.Chat", 2);
782 m_configs
[CONFIG_GM_WISPERING_TO
] = sConfig
.GetIntDefault("GM.WhisperingTo", 2);
784 m_configs
[CONFIG_GM_IN_GM_LIST
] = sConfig
.GetBoolDefault("GM.InGMList", false);
785 m_configs
[CONFIG_GM_IN_WHO_LIST
] = sConfig
.GetBoolDefault("GM.InWhoList", false);
786 m_configs
[CONFIG_GM_LOG_TRADE
] = sConfig
.GetBoolDefault("GM.LogTrade", false);
788 m_configs
[CONFIG_START_GM_LEVEL
] = sConfig
.GetIntDefault("GM.StartLevel", 1);
789 if(m_configs
[CONFIG_START_GM_LEVEL
] < m_configs
[CONFIG_START_PLAYER_LEVEL
])
791 sLog
.outError("GM.StartLevel (%i) must be in range StartPlayerLevel(%u)..%u. Set to %u.",
792 m_configs
[CONFIG_START_GM_LEVEL
],m_configs
[CONFIG_START_PLAYER_LEVEL
], MAX_LEVEL
, m_configs
[CONFIG_START_PLAYER_LEVEL
]);
793 m_configs
[CONFIG_START_GM_LEVEL
] = m_configs
[CONFIG_START_PLAYER_LEVEL
];
795 else if(m_configs
[CONFIG_START_GM_LEVEL
] > MAX_LEVEL
)
797 sLog
.outError("GM.StartLevel (%i) must be in range 1..%u. Set to %u.", m_configs
[CONFIG_START_GM_LEVEL
], MAX_LEVEL
, MAX_LEVEL
);
798 m_configs
[CONFIG_START_GM_LEVEL
] = MAX_LEVEL
;
800 m_configs
[CONFIG_GM_LOWER_SECURITY
] = sConfig
.GetBoolDefault("GM.LowerSecurity", false);
801 m_configs
[CONFIG_GM_ALLOW_ACHIEVEMENT_GAINS
] = sConfig
.GetBoolDefault("GM.AllowAchievementGain", true);
803 m_configs
[CONFIG_GROUP_VISIBILITY
] = sConfig
.GetIntDefault("Visibility.GroupMode",0);
805 m_configs
[CONFIG_MAIL_DELIVERY_DELAY
] = sConfig
.GetIntDefault("MailDeliveryDelay",HOUR
);
807 m_configs
[CONFIG_UPTIME_UPDATE
] = sConfig
.GetIntDefault("UpdateUptimeInterval", 10);
808 if(int32(m_configs
[CONFIG_UPTIME_UPDATE
])<=0)
810 sLog
.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs
[CONFIG_UPTIME_UPDATE
]);
811 m_configs
[CONFIG_UPTIME_UPDATE
] = 10;
815 m_timers
[WUPDATE_UPTIME
].SetInterval(m_configs
[CONFIG_UPTIME_UPDATE
]*MINUTE
*IN_MILISECONDS
);
816 m_timers
[WUPDATE_UPTIME
].Reset();
819 m_configs
[CONFIG_SKILL_CHANCE_ORANGE
] = sConfig
.GetIntDefault("SkillChance.Orange",100);
820 m_configs
[CONFIG_SKILL_CHANCE_YELLOW
] = sConfig
.GetIntDefault("SkillChance.Yellow",75);
821 m_configs
[CONFIG_SKILL_CHANCE_GREEN
] = sConfig
.GetIntDefault("SkillChance.Green",25);
822 m_configs
[CONFIG_SKILL_CHANCE_GREY
] = sConfig
.GetIntDefault("SkillChance.Grey",0);
824 m_configs
[CONFIG_SKILL_CHANCE_MINING_STEPS
] = sConfig
.GetIntDefault("SkillChance.MiningSteps",75);
825 m_configs
[CONFIG_SKILL_CHANCE_SKINNING_STEPS
] = sConfig
.GetIntDefault("SkillChance.SkinningSteps",75);
827 m_configs
[CONFIG_SKILL_PROSPECTING
] = sConfig
.GetBoolDefault("SkillChance.Prospecting",false);
828 m_configs
[CONFIG_SKILL_MILLING
] = sConfig
.GetBoolDefault("SkillChance.Milling",false);
830 m_configs
[CONFIG_SKILL_GAIN_CRAFTING
] = sConfig
.GetIntDefault("SkillGain.Crafting", 1);
831 if(m_configs
[CONFIG_SKILL_GAIN_CRAFTING
] < 0)
833 sLog
.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs
[CONFIG_SKILL_GAIN_CRAFTING
]);
834 m_configs
[CONFIG_SKILL_GAIN_CRAFTING
] = 1;
837 m_configs
[CONFIG_SKILL_GAIN_DEFENSE
] = sConfig
.GetIntDefault("SkillGain.Defense", 1);
838 if(m_configs
[CONFIG_SKILL_GAIN_DEFENSE
] < 0)
840 sLog
.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs
[CONFIG_SKILL_GAIN_DEFENSE
]);
841 m_configs
[CONFIG_SKILL_GAIN_DEFENSE
] = 1;
844 m_configs
[CONFIG_SKILL_GAIN_GATHERING
] = sConfig
.GetIntDefault("SkillGain.Gathering", 1);
845 if(m_configs
[CONFIG_SKILL_GAIN_GATHERING
] < 0)
847 sLog
.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs
[CONFIG_SKILL_GAIN_GATHERING
]);
848 m_configs
[CONFIG_SKILL_GAIN_GATHERING
] = 1;
851 m_configs
[CONFIG_SKILL_GAIN_WEAPON
] = sConfig
.GetIntDefault("SkillGain.Weapon", 1);
852 if(m_configs
[CONFIG_SKILL_GAIN_WEAPON
] < 0)
854 sLog
.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs
[CONFIG_SKILL_GAIN_WEAPON
]);
855 m_configs
[CONFIG_SKILL_GAIN_WEAPON
] = 1;
858 m_configs
[CONFIG_MAX_OVERSPEED_PINGS
] = sConfig
.GetIntDefault("MaxOverspeedPings",2);
859 if(m_configs
[CONFIG_MAX_OVERSPEED_PINGS
] != 0 && m_configs
[CONFIG_MAX_OVERSPEED_PINGS
] < 2)
861 sLog
.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs
[CONFIG_MAX_OVERSPEED_PINGS
]);
862 m_configs
[CONFIG_MAX_OVERSPEED_PINGS
] = 2;
865 m_configs
[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY
] = sConfig
.GetBoolDefault("SaveRespawnTimeImmediately",true);
866 m_configs
[CONFIG_WEATHER
] = sConfig
.GetBoolDefault("ActivateWeather",true);
868 m_configs
[CONFIG_DISABLE_BREATHING
] = sConfig
.GetIntDefault("DisableWaterBreath", SEC_CONSOLE
);
870 m_configs
[CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL
] = sConfig
.GetBoolDefault("AlwaysMaxSkillForLevel", false);
874 uint32 val
= sConfig
.GetIntDefault("Expansion",1);
875 if(val
!=m_configs
[CONFIG_EXPANSION
])
876 sLog
.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs
[CONFIG_EXPANSION
]);
879 m_configs
[CONFIG_EXPANSION
] = sConfig
.GetIntDefault("Expansion",1);
881 m_configs
[CONFIG_CHATFLOOD_MESSAGE_COUNT
] = sConfig
.GetIntDefault("ChatFlood.MessageCount",10);
882 m_configs
[CONFIG_CHATFLOOD_MESSAGE_DELAY
] = sConfig
.GetIntDefault("ChatFlood.MessageDelay",1);
883 m_configs
[CONFIG_CHATFLOOD_MUTE_TIME
] = sConfig
.GetIntDefault("ChatFlood.MuteTime",10);
885 m_configs
[CONFIG_EVENT_ANNOUNCE
] = sConfig
.GetIntDefault("Event.Announce",0);
887 m_configs
[CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS
] = sConfig
.GetIntDefault("CreatureFamilyAssistanceRadius",10);
888 m_configs
[CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY
] = sConfig
.GetIntDefault("CreatureFamilyAssistanceDelay",1500);
890 m_configs
[CONFIG_WORLD_BOSS_LEVEL_DIFF
] = sConfig
.GetIntDefault("WorldBossLevelDiff",3);
892 // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level MAX_LEVEL(100)
893 m_configs
[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF
] = sConfig
.GetIntDefault("Quests.LowLevelHideDiff", 4);
894 if(m_configs
[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF
] > MAX_LEVEL
)
895 m_configs
[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF
] = MAX_LEVEL
;
896 m_configs
[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
] = sConfig
.GetIntDefault("Quests.HighLevelHideDiff", 7);
897 if(m_configs
[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
] > MAX_LEVEL
)
898 m_configs
[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
] = MAX_LEVEL
;
900 m_configs
[CONFIG_DETECT_POS_COLLISION
] = sConfig
.GetBoolDefault("DetectPosCollision", true);
902 m_configs
[CONFIG_RESTRICTED_LFG_CHANNEL
] = sConfig
.GetBoolDefault("Channel.RestrictedLfg", true);
903 m_configs
[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL
] = sConfig
.GetBoolDefault("Channel.SilentlyGMJoin", false);
905 m_configs
[CONFIG_TALENTS_INSPECTING
] = sConfig
.GetBoolDefault("TalentsInspecting", true);
906 m_configs
[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING
] = sConfig
.GetBoolDefault("ChatFakeMessagePreventing", false);
908 m_configs
[CONFIG_CORPSE_DECAY_NORMAL
] = sConfig
.GetIntDefault("Corpse.Decay.NORMAL", 60);
909 m_configs
[CONFIG_CORPSE_DECAY_RARE
] = sConfig
.GetIntDefault("Corpse.Decay.RARE", 300);
910 m_configs
[CONFIG_CORPSE_DECAY_ELITE
] = sConfig
.GetIntDefault("Corpse.Decay.ELITE", 300);
911 m_configs
[CONFIG_CORPSE_DECAY_RAREELITE
] = sConfig
.GetIntDefault("Corpse.Decay.RAREELITE", 300);
912 m_configs
[CONFIG_CORPSE_DECAY_WORLDBOSS
] = sConfig
.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
914 m_configs
[CONFIG_DEATH_SICKNESS_LEVEL
] = sConfig
.GetIntDefault ("Death.SicknessLevel", 11);
915 m_configs
[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
] = sConfig
.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
916 m_configs
[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
] = sConfig
.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
917 m_configs
[CONFIG_DEATH_BONES_WORLD
] = sConfig
.GetBoolDefault("Death.Bones.World", true);
918 m_configs
[CONFIG_DEATH_BONES_BG_OR_ARENA
] = sConfig
.GetBoolDefault("Death.Bones.BattlegroundOrArena", true);
920 m_configs
[CONFIG_THREAT_RADIUS
] = sConfig
.GetIntDefault("ThreatRadius", 100);
922 // always use declined names in the russian client
923 m_configs
[CONFIG_DECLINED_NAMES_USED
] =
924 (m_configs
[CONFIG_REALM_ZONE
] == REALM_ZONE_RUSSIAN
) ? true : sConfig
.GetBoolDefault("DeclinedNames", false);
926 m_configs
[CONFIG_LISTEN_RANGE_SAY
] = sConfig
.GetIntDefault("ListenRange.Say", 25);
927 m_configs
[CONFIG_LISTEN_RANGE_TEXTEMOTE
] = sConfig
.GetIntDefault("ListenRange.TextEmote", 25);
928 m_configs
[CONFIG_LISTEN_RANGE_YELL
] = sConfig
.GetIntDefault("ListenRange.Yell", 300);
930 m_configs
[CONFIG_BATTLEGROUND_CAST_DESERTER
] = sConfig
.GetBoolDefault("Battleground.CastDeserter", true);
931 m_configs
[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE
] = sConfig
.GetBoolDefault("Battleground.QueueAnnouncer.Enable", false);
932 m_configs
[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY
] = sConfig
.GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false);
933 m_configs
[CONFIG_BATTLEGROUND_INVITATION_TYPE
] = sConfig
.GetIntDefault ("Battleground.InvitationType", 0);
934 m_configs
[CONFIG_BATTLEGROUND_PREMATURE_FINISH_TIMER
] = sConfig
.GetIntDefault ("BattleGround.PrematureFinishTimer", 5 * MINUTE
* IN_MILISECONDS
);
935 m_configs
[CONFIG_BATTLEGROUND_PREMADE_GROUP_WAIT_FOR_MATCH
] = sConfig
.GetIntDefault ("BattleGround.PremadeGroupWaitForMatch", 30 * MINUTE
* IN_MILISECONDS
);
936 m_configs
[CONFIG_ARENA_MAX_RATING_DIFFERENCE
] = sConfig
.GetIntDefault ("Arena.MaxRatingDifference", 150);
937 m_configs
[CONFIG_ARENA_RATING_DISCARD_TIMER
] = sConfig
.GetIntDefault ("Arena.RatingDiscardTimer", 10 * MINUTE
* IN_MILISECONDS
);
938 m_configs
[CONFIG_ARENA_AUTO_DISTRIBUTE_POINTS
] = sConfig
.GetBoolDefault("Arena.AutoDistributePoints", false);
939 m_configs
[CONFIG_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS
] = sConfig
.GetIntDefault ("Arena.AutoDistributeInterval", 7);
940 m_configs
[CONFIG_ARENA_QUEUE_ANNOUNCER_ENABLE
] = sConfig
.GetBoolDefault("Arena.QueueAnnouncer.Enable", false);
941 m_configs
[CONFIG_ARENA_SEASON_ID
] = sConfig
.GetIntDefault ("Arena.ArenaSeason.ID", 1);
942 m_configs
[CONFIG_ARENA_SEASON_IN_PROGRESS
] = sConfig
.GetBoolDefault("Arena.ArenaSeason.InProgress", true);
944 m_configs
[CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET
] = sConfig
.GetBoolDefault("OffhandCheckAtTalentsReset", false);
946 m_configs
[CONFIG_INSTANT_LOGOUT
] = sConfig
.GetIntDefault("InstantLogout", SEC_MODERATOR
);
948 m_VisibleUnitGreyDistance
= sConfig
.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
949 if(m_VisibleUnitGreyDistance
> MAX_VISIBILITY_DISTANCE
)
951 sLog
.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE
);
952 m_VisibleUnitGreyDistance
= MAX_VISIBILITY_DISTANCE
;
954 m_VisibleObjectGreyDistance
= sConfig
.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
955 if(m_VisibleObjectGreyDistance
> MAX_VISIBILITY_DISTANCE
)
957 sLog
.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE
);
958 m_VisibleObjectGreyDistance
= MAX_VISIBILITY_DISTANCE
;
961 m_MaxVisibleDistanceForCreature
= sConfig
.GetFloatDefault("Visibility.Distance.Creature", DEFAULT_VISIBILITY_DISTANCE
);
962 if(m_MaxVisibleDistanceForCreature
< 45*sWorld
.getRate(RATE_CREATURE_AGGRO
))
964 sLog
.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld
.getRate(RATE_CREATURE_AGGRO
));
965 m_MaxVisibleDistanceForCreature
= 45*sWorld
.getRate(RATE_CREATURE_AGGRO
);
967 else if(m_MaxVisibleDistanceForCreature
+ m_VisibleUnitGreyDistance
> MAX_VISIBILITY_DISTANCE
)
969 sLog
.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE
- m_VisibleUnitGreyDistance
);
970 m_MaxVisibleDistanceForCreature
= MAX_VISIBILITY_DISTANCE
-m_VisibleUnitGreyDistance
;
972 m_MaxVisibleDistanceForPlayer
= sConfig
.GetFloatDefault("Visibility.Distance.Player", DEFAULT_VISIBILITY_DISTANCE
);
973 if(m_MaxVisibleDistanceForPlayer
< 45*sWorld
.getRate(RATE_CREATURE_AGGRO
))
975 sLog
.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld
.getRate(RATE_CREATURE_AGGRO
));
976 m_MaxVisibleDistanceForPlayer
= 45*sWorld
.getRate(RATE_CREATURE_AGGRO
);
978 else if(m_MaxVisibleDistanceForPlayer
+ m_VisibleUnitGreyDistance
> MAX_VISIBILITY_DISTANCE
)
980 sLog
.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE
- m_VisibleUnitGreyDistance
);
981 m_MaxVisibleDistanceForPlayer
= MAX_VISIBILITY_DISTANCE
- m_VisibleUnitGreyDistance
;
983 m_MaxVisibleDistanceForObject
= sConfig
.GetFloatDefault("Visibility.Distance.Gameobject", DEFAULT_VISIBILITY_DISTANCE
);
984 if(m_MaxVisibleDistanceForObject
< INTERACTION_DISTANCE
)
986 sLog
.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE
));
987 m_MaxVisibleDistanceForObject
= INTERACTION_DISTANCE
;
989 else if(m_MaxVisibleDistanceForObject
+ m_VisibleObjectGreyDistance
> MAX_VISIBILITY_DISTANCE
)
991 sLog
.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE
-m_VisibleObjectGreyDistance
);
992 m_MaxVisibleDistanceForObject
= MAX_VISIBILITY_DISTANCE
- m_VisibleObjectGreyDistance
;
994 m_MaxVisibleDistanceInFlight
= sConfig
.GetFloatDefault("Visibility.Distance.InFlight", DEFAULT_VISIBILITY_DISTANCE
);
995 if(m_MaxVisibleDistanceInFlight
+ m_VisibleObjectGreyDistance
> MAX_VISIBILITY_DISTANCE
)
997 sLog
.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE
-m_VisibleObjectGreyDistance
);
998 m_MaxVisibleDistanceInFlight
= MAX_VISIBILITY_DISTANCE
- m_VisibleObjectGreyDistance
;
1001 ///- Read the "Data" directory from the config file
1002 std::string dataPath
= sConfig
.GetStringDefault("DataDir","./");
1003 if( dataPath
.at(dataPath
.length()-1)!='/' && dataPath
.at(dataPath
.length()-1)!='\\' )
1004 dataPath
.append("/");
1008 if(dataPath
!=m_dataPath
)
1009 sLog
.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath
.c_str());
1013 m_dataPath
= dataPath
;
1014 sLog
.outString("Using DataDir %s",m_dataPath
.c_str());
1017 bool enableLOS
= sConfig
.GetBoolDefault("vmap.enableLOS", false);
1018 bool enableHeight
= sConfig
.GetBoolDefault("vmap.enableHeight", false);
1019 std::string ignoreMapIds
= sConfig
.GetStringDefault("vmap.ignoreMapIds", "");
1020 std::string ignoreSpellIds
= sConfig
.GetStringDefault("vmap.ignoreSpellIds", "");
1021 VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS
);
1022 VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight
);
1023 VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds
.c_str());
1024 VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds
.c_str());
1025 sLog
.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS
, enableHeight
);
1026 sLog
.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath
.c_str());
1027 sLog
.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
1030 /// Initialize the World
1031 void World::SetInitialWorldSettings()
1033 ///- Initialize the random number generator
1034 srand((unsigned int)time(NULL
));
1036 ///- Initialize config settings
1037 LoadConfigSettings();
1039 ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
1040 objmgr
.SetHighestGuids();
1042 ///- Check the existence of the map files for all races' startup areas.
1043 if( !MapManager::ExistMapAndVMap(0,-6240.32f
, 331.033f
)
1044 ||!MapManager::ExistMapAndVMap(0,-8949.95f
,-132.493f
)
1045 ||!MapManager::ExistMapAndVMap(0,-8949.95f
,-132.493f
)
1046 ||!MapManager::ExistMapAndVMap(1,-618.518f
,-4251.67f
)
1047 ||!MapManager::ExistMapAndVMap(0, 1676.35f
, 1677.45f
)
1048 ||!MapManager::ExistMapAndVMap(1, 10311.3f
, 832.463f
)
1049 ||!MapManager::ExistMapAndVMap(1,-2917.58f
,-257.98f
)
1050 ||m_configs
[CONFIG_EXPANSION
] && (
1051 !MapManager::ExistMapAndVMap(530,10349.6f
,-6357.29f
) || !MapManager::ExistMapAndVMap(530,-3961.64f
,-13931.2f
) ) )
1053 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());
1057 ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
1059 sLog
.outString("Loading MaNGOS strings...");
1060 if (!objmgr
.LoadMangosStrings())
1061 exit(1); // Error message displayed in function already
1063 ///- Update the realm entry in the database with the realm type from the config file
1064 //No SQL injection as values are treated as integers
1066 // not send custom type REALM_FFA_PVP to realm list
1067 uint32 server_type
= IsFFAPvPRealm() ? REALM_TYPE_PVP
: getConfig(CONFIG_GAME_TYPE
);
1068 uint32 realm_zone
= getConfig(CONFIG_REALM_ZONE
);
1069 loginDatabase
.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type
, realm_zone
, realmID
);
1071 ///- Remove the bones after a restart
1072 CharacterDatabase
.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
1074 ///- Load the DBC files
1075 sLog
.outString("Initialize data stores...");
1076 LoadDBCStores(m_dataPath
);
1079 sLog
.outString( "Loading Script Names...");
1080 objmgr
.LoadScriptNames();
1082 sLog
.outString( "Loading InstanceTemplate..." );
1083 objmgr
.LoadInstanceTemplate();
1085 sLog
.outString( "Loading SkillLineAbilityMultiMap Data..." );
1086 spellmgr
.LoadSkillLineAbilityMap();
1088 ///- Clean up and pack instances
1089 sLog
.outString( "Cleaning up instances..." );
1090 sInstanceSaveManager
.CleanupInstances(); // must be called before `creature_respawn`/`gameobject_respawn` tables
1092 sLog
.outString( "Packing instances..." );
1093 sInstanceSaveManager
.PackInstances();
1096 sLog
.outString( "Loading Localization strings..." );
1097 objmgr
.LoadCreatureLocales();
1098 objmgr
.LoadGameObjectLocales();
1099 objmgr
.LoadItemLocales();
1100 objmgr
.LoadQuestLocales();
1101 objmgr
.LoadNpcTextLocales();
1102 objmgr
.LoadPageTextLocales();
1103 objmgr
.LoadNpcOptionLocales();
1104 objmgr
.LoadPointOfInterestLocales();
1105 objmgr
.SetDBCLocaleIndex(GetDefaultDbcLocale()); // Get once for all the locale index of DBC language (console/broadcasts)
1106 sLog
.outString( ">>> Localization strings loaded" );
1109 sLog
.outString( "Loading Page Texts..." );
1110 objmgr
.LoadPageTexts();
1112 sLog
.outString( "Loading Game Object Templates..." ); // must be after LoadPageTexts
1113 objmgr
.LoadGameobjectInfo();
1115 sLog
.outString( "Loading Spell Chain Data..." );
1116 spellmgr
.LoadSpellChains();
1118 sLog
.outString( "Loading Spell Elixir types..." );
1119 spellmgr
.LoadSpellElixirs();
1121 sLog
.outString( "Loading Spell Learn Skills..." );
1122 spellmgr
.LoadSpellLearnSkills(); // must be after LoadSpellChains
1124 sLog
.outString( "Loading Spell Learn Spells..." );
1125 spellmgr
.LoadSpellLearnSpells();
1127 sLog
.outString( "Loading Spell Proc Event conditions..." );
1128 spellmgr
.LoadSpellProcEvents();
1130 sLog
.outString( "Loading Spell Bonus Data..." );
1131 spellmgr
.LoadSpellBonusess();
1133 sLog
.outString( "Loading Aggro Spells Definitions...");
1134 spellmgr
.LoadSpellThreats();
1136 sLog
.outString( "Loading NPC Texts..." );
1137 objmgr
.LoadGossipText();
1139 sLog
.outString( "Loading Item Random Enchantments Table..." );
1140 LoadRandomEnchantmentsTable();
1142 sLog
.outString( "Loading Items..." ); // must be after LoadRandomEnchantmentsTable and LoadPageTexts
1143 objmgr
.LoadItemPrototypes();
1145 sLog
.outString( "Loading Item Texts..." );
1146 objmgr
.LoadItemTexts();
1148 sLog
.outString( "Loading Creature Model Based Info Data..." );
1149 objmgr
.LoadCreatureModelInfo();
1151 sLog
.outString( "Loading Equipment templates...");
1152 objmgr
.LoadEquipmentTemplates();
1154 sLog
.outString( "Loading Creature templates..." );
1155 objmgr
.LoadCreatureTemplates();
1157 sLog
.outString( "Loading SpellsScriptTarget...");
1158 spellmgr
.LoadSpellScriptTarget(); // must be after LoadCreatureTemplates and LoadGameobjectInfo
1160 sLog
.outString( "Loading Creature Reputation OnKill Data..." );
1161 objmgr
.LoadReputationOnKill();
1163 sLog
.outString( "Loading Points Of Interest Data..." );
1164 objmgr
.LoadPointsOfInterest();
1166 sLog
.outString( "Loading Pet Create Spells..." );
1167 objmgr
.LoadPetCreateSpells();
1169 sLog
.outString( "Loading Creature Data..." );
1170 objmgr
.LoadCreatures();
1172 sLog
.outString( "Loading Creature Addon Data..." );
1174 objmgr
.LoadCreatureAddons(); // must be after LoadCreatureTemplates() and LoadCreatures()
1175 sLog
.outString( ">>> Creature Addon Data loaded" );
1178 sLog
.outString( "Loading Creature Respawn Data..." ); // must be after PackInstances()
1179 objmgr
.LoadCreatureRespawnTimes();
1181 sLog
.outString( "Loading Gameobject Data..." );
1182 objmgr
.LoadGameobjects();
1184 sLog
.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1185 objmgr
.LoadGameobjectRespawnTimes();
1187 sLog
.outString( "Loading Objects Pooling Data...");
1188 poolhandler
.LoadFromDB();
1190 sLog
.outString( "Loading Game Event Data...");
1192 gameeventmgr
.LoadFromDB();
1193 sLog
.outString( ">>> Game Event Data loaded" );
1196 sLog
.outString( "Loading Weather Data..." );
1197 objmgr
.LoadWeatherZoneChances();
1199 sLog
.outString( "Loading Quests..." );
1200 objmgr
.LoadQuests(); // must be loaded after DBCs, creature_template, item_template, gameobject tables
1202 sLog
.outString( "Loading Quests Relations..." );
1204 objmgr
.LoadQuestRelations(); // must be after quest load
1205 sLog
.outString( ">>> Quests Relations loaded" );
1208 sLog
.outString( "Loading SpellArea Data..." ); // must be after quest load
1209 spellmgr
.LoadSpellAreas();
1211 sLog
.outString( "Loading AreaTrigger definitions..." );
1212 objmgr
.LoadAreaTriggerTeleports(); // must be after item template load
1214 sLog
.outString( "Loading Quest Area Triggers..." );
1215 objmgr
.LoadQuestAreaTriggers(); // must be after LoadQuests
1217 sLog
.outString( "Loading Tavern Area Triggers..." );
1218 objmgr
.LoadTavernAreaTriggers();
1220 sLog
.outString( "Loading AreaTrigger script names..." );
1221 objmgr
.LoadAreaTriggerScripts();
1223 sLog
.outString( "Loading Graveyard-zone links...");
1224 objmgr
.LoadGraveyardZones();
1226 sLog
.outString( "Loading Spell target coordinates..." );
1227 spellmgr
.LoadSpellTargetPositions();
1229 sLog
.outString( "Loading SpellAffect definitions..." );
1230 spellmgr
.LoadSpellAffects();
1232 sLog
.outString( "Loading spell pet auras..." );
1233 spellmgr
.LoadSpellPetAuras();
1235 sLog
.outString( "Loading pet levelup spells..." );
1236 spellmgr
.LoadPetLevelupSpellMap();
1238 sLog
.outString( "Loading Player Create Info & Level Stats..." );
1240 objmgr
.LoadPlayerInfo();
1241 sLog
.outString( ">>> Player Create Info & Level Stats loaded" );
1244 sLog
.outString( "Loading Exploration BaseXP Data..." );
1245 objmgr
.LoadExplorationBaseXP();
1247 sLog
.outString( "Loading Pet Name Parts..." );
1248 objmgr
.LoadPetNames();
1250 sLog
.outString( "Loading the max pet number..." );
1251 objmgr
.LoadPetNumber();
1253 sLog
.outString( "Loading pet level stats..." );
1254 objmgr
.LoadPetLevelInfo();
1256 sLog
.outString( "Loading Player Corpses..." );
1257 objmgr
.LoadCorpses();
1259 sLog
.outString( "Loading Loot Tables..." );
1262 sLog
.outString( ">>> Loot Tables loaded" );
1265 sLog
.outString( "Loading Skill Discovery Table..." );
1266 LoadSkillDiscoveryTable();
1268 sLog
.outString( "Loading Skill Extra Item Table..." );
1269 LoadSkillExtraItemTable();
1271 sLog
.outString( "Loading Skill Fishing base level requirements..." );
1272 objmgr
.LoadFishingBaseSkillLevel();
1274 sLog
.outString( "Loading Achievements..." );
1276 achievementmgr
.LoadAchievementCriteriaList();
1277 achievementmgr
.LoadRewards();
1278 achievementmgr
.LoadRewardLocales();
1279 achievementmgr
.LoadCompletedAchievements();
1280 sLog
.outString( ">>> Achievements loaded" );
1283 ///- Load dynamic data tables from the database
1284 sLog
.outString( "Loading Auctions..." );
1286 auctionmgr
.LoadAuctionItems();
1287 auctionmgr
.LoadAuctions();
1288 sLog
.outString( ">>> Auctions loaded" );
1291 sLog
.outString( "Loading Guilds..." );
1292 objmgr
.LoadGuilds();
1294 sLog
.outString( "Loading ArenaTeams..." );
1295 objmgr
.LoadArenaTeams();
1297 sLog
.outString( "Loading Groups..." );
1298 objmgr
.LoadGroups();
1300 sLog
.outString( "Loading ReservedNames..." );
1301 objmgr
.LoadReservedPlayersNames();
1303 sLog
.outString( "Loading GameObjects for quests..." );
1304 objmgr
.LoadGameObjectForQuests();
1306 sLog
.outString( "Loading BattleMasters..." );
1307 sBattleGroundMgr
.LoadBattleMastersEntry();
1309 sLog
.outString( "Loading GameTeleports..." );
1310 objmgr
.LoadGameTele();
1312 sLog
.outString( "Loading Npc Text Id..." );
1313 objmgr
.LoadNpcTextId(); // must be after load Creature and NpcText
1315 sLog
.outString( "Loading Npc Options..." );
1316 objmgr
.LoadNpcOptions();
1318 sLog
.outString( "Loading Vendors..." );
1319 objmgr
.LoadVendors(); // must be after load CreatureTemplate and ItemTemplate
1321 sLog
.outString( "Loading Trainers..." );
1322 objmgr
.LoadTrainerSpell(); // must be after load CreatureTemplate
1324 sLog
.outString( "Loading Waypoints..." );
1328 sLog
.outString( "Loading GM tickets...");
1329 ticketmgr
.LoadGMTickets();
1331 ///- Handle outdated emails (delete/return)
1332 sLog
.outString( "Returning old mails..." );
1333 objmgr
.ReturnOrDeleteOldMails(false);
1335 ///- Load and initialize scripts
1336 sLog
.outString( "Loading Scripts..." );
1338 objmgr
.LoadQuestStartScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1339 objmgr
.LoadQuestEndScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1340 objmgr
.LoadSpellScripts(); // must be after load Creature/Gameobject(Template/Data)
1341 objmgr
.LoadGameObjectScripts(); // must be after load Creature/Gameobject(Template/Data)
1342 objmgr
.LoadEventScripts(); // must be after load Creature/Gameobject(Template/Data)
1343 sLog
.outString( ">>> Scripts loaded" );
1346 sLog
.outString( "Loading Scripts text locales..." ); // must be after Load*Scripts calls
1347 objmgr
.LoadDbScriptStrings();
1349 sLog
.outString( "Initializing Scripts..." );
1350 if(!LoadScriptingModule())
1353 ///- Initialize game time and timers
1354 sLog
.outString( "DEBUG:: Initialize game time and timers" );
1355 m_gameTime
= time(NULL
);
1356 m_startTime
=m_gameTime
;
1361 local
=*(localtime(&curr
)); // dereference and assign
1363 sprintf( isoDate
, "%04d-%02d-%02d %02d:%02d:%02d",
1364 local
.tm_year
+1900, local
.tm_mon
+1, local
.tm_mday
, local
.tm_hour
, local
.tm_min
, local
.tm_sec
);
1366 WorldDatabase
.PExecute("INSERT INTO uptime (startstring, starttime, uptime) VALUES('%s', " I64FMTD
", 0)",
1367 isoDate
, uint64(m_startTime
));
1369 m_timers
[WUPDATE_OBJECTS
].SetInterval(0);
1370 m_timers
[WUPDATE_SESSIONS
].SetInterval(0);
1371 m_timers
[WUPDATE_WEATHERS
].SetInterval(1*IN_MILISECONDS
);
1372 m_timers
[WUPDATE_AUCTIONS
].SetInterval(MINUTE
*IN_MILISECONDS
);
1373 m_timers
[WUPDATE_UPTIME
].SetInterval(m_configs
[CONFIG_UPTIME_UPDATE
]*MINUTE
*IN_MILISECONDS
);
1374 //Update "uptime" table based on configuration entry in minutes.
1375 m_timers
[WUPDATE_CORPSES
].SetInterval(20*MINUTE
*IN_MILISECONDS
);
1376 //erase corpses every 20 minutes
1378 //to set mailtimer to return mails every day between 4 and 5 am
1379 //mailtimer is increased when updating auctions
1380 //one second is 1000 -(tested on win system)
1381 mail_timer
= ((((localtime( &m_gameTime
)->tm_hour
+ 20) % 24)* HOUR
* IN_MILISECONDS
) / m_timers
[WUPDATE_AUCTIONS
].GetInterval() );
1383 mail_timer_expires
= ( (DAY
* IN_MILISECONDS
) / (m_timers
[WUPDATE_AUCTIONS
].GetInterval()));
1384 sLog
.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer
, mail_timer_expires
);
1386 ///- Initilize static helper structures
1387 AIRegistry::Initialize();
1388 WaypointMovementGenerator
<Creature
>::Initialize();
1389 Player::InitVisibleBits();
1391 ///- Initialize MapManager
1392 sLog
.outString( "Starting Map System" );
1393 MapManager::Instance().Initialize();
1395 ///- Initialize Battlegrounds
1396 sLog
.outString( "Starting BattleGround System" );
1397 sBattleGroundMgr
.CreateInitialBattleGrounds();
1398 sBattleGroundMgr
.InitAutomaticArenaPointDistribution();
1400 //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1401 sLog
.outString( "Loading Transports..." );
1402 MapManager::Instance().LoadTransports();
1404 sLog
.outString("Deleting expired bans..." );
1405 loginDatabase
.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1407 sLog
.outString("Calculate next daily quest reset time..." );
1408 InitDailyQuestResetTime();
1410 sLog
.outString("Starting objects Pooling system..." );
1411 poolhandler
.Initialize();
1413 sLog
.outString("Starting Game Event system..." );
1414 uint32 nextGameEvent
= gameeventmgr
.Initialize();
1415 m_timers
[WUPDATE_EVENTS
].SetInterval(nextGameEvent
); //depend on next event
1417 sLog
.outString( "WORLD: World initialized" );
1420 void World::DetectDBCLang()
1422 uint32 m_lang_confid
= sConfig
.GetIntDefault("DBC.Locale", 255);
1424 if(m_lang_confid
!= 255 && m_lang_confid
>= MAX_LOCALE
)
1426 sLog
.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE
);
1427 m_lang_confid
= LOCALE_enUS
;
1430 ChrRacesEntry
const* race
= sChrRacesStore
.LookupEntry(1);
1432 std::string availableLocalsStr
;
1434 int default_locale
= MAX_LOCALE
;
1435 for (int i
= MAX_LOCALE
-1; i
>= 0; --i
)
1437 if ( strlen(race
->name
[i
]) > 0) // check by race names
1440 m_availableDbcLocaleMask
|= (1 << i
);
1441 availableLocalsStr
+= localeNames
[i
];
1442 availableLocalsStr
+= " ";
1446 if( default_locale
!= m_lang_confid
&& m_lang_confid
< MAX_LOCALE
&&
1447 (m_availableDbcLocaleMask
& (1 << m_lang_confid
)) )
1449 default_locale
= m_lang_confid
;
1452 if(default_locale
>= MAX_LOCALE
)
1454 sLog
.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1458 m_defaultDbcLocale
= LocaleConstant(default_locale
);
1460 sLog
.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames
[m_defaultDbcLocale
],availableLocalsStr
.empty() ? "<none>" : availableLocalsStr
.c_str());
1464 /// Update the World !
1465 void World::Update(uint32 diff
)
1467 ///- Update the different timers
1468 for(int i
= 0; i
< WUPDATE_COUNT
; i
++)
1469 if(m_timers
[i
].GetCurrent()>=0)
1470 m_timers
[i
].Update(diff
);
1471 else m_timers
[i
].SetCurrent(0);
1473 ///- Update the game time and check for shutdown time
1476 /// Handle daily quests reset time
1477 if(m_gameTime
> m_NextDailyQuestReset
)
1480 m_NextDailyQuestReset
+= DAY
;
1483 /// <ul><li> Handle auctions when the timer has passed
1484 if (m_timers
[WUPDATE_AUCTIONS
].Passed())
1486 m_timers
[WUPDATE_AUCTIONS
].Reset();
1488 ///- Update mails (return old mails with item, or delete them)
1489 //(tested... works on win)
1490 if (++mail_timer
> mail_timer_expires
)
1493 objmgr
.ReturnOrDeleteOldMails(true);
1496 ///- Handle expired auctions
1497 auctionmgr
.Update();
1500 /// <li> Handle session updates when the timer has passed
1501 if (m_timers
[WUPDATE_SESSIONS
].Passed())
1503 m_timers
[WUPDATE_SESSIONS
].Reset();
1505 UpdateSessions(diff
);
1508 /// <li> Handle weather updates when the timer has passed
1509 if (m_timers
[WUPDATE_WEATHERS
].Passed())
1511 m_timers
[WUPDATE_WEATHERS
].Reset();
1513 ///- Send an update signal to Weather objects
1514 WeatherMap::iterator itr
, next
;
1515 for (itr
= m_weathers
.begin(); itr
!= m_weathers
.end(); itr
= next
)
1520 ///- and remove Weather objects for zones with no player
1521 //As interval > WorldTick
1522 if(!itr
->second
->Update(m_timers
[WUPDATE_WEATHERS
].GetInterval()))
1525 m_weathers
.erase(itr
);
1529 /// <li> Update uptime table
1530 if (m_timers
[WUPDATE_UPTIME
].Passed())
1532 uint32 tmpDiff
= (m_gameTime
- m_startTime
);
1533 uint32 maxClientsNum
= sWorld
.GetMaxActiveSessionCount();
1535 m_timers
[WUPDATE_UPTIME
].Reset();
1536 WorldDatabase
.PExecute("UPDATE uptime SET uptime = %d, maxplayers = %d WHERE starttime = " I64FMTD
, tmpDiff
, maxClientsNum
, uint64(m_startTime
));
1539 /// <li> Handle all other objects
1540 if (m_timers
[WUPDATE_OBJECTS
].Passed())
1542 m_timers
[WUPDATE_OBJECTS
].Reset();
1543 ///- Update objects when the timer has passed (maps, transport, creatures,...)
1544 MapManager::Instance().Update(diff
); // As interval = 0
1546 ///- Process necessary scripts
1547 if (!m_scriptSchedule
.empty())
1550 sBattleGroundMgr
.Update(diff
);
1553 // execute callbacks from sql queries that were queued recently
1554 UpdateResultQueue();
1556 ///- Erase corpses once every 20 minutes
1557 if (m_timers
[WUPDATE_CORPSES
].Passed())
1559 m_timers
[WUPDATE_CORPSES
].Reset();
1564 ///- Process Game events when necessary
1565 if (m_timers
[WUPDATE_EVENTS
].Passed())
1567 m_timers
[WUPDATE_EVENTS
].Reset(); // to give time for Update() to be processed
1568 uint32 nextGameEvent
= gameeventmgr
.Update();
1569 m_timers
[WUPDATE_EVENTS
].SetInterval(nextGameEvent
);
1570 m_timers
[WUPDATE_EVENTS
].Reset();
1574 ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1575 MapManager::Instance().DoDelayedMovesAndRemoves();
1577 // update the instance reset times
1578 sInstanceSaveManager
.Update();
1580 // And last, but not least handle the issued cli commands
1581 ProcessCliCommands();
1584 /// Put scripts in the execution queue
1585 void World::ScriptsStart(ScriptMapMap
const& scripts
, uint32 id
, Object
* source
, Object
* target
)
1587 ///- Find the script map
1588 ScriptMapMap::const_iterator s
= scripts
.find(id
);
1589 if (s
== scripts
.end())
1592 // prepare static data
1593 uint64 sourceGUID
= source
->GetGUID();
1594 uint64 targetGUID
= target
? target
->GetGUID() : (uint64
)0;
1595 uint64 ownerGUID
= (source
->GetTypeId()==TYPEID_ITEM
) ? ((Item
*)source
)->GetOwnerGUID() : (uint64
)0;
1597 ///- Schedule script execution for all scripts in the script map
1598 ScriptMap
const *s2
= &(s
->second
);
1599 bool immedScript
= false;
1600 for (ScriptMap::const_iterator iter
= s2
->begin(); iter
!= s2
->end(); ++iter
)
1603 sa
.sourceGUID
= sourceGUID
;
1604 sa
.targetGUID
= targetGUID
;
1605 sa
.ownerGUID
= ownerGUID
;
1607 sa
.script
= &iter
->second
;
1608 m_scriptSchedule
.insert(std::pair
<time_t, ScriptAction
>(m_gameTime
+ iter
->first
, sa
));
1609 if (iter
->first
== 0)
1612 ///- If one of the effects should be immediate, launch the script execution
1617 void World::ScriptCommandStart(ScriptInfo
const& script
, uint32 delay
, Object
* source
, Object
* target
)
1619 // NOTE: script record _must_ exist until command executed
1621 // prepare static data
1622 uint64 sourceGUID
= source
->GetGUID();
1623 uint64 targetGUID
= target
? target
->GetGUID() : (uint64
)0;
1624 uint64 ownerGUID
= (source
->GetTypeId()==TYPEID_ITEM
) ? ((Item
*)source
)->GetOwnerGUID() : (uint64
)0;
1627 sa
.sourceGUID
= sourceGUID
;
1628 sa
.targetGUID
= targetGUID
;
1629 sa
.ownerGUID
= ownerGUID
;
1631 sa
.script
= &script
;
1632 m_scriptSchedule
.insert(std::pair
<time_t, ScriptAction
>(m_gameTime
+ delay
, sa
));
1634 ///- If effects should be immediate, launch the script execution
1639 /// Process queued scripts
1640 void World::ScriptsProcess()
1642 if (m_scriptSchedule
.empty())
1645 ///- Process overdue queued scripts
1646 std::multimap
<time_t, ScriptAction
>::iterator iter
= m_scriptSchedule
.begin();
1647 // ok as multimap is a *sorted* associative container
1648 while (!m_scriptSchedule
.empty() && (iter
->first
<= m_gameTime
))
1650 ScriptAction
const& step
= iter
->second
;
1652 Object
* source
= NULL
;
1656 switch(GUID_HIPART(step
.sourceGUID
))
1659 // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1661 Player
* player
= HashMapHolder
<Player
>::Find(step
.ownerGUID
);
1663 source
= player
->GetItemByGuid(step
.sourceGUID
);
1667 source
= HashMapHolder
<Creature
>::Find(step
.sourceGUID
);
1670 source
= HashMapHolder
<Pet
>::Find(step
.sourceGUID
);
1672 case HIGHGUID_VEHICLE
:
1673 source
= HashMapHolder
<Vehicle
>::Find(step
.sourceGUID
);
1675 case HIGHGUID_PLAYER
:
1676 source
= HashMapHolder
<Player
>::Find(step
.sourceGUID
);
1678 case HIGHGUID_GAMEOBJECT
:
1679 source
= HashMapHolder
<GameObject
>::Find(step
.sourceGUID
);
1681 case HIGHGUID_CORPSE
:
1682 source
= HashMapHolder
<Corpse
>::Find(step
.sourceGUID
);
1685 sLog
.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step
.sourceGUID
));
1690 if(source
&& !source
->IsInWorld()) source
= NULL
;
1692 Object
* target
= NULL
;
1696 switch(GUID_HIPART(step
.targetGUID
))
1699 target
= HashMapHolder
<Creature
>::Find(step
.targetGUID
);
1702 target
= HashMapHolder
<Pet
>::Find(step
.targetGUID
);
1704 case HIGHGUID_VEHICLE
:
1705 target
= HashMapHolder
<Vehicle
>::Find(step
.targetGUID
);
1707 case HIGHGUID_PLAYER
: // empty GUID case also
1708 target
= HashMapHolder
<Player
>::Find(step
.targetGUID
);
1710 case HIGHGUID_GAMEOBJECT
:
1711 target
= HashMapHolder
<GameObject
>::Find(step
.targetGUID
);
1713 case HIGHGUID_CORPSE
:
1714 target
= HashMapHolder
<Corpse
>::Find(step
.targetGUID
);
1717 sLog
.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step
.targetGUID
));
1722 if(target
&& !target
->IsInWorld()) target
= NULL
;
1724 switch (step
.script
->command
)
1726 case SCRIPT_COMMAND_TALK
:
1730 sLog
.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1734 if(source
->GetTypeId()!=TYPEID_UNIT
)
1736 sLog
.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source
->GetTypeId());
1740 uint64 unit_target
= target
? target
->GetGUID() : 0;
1742 //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1743 switch(step
.script
->datalong
)
1746 ((Creature
*)source
)->Say(step
.script
->dataint
, LANG_UNIVERSAL
, unit_target
);
1751 sLog
.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step
.script
->datalong
);
1754 ((Creature
*)source
)->Whisper(step
.script
->dataint
,unit_target
);
1757 ((Creature
*)source
)->Yell(step
.script
->dataint
, LANG_UNIVERSAL
, unit_target
);
1759 case 3: // Emote text
1760 ((Creature
*)source
)->TextEmote(step
.script
->dataint
, unit_target
);
1763 break; // must be already checked at load
1768 case SCRIPT_COMMAND_EMOTE
:
1771 sLog
.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1775 if(source
->GetTypeId()!=TYPEID_UNIT
)
1777 sLog
.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source
->GetTypeId());
1781 ((Creature
*)source
)->HandleEmoteCommand(step
.script
->datalong
);
1783 case SCRIPT_COMMAND_FIELD_SET
:
1786 sLog
.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1789 if(step
.script
->datalong
<= OBJECT_FIELD_ENTRY
|| step
.script
->datalong
>= source
->GetValuesCount())
1791 sLog
.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1792 step
.script
->datalong
,source
->GetValuesCount(),source
->GetTypeId());
1796 source
->SetUInt32Value(step
.script
->datalong
, step
.script
->datalong2
);
1798 case SCRIPT_COMMAND_MOVE_TO
:
1801 sLog
.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1805 if(source
->GetTypeId()!=TYPEID_UNIT
)
1807 sLog
.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source
->GetTypeId());
1810 ((Unit
*)source
)->SendMonsterMoveWithSpeed(step
.script
->x
, step
.script
->y
, step
.script
->z
, step
.script
->datalong2
);
1811 ((Unit
*)source
)->GetMap()->CreatureRelocation(((Creature
*)source
), step
.script
->x
, step
.script
->y
, step
.script
->z
, 0);
1813 case SCRIPT_COMMAND_FLAG_SET
:
1816 sLog
.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1819 if(step
.script
->datalong
<= OBJECT_FIELD_ENTRY
|| step
.script
->datalong
>= source
->GetValuesCount())
1821 sLog
.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1822 step
.script
->datalong
,source
->GetValuesCount(),source
->GetTypeId());
1826 source
->SetFlag(step
.script
->datalong
, step
.script
->datalong2
);
1828 case SCRIPT_COMMAND_FLAG_REMOVE
:
1831 sLog
.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1834 if(step
.script
->datalong
<= OBJECT_FIELD_ENTRY
|| step
.script
->datalong
>= source
->GetValuesCount())
1836 sLog
.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1837 step
.script
->datalong
,source
->GetValuesCount(),source
->GetTypeId());
1841 source
->RemoveFlag(step
.script
->datalong
, step
.script
->datalong2
);
1844 case SCRIPT_COMMAND_TELEPORT_TO
:
1846 // accept player in any one from target/source arg
1847 if (!target
&& !source
)
1849 sLog
.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1853 // must be only Player
1854 if((!target
|| target
->GetTypeId() != TYPEID_PLAYER
) && (!source
|| source
->GetTypeId() != TYPEID_PLAYER
))
1856 sLog
.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source
? source
->GetTypeId() : 0, target
? target
->GetTypeId() : 0);
1860 Player
* pSource
= target
&& target
->GetTypeId() == TYPEID_PLAYER
? (Player
*)target
: (Player
*)source
;
1862 pSource
->TeleportTo(step
.script
->datalong
, step
.script
->x
, step
.script
->y
, step
.script
->z
, step
.script
->o
);
1866 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE
:
1868 if(!step
.script
->datalong
) // creature not specified
1870 sLog
.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1876 sLog
.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1880 WorldObject
* summoner
= dynamic_cast<WorldObject
*>(source
);
1884 sLog
.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source
->GetTypeId());
1888 float x
= step
.script
->x
;
1889 float y
= step
.script
->y
;
1890 float z
= step
.script
->z
;
1891 float o
= step
.script
->o
;
1893 Creature
* pCreature
= summoner
->SummonCreature(step
.script
->datalong
, x
, y
, z
, o
,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN
,step
.script
->datalong2
);
1896 sLog
.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step
.script
->datalong
);
1903 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT
:
1905 if(!step
.script
->datalong
) // gameobject not specified
1907 sLog
.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1913 sLog
.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1917 WorldObject
* summoner
= dynamic_cast<WorldObject
*>(source
);
1921 sLog
.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source
->GetTypeId());
1925 GameObject
*go
= NULL
;
1926 int32 time_to_despawn
= step
.script
->datalong2
<5 ? 5 : (int32
)step
.script
->datalong2
;
1928 CellPair
p(MaNGOS::ComputeCellPair(summoner
->GetPositionX(), summoner
->GetPositionY()));
1930 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
1932 MaNGOS::GameObjectWithDbGUIDCheck
go_check(*summoner
,step
.script
->datalong
);
1933 MaNGOS::GameObjectSearcher
<MaNGOS::GameObjectWithDbGUIDCheck
> checker(summoner
, go
,go_check
);
1935 TypeContainerVisitor
<MaNGOS::GameObjectSearcher
<MaNGOS::GameObjectWithDbGUIDCheck
>, GridTypeMapContainer
> object_checker(checker
);
1936 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
1937 cell_lock
->Visit(cell_lock
, object_checker
, *summoner
->GetMap());
1941 sLog
.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step
.script
->datalong
);
1945 if( go
->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE
||
1946 go
->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE
||
1947 go
->GetGoType()==GAMEOBJECT_TYPE_DOOR
||
1948 go
->GetGoType()==GAMEOBJECT_TYPE_BUTTON
||
1949 go
->GetGoType()==GAMEOBJECT_TYPE_TRAP
)
1951 sLog
.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go
->GetGoType()), step
.script
->datalong
);
1955 if( go
->isSpawned() )
1956 break; //gameobject already spawned
1958 go
->SetLootState(GO_READY
);
1959 go
->SetRespawnTime(time_to_despawn
); //despawn object in ? seconds
1961 go
->GetMap()->Add(go
);
1964 case SCRIPT_COMMAND_OPEN_DOOR
:
1966 if(!step
.script
->datalong
) // door not specified
1968 sLog
.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1974 sLog
.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1978 if(!source
->isType(TYPEMASK_UNIT
)) // must be any Unit (creature or player)
1980 sLog
.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source
->GetTypeId());
1984 Unit
* caster
= (Unit
*)source
;
1986 GameObject
*door
= NULL
;
1987 int32 time_to_close
= step
.script
->datalong2
< 15 ? 15 : (int32
)step
.script
->datalong2
;
1989 CellPair
p(MaNGOS::ComputeCellPair(caster
->GetPositionX(), caster
->GetPositionY()));
1991 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
1993 MaNGOS::GameObjectWithDbGUIDCheck
go_check(*caster
,step
.script
->datalong
);
1994 MaNGOS::GameObjectSearcher
<MaNGOS::GameObjectWithDbGUIDCheck
> checker(caster
,door
,go_check
);
1996 TypeContainerVisitor
<MaNGOS::GameObjectSearcher
<MaNGOS::GameObjectWithDbGUIDCheck
>, GridTypeMapContainer
> object_checker(checker
);
1997 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
1998 cell_lock
->Visit(cell_lock
, object_checker
, *caster
->GetMap());
2002 sLog
.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step
.script
->datalong
);
2005 if ( door
->GetGoType() != GAMEOBJECT_TYPE_DOOR
)
2007 sLog
.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door
->GetGoType());
2011 if( !door
->GetGoState() )
2012 break; //door already open
2014 door
->UseDoorOrButton(time_to_close
);
2016 if(target
&& target
->isType(TYPEMASK_GAMEOBJECT
) && ((GameObject
*)target
)->GetGoType()==GAMEOBJECT_TYPE_BUTTON
)
2017 ((GameObject
*)target
)->UseDoorOrButton(time_to_close
);
2020 case SCRIPT_COMMAND_CLOSE_DOOR
:
2022 if(!step
.script
->datalong
) // guid for door not specified
2024 sLog
.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
2030 sLog
.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
2034 if(!source
->isType(TYPEMASK_UNIT
)) // must be any Unit (creature or player)
2036 sLog
.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source
->GetTypeId());
2040 Unit
* caster
= (Unit
*)source
;
2042 GameObject
*door
= NULL
;
2043 int32 time_to_open
= step
.script
->datalong2
< 15 ? 15 : (int32
)step
.script
->datalong2
;
2045 CellPair
p(MaNGOS::ComputeCellPair(caster
->GetPositionX(), caster
->GetPositionY()));
2047 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
2049 MaNGOS::GameObjectWithDbGUIDCheck
go_check(*caster
,step
.script
->datalong
);
2050 MaNGOS::GameObjectSearcher
<MaNGOS::GameObjectWithDbGUIDCheck
> checker(caster
,door
,go_check
);
2052 TypeContainerVisitor
<MaNGOS::GameObjectSearcher
<MaNGOS::GameObjectWithDbGUIDCheck
>, GridTypeMapContainer
> object_checker(checker
);
2053 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
2054 cell_lock
->Visit(cell_lock
, object_checker
, *caster
->GetMap());
2058 sLog
.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step
.script
->datalong
);
2061 if ( door
->GetGoType() != GAMEOBJECT_TYPE_DOOR
)
2063 sLog
.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door
->GetGoType());
2067 if( door
->GetGoState() )
2068 break; //door already closed
2070 door
->UseDoorOrButton(time_to_open
);
2072 if(target
&& target
->isType(TYPEMASK_GAMEOBJECT
) && ((GameObject
*)target
)->GetGoType()==GAMEOBJECT_TYPE_BUTTON
)
2073 ((GameObject
*)target
)->UseDoorOrButton(time_to_open
);
2077 case SCRIPT_COMMAND_QUEST_EXPLORED
:
2081 sLog
.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
2087 sLog
.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
2091 // when script called for item spell casting then target == (unit or GO) and source is player
2092 WorldObject
* worldObject
;
2095 if(target
->GetTypeId()==TYPEID_PLAYER
)
2097 if(source
->GetTypeId()!=TYPEID_UNIT
&& source
->GetTypeId()!=TYPEID_GAMEOBJECT
)
2099 sLog
.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source
->GetTypeId());
2103 worldObject
= (WorldObject
*)source
;
2104 player
= (Player
*)target
;
2108 if(target
->GetTypeId()!=TYPEID_UNIT
&& target
->GetTypeId()!=TYPEID_GAMEOBJECT
)
2110 sLog
.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target
->GetTypeId());
2114 if(source
->GetTypeId()!=TYPEID_PLAYER
)
2116 sLog
.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source
->GetTypeId());
2120 worldObject
= (WorldObject
*)target
;
2121 player
= (Player
*)source
;
2124 // quest id and flags checked at script loading
2125 if( (worldObject
->GetTypeId()!=TYPEID_UNIT
|| ((Unit
*)worldObject
)->isAlive()) &&
2126 (step
.script
->datalong2
==0 || worldObject
->IsWithinDistInMap(player
,float(step
.script
->datalong2
))) )
2127 player
->AreaExploredOrEventHappens(step
.script
->datalong
);
2129 player
->FailQuest(step
.script
->datalong
);
2134 case SCRIPT_COMMAND_ACTIVATE_OBJECT
:
2138 sLog
.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
2142 if(!source
->isType(TYPEMASK_UNIT
))
2144 sLog
.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source
->GetTypeId());
2150 sLog
.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
2154 if(target
->GetTypeId()!=TYPEID_GAMEOBJECT
)
2156 sLog
.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target
->GetTypeId());
2160 Unit
* caster
= (Unit
*)source
;
2162 GameObject
*go
= (GameObject
*)target
;
2168 case SCRIPT_COMMAND_REMOVE_AURA
:
2170 Object
* cmdTarget
= step
.script
->datalong2
? source
: target
;
2174 sLog
.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step
.script
->datalong2
? "source" : "target");
2178 if(!cmdTarget
->isType(TYPEMASK_UNIT
))
2180 sLog
.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step
.script
->datalong2
? "source" : "target",cmdTarget
->GetTypeId());
2184 ((Unit
*)cmdTarget
)->RemoveAurasDueToSpell(step
.script
->datalong
);
2188 case SCRIPT_COMMAND_CAST_SPELL
:
2192 sLog
.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
2196 if(!source
->isType(TYPEMASK_UNIT
))
2198 sLog
.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source
->GetTypeId());
2202 Object
* cmdTarget
= step
.script
->datalong2
& 0x01 ? source
: target
;
2206 sLog
.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step
.script
->datalong2
& 0x01 ? "source" : "target");
2210 if(!cmdTarget
->isType(TYPEMASK_UNIT
))
2212 sLog
.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step
.script
->datalong2
& 0x01 ? "source" : "target",cmdTarget
->GetTypeId());
2216 Unit
* spellTarget
= (Unit
*)cmdTarget
;
2218 Object
* cmdSource
= step
.script
->datalong2
& 0x02 ? target
: source
;
2222 sLog
.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step
.script
->datalong2
& 0x02 ? "target" : "source");
2226 if(!cmdSource
->isType(TYPEMASK_UNIT
))
2228 sLog
.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step
.script
->datalong2
& 0x02 ? "target" : "source", cmdSource
->GetTypeId());
2232 Unit
* spellSource
= (Unit
*)cmdSource
;
2234 //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2235 spellSource
->CastSpell(spellTarget
,step
.script
->datalong
,false);
2240 case SCRIPT_COMMAND_PLAY_SOUND
:
2244 sLog
.outError("SCRIPT_COMMAND_PLAY_SOUND call for NULL creature.");
2248 WorldObject
* pSource
= dynamic_cast<WorldObject
*>(source
);
2251 sLog
.outError("SCRIPT_COMMAND_PLAY_SOUND call for non-world object (TypeId: %u), skipping.",source
->GetTypeId());
2255 // bitmask: 0/1=anyone/target, 0/2=with distance dependent
2256 Player
* pTarget
= NULL
;
2257 if(step
.script
->datalong2
& 1)
2261 sLog
.outError("SCRIPT_COMMAND_PLAY_SOUND in targeted mode call for NULL target.");
2265 if(target
->GetTypeId()!=TYPEID_PLAYER
)
2267 sLog
.outError("SCRIPT_COMMAND_PLAY_SOUND in targeted mode call for non-player (TypeId: %u), skipping.",target
->GetTypeId());
2271 pTarget
= (Player
*)target
;
2274 // bitmask: 0/1=anyone/target, 0/2=with distance dependent
2275 if(step
.script
->datalong2
& 2)
2276 pSource
->PlayDistanceSound(step
.script
->datalong
,pTarget
);
2278 pSource
->PlayDirectSound(step
.script
->datalong
,pTarget
);
2282 sLog
.outError("Unknown script command %u called.",step
.script
->command
);
2286 m_scriptSchedule
.erase(iter
);
2288 iter
= m_scriptSchedule
.begin();
2293 /// Send a packet to all players (except self if mentioned)
2294 void World::SendGlobalMessage(WorldPacket
*packet
, WorldSession
*self
, uint32 team
)
2296 SessionMap::iterator itr
;
2297 for (itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2300 itr
->second
->GetPlayer() &&
2301 itr
->second
->GetPlayer()->IsInWorld() &&
2302 itr
->second
!= self
&&
2303 (team
== 0 || itr
->second
->GetPlayer()->GetTeam() == team
) )
2305 itr
->second
->SendPacket(packet
);
2312 class WorldWorldTextBuilder
2315 typedef std::vector
<WorldPacket
*> WorldPacketList
;
2316 explicit WorldWorldTextBuilder(int32 textId
, va_list* args
= NULL
) : i_textId(textId
), i_args(args
) {}
2317 void operator()(WorldPacketList
& data_list
, int32 loc_idx
)
2319 char const* text
= objmgr
.GetMangosString(i_textId
,loc_idx
);
2323 // we need copy va_list before use or original va_list will corrupted
2325 va_copy(ap
,*i_args
);
2328 vsnprintf(str
,2048,text
, ap
);
2331 do_helper(data_list
,&str
[0]);
2334 do_helper(data_list
,(char*)text
);
2337 char* lineFromMessage(char*& pos
) { char* start
= strtok(pos
,"\n"); pos
= NULL
; return start
; }
2338 void do_helper(WorldPacketList
& data_list
, char* text
)
2342 while(char* line
= lineFromMessage(pos
))
2344 WorldPacket
* data
= new WorldPacket();
2346 uint32 lineLength
= (line
? strlen(line
) : 0) + 1;
2348 data
->Initialize(SMSG_MESSAGECHAT
, 100); // guess size
2349 *data
<< uint8(CHAT_MSG_SYSTEM
);
2350 *data
<< uint32(LANG_UNIVERSAL
);
2352 *data
<< uint32(0); // can be chat msg group or something
2354 *data
<< uint32(lineLength
);
2358 data_list
.push_back(data
);
2365 } // namespace MaNGOS
2367 /// Send a System Message to all players (except self if mentioned)
2368 void World::SendWorldText(int32 string_id
, ...)
2371 va_start(ap
, string_id
);
2373 MaNGOS::WorldWorldTextBuilder
wt_builder(string_id
, &ap
);
2374 MaNGOS::LocalizedPacketListDo
<MaNGOS::WorldWorldTextBuilder
> wt_do(wt_builder
);
2375 for(SessionMap::iterator itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2377 if(!itr
->second
|| !itr
->second
->GetPlayer() || !itr
->second
->GetPlayer()->IsInWorld() )
2380 wt_do(itr
->second
->GetPlayer());
2386 /// DEPRICATED, only for debug purpose. Send a System Message to all players (except self if mentioned)
2387 void World::SendGlobalText(const char* text
, WorldSession
*self
)
2391 // need copy to prevent corruption by strtok call in LineFromMessage original string
2392 char* buf
= strdup(text
);
2395 while(char* line
= ChatHandler::LineFromMessage(pos
))
2397 ChatHandler::FillMessageData(&data
, NULL
, CHAT_MSG_SYSTEM
, LANG_UNIVERSAL
, NULL
, 0, line
, NULL
);
2398 SendGlobalMessage(&data
, self
);
2404 /// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2405 void World::SendZoneMessage(uint32 zone
, WorldPacket
*packet
, WorldSession
*self
, uint32 team
)
2407 SessionMap::iterator itr
;
2408 for (itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2411 itr
->second
->GetPlayer() &&
2412 itr
->second
->GetPlayer()->IsInWorld() &&
2413 itr
->second
->GetPlayer()->GetZoneId() == zone
&&
2414 itr
->second
!= self
&&
2415 (team
== 0 || itr
->second
->GetPlayer()->GetTeam() == team
) )
2417 itr
->second
->SendPacket(packet
);
2422 /// Send a System Message to all players in the zone (except self if mentioned)
2423 void World::SendZoneText(uint32 zone
, const char* text
, WorldSession
*self
, uint32 team
)
2426 ChatHandler::FillMessageData(&data
, NULL
, CHAT_MSG_SYSTEM
, LANG_UNIVERSAL
, NULL
, 0, text
, NULL
);
2427 SendZoneMessage(zone
, &data
, self
,team
);
2430 /// Kick (and save) all players
2431 void World::KickAll()
2433 m_QueuedPlayer
.clear(); // prevent send queue update packet and login queued sessions
2435 // session not removed at kick and will removed in next update tick
2436 for (SessionMap::iterator itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2437 itr
->second
->KickPlayer();
2440 /// Kick (and save) all players with security level less `sec`
2441 void World::KickAllLess(AccountTypes sec
)
2443 // session not removed at kick and will removed in next update tick
2444 for (SessionMap::iterator itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2445 if(itr
->second
->GetSecurity() < sec
)
2446 itr
->second
->KickPlayer();
2449 /// Kick (and save) the designated player
2450 bool World::KickPlayer(const std::string
& playerName
)
2452 SessionMap::iterator itr
;
2454 // session not removed at kick and will removed in next update tick
2455 for (itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2459 Player
*player
= itr
->second
->GetPlayer();
2462 if( player
->IsInWorld() )
2464 if (playerName
== player
->GetName())
2466 itr
->second
->KickPlayer();
2474 /// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2475 BanReturn
World::BanAccount(BanMode mode
, std::string nameOrIP
, std::string duration
, std::string reason
, std::string author
)
2477 loginDatabase
.escape_string(nameOrIP
);
2478 loginDatabase
.escape_string(reason
);
2479 std::string safe_author
=author
;
2480 loginDatabase
.escape_string(safe_author
);
2482 uint32 duration_secs
= TimeStringToSecs(duration
);
2483 QueryResult
*resultAccounts
= NULL
; //used for kicking
2485 ///- Update the database with ban information
2489 //No SQL injection as strings are escaped
2490 resultAccounts
= loginDatabase
.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP
.c_str());
2491 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());
2494 //No SQL injection as string is escaped
2495 resultAccounts
= loginDatabase
.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP
.c_str());
2498 //No SQL injection as string is escaped
2499 resultAccounts
= CharacterDatabase
.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP
.c_str());
2502 return BAN_SYNTAX_ERROR
;
2508 return BAN_SUCCESS
; // ip correctly banned but nobody affected (yet)
2510 return BAN_NOTFOUND
; // Nobody to ban
2513 ///- Disconnect all affected players (for IP it can be several)
2516 Field
* fieldsAccount
= resultAccounts
->Fetch();
2517 uint32 account
= fieldsAccount
->GetUInt32();
2521 //No SQL injection as strings are escaped
2522 loginDatabase
.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2523 account
,duration_secs
,safe_author
.c_str(),reason
.c_str());
2526 if (WorldSession
* sess
= FindSession(account
))
2527 if(std::string(sess
->GetPlayerName()) != author
)
2530 while( resultAccounts
->NextRow() );
2532 delete resultAccounts
;
2536 /// Remove a ban from an account or IP address
2537 bool World::RemoveBanAccount(BanMode mode
, std::string nameOrIP
)
2541 loginDatabase
.escape_string(nameOrIP
);
2542 loginDatabase
.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP
.c_str());
2547 if (mode
== BAN_ACCOUNT
)
2548 account
= accmgr
.GetId (nameOrIP
);
2549 else if (mode
== BAN_CHARACTER
)
2550 account
= objmgr
.GetPlayerAccountIdByPlayerName (nameOrIP
);
2555 //NO SQL injection as account is uint32
2556 loginDatabase
.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account
);
2561 /// Update the game time
2562 void World::_UpdateGameTime()
2564 ///- update the time
2565 time_t thisTime
= time(NULL
);
2566 uint32 elapsed
= uint32(thisTime
- m_gameTime
);
2567 m_gameTime
= thisTime
;
2569 ///- if there is a shutdown timer
2570 if(!m_stopEvent
&& m_ShutdownTimer
> 0 && elapsed
> 0)
2572 ///- ... and it is overdue, stop the world (set m_stopEvent)
2573 if( m_ShutdownTimer
<= elapsed
)
2575 if(!(m_ShutdownMask
& SHUTDOWN_MASK_IDLE
) || GetActiveAndQueuedSessionCount()==0)
2576 m_stopEvent
= true; // exist code already set
2578 m_ShutdownTimer
= 1; // minimum timer value to wait idle state
2580 ///- ... else decrease it and if necessary display a shutdown countdown to the users
2583 m_ShutdownTimer
-= elapsed
;
2590 /// Shutdown the server
2591 void World::ShutdownServ(uint32 time
, uint32 options
, uint8 exitcode
)
2593 // ignore if server shutdown at next tick
2597 m_ShutdownMask
= options
;
2598 m_ExitCode
= exitcode
;
2600 ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2603 if(!(options
& SHUTDOWN_MASK_IDLE
) || GetActiveAndQueuedSessionCount()==0)
2604 m_stopEvent
= true; // exist code already set
2606 m_ShutdownTimer
= 1; //So that the session count is re-evaluated at next world tick
2608 ///- Else set the shutdown timer and warn users
2611 m_ShutdownTimer
= time
;
2616 /// Display a shutdown message to the user(s)
2617 void World::ShutdownMsg(bool show
, Player
* player
)
2619 // not show messages for idle shutdown mode
2620 if(m_ShutdownMask
& SHUTDOWN_MASK_IDLE
)
2623 ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2625 (m_ShutdownTimer
< 10) ||
2626 // < 30 sec; every 5 sec
2627 (m_ShutdownTimer
<30 && (m_ShutdownTimer
% 5 )==0) ||
2628 // < 5 min ; every 1 min
2629 (m_ShutdownTimer
<5*MINUTE
&& (m_ShutdownTimer
% MINUTE
)==0) ||
2630 // < 30 min ; every 5 min
2631 (m_ShutdownTimer
<30*MINUTE
&& (m_ShutdownTimer
% (5*MINUTE
))==0) ||
2632 // < 12 h ; every 1 h
2633 (m_ShutdownTimer
<12*HOUR
&& (m_ShutdownTimer
% HOUR
)==0) ||
2634 // > 12 h ; every 12 h
2635 (m_ShutdownTimer
>12*HOUR
&& (m_ShutdownTimer
% (12*HOUR
) )==0))
2637 std::string str
= secsToTimeString(m_ShutdownTimer
);
2639 uint32 msgid
= (m_ShutdownMask
& SHUTDOWN_MASK_RESTART
) ? SERVER_MSG_RESTART_TIME
: SERVER_MSG_SHUTDOWN_TIME
;
2641 SendServerMessage(msgid
,str
.c_str(),player
);
2642 DEBUG_LOG("Server is %s in %s",(m_ShutdownMask
& SHUTDOWN_MASK_RESTART
? "restart" : "shuttingdown"),str
.c_str());
2646 /// Cancel a planned server shutdown
2647 void World::ShutdownCancel()
2649 // nothing cancel or too later
2650 if(!m_ShutdownTimer
|| m_stopEvent
)
2653 uint32 msgid
= (m_ShutdownMask
& SHUTDOWN_MASK_RESTART
) ? SERVER_MSG_RESTART_CANCELLED
: SERVER_MSG_SHUTDOWN_CANCELLED
;
2656 m_ShutdownTimer
= 0;
2657 m_ExitCode
= SHUTDOWN_EXIT_CODE
; // to default value
2658 SendServerMessage(msgid
);
2660 DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask
& SHUTDOWN_MASK_RESTART
? "restart" : "shuttingdown"));
2663 /// Send a server message to the user(s)
2664 void World::SendServerMessage(uint32 type
, const char *text
, Player
* player
)
2666 WorldPacket
data(SMSG_SERVER_MESSAGE
, 50); // guess size
2667 data
<< uint32(type
);
2668 if(type
<= SERVER_MSG_STRING
)
2672 player
->GetSession()->SendPacket(&data
);
2674 SendGlobalMessage( &data
);
2677 void World::UpdateSessions( uint32 diff
)
2679 ///- Add new sessions
2680 while(!addSessQueue
.empty())
2682 WorldSession
* sess
= addSessQueue
.next ();
2686 ///- Then send an update signal to remaining ones
2687 for (SessionMap::iterator itr
= m_sessions
.begin(), next
; itr
!= m_sessions
.end(); itr
= next
)
2695 ///- and remove not active sessions from the list
2696 if(!itr
->second
->Update(diff
)) // As interval = 0
2698 RemoveQueuedPlayer (itr
->second
);
2700 m_sessions
.erase(itr
);
2705 // This handles the issued and queued CLI commands
2706 void World::ProcessCliCommands()
2708 if (cliCmdQueue
.empty())
2711 CliCommandHolder::Print
* zprint
;
2713 while (!cliCmdQueue
.empty())
2715 sLog
.outDebug("CLI command under processing...");
2716 CliCommandHolder
*command
= cliCmdQueue
.next();
2718 zprint
= command
->m_print
;
2720 CliHandler(zprint
).ParseCommands(command
->m_command
);
2725 // print the console message here so it looks right
2729 void World::InitResultQueue()
2731 m_resultQueue
= new SqlResultQueue
;
2732 CharacterDatabase
.SetResultQueue(m_resultQueue
);
2735 void World::UpdateResultQueue()
2737 m_resultQueue
->Update();
2740 void World::UpdateRealmCharCount(uint32 accountId
)
2742 CharacterDatabase
.AsyncPQuery(this, &World::_UpdateRealmCharCount
, accountId
,
2743 "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId
);
2746 void World::_UpdateRealmCharCount(QueryResult
*resultCharCount
, uint32 accountId
)
2748 if (resultCharCount
)
2750 Field
*fields
= resultCharCount
->Fetch();
2751 uint32 charCount
= fields
[0].GetUInt32();
2752 delete resultCharCount
;
2753 loginDatabase
.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId
, realmID
);
2754 loginDatabase
.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount
, accountId
, realmID
);
2758 void World::InitDailyQuestResetTime()
2760 time_t mostRecentQuestTime
;
2762 QueryResult
* result
= CharacterDatabase
.Query("SELECT MAX(time) FROM character_queststatus_daily");
2765 Field
*fields
= result
->Fetch();
2767 mostRecentQuestTime
= (time_t)fields
[0].GetUInt64();
2771 mostRecentQuestTime
= 0;
2773 // client built-in time for reset is 6:00 AM
2774 // FIX ME: client not show day start time
2775 time_t curTime
= time(NULL
);
2776 tm localTm
= *localtime(&curTime
);
2777 localTm
.tm_hour
= 6;
2781 // current day reset time
2782 time_t curDayResetTime
= mktime(&localTm
);
2784 // last reset time before current moment
2785 time_t resetTime
= (curTime
< curDayResetTime
) ? curDayResetTime
- DAY
: curDayResetTime
;
2787 // need reset (if we have quest time before last reset time (not processed by some reason)
2788 if(mostRecentQuestTime
&& mostRecentQuestTime
<= resetTime
)
2789 m_NextDailyQuestReset
= mostRecentQuestTime
;
2792 // plan next reset time
2793 m_NextDailyQuestReset
= (curTime
>= curDayResetTime
) ? curDayResetTime
+ DAY
: curDayResetTime
;
2797 void World::ResetDailyQuests()
2799 sLog
.outDetail("Daily quests reset for all characters.");
2800 CharacterDatabase
.Execute("DELETE FROM character_queststatus_daily");
2801 for(SessionMap::iterator itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2802 if(itr
->second
->GetPlayer())
2803 itr
->second
->GetPlayer()->ResetDailyQuestStatus();
2806 void World::SetPlayerLimit( int32 limit
, bool needUpdate
)
2808 if(limit
< -SEC_ADMINISTRATOR
)
2809 limit
= -SEC_ADMINISTRATOR
;
2812 bool db_update_need
= needUpdate
|| (limit
< 0) != (m_playerLimit
< 0) || (limit
< 0 && m_playerLimit
< 0 && limit
!= m_playerLimit
);
2814 m_playerLimit
= limit
;
2817 loginDatabase
.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID
);
2820 void World::UpdateMaxSessionCounters()
2822 m_maxActiveSessionCount
= std::max(m_maxActiveSessionCount
,uint32(m_sessions
.size()-m_QueuedPlayer
.size()));
2823 m_maxQueuedSessionCount
= std::max(m_maxQueuedSessionCount
,uint32(m_QueuedPlayer
.size()));
2826 void World::LoadDBVersion()
2828 QueryResult
* result
= WorldDatabase
.Query("SELECT version FROM db_version LIMIT 1");
2831 Field
* fields
= result
->Fetch();
2833 m_DBVersion
= fields
[0].GetString();
2837 m_DBVersion
= "unknown world database";