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"
41 #include "CreatureEventAIMgr.h"
44 #include "DBCStores.h"
46 #include "ItemEnchantmentMgr.h"
47 #include "MapManager.h"
48 #include "ScriptCalls.h"
49 #include "CreatureAIRegistry.h"
50 #include "Policies/SingletonImp.h"
51 #include "BattleGroundMgr.h"
52 #include "TemporarySummon.h"
53 #include "WaypointMovementGenerator.h"
54 #include "VMapFactory.h"
55 #include "GlobalEvents.h"
56 #include "GameEventMgr.h"
57 #include "PoolHandler.h"
58 #include "Database/DatabaseImpl.h"
59 #include "GridNotifiersImpl.h"
61 #include "InstanceSaveMgr.h"
62 #include "WaypointManager.h"
63 #include "GMTicketMgr.h"
65 #include "AuctionHouseBot.h"
67 INSTANTIATE_SINGLETON_1( World
);
69 volatile bool World::m_stopEvent
= false;
70 uint8
World::m_ExitCode
= SHUTDOWN_EXIT_CODE
;
71 volatile uint32
World::m_worldLoopCounter
= 0;
73 float World::m_MaxVisibleDistanceForCreature
= DEFAULT_VISIBILITY_DISTANCE
;
74 float World::m_MaxVisibleDistanceForPlayer
= DEFAULT_VISIBILITY_DISTANCE
;
75 float World::m_MaxVisibleDistanceForObject
= DEFAULT_VISIBILITY_DISTANCE
;
76 float World::m_MaxVisibleDistanceInFlight
= DEFAULT_VISIBILITY_DISTANCE
;
77 float World::m_VisibleUnitGreyDistance
= 0;
78 float World::m_VisibleObjectGreyDistance
= 0;
84 uint64 ownerGUID
; // owner of source if source is item
85 ScriptInfo
const* script
; // pointer to static script data
92 m_allowMovement
= true;
95 m_gameTime
=time(NULL
);
96 m_startTime
=m_gameTime
;
97 m_maxActiveSessionCount
= 0;
98 m_maxQueuedSessionCount
= 0;
100 m_NextDailyQuestReset
= 0;
102 m_defaultDbcLocale
= LOCALE_enUS
;
103 m_availableDbcLocaleMask
= 0;
109 ///- Empty the kicked session set
110 while (!m_sessions
.empty())
112 // not remove from queue, prevent loading new sessions
113 delete m_sessions
.begin()->second
;
114 m_sessions
.erase(m_sessions
.begin());
117 ///- Empty the WeatherMap
118 for (WeatherMap::const_iterator itr
= m_weathers
.begin(); itr
!= m_weathers
.end(); ++itr
)
123 while (!cliCmdQueue
.empty())
124 delete cliCmdQueue
.next();
126 VMAP::VMapFactory::clear();
128 if(m_resultQueue
) delete m_resultQueue
;
130 //TODO free addSessQueue
133 /// Find a player in a specified zone
134 Player
* World::FindPlayerInZone(uint32 zone
)
136 ///- circle through active sessions and return the first player found in the zone
137 SessionMap::const_iterator itr
;
138 for (itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
142 Player
*player
= itr
->second
->GetPlayer();
145 if( player
->IsInWorld() && player
->GetZoneId() == zone
)
147 // Used by the weather system. We return the player to broadcast the change weather message to him and all players in the zone.
154 /// Find a session by its id
155 WorldSession
* World::FindSession(uint32 id
) const
157 SessionMap::const_iterator itr
= m_sessions
.find(id
);
159 if(itr
!= m_sessions
.end())
160 return itr
->second
; // also can return NULL for kicked session
165 /// Remove a given session
166 bool World::RemoveSession(uint32 id
)
168 ///- Find the session, kick the user, but we can't delete session at this moment to prevent iterator invalidation
169 SessionMap::const_iterator itr
= m_sessions
.find(id
);
171 if(itr
!= m_sessions
.end() && itr
->second
)
173 if (itr
->second
->PlayerLoading())
175 itr
->second
->KickPlayer();
181 void World::AddSession(WorldSession
* s
)
187 World::AddSession_ (WorldSession
* s
)
191 //NOTE - Still there is race condition in WorldSession* being used in the Sockets
193 ///- kick already loaded player with same account (if any) and remove session
194 ///- if player is in loading and want to load again, return
195 if (!RemoveSession (s
->GetAccountId ()))
198 delete s
; // session not added yet in session list, so not listed in queue
202 // decrease session counts only at not reconnection case
203 bool decrease_session
= true;
205 // if session already exist, prepare to it deleting at next world update
206 // NOTE - KickPlayer() should be called on "old" in RemoveSession()
208 SessionMap::const_iterator old
= m_sessions
.find(s
->GetAccountId ());
210 if(old
!= m_sessions
.end())
212 // prevent decrease sessions count if session queued
213 if(RemoveQueuedPlayer(old
->second
))
214 decrease_session
= false;
215 // not remove replaced session form queue if listed
220 m_sessions
[s
->GetAccountId ()] = s
;
222 uint32 Sessions
= GetActiveAndQueuedSessionCount ();
223 uint32 pLimit
= GetPlayerAmountLimit ();
224 uint32 QueueSize
= GetQueueSize (); //number of players in the queue
226 //so we don't count the user trying to
227 //login as a session and queue the socket that we are using
231 if (pLimit
> 0 && Sessions
>= pLimit
&& s
->GetSecurity () == SEC_PLAYER
)
234 UpdateMaxSessionCounters ();
235 sLog
.outDetail ("PlayerQueue: Account id %u is in Queue Position (%u).", s
->GetAccountId (), ++QueueSize
);
239 WorldPacket
packet(SMSG_AUTH_RESPONSE
, 1 + 4 + 1 + 4 + 1);
240 packet
<< uint8 (AUTH_OK
);
241 packet
<< uint32 (0); // BillingTimeRemaining
242 packet
<< uint8 (0); // BillingPlanFlags
243 packet
<< uint32 (0); // BillingTimeRested
244 packet
<< uint8 (s
->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
245 s
->SendPacket (&packet
);
248 s
->SendTutorialsData();
250 UpdateMaxSessionCounters ();
252 // Updates the population
255 float popu
= GetActiveSessionCount (); //updated number of users on the server
258 loginDatabase
.PExecute ("UPDATE realmlist SET population = '%f' WHERE id = '%d'", popu
, realmID
);
259 sLog
.outDetail ("Server Population (%f).", popu
);
263 int32
World::GetQueuePos(WorldSession
* sess
)
267 for(Queue::const_iterator iter
= m_QueuedPlayer
.begin(); iter
!= m_QueuedPlayer
.end(); ++iter
, ++position
)
274 void World::AddQueuedPlayer(WorldSession
* sess
)
276 sess
->SetInQueue(true);
277 m_QueuedPlayer
.push_back (sess
);
279 // The 1st SMSG_AUTH_RESPONSE needs to contain other info too.
280 WorldPacket
packet (SMSG_AUTH_RESPONSE
, 1 + 4 + 1 + 4 + 1);
281 packet
<< uint8 (AUTH_WAIT_QUEUE
);
282 packet
<< uint32 (0); // BillingTimeRemaining
283 packet
<< uint8 (0); // BillingPlanFlags
284 packet
<< uint32 (0); // BillingTimeRested
285 packet
<< uint8 (sess
->Expansion()); // 0 - normal, 1 - TBC, must be set in database manually for each account
286 packet
<< uint32(GetQueuePos (sess
));
287 sess
->SendPacket (&packet
);
289 //sess->SendAuthWaitQue (GetQueuePos (sess));
292 bool World::RemoveQueuedPlayer(WorldSession
* sess
)
294 // sessions count including queued to remove (if removed_session set)
295 uint32 sessions
= GetActiveSessionCount();
298 Queue::iterator iter
= m_QueuedPlayer
.begin();
300 // search to remove and count skipped positions
303 for(;iter
!= m_QueuedPlayer
.end(); ++iter
, ++position
)
307 sess
->SetInQueue(false);
308 iter
= m_QueuedPlayer
.erase(iter
);
309 found
= true; // removing queued session
314 // iter point to next socked after removed or end()
315 // position store position of removed socket and then new position next socket after removed
317 // if session not queued then we need decrease sessions count
318 if(!found
&& sessions
)
321 // accept first in queue
322 if( (!m_playerLimit
|| sessions
< m_playerLimit
) && !m_QueuedPlayer
.empty() )
324 WorldSession
* pop_sess
= m_QueuedPlayer
.front();
325 pop_sess
->SetInQueue(false);
326 pop_sess
->SendAuthWaitQue(0);
327 m_QueuedPlayer
.pop_front();
329 // update iter to point first queued socket or end() if queue is empty now
330 iter
= m_QueuedPlayer
.begin();
334 // update position from iter to end()
335 // iter point to first not updated socket, position store new position
336 for(; iter
!= m_QueuedPlayer
.end(); ++iter
, ++position
)
337 (*iter
)->SendAuthWaitQue(position
);
342 /// Find a Weather object by the given zoneid
343 Weather
* World::FindWeather(uint32 id
) const
345 WeatherMap::const_iterator itr
= m_weathers
.find(id
);
347 if(itr
!= m_weathers
.end())
353 /// Remove a Weather object for the given zoneid
354 void World::RemoveWeather(uint32 id
)
356 // not called at the moment. Kept for completeness
357 WeatherMap::iterator itr
= m_weathers
.find(id
);
359 if(itr
!= m_weathers
.end())
362 m_weathers
.erase(itr
);
366 /// Add a Weather object to the list
367 Weather
* World::AddWeather(uint32 zone_id
)
369 WeatherZoneChances
const* weatherChances
= objmgr
.GetWeatherChances(zone_id
);
371 // zone not have weather, ignore
375 Weather
* w
= new Weather(zone_id
,weatherChances
);
376 m_weathers
[w
->GetZone()] = w
;
382 /// Initialize config values
383 void World::LoadConfigSettings(bool reload
)
387 if(!sConfig
.Reload())
389 sLog
.outError("World settings reload fail: can't read settings from %s.",sConfig
.GetFilename().c_str());
394 ///- Read the version of the configuration file and warn the user in case of emptiness or mismatch
395 uint32 confVersion
= sConfig
.GetIntDefault("ConfVersion", 0);
398 sLog
.outError("*****************************************************************************");
399 sLog
.outError(" WARNING: mangosd.conf does not include a ConfVersion variable.");
400 sLog
.outError(" Your configuration file may be out of date!");
401 sLog
.outError("*****************************************************************************");
402 clock_t pause
= 3000 + clock();
403 while (pause
> clock())
408 if (confVersion
< _MANGOSDCONFVERSION
)
410 sLog
.outError("*****************************************************************************");
411 sLog
.outError(" WARNING: Your mangosd.conf version indicates your conf file is out of date!");
412 sLog
.outError(" Please check for updates, as your current default values may cause");
413 sLog
.outError(" unexpected behavior.");
414 sLog
.outError("*****************************************************************************");
415 clock_t pause
= 3000 + clock();
416 while (pause
> clock())
421 ///- Read the player limit and the Message of the day from the config file
422 SetPlayerLimit( sConfig
.GetIntDefault("PlayerLimit", DEFAULT_PLAYER_LIMIT
), true );
423 SetMotd( sConfig
.GetStringDefault("Motd", "Welcome to the Massive Network Game Object Server." ) );
425 ///- Read all rates from the config file
426 rate_values
[RATE_HEALTH
] = sConfig
.GetFloatDefault("Rate.Health", 1);
427 if(rate_values
[RATE_HEALTH
] < 0)
429 sLog
.outError("Rate.Health (%f) must be > 0. Using 1 instead.",rate_values
[RATE_HEALTH
]);
430 rate_values
[RATE_HEALTH
] = 1;
432 rate_values
[RATE_POWER_MANA
] = sConfig
.GetFloatDefault("Rate.Mana", 1);
433 if(rate_values
[RATE_POWER_MANA
] < 0)
435 sLog
.outError("Rate.Mana (%f) must be > 0. Using 1 instead.",rate_values
[RATE_POWER_MANA
]);
436 rate_values
[RATE_POWER_MANA
] = 1;
438 rate_values
[RATE_POWER_RAGE_INCOME
] = sConfig
.GetFloatDefault("Rate.Rage.Income", 1);
439 rate_values
[RATE_POWER_RAGE_LOSS
] = sConfig
.GetFloatDefault("Rate.Rage.Loss", 1);
440 if(rate_values
[RATE_POWER_RAGE_LOSS
] < 0)
442 sLog
.outError("Rate.Rage.Loss (%f) must be > 0. Using 1 instead.",rate_values
[RATE_POWER_RAGE_LOSS
]);
443 rate_values
[RATE_POWER_RAGE_LOSS
] = 1;
445 rate_values
[RATE_POWER_RUNICPOWER_INCOME
] = sConfig
.GetFloatDefault("Rate.RunicPower.Income", 1);
446 rate_values
[RATE_POWER_RUNICPOWER_LOSS
] = sConfig
.GetFloatDefault("Rate.RunicPower.Loss", 1);
447 if(rate_values
[RATE_POWER_RUNICPOWER_LOSS
] < 0)
449 sLog
.outError("Rate.RunicPower.Loss (%f) must be > 0. Using 1 instead.",rate_values
[RATE_POWER_RUNICPOWER_LOSS
]);
450 rate_values
[RATE_POWER_RUNICPOWER_LOSS
] = 1;
452 rate_values
[RATE_POWER_FOCUS
] = sConfig
.GetFloatDefault("Rate.Focus", 1.0f
);
453 rate_values
[RATE_SKILL_DISCOVERY
] = sConfig
.GetFloatDefault("Rate.Skill.Discovery", 1.0f
);
454 rate_values
[RATE_DROP_ITEM_POOR
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Poor", 1.0f
);
455 rate_values
[RATE_DROP_ITEM_NORMAL
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Normal", 1.0f
);
456 rate_values
[RATE_DROP_ITEM_UNCOMMON
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Uncommon", 1.0f
);
457 rate_values
[RATE_DROP_ITEM_RARE
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Rare", 1.0f
);
458 rate_values
[RATE_DROP_ITEM_EPIC
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Epic", 1.0f
);
459 rate_values
[RATE_DROP_ITEM_LEGENDARY
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Legendary", 1.0f
);
460 rate_values
[RATE_DROP_ITEM_ARTIFACT
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Artifact", 1.0f
);
461 rate_values
[RATE_DROP_ITEM_REFERENCED
] = sConfig
.GetFloatDefault("Rate.Drop.Item.Referenced", 1.0f
);
462 rate_values
[RATE_DROP_MONEY
] = sConfig
.GetFloatDefault("Rate.Drop.Money", 1.0f
);
463 rate_values
[RATE_XP_KILL
] = sConfig
.GetFloatDefault("Rate.XP.Kill", 1.0f
);
464 rate_values
[RATE_XP_QUEST
] = sConfig
.GetFloatDefault("Rate.XP.Quest", 1.0f
);
465 rate_values
[RATE_XP_EXPLORE
] = sConfig
.GetFloatDefault("Rate.XP.Explore", 1.0f
);
466 rate_values
[RATE_REPUTATION_GAIN
] = sConfig
.GetFloatDefault("Rate.Reputation.Gain", 1.0f
);
467 rate_values
[RATE_REPUTATION_LOWLEVEL_KILL
] = sConfig
.GetFloatDefault("Rate.Reputation.LowLevel.Kill", 1.0f
);
468 rate_values
[RATE_REPUTATION_LOWLEVEL_QUEST
] = sConfig
.GetFloatDefault("Rate.Reputation.LowLevel.Quest", 1.0f
);
469 rate_values
[RATE_CREATURE_NORMAL_DAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Normal.Damage", 1.0f
);
470 rate_values
[RATE_CREATURE_ELITE_ELITE_DAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.Elite.Damage", 1.0f
);
471 rate_values
[RATE_CREATURE_ELITE_RAREELITE_DAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.RAREELITE.Damage", 1.0f
);
472 rate_values
[RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.Damage", 1.0f
);
473 rate_values
[RATE_CREATURE_ELITE_RARE_DAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.RARE.Damage", 1.0f
);
474 rate_values
[RATE_CREATURE_NORMAL_HP
] = sConfig
.GetFloatDefault("Rate.Creature.Normal.HP", 1.0f
);
475 rate_values
[RATE_CREATURE_ELITE_ELITE_HP
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.Elite.HP", 1.0f
);
476 rate_values
[RATE_CREATURE_ELITE_RAREELITE_HP
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.RAREELITE.HP", 1.0f
);
477 rate_values
[RATE_CREATURE_ELITE_WORLDBOSS_HP
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.HP", 1.0f
);
478 rate_values
[RATE_CREATURE_ELITE_RARE_HP
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.RARE.HP", 1.0f
);
479 rate_values
[RATE_CREATURE_NORMAL_SPELLDAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Normal.SpellDamage", 1.0f
);
480 rate_values
[RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.Elite.SpellDamage", 1.0f
);
481 rate_values
[RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.RAREELITE.SpellDamage", 1.0f
);
482 rate_values
[RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.WORLDBOSS.SpellDamage", 1.0f
);
483 rate_values
[RATE_CREATURE_ELITE_RARE_SPELLDAMAGE
] = sConfig
.GetFloatDefault("Rate.Creature.Elite.RARE.SpellDamage", 1.0f
);
484 rate_values
[RATE_CREATURE_AGGRO
] = sConfig
.GetFloatDefault("Rate.Creature.Aggro", 1.0f
);
485 rate_values
[RATE_REST_INGAME
] = sConfig
.GetFloatDefault("Rate.Rest.InGame", 1.0f
);
486 rate_values
[RATE_REST_OFFLINE_IN_TAVERN_OR_CITY
] = sConfig
.GetFloatDefault("Rate.Rest.Offline.InTavernOrCity", 1.0f
);
487 rate_values
[RATE_REST_OFFLINE_IN_WILDERNESS
] = sConfig
.GetFloatDefault("Rate.Rest.Offline.InWilderness", 1.0f
);
488 rate_values
[RATE_DAMAGE_FALL
] = sConfig
.GetFloatDefault("Rate.Damage.Fall", 1.0f
);
489 rate_values
[RATE_AUCTION_TIME
] = sConfig
.GetFloatDefault("Rate.Auction.Time", 1.0f
);
490 rate_values
[RATE_AUCTION_DEPOSIT
] = sConfig
.GetFloatDefault("Rate.Auction.Deposit", 1.0f
);
491 rate_values
[RATE_AUCTION_CUT
] = sConfig
.GetFloatDefault("Rate.Auction.Cut", 1.0f
);
492 rate_values
[RATE_HONOR
] = sConfig
.GetFloatDefault("Rate.Honor",1.0f
);
493 rate_values
[RATE_MINING_AMOUNT
] = sConfig
.GetFloatDefault("Rate.Mining.Amount",1.0f
);
494 rate_values
[RATE_MINING_NEXT
] = sConfig
.GetFloatDefault("Rate.Mining.Next",1.0f
);
495 rate_values
[RATE_INSTANCE_RESET_TIME
] = sConfig
.GetFloatDefault("Rate.InstanceResetTime",1.0f
);
496 rate_values
[RATE_TALENT
] = sConfig
.GetFloatDefault("Rate.Talent",1.0f
);
497 if(rate_values
[RATE_TALENT
] < 0.0f
)
499 sLog
.outError("Rate.Talent (%f) mustbe > 0. Using 1 instead.",rate_values
[RATE_TALENT
]);
500 rate_values
[RATE_TALENT
] = 1.0f
;
502 rate_values
[RATE_CORPSE_DECAY_LOOTED
] = sConfig
.GetFloatDefault("Rate.Corpse.Decay.Looted",0.1f
);
504 rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
] = sConfig
.GetFloatDefault("TargetPosRecalculateRange",1.5f
);
505 if(rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
] < CONTACT_DISTANCE
)
507 sLog
.outError("TargetPosRecalculateRange (%f) must be >= %f. Using %f instead.",rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
],CONTACT_DISTANCE
,CONTACT_DISTANCE
);
508 rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
] = CONTACT_DISTANCE
;
510 else if(rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
] > ATTACK_DISTANCE
)
512 sLog
.outError("TargetPosRecalculateRange (%f) must be <= %f. Using %f instead.",
513 rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
],ATTACK_DISTANCE
,ATTACK_DISTANCE
);
514 rate_values
[RATE_TARGET_POS_RECALCULATION_RANGE
] = ATTACK_DISTANCE
;
517 rate_values
[RATE_DURABILITY_LOSS_DAMAGE
] = sConfig
.GetFloatDefault("DurabilityLossChance.Damage",0.5f
);
518 if(rate_values
[RATE_DURABILITY_LOSS_DAMAGE
] < 0.0f
)
520 sLog
.outError("DurabilityLossChance.Damage (%f) must be >=0. Using 0.0 instead.",rate_values
[RATE_DURABILITY_LOSS_DAMAGE
]);
521 rate_values
[RATE_DURABILITY_LOSS_DAMAGE
] = 0.0f
;
523 rate_values
[RATE_DURABILITY_LOSS_ABSORB
] = sConfig
.GetFloatDefault("DurabilityLossChance.Absorb",0.5f
);
524 if(rate_values
[RATE_DURABILITY_LOSS_ABSORB
] < 0.0f
)
526 sLog
.outError("DurabilityLossChance.Absorb (%f) must be >=0. Using 0.0 instead.",rate_values
[RATE_DURABILITY_LOSS_ABSORB
]);
527 rate_values
[RATE_DURABILITY_LOSS_ABSORB
] = 0.0f
;
529 rate_values
[RATE_DURABILITY_LOSS_PARRY
] = sConfig
.GetFloatDefault("DurabilityLossChance.Parry",0.05f
);
530 if(rate_values
[RATE_DURABILITY_LOSS_PARRY
] < 0.0f
)
532 sLog
.outError("DurabilityLossChance.Parry (%f) must be >=0. Using 0.0 instead.",rate_values
[RATE_DURABILITY_LOSS_PARRY
]);
533 rate_values
[RATE_DURABILITY_LOSS_PARRY
] = 0.0f
;
535 rate_values
[RATE_DURABILITY_LOSS_BLOCK
] = sConfig
.GetFloatDefault("DurabilityLossChance.Block",0.05f
);
536 if(rate_values
[RATE_DURABILITY_LOSS_BLOCK
] < 0.0f
)
538 sLog
.outError("DurabilityLossChance.Block (%f) must be >=0. Using 0.0 instead.",rate_values
[RATE_DURABILITY_LOSS_BLOCK
]);
539 rate_values
[RATE_DURABILITY_LOSS_BLOCK
] = 0.0f
;
542 ///- Read other configuration items from the config file
544 m_configs
[CONFIG_COMPRESSION
] = sConfig
.GetIntDefault("Compression", 1);
545 if(m_configs
[CONFIG_COMPRESSION
] < 1 || m_configs
[CONFIG_COMPRESSION
] > 9)
547 sLog
.outError("Compression level (%i) must be in range 1..9. Using default compression level (1).",m_configs
[CONFIG_COMPRESSION
]);
548 m_configs
[CONFIG_COMPRESSION
] = 1;
550 m_configs
[CONFIG_ADDON_CHANNEL
] = sConfig
.GetBoolDefault("AddonChannel", true);
551 m_configs
[CONFIG_GRID_UNLOAD
] = sConfig
.GetBoolDefault("GridUnload", true);
552 m_configs
[CONFIG_INTERVAL_SAVE
] = sConfig
.GetIntDefault("PlayerSaveInterval", 15 * MINUTE
* IN_MILISECONDS
);
554 m_configs
[CONFIG_INTERVAL_GRIDCLEAN
] = sConfig
.GetIntDefault("GridCleanUpDelay", 5 * MINUTE
* IN_MILISECONDS
);
555 if(m_configs
[CONFIG_INTERVAL_GRIDCLEAN
] < MIN_GRID_DELAY
)
557 sLog
.outError("GridCleanUpDelay (%i) must be greater %u. Use this minimal value.",m_configs
[CONFIG_INTERVAL_GRIDCLEAN
],MIN_GRID_DELAY
);
558 m_configs
[CONFIG_INTERVAL_GRIDCLEAN
] = MIN_GRID_DELAY
;
561 MapManager::Instance().SetGridCleanUpDelay(m_configs
[CONFIG_INTERVAL_GRIDCLEAN
]);
563 m_configs
[CONFIG_INTERVAL_MAPUPDATE
] = sConfig
.GetIntDefault("MapUpdateInterval", 100);
564 if(m_configs
[CONFIG_INTERVAL_MAPUPDATE
] < MIN_MAP_UPDATE_DELAY
)
566 sLog
.outError("MapUpdateInterval (%i) must be greater %u. Use this minimal value.",m_configs
[CONFIG_INTERVAL_MAPUPDATE
],MIN_MAP_UPDATE_DELAY
);
567 m_configs
[CONFIG_INTERVAL_MAPUPDATE
] = MIN_MAP_UPDATE_DELAY
;
570 MapManager::Instance().SetMapUpdateInterval(m_configs
[CONFIG_INTERVAL_MAPUPDATE
]);
572 m_configs
[CONFIG_INTERVAL_CHANGEWEATHER
] = sConfig
.GetIntDefault("ChangeWeatherInterval", 10 * MINUTE
* IN_MILISECONDS
);
576 uint32 val
= sConfig
.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT
);
577 if(val
!=m_configs
[CONFIG_PORT_WORLD
])
578 sLog
.outError("WorldServerPort option can't be changed at mangosd.conf reload, using current value (%u).",m_configs
[CONFIG_PORT_WORLD
]);
581 m_configs
[CONFIG_PORT_WORLD
] = sConfig
.GetIntDefault("WorldServerPort", DEFAULT_WORLDSERVER_PORT
);
585 uint32 val
= sConfig
.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME
);
586 if(val
!=m_configs
[CONFIG_SOCKET_SELECTTIME
])
587 sLog
.outError("SocketSelectTime option can't be changed at mangosd.conf reload, using current value (%u).",m_configs
[CONFIG_SOCKET_SELECTTIME
]);
590 m_configs
[CONFIG_SOCKET_SELECTTIME
] = sConfig
.GetIntDefault("SocketSelectTime", DEFAULT_SOCKET_SELECT_TIME
);
592 m_configs
[CONFIG_GROUP_XP_DISTANCE
] = sConfig
.GetIntDefault("MaxGroupXPDistance", 74);
593 /// \todo Add MonsterSight and GuarderSight (with meaning) in mangosd.conf or put them as define
594 m_configs
[CONFIG_SIGHT_MONSTER
] = sConfig
.GetIntDefault("MonsterSight", 50);
595 m_configs
[CONFIG_SIGHT_GUARDER
] = sConfig
.GetIntDefault("GuarderSight", 50);
599 uint32 val
= sConfig
.GetIntDefault("GameType", 0);
600 if(val
!=m_configs
[CONFIG_GAME_TYPE
])
601 sLog
.outError("GameType option can't be changed at mangosd.conf reload, using current value (%u).",m_configs
[CONFIG_GAME_TYPE
]);
604 m_configs
[CONFIG_GAME_TYPE
] = sConfig
.GetIntDefault("GameType", 0);
608 uint32 val
= sConfig
.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT
);
609 if(val
!=m_configs
[CONFIG_REALM_ZONE
])
610 sLog
.outError("RealmZone option can't be changed at mangosd.conf reload, using current value (%u).",m_configs
[CONFIG_REALM_ZONE
]);
613 m_configs
[CONFIG_REALM_ZONE
] = sConfig
.GetIntDefault("RealmZone", REALM_ZONE_DEVELOPMENT
);
615 m_configs
[CONFIG_ALLOW_TWO_SIDE_ACCOUNTS
] = sConfig
.GetBoolDefault("AllowTwoSide.Accounts", false);
616 m_configs
[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT
] = sConfig
.GetBoolDefault("AllowTwoSide.Interaction.Chat",false);
617 m_configs
[CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHANNEL
] = sConfig
.GetBoolDefault("AllowTwoSide.Interaction.Channel",false);
618 m_configs
[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GROUP
] = sConfig
.GetBoolDefault("AllowTwoSide.Interaction.Group",false);
619 m_configs
[CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD
] = sConfig
.GetBoolDefault("AllowTwoSide.Interaction.Guild",false);
620 m_configs
[CONFIG_ALLOW_TWO_SIDE_INTERACTION_AUCTION
] = sConfig
.GetBoolDefault("AllowTwoSide.Interaction.Auction",false);
621 m_configs
[CONFIG_ALLOW_TWO_SIDE_INTERACTION_MAIL
] = sConfig
.GetBoolDefault("AllowTwoSide.Interaction.Mail",false);
622 m_configs
[CONFIG_ALLOW_TWO_SIDE_WHO_LIST
] = sConfig
.GetBoolDefault("AllowTwoSide.WhoList", false);
623 m_configs
[CONFIG_ALLOW_TWO_SIDE_ADD_FRIEND
] = sConfig
.GetBoolDefault("AllowTwoSide.AddFriend", false);
624 m_configs
[CONFIG_STRICT_PLAYER_NAMES
] = sConfig
.GetIntDefault ("StrictPlayerNames", 0);
625 m_configs
[CONFIG_STRICT_CHARTER_NAMES
] = sConfig
.GetIntDefault ("StrictCharterNames", 0);
626 m_configs
[CONFIG_STRICT_PET_NAMES
] = sConfig
.GetIntDefault ("StrictPetNames", 0);
628 m_configs
[CONFIG_CHARACTERS_CREATING_DISABLED
] = sConfig
.GetIntDefault ("CharactersCreatingDisabled", 0);
630 m_configs
[CONFIG_CHARACTERS_PER_REALM
] = sConfig
.GetIntDefault("CharactersPerRealm", 10);
631 if(m_configs
[CONFIG_CHARACTERS_PER_REALM
] < 1 || m_configs
[CONFIG_CHARACTERS_PER_REALM
] > 10)
633 sLog
.outError("CharactersPerRealm (%i) must be in range 1..10. Set to 10.",m_configs
[CONFIG_CHARACTERS_PER_REALM
]);
634 m_configs
[CONFIG_CHARACTERS_PER_REALM
] = 10;
637 // must be after CONFIG_CHARACTERS_PER_REALM
638 m_configs
[CONFIG_CHARACTERS_PER_ACCOUNT
] = sConfig
.GetIntDefault("CharactersPerAccount", 50);
639 if(m_configs
[CONFIG_CHARACTERS_PER_ACCOUNT
] < m_configs
[CONFIG_CHARACTERS_PER_REALM
])
641 sLog
.outError("CharactersPerAccount (%i) can't be less than CharactersPerRealm (%i).",m_configs
[CONFIG_CHARACTERS_PER_ACCOUNT
],m_configs
[CONFIG_CHARACTERS_PER_REALM
]);
642 m_configs
[CONFIG_CHARACTERS_PER_ACCOUNT
] = m_configs
[CONFIG_CHARACTERS_PER_REALM
];
645 m_configs
[CONFIG_HEROIC_CHARACTERS_PER_REALM
] = sConfig
.GetIntDefault("HeroicCharactersPerRealm", 1);
646 if(int32(m_configs
[CONFIG_HEROIC_CHARACTERS_PER_REALM
]) < 0 || m_configs
[CONFIG_HEROIC_CHARACTERS_PER_REALM
] > 10)
648 sLog
.outError("HeroicCharactersPerRealm (%i) must be in range 0..10. Set to 1.",m_configs
[CONFIG_HEROIC_CHARACTERS_PER_REALM
]);
649 m_configs
[CONFIG_HEROIC_CHARACTERS_PER_REALM
] = 1;
652 m_configs
[CONFIG_MIN_LEVEL_FOR_HEROIC_CHARACTER_CREATING
] = sConfig
.GetIntDefault("MinLevelForHeroicCharacterCreating", 55);
654 m_configs
[CONFIG_SKIP_CINEMATICS
] = sConfig
.GetIntDefault("SkipCinematics", 0);
655 if(int32(m_configs
[CONFIG_SKIP_CINEMATICS
]) < 0 || m_configs
[CONFIG_SKIP_CINEMATICS
] > 2)
657 sLog
.outError("SkipCinematics (%i) must be in range 0..2. Set to 0.",m_configs
[CONFIG_SKIP_CINEMATICS
]);
658 m_configs
[CONFIG_SKIP_CINEMATICS
] = 0;
663 uint32 val
= sConfig
.GetIntDefault("MaxPlayerLevel", 80);
664 if(val
!=m_configs
[CONFIG_MAX_PLAYER_LEVEL
])
665 sLog
.outError("MaxPlayerLevel option can't be changed at mangosd.conf reload, using current value (%u).",m_configs
[CONFIG_MAX_PLAYER_LEVEL
]);
668 m_configs
[CONFIG_MAX_PLAYER_LEVEL
] = sConfig
.GetIntDefault("MaxPlayerLevel", 80);
670 if(m_configs
[CONFIG_MAX_PLAYER_LEVEL
] > MAX_LEVEL
)
672 sLog
.outError("MaxPlayerLevel (%i) must be in range 1..%u. Set to %u.",m_configs
[CONFIG_MAX_PLAYER_LEVEL
],MAX_LEVEL
,MAX_LEVEL
);
673 m_configs
[CONFIG_MAX_PLAYER_LEVEL
] = MAX_LEVEL
;
676 m_configs
[CONFIG_START_PLAYER_LEVEL
] = sConfig
.GetIntDefault("StartPlayerLevel", 1);
677 if(m_configs
[CONFIG_START_PLAYER_LEVEL
] < 1)
679 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
]);
680 m_configs
[CONFIG_START_PLAYER_LEVEL
] = 1;
682 else if(m_configs
[CONFIG_START_PLAYER_LEVEL
] > m_configs
[CONFIG_MAX_PLAYER_LEVEL
])
684 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
]);
685 m_configs
[CONFIG_START_PLAYER_LEVEL
] = m_configs
[CONFIG_MAX_PLAYER_LEVEL
];
688 m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
] = sConfig
.GetIntDefault("StartHeroicPlayerLevel", 55);
689 if(m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
] < 1)
691 sLog
.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to 55.",
692 m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
],m_configs
[CONFIG_MAX_PLAYER_LEVEL
]);
693 m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
] = 55;
695 else if(m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
] > m_configs
[CONFIG_MAX_PLAYER_LEVEL
])
697 sLog
.outError("StartHeroicPlayerLevel (%i) must be in range 1..MaxPlayerLevel(%u). Set to %u.",
698 m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
],m_configs
[CONFIG_MAX_PLAYER_LEVEL
],m_configs
[CONFIG_MAX_PLAYER_LEVEL
]);
699 m_configs
[CONFIG_START_HEROIC_PLAYER_LEVEL
] = m_configs
[CONFIG_MAX_PLAYER_LEVEL
];
702 m_configs
[CONFIG_START_PLAYER_MONEY
] = sConfig
.GetIntDefault("StartPlayerMoney", 0);
703 if(int32(m_configs
[CONFIG_START_PLAYER_MONEY
]) < 0)
705 sLog
.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",m_configs
[CONFIG_START_PLAYER_MONEY
],MAX_MONEY_AMOUNT
,0);
706 m_configs
[CONFIG_START_PLAYER_MONEY
] = 0;
708 else if(m_configs
[CONFIG_START_PLAYER_MONEY
] > MAX_MONEY_AMOUNT
)
710 sLog
.outError("StartPlayerMoney (%i) must be in range 0..%u. Set to %u.",
711 m_configs
[CONFIG_START_PLAYER_MONEY
],MAX_MONEY_AMOUNT
,MAX_MONEY_AMOUNT
);
712 m_configs
[CONFIG_START_PLAYER_MONEY
] = MAX_MONEY_AMOUNT
;
715 m_configs
[CONFIG_MAX_HONOR_POINTS
] = sConfig
.GetIntDefault("MaxHonorPoints", 75000);
716 if(int32(m_configs
[CONFIG_MAX_HONOR_POINTS
]) < 0)
718 sLog
.outError("MaxHonorPoints (%i) can't be negative. Set to 0.",m_configs
[CONFIG_MAX_HONOR_POINTS
]);
719 m_configs
[CONFIG_MAX_HONOR_POINTS
] = 0;
722 m_configs
[CONFIG_START_HONOR_POINTS
] = sConfig
.GetIntDefault("StartHonorPoints", 0);
723 if(int32(m_configs
[CONFIG_START_HONOR_POINTS
]) < 0)
725 sLog
.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
726 m_configs
[CONFIG_START_HONOR_POINTS
],m_configs
[CONFIG_MAX_HONOR_POINTS
],0);
727 m_configs
[CONFIG_START_HONOR_POINTS
] = 0;
729 else if(m_configs
[CONFIG_START_HONOR_POINTS
] > m_configs
[CONFIG_MAX_HONOR_POINTS
])
731 sLog
.outError("StartHonorPoints (%i) must be in range 0..MaxHonorPoints(%u). Set to %u.",
732 m_configs
[CONFIG_START_HONOR_POINTS
],m_configs
[CONFIG_MAX_HONOR_POINTS
],m_configs
[CONFIG_MAX_HONOR_POINTS
]);
733 m_configs
[CONFIG_START_HONOR_POINTS
] = m_configs
[CONFIG_MAX_HONOR_POINTS
];
736 m_configs
[CONFIG_MAX_ARENA_POINTS
] = sConfig
.GetIntDefault("MaxArenaPoints", 5000);
737 if(int32(m_configs
[CONFIG_MAX_ARENA_POINTS
]) < 0)
739 sLog
.outError("MaxArenaPoints (%i) can't be negative. Set to 0.",m_configs
[CONFIG_MAX_ARENA_POINTS
]);
740 m_configs
[CONFIG_MAX_ARENA_POINTS
] = 0;
743 m_configs
[CONFIG_START_ARENA_POINTS
] = sConfig
.GetIntDefault("StartArenaPoints", 0);
744 if(int32(m_configs
[CONFIG_START_ARENA_POINTS
]) < 0)
746 sLog
.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
747 m_configs
[CONFIG_START_ARENA_POINTS
],m_configs
[CONFIG_MAX_ARENA_POINTS
],0);
748 m_configs
[CONFIG_MAX_ARENA_POINTS
] = 0;
750 else if(m_configs
[CONFIG_START_ARENA_POINTS
] > m_configs
[CONFIG_MAX_ARENA_POINTS
])
752 sLog
.outError("StartArenaPoints (%i) must be in range 0..MaxArenaPoints(%u). Set to %u.",
753 m_configs
[CONFIG_START_ARENA_POINTS
],m_configs
[CONFIG_MAX_ARENA_POINTS
],m_configs
[CONFIG_MAX_ARENA_POINTS
]);
754 m_configs
[CONFIG_START_ARENA_POINTS
] = m_configs
[CONFIG_MAX_ARENA_POINTS
];
757 m_configs
[CONFIG_ALL_TAXI_PATHS
] = sConfig
.GetBoolDefault("AllFlightPaths", false);
759 m_configs
[CONFIG_INSTANCE_IGNORE_LEVEL
] = sConfig
.GetBoolDefault("Instance.IgnoreLevel", false);
760 m_configs
[CONFIG_INSTANCE_IGNORE_RAID
] = sConfig
.GetBoolDefault("Instance.IgnoreRaid", false);
762 m_configs
[CONFIG_CAST_UNSTUCK
] = sConfig
.GetBoolDefault("CastUnstuck", true);
763 m_configs
[CONFIG_INSTANCE_RESET_TIME_HOUR
] = sConfig
.GetIntDefault("Instance.ResetTimeHour", 4);
764 m_configs
[CONFIG_INSTANCE_UNLOAD_DELAY
] = sConfig
.GetIntDefault("Instance.UnloadDelay", 30 * MINUTE
* IN_MILISECONDS
);
766 m_configs
[CONFIG_MAX_PRIMARY_TRADE_SKILL
] = sConfig
.GetIntDefault("MaxPrimaryTradeSkill", 2);
767 m_configs
[CONFIG_MIN_PETITION_SIGNS
] = sConfig
.GetIntDefault("MinPetitionSigns", 9);
768 if(m_configs
[CONFIG_MIN_PETITION_SIGNS
] > 9)
770 sLog
.outError("MinPetitionSigns (%i) must be in range 0..9. Set to 9.", m_configs
[CONFIG_MIN_PETITION_SIGNS
]);
771 m_configs
[CONFIG_MIN_PETITION_SIGNS
] = 9;
774 m_configs
[CONFIG_GM_LOGIN_STATE
] = sConfig
.GetIntDefault("GM.LoginState", 2);
775 m_configs
[CONFIG_GM_VISIBLE_STATE
] = sConfig
.GetIntDefault("GM.Visible", 2);
776 m_configs
[CONFIG_GM_ACCEPT_TICKETS
] = sConfig
.GetIntDefault("GM.AcceptTickets", 2);
777 m_configs
[CONFIG_GM_CHAT
] = sConfig
.GetIntDefault("GM.Chat", 2);
778 m_configs
[CONFIG_GM_WISPERING_TO
] = sConfig
.GetIntDefault("GM.WhisperingTo", 2);
780 m_configs
[CONFIG_GM_IN_GM_LIST
] = sConfig
.GetBoolDefault("GM.InGMList", false);
781 m_configs
[CONFIG_GM_IN_WHO_LIST
] = sConfig
.GetBoolDefault("GM.InWhoList", false);
782 m_configs
[CONFIG_GM_LOG_TRADE
] = sConfig
.GetBoolDefault("GM.LogTrade", false);
784 m_configs
[CONFIG_START_GM_LEVEL
] = sConfig
.GetIntDefault("GM.StartLevel", 1);
785 if(m_configs
[CONFIG_START_GM_LEVEL
] < m_configs
[CONFIG_START_PLAYER_LEVEL
])
787 sLog
.outError("GM.StartLevel (%i) must be in range StartPlayerLevel(%u)..%u. Set to %u.",
788 m_configs
[CONFIG_START_GM_LEVEL
],m_configs
[CONFIG_START_PLAYER_LEVEL
], MAX_LEVEL
, m_configs
[CONFIG_START_PLAYER_LEVEL
]);
789 m_configs
[CONFIG_START_GM_LEVEL
] = m_configs
[CONFIG_START_PLAYER_LEVEL
];
791 else if(m_configs
[CONFIG_START_GM_LEVEL
] > MAX_LEVEL
)
793 sLog
.outError("GM.StartLevel (%i) must be in range 1..%u. Set to %u.", m_configs
[CONFIG_START_GM_LEVEL
], MAX_LEVEL
, MAX_LEVEL
);
794 m_configs
[CONFIG_START_GM_LEVEL
] = MAX_LEVEL
;
796 m_configs
[CONFIG_GM_LOWER_SECURITY
] = sConfig
.GetBoolDefault("GM.LowerSecurity", false);
797 m_configs
[CONFIG_GM_ALLOW_ACHIEVEMENT_GAINS
] = sConfig
.GetBoolDefault("GM.AllowAchievementGain", true);
799 m_configs
[CONFIG_GROUP_VISIBILITY
] = sConfig
.GetIntDefault("Visibility.GroupMode",0);
801 m_configs
[CONFIG_MAIL_DELIVERY_DELAY
] = sConfig
.GetIntDefault("MailDeliveryDelay",HOUR
);
803 m_configs
[CONFIG_UPTIME_UPDATE
] = sConfig
.GetIntDefault("UpdateUptimeInterval", 10);
804 if(int32(m_configs
[CONFIG_UPTIME_UPDATE
])<=0)
806 sLog
.outError("UpdateUptimeInterval (%i) must be > 0, set to default 10.",m_configs
[CONFIG_UPTIME_UPDATE
]);
807 m_configs
[CONFIG_UPTIME_UPDATE
] = 10;
811 m_timers
[WUPDATE_UPTIME
].SetInterval(m_configs
[CONFIG_UPTIME_UPDATE
]*MINUTE
*IN_MILISECONDS
);
812 m_timers
[WUPDATE_UPTIME
].Reset();
815 m_configs
[CONFIG_SKILL_CHANCE_ORANGE
] = sConfig
.GetIntDefault("SkillChance.Orange",100);
816 m_configs
[CONFIG_SKILL_CHANCE_YELLOW
] = sConfig
.GetIntDefault("SkillChance.Yellow",75);
817 m_configs
[CONFIG_SKILL_CHANCE_GREEN
] = sConfig
.GetIntDefault("SkillChance.Green",25);
818 m_configs
[CONFIG_SKILL_CHANCE_GREY
] = sConfig
.GetIntDefault("SkillChance.Grey",0);
820 m_configs
[CONFIG_SKILL_CHANCE_MINING_STEPS
] = sConfig
.GetIntDefault("SkillChance.MiningSteps",75);
821 m_configs
[CONFIG_SKILL_CHANCE_SKINNING_STEPS
] = sConfig
.GetIntDefault("SkillChance.SkinningSteps",75);
823 m_configs
[CONFIG_SKILL_PROSPECTING
] = sConfig
.GetBoolDefault("SkillChance.Prospecting",false);
824 m_configs
[CONFIG_SKILL_MILLING
] = sConfig
.GetBoolDefault("SkillChance.Milling",false);
826 m_configs
[CONFIG_SKILL_GAIN_CRAFTING
] = sConfig
.GetIntDefault("SkillGain.Crafting", 1);
827 if(m_configs
[CONFIG_SKILL_GAIN_CRAFTING
] < 0)
829 sLog
.outError("SkillGain.Crafting (%i) can't be negative. Set to 1.",m_configs
[CONFIG_SKILL_GAIN_CRAFTING
]);
830 m_configs
[CONFIG_SKILL_GAIN_CRAFTING
] = 1;
833 m_configs
[CONFIG_SKILL_GAIN_DEFENSE
] = sConfig
.GetIntDefault("SkillGain.Defense", 1);
834 if(m_configs
[CONFIG_SKILL_GAIN_DEFENSE
] < 0)
836 sLog
.outError("SkillGain.Defense (%i) can't be negative. Set to 1.",m_configs
[CONFIG_SKILL_GAIN_DEFENSE
]);
837 m_configs
[CONFIG_SKILL_GAIN_DEFENSE
] = 1;
840 m_configs
[CONFIG_SKILL_GAIN_GATHERING
] = sConfig
.GetIntDefault("SkillGain.Gathering", 1);
841 if(m_configs
[CONFIG_SKILL_GAIN_GATHERING
] < 0)
843 sLog
.outError("SkillGain.Gathering (%i) can't be negative. Set to 1.",m_configs
[CONFIG_SKILL_GAIN_GATHERING
]);
844 m_configs
[CONFIG_SKILL_GAIN_GATHERING
] = 1;
847 m_configs
[CONFIG_SKILL_GAIN_WEAPON
] = sConfig
.GetIntDefault("SkillGain.Weapon", 1);
848 if(m_configs
[CONFIG_SKILL_GAIN_WEAPON
] < 0)
850 sLog
.outError("SkillGain.Weapon (%i) can't be negative. Set to 1.",m_configs
[CONFIG_SKILL_GAIN_WEAPON
]);
851 m_configs
[CONFIG_SKILL_GAIN_WEAPON
] = 1;
854 m_configs
[CONFIG_MAX_OVERSPEED_PINGS
] = sConfig
.GetIntDefault("MaxOverspeedPings",2);
855 if(m_configs
[CONFIG_MAX_OVERSPEED_PINGS
] != 0 && m_configs
[CONFIG_MAX_OVERSPEED_PINGS
] < 2)
857 sLog
.outError("MaxOverspeedPings (%i) must be in range 2..infinity (or 0 to disable check. Set to 2.",m_configs
[CONFIG_MAX_OVERSPEED_PINGS
]);
858 m_configs
[CONFIG_MAX_OVERSPEED_PINGS
] = 2;
861 m_configs
[CONFIG_SAVE_RESPAWN_TIME_IMMEDIATLY
] = sConfig
.GetBoolDefault("SaveRespawnTimeImmediately",true);
862 m_configs
[CONFIG_WEATHER
] = sConfig
.GetBoolDefault("ActivateWeather",true);
864 m_configs
[CONFIG_DISABLE_BREATHING
] = sConfig
.GetIntDefault("DisableWaterBreath", SEC_CONSOLE
);
866 m_configs
[CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL
] = sConfig
.GetBoolDefault("AlwaysMaxSkillForLevel", false);
870 uint32 val
= sConfig
.GetIntDefault("Expansion",1);
871 if(val
!=m_configs
[CONFIG_EXPANSION
])
872 sLog
.outError("Expansion option can't be changed at mangosd.conf reload, using current value (%u).",m_configs
[CONFIG_EXPANSION
]);
875 m_configs
[CONFIG_EXPANSION
] = sConfig
.GetIntDefault("Expansion",1);
877 m_configs
[CONFIG_CHATFLOOD_MESSAGE_COUNT
] = sConfig
.GetIntDefault("ChatFlood.MessageCount",10);
878 m_configs
[CONFIG_CHATFLOOD_MESSAGE_DELAY
] = sConfig
.GetIntDefault("ChatFlood.MessageDelay",1);
879 m_configs
[CONFIG_CHATFLOOD_MUTE_TIME
] = sConfig
.GetIntDefault("ChatFlood.MuteTime",10);
881 m_configs
[CONFIG_EVENT_ANNOUNCE
] = sConfig
.GetIntDefault("Event.Announce",0);
883 m_configs
[CONFIG_CREATURE_FAMILY_ASSISTANCE_RADIUS
] = sConfig
.GetIntDefault("CreatureFamilyAssistanceRadius",10);
884 m_configs
[CONFIG_CREATURE_FAMILY_ASSISTANCE_DELAY
] = sConfig
.GetIntDefault("CreatureFamilyAssistanceDelay",1500);
886 m_configs
[CONFIG_WORLD_BOSS_LEVEL_DIFF
] = sConfig
.GetIntDefault("WorldBossLevelDiff",3);
888 // note: disable value (-1) will assigned as 0xFFFFFFF, to prevent overflow at calculations limit it to max possible player level MAX_LEVEL(100)
889 m_configs
[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF
] = sConfig
.GetIntDefault("Quests.LowLevelHideDiff", 4);
890 if(m_configs
[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF
] > MAX_LEVEL
)
891 m_configs
[CONFIG_QUEST_LOW_LEVEL_HIDE_DIFF
] = MAX_LEVEL
;
892 m_configs
[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
] = sConfig
.GetIntDefault("Quests.HighLevelHideDiff", 7);
893 if(m_configs
[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
] > MAX_LEVEL
)
894 m_configs
[CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
] = MAX_LEVEL
;
896 m_configs
[CONFIG_DETECT_POS_COLLISION
] = sConfig
.GetBoolDefault("DetectPosCollision", true);
898 m_configs
[CONFIG_RESTRICTED_LFG_CHANNEL
] = sConfig
.GetBoolDefault("Channel.RestrictedLfg", true);
899 m_configs
[CONFIG_SILENTLY_GM_JOIN_TO_CHANNEL
] = sConfig
.GetBoolDefault("Channel.SilentlyGMJoin", false);
901 m_configs
[CONFIG_TALENTS_INSPECTING
] = sConfig
.GetBoolDefault("TalentsInspecting", true);
902 m_configs
[CONFIG_CHAT_FAKE_MESSAGE_PREVENTING
] = sConfig
.GetBoolDefault("ChatFakeMessagePreventing", false);
904 m_configs
[CONFIG_CORPSE_DECAY_NORMAL
] = sConfig
.GetIntDefault("Corpse.Decay.NORMAL", 60);
905 m_configs
[CONFIG_CORPSE_DECAY_RARE
] = sConfig
.GetIntDefault("Corpse.Decay.RARE", 300);
906 m_configs
[CONFIG_CORPSE_DECAY_ELITE
] = sConfig
.GetIntDefault("Corpse.Decay.ELITE", 300);
907 m_configs
[CONFIG_CORPSE_DECAY_RAREELITE
] = sConfig
.GetIntDefault("Corpse.Decay.RAREELITE", 300);
908 m_configs
[CONFIG_CORPSE_DECAY_WORLDBOSS
] = sConfig
.GetIntDefault("Corpse.Decay.WORLDBOSS", 3600);
910 m_configs
[CONFIG_DEATH_SICKNESS_LEVEL
] = sConfig
.GetIntDefault ("Death.SicknessLevel", 11);
911 m_configs
[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
] = sConfig
.GetBoolDefault("Death.CorpseReclaimDelay.PvP", true);
912 m_configs
[CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
] = sConfig
.GetBoolDefault("Death.CorpseReclaimDelay.PvE", true);
913 m_configs
[CONFIG_DEATH_BONES_WORLD
] = sConfig
.GetBoolDefault("Death.Bones.World", true);
914 m_configs
[CONFIG_DEATH_BONES_BG_OR_ARENA
] = sConfig
.GetBoolDefault("Death.Bones.BattlegroundOrArena", true);
916 m_configs
[CONFIG_THREAT_RADIUS
] = sConfig
.GetIntDefault("ThreatRadius", 100);
918 // always use declined names in the russian client
919 m_configs
[CONFIG_DECLINED_NAMES_USED
] =
920 (m_configs
[CONFIG_REALM_ZONE
] == REALM_ZONE_RUSSIAN
) ? true : sConfig
.GetBoolDefault("DeclinedNames", false);
922 m_configs
[CONFIG_LISTEN_RANGE_SAY
] = sConfig
.GetIntDefault("ListenRange.Say", 25);
923 m_configs
[CONFIG_LISTEN_RANGE_TEXTEMOTE
] = sConfig
.GetIntDefault("ListenRange.TextEmote", 25);
924 m_configs
[CONFIG_LISTEN_RANGE_YELL
] = sConfig
.GetIntDefault("ListenRange.Yell", 300);
926 m_configs
[CONFIG_BATTLEGROUND_CAST_DESERTER
] = sConfig
.GetBoolDefault("Battleground.CastDeserter", true);
927 m_configs
[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_ENABLE
] = sConfig
.GetBoolDefault("Battleground.QueueAnnouncer.Enable", false);
928 m_configs
[CONFIG_BATTLEGROUND_QUEUE_ANNOUNCER_PLAYERONLY
] = sConfig
.GetBoolDefault("Battleground.QueueAnnouncer.PlayerOnly", false);
929 m_configs
[CONFIG_BATTLEGROUND_INVITATION_TYPE
] = sConfig
.GetIntDefault ("Battleground.InvitationType", 0);
930 m_configs
[CONFIG_BATTLEGROUND_PREMATURE_FINISH_TIMER
] = sConfig
.GetIntDefault ("BattleGround.PrematureFinishTimer", 5 * MINUTE
* IN_MILISECONDS
);
931 m_configs
[CONFIG_BATTLEGROUND_PREMADE_GROUP_WAIT_FOR_MATCH
] = sConfig
.GetIntDefault ("BattleGround.PremadeGroupWaitForMatch", 30 * MINUTE
* IN_MILISECONDS
);
932 m_configs
[CONFIG_ARENA_MAX_RATING_DIFFERENCE
] = sConfig
.GetIntDefault ("Arena.MaxRatingDifference", 150);
933 m_configs
[CONFIG_ARENA_RATING_DISCARD_TIMER
] = sConfig
.GetIntDefault ("Arena.RatingDiscardTimer", 10 * MINUTE
* IN_MILISECONDS
);
934 m_configs
[CONFIG_ARENA_AUTO_DISTRIBUTE_POINTS
] = sConfig
.GetBoolDefault("Arena.AutoDistributePoints", false);
935 m_configs
[CONFIG_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS
] = sConfig
.GetIntDefault ("Arena.AutoDistributeInterval", 7);
936 m_configs
[CONFIG_ARENA_QUEUE_ANNOUNCER_ENABLE
] = sConfig
.GetBoolDefault("Arena.QueueAnnouncer.Enable", false);
937 m_configs
[CONFIG_ARENA_SEASON_ID
] = sConfig
.GetIntDefault ("Arena.ArenaSeason.ID", 1);
938 m_configs
[CONFIG_ARENA_SEASON_IN_PROGRESS
] = sConfig
.GetBoolDefault("Arena.ArenaSeason.InProgress", true);
940 m_configs
[CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET
] = sConfig
.GetBoolDefault("OffhandCheckAtTalentsReset", false);
942 m_configs
[CONFIG_INSTANT_LOGOUT
] = sConfig
.GetIntDefault("InstantLogout", SEC_MODERATOR
);
944 m_VisibleUnitGreyDistance
= sConfig
.GetFloatDefault("Visibility.Distance.Grey.Unit", 1);
945 if(m_VisibleUnitGreyDistance
> MAX_VISIBILITY_DISTANCE
)
947 sLog
.outError("Visibility.Distance.Grey.Unit can't be greater %f",MAX_VISIBILITY_DISTANCE
);
948 m_VisibleUnitGreyDistance
= MAX_VISIBILITY_DISTANCE
;
950 m_VisibleObjectGreyDistance
= sConfig
.GetFloatDefault("Visibility.Distance.Grey.Object", 10);
951 if(m_VisibleObjectGreyDistance
> MAX_VISIBILITY_DISTANCE
)
953 sLog
.outError("Visibility.Distance.Grey.Object can't be greater %f",MAX_VISIBILITY_DISTANCE
);
954 m_VisibleObjectGreyDistance
= MAX_VISIBILITY_DISTANCE
;
957 m_MaxVisibleDistanceForCreature
= sConfig
.GetFloatDefault("Visibility.Distance.Creature", DEFAULT_VISIBILITY_DISTANCE
);
958 if(m_MaxVisibleDistanceForCreature
< 45*sWorld
.getRate(RATE_CREATURE_AGGRO
))
960 sLog
.outError("Visibility.Distance.Creature can't be less max aggro radius %f",45*sWorld
.getRate(RATE_CREATURE_AGGRO
));
961 m_MaxVisibleDistanceForCreature
= 45*sWorld
.getRate(RATE_CREATURE_AGGRO
);
963 else if(m_MaxVisibleDistanceForCreature
+ m_VisibleUnitGreyDistance
> MAX_VISIBILITY_DISTANCE
)
965 sLog
.outError("Visibility. Distance .Creature can't be greater %f",MAX_VISIBILITY_DISTANCE
- m_VisibleUnitGreyDistance
);
966 m_MaxVisibleDistanceForCreature
= MAX_VISIBILITY_DISTANCE
-m_VisibleUnitGreyDistance
;
968 m_MaxVisibleDistanceForPlayer
= sConfig
.GetFloatDefault("Visibility.Distance.Player", DEFAULT_VISIBILITY_DISTANCE
);
969 if(m_MaxVisibleDistanceForPlayer
< 45*sWorld
.getRate(RATE_CREATURE_AGGRO
))
971 sLog
.outError("Visibility.Distance.Player can't be less max aggro radius %f",45*sWorld
.getRate(RATE_CREATURE_AGGRO
));
972 m_MaxVisibleDistanceForPlayer
= 45*sWorld
.getRate(RATE_CREATURE_AGGRO
);
974 else if(m_MaxVisibleDistanceForPlayer
+ m_VisibleUnitGreyDistance
> MAX_VISIBILITY_DISTANCE
)
976 sLog
.outError("Visibility.Distance.Player can't be greater %f",MAX_VISIBILITY_DISTANCE
- m_VisibleUnitGreyDistance
);
977 m_MaxVisibleDistanceForPlayer
= MAX_VISIBILITY_DISTANCE
- m_VisibleUnitGreyDistance
;
979 m_MaxVisibleDistanceForObject
= sConfig
.GetFloatDefault("Visibility.Distance.Gameobject", DEFAULT_VISIBILITY_DISTANCE
);
980 if(m_MaxVisibleDistanceForObject
< INTERACTION_DISTANCE
)
982 sLog
.outError("Visibility.Distance.Object can't be less max aggro radius %f",float(INTERACTION_DISTANCE
));
983 m_MaxVisibleDistanceForObject
= INTERACTION_DISTANCE
;
985 else if(m_MaxVisibleDistanceForObject
+ m_VisibleObjectGreyDistance
> MAX_VISIBILITY_DISTANCE
)
987 sLog
.outError("Visibility.Distance.Object can't be greater %f",MAX_VISIBILITY_DISTANCE
-m_VisibleObjectGreyDistance
);
988 m_MaxVisibleDistanceForObject
= MAX_VISIBILITY_DISTANCE
- m_VisibleObjectGreyDistance
;
990 m_MaxVisibleDistanceInFlight
= sConfig
.GetFloatDefault("Visibility.Distance.InFlight", DEFAULT_VISIBILITY_DISTANCE
);
991 if(m_MaxVisibleDistanceInFlight
+ m_VisibleObjectGreyDistance
> MAX_VISIBILITY_DISTANCE
)
993 sLog
.outError("Visibility.Distance.InFlight can't be greater %f",MAX_VISIBILITY_DISTANCE
-m_VisibleObjectGreyDistance
);
994 m_MaxVisibleDistanceInFlight
= MAX_VISIBILITY_DISTANCE
- m_VisibleObjectGreyDistance
;
997 ///- Read the "Data" directory from the config file
998 std::string dataPath
= sConfig
.GetStringDefault("DataDir","./");
999 if( dataPath
.at(dataPath
.length()-1)!='/' && dataPath
.at(dataPath
.length()-1)!='\\' )
1000 dataPath
.append("/");
1004 if(dataPath
!=m_dataPath
)
1005 sLog
.outError("DataDir option can't be changed at mangosd.conf reload, using current value (%s).",m_dataPath
.c_str());
1009 m_dataPath
= dataPath
;
1010 sLog
.outString("Using DataDir %s",m_dataPath
.c_str());
1013 bool enableLOS
= sConfig
.GetBoolDefault("vmap.enableLOS", false);
1014 bool enableHeight
= sConfig
.GetBoolDefault("vmap.enableHeight", false);
1015 std::string ignoreMapIds
= sConfig
.GetStringDefault("vmap.ignoreMapIds", "");
1016 std::string ignoreSpellIds
= sConfig
.GetStringDefault("vmap.ignoreSpellIds", "");
1017 VMAP::VMapFactory::createOrGetVMapManager()->setEnableLineOfSightCalc(enableLOS
);
1018 VMAP::VMapFactory::createOrGetVMapManager()->setEnableHeightCalc(enableHeight
);
1019 VMAP::VMapFactory::createOrGetVMapManager()->preventMapsFromBeingUsed(ignoreMapIds
.c_str());
1020 VMAP::VMapFactory::preventSpellsFromBeingTestedForLoS(ignoreSpellIds
.c_str());
1021 sLog
.outString( "WORLD: VMap support included. LineOfSight:%i, getHeight:%i",enableLOS
, enableHeight
);
1022 sLog
.outString( "WORLD: VMap data directory is: %svmaps",m_dataPath
.c_str());
1023 sLog
.outString( "WORLD: VMap config keys are: vmap.enableLOS, vmap.enableHeight, vmap.ignoreMapIds, vmap.ignoreSpellIds");
1026 /// Initialize the World
1027 void World::SetInitialWorldSettings()
1029 ///- Initialize the random number generator
1030 srand((unsigned int)time(NULL
));
1032 ///- Initialize config settings
1033 LoadConfigSettings();
1035 ///- Init highest guids before any table loading to prevent using not initialized guids in some code.
1036 objmgr
.SetHighestGuids();
1038 ///- Check the existence of the map files for all races' startup areas.
1039 if( !MapManager::ExistMapAndVMap(0,-6240.32f
, 331.033f
)
1040 ||!MapManager::ExistMapAndVMap(0,-8949.95f
,-132.493f
)
1041 ||!MapManager::ExistMapAndVMap(0,-8949.95f
,-132.493f
)
1042 ||!MapManager::ExistMapAndVMap(1,-618.518f
,-4251.67f
)
1043 ||!MapManager::ExistMapAndVMap(0, 1676.35f
, 1677.45f
)
1044 ||!MapManager::ExistMapAndVMap(1, 10311.3f
, 832.463f
)
1045 ||!MapManager::ExistMapAndVMap(1,-2917.58f
,-257.98f
)
1046 ||m_configs
[CONFIG_EXPANSION
] && (
1047 !MapManager::ExistMapAndVMap(530,10349.6f
,-6357.29f
) || !MapManager::ExistMapAndVMap(530,-3961.64f
,-13931.2f
) ) )
1049 sLog
.outError("Correct *.map files not found in path '%smaps' or *.vmap/*vmdir files in '%svmaps'. Please place *.map/*.vmap/*.vmdir files in appropriate directories or correct the DataDir value in the mangosd.conf file.",m_dataPath
.c_str(),m_dataPath
.c_str());
1053 ///- Loading strings. Getting no records means core load has to be canceled because no error message can be output.
1055 sLog
.outString("Loading MaNGOS strings...");
1056 if (!objmgr
.LoadMangosStrings())
1057 exit(1); // Error message displayed in function already
1059 ///- Update the realm entry in the database with the realm type from the config file
1060 //No SQL injection as values are treated as integers
1062 // not send custom type REALM_FFA_PVP to realm list
1063 uint32 server_type
= IsFFAPvPRealm() ? REALM_TYPE_PVP
: getConfig(CONFIG_GAME_TYPE
);
1064 uint32 realm_zone
= getConfig(CONFIG_REALM_ZONE
);
1065 loginDatabase
.PExecute("UPDATE realmlist SET icon = %u, timezone = %u WHERE id = '%d'", server_type
, realm_zone
, realmID
);
1067 ///- Remove the bones after a restart
1068 CharacterDatabase
.PExecute("DELETE FROM corpse WHERE corpse_type = '0'");
1070 ///- Load the DBC files
1071 sLog
.outString("Initialize data stores...");
1072 LoadDBCStores(m_dataPath
);
1075 sLog
.outString( "Loading Script Names...");
1076 objmgr
.LoadScriptNames();
1078 sLog
.outString( "Loading InstanceTemplate..." );
1079 objmgr
.LoadInstanceTemplate();
1081 sLog
.outString( "Loading SkillLineAbilityMultiMap Data..." );
1082 spellmgr
.LoadSkillLineAbilityMap();
1084 ///- Clean up and pack instances
1085 sLog
.outString( "Cleaning up instances..." );
1086 sInstanceSaveManager
.CleanupInstances(); // must be called before `creature_respawn`/`gameobject_respawn` tables
1088 sLog
.outString( "Packing instances..." );
1089 sInstanceSaveManager
.PackInstances();
1092 sLog
.outString( "Loading Localization strings..." );
1093 objmgr
.LoadCreatureLocales();
1094 objmgr
.LoadGameObjectLocales();
1095 objmgr
.LoadItemLocales();
1096 objmgr
.LoadQuestLocales();
1097 objmgr
.LoadNpcTextLocales();
1098 objmgr
.LoadPageTextLocales();
1099 objmgr
.LoadNpcOptionLocales();
1100 objmgr
.LoadPointOfInterestLocales();
1101 objmgr
.SetDBCLocaleIndex(GetDefaultDbcLocale()); // Get once for all the locale index of DBC language (console/broadcasts)
1102 sLog
.outString( ">>> Localization strings loaded" );
1105 sLog
.outString( "Loading Page Texts..." );
1106 objmgr
.LoadPageTexts();
1108 sLog
.outString( "Loading Game Object Templates..." ); // must be after LoadPageTexts
1109 objmgr
.LoadGameobjectInfo();
1111 sLog
.outString( "Loading Spell Chain Data..." );
1112 spellmgr
.LoadSpellChains();
1114 sLog
.outString( "Loading Spell Elixir types..." );
1115 spellmgr
.LoadSpellElixirs();
1117 sLog
.outString( "Loading Spell Learn Skills..." );
1118 spellmgr
.LoadSpellLearnSkills(); // must be after LoadSpellChains
1120 sLog
.outString( "Loading Spell Learn Spells..." );
1121 spellmgr
.LoadSpellLearnSpells();
1123 sLog
.outString( "Loading Spell Proc Event conditions..." );
1124 spellmgr
.LoadSpellProcEvents();
1126 sLog
.outString( "Loading Spell Bonus Data..." );
1127 spellmgr
.LoadSpellBonusess();
1129 sLog
.outString( "Loading Aggro Spells Definitions...");
1130 spellmgr
.LoadSpellThreats();
1132 sLog
.outString( "Loading NPC Texts..." );
1133 objmgr
.LoadGossipText();
1135 sLog
.outString( "Loading Item Random Enchantments Table..." );
1136 LoadRandomEnchantmentsTable();
1138 sLog
.outString( "Loading Items..." ); // must be after LoadRandomEnchantmentsTable and LoadPageTexts
1139 objmgr
.LoadItemPrototypes();
1141 sLog
.outString( "Loading Item Texts..." );
1142 objmgr
.LoadItemTexts();
1144 sLog
.outString( "Loading Creature Model Based Info Data..." );
1145 objmgr
.LoadCreatureModelInfo();
1147 sLog
.outString( "Loading Equipment templates...");
1148 objmgr
.LoadEquipmentTemplates();
1150 sLog
.outString( "Loading Creature templates..." );
1151 objmgr
.LoadCreatureTemplates();
1153 sLog
.outString( "Loading SpellsScriptTarget...");
1154 spellmgr
.LoadSpellScriptTarget(); // must be after LoadCreatureTemplates and LoadGameobjectInfo
1156 sLog
.outString( "Loading Creature Reputation OnKill Data..." );
1157 objmgr
.LoadReputationOnKill();
1159 sLog
.outString( "Loading Points Of Interest Data..." );
1160 objmgr
.LoadPointsOfInterest();
1162 sLog
.outString( "Loading Pet Create Spells..." );
1163 objmgr
.LoadPetCreateSpells();
1165 sLog
.outString( "Loading Creature Data..." );
1166 objmgr
.LoadCreatures();
1168 sLog
.outString( "Loading Creature Addon Data..." );
1170 objmgr
.LoadCreatureAddons(); // must be after LoadCreatureTemplates() and LoadCreatures()
1171 sLog
.outString( ">>> Creature Addon Data loaded" );
1174 sLog
.outString( "Loading Creature Respawn Data..." ); // must be after PackInstances()
1175 objmgr
.LoadCreatureRespawnTimes();
1177 sLog
.outString( "Loading Gameobject Data..." );
1178 objmgr
.LoadGameobjects();
1180 sLog
.outString( "Loading Gameobject Respawn Data..." ); // must be after PackInstances()
1181 objmgr
.LoadGameobjectRespawnTimes();
1183 sLog
.outString( "Loading Objects Pooling Data...");
1184 poolhandler
.LoadFromDB();
1186 sLog
.outString( "Loading Game Event Data...");
1188 gameeventmgr
.LoadFromDB();
1189 sLog
.outString( ">>> Game Event Data loaded" );
1192 sLog
.outString( "Loading Weather Data..." );
1193 objmgr
.LoadWeatherZoneChances();
1195 sLog
.outString( "Loading Quests..." );
1196 objmgr
.LoadQuests(); // must be loaded after DBCs, creature_template, item_template, gameobject tables
1198 sLog
.outString( "Loading Quests Relations..." );
1200 objmgr
.LoadQuestRelations(); // must be after quest load
1201 sLog
.outString( ">>> Quests Relations loaded" );
1204 sLog
.outString( "Loading SpellArea Data..." ); // must be after quest load
1205 spellmgr
.LoadSpellAreas();
1207 sLog
.outString( "Loading AreaTrigger definitions..." );
1208 objmgr
.LoadAreaTriggerTeleports(); // must be after item template load
1210 sLog
.outString( "Loading Quest Area Triggers..." );
1211 objmgr
.LoadQuestAreaTriggers(); // must be after LoadQuests
1213 sLog
.outString( "Loading Tavern Area Triggers..." );
1214 objmgr
.LoadTavernAreaTriggers();
1216 sLog
.outString( "Loading AreaTrigger script names..." );
1217 objmgr
.LoadAreaTriggerScripts();
1219 sLog
.outString( "Loading Graveyard-zone links...");
1220 objmgr
.LoadGraveyardZones();
1222 sLog
.outString( "Loading Spell target coordinates..." );
1223 spellmgr
.LoadSpellTargetPositions();
1225 sLog
.outString( "Loading SpellAffect definitions..." );
1226 spellmgr
.LoadSpellAffects();
1228 sLog
.outString( "Loading spell pet auras..." );
1229 spellmgr
.LoadSpellPetAuras();
1231 sLog
.outString( "Loading pet levelup spells..." );
1232 spellmgr
.LoadPetLevelupSpellMap();
1234 sLog
.outString( "Loading Player Create Info & Level Stats..." );
1236 objmgr
.LoadPlayerInfo();
1237 sLog
.outString( ">>> Player Create Info & Level Stats loaded" );
1240 sLog
.outString( "Loading Exploration BaseXP Data..." );
1241 objmgr
.LoadExplorationBaseXP();
1243 sLog
.outString( "Loading Pet Name Parts..." );
1244 objmgr
.LoadPetNames();
1246 sLog
.outString( "Loading the max pet number..." );
1247 objmgr
.LoadPetNumber();
1249 sLog
.outString( "Loading pet level stats..." );
1250 objmgr
.LoadPetLevelInfo();
1252 sLog
.outString( "Loading Player Corpses..." );
1253 objmgr
.LoadCorpses();
1255 sLog
.outString( "Loading Loot Tables..." );
1258 sLog
.outString( ">>> Loot Tables loaded" );
1261 sLog
.outString( "Loading Skill Discovery Table..." );
1262 LoadSkillDiscoveryTable();
1264 sLog
.outString( "Loading Skill Extra Item Table..." );
1265 LoadSkillExtraItemTable();
1267 sLog
.outString( "Loading Skill Fishing base level requirements..." );
1268 objmgr
.LoadFishingBaseSkillLevel();
1270 sLog
.outString( "Loading Achievements..." );
1272 achievementmgr
.LoadAchievementReferenceList();
1273 achievementmgr
.LoadAchievementCriteriaList();
1274 achievementmgr
.LoadAchievementCriteriaData();
1275 achievementmgr
.LoadRewards();
1276 achievementmgr
.LoadRewardLocales();
1277 achievementmgr
.LoadCompletedAchievements();
1278 sLog
.outString( ">>> Achievements loaded" );
1281 ///- Load dynamic data tables from the database
1282 sLog
.outString( "Loading Auctions..." );
1284 auctionmgr
.LoadAuctionItems();
1285 auctionmgr
.LoadAuctions();
1286 sLog
.outString( ">>> Auctions loaded" );
1289 sLog
.outString( "Loading Guilds..." );
1290 objmgr
.LoadGuilds();
1292 sLog
.outString( "Loading ArenaTeams..." );
1293 objmgr
.LoadArenaTeams();
1295 sLog
.outString( "Loading Groups..." );
1296 objmgr
.LoadGroups();
1298 sLog
.outString( "Loading ReservedNames..." );
1299 objmgr
.LoadReservedPlayersNames();
1301 sLog
.outString( "Loading GameObjects for quests..." );
1302 objmgr
.LoadGameObjectForQuests();
1304 sLog
.outString( "Loading BattleMasters..." );
1305 sBattleGroundMgr
.LoadBattleMastersEntry();
1307 sLog
.outString( "Loading GameTeleports..." );
1308 objmgr
.LoadGameTele();
1310 sLog
.outString( "Loading Npc Text Id..." );
1311 objmgr
.LoadNpcTextId(); // must be after load Creature and NpcText
1313 sLog
.outString( "Loading Npc Options..." );
1314 objmgr
.LoadNpcOptions();
1316 sLog
.outString( "Loading Vendors..." );
1317 objmgr
.LoadVendors(); // must be after load CreatureTemplate and ItemTemplate
1319 sLog
.outString( "Loading Trainers..." );
1320 objmgr
.LoadTrainerSpell(); // must be after load CreatureTemplate
1322 sLog
.outString( "Loading Waypoints..." );
1326 sLog
.outString( "Loading GM tickets...");
1327 ticketmgr
.LoadGMTickets();
1329 ///- Handle outdated emails (delete/return)
1330 sLog
.outString( "Returning old mails..." );
1331 objmgr
.ReturnOrDeleteOldMails(false);
1333 ///- Load and initialize scripts
1334 sLog
.outString( "Loading Scripts..." );
1336 objmgr
.LoadQuestStartScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1337 objmgr
.LoadQuestEndScripts(); // must be after load Creature/Gameobject(Template/Data) and QuestTemplate
1338 objmgr
.LoadSpellScripts(); // must be after load Creature/Gameobject(Template/Data)
1339 objmgr
.LoadGameObjectScripts(); // must be after load Creature/Gameobject(Template/Data)
1340 objmgr
.LoadEventScripts(); // must be after load Creature/Gameobject(Template/Data)
1341 sLog
.outString( ">>> Scripts loaded" );
1344 sLog
.outString( "Loading Scripts text locales..." ); // must be after Load*Scripts calls
1345 objmgr
.LoadDbScriptStrings();
1347 sLog
.outString( "Loading CreatureEventAI Texts...");
1348 CreatureEAI_Mgr
.LoadCreatureEventAI_Texts();
1350 sLog
.outString( "Loading CreatureEventAI Summons...");
1351 CreatureEAI_Mgr
.LoadCreatureEventAI_Summons();
1353 sLog
.outString( "Loading CreatureEventAI Scripts...");
1354 CreatureEAI_Mgr
.LoadCreatureEventAI_Scripts();
1356 sLog
.outString( "Initializing Scripts..." );
1357 if(!LoadScriptingModule())
1360 ///- Initialize game time and timers
1361 sLog
.outString( "DEBUG:: Initialize game time and timers" );
1362 m_gameTime
= time(NULL
);
1363 m_startTime
=m_gameTime
;
1368 local
=*(localtime(&curr
)); // dereference and assign
1370 sprintf( isoDate
, "%04d-%02d-%02d %02d:%02d:%02d",
1371 local
.tm_year
+1900, local
.tm_mon
+1, local
.tm_mday
, local
.tm_hour
, local
.tm_min
, local
.tm_sec
);
1373 loginDatabase
.PExecute("INSERT INTO uptime (realmid, starttime, startstring, uptime) VALUES('%u', " I64FMTD
", '%s', 0)",
1374 realmID
, uint64(m_startTime
), isoDate
);
1376 m_timers
[WUPDATE_OBJECTS
].SetInterval(0);
1377 m_timers
[WUPDATE_SESSIONS
].SetInterval(0);
1378 m_timers
[WUPDATE_WEATHERS
].SetInterval(1*IN_MILISECONDS
);
1379 m_timers
[WUPDATE_AUCTIONS
].SetInterval(MINUTE
*IN_MILISECONDS
);
1380 m_timers
[WUPDATE_UPTIME
].SetInterval(m_configs
[CONFIG_UPTIME_UPDATE
]*MINUTE
*IN_MILISECONDS
);
1381 //Update "uptime" table based on configuration entry in minutes.
1382 m_timers
[WUPDATE_CORPSES
].SetInterval(20*MINUTE
*IN_MILISECONDS
);
1383 //erase corpses every 20 minutes
1385 //to set mailtimer to return mails every day between 4 and 5 am
1386 //mailtimer is increased when updating auctions
1387 //one second is 1000 -(tested on win system)
1388 mail_timer
= ((((localtime( &m_gameTime
)->tm_hour
+ 20) % 24)* HOUR
* IN_MILISECONDS
) / m_timers
[WUPDATE_AUCTIONS
].GetInterval() );
1390 mail_timer_expires
= ( (DAY
* IN_MILISECONDS
) / (m_timers
[WUPDATE_AUCTIONS
].GetInterval()));
1391 sLog
.outDebug("Mail timer set to: %u, mail return is called every %u minutes", mail_timer
, mail_timer_expires
);
1393 ///- Initilize static helper structures
1394 AIRegistry::Initialize();
1395 WaypointMovementGenerator
<Creature
>::Initialize();
1396 Player::InitVisibleBits();
1398 ///- Initialize MapManager
1399 sLog
.outString( "Starting Map System" );
1400 MapManager::Instance().Initialize();
1402 ///- Initialize Battlegrounds
1403 sLog
.outString( "Starting BattleGround System" );
1404 sBattleGroundMgr
.CreateInitialBattleGrounds();
1405 sBattleGroundMgr
.InitAutomaticArenaPointDistribution();
1407 //Not sure if this can be moved up in the sequence (with static data loading) as it uses MapManager
1408 sLog
.outString( "Loading Transports..." );
1409 MapManager::Instance().LoadTransports();
1411 sLog
.outString("Deleting expired bans..." );
1412 loginDatabase
.Execute("DELETE FROM ip_banned WHERE unbandate<=UNIX_TIMESTAMP() AND unbandate<>bandate");
1414 sLog
.outString("Calculate next daily quest reset time..." );
1415 InitDailyQuestResetTime();
1417 sLog
.outString("Starting objects Pooling system..." );
1418 poolhandler
.Initialize();
1420 sLog
.outString("Starting Game Event system..." );
1421 uint32 nextGameEvent
= gameeventmgr
.Initialize();
1422 m_timers
[WUPDATE_EVENTS
].SetInterval(nextGameEvent
); //depend on next event
1424 sLog
.outString("Initialize AuctionHouseBot...");
1425 AuctionHouseBotInit();
1427 sLog
.outString( "WORLD: World initialized" );
1430 void World::DetectDBCLang()
1432 uint32 m_lang_confid
= sConfig
.GetIntDefault("DBC.Locale", 255);
1434 if(m_lang_confid
!= 255 && m_lang_confid
>= MAX_LOCALE
)
1436 sLog
.outError("Incorrect DBC.Locale! Must be >= 0 and < %d (set to 0)",MAX_LOCALE
);
1437 m_lang_confid
= LOCALE_enUS
;
1440 ChrRacesEntry
const* race
= sChrRacesStore
.LookupEntry(1);
1442 std::string availableLocalsStr
;
1444 int default_locale
= MAX_LOCALE
;
1445 for (int i
= MAX_LOCALE
-1; i
>= 0; --i
)
1447 if ( strlen(race
->name
[i
]) > 0) // check by race names
1450 m_availableDbcLocaleMask
|= (1 << i
);
1451 availableLocalsStr
+= localeNames
[i
];
1452 availableLocalsStr
+= " ";
1456 if( default_locale
!= m_lang_confid
&& m_lang_confid
< MAX_LOCALE
&&
1457 (m_availableDbcLocaleMask
& (1 << m_lang_confid
)) )
1459 default_locale
= m_lang_confid
;
1462 if(default_locale
>= MAX_LOCALE
)
1464 sLog
.outError("Unable to determine your DBC Locale! (corrupt DBC?)");
1468 m_defaultDbcLocale
= LocaleConstant(default_locale
);
1470 sLog
.outString("Using %s DBC Locale as default. All available DBC locales: %s",localeNames
[m_defaultDbcLocale
],availableLocalsStr
.empty() ? "<none>" : availableLocalsStr
.c_str());
1474 /// Update the World !
1475 void World::Update(uint32 diff
)
1477 ///- Update the different timers
1478 for(int i
= 0; i
< WUPDATE_COUNT
; ++i
)
1479 if(m_timers
[i
].GetCurrent()>=0)
1480 m_timers
[i
].Update(diff
);
1481 else m_timers
[i
].SetCurrent(0);
1483 ///- Update the game time and check for shutdown time
1486 /// Handle daily quests reset time
1487 if(m_gameTime
> m_NextDailyQuestReset
)
1490 m_NextDailyQuestReset
+= DAY
;
1493 /// <ul><li> Handle auctions when the timer has passed
1494 if (m_timers
[WUPDATE_AUCTIONS
].Passed())
1497 m_timers
[WUPDATE_AUCTIONS
].Reset();
1499 ///- Update mails (return old mails with item, or delete them)
1500 //(tested... works on win)
1501 if (++mail_timer
> mail_timer_expires
)
1504 objmgr
.ReturnOrDeleteOldMails(true);
1507 ///- Handle expired auctions
1508 auctionmgr
.Update();
1511 /// <li> Handle session updates when the timer has passed
1512 if (m_timers
[WUPDATE_SESSIONS
].Passed())
1514 m_timers
[WUPDATE_SESSIONS
].Reset();
1516 UpdateSessions(diff
);
1519 /// <li> Handle weather updates when the timer has passed
1520 if (m_timers
[WUPDATE_WEATHERS
].Passed())
1522 m_timers
[WUPDATE_WEATHERS
].Reset();
1524 ///- Send an update signal to Weather objects
1525 WeatherMap::iterator itr
, next
;
1526 for (itr
= m_weathers
.begin(); itr
!= m_weathers
.end(); itr
= next
)
1531 ///- and remove Weather objects for zones with no player
1532 //As interval > WorldTick
1533 if(!itr
->second
->Update(m_timers
[WUPDATE_WEATHERS
].GetInterval()))
1536 m_weathers
.erase(itr
);
1540 /// <li> Update uptime table
1541 if (m_timers
[WUPDATE_UPTIME
].Passed())
1543 uint32 tmpDiff
= (m_gameTime
- m_startTime
);
1544 uint32 maxClientsNum
= GetMaxActiveSessionCount();
1546 m_timers
[WUPDATE_UPTIME
].Reset();
1547 loginDatabase
.PExecute("UPDATE uptime SET uptime = %u, maxplayers = %u WHERE realmid = %u AND starttime = " I64FMTD
, tmpDiff
, maxClientsNum
, realmID
, uint64(m_startTime
));
1550 /// <li> Handle all other objects
1551 if (m_timers
[WUPDATE_OBJECTS
].Passed())
1553 m_timers
[WUPDATE_OBJECTS
].Reset();
1554 ///- Update objects when the timer has passed (maps, transport, creatures,...)
1555 MapManager::Instance().Update(diff
); // As interval = 0
1557 ///- Process necessary scripts
1558 if (!m_scriptSchedule
.empty())
1561 sBattleGroundMgr
.Update(diff
);
1564 // execute callbacks from sql queries that were queued recently
1565 UpdateResultQueue();
1567 ///- Erase corpses once every 20 minutes
1568 if (m_timers
[WUPDATE_CORPSES
].Passed())
1570 m_timers
[WUPDATE_CORPSES
].Reset();
1575 ///- Process Game events when necessary
1576 if (m_timers
[WUPDATE_EVENTS
].Passed())
1578 m_timers
[WUPDATE_EVENTS
].Reset(); // to give time for Update() to be processed
1579 uint32 nextGameEvent
= gameeventmgr
.Update();
1580 m_timers
[WUPDATE_EVENTS
].SetInterval(nextGameEvent
);
1581 m_timers
[WUPDATE_EVENTS
].Reset();
1585 ///- Move all creatures with "delayed move" and remove and delete all objects with "delayed remove"
1586 MapManager::Instance().DoDelayedMovesAndRemoves();
1588 // update the instance reset times
1589 sInstanceSaveManager
.Update();
1591 // And last, but not least handle the issued cli commands
1592 ProcessCliCommands();
1595 /// Put scripts in the execution queue
1596 void World::ScriptsStart(ScriptMapMap
const& scripts
, uint32 id
, Object
* source
, Object
* target
)
1598 ///- Find the script map
1599 ScriptMapMap::const_iterator s
= scripts
.find(id
);
1600 if (s
== scripts
.end())
1603 // prepare static data
1604 uint64 sourceGUID
= source
->GetGUID();
1605 uint64 targetGUID
= target
? target
->GetGUID() : (uint64
)0;
1606 uint64 ownerGUID
= (source
->GetTypeId()==TYPEID_ITEM
) ? ((Item
*)source
)->GetOwnerGUID() : (uint64
)0;
1608 ///- Schedule script execution for all scripts in the script map
1609 ScriptMap
const *s2
= &(s
->second
);
1610 bool immedScript
= false;
1611 for (ScriptMap::const_iterator iter
= s2
->begin(); iter
!= s2
->end(); ++iter
)
1614 sa
.sourceGUID
= sourceGUID
;
1615 sa
.targetGUID
= targetGUID
;
1616 sa
.ownerGUID
= ownerGUID
;
1618 sa
.script
= &iter
->second
;
1619 m_scriptSchedule
.insert(std::pair
<time_t, ScriptAction
>(m_gameTime
+ iter
->first
, sa
));
1620 if (iter
->first
== 0)
1623 ///- If one of the effects should be immediate, launch the script execution
1628 void World::ScriptCommandStart(ScriptInfo
const& script
, uint32 delay
, Object
* source
, Object
* target
)
1630 // NOTE: script record _must_ exist until command executed
1632 // prepare static data
1633 uint64 sourceGUID
= source
->GetGUID();
1634 uint64 targetGUID
= target
? target
->GetGUID() : (uint64
)0;
1635 uint64 ownerGUID
= (source
->GetTypeId()==TYPEID_ITEM
) ? ((Item
*)source
)->GetOwnerGUID() : (uint64
)0;
1638 sa
.sourceGUID
= sourceGUID
;
1639 sa
.targetGUID
= targetGUID
;
1640 sa
.ownerGUID
= ownerGUID
;
1642 sa
.script
= &script
;
1643 m_scriptSchedule
.insert(std::pair
<time_t, ScriptAction
>(m_gameTime
+ delay
, sa
));
1645 ///- If effects should be immediate, launch the script execution
1650 /// Process queued scripts
1651 void World::ScriptsProcess()
1653 if (m_scriptSchedule
.empty())
1656 ///- Process overdue queued scripts
1657 std::multimap
<time_t, ScriptAction
>::iterator iter
= m_scriptSchedule
.begin();
1658 // ok as multimap is a *sorted* associative container
1659 while (!m_scriptSchedule
.empty() && (iter
->first
<= m_gameTime
))
1661 ScriptAction
const& step
= iter
->second
;
1663 Object
* source
= NULL
;
1667 switch(GUID_HIPART(step
.sourceGUID
))
1670 // case HIGHGUID_CONTAINER: ==HIGHGUID_ITEM
1672 Player
* player
= HashMapHolder
<Player
>::Find(step
.ownerGUID
);
1674 source
= player
->GetItemByGuid(step
.sourceGUID
);
1678 source
= HashMapHolder
<Creature
>::Find(step
.sourceGUID
);
1681 source
= HashMapHolder
<Pet
>::Find(step
.sourceGUID
);
1683 case HIGHGUID_VEHICLE
:
1684 source
= HashMapHolder
<Vehicle
>::Find(step
.sourceGUID
);
1686 case HIGHGUID_PLAYER
:
1687 source
= HashMapHolder
<Player
>::Find(step
.sourceGUID
);
1689 case HIGHGUID_GAMEOBJECT
:
1690 source
= HashMapHolder
<GameObject
>::Find(step
.sourceGUID
);
1692 case HIGHGUID_CORPSE
:
1693 source
= HashMapHolder
<Corpse
>::Find(step
.sourceGUID
);
1696 sLog
.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step
.sourceGUID
));
1701 if(source
&& !source
->IsInWorld()) source
= NULL
;
1703 Object
* target
= NULL
;
1707 switch(GUID_HIPART(step
.targetGUID
))
1710 target
= HashMapHolder
<Creature
>::Find(step
.targetGUID
);
1713 target
= HashMapHolder
<Pet
>::Find(step
.targetGUID
);
1715 case HIGHGUID_VEHICLE
:
1716 target
= HashMapHolder
<Vehicle
>::Find(step
.targetGUID
);
1718 case HIGHGUID_PLAYER
: // empty GUID case also
1719 target
= HashMapHolder
<Player
>::Find(step
.targetGUID
);
1721 case HIGHGUID_GAMEOBJECT
:
1722 target
= HashMapHolder
<GameObject
>::Find(step
.targetGUID
);
1724 case HIGHGUID_CORPSE
:
1725 target
= HashMapHolder
<Corpse
>::Find(step
.targetGUID
);
1728 sLog
.outError("*_script source with unsupported high guid value %u",GUID_HIPART(step
.targetGUID
));
1733 if(target
&& !target
->IsInWorld()) target
= NULL
;
1735 switch (step
.script
->command
)
1737 case SCRIPT_COMMAND_TALK
:
1741 sLog
.outError("SCRIPT_COMMAND_TALK call for NULL creature.");
1745 if(source
->GetTypeId()!=TYPEID_UNIT
)
1747 sLog
.outError("SCRIPT_COMMAND_TALK call for non-creature (TypeId: %u), skipping.",source
->GetTypeId());
1751 uint64 unit_target
= target
? target
->GetGUID() : 0;
1753 //datalong 0=normal say, 1=whisper, 2=yell, 3=emote text
1754 switch(step
.script
->datalong
)
1757 ((Creature
*)source
)->Say(step
.script
->dataint
, LANG_UNIVERSAL
, unit_target
);
1762 sLog
.outError("SCRIPT_COMMAND_TALK attempt to whisper (%u) NULL, skipping.",step
.script
->datalong
);
1765 ((Creature
*)source
)->Whisper(step
.script
->dataint
,unit_target
);
1768 ((Creature
*)source
)->Yell(step
.script
->dataint
, LANG_UNIVERSAL
, unit_target
);
1770 case 3: // Emote text
1771 ((Creature
*)source
)->TextEmote(step
.script
->dataint
, unit_target
);
1774 break; // must be already checked at load
1779 case SCRIPT_COMMAND_EMOTE
:
1782 sLog
.outError("SCRIPT_COMMAND_EMOTE call for NULL creature.");
1786 if(source
->GetTypeId()!=TYPEID_UNIT
)
1788 sLog
.outError("SCRIPT_COMMAND_EMOTE call for non-creature (TypeId: %u), skipping.",source
->GetTypeId());
1792 ((Creature
*)source
)->HandleEmoteCommand(step
.script
->datalong
);
1794 case SCRIPT_COMMAND_FIELD_SET
:
1797 sLog
.outError("SCRIPT_COMMAND_FIELD_SET call for NULL object.");
1800 if(step
.script
->datalong
<= OBJECT_FIELD_ENTRY
|| step
.script
->datalong
>= source
->GetValuesCount())
1802 sLog
.outError("SCRIPT_COMMAND_FIELD_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1803 step
.script
->datalong
,source
->GetValuesCount(),source
->GetTypeId());
1807 source
->SetUInt32Value(step
.script
->datalong
, step
.script
->datalong2
);
1809 case SCRIPT_COMMAND_MOVE_TO
:
1812 sLog
.outError("SCRIPT_COMMAND_MOVE_TO call for NULL creature.");
1816 if(source
->GetTypeId()!=TYPEID_UNIT
)
1818 sLog
.outError("SCRIPT_COMMAND_MOVE_TO call for non-creature (TypeId: %u), skipping.",source
->GetTypeId());
1821 ((Unit
*)source
)->SendMonsterMoveWithSpeed(step
.script
->x
, step
.script
->y
, step
.script
->z
, step
.script
->datalong2
);
1822 ((Unit
*)source
)->GetMap()->CreatureRelocation(((Creature
*)source
), step
.script
->x
, step
.script
->y
, step
.script
->z
, 0);
1824 case SCRIPT_COMMAND_FLAG_SET
:
1827 sLog
.outError("SCRIPT_COMMAND_FLAG_SET call for NULL object.");
1830 if(step
.script
->datalong
<= OBJECT_FIELD_ENTRY
|| step
.script
->datalong
>= source
->GetValuesCount())
1832 sLog
.outError("SCRIPT_COMMAND_FLAG_SET call for wrong field %u (max count: %u) in object (TypeId: %u).",
1833 step
.script
->datalong
,source
->GetValuesCount(),source
->GetTypeId());
1837 source
->SetFlag(step
.script
->datalong
, step
.script
->datalong2
);
1839 case SCRIPT_COMMAND_FLAG_REMOVE
:
1842 sLog
.outError("SCRIPT_COMMAND_FLAG_REMOVE call for NULL object.");
1845 if(step
.script
->datalong
<= OBJECT_FIELD_ENTRY
|| step
.script
->datalong
>= source
->GetValuesCount())
1847 sLog
.outError("SCRIPT_COMMAND_FLAG_REMOVE call for wrong field %u (max count: %u) in object (TypeId: %u).",
1848 step
.script
->datalong
,source
->GetValuesCount(),source
->GetTypeId());
1852 source
->RemoveFlag(step
.script
->datalong
, step
.script
->datalong2
);
1855 case SCRIPT_COMMAND_TELEPORT_TO
:
1857 // accept player in any one from target/source arg
1858 if (!target
&& !source
)
1860 sLog
.outError("SCRIPT_COMMAND_TELEPORT_TO call for NULL object.");
1864 // must be only Player
1865 if((!target
|| target
->GetTypeId() != TYPEID_PLAYER
) && (!source
|| source
->GetTypeId() != TYPEID_PLAYER
))
1867 sLog
.outError("SCRIPT_COMMAND_TELEPORT_TO call for non-player (TypeIdSource: %u)(TypeIdTarget: %u), skipping.", source
? source
->GetTypeId() : 0, target
? target
->GetTypeId() : 0);
1871 Player
* pSource
= target
&& target
->GetTypeId() == TYPEID_PLAYER
? (Player
*)target
: (Player
*)source
;
1873 pSource
->TeleportTo(step
.script
->datalong
, step
.script
->x
, step
.script
->y
, step
.script
->z
, step
.script
->o
);
1877 case SCRIPT_COMMAND_TEMP_SUMMON_CREATURE
:
1879 if(!step
.script
->datalong
) // creature not specified
1881 sLog
.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL creature.");
1887 sLog
.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for NULL world object.");
1891 WorldObject
* summoner
= dynamic_cast<WorldObject
*>(source
);
1895 sLog
.outError("SCRIPT_COMMAND_TEMP_SUMMON_CREATURE call for non-WorldObject (TypeId: %u), skipping.",source
->GetTypeId());
1899 float x
= step
.script
->x
;
1900 float y
= step
.script
->y
;
1901 float z
= step
.script
->z
;
1902 float o
= step
.script
->o
;
1904 Creature
* pCreature
= summoner
->SummonCreature(step
.script
->datalong
, x
, y
, z
, o
,TEMPSUMMON_TIMED_OR_DEAD_DESPAWN
,step
.script
->datalong2
);
1907 sLog
.outError("SCRIPT_COMMAND_TEMP_SUMMON failed for creature (entry: %u).",step
.script
->datalong
);
1914 case SCRIPT_COMMAND_RESPAWN_GAMEOBJECT
:
1916 if(!step
.script
->datalong
) // gameobject not specified
1918 sLog
.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL gameobject.");
1924 sLog
.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for NULL world object.");
1928 WorldObject
* summoner
= dynamic_cast<WorldObject
*>(source
);
1932 sLog
.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT call for non-WorldObject (TypeId: %u), skipping.",source
->GetTypeId());
1936 GameObject
*go
= NULL
;
1937 int32 time_to_despawn
= step
.script
->datalong2
<5 ? 5 : (int32
)step
.script
->datalong2
;
1939 CellPair
p(MaNGOS::ComputeCellPair(summoner
->GetPositionX(), summoner
->GetPositionY()));
1941 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
1943 MaNGOS::GameObjectWithDbGUIDCheck
go_check(*summoner
,step
.script
->datalong
);
1944 MaNGOS::GameObjectSearcher
<MaNGOS::GameObjectWithDbGUIDCheck
> checker(summoner
, go
,go_check
);
1946 TypeContainerVisitor
<MaNGOS::GameObjectSearcher
<MaNGOS::GameObjectWithDbGUIDCheck
>, GridTypeMapContainer
> object_checker(checker
);
1947 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
1948 cell_lock
->Visit(cell_lock
, object_checker
, *summoner
->GetMap());
1952 sLog
.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT failed for gameobject(guid: %u).", step
.script
->datalong
);
1956 if( go
->GetGoType()==GAMEOBJECT_TYPE_FISHINGNODE
||
1957 go
->GetGoType()==GAMEOBJECT_TYPE_DOOR
||
1958 go
->GetGoType()==GAMEOBJECT_TYPE_BUTTON
||
1959 go
->GetGoType()==GAMEOBJECT_TYPE_TRAP
)
1961 sLog
.outError("SCRIPT_COMMAND_RESPAWN_GAMEOBJECT can not be used with gameobject of type %u (guid: %u).", uint32(go
->GetGoType()), step
.script
->datalong
);
1965 if( go
->isSpawned() )
1966 break; //gameobject already spawned
1968 go
->SetLootState(GO_READY
);
1969 go
->SetRespawnTime(time_to_despawn
); //despawn object in ? seconds
1971 go
->GetMap()->Add(go
);
1974 case SCRIPT_COMMAND_OPEN_DOOR
:
1976 if(!step
.script
->datalong
) // door not specified
1978 sLog
.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL door.");
1984 sLog
.outError("SCRIPT_COMMAND_OPEN_DOOR call for NULL unit.");
1988 if(!source
->isType(TYPEMASK_UNIT
)) // must be any Unit (creature or player)
1990 sLog
.outError("SCRIPT_COMMAND_OPEN_DOOR call for non-unit (TypeId: %u), skipping.",source
->GetTypeId());
1994 Unit
* caster
= (Unit
*)source
;
1996 GameObject
*door
= NULL
;
1997 int32 time_to_close
= step
.script
->datalong2
< 15 ? 15 : (int32
)step
.script
->datalong2
;
1999 CellPair
p(MaNGOS::ComputeCellPair(caster
->GetPositionX(), caster
->GetPositionY()));
2001 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
2003 MaNGOS::GameObjectWithDbGUIDCheck
go_check(*caster
,step
.script
->datalong
);
2004 MaNGOS::GameObjectSearcher
<MaNGOS::GameObjectWithDbGUIDCheck
> checker(caster
,door
,go_check
);
2006 TypeContainerVisitor
<MaNGOS::GameObjectSearcher
<MaNGOS::GameObjectWithDbGUIDCheck
>, GridTypeMapContainer
> object_checker(checker
);
2007 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
2008 cell_lock
->Visit(cell_lock
, object_checker
, *caster
->GetMap());
2012 sLog
.outError("SCRIPT_COMMAND_OPEN_DOOR failed for gameobject(guid: %u).", step
.script
->datalong
);
2015 if (door
->GetGoType() != GAMEOBJECT_TYPE_DOOR
)
2017 sLog
.outError("SCRIPT_COMMAND_OPEN_DOOR failed for non-door(GoType: %u).", door
->GetGoType());
2021 if (door
->GetGoState() != GO_STATE_READY
)
2022 break; //door already open
2024 door
->UseDoorOrButton(time_to_close
);
2026 if(target
&& target
->isType(TYPEMASK_GAMEOBJECT
) && ((GameObject
*)target
)->GetGoType()==GAMEOBJECT_TYPE_BUTTON
)
2027 ((GameObject
*)target
)->UseDoorOrButton(time_to_close
);
2030 case SCRIPT_COMMAND_CLOSE_DOOR
:
2032 if(!step
.script
->datalong
) // guid for door not specified
2034 sLog
.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL door.");
2040 sLog
.outError("SCRIPT_COMMAND_CLOSE_DOOR call for NULL unit.");
2044 if(!source
->isType(TYPEMASK_UNIT
)) // must be any Unit (creature or player)
2046 sLog
.outError("SCRIPT_COMMAND_CLOSE_DOOR call for non-unit (TypeId: %u), skipping.",source
->GetTypeId());
2050 Unit
* caster
= (Unit
*)source
;
2052 GameObject
*door
= NULL
;
2053 int32 time_to_open
= step
.script
->datalong2
< 15 ? 15 : (int32
)step
.script
->datalong2
;
2055 CellPair
p(MaNGOS::ComputeCellPair(caster
->GetPositionX(), caster
->GetPositionY()));
2057 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
2059 MaNGOS::GameObjectWithDbGUIDCheck
go_check(*caster
,step
.script
->datalong
);
2060 MaNGOS::GameObjectSearcher
<MaNGOS::GameObjectWithDbGUIDCheck
> checker(caster
,door
,go_check
);
2062 TypeContainerVisitor
<MaNGOS::GameObjectSearcher
<MaNGOS::GameObjectWithDbGUIDCheck
>, GridTypeMapContainer
> object_checker(checker
);
2063 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
2064 cell_lock
->Visit(cell_lock
, object_checker
, *caster
->GetMap());
2068 sLog
.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for gameobject(guid: %u).", step
.script
->datalong
);
2071 if ( door
->GetGoType() != GAMEOBJECT_TYPE_DOOR
)
2073 sLog
.outError("SCRIPT_COMMAND_CLOSE_DOOR failed for non-door(GoType: %u).", door
->GetGoType());
2077 if( door
->GetGoState() == GO_STATE_READY
)
2078 break; //door already closed
2080 door
->UseDoorOrButton(time_to_open
);
2082 if(target
&& target
->isType(TYPEMASK_GAMEOBJECT
) && ((GameObject
*)target
)->GetGoType()==GAMEOBJECT_TYPE_BUTTON
)
2083 ((GameObject
*)target
)->UseDoorOrButton(time_to_open
);
2087 case SCRIPT_COMMAND_QUEST_EXPLORED
:
2091 sLog
.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL source.");
2097 sLog
.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for NULL target.");
2101 // when script called for item spell casting then target == (unit or GO) and source is player
2102 WorldObject
* worldObject
;
2105 if(target
->GetTypeId()==TYPEID_PLAYER
)
2107 if(source
->GetTypeId()!=TYPEID_UNIT
&& source
->GetTypeId()!=TYPEID_GAMEOBJECT
)
2109 sLog
.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",source
->GetTypeId());
2113 worldObject
= (WorldObject
*)source
;
2114 player
= (Player
*)target
;
2118 if(target
->GetTypeId()!=TYPEID_UNIT
&& target
->GetTypeId()!=TYPEID_GAMEOBJECT
)
2120 sLog
.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-creature and non-gameobject (TypeId: %u), skipping.",target
->GetTypeId());
2124 if(source
->GetTypeId()!=TYPEID_PLAYER
)
2126 sLog
.outError("SCRIPT_COMMAND_QUEST_EXPLORED call for non-player(TypeId: %u), skipping.",source
->GetTypeId());
2130 worldObject
= (WorldObject
*)target
;
2131 player
= (Player
*)source
;
2134 // quest id and flags checked at script loading
2135 if( (worldObject
->GetTypeId()!=TYPEID_UNIT
|| ((Unit
*)worldObject
)->isAlive()) &&
2136 (step
.script
->datalong2
==0 || worldObject
->IsWithinDistInMap(player
,float(step
.script
->datalong2
))) )
2137 player
->AreaExploredOrEventHappens(step
.script
->datalong
);
2139 player
->FailQuest(step
.script
->datalong
);
2144 case SCRIPT_COMMAND_ACTIVATE_OBJECT
:
2148 sLog
.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT must have source caster.");
2152 if(!source
->isType(TYPEMASK_UNIT
))
2154 sLog
.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT source caster isn't unit (TypeId: %u), skipping.",source
->GetTypeId());
2160 sLog
.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for NULL gameobject.");
2164 if(target
->GetTypeId()!=TYPEID_GAMEOBJECT
)
2166 sLog
.outError("SCRIPT_COMMAND_ACTIVATE_OBJECT call for non-gameobject (TypeId: %u), skipping.",target
->GetTypeId());
2170 Unit
* caster
= (Unit
*)source
;
2172 GameObject
*go
= (GameObject
*)target
;
2178 case SCRIPT_COMMAND_REMOVE_AURA
:
2180 Object
* cmdTarget
= step
.script
->datalong2
? source
: target
;
2184 sLog
.outError("SCRIPT_COMMAND_REMOVE_AURA call for NULL %s.",step
.script
->datalong2
? "source" : "target");
2188 if(!cmdTarget
->isType(TYPEMASK_UNIT
))
2190 sLog
.outError("SCRIPT_COMMAND_REMOVE_AURA %s isn't unit (TypeId: %u), skipping.",step
.script
->datalong2
? "source" : "target",cmdTarget
->GetTypeId());
2194 ((Unit
*)cmdTarget
)->RemoveAurasDueToSpell(step
.script
->datalong
);
2198 case SCRIPT_COMMAND_CAST_SPELL
:
2202 sLog
.outError("SCRIPT_COMMAND_CAST_SPELL must have source caster.");
2206 if(!source
->isType(TYPEMASK_UNIT
))
2208 sLog
.outError("SCRIPT_COMMAND_CAST_SPELL source caster isn't unit (TypeId: %u), skipping.",source
->GetTypeId());
2212 Object
* cmdTarget
= step
.script
->datalong2
& 0x01 ? source
: target
;
2216 sLog
.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step
.script
->datalong2
& 0x01 ? "source" : "target");
2220 if(!cmdTarget
->isType(TYPEMASK_UNIT
))
2222 sLog
.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step
.script
->datalong2
& 0x01 ? "source" : "target",cmdTarget
->GetTypeId());
2226 Unit
* spellTarget
= (Unit
*)cmdTarget
;
2228 Object
* cmdSource
= step
.script
->datalong2
& 0x02 ? target
: source
;
2232 sLog
.outError("SCRIPT_COMMAND_CAST_SPELL call for NULL %s.",step
.script
->datalong2
& 0x02 ? "target" : "source");
2236 if(!cmdSource
->isType(TYPEMASK_UNIT
))
2238 sLog
.outError("SCRIPT_COMMAND_CAST_SPELL %s isn't unit (TypeId: %u), skipping.",step
.script
->datalong2
& 0x02 ? "target" : "source", cmdSource
->GetTypeId());
2242 Unit
* spellSource
= (Unit
*)cmdSource
;
2244 //TODO: when GO cast implemented, code below must be updated accordingly to also allow GO spell cast
2245 spellSource
->CastSpell(spellTarget
,step
.script
->datalong
,false);
2250 case SCRIPT_COMMAND_PLAY_SOUND
:
2254 sLog
.outError("SCRIPT_COMMAND_PLAY_SOUND call for NULL creature.");
2258 WorldObject
* pSource
= dynamic_cast<WorldObject
*>(source
);
2261 sLog
.outError("SCRIPT_COMMAND_PLAY_SOUND call for non-world object (TypeId: %u), skipping.",source
->GetTypeId());
2265 // bitmask: 0/1=anyone/target, 0/2=with distance dependent
2266 Player
* pTarget
= NULL
;
2267 if(step
.script
->datalong2
& 1)
2271 sLog
.outError("SCRIPT_COMMAND_PLAY_SOUND in targeted mode call for NULL target.");
2275 if(target
->GetTypeId()!=TYPEID_PLAYER
)
2277 sLog
.outError("SCRIPT_COMMAND_PLAY_SOUND in targeted mode call for non-player (TypeId: %u), skipping.",target
->GetTypeId());
2281 pTarget
= (Player
*)target
;
2284 // bitmask: 0/1=anyone/target, 0/2=with distance dependent
2285 if(step
.script
->datalong2
& 2)
2286 pSource
->PlayDistanceSound(step
.script
->datalong
,pTarget
);
2288 pSource
->PlayDirectSound(step
.script
->datalong
,pTarget
);
2292 sLog
.outError("Unknown script command %u called.",step
.script
->command
);
2296 m_scriptSchedule
.erase(iter
);
2298 iter
= m_scriptSchedule
.begin();
2303 /// Send a packet to all players (except self if mentioned)
2304 void World::SendGlobalMessage(WorldPacket
*packet
, WorldSession
*self
, uint32 team
)
2306 SessionMap::const_iterator itr
;
2307 for (itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2310 itr
->second
->GetPlayer() &&
2311 itr
->second
->GetPlayer()->IsInWorld() &&
2312 itr
->second
!= self
&&
2313 (team
== 0 || itr
->second
->GetPlayer()->GetTeam() == team
) )
2315 itr
->second
->SendPacket(packet
);
2322 class WorldWorldTextBuilder
2325 typedef std::vector
<WorldPacket
*> WorldPacketList
;
2326 explicit WorldWorldTextBuilder(int32 textId
, va_list* args
= NULL
) : i_textId(textId
), i_args(args
) {}
2327 void operator()(WorldPacketList
& data_list
, int32 loc_idx
)
2329 char const* text
= objmgr
.GetMangosString(i_textId
,loc_idx
);
2333 // we need copy va_list before use or original va_list will corrupted
2335 va_copy(ap
,*i_args
);
2338 vsnprintf(str
,2048,text
, ap
);
2341 do_helper(data_list
,&str
[0]);
2344 do_helper(data_list
,(char*)text
);
2347 char* lineFromMessage(char*& pos
) { char* start
= strtok(pos
,"\n"); pos
= NULL
; return start
; }
2348 void do_helper(WorldPacketList
& data_list
, char* text
)
2352 while(char* line
= lineFromMessage(pos
))
2354 WorldPacket
* data
= new WorldPacket();
2356 uint32 lineLength
= (line
? strlen(line
) : 0) + 1;
2358 data
->Initialize(SMSG_MESSAGECHAT
, 100); // guess size
2359 *data
<< uint8(CHAT_MSG_SYSTEM
);
2360 *data
<< uint32(LANG_UNIVERSAL
);
2362 *data
<< uint32(0); // can be chat msg group or something
2364 *data
<< uint32(lineLength
);
2368 data_list
.push_back(data
);
2375 } // namespace MaNGOS
2377 /// Send a System Message to all players (except self if mentioned)
2378 void World::SendWorldText(int32 string_id
, ...)
2381 va_start(ap
, string_id
);
2383 MaNGOS::WorldWorldTextBuilder
wt_builder(string_id
, &ap
);
2384 MaNGOS::LocalizedPacketListDo
<MaNGOS::WorldWorldTextBuilder
> wt_do(wt_builder
);
2385 for(SessionMap::const_iterator itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2387 if(!itr
->second
|| !itr
->second
->GetPlayer() || !itr
->second
->GetPlayer()->IsInWorld() )
2390 wt_do(itr
->second
->GetPlayer());
2396 /// DEPRICATED, only for debug purpose. Send a System Message to all players (except self if mentioned)
2397 void World::SendGlobalText(const char* text
, WorldSession
*self
)
2401 // need copy to prevent corruption by strtok call in LineFromMessage original string
2402 char* buf
= strdup(text
);
2405 while(char* line
= ChatHandler::LineFromMessage(pos
))
2407 ChatHandler::FillMessageData(&data
, NULL
, CHAT_MSG_SYSTEM
, LANG_UNIVERSAL
, NULL
, 0, line
, NULL
);
2408 SendGlobalMessage(&data
, self
);
2414 /// Send a packet to all players (or players selected team) in the zone (except self if mentioned)
2415 void World::SendZoneMessage(uint32 zone
, WorldPacket
*packet
, WorldSession
*self
, uint32 team
)
2417 SessionMap::const_iterator itr
;
2418 for (itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2421 itr
->second
->GetPlayer() &&
2422 itr
->second
->GetPlayer()->IsInWorld() &&
2423 itr
->second
->GetPlayer()->GetZoneId() == zone
&&
2424 itr
->second
!= self
&&
2425 (team
== 0 || itr
->second
->GetPlayer()->GetTeam() == team
) )
2427 itr
->second
->SendPacket(packet
);
2432 /// Send a System Message to all players in the zone (except self if mentioned)
2433 void World::SendZoneText(uint32 zone
, const char* text
, WorldSession
*self
, uint32 team
)
2436 ChatHandler::FillMessageData(&data
, NULL
, CHAT_MSG_SYSTEM
, LANG_UNIVERSAL
, NULL
, 0, text
, NULL
);
2437 SendZoneMessage(zone
, &data
, self
,team
);
2440 /// Kick (and save) all players
2441 void World::KickAll()
2443 m_QueuedPlayer
.clear(); // prevent send queue update packet and login queued sessions
2445 // session not removed at kick and will removed in next update tick
2446 for (SessionMap::const_iterator itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2447 itr
->second
->KickPlayer();
2450 /// Kick (and save) all players with security level less `sec`
2451 void World::KickAllLess(AccountTypes sec
)
2453 // session not removed at kick and will removed in next update tick
2454 for (SessionMap::const_iterator itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2455 if(itr
->second
->GetSecurity() < sec
)
2456 itr
->second
->KickPlayer();
2459 /// Kick (and save) the designated player
2460 bool World::KickPlayer(const std::string
& playerName
)
2462 SessionMap::const_iterator itr
;
2464 // session not removed at kick and will removed in next update tick
2465 for (itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2469 Player
*player
= itr
->second
->GetPlayer();
2472 if( player
->IsInWorld() )
2474 if (playerName
== player
->GetName())
2476 itr
->second
->KickPlayer();
2484 /// Ban an account or ban an IP address, duration will be parsed using TimeStringToSecs if it is positive, otherwise permban
2485 BanReturn
World::BanAccount(BanMode mode
, std::string nameOrIP
, std::string duration
, std::string reason
, std::string author
)
2487 loginDatabase
.escape_string(nameOrIP
);
2488 loginDatabase
.escape_string(reason
);
2489 std::string safe_author
=author
;
2490 loginDatabase
.escape_string(safe_author
);
2492 uint32 duration_secs
= TimeStringToSecs(duration
);
2493 QueryResult
*resultAccounts
= NULL
; //used for kicking
2495 ///- Update the database with ban information
2499 //No SQL injection as strings are escaped
2500 resultAccounts
= loginDatabase
.PQuery("SELECT id FROM account WHERE last_ip = '%s'",nameOrIP
.c_str());
2501 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());
2504 //No SQL injection as string is escaped
2505 resultAccounts
= loginDatabase
.PQuery("SELECT id FROM account WHERE username = '%s'",nameOrIP
.c_str());
2508 //No SQL injection as string is escaped
2509 resultAccounts
= CharacterDatabase
.PQuery("SELECT account FROM characters WHERE name = '%s'",nameOrIP
.c_str());
2512 return BAN_SYNTAX_ERROR
;
2518 return BAN_SUCCESS
; // ip correctly banned but nobody affected (yet)
2520 return BAN_NOTFOUND
; // Nobody to ban
2523 ///- Disconnect all affected players (for IP it can be several)
2526 Field
* fieldsAccount
= resultAccounts
->Fetch();
2527 uint32 account
= fieldsAccount
->GetUInt32();
2531 //No SQL injection as strings are escaped
2532 loginDatabase
.PExecute("INSERT INTO account_banned VALUES ('%u', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()+%u, '%s', '%s', '1')",
2533 account
,duration_secs
,safe_author
.c_str(),reason
.c_str());
2536 if (WorldSession
* sess
= FindSession(account
))
2537 if(std::string(sess
->GetPlayerName()) != author
)
2540 while( resultAccounts
->NextRow() );
2542 delete resultAccounts
;
2546 /// Remove a ban from an account or IP address
2547 bool World::RemoveBanAccount(BanMode mode
, std::string nameOrIP
)
2551 loginDatabase
.escape_string(nameOrIP
);
2552 loginDatabase
.PExecute("DELETE FROM ip_banned WHERE ip = '%s'",nameOrIP
.c_str());
2557 if (mode
== BAN_ACCOUNT
)
2558 account
= accmgr
.GetId (nameOrIP
);
2559 else if (mode
== BAN_CHARACTER
)
2560 account
= objmgr
.GetPlayerAccountIdByPlayerName (nameOrIP
);
2565 //NO SQL injection as account is uint32
2566 loginDatabase
.PExecute("UPDATE account_banned SET active = '0' WHERE id = '%u'",account
);
2571 /// Update the game time
2572 void World::_UpdateGameTime()
2574 ///- update the time
2575 time_t thisTime
= time(NULL
);
2576 uint32 elapsed
= uint32(thisTime
- m_gameTime
);
2577 m_gameTime
= thisTime
;
2579 ///- if there is a shutdown timer
2580 if(!m_stopEvent
&& m_ShutdownTimer
> 0 && elapsed
> 0)
2582 ///- ... and it is overdue, stop the world (set m_stopEvent)
2583 if( m_ShutdownTimer
<= elapsed
)
2585 if(!(m_ShutdownMask
& SHUTDOWN_MASK_IDLE
) || GetActiveAndQueuedSessionCount()==0)
2586 m_stopEvent
= true; // exist code already set
2588 m_ShutdownTimer
= 1; // minimum timer value to wait idle state
2590 ///- ... else decrease it and if necessary display a shutdown countdown to the users
2593 m_ShutdownTimer
-= elapsed
;
2600 /// Shutdown the server
2601 void World::ShutdownServ(uint32 time
, uint32 options
, uint8 exitcode
)
2603 // ignore if server shutdown at next tick
2607 m_ShutdownMask
= options
;
2608 m_ExitCode
= exitcode
;
2610 ///- If the shutdown time is 0, set m_stopEvent (except if shutdown is 'idle' with remaining sessions)
2613 if(!(options
& SHUTDOWN_MASK_IDLE
) || GetActiveAndQueuedSessionCount()==0)
2614 m_stopEvent
= true; // exist code already set
2616 m_ShutdownTimer
= 1; //So that the session count is re-evaluated at next world tick
2618 ///- Else set the shutdown timer and warn users
2621 m_ShutdownTimer
= time
;
2626 /// Display a shutdown message to the user(s)
2627 void World::ShutdownMsg(bool show
, Player
* player
)
2629 // not show messages for idle shutdown mode
2630 if(m_ShutdownMask
& SHUTDOWN_MASK_IDLE
)
2633 ///- Display a message every 12 hours, hours, 5 minutes, minute, 5 seconds and finally seconds
2635 (m_ShutdownTimer
< 10) ||
2636 // < 30 sec; every 5 sec
2637 (m_ShutdownTimer
<30 && (m_ShutdownTimer
% 5 )==0) ||
2638 // < 5 min ; every 1 min
2639 (m_ShutdownTimer
<5*MINUTE
&& (m_ShutdownTimer
% MINUTE
)==0) ||
2640 // < 30 min ; every 5 min
2641 (m_ShutdownTimer
<30*MINUTE
&& (m_ShutdownTimer
% (5*MINUTE
))==0) ||
2642 // < 12 h ; every 1 h
2643 (m_ShutdownTimer
<12*HOUR
&& (m_ShutdownTimer
% HOUR
)==0) ||
2644 // > 12 h ; every 12 h
2645 (m_ShutdownTimer
>12*HOUR
&& (m_ShutdownTimer
% (12*HOUR
) )==0))
2647 std::string str
= secsToTimeString(m_ShutdownTimer
);
2649 ServerMessageType msgid
= (m_ShutdownMask
& SHUTDOWN_MASK_RESTART
) ? SERVER_MSG_RESTART_TIME
: SERVER_MSG_SHUTDOWN_TIME
;
2651 SendServerMessage(msgid
,str
.c_str(),player
);
2652 DEBUG_LOG("Server is %s in %s",(m_ShutdownMask
& SHUTDOWN_MASK_RESTART
? "restart" : "shuttingdown"),str
.c_str());
2656 /// Cancel a planned server shutdown
2657 void World::ShutdownCancel()
2659 // nothing cancel or too later
2660 if(!m_ShutdownTimer
|| m_stopEvent
)
2663 ServerMessageType msgid
= (m_ShutdownMask
& SHUTDOWN_MASK_RESTART
) ? SERVER_MSG_RESTART_CANCELLED
: SERVER_MSG_SHUTDOWN_CANCELLED
;
2666 m_ShutdownTimer
= 0;
2667 m_ExitCode
= SHUTDOWN_EXIT_CODE
; // to default value
2668 SendServerMessage(msgid
);
2670 DEBUG_LOG("Server %s cancelled.",(m_ShutdownMask
& SHUTDOWN_MASK_RESTART
? "restart" : "shuttingdown"));
2673 /// Send a server message to the user(s)
2674 void World::SendServerMessage(ServerMessageType type
, const char *text
, Player
* player
)
2676 WorldPacket
data(SMSG_SERVER_MESSAGE
, 50); // guess size
2677 data
<< uint32(type
);
2678 if(type
<= SERVER_MSG_STRING
)
2682 player
->GetSession()->SendPacket(&data
);
2684 SendGlobalMessage( &data
);
2687 void World::UpdateSessions( uint32 diff
)
2689 ///- Add new sessions
2690 while(!addSessQueue
.empty())
2692 WorldSession
* sess
= addSessQueue
.next ();
2696 ///- Then send an update signal to remaining ones
2697 for (SessionMap::iterator itr
= m_sessions
.begin(), next
; itr
!= m_sessions
.end(); itr
= next
)
2705 ///- and remove not active sessions from the list
2706 if(!itr
->second
->Update(diff
)) // As interval = 0
2708 RemoveQueuedPlayer (itr
->second
);
2710 m_sessions
.erase(itr
);
2715 // This handles the issued and queued CLI commands
2716 void World::ProcessCliCommands()
2718 if (cliCmdQueue
.empty())
2721 CliCommandHolder::Print
* zprint
;
2723 while (!cliCmdQueue
.empty())
2725 sLog
.outDebug("CLI command under processing...");
2726 CliCommandHolder
*command
= cliCmdQueue
.next();
2728 zprint
= command
->m_print
;
2730 CliHandler(zprint
).ParseCommands(command
->m_command
);
2735 // print the console message here so it looks right
2739 void World::InitResultQueue()
2741 m_resultQueue
= new SqlResultQueue
;
2742 CharacterDatabase
.SetResultQueue(m_resultQueue
);
2745 void World::UpdateResultQueue()
2747 m_resultQueue
->Update();
2750 void World::UpdateRealmCharCount(uint32 accountId
)
2752 CharacterDatabase
.AsyncPQuery(this, &World::_UpdateRealmCharCount
, accountId
,
2753 "SELECT COUNT(guid) FROM characters WHERE account = '%u'", accountId
);
2756 void World::_UpdateRealmCharCount(QueryResult
*resultCharCount
, uint32 accountId
)
2758 if (resultCharCount
)
2760 Field
*fields
= resultCharCount
->Fetch();
2761 uint32 charCount
= fields
[0].GetUInt32();
2762 delete resultCharCount
;
2763 loginDatabase
.PExecute("DELETE FROM realmcharacters WHERE acctid= '%d' AND realmid = '%d'", accountId
, realmID
);
2764 loginDatabase
.PExecute("INSERT INTO realmcharacters (numchars, acctid, realmid) VALUES (%u, %u, %u)", charCount
, accountId
, realmID
);
2768 void World::InitDailyQuestResetTime()
2770 time_t mostRecentQuestTime
;
2772 QueryResult
* result
= CharacterDatabase
.Query("SELECT MAX(time) FROM character_queststatus_daily");
2775 Field
*fields
= result
->Fetch();
2777 mostRecentQuestTime
= (time_t)fields
[0].GetUInt64();
2781 mostRecentQuestTime
= 0;
2783 // client built-in time for reset is 6:00 AM
2784 // FIX ME: client not show day start time
2785 time_t curTime
= time(NULL
);
2786 tm localTm
= *localtime(&curTime
);
2787 localTm
.tm_hour
= 6;
2791 // current day reset time
2792 time_t curDayResetTime
= mktime(&localTm
);
2794 // last reset time before current moment
2795 time_t resetTime
= (curTime
< curDayResetTime
) ? curDayResetTime
- DAY
: curDayResetTime
;
2797 // need reset (if we have quest time before last reset time (not processed by some reason)
2798 if(mostRecentQuestTime
&& mostRecentQuestTime
<= resetTime
)
2799 m_NextDailyQuestReset
= mostRecentQuestTime
;
2802 // plan next reset time
2803 m_NextDailyQuestReset
= (curTime
>= curDayResetTime
) ? curDayResetTime
+ DAY
: curDayResetTime
;
2807 void World::ResetDailyQuests()
2809 sLog
.outDetail("Daily quests reset for all characters.");
2810 CharacterDatabase
.Execute("DELETE FROM character_queststatus_daily");
2811 for(SessionMap::const_iterator itr
= m_sessions
.begin(); itr
!= m_sessions
.end(); ++itr
)
2812 if(itr
->second
->GetPlayer())
2813 itr
->second
->GetPlayer()->ResetDailyQuestStatus();
2816 void World::SetPlayerLimit( int32 limit
, bool needUpdate
)
2818 if(limit
< -SEC_ADMINISTRATOR
)
2819 limit
= -SEC_ADMINISTRATOR
;
2822 bool db_update_need
= needUpdate
|| (limit
< 0) != (m_playerLimit
< 0) || (limit
< 0 && m_playerLimit
< 0 && limit
!= m_playerLimit
);
2824 m_playerLimit
= limit
;
2827 loginDatabase
.PExecute("UPDATE realmlist SET allowedSecurityLevel = '%u' WHERE id = '%d'",uint8(GetPlayerSecurityLimit()),realmID
);
2830 void World::UpdateMaxSessionCounters()
2832 m_maxActiveSessionCount
= std::max(m_maxActiveSessionCount
,uint32(m_sessions
.size()-m_QueuedPlayer
.size()));
2833 m_maxQueuedSessionCount
= std::max(m_maxQueuedSessionCount
,uint32(m_QueuedPlayer
.size()));
2836 void World::LoadDBVersion()
2838 QueryResult
* result
= WorldDatabase
.Query("SELECT version, creature_ai_version FROM db_version LIMIT 1");
2841 Field
* fields
= result
->Fetch();
2843 m_DBVersion
= fields
[0].GetCppString();
2844 m_CreatureEventAIVersion
= fields
[1].GetCppString();
2848 if(m_DBVersion
.empty())
2849 m_DBVersion
= "Unknown world database.";
2851 if(m_CreatureEventAIVersion
.empty())
2852 m_CreatureEventAIVersion
= "Unknown creature EventAI.";