[9290] Some cleanups in realmd, no functional changes
[getmangos.git] / src / game / Player.cpp
blobb465bddf169e8417f86e756a95eef9e0a5c590e5
1 /*
2 * Copyright (C) 2005-2010 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Language.h"
21 #include "Database/DatabaseEnv.h"
22 #include "Log.h"
23 #include "Opcodes.h"
24 #include "SpellMgr.h"
25 #include "World.h"
26 #include "WorldPacket.h"
27 #include "WorldSession.h"
28 #include "UpdateMask.h"
29 #include "Player.h"
30 #include "Vehicle.h"
31 #include "SkillDiscovery.h"
32 #include "QuestDef.h"
33 #include "GossipDef.h"
34 #include "UpdateData.h"
35 #include "Channel.h"
36 #include "ChannelMgr.h"
37 #include "MapManager.h"
38 #include "MapInstanced.h"
39 #include "InstanceSaveMgr.h"
40 #include "GridNotifiers.h"
41 #include "GridNotifiersImpl.h"
42 #include "CellImpl.h"
43 #include "ObjectMgr.h"
44 #include "ObjectAccessor.h"
45 #include "ObjectDefines.h"
46 #include "CreatureAI.h"
47 #include "Formulas.h"
48 #include "Group.h"
49 #include "Guild.h"
50 #include "Pet.h"
51 #include "Util.h"
52 #include "Transports.h"
53 #include "Weather.h"
54 #include "BattleGround.h"
55 #include "BattleGroundAV.h"
56 #include "BattleGroundMgr.h"
57 #include "ArenaTeam.h"
58 #include "Chat.h"
59 #include "Database/DatabaseImpl.h"
60 #include "Spell.h"
61 #include "SocialMgr.h"
62 #include "AchievementMgr.h"
64 #include <cmath>
66 #define ZONE_UPDATE_INTERVAL (1*IN_MILISECONDS)
68 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
69 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
70 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
72 #define SKILL_VALUE(x) PAIR32_LOPART(x)
73 #define SKILL_MAX(x) PAIR32_HIPART(x)
74 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
76 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
77 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
78 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
80 enum CharacterFlags
82 CHARACTER_FLAG_NONE = 0x00000000,
83 CHARACTER_FLAG_UNK1 = 0x00000001,
84 CHARACTER_FLAG_UNK2 = 0x00000002,
85 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
86 CHARACTER_FLAG_UNK4 = 0x00000008,
87 CHARACTER_FLAG_UNK5 = 0x00000010,
88 CHARACTER_FLAG_UNK6 = 0x00000020,
89 CHARACTER_FLAG_UNK7 = 0x00000040,
90 CHARACTER_FLAG_UNK8 = 0x00000080,
91 CHARACTER_FLAG_UNK9 = 0x00000100,
92 CHARACTER_FLAG_UNK10 = 0x00000200,
93 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
94 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
95 CHARACTER_FLAG_UNK13 = 0x00001000,
96 CHARACTER_FLAG_GHOST = 0x00002000,
97 CHARACTER_FLAG_RENAME = 0x00004000,
98 CHARACTER_FLAG_UNK16 = 0x00008000,
99 CHARACTER_FLAG_UNK17 = 0x00010000,
100 CHARACTER_FLAG_UNK18 = 0x00020000,
101 CHARACTER_FLAG_UNK19 = 0x00040000,
102 CHARACTER_FLAG_UNK20 = 0x00080000,
103 CHARACTER_FLAG_UNK21 = 0x00100000,
104 CHARACTER_FLAG_UNK22 = 0x00200000,
105 CHARACTER_FLAG_UNK23 = 0x00400000,
106 CHARACTER_FLAG_UNK24 = 0x00800000,
107 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
108 CHARACTER_FLAG_DECLINED = 0x02000000,
109 CHARACTER_FLAG_UNK27 = 0x04000000,
110 CHARACTER_FLAG_UNK28 = 0x08000000,
111 CHARACTER_FLAG_UNK29 = 0x10000000,
112 CHARACTER_FLAG_UNK30 = 0x20000000,
113 CHARACTER_FLAG_UNK31 = 0x40000000,
114 CHARACTER_FLAG_UNK32 = 0x80000000
117 enum CharacterCustomizeFlags
119 CHAR_CUSTOMIZE_FLAG_NONE = 0x00000000,
120 CHAR_CUSTOMIZE_FLAG_CUSTOMIZE = 0x00000001, // name, gender, etc...
121 CHAR_CUSTOMIZE_FLAG_FACTION = 0x00010000, // name, gender, faction, etc...
122 CHAR_CUSTOMIZE_FLAG_RACE = 0x00100000 // name, gender, race, etc...
125 // corpse reclaim times
126 #define DEATH_EXPIRE_STEP (5*MINUTE)
127 #define MAX_DEATH_COUNT 3
129 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
131 //== PlayerTaxi ================================================
133 PlayerTaxi::PlayerTaxi()
135 // Taxi nodes
136 memset(m_taximask, 0, sizeof(m_taximask));
139 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
141 // class specific initial known nodes
142 switch(chrClass)
144 case CLASS_DEATH_KNIGHT:
146 for(int i = 0; i < TaxiMaskSize; ++i)
147 m_taximask[i] |= sOldContinentsNodesMask[i];
148 break;
152 // race specific initial known nodes: capital and taxi hub masks
153 switch(race)
155 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
156 case RACE_ORC: SetTaximaskNode(23); break; // Orc
157 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
158 case RACE_NIGHTELF: SetTaximaskNode(26);
159 SetTaximaskNode(27); break; // Night Elf
160 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
161 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
162 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
163 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
164 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
165 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
168 // new continent starting masks (It will be accessible only at new map)
169 switch(Player::TeamForRace(race))
171 case ALLIANCE: SetTaximaskNode(100); break;
172 case HORDE: SetTaximaskNode(99); break;
174 // level dependent taxi hubs
175 if(level>=68)
176 SetTaximaskNode(213); //Shattered Sun Staging Area
179 void PlayerTaxi::LoadTaxiMask(const char* data)
181 Tokens tokens = StrSplit(data, " ");
183 int index;
184 Tokens::iterator iter;
185 for (iter = tokens.begin(), index = 0;
186 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
188 // load and set bits only for existed taxi nodes
189 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
193 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
195 if(all)
197 for (uint8 i=0; i<TaxiMaskSize; ++i)
198 data << uint32(sTaxiNodesMask[i]); // all existed nodes
200 else
202 for (uint8 i=0; i<TaxiMaskSize; ++i)
203 data << uint32(m_taximask[i]); // known nodes
207 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string& values, uint32 team )
209 ClearTaxiDestinations();
211 Tokens tokens = StrSplit(values," ");
213 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
215 uint32 node = uint32(atol(iter->c_str()));
216 AddTaxiDestination(node);
219 if(m_TaxiDestinations.empty())
220 return true;
222 // Check integrity
223 if(m_TaxiDestinations.size() < 2)
224 return false;
226 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
228 uint32 cost;
229 uint32 path;
230 sObjectMgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
231 if(!path)
232 return false;
235 // can't load taxi path without mount set (quest taxi path?)
236 if(!sObjectMgr.GetTaxiMountDisplayId(GetTaxiSource(),team,true))
237 return false;
239 return true;
242 std::string PlayerTaxi::SaveTaxiDestinationsToString()
244 if(m_TaxiDestinations.empty())
245 return "";
247 std::ostringstream ss;
249 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
250 ss << m_TaxiDestinations[i] << " ";
252 return ss.str();
255 uint32 PlayerTaxi::GetCurrentTaxiPath() const
257 if(m_TaxiDestinations.size() < 2)
258 return 0;
260 uint32 path;
261 uint32 cost;
263 sObjectMgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
265 return path;
268 std::ostringstream& operator<< (std::ostringstream& ss, PlayerTaxi const& taxi)
270 ss << "'";
271 for(int i = 0; i < TaxiMaskSize; ++i)
272 ss << taxi.m_taximask[i] << " ";
273 ss << "'";
274 return ss;
277 SpellModifier::SpellModifier( SpellModOp _op, SpellModType _type, int32 _value, SpellEntry const* spellEntry, uint8 eff, int16 _charges /*= 0*/ ) : op(_op), type(_type), charges(_charges), value(_value), spellId(spellEntry->Id), lastAffected(NULL)
279 uint32 const* ptr = spellEntry->GetEffectSpellClassMask(eff);
280 mask = uint64(ptr[0]) | (uint64(ptr[1]) << 32);
281 mask2= ptr[2];
284 SpellModifier::SpellModifier( SpellModOp _op, SpellModType _type, int32 _value, Aura const* aura, int16 _charges /*= 0*/ ) : op(_op), type(_type), charges(_charges), value(_value), spellId(aura->GetId()), lastAffected(NULL)
286 uint32 const* ptr = aura->getAuraSpellClassMask();
287 mask = uint64(ptr[0]) | (uint64(ptr[1]) << 32);
288 mask2= ptr[2];
291 bool SpellModifier::isAffectedOnSpell( SpellEntry const *spell ) const
293 SpellEntry const *affect_spell = sSpellStore.LookupEntry(spellId);
294 // False if affect_spell == NULL or spellFamily not equal
295 if (!affect_spell || affect_spell->SpellFamilyName != spell->SpellFamilyName)
296 return false;
297 if (mask & spell->SpellFamilyFlags)
298 return true;
299 if (mask2 & spell->SpellFamilyFlags2)
300 return true;
301 return false;
304 //== Player ====================================================
306 UpdateMask Player::updateVisualBits;
308 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this), m_reputationMgr(this)
310 m_transport = 0;
312 m_speakTime = 0;
313 m_speakCount = 0;
315 m_objectType |= TYPEMASK_PLAYER;
316 m_objectTypeId = TYPEID_PLAYER;
318 m_valuesCount = PLAYER_END;
320 m_session = session;
322 m_divider = 0;
324 m_ExtraFlags = 0;
325 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
326 SetAcceptTicket(true);
328 // players always accept
329 if(GetSession()->GetSecurity() == SEC_PLAYER)
330 SetAcceptWhispers(true);
332 m_curSelection = 0;
333 m_lootGuid = 0;
335 m_comboTarget = 0;
336 m_comboPoints = 0;
338 m_usedTalentCount = 0;
339 m_questRewardTalentCount = 0;
341 m_regenTimer = 0;
342 m_weaponChangeTimer = 0;
344 m_zoneUpdateId = 0;
345 m_zoneUpdateTimer = 0;
347 m_areaUpdateId = 0;
349 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
351 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
352 // this must help in case next save after mass player load after server startup
353 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
355 clearResurrectRequestData();
357 m_SpellModRemoveCount = 0;
359 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
361 m_social = NULL;
363 // group is initialized in the reference constructor
364 SetGroupInvite(NULL);
365 m_groupUpdateMask = 0;
366 m_auraUpdateMask = 0;
368 duel = NULL;
370 m_GuildIdInvited = 0;
371 m_ArenaTeamIdInvited = 0;
373 m_atLoginFlags = AT_LOGIN_NONE;
375 mSemaphoreTeleport_Near = false;
376 mSemaphoreTeleport_Far = false;
378 m_DelayedOperations = 0;
379 m_bCanDelayTeleport = false;
380 m_bHasDelayedTeleport = false;
381 m_teleport_options = 0;
383 pTrader = 0;
384 ClearTrade();
386 m_cinematic = 0;
388 PlayerTalkClass = new PlayerMenu( GetSession() );
389 m_currentBuybackSlot = BUYBACK_SLOT_START;
391 m_DailyQuestChanged = false;
392 m_lastDailyQuestTime = 0;
394 for (int i=0; i<MAX_TIMERS; ++i)
395 m_MirrorTimer[i] = DISABLED_MIRROR_TIMER;
397 m_MirrorTimerFlags = UNDERWATER_NONE;
398 m_MirrorTimerFlagsLast = UNDERWATER_NONE;
399 m_isInWater = false;
400 m_drunkTimer = 0;
401 m_drunk = 0;
402 m_restTime = 0;
403 m_deathTimer = 0;
404 m_deathExpireTime = 0;
406 m_swingErrorMsg = 0;
408 m_DetectInvTimer = 1*IN_MILISECONDS;
410 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; ++j)
412 m_bgBattleGroundQueueID[j].bgQueueTypeId = BATTLEGROUND_QUEUE_NONE;
413 m_bgBattleGroundQueueID[j].invitedToInstance = 0;
416 m_logintime = time(NULL);
417 m_Last_tick = m_logintime;
418 m_WeaponProficiency = 0;
419 m_ArmorProficiency = 0;
420 m_canParry = false;
421 m_canBlock = false;
422 m_canDualWield = false;
423 m_canTitanGrip = false;
424 m_ammoDPS = 0.0f;
426 m_temporaryUnsummonedPetNumber = 0;
427 //cache for UNIT_CREATED_BY_SPELL to allow
428 //returning reagents for temporarily removed pets
429 //when dying/logging out
430 m_oldpetspell = 0;
432 ////////////////////Rest System/////////////////////
433 time_inn_enter=0;
434 inn_pos_mapid=0;
435 inn_pos_x=0;
436 inn_pos_y=0;
437 inn_pos_z=0;
438 m_rest_bonus=0;
439 rest_type=REST_TYPE_NO;
440 ////////////////////Rest System/////////////////////
442 m_mailsUpdated = false;
443 unReadMails = 0;
444 m_nextMailDelivereTime = 0;
446 m_resetTalentsCost = 0;
447 m_resetTalentsTime = 0;
448 m_itemUpdateQueueBlocked = false;
450 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
451 m_forced_speed_changes[i] = 0;
453 m_stableSlots = 0;
455 /////////////////// Instance System /////////////////////
457 m_HomebindTimer = 0;
458 m_InstanceValid = true;
459 m_dungeonDifficulty = DUNGEON_DIFFICULTY_NORMAL;
460 m_raidDifficulty = RAID_DIFFICULTY_10MAN_NORMAL;
462 m_lastPotionId = 0;
464 m_activeSpec = 0;
465 m_specsCount = 1;
467 for (int i = 0; i < BASEMOD_END; ++i)
469 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
470 m_auraBaseMod[i][PCT_MOD] = 1.0f;
473 for (int i = 0; i < MAX_COMBAT_RATING; ++i)
474 m_baseRatingValue[i] = 0;
476 m_baseSpellPower = 0;
477 m_baseFeralAP = 0;
478 m_baseManaRegen = 0;
479 m_armorPenetrationPct = 0.0f;
481 // Honor System
482 m_lastHonorUpdateTime = time(NULL);
484 // Player summoning
485 m_summon_expire = 0;
486 m_summon_mapid = 0;
487 m_summon_x = 0.0f;
488 m_summon_y = 0.0f;
489 m_summon_z = 0.0f;
491 m_mover = this;
493 m_miniPet = 0;
494 m_contestedPvPTimer = 0;
496 m_declinedname = NULL;
497 m_runes = NULL;
499 m_lastFallTime = 0;
500 m_lastFallZ = 0;
503 Player::~Player ()
505 CleanupsBeforeDelete();
507 // it must be unloaded already in PlayerLogout and accessed only for loggined player
508 //m_social = NULL;
510 // Note: buy back item already deleted from DB when player was saved
511 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
513 if(m_items[i])
514 delete m_items[i];
516 CleanupChannels();
518 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
519 delete itr->second;
521 //all mailed items should be deleted, also all mail should be deallocated
522 for (PlayerMails::const_iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
523 delete *itr;
525 for (ItemMap::const_iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
526 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
528 delete PlayerTalkClass;
530 if (m_transport)
532 m_transport->RemovePassenger(this);
535 for(size_t x = 0; x < ItemSetEff.size(); x++)
536 if(ItemSetEff[x])
537 delete ItemSetEff[x];
539 // clean up player-instance binds, may unload some instance saves
540 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
541 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
542 itr->second.save->RemovePlayer(this);
544 delete m_declinedname;
545 delete m_runes;
548 void Player::CleanupsBeforeDelete()
550 if(m_uint32Values) // only for fully created Object
552 TradeCancel(false);
553 DuelComplete(DUEL_INTERUPTED);
555 Unit::CleanupsBeforeDelete();
558 bool Player::Create( uint32 guidlow, const std::string& name, uint8 race, uint8 class_, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair, uint8 outfitId )
560 //FIXME: outfitId not used in player creating
562 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
564 m_name = name;
566 PlayerInfo const* info = sObjectMgr.GetPlayerInfo(race, class_);
567 if(!info)
569 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
570 return false;
573 for (int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
574 m_items[i] = NULL;
576 SetLocationMapId(info->mapId);
577 Relocate(info->positionX,info->positionY,info->positionZ);
579 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
580 if(!cEntry)
582 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
583 return false;
586 SetMap(sMapMgr.CreateMap(info->mapId, this));
588 uint8 powertype = cEntry->powerType;
590 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
591 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
593 setFactionForRace(race);
595 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
597 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
598 InitDisplayIds();
599 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
600 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
601 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
602 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
603 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
605 // -1 is default value
606 SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, -1);
608 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
609 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
610 SetByteValue(PLAYER_BYTES_3, 0, gender);
612 SetUInt32Value( PLAYER_GUILDID, 0 );
613 SetUInt32Value( PLAYER_GUILDRANK, 0 );
614 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
616 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
617 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
618 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES2, 0 ); // 0=disabled
619 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
620 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
621 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
622 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
623 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
625 // set starting level
626 uint32 start_level = getClass() != CLASS_DEATH_KNIGHT
627 ? sWorld.getConfig(CONFIG_START_PLAYER_LEVEL)
628 : sWorld.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL);
630 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
632 uint32 gm_level = sWorld.getConfig(CONFIG_START_GM_LEVEL);
633 if(gm_level > start_level)
634 start_level = gm_level;
637 SetUInt32Value(UNIT_FIELD_LEVEL, start_level);
639 InitRunes();
641 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
642 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
643 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
645 // Played time
646 m_Last_tick = time(NULL);
647 m_Played_time[PLAYED_TIME_TOTAL] = 0;
648 m_Played_time[PLAYED_TIME_LEVEL] = 0;
650 // base stats and related field values
651 InitStatsForLevel();
652 InitTaxiNodesForLevel();
653 InitGlyphsForLevel();
654 InitTalentForLevel();
655 InitPrimaryProfessions(); // to max set before any spell added
657 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
658 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
659 SetHealth(GetMaxHealth());
660 if (getPowerType()==POWER_MANA)
662 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
663 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
666 if(getPowerType() == POWER_RUNIC_POWER)
668 SetPower(POWER_RUNE, 8);
669 SetMaxPower(POWER_RUNE, 8);
670 SetPower(POWER_RUNIC_POWER, 0);
671 SetMaxPower(POWER_RUNIC_POWER, 1000);
674 // original spells
675 learnDefaultSpells();
677 // original action bar
678 for (PlayerCreateInfoActions::const_iterator action_itr = info->action.begin(); action_itr != info->action.end(); ++action_itr)
679 addActionButton(action_itr->button,action_itr->action,action_itr->type);
681 // original items
682 CharStartOutfitEntry const* oEntry = NULL;
683 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
685 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
687 if(entry->RaceClassGender == RaceClassGender)
689 oEntry = entry;
690 break;
695 if(oEntry)
697 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
699 if(oEntry->ItemId[j] <= 0)
700 continue;
702 uint32 item_id = oEntry->ItemId[j];
704 // just skip, reported in ObjectMgr::LoadItemPrototypes
705 ItemPrototype const* iProto = ObjectMgr::GetItemPrototype(item_id);
706 if(!iProto)
707 continue;
709 // BuyCount by default
710 uint32 count = iProto->BuyCount;
712 // special amount for foor/drink
713 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
715 switch(iProto->Spells[0].SpellCategory)
717 case 11: // food
718 count = getClass()==CLASS_DEATH_KNIGHT ? 10 : 4;
719 break;
720 case 59: // drink
721 count = 2;
722 break;
724 if(iProto->Stackable < count)
725 count = iProto->Stackable;
727 // special amount for daggers
728 else if(iProto->Class==ITEM_CLASS_WEAPON && iProto->SubClass==ITEM_SUBCLASS_WEAPON_DAGGER)
730 count = 2; // will placed to 2 slots
733 StoreNewItemInBestSlots(item_id, count);
737 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
738 StoreNewItemInBestSlots(item_id_itr->item_id, item_id_itr->item_amount);
740 // bags and main-hand weapon must equipped at this moment
741 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
742 // or ammo not equipped in special bag
743 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
745 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
747 uint16 eDest;
748 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
749 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
750 if( msg == EQUIP_ERR_OK )
752 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
753 EquipItem( eDest, pItem, true);
755 // move other items to more appropriate slots (ammo not equipped in special bag)
756 else
758 ItemPosCountVec sDest;
759 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
760 if( msg == EQUIP_ERR_OK )
762 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
763 pItem = StoreItem( sDest, pItem, true);
766 // if this is ammo then use it
767 msg = CanUseAmmo( pItem->GetEntry() );
768 if( msg == EQUIP_ERR_OK )
769 SetAmmo( pItem->GetEntry() );
773 // all item positions resolved
775 return true;
778 bool Player::StoreNewItemInBestSlots(uint32 titem_id, uint32 titem_amount)
780 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
782 // attempt equip by one
783 while(titem_amount > 0)
785 uint16 eDest;
786 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, false );
787 if( msg != EQUIP_ERR_OK )
788 break;
790 EquipNewItem( eDest, titem_id, true);
791 AutoUnequipOffhandIfNeed();
792 --titem_amount;
795 if(titem_amount == 0)
796 return true; // equipped
798 // attempt store
799 ItemPosCountVec sDest;
800 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
801 uint8 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
802 if( msg == EQUIP_ERR_OK )
804 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
805 return true; // stored
808 // item can't be added
809 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
810 return false;
813 // helper function, mainly for script side, but can be used for simple task in mangos also.
814 Item* Player::StoreNewItemInInventorySlot(uint32 itemEntry, uint32 amount)
816 ItemPosCountVec vDest;
818 uint8 msg = CanStoreNewItem(INVENTORY_SLOT_BAG_0, NULL_SLOT, vDest, itemEntry, amount);
820 if (msg == EQUIP_ERR_OK)
822 if (Item* pItem = StoreNewItem(vDest, itemEntry, true, Item::GenerateItemRandomPropertyId(itemEntry)))
823 return pItem;
826 return NULL;
829 void Player::SendMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, int32 Regen)
831 if (int(MaxValue) == DISABLED_MIRROR_TIMER)
833 if (int(CurrentValue) != DISABLED_MIRROR_TIMER)
834 StopMirrorTimer(Type);
835 return;
837 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
838 data << (uint32)Type;
839 data << CurrentValue;
840 data << MaxValue;
841 data << Regen;
842 data << (uint8)0;
843 data << (uint32)0; // spell id
844 GetSession()->SendPacket( &data );
847 void Player::StopMirrorTimer(MirrorTimerType Type)
849 m_MirrorTimer[Type] = DISABLED_MIRROR_TIMER;
850 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
851 data << (uint32)Type;
852 GetSession()->SendPacket( &data );
855 uint32 Player::EnvironmentalDamage(EnviromentalDamage type, uint32 damage)
857 if(!isAlive() || isGameMaster())
858 return 0;
860 // Absorb, resist some environmental damage type
861 uint32 absorb = 0;
862 uint32 resist = 0;
863 if (type == DAMAGE_LAVA)
864 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE, DIRECT_DAMAGE, damage, &absorb, &resist);
865 else if (type == DAMAGE_SLIME)
866 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE, DIRECT_DAMAGE, damage, &absorb, &resist);
868 damage-=absorb+resist;
870 DealDamageMods(this,damage,&absorb);
872 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
873 data << uint64(GetGUID());
874 data << uint8(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
875 data << uint32(damage);
876 data << uint32(absorb);
877 data << uint32(resist);
878 SendMessageToSet(&data, true);
880 uint32 final_damage = DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
882 if(!isAlive())
884 if(type==DAMAGE_FALL) // DealDamage not apply item durability loss at self damage
886 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
887 DurabilityLossAll(0.10f,false);
888 // durability lost message
889 WorldPacket data2(SMSG_DURABILITY_DAMAGE_DEATH, 0);
890 GetSession()->SendPacket(&data2);
893 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM, 1, type);
896 return final_damage;
899 int32 Player::getMaxTimer(MirrorTimerType timer)
901 switch (timer)
903 case FATIGUE_TIMER:
904 if (GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_TIMERBAR_FATIGUE_GMLEVEL))
905 return DISABLED_MIRROR_TIMER;
906 return sWorld.getConfig(CONFIG_TIMERBAR_FATIGUE_MAX)*IN_MILISECONDS;
907 case BREATH_TIMER:
909 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING) ||
910 GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_TIMERBAR_BREATH_GMLEVEL))
911 return DISABLED_MIRROR_TIMER;
912 int32 UnderWaterTime = sWorld.getConfig(CONFIG_TIMERBAR_BREATH_MAX)*IN_MILISECONDS;
913 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
914 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
915 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
916 return UnderWaterTime;
918 case FIRE_TIMER:
920 if (!isAlive() || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_TIMERBAR_FIRE_GMLEVEL))
921 return DISABLED_MIRROR_TIMER;
922 return sWorld.getConfig(CONFIG_TIMERBAR_FIRE_MAX)*IN_MILISECONDS;
924 default:
925 return 0;
927 return 0;
930 void Player::UpdateMirrorTimers()
932 // Desync flags for update on next HandleDrowning
933 if (m_MirrorTimerFlags)
934 m_MirrorTimerFlagsLast = ~m_MirrorTimerFlags;
937 void Player::HandleDrowning(uint32 time_diff)
939 if (!m_MirrorTimerFlags)
940 return;
942 // In water
943 if (m_MirrorTimerFlags & UNDERWATER_INWATER)
945 // Breath timer not activated - activate it
946 if (m_MirrorTimer[BREATH_TIMER] == DISABLED_MIRROR_TIMER)
948 m_MirrorTimer[BREATH_TIMER] = getMaxTimer(BREATH_TIMER);
949 SendMirrorTimer(BREATH_TIMER, m_MirrorTimer[BREATH_TIMER], m_MirrorTimer[BREATH_TIMER], -1);
951 else // If activated - do tick
953 m_MirrorTimer[BREATH_TIMER]-=time_diff;
954 // Timer limit - need deal damage
955 if (m_MirrorTimer[BREATH_TIMER] < 0)
957 m_MirrorTimer[BREATH_TIMER]+= 1*IN_MILISECONDS;
958 // Calculate and deal damage
959 // TODO: Check this formula
960 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
961 EnvironmentalDamage(DAMAGE_DROWNING, damage);
963 else if (!(m_MirrorTimerFlagsLast & UNDERWATER_INWATER)) // Update time in client if need
964 SendMirrorTimer(BREATH_TIMER, getMaxTimer(BREATH_TIMER), m_MirrorTimer[BREATH_TIMER], -1);
967 else if (m_MirrorTimer[BREATH_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
969 int32 UnderWaterTime = getMaxTimer(BREATH_TIMER);
970 // Need breath regen
971 m_MirrorTimer[BREATH_TIMER]+=10*time_diff;
972 if (m_MirrorTimer[BREATH_TIMER] >= UnderWaterTime || !isAlive())
973 StopMirrorTimer(BREATH_TIMER);
974 else if (m_MirrorTimerFlagsLast & UNDERWATER_INWATER)
975 SendMirrorTimer(BREATH_TIMER, UnderWaterTime, m_MirrorTimer[BREATH_TIMER], 10);
978 // In dark water
979 if (m_MirrorTimerFlags & UNDERWARER_INDARKWATER)
981 // Fatigue timer not activated - activate it
982 if (m_MirrorTimer[FATIGUE_TIMER] == DISABLED_MIRROR_TIMER)
984 m_MirrorTimer[FATIGUE_TIMER] = getMaxTimer(FATIGUE_TIMER);
985 SendMirrorTimer(FATIGUE_TIMER, m_MirrorTimer[FATIGUE_TIMER], m_MirrorTimer[FATIGUE_TIMER], -1);
987 else
989 m_MirrorTimer[FATIGUE_TIMER]-=time_diff;
990 // Timer limit - need deal damage or teleport ghost to graveyard
991 if (m_MirrorTimer[FATIGUE_TIMER] < 0)
993 m_MirrorTimer[FATIGUE_TIMER]+= 1*IN_MILISECONDS;
994 if (isAlive()) // Calculate and deal damage
996 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
997 EnvironmentalDamage(DAMAGE_EXHAUSTED, damage);
999 else if (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) // Teleport ghost to graveyard
1000 RepopAtGraveyard();
1002 else if (!(m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER))
1003 SendMirrorTimer(FATIGUE_TIMER, getMaxTimer(FATIGUE_TIMER), m_MirrorTimer[FATIGUE_TIMER], -1);
1006 else if (m_MirrorTimer[FATIGUE_TIMER] != DISABLED_MIRROR_TIMER) // Regen timer
1008 int32 DarkWaterTime = getMaxTimer(FATIGUE_TIMER);
1009 m_MirrorTimer[FATIGUE_TIMER]+=10*time_diff;
1010 if (m_MirrorTimer[FATIGUE_TIMER] >= DarkWaterTime || !isAlive())
1011 StopMirrorTimer(FATIGUE_TIMER);
1012 else if (m_MirrorTimerFlagsLast & UNDERWARER_INDARKWATER)
1013 SendMirrorTimer(FATIGUE_TIMER, DarkWaterTime, m_MirrorTimer[FATIGUE_TIMER], 10);
1016 if (m_MirrorTimerFlags & (UNDERWATER_INLAVA|UNDERWATER_INSLIME))
1018 // Breath timer not activated - activate it
1019 if (m_MirrorTimer[FIRE_TIMER] == DISABLED_MIRROR_TIMER)
1020 m_MirrorTimer[FIRE_TIMER] = getMaxTimer(FIRE_TIMER);
1021 else
1023 m_MirrorTimer[FIRE_TIMER]-=time_diff;
1024 if (m_MirrorTimer[FIRE_TIMER] < 0)
1026 m_MirrorTimer[FIRE_TIMER]+= 1*IN_MILISECONDS;
1027 // Calculate and deal damage
1028 // TODO: Check this formula
1029 uint32 damage = urand(600, 700);
1030 if (m_MirrorTimerFlags&UNDERWATER_INLAVA)
1031 EnvironmentalDamage(DAMAGE_LAVA, damage);
1032 else
1033 EnvironmentalDamage(DAMAGE_SLIME, damage);
1037 else
1038 m_MirrorTimer[FIRE_TIMER] = DISABLED_MIRROR_TIMER;
1040 // Recheck timers flag
1041 m_MirrorTimerFlags&=~UNDERWATER_EXIST_TIMERS;
1042 for (int i = 0; i< MAX_TIMERS; ++i)
1043 if (m_MirrorTimer[i]!=DISABLED_MIRROR_TIMER)
1045 m_MirrorTimerFlags|=UNDERWATER_EXIST_TIMERS;
1046 break;
1048 m_MirrorTimerFlagsLast = m_MirrorTimerFlags;
1051 ///The player sobers by 256 every 10 seconds
1052 void Player::HandleSobering()
1054 m_drunkTimer = 0;
1056 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
1057 SetDrunkValue(drunk);
1060 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
1062 if(value >= 23000)
1063 return DRUNKEN_SMASHED;
1064 if(value >= 12800)
1065 return DRUNKEN_DRUNK;
1066 if(value & 0xFFFE)
1067 return DRUNKEN_TIPSY;
1068 return DRUNKEN_SOBER;
1071 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
1073 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1075 m_drunk = newDrunkenValue;
1076 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
1078 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
1080 // special drunk invisibility detection
1081 if(newDrunkenState >= DRUNKEN_DRUNK)
1082 m_detectInvisibilityMask |= (1<<6);
1083 else
1084 m_detectInvisibilityMask &= ~(1<<6);
1086 if(newDrunkenState == oldDrunkenState)
1087 return;
1089 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
1090 data << uint64(GetGUID());
1091 data << uint32(newDrunkenState);
1092 data << uint32(itemId);
1094 SendMessageToSet(&data, true);
1097 void Player::Update( uint32 p_time )
1099 if(!IsInWorld())
1100 return;
1102 // undelivered mail
1103 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
1105 SendNewMail();
1106 ++unReadMails;
1108 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1109 m_nextMailDelivereTime = 0;
1112 //used to implement delayed far teleports
1113 SetCanDelayTeleport(true);
1114 Unit::Update( p_time );
1115 SetCanDelayTeleport(false);
1117 // update player only attacks
1118 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1120 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1123 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1125 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1128 time_t now = time (NULL);
1130 UpdatePvPFlag(now);
1132 UpdateContestedPvP(p_time);
1134 UpdateDuelFlag(now);
1136 CheckDuelDistance(now);
1138 UpdateAfkReport(now);
1140 // Update items that have just a limited lifetime
1141 if (now>m_Last_tick)
1142 UpdateItemDuration(uint32(now- m_Last_tick));
1144 if (!m_timedquests.empty())
1146 std::set<uint32>::iterator iter = m_timedquests.begin();
1147 while (iter != m_timedquests.end())
1149 QuestStatusData& q_status = mQuestStatus[*iter];
1150 if( q_status.m_timer <= p_time )
1152 uint32 quest_id = *iter;
1153 ++iter; // current iter will be removed in FailQuest
1154 FailQuest(quest_id);
1156 else
1158 q_status.m_timer -= p_time;
1159 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1160 ++iter;
1165 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1167 Unit *pVictim = getVictim();
1168 if (pVictim && !IsNonMeleeSpellCasted(false))
1170 // default combat reach 10
1171 // TODO add weapon,skill check
1173 float pldistance = ATTACK_DISTANCE;
1175 if (isAttackReady(BASE_ATTACK))
1177 if(!IsWithinDistInMap(pVictim, pldistance))
1179 setAttackTimer(BASE_ATTACK,100);
1180 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1182 SendAttackSwingNotInRange();
1183 m_swingErrorMsg = 1;
1186 //120 degrees of radiant range
1187 else if( !HasInArc( 2*M_PI/3, pVictim ))
1189 setAttackTimer(BASE_ATTACK,100);
1190 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1192 SendAttackSwingBadFacingAttack();
1193 m_swingErrorMsg = 2;
1196 else
1198 m_swingErrorMsg = 0; // reset swing error state
1200 // prevent base and off attack in same time, delay attack at 0.2 sec
1201 if(haveOffhandWeapon())
1203 uint32 off_att = getAttackTimer(OFF_ATTACK);
1204 if(off_att < ATTACK_DISPLAY_DELAY)
1205 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1207 AttackerStateUpdate(pVictim, BASE_ATTACK);
1208 resetAttackTimer(BASE_ATTACK);
1212 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1214 if(!IsWithinDistInMap(pVictim, pldistance))
1216 setAttackTimer(OFF_ATTACK,100);
1218 else if( !HasInArc( 2*M_PI/3, pVictim ))
1220 setAttackTimer(OFF_ATTACK,100);
1222 else
1224 // prevent base and off attack in same time, delay attack at 0.2 sec
1225 uint32 base_att = getAttackTimer(BASE_ATTACK);
1226 if(base_att < ATTACK_DISPLAY_DELAY)
1227 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1228 // do attack
1229 AttackerStateUpdate(pVictim, OFF_ATTACK);
1230 resetAttackTimer(OFF_ATTACK);
1234 Unit *owner = pVictim->GetOwner();
1235 Unit *u = owner ? owner : pVictim;
1236 if(u->IsPvP() && (!duel || duel->opponent != u))
1238 UpdatePvP(true);
1239 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1244 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1246 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1248 int time_inn = time(NULL)-GetTimeInnEnter();
1249 if (time_inn >= 10) //freeze update
1251 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1252 //speed collect rest bonus (section/in hour)
1253 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1254 UpdateInnerTime(time(NULL));
1259 if (m_regenTimer)
1261 if(p_time >= m_regenTimer)
1262 m_regenTimer = 0;
1263 else
1264 m_regenTimer -= p_time;
1267 if (m_weaponChangeTimer > 0)
1269 if(p_time >= m_weaponChangeTimer)
1270 m_weaponChangeTimer = 0;
1271 else
1272 m_weaponChangeTimer -= p_time;
1275 if (m_zoneUpdateTimer > 0)
1277 if(p_time >= m_zoneUpdateTimer)
1279 uint32 newzone, newarea;
1280 GetZoneAndAreaId(newzone,newarea);
1282 if( m_zoneUpdateId != newzone )
1283 UpdateZone(newzone,newarea); // also update area
1284 else
1286 // use area updates as well
1287 // needed for free far all arenas for example
1288 if( m_areaUpdateId != newarea )
1289 UpdateArea(newarea);
1291 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1294 else
1295 m_zoneUpdateTimer -= p_time;
1298 if (isAlive())
1300 // if no longer casting, set regen power as soon as it is up.
1301 if (!IsUnderLastManaUseEffect())
1302 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
1304 if (!m_regenTimer)
1305 RegenerateAll();
1308 if (m_deathState == JUST_DIED)
1310 KillPlayer();
1313 if(m_nextSave > 0)
1315 if(p_time >= m_nextSave)
1317 // m_nextSave reseted in SaveToDB call
1318 SaveToDB();
1319 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1321 else
1323 m_nextSave -= p_time;
1327 //Handle Water/drowning
1328 HandleDrowning(p_time);
1330 //Handle detect stealth players
1331 if (m_DetectInvTimer > 0)
1333 if (p_time >= m_DetectInvTimer)
1335 HandleStealthedUnitsDetection();
1336 m_DetectInvTimer = 3000;
1338 else
1339 m_DetectInvTimer -= p_time;
1342 // Played time
1343 if (now > m_Last_tick)
1345 uint32 elapsed = uint32(now - m_Last_tick);
1346 m_Played_time[PLAYED_TIME_TOTAL] += elapsed; // Total played time
1347 m_Played_time[PLAYED_TIME_LEVEL] += elapsed; // Level played time
1348 m_Last_tick = now;
1351 if (m_drunk)
1353 m_drunkTimer += p_time;
1355 if (m_drunkTimer > 10*IN_MILISECONDS)
1356 HandleSobering();
1359 // not auto-free ghost from body in instances
1360 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1362 if(p_time >= m_deathTimer)
1364 m_deathTimer = 0;
1365 BuildPlayerRepop();
1366 RepopAtGraveyard();
1368 else
1369 m_deathTimer -= p_time;
1372 UpdateEnchantTime(p_time);
1373 UpdateHomebindTime(p_time);
1375 // group update
1376 SendUpdateToOutOfRangeGroupMembers();
1378 Pet* pet = GetPet();
1379 if(pet && !pet->IsWithinDistInMap(this, GetMap()->GetVisibilityDistance()) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1381 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1384 //we should execute delayed teleports only for alive(!) players
1385 //because we don't want player's ghost teleported from graveyard
1386 if(IsHasDelayedTeleport() && isAlive())
1387 TeleportTo(m_teleport_dest, m_teleport_options);
1390 void Player::setDeathState(DeathState s)
1392 uint32 ressSpellId = 0;
1394 bool cur = isAlive();
1396 if(s == JUST_DIED && cur)
1398 // drunken state is cleared on death
1399 SetDrunkValue(0);
1400 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1401 ClearComboPoints();
1403 clearResurrectRequestData();
1405 // remove form before other mods to prevent incorrect stats calculation
1406 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1408 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1409 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1411 // remove uncontrolled pets
1412 RemoveMiniPet();
1414 // save value before aura remove in Unit::setDeathState
1415 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1417 // passive spell
1418 if(!ressSpellId)
1419 ressSpellId = GetResurrectionSpellId();
1420 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1421 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH, 1);
1422 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON, 1);
1424 Unit::setDeathState(s);
1426 // restore resurrection spell id for player after aura remove
1427 if(s == JUST_DIED && cur && ressSpellId)
1428 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1430 if(isAlive() && !cur)
1432 //clear aura case after resurrection by another way (spells will be applied before next death)
1433 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1435 // restore default warrior stance
1436 if(getClass()== CLASS_WARRIOR)
1437 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1441 bool Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1443 // 0 1 2 3 4 5 6 7
1444 // "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.playerBytes, characters.playerBytes2, characters.level, "
1445 // 8 9 10 11 12 13 14
1446 // "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, "
1447 // 15 16 17 18 19 20
1448 // "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.data, character_declinedname.genitive "
1450 Field *fields = result->Fetch();
1452 uint32 guid = fields[0].GetUInt32();
1453 uint8 pRace = fields[2].GetUInt8();
1454 uint8 pClass = fields[3].GetUInt8();
1456 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(pRace, pClass);
1457 if(!info)
1459 sLog.outError("Player %u has incorrect race/class pair. Don't build enum.", guid);
1460 return false;
1463 *p_data << uint64(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
1464 *p_data << fields[1].GetString(); // name
1465 *p_data << uint8(pRace); // race
1466 *p_data << uint8(pClass); // class
1467 *p_data << uint8(fields[4].GetUInt8()); // gender
1469 uint32 playerBytes = fields[5].GetUInt32();
1470 *p_data << uint8(playerBytes); // skin
1471 *p_data << uint8(playerBytes >> 8); // face
1472 *p_data << uint8(playerBytes >> 16); // hair style
1473 *p_data << uint8(playerBytes >> 24); // hair color
1475 uint32 playerBytes2 = fields[6].GetUInt32();
1476 *p_data << uint8(playerBytes2 & 0xFF); // facial hair
1478 *p_data << uint8(fields[7].GetUInt8()); // level
1479 *p_data << uint32(fields[8].GetUInt32()); // zone
1480 *p_data << uint32(fields[9].GetUInt32()); // map
1482 *p_data << fields[10].GetFloat(); // x
1483 *p_data << fields[11].GetFloat(); // y
1484 *p_data << fields[12].GetFloat(); // z
1486 *p_data << uint32(fields[13].GetUInt32()); // guild id
1488 uint32 char_flags = 0;
1489 uint32 playerFlags = fields[14].GetUInt32();
1490 uint32 atLoginFlags = fields[15].GetUInt32();
1491 if(playerFlags & PLAYER_FLAGS_HIDE_HELM)
1492 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1493 if(playerFlags & PLAYER_FLAGS_HIDE_CLOAK)
1494 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1495 if(playerFlags & PLAYER_FLAGS_GHOST)
1496 char_flags |= CHARACTER_FLAG_GHOST;
1497 if(atLoginFlags & AT_LOGIN_RENAME)
1498 char_flags |= CHARACTER_FLAG_RENAME;
1499 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED))
1501 if(!fields[20].GetCppString().empty())
1502 char_flags |= CHARACTER_FLAG_DECLINED;
1504 else
1505 char_flags |= CHARACTER_FLAG_DECLINED;
1507 *p_data << uint32(char_flags); // character flags
1508 // character customize flags
1509 *p_data << uint32(atLoginFlags & AT_LOGIN_CUSTOMIZE ? CHAR_CUSTOMIZE_FLAG_CUSTOMIZE : CHAR_CUSTOMIZE_FLAG_NONE);
1510 *p_data << uint8(1); // unknown
1512 // Pets info
1514 uint32 petDisplayId = 0;
1515 uint32 petLevel = 0;
1516 uint32 petFamily = 0;
1518 // show pet at selection character in character list only for non-ghost character
1519 if (result && !(playerFlags & PLAYER_FLAGS_GHOST) && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER || pClass == CLASS_DEATH_KNIGHT))
1521 uint32 entry = fields[16].GetUInt32();
1522 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1523 if(cInfo)
1525 petDisplayId = fields[17].GetUInt32();
1526 petLevel = fields[18].GetUInt32();
1527 petFamily = cInfo->family;
1531 *p_data << uint32(petDisplayId);
1532 *p_data << uint32(petLevel);
1533 *p_data << uint32(petFamily);
1536 // TODO: do not access data field here
1537 Tokens data = StrSplit(fields[19].GetCppString(), " ");
1539 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1541 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2);
1542 uint32 item_id = GetUInt32ValueFromArray(data, visualbase);
1543 const ItemPrototype * proto = ObjectMgr::GetItemPrototype(item_id);
1544 if(!proto)
1546 *p_data << uint32(0);
1547 *p_data << uint8(0);
1548 *p_data << uint32(0);
1549 continue;
1552 SpellItemEnchantmentEntry const *enchant = NULL;
1554 uint32 enchants = GetUInt32ValueFromArray(data, visualbase + 1);
1555 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot <= TEMP_ENCHANTMENT_SLOT; ++enchantSlot)
1557 // values stored in 2 uint16
1558 uint32 enchantId = 0x0000FFFF & (enchants >> enchantSlot*16);
1559 if(!enchantId)
1560 continue;
1562 if ((enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId)))
1563 break;
1566 *p_data << uint32(proto->DisplayInfoID);
1567 *p_data << uint8(proto->InventoryType);
1568 *p_data << uint32(enchant ? enchant->aura_id : 0);
1570 *p_data << uint32(0); // first bag display id
1571 *p_data << uint8(0); // first bag inventory type
1572 *p_data << uint32(0); // enchant?
1574 return true;
1577 bool Player::ToggleAFK()
1579 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1581 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1583 // afk player not allowed in battleground
1584 if(state && InBattleGround())
1585 LeaveBattleground();
1587 return state;
1590 bool Player::ToggleDND()
1592 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1594 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1597 uint8 Player::chatTag() const
1599 // it's bitmask
1600 // 0x8 - ??
1601 // 0x4 - gm
1602 // 0x2 - dnd
1603 // 0x1 - afk
1604 if(isGMChat())
1605 return 4;
1606 else if(isDND())
1607 return 3;
1608 if(isAFK())
1609 return 1;
1610 else
1611 return 0;
1614 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1616 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1618 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1619 return false;
1622 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1623 Pet* pet = GetPet();
1625 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1627 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1628 // don't let gm level > 1 either
1629 if(!InBattleGround() && mEntry->IsBattleGroundOrArena())
1630 return false;
1632 // client without expansion support
1633 if(GetSession()->Expansion() < mEntry->Expansion())
1635 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1637 if(GetTransport())
1638 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1640 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1642 return false; // normal client can't teleport to this map...
1644 else
1646 sLog.outDebug("Player %s is being teleported to map %u", GetName(), mapid);
1649 // if we were on a transport, leave
1650 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1652 m_transport->RemovePassenger(this);
1653 m_transport = NULL;
1654 m_movementInfo.SetTransportData(0, 0.0f, 0.0f, 0.0f, 0.0f, 0, -1);
1657 // The player was ported to another map and looses the duel immediately.
1658 // We have to perform this check before the teleport, otherwise the
1659 // ObjectAccessor won't find the flag.
1660 if (duel && GetMapId() != mapid)
1662 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
1663 if (obj)
1664 DuelComplete(DUEL_FLED);
1667 // reset movement flags at teleport, because player will continue move with these flags after teleport
1668 m_movementInfo.SetMovementFlags(MOVEFLAG_NONE);
1670 if ((GetMapId() == mapid) && (!m_transport))
1672 //lets reset far teleport flag if it wasn't reset during chained teleports
1673 SetSemaphoreTeleportFar(false);
1674 //setup delayed teleport flag
1675 SetDelayedTeleportFlag(IsCanDelayTeleport());
1676 //if teleport spell is casted in Unit::Update() func
1677 //then we need to delay it until update process will be finished
1678 if(IsHasDelayedTeleport())
1680 SetSemaphoreTeleportNear(true);
1681 //lets save teleport destination for player
1682 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1683 m_teleport_options = options;
1684 return true;
1687 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1689 //same map, only remove pet if out of range for new position
1690 if(pet && !pet->IsWithinDist3d(x, y, z, GetMap()->GetVisibilityDistance()))
1691 UnsummonPetTemporaryIfAny();
1694 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1695 CombatStop();
1697 // this will be used instead of the current location in SaveToDB
1698 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1699 SetFallInformation(0, z);
1701 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1702 // at client packet MSG_MOVE_TELEPORT_ACK
1703 SetSemaphoreTeleportNear(true);
1704 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1705 if(!GetSession()->PlayerLogout())
1707 WorldPacket data;
1708 BuildTeleportAckMsg(&data, x, y, z, orientation);
1709 GetSession()->SendPacket(&data);
1712 else
1714 // far teleport to another map
1715 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1716 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1718 // Check enter rights before map getting to avoid creating instance copy for player
1719 // this check not dependent from map instance copy and same for all instance copies of selected map
1720 if (!sMapMgr.CanPlayerEnter(mapid, this))
1721 return false;
1723 // If the map is not created, assume it is possible to enter it.
1724 // It will be created in the WorldPortAck.
1725 Map *map = sMapMgr.FindMap(mapid);
1726 if (!map || map->CanEnter(this))
1728 //lets reset near teleport flag if it wasn't reset during chained teleports
1729 SetSemaphoreTeleportNear(false);
1730 //setup delayed teleport flag
1731 SetDelayedTeleportFlag(IsCanDelayTeleport());
1732 //if teleport spell is casted in Unit::Update() func
1733 //then we need to delay it until update process will be finished
1734 if(IsHasDelayedTeleport())
1736 SetSemaphoreTeleportFar(true);
1737 //lets save teleport destination for player
1738 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1739 m_teleport_options = options;
1740 return true;
1743 SetSelection(0);
1745 CombatStop();
1747 ResetContestedPvP();
1749 // remove player from battleground on far teleport (when changing maps)
1750 if(BattleGround const* bg = GetBattleGround())
1752 // Note: at battleground join battleground id set before teleport
1753 // and we already will found "current" battleground
1754 // just need check that this is targeted map or leave
1755 if(bg->GetMapId() != mapid)
1756 LeaveBattleground(false); // don't teleport to entry point
1759 // remove pet on map change
1760 if (pet)
1761 UnsummonPetTemporaryIfAny();
1763 // remove all dyn objects
1764 RemoveAllDynObjects();
1766 // stop spellcasting
1767 // not attempt interrupt teleportation spell at caster teleport
1768 if(!(options & TELE_TO_SPELL))
1769 if(IsNonMeleeSpellCasted(true))
1770 InterruptNonMeleeSpells(true);
1772 //remove auras before removing from map...
1773 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP | AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
1775 if(!GetSession()->PlayerLogout())
1777 // send transfer packets
1778 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1779 data << uint32(mapid);
1780 if (m_transport)
1782 data << uint32(m_transport->GetEntry());
1783 data << uint32(GetMapId());
1785 GetSession()->SendPacket(&data);
1787 data.Initialize(SMSG_NEW_WORLD, (20));
1788 if (m_transport)
1790 data << uint32(mapid);
1791 data << float(m_movementInfo.GetTransportPos()->x);
1792 data << float(m_movementInfo.GetTransportPos()->y);
1793 data << float(m_movementInfo.GetTransportPos()->z);
1794 data << float(m_movementInfo.GetTransportPos()->o);
1796 else
1798 data << uint32(mapid);
1799 data << float(x);
1800 data << float(y);
1801 data << float(z);
1802 data << float(orientation);
1804 GetSession()->SendPacket( &data );
1805 SendSavedInstances();
1808 // remove from old map now
1809 if(oldmap)
1810 oldmap->Remove(this, false);
1812 // new final coordinates
1813 float final_x = x;
1814 float final_y = y;
1815 float final_z = z;
1816 float final_o = orientation;
1818 if(m_transport)
1820 final_x += m_movementInfo.GetTransportPos()->x;
1821 final_y += m_movementInfo.GetTransportPos()->y;
1822 final_z += m_movementInfo.GetTransportPos()->z;
1823 final_o += m_movementInfo.GetTransportPos()->o;
1826 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1827 SetFallInformation(0, final_z);
1828 // if the player is saved before worldport ack (at logout for example)
1829 // this will be used instead of the current location in SaveToDB
1831 // move packet sent by client always after far teleport
1832 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1833 SetSemaphoreTeleportFar(true);
1835 else
1836 return false;
1838 return true;
1841 bool Player::TeleportToBGEntryPoint()
1843 ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE);
1844 ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE);
1845 return TeleportTo(m_bgData.joinPos);
1848 void Player::ProcessDelayedOperations()
1850 if(m_DelayedOperations == 0)
1851 return;
1853 if(m_DelayedOperations & DELAYED_RESURRECT_PLAYER)
1855 ResurrectPlayer(0.0f, false);
1857 if(GetMaxHealth() > m_resurrectHealth)
1858 SetHealth( m_resurrectHealth );
1859 else
1860 SetHealth( GetMaxHealth() );
1862 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
1863 SetPower(POWER_MANA, m_resurrectMana );
1864 else
1865 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
1867 SetPower(POWER_RAGE, 0 );
1868 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
1870 SpawnCorpseBones();
1873 if(m_DelayedOperations & DELAYED_SAVE_PLAYER)
1875 SaveToDB();
1878 if(m_DelayedOperations & DELAYED_SPELL_CAST_DESERTER)
1880 CastSpell(this, 26013, true); // Deserter
1883 if (m_DelayedOperations & DELAYED_BG_MOUNT_RESTORE)
1885 if (m_bgData.mountSpell)
1887 CastSpell(this, m_bgData.mountSpell, true);
1888 m_bgData.mountSpell = 0;
1892 if (m_DelayedOperations & DELAYED_BG_TAXI_RESTORE)
1894 if (m_bgData.HasTaxiPath())
1896 m_taxi.AddTaxiDestination(m_bgData.taxiPath[0]);
1897 m_taxi.AddTaxiDestination(m_bgData.taxiPath[1]);
1898 m_bgData.ClearTaxiPath();
1900 ContinueTaxiFlight();
1904 //we have executed ALL delayed ops, so clear the flag
1905 m_DelayedOperations = 0;
1908 void Player::AddToWorld()
1910 ///- Do not add/remove the player from the object storage
1911 ///- It will crash when updating the ObjectAccessor
1912 ///- The player should only be added when logging in
1913 Unit::AddToWorld();
1915 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1917 if(m_items[i])
1918 m_items[i]->AddToWorld();
1922 void Player::RemoveFromWorld()
1924 // cleanup
1925 if(IsInWorld())
1927 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1928 UnsummonAllTotems();
1929 RemoveMiniPet();
1932 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; ++i)
1934 if(m_items[i])
1935 m_items[i]->RemoveFromWorld();
1938 ///- Do not add/remove the player from the object storage
1939 ///- It will crash when updating the ObjectAccessor
1940 ///- The player should only be removed when logging out
1941 Unit::RemoveFromWorld();
1944 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1946 float addRage;
1948 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1950 if(attacker)
1952 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1954 // talent who gave more rage on attack
1955 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1957 else
1959 addRage = damage/rageconversion*2.5;
1961 // Berserker Rage effect
1962 if(HasAura(18499,0))
1963 addRage *= 1.3;
1966 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1968 ModifyPower(POWER_RAGE, uint32(addRage*10));
1971 void Player::RegenerateAll(uint32 diff)
1973 // Not in combat or they have regeneration
1974 if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1975 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1977 RegenerateHealth(diff);
1978 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1980 Regenerate(POWER_RAGE, diff);
1981 if(getClass() == CLASS_DEATH_KNIGHT)
1982 Regenerate(POWER_RUNIC_POWER, diff);
1986 Regenerate(POWER_ENERGY, diff);
1988 Regenerate(POWER_MANA, diff);
1990 if (getClass() == CLASS_DEATH_KNIGHT)
1991 Regenerate(POWER_RUNE, diff);
1993 m_regenTimer = REGEN_TIME_FULL;
1996 // diff contains the time in milliseconds since last regen.
1997 void Player::Regenerate(Powers power, uint32 diff)
1999 uint32 curValue = GetPower(power);
2000 uint32 maxValue = GetMaxPower(power);
2002 float addvalue = 0.0f;
2004 switch (power)
2006 case POWER_MANA:
2008 bool recentCast = IsUnderLastManaUseEffect();
2009 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
2010 if (recentCast)
2012 // Mangos Updates Mana in intervals of 2s, which is correct
2013 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
2015 else
2017 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
2019 } break;
2020 case POWER_RAGE: // Regenerate rage
2022 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
2023 addvalue = 20 * RageDecreaseRate; // 2 rage by tick (= 2 seconds => 1 rage/sec)
2024 } break;
2025 case POWER_ENERGY: // Regenerate energy (rogue)
2026 addvalue = 20;
2027 break;
2028 case POWER_RUNIC_POWER:
2030 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
2031 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
2032 } break;
2033 case POWER_RUNE:
2035 if (getClass() != CLASS_DEATH_KNIGHT)
2036 break;
2038 for(uint32 i = 0; i < MAX_RUNES; ++i)
2040 if(uint16 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
2041 SetRuneCooldown(i, (cd < diff) ? 0 : cd - diff);
2043 } break;
2044 case POWER_FOCUS:
2045 case POWER_HAPPINESS:
2046 case POWER_HEALTH:
2047 break;
2050 // Mana regen calculated in Player::UpdateManaRegen()
2051 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
2052 if(power != POWER_MANA)
2054 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
2055 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
2056 if ((*i)->GetModifier()->m_miscvalue == power)
2057 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
2060 // addvalue computed on a 2sec basis. => update to diff time
2061 addvalue *= float(diff) / REGEN_TIME_FULL;
2063 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
2065 curValue += uint32(addvalue);
2066 if (curValue > maxValue)
2067 curValue = maxValue;
2069 else
2071 if(curValue <= uint32(addvalue))
2072 curValue = 0;
2073 else
2074 curValue -= uint32(addvalue);
2076 SetPower(power, curValue);
2079 void Player::RegenerateHealth(uint32 diff)
2081 uint32 curValue = GetHealth();
2082 uint32 maxValue = GetMaxHealth();
2084 if (curValue >= maxValue) return;
2086 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
2088 float addvalue = 0.0f;
2090 // polymorphed case
2091 if ( IsPolymorphed() )
2092 addvalue = GetMaxHealth()/3;
2093 // normal regen case (maybe partly in combat case)
2094 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
2096 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
2097 if (!isInCombat())
2099 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
2100 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
2101 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
2103 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
2104 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
2106 if(!IsStandState())
2107 addvalue *= 1.5;
2110 // always regeneration bonus (including combat)
2111 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
2113 if(addvalue < 0)
2114 addvalue = 0;
2116 addvalue *= (float)diff / REGEN_TIME_FULL;
2118 ModifyHealth(int32(addvalue));
2121 Creature* Player::GetNPCIfCanInteractWith(uint64 guid, uint32 npcflagmask)
2123 // unit checks
2124 if (!guid || !IsInWorld() || isInFlight())
2125 return NULL;
2127 // exist (we need look pets also for some interaction (quest/etc)
2128 Creature *unit = GetMap()->GetCreatureOrPetOrVehicle(guid);
2129 if (!unit)
2130 return NULL;
2132 // appropriate npc type
2133 if (npcflagmask && !unit->HasFlag( UNIT_NPC_FLAGS, npcflagmask ))
2134 return NULL;
2136 if (npcflagmask == UNIT_NPC_FLAG_STABLEMASTER)
2138 if (getClass() != CLASS_HUNTER)
2139 return NULL;
2142 // if a dead unit should be able to talk - the creature must be alive and have special flags
2143 if (!unit->isAlive())
2144 return NULL;
2146 if (isAlive() && unit->isInvisibleForAlive())
2147 return NULL;
2149 // not allow interaction under control, but allow with own pets
2150 if (unit->GetCharmerGUID())
2151 return NULL;
2153 // not enemy
2154 if (unit->IsHostileTo(this))
2155 return NULL;
2157 // not unfriendly
2158 if(FactionTemplateEntry const* factionTemplate = sFactionTemplateStore.LookupEntry(unit->getFaction()))
2159 if(factionTemplate->faction)
2160 if(FactionEntry const* faction = sFactionStore.LookupEntry(factionTemplate->faction))
2161 if(faction->reputationListID >= 0 && GetReputationMgr().GetRank(faction) <= REP_UNFRIENDLY)
2162 return NULL;
2164 // not too far
2165 if(!unit->IsWithinDistInMap(this,INTERACTION_DISTANCE))
2166 return NULL;
2168 return unit;
2171 GameObject* Player::GetGameObjectIfCanInteractWith(uint64 guid, uint32 gameobject_type) const
2173 if (GameObject *go = GetMap()->GetGameObject(guid))
2175 if (uint32(go->GetGoType()) == gameobject_type || gameobject_type == MAX_GAMEOBJECT_TYPE)
2177 float maxdist;
2178 switch(go->GetGoType())
2180 // TODO: find out how the client calculates the maximal usage distance to spellless working
2181 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2182 case GAMEOBJECT_TYPE_GUILD_BANK:
2183 case GAMEOBJECT_TYPE_MAILBOX:
2184 maxdist = 10.0f;
2185 break;
2186 case GAMEOBJECT_TYPE_FISHINGHOLE:
2187 maxdist = 20.0f+CONTACT_DISTANCE; // max spell range
2188 break;
2189 default:
2190 maxdist = INTERACTION_DISTANCE;
2191 break;
2194 if (go->IsWithinDistInMap(this, maxdist) && go->isSpawned())
2195 return go;
2197 sLog.outError("GetGameObjectIfCanInteractWith: GameObject '%s' [GUID: %u] is too far away from player %s [GUID: %u] to be used by him (distance=%f, maximal 10 is allowed)", go->GetGOInfo()->name,
2198 go->GetGUIDLow(), GetName(), GetGUIDLow(), go->GetDistance(this));
2201 return NULL;
2204 bool Player::IsUnderWater() const
2206 return IsInWater() &&
2207 GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2210 void Player::SetInWater(bool apply)
2212 if(m_isInWater==apply)
2213 return;
2215 //define player in water by opcodes
2216 //move player's guid into HateOfflineList of those mobs
2217 //which can't swim and move guid back into ThreatList when
2218 //on surface.
2219 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2220 m_isInWater = apply;
2222 // remove auras that need water/land
2223 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
2225 getHostileRefManager().updateThreatTables();
2228 struct SetGameMasterOnHelper
2230 explicit SetGameMasterOnHelper() {}
2231 void operator()(Unit* unit) const
2233 unit->setFaction(35);
2234 unit->getHostileRefManager().setOnlineOfflineState(false);
2238 struct SetGameMasterOffHelper
2240 explicit SetGameMasterOffHelper(uint32 _faction) : faction(_faction) {}
2241 void operator()(Unit* unit) const
2243 unit->setFaction(faction);
2244 unit->getHostileRefManager().setOnlineOfflineState(true);
2246 uint32 faction;
2249 void Player::SetGameMaster(bool on)
2251 if(on)
2253 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
2254 setFaction(35);
2255 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2257 CallForAllControlledUnits(SetGameMasterOnHelper(),true,true,true,false);
2259 SetFFAPvP(false);
2260 ResetContestedPvP();
2262 getHostileRefManager().setOnlineOfflineState(false);
2263 CombatStopWithPets();
2265 SetPhaseMask(PHASEMASK_ANYWHERE,false); // see and visible in all phases
2267 else
2269 // restore phase
2270 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
2271 SetPhaseMask(!phases.empty() ? phases.front()->GetMiscValue() : PHASEMASK_NORMAL,false);
2273 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
2274 setFactionForRace(getRace());
2275 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
2277 CallForAllControlledUnits(SetGameMasterOffHelper(getFaction()),true,true,true,false);
2279 // restore FFA PvP Server state
2280 if(sWorld.IsFFAPvPRealm())
2281 SetFFAPvP(true);
2283 // restore FFA PvP area state, remove not allowed for GM mounts
2284 UpdateArea(m_areaUpdateId);
2286 getHostileRefManager().setOnlineOfflineState(true);
2289 UpdateVisibilityForPlayer();
2292 void Player::SetGMVisible(bool on)
2294 if(on)
2296 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
2298 // Reapply stealth/invisibility if active or show if not any
2299 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2300 SetVisibility(VISIBILITY_GROUP_STEALTH);
2301 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2302 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2303 else
2304 SetVisibility(VISIBILITY_ON);
2306 else
2308 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2310 SetAcceptWhispers(false);
2311 SetGameMaster(true);
2313 SetVisibility(VISIBILITY_OFF);
2317 bool Player::IsGroupVisibleFor(Player* p) const
2319 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2321 default: return IsInSameGroupWith(p);
2322 case 1: return IsInSameRaidWith(p);
2323 case 2: return GetTeam()==p->GetTeam();
2327 bool Player::IsInSameGroupWith(Player const* p) const
2329 return (p==this || (GetGroup() != NULL &&
2330 GetGroup()->SameSubGroup((Player*)this, (Player*)p)));
2333 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2334 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2335 void Player::UninviteFromGroup()
2337 Group* group = GetGroupInvite();
2338 if(!group)
2339 return;
2341 group->RemoveInvite(this);
2343 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2345 if(group->IsCreated())
2347 group->Disband(true);
2348 sObjectMgr.RemoveGroup(group);
2350 else
2351 group->RemoveAllInvites();
2353 delete group;
2357 void Player::RemoveFromGroup(Group* group, uint64 guid)
2359 if(group)
2361 if (group->RemoveMember(guid, 0) <= 1)
2363 // group->Disband(); already disbanded in RemoveMember
2364 sObjectMgr.RemoveGroup(group);
2365 delete group;
2366 // removemember sets the player's group pointer to NULL
2371 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2373 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2374 data << uint64(victim ? victim->GetGUID() : 0); // guid
2375 data << uint32(GivenXP+RestXP); // given experience
2376 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2377 if(victim)
2379 data << uint32(GivenXP); // experience without rested bonus
2380 data << float(1); // 1 - none 0 - 100% group bonus output
2382 data << uint8(0); // new 2.4.0
2383 GetSession()->SendPacket(&data);
2386 void Player::GiveXP(uint32 xp, Unit* victim)
2388 if ( xp < 1 )
2389 return;
2391 if(!isAlive())
2392 return;
2394 uint32 level = getLevel();
2396 // XP to money conversion processed in Player::RewardQuest
2397 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2398 return;
2400 if(victim)
2402 // handle SPELL_AURA_MOD_KILL_XP_PCT auras
2403 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_KILL_XP_PCT);
2404 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2405 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2407 else
2409 // handle SPELL_AURA_MOD_QUEST_XP_PCT auras
2410 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_QUEST_XP_PCT);
2411 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2412 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2415 // XP resting bonus for kill
2416 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2418 SendLogXPGain(xp,victim,rested_bonus_xp);
2420 uint32 curXP = GetUInt32Value(PLAYER_XP);
2421 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2422 uint32 newXP = curXP + xp + rested_bonus_xp;
2424 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2426 newXP -= nextLvlXP;
2428 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2429 GiveLevel(level + 1);
2431 level = getLevel();
2432 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2435 SetUInt32Value(PLAYER_XP, newXP);
2438 // Update player to next level
2439 // Current player experience not update (must be update by caller)
2440 void Player::GiveLevel(uint32 level)
2442 if ( level == getLevel() )
2443 return;
2445 PlayerLevelInfo info;
2446 sObjectMgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2448 PlayerClassLevelInfo classInfo;
2449 sObjectMgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2451 // send levelup info to client
2452 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2453 data << uint32(level);
2454 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2455 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2456 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2457 data << uint32(0);
2458 data << uint32(0);
2459 data << uint32(0);
2460 data << uint32(0);
2461 data << uint32(0);
2462 data << uint32(0);
2463 // end for
2464 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2465 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2467 GetSession()->SendPacket(&data);
2469 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr.GetXPForLevel(level));
2471 //update level, max level of skills
2472 m_Played_time[PLAYED_TIME_LEVEL] = 0; // Level Played Time reset
2474 _ApplyAllLevelScaleItemMods(false);
2476 SetLevel(level);
2478 UpdateSkillsForLevel ();
2480 // save base values (bonuses already included in stored stats
2481 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2482 SetCreateStat(Stats(i), info.stats[i]);
2484 SetCreateHealth(classInfo.basehealth);
2485 SetCreateMana(classInfo.basemana);
2487 InitTalentForLevel();
2488 InitTaxiNodesForLevel();
2489 InitGlyphsForLevel();
2491 UpdateAllStats();
2493 // set current level health and mana/energy to maximum after applying all mods.
2494 SetHealth(GetMaxHealth());
2495 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2496 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2497 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2498 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2499 SetPower(POWER_FOCUS, 0);
2500 SetPower(POWER_HAPPINESS, 0);
2502 _ApplyAllLevelScaleItemMods(true);
2504 // update level to hunter/summon pet
2505 if (Pet* pet = GetPet())
2506 pet->SynchronizeLevelWithOwner();
2508 if (MailLevelReward const* mailReward = sObjectMgr.GetMailLevelReward(level,getRaceMask()))
2509 MailDraft(mailReward->mailTemplateId).SendMailTo(this,MailSender(MAIL_CREATURE,mailReward->senderEntry));
2511 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2514 void Player::InitTalentForLevel()
2516 uint32 level = getLevel();
2517 // talents base at level diff ( talents = level - 9 but some can be used already)
2518 if(level < 10)
2520 // Remove all talent points
2521 if(m_usedTalentCount > 0) // Free any used talents
2523 resetTalents(true);
2524 SetFreeTalentPoints(0);
2527 else
2529 uint32 talentPointsForLevel = CalculateTalentsPoints();
2531 // if used more that have then reset
2532 if(m_usedTalentCount > talentPointsForLevel)
2534 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2535 resetTalents(true);
2536 else
2537 SetFreeTalentPoints(0);
2539 // else update amount of free points
2540 else
2541 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2544 if(!GetSession()->PlayerLoading())
2545 SendTalentsInfoData(false); // update at client
2548 void Player::InitStatsForLevel(bool reapplyMods)
2550 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2551 _RemoveAllStatBonuses();
2553 PlayerClassLevelInfo classInfo;
2554 sObjectMgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2556 PlayerLevelInfo info;
2557 sObjectMgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2559 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2560 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, sObjectMgr.GetXPForLevel(getLevel()));
2562 // reset before any aura state sources (health set/aura apply)
2563 SetUInt32Value(UNIT_FIELD_AURASTATE, 0);
2565 UpdateSkillsForLevel ();
2567 // set default cast time multiplier
2568 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2570 // reset size before reapply auras
2571 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2573 // save base values (bonuses already included in stored stats
2574 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2575 SetCreateStat(Stats(i), info.stats[i]);
2577 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2578 SetStat(Stats(i), info.stats[i]);
2580 SetCreateHealth(classInfo.basehealth);
2582 //set create powers
2583 SetCreateMana(classInfo.basemana);
2585 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2587 InitStatBuffMods();
2589 //reset rating fields values
2590 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2591 SetUInt32Value(index, 0);
2593 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2594 for (int i = 0; i < 7; ++i)
2596 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2597 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2598 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2601 //reset attack power, damage and attack speed fields
2602 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2603 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2604 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2606 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2607 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2608 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2609 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2610 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2611 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2613 SetInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2614 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2615 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2616 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2617 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2618 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2620 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2621 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2622 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2623 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2625 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2626 for (uint8 i = 0; i < 7; ++i)
2627 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2629 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2630 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2631 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2633 // Dodge percentage
2634 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2636 // set armor (resistance 0) to original value (create_agility*2)
2637 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2638 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2639 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2640 // set other resistance to original value (0)
2641 for (int i = 1; i < MAX_SPELL_SCHOOL; ++i)
2643 SetResistance(SpellSchools(i), 0);
2644 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2645 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2648 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2649 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2650 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2652 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER+i,0);
2653 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2655 // Reset no reagent cost field
2656 for(int i = 0; i < 3; ++i)
2657 SetUInt32Value(PLAYER_NO_REAGENT_COST_1 + i, 0);
2658 // Init data for form but skip reapply item mods for form
2659 InitDataForForm(reapplyMods);
2661 // save new stats
2662 for (int i = POWER_MANA; i < MAX_POWERS; ++i)
2663 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2665 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2667 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2668 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2670 // cleanup unit flags (will be re-applied if need at aura load).
2671 RemoveFlag( UNIT_FIELD_FLAGS,
2672 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2673 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2674 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2675 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2676 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2677 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2679 SetFlag(UNIT_FIELD_FLAGS_2,UNIT_FLAG2_REGENERATE_POWER);// must be set
2681 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2682 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST);
2684 RemoveStandFlags(UNIT_STAND_FLAGS_ALL); // one form stealth modified bytes
2685 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_FFA_PVP | UNIT_BYTE2_FLAG_SANCTUARY);
2687 // restore if need some important flags
2688 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2690 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2691 _ApplyAllStatBonuses();
2693 // set current level health and mana/energy to maximum after applying all mods.
2694 SetHealth(GetMaxHealth());
2695 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2696 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2697 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2698 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2699 SetPower(POWER_FOCUS, 0);
2700 SetPower(POWER_HAPPINESS, 0);
2701 SetPower(POWER_RUNIC_POWER, 0);
2703 // update level to hunter/summon pet
2704 if (Pet* pet = GetPet())
2705 pet->SynchronizeLevelWithOwner();
2708 void Player::SendInitialSpells()
2710 time_t curTime = time(NULL);
2711 time_t infTime = curTime + infinityCooldownDelayCheck;
2713 uint16 spellCount = 0;
2715 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2716 data << uint8(0);
2718 size_t countPos = data.wpos();
2719 data << uint16(spellCount); // spell count placeholder
2721 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2723 if(itr->second->state == PLAYERSPELL_REMOVED)
2724 continue;
2726 if(!itr->second->active || itr->second->disabled)
2727 continue;
2729 data << uint32(itr->first);
2730 data << uint16(0); // it's not slot id
2732 spellCount +=1;
2735 data.put<uint16>(countPos,spellCount); // write real count value
2737 uint16 spellCooldowns = m_spellCooldowns.size();
2738 data << uint16(spellCooldowns);
2739 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2741 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2742 if(!sEntry)
2743 continue;
2745 data << uint32(itr->first);
2747 data << uint16(itr->second.itemid); // cast item id
2748 data << uint16(sEntry->Category); // spell category
2750 // send infinity cooldown in special format
2751 if(itr->second.end >= infTime)
2753 data << uint32(1); // cooldown
2754 data << uint32(0x80000000); // category cooldown
2755 continue;
2758 time_t cooldown = itr->second.end > curTime ? (itr->second.end-curTime)*IN_MILISECONDS : 0;
2760 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2762 data << uint32(0); // cooldown
2763 data << uint32(cooldown); // category cooldown
2765 else
2767 data << uint32(cooldown); // cooldown
2768 data << uint32(0); // category cooldown
2772 GetSession()->SendPacket(&data);
2774 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2777 void Player::RemoveMail(uint32 id)
2779 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2781 if ((*itr)->messageID == id)
2783 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2784 m_mail.erase(itr);
2785 return;
2790 void Player::SendMailResult(uint32 mailId, MailResponseType mailAction, MailResponseResult mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2792 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_EQUIP_ERROR?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2793 data << (uint32) mailId;
2794 data << (uint32) mailAction;
2795 data << (uint32) mailError;
2796 if ( mailError == MAIL_ERR_EQUIP_ERROR )
2797 data << (uint32) equipError;
2798 else if( mailAction == MAIL_ITEM_TAKEN )
2800 data << (uint32) item_guid; // item guid low?
2801 data << (uint32) item_count; // item count?
2803 GetSession()->SendPacket(&data);
2806 void Player::SendNewMail()
2808 // deliver undelivered mail
2809 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2810 data << (uint32) 0;
2811 GetSession()->SendPacket(&data);
2814 void Player::UpdateNextMailTimeAndUnreads()
2816 // calculate next delivery time (min. from non-delivered mails
2817 // and recalculate unReadMail
2818 time_t cTime = time(NULL);
2819 m_nextMailDelivereTime = 0;
2820 unReadMails = 0;
2821 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2823 if((*itr)->deliver_time > cTime)
2825 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2826 m_nextMailDelivereTime = (*itr)->deliver_time;
2828 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2829 ++unReadMails;
2833 void Player::AddNewMailDeliverTime(time_t deliver_time)
2835 if(deliver_time <= time(NULL)) // ready now
2837 ++unReadMails;
2838 SendNewMail();
2840 else // not ready and no have ready mails
2842 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2843 m_nextMailDelivereTime = deliver_time;
2847 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool dependent, bool disabled)
2849 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2850 if (!spellInfo)
2852 // do character spell book cleanup (all characters)
2853 if(!IsInWorld() && !learning) // spell load case
2855 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2856 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2858 else
2859 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2861 return false;
2864 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2866 // do character spell book cleanup (all characters)
2867 if(!IsInWorld() && !learning) // spell load case
2869 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2870 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2872 else
2873 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2875 return false;
2878 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2880 bool dependent_set = false;
2881 bool disabled_case = false;
2882 bool superceded_old = false;
2884 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2885 if (itr != m_spells.end())
2887 uint32 next_active_spell_id = 0;
2888 // fix activate state for non-stackable low rank (and find next spell for !active case)
2889 if(!SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
2891 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
2892 for(SpellChainMapNext::const_iterator next_itr = nextMap.lower_bound(spell_id); next_itr != nextMap.upper_bound(spell_id); ++next_itr)
2894 if(HasSpell(next_itr->second))
2896 // high rank already known so this must !active
2897 active = false;
2898 next_active_spell_id = next_itr->second;
2899 break;
2904 // not do anything if already known in expected state
2905 if(itr->second->state != PLAYERSPELL_REMOVED && itr->second->active == active &&
2906 itr->second->dependent == dependent && itr->second->disabled == disabled)
2908 if(!IsInWorld() && !learning) // explicitly load from DB and then exist in it already and set correctly
2909 itr->second->state = PLAYERSPELL_UNCHANGED;
2911 return false;
2914 // dependent spell known as not dependent, overwrite state
2915 if (itr->second->state != PLAYERSPELL_REMOVED && !itr->second->dependent && dependent)
2917 itr->second->dependent = dependent;
2918 if (itr->second->state != PLAYERSPELL_NEW)
2919 itr->second->state = PLAYERSPELL_CHANGED;
2920 dependent_set = true;
2923 // update active state for known spell
2924 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2926 itr->second->active = active;
2928 if(!IsInWorld() && !learning && !dependent_set) // explicitly load from DB and then exist in it already and set correctly
2929 itr->second->state = PLAYERSPELL_UNCHANGED;
2930 else if(itr->second->state != PLAYERSPELL_NEW)
2931 itr->second->state = PLAYERSPELL_CHANGED;
2933 if(active)
2935 if (IsPassiveSpell(spell_id) && IsNeedCastPassiveSpellAtLearn(spellInfo))
2936 CastSpell (this,spell_id,true);
2938 else if(IsInWorld())
2940 if(next_active_spell_id)
2942 // update spell ranks in spellbook and action bar
2943 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
2944 data << uint32(spell_id);
2945 data << uint32(next_active_spell_id);
2946 GetSession()->SendPacket( &data );
2948 else
2950 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2951 data << uint32(spell_id);
2952 GetSession()->SendPacket(&data);
2956 return active; // learn (show in spell book if active now)
2959 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2961 if(itr->second->state != PLAYERSPELL_NEW)
2962 itr->second->state = PLAYERSPELL_CHANGED;
2963 itr->second->disabled = disabled;
2965 if(disabled)
2966 return false;
2968 disabled_case = true;
2970 else switch(itr->second->state)
2972 case PLAYERSPELL_UNCHANGED: // known saved spell
2973 return false;
2974 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2976 delete itr->second;
2977 m_spells.erase(itr);
2978 state = PLAYERSPELL_CHANGED;
2979 break; // need re-add
2981 default: // known not saved yet spell (new or modified)
2983 // can be in case spell loading but learned at some previous spell loading
2984 if(!IsInWorld() && !learning && !dependent_set)
2985 itr->second->state = PLAYERSPELL_UNCHANGED;
2987 return false;
2992 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2994 // talent: unlearn all other talent ranks (high and low)
2995 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2997 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2999 for(int i=0; i < MAX_TALENT_RANK; ++i)
3001 // skip learning spell and no rank spell case
3002 uint32 rankSpellId = talentInfo->RankID[i];
3003 if(!rankSpellId || rankSpellId==spell_id)
3004 continue;
3006 removeSpell(rankSpellId,false,false);
3010 // non talent spell: learn low ranks (recursive call)
3011 else if(uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id))
3013 if(!IsInWorld() || disabled) // at spells loading, no output, but allow save
3014 addSpell(prev_spell,active,true,true,disabled);
3015 else // at normal learning
3016 learnSpell(prev_spell,true);
3019 PlayerSpell *newspell = new PlayerSpell;
3020 newspell->state = state;
3021 newspell->active = active;
3022 newspell->dependent = dependent;
3023 newspell->disabled = disabled;
3025 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
3026 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
3028 for( PlayerSpellMap::iterator itr2 = m_spells.begin(); itr2 != m_spells.end(); ++itr2 )
3030 if(itr2->second->state == PLAYERSPELL_REMOVED) continue;
3031 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr2->first);
3032 if(!i_spellInfo) continue;
3034 if( sSpellMgr.IsRankSpellDueToSpell(spellInfo,itr2->first) )
3036 if(itr2->second->active)
3038 if(sSpellMgr.IsHighRankOfSpell(spell_id,itr2->first))
3040 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
3042 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3043 data << uint32(itr2->first);
3044 data << uint32(spell_id);
3045 GetSession()->SendPacket( &data );
3048 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
3049 itr2->second->active = false;
3050 if(itr2->second->state != PLAYERSPELL_NEW)
3051 itr2->second->state = PLAYERSPELL_CHANGED;
3052 superceded_old = true; // new spell replace old in action bars and spell book.
3054 else if(sSpellMgr.IsHighRankOfSpell(itr2->first,spell_id))
3056 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
3058 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3059 data << uint32(spell_id);
3060 data << uint32(itr2->first);
3061 GetSession()->SendPacket( &data );
3064 // mark new spell as disable (not learned yet for client and will not learned)
3065 newspell->active = false;
3066 if(newspell->state != PLAYERSPELL_NEW)
3067 newspell->state = PLAYERSPELL_CHANGED;
3074 m_spells[spell_id] = newspell;
3076 // return false if spell disabled
3077 if (newspell->disabled)
3078 return false;
3081 uint32 talentCost = GetTalentSpellCost(spell_id);
3083 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
3084 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
3085 if (talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL))
3087 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
3088 CastSpell(this, spell_id, true);
3090 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
3091 else if (IsPassiveSpell(spell_id))
3093 if (IsNeedCastPassiveSpellAtLearn(spellInfo))
3094 CastSpell(this, spell_id, true);
3096 else if (IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP))
3098 CastSpell(this, spell_id, true);
3099 return false;
3102 // update used talent points count
3103 m_usedTalentCount += talentCost;
3105 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
3106 if (uint32 freeProfs = GetFreePrimaryProfessionPoints())
3108 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3109 SetFreePrimaryProfessions(freeProfs-1);
3112 // add dependent skills
3113 uint16 maxskill = GetMaxSkillValueForLevel();
3115 SpellLearnSkillNode const* spellLearnSkill = sSpellMgr.GetSpellLearnSkill(spell_id);
3117 SkillLineAbilityMapBounds skill_bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
3119 if (spellLearnSkill)
3121 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
3122 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
3124 if (skill_value < spellLearnSkill->value)
3125 skill_value = spellLearnSkill->value;
3127 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
3129 if (skill_max_value < new_skill_max_value)
3130 skill_max_value = new_skill_max_value;
3132 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
3134 else
3136 // not ranked skills
3137 for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
3139 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3140 if (!pSkill)
3141 continue;
3143 if (HasSkill(pSkill->id))
3144 continue;
3146 if (_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
3147 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3148 ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
3150 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
3152 case SKILL_RANGE_LANGUAGE:
3153 SetSkill(pSkill->id, 300, 300 );
3154 break;
3155 case SKILL_RANGE_LEVEL:
3156 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
3157 break;
3158 case SKILL_RANGE_MONO:
3159 SetSkill(pSkill->id, 1, 1 );
3160 break;
3161 default:
3162 break;
3168 // learn dependent spells
3169 SpellLearnSpellMapBounds spell_bounds = sSpellMgr.GetSpellLearnSpellMapBounds(spell_id);
3171 for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
3173 if (!itr2->second.autoLearned)
3175 if (!IsInWorld() || !itr2->second.active) // at spells loading, no output, but allow save
3176 addSpell(itr2->second.spell,itr2->second.active,true,true,false);
3177 else // at normal learning
3178 learnSpell(itr2->second.spell,true);
3182 if (!GetSession()->PlayerLoading())
3184 // not ranked skills
3185 for(SkillLineAbilityMap::const_iterator _spell_idx = skill_bounds.first; _spell_idx != skill_bounds.second; ++_spell_idx)
3187 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE,_spell_idx->second->skillId);
3188 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS,_spell_idx->second->skillId);
3191 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL,spell_id);
3194 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
3195 return active && !disabled && !superceded_old;
3198 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry const* spellInfo) const
3200 // note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell
3201 // talent dependent passives activated at form apply have proper stance data
3202 bool need_cast = (!spellInfo->Stances || (m_form != 0 && (spellInfo->Stances & (1<<(m_form-1)))));
3204 //Check CasterAuraStates
3205 return need_cast && (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)));
3208 void Player::learnSpell(uint32 spell_id, bool dependent)
3210 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3212 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
3213 bool active = disabled ? itr->second->active : true;
3215 bool learning = addSpell(spell_id,active,true,dependent,false);
3217 // learn all disabled higher ranks (recursive)
3218 if(disabled)
3220 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
3221 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
3223 PlayerSpellMap::iterator iter = m_spells.find(i->second);
3224 if (iter != m_spells.end() && iter->second->disabled)
3225 learnSpell(i->second,false);
3229 // prevent duplicated entires in spell book, also not send if not in world (loading)
3230 if(!learning || !IsInWorld ())
3231 return;
3233 WorldPacket data(SMSG_LEARNED_SPELL, 4);
3234 data << uint32(spell_id);
3235 GetSession()->SendPacket(&data);
3238 void Player::removeSpell(uint32 spell_id, bool disabled, bool learn_low_rank, bool sendUpdate)
3240 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3241 if (itr == m_spells.end())
3242 return;
3244 if (itr->second->state == PLAYERSPELL_REMOVED || (disabled && itr->second->disabled))
3245 return;
3247 // unlearn non talent higher ranks (recursive)
3248 SpellChainMapNext const& nextMap = sSpellMgr.GetSpellChainNext();
3249 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
3250 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
3251 removeSpell(itr2->second,disabled,false);
3253 // re-search, it can be corrupted in prev loop
3254 itr = m_spells.find(spell_id);
3255 if (itr == m_spells.end())
3256 return; // already unleared
3258 bool cur_active = itr->second->active;
3259 bool cur_dependent = itr->second->dependent;
3261 if (disabled)
3263 itr->second->disabled = disabled;
3264 if(itr->second->state != PLAYERSPELL_NEW)
3265 itr->second->state = PLAYERSPELL_CHANGED;
3267 else
3269 if(itr->second->state == PLAYERSPELL_NEW)
3271 delete itr->second;
3272 m_spells.erase(itr);
3274 else
3275 itr->second->state = PLAYERSPELL_REMOVED;
3278 RemoveAurasDueToSpell(spell_id);
3280 // remove pet auras
3281 for(int i = 0; i < 3; ++i)
3282 if(PetAura const* petSpell = sSpellMgr.GetPetAura(spell_id, i))
3283 RemovePetAura(petSpell);
3285 // free talent points
3286 uint32 talentCosts = GetTalentSpellCost(spell_id);
3287 if(talentCosts > 0)
3289 if(talentCosts < m_usedTalentCount)
3290 m_usedTalentCount -= talentCosts;
3291 else
3292 m_usedTalentCount = 0;
3295 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3296 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell_id))
3298 uint32 freeProfs = GetFreePrimaryProfessionPoints()+1;
3299 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
3300 SetFreePrimaryProfessions(freeProfs);
3303 // remove dependent skill
3304 SpellLearnSkillNode const* spellLearnSkill = sSpellMgr.GetSpellLearnSkill(spell_id);
3305 if(spellLearnSkill)
3307 uint32 prev_spell = sSpellMgr.GetPrevSpellInChain(spell_id);
3308 if(!prev_spell) // first rank, remove skill
3309 SetSkill(spellLearnSkill->skill,0,0);
3310 else
3312 // search prev. skill setting by spell ranks chain
3313 SpellLearnSkillNode const* prevSkill = sSpellMgr.GetSpellLearnSkill(prev_spell);
3314 while(!prevSkill && prev_spell)
3316 prev_spell = sSpellMgr.GetPrevSpellInChain(prev_spell);
3317 prevSkill = sSpellMgr.GetSpellLearnSkill(sSpellMgr.GetFirstSpellInChain(prev_spell));
3320 if (!prevSkill) // not found prev skill setting, remove skill
3321 SetSkill(spellLearnSkill->skill,0,0);
3322 else // set to prev. skill setting values
3324 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
3325 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
3327 if (skill_value > prevSkill->value)
3328 skill_value = prevSkill->value;
3330 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
3332 if (skill_max_value > new_skill_max_value)
3333 skill_max_value = new_skill_max_value;
3335 SetSkill(prevSkill->skill,skill_value,skill_max_value);
3340 else
3342 // not ranked skills
3343 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
3345 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
3347 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
3348 if (!pSkill)
3349 continue;
3351 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL &&
3352 pSkill->categoryId != SKILL_CATEGORY_CLASS ||// not unlearn class skills (spellbook/talent pages)
3353 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3354 ((pSkill->id==SKILL_LOCKPICKING || pSkill->id==SKILL_RUNEFORGING) && _spell_idx->second->max_value==0))
3356 // not reset skills for professions and racial abilities
3357 if ((pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
3358 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0))
3359 continue;
3361 SetSkill(pSkill->id, 0, 0 );
3366 // remove dependent spells
3367 SpellLearnSpellMapBounds spell_bounds = sSpellMgr.GetSpellLearnSpellMapBounds(spell_id);
3369 for(SpellLearnSpellMap::const_iterator itr2 = spell_bounds.first; itr2 != spell_bounds.second; ++itr2)
3370 removeSpell(itr2->second.spell, disabled);
3372 // activate lesser rank in spellbook/action bar, and cast it if need
3373 bool prev_activate = false;
3375 if (uint32 prev_id = sSpellMgr.GetPrevSpellInChain (spell_id))
3377 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
3379 // if talent then lesser rank also talent and need learn
3380 if (talentCosts)
3382 if(learn_low_rank)
3383 learnSpell (prev_id,false);
3385 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3386 else if (cur_active && !SpellMgr::canStackSpellRanks(spellInfo) && sSpellMgr.GetSpellRank(spellInfo->Id) != 0)
3388 // need manually update dependence state (learn spell ignore like attempts)
3389 PlayerSpellMap::iterator prev_itr = m_spells.find(prev_id);
3390 if (prev_itr != m_spells.end())
3392 if (prev_itr->second->dependent != cur_dependent)
3394 prev_itr->second->dependent = cur_dependent;
3395 if (prev_itr->second->state != PLAYERSPELL_NEW)
3396 prev_itr->second->state = PLAYERSPELL_CHANGED;
3399 // now re-learn if need re-activate
3400 if (cur_active && !prev_itr->second->active && learn_low_rank)
3402 if (addSpell(prev_id,true,false,prev_itr->second->dependent,prev_itr->second->disabled))
3404 // downgrade spell ranks in spellbook and action bar
3405 WorldPacket data(SMSG_SUPERCEDED_SPELL, 4 + 4);
3406 data << uint32(spell_id);
3407 data << uint32(prev_id);
3408 GetSession()->SendPacket( &data );
3409 prev_activate = true;
3416 // remove from spell book if not replaced by lesser rank
3417 if (!prev_activate && sendUpdate)
3419 WorldPacket data(SMSG_REMOVED_SPELL, 4);
3420 data << uint32(spell_id);
3421 GetSession()->SendPacket(&data);
3425 void Player::RemoveSpellCooldown( uint32 spell_id, bool update /* = false */ )
3427 m_spellCooldowns.erase(spell_id);
3429 if(update)
3430 SendClearCooldown(spell_id, this);
3433 void Player::RemoveSpellCategoryCooldown(uint32 cat, bool update /* = false */)
3435 SpellCategoryStore::const_iterator ct = sSpellCategoryStore.find(cat);
3436 if (ct == sSpellCategoryStore.end())
3437 return;
3439 const SpellCategorySet& ct_set = ct->second;
3440 for (SpellCooldowns::const_iterator i = m_spellCooldowns.begin(); i != m_spellCooldowns.end();)
3442 if (ct_set.find(i->first) != ct_set.end())
3443 RemoveSpellCooldown((i++)->first, update);
3444 else
3445 ++i;
3449 void Player::RemoveArenaSpellCooldowns()
3451 // remove cooldowns on spells that has < 15 min CD
3452 SpellCooldowns::iterator itr, next;
3453 // iterate spell cooldowns
3454 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
3456 next = itr;
3457 ++next;
3458 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3459 // check if spellentry is present and if the cooldown is less than 15 mins
3460 if( entry &&
3461 entry->RecoveryTime <= 15 * MINUTE * IN_MILISECONDS &&
3462 entry->CategoryRecoveryTime <= 15 * MINUTE * IN_MILISECONDS )
3464 // remove & notify
3465 RemoveSpellCooldown(itr->first, true);
3470 void Player::RemoveAllSpellCooldown()
3472 if(!m_spellCooldowns.empty())
3474 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3475 SendClearCooldown(itr->first, this);
3477 m_spellCooldowns.clear();
3481 void Player::_LoadSpellCooldowns(QueryResult *result)
3483 // some cooldowns can be already set at aura loading...
3485 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3487 if(result)
3489 time_t curTime = time(NULL);
3493 Field *fields = result->Fetch();
3495 uint32 spell_id = fields[0].GetUInt32();
3496 uint32 item_id = fields[1].GetUInt32();
3497 time_t db_time = (time_t)fields[2].GetUInt64();
3499 if(!sSpellStore.LookupEntry(spell_id))
3501 sLog.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3502 continue;
3505 // skip outdated cooldown
3506 if(db_time <= curTime)
3507 continue;
3509 AddSpellCooldown(spell_id, item_id, db_time);
3511 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3513 while( result->NextRow() );
3515 delete result;
3519 void Player::_SaveSpellCooldowns()
3521 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3523 time_t curTime = time(NULL);
3524 time_t infTime = curTime + infinityCooldownDelayCheck;
3526 /* copied following sql-code partly from achievementmgr */
3527 bool first_round = true;
3528 std::ostringstream ss;
3530 // remove outdated and save active
3531 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3533 if(itr->second.end <= curTime)
3534 m_spellCooldowns.erase(itr++);
3535 else if(itr->second.end <= infTime) // not save locked cooldowns, it will be reset or set at reload
3537 if (first_round)
3539 ss << "INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ";
3540 first_round = false;
3542 // next new/changed record prefix
3543 else
3544 ss << ", ";
3545 ss << "(" << GetGUIDLow() << "," << itr->first << "," << itr->second.itemid << "," << uint64(itr->second.end) << ")";
3546 ++itr;
3548 else
3549 ++itr;
3552 // if something changed execute
3553 if (!first_round)
3554 CharacterDatabase.Execute( ss.str().c_str() );
3557 uint32 Player::resetTalentsCost() const
3559 // The first time reset costs 1 gold
3560 if(m_resetTalentsCost < 1*GOLD)
3561 return 1*GOLD;
3562 // then 5 gold
3563 else if(m_resetTalentsCost < 5*GOLD)
3564 return 5*GOLD;
3565 // After that it increases in increments of 5 gold
3566 else if(m_resetTalentsCost < 10*GOLD)
3567 return 10*GOLD;
3568 else
3570 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3571 if(months > 0)
3573 // This cost will be reduced by a rate of 5 gold per month
3574 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3575 // to a minimum of 10 gold.
3576 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3578 else
3580 // After that it increases in increments of 5 gold
3581 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3582 // until it hits a cap of 50 gold.
3583 if(new_cost > 50*GOLD)
3584 new_cost = 50*GOLD;
3585 return new_cost;
3590 bool Player::resetTalents(bool no_cost)
3592 // not need after this call
3593 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3594 RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS,true);
3596 uint32 talentPointsForLevel = CalculateTalentsPoints();
3598 if (m_usedTalentCount == 0)
3600 SetFreeTalentPoints(talentPointsForLevel);
3601 return false;
3604 uint32 cost = 0;
3606 if(!no_cost)
3608 cost = resetTalentsCost();
3610 if (GetMoney() < cost)
3612 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3613 return false;
3617 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); ++i)
3619 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3621 if (!talentInfo) continue;
3623 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3625 if(!talentTabInfo)
3626 continue;
3628 // unlearn only talents for character class
3629 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3630 // to prevent unexpected lost normal learned spell skip another class talents
3631 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3632 continue;
3634 for (int j = 0; j < MAX_TALENT_RANK; ++j)
3636 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3638 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3640 ++itr;
3641 continue;
3644 // remove learned spells (all ranks)
3645 uint32 itrFirstId = sSpellMgr.GetFirstSpellInChain(itr->first);
3647 // unlearn if first rank is talent or learned by talent
3648 if (itrFirstId == talentInfo->RankID[j])
3650 removeSpell(itr->first,!IsPassiveSpell(itr->first),false);
3651 itr = GetSpellMap().begin();
3652 continue;
3654 else if (sSpellMgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3656 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3657 itr = GetSpellMap().begin();
3658 continue;
3660 else
3661 ++itr;
3666 SetFreeTalentPoints(talentPointsForLevel);
3668 if(!no_cost)
3670 ModifyMoney(-(int32)cost);
3671 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS, cost);
3672 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS, 1);
3674 m_resetTalentsCost = cost;
3675 m_resetTalentsTime = time(NULL);
3678 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3679 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3680 /* when prev line will dropped use next line
3681 if(Pet* pet = GetPet())
3683 if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
3684 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3689 if(m_canTitanGrip)
3691 m_canTitanGrip = false;
3692 if(sWorld.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET))
3693 AutoUnequipOffhandIfNeed();
3696 return true;
3699 Mail* Player::GetMail(uint32 id)
3701 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3703 if ((*itr)->messageID == id)
3705 return (*itr);
3708 return NULL;
3711 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3713 if(target == this)
3715 Object::_SetCreateBits(updateMask, target);
3717 else
3719 for(uint16 index = 0; index < m_valuesCount; index++)
3721 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3722 updateMask->SetBit(index);
3727 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3729 if(target == this)
3731 Object::_SetUpdateBits(updateMask, target);
3733 else
3735 Object::_SetUpdateBits(updateMask, target);
3736 *updateMask &= updateVisualBits;
3740 void Player::InitVisibleBits()
3742 updateVisualBits.SetCount(PLAYER_END);
3744 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3745 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3746 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3747 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3748 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3749 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3750 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3751 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3752 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3753 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3754 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3755 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3756 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3757 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3758 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3759 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3760 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3761 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3762 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3763 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3764 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3765 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3766 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3767 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3768 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3769 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3770 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3771 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3772 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3773 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3774 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3775 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3776 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3777 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3778 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3779 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3780 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3781 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3782 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3783 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3784 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3785 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3786 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3787 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3788 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3789 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3790 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3791 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3792 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3793 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3794 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3795 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3796 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3797 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3798 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3800 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3801 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3802 updateVisualBits.SetBit(PLAYER_FLAGS);
3803 updateVisualBits.SetBit(PLAYER_GUILDID);
3804 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3805 updateVisualBits.SetBit(PLAYER_BYTES);
3806 updateVisualBits.SetBit(PLAYER_BYTES_2);
3807 updateVisualBits.SetBit(PLAYER_BYTES_3);
3808 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3809 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3811 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3812 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += MAX_QUEST_OFFSET)
3813 updateVisualBits.SetBit(i);
3815 // Players visible items are not inventory stuff
3816 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3818 uint32 offset = i * 2;
3820 // item entry
3821 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID + offset);
3822 // enchant
3823 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + offset);
3826 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3829 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3831 for(int i = 0; i < EQUIPMENT_SLOT_END; ++i)
3833 if(m_items[i] == NULL)
3834 continue;
3836 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3839 if(target == this)
3841 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3843 if(m_items[i] == NULL)
3844 continue;
3846 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3848 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3850 if(m_items[i] == NULL)
3851 continue;
3853 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3857 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3860 void Player::DestroyForPlayer( Player *target, bool anim ) const
3862 Unit::DestroyForPlayer( target, anim );
3864 for(int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
3866 if(m_items[i] == NULL)
3867 continue;
3869 m_items[i]->DestroyForPlayer( target );
3872 if(target == this)
3874 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
3876 if(m_items[i] == NULL)
3877 continue;
3879 m_items[i]->DestroyForPlayer( target );
3881 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
3883 if(m_items[i] == NULL)
3884 continue;
3886 m_items[i]->DestroyForPlayer( target );
3891 bool Player::HasSpell(uint32 spell) const
3893 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3894 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3895 !itr->second->disabled);
3898 bool Player::HasActiveSpell(uint32 spell) const
3900 PlayerSpellMap::const_iterator itr = m_spells.find(spell);
3901 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED &&
3902 itr->second->active && !itr->second->disabled);
3905 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3907 if (!trainer_spell)
3908 return TRAINER_SPELL_RED;
3910 if (!trainer_spell->learnedSpell)
3911 return TRAINER_SPELL_RED;
3913 // known spell
3914 if(HasSpell(trainer_spell->learnedSpell))
3915 return TRAINER_SPELL_GRAY;
3917 // check race/class requirement
3918 if(!IsSpellFitByClassAndRace(trainer_spell->learnedSpell))
3919 return TRAINER_SPELL_RED;
3921 // check level requirement
3922 if(getLevel() < trainer_spell->reqLevel)
3923 return TRAINER_SPELL_RED;
3925 if(SpellChainNode const* spell_chain = sSpellMgr.GetSpellChainNode(trainer_spell->learnedSpell))
3927 // check prev.rank requirement
3928 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3929 return TRAINER_SPELL_RED;
3931 // check additional spell requirement
3932 if(spell_chain->req && !HasSpell(spell_chain->req))
3933 return TRAINER_SPELL_RED;
3936 // check skill requirement
3937 if(trainer_spell->reqSkill && GetBaseSkillValue(trainer_spell->reqSkill) < trainer_spell->reqSkillValue)
3938 return TRAINER_SPELL_RED;
3940 // exist, already checked at loading
3941 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->learnedSpell);
3943 // secondary prof. or not prof. spell
3944 uint32 skill = spell->EffectMiscValue[1];
3946 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3947 return TRAINER_SPELL_GREEN;
3949 // check primary prof. limit
3950 if(sSpellMgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProfessionPoints() == 0)
3951 return TRAINER_SPELL_GREEN_DISABLED;
3953 return TRAINER_SPELL_GREEN;
3956 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3958 uint32 guid = GUID_LOPART(playerguid);
3960 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3961 // bones will be deleted by corpse/bones deleting thread shortly
3962 sObjectAccessor.ConvertCorpseForPlayer(playerguid);
3964 // remove from guild
3965 uint32 guildId = GetGuildIdFromDB(playerguid);
3966 if(guildId != 0)
3968 Guild* guild = sObjectMgr.GetGuildById(guildId);
3969 if(guild)
3970 guild->DelMember(guid);
3973 // remove from arena teams
3974 LeaveAllArenaTeams(playerguid);
3976 // the player was uninvited already on logout so just remove from group
3977 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3978 if(resultGroup)
3980 uint32 leaderGuidLow = (*resultGroup)[0].GetUInt32();
3981 delete resultGroup;
3982 if (Group* group = sObjectMgr.GetGroupByLeaderLowGUID(leaderGuidLow))
3983 RemoveFromGroup(group, playerguid);
3986 // remove signs from petitions (also remove petitions if owner);
3987 RemovePetitionsAndSigns(playerguid, 10);
3989 // return back all mails with COD and Item 0 1 2 3 4 5 6 7
3990 QueryResult *resultMail = CharacterDatabase.PQuery("SELECT id,messageType,mailTemplateId,sender,subject,itemTextId,money,has_items FROM mail WHERE receiver='%u' AND has_items<>0 AND cod<>0", guid);
3991 if(resultMail)
3995 Field *fields = resultMail->Fetch();
3997 uint32 mail_id = fields[0].GetUInt32();
3998 uint16 mailType = fields[1].GetUInt16();
3999 uint16 mailTemplateId= fields[2].GetUInt16();
4000 uint32 sender = fields[3].GetUInt32();
4001 std::string subject = fields[4].GetCppString();
4002 uint32 itemTextId = fields[5].GetUInt32();
4003 uint32 money = fields[6].GetUInt32();
4004 bool has_items = fields[7].GetBool();
4006 //we can return mail now
4007 //so firstly delete the old one
4008 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
4010 // mail not from player
4011 if (mailType != MAIL_NORMAL)
4013 if(has_items)
4014 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
4015 continue;
4018 MailDraft draft(subject, itemTextId);
4019 if (mailTemplateId)
4020 draft = MailDraft(mailTemplateId,false); // itesm already included
4022 if(has_items)
4024 // data needs to be at first place for Item::LoadFromDB
4025 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT data,item_guid,item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail_id);
4026 if(resultItems)
4030 Field *fields2 = resultItems->Fetch();
4032 uint32 item_guidlow = fields2[1].GetUInt32();
4033 uint32 item_template = fields2[2].GetUInt32();
4035 ItemPrototype const* itemProto = ObjectMgr::GetItemPrototype(item_template);
4036 if(!itemProto)
4038 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
4039 continue;
4042 Item *pItem = NewItemOrBag(itemProto);
4043 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER),resultItems))
4045 pItem->FSetState(ITEM_REMOVED);
4046 pItem->SaveToDB(); // it also deletes item object !
4047 continue;
4050 draft.AddItem(pItem);
4052 while (resultItems->NextRow());
4054 delete resultItems;
4058 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
4060 uint32 pl_account = sObjectMgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
4062 draft.AddMoney(money).SendReturnToSender(pl_account, guid, sender);
4064 while (resultMail->NextRow());
4066 delete resultMail;
4069 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
4070 // Get guids of character's pets, will deleted in transaction
4071 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
4073 // NOW we can finally clear other DB data related to character
4074 CharacterDatabase.BeginTransaction();
4075 if (resultPets)
4079 Field *fields3 = resultPets->Fetch();
4080 uint32 petguidlow = fields3[0].GetUInt32();
4081 Pet::DeleteFromDB(petguidlow);
4082 } while (resultPets->NextRow());
4083 delete resultPets;
4086 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
4087 CharacterDatabase.PExecute("DELETE FROM character_account_data WHERE guid = '%u'",guid);
4088 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
4089 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
4090 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
4091 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
4092 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
4093 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
4094 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
4095 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
4096 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
4097 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",guid);
4098 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
4099 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u'",guid);
4100 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
4101 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
4102 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
4103 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
4104 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
4105 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
4106 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
4107 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
4108 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
4109 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
4110 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
4111 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid);
4112 CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid1 = '%u'",guid);
4113 CharacterDatabase.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid2 = '%u'",guid);
4114 CharacterDatabase.PExecute("DELETE FROM guild_bank_eventlog WHERE PlayerGuid = '%u'",guid);
4115 CharacterDatabase.CommitTransaction();
4117 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
4118 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
4121 void Player::SetMovement(PlayerMovementType pType)
4123 WorldPacket data;
4124 switch(pType)
4126 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
4127 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
4128 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
4129 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
4130 default:
4131 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
4132 return;
4134 data.append(GetPackGUID());
4135 data << uint32(0);
4136 GetSession()->SendPacket( &data );
4139 /* Preconditions:
4140 - a resurrectable corpse must not be loaded for the player (only bones)
4141 - the player must be in world
4143 void Player::BuildPlayerRepop()
4145 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
4146 data.append(GetPackGUID());
4147 GetSession()->SendPacket(&data);
4149 if(getRace() == RACE_NIGHTELF)
4150 CastSpell(this, 20584, true); // auras SPELL_AURA_INCREASE_SPEED(+speed in wisp form), SPELL_AURA_INCREASE_SWIM_SPEED(+swim speed in wisp form), SPELL_AURA_TRANSFORM (to wisp form)
4151 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
4153 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
4154 // there must be SMSG.STOP_MIRROR_TIMER
4155 // there we must send 888 opcode
4157 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
4158 if(GetCorpse())
4160 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
4161 assert(false);
4164 // create a corpse and place it at the player's location
4165 CreateCorpse();
4166 Corpse *corpse = GetCorpse();
4167 if(!corpse)
4169 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
4170 return;
4172 GetMap()->Add(corpse);
4174 // convert player body to ghost
4175 SetHealth( 1 );
4177 SetMovement(MOVE_WATER_WALK);
4178 if(!GetSession()->isLogingOut())
4179 SetMovement(MOVE_UNROOT);
4181 // BG - remove insignia related
4182 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
4184 SendCorpseReclaimDelay();
4186 // to prevent cheating
4187 corpse->ResetGhostTime();
4189 StopMirrorTimers(); //disable timers(bars)
4191 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
4193 // set and clear other
4194 SetByteValue(UNIT_FIELD_BYTES_1, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND);
4197 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
4199 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
4200 data << uint32(-1);
4201 data << float(0);
4202 data << float(0);
4203 data << float(0);
4204 GetSession()->SendPacket(&data);
4206 // speed change, land walk
4208 // remove death flag + set aura
4209 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
4210 if(getRace() == RACE_NIGHTELF)
4211 RemoveAurasDueToSpell(20584); // speed bonuses
4212 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
4214 setDeathState(ALIVE);
4216 SetMovement(MOVE_LAND_WALK);
4217 SetMovement(MOVE_UNROOT);
4219 m_deathTimer = 0;
4221 // set health/powers (0- will be set in caller)
4222 if(restore_percent>0.0f)
4224 SetHealth(uint32(GetMaxHealth()*restore_percent));
4225 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
4226 SetPower(POWER_RAGE, 0);
4227 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
4230 // trigger update zone for alive state zone updates
4231 uint32 newzone, newarea;
4232 GetZoneAndAreaId(newzone,newarea);
4233 UpdateZone(newzone,newarea);
4235 // update visibility
4236 UpdateVisibilityForPlayer();
4238 if(!applySickness)
4239 return;
4241 //Characters from level 1-10 are not affected by resurrection sickness.
4242 //Characters from level 11-19 will suffer from one minute of sickness
4243 //for each level they are above 10.
4244 //Characters level 20 and up suffer from ten minutes of sickness.
4245 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
4247 if(int32(getLevel()) >= startLevel)
4249 // set resurrection sickness
4250 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
4252 // not full duration
4253 if(int32(getLevel()) < startLevel+9)
4255 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
4257 for(int i =0; i < 3; ++i)
4259 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
4261 Aur->SetAuraDuration(delta*IN_MILISECONDS);
4262 Aur->SendAuraUpdate(false);
4269 void Player::KillPlayer()
4271 SetMovement(MOVE_ROOT);
4273 StopMirrorTimers(); //disable timers(bars)
4275 setDeathState(CORPSE);
4276 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4278 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
4279 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
4281 // 6 minutes until repop at graveyard
4282 m_deathTimer = 6*MINUTE*IN_MILISECONDS;
4284 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4286 // don't create corpse at this moment, player might be falling
4288 // update visibility
4289 UpdateObjectVisibility();
4292 void Player::CreateCorpse()
4294 // prevent existence 2 corpse for player
4295 SpawnCorpseBones();
4297 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
4299 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
4300 SetPvPDeath(false);
4302 if(!corpse->Create(sObjectMgr.GenerateLowGuid(HIGHGUID_CORPSE), this))
4304 delete corpse;
4305 return;
4308 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
4309 _pb = GetUInt32Value(PLAYER_BYTES);
4310 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
4312 uint8 race = (uint8)(_uf);
4313 uint8 skin = (uint8)(_pb);
4314 uint8 face = (uint8)(_pb >> 8);
4315 uint8 hairstyle = (uint8)(_pb >> 16);
4316 uint8 haircolor = (uint8)(_pb >> 24);
4317 uint8 facialhair = (uint8)(_pb2);
4319 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
4320 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
4322 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
4323 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
4325 uint32 flags = CORPSE_FLAG_UNK2;
4326 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
4327 flags |= CORPSE_FLAG_HIDE_HELM;
4328 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
4329 flags |= CORPSE_FLAG_HIDE_CLOAK;
4330 if(InBattleGround() && !InArena())
4331 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
4332 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
4334 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
4336 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
4338 uint32 iDisplayID;
4339 uint32 iIventoryType;
4340 uint32 _cfi;
4341 for (int i = 0; i < EQUIPMENT_SLOT_END; ++i)
4343 if(m_items[i])
4345 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
4346 iIventoryType = m_items[i]->GetProto()->InventoryType;
4348 _cfi = iDisplayID | (iIventoryType << 24);
4349 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i, _cfi);
4353 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4354 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
4355 assert(entry);
4356 if(entry->map_type != MAP_BATTLEGROUND)
4357 corpse->SaveToDB();
4359 // register for player, but not show
4360 sObjectAccessor.AddCorpse(corpse);
4363 void Player::SpawnCorpseBones()
4365 if(sObjectAccessor.ConvertCorpseForPlayer(GetGUID()))
4366 if (!GetSession()->PlayerLogoutWithSave()) // at logout we will already store the player
4367 SaveToDB(); // prevent loading as ghost without corpse
4370 Corpse* Player::GetCorpse() const
4372 return sObjectAccessor.GetCorpseForPlayerGUID(GetGUID());
4375 void Player::DurabilityLossAll(double percent, bool inventory)
4377 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4378 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4379 DurabilityLoss(pItem,percent);
4381 if(inventory)
4383 // bags not have durability
4384 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4386 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4387 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4388 DurabilityLoss(pItem,percent);
4390 // keys not have durability
4391 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4393 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4394 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4395 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4396 if(Item* pItem = GetItemByPos( i, j ))
4397 DurabilityLoss(pItem,percent);
4401 void Player::DurabilityLoss(Item* item, double percent)
4403 if(!item )
4404 return;
4406 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4408 if(!pMaxDurability)
4409 return;
4411 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
4413 if(pDurabilityLoss < 1 )
4414 pDurabilityLoss = 1;
4416 DurabilityPointsLoss(item,pDurabilityLoss);
4419 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
4421 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
4422 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4423 DurabilityPointsLoss(pItem,points);
4425 if(inventory)
4427 // bags not have durability
4428 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4430 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4431 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4432 DurabilityPointsLoss(pItem,points);
4434 // keys not have durability
4435 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4437 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4438 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
4439 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
4440 if(Item* pItem = GetItemByPos( i, j ))
4441 DurabilityPointsLoss(pItem,points);
4445 void Player::DurabilityPointsLoss(Item* item, int32 points)
4447 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4448 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4449 int32 pNewDurability = pOldDurability - points;
4451 if (pNewDurability < 0)
4452 pNewDurability = 0;
4453 else if (pNewDurability > pMaxDurability)
4454 pNewDurability = pMaxDurability;
4456 if (pOldDurability != pNewDurability)
4458 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4459 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
4460 _ApplyItemMods(item,item->GetSlot(), false);
4462 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
4464 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4465 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
4466 _ApplyItemMods(item,item->GetSlot(), true);
4468 item->SetState(ITEM_CHANGED, this);
4472 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
4474 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
4475 DurabilityPointsLoss(pItem,1);
4478 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
4480 uint32 TotalCost = 0;
4481 // equipped, backpack, bags itself
4482 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
4483 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
4485 // bank, buyback and keys not repaired
4487 // items in inventory bags
4488 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; ++j)
4489 for(int i = 0; i < MAX_BAG_SIZE; ++i)
4490 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4491 return TotalCost;
4494 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4496 Item* item = GetItemByPos(pos);
4498 uint32 TotalCost = 0;
4499 if(!item)
4500 return TotalCost;
4502 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4503 if(!maxDurability)
4504 return TotalCost;
4506 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4508 if(cost)
4510 uint32 LostDurability = maxDurability - curDurability;
4511 if(LostDurability>0)
4513 ItemPrototype const *ditemProto = item->GetProto();
4515 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4516 if(!dcost)
4518 sLog.outError("RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4519 return TotalCost;
4522 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4523 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4524 if(!dQualitymodEntry)
4526 sLog.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4527 return TotalCost;
4530 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4531 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4533 costs = uint32(costs * discountMod);
4535 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4536 costs = 1;
4538 if (guildBank)
4540 if (GetGuildId()==0)
4542 DEBUG_LOG("You are not member of a guild");
4543 return TotalCost;
4546 Guild *pGuild = sObjectMgr.GetGuildById(GetGuildId());
4547 if (!pGuild)
4548 return TotalCost;
4550 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4552 DEBUG_LOG("You do not have rights to withdraw for repairs");
4553 return TotalCost;
4556 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4558 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4559 return TotalCost;
4562 if (pGuild->GetGuildBankMoney() < costs)
4564 DEBUG_LOG("There is not enough money in bank");
4565 return TotalCost;
4568 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4569 TotalCost = costs;
4571 else if (GetMoney() < costs)
4573 DEBUG_LOG("You do not have enough money");
4574 return TotalCost;
4576 else
4577 ModifyMoney( -int32(costs) );
4581 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4582 item->SetState(ITEM_CHANGED, this);
4584 // reapply mods for total broken and repaired item if equipped
4585 if(IsEquipmentPos(pos) && !curDurability)
4586 _ApplyItemMods(item,pos & 255, true);
4587 return TotalCost;
4590 void Player::RepopAtGraveyard()
4592 // note: this can be called also when the player is alive
4593 // for example from WorldSession::HandleMovementOpcodes
4595 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4597 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4598 if ((!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY) || GetTransport())
4600 ResurrectPlayer(0.5f);
4601 SpawnCorpseBones();
4604 WorldSafeLocsEntry const *ClosestGrave = NULL;
4606 // Special handle for battleground maps
4607 if( BattleGround *bg = GetBattleGround() )
4608 ClosestGrave = bg->GetClosestGraveYard(this);
4609 else
4610 ClosestGrave = sObjectMgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4612 // stop countdown until repop
4613 m_deathTimer = 0;
4615 // if no grave found, stay at the current location
4616 // and don't show spirit healer location
4617 if(ClosestGrave)
4619 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4620 if(isDead()) // not send if alive, because it used in TeleportTo()
4622 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4623 data << ClosestGrave->map_id;
4624 data << ClosestGrave->x;
4625 data << ClosestGrave->y;
4626 data << ClosestGrave->z;
4627 GetSession()->SendPacket(&data);
4632 void Player::JoinedChannel(Channel *c)
4634 m_channels.push_back(c);
4637 void Player::LeftChannel(Channel *c)
4639 m_channels.remove(c);
4642 void Player::CleanupChannels()
4644 while(!m_channels.empty())
4646 Channel* ch = *m_channels.begin();
4647 m_channels.erase(m_channels.begin()); // remove from player's channel list
4648 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4649 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4650 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4653 sLog.outDebug("Player: channels cleaned up!");
4656 void Player::UpdateLocalChannels(uint32 newZone )
4658 if(m_channels.empty())
4659 return;
4661 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4662 if(!current_zone)
4663 return;
4665 ChannelMgr* cMgr = channelMgr(GetTeam());
4666 if(!cMgr)
4667 return;
4669 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4671 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4673 next = i; ++next;
4675 // skip non built-in channels
4676 if(!(*i)->IsConstant())
4677 continue;
4679 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4680 if(!ch)
4681 continue;
4683 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4684 continue;
4686 // new channel
4687 char new_channel_name_buf[100];
4688 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4689 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4691 if((*i)!=new_channel)
4693 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4695 // leave old channel
4696 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4697 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4698 LeftChannel(*i); // remove from player's channel list
4699 cMgr->LeftChannel(name); // delete if empty
4702 sLog.outDebug("Player: channels cleaned up!");
4705 void Player::LeaveLFGChannel()
4707 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4709 if((*i)->IsLFG())
4711 (*i)->Leave(GetGUID());
4712 break;
4717 void Player::UpdateDefense()
4719 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4721 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4723 // update dependent from defense skill part
4724 UpdateDefenseBonusesMod();
4728 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4730 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4732 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4733 return;
4736 float val = 1.0f;
4738 switch(modType)
4740 case FLAT_MOD:
4741 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4742 break;
4743 case PCT_MOD:
4744 if(amount <= -100.0f)
4745 amount = -200.0f;
4747 val = (100.0f + amount) / 100.0f;
4748 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4749 break;
4752 if(!CanModifyStats())
4753 return;
4755 switch(modGroup)
4757 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4758 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4759 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4760 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4761 default: break;
4765 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4767 if(modGroup >= BASEMOD_END || modType > MOD_END)
4769 sLog.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4770 return 0.0f;
4773 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4774 return 0.0f;
4776 return m_auraBaseMod[modGroup][modType];
4779 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4781 if(modGroup >= BASEMOD_END)
4783 sLog.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4784 return 0.0f;
4787 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4788 return 0.0f;
4790 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4793 uint32 Player::GetShieldBlockValue() const
4795 float value = (m_auraBaseMod[SHIELD_BLOCK_VALUE][FLAT_MOD] + GetStat(STAT_STRENGTH) * 0.5f - 10)*m_auraBaseMod[SHIELD_BLOCK_VALUE][PCT_MOD];
4797 value = (value < 0) ? 0 : value;
4799 return uint32(value);
4802 float Player::GetMeleeCritFromAgility()
4804 uint32 level = getLevel();
4805 uint32 pclass = getClass();
4807 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4809 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4810 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4811 if (critBase==NULL || critRatio==NULL)
4812 return 0.0f;
4814 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4815 return crit*100.0f;
4818 float Player::GetDodgeFromAgility()
4820 // Table for base dodge values
4821 float dodge_base[MAX_CLASSES] = {
4822 0.0075f, // Warrior
4823 0.00652f, // Paladin
4824 -0.0545f, // Hunter
4825 -0.0059f, // Rogue
4826 0.03183f, // Priest
4827 0.0114f, // DK
4828 0.0167f, // Shaman
4829 0.034575f, // Mage
4830 0.02011f, // Warlock
4831 0.0f, // ??
4832 -0.0187f // Druid
4834 // Crit/agility to dodge/agility coefficient multipliers
4835 float crit_to_dodge[MAX_CLASSES] = {
4836 1.1f, // Warrior
4837 1.0f, // Paladin
4838 1.6f, // Hunter
4839 2.0f, // Rogue
4840 1.0f, // Priest
4841 1.0f, // DK?
4842 1.0f, // Shaman
4843 1.0f, // Mage
4844 1.0f, // Warlock
4845 0.0f, // ??
4846 1.7f // Druid
4849 uint32 level = getLevel();
4850 uint32 pclass = getClass();
4852 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4854 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4855 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4856 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4857 return 0.0f;
4859 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4860 return dodge*100.0f;
4863 float Player::GetSpellCritFromIntellect()
4865 uint32 level = getLevel();
4866 uint32 pclass = getClass();
4868 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4870 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4871 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4872 if (critBase==NULL || critRatio==NULL)
4873 return 0.0f;
4875 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4876 return crit*100.0f;
4879 float Player::GetRatingCoefficient(CombatRating cr) const
4881 uint32 level = getLevel();
4883 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4885 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4886 if (Rating == NULL)
4887 return 1.0f; // By default use minimum coefficient (not must be called)
4889 return Rating->ratio;
4892 float Player::GetRatingBonusValue(CombatRating cr) const
4894 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4897 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4899 switch (attType)
4901 case BASE_ATTACK:
4902 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4903 case OFF_ATTACK:
4904 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4905 default:
4906 break;
4908 return 0.0f;
4911 float Player::OCTRegenHPPerSpirit()
4913 uint32 level = getLevel();
4914 uint32 pclass = getClass();
4916 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4918 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4919 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4920 if (baseRatio==NULL || moreRatio==NULL)
4921 return 0.0f;
4923 // Formula from PaperDollFrame script
4924 float spirit = GetStat(STAT_SPIRIT);
4925 float baseSpirit = spirit;
4926 if (baseSpirit>50) baseSpirit = 50;
4927 float moreSpirit = spirit - baseSpirit;
4928 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4929 return regen;
4932 float Player::OCTRegenMPPerSpirit()
4934 uint32 level = getLevel();
4935 uint32 pclass = getClass();
4937 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4939 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4940 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4941 if (moreRatio==NULL)
4942 return 0.0f;
4944 // Formula get from PaperDollFrame script
4945 float spirit = GetStat(STAT_SPIRIT);
4946 float regen = spirit * moreRatio->ratio;
4947 return regen;
4950 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4952 m_baseRatingValue[cr]+=(apply ? value : -value);
4954 // explicit affected values
4955 switch (cr)
4957 case CR_HASTE_MELEE:
4959 float RatingChange = value / GetRatingCoefficient(cr);
4960 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4961 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4962 break;
4964 case CR_HASTE_RANGED:
4966 float RatingChange = value / GetRatingCoefficient(cr);
4967 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4968 break;
4970 case CR_HASTE_SPELL:
4972 float RatingChange = value / GetRatingCoefficient(cr);
4973 ApplyCastTimePercentMod(RatingChange,apply);
4974 break;
4978 UpdateRating(cr);
4981 void Player::UpdateRating(CombatRating cr)
4983 int32 amount = m_baseRatingValue[cr];
4984 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4985 // stat used stored in miscValueB for this aura
4986 AuraList const& modRatingFromStat = GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT);
4987 for(AuraList::const_iterator i = modRatingFromStat.begin();i != modRatingFromStat.end(); ++i)
4988 if ((*i)->GetMiscValue() & (1<<cr))
4989 amount += int32(GetStat(Stats((*i)->GetMiscBValue())) * (*i)->GetModifier()->m_amount / 100.0f);
4990 if (amount < 0)
4991 amount = 0;
4992 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, uint32(amount));
4994 bool affectStats = CanModifyStats();
4996 switch (cr)
4998 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4999 case CR_DEFENSE_SKILL:
5000 UpdateDefenseBonusesMod();
5001 break;
5002 case CR_DODGE:
5003 UpdateDodgePercentage();
5004 break;
5005 case CR_PARRY:
5006 UpdateParryPercentage();
5007 break;
5008 case CR_BLOCK:
5009 UpdateBlockPercentage();
5010 break;
5011 case CR_HIT_MELEE:
5012 UpdateMeleeHitChances();
5013 break;
5014 case CR_HIT_RANGED:
5015 UpdateRangedHitChances();
5016 break;
5017 case CR_HIT_SPELL:
5018 UpdateSpellHitChances();
5019 break;
5020 case CR_CRIT_MELEE:
5021 if(affectStats)
5023 UpdateCritPercentage(BASE_ATTACK);
5024 UpdateCritPercentage(OFF_ATTACK);
5026 break;
5027 case CR_CRIT_RANGED:
5028 if(affectStats)
5029 UpdateCritPercentage(RANGED_ATTACK);
5030 break;
5031 case CR_CRIT_SPELL:
5032 if(affectStats)
5033 UpdateAllSpellCritChances();
5034 break;
5035 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
5036 case CR_HIT_TAKEN_RANGED:
5037 break;
5038 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
5039 break;
5040 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
5041 case CR_CRIT_TAKEN_RANGED:
5042 break;
5043 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
5044 break;
5045 case CR_HASTE_MELEE: // Implemented in Player::ApplyRatingMod
5046 case CR_HASTE_RANGED:
5047 case CR_HASTE_SPELL:
5048 break;
5049 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
5050 case CR_WEAPON_SKILL_OFFHAND:
5051 case CR_WEAPON_SKILL_RANGED:
5052 break;
5053 case CR_EXPERTISE:
5054 if(affectStats)
5056 UpdateExpertise(BASE_ATTACK);
5057 UpdateExpertise(OFF_ATTACK);
5059 break;
5060 case CR_ARMOR_PENETRATION:
5061 if(affectStats)
5062 UpdateArmorPenetration();
5063 break;
5067 void Player::UpdateAllRatings()
5069 for(int cr = 0; cr < MAX_COMBAT_RATING; ++cr)
5070 UpdateRating(CombatRating(cr));
5073 void Player::SetRegularAttackTime()
5075 for(int i = 0; i < MAX_ATTACK; ++i)
5077 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i),true,false);
5078 if (tmpitem)
5080 ItemPrototype const *proto = tmpitem->GetProto();
5081 if(proto->Delay)
5082 SetAttackTime(WeaponAttackType(i), proto->Delay);
5083 else
5084 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
5089 //skill+step, checking for max value
5090 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
5092 if(!skill_id)
5093 return false;
5095 SkillStatusMap::iterator itr = mSkillStatus.find(skill_id);
5096 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5097 return false;
5099 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5100 uint32 data = GetUInt32Value(valueIndex);
5101 uint32 value = SKILL_VALUE(data);
5102 uint32 max = SKILL_MAX(data);
5104 if ((!max) || (!value) || (value >= max))
5105 return false;
5107 if (value*512 < max*urand(0,512))
5109 uint32 new_value = value+step;
5110 if(new_value > max)
5111 new_value = max;
5113 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,max));
5114 if(itr->second.uState != SKILL_NEW)
5115 itr->second.uState = SKILL_CHANGED;
5116 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,skill_id);
5117 return true;
5120 return false;
5123 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
5125 if ( SkillValue >= GrayLevel )
5126 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
5127 if ( SkillValue >= GreenLevel )
5128 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
5129 if ( SkillValue >= YellowLevel )
5130 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
5131 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
5134 bool Player::UpdateCraftSkill(uint32 spellid)
5136 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
5138 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spellid);
5140 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
5142 if (_spell_idx->second->skillId)
5144 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
5146 // Alchemy Discoveries here
5147 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
5148 if (spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
5150 if (uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
5151 learnSpell(discoveredSpell,false);
5154 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
5156 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
5157 _spell_idx->second->max_value,
5158 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
5159 _spell_idx->second->min_value),
5160 craft_skill_gain);
5163 return false;
5166 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
5168 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
5170 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
5172 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
5173 switch (SkillId)
5175 case SKILL_HERBALISM:
5176 case SKILL_LOCKPICKING:
5177 case SKILL_JEWELCRAFTING:
5178 case SKILL_INSCRIPTION:
5179 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5180 case SKILL_SKINNING:
5181 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
5182 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5183 else
5184 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
5185 case SKILL_MINING:
5186 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
5187 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
5188 else
5189 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
5191 return false;
5194 bool Player::UpdateFishingSkill()
5196 sLog.outDebug("UpdateFishingSkill");
5198 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
5200 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
5202 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
5204 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
5207 // levels sync. with spell requirement for skill levels to learn
5208 // bonus abilities in sSkillLineAbilityStore
5209 // Used only to avoid scan DBC at each skill grow
5210 static uint32 bonusSkillLevels[] = {75,150,225,300,375,450};
5212 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
5214 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
5215 if ( !SkillId )
5216 return false;
5218 if(Chance <= 0) // speedup in 0 chance case
5220 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5221 return false;
5224 SkillStatusMap::iterator itr = mSkillStatus.find(SkillId);
5225 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5226 return false;
5228 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5230 uint32 data = GetUInt32Value(valueIndex);
5231 uint16 SkillValue = SKILL_VALUE(data);
5232 uint16 MaxValue = SKILL_MAX(data);
5234 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
5235 return false;
5237 int32 Roll = irand(1,1000);
5239 if ( Roll <= Chance )
5241 uint32 new_value = SkillValue+step;
5242 if(new_value > MaxValue)
5243 new_value = MaxValue;
5245 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(new_value,MaxValue));
5246 if(itr->second.uState != SKILL_NEW)
5247 itr->second.uState = SKILL_CHANGED;
5248 for(uint32* bsl = &bonusSkillLevels[0]; *bsl; ++bsl)
5250 if((SkillValue < *bsl && new_value >= *bsl))
5252 learnSkillRewardedSpells( SkillId, new_value);
5253 break;
5256 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,SkillId);
5257 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
5258 return true;
5261 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
5262 return false;
5265 void Player::UpdateWeaponSkill (WeaponAttackType attType)
5267 // no skill gain in pvp
5268 Unit *pVictim = getVictim();
5269 if(pVictim && pVictim->IsCharmerOrOwnerPlayerOrPlayerItself())
5270 return;
5272 if(IsInFeralForm())
5273 return; // always maximized SKILL_FERAL_COMBAT in fact
5275 if(m_form == FORM_TREE)
5276 return; // use weapon but not skill up
5278 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
5280 switch(attType)
5282 case BASE_ATTACK:
5284 Item *tmpitem = GetWeaponForAttack(attType,true,true);
5286 if (!tmpitem)
5287 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
5288 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
5289 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5290 break;
5292 case OFF_ATTACK:
5293 case RANGED_ATTACK:
5295 Item *tmpitem = GetWeaponForAttack(attType,true,true);
5296 if (tmpitem)
5297 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
5298 break;
5301 UpdateAllCritPercentages();
5304 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, bool defence)
5306 uint32 plevel = getLevel(); // if defense than pVictim == attacker
5307 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
5308 uint32 moblevel = pVictim->getLevelForTarget(this);
5309 if(moblevel < greylevel)
5310 return;
5312 if (moblevel > plevel + 5)
5313 moblevel = plevel + 5;
5315 uint32 lvldif = moblevel - greylevel;
5316 if(lvldif < 3)
5317 lvldif = 3;
5319 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
5320 if(skilldif <= 0)
5321 return;
5323 float chance = float(3 * lvldif * skilldif) / plevel;
5324 if(!defence)
5326 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
5327 chance *= 0.1f * GetStat(STAT_INTELLECT);
5330 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
5332 if(roll_chance_f(chance))
5334 if(defence)
5335 UpdateDefense();
5336 else
5337 UpdateWeaponSkill(attType);
5339 else
5340 return;
5343 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
5345 SkillStatusMap::const_iterator itr = mSkillStatus.find(skillid);
5346 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5347 return;
5349 uint32 bonusIndex = PLAYER_SKILL_BONUS_INDEX(itr->second.pos);
5351 uint32 bonus_val = GetUInt32Value(bonusIndex);
5352 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
5353 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
5355 if(talent) // permanent bonus stored in high part
5356 SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
5357 else // temporary/item bonus stored in low part
5358 SetUInt32Value(bonusIndex,MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
5361 void Player::UpdateSkillsForLevel()
5363 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
5364 uint32 maxSkill = GetMaxSkillValueForLevel();
5366 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
5368 for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
5370 if(itr->second.uState == SKILL_DELETED)
5371 continue;
5373 uint32 pskill = itr->first;
5375 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
5376 if(!pSkill)
5377 continue;
5379 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
5380 continue;
5382 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5383 uint32 data = GetUInt32Value(valueIndex);
5384 uint32 max = SKILL_MAX(data);
5385 uint32 val = SKILL_VALUE(data);
5387 /// update only level dependent max skill values
5388 if(max!=1)
5390 /// maximize skill always
5391 if(alwaysMaxSkill)
5393 SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(maxSkill,maxSkill));
5394 if(itr->second.uState != SKILL_NEW)
5395 itr->second.uState = SKILL_CHANGED;
5397 else if(max != maxconfskill) /// update max skill value if current max skill not maximized
5399 SetUInt32Value(valueIndex, MAKE_SKILL_VALUE(val,maxSkill));
5400 if(itr->second.uState != SKILL_NEW)
5401 itr->second.uState = SKILL_CHANGED;
5407 void Player::UpdateSkillsToMaxSkillsForLevel()
5409 for(SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); ++itr)
5411 if(itr->second.uState == SKILL_DELETED)
5412 continue;
5414 uint32 pskill = itr->first;
5415 if( IsProfessionOrRidingSkill(pskill))
5416 continue;
5417 uint32 valueIndex = PLAYER_SKILL_VALUE_INDEX(itr->second.pos);
5418 uint32 data = GetUInt32Value(valueIndex);
5420 uint32 max = SKILL_MAX(data);
5422 if(max > 1)
5424 SetUInt32Value(valueIndex,MAKE_SKILL_VALUE(max,max));
5425 if(itr->second.uState != SKILL_NEW)
5426 itr->second.uState = SKILL_CHANGED;
5429 if(pskill == SKILL_DEFENSE)
5430 UpdateDefenseBonusesMod();
5434 // This functions sets a skill line value (and adds if doesn't exist yet)
5435 // To "remove" a skill line, set it's values to zero
5436 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
5438 if(!id)
5439 return;
5441 SkillStatusMap::iterator itr = mSkillStatus.find(id);
5443 //has skill
5444 if(itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED)
5446 if(currVal)
5448 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos),MAKE_SKILL_VALUE(currVal,maxVal));
5449 if(itr->second.uState != SKILL_NEW)
5450 itr->second.uState = SKILL_CHANGED;
5451 learnSkillRewardedSpells(id, currVal);
5452 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5453 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5455 else //remove
5457 // clear skill fields
5458 SetUInt32Value(PLAYER_SKILL_INDEX(itr->second.pos),0);
5459 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos),0);
5460 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos),0);
5462 // mark as deleted or simply remove from map if not saved yet
5463 if(itr->second.uState != SKILL_NEW)
5464 itr->second.uState = SKILL_DELETED;
5465 else
5466 mSkillStatus.erase(itr);
5468 // remove all spells that related to this skill
5469 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
5470 if(SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j))
5471 if (pAbility->skillId==id)
5472 removeSpell(sSpellMgr.GetFirstSpellInChain(pAbility->spellId));
5475 else if(currVal) //add
5477 for (int i=0; i < PLAYER_MAX_SKILLS; ++i)
5478 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
5480 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
5481 if(!pSkill)
5483 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
5484 return;
5486 // enable unlearn button for primary professions only
5487 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
5488 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
5489 else
5490 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
5491 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
5492 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL,id);
5493 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL,id);
5495 // insert new entry or update if not deleted old entry yet
5496 if(itr != mSkillStatus.end())
5498 itr->second.pos = i;
5499 itr->second.uState = SKILL_CHANGED;
5501 else
5502 mSkillStatus.insert(SkillStatusMap::value_type(id, SkillStatusData(i, SKILL_NEW)));
5504 // apply skill bonuses
5505 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5507 // temporary bonuses
5508 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5509 for(AuraList::const_iterator j = mModSkill.begin(); j != mModSkill.end(); ++j)
5510 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5511 (*j)->ApplyModifier(true);
5513 // permanent bonuses
5514 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5515 for(AuraList::const_iterator j = mModSkillTalent.begin(); j != mModSkillTalent.end(); ++j)
5516 if ((*j)->GetModifier()->m_miscvalue == int32(id))
5517 (*j)->ApplyModifier(true);
5519 // Learn all spells for skill
5520 learnSkillRewardedSpells(id, currVal);
5521 return;
5526 bool Player::HasSkill(uint32 skill) const
5528 if(!skill)
5529 return false;
5531 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5532 return (itr != mSkillStatus.end() && itr->second.uState != SKILL_DELETED);
5535 uint16 Player::GetSkillValue(uint32 skill) const
5537 if(!skill)
5538 return 0;
5540 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5541 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5542 return 0;
5544 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
5546 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5547 result += SKILL_TEMP_BONUS(bonus);
5548 result += SKILL_PERM_BONUS(bonus);
5549 return result < 0 ? 0 : result;
5552 uint16 Player::GetMaxSkillValue(uint32 skill) const
5554 if(!skill)
5555 return 0;
5557 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5558 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5559 return 0;
5561 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos));
5563 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5564 result += SKILL_TEMP_BONUS(bonus);
5565 result += SKILL_PERM_BONUS(bonus);
5566 return result < 0 ? 0 : result;
5569 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5571 if(!skill)
5572 return 0;
5574 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5575 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5576 return 0;
5578 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
5581 uint16 Player::GetBaseSkillValue(uint32 skill) const
5583 if(!skill)
5584 return 0;
5586 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5587 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5588 return 0;
5590 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos))));
5591 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5592 return result < 0 ? 0 : result;
5595 uint16 Player::GetPureSkillValue(uint32 skill) const
5597 if(!skill)
5598 return 0;
5600 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5601 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5602 return 0;
5604 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos)));
5607 int16 Player::GetSkillPermBonusValue(uint32 skill) const
5609 if(!skill)
5610 return 0;
5612 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5613 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5614 return 0;
5616 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5619 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5621 if(!skill)
5622 return 0;
5624 SkillStatusMap::const_iterator itr = mSkillStatus.find(skill);
5625 if(itr == mSkillStatus.end() || itr->second.uState == SKILL_DELETED)
5626 return 0;
5628 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr->second.pos)));
5631 void Player::SendInitialActionButtons() const
5633 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5635 WorldPacket data(SMSG_ACTION_BUTTONS, 1+(MAX_ACTION_BUTTONS*4));
5636 data << uint8(0); // can be 0, 1, 2 (talent spec)
5637 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5639 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5640 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5641 data << uint32(itr->second.packedData);
5642 else
5643 data << uint32(0);
5646 GetSession()->SendPacket( &data );
5647 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5650 bool Player::IsActionButtonDataValid(uint8 button, uint32 action, uint8 type, Player* player)
5652 if(button >= MAX_ACTION_BUTTONS)
5654 if (player)
5655 sLog.outError( "Action %u not added into button %u for player %s: button must be < %u", action, button, player->GetName(), MAX_ACTION_BUTTONS );
5656 else
5657 sLog.outError( "Table `playercreateinfo_action` have action %u into button %u : button must be < %u", action, button, MAX_ACTION_BUTTONS );
5658 return false;
5661 if(action >= MAX_ACTION_BUTTON_ACTION_VALUE)
5663 if (player)
5664 sLog.outError( "Action %u not added into button %u for player %s: action must be < %u", action, button, player->GetName(), MAX_ACTION_BUTTON_ACTION_VALUE );
5665 else
5666 sLog.outError( "Table `playercreateinfo_action` have action %u into button %u : action must be < %u", action, button, MAX_ACTION_BUTTON_ACTION_VALUE );
5667 return false;
5670 switch(type)
5672 case ACTION_BUTTON_SPELL:
5673 if(!sSpellStore.LookupEntry(action))
5675 if (player)
5676 sLog.outError( "Spell action %u not added into button %u for player %s: spell not exist", action, button, player->GetName() );
5677 else
5678 sLog.outError( "Table `playercreateinfo_action` have spell action %u into button %u: spell not exist", action, button );
5679 return false;
5682 if(player && !player->HasSpell(action))
5684 sLog.outError( "Spell action %u not added into button %u for player %s: player don't known this spell", action, button, player->GetName() );
5685 return false;
5687 break;
5688 case ACTION_BUTTON_ITEM:
5689 if(!ObjectMgr::GetItemPrototype(action))
5691 if (player)
5692 sLog.outError( "Item action %u not added into button %u for player %s: item not exist", action, button, player->GetName() );
5693 else
5694 sLog.outError( "Table `playercreateinfo_action` have item action %u into button %u: item not exist", action, button );
5695 return false;
5697 break;
5698 default:
5699 break; // other cases not checked at this moment
5702 return true;
5705 ActionButton* Player::addActionButton(uint8 button, uint32 action, uint8 type)
5708 if (!IsActionButtonDataValid(button,action,type,this))
5709 return NULL;
5711 // it create new button (NEW state) if need or return existed
5712 ActionButton& ab = m_actionButtons[button];
5714 // set data and update to CHANGED if not NEW
5715 ab.SetActionAndType(action,ActionButtonType(type));
5717 sLog.outDetail( "Player '%u' Added Action '%u' (type %u) to Button '%u'", GetGUIDLow(), action, uint32(type), button );
5718 return &ab;
5721 void Player::removeActionButton(uint8 button)
5723 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5724 if (buttonItr==m_actionButtons.end())
5725 return;
5727 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5728 m_actionButtons.erase(buttonItr); // new and not saved
5729 else
5730 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5732 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5735 ActionButton const* Player::GetActionButton(uint8 button)
5737 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5738 if (buttonItr==m_actionButtons.end() || buttonItr->second.uState == ACTIONBUTTON_DELETED)
5739 return NULL;
5741 return &buttonItr->second;
5744 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5746 // prevent crash when a bad coord is sent by the client
5747 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5749 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5750 return false;
5753 Map *m = GetMap();
5755 const float old_x = GetPositionX();
5756 const float old_y = GetPositionY();
5757 const float old_z = GetPositionZ();
5758 const float old_r = GetOrientation();
5760 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5762 if (teleport || old_x != x || old_y != y || old_z != z)
5763 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5764 else
5765 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5767 // move and update visible state if need
5768 m->PlayerRelocation(this, x, y, z, orientation);
5770 // reread after Map::Relocation
5771 m = GetMap();
5772 x = GetPositionX();
5773 y = GetPositionY();
5774 z = GetPositionZ();
5776 // group update
5777 if(GetGroup() && (old_x != x || old_y != y))
5778 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5781 // code block for underwater state update
5782 UpdateUnderwaterState(m, x, y, z);
5784 CheckExploreSystem();
5786 return true;
5789 void Player::SaveRecallPosition()
5791 m_recallMap = GetMapId();
5792 m_recallX = GetPositionX();
5793 m_recallY = GetPositionY();
5794 m_recallZ = GetPositionZ();
5795 m_recallO = GetOrientation();
5798 void Player::SendMessageToSet(WorldPacket *data, bool self)
5800 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5801 if(_map)
5803 _map->MessageBroadcast(this, data, self);
5804 return;
5807 //if player is not in world and map in not created/already destroyed
5808 //no need to create one, just send packet for itself!
5809 if(self)
5810 GetSession()->SendPacket(data);
5813 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5815 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5816 if(_map)
5818 _map->MessageDistBroadcast(this, data, dist, self);
5819 return;
5822 if(self)
5823 GetSession()->SendPacket(data);
5826 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5828 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
5829 if(_map)
5831 _map->MessageDistBroadcast(this, data, dist, self, own_team_only);
5832 return;
5835 if(self)
5836 GetSession()->SendPacket(data);
5839 void Player::SendDirectMessage(WorldPacket *data)
5841 GetSession()->SendPacket(data);
5844 void Player::SendCinematicStart(uint32 CinematicSequenceId)
5846 WorldPacket data(SMSG_TRIGGER_CINEMATIC, 4);
5847 data << uint32(CinematicSequenceId);
5848 SendDirectMessage(&data);
5851 void Player::SendMovieStart(uint32 MovieId)
5853 WorldPacket data(SMSG_TRIGGER_MOVIE, 4);
5854 data << uint32(MovieId);
5855 SendDirectMessage(&data);
5858 void Player::CheckExploreSystem()
5860 if (!isAlive())
5861 return;
5863 if (isInFlight())
5864 return;
5866 uint16 areaFlag = GetBaseMap()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5867 if(areaFlag==0xffff)
5868 return;
5869 int offset = areaFlag / 32;
5871 if(offset >= 128)
5873 sLog.outError("Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < 128 ).",areaFlag,GetPositionX(),GetPositionY(),offset,offset);
5874 return;
5877 uint32 val = (uint32)(1 << (areaFlag % 32));
5878 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5880 if( !(currFields & val) )
5882 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5884 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5886 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5887 if(!p)
5889 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5891 else if(p->area_level > 0)
5893 uint32 area = p->ID;
5894 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5896 SendExplorationExperience(area,0);
5898 else
5900 int32 diff = int32(getLevel()) - p->area_level;
5901 uint32 XP = 0;
5902 if (diff < -5)
5904 XP = uint32(sObjectMgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5906 else if (diff > 5)
5908 int32 exploration_percent = (100-((diff-5)*5));
5909 if (exploration_percent > 100)
5910 exploration_percent = 100;
5911 else if (exploration_percent < 0)
5912 exploration_percent = 0;
5914 XP = uint32(sObjectMgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5916 else
5918 XP = uint32(sObjectMgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5921 GiveXP( XP, NULL );
5922 SendExplorationExperience(area,XP);
5924 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5929 uint32 Player::TeamForRace(uint8 race)
5931 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5932 if(!rEntry)
5934 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5935 return ALLIANCE;
5938 switch(rEntry->TeamID)
5940 case 7: return ALLIANCE;
5941 case 1: return HORDE;
5944 sLog.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5945 return ALLIANCE;
5948 uint32 Player::getFactionForRace(uint8 race)
5950 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5951 if(!rEntry)
5953 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5954 return 0;
5957 return rEntry->FactionID;
5960 void Player::setFactionForRace(uint8 race)
5962 m_team = TeamForRace(race);
5963 setFaction( getFactionForRace(race) );
5966 ReputationRank Player::GetReputationRank(uint32 faction) const
5968 FactionEntry const* factionEntry = sFactionStore.LookupEntry(faction);
5969 return GetReputationMgr().GetRank(factionEntry);
5972 //Calculate total reputation percent player gain with quest/creature level
5973 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, int32 faction, bool for_quest)
5975 float percent = 100.0f;
5977 float rate = for_quest ? sWorld.getRate(RATE_REPUTATION_LOWLEVEL_QUEST) : sWorld.getRate(RATE_REPUTATION_LOWLEVEL_KILL);
5979 if (rate != 1.0f && creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))
5980 percent *= rate;
5982 float repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5984 if (!for_quest)
5985 repMod += GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN, faction);
5987 percent += rep > 0 ? repMod : -repMod;
5989 if (percent <= 0.0f)
5990 return 0;
5992 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100.0f);
5995 //Calculates how many reputation points player gains in victim's enemy factions
5996 void Player::RewardReputation(Unit *pVictim, float rate)
5998 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5999 return;
6001 ReputationOnKillEntry const* Rep = sObjectMgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
6003 if(!Rep)
6004 return;
6006 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
6008 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue1, Rep->repfaction1, false);
6009 donerep1 = int32(donerep1*rate);
6010 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
6011 uint32 current_reputation_rank1 = GetReputationMgr().GetRank(factionEntry1);
6012 if (factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
6013 GetReputationMgr().ModifyReputation(factionEntry1, donerep1);
6015 // Wiki: Team factions value divided by 2
6016 if (factionEntry1 && Rep->is_teamaward1)
6018 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
6019 if(team1_factionEntry)
6020 GetReputationMgr().ModifyReputation(team1_factionEntry, donerep1 / 2);
6024 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
6026 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(), Rep->repvalue2, Rep->repfaction2, false);
6027 donerep2 = int32(donerep2*rate);
6028 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
6029 uint32 current_reputation_rank2 = GetReputationMgr().GetRank(factionEntry2);
6030 if (factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
6031 GetReputationMgr().ModifyReputation(factionEntry2, donerep2);
6033 // Wiki: Team factions value divided by 2
6034 if (factionEntry2 && Rep->is_teamaward2)
6036 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
6037 if(team2_factionEntry)
6038 GetReputationMgr().ModifyReputation(team2_factionEntry, donerep2 / 2);
6043 //Calculate how many reputation points player gain with the quest
6044 void Player::RewardReputation(Quest const *pQuest)
6046 // quest reputation reward/loss
6047 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
6049 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
6051 int32 rep = CalculateReputationGain(GetQuestLevelForPlayer(pQuest), pQuest->RewRepValue[i], pQuest->RewRepFaction[i], true);
6052 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
6053 if(factionEntry)
6054 GetReputationMgr().ModifyReputation(factionEntry, rep);
6058 // TODO: implement reputation spillover
6061 void Player::UpdateArenaFields(void)
6063 /* arena calcs go here */
6066 void Player::UpdateHonorFields()
6068 /// called when rewarding honor and at each save
6069 uint64 now = time(NULL);
6070 uint64 today = uint64(time(NULL) / DAY) * DAY;
6072 if(m_lastHonorUpdateTime < today)
6074 uint64 yesterday = today - DAY;
6076 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
6078 // update yesterday's contribution
6079 if(m_lastHonorUpdateTime >= yesterday )
6081 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
6083 // this is the first update today, reset today's contribution
6084 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
6085 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
6087 else
6089 // no honor/kills yesterday or today, reset
6090 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
6091 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
6095 m_lastHonorUpdateTime = now;
6098 ///Calculate the amount of honor gained based on the victim
6099 ///and the size of the group for which the honor is divided
6100 ///An exact honor value can also be given (overriding the calcs)
6101 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
6103 // do not reward honor in arenas, but enable onkill spellproc
6104 if(InArena())
6106 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
6107 return false;
6109 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
6110 return false;
6112 return true;
6115 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
6116 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
6117 return false;
6119 uint64 victim_guid = 0;
6120 uint32 victim_rank = 0;
6122 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6123 UpdateHonorFields();
6125 if(honor <= 0)
6127 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
6128 return false;
6130 victim_guid = uVictim->GetGUID();
6132 if( uVictim->GetTypeId() == TYPEID_PLAYER )
6134 Player *pVictim = (Player *)uVictim;
6136 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
6137 return false;
6139 float f = 1; //need for total kills (?? need more info)
6140 uint32 k_grey = 0;
6141 uint32 k_level = getLevel();
6142 uint32 v_level = pVictim->getLevel();
6145 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6146 // [0] Just name
6147 // [1..14] Alliance honor titles and player name
6148 // [15..28] Horde honor titles and player name
6149 // [29..38] Other title and player name
6150 // [39+] Nothing
6151 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
6152 // Get Killer titles, CharTitlesEntry::bit_index
6153 // Ranks:
6154 // title[1..14] -> rank[5..18]
6155 // title[15..28] -> rank[5..18]
6156 // title[other] -> 0
6157 if (victim_title == 0)
6158 victim_guid = 0; // Don't show HK: <rank> message, only log.
6159 else if (victim_title < 15)
6160 victim_rank = victim_title + 4;
6161 else if (victim_title < 29)
6162 victim_rank = victim_title - 14 + 4;
6163 else
6164 victim_guid = 0; // Don't show HK: <rank> message, only log.
6167 k_grey = MaNGOS::XP::GetGrayLevel(k_level);
6169 if(v_level<=k_grey)
6170 return false;
6172 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
6174 int32 v_rank =1; //need more info
6176 honor = ((f * diff_level * (190 + v_rank*10))/6);
6177 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
6179 // count the number of playerkills in one day
6180 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
6181 // and those in a lifetime
6182 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
6183 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL);
6184 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS, pVictim->getClass());
6185 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE, pVictim->getRace());
6187 else
6189 Creature *cVictim = (Creature *)uVictim;
6191 if (!cVictim->isRacialLeader())
6192 return false;
6194 honor = 100; // ??? need more info
6195 victim_rank = 19; // HK: Leader
6199 if (uVictim != NULL)
6201 honor *= sWorld.getRate(RATE_HONOR);
6202 honor *= (GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN) + 100.0f)/100.0f;
6204 if(groupsize > 1)
6205 honor /= groupsize;
6207 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6210 // honor - for show honor points in log
6211 // victim_guid - for show victim name in log
6212 // victim_rank [1..4] HK: <dishonored rank>
6213 // victim_rank [5..19] HK: <alliance\horde rank>
6214 // victim_rank [0,20+] HK: <>
6215 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
6216 data << (uint32) honor;
6217 data << (uint64) victim_guid;
6218 data << (uint32) victim_rank;
6220 GetSession()->SendPacket(&data);
6222 // add honor points
6223 ModifyHonorPoints(int32(honor));
6225 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
6226 return true;
6229 void Player::ModifyHonorPoints( int32 value )
6231 if(value < 0)
6233 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
6234 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
6235 else
6236 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6238 else
6239 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6242 void Player::ModifyArenaPoints( int32 value )
6244 if(value < 0)
6246 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6247 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6248 else
6249 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6251 else
6252 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6255 uint32 Player::GetGuildIdFromDB(uint64 guid)
6257 QueryResult* result = CharacterDatabase.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid));
6258 if(!result)
6259 return 0;
6261 uint32 id = result->Fetch()[0].GetUInt32();
6262 delete result;
6263 return id;
6266 uint32 Player::GetRankFromDB(uint64 guid)
6268 QueryResult *result = CharacterDatabase.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid) );
6269 if( result )
6271 uint32 v = result->Fetch()[0].GetUInt32();
6272 delete result;
6273 return v;
6275 else
6276 return 0;
6279 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6281 QueryResult *result = CharacterDatabase.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u' AND type='%u' LIMIT 1", GUID_LOPART(guid), type);
6282 if(!result)
6283 return 0;
6285 uint32 id = (*result)[0].GetUInt32();
6286 delete result;
6287 return id;
6290 uint32 Player::GetZoneIdFromDB(uint64 guid)
6292 uint32 guidLow = GUID_LOPART(guid);
6293 QueryResult *result = CharacterDatabase.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow );
6294 if (!result)
6295 return 0;
6296 Field* fields = result->Fetch();
6297 uint32 zone = fields[0].GetUInt32();
6298 delete result;
6300 if (!zone)
6302 // stored zone is zero, use generic and slow zone detection
6303 result = CharacterDatabase.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow);
6304 if( !result )
6305 return 0;
6306 fields = result->Fetch();
6307 uint32 map = fields[0].GetUInt32();
6308 float posx = fields[1].GetFloat();
6309 float posy = fields[2].GetFloat();
6310 float posz = fields[3].GetFloat();
6311 delete result;
6313 zone = sMapMgr.GetZoneId(map,posx,posy,posz);
6315 if (zone > 0)
6316 CharacterDatabase.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone, guidLow);
6319 return zone;
6322 uint32 Player::GetLevelFromDB(uint64 guid)
6324 QueryResult *result = CharacterDatabase.PQuery( "SELECT level FROM characters WHERE guid='%u'", GUID_LOPART(guid) );
6325 if (!result)
6326 return 0;
6328 Field* fields = result->Fetch();
6329 uint32 level = fields[0].GetUInt32();
6330 delete result;
6332 return level;
6335 void Player::UpdateArea(uint32 newArea)
6337 // FFA_PVP flags are area and not zone id dependent
6338 // so apply them accordingly
6339 m_areaUpdateId = newArea;
6341 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6343 if(area && (area->flags & AREA_FLAG_ARENA))
6345 if(!isGameMaster())
6346 SetFFAPvP(true);
6348 else
6350 // remove ffa flag only if not ffapvp realm
6351 // removal in sanctuaries and capitals is handled in zone update
6352 if(IsFFAPvP() && !sWorld.IsFFAPvPRealm())
6353 SetFFAPvP(false);
6356 UpdateAreaDependentAuras(newArea);
6359 void Player::UpdateZone(uint32 newZone, uint32 newArea)
6361 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6362 if(!zone)
6363 return;
6365 if(m_zoneUpdateId != newZone)
6367 SendInitWorldStates(newZone, newArea); // only if really enters to new zone, not just area change, works strange...
6369 if (sWorld.getConfig(CONFIG_WEATHER))
6371 if(Weather *wth = sWorld.FindWeather(zone->ID))
6372 wth->SendWeatherUpdateToPlayer(this);
6373 else if(!sWorld.AddWeather(zone->ID))
6375 // send fine weather packet to remove old zone's weather
6376 Weather::SendFineWeatherUpdateToPlayer(this);
6381 m_zoneUpdateId = newZone;
6382 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6384 // zone changed, so area changed as well, update it
6385 UpdateArea(newArea);
6387 // in PvP, any not controlled zone (except zone->team == 6, default case)
6388 // in PvE, only opposition team capital
6389 switch(zone->team)
6391 case AREATEAM_ALLY:
6392 pvpInfo.inHostileArea = GetTeam() != ALLIANCE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6393 break;
6394 case AREATEAM_HORDE:
6395 pvpInfo.inHostileArea = GetTeam() != HORDE && (sWorld.IsPvPRealm() || zone->flags & AREA_FLAG_CAPITAL);
6396 break;
6397 case AREATEAM_NONE:
6398 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6399 pvpInfo.inHostileArea = sWorld.IsPvPRealm() || InBattleGround();
6400 break;
6401 default: // 6 in fact
6402 pvpInfo.inHostileArea = false;
6403 break;
6406 if(pvpInfo.inHostileArea) // in hostile area
6408 if(!IsPvP() || pvpInfo.endTimer != 0)
6409 UpdatePvP(true, true);
6411 else // in friendly area
6413 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6414 pvpInfo.endTimer = time(0); // start toggle-off
6417 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6419 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6420 if(sWorld.IsFFAPvPRealm())
6421 SetFFAPvP(false);
6423 else
6425 RemoveByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_SANCTUARY);
6428 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6430 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6431 SetRestType(REST_TYPE_IN_CITY);
6432 InnEnter(time(0),GetMapId(),0,0,0);
6434 if(sWorld.IsFFAPvPRealm())
6435 SetFFAPvP(false);
6437 else // anywhere else
6439 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6441 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6443 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6445 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6446 SetRestType(REST_TYPE_NO);
6448 if(sWorld.IsFFAPvPRealm())
6449 SetFFAPvP(true);
6452 else // not in tavern (leave city then)
6454 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6455 SetRestType(REST_TYPE_NO);
6457 // Set player to FFA PVP when not in rested environment.
6458 if(sWorld.IsFFAPvPRealm())
6459 SetFFAPvP(true);
6464 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6465 // if player resurrected at teleport this will be applied in resurrect code
6466 if(isAlive())
6467 DestroyZoneLimitedItem( true, newZone );
6469 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6470 AutoUnequipOffhandIfNeed();
6472 // recent client version not send leave/join channel packets for built-in local channels
6473 UpdateLocalChannels( newZone );
6475 // group update
6476 if(GetGroup())
6477 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6479 UpdateZoneDependentAuras(newZone);
6482 //If players are too far way of duel flag... then player loose the duel
6483 void Player::CheckDuelDistance(time_t currTime)
6485 if(!duel)
6486 return;
6488 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6489 GameObject* obj = GetMap()->GetGameObject(duelFlagGUID);
6490 if(!obj)
6491 return;
6493 if(duel->outOfBound == 0)
6495 if(!IsWithinDistInMap(obj, 50))
6497 duel->outOfBound = currTime;
6499 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6500 GetSession()->SendPacket(&data);
6503 else
6505 if(IsWithinDistInMap(obj, 40))
6507 duel->outOfBound = 0;
6509 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6510 GetSession()->SendPacket(&data);
6512 else if(currTime >= (duel->outOfBound+10))
6514 DuelComplete(DUEL_FLED);
6519 void Player::DuelComplete(DuelCompleteType type)
6521 // duel not requested
6522 if(!duel)
6523 return;
6525 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6526 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6527 GetSession()->SendPacket(&data);
6528 duel->opponent->GetSession()->SendPacket(&data);
6530 if(type != DUEL_INTERUPTED)
6532 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6533 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6534 data << duel->opponent->GetName();
6535 data << GetName();
6536 SendMessageToSet(&data,true);
6539 if (type == DUEL_WON)
6541 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL, 1);
6542 if (duel->opponent)
6543 duel->opponent->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL, 1);
6546 //Remove Duel Flag object
6547 GameObject* obj = GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER));
6548 if(obj)
6549 duel->initiator->RemoveGameObject(obj,true);
6551 /* remove auras */
6552 std::vector<uint32> auras2remove;
6553 AuraMap const& vAuras = duel->opponent->GetAuras();
6554 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6556 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6557 auras2remove.push_back(i->second->GetId());
6560 for(size_t i=0; i<auras2remove.size(); ++i)
6561 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6563 auras2remove.clear();
6564 AuraMap const& auras = GetAuras();
6565 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6567 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6568 auras2remove.push_back(i->second->GetId());
6570 for(size_t i=0; i<auras2remove.size(); ++i)
6571 RemoveAurasDueToSpell(auras2remove[i]);
6573 // cleanup combo points
6574 if(GetComboTarget()==duel->opponent->GetGUID())
6575 ClearComboPoints();
6576 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6577 ClearComboPoints();
6579 if(duel->opponent->GetComboTarget()==GetGUID())
6580 duel->opponent->ClearComboPoints();
6581 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6582 duel->opponent->ClearComboPoints();
6584 //cleanups
6585 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6586 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6587 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6588 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6590 delete duel->opponent->duel;
6591 duel->opponent->duel = NULL;
6592 delete duel;
6593 duel = NULL;
6596 //---------------------------------------------------------//
6598 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6600 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6601 return;
6603 // not apply/remove mods for broken item
6604 if(item->IsBroken())
6605 return;
6607 ItemPrototype const *proto = item->GetProto();
6609 if(!proto)
6610 return;
6612 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6614 uint32 attacktype = Player::GetAttackBySlot(slot);
6615 if(attacktype < MAX_ATTACK)
6616 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6618 _ApplyItemBonuses(proto,slot,apply);
6620 if( slot==EQUIPMENT_SLOT_RANGED )
6621 _ApplyAmmoBonuses();
6623 ApplyItemEquipSpell(item,apply);
6624 ApplyEnchantment(item, apply);
6626 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6627 CorrectMetaGemEnchants(slot, apply);
6629 sLog.outDebug("_ApplyItemMods complete.");
6632 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply, bool only_level_scale /*= false*/)
6634 if (slot >= INVENTORY_SLOT_BAG_END || !proto)
6635 return;
6637 ScalingStatDistributionEntry const *ssd = proto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution) : NULL;
6638 if (only_level_scale && !ssd)
6639 return;
6641 // req. check at equip, but allow use for extended range if range limit max level, set proper level
6642 uint32 ssd_level = getLevel();
6643 if (ssd && ssd_level > ssd->MaxLevel)
6644 ssd_level = ssd->MaxLevel;
6646 ScalingStatValuesEntry const *ssv = proto->ScalingStatValue ? sScalingStatValuesStore.LookupEntry(ssd_level) : NULL;
6647 if (only_level_scale && !ssv)
6648 return;
6650 for (int i = 0; i < MAX_ITEM_PROTO_STATS; ++i)
6652 uint32 statType = 0;
6653 int32 val = 0;
6654 // If set ScalingStatDistribution need get stats and values from it
6655 if (ssd && ssv)
6657 if (ssd->StatMod[i] < 0)
6658 continue;
6659 statType = ssd->StatMod[i];
6660 val = (ssv->getssdMultiplier(proto->ScalingStatValue) * ssd->Modifier[i]) / 10000;
6662 else
6664 if (i >= proto->StatsCount)
6665 continue;
6666 statType = proto->ItemStat[i].ItemStatType;
6667 val = proto->ItemStat[i].ItemStatValue;
6670 if(val == 0)
6671 continue;
6673 switch (statType)
6675 case ITEM_MOD_MANA:
6676 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6677 break;
6678 case ITEM_MOD_HEALTH: // modify HP
6679 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6680 break;
6681 case ITEM_MOD_AGILITY: // modify agility
6682 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6683 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6684 break;
6685 case ITEM_MOD_STRENGTH: //modify strength
6686 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6687 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6688 break;
6689 case ITEM_MOD_INTELLECT: //modify intellect
6690 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6691 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6692 break;
6693 case ITEM_MOD_SPIRIT: //modify spirit
6694 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6695 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6696 break;
6697 case ITEM_MOD_STAMINA: //modify stamina
6698 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6699 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6700 break;
6701 case ITEM_MOD_DEFENSE_SKILL_RATING:
6702 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6703 break;
6704 case ITEM_MOD_DODGE_RATING:
6705 ApplyRatingMod(CR_DODGE, int32(val), apply);
6706 break;
6707 case ITEM_MOD_PARRY_RATING:
6708 ApplyRatingMod(CR_PARRY, int32(val), apply);
6709 break;
6710 case ITEM_MOD_BLOCK_RATING:
6711 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6712 break;
6713 case ITEM_MOD_HIT_MELEE_RATING:
6714 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6715 break;
6716 case ITEM_MOD_HIT_RANGED_RATING:
6717 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6718 break;
6719 case ITEM_MOD_HIT_SPELL_RATING:
6720 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6721 break;
6722 case ITEM_MOD_CRIT_MELEE_RATING:
6723 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6724 break;
6725 case ITEM_MOD_CRIT_RANGED_RATING:
6726 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6727 break;
6728 case ITEM_MOD_CRIT_SPELL_RATING:
6729 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6730 break;
6731 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6732 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6733 break;
6734 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6735 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6736 break;
6737 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6738 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6739 break;
6740 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6741 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6742 break;
6743 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6744 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6745 break;
6746 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6747 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6748 break;
6749 case ITEM_MOD_HASTE_MELEE_RATING:
6750 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6751 break;
6752 case ITEM_MOD_HASTE_RANGED_RATING:
6753 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6754 break;
6755 case ITEM_MOD_HASTE_SPELL_RATING:
6756 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6757 break;
6758 case ITEM_MOD_HIT_RATING:
6759 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6760 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6761 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6762 break;
6763 case ITEM_MOD_CRIT_RATING:
6764 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6765 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6766 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6767 break;
6768 case ITEM_MOD_HIT_TAKEN_RATING:
6769 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6770 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6771 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6772 break;
6773 case ITEM_MOD_CRIT_TAKEN_RATING:
6774 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6775 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6776 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6777 break;
6778 case ITEM_MOD_RESILIENCE_RATING:
6779 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6780 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6781 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6782 break;
6783 case ITEM_MOD_HASTE_RATING:
6784 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6785 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6786 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6787 break;
6788 case ITEM_MOD_EXPERTISE_RATING:
6789 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6790 break;
6791 case ITEM_MOD_ATTACK_POWER:
6792 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(val), apply);
6793 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6794 break;
6795 case ITEM_MOD_RANGED_ATTACK_POWER:
6796 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(val), apply);
6797 break;
6798 case ITEM_MOD_MANA_REGENERATION:
6799 ApplyManaRegenBonus(int32(val), apply);
6800 break;
6801 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6802 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6803 break;
6804 case ITEM_MOD_SPELL_POWER:
6805 ApplySpellPowerBonus(int32(val), apply);
6806 break;
6807 // depricated item mods
6808 case ITEM_MOD_FERAL_ATTACK_POWER:
6809 case ITEM_MOD_SPELL_HEALING_DONE:
6810 case ITEM_MOD_SPELL_DAMAGE_DONE:
6811 break;
6815 // Apply Spell Power from ScalingStatValue if set
6816 if(ssv)
6818 if (int32 spellbonus = ssv->getSpellBonus(proto->ScalingStatValue))
6819 ApplySpellPowerBonus(spellbonus, apply);
6822 // If set ScalingStatValue armor get it or use item armor
6823 uint32 armor = proto->Armor;
6824 if (ssv)
6826 if (uint32 ssvarmor = ssv->getArmorMod(proto->ScalingStatValue))
6827 armor = ssvarmor;
6829 // Add armor bonus from ArmorDamageModifier if > 0
6830 if (proto->ArmorDamageModifier > 0)
6831 armor += uint32(proto->ArmorDamageModifier);
6833 if (armor)
6834 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(armor), apply);
6836 if (proto->Block)
6837 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6839 if (proto->HolyRes)
6840 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6842 if (proto->FireRes)
6843 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6845 if (proto->NatureRes)
6846 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6848 if (proto->FrostRes)
6849 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6851 if (proto->ShadowRes)
6852 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6854 if (proto->ArcaneRes)
6855 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6857 WeaponAttackType attType = BASE_ATTACK;
6858 float damage = 0.0f;
6860 if( slot == EQUIPMENT_SLOT_RANGED && (
6861 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6862 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6864 attType = RANGED_ATTACK;
6866 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6868 attType = OFF_ATTACK;
6871 float minDamage = proto->Damage[0].DamageMin;
6872 float maxDamage = proto->Damage[0].DamageMax;
6873 int32 extraDPS = 0;
6874 // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
6875 if (ssv)
6877 if ((extraDPS = ssv->getDPSMod(proto->ScalingStatValue)))
6879 float average = extraDPS * proto->Delay / 1000.0f;
6880 minDamage = 0.7f * average;
6881 maxDamage = 1.3f * average;
6884 if (minDamage > 0 )
6886 damage = apply ? minDamage : BASE_MINDAMAGE;
6887 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6888 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6891 if (maxDamage > 0 )
6893 damage = apply ? maxDamage : BASE_MAXDAMAGE;
6894 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6897 // Apply feral bonus from ScalingStatValue if set
6898 if (ssv)
6900 if (int32 feral_bonus = ssv->getFeralBonus(proto->ScalingStatValue))
6901 ApplyFeralAPBonus(feral_bonus, apply);
6903 // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
6904 if(getClass() == CLASS_DRUID)
6906 int32 feral_bonus = proto->getFeralBonus(extraDPS);
6907 if (feral_bonus > 0)
6908 ApplyFeralAPBonus(feral_bonus, apply);
6911 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6912 return;
6914 if (proto->Delay)
6916 if(slot == EQUIPMENT_SLOT_RANGED)
6917 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6918 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6919 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6920 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6921 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6924 if(CanModifyStats() && (damage || proto->Delay))
6925 UpdateDamagePhysical(attType);
6928 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6930 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6931 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6932 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6934 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6935 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6936 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6938 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6939 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6940 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6943 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6945 // generic not weapon specific case processes in aura code
6946 if(aura->GetSpellProto()->EquippedItemClass == -1)
6947 return;
6949 BaseModGroup mod = BASEMOD_END;
6950 switch(attackType)
6952 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6953 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6954 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6955 default: return;
6958 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6960 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6964 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6966 // ignore spell mods for not wands
6967 Modifier const* modifier = aura->GetModifier();
6968 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6969 return;
6971 // generic not weapon specific case processes in aura code
6972 if(aura->GetSpellProto()->EquippedItemClass == -1)
6973 return;
6975 UnitMods unitMod = UNIT_MOD_END;
6976 switch(attackType)
6978 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6979 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6980 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6981 default: return;
6984 UnitModifierType unitModType = TOTAL_VALUE;
6985 switch(modifier->m_auraname)
6987 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6988 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6989 default: return;
6992 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6994 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6998 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
7000 if(!item)
7001 return;
7003 ItemPrototype const *proto = item->GetProto();
7004 if(!proto)
7005 return;
7007 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7009 _Spell const& spellData = proto->Spells[i];
7011 // no spell
7012 if(!spellData.SpellId )
7013 continue;
7015 // wrong triggering type
7016 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
7017 continue;
7019 // check if it is valid spell
7020 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
7021 if(!spellproto)
7022 continue;
7024 ApplyEquipSpell(spellproto,item,apply,form_change);
7028 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
7030 if(apply)
7032 // Cannot be used in this stance/form
7033 if(GetErrorAtShapeshiftedCast(spellInfo, m_form) != SPELL_CAST_OK)
7034 return;
7036 if(form_change) // check aura active state from other form
7038 bool found = false;
7039 for (int k=0; k < 3; ++k)
7041 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
7042 for (AuraMap::const_iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
7044 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
7046 found = true;
7047 break;
7050 if(found)
7051 break;
7054 if(found) // and skip re-cast already active aura at form change
7055 return;
7058 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
7060 CastSpell(this,spellInfo,true,item);
7062 else
7064 if(form_change) // check aura compatibility
7066 // Cannot be used in this stance/form
7067 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==SPELL_CAST_OK)
7068 return; // and remove only not compatible at form change
7071 if(item)
7072 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
7073 else
7074 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
7078 void Player::UpdateEquipSpellsAtFormChange()
7080 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7082 if(m_items[i] && !m_items[i]->IsBroken())
7084 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
7085 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
7089 // item set bonuses not dependent from item broken state
7090 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
7092 ItemSetEffect* eff = ItemSetEff[setindex];
7093 if(!eff)
7094 continue;
7096 for(uint32 y=0;y<8; ++y)
7098 SpellEntry const* spellInfo = eff->spells[y];
7099 if(!spellInfo)
7100 continue;
7102 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
7103 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
7108 void Player::CastItemCombatSpell(Unit* Target, WeaponAttackType attType)
7110 Item *item = GetWeaponForAttack(attType, true, false);
7111 if(!item)
7112 return;
7114 ItemPrototype const *proto = item->GetProto();
7115 if(!proto)
7116 return;
7118 if (!Target || Target == this )
7119 return;
7121 for (int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7123 _Spell const& spellData = proto->Spells[i];
7125 // no spell
7126 if(!spellData.SpellId )
7127 continue;
7129 // wrong triggering type
7130 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
7131 continue;
7133 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7134 if(!spellInfo)
7136 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
7137 continue;
7140 // not allow proc extra attack spell at extra attack
7141 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
7142 return;
7144 float chance = spellInfo->procChance;
7146 if(spellData.SpellPPMRate)
7148 uint32 WeaponSpeed = proto->Delay;
7149 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
7151 else if(chance > 100.0f)
7153 chance = GetWeaponProcChance();
7156 if (roll_chance_f(chance))
7157 CastSpell(Target, spellInfo->Id, true, item);
7160 // item combat enchantments
7161 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7163 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7164 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7165 if(!pEnchant) continue;
7166 for (int s=0;s<3;s++)
7168 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
7169 continue;
7171 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7172 if (!spellInfo)
7174 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7175 continue;
7178 // Use first rank to access spell item enchant procs
7179 float ppmRate = sSpellMgr.GetItemEnchantProcChance(spellInfo->Id);
7181 float chance = ppmRate
7182 ? GetPPMProcChance(proto->Delay, ppmRate)
7183 : pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
7186 ApplySpellMod(spellInfo->Id,SPELLMOD_CHANCE_OF_SUCCESS,chance);
7187 ApplySpellMod(spellInfo->Id,SPELLMOD_FREQUENCY_OF_SUCCESS,chance);
7189 if (roll_chance_f(chance))
7191 if(IsPositiveSpell(pEnchant->spellid[s]))
7192 CastSpell(this, pEnchant->spellid[s], true, item);
7193 else
7194 CastSpell(Target, pEnchant->spellid[s], true, item);
7200 void Player::CastItemUseSpell(Item *item,SpellCastTargets const& targets,uint8 cast_count, uint32 glyphIndex)
7202 ItemPrototype const* proto = item->GetProto();
7203 // special learning case
7204 if(proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN || proto->Spells[0].SpellId==SPELL_ID_GENERIC_LEARN_PET)
7206 uint32 learn_spell_id = proto->Spells[0].SpellId;
7207 uint32 learning_spell_id = proto->Spells[1].SpellId;
7209 SpellEntry const *spellInfo = sSpellStore.LookupEntry(learn_spell_id);
7210 if(!spellInfo)
7212 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto->ItemId, learn_spell_id);
7213 SendEquipError(EQUIP_ERR_NONE,item,NULL);
7214 return;
7217 Spell *spell = new Spell(this, spellInfo, false);
7218 spell->m_CastItem = item;
7219 spell->m_cast_count = cast_count; //set count of casts
7220 spell->m_currentBasePoints[0] = learning_spell_id;
7221 spell->prepare(&targets);
7222 return;
7225 // use triggered flag only for items with many spell casts and for not first cast
7226 int count = 0;
7228 // item spells casted at use
7229 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
7231 _Spell const& spellData = proto->Spells[i];
7233 // no spell
7234 if(!spellData.SpellId)
7235 continue;
7237 // wrong triggering type
7238 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_NO_DELAY_USE)
7239 continue;
7241 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
7242 if(!spellInfo)
7244 sLog.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto->ItemId, spellData.SpellId);
7245 continue;
7248 Spell *spell = new Spell(this, spellInfo, (count > 0));
7249 spell->m_CastItem = item;
7250 spell->m_cast_count = cast_count; // set count of casts
7251 spell->m_glyphIndex = glyphIndex; // glyph index
7252 spell->prepare(&targets);
7254 ++count;
7257 // Item enchantments spells casted at use
7258 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
7260 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
7261 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
7262 if(!pEnchant) continue;
7263 for (int s=0;s<3;s++)
7265 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL)
7266 continue;
7268 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
7269 if (!spellInfo)
7271 sLog.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
7272 continue;
7275 Spell *spell = new Spell(this, spellInfo, (count > 0));
7276 spell->m_CastItem = item;
7277 spell->m_cast_count = cast_count; // set count of casts
7278 spell->m_glyphIndex = glyphIndex; // glyph index
7279 spell->prepare(&targets);
7281 ++count;
7286 void Player::_RemoveAllItemMods()
7288 sLog.outDebug("_RemoveAllItemMods start.");
7290 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7292 if(m_items[i])
7294 ItemPrototype const *proto = m_items[i]->GetProto();
7295 if(!proto)
7296 continue;
7298 // item set bonuses not dependent from item broken state
7299 if(proto->ItemSet)
7300 RemoveItemsSetItem(this,proto);
7302 if(m_items[i]->IsBroken())
7303 continue;
7305 ApplyItemEquipSpell(m_items[i],false);
7306 ApplyEnchantment(m_items[i], false);
7310 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7312 if(m_items[i])
7314 if(m_items[i]->IsBroken())
7315 continue;
7316 ItemPrototype const *proto = m_items[i]->GetProto();
7317 if(!proto)
7318 continue;
7320 uint32 attacktype = Player::GetAttackBySlot(i);
7321 if(attacktype < MAX_ATTACK)
7322 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
7324 _ApplyItemBonuses(proto,i, false);
7326 if( i == EQUIPMENT_SLOT_RANGED )
7327 _ApplyAmmoBonuses();
7331 sLog.outDebug("_RemoveAllItemMods complete.");
7334 void Player::_ApplyAllItemMods()
7336 sLog.outDebug("_ApplyAllItemMods start.");
7338 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7340 if(m_items[i])
7342 if(m_items[i]->IsBroken())
7343 continue;
7345 ItemPrototype const *proto = m_items[i]->GetProto();
7346 if(!proto)
7347 continue;
7349 uint32 attacktype = Player::GetAttackBySlot(i);
7350 if(attacktype < MAX_ATTACK)
7351 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7353 _ApplyItemBonuses(proto,i, true);
7355 if( i == EQUIPMENT_SLOT_RANGED )
7356 _ApplyAmmoBonuses();
7360 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7362 if(m_items[i])
7364 ItemPrototype const *proto = m_items[i]->GetProto();
7365 if(!proto)
7366 continue;
7368 // item set bonuses not dependent from item broken state
7369 if(proto->ItemSet)
7370 AddItemsSetItem(this,m_items[i]);
7372 if(m_items[i]->IsBroken())
7373 continue;
7375 ApplyItemEquipSpell(m_items[i],true);
7376 ApplyEnchantment(m_items[i], true);
7380 sLog.outDebug("_ApplyAllItemMods complete.");
7383 void Player::_ApplyAllLevelScaleItemMods(bool apply)
7385 for (int i = 0; i < INVENTORY_SLOT_BAG_END; ++i)
7387 if(m_items[i])
7389 if(m_items[i]->IsBroken())
7390 continue;
7392 ItemPrototype const *proto = m_items[i]->GetProto();
7393 if(!proto)
7394 continue;
7396 _ApplyItemBonuses(proto,i, apply, true);
7401 void Player::_ApplyAmmoBonuses()
7403 // check ammo
7404 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7405 if(!ammo_id)
7406 return;
7408 float currentAmmoDPS;
7410 ItemPrototype const *ammo_proto = ObjectMgr::GetItemPrototype( ammo_id );
7411 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7412 currentAmmoDPS = 0.0f;
7413 else
7414 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7416 if(currentAmmoDPS == GetAmmoDPS())
7417 return;
7419 m_ammoDPS = currentAmmoDPS;
7421 if(CanModifyStats())
7422 UpdateDamagePhysical(RANGED_ATTACK);
7425 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7427 if(!ammo_proto)
7428 return false;
7430 // check ranged weapon
7431 Item *weapon = GetWeaponForAttack( RANGED_ATTACK, true, false );
7432 if (!weapon)
7433 return false;
7435 ItemPrototype const* weapon_proto = weapon->GetProto();
7436 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7437 return false;
7439 // check ammo ws. weapon compatibility
7440 switch(weapon_proto->SubClass)
7442 case ITEM_SUBCLASS_WEAPON_BOW:
7443 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7444 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7445 return false;
7446 break;
7447 case ITEM_SUBCLASS_WEAPON_GUN:
7448 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7449 return false;
7450 break;
7451 default:
7452 return false;
7455 return true;
7458 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7459 Called by remove insignia spell effect */
7460 void Player::RemovedInsignia(Player* looterPlr)
7462 if (!GetBattleGroundId())
7463 return;
7465 // If not released spirit, do it !
7466 if(m_deathTimer > 0)
7468 m_deathTimer = 0;
7469 BuildPlayerRepop();
7470 RepopAtGraveyard();
7473 Corpse *corpse = GetCorpse();
7474 if (!corpse)
7475 return;
7477 // We have to convert player corpse to bones, not to be able to resurrect there
7478 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7479 Corpse *bones = sObjectAccessor.ConvertCorpseForPlayer(GetGUID(),true);
7480 if (!bones)
7481 return;
7483 // Now we must make bones lootable, and send player loot
7484 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7486 // We store the level of our player in the gold field
7487 // We retrieve this information at Player::SendLoot()
7488 bones->loot.gold = getLevel();
7489 bones->lootRecipient = looterPlr;
7490 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7493 void Player::SendLootRelease( uint64 guid )
7495 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7496 data << uint64(guid) << uint8(1);
7497 SendDirectMessage( &data );
7500 void Player::SendLoot(uint64 guid, LootType loot_type)
7502 if (uint64 lguid = GetLootGUID())
7503 m_session->DoLootRelease(lguid);
7505 Loot *loot = 0;
7506 PermissionTypes permission = ALL_PERMISSION;
7508 sLog.outDebug("Player::SendLoot");
7509 if (IS_GAMEOBJECT_GUID(guid))
7511 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7512 GameObject *go = GetMap()->GetGameObject(guid);
7514 // not check distance for GO in case owned GO (fishing bobber case, for example)
7515 // And permit out of range GO with no owner in case fishing hole
7516 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7518 SendLootRelease(guid);
7519 return;
7522 loot = &go->loot;
7524 if (go->getLootState() == GO_READY)
7526 uint32 lootid = go->GetGOInfo()->GetLootId();
7527 if ((go->GetEntry() == BG_AV_OBJECTID_MINE_N || go->GetEntry() == BG_AV_OBJECTID_MINE_S))
7528 if (BattleGround *bg = GetBattleGround())
7529 if (bg->GetTypeID() == BATTLEGROUND_AV)
7530 if (!(((BattleGroundAV*)bg)->PlayerCanDoMineQuest(go->GetEntry(), GetTeam())))
7532 SendLootRelease(guid);
7533 return;
7536 if (lootid)
7538 sLog.outDebug(" if(lootid)");
7539 loot->clear();
7540 loot->FillLoot(lootid, LootTemplates_Gameobject, this, false);
7543 if (loot_type == LOOT_FISHING)
7544 go->getFishLoot(loot,this);
7546 go->SetLootState(GO_ACTIVATED);
7549 else if (IS_ITEM_GUID(guid))
7551 Item *item = GetItemByGuid( guid );
7553 if (!item)
7555 SendLootRelease(guid);
7556 return;
7559 loot = &item->loot;
7561 if (!item->m_lootGenerated)
7563 item->m_lootGenerated = true;
7564 loot->clear();
7566 switch(loot_type)
7568 case LOOT_DISENCHANTING:
7569 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this,true);
7570 break;
7571 case LOOT_PROSPECTING:
7572 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this,true);
7573 break;
7574 case LOOT_MILLING:
7575 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this,true);
7576 break;
7577 default:
7578 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this,true);
7579 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7580 break;
7584 else if (IS_CORPSE_GUID(guid)) // remove insignia
7586 Corpse *bones = GetMap()->GetCorpse(guid);
7588 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7590 SendLootRelease(guid);
7591 return;
7594 loot = &bones->loot;
7596 if (!bones->lootForBody)
7598 bones->lootForBody = true;
7599 uint32 pLevel = bones->loot.gold;
7600 bones->loot.clear();
7601 if (GetBattleGround()->GetTypeID() == BATTLEGROUND_AV)
7602 loot->FillLoot(0, LootTemplates_Creature, this, false);
7603 // It may need a better formula
7604 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7605 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7608 if (bones->lootRecipient != this)
7609 permission = NONE_PERMISSION;
7611 else
7613 Creature *creature = GetMap()->GetCreature(guid);
7615 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7616 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7618 SendLootRelease(guid);
7619 return;
7622 if (loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7624 SendLootRelease(guid);
7625 return;
7628 loot = &creature->loot;
7630 if (loot_type == LOOT_PICKPOCKETING)
7632 if (!creature->lootForPickPocketed)
7634 creature->lootForPickPocketed = true;
7635 loot->clear();
7637 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7638 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this, false);
7640 // Generate extra money for pick pocket loot
7641 const uint32 a = urand(0, creature->getLevel()/2);
7642 const uint32 b = urand(0, getLevel()/2);
7643 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7646 else
7648 // the player whose group may loot the corpse
7649 Player *recipient = creature->GetLootRecipient();
7650 if (!recipient)
7652 creature->SetLootRecipient(this);
7653 recipient = this;
7656 if (creature->lootForPickPocketed)
7658 creature->lootForPickPocketed = false;
7659 loot->clear();
7662 if (!creature->lootForBody)
7664 creature->lootForBody = true;
7665 loot->clear();
7667 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7668 loot->FillLoot(lootid, LootTemplates_Creature, recipient, false);
7670 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7672 if (Group* group = recipient->GetGroup())
7674 group->UpdateLooterGuid(creature,true);
7676 switch (group->GetLootMethod())
7678 case GROUP_LOOT:
7679 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7680 group->GroupLoot(recipient->GetGUID(), loot, creature);
7681 break;
7682 case NEED_BEFORE_GREED:
7683 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7684 break;
7685 case MASTER_LOOT:
7686 group->MasterLoot(recipient->GetGUID(), loot, creature);
7687 break;
7688 default:
7689 break;
7694 // possible only if creature->lootForBody && loot->empty() at spell cast check
7695 if (loot_type == LOOT_SKINNING)
7697 loot->clear();
7698 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this, false);
7700 // set group rights only for loot_type != LOOT_SKINNING
7701 else
7703 if(Group* group = GetGroup())
7705 if (group == recipient->GetGroup())
7707 if (group->GetLootMethod() == FREE_FOR_ALL)
7708 permission = ALL_PERMISSION;
7709 else if (group->GetLooterGuid() == GetGUID())
7711 if (group->GetLootMethod() == MASTER_LOOT)
7712 permission = MASTER_PERMISSION;
7713 else
7714 permission = ALL_PERMISSION;
7716 else
7717 permission = GROUP_PERMISSION;
7719 else
7720 permission = NONE_PERMISSION;
7722 else if (recipient == this)
7723 permission = ALL_PERMISSION;
7724 else
7725 permission = NONE_PERMISSION;
7730 SetLootGUID(guid);
7732 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7733 switch(loot_type)
7735 case LOOT_INSIGNIA: loot_type = LOOT_SKINNING; break;
7736 case LOOT_FISHINGHOLE: loot_type = LOOT_FISHING; break;
7737 default: break;
7740 // need know merged fishing/corpse loot type for achievements
7741 loot->loot_type = loot_type;
7743 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7745 data << uint64(guid);
7746 data << uint8(loot_type);
7747 data << LootView(*loot, this, permission);
7749 SendDirectMessage(&data);
7751 // add 'this' player as one of the players that are looting 'loot'
7752 if (permission != NONE_PERMISSION)
7753 loot->AddLooter(GetGUID());
7755 if (loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid))
7756 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7759 void Player::SendNotifyLootMoneyRemoved()
7761 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7762 GetSession()->SendPacket( &data );
7765 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7767 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7768 data << uint8(lootSlot);
7769 GetSession()->SendPacket( &data );
7772 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7774 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7775 data << Field;
7776 data << Value;
7777 GetSession()->SendPacket(&data);
7780 void Player::SendInitWorldStates(uint32 zoneid, uint32 areaid)
7782 // data depends on zoneid/mapid...
7783 BattleGround* bg = GetBattleGround();
7784 uint16 NumberOfFields = 0;
7785 uint32 mapid = GetMapId();
7787 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7789 // may be exist better way to do this...
7790 switch(zoneid)
7792 case 0:
7793 case 1:
7794 case 4:
7795 case 8:
7796 case 10:
7797 case 11:
7798 case 12:
7799 case 36:
7800 case 38:
7801 case 40:
7802 case 41:
7803 case 51:
7804 case 267:
7805 case 1519:
7806 case 1537:
7807 case 2257:
7808 case 2918:
7809 NumberOfFields = 8;
7810 break;
7811 case 139:
7812 NumberOfFields = 41;
7813 break;
7814 case 1377:
7815 NumberOfFields = 15;
7816 break;
7817 case 2597:
7818 NumberOfFields = 83;
7819 break;
7820 case 3277:
7821 NumberOfFields = 16;
7822 break;
7823 case 3358:
7824 case 3820:
7825 NumberOfFields = 40;
7826 break;
7827 case 3483:
7828 NumberOfFields = 27;
7829 break;
7830 case 3518:
7831 NumberOfFields = 39;
7832 break;
7833 case 3519:
7834 NumberOfFields = 38;
7835 break;
7836 case 3521:
7837 NumberOfFields = 37;
7838 break;
7839 case 3698:
7840 case 3702:
7841 case 3968:
7842 NumberOfFields = 11;
7843 break;
7844 case 3703:
7845 NumberOfFields = 11;
7846 break;
7847 default:
7848 NumberOfFields = 12;
7849 break;
7852 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7853 data << uint32(mapid); // mapid
7854 data << uint32(zoneid); // zone id
7855 data << uint32(areaid); // area id, new 2.1.0
7856 data << uint16(NumberOfFields); // count of uint64 blocks
7857 data << uint32(0x8d8) << uint32(0x0); // 1
7858 data << uint32(0x8d7) << uint32(0x0); // 2
7859 data << uint32(0x8d6) << uint32(0x0); // 3
7860 data << uint32(0x8d5) << uint32(0x0); // 4
7861 data << uint32(0x8d4) << uint32(0x0); // 5
7862 data << uint32(0x8d3) << uint32(0x0); // 6
7863 // 7 1 - Arena season in progress, 0 - end of season
7864 data << uint32(0xC77) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS));
7865 // 8 Arena season id
7866 data << uint32(0xF3D) << uint32(sWorld.getConfig(CONFIG_ARENA_SEASON_ID));
7867 if(mapid == 530) // Outland
7869 data << uint32(0x9bf) << uint32(0x0); // 7
7870 data << uint32(0x9bd) << uint32(0xF); // 8
7871 data << uint32(0x9bb) << uint32(0xF); // 9
7873 switch(zoneid)
7875 case 1:
7876 case 11:
7877 case 12:
7878 case 38:
7879 case 40:
7880 case 51:
7881 case 1519:
7882 case 1537:
7883 case 2257:
7884 break;
7885 case 2597: // AV
7886 if (bg && bg->GetTypeID() == BATTLEGROUND_AV)
7887 bg->FillInitialWorldStates(data);
7888 else
7890 data << uint32(0x7ae) << uint32(0x1); // 7 snowfall n
7891 data << uint32(0x532) << uint32(0x1); // 8 frostwolfhut hc
7892 data << uint32(0x531) << uint32(0x0); // 9 frostwolfhut ac
7893 data << uint32(0x52e) << uint32(0x0); // 10 stormpike firstaid a_a
7894 data << uint32(0x571) << uint32(0x0); // 11 east frostwolf tower horde assaulted -unused
7895 data << uint32(0x570) << uint32(0x0); // 12 west frostwolf tower horde assaulted - unused
7896 data << uint32(0x567) << uint32(0x1); // 13 frostwolfe c
7897 data << uint32(0x566) << uint32(0x1); // 14 frostwolfw c
7898 data << uint32(0x550) << uint32(0x1); // 15 irondeep (N) ally
7899 data << uint32(0x544) << uint32(0x0); // 16 ice grave a_a
7900 data << uint32(0x536) << uint32(0x0); // 17 stormpike grave h_c
7901 data << uint32(0x535) << uint32(0x1); // 18 stormpike grave a_c
7902 data << uint32(0x518) << uint32(0x0); // 19 stoneheart grave a_a
7903 data << uint32(0x517) << uint32(0x0); // 20 stoneheart grave h_a
7904 data << uint32(0x574) << uint32(0x0); // 21 1396 unk
7905 data << uint32(0x573) << uint32(0x0); // 22 iceblood tower horde assaulted -unused
7906 data << uint32(0x572) << uint32(0x0); // 23 towerpoint horde assaulted - unused
7907 data << uint32(0x56f) << uint32(0x0); // 24 1391 unk
7908 data << uint32(0x56e) << uint32(0x0); // 25 iceblood a
7909 data << uint32(0x56d) << uint32(0x0); // 26 towerp a
7910 data << uint32(0x56c) << uint32(0x0); // 27 frostwolfe a
7911 data << uint32(0x56b) << uint32(0x0); // 28 froswolfw a
7912 data << uint32(0x56a) << uint32(0x1); // 29 1386 unk
7913 data << uint32(0x569) << uint32(0x1); // 30 iceblood c
7914 data << uint32(0x568) << uint32(0x1); // 31 towerp c
7915 data << uint32(0x565) << uint32(0x0); // 32 stoneh tower a
7916 data << uint32(0x564) << uint32(0x0); // 33 icewing tower a
7917 data << uint32(0x563) << uint32(0x0); // 34 dunn a
7918 data << uint32(0x562) << uint32(0x0); // 35 duns a
7919 data << uint32(0x561) << uint32(0x0); // 36 stoneheart bunker alliance assaulted - unused
7920 data << uint32(0x560) << uint32(0x0); // 37 icewing bunker alliance assaulted - unused
7921 data << uint32(0x55f) << uint32(0x0); // 38 dunbaldar south alliance assaulted - unused
7922 data << uint32(0x55e) << uint32(0x0); // 39 dunbaldar north alliance assaulted - unused
7923 data << uint32(0x55d) << uint32(0x0); // 40 stone tower d
7924 data << uint32(0x3c6) << uint32(0x0); // 41 966 unk
7925 data << uint32(0x3c4) << uint32(0x0); // 42 964 unk
7926 data << uint32(0x3c2) << uint32(0x0); // 43 962 unk
7927 data << uint32(0x516) << uint32(0x1); // 44 stoneheart grave a_c
7928 data << uint32(0x515) << uint32(0x0); // 45 stonheart grave h_c
7929 data << uint32(0x3b6) << uint32(0x0); // 46 950 unk
7930 data << uint32(0x55c) << uint32(0x0); // 47 icewing tower d
7931 data << uint32(0x55b) << uint32(0x0); // 48 dunn d
7932 data << uint32(0x55a) << uint32(0x0); // 49 duns d
7933 data << uint32(0x559) << uint32(0x0); // 50 1369 unk
7934 data << uint32(0x558) << uint32(0x0); // 51 iceblood d
7935 data << uint32(0x557) << uint32(0x0); // 52 towerp d
7936 data << uint32(0x556) << uint32(0x0); // 53 frostwolfe d
7937 data << uint32(0x555) << uint32(0x0); // 54 frostwolfw d
7938 data << uint32(0x554) << uint32(0x1); // 55 stoneh tower c
7939 data << uint32(0x553) << uint32(0x1); // 56 icewing tower c
7940 data << uint32(0x552) << uint32(0x1); // 57 dunn c
7941 data << uint32(0x551) << uint32(0x1); // 58 duns c
7942 data << uint32(0x54f) << uint32(0x0); // 59 irondeep (N) horde
7943 data << uint32(0x54e) << uint32(0x0); // 60 irondeep (N) ally
7944 data << uint32(0x54d) << uint32(0x1); // 61 mine (S) neutral
7945 data << uint32(0x54c) << uint32(0x0); // 62 mine (S) horde
7946 data << uint32(0x54b) << uint32(0x0); // 63 mine (S) ally
7947 data << uint32(0x545) << uint32(0x0); // 64 iceblood h_a
7948 data << uint32(0x543) << uint32(0x1); // 65 iceblod h_c
7949 data << uint32(0x542) << uint32(0x0); // 66 iceblood a_c
7950 data << uint32(0x540) << uint32(0x0); // 67 snowfall h_a
7951 data << uint32(0x53f) << uint32(0x0); // 68 snowfall a_a
7952 data << uint32(0x53e) << uint32(0x0); // 69 snowfall h_c
7953 data << uint32(0x53d) << uint32(0x0); // 70 snowfall a_c
7954 data << uint32(0x53c) << uint32(0x0); // 71 frostwolf g h_a
7955 data << uint32(0x53b) << uint32(0x0); // 72 frostwolf g a_a
7956 data << uint32(0x53a) << uint32(0x1); // 73 frostwolf g h_c
7957 data << uint32(0x539) << uint32(0x0); // 74 frostwolf g a_c
7958 data << uint32(0x538) << uint32(0x0); // 75 stormpike grave h_a
7959 data << uint32(0x537) << uint32(0x0); // 76 stormpike grave a_a
7960 data << uint32(0x534) << uint32(0x0); // 77 frostwolf hut h_a
7961 data << uint32(0x533) << uint32(0x0); // 78 frostwolf hut a_a
7962 data << uint32(0x530) << uint32(0x0); // 79 stormpike first aid h_a
7963 data << uint32(0x52f) << uint32(0x0); // 80 stormpike first aid h_c
7964 data << uint32(0x52d) << uint32(0x1); // 81 stormpike first aid a_c
7966 break;
7967 case 3277: // WS
7968 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7969 bg->FillInitialWorldStates(data);
7970 else
7972 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7973 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7974 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7975 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7976 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7977 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7978 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7979 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7981 break;
7982 case 3358: // AB
7983 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7984 bg->FillInitialWorldStates(data);
7985 else
7987 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7988 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7989 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7990 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7991 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7992 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7993 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7994 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7995 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7996 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7997 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7998 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7999 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
8000 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
8001 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
8002 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
8003 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
8004 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
8005 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
8006 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
8007 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
8008 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
8009 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
8010 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
8011 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
8012 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
8013 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
8014 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
8015 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
8016 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
8017 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
8018 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
8020 break;
8021 case 3820: // EY
8022 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
8023 bg->FillInitialWorldStates(data);
8024 else
8026 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
8027 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
8028 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
8029 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
8030 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
8031 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
8032 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
8033 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
8034 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
8035 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
8036 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
8037 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
8038 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
8039 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
8040 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
8041 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
8042 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
8043 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
8044 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
8045 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
8046 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
8047 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
8048 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
8049 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
8050 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
8051 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
8052 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
8053 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
8054 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
8055 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
8056 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
8057 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
8058 // and some more ... unknown
8060 break;
8061 case 3483: // Hellfire Peninsula
8062 data << uint32(0x9ba) << uint32(0x1); // 10
8063 data << uint32(0x9b9) << uint32(0x1); // 11
8064 data << uint32(0x9b5) << uint32(0x0); // 12
8065 data << uint32(0x9b4) << uint32(0x1); // 13
8066 data << uint32(0x9b3) << uint32(0x0); // 14
8067 data << uint32(0x9b2) << uint32(0x0); // 15
8068 data << uint32(0x9b1) << uint32(0x1); // 16
8069 data << uint32(0x9b0) << uint32(0x0); // 17
8070 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
8071 data << uint32(0x9ac) << uint32(0x0); // 19
8072 data << uint32(0x9a8) << uint32(0x0); // 20
8073 data << uint32(0x9a7) << uint32(0x0); // 21
8074 data << uint32(0x9a6) << uint32(0x1); // 22
8075 break;
8076 case 3519: // Terokkar Forest
8077 data << uint32(0xa41) << uint32(0x0); // 10
8078 data << uint32(0xa40) << uint32(0x14); // 11
8079 data << uint32(0xa3f) << uint32(0x0); // 12
8080 data << uint32(0xa3e) << uint32(0x0); // 13
8081 data << uint32(0xa3d) << uint32(0x5); // 14
8082 data << uint32(0xa3c) << uint32(0x0); // 15
8083 data << uint32(0xa87) << uint32(0x0); // 16
8084 data << uint32(0xa86) << uint32(0x0); // 17
8085 data << uint32(0xa85) << uint32(0x0); // 18
8086 data << uint32(0xa84) << uint32(0x0); // 19
8087 data << uint32(0xa83) << uint32(0x0); // 20
8088 data << uint32(0xa82) << uint32(0x0); // 21
8089 data << uint32(0xa81) << uint32(0x0); // 22
8090 data << uint32(0xa80) << uint32(0x0); // 23
8091 data << uint32(0xa7e) << uint32(0x0); // 24
8092 data << uint32(0xa7d) << uint32(0x0); // 25
8093 data << uint32(0xa7c) << uint32(0x0); // 26
8094 data << uint32(0xa7b) << uint32(0x0); // 27
8095 data << uint32(0xa7a) << uint32(0x0); // 28
8096 data << uint32(0xa79) << uint32(0x0); // 29
8097 data << uint32(0x9d0) << uint32(0x5); // 30
8098 data << uint32(0x9ce) << uint32(0x0); // 31
8099 data << uint32(0x9cd) << uint32(0x0); // 32
8100 data << uint32(0x9cc) << uint32(0x0); // 33
8101 data << uint32(0xa88) << uint32(0x0); // 34
8102 data << uint32(0xad0) << uint32(0x0); // 35
8103 data << uint32(0xacf) << uint32(0x1); // 36
8104 break;
8105 case 3521: // Zangarmarsh
8106 data << uint32(0x9e1) << uint32(0x0); // 10
8107 data << uint32(0x9e0) << uint32(0x0); // 11
8108 data << uint32(0x9df) << uint32(0x0); // 12
8109 data << uint32(0xa5d) << uint32(0x1); // 13
8110 data << uint32(0xa5c) << uint32(0x0); // 14
8111 data << uint32(0xa5b) << uint32(0x1); // 15
8112 data << uint32(0xa5a) << uint32(0x0); // 16
8113 data << uint32(0xa59) << uint32(0x1); // 17
8114 data << uint32(0xa58) << uint32(0x0); // 18
8115 data << uint32(0xa57) << uint32(0x0); // 19
8116 data << uint32(0xa56) << uint32(0x0); // 20
8117 data << uint32(0xa55) << uint32(0x1); // 21
8118 data << uint32(0xa54) << uint32(0x0); // 22
8119 data << uint32(0x9e7) << uint32(0x0); // 23
8120 data << uint32(0x9e6) << uint32(0x0); // 24
8121 data << uint32(0x9e5) << uint32(0x0); // 25
8122 data << uint32(0xa00) << uint32(0x0); // 26
8123 data << uint32(0x9ff) << uint32(0x1); // 27
8124 data << uint32(0x9fe) << uint32(0x0); // 28
8125 data << uint32(0x9fd) << uint32(0x0); // 29
8126 data << uint32(0x9fc) << uint32(0x1); // 30
8127 data << uint32(0x9fb) << uint32(0x0); // 31
8128 data << uint32(0xa62) << uint32(0x0); // 32
8129 data << uint32(0xa61) << uint32(0x1); // 33
8130 data << uint32(0xa60) << uint32(0x1); // 34
8131 data << uint32(0xa5f) << uint32(0x0); // 35
8132 break;
8133 case 3698: // Nagrand Arena
8134 if (bg && bg->GetTypeID() == BATTLEGROUND_NA)
8135 bg->FillInitialWorldStates(data);
8136 else
8138 data << uint32(0xa0f) << uint32(0x0); // 7
8139 data << uint32(0xa10) << uint32(0x0); // 8
8140 data << uint32(0xa11) << uint32(0x0); // 9 show
8142 break;
8143 case 3702: // Blade's Edge Arena
8144 if (bg && bg->GetTypeID() == BATTLEGROUND_BE)
8145 bg->FillInitialWorldStates(data);
8146 else
8148 data << uint32(0x9f0) << uint32(0x0); // 7 gold
8149 data << uint32(0x9f1) << uint32(0x0); // 8 green
8150 data << uint32(0x9f3) << uint32(0x0); // 9 show
8152 break;
8153 case 3968: // Ruins of Lordaeron
8154 if (bg && bg->GetTypeID() == BATTLEGROUND_RL)
8155 bg->FillInitialWorldStates(data);
8156 else
8158 data << uint32(0xbb8) << uint32(0x0); // 7 gold
8159 data << uint32(0xbb9) << uint32(0x0); // 8 green
8160 data << uint32(0xbba) << uint32(0x0); // 9 show
8162 break;
8163 case 3703: // Shattrath City
8164 break;
8165 default:
8166 data << uint32(0x914) << uint32(0x0); // 7
8167 data << uint32(0x913) << uint32(0x0); // 8
8168 data << uint32(0x912) << uint32(0x0); // 9
8169 data << uint32(0x915) << uint32(0x0); // 10
8170 break;
8172 GetSession()->SendPacket(&data);
8175 uint32 Player::GetXPRestBonus(uint32 xp)
8177 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
8179 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
8180 rested_bonus = xp;
8182 SetRestBonus( GetRestBonus() - rested_bonus);
8184 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
8185 return rested_bonus;
8188 void Player::SetBindPoint(uint64 guid)
8190 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
8191 data << uint64(guid);
8192 GetSession()->SendPacket( &data );
8195 void Player::SendTalentWipeConfirm(uint64 guid)
8197 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
8198 data << uint64(guid);
8199 data << uint32(resetTalentsCost());
8200 GetSession()->SendPacket( &data );
8203 void Player::SendPetSkillWipeConfirm()
8205 Pet* pet = GetPet();
8206 if(!pet)
8207 return;
8208 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
8209 data << pet->GetGUID();
8210 data << uint32(pet->resetTalentsCost());
8211 GetSession()->SendPacket( &data );
8214 /*********************************************************/
8215 /*** STORAGE SYSTEM ***/
8216 /*********************************************************/
8218 void Player::SetVirtualItemSlot( uint8 i, Item* item)
8220 assert(i < 3);
8221 if(i < 2 && item)
8223 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
8224 return;
8225 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
8226 if(charges == 0)
8227 return;
8228 if(charges > 1)
8229 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
8230 else if(charges <= 1)
8232 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
8233 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
8238 void Player::SetSheath( SheathState sheathed )
8240 switch (sheathed)
8242 case SHEATH_STATE_UNARMED: // no prepared weapon
8243 SetVirtualItemSlot(0,NULL);
8244 SetVirtualItemSlot(1,NULL);
8245 SetVirtualItemSlot(2,NULL);
8246 break;
8247 case SHEATH_STATE_MELEE: // prepared melee weapon
8249 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true,true));
8250 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true,true));
8251 SetVirtualItemSlot(2,NULL);
8252 }; break;
8253 case SHEATH_STATE_RANGED: // prepared ranged weapon
8254 SetVirtualItemSlot(0,NULL);
8255 SetVirtualItemSlot(1,NULL);
8256 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true,true));
8257 break;
8258 default:
8259 SetVirtualItemSlot(0,NULL);
8260 SetVirtualItemSlot(1,NULL);
8261 SetVirtualItemSlot(2,NULL);
8262 break;
8264 Unit::SetSheath(sheathed); // this must visualize Sheath changing for other players...
8267 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
8269 uint8 pClass = getClass();
8271 uint8 slots[4];
8272 slots[0] = NULL_SLOT;
8273 slots[1] = NULL_SLOT;
8274 slots[2] = NULL_SLOT;
8275 slots[3] = NULL_SLOT;
8276 switch( proto->InventoryType )
8278 case INVTYPE_HEAD:
8279 slots[0] = EQUIPMENT_SLOT_HEAD;
8280 break;
8281 case INVTYPE_NECK:
8282 slots[0] = EQUIPMENT_SLOT_NECK;
8283 break;
8284 case INVTYPE_SHOULDERS:
8285 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
8286 break;
8287 case INVTYPE_BODY:
8288 slots[0] = EQUIPMENT_SLOT_BODY;
8289 break;
8290 case INVTYPE_CHEST:
8291 slots[0] = EQUIPMENT_SLOT_CHEST;
8292 break;
8293 case INVTYPE_ROBE:
8294 slots[0] = EQUIPMENT_SLOT_CHEST;
8295 break;
8296 case INVTYPE_WAIST:
8297 slots[0] = EQUIPMENT_SLOT_WAIST;
8298 break;
8299 case INVTYPE_LEGS:
8300 slots[0] = EQUIPMENT_SLOT_LEGS;
8301 break;
8302 case INVTYPE_FEET:
8303 slots[0] = EQUIPMENT_SLOT_FEET;
8304 break;
8305 case INVTYPE_WRISTS:
8306 slots[0] = EQUIPMENT_SLOT_WRISTS;
8307 break;
8308 case INVTYPE_HANDS:
8309 slots[0] = EQUIPMENT_SLOT_HANDS;
8310 break;
8311 case INVTYPE_FINGER:
8312 slots[0] = EQUIPMENT_SLOT_FINGER1;
8313 slots[1] = EQUIPMENT_SLOT_FINGER2;
8314 break;
8315 case INVTYPE_TRINKET:
8316 slots[0] = EQUIPMENT_SLOT_TRINKET1;
8317 slots[1] = EQUIPMENT_SLOT_TRINKET2;
8318 break;
8319 case INVTYPE_CLOAK:
8320 slots[0] = EQUIPMENT_SLOT_BACK;
8321 break;
8322 case INVTYPE_WEAPON:
8324 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8326 // suggest offhand slot only if know dual wielding
8327 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8328 if(CanDualWield())
8329 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8330 break;
8332 case INVTYPE_SHIELD:
8333 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8334 break;
8335 case INVTYPE_RANGED:
8336 slots[0] = EQUIPMENT_SLOT_RANGED;
8337 break;
8338 case INVTYPE_2HWEAPON:
8339 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8340 if (CanDualWield() && CanTitanGrip())
8341 slots[1] = EQUIPMENT_SLOT_OFFHAND;
8342 break;
8343 case INVTYPE_TABARD:
8344 slots[0] = EQUIPMENT_SLOT_TABARD;
8345 break;
8346 case INVTYPE_WEAPONMAINHAND:
8347 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8348 break;
8349 case INVTYPE_WEAPONOFFHAND:
8350 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8351 break;
8352 case INVTYPE_HOLDABLE:
8353 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8354 break;
8355 case INVTYPE_THROWN:
8356 slots[0] = EQUIPMENT_SLOT_RANGED;
8357 break;
8358 case INVTYPE_RANGEDRIGHT:
8359 slots[0] = EQUIPMENT_SLOT_RANGED;
8360 break;
8361 case INVTYPE_BAG:
8362 slots[0] = INVENTORY_SLOT_BAG_START + 0;
8363 slots[1] = INVENTORY_SLOT_BAG_START + 1;
8364 slots[2] = INVENTORY_SLOT_BAG_START + 2;
8365 slots[3] = INVENTORY_SLOT_BAG_START + 3;
8366 break;
8367 case INVTYPE_RELIC:
8369 switch(proto->SubClass)
8371 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8372 if (pClass == CLASS_PALADIN)
8373 slots[0] = EQUIPMENT_SLOT_RANGED;
8374 break;
8375 case ITEM_SUBCLASS_ARMOR_IDOL:
8376 if (pClass == CLASS_DRUID)
8377 slots[0] = EQUIPMENT_SLOT_RANGED;
8378 break;
8379 case ITEM_SUBCLASS_ARMOR_TOTEM:
8380 if (pClass == CLASS_SHAMAN)
8381 slots[0] = EQUIPMENT_SLOT_RANGED;
8382 break;
8383 case ITEM_SUBCLASS_ARMOR_MISC:
8384 if (pClass == CLASS_WARLOCK)
8385 slots[0] = EQUIPMENT_SLOT_RANGED;
8386 break;
8387 case ITEM_SUBCLASS_ARMOR_SIGIL:
8388 if (pClass == CLASS_DEATH_KNIGHT)
8389 slots[0] = EQUIPMENT_SLOT_RANGED;
8390 break;
8392 break;
8394 default :
8395 return NULL_SLOT;
8398 if( slot != NULL_SLOT )
8400 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8402 for (int i = 0; i < 4; ++i)
8404 if ( slots[i] == slot )
8405 return slot;
8409 else
8411 // search free slot at first
8412 for (int i = 0; i < 4; ++i)
8414 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8416 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8417 if(slots[i]!=EQUIPMENT_SLOT_OFFHAND || !IsTwoHandUsed())
8418 return slots[i];
8422 // if not found free and can swap return first appropriate from used
8423 for (int i = 0; i < 4; ++i)
8425 if ( slots[i] != NULL_SLOT && swap )
8426 return slots[i];
8430 // no free position
8431 return NULL_SLOT;
8434 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8436 Item *pItem;
8437 uint32 tempcount = 0;
8439 uint8 res = EQUIP_ERR_OK;
8441 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
8443 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8444 if( pItem && pItem->GetEntry() == item )
8446 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8447 if(ires==EQUIP_ERR_OK)
8449 tempcount += pItem->GetCount();
8450 if( tempcount >= count )
8451 return EQUIP_ERR_OK;
8453 else
8454 res = ires;
8457 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8459 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8460 if( pItem && pItem->GetEntry() == item )
8462 tempcount += pItem->GetCount();
8463 if( tempcount >= count )
8464 return EQUIP_ERR_OK;
8467 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8469 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8470 if( pItem && pItem->GetEntry() == item )
8472 tempcount += pItem->GetCount();
8473 if( tempcount >= count )
8474 return EQUIP_ERR_OK;
8477 Bag *pBag;
8478 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8480 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8481 if( pBag )
8483 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8485 pItem = GetItemByPos( i, j );
8486 if( pItem && pItem->GetEntry() == item )
8488 tempcount += pItem->GetCount();
8489 if( tempcount >= count )
8490 return EQUIP_ERR_OK;
8496 // not found req. item count and have unequippable items
8497 return res;
8500 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8502 uint32 count = 0;
8503 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8505 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8506 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8507 count += pItem->GetCount();
8509 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8511 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8512 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8513 count += pItem->GetCount();
8515 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8517 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8518 if( pBag )
8519 count += pBag->GetItemCount(item,skipItem);
8522 if(skipItem && skipItem->GetProto()->GemProperties)
8524 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8526 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8527 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8528 count += pItem->GetGemCountWithID(item);
8532 if(inBankAlso)
8534 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8536 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8537 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8538 count += pItem->GetCount();
8540 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8542 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8543 if( pBag )
8544 count += pBag->GetItemCount(item,skipItem);
8547 if(skipItem && skipItem->GetProto()->GemProperties)
8549 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8551 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8552 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8553 count += pItem->GetGemCountWithID(item);
8558 return count;
8561 Item* Player::GetItemByGuid( uint64 guid ) const
8563 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8565 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8566 if( pItem && pItem->GetGUID() == guid )
8567 return pItem;
8569 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8571 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8572 if( pItem && pItem->GetGUID() == guid )
8573 return pItem;
8576 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8578 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8579 if( pBag )
8581 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8583 Item* pItem = pBag->GetItemByPos( j );
8584 if( pItem && pItem->GetGUID() == guid )
8585 return pItem;
8589 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8591 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8592 if( pBag )
8594 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8596 Item* pItem = pBag->GetItemByPos( j );
8597 if( pItem && pItem->GetGUID() == guid )
8598 return pItem;
8603 return NULL;
8606 Item* Player::GetItemByPos( uint16 pos ) const
8608 uint8 bag = pos >> 8;
8609 uint8 slot = pos & 255;
8610 return GetItemByPos( bag, slot );
8613 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8615 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || (slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END )) )
8616 return m_items[slot];
8617 else if ((bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8618 || (bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END) )
8620 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8621 if ( pBag )
8622 return pBag->GetItemByPos(slot);
8624 return NULL;
8627 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool nonbroken, bool useable) const
8629 uint16 slot;
8630 switch (attackType)
8632 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8633 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8634 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8635 default: return NULL;
8638 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8639 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8640 return NULL;
8642 if (useable && !IsUseEquipedWeapon(attackType==BASE_ATTACK))
8643 return NULL;
8645 if (nonbroken && item->IsBroken())
8646 return NULL;
8648 return item;
8651 Item* Player::GetShield(bool useable) const
8653 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8654 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8655 return NULL;
8657 if(!useable)
8658 return item;
8660 if( item->IsBroken())
8661 return NULL;
8663 return item;
8666 uint32 Player::GetAttackBySlot( uint8 slot )
8668 switch(slot)
8670 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8671 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8672 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8673 default: return MAX_ATTACK;
8677 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8679 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8680 return true;
8681 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8682 return true;
8683 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8684 return true;
8685 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < CURRENCYTOKEN_SLOT_END ) )
8686 return true;
8687 return false;
8690 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8692 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8693 return true;
8694 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8695 return true;
8696 return false;
8699 bool Player::IsBankPos( uint8 bag, uint8 slot )
8701 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8702 return true;
8703 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8704 return true;
8705 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8706 return true;
8707 return false;
8710 bool Player::IsBagPos( uint16 pos )
8712 uint8 bag = pos >> 8;
8713 uint8 slot = pos & 255;
8714 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8715 return true;
8716 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8717 return true;
8718 return false;
8721 bool Player::IsValidPos( uint8 bag, uint8 slot, bool explicit_pos )
8723 // post selected
8724 if(bag == NULL_BAG && !explicit_pos)
8725 return true;
8727 if (bag == INVENTORY_SLOT_BAG_0)
8729 // any post selected
8730 if (slot == NULL_SLOT && !explicit_pos)
8731 return true;
8733 // equipment
8734 if (slot < EQUIPMENT_SLOT_END)
8735 return true;
8737 // bag equip slots
8738 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8739 return true;
8741 // backpack slots
8742 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8743 return true;
8745 // keyring slots
8746 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8747 return true;
8749 // bank main slots
8750 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8751 return true;
8753 // bank bag slots
8754 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8755 return true;
8757 return false;
8760 // bag content slots
8761 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8763 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8764 if(!pBag)
8765 return false;
8767 // any post selected
8768 if (slot == NULL_SLOT && !explicit_pos)
8769 return true;
8771 return slot < pBag->GetBagSize();
8774 // bank bag content slots
8775 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8777 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8778 if(!pBag)
8779 return false;
8781 // any post selected
8782 if (slot == NULL_SLOT && !explicit_pos)
8783 return true;
8785 return slot < pBag->GetBagSize();
8788 // where this?
8789 return false;
8793 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8795 uint32 tempcount = 0;
8796 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8798 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8799 if( pItem && pItem->GetEntry() == item )
8801 tempcount += pItem->GetCount();
8802 if( tempcount >= count )
8803 return true;
8806 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8808 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8809 if( pItem && pItem->GetEntry() == item )
8811 tempcount += pItem->GetCount();
8812 if( tempcount >= count )
8813 return true;
8816 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8818 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8820 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8822 Item* pItem = GetItemByPos( i, j );
8823 if( pItem && pItem->GetEntry() == item )
8825 tempcount += pItem->GetCount();
8826 if( tempcount >= count )
8827 return true;
8833 if(inBankAlso)
8835 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; ++i)
8837 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8838 if( pItem && pItem->GetEntry() == item )
8840 tempcount += pItem->GetCount();
8841 if( tempcount >= count )
8842 return true;
8845 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
8847 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8849 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8851 Item* pItem = GetItemByPos( i, j );
8852 if( pItem && pItem->GetEntry() == item )
8854 tempcount += pItem->GetCount();
8855 if( tempcount >= count )
8856 return true;
8863 return false;
8866 bool Player::HasItemOrGemWithIdEquipped( uint32 item, uint32 count, uint8 except_slot ) const
8868 uint32 tempcount = 0;
8869 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8871 if(i==int(except_slot))
8872 continue;
8874 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8875 if( pItem && pItem->GetEntry() == item)
8877 tempcount += pItem->GetCount();
8878 if( tempcount >= count )
8879 return true;
8883 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(item);
8884 if (pProto && pProto->GemProperties)
8886 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8888 if(i==int(except_slot))
8889 continue;
8891 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8892 if( pItem && pItem->GetProto()->Socket[0].Color)
8894 tempcount += pItem->GetGemCountWithID(item);
8895 if( tempcount >= count )
8896 return true;
8901 return false;
8904 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory, uint32 count, uint8 except_slot ) const
8906 uint32 tempcount = 0;
8907 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
8909 if(i==int(except_slot))
8910 continue;
8912 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8913 if (!pItem)
8914 continue;
8916 ItemPrototype const *pProto = pItem->GetProto();
8917 if (!pProto)
8918 continue;
8920 if (pProto->ItemLimitCategory == limitCategory)
8922 tempcount += pItem->GetCount();
8923 if( tempcount >= count )
8924 return true;
8927 if( pProto->Socket[0].Color)
8929 tempcount += pItem->GetGemCountWithLimitCategory(limitCategory);
8930 if( tempcount >= count )
8931 return true;
8935 return false;
8938 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8940 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry);
8941 if( !pProto )
8943 if(no_space_count)
8944 *no_space_count = count;
8945 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8948 // no maximum
8949 if(pProto->MaxCount <= 0)
8950 return EQUIP_ERR_OK;
8952 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8954 if (curcount + count > uint32(pProto->MaxCount))
8956 if(no_space_count)
8957 *no_space_count = count +curcount - pProto->MaxCount;
8958 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8961 return EQUIP_ERR_OK;
8964 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8966 Item *pItem;
8967 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8969 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8970 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8971 return true;
8973 for(uint8 i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
8975 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8976 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8977 return true;
8979 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8981 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8983 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8985 pItem = GetItemByPos( i, j );
8986 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8987 return true;
8991 return false;
8994 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8996 Item* pItem2 = GetItemByPos( bag, slot );
8998 // ignore move item (this slot will be empty at move)
8999 if (pItem2==pSrcItem)
9000 pItem2 = NULL;
9002 uint32 need_space;
9004 // empty specific slot - check item fit to slot
9005 if (!pItem2 || swap)
9007 if (bag == INVENTORY_SLOT_BAG_0)
9009 // keyring case
9010 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
9011 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9013 // currencytoken case
9014 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
9015 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9017 // prevent cheating
9018 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
9019 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9021 else
9023 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
9024 if (!pBag)
9025 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9027 ItemPrototype const* pBagProto = pBag->GetProto();
9028 if (!pBagProto)
9029 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9031 if (slot >= pBagProto->ContainerSlots)
9032 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9034 if (!ItemCanGoIntoBag(pProto,pBagProto))
9035 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9038 // non empty stack with space
9039 need_space = pProto->GetMaxStackSize();
9041 // non empty slot, check item type
9042 else
9044 // can be merged at least partly
9045 uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
9046 if (res != EQUIP_ERR_OK)
9047 return res;
9049 // free stack space or infinity
9050 need_space = pProto->GetMaxStackSize() - pItem2->GetCount();
9053 if (need_space > count)
9054 need_space = count;
9056 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
9057 if (!newPosition.isContainedIn(dest))
9059 dest.push_back(newPosition);
9060 count -= need_space;
9062 return EQUIP_ERR_OK;
9065 uint8 Player::_CanStoreItem_InBag( uint8 bag, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool merge, bool non_specialized, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot ) const
9067 // skip specific bag already processed in first called _CanStoreItem_InBag
9068 if (bag==skip_bag)
9069 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9071 // skip not existed bag or self targeted bag
9072 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
9073 if (!pBag || pBag==pSrcItem)
9074 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9076 ItemPrototype const* pBagProto = pBag->GetProto();
9077 if (!pBagProto)
9078 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9080 // specialized bag mode or non-specilized
9081 if (non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER))
9082 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9084 if (!ItemCanGoIntoBag(pProto,pBagProto))
9085 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
9087 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9089 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9090 if (j==skip_slot)
9091 continue;
9093 Item* pItem2 = GetItemByPos( bag, j );
9095 // ignore move item (this slot will be empty at move)
9096 if (pItem2 == pSrcItem)
9097 pItem2 = NULL;
9099 // if merge skip empty, if !merge skip non-empty
9100 if ((pItem2 != NULL) != merge)
9101 continue;
9103 uint32 need_space = pProto->GetMaxStackSize();
9105 if (pItem2)
9107 // can be merged at least partly
9108 uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
9109 if (res != EQUIP_ERR_OK)
9110 continue;
9112 // descrease at current stacksize
9113 need_space -= pItem2->GetCount();
9116 if (need_space > count)
9117 need_space = count;
9119 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
9120 if (!newPosition.isContainedIn(dest))
9122 dest.push_back(newPosition);
9123 count -= need_space;
9125 if (count==0)
9126 return EQUIP_ERR_OK;
9129 return EQUIP_ERR_OK;
9132 uint8 Player::_CanStoreItem_InInventorySlots( uint8 slot_begin, uint8 slot_end, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool merge, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot ) const
9134 for(uint32 j = slot_begin; j < slot_end; ++j)
9136 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9137 if (INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
9138 continue;
9140 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
9142 // ignore move item (this slot will be empty at move)
9143 if (pItem2==pSrcItem)
9144 pItem2 = NULL;
9146 // if merge skip empty, if !merge skip non-empty
9147 if ((pItem2 != NULL) != merge)
9148 continue;
9150 uint32 need_space = pProto->GetMaxStackSize();
9152 if (pItem2)
9154 // can be merged at least partly
9155 uint8 res = pItem2->CanBeMergedPartlyWith(pProto);
9156 if (res != EQUIP_ERR_OK)
9157 continue;
9159 // descrease at current stacksize
9160 need_space -= pItem2->GetCount();
9163 if (need_space > count)
9164 need_space = count;
9166 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
9167 if (!newPosition.isContainedIn(dest))
9169 dest.push_back(newPosition);
9170 count -= need_space;
9172 if (count==0)
9173 return EQUIP_ERR_OK;
9176 return EQUIP_ERR_OK;
9179 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
9181 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
9183 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(entry);
9184 if (!pProto)
9186 if (no_space_count)
9187 *no_space_count = count;
9188 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
9191 if (pItem)
9193 // item used
9194 if(pItem->m_lootGenerated)
9196 if (no_space_count)
9197 *no_space_count = count;
9198 return EQUIP_ERR_ALREADY_LOOTED;
9201 if (pItem->IsBindedNotWith(this))
9203 if (no_space_count)
9204 *no_space_count = count;
9205 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9209 // check count of items (skip for auto move for same player from bank)
9210 uint32 no_similar_count = 0; // can't store this amount similar items
9211 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
9212 if (res!=EQUIP_ERR_OK)
9214 if (count==no_similar_count)
9216 if (no_space_count)
9217 *no_space_count = no_similar_count;
9218 return res;
9220 count -= no_similar_count;
9223 // in specific slot
9224 if (bag != NULL_BAG && slot != NULL_SLOT)
9226 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9227 if (res!=EQUIP_ERR_OK)
9229 if (no_space_count)
9230 *no_space_count = count + no_similar_count;
9231 return res;
9234 if (count==0)
9236 if (no_similar_count==0)
9237 return EQUIP_ERR_OK;
9239 if (no_space_count)
9240 *no_space_count = count + no_similar_count;
9241 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9245 // not specific slot or have space for partly store only in specific slot
9247 // in specific bag
9248 if (bag != NULL_BAG)
9250 // search stack in bag for merge to
9251 if (pProto->Stackable != 1)
9253 if (bag == INVENTORY_SLOT_BAG_0) // inventory
9255 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9256 if (res!=EQUIP_ERR_OK)
9258 if (no_space_count)
9259 *no_space_count = count + no_similar_count;
9260 return res;
9263 if (count==0)
9265 if (no_similar_count==0)
9266 return EQUIP_ERR_OK;
9268 if (no_space_count)
9269 *no_space_count = count + no_similar_count;
9270 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9273 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9274 if (res!=EQUIP_ERR_OK)
9276 if (no_space_count)
9277 *no_space_count = count + no_similar_count;
9278 return res;
9281 if (count==0)
9283 if (no_similar_count==0)
9284 return EQUIP_ERR_OK;
9286 if (no_space_count)
9287 *no_space_count = count + no_similar_count;
9288 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9291 else // equipped bag
9293 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9294 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9295 if (res!=EQUIP_ERR_OK)
9296 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9298 if (res!=EQUIP_ERR_OK)
9300 if (no_space_count)
9301 *no_space_count = count + no_similar_count;
9302 return res;
9305 if (count==0)
9307 if (no_similar_count==0)
9308 return EQUIP_ERR_OK;
9310 if (no_space_count)
9311 *no_space_count = count + no_similar_count;
9312 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9317 // search free slot in bag for place to
9318 if(bag == INVENTORY_SLOT_BAG_0) // inventory
9320 // search free slot - keyring case
9321 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9323 uint32 keyringSize = GetMaxKeyringSize();
9324 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9325 if (res!=EQUIP_ERR_OK)
9327 if (no_space_count)
9328 *no_space_count = count + no_similar_count;
9329 return res;
9332 if (count==0)
9334 if (no_similar_count==0)
9335 return EQUIP_ERR_OK;
9337 if (no_space_count)
9338 *no_space_count = count + no_similar_count;
9339 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9342 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9343 if (res!=EQUIP_ERR_OK)
9345 if (no_space_count)
9346 *no_space_count = count + no_similar_count;
9347 return res;
9350 if (count==0)
9352 if (no_similar_count==0)
9353 return EQUIP_ERR_OK;
9355 if (no_space_count)
9356 *no_space_count = count + no_similar_count;
9357 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9360 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9362 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9363 if (res!=EQUIP_ERR_OK)
9365 if (no_space_count)
9366 *no_space_count = count + no_similar_count;
9367 return res;
9370 if (count==0)
9372 if (no_similar_count==0)
9373 return EQUIP_ERR_OK;
9375 if (no_space_count)
9376 *no_space_count = count + no_similar_count;
9377 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9381 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9382 if (res!=EQUIP_ERR_OK)
9384 if (no_space_count)
9385 *no_space_count = count + no_similar_count;
9386 return res;
9389 if (count==0)
9391 if (no_similar_count==0)
9392 return EQUIP_ERR_OK;
9394 if (no_space_count)
9395 *no_space_count = count + no_similar_count;
9396 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9399 else // equipped bag
9401 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9402 if (res!=EQUIP_ERR_OK)
9403 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9405 if (res!=EQUIP_ERR_OK)
9407 if (no_space_count)
9408 *no_space_count = count + no_similar_count;
9409 return res;
9412 if (count==0)
9414 if (no_similar_count==0)
9415 return EQUIP_ERR_OK;
9417 if (no_space_count)
9418 *no_space_count = count + no_similar_count;
9419 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9424 // not specific bag or have space for partly store only in specific bag
9426 // search stack for merge to
9427 if (pProto->Stackable != 1)
9429 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9430 if (res!=EQUIP_ERR_OK)
9432 if (no_space_count)
9433 *no_space_count = count + no_similar_count;
9434 return res;
9437 if (count==0)
9439 if (no_similar_count==0)
9440 return EQUIP_ERR_OK;
9442 if (no_space_count)
9443 *no_space_count = count + no_similar_count;
9444 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9447 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9448 if (res!=EQUIP_ERR_OK)
9450 if (no_space_count)
9451 *no_space_count = count + no_similar_count;
9452 return res;
9455 if (count==0)
9457 if (no_similar_count==0)
9458 return EQUIP_ERR_OK;
9460 if (no_space_count)
9461 *no_space_count = count + no_similar_count;
9462 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9465 if (pProto->BagFamily)
9467 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9469 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9470 if (res!=EQUIP_ERR_OK)
9471 continue;
9473 if (count==0)
9475 if (no_similar_count==0)
9476 return EQUIP_ERR_OK;
9478 if (no_space_count)
9479 *no_space_count = count + no_similar_count;
9480 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9485 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9487 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9488 if (res!=EQUIP_ERR_OK)
9489 continue;
9491 if (count==0)
9493 if (no_similar_count==0)
9494 return EQUIP_ERR_OK;
9496 if (no_space_count)
9497 *no_space_count = count + no_similar_count;
9498 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9503 // search free slot - special bag case
9504 if (pProto->BagFamily)
9506 if (pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9508 uint32 keyringSize = GetMaxKeyringSize();
9509 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9510 if (res!=EQUIP_ERR_OK)
9512 if (no_space_count)
9513 *no_space_count = count + no_similar_count;
9514 return res;
9517 if (count==0)
9519 if (no_similar_count==0)
9520 return EQUIP_ERR_OK;
9522 if (no_space_count)
9523 *no_space_count = count + no_similar_count;
9524 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9527 else if (pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9529 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9530 if (res!=EQUIP_ERR_OK)
9532 if (no_space_count)
9533 *no_space_count = count + no_similar_count;
9534 return res;
9537 if (count==0)
9539 if (no_similar_count==0)
9540 return EQUIP_ERR_OK;
9542 if (no_space_count)
9543 *no_space_count = count + no_similar_count;
9544 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9548 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9550 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9551 if (res!=EQUIP_ERR_OK)
9552 continue;
9554 if (count==0)
9556 if (no_similar_count==0)
9557 return EQUIP_ERR_OK;
9559 if (no_space_count)
9560 *no_space_count = count + no_similar_count;
9561 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9566 // search free slot
9567 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9568 if (res!=EQUIP_ERR_OK)
9570 if (no_space_count)
9571 *no_space_count = count + no_similar_count;
9572 return res;
9575 if (count==0)
9577 if (no_similar_count==0)
9578 return EQUIP_ERR_OK;
9580 if (no_space_count)
9581 *no_space_count = count + no_similar_count;
9582 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9585 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9587 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9588 if (res!=EQUIP_ERR_OK)
9589 continue;
9591 if (count==0)
9593 if (no_similar_count==0)
9594 return EQUIP_ERR_OK;
9596 if (no_space_count)
9597 *no_space_count = count + no_similar_count;
9598 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9602 if (no_space_count)
9603 *no_space_count = count + no_similar_count;
9605 return EQUIP_ERR_INVENTORY_FULL;
9608 //////////////////////////////////////////////////////////////////////////
9609 uint8 Player::CanStoreItems( Item **pItems,int count) const
9611 Item *pItem2;
9613 // fill space table
9614 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9615 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9616 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9617 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9619 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9620 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9621 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9622 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9624 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
9626 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9628 if (pItem2 && !pItem2->IsInTrade())
9630 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9634 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
9636 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9638 if (pItem2 && !pItem2->IsInTrade())
9640 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9644 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
9646 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9648 if (pItem2 && !pItem2->IsInTrade())
9650 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9654 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9656 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9658 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9660 pItem2 = GetItemByPos( i, j );
9661 if (pItem2 && !pItem2->IsInTrade())
9663 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9669 // check free space for all items
9670 for (int k = 0; k < count; ++k)
9672 Item *pItem = pItems[k];
9674 // no item
9675 if (!pItem) continue;
9677 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9678 ItemPrototype const *pProto = pItem->GetProto();
9680 // strange item
9681 if( !pProto )
9682 return EQUIP_ERR_ITEM_NOT_FOUND;
9684 // item used
9685 if(pItem->m_lootGenerated)
9686 return EQUIP_ERR_ALREADY_LOOTED;
9688 // item it 'bind'
9689 if(pItem->IsBindedNotWith(this))
9690 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9692 Bag *pBag;
9693 ItemPrototype const *pBagProto;
9695 // item is 'one item only'
9696 uint8 res = CanTakeMoreSimilarItems(pItem);
9697 if(res != EQUIP_ERR_OK)
9698 return res;
9700 // search stack for merge to
9701 if( pProto->Stackable != 1 )
9703 bool b_found = false;
9705 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; ++t)
9707 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9708 if( pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9710 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9711 b_found = true;
9712 break;
9715 if (b_found) continue;
9717 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9719 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9720 if( pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9722 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9723 b_found = true;
9724 break;
9727 if (b_found) continue;
9729 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9731 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9732 if( pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->GetMaxStackSize())
9734 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9735 b_found = true;
9736 break;
9739 if (b_found) continue;
9741 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9743 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9744 if( pBag )
9746 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9748 pItem2 = GetItemByPos( t, j );
9749 if( pItem2 && pItem2->CanBeMergedPartlyWith(pProto) == EQUIP_ERR_OK && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->GetMaxStackSize())
9751 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9752 b_found = true;
9753 break;
9758 if (b_found) continue;
9761 // special bag case
9762 if( pProto->BagFamily )
9764 bool b_found = false;
9765 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9767 uint32 keyringSize = GetMaxKeyringSize();
9768 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9770 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9772 inv_keys[t-KEYRING_SLOT_START] = 1;
9773 b_found = true;
9774 break;
9779 if (b_found) continue;
9781 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9783 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9785 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9787 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9788 b_found = true;
9789 break;
9794 if (b_found) continue;
9796 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9798 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9799 if( pBag )
9801 pBagProto = pBag->GetProto();
9803 // not plain container check
9804 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9805 ItemCanGoIntoBag(pProto,pBagProto) )
9807 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9809 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9811 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9812 b_found = true;
9813 break;
9819 if (b_found) continue;
9822 // search free slot
9823 bool b_found = false;
9824 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; ++t)
9826 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9828 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9829 b_found = true;
9830 break;
9833 if (b_found) continue;
9835 // search free slot in bags
9836 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; ++t)
9838 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9839 if( pBag )
9841 pBagProto = pBag->GetProto();
9843 // special bag already checked
9844 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER))
9845 continue;
9847 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
9849 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9851 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9852 b_found = true;
9853 break;
9859 // no free slot found?
9860 if (!b_found)
9861 return EQUIP_ERR_INVENTORY_FULL;
9864 return EQUIP_ERR_OK;
9867 //////////////////////////////////////////////////////////////////////////
9868 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, bool swap ) const
9870 dest = 0;
9871 Item *pItem = Item::CreateItem( item, 1, this );
9872 if( pItem )
9874 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9875 delete pItem;
9876 return result;
9879 return EQUIP_ERR_ITEM_NOT_FOUND;
9882 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9884 dest = 0;
9885 if( pItem )
9887 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9888 ItemPrototype const *pProto = pItem->GetProto();
9889 if( pProto )
9891 // item used
9892 if(pItem->m_lootGenerated)
9893 return EQUIP_ERR_ALREADY_LOOTED;
9895 if(pItem->IsBindedNotWith(this))
9896 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9898 // check count of items (skip for auto move for same player from bank)
9899 uint8 res = CanTakeMoreSimilarItems(pItem);
9900 if(res != EQUIP_ERR_OK)
9901 return res;
9903 // check this only in game
9904 if(not_loading)
9906 // May be here should be more stronger checks; STUNNED checked
9907 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9908 if (hasUnitState(UNIT_STAT_STUNNED))
9909 return EQUIP_ERR_YOU_ARE_STUNNED;
9911 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9912 // - combat
9913 // - in-progress arenas
9914 if( !pProto->CanChangeEquipStateInCombat() )
9916 if( isInCombat() )
9917 return EQUIP_ERR_NOT_IN_COMBAT;
9919 if(BattleGround* bg = GetBattleGround())
9920 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9921 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9924 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9925 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9927 if(IsNonMeleeSpellCasted(false))
9928 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9931 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : 0;
9932 // check allowed level (extend range to upper values if MaxLevel more or equal max player level, this let GM set high level with 1...max range items)
9933 if (ssd && ssd->MaxLevel < DEFAULT_MAX_LEVEL && ssd->MaxLevel < getLevel())
9934 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9936 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9937 if (eslot == NULL_SLOT)
9938 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9940 uint8 msg = CanUseItem(pItem , not_loading);
9941 if (msg != EQUIP_ERR_OK)
9942 return msg;
9943 if (!swap && GetItemByPos(INVENTORY_SLOT_BAG_0, eslot))
9944 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9946 // if swap ignore item (equipped also)
9947 if (uint8 res2 = CanEquipUniqueItem(pItem, swap ? eslot : NULL_SLOT))
9948 return res2;
9950 // check unique-equipped special item classes
9951 if (pProto->Class == ITEM_CLASS_QUIVER)
9953 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9955 if (Item* pBag = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
9957 if (pBag != pItem)
9959 if (ItemPrototype const* pBagProto = pBag->GetProto())
9961 if (pBagProto->Class==pProto->Class && (!swap || pBag->GetSlot() != eslot))
9962 return (pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9963 ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
9964 : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9971 uint32 type = pProto->InventoryType;
9973 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9975 if (type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
9977 if (!CanDualWield())
9978 return EQUIP_ERR_CANT_DUAL_WIELD;
9980 else if (type == INVTYPE_2HWEAPON)
9982 if (!CanDualWield() || !CanTitanGrip())
9983 return EQUIP_ERR_CANT_DUAL_WIELD;
9986 if (IsTwoHandUsed())
9987 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9990 // equip two-hand weapon case (with possible unequip 2 items)
9991 if (type == INVTYPE_2HWEAPON)
9993 if (eslot == EQUIPMENT_SLOT_OFFHAND)
9995 if (!CanTitanGrip())
9996 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9998 else if (eslot != EQUIPMENT_SLOT_MAINHAND)
9999 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
10001 if (!CanTitanGrip())
10003 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
10004 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
10005 ItemPosCountVec off_dest;
10006 if (offItem && (!not_loading ||
10007 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
10008 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ))
10009 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
10012 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
10013 return EQUIP_ERR_OK;
10017 return !swap ? EQUIP_ERR_ITEM_NOT_FOUND : EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
10020 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
10022 // Applied only to equipped items and bank bags
10023 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
10024 return EQUIP_ERR_OK;
10026 Item* pItem = GetItemByPos(pos);
10028 // Applied only to existed equipped item
10029 if( !pItem )
10030 return EQUIP_ERR_OK;
10032 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
10034 ItemPrototype const *pProto = pItem->GetProto();
10035 if( !pProto )
10036 return EQUIP_ERR_ITEM_NOT_FOUND;
10038 // item used
10039 if(pItem->m_lootGenerated)
10040 return EQUIP_ERR_ALREADY_LOOTED;
10042 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
10043 // - combat
10044 // - in-progress arenas
10045 if( !pProto->CanChangeEquipStateInCombat() )
10047 if( isInCombat() )
10048 return EQUIP_ERR_NOT_IN_COMBAT;
10050 if(BattleGround* bg = GetBattleGround())
10051 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
10052 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
10055 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
10056 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
10058 return EQUIP_ERR_OK;
10061 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
10063 if (!pItem)
10064 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10066 uint32 count = pItem->GetCount();
10068 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
10069 ItemPrototype const *pProto = pItem->GetProto();
10070 if (!pProto)
10071 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
10073 // item used
10074 if(pItem->m_lootGenerated)
10075 return EQUIP_ERR_ALREADY_LOOTED;
10077 if (pItem->IsBindedNotWith(this))
10078 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10080 // check count of items (skip for auto move for same player from bank)
10081 uint8 res = CanTakeMoreSimilarItems(pItem);
10082 if (res != EQUIP_ERR_OK)
10083 return res;
10085 // in specific slot
10086 if (bag != NULL_BAG && slot != NULL_SLOT)
10088 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
10090 if (!pItem->IsBag())
10091 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
10093 if (slot - BANK_SLOT_BAG_START >= GetBankBagSlotCount())
10094 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
10096 if (uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK)
10097 return cantuse;
10100 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
10101 if (res!=EQUIP_ERR_OK)
10102 return res;
10104 if (count==0)
10105 return EQUIP_ERR_OK;
10108 // not specific slot or have space for partly store only in specific slot
10110 // in specific bag
10111 if( bag != NULL_BAG )
10113 if( pProto->InventoryType == INVTYPE_BAG )
10115 Bag *pBag = (Bag*)pItem;
10116 if( pBag && !pBag->IsEmpty() )
10117 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
10120 // search stack in bag for merge to
10121 if( pProto->Stackable != 1 )
10123 if( bag == INVENTORY_SLOT_BAG_0 )
10125 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10126 if(res!=EQUIP_ERR_OK)
10127 return res;
10129 if(count==0)
10130 return EQUIP_ERR_OK;
10132 else
10134 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
10135 if(res!=EQUIP_ERR_OK)
10136 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
10138 if(res!=EQUIP_ERR_OK)
10139 return res;
10141 if(count==0)
10142 return EQUIP_ERR_OK;
10146 // search free slot in bag
10147 if( bag == INVENTORY_SLOT_BAG_0 )
10149 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10150 if(res!=EQUIP_ERR_OK)
10151 return res;
10153 if(count==0)
10154 return EQUIP_ERR_OK;
10156 else
10158 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, false, pItem, NULL_BAG, slot);
10159 if(res != EQUIP_ERR_OK)
10160 res = _CanStoreItem_InBag(bag, dest, pProto, count, false, true, pItem, NULL_BAG, slot);
10162 if(res != EQUIP_ERR_OK)
10163 return res;
10165 if(count == 0)
10166 return EQUIP_ERR_OK;
10170 // not specific bag or have space for partly store only in specific bag
10172 // search stack for merge to
10173 if( pProto->Stackable != 1 )
10175 // in slots
10176 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
10177 if(res != EQUIP_ERR_OK)
10178 return res;
10180 if(count == 0)
10181 return EQUIP_ERR_OK;
10183 // in special bags
10184 if( pProto->BagFamily )
10186 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10188 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
10189 if(res!=EQUIP_ERR_OK)
10190 continue;
10192 if(count==0)
10193 return EQUIP_ERR_OK;
10197 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10199 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
10200 if(res!=EQUIP_ERR_OK)
10201 continue;
10203 if(count==0)
10204 return EQUIP_ERR_OK;
10208 // search free place in special bag
10209 if( pProto->BagFamily )
10211 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10213 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
10214 if(res!=EQUIP_ERR_OK)
10215 continue;
10217 if(count==0)
10218 return EQUIP_ERR_OK;
10222 // search free space
10223 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10224 if(res!=EQUIP_ERR_OK)
10225 return res;
10227 if(count==0)
10228 return EQUIP_ERR_OK;
10230 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; ++i)
10232 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
10233 if(res!=EQUIP_ERR_OK)
10234 continue;
10236 if(count==0)
10237 return EQUIP_ERR_OK;
10239 return EQUIP_ERR_BANK_FULL;
10242 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
10244 if (pItem)
10246 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
10248 if (!isAlive() && not_loading)
10249 return EQUIP_ERR_YOU_ARE_DEAD;
10251 //if (isStunned())
10252 // return EQUIP_ERR_YOU_ARE_STUNNED;
10254 ItemPrototype const *pProto = pItem->GetProto();
10255 if (pProto)
10257 if (pItem->IsBindedNotWith(this))
10258 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10260 if ((pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0)
10261 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10263 if (uint32 item_use_skill = pItem->GetSkill())
10265 if (GetSkillValue(item_use_skill) == 0)
10267 // armor items with scaling stats can downgrade armor skill reqs if related class can learn armor use at some level
10268 if (pProto->Class != ITEM_CLASS_ARMOR)
10269 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10271 ScalingStatDistributionEntry const *ssd = pProto->ScalingStatDistribution ? sScalingStatDistributionStore.LookupEntry(pProto->ScalingStatDistribution) : NULL;
10272 if (!ssd)
10273 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10275 bool allowScaleSkill = false;
10276 for (uint32 i = 0; i < sSkillLineAbilityStore.GetNumRows(); ++i)
10278 SkillLineAbilityEntry const *skillInfo = sSkillLineAbilityStore.LookupEntry(i);
10279 if (!skillInfo)
10280 continue;
10282 if (skillInfo->skillId != item_use_skill)
10283 continue;
10285 // can't learn
10286 if (skillInfo->classmask && (skillInfo->classmask & getClassMask()) == 0)
10287 continue;
10289 if (skillInfo->racemask && (skillInfo->racemask & getRaceMask()) == 0)
10290 continue;
10292 allowScaleSkill = true;
10293 break;
10296 if (!allowScaleSkill)
10297 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10301 if (pProto->RequiredSkill != 0)
10303 if (GetSkillValue( pProto->RequiredSkill ) == 0)
10304 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10306 if (GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank)
10307 return EQUIP_ERR_CANT_EQUIP_SKILL;
10310 if (pProto->RequiredSpell != 0 && !HasSpell(pProto->RequiredSpell))
10311 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10313 if (pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
10314 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10316 if (getLevel() < pProto->RequiredLevel)
10317 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10319 return EQUIP_ERR_OK;
10322 return EQUIP_ERR_ITEM_NOT_FOUND;
10325 bool Player::CanUseItem( ItemPrototype const *pProto )
10327 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10329 if( pProto )
10331 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10332 return false;
10333 if( pProto->RequiredSkill != 0 )
10335 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10336 return false;
10337 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10338 return false;
10340 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10341 return false;
10342 if( getLevel() < pProto->RequiredLevel )
10343 return false;
10344 return true;
10346 return false;
10349 uint8 Player::CanUseAmmo( uint32 item ) const
10351 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10352 if( !isAlive() )
10353 return EQUIP_ERR_YOU_ARE_DEAD;
10354 //if( isStunned() )
10355 // return EQUIP_ERR_YOU_ARE_STUNNED;
10356 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype( item );
10357 if( pProto )
10359 if( pProto->InventoryType!= INVTYPE_AMMO )
10360 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10361 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10362 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10363 if( pProto->RequiredSkill != 0 )
10365 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10366 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10367 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10368 return EQUIP_ERR_CANT_EQUIP_SKILL;
10370 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10371 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10372 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
10373 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10375 if( getLevel() < pProto->RequiredLevel )
10376 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10378 // Requires No Ammo
10379 if(GetDummyAura(46699))
10380 return EQUIP_ERR_BAG_FULL6;
10382 return EQUIP_ERR_OK;
10384 return EQUIP_ERR_ITEM_NOT_FOUND;
10387 void Player::SetAmmo( uint32 item )
10389 if(!item)
10390 return;
10392 // already set
10393 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10394 return;
10396 // check ammo
10397 if(item)
10399 uint8 msg = CanUseAmmo( item );
10400 if( msg != EQUIP_ERR_OK )
10402 SendEquipError( msg, NULL, NULL );
10403 return;
10407 SetUInt32Value(PLAYER_AMMO_ID, item);
10409 _ApplyAmmoBonuses();
10412 void Player::RemoveAmmo()
10414 SetUInt32Value(PLAYER_AMMO_ID, 0);
10416 m_ammoDPS = 0.0f;
10418 if(CanModifyStats())
10419 UpdateDamagePhysical(RANGED_ATTACK);
10422 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10423 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10425 uint32 count = 0;
10426 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10427 count += itr->count;
10429 Item *pItem = Item::CreateItem( item, count, this );
10430 if( pItem )
10432 ItemAddedQuestCheck( item, count );
10433 if(randomPropertyId)
10434 pItem->SetItemRandomProperties(randomPropertyId);
10435 pItem = StoreItem( dest, pItem, update );
10437 return pItem;
10440 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10442 if( !pItem )
10443 return NULL;
10445 Item* lastItem = pItem;
10446 uint32 entry = pItem->GetEntry();
10447 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10449 uint16 pos = itr->pos;
10450 uint32 count = itr->count;
10452 ++itr;
10454 if(itr == dest.end())
10456 lastItem = _StoreItem(pos,pItem,count,false,update);
10457 break;
10460 lastItem = _StoreItem(pos,pItem,count,true,update);
10462 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
10463 return lastItem;
10466 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10467 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10469 if( !pItem )
10470 return NULL;
10472 uint8 bag = pos >> 8;
10473 uint8 slot = pos & 255;
10475 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10477 Item *pItem2 = GetItemByPos( bag, slot );
10479 if (!pItem2)
10481 if (clone)
10482 pItem = pItem->CloneItem(count, this);
10483 else
10484 pItem->SetCount(count);
10486 if (!pItem)
10487 return NULL;
10489 if (pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10490 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10491 (pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10492 pItem->SetBinding( true );
10494 if (bag == INVENTORY_SLOT_BAG_0)
10496 m_items[slot] = pItem;
10497 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10498 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10499 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10501 pItem->SetSlot( slot );
10502 pItem->SetContainer( NULL );
10504 // need update known currency
10505 if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10506 UpdateKnownCurrencies(pItem->GetEntry(), true);
10508 if (IsInWorld() && update)
10510 pItem->AddToWorld();
10511 pItem->SendCreateUpdateToPlayer( this );
10514 pItem->SetState(ITEM_CHANGED, this);
10516 else if (Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10518 pBag->StoreItem( slot, pItem, update );
10519 if( IsInWorld() && update )
10521 pItem->AddToWorld();
10522 pItem->SendCreateUpdateToPlayer( this );
10524 pItem->SetState(ITEM_CHANGED, this);
10525 pBag->SetState(ITEM_CHANGED, this);
10528 AddEnchantmentDurations(pItem);
10529 AddItemDurations(pItem);
10531 return pItem;
10533 else
10535 if (pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10536 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10537 (pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos)))
10538 pItem2->SetBinding( true );
10540 pItem2->SetCount( pItem2->GetCount() + count );
10541 if (IsInWorld() && update)
10542 pItem2->SendCreateUpdateToPlayer( this );
10544 if (!clone)
10546 // delete item (it not in any slot currently)
10547 if (IsInWorld() && update)
10549 pItem->RemoveFromWorld();
10550 pItem->DestroyForPlayer( this );
10553 RemoveEnchantmentDurations(pItem);
10554 RemoveItemDurations(pItem);
10556 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10557 pItem->SetState(ITEM_REMOVED, this);
10560 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10561 AddEnchantmentDurations(pItem2);
10563 pItem2->SetState(ITEM_CHANGED, this);
10565 return pItem2;
10569 Item* Player::EquipNewItem( uint16 pos, uint32 item, bool update )
10571 if (Item *pItem = Item::CreateItem( item, 1, this ))
10573 ItemAddedQuestCheck( item, 1 );
10574 return EquipItem( pos, pItem, update );
10577 return NULL;
10580 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10582 AddEnchantmentDurations(pItem);
10583 AddItemDurations(pItem);
10585 uint8 bag = pos >> 8;
10586 uint8 slot = pos & 255;
10588 Item *pItem2 = GetItemByPos( bag, slot );
10590 if( !pItem2 )
10592 VisualizeItem( slot, pItem);
10594 if(isAlive())
10596 ItemPrototype const *pProto = pItem->GetProto();
10598 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10599 if(pProto && pProto->ItemSet)
10600 AddItemsSetItem(this, pItem);
10602 _ApplyItemMods(pItem, slot, true);
10604 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10606 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10608 if (getClass() == CLASS_ROGUE)
10609 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10611 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10613 if (!spellProto)
10614 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10615 else
10617 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10619 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10620 data << uint64(GetGUID());
10621 data << uint8(1);
10622 data << uint32(cooldownSpell);
10623 data << uint32(0);
10624 GetSession()->SendPacket(&data);
10629 if( IsInWorld() && update )
10631 pItem->AddToWorld();
10632 pItem->SendCreateUpdateToPlayer( this );
10635 ApplyEquipCooldown(pItem);
10637 if( slot == EQUIPMENT_SLOT_MAINHAND )
10639 UpdateExpertise(BASE_ATTACK);
10640 UpdateArmorPenetration();
10642 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10644 UpdateExpertise(OFF_ATTACK);
10645 UpdateArmorPenetration();
10648 else
10650 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10651 if( IsInWorld() && update )
10652 pItem2->SendCreateUpdateToPlayer( this );
10654 // delete item (it not in any slot currently)
10655 //pItem->DeleteFromDB();
10656 if( IsInWorld() && update )
10658 pItem->RemoveFromWorld();
10659 pItem->DestroyForPlayer( this );
10662 RemoveEnchantmentDurations(pItem);
10663 RemoveItemDurations(pItem);
10665 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10666 pItem->SetState(ITEM_REMOVED, this);
10667 pItem2->SetState(ITEM_CHANGED, this);
10669 ApplyEquipCooldown(pItem2);
10671 return pItem2;
10674 // only for full equip instead adding to stack
10675 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10677 return pItem;
10680 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10682 if( pItem )
10684 AddEnchantmentDurations(pItem);
10685 AddItemDurations(pItem);
10687 uint8 slot = pos & 255;
10688 VisualizeItem( slot, pItem);
10690 if( IsInWorld() )
10692 pItem->AddToWorld();
10693 pItem->SendCreateUpdateToPlayer( this );
10696 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM, pItem->GetEntry());
10700 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10702 if(pItem)
10704 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), pItem->GetEntry());
10705 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0, pItem->GetEnchantmentId(PERM_ENCHANTMENT_SLOT));
10706 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 1, pItem->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT));
10708 else
10710 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID + (slot * 2), 0);
10711 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (slot * 2), 0);
10715 void Player::VisualizeItem( uint8 slot, Item *pItem)
10717 if(!pItem)
10718 return;
10720 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10721 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10722 pItem->SetBinding( true );
10724 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10726 m_items[slot] = pItem;
10727 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), pItem->GetGUID() );
10728 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10729 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10730 pItem->SetSlot( slot );
10731 pItem->SetContainer( NULL );
10733 if( slot < EQUIPMENT_SLOT_END )
10734 SetVisibleItemSlot(slot, pItem);
10736 pItem->SetState(ITEM_CHANGED, this);
10739 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10741 // note: removeitem does not actually change the item
10742 // it only takes the item out of storage temporarily
10743 // note2: if removeitem is to be used for delinking
10744 // the item must be removed from the player's updatequeue
10746 Item *pItem = GetItemByPos( bag, slot );
10747 if( pItem )
10749 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10751 RemoveEnchantmentDurations(pItem);
10752 RemoveItemDurations(pItem);
10754 if( bag == INVENTORY_SLOT_BAG_0 )
10756 if ( slot < INVENTORY_SLOT_BAG_END )
10758 ItemPrototype const *pProto = pItem->GetProto();
10759 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10761 if(pProto && pProto->ItemSet)
10762 RemoveItemsSetItem(this, pProto);
10764 _ApplyItemMods(pItem, slot, false);
10766 // remove item dependent auras and casts (only weapon and armor slots)
10767 if(slot < EQUIPMENT_SLOT_END)
10769 RemoveItemDependentAurasAndCasts(pItem);
10771 // remove held enchantments, update expertise
10772 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10774 if (pItem->GetItemSuffixFactor())
10776 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10777 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10779 else
10781 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10782 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10785 UpdateExpertise(BASE_ATTACK);
10786 UpdateArmorPenetration();
10788 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10790 UpdateExpertise(OFF_ATTACK);
10791 UpdateArmorPenetration();
10795 // need update known currency
10796 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10797 UpdateKnownCurrencies(pItem->GetEntry(), false);
10799 m_items[slot] = NULL;
10800 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10802 if ( slot < EQUIPMENT_SLOT_END )
10803 SetVisibleItemSlot(slot, NULL);
10805 else
10807 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10808 if( pBag )
10809 pBag->RemoveItem(slot, update);
10811 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10812 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10813 pItem->SetSlot( NULL_SLOT );
10814 if( IsInWorld() && update )
10815 pItem->SendCreateUpdateToPlayer( this );
10819 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10820 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10822 if(Item* it = GetItemByPos(bag,slot))
10824 ItemRemovedQuestCheck(it->GetEntry(), it->GetCount());
10825 RemoveItem(bag, slot, update);
10826 it->RemoveFromUpdateQueueOf(this);
10827 if(it->IsInWorld())
10829 it->RemoveFromWorld();
10830 it->DestroyForPlayer( this );
10835 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10836 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10838 // update quest counters
10839 ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount());
10841 // store item
10842 Item* pLastItem = StoreItem(dest, pItem, update);
10844 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10845 if(pLastItem == pItem)
10847 // update owner for last item (this can be original item with wrong owner
10848 if(pLastItem->GetOwnerGUID() != GetGUID())
10849 pLastItem->SetOwnerGUID(GetGUID());
10851 // if this original item then it need create record in inventory
10852 // in case trade we already have item in other player inventory
10853 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10857 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10859 Item *pItem = GetItemByPos( bag, slot );
10860 if( pItem )
10862 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10864 // start from destroy contained items (only equipped bag can have its)
10865 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10867 for (int i = 0; i < MAX_BAG_SIZE; ++i)
10868 DestroyItem(slot, i, update);
10871 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10872 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10874 RemoveEnchantmentDurations(pItem);
10875 RemoveItemDurations(pItem);
10877 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10879 if( bag == INVENTORY_SLOT_BAG_0 )
10881 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0);
10883 // equipment and equipped bags can have applied bonuses
10884 if ( slot < INVENTORY_SLOT_BAG_END )
10886 ItemPrototype const *pProto = pItem->GetProto();
10888 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10889 if(pProto && pProto->ItemSet)
10890 RemoveItemsSetItem(this, pProto);
10892 _ApplyItemMods(pItem, slot, false);
10895 if ( slot < EQUIPMENT_SLOT_END )
10897 // remove item dependent auras and casts (only weapon and armor slots)
10898 RemoveItemDependentAurasAndCasts(pItem);
10900 // update expertise
10901 if( slot == EQUIPMENT_SLOT_MAINHAND )
10903 UpdateExpertise(BASE_ATTACK);
10904 UpdateArmorPenetration();
10906 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10908 UpdateExpertise(OFF_ATTACK);
10909 UpdateArmorPenetration();
10912 // equipment visual show
10913 SetVisibleItemSlot(slot, NULL);
10915 // need update known currency
10916 else if (slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END)
10917 UpdateKnownCurrencies(pItem->GetEntry(), false);
10919 m_items[slot] = NULL;
10921 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10922 pBag->RemoveItem(slot, update);
10924 if( IsInWorld() && update )
10926 pItem->RemoveFromWorld();
10927 pItem->DestroyForPlayer(this);
10930 //pItem->SetOwnerGUID(0);
10931 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10932 pItem->SetSlot( NULL_SLOT );
10933 pItem->SetState(ITEM_REMOVED, this);
10937 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10939 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10940 uint32 remcount = 0;
10942 // in inventory
10943 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
10945 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10947 if (pItem->GetEntry() == item)
10949 if (pItem->GetCount() + remcount <= count)
10951 // all items in inventory can unequipped
10952 remcount += pItem->GetCount();
10953 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10955 if (remcount >= count)
10956 return;
10958 else
10960 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10961 pItem->SetCount( pItem->GetCount() - count + remcount );
10962 if (IsInWorld() & update)
10963 pItem->SendCreateUpdateToPlayer( this );
10964 pItem->SetState(ITEM_CHANGED, this);
10965 return;
10971 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
10973 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10975 if (pItem->GetEntry() == item)
10977 if (pItem->GetCount() + remcount <= count)
10979 // all keys can be unequipped
10980 remcount += pItem->GetCount();
10981 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10983 if (remcount >= count)
10984 return;
10986 else
10988 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10989 pItem->SetCount( pItem->GetCount() - count + remcount );
10990 if (IsInWorld() & update)
10991 pItem->SendCreateUpdateToPlayer( this );
10992 pItem->SetState(ITEM_CHANGED, this);
10993 return;
10999 // in inventory bags
11000 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11002 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11004 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11006 if(Item* pItem = pBag->GetItemByPos(j))
11008 if (pItem->GetEntry() == item)
11010 // all items in bags can be unequipped
11011 if (pItem->GetCount() + remcount <= count)
11013 remcount += pItem->GetCount();
11014 DestroyItem( i, j, update );
11016 if (remcount >= count)
11017 return;
11019 else
11021 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11022 pItem->SetCount( pItem->GetCount() - count + remcount );
11023 if (IsInWorld() && update)
11024 pItem->SendCreateUpdateToPlayer( this );
11025 pItem->SetState(ITEM_CHANGED, this);
11026 return;
11034 // in equipment and bag list
11035 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
11037 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11039 if (pItem && pItem->GetEntry() == item)
11041 if (pItem->GetCount() + remcount <= count)
11043 if (!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false) == EQUIP_ERR_OK )
11045 remcount += pItem->GetCount();
11046 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11048 if (remcount >= count)
11049 return;
11052 else
11054 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
11055 pItem->SetCount( pItem->GetCount() - count + remcount );
11056 if (IsInWorld() & update)
11057 pItem->SendCreateUpdateToPlayer( this );
11058 pItem->SetState(ITEM_CHANGED, this);
11059 return;
11066 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
11068 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
11070 // in inventory
11071 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11072 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11073 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11074 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11076 for(int i = KEYRING_SLOT_START; i < CURRENCYTOKEN_SLOT_END; ++i)
11077 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11078 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11079 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11081 // in inventory bags
11082 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11083 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11084 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11085 if (Item* pItem = pBag->GetItemByPos(j))
11086 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11087 DestroyItem(i, j, update);
11089 // in equipment and bag list
11090 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
11091 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11092 if (pItem->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone))
11093 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11096 void Player::DestroyConjuredItems( bool update )
11098 // used when entering arena
11099 // destroys all conjured items
11100 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
11102 // in inventory
11103 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11104 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11105 if (pItem->IsConjuredConsumable())
11106 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11108 // in inventory bags
11109 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11110 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11111 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11112 if (Item* pItem = pBag->GetItemByPos(j))
11113 if (pItem->IsConjuredConsumable())
11114 DestroyItem( i, j, update);
11116 // in equipment and bag list
11117 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; ++i)
11118 if (Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11119 if (pItem->IsConjuredConsumable())
11120 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
11123 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
11125 if(!pItem)
11126 return;
11128 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
11130 if( pItem->GetCount() <= count )
11132 count -= pItem->GetCount();
11134 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
11136 else
11138 ItemRemovedQuestCheck( pItem->GetEntry(), count);
11139 pItem->SetCount( pItem->GetCount() - count );
11140 count = 0;
11141 if( IsInWorld() & update )
11142 pItem->SendCreateUpdateToPlayer( this );
11143 pItem->SetState(ITEM_CHANGED, this);
11147 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
11149 uint8 srcbag = src >> 8;
11150 uint8 srcslot = src & 255;
11152 uint8 dstbag = dst >> 8;
11153 uint8 dstslot = dst & 255;
11155 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11156 if( !pSrcItem )
11158 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11159 return;
11162 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
11164 //best error message found for attempting to split while looting
11165 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11166 return;
11169 // not let split all items (can be only at cheating)
11170 if(pSrcItem->GetCount() == count)
11172 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
11173 return;
11176 // not let split more existed items (can be only at cheating)
11177 if(pSrcItem->GetCount() < count)
11179 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
11180 return;
11183 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
11184 Item *pNewItem = pSrcItem->CloneItem( count, this );
11185 if( !pNewItem )
11187 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
11188 return;
11191 if( IsInventoryPos( dst ) )
11193 // change item amount before check (for unique max count check)
11194 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11196 ItemPosCountVec dest;
11197 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
11198 if( msg != EQUIP_ERR_OK )
11200 delete pNewItem;
11201 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11202 SendEquipError( msg, pSrcItem, NULL );
11203 return;
11206 if( IsInWorld() )
11207 pSrcItem->SendCreateUpdateToPlayer( this );
11208 pSrcItem->SetState(ITEM_CHANGED, this);
11209 StoreItem( dest, pNewItem, true);
11211 else if( IsBankPos ( dst ) )
11213 // change item amount before check (for unique max count check)
11214 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11216 ItemPosCountVec dest;
11217 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
11218 if( msg != EQUIP_ERR_OK )
11220 delete pNewItem;
11221 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11222 SendEquipError( msg, pSrcItem, NULL );
11223 return;
11226 if( IsInWorld() )
11227 pSrcItem->SendCreateUpdateToPlayer( this );
11228 pSrcItem->SetState(ITEM_CHANGED, this);
11229 BankItem( dest, pNewItem, true);
11231 else if( IsEquipmentPos ( dst ) )
11233 // change item amount before check (for unique max count check), provide space for splitted items
11234 pSrcItem->SetCount( pSrcItem->GetCount() - count );
11236 uint16 dest;
11237 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
11238 if( msg != EQUIP_ERR_OK )
11240 delete pNewItem;
11241 pSrcItem->SetCount( pSrcItem->GetCount() + count );
11242 SendEquipError( msg, pSrcItem, NULL );
11243 return;
11246 if( IsInWorld() )
11247 pSrcItem->SendCreateUpdateToPlayer( this );
11248 pSrcItem->SetState(ITEM_CHANGED, this);
11249 EquipItem( dest, pNewItem, true);
11250 AutoUnequipOffhandIfNeed();
11254 void Player::SwapItem( uint16 src, uint16 dst )
11256 uint8 srcbag = src >> 8;
11257 uint8 srcslot = src & 255;
11259 uint8 dstbag = dst >> 8;
11260 uint8 dstslot = dst & 255;
11262 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11263 Item *pDstItem = GetItemByPos( dstbag, dstslot );
11265 if (!pSrcItem)
11266 return;
11268 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
11270 if (!isAlive())
11272 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
11273 return;
11276 // SRC checks
11278 // check unequip potability for equipped items and bank bags
11279 if (IsEquipmentPos(src) || IsBagPos(src))
11281 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11282 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ) || (pDstItem && pDstItem->IsBag() && ((Bag*)pDstItem)->IsEmpty()));
11283 if (msg != EQUIP_ERR_OK)
11285 SendEquipError( msg, pSrcItem, pDstItem );
11286 return;
11290 // prevent put equipped/bank bag in self
11291 if (IsBagPos(src) && srcslot == dstbag)
11293 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11294 return;
11297 // prevent put equipped/bank bag in self
11298 if (IsBagPos(dst) && dstslot == srcbag)
11300 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pDstItem, pSrcItem );
11301 return;
11304 // DST checks
11306 if (pDstItem)
11308 // check unequip potability for equipped items and bank bags
11309 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11311 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11312 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) || (pSrcItem->IsBag() && ((Bag*)pSrcItem)->IsEmpty()));
11313 if(msg != EQUIP_ERR_OK)
11315 SendEquipError( msg, pSrcItem, pDstItem );
11316 return;
11321 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11322 // or swap empty bag with another empty or not empty bag (with items exchange)
11324 // Move case
11325 if( !pDstItem )
11327 if( IsInventoryPos( dst ) )
11329 ItemPosCountVec dest;
11330 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
11331 if( msg != EQUIP_ERR_OK )
11333 SendEquipError( msg, pSrcItem, NULL );
11334 return;
11337 RemoveItem(srcbag, srcslot, true);
11338 StoreItem( dest, pSrcItem, true);
11340 else if( IsBankPos ( dst ) )
11342 ItemPosCountVec dest;
11343 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11344 if( msg != EQUIP_ERR_OK )
11346 SendEquipError( msg, pSrcItem, NULL );
11347 return;
11350 RemoveItem(srcbag, srcslot, true);
11351 BankItem( dest, pSrcItem, true);
11353 else if( IsEquipmentPos ( dst ) )
11355 uint16 dest;
11356 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11357 if( msg != EQUIP_ERR_OK )
11359 SendEquipError( msg, pSrcItem, NULL );
11360 return;
11363 RemoveItem(srcbag, srcslot, true);
11364 EquipItem(dest, pSrcItem, true);
11365 AutoUnequipOffhandIfNeed();
11368 return;
11371 // attempt merge to / fill target item
11372 if(!pSrcItem->IsBag() && !pDstItem->IsBag())
11374 uint8 msg;
11375 ItemPosCountVec sDest;
11376 uint16 eDest;
11377 if( IsInventoryPos( dst ) )
11378 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11379 else if( IsBankPos ( dst ) )
11380 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11381 else if( IsEquipmentPos ( dst ) )
11382 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11383 else
11384 return;
11386 // can be merge/fill
11387 if(msg == EQUIP_ERR_OK)
11389 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->GetMaxStackSize())
11391 RemoveItem(srcbag, srcslot, true);
11393 if( IsInventoryPos( dst ) )
11394 StoreItem( sDest, pSrcItem, true);
11395 else if( IsBankPos ( dst ) )
11396 BankItem( sDest, pSrcItem, true);
11397 else if( IsEquipmentPos ( dst ) )
11399 EquipItem( eDest, pSrcItem, true);
11400 AutoUnequipOffhandIfNeed();
11403 else
11405 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->GetMaxStackSize());
11406 pDstItem->SetCount( pSrcItem->GetProto()->GetMaxStackSize());
11407 pSrcItem->SetState(ITEM_CHANGED, this);
11408 pDstItem->SetState(ITEM_CHANGED, this);
11409 if( IsInWorld() )
11411 pSrcItem->SendCreateUpdateToPlayer( this );
11412 pDstItem->SendCreateUpdateToPlayer( this );
11415 return;
11419 // impossible merge/fill, do real swap
11420 uint8 msg;
11422 // check src->dest move possibility
11423 ItemPosCountVec sDest;
11424 uint16 eDest = 0;
11425 if( IsInventoryPos( dst ) )
11426 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11427 else if( IsBankPos( dst ) )
11428 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11429 else if( IsEquipmentPos( dst ) )
11431 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11432 if( msg == EQUIP_ERR_OK )
11433 msg = CanUnequipItem( eDest, true );
11436 if( msg != EQUIP_ERR_OK )
11438 SendEquipError( msg, pSrcItem, pDstItem );
11439 return;
11442 // check dest->src move possibility
11443 ItemPosCountVec sDest2;
11444 uint16 eDest2 = 0;
11445 if( IsInventoryPos( src ) )
11446 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11447 else if( IsBankPos( src ) )
11448 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11449 else if( IsEquipmentPos( src ) )
11451 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11452 if( msg == EQUIP_ERR_OK )
11453 msg = CanUnequipItem( eDest2, true);
11456 if( msg != EQUIP_ERR_OK )
11458 SendEquipError( msg, pDstItem, pSrcItem );
11459 return;
11462 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11463 if(pSrcItem->IsBag() && pDstItem->IsBag())
11465 Bag* emptyBag = NULL;
11466 Bag* fullBag = NULL;
11467 if(((Bag*)pSrcItem)->IsEmpty() && !IsBagPos(src))
11469 emptyBag = (Bag*)pSrcItem;
11470 fullBag = (Bag*)pDstItem;
11472 else if(((Bag*)pDstItem)->IsEmpty() && !IsBagPos(dst))
11474 emptyBag = (Bag*)pDstItem;
11475 fullBag = (Bag*)pSrcItem;
11478 // bag swap (with items exchange) case
11479 if(emptyBag && fullBag)
11481 ItemPrototype const* emotyProto = emptyBag->GetProto();
11483 uint32 count = 0;
11485 for(int i=0; i < fullBag->GetBagSize(); ++i)
11487 Item *bagItem = fullBag->GetItemByPos(i);
11488 if (!bagItem)
11489 continue;
11491 ItemPrototype const* bagItemProto = bagItem->GetProto();
11492 if (!bagItemProto || !ItemCanGoIntoBag(bagItemProto, emotyProto))
11494 // one from items not go to empty target bag
11495 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11496 return;
11499 ++count;
11503 if (count > emptyBag->GetBagSize())
11505 // too small targeted bag
11506 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, pSrcItem, pDstItem );
11507 return;
11510 // Items swap
11511 count = 0; // will pos in new bag
11512 for(int i = 0; i< fullBag->GetBagSize(); ++i)
11514 Item *bagItem = fullBag->GetItemByPos(i);
11515 if (!bagItem)
11516 continue;
11518 fullBag->RemoveItem(i, true);
11519 emptyBag->StoreItem(count, bagItem, true);
11520 bagItem->SetState(ITEM_CHANGED, this);
11522 ++count;
11527 // now do moves, remove...
11528 RemoveItem(dstbag, dstslot, false);
11529 RemoveItem(srcbag, srcslot, false);
11531 // add to dest
11532 if (IsInventoryPos(dst))
11533 StoreItem(sDest, pSrcItem, true);
11534 else if (IsBankPos(dst))
11535 BankItem(sDest, pSrcItem, true);
11536 else if (IsEquipmentPos(dst))
11537 EquipItem(eDest, pSrcItem, true);
11539 // add to src
11540 if (IsInventoryPos(src))
11541 StoreItem(sDest2, pDstItem, true);
11542 else if (IsBankPos(src))
11543 BankItem(sDest2, pDstItem, true);
11544 else if (IsEquipmentPos(src))
11545 EquipItem(eDest2, pDstItem, true);
11547 AutoUnequipOffhandIfNeed();
11550 void Player::AddItemToBuyBackSlot( Item *pItem )
11552 if (pItem)
11554 uint32 slot = m_currentBuybackSlot;
11555 // if current back slot non-empty search oldest or free
11556 if (m_items[slot])
11558 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11559 uint32 oldest_slot = BUYBACK_SLOT_START;
11561 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11563 // found empty
11564 if (!m_items[i])
11566 slot = i;
11567 break;
11570 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11572 if (oldest_time > i_time)
11574 oldest_time = i_time;
11575 oldest_slot = i;
11579 // find oldest
11580 slot = oldest_slot;
11583 RemoveItemFromBuyBackSlot( slot, true );
11584 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11586 m_items[slot] = pItem;
11587 time_t base = time(NULL);
11588 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11589 uint32 eslot = slot - BUYBACK_SLOT_START;
11591 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), pItem->GetGUID() );
11592 if (ItemPrototype const *pProto = pItem->GetProto())
11593 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11594 else
11595 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11596 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11598 // move to next (for non filled list is move most optimized choice)
11599 if (m_currentBuybackSlot < BUYBACK_SLOT_END - 1)
11600 ++m_currentBuybackSlot;
11604 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11606 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11607 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
11608 return m_items[slot];
11609 return NULL;
11612 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11614 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11615 if (slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END)
11617 Item *pItem = m_items[slot];
11618 if (pItem)
11620 pItem->RemoveFromWorld();
11621 if(del) pItem->SetState(ITEM_REMOVED, this);
11624 m_items[slot] = NULL;
11626 uint32 eslot = slot - BUYBACK_SLOT_START;
11627 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0 );
11628 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11629 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11631 // if current backslot is filled set to now free slot
11632 if (m_items[m_currentBuybackSlot])
11633 m_currentBuybackSlot = slot;
11637 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11639 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg);
11640 WorldPacket data(SMSG_INVENTORY_CHANGE_FAILURE, 1+8+8+1);
11641 data << uint8(msg);
11643 if (msg != EQUIP_ERR_OK)
11645 data << uint64(pItem ? pItem->GetGUID() : 0);
11646 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11647 data << uint8(0); // bag type subclass, used with EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM and EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG2
11649 switch(msg)
11651 case EQUIP_ERR_CANT_EQUIP_LEVEL_I:
11652 case EQUIP_ERR_PURCHASE_LEVEL_TOO_LOW:
11654 ItemPrototype const* proto = pItem ? pItem->GetProto() : NULL;
11655 data << uint32(proto ? proto->RequiredLevel : 0);
11656 } break;
11657 case EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM: // no idea about this one...
11659 data << uint64(0);
11660 data << uint32(0);
11661 data << uint64(0);
11662 } break;
11663 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS:
11664 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED_IS:
11665 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS:
11667 ItemPrototype const* proto = pItem ? pItem->GetProto() : NULL;
11668 data << uint32(proto ? proto->ItemLimitCategory : 0);
11669 } break;
11670 default:
11671 break;
11674 GetSession()->SendPacket(&data);
11677 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11679 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11680 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11681 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11682 data << uint32(item);
11683 if (param > 0)
11684 data << uint32(param);
11685 data << uint8(msg);
11686 GetSession()->SendPacket(&data);
11689 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11691 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11692 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11693 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11694 data << uint64(guid);
11695 if (param > 0)
11696 data << uint32(param);
11697 data << uint8(msg);
11698 GetSession()->SendPacket(&data);
11701 void Player::ClearTrade()
11703 tradeGold = 0;
11704 acceptTrade = false;
11705 for(int i = 0; i < TRADE_SLOT_COUNT; ++i)
11706 tradeItems[i] = NULL_SLOT;
11709 void Player::TradeCancel(bool sendback)
11711 if (pTrader)
11713 // send yellow "Trade canceled" message to both traders
11714 WorldSession* ws;
11715 ws = GetSession();
11716 if (sendback)
11717 ws->SendCancelTrade();
11718 ws = pTrader->GetSession();
11719 if (!ws->PlayerLogout())
11720 ws->SendCancelTrade();
11722 // cleanup
11723 ClearTrade();
11724 pTrader->ClearTrade();
11725 // prevent loss of reference
11726 pTrader->pTrader = NULL;
11727 pTrader = NULL;
11731 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11733 if (m_itemDuration.empty())
11734 return;
11736 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time, realtimeonly);
11738 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); )
11740 Item* item = *itr;
11741 ++itr; // current element can be erased in UpdateDuration
11743 if ((realtimeonly && item->GetProto()->Duration < 0) || !realtimeonly)
11744 item->UpdateDuration(this,time);
11748 void Player::UpdateEnchantTime(uint32 time)
11750 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11752 assert(itr->item);
11753 next = itr;
11754 if (!itr->item->GetEnchantmentId(itr->slot))
11756 next = m_enchantDuration.erase(itr);
11758 else if (itr->leftduration <= time)
11760 ApplyEnchantment(itr->item, itr->slot, false, false);
11761 itr->item->ClearEnchantment(itr->slot);
11762 next = m_enchantDuration.erase(itr);
11764 else if (itr->leftduration > time)
11766 itr->leftduration -= time;
11767 ++next;
11772 void Player::AddEnchantmentDurations(Item *item)
11774 for(int x = 0; x < MAX_ENCHANTMENT_SLOT; ++x)
11776 if (!item->GetEnchantmentId(EnchantmentSlot(x)))
11777 continue;
11779 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11780 if (duration > 0)
11781 AddEnchantmentDuration(item, EnchantmentSlot(x), duration);
11785 void Player::RemoveEnchantmentDurations(Item *item)
11787 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end();)
11789 if (itr->item == item)
11791 // save duration in item
11792 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot), itr->leftduration);
11793 itr = m_enchantDuration.erase(itr);
11795 else
11796 ++itr;
11800 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11802 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11803 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(), next; itr != m_enchantDuration.end(); itr = next)
11805 next = itr;
11806 if (itr->slot == slot)
11808 if (itr->item && itr->item->GetEnchantmentId(slot))
11810 // remove from stats
11811 ApplyEnchantment(itr->item, slot, false, false);
11812 // remove visual
11813 itr->item->ClearEnchantment(slot);
11815 // remove from update list
11816 next = m_enchantDuration.erase(itr);
11818 else
11819 ++next;
11822 // remove enchants from inventory items
11823 // NOTE: no need to remove these from stats, since these aren't equipped
11824 // in inventory
11825 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; ++i)
11826 if (Item* pItem = GetItemByPos(INVENTORY_SLOT_BAG_0, i))
11827 if (pItem->GetEnchantmentId(slot))
11828 pItem->ClearEnchantment(slot);
11830 // in inventory bags
11831 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
11832 if (Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
11833 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
11834 if (Item* pItem = pBag->GetItemByPos(j))
11835 if (pItem->GetEnchantmentId(slot))
11836 pItem->ClearEnchantment(slot);
11839 // duration == 0 will remove item enchant
11840 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11842 if (!item)
11843 return;
11845 if (slot >= MAX_ENCHANTMENT_SLOT)
11846 return;
11848 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
11850 if (itr->item == item && itr->slot == slot)
11852 itr->item->SetEnchantmentDuration(itr->slot, itr->leftduration);
11853 m_enchantDuration.erase(itr);
11854 break;
11857 if (item && duration > 0 )
11859 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(), slot, uint32(duration/1000));
11860 m_enchantDuration.push_back(EnchantDuration(item, slot, duration));
11864 void Player::ApplyEnchantment(Item *item,bool apply)
11866 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11867 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11870 void Player::ApplyEnchantment(Item *item, EnchantmentSlot slot, bool apply, bool apply_dur, bool ignore_condition)
11872 if (!item)
11873 return;
11875 if (!item->IsEquipped())
11876 return;
11878 if (slot >= MAX_ENCHANTMENT_SLOT)
11879 return;
11881 uint32 enchant_id = item->GetEnchantmentId(slot);
11882 if (!enchant_id)
11883 return;
11885 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11886 if (!pEnchant)
11887 return;
11889 if (!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11890 return;
11892 if (!item->IsBroken())
11894 for (int s = 0; s < 3; ++s)
11896 uint32 enchant_display_type = pEnchant->type[s];
11897 uint32 enchant_amount = pEnchant->amount[s];
11898 uint32 enchant_spell_id = pEnchant->spellid[s];
11900 switch(enchant_display_type)
11902 case ITEM_ENCHANTMENT_TYPE_NONE:
11903 break;
11904 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11905 // processed in Player::CastItemCombatSpell
11906 break;
11907 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11908 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11909 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11910 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11911 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11912 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11913 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11914 break;
11915 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11916 if (enchant_spell_id)
11918 if (apply)
11920 int32 basepoints = 0;
11921 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11922 if (item->GetItemRandomPropertyId())
11924 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11925 if (item_rand)
11927 // Search enchant_amount
11928 for (int k = 0; k < 3; ++k)
11930 if(item_rand->enchant_id[k] == enchant_id)
11932 basepoints = int32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11933 break;
11938 // Cast custom spell vs all equal basepoints getted from enchant_amount
11939 if (basepoints)
11940 CastCustomSpell(this, enchant_spell_id, &basepoints, &basepoints, &basepoints, true, item);
11941 else
11942 CastSpell(this, enchant_spell_id, true, item);
11944 else
11945 RemoveAurasDueToItemSpell(item, enchant_spell_id);
11947 break;
11948 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11949 if (!enchant_amount)
11951 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11952 if(item_rand)
11954 for (int k = 0; k < 3; ++k)
11956 if(item_rand->enchant_id[k] == enchant_id)
11958 enchant_amount = uint32((item_rand->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11959 break;
11965 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11966 break;
11967 case ITEM_ENCHANTMENT_TYPE_STAT:
11969 if (!enchant_amount)
11971 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11972 if(item_rand_suffix)
11974 for (int k = 0; k < 3; ++k)
11976 if(item_rand_suffix->enchant_id[k] == enchant_id)
11978 enchant_amount = uint32((item_rand_suffix->prefix[k] * item->GetItemSuffixFactor()) / 10000 );
11979 break;
11985 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11986 switch (enchant_spell_id)
11988 case ITEM_MOD_MANA:
11989 sLog.outDebug("+ %u MANA",enchant_amount);
11990 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(enchant_amount), apply);
11991 break;
11992 case ITEM_MOD_HEALTH:
11993 sLog.outDebug("+ %u HEALTH",enchant_amount);
11994 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(enchant_amount), apply);
11995 break;
11996 case ITEM_MOD_AGILITY:
11997 sLog.outDebug("+ %u AGILITY",enchant_amount);
11998 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11999 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
12000 break;
12001 case ITEM_MOD_STRENGTH:
12002 sLog.outDebug("+ %u STRENGTH",enchant_amount);
12003 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
12004 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
12005 break;
12006 case ITEM_MOD_INTELLECT:
12007 sLog.outDebug("+ %u INTELLECT",enchant_amount);
12008 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
12009 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
12010 break;
12011 case ITEM_MOD_SPIRIT:
12012 sLog.outDebug("+ %u SPIRIT",enchant_amount);
12013 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
12014 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
12015 break;
12016 case ITEM_MOD_STAMINA:
12017 sLog.outDebug("+ %u STAMINA",enchant_amount);
12018 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
12019 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
12020 break;
12021 case ITEM_MOD_DEFENSE_SKILL_RATING:
12022 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
12023 sLog.outDebug("+ %u DEFENCE", enchant_amount);
12024 break;
12025 case ITEM_MOD_DODGE_RATING:
12026 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
12027 sLog.outDebug("+ %u DODGE", enchant_amount);
12028 break;
12029 case ITEM_MOD_PARRY_RATING:
12030 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
12031 sLog.outDebug("+ %u PARRY", enchant_amount);
12032 break;
12033 case ITEM_MOD_BLOCK_RATING:
12034 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
12035 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
12036 break;
12037 case ITEM_MOD_HIT_MELEE_RATING:
12038 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
12039 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
12040 break;
12041 case ITEM_MOD_HIT_RANGED_RATING:
12042 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
12043 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
12044 break;
12045 case ITEM_MOD_HIT_SPELL_RATING:
12046 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
12047 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
12048 break;
12049 case ITEM_MOD_CRIT_MELEE_RATING:
12050 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12051 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
12052 break;
12053 case ITEM_MOD_CRIT_RANGED_RATING:
12054 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12055 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
12056 break;
12057 case ITEM_MOD_CRIT_SPELL_RATING:
12058 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12059 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
12060 break;
12061 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
12062 // in Enchantments
12063 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
12064 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12065 // break;
12066 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
12067 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12068 // break;
12069 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
12070 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12071 // break;
12072 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
12073 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12074 // break;
12075 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
12076 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12077 // break;
12078 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
12079 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12080 // break;
12081 // case ITEM_MOD_HASTE_MELEE_RATING:
12082 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12083 // break;
12084 // case ITEM_MOD_HASTE_RANGED_RATING:
12085 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12086 // break;
12087 case ITEM_MOD_HASTE_SPELL_RATING:
12088 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12089 break;
12090 case ITEM_MOD_HIT_RATING:
12091 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
12092 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
12093 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
12094 sLog.outDebug("+ %u HIT", enchant_amount);
12095 break;
12096 case ITEM_MOD_CRIT_RATING:
12097 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
12098 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
12099 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
12100 sLog.outDebug("+ %u CRITICAL", enchant_amount);
12101 break;
12102 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
12103 // case ITEM_MOD_HIT_TAKEN_RATING:
12104 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12105 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12106 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12107 // break;
12108 // case ITEM_MOD_CRIT_TAKEN_RATING:
12109 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12110 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12111 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12112 // break;
12113 case ITEM_MOD_RESILIENCE_RATING:
12114 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12115 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12116 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12117 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
12118 break;
12119 case ITEM_MOD_HASTE_RATING:
12120 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12121 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12122 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
12123 sLog.outDebug("+ %u HASTE", enchant_amount);
12124 break;
12125 case ITEM_MOD_EXPERTISE_RATING:
12126 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
12127 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
12128 break;
12129 case ITEM_MOD_ATTACK_POWER:
12130 HandleStatModifier(UNIT_MOD_ATTACK_POWER, TOTAL_VALUE, float(enchant_amount), apply);
12131 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12132 sLog.outDebug("+ %u ATTACK_POWER", enchant_amount);
12133 break;
12134 case ITEM_MOD_RANGED_ATTACK_POWER:
12135 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
12136 sLog.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount);
12137 break;
12138 case ITEM_MOD_MANA_REGENERATION:
12139 ((Player*)this)->ApplyManaRegenBonus(enchant_amount, apply);
12140 sLog.outDebug("+ %u MANA_REGENERATION", enchant_amount);
12141 break;
12142 case ITEM_MOD_ARMOR_PENETRATION_RATING:
12143 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
12144 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
12145 break;
12146 case ITEM_MOD_SPELL_POWER:
12147 ((Player*)this)->ApplySpellPowerBonus(enchant_amount, apply);
12148 sLog.outDebug("+ %u SPELL_POWER", enchant_amount);
12149 break;
12150 case ITEM_MOD_FERAL_ATTACK_POWER:
12151 case ITEM_MOD_SPELL_HEALING_DONE: // deprecated
12152 case ITEM_MOD_SPELL_DAMAGE_DONE: // deprecated
12153 default:
12154 break;
12156 break;
12158 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
12160 if(getClass() == CLASS_SHAMAN)
12162 float addValue = 0.0f;
12163 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
12165 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
12166 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
12168 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
12170 addValue = float(enchant_amount * item->GetProto()->Delay / 1000.0f);
12171 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
12174 break;
12176 case ITEM_ENCHANTMENT_TYPE_USE_SPELL:
12177 // processed in Player::CastItemUseSpell
12178 break;
12179 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET:
12180 // nothing do..
12181 break;
12182 default:
12183 sLog.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id, enchant_display_type);
12184 break;
12185 } /*switch(enchant_display_type)*/
12186 } /*for*/
12189 // visualize enchantment at player and equipped items
12190 if(slot == PERM_ENCHANTMENT_SLOT)
12191 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 0, apply ? item->GetEnchantmentId(slot) : 0);
12193 if(slot == TEMP_ENCHANTMENT_SLOT)
12194 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT + (item->GetSlot() * 2), 1, apply ? item->GetEnchantmentId(slot) : 0);
12197 if(apply_dur)
12199 if(apply)
12201 // set duration
12202 uint32 duration = item->GetEnchantmentDuration(slot);
12203 if(duration > 0)
12204 AddEnchantmentDuration(item, slot, duration);
12206 else
12208 // duration == 0 will remove EnchantDuration
12209 AddEnchantmentDuration(item, slot, 0);
12214 void Player::SendEnchantmentDurations()
12216 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin(); itr != m_enchantDuration.end(); ++itr)
12218 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(), itr->slot, uint32(itr->leftduration) / 1000);
12222 void Player::SendItemDurations()
12224 for(ItemDurationList::const_iterator itr = m_itemDuration.begin(); itr != m_itemDuration.end(); ++itr)
12226 (*itr)->SendTimeUpdate(this);
12230 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
12232 if(!item) // prevent crash
12233 return;
12235 // last check 2.0.10
12236 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
12237 data << uint64(GetGUID()); // player GUID
12238 data << uint32(received); // 0=looted, 1=from npc
12239 data << uint32(created); // 0=received, 1=created
12240 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
12241 data << uint8(item->GetBagSlot()); // bagslot
12242 // item slot, but when added to stack: 0xFFFFFFFF
12243 data << uint32((item->GetCount() == count) ? item->GetSlot() : -1);
12244 data << uint32(item->GetEntry()); // item id
12245 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
12246 data << uint32(item->GetItemRandomPropertyId()); // random item property id
12247 data << uint32(count); // count of items
12248 data << uint32(GetItemCount(item->GetEntry())); // count of items in inventory
12250 if (broadcast && GetGroup())
12251 GetGroup()->BroadcastPacket(&data, true);
12252 else
12253 GetSession()->SendPacket(&data);
12256 /*********************************************************/
12257 /*** GOSSIP SYSTEM ***/
12258 /*********************************************************/
12260 void Player::PrepareGossipMenu(WorldObject *pSource, uint32 menuId)
12262 PlayerMenu* pMenu = PlayerTalkClass;
12263 pMenu->ClearMenus();
12265 pMenu->GetGossipMenu().SetMenuId(menuId);
12267 GossipMenuItemsMapBounds pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(menuId);
12269 // if default menuId and no menu options exist for this, use options from default options
12270 if (pMenuItemBounds.first == pMenuItemBounds.second && menuId == GetDefaultGossipMenuForSource(pSource))
12271 pMenuItemBounds = sObjectMgr.GetGossipMenuItemsMapBounds(0);
12273 for(GossipMenuItemsMap::const_iterator itr = pMenuItemBounds.first; itr != pMenuItemBounds.second; ++itr)
12275 bool bCanTalk = true;
12277 if (itr->second.cond_1 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_1))
12278 continue;
12280 if (itr->second.cond_2 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
12281 continue;
12283 if (itr->second.cond_3 && !sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_3))
12284 continue;
12286 if (pSource->GetTypeId() == TYPEID_UNIT)
12288 Creature *pCreature = (Creature*)pSource;
12290 uint32 npcflags = pCreature->GetUInt32Value(UNIT_NPC_FLAGS);
12292 if (!(itr->second.npc_option_npcflag & npcflags))
12293 continue;
12295 switch(itr->second.option_id)
12297 case GOSSIP_OPTION_QUESTGIVER:
12298 PrepareQuestMenu(pSource->GetGUID());
12299 bCanTalk = false;
12300 break;
12301 case GOSSIP_OPTION_ARMORER:
12302 bCanTalk = false; // added in special mode
12303 break;
12304 case GOSSIP_OPTION_SPIRITHEALER:
12305 if (!isDead())
12306 bCanTalk = false;
12307 break;
12308 case GOSSIP_OPTION_VENDOR:
12310 VendorItemData const* vItems = pCreature->GetVendorItems();
12311 if (!vItems || vItems->Empty())
12313 sLog.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", pCreature->GetGUIDLow(), pCreature->GetEntry());
12314 bCanTalk = false;
12316 break;
12318 case GOSSIP_OPTION_TRAINER:
12319 if (!pCreature->isCanTrainingOf(this, false))
12320 bCanTalk = false;
12321 break;
12322 case GOSSIP_OPTION_UNLEARNTALENTS:
12323 if (!pCreature->isCanTrainingAndResetTalentsOf(this))
12324 bCanTalk = false;
12325 break;
12326 case GOSSIP_OPTION_UNLEARNPETSKILLS:
12327 if (!GetPet() || GetPet()->getPetType() != HUNTER_PET || GetPet()->m_spells.size() <= 1 || pCreature->GetCreatureInfo()->trainer_type != TRAINER_TYPE_PETS || pCreature->GetCreatureInfo()->trainer_class != CLASS_HUNTER)
12328 bCanTalk = false;
12329 break;
12330 case GOSSIP_OPTION_TAXIVENDOR:
12331 if (GetSession()->SendLearnNewTaxiNode(pCreature))
12332 return;
12333 break;
12334 case GOSSIP_OPTION_BATTLEFIELD:
12335 if (!pCreature->isCanInteractWithBattleMaster(this, false))
12336 bCanTalk = false;
12337 break;
12338 case GOSSIP_OPTION_STABLEPET:
12339 if (getClass() != CLASS_HUNTER)
12340 bCanTalk = false;
12341 break;
12342 case GOSSIP_OPTION_GOSSIP:
12343 case GOSSIP_OPTION_SPIRITGUIDE:
12344 case GOSSIP_OPTION_INNKEEPER:
12345 case GOSSIP_OPTION_BANKER:
12346 case GOSSIP_OPTION_PETITIONER:
12347 case GOSSIP_OPTION_TABARDDESIGNER:
12348 case GOSSIP_OPTION_AUCTIONEER:
12349 break; // no checks
12350 default:
12351 sLog.outErrorDb("Creature entry %u have unknown gossip option %u for menu %u", pCreature->GetEntry(), itr->second.option_id, itr->second.menu_id);
12352 bCanTalk = false;
12353 break;
12356 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12358 GameObject *pGo = (GameObject*)pSource;
12360 switch(itr->second.option_id)
12362 case GOSSIP_OPTION_QUESTGIVER:
12363 if (pGo->GetGoType() == GAMEOBJECT_TYPE_QUESTGIVER)
12364 PrepareQuestMenu(pSource->GetGUID());
12365 bCanTalk = false;
12366 break;
12367 case GOSSIP_OPTION_GOSSIP:
12368 if (pGo->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER && pGo->GetGoType() != GAMEOBJECT_TYPE_GOOBER)
12369 bCanTalk = false;
12370 break;
12371 default:
12372 bCanTalk = false;
12373 break;
12377 if (bCanTalk)
12379 std::string strOptionText = itr->second.option_text;
12380 std::string strBoxText = itr->second.box_text;
12382 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12384 if (loc_idx >= 0)
12386 uint32 idxEntry = MAKE_PAIR32(menuId, itr->second.id);
12388 if (GossipMenuItemsLocale const *no = sObjectMgr.GetGossipMenuItemsLocale(idxEntry))
12390 if (no->OptionText.size() > (size_t)loc_idx && !no->OptionText[loc_idx].empty())
12391 strOptionText = no->OptionText[loc_idx];
12393 if (no->BoxText.size() > (size_t)loc_idx && !no->BoxText[loc_idx].empty())
12394 strBoxText = no->BoxText[loc_idx];
12398 pMenu->GetGossipMenu().AddMenuItem(itr->second.option_icon, strOptionText, 0, itr->second.option_id, strBoxText, itr->second.box_money, itr->second.box_coded);
12399 pMenu->GetGossipMenu().AddGossipMenuItemData(itr->second.action_menu_id, itr->second.action_poi_id, itr->second.action_script_id);
12403 // some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
12404 /*if (pMenu->Empty())
12406 if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
12408 // output error message if need
12409 pCreature->isCanTrainingOf(this, true);
12412 if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
12414 // output error message if need
12415 pCreature->isCanInteractWithBattleMaster(this, true);
12420 void Player::SendPreparedGossip(WorldObject *pSource)
12422 if (!pSource)
12423 return;
12425 if (pSource->GetTypeId() == TYPEID_UNIT)
12427 // in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
12428 if (!((Creature*)pSource)->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_GOSSIP) && !PlayerTalkClass->GetQuestMenu().Empty())
12430 SendPreparedQuest(pSource->GetGUID());
12431 return;
12434 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12436 // probably need to find a better way here
12437 if (!PlayerTalkClass->GetGossipMenu().GetMenuId() && !PlayerTalkClass->GetQuestMenu().Empty())
12439 SendPreparedQuest(pSource->GetGUID());
12440 return;
12444 // in case non empty gossip menu (that not included quests list size) show it
12445 // (quest entries from quest menu will be included in list)
12447 uint32 textId = GetGossipTextId(pSource);
12449 if (uint32 menuId = PlayerTalkClass->GetGossipMenu().GetMenuId())
12450 textId = GetGossipTextId(menuId);
12452 PlayerTalkClass->SendGossipMenu(textId, pSource->GetGUID());
12455 void Player::OnGossipSelect(WorldObject* pSource, uint32 gossipListId, uint32 menuId)
12457 GossipMenu& gossipmenu = PlayerTalkClass->GetGossipMenu();
12459 if (gossipListId >= gossipmenu.MenuItemCount())
12460 return;
12462 // if not same, then something funky is going on
12463 if (menuId != gossipmenu.GetMenuId())
12464 return;
12466 uint32 gossipOptionId = gossipmenu.GetItem(gossipListId).m_gOptionId;
12467 uint64 guid = pSource->GetGUID();
12469 if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12471 if (gossipOptionId > GOSSIP_OPTION_QUESTGIVER)
12473 sLog.outError("Player guid %u request invalid gossip option for GameObject entry %u", GetGUIDLow(), pSource->GetEntry());
12474 return;
12478 GossipMenuItemData pMenuData = gossipmenu.GetItemData(gossipListId);
12480 switch(gossipOptionId)
12482 case GOSSIP_OPTION_GOSSIP:
12484 if (pMenuData.m_gAction_poi)
12485 PlayerTalkClass->SendPointOfInterest(pMenuData.m_gAction_poi);
12487 if (pMenuData.m_gAction_menu)
12489 PrepareGossipMenu(pSource, pMenuData.m_gAction_menu);
12490 SendPreparedGossip(pSource);
12493 if (pMenuData.m_gAction_script)
12495 if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12496 GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, this, pSource);
12497 else if (pSource->GetTypeId() == TYPEID_UNIT)
12498 GetMap()->ScriptsStart(sGossipScripts, pMenuData.m_gAction_script, pSource, this);
12501 break;
12503 case GOSSIP_OPTION_SPIRITHEALER:
12504 if (isDead())
12505 ((Creature*)pSource)->CastSpell(((Creature*)pSource),17251,true,NULL,NULL,GetGUID());
12506 break;
12507 case GOSSIP_OPTION_QUESTGIVER:
12508 PrepareQuestMenu(guid);
12509 SendPreparedQuest(guid);
12510 break;
12511 case GOSSIP_OPTION_VENDOR:
12512 case GOSSIP_OPTION_ARMORER:
12513 GetSession()->SendListInventory(guid);
12514 break;
12515 case GOSSIP_OPTION_STABLEPET:
12516 GetSession()->SendStablePet(guid);
12517 break;
12518 case GOSSIP_OPTION_TRAINER:
12519 GetSession()->SendTrainerList(guid);
12520 break;
12521 case GOSSIP_OPTION_UNLEARNTALENTS:
12522 PlayerTalkClass->CloseGossip();
12523 SendTalentWipeConfirm(guid);
12524 break;
12525 case GOSSIP_OPTION_UNLEARNPETSKILLS:
12526 PlayerTalkClass->CloseGossip();
12527 SendPetSkillWipeConfirm();
12528 break;
12529 case GOSSIP_OPTION_TAXIVENDOR:
12530 GetSession()->SendTaxiMenu(((Creature*)pSource));
12531 break;
12532 case GOSSIP_OPTION_INNKEEPER:
12533 PlayerTalkClass->CloseGossip();
12534 SetBindPoint(guid);
12535 break;
12536 case GOSSIP_OPTION_BANKER:
12537 GetSession()->SendShowBank(guid);
12538 break;
12539 case GOSSIP_OPTION_PETITIONER:
12540 PlayerTalkClass->CloseGossip();
12541 GetSession()->SendPetitionShowList(guid);
12542 break;
12543 case GOSSIP_OPTION_TABARDDESIGNER:
12544 PlayerTalkClass->CloseGossip();
12545 GetSession()->SendTabardVendorActivate(guid);
12546 break;
12547 case GOSSIP_OPTION_AUCTIONEER:
12548 GetSession()->SendAuctionHello(guid, ((Creature*)pSource));
12549 break;
12550 case GOSSIP_OPTION_SPIRITGUIDE:
12551 PrepareGossipMenu(pSource);
12552 SendPreparedGossip(pSource);
12553 break;
12554 case GOSSIP_OPTION_BATTLEFIELD:
12556 BattleGroundTypeId bgTypeId = sBattleGroundMgr.GetBattleMasterBG(pSource->GetEntry());
12558 if (bgTypeId == BATTLEGROUND_TYPE_NONE)
12560 sLog.outError("a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUIDLow());
12561 return;
12564 GetSession()->SendBattlegGroundList(guid, bgTypeId);
12565 break;
12570 uint32 Player::GetGossipTextId(WorldObject *pSource)
12572 if (!pSource || pSource->GetTypeId() != TYPEID_UNIT || !((Creature*)pSource)->GetDBTableGUIDLow())
12573 return DEFAULT_GOSSIP_MESSAGE;
12575 if (uint32 pos = sObjectMgr.GetNpcGossip(((Creature*)pSource)->GetDBTableGUIDLow()))
12576 return pos;
12578 return DEFAULT_GOSSIP_MESSAGE;
12581 uint32 Player::GetGossipTextId(uint32 menuId)
12583 uint32 textId = DEFAULT_GOSSIP_MESSAGE;
12585 if (!menuId)
12586 return textId;
12588 GossipMenusMapBounds pMenuBounds = sObjectMgr.GetGossipMenusMapBounds(menuId);
12590 for(GossipMenusMap::const_iterator itr = pMenuBounds.first; itr != pMenuBounds.second; ++itr)
12592 if (sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_1) && sObjectMgr.IsPlayerMeetToCondition(this, itr->second.cond_2))
12593 textId = itr->second.text_id;
12596 return textId;
12599 uint32 Player::GetDefaultGossipMenuForSource(WorldObject *pSource)
12601 if (pSource->GetTypeId() == TYPEID_UNIT)
12602 return ((Creature*)pSource)->GetCreatureInfo()->GossipMenuId;
12603 else if (pSource->GetTypeId() == TYPEID_GAMEOBJECT)
12604 return((GameObject*)pSource)->GetGOInfo()->GetGossipMenuId();
12606 return 0;
12609 /*********************************************************/
12610 /*** QUEST SYSTEM ***/
12611 /*********************************************************/
12613 void Player::PrepareQuestMenu( uint64 guid )
12615 Object *pObject;
12616 QuestRelations* pObjectQR;
12617 QuestRelations* pObjectQIR;
12619 // pets also can have quests
12620 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12622 pObject = (Object*)pCreature;
12623 pObjectQR = &sObjectMgr.mCreatureQuestRelations;
12624 pObjectQIR = &sObjectMgr.mCreatureQuestInvolvedRelations;
12626 else
12628 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12629 //only for quests which cast teleport spells on player
12630 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
12631 ASSERT(_map);
12632 GameObject *pGameObject = _map->GetGameObject(guid);
12633 if( pGameObject )
12635 pObject = (Object*)pGameObject;
12636 pObjectQR = &sObjectMgr.mGOQuestRelations;
12637 pObjectQIR = &sObjectMgr.mGOQuestInvolvedRelations;
12639 else
12640 return;
12643 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
12644 qm.ClearMenu();
12646 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
12648 uint32 quest_id = i->second;
12649 QuestStatus status = GetQuestStatus( quest_id );
12650 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
12651 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12652 else if ( status == QUEST_STATUS_INCOMPLETE )
12653 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12654 else if (status == QUEST_STATUS_AVAILABLE )
12655 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12658 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
12660 uint32 quest_id = i->second;
12661 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
12662 if(!pQuest) continue;
12664 QuestStatus status = GetQuestStatus( quest_id );
12666 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
12667 qm.AddMenuItem(quest_id, DIALOG_STATUS_UNK2);
12668 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
12669 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
12673 void Player::SendPreparedQuest(uint64 guid)
12675 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
12677 if (questMenu.Empty())
12678 return;
12680 QuestMenuItem const& qmi0 = questMenu.GetItem(0);
12682 uint32 status = qmi0.m_qIcon;
12684 // single element case
12685 if (questMenu.MenuItemCount() == 1)
12687 // Auto open -- maybe also should verify there is no greeting
12688 uint32 quest_id = qmi0.m_qId;
12689 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
12691 if (pQuest)
12693 if (status == DIALOG_STATUS_UNK2 && !GetQuestRewardStatus(quest_id))
12694 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
12695 else if (status == DIALOG_STATUS_UNK2)
12696 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanRewardQuest(pQuest, false), true);
12697 // Send completable on repeatable and autoCompletable quest if player don't have quest
12698 // TODO: verify if check for !pQuest->IsDaily() is really correct (possibly not)
12699 else if (pQuest->IsAutoComplete() && pQuest->IsRepeatable() && !pQuest->IsDaily())
12700 PlayerTalkClass->SendQuestGiverRequestItems(pQuest, guid, CanCompleteRepeatableQuest(pQuest), true);
12701 else
12702 PlayerTalkClass->SendQuestGiverQuestDetails(pQuest, guid, true);
12705 // multiply entries
12706 else
12708 QEmote qe;
12709 qe._Delay = 0;
12710 qe._Emote = 0;
12711 std::string title = "";
12713 // need pet case for some quests
12714 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12716 uint32 textid = GetGossipTextId(pCreature);
12718 GossipText const* gossiptext = sObjectMgr.GetGossipText(textid);
12719 if (!gossiptext)
12721 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12722 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12723 title = "";
12725 else
12727 qe = gossiptext->Options[0].Emotes[0];
12729 if(!gossiptext->Options[0].Text_0.empty())
12731 title = gossiptext->Options[0].Text_0;
12733 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12734 if (loc_idx >= 0)
12736 NpcTextLocale const *nl = sObjectMgr.GetNpcTextLocale(textid);
12737 if (nl)
12739 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12740 title = nl->Text_0[0][loc_idx];
12744 else
12746 title = gossiptext->Options[0].Text_1;
12748 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12749 if (loc_idx >= 0)
12751 NpcTextLocale const *nl = sObjectMgr.GetNpcTextLocale(textid);
12752 if (nl)
12754 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12755 title = nl->Text_1[0][loc_idx];
12761 PlayerTalkClass->SendQuestGiverQuestList(qe, title, guid);
12765 bool Player::IsActiveQuest( uint32 quest_id ) const
12767 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12769 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12772 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12774 Object *pObject;
12775 QuestRelations* pObjectQR;
12776 QuestRelations* pObjectQIR;
12778 if (Creature *pCreature = GetMap()->GetCreatureOrPetOrVehicle(guid))
12780 pObject = (Object*)pCreature;
12781 pObjectQR = &sObjectMgr.mCreatureQuestRelations;
12782 pObjectQIR = &sObjectMgr.mCreatureQuestInvolvedRelations;
12784 else
12786 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12787 //only for quests which cast teleport spells on player
12788 Map * _map = IsInWorld() ? GetMap() : sMapMgr.FindMap(GetMapId(), GetInstanceId());
12789 ASSERT(_map);
12790 GameObject *pGameObject = _map->GetGameObject(guid);
12791 if( pGameObject )
12793 pObject = (Object*)pGameObject;
12794 pObjectQR = &sObjectMgr.mGOQuestRelations;
12795 pObjectQIR = &sObjectMgr.mGOQuestInvolvedRelations;
12797 else
12798 return NULL;
12801 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12802 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12804 if (itr->second == nextQuestID)
12805 return sObjectMgr.GetQuestTemplate(nextQuestID);
12808 return NULL;
12811 bool Player::CanSeeStartQuest( Quest const *pQuest )
12813 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12814 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12815 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12816 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12818 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12821 return false;
12824 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12826 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12827 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12828 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12829 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12830 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12831 && SatisfyQuestDay( pQuest, msg );
12834 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12836 if( !SatisfyQuestLog( msg ) )
12837 return false;
12839 uint32 srcitem = pQuest->GetSrcItemId();
12840 if( srcitem > 0 )
12842 uint32 count = pQuest->GetSrcItemCount();
12843 ItemPosCountVec dest;
12844 uint8 msg2 = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12846 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12847 if( msg2 == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12848 return true;
12849 else if( msg2 != EQUIP_ERR_OK )
12851 SendEquipError( msg2, NULL, NULL );
12852 return false;
12855 return true;
12858 bool Player::CanCompleteQuest( uint32 quest_id )
12860 if( quest_id )
12862 QuestStatusData& q_status = mQuestStatus[quest_id];
12863 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12864 return false; // not allow re-complete quest
12866 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
12868 if(!qInfo)
12869 return false;
12871 // auto complete quest
12872 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12873 return true;
12875 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12878 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12880 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
12882 if( qInfo->ReqItemCount[i] != 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12883 return false;
12887 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12889 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
12891 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12892 continue;
12894 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12895 return false;
12899 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12900 return false;
12902 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12903 return false;
12905 if ( qInfo->GetRewOrReqMoney() < 0 )
12907 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12908 return false;
12911 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12912 if ( repFacId && GetReputationMgr().GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12913 return false;
12915 return true;
12918 return false;
12921 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12923 // Solve problem that player don't have the quest and try complete it.
12924 // if repeatable she must be able to complete event if player don't have it.
12925 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12926 if( !CanTakeQuest(pQuest, false) )
12927 return false;
12929 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12930 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
12931 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i], pQuest->ReqItemCount[i]) )
12932 return false;
12934 if( !CanRewardQuest(pQuest, false) )
12935 return false;
12937 return true;
12940 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12942 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12943 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12944 return false;
12946 // daily quest can't be rewarded (25 daily quest already completed)
12947 if(!SatisfyQuestDay(pQuest,true))
12948 return false;
12950 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12951 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12952 return false;
12954 // prevent receive reward with quest items in bank
12955 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12957 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
12959 if( pQuest->ReqItemCount[i] != 0 &&
12960 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12962 if(msg)
12963 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12964 return false;
12969 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12970 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12971 return false;
12973 return true;
12976 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12978 // prevent receive reward with quest items in bank or for not completed quest
12979 if(!CanRewardQuest(pQuest,msg))
12980 return false;
12982 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12984 if( pQuest->RewChoiceItemId[reward] )
12986 ItemPosCountVec dest;
12987 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12988 if( res != EQUIP_ERR_OK )
12990 SendEquipError( res, NULL, NULL );
12991 return false;
12996 if ( pQuest->GetRewItemsCount() > 0 )
12998 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
13000 if( pQuest->RewItemId[i] )
13002 ItemPosCountVec dest;
13003 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
13004 if( res != EQUIP_ERR_OK )
13006 SendEquipError( res, NULL, NULL );
13007 return false;
13013 return true;
13016 void Player::SendPetTameFailure(PetTameFailureReason reason)
13018 WorldPacket data(SMSG_PET_TAME_FAILURE, 1);
13019 data << uint8(reason);
13020 GetSession()->SendPacket(&data);
13023 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
13025 uint16 log_slot = FindQuestSlot( 0 );
13026 assert(log_slot < MAX_QUEST_LOG_SIZE);
13028 uint32 quest_id = pQuest->GetQuestId();
13030 // if not exist then created with set uState==NEW and rewarded=false
13031 QuestStatusData& questStatusData = mQuestStatus[quest_id];
13033 // check for repeatable quests status reset
13034 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
13035 questStatusData.m_explored = false;
13037 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13039 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13040 questStatusData.m_itemcount[i] = 0;
13043 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
13045 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; ++i)
13046 questStatusData.m_creatureOrGOcount[i] = 0;
13049 GiveQuestSourceItem( pQuest );
13050 AdjustQuestReqItemCount( pQuest, questStatusData );
13052 if( pQuest->GetRepObjectiveFaction() )
13053 if(FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->GetRepObjectiveFaction()))
13054 GetReputationMgr().SetVisible(factionEntry);
13056 uint32 qtime = 0;
13057 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13059 uint32 limittime = pQuest->GetLimitTime();
13061 // shared timed quest
13062 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
13063 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / IN_MILISECONDS;
13065 AddTimedQuest( quest_id );
13066 questStatusData.m_timer = limittime * IN_MILISECONDS;
13067 qtime = static_cast<uint32>(time(NULL)) + limittime;
13069 else
13070 questStatusData.m_timer = 0;
13072 SetQuestSlot(log_slot, quest_id, qtime);
13074 if (questStatusData.uState != QUEST_NEW)
13075 questStatusData.uState = QUEST_CHANGED;
13077 //starting initial quest script
13078 if(questGiver && pQuest->GetQuestStartScript()!=0)
13079 GetMap()->ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
13081 // Some spells applied at quest activation
13082 SpellAreaForQuestMapBounds saBounds = sSpellMgr.GetSpellAreaForQuestMapBounds(quest_id,true);
13083 if(saBounds.first != saBounds.second)
13085 uint32 zone, area;
13086 GetZoneAndAreaId(zone,area);
13088 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
13089 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
13090 if( !HasAura(itr->second->spellId,0) )
13091 CastSpell(this,itr->second->spellId,true);
13094 UpdateForQuestWorldObjects();
13097 void Player::CompleteQuest( uint32 quest_id )
13099 if( quest_id )
13101 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
13103 uint16 log_slot = FindQuestSlot( quest_id );
13104 if( log_slot < MAX_QUEST_LOG_SIZE)
13105 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
13107 if(Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id))
13109 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
13110 RewardQuest(qInfo,0,this,false);
13111 else
13112 SendQuestComplete( quest_id );
13117 void Player::IncompleteQuest( uint32 quest_id )
13119 if( quest_id )
13121 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
13123 uint16 log_slot = FindQuestSlot( quest_id );
13124 if( log_slot < MAX_QUEST_LOG_SIZE)
13125 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
13129 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
13131 //this THING should be here to protect code from quest, which cast on player far teleport as a reward
13132 //should work fine, cause far teleport will be executed in Player::Update()
13133 SetCanDelayTeleport(true);
13135 uint32 quest_id = pQuest->GetQuestId();
13137 for (int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i )
13139 if (pQuest->ReqItemId[i])
13140 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
13143 RemoveTimedQuest(quest_id);
13145 if (BattleGround* bg = GetBattleGround())
13146 if (bg->GetTypeID() == BATTLEGROUND_AV)
13147 ((BattleGroundAV*)bg)->HandleQuestComplete(pQuest->GetQuestId(), this);
13149 if (pQuest->GetRewChoiceItemsCount() > 0)
13151 if (uint32 itemId = pQuest->RewChoiceItemId[reward])
13153 ItemPosCountVec dest;
13154 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK)
13156 Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
13157 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
13162 if (pQuest->GetRewItemsCount() > 0)
13164 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
13166 if (uint32 itemId = pQuest->RewItemId[i])
13168 ItemPosCountVec dest;
13169 if (CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, itemId, pQuest->RewItemCount[i] ) == EQUIP_ERR_OK)
13171 Item* item = StoreNewItem( dest, itemId, true, Item::GenerateItemRandomPropertyId(itemId));
13172 SendNewItem(item, pQuest->RewItemCount[i], true, false);
13178 RewardReputation( pQuest );
13180 uint16 log_slot = FindQuestSlot( quest_id );
13181 if (log_slot < MAX_QUEST_LOG_SIZE)
13182 SetQuestSlot(log_slot,0);
13184 QuestStatusData& q_status = mQuestStatus[quest_id];
13186 // Not give XP in case already completed once repeatable quest
13187 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
13189 if (getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
13190 GiveXP( XP , NULL );
13191 else
13193 uint32 money = uint32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY));
13194 ModifyMoney( money );
13195 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, money);
13198 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
13199 if (pQuest->GetRewOrReqMoney())
13201 ModifyMoney( pQuest->GetRewOrReqMoney() );
13203 if (pQuest->GetRewOrReqMoney() > 0)
13204 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD, pQuest->GetRewOrReqMoney());
13207 // honor reward
13208 if (pQuest->GetRewHonorableKills())
13209 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13211 // title reward
13212 if (pQuest->GetCharTitleId())
13214 if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
13215 SetTitle(titleEntry);
13218 if (pQuest->GetBonusTalents())
13220 m_questRewardTalentCount+=pQuest->GetBonusTalents();
13221 InitTalentForLevel();
13224 // Send reward mail
13225 if (uint32 mail_template_id = pQuest->GetRewMailTemplateId())
13226 MailDraft(mail_template_id).SendMailTo(this, questGiver, MAIL_CHECK_MASK_NONE, pQuest->GetRewMailDelaySecs());
13228 if (pQuest->IsDaily())
13230 SetDailyQuestStatus(quest_id);
13231 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
13234 if (!pQuest->IsRepeatable())
13235 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
13236 else
13237 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
13239 q_status.m_rewarded = true;
13240 if (q_status.uState != QUEST_NEW)
13241 q_status.uState = QUEST_CHANGED;
13243 if (announce)
13244 SendQuestReward( pQuest, XP, questGiver );
13246 // cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data)
13247 if (pQuest->GetRewSpellCast() > 0)
13248 CastSpell( this, pQuest->GetRewSpellCast(), true);
13249 else if ( pQuest->GetRewSpell() > 0)
13250 CastSpell( this, pQuest->GetRewSpell(), true);
13252 if (pQuest->GetZoneOrSort() > 0)
13253 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE, pQuest->GetZoneOrSort());
13254 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
13255 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST, pQuest->GetQuestId());
13257 uint32 zone = 0;
13258 uint32 area = 0;
13260 // remove auras from spells with quest reward state limitations
13261 SpellAreaForQuestMapBounds saEndBounds = sSpellMgr.GetSpellAreaForQuestEndMapBounds(quest_id);
13262 if(saEndBounds.first != saEndBounds.second)
13264 GetZoneAndAreaId(zone,area);
13266 for(SpellAreaForAreaMap::const_iterator itr = saEndBounds.first; itr != saEndBounds.second; ++itr)
13267 if(!itr->second->IsFitToRequirements(this,zone,area))
13268 RemoveAurasDueToSpell(itr->second->spellId);
13271 // Some spells applied at quest reward
13272 SpellAreaForQuestMapBounds saBounds = sSpellMgr.GetSpellAreaForQuestMapBounds(quest_id,false);
13273 if(saBounds.first != saBounds.second)
13275 if(!zone || !area)
13276 GetZoneAndAreaId(zone,area);
13278 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
13279 if(itr->second->autocast && itr->second->IsFitToRequirements(this,zone,area))
13280 if( !HasAura(itr->second->spellId,0) )
13281 CastSpell(this,itr->second->spellId,true);
13284 //lets remove flag for delayed teleports
13285 SetCanDelayTeleport(false);
13288 void Player::FailQuest(uint32 questId)
13290 if (Quest const* pQuest = sObjectMgr.GetQuestTemplate(questId))
13292 SetQuestStatus(questId, QUEST_STATUS_FAILED);
13294 uint16 log_slot = FindQuestSlot(questId);
13296 if (log_slot < MAX_QUEST_LOG_SIZE)
13298 SetQuestSlotTimer(log_slot, 1);
13299 SetQuestSlotState(log_slot, QUEST_STATE_FAIL);
13302 if (pQuest->HasFlag(QUEST_MANGOS_FLAGS_TIMED))
13304 QuestStatusData& q_status = mQuestStatus[questId];
13306 RemoveTimedQuest(questId);
13307 q_status.m_timer = 0;
13309 SendQuestTimerFailed(questId);
13311 else
13312 SendQuestFailed(questId);
13316 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
13318 int32 zoneOrSort = qInfo->GetZoneOrSort();
13319 int32 skillOrClass = qInfo->GetSkillOrClass();
13321 // skip zone zoneOrSort and 0 case skillOrClass
13322 if( zoneOrSort >= 0 && skillOrClass == 0 )
13323 return true;
13325 int32 questSort = -zoneOrSort;
13326 uint8 reqSortClass = ClassByQuestSort(questSort);
13328 // check class sort cases in zoneOrSort
13329 if( reqSortClass != 0 && getClass() != reqSortClass)
13331 if( msg )
13332 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13333 return false;
13336 // check class
13337 if( skillOrClass < 0 )
13339 uint8 reqClass = -int32(skillOrClass);
13340 if(getClass() != reqClass)
13342 if( msg )
13343 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13344 return false;
13347 // check skill
13348 else if( skillOrClass > 0 )
13350 uint32 reqSkill = skillOrClass;
13351 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
13353 if( msg )
13354 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13355 return false;
13359 return true;
13362 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
13364 if( getLevel() < qInfo->GetMinLevel() )
13366 if( msg )
13367 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13368 return false;
13370 return true;
13373 bool Player::SatisfyQuestLog( bool msg )
13375 // exist free slot
13376 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
13377 return true;
13379 if( msg )
13381 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
13382 GetSession()->SendPacket( &data );
13383 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
13385 return false;
13388 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
13390 // No previous quest (might be first quest in a series)
13391 if( qInfo->prevQuests.empty())
13392 return true;
13394 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
13396 uint32 prevId = abs(*iter);
13398 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
13399 Quest const* qPrevInfo = sObjectMgr.GetQuestTemplate(prevId);
13401 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
13403 // If any of the positive previous quests completed, return true
13404 if( *iter > 0 && i_prevstatus->second.m_rewarded )
13406 // skip one-from-all exclusive group
13407 if(qPrevInfo->GetExclusiveGroup() >= 0)
13408 return true;
13410 // each-from-all exclusive group ( < 0)
13411 // can be start if only all quests in prev quest exclusive group completed and rewarded
13412 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = sObjectMgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13413 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13415 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13417 for(; iter2 != end; ++iter2)
13419 uint32 exclude_Id = iter2->second;
13421 // skip checked quest id, only state of other quests in group is interesting
13422 if(exclude_Id == prevId)
13423 continue;
13425 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
13427 // alternative quest from group also must be completed and rewarded(reported)
13428 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
13430 if( msg )
13431 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13432 return false;
13435 return true;
13437 // If any of the negative previous quests active, return true
13438 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13439 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
13441 // skip one-from-all exclusive group
13442 if(qPrevInfo->GetExclusiveGroup() >= 0)
13443 return true;
13445 // each-from-all exclusive group ( < 0)
13446 // can be start if only all quests in prev quest exclusive group active
13447 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2 = sObjectMgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
13448 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
13450 assert(iter2!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
13452 for(; iter2 != end; ++iter2)
13454 uint32 exclude_Id = iter2->second;
13456 // skip checked quest id, only state of other quests in group is interesting
13457 if(exclude_Id == prevId)
13458 continue;
13460 QuestStatusMap::const_iterator i_exstatus = mQuestStatus.find( exclude_Id );
13462 // alternative quest from group also must be active
13463 if( i_exstatus == mQuestStatus.end() ||
13464 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
13465 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
13467 if( msg )
13468 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13469 return false;
13472 return true;
13477 // Has only positive prev. quests in non-rewarded state
13478 // and negative prev. quests in non-active state
13479 if( msg )
13480 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13482 return false;
13485 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
13487 uint32 reqraces = qInfo->GetRequiredRaces();
13488 if ( reqraces == 0 )
13489 return true;
13490 if( (reqraces & getRaceMask()) == 0 )
13492 if( msg )
13493 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
13494 return false;
13496 return true;
13499 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
13501 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
13502 if(fIdMin && GetReputationMgr().GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
13504 if( msg )
13505 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13506 return false;
13509 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
13510 if(fIdMax && GetReputationMgr().GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
13512 if( msg )
13513 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13514 return false;
13517 return true;
13520 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
13522 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
13523 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
13525 if( msg )
13526 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
13527 return false;
13529 return true;
13532 bool Player::SatisfyQuestTimed(Quest const* qInfo, bool msg)
13534 if (!m_timedquests.empty() && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED))
13536 if (msg)
13537 SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED);
13539 return false;
13541 return true;
13544 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
13546 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13547 if(qInfo->GetExclusiveGroup() <= 0)
13548 return true;
13550 ObjectMgr::ExclusiveQuestGroups::const_iterator iter = sObjectMgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
13551 ObjectMgr::ExclusiveQuestGroups::const_iterator end = sObjectMgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
13553 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
13555 for(; iter != end; ++iter)
13557 uint32 exclude_Id = iter->second;
13559 // skip checked quest id, only state of other quests in group is interesting
13560 if(exclude_Id == qInfo->GetQuestId())
13561 continue;
13563 // not allow have daily quest if daily quest from exclusive group already recently completed
13564 Quest const* Nquest = sObjectMgr.GetQuestTemplate(exclude_Id);
13565 if( !SatisfyQuestDay(Nquest, false) )
13567 if( msg )
13568 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13569 return false;
13572 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
13574 // alternative quest already started or completed
13575 if( i_exstatus != mQuestStatus.end()
13576 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
13578 if( msg )
13579 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13580 return false;
13583 return true;
13586 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
13588 if(!qInfo->GetNextQuestInChain())
13589 return true;
13591 // next quest in chain already started or completed
13592 QuestStatusMap::const_iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
13593 if( itr != mQuestStatus.end()
13594 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
13596 if( msg )
13597 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13598 return false;
13601 // check for all quests further up the chain
13602 // only necessary if there are quest chains with more than one quest that can be skipped
13603 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13604 return true;
13607 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
13609 // No previous quest in chain
13610 if( qInfo->prevChainQuests.empty())
13611 return true;
13613 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
13615 uint32 prevId = *iter;
13617 QuestStatusMap::const_iterator i_prevstatus = mQuestStatus.find( prevId );
13619 if( i_prevstatus != mQuestStatus.end() )
13621 // If any of the previous quests in chain active, return false
13622 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
13623 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
13625 if( msg )
13626 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
13627 return false;
13631 // check for all quests further down the chain
13632 // only necessary if there are quest chains with more than one quest that can be skipped
13633 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13634 // return false;
13637 // No previous quest in chain active
13638 return true;
13641 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
13643 if(!qInfo->IsDaily())
13644 return true;
13646 bool have_slot = false;
13647 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
13649 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
13650 if(qInfo->GetQuestId()==id)
13651 return false;
13653 if(!id)
13654 have_slot = true;
13657 if(!have_slot)
13659 if( msg )
13660 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
13661 return false;
13664 return true;
13667 bool Player::GiveQuestSourceItem( Quest const *pQuest )
13669 uint32 srcitem = pQuest->GetSrcItemId();
13670 if( srcitem > 0 )
13672 uint32 count = pQuest->GetSrcItemCount();
13673 if( count <= 0 )
13674 count = 1;
13676 ItemPosCountVec dest;
13677 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
13678 if( msg == EQUIP_ERR_OK )
13680 Item * item = StoreNewItem(dest, srcitem, true);
13681 SendNewItem(item, count, true, false);
13682 return true;
13684 // player already have max amount required item, just report success
13685 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
13686 return true;
13687 else
13688 SendEquipError( msg, NULL, NULL );
13689 return false;
13692 return true;
13695 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
13697 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13698 if( qInfo )
13700 uint32 srcitem = qInfo->GetSrcItemId();
13701 if( srcitem > 0 )
13703 uint32 count = qInfo->GetSrcItemCount();
13704 if( count <= 0 )
13705 count = 1;
13707 // exist one case when destroy source quest item not possible:
13708 // non un-equippable item (equipped non-empty bag, for example)
13709 uint8 res = CanUnequipItems(srcitem,count);
13710 if(res != EQUIP_ERR_OK)
13712 if(msg)
13713 SendEquipError( res, NULL, NULL );
13714 return false;
13717 DestroyItemCount(srcitem, count, true, true);
13720 return true;
13723 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
13725 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13726 if( qInfo )
13728 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13729 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13730 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
13731 && !qInfo->IsRepeatable() )
13732 return itr->second.m_rewarded;
13734 return false;
13736 return false;
13739 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13741 if( quest_id )
13743 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13744 if( itr != mQuestStatus.end() )
13745 return itr->second.m_status;
13747 return QUEST_STATUS_NONE;
13750 bool Player::CanShareQuest(uint32 quest_id) const
13752 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13753 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13755 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13756 if( itr != mQuestStatus.end() )
13757 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13759 return false;
13762 void Player::SetQuestStatus(uint32 quest_id, QuestStatus status)
13764 if (Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id))
13766 QuestStatusData& q_status = mQuestStatus[quest_id];
13768 q_status.m_status = status;
13770 if (q_status.uState != QUEST_NEW)
13771 q_status.uState = QUEST_CHANGED;
13774 UpdateForQuestWorldObjects();
13777 // not used in MaNGOS, but used in scripting code
13778 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13780 Quest const* qInfo = sObjectMgr.GetQuestTemplate(quest_id);
13781 if( !qInfo )
13782 return 0;
13784 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13785 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13786 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13788 return 0;
13791 void Player::AdjustQuestReqItemCount( Quest const* pQuest, QuestStatusData& questStatusData )
13793 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13795 for(int i = 0; i < QUEST_ITEM_OBJECTIVES_COUNT; ++i)
13797 uint32 reqitemcount = pQuest->ReqItemCount[i];
13798 if( reqitemcount != 0 )
13800 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i], true);
13802 questStatusData.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13803 if (questStatusData.uState != QUEST_NEW) questStatusData.uState = QUEST_CHANGED;
13809 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13811 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13812 if ( GetQuestSlotQuestId(i) == quest_id )
13813 return i;
13815 return MAX_QUEST_LOG_SIZE;
13818 void Player::AreaExploredOrEventHappens( uint32 questId )
13820 if( questId )
13822 uint16 log_slot = FindQuestSlot( questId );
13823 if( log_slot < MAX_QUEST_LOG_SIZE)
13825 QuestStatusData& q_status = mQuestStatus[questId];
13827 if(!q_status.m_explored)
13829 q_status.m_explored = true;
13830 if (q_status.uState != QUEST_NEW)
13831 q_status.uState = QUEST_CHANGED;
13834 if( CanCompleteQuest( questId ) )
13835 CompleteQuest( questId );
13839 //not used in mangosd, function for external script library
13840 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13842 if( Group *pGroup = GetGroup() )
13844 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13846 Player *pGroupGuy = itr->getSource();
13848 // for any leave or dead (with not released body) group member at appropriate distance
13849 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13850 pGroupGuy->AreaExploredOrEventHappens(questId);
13853 else
13854 AreaExploredOrEventHappens(questId);
13857 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13859 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13861 uint32 questid = GetQuestSlotQuestId(i);
13862 if ( questid == 0 )
13863 continue;
13865 QuestStatusData& q_status = mQuestStatus[questid];
13867 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13868 continue;
13870 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
13871 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13872 continue;
13874 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
13876 uint32 reqitem = qInfo->ReqItemId[j];
13877 if ( reqitem == entry )
13879 uint32 reqitemcount = qInfo->ReqItemCount[j];
13880 uint32 curitemcount = q_status.m_itemcount[j];
13881 if ( curitemcount < reqitemcount )
13883 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13884 q_status.m_itemcount[j] += additemcount;
13885 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13887 SendQuestUpdateAddItem( qInfo, j, additemcount );
13889 if ( CanCompleteQuest( questid ) )
13890 CompleteQuest( questid );
13891 return;
13895 UpdateForQuestWorldObjects();
13898 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13900 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13902 uint32 questid = GetQuestSlotQuestId(i);
13903 if(!questid)
13904 continue;
13905 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
13906 if ( !qInfo )
13907 continue;
13908 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13909 continue;
13911 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
13913 uint32 reqitem = qInfo->ReqItemId[j];
13914 if ( reqitem == entry )
13916 QuestStatusData& q_status = mQuestStatus[questid];
13918 uint32 reqitemcount = qInfo->ReqItemCount[j];
13919 uint32 curitemcount;
13920 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13921 curitemcount = q_status.m_itemcount[j];
13922 else
13923 curitemcount = GetItemCount(entry, true);
13924 if ( curitemcount < reqitemcount + count )
13926 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13927 q_status.m_itemcount[j] = curitemcount - remitemcount;
13928 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13930 IncompleteQuest( questid );
13932 return;
13936 UpdateForQuestWorldObjects();
13939 void Player::KilledMonster( CreatureInfo const* cInfo, uint64 guid )
13941 if(cInfo->Entry)
13942 KilledMonsterCredit(cInfo->Entry,guid);
13944 for(int i = 0; i < MAX_KILL_CREDIT; ++i)
13945 if(cInfo->KillCredit[i])
13946 KilledMonsterCredit(cInfo->KillCredit[i],guid);
13949 void Player::KilledMonsterCredit( uint32 entry, uint64 guid )
13951 uint32 addkillcount = 1;
13952 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13953 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
13955 uint32 questid = GetQuestSlotQuestId(i);
13956 if(!questid)
13957 continue;
13959 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
13960 if( !qInfo )
13961 continue;
13962 // just if !ingroup || !noraidgroup || raidgroup
13963 QuestStatusData& q_status = mQuestStatus[questid];
13964 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13966 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13968 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
13970 // skip GO activate objective or none
13971 if(qInfo->ReqCreatureOrGOId[j] <=0)
13972 continue;
13974 // skip Cast at creature objective
13975 if(qInfo->ReqSpell[j] !=0 )
13976 continue;
13978 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13980 if ( reqkill == entry )
13982 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13983 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13984 if ( curkillcount < reqkillcount )
13986 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13987 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13989 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13991 if ( CanCompleteQuest( questid ) )
13992 CompleteQuest( questid );
13994 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13995 continue;
14003 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
14005 bool isCreature = IS_CREATURE_GUID(guid);
14007 uint32 addCastCount = 1;
14008 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i)
14010 uint32 questid = GetQuestSlotQuestId(i);
14011 if(!questid)
14012 continue;
14014 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14015 if ( !qInfo )
14016 continue;
14018 QuestStatusData& q_status = mQuestStatus[questid];
14020 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14022 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
14024 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
14026 // skip kill creature objective (0) or wrong spell casts
14027 if(qInfo->ReqSpell[j] != spell_id )
14028 continue;
14030 uint32 reqTarget = 0;
14032 if(isCreature)
14034 // creature activate objectives
14035 if(qInfo->ReqCreatureOrGOId[j] > 0)
14036 // checked at quest_template loading
14037 reqTarget = qInfo->ReqCreatureOrGOId[j];
14039 else
14041 // GO activate objective
14042 if(qInfo->ReqCreatureOrGOId[j] < 0)
14043 // checked at quest_template loading
14044 reqTarget = - qInfo->ReqCreatureOrGOId[j];
14047 // other not this creature/GO related objectives
14048 if( reqTarget != entry )
14049 continue;
14051 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
14052 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
14053 if ( curCastCount < reqCastCount )
14055 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
14056 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14058 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
14061 if ( CanCompleteQuest( questid ) )
14062 CompleteQuest( questid );
14064 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14065 break;
14072 void Player::TalkedToCreature( uint32 entry, uint64 guid )
14074 uint32 addTalkCount = 1;
14075 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14077 uint32 questid = GetQuestSlotQuestId(i);
14078 if(!questid)
14079 continue;
14081 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14082 if ( !qInfo )
14083 continue;
14085 QuestStatusData& q_status = mQuestStatus[questid];
14087 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14089 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
14091 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
14093 // skip spell casts and Gameobject objectives
14094 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
14095 continue;
14097 uint32 reqTarget = 0;
14099 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
14100 // checked at quest_template loading
14101 reqTarget = qInfo->ReqCreatureOrGOId[j];
14102 else
14103 continue;
14105 if ( reqTarget == entry )
14107 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
14108 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
14109 if ( curTalkCount < reqTalkCount )
14111 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
14112 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
14114 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
14116 if ( CanCompleteQuest( questid ) )
14117 CompleteQuest( questid );
14119 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14120 continue;
14128 void Player::MoneyChanged( uint32 count )
14130 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14132 uint32 questid = GetQuestSlotQuestId(i);
14133 if (!questid)
14134 continue;
14136 Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid);
14137 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
14139 QuestStatusData& q_status = mQuestStatus[questid];
14141 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14143 if(int32(count) >= -qInfo->GetRewOrReqMoney())
14145 if ( CanCompleteQuest( questid ) )
14146 CompleteQuest( questid );
14149 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
14151 if(int32(count) < -qInfo->GetRewOrReqMoney())
14152 IncompleteQuest( questid );
14158 void Player::ReputationChanged(FactionEntry const* factionEntry )
14160 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14162 if(uint32 questid = GetQuestSlotQuestId(i))
14164 if(Quest const* qInfo = sObjectMgr.GetQuestTemplate(questid))
14166 if(qInfo->GetRepObjectiveFaction() == factionEntry->ID )
14168 QuestStatusData& q_status = mQuestStatus[questid];
14169 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
14171 if(GetReputationMgr().GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
14172 if ( CanCompleteQuest( questid ) )
14173 CompleteQuest( questid );
14175 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
14177 if(GetReputationMgr().GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
14178 IncompleteQuest( questid );
14186 bool Player::HasQuestForItem( uint32 itemid ) const
14188 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
14190 uint32 questid = GetQuestSlotQuestId(i);
14191 if ( questid == 0 )
14192 continue;
14194 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
14195 if(qs_itr == mQuestStatus.end())
14196 continue;
14198 QuestStatusData const& q_status = qs_itr->second;
14200 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
14202 Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid);
14203 if(!qinfo)
14204 continue;
14206 // hide quest if player is in raid-group and quest is no raid quest
14207 if (GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID
14208 && !InBattleGround())
14209 continue;
14211 // There should be no mixed ReqItem/ReqSource drop
14212 // This part for ReqItem drop
14213 for (int j = 0; j < QUEST_ITEM_OBJECTIVES_COUNT; ++j)
14215 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
14216 return true;
14218 // This part - for ReqSource
14219 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; ++j)
14221 // examined item is a source item
14222 if (qinfo->ReqSourceId[j] == itemid)
14224 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype(itemid);
14226 // 'unique' item
14227 if (pProto->MaxCount && GetItemCount(itemid,true) < pProto->MaxCount)
14228 return true;
14230 // allows custom amount drop when not 0
14231 if (qinfo->ReqSourceCount[j])
14233 if (GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
14234 return true;
14235 } else if (GetItemCount(itemid,true) < pProto->Stackable)
14236 return true;
14241 return false;
14244 void Player::SendQuestComplete( uint32 quest_id )
14246 if( quest_id )
14248 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
14249 data << uint32(quest_id);
14250 GetSession()->SendPacket( &data );
14251 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
14255 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
14257 uint32 questid = pQuest->GetQuestId();
14258 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
14259 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
14260 data << uint32(questid);
14262 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
14264 data << uint32(XP);
14265 data << uint32(pQuest->GetRewOrReqMoney());
14267 else
14269 data << uint32(0);
14270 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
14273 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
14274 data << uint32(pQuest->GetBonusTalents()); // bonus talents
14275 data << uint32(0);
14276 GetSession()->SendPacket( &data );
14278 if (pQuest->GetQuestCompleteScript() != 0)
14279 GetMap()->ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
14282 void Player::SendQuestFailed( uint32 quest_id )
14284 if( quest_id )
14286 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
14287 data << uint32(quest_id);
14288 data << uint32(0); // failed reason (4 for inventory is full)
14289 GetSession()->SendPacket( &data );
14290 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
14294 void Player::SendQuestTimerFailed( uint32 quest_id )
14296 if( quest_id )
14298 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
14299 data << uint32(quest_id);
14300 GetSession()->SendPacket( &data );
14301 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
14305 void Player::SendCanTakeQuestResponse( uint32 msg )
14307 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
14308 data << uint32(msg);
14309 GetSession()->SendPacket( &data );
14310 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
14313 void Player::SendQuestConfirmAccept(const Quest* pQuest, Player* pReceiver)
14315 if (pReceiver)
14317 std::string strTitle = pQuest->GetTitle();
14319 int loc_idx = pReceiver->GetSession()->GetSessionDbLocaleIndex();
14321 if (loc_idx >= 0)
14323 if (const QuestLocale* pLocale = sObjectMgr.GetQuestLocale(pQuest->GetQuestId()))
14325 if (pLocale->Title.size() > loc_idx && !pLocale->Title[loc_idx].empty())
14326 strTitle = pLocale->Title[loc_idx];
14330 WorldPacket data(SMSG_QUEST_CONFIRM_ACCEPT, (4 + strTitle.size() + 8));
14331 data << uint32(pQuest->GetQuestId());
14332 data << strTitle;
14333 data << uint64(GetGUID());
14334 pReceiver->GetSession()->SendPacket(&data);
14336 sLog.outDebug("WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT");
14340 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
14342 if( pPlayer )
14344 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
14345 data << uint64(pPlayer->GetGUID());
14346 data << uint8(msg); // valid values: 0-8
14347 GetSession()->SendPacket( &data );
14348 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
14352 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
14354 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
14355 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
14356 //data << pQuest->ReqItemId[item_idx];
14357 //data << count;
14358 GetSession()->SendPacket( &data );
14361 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
14363 assert(old_count + add_count < 65536 && "mob/GO count store in 16 bits 2^16 = 65536 (0..65536)");
14365 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
14366 if (entry < 0)
14367 // client expected gameobject template id in form (id|0x80000000)
14368 entry = (-entry) | 0x80000000;
14370 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
14371 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
14372 data << uint32(pQuest->GetQuestId());
14373 data << uint32(entry);
14374 data << uint32(old_count + add_count);
14375 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
14376 data << uint64(guid);
14377 GetSession()->SendPacket(&data);
14379 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
14380 if( log_slot < MAX_QUEST_LOG_SIZE)
14381 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
14384 /*********************************************************/
14385 /*** LOAD SYSTEM ***/
14386 /*********************************************************/
14388 void Player::_LoadDeclinedNames(QueryResult* result)
14390 if(!result)
14391 return;
14393 if(m_declinedname)
14394 delete m_declinedname;
14396 m_declinedname = new DeclinedName;
14397 Field *fields = result->Fetch();
14398 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
14399 m_declinedname->name[i] = fields[i].GetCppString();
14401 delete result;
14404 void Player::_LoadArenaTeamInfo(QueryResult *result)
14406 // arenateamid, played_week, played_season, personal_rating
14407 memset((void*)&m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1], 0, sizeof(uint32) * MAX_ARENA_SLOT * ARENA_TEAM_END);
14408 if (!result)
14409 return;
14413 Field *fields = result->Fetch();
14415 uint32 arenateamid = fields[0].GetUInt32();
14416 uint32 played_week = fields[1].GetUInt32();
14417 uint32 played_season = fields[2].GetUInt32();
14418 uint32 wons_season = fields[3].GetUInt32();
14419 uint32 personal_rating = fields[4].GetUInt32();
14421 ArenaTeam* aTeam = sObjectMgr.GetArenaTeamById(arenateamid);
14422 if(!aTeam)
14424 sLog.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u", arenateamid);
14425 continue;
14427 uint8 arenaSlot = aTeam->GetSlot();
14429 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_ID] = arenateamid; // TeamID
14430 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_TYPE] = aTeam->GetType(); // team type
14431 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_MEMBER] = ((aTeam->GetCaptain() == GetGUID()) ? (uint32)0 : (uint32)1); // Captain 0, member 1
14432 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_GAMES_WEEK] = played_week; // Played Week
14433 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_GAMES_SEASON] = played_season; // Played Season
14434 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_WINS_SEASON] = wons_season; // wins season
14435 m_uint32Values[PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arenaSlot * ARENA_TEAM_END) + ARENA_TEAM_PERSONAL_RATING] = personal_rating; // Personal Rating
14437 } while (result->NextRow());
14438 delete result;
14441 void Player::_LoadEquipmentSets(QueryResult *result)
14443 // SetPQuery(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS, "SELECT setguid, setindex, name, iconname, item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18 FROM character_equipmentsets WHERE guid = '%u' ORDER BY setindex", GUID_LOPART(m_guid));
14444 if (!result)
14445 return;
14447 uint32 count = 0;
14450 Field *fields = result->Fetch();
14452 EquipmentSet eqSet;
14454 eqSet.Guid = fields[0].GetUInt64();
14455 uint32 index = fields[1].GetUInt32();
14456 eqSet.Name = fields[2].GetCppString();
14457 eqSet.IconName = fields[3].GetCppString();
14458 eqSet.state = EQUIPMENT_SET_UNCHANGED;
14460 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
14461 eqSet.Items[i] = fields[4+i].GetUInt32();
14463 m_EquipmentSets[index] = eqSet;
14465 ++count;
14467 if(count >= MAX_EQUIPMENT_SET_INDEX) // client limit
14468 break;
14469 } while (result->NextRow());
14470 delete result;
14473 void Player::_LoadBGData(QueryResult* result)
14475 if (!result)
14476 return;
14478 // Expecting only one row
14479 Field *fields = result->Fetch();
14480 /* bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
14481 m_bgData.bgInstanceID = fields[0].GetUInt32();
14482 m_bgData.bgTeam = fields[1].GetUInt32();
14483 m_bgData.joinPos = WorldLocation(fields[6].GetUInt32(), // Map
14484 fields[2].GetFloat(), // X
14485 fields[3].GetFloat(), // Y
14486 fields[4].GetFloat(), // Z
14487 fields[5].GetFloat()); // Orientation
14488 m_bgData.taxiPath[0] = fields[7].GetUInt32();
14489 m_bgData.taxiPath[1] = fields[8].GetUInt32();
14490 m_bgData.mountSpell = fields[9].GetUInt32();
14492 delete result;
14495 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
14497 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
14498 if(!result)
14499 return false;
14501 Field *fields = result->Fetch();
14503 x = fields[0].GetFloat();
14504 y = fields[1].GetFloat();
14505 z = fields[2].GetFloat();
14506 o = fields[3].GetFloat();
14507 mapid = fields[4].GetUInt32();
14508 in_flight = !fields[5].GetCppString().empty();
14510 delete result;
14511 return true;
14514 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
14516 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
14517 if( !result )
14518 return false;
14520 Field *fields = result->Fetch();
14522 data = StrSplit(fields[0].GetCppString(), " ");
14524 delete result;
14526 return true;
14529 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
14531 if(index >= data.size())
14532 return 0;
14534 return (uint32)atoi(data[index].c_str());
14537 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
14539 float result;
14540 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
14541 memcpy(&result, &temp, sizeof(result));
14543 return result;
14546 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
14548 Tokens data;
14549 if(!LoadValuesArrayFromDB(data,guid))
14550 return 0;
14552 return GetUInt32ValueFromArray(data,index);
14555 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
14557 float result;
14558 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
14559 memcpy(&result, &temp, sizeof(result));
14561 return result;
14564 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
14566 // 0 1 2 3 4 5 6 7 8 9 10 11 12
14567 //SELECT guid, account, data, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags,"
14568 // 13 14 15 16 17 18 19 20 21 22 23 24 25
14569 //"position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost,"
14570 // 26 27 28 29 30 31 32 33 34 35 36 37 38 39
14571 //"resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty,"
14572 // 40 41 42 43 44 45 46 47 48 49 50
14573 //"arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk,"
14574 // 51 52 53 54 55 56 57 58
14575 //"health, power1, power2, power3, power4, power5, power6, power7 FROM characters WHERE guid = '%u'", GUID_LOPART(m_guid));
14576 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
14578 if(!result)
14580 sLog.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid);
14581 return false;
14584 Field *fields = result->Fetch();
14586 uint32 dbAccountId = fields[1].GetUInt32();
14588 // check if the character's account in the db and the logged in account match.
14589 // player should be able to load/delete character only with correct account!
14590 if( dbAccountId != GetSession()->GetAccountId() )
14592 sLog.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
14593 delete result;
14594 return false;
14597 Object::_Create( guid, 0, HIGHGUID_PLAYER );
14599 m_name = fields[3].GetCppString();
14601 // check name limitations
14602 if (ObjectMgr::CheckPlayerName(m_name) != CHAR_NAME_SUCCESS ||
14603 (GetSession()->GetSecurity() == SEC_PLAYER && sObjectMgr.IsReservedName(m_name)))
14605 delete result;
14606 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
14607 return false;
14610 if(!LoadValues( fields[2].GetString()))
14612 sLog.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid));
14613 delete result;
14614 return false;
14617 // overwrite possible wrong/corrupted guid
14618 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
14620 // overwrite some data fields
14621 uint32 bytes0 = GetUInt32Value(UNIT_FIELD_BYTES_0) & 0xFF000000;
14622 bytes0 |= fields[4].GetUInt8(); // race
14623 bytes0 |= fields[5].GetUInt8() << 8; // class
14624 bytes0 |= fields[6].GetUInt8() << 16; // gender
14625 SetUInt32Value(UNIT_FIELD_BYTES_0, bytes0);
14627 SetUInt32Value(UNIT_FIELD_LEVEL, fields[7].GetUInt8());
14628 SetUInt32Value(PLAYER_XP, fields[8].GetUInt32());
14630 uint32 money = fields[9].GetUInt32();
14631 if(money > MAX_MONEY_AMOUNT)
14632 money = MAX_MONEY_AMOUNT;
14633 SetMoney(money);
14635 SetUInt32Value(PLAYER_BYTES, fields[10].GetUInt32());
14636 SetUInt32Value(PLAYER_BYTES_2, fields[11].GetUInt32());
14637 SetUInt32Value(PLAYER_BYTES_3, (fields[50].GetUInt16() & 0xFFFE) | fields[6].GetUInt8());
14638 SetUInt32Value(PLAYER_FLAGS, fields[12].GetUInt32());
14639 SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, fields[49].GetInt32());
14641 SetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES, fields[48].GetUInt64());
14644 InitDisplayIds();
14646 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14647 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
14649 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2), 0 );
14650 SetVisibleItemSlot(slot, NULL);
14652 if (m_items[slot])
14654 delete m_items[slot];
14655 m_items[slot] = NULL;
14659 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
14660 outDebugValues();
14662 //Need to call it to initialize m_team (m_team can be calculated from race)
14663 //Other way is to saves m_team into characters table.
14664 setFactionForRace(getRace());
14665 SetCharm(NULL);
14667 // load home bind and check in same time class/race pair, it used later for restore broken positions
14668 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
14670 delete result;
14671 return false;
14674 InitPrimaryProfessions(); // to max set before any spell loaded
14676 // init saved position, and fix it later if problematic
14677 uint32 transGUID = fields[31].GetUInt32();
14678 Relocate(fields[13].GetFloat(),fields[14].GetFloat(),fields[15].GetFloat(),fields[17].GetFloat());
14679 SetLocationMapId(fields[16].GetUInt32());
14681 uint32 difficulty = fields[39].GetUInt32();
14682 if(difficulty >= MAX_DUNGEON_DIFFICULTY)
14683 difficulty = DUNGEON_DIFFICULTY_NORMAL;
14684 SetDungeonDifficulty(Difficulty(difficulty)); // may be changed in _LoadGroup
14686 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
14688 _LoadArenaTeamInfo(holder->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO));
14690 uint32 arena_currency = fields[40].GetUInt32();
14691 if (arena_currency > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
14692 arena_currency = sWorld.getConfig(CONFIG_MAX_ARENA_POINTS);
14694 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, arena_currency);
14696 // check arena teams integrity
14697 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
14699 uint32 arena_team_id = GetArenaTeamId(arena_slot);
14700 if(!arena_team_id)
14701 continue;
14703 if(ArenaTeam * at = sObjectMgr.GetArenaTeamById(arena_team_id))
14704 if(at->HaveMember(GetGUID()))
14705 continue;
14707 // arena team not exist or not member, cleanup fields
14708 for(int j = 0; j < ARENA_TEAM_END; ++j)
14709 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (arena_slot * ARENA_TEAM_END) + j, 0);
14712 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, fields[41].GetUInt32());
14713 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, fields[42].GetUInt32());
14714 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, fields[43].GetUInt32());
14715 SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, fields[44].GetUInt32());
14716 SetUInt16Value(PLAYER_FIELD_KILLS, 0, fields[45].GetUInt16());
14717 SetUInt16Value(PLAYER_FIELD_KILLS, 1, fields[46].GetUInt16());
14719 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
14721 if(!IsPositionValid())
14723 sLog.outError("Player (guidlow %d) have invalid coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",guid,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
14724 RelocateToHomebind();
14726 transGUID = 0;
14728 m_movementInfo.SetTransportData(0, 0.0f, 0.0f, 0.0f, 0.0f, 0, -1);
14731 _LoadBGData(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBGDATA));
14733 if(m_bgData.bgInstanceID) //saved in BattleGround
14735 BattleGround *currentBg = sBattleGroundMgr.GetBattleGround(m_bgData.bgInstanceID, BATTLEGROUND_TYPE_NONE);
14737 bool player_at_bg = currentBg && currentBg->IsPlayerInBattleGround(GetGUID());
14739 if(player_at_bg && currentBg->GetStatus() != STATUS_WAIT_LEAVE)
14741 BattleGroundQueueTypeId bgQueueTypeId = BattleGroundMgr::BGQueueTypeId(currentBg->GetTypeID(), currentBg->GetArenaType());
14742 AddBattleGroundQueueId(bgQueueTypeId);
14744 m_bgData.bgTypeID = currentBg->GetTypeID();
14746 //join player to battleground group
14747 currentBg->EventPlayerLoggedIn(this, GetGUID());
14748 currentBg->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), m_bgData.bgTeam);
14750 SetInviteForBattleGroundQueueType(bgQueueTypeId,currentBg->GetInstanceID());
14752 else
14754 // leave bg
14755 if (player_at_bg)
14756 currentBg->RemovePlayerAtLeave(GetGUID(), false, true);
14758 // move to bg enter point
14759 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14760 SetLocationMapId(_loc.mapid);
14761 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14763 // We are not in BG anymore
14764 m_bgData.bgInstanceID = 0;
14767 else
14769 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14770 // if server restart after player save in BG or area
14771 // player can have current coordinates in to BG/Arena map, fix this
14772 if(!mapEntry || mapEntry->IsBattleGroundOrArena())
14774 const WorldLocation& _loc = GetBattleGroundEntryPoint();
14775 SetLocationMapId(_loc.mapid);
14776 Relocate(_loc.coord_x, _loc.coord_y, _loc.coord_z, _loc.orientation);
14780 if (transGUID != 0)
14782 m_movementInfo.SetTransportData(transGUID, fields[27].GetFloat(), fields[28].GetFloat(), fields[29].GetFloat(), fields[30].GetFloat(), 0, -1);
14784 if( !MaNGOS::IsValidMapCoord(
14785 GetPositionX() + m_movementInfo.GetTransportPos()->x, GetPositionY() + m_movementInfo.GetTransportPos()->y,
14786 GetPositionZ() + m_movementInfo.GetTransportPos()->z, GetOrientation() + m_movementInfo.GetTransportPos()->o) ||
14787 // transport size limited
14788 m_movementInfo.GetTransportPos()->x > 50 || m_movementInfo.GetTransportPos()->y > 50 || m_movementInfo.GetTransportPos()->z > 50 )
14790 sLog.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14791 guid, GetPositionX() + m_movementInfo.GetTransportPos()->x, GetPositionY() + m_movementInfo.GetTransportPos()->y,
14792 GetPositionZ() + m_movementInfo.GetTransportPos()->z, GetOrientation() + m_movementInfo.GetTransportPos()->o);
14794 RelocateToHomebind();
14796 m_movementInfo.SetTransportData(0, 0.0f, 0.0f, 0.0f, 0.0f, 0, -1);
14798 transGUID = 0;
14802 if (transGUID != 0)
14804 for (MapManager::TransportSet::const_iterator iter = sMapMgr.m_Transports.begin(); iter != sMapMgr.m_Transports.end(); ++iter)
14806 if( (*iter)->GetGUIDLow() == transGUID)
14808 MapEntry const* transMapEntry = sMapStore.LookupEntry((*iter)->GetMapId());
14809 // client without expansion support
14810 if(GetSession()->Expansion() < transMapEntry->Expansion())
14812 sLog.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter)->GetMapId());
14813 break;
14816 m_transport = *iter;
14817 m_transport->AddPassenger(this);
14818 SetLocationMapId(m_transport->GetMapId());
14819 break;
14823 if(!m_transport)
14825 sLog.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14826 guid,transGUID);
14828 RelocateToHomebind();
14830 m_movementInfo.SetTransportData(0, 0.0f, 0.0f, 0.0f, 0.0f, 0, -1);
14832 transGUID = 0;
14835 else // not transport case
14837 MapEntry const* mapEntry = sMapStore.LookupEntry(GetMapId());
14838 // client without expansion support
14839 if(GetSession()->Expansion() < mapEntry->Expansion())
14841 sLog.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14842 RelocateToHomebind();
14846 // NOW player must have valid map
14847 // load the player's map here if it's not already loaded
14848 SetMap(sMapMgr.CreateMap(GetMapId(), this));
14850 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14851 if(GetInstanceId() && !sInstanceSaveMgr.GetInstanceSave(GetInstanceId()))
14853 AreaTrigger const* at = sObjectMgr.GetMapEntranceTrigger(GetMapId());
14854 if(at)
14855 Relocate(at->target_X, at->target_Y, at->target_Z, at->target_Orientation);
14856 else
14857 sLog.outError("Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no area-trigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), GetMapId());
14860 SaveRecallPosition();
14862 time_t now = time(NULL);
14863 time_t logoutTime = time_t(fields[23].GetUInt64());
14865 // since last logout (in seconds)
14866 uint64 time_diff = uint64(now - logoutTime);
14868 // set value, including drunk invisibility detection
14869 // calculate sobering. after 15 minutes logged out, the player will be sober again
14870 float soberFactor;
14871 if(time_diff > 15*MINUTE)
14872 soberFactor = 0;
14873 else
14874 soberFactor = 1-time_diff/(15.0f*MINUTE);
14875 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
14876 SetDrunkValue(newDrunkenValue);
14878 m_rest_bonus = fields[22].GetFloat();
14879 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14880 float bubble0 = 0.031;
14881 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14882 float bubble1 = 0.125;
14884 if(time_diff > 0)
14886 float bubble = fields[24].GetUInt32() > 0
14887 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
14888 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
14890 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
14893 m_cinematic = fields[19].GetUInt32();
14894 m_Played_time[PLAYED_TIME_TOTAL]= fields[20].GetUInt32();
14895 m_Played_time[PLAYED_TIME_LEVEL]= fields[21].GetUInt32();
14897 m_resetTalentsCost = fields[25].GetUInt32();
14898 m_resetTalentsTime = time_t(fields[26].GetUInt64());
14900 // reserve some flags
14901 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
14903 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
14904 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
14906 m_taxi.LoadTaxiMask( fields[18].GetString() ); // must be before InitTaxiNodesForLevel
14908 uint32 extraflags = fields[32].GetUInt32();
14910 m_stableSlots = fields[33].GetUInt32();
14911 if(m_stableSlots > MAX_PET_STABLES)
14913 sLog.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES,uint32(m_stableSlots));
14914 m_stableSlots = MAX_PET_STABLES;
14917 m_atLoginFlags = fields[34].GetUInt32();
14919 // Honor system
14920 // Update Honor kills data
14921 m_lastHonorUpdateTime = logoutTime;
14922 UpdateHonorFields();
14924 m_deathExpireTime = (time_t)fields[37].GetUInt64();
14925 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
14926 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
14928 std::string taxi_nodes = fields[38].GetCppString();
14930 // clear channel spell data (if saved at channel spell casting)
14931 SetChannelObjectGUID(0);
14932 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
14934 // clear charm/summon related fields
14935 SetCharm(NULL);
14936 SetPet(NULL);
14937 SetTargetGUID(0);
14938 SetChannelObjectGUID(0);
14939 SetCharmerGUID(0);
14940 SetOwnerGUID(0);
14941 SetCreatorGUID(0);
14943 // reset some aura modifiers before aura apply
14944 SetFarSightGUID(0);
14945 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14946 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14948 // cleanup aura list explicitly before skill load wher some spells can be applied
14949 RemoveAllAuras();
14951 // make sure the unit is considered out of combat for proper loading
14952 ClearInCombat();
14954 // make sure the unit is considered not in duel for proper loading
14955 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14956 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14958 // reset stats before loading any modifiers
14959 InitStatsForLevel();
14960 InitGlyphsForLevel();
14961 InitTaxiNodesForLevel();
14962 InitRunes();
14964 // load skills after InitStatsForLevel because it triggering aura apply also
14965 _LoadSkills(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSKILLS));
14967 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14969 // Mail
14970 _LoadMail();
14972 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14973 _LoadGlyphAuras();
14975 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14976 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14977 m_deathState = DEAD;
14979 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14981 // after spell load, learn rewarded spell if need also
14982 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14983 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14985 // after spell and quest load
14986 InitTalentForLevel();
14987 learnDefaultSpells();
14989 // must be before inventory (some items required reputation check)
14990 m_reputationMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14992 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14994 // update items with duration and realtime
14995 UpdateItemDuration(time_diff, true);
14997 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14999 // unread mails and next delivery time, actual mails not loaded
15000 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
15002 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
15004 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
15005 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
15006 uint32 curTitle = fields[10].GetUInt32();
15007 if (curTitle && !HasTitle(curTitle))
15008 curTitle = 0;
15010 SetUInt32Value(PLAYER_CHOSEN_TITLE, curTitle);
15012 // Not finish taxi flight path
15013 if(m_bgData.HasTaxiPath())
15015 m_taxi.ClearTaxiDestinations();
15016 for (int i = 0; i < 2; ++i)
15017 m_taxi.AddTaxiDestination(m_bgData.taxiPath[i]);
15019 else if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes,GetTeam()))
15021 // problems with taxi path loading
15022 TaxiNodesEntry const* nodeEntry = NULL;
15023 if(uint32 node_id = m_taxi.GetTaxiSource())
15024 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
15026 if(!nodeEntry) // don't know taxi start node, to homebind
15028 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
15029 RelocateToHomebind();
15031 else // have start node, to it
15033 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
15034 SetLocationMapId(nodeEntry->map_id);
15035 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
15038 //we can be relocated from taxi and still have an outdated Map pointer!
15039 //so we need to get a new Map pointer!
15040 SetMap(sMapMgr.CreateMap(GetMapId(), this));
15041 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
15043 m_taxi.ClearTaxiDestinations();
15046 if(uint32 node_id = m_taxi.GetTaxiSource())
15048 // save source node as recall coord to prevent recall and fall from sky
15049 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
15050 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
15051 m_recallMap = nodeEntry->map_id;
15052 m_recallX = nodeEntry->x;
15053 m_recallY = nodeEntry->y;
15054 m_recallZ = nodeEntry->z;
15056 // flight will started later
15059 // has to be called after last Relocate() in Player::LoadFromDB
15060 SetFallInformation(0, GetPositionZ());
15062 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
15064 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
15065 // Do now before stats re-calculation cleanup for ghost state unexpected auras
15066 if(!isAlive())
15067 RemoveAllAurasOnDeath();
15069 //apply all stat bonuses from items and auras
15070 SetCanModifyStats(true);
15071 UpdateAllStats();
15073 // restore remembered power/health values (but not more max values)
15074 uint32 savedhealth = fields[51].GetUInt32();
15075 SetHealth(savedhealth > GetMaxHealth() ? GetMaxHealth() : savedhealth);
15076 for(uint32 i = 0; i < MAX_POWERS; ++i)
15078 uint32 savedpower = fields[52+i].GetUInt32();
15079 SetPower(Powers(i),savedpower > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedpower);
15082 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
15083 outDebugValues();
15085 // all fields read
15086 delete result;
15088 // GM state
15089 if(GetSession()->GetSecurity() > SEC_PLAYER)
15091 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
15093 default:
15094 case 0: break; // disable
15095 case 1: SetGameMaster(true); break; // enable
15096 case 2: // save state
15097 if(extraflags & PLAYER_EXTRA_GM_ON)
15098 SetGameMaster(true);
15099 break;
15102 switch(sWorld.getConfig(CONFIG_GM_VISIBLE_STATE))
15104 default:
15105 case 0: SetGMVisible(false); break; // invisible
15106 case 1: break; // visible
15107 case 2: // save state
15108 if(extraflags & PLAYER_EXTRA_GM_INVISIBLE)
15109 SetGMVisible(false);
15110 break;
15113 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
15115 default:
15116 case 0: break; // disable
15117 case 1: SetAcceptTicket(true); break; // enable
15118 case 2: // save state
15119 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
15120 SetAcceptTicket(true);
15121 break;
15124 switch(sWorld.getConfig(CONFIG_GM_CHAT))
15126 default:
15127 case 0: break; // disable
15128 case 1: SetGMChat(true); break; // enable
15129 case 2: // save state
15130 if(extraflags & PLAYER_EXTRA_GM_CHAT)
15131 SetGMChat(true);
15132 break;
15135 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
15137 default:
15138 case 0: break; // disable
15139 case 1: SetAcceptWhispers(true); break; // enable
15140 case 2: // save state
15141 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
15142 SetAcceptWhispers(true);
15143 break;
15147 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
15149 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
15150 m_achievementMgr.CheckAllAchievementCriteria();
15152 _LoadEquipmentSets(holder->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS));
15154 return true;
15157 bool Player::isAllowedToLoot(Creature* creature)
15159 if(Player* recipient = creature->GetLootRecipient())
15161 if (recipient == this)
15162 return true;
15163 if( Group* otherGroup = recipient->GetGroup())
15165 Group* thisGroup = GetGroup();
15166 if(!thisGroup)
15167 return false;
15168 return thisGroup == otherGroup;
15170 return false;
15172 else
15173 // prevent other players from looting if the recipient got disconnected
15174 return !creature->hasLootRecipient();
15177 void Player::_LoadActions(QueryResult *result)
15179 m_actionButtons.clear();
15181 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
15183 if(result)
15187 Field *fields = result->Fetch();
15189 uint8 button = fields[0].GetUInt8();
15190 uint32 action = fields[1].GetUInt32();
15191 uint8 type = fields[2].GetUInt8();
15193 if(ActionButton* ab = addActionButton(button, action, type))
15194 ab->uState = ACTIONBUTTON_UNCHANGED;
15195 else
15197 sLog.outError( " ...at loading, and will deleted in DB also");
15199 // Will deleted in DB at next save (it can create data until save but marked as deleted)
15200 m_actionButtons[button].uState = ACTIONBUTTON_DELETED;
15203 while( result->NextRow() );
15205 delete result;
15209 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
15211 //RemoveAllAuras(); -- some spells casted before aura load, for example in LoadSkills, aura list explcitly cleaned early
15213 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15215 if(result)
15219 Field *fields = result->Fetch();
15220 uint64 caster_guid = fields[0].GetUInt64();
15221 uint32 spellid = fields[1].GetUInt32();
15222 uint32 effindex = fields[2].GetUInt32();
15223 uint32 stackcount = fields[3].GetUInt32();
15224 int32 damage = (int32)fields[4].GetUInt32();
15225 int32 maxduration = (int32)fields[5].GetUInt32();
15226 int32 remaintime = (int32)fields[6].GetUInt32();
15227 int32 remaincharges = (int32)fields[7].GetUInt32();
15229 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
15230 if(!spellproto)
15232 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
15233 continue;
15236 if(effindex >= 3)
15238 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
15239 continue;
15242 // negative effects should continue counting down after logout
15243 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
15245 if (remaintime/IN_MILISECONDS <= int32(timediff))
15246 continue;
15248 remaintime -= timediff*IN_MILISECONDS;
15251 // prevent wrong values of remaincharges
15252 if(spellproto->procCharges)
15254 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
15255 remaincharges = spellproto->procCharges;
15257 else
15258 remaincharges = 0;
15261 for(uint32 i=0; i<stackcount; ++i)
15263 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
15264 if(!damage)
15265 damage = aura->GetModifier()->m_amount;
15267 // reset stolen single target auras
15268 if (caster_guid != GetGUID() && aura->IsSingleTarget())
15269 aura->SetIsSingleTarget(false);
15271 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
15272 AddAura(aura);
15273 sLog.outDetail("Added aura spellid %u, effect %u", spellproto->Id, effindex);
15276 while( result->NextRow() );
15278 delete result;
15281 if(getClass() == CLASS_WARRIOR && !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT))
15282 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
15285 void Player::_LoadGlyphAuras()
15287 for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
15289 if (uint32 glyph = GetGlyph(i))
15291 if (GlyphPropertiesEntry const *gp = sGlyphPropertiesStore.LookupEntry(glyph))
15293 if (GlyphSlotEntry const *gs = sGlyphSlotStore.LookupEntry(GetGlyphSlot(i)))
15295 if(gp->TypeFlags == gs->TypeFlags)
15297 CastSpell(this, gp->SpellId, true);
15298 continue;
15300 else
15301 sLog.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name.c_str(), gp->TypeFlags, gs->TypeFlags);
15303 else
15304 sLog.outError("Player %s has not existing glyph slot entry %u on index %u", m_name.c_str(), GetGlyphSlot(i), i);
15306 else
15307 sLog.outError("Player %s has not existing glyph entry %u on index %u", m_name.c_str(), glyph, i);
15309 // On any error remove glyph
15310 SetGlyph(i, 0);
15315 void Player::LoadCorpse()
15317 if( isAlive() )
15319 sObjectAccessor.ConvertCorpseForPlayer(GetGUID());
15321 else
15323 if(Corpse *corpse = GetCorpse())
15325 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
15327 else
15329 //Prevent Dead Player login without corpse
15330 ResurrectPlayer(0.5f);
15335 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
15337 //QueryResult *result = CharacterDatabase.PQuery("SELECT data,bag,slot,item,item_template FROM character_inventory JOIN item_instance ON character_inventory.item = item_instance.guid WHERE character_inventory.guid = '%u' ORDER BY bag,slot", GetGUIDLow());
15338 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
15339 //NOTE: the "order by `bag`" is important because it makes sure
15340 //the bagMap is filled before items in the bags are loaded
15341 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
15342 //expected to be equipped before offhand items (TODO: fixme)
15344 uint32 zone = GetZoneId();
15346 if (result)
15348 std::list<Item*> problematicItems;
15350 // prevent items from being added to the queue when stored
15351 m_itemUpdateQueueBlocked = true;
15354 Field *fields = result->Fetch();
15355 uint32 bag_guid = fields[1].GetUInt32();
15356 uint8 slot = fields[2].GetUInt8();
15357 uint32 item_guid = fields[3].GetUInt32();
15358 uint32 item_id = fields[4].GetUInt32();
15360 ItemPrototype const * proto = ObjectMgr::GetItemPrototype(item_id);
15362 if(!proto)
15364 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15365 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
15366 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
15367 continue;
15370 Item *item = NewItemOrBag(proto);
15372 if(!item->LoadFromDB(item_guid, GetGUID(), result))
15374 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
15375 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15376 item->FSetState(ITEM_REMOVED);
15377 item->SaveToDB(); // it also deletes item object !
15378 continue;
15381 // not allow have in alive state item limited to another map/zone
15382 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
15384 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15385 item->FSetState(ITEM_REMOVED);
15386 item->SaveToDB(); // it also deletes item object !
15387 continue;
15390 // "Conjured items disappear if you are logged out for more than 15 minutes"
15391 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
15393 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15394 item->FSetState(ITEM_REMOVED);
15395 item->SaveToDB(); // it also deletes item object !
15396 continue;
15399 bool success = true;
15401 // the item/bag is not in a bag
15402 if (!bag_guid)
15404 item->SetContainer( NULL );
15405 item->SetSlot(slot);
15407 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
15409 ItemPosCountVec dest;
15410 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
15411 item = StoreItem(dest, item, true);
15412 else
15413 success = false;
15415 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
15417 uint16 dest;
15418 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
15419 QuickEquipItem(dest, item);
15420 else
15421 success = false;
15423 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
15425 ItemPosCountVec dest;
15426 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
15427 item = BankItem(dest, item, true);
15428 else
15429 success = false;
15432 if(success)
15434 // store bags that may contain items in them
15435 if(item->IsBag() && IsBagPos(item->GetPos()))
15436 bagMap[item_guid] = (Bag*)item;
15439 // the item/bag in a bag
15440 else
15442 item->SetSlot(NULL_SLOT);
15443 // the item is in a bag, find the bag
15444 std::map<uint64, Bag*>::const_iterator itr = bagMap.find(bag_guid);
15445 if(itr != bagMap.end() && slot < itr->second->GetBagSize())
15447 ItemPosCountVec dest;
15448 if( CanStoreItem( itr->second->GetSlot(), slot, dest, item, false ) == EQUIP_ERR_OK )
15449 item = StoreItem(dest, item, true);
15450 else
15451 success = false;
15453 else
15454 success = false;
15457 // item's state may have changed after stored
15458 if (success)
15459 item->SetState(ITEM_UNCHANGED, this);
15460 else
15462 sLog.outError("Player::_LoadInventory: Player %s has item (GUID: %u Entry: %u) can't be loaded to inventory (Bag GUID: %u Slot: %u) by some reason, will send by mail.", GetName(),item_guid, item_id, bag_guid, slot);
15463 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
15464 problematicItems.push_back(item);
15466 } while (result->NextRow());
15468 delete result;
15469 m_itemUpdateQueueBlocked = false;
15471 // send by mail problematic items
15472 while(!problematicItems.empty())
15474 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
15476 // fill mail
15477 MailDraft draft(subject);
15479 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
15481 Item* item = problematicItems.front();
15482 problematicItems.pop_front();
15484 draft.AddItem(item);
15487 draft.SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM));
15490 //if(isAlive())
15491 _ApplyAllItemMods();
15494 // load mailed item which should receive current player
15495 void Player::_LoadMailedItems(Mail *mail)
15497 // data needs to be at first place for Item::LoadFromDB
15498 QueryResult* result = CharacterDatabase.PQuery("SELECT data, item_guid, item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail->messageID);
15499 if(!result)
15500 return;
15504 Field *fields = result->Fetch();
15505 uint32 item_guid_low = fields[1].GetUInt32();
15506 uint32 item_template = fields[2].GetUInt32();
15508 mail->AddItem(item_guid_low, item_template);
15510 ItemPrototype const *proto = ObjectMgr::GetItemPrototype(item_template);
15512 if(!proto)
15514 sLog.outError( "Player %u has unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), item_guid_low, item_template,mail->messageID);
15515 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
15516 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
15517 continue;
15520 Item *item = NewItemOrBag(proto);
15522 if(!item->LoadFromDB(item_guid_low, 0, result))
15524 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
15525 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
15526 item->FSetState(ITEM_REMOVED);
15527 item->SaveToDB(); // it also deletes item object !
15528 continue;
15531 AddMItem(item);
15532 } while (result->NextRow());
15534 delete result;
15537 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
15539 //set a count of unread mails
15540 //QueryResult *resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" UI64FMTD "'", GUID_LOPART(playerGuid),(uint64)cTime);
15541 if (resultUnread)
15543 Field *fieldMail = resultUnread->Fetch();
15544 unReadMails = fieldMail[0].GetUInt8();
15545 delete resultUnread;
15548 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
15549 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
15550 if (resultDelivery)
15552 Field *fieldMail = resultDelivery->Fetch();
15553 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
15554 delete resultDelivery;
15558 void Player::_LoadMail()
15560 m_mail.clear();
15561 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
15562 QueryResult *result = CharacterDatabase.PQuery("SELECT id,messageType,sender,receiver,subject,itemTextId,has_items,expire_time,deliver_time,money,cod,checked,stationery,mailTemplateId FROM mail WHERE receiver = '%u' ORDER BY id DESC",GetGUIDLow());
15563 if(result)
15567 Field *fields = result->Fetch();
15568 Mail *m = new Mail;
15569 m->messageID = fields[0].GetUInt32();
15570 m->messageType = fields[1].GetUInt8();
15571 m->sender = fields[2].GetUInt32();
15572 m->receiver = fields[3].GetUInt32();
15573 m->subject = fields[4].GetCppString();
15574 m->itemTextId = fields[5].GetUInt32();
15575 bool has_items = fields[6].GetBool();
15576 m->expire_time = (time_t)fields[7].GetUInt64();
15577 m->deliver_time = (time_t)fields[8].GetUInt64();
15578 m->money = fields[9].GetUInt32();
15579 m->COD = fields[10].GetUInt32();
15580 m->checked = fields[11].GetUInt32();
15581 m->stationery = fields[12].GetUInt8();
15582 m->mailTemplateId = fields[13].GetInt16();
15584 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
15586 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
15587 m->mailTemplateId = 0;
15590 m->state = MAIL_STATE_UNCHANGED;
15592 if (has_items)
15593 _LoadMailedItems(m);
15595 m_mail.push_back(m);
15596 } while( result->NextRow() );
15597 delete result;
15601 void Player::LoadPet()
15603 //fixme: the pet should still be loaded if the player is not in world
15604 // just not added to the map
15605 if(IsInWorld())
15607 Pet *pet = new Pet;
15608 if(!pet->LoadPetFromDB(this,0,0,true))
15609 delete pet;
15613 void Player::_LoadQuestStatus(QueryResult *result)
15615 mQuestStatus.clear();
15617 uint32 slot = 0;
15619 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15620 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest, status, rewarded, explored, timer, mobcount1, mobcount2, mobcount3, mobcount4, itemcount1, itemcount2, itemcount3, itemcount4 FROM character_queststatus WHERE guid = '%u'", GetGUIDLow());
15622 if(result)
15626 Field *fields = result->Fetch();
15628 uint32 quest_id = fields[0].GetUInt32();
15629 // used to be new, no delete?
15630 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
15631 if( pQuest )
15633 // find or create
15634 QuestStatusData& questStatusData = mQuestStatus[quest_id];
15636 uint32 qstatus = fields[1].GetUInt32();
15637 if(qstatus < MAX_QUEST_STATUS)
15638 questStatusData.m_status = QuestStatus(qstatus);
15639 else
15641 questStatusData.m_status = QUEST_STATUS_NONE;
15642 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
15645 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
15646 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
15648 time_t quest_time = time_t(fields[4].GetUInt64());
15650 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
15652 AddTimedQuest( quest_id );
15654 if (quest_time <= sWorld.GetGameTime())
15655 questStatusData.m_timer = 1;
15656 else
15657 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * IN_MILISECONDS;
15659 else
15660 quest_time = 0;
15662 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
15663 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
15664 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
15665 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
15666 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
15667 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
15668 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
15669 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
15671 questStatusData.uState = QUEST_UNCHANGED;
15673 // add to quest log
15674 if (slot < MAX_QUEST_LOG_SIZE &&
15675 ((questStatusData.m_status == QUEST_STATUS_INCOMPLETE ||
15676 questStatusData.m_status == QUEST_STATUS_COMPLETE ||
15677 questStatusData.m_status == QUEST_STATUS_FAILED) &&
15678 (!questStatusData.m_rewarded || pQuest->IsRepeatable())))
15680 SetQuestSlot(slot, quest_id, quest_time);
15682 if (questStatusData.m_status == QUEST_STATUS_COMPLETE)
15683 SetQuestSlotState(slot, QUEST_STATE_COMPLETE);
15685 if (questStatusData.m_status == QUEST_STATUS_FAILED)
15686 SetQuestSlotState(slot, QUEST_STATE_FAIL);
15688 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
15689 if(questStatusData.m_creatureOrGOcount[idx])
15690 SetQuestSlotCounter(slot, idx, questStatusData.m_creatureOrGOcount[idx]);
15692 ++slot;
15695 if(questStatusData.m_rewarded)
15697 // learn rewarded spell if unknown
15698 learnQuestRewardedSpells(pQuest);
15700 // set rewarded title if any
15701 if(pQuest->GetCharTitleId())
15703 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
15704 SetTitle(titleEntry);
15707 if(pQuest->GetBonusTalents())
15708 m_questRewardTalentCount += pQuest->GetBonusTalents();
15711 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
15714 while( result->NextRow() );
15716 delete result;
15719 // clear quest log tail
15720 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
15721 SetQuestSlot(i, 0);
15724 void Player::_LoadDailyQuestStatus(QueryResult *result)
15726 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15727 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
15729 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15731 if(result)
15733 uint32 quest_daily_idx = 0;
15737 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
15739 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15740 break;
15743 Field *fields = result->Fetch();
15745 uint32 quest_id = fields[0].GetUInt32();
15747 // save _any_ from daily quest times (it must be after last reset anyway)
15748 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
15750 Quest const* pQuest = sObjectMgr.GetQuestTemplate(quest_id);
15751 if( !pQuest )
15752 continue;
15754 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
15755 ++quest_daily_idx;
15757 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
15759 while( result->NextRow() );
15761 delete result;
15764 m_DailyQuestChanged = false;
15767 void Player::_LoadSpells(QueryResult *result)
15769 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15771 if(result)
15775 Field *fields = result->Fetch();
15777 addSpell(fields[0].GetUInt32(), fields[1].GetBool(), false, false, fields[2].GetBool());
15779 while( result->NextRow() );
15781 delete result;
15785 void Player::_LoadGroup(QueryResult *result)
15787 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15788 if (result)
15790 uint32 leaderGuidLow = (*result)[0].GetUInt32();
15791 delete result;
15793 if (Group* group = sObjectMgr.GetGroupByLeaderLowGUID(leaderGuidLow))
15795 uint8 subgroup = group->GetMemberGroup(GetGUID());
15796 SetGroup(group, subgroup);
15797 if (getLevel() >= LEVELREQUIREMENT_HEROIC)
15799 // the group leader may change the instance difficulty while the player is offline
15800 SetDungeonDifficulty(group->GetDungeonDifficulty());
15801 SetRaidDifficulty(group->GetRaidDifficulty());
15807 void Player::_LoadBoundInstances(QueryResult *result)
15809 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
15810 m_boundInstances[i].clear();
15812 Group *group = GetGroup();
15814 //QueryResult *result = CharacterDatabase.PQuery("SELECT id, permanent, map, difficulty, resettime FROM character_instance LEFT JOIN instance ON instance = id WHERE guid = '%u'", GUID_LOPART(m_guid));
15815 if(result)
15819 Field *fields = result->Fetch();
15820 bool perm = fields[1].GetBool();
15821 uint32 mapId = fields[2].GetUInt32();
15822 uint32 instanceId = fields[0].GetUInt32();
15823 uint8 difficulty = fields[3].GetUInt8();
15825 time_t resetTime = (time_t)fields[4].GetUInt64();
15826 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15827 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15828 // and in that case it is not used
15830 MapEntry const* mapEntry = sMapStore.LookupEntry(mapId);
15831 if(!mapEntry || !mapEntry->IsDungeon())
15833 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId);
15834 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15835 continue;
15838 if(difficulty >= MAX_DIFFICULTY)
15840 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
15841 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15842 continue;
15845 MapDifficulty const* mapDiff = GetMapDifficultyData(mapId,Difficulty(difficulty));
15846 if(!mapDiff)
15848 sLog.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty, mapId);
15849 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15850 continue;
15853 if(!perm && group)
15855 sLog.outError("_LoadBoundInstances: player %s(%d) is in group %d but has a non-permanent character bind to map %d,%d,%d", GetName(), GetGUIDLow(), GUID_LOPART(group->GetLeaderGUID()), mapId, instanceId, difficulty);
15856 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
15857 continue;
15860 // since non permanent binds are always solo bind, they can always be reset
15861 InstanceSave *save = sInstanceSaveMgr.AddInstanceSave(mapId, instanceId, Difficulty(difficulty), resetTime, !perm, true);
15862 if(save) BindToInstance(save, perm, true);
15863 } while(result->NextRow());
15864 delete result;
15868 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, Difficulty difficulty)
15870 // some instances only have one difficulty
15871 MapDifficulty const* mapDiff = GetMapDifficultyData(mapid,difficulty);
15872 if(!mapDiff)
15873 return NULL;
15875 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15876 if(itr != m_boundInstances[difficulty].end())
15877 return &itr->second;
15878 else
15879 return NULL;
15882 void Player::UnbindInstance(uint32 mapid, Difficulty difficulty, bool unload)
15884 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
15885 UnbindInstance(itr, difficulty, unload);
15888 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, Difficulty difficulty, bool unload)
15890 if(itr != m_boundInstances[difficulty].end())
15892 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
15893 itr->second.save->RemovePlayer(this); // save can become invalid
15894 m_boundInstances[difficulty].erase(itr++);
15898 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
15900 if(save)
15902 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
15903 if(bind.save)
15905 // update the save when the group kills a boss
15906 if(permanent != bind.perm || save != bind.save)
15907 if(!load) CharacterDatabase.PExecute("UPDATE character_instance SET instance = '%u', permanent = '%u' WHERE guid = '%u' AND instance = '%u'", save->GetInstanceId(), permanent, GetGUIDLow(), bind.save->GetInstanceId());
15909 else
15910 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
15912 if(bind.save != save)
15914 if(bind.save) bind.save->RemovePlayer(this);
15915 save->AddPlayer(this);
15918 if(permanent) save->SetCanReset(false);
15920 bind.save = save;
15921 bind.perm = permanent;
15922 if(!load) sLog.outDebug("Player::BindToInstance: %s(%d) is now bound to map %d, instance %d, difficulty %d", GetName(), GetGUIDLow(), save->GetMapId(), save->GetInstanceId(), save->GetDifficulty());
15923 return &bind;
15925 else
15926 return NULL;
15929 void Player::SendRaidInfo()
15931 uint32 counter = 0;
15933 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
15935 size_t p_counter = data.wpos();
15936 data << uint32(counter); // placeholder
15938 time_t now = time(NULL);
15940 for(int i = 0; i < MAX_DIFFICULTY; ++i)
15942 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15944 if(itr->second.perm)
15946 InstanceSave *save = itr->second.save;
15947 data << uint32(save->GetMapId()); // map id
15948 data << uint32(save->GetDifficulty()); // difficulty
15949 data << uint64(save->GetInstanceId()); // instance id
15950 data << uint8(1); // expired = 0
15951 data << uint8(0); // extended = 1
15952 data << uint32(save->GetResetTime() - now); // reset time
15953 ++counter;
15957 data.put<uint32>(p_counter, counter);
15958 GetSession()->SendPacket(&data);
15962 - called on every successful teleportation to a map
15964 void Player::SendSavedInstances()
15966 bool hasBeenSaved = false;
15967 WorldPacket data;
15969 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
15971 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15973 if(itr->second.perm) // only permanent binds are sent
15975 hasBeenSaved = true;
15976 break;
15981 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15982 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15983 data << uint32(hasBeenSaved);
15984 GetSession()->SendPacket(&data);
15986 if(!hasBeenSaved)
15987 return;
15989 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
15991 for (BoundInstancesMap::const_iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15993 if(itr->second.perm)
15995 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15996 data << uint32(itr->second.save->GetMapId());
15997 GetSession()->SendPacket(&data);
16003 /// convert the player's binds to the group
16004 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
16006 bool has_binds = false;
16007 bool has_solo = false;
16009 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
16010 assert(player_guid);
16012 // copy all binds to the group, when changing leader it's assumed the character
16013 // will not have any solo binds
16015 if(player)
16017 for(uint8 i = 0; i < MAX_DIFFICULTY; ++i)
16019 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
16021 has_binds = true;
16022 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
16023 // permanent binds are not removed
16024 if(!itr->second.perm)
16026 // increments itr in call
16027 player->UnbindInstance(itr, Difficulty(i), true);
16028 has_solo = true;
16030 else
16031 ++itr;
16036 // if the player's not online we don't know what binds it has
16037 if(!player || !group || has_binds) CharacterDatabase.PExecute("INSERT INTO group_instance SELECT guid, instance, permanent FROM character_instance WHERE guid = '%u'", GUID_LOPART(player_guid));
16038 // the following should not get executed when changing leaders
16039 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
16042 bool Player::_LoadHomeBind(QueryResult *result)
16044 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass());
16045 if(!info)
16047 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
16048 return false;
16051 bool ok = false;
16052 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
16053 if (result)
16055 Field *fields = result->Fetch();
16056 m_homebindMapId = fields[0].GetUInt32();
16057 m_homebindZoneId = fields[1].GetUInt16();
16058 m_homebindX = fields[2].GetFloat();
16059 m_homebindY = fields[3].GetFloat();
16060 m_homebindZ = fields[4].GetFloat();
16061 delete result;
16063 MapEntry const* bindMapEntry = sMapStore.LookupEntry(m_homebindMapId);
16065 // accept saved data only for valid position (and non instanceable), and accessable
16066 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
16067 !bindMapEntry->Instanceable() && GetSession()->Expansion() >= bindMapEntry->Expansion())
16069 ok = true;
16071 else
16072 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
16075 if(!ok)
16077 m_homebindMapId = info->mapId;
16078 m_homebindZoneId = info->zoneId;
16079 m_homebindX = info->positionX;
16080 m_homebindY = info->positionY;
16081 m_homebindZ = info->positionZ;
16083 CharacterDatabase.PExecute("INSERT INTO character_homebind (guid,map,zone,position_x,position_y,position_z) VALUES ('%u', '%u', '%u', '%f', '%f', '%f')", GetGUIDLow(), m_homebindMapId, (uint32)m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
16086 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
16087 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
16089 return true;
16092 /*********************************************************/
16093 /*** SAVE SYSTEM ***/
16094 /*********************************************************/
16096 void Player::SaveToDB()
16098 // we should assure this: assert((m_nextSave != sWorld.getConfig(CONFIG_INTERVAL_SAVE)));
16099 // delay auto save at any saves (manual, in code, or autosave)
16100 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
16102 //lets allow only players in world to be saved
16103 if(IsBeingTeleportedFar())
16105 ScheduleDelayedOperation(DELAYED_SAVE_PLAYER);
16106 return;
16109 // first save/honor gain after midnight will also update the player's honor fields
16110 UpdateHonorFields();
16112 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
16113 outDebugValues();
16115 CharacterDatabase.BeginTransaction();
16117 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
16119 std::string sql_name = m_name;
16120 CharacterDatabase.escape_string(sql_name);
16122 std::ostringstream ss;
16123 ss << "INSERT INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags,"
16124 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
16125 "taximask, online, cinematic, "
16126 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
16127 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
16128 "death_expire_time, taxi_path, arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, "
16129 "todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk, health, power1, power2, power3, "
16130 "power4, power5, power6, power7) VALUES ("
16131 << GetGUIDLow() << ", "
16132 << GetSession()->GetAccountId() << ", '"
16133 << sql_name << "', "
16134 << (uint32)getRace() << ", "
16135 << (uint32)getClass() << ", "
16136 << (uint32)getGender() << ", "
16137 << getLevel() << ", "
16138 << GetUInt32Value(PLAYER_XP) << ", "
16139 << GetMoney() << ", "
16140 << GetUInt32Value(PLAYER_BYTES) << ", "
16141 << GetUInt32Value(PLAYER_BYTES_2) << ", "
16142 << GetUInt32Value(PLAYER_FLAGS) << ", ";
16144 if(!IsBeingTeleported())
16146 ss << GetMapId() << ", "
16147 << (uint32)GetDungeonDifficulty() << ", "
16148 << finiteAlways(GetPositionX()) << ", "
16149 << finiteAlways(GetPositionY()) << ", "
16150 << finiteAlways(GetPositionZ()) << ", "
16151 << finiteAlways(GetOrientation()) << ", '";
16153 else
16155 ss << GetTeleportDest().mapid << ", "
16156 << (uint32)GetDungeonDifficulty() << ", "
16157 << finiteAlways(GetTeleportDest().coord_x) << ", "
16158 << finiteAlways(GetTeleportDest().coord_y) << ", "
16159 << finiteAlways(GetTeleportDest().coord_z) << ", "
16160 << finiteAlways(GetTeleportDest().orientation) << ", '";
16163 uint16 i;
16164 for( i = 0; i < m_valuesCount; ++i )
16166 ss << GetUInt32Value(i) << " ";
16169 ss << "', ";
16171 ss << m_taxi << ", "; // string with TaxiMaskSize numbers
16173 ss << (IsInWorld() ? 1 : 0) << ", ";
16175 ss << m_cinematic << ", ";
16177 ss << m_Played_time[PLAYED_TIME_TOTAL] << ", ";
16178 ss << m_Played_time[PLAYED_TIME_LEVEL] << ", ";
16180 ss << finiteAlways(m_rest_bonus) << ", ";
16181 ss << (uint64)time(NULL) << ", ";
16182 ss << (HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0) << ", ";
16183 //save, far from tavern/city
16184 //save, but in tavern/city
16185 ss << m_resetTalentsCost << ", ";
16186 ss << (uint64)m_resetTalentsTime << ", ";
16188 ss << finiteAlways(m_movementInfo.GetTransportPos()->x) << ", ";
16189 ss << finiteAlways(m_movementInfo.GetTransportPos()->y) << ", ";
16190 ss << finiteAlways(m_movementInfo.GetTransportPos()->z) << ", ";
16191 ss << finiteAlways(m_movementInfo.GetTransportPos()->o) << ", ";
16192 if (m_transport)
16193 ss << m_transport->GetGUIDLow();
16194 else
16195 ss << "0";
16196 ss << ", ";
16198 ss << m_ExtraFlags << ", ";
16200 ss << uint32(m_stableSlots) << ", "; // to prevent save uint8 as char
16202 ss << uint32(m_atLoginFlags) << ", ";
16204 ss << GetZoneId() << ", ";
16206 ss << (uint64)m_deathExpireTime << ", '";
16208 ss << m_taxi.SaveTaxiDestinationsToString() << "', ";
16210 ss << GetArenaPoints() << ", ";
16212 ss << GetHonorPoints() << ", ";
16214 ss << GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION) << ", ";
16216 ss << GetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION) << ", ";
16218 ss << GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS) << ", ";
16220 ss << GetUInt16Value(PLAYER_FIELD_KILLS, 0) << ", ";
16222 ss << GetUInt16Value(PLAYER_FIELD_KILLS, 1) << ", ";
16224 ss << GetUInt32Value(PLAYER_CHOSEN_TITLE) << ", ";
16226 ss << GetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES) << ", ";
16228 // FIXME: at this moment send to DB as unsigned, including unit32(-1)
16229 ss << GetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX) << ", ";
16231 ss << (uint16)(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE) << ", ";
16233 ss << GetHealth();
16235 for(uint32 i = 0; i < MAX_POWERS; ++i)
16236 ss << "," << GetPower(Powers(i));
16238 ss << ")";
16240 CharacterDatabase.Execute( ss.str().c_str() );
16242 if(m_mailsUpdated) //save mails only when needed
16243 _SaveMail();
16245 _SaveBGData();
16246 _SaveInventory();
16247 _SaveQuestStatus();
16248 _SaveDailyQuestStatus();
16249 _SaveSpells();
16250 _SaveSpellCooldowns();
16251 _SaveActions();
16252 _SaveAuras();
16253 _SaveSkills();
16254 m_achievementMgr.SaveToDB();
16255 m_reputationMgr.SaveToDB();
16256 _SaveEquipmentSets();
16257 GetSession()->SaveTutorialsData(); // changed only while character in game
16259 CharacterDatabase.CommitTransaction();
16261 // save pet (hunter pet level and experience and all type pets health/mana).
16262 if(Pet* pet = GetPet())
16263 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
16266 // fast save function for item/money cheating preventing - save only inventory and money state
16267 void Player::SaveInventoryAndGoldToDB()
16269 _SaveInventory();
16270 SaveGoldToDB();
16273 void Player::SaveGoldToDB()
16275 CharacterDatabase.PExecute("UPDATE characters SET money = '%u' WHERE guid = '%u'", GetMoney(), GetGUIDLow());
16278 void Player::_SaveActions()
16280 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
16282 switch (itr->second.uState)
16284 case ACTIONBUTTON_NEW:
16285 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type) VALUES ('%u', '%u', '%u', '%u')",
16286 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.GetAction(), (uint32)itr->second.GetType() );
16287 itr->second.uState = ACTIONBUTTON_UNCHANGED;
16288 ++itr;
16289 break;
16290 case ACTIONBUTTON_CHANGED:
16291 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u' WHERE guid= '%u' AND button= '%u' ",
16292 (uint32)itr->second.GetAction(), (uint32)itr->second.GetType(), GetGUIDLow(), (uint32)itr->first );
16293 itr->second.uState = ACTIONBUTTON_UNCHANGED;
16294 ++itr;
16295 break;
16296 case ACTIONBUTTON_DELETED:
16297 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
16298 m_actionButtons.erase(itr++);
16299 break;
16300 default:
16301 ++itr;
16302 break;
16307 void Player::_SaveAuras()
16309 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
16311 AuraMap const& auras = GetAuras();
16313 if (auras.empty())
16314 return;
16316 spellEffectPair lastEffectPair = auras.begin()->first;
16317 uint32 stackCounter = 1;
16319 /* copied following sql-code partly from achievementmgr */
16320 bool first_round = true;
16321 std::ostringstream ss;
16322 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
16324 if(itr == auras.end() || lastEffectPair != itr->first)
16326 AuraMap::const_iterator itr2 = itr;
16327 // save previous spellEffectPair to db
16328 itr2--;
16330 //skip all auras from spells that are passive
16331 //do not save single target auras (unless they were cast by the player)
16332 if (!itr2->second->IsPassive() && (itr2->second->GetCasterGUID() == GetGUID() || !itr2->second->IsSingleTarget()))
16334 if (first_round)
16336 ss << "INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges)VALUES ";
16337 first_round = false;
16339 // next new/changed record prefix
16340 else
16341 ss << ", ";
16343 ss << "("<< GetGUIDLow() << "," << itr2->second->GetCasterGUID() << ","
16344 << (uint32)itr2->second->GetId() << "," << (uint32)itr2->second->GetEffIndex() << ","
16345 << stackCounter << "," << itr2->second->GetModifier()->m_amount << ","
16346 <<int(itr2->second->GetAuraMaxDuration()) << "," << int(itr2->second->GetAuraDuration()) << ","
16347 << int(itr2->second->GetAuraCharges()) << ")";
16350 if(itr == auras.end())
16351 break;
16354 if (lastEffectPair == itr->first)
16355 stackCounter++;
16356 else
16358 lastEffectPair = itr->first;
16359 stackCounter = 1;
16363 // if something changed execute
16364 if (!first_round)
16365 CharacterDatabase.Execute( ss.str().c_str() );
16368 void Player::_SaveInventory()
16370 // force items in buyback slots to new state
16371 // and remove those that aren't already
16372 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; ++i)
16374 Item *item = m_items[i];
16375 if (!item || item->GetState() == ITEM_NEW) continue;
16376 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
16377 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
16378 m_items[i]->FSetState(ITEM_NEW);
16381 // update enchantment durations
16382 for(EnchantDurationList::const_iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
16384 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
16387 // if no changes
16388 if (m_itemUpdateQueue.empty()) return;
16390 // do not save if the update queue is corrupt
16391 bool error = false;
16392 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
16394 Item *item = m_itemUpdateQueue[i];
16395 if(!item || item->GetState() == ITEM_REMOVED) continue;
16396 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
16398 if (test == NULL)
16400 sLog.outError("Player(GUID: %u Name: %s)::_SaveInventory - the bag(%d) and slot(%d) values for the item with guid %d are incorrect, the player doesn't have an item at that position!", GetGUIDLow(), GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow());
16401 error = true;
16403 else if (test != item)
16405 sLog.outError("Player(GUID: %u Name: %s)::_SaveInventory - the bag(%d) and slot(%d) values for the item with guid %d are incorrect, the item with guid %d is there instead!", GetGUIDLow(), GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow(), test->GetGUIDLow());
16406 error = true;
16410 if (error)
16412 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
16413 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
16414 return;
16417 for(size_t i = 0; i < m_itemUpdateQueue.size(); ++i)
16419 Item *item = m_itemUpdateQueue[i];
16420 if(!item) continue;
16422 Bag *container = item->GetContainer();
16423 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
16425 switch(item->GetState())
16427 case ITEM_NEW:
16428 CharacterDatabase.PExecute("INSERT INTO character_inventory (guid,bag,slot,item,item_template) VALUES ('%u', '%u', '%u', '%u', '%u')", GetGUIDLow(), bag_guid, item->GetSlot(), item->GetGUIDLow(), item->GetEntry());
16429 break;
16430 case ITEM_CHANGED:
16431 CharacterDatabase.PExecute("UPDATE character_inventory SET guid='%u', bag='%u', slot='%u', item_template='%u' WHERE item='%u'", GetGUIDLow(), bag_guid, item->GetSlot(), item->GetEntry(), item->GetGUIDLow());
16432 break;
16433 case ITEM_REMOVED:
16434 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
16435 break;
16436 case ITEM_UNCHANGED:
16437 break;
16440 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
16442 m_itemUpdateQueue.clear();
16445 void Player::_SaveMail()
16447 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
16449 Mail *m = (*itr);
16450 if (m->state == MAIL_STATE_CHANGED)
16452 CharacterDatabase.PExecute("UPDATE mail SET itemTextId = '%u',has_items = '%u',expire_time = '" UI64FMTD "', deliver_time = '" UI64FMTD "',money = '%u',cod = '%u',checked = '%u' WHERE id = '%u'",
16453 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
16454 if(m->removedItems.size())
16456 for(std::vector<uint32>::const_iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
16457 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
16458 m->removedItems.clear();
16460 m->state = MAIL_STATE_UNCHANGED;
16462 else if (m->state == MAIL_STATE_DELETED)
16464 if (m->HasItems())
16465 for(std::vector<MailItemInfo>::const_iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
16466 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
16467 if (m->itemTextId)
16468 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
16469 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
16470 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
16474 //deallocate deleted mails...
16475 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
16477 if ((*itr)->state == MAIL_STATE_DELETED)
16479 Mail* m = *itr;
16480 m_mail.erase(itr);
16481 delete m;
16482 itr = m_mail.begin();
16484 else
16485 ++itr;
16488 m_mailsUpdated = false;
16491 void Player::_SaveQuestStatus()
16493 // we don't need transactions here.
16494 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
16496 switch (i->second.uState)
16498 case QUEST_NEW :
16499 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
16500 "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
16501 GetGUIDLow(), i->first, i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / IN_MILISECONDS+ sWorld.GetGameTime()), i->second.m_creatureOrGOcount[0], i->second.m_creatureOrGOcount[1], i->second.m_creatureOrGOcount[2], i->second.m_creatureOrGOcount[3], i->second.m_itemcount[0], i->second.m_itemcount[1], i->second.m_itemcount[2], i->second.m_itemcount[3]);
16502 break;
16503 case QUEST_CHANGED :
16504 CharacterDatabase.PExecute("UPDATE character_queststatus SET status = '%u',rewarded = '%u',explored = '%u',timer = '" UI64FMTD "',mobcount1 = '%u',mobcount2 = '%u',mobcount3 = '%u',mobcount4 = '%u',itemcount1 = '%u',itemcount2 = '%u',itemcount3 = '%u',itemcount4 = '%u' WHERE guid = '%u' AND quest = '%u' ",
16505 i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / IN_MILISECONDS + sWorld.GetGameTime()), i->second.m_creatureOrGOcount[0], i->second.m_creatureOrGOcount[1], i->second.m_creatureOrGOcount[2], i->second.m_creatureOrGOcount[3], i->second.m_itemcount[0], i->second.m_itemcount[1], i->second.m_itemcount[2], i->second.m_itemcount[3], GetGUIDLow(), i->first );
16506 break;
16507 case QUEST_UNCHANGED:
16508 break;
16510 i->second.uState = QUEST_UNCHANGED;
16514 void Player::_SaveDailyQuestStatus()
16516 if(!m_DailyQuestChanged)
16517 return;
16519 m_DailyQuestChanged = false;
16521 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
16523 // we don't need transactions here.
16524 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
16525 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
16526 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
16527 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" UI64FMTD "')",
16528 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
16532 void Player::_SaveSkills()
16534 // we don't need transactions here.
16535 for( SkillStatusMap::iterator itr = mSkillStatus.begin(); itr != mSkillStatus.end(); )
16537 if(itr->second.uState == SKILL_UNCHANGED)
16539 ++itr;
16540 continue;
16543 if(itr->second.uState == SKILL_DELETED)
16545 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), itr->first );
16546 mSkillStatus.erase(itr++);
16547 continue;
16550 uint32 valueData = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr->second.pos));
16551 uint16 value = SKILL_VALUE(valueData);
16552 uint16 max = SKILL_MAX(valueData);
16554 switch (itr->second.uState)
16556 case SKILL_NEW:
16557 CharacterDatabase.PExecute("INSERT INTO character_skills (guid, skill, value, max) VALUES ('%u', '%u', '%u', '%u')",
16558 GetGUIDLow(), itr->first, value, max);
16559 break;
16560 case SKILL_CHANGED:
16561 CharacterDatabase.PExecute("UPDATE character_skills SET value = '%u',max = '%u'WHERE guid = '%u' AND skill = '%u' ",
16562 value, max, GetGUIDLow(), itr->first );
16563 break;
16565 itr->second.uState = SKILL_UNCHANGED;
16567 ++itr;
16571 void Player::_SaveSpells()
16573 for (PlayerSpellMap::iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end();)
16575 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
16576 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
16578 // add only changed/new not dependent spells
16579 if (!itr->second->dependent && (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED))
16580 CharacterDatabase.PExecute("INSERT INTO character_spell (guid,spell,active,disabled) VALUES ('%u', '%u', '%u', '%u')", GetGUIDLow(), itr->first, itr->second->active ? 1 : 0,itr->second->disabled ? 1 : 0);
16582 if (itr->second->state == PLAYERSPELL_REMOVED)
16584 delete itr->second;
16585 m_spells.erase(itr++);
16587 else
16589 itr->second->state = PLAYERSPELL_UNCHANGED;
16590 ++itr;
16596 void Player::outDebugValues() const
16598 if(!sLog.IsOutDebug()) // optimize disabled debug output
16599 return;
16601 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
16602 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
16603 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
16604 sLog.outDebug("STAMINA is: \t\t%f",GetStat(STAT_STAMINA));
16605 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
16606 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
16607 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
16608 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
16609 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
16610 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
16611 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
16612 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
16615 /*********************************************************/
16616 /*** FLOOD FILTER SYSTEM ***/
16617 /*********************************************************/
16619 void Player::UpdateSpeakTime()
16621 // ignore chat spam protection for GMs in any mode
16622 if(GetSession()->GetSecurity() > SEC_PLAYER)
16623 return;
16625 time_t current = time (NULL);
16626 if(m_speakTime > current)
16628 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
16629 if(!max_count)
16630 return;
16632 ++m_speakCount;
16633 if(m_speakCount >= max_count)
16635 // prevent overwrite mute time, if message send just before mutes set, for example.
16636 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
16637 if(GetSession()->m_muteTime < new_mute)
16638 GetSession()->m_muteTime = new_mute;
16640 m_speakCount = 0;
16643 else
16644 m_speakCount = 0;
16646 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
16649 bool Player::CanSpeak() const
16651 return GetSession()->m_muteTime <= time (NULL);
16654 /*********************************************************/
16655 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
16656 /*********************************************************/
16658 void Player::SendAttackSwingNotInRange()
16660 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
16661 GetSession()->SendPacket( &data );
16664 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
16666 std::ostringstream ss;
16667 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
16668 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
16669 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
16670 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16671 sLog.outDebug("%s", ss.str().c_str());
16672 CharacterDatabase.Execute(ss.str().c_str());
16675 void Player::SaveDataFieldToDB()
16677 std::ostringstream ss;
16678 ss<<"UPDATE characters SET data='";
16680 for(uint16 i = 0; i < m_valuesCount; ++i )
16682 ss << GetUInt32Value(i) << " ";
16684 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16686 CharacterDatabase.Execute(ss.str().c_str());
16689 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
16691 std::ostringstream ss2;
16692 ss2<<"UPDATE characters SET data='";
16693 int i=0;
16694 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
16696 ss2<<tokens[i]<<" ";
16698 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
16700 return CharacterDatabase.Execute(ss2.str().c_str());
16703 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
16705 char buf[11];
16706 snprintf(buf,11,"%u",value);
16708 if(index >= tokens.size())
16709 return;
16711 tokens[index] = buf;
16714 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
16716 Tokens tokens;
16717 if(!LoadValuesArrayFromDB(tokens,guid))
16718 return;
16720 if(index >= tokens.size())
16721 return;
16723 char buf[11];
16724 snprintf(buf,11,"%u",value);
16725 tokens[index] = buf;
16727 SaveValuesArrayInDB(tokens,guid);
16730 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
16732 uint32 temp;
16733 memcpy(&temp, &value, sizeof(value));
16734 Player::SetUInt32ValueInDB(index, temp, guid);
16737 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
16739 // 0
16740 QueryResult* result = CharacterDatabase.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", GUID_LOPART(guid));
16741 if(!result)
16742 return;
16744 Field* fields = result->Fetch();
16746 uint32 player_bytes2 = fields[0].GetUInt32();
16747 player_bytes2 &= ~0xFF;
16748 player_bytes2 |= facialHair;
16750 CharacterDatabase.PExecute("UPDATE characters SET gender = '%u', playerBytes = '%u', playerBytes2 = '%u' WHERE guid = '%u'", gender, skin | (face << 8) | (hairStyle << 16) | (hairColor << 24), player_bytes2, GUID_LOPART(guid));
16752 delete result;
16755 void Player::SendAttackSwingDeadTarget()
16757 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
16758 GetSession()->SendPacket( &data );
16761 void Player::SendAttackSwingCantAttack()
16763 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
16764 GetSession()->SendPacket( &data );
16767 void Player::SendAttackSwingCancelAttack()
16769 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
16770 GetSession()->SendPacket( &data );
16773 void Player::SendAttackSwingBadFacingAttack()
16775 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
16776 GetSession()->SendPacket( &data );
16779 void Player::SendAutoRepeatCancel(Unit *target)
16781 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, target->GetPackGUID().size());
16782 data.append(target->GetPackGUID()); // may be it's target guid
16783 GetSession()->SendPacket( &data );
16786 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
16788 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
16789 data << Area;
16790 data << Experience;
16791 GetSession()->SendPacket(&data);
16794 void Player::SendDungeonDifficulty(bool IsInGroup)
16796 uint8 val = 0x00000001;
16797 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
16798 data << (uint32)GetDungeonDifficulty();
16799 data << uint32(val);
16800 data << uint32(IsInGroup);
16801 GetSession()->SendPacket(&data);
16804 void Player::SendRaidDifficulty(bool IsInGroup)
16806 uint8 val = 0x00000001;
16807 WorldPacket data(MSG_SET_RAID_DIFFICULTY, 12);
16808 data << uint32(GetRaidDifficulty());
16809 data << uint32(val);
16810 data << uint32(IsInGroup);
16811 GetSession()->SendPacket(&data);
16814 void Player::SendResetFailedNotify(uint32 mapid)
16816 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
16817 data << uint32(mapid);
16818 GetSession()->SendPacket(&data);
16821 /// Reset all solo instances and optionally send a message on success for each
16822 void Player::ResetInstances(uint8 method, bool isRaid)
16824 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16826 // we assume that when the difficulty changes, all instances that can be reset will be
16827 Difficulty diff = GetDifficulty(isRaid);
16829 for (BoundInstancesMap::iterator itr = m_boundInstances[diff].begin(); itr != m_boundInstances[diff].end();)
16831 InstanceSave *p = itr->second.save;
16832 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
16833 if(!entry || entry->IsRaid() != isRaid || !p->CanReset())
16835 ++itr;
16836 continue;
16839 if(method == INSTANCE_RESET_ALL)
16841 // the "reset all instances" method can only reset normal maps
16842 if(entry->map_type == MAP_RAID || diff == DUNGEON_DIFFICULTY_HEROIC)
16844 ++itr;
16845 continue;
16849 // if the map is loaded, reset it
16850 Map *map = sMapMgr.FindMap(p->GetMapId(), p->GetInstanceId());
16851 if(map && map->IsDungeon())
16852 ((InstanceMap*)map)->Reset(method);
16854 // since this is a solo instance there should not be any players inside
16855 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
16856 SendResetInstanceSuccess(p->GetMapId());
16858 p->DeleteFromDB();
16859 m_boundInstances[diff].erase(itr++);
16861 // the following should remove the instance save from the manager and delete it as well
16862 p->RemovePlayer(this);
16866 void Player::SendResetInstanceSuccess(uint32 MapId)
16868 WorldPacket data(SMSG_INSTANCE_RESET, 4);
16869 data << MapId;
16870 GetSession()->SendPacket(&data);
16873 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
16875 // TODO: find what other fail reasons there are besides players in the instance
16876 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
16877 data << reason;
16878 data << MapId;
16879 GetSession()->SendPacket(&data);
16882 /*********************************************************/
16883 /*** Update timers ***/
16884 /*********************************************************/
16886 ///checks the 15 afk reports per 5 minutes limit
16887 void Player::UpdateAfkReport(time_t currTime)
16889 if(m_bgData.bgAfkReportedTimer <= currTime)
16891 m_bgData.bgAfkReportedCount = 0;
16892 m_bgData.bgAfkReportedTimer = currTime+5*MINUTE;
16896 void Player::UpdateContestedPvP(uint32 diff)
16898 if(!m_contestedPvPTimer||isInCombat())
16899 return;
16900 if(m_contestedPvPTimer <= diff)
16902 ResetContestedPvP();
16904 else
16905 m_contestedPvPTimer -= diff;
16908 void Player::UpdatePvPFlag(time_t currTime)
16910 if(!IsPvP())
16911 return;
16912 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
16913 return;
16915 UpdatePvP(false);
16918 void Player::UpdateDuelFlag(time_t currTime)
16920 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
16921 return;
16923 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
16924 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
16926 duel->startTimer = 0;
16927 duel->startTime = currTime;
16928 duel->opponent->duel->startTimer = 0;
16929 duel->opponent->duel->startTime = currTime;
16932 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
16934 if(!pet)
16935 pet = GetPet();
16937 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16938 return;
16940 // not save secondary permanent pet as current
16941 if (pet && m_temporaryUnsummonedPetNumber != pet->GetCharmInfo()->GetPetNumber() && mode == PET_SAVE_AS_CURRENT)
16942 mode = PET_SAVE_NOT_IN_SLOT;
16944 if(returnreagent && pet && mode != PET_SAVE_AS_CURRENT)
16946 //returning of reagents only for players, so best done here
16947 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16948 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16950 if(spellInfo)
16952 for(uint32 i = 0; i < 7; ++i)
16954 if(spellInfo->Reagent[i] > 0)
16956 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16957 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16958 if( msg == EQUIP_ERR_OK )
16960 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16961 if(IsInWorld())
16962 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16969 // only if current pet in slot
16970 switch(pet->getPetType())
16972 case MINI_PET:
16973 m_miniPet = 0;
16974 break;
16975 case GUARDIAN_PET:
16976 RemoveGuardian(pet);
16977 break;
16978 default:
16979 if(GetPetGUID() == pet->GetGUID())
16980 SetPet(NULL);
16981 break;
16984 pet->CombatStop();
16986 pet->SavePetToDB(mode);
16988 pet->AddObjectToRemoveList();
16989 pet->m_removed = true;
16991 if(pet->isControlled())
16993 RemovePetActionBar();
16995 if(GetGroup())
16996 SetGroupUpdateFlag(GROUP_UPDATE_PET);
17000 void Player::RemoveMiniPet()
17002 if(Pet* pet = GetMiniPet())
17004 pet->Remove(PET_SAVE_AS_DELETED);
17005 m_miniPet = 0;
17009 Pet* Player::GetMiniPet()
17011 if(!m_miniPet)
17012 return NULL;
17013 return GetMap()->GetPet(m_miniPet);
17016 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
17018 *data << (uint8)msgtype;
17019 *data << (uint32)language;
17020 *data << (uint64)GetGUID();
17021 *data << (uint32)language; //language 2.1.0 ?
17022 *data << (uint64)GetGUID();
17023 *data << (uint32)(text.length()+1);
17024 *data << text;
17025 *data << (uint8)chatTag();
17028 void Player::Say(const std::string& text, const uint32 language)
17030 WorldPacket data(SMSG_MESSAGECHAT, 200);
17031 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
17032 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
17035 void Player::Yell(const std::string& text, const uint32 language)
17037 WorldPacket data(SMSG_MESSAGECHAT, 200);
17038 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
17039 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
17042 void Player::TextEmote(const std::string& text)
17044 WorldPacket data(SMSG_MESSAGECHAT, 200);
17045 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
17046 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
17049 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
17051 if (language != LANG_ADDON) // if not addon data
17052 language = LANG_UNIVERSAL; // whispers should always be readable
17054 Player *rPlayer = sObjectMgr.GetPlayer(receiver);
17056 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
17057 if(!rPlayer->isDND() || isGameMaster())
17059 WorldPacket data(SMSG_MESSAGECHAT, 200);
17060 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
17061 rPlayer->GetSession()->SendPacket(&data);
17063 // not send confirmation for addon messages
17064 if (language != LANG_ADDON)
17066 data.Initialize(SMSG_MESSAGECHAT, 200);
17067 rPlayer->BuildPlayerChat(&data, CHAT_MSG_WHISPER_INFORM, text, language);
17068 GetSession()->SendPacket(&data);
17071 else
17073 // announce to player that player he is whispering to is dnd and cannot receive his message
17074 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
17077 if(!isAcceptWhispers())
17079 SetAcceptWhispers(true);
17080 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
17083 // announce to player that player he is whispering to is afk
17084 if(rPlayer->isAFK())
17085 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
17087 // if player whisper someone, auto turn of dnd to be able to receive an answer
17088 if(isDND() && !rPlayer->isGameMaster())
17089 ToggleDND();
17092 void Player::PetSpellInitialize()
17094 Pet* pet = GetPet();
17096 if(!pet)
17097 return;
17099 sLog.outDebug("Pet Spells Groups");
17101 CharmInfo *charmInfo = pet->GetCharmInfo();
17103 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
17104 data << uint64(pet->GetGUID());
17105 data << uint16(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
17106 data << uint32(0);
17107 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
17109 // action bar loop
17110 charmInfo->BuildActionBar(&data);
17112 size_t spellsCountPos = data.wpos();
17114 // spells count
17115 uint8 addlist = 0;
17116 data << uint8(addlist); // placeholder
17118 if (pet->IsPermanentPetFor(this))
17120 // spells loop
17121 for (PetSpellMap::const_iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
17123 if(itr->second.state == PETSPELL_REMOVED)
17124 continue;
17126 data << uint32(MAKE_UNIT_ACTION_BUTTON(itr->first,itr->second.active));
17127 ++addlist;
17131 data.put<uint8>(spellsCountPos, addlist);
17133 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
17134 data << uint8(cooldownsCount);
17136 time_t curTime = time(NULL);
17138 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
17140 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
17142 data << uint32(itr->first); // spellid
17143 data << uint16(0); // spell category?
17144 data << uint32(cooldown); // cooldown
17145 data << uint32(0); // category cooldown
17148 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
17150 time_t cooldown = (itr->second > curTime) ? (itr->second - curTime) * IN_MILISECONDS : 0;
17152 data << uint32(itr->first); // spellid
17153 data << uint16(0); // spell category?
17154 data << uint32(0); // cooldown
17155 data << uint32(cooldown); // category cooldown
17158 GetSession()->SendPacket(&data);
17161 void Player::SendPetGUIDs()
17163 if(!GetPetGUID())
17164 return;
17166 // Later this function might get modified for multiple guids
17167 WorldPacket data(SMSG_PET_GUIDS, 12);
17168 data << uint32(1); // count
17169 data << uint64(GetPetGUID());
17170 GetSession()->SendPacket(&data);
17173 void Player::PossessSpellInitialize()
17175 Unit* charm = GetCharm();
17177 if(!charm)
17178 return;
17180 CharmInfo *charmInfo = charm->GetCharmInfo();
17182 if(!charmInfo)
17184 sLog.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
17185 return;
17188 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
17189 data << uint64(charm->GetGUID());
17190 data << uint16(0);
17191 data << uint32(0);
17192 data << uint32(0);
17194 charmInfo->BuildActionBar(&data);
17196 data << uint8(0); // spells count
17197 data << uint8(0); // cooldowns count
17199 GetSession()->SendPacket(&data);
17202 void Player::CharmSpellInitialize()
17204 Unit* charm = GetCharm();
17206 if(!charm)
17207 return;
17209 CharmInfo *charmInfo = charm->GetCharmInfo();
17210 if(!charmInfo)
17212 sLog.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm->GetGUIDLow(),charm->GetTypeId());
17213 return;
17216 uint8 addlist = 0;
17218 if(charm->GetTypeId() != TYPEID_PLAYER)
17220 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
17222 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
17224 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
17226 if(charmInfo->GetCharmSpell(i)->GetAction())
17227 ++addlist;
17232 WorldPacket data(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+4*addlist+1);
17233 data << uint64(charm->GetGUID());
17234 data << uint16(0);
17235 data << uint32(0);
17237 if(charm->GetTypeId() != TYPEID_PLAYER)
17238 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
17239 else
17240 data << uint8(0) << uint8(0) << uint16(0);
17242 charmInfo->BuildActionBar(&data);
17244 data << uint8(addlist);
17246 if(addlist)
17248 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
17250 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
17251 if(cspell->GetAction())
17252 data << uint32(cspell->packedData);
17256 data << uint8(0); // cooldowns count
17258 GetSession()->SendPacket(&data);
17261 void Player::RemovePetActionBar()
17263 WorldPacket data(SMSG_PET_SPELLS, 8);
17264 data << uint64(0);
17265 SendDirectMessage(&data);
17268 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
17270 if (!mod || !spellInfo)
17271 return false;
17273 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
17275 // prevent apply to any spell except spell that trigger expire
17276 if(spell)
17278 if(mod->lastAffected != spell)
17279 return false;
17281 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
17282 return false;
17285 return mod->isAffectedOnSpell(spellInfo);
17288 void Player::AddSpellMod(SpellModifier* mod, bool apply)
17290 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
17292 for(int eff=0;eff<96;++eff)
17294 uint64 _mask = 0;
17295 uint32 _mask2= 0;
17296 if (eff<64) _mask = uint64(1) << (eff- 0);
17297 else _mask2= uint32(1) << (eff-64);
17298 if ( mod->mask & _mask || mod->mask2 & _mask2)
17300 int32 val = 0;
17301 for (SpellModList::const_iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
17303 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
17304 val += (*itr)->value;
17306 val += apply ? mod->value : -(mod->value);
17307 WorldPacket data(Opcode, (1+1+4));
17308 data << uint8(eff);
17309 data << uint8(mod->op);
17310 data << int32(val);
17311 SendDirectMessage(&data);
17315 if (apply)
17316 m_spellMods[mod->op].push_back(mod);
17317 else
17319 if (mod->charges == -1)
17320 --m_SpellModRemoveCount;
17321 m_spellMods[mod->op].remove(mod);
17322 delete mod;
17326 void Player::RemoveSpellMods(Spell const* spell)
17328 if(!spell || (m_SpellModRemoveCount == 0))
17329 return;
17331 for(int i=0;i<MAX_SPELLMOD;++i)
17333 for (SpellModList::const_iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
17335 SpellModifier *mod = *itr;
17336 ++itr;
17338 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
17340 RemoveAurasDueToSpell(mod->spellId);
17341 if (m_spellMods[i].empty())
17342 break;
17343 else
17344 itr = m_spellMods[i].begin();
17350 // send Proficiency
17351 void Player::SendProficiency(uint8 pr1, uint32 pr2)
17353 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
17354 data << pr1 << pr2;
17355 GetSession()->SendPacket (&data);
17358 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
17360 QueryResult *result = NULL;
17361 if(type==10)
17362 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
17363 else
17364 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17365 if(result)
17367 do // this part effectively does nothing, since the deletion / modification only takes place _after_ the PetitionQuery. Though I don't know if the result remains intact if I execute the delete query beforehand.
17368 { // and SendPetitionQueryOpcode reads data from the DB
17369 Field *fields = result->Fetch();
17370 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
17371 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
17373 // send update if charter owner in game
17374 Player* owner = sObjectMgr.GetPlayer(ownerguid);
17375 if(owner)
17376 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
17378 } while ( result->NextRow() );
17380 delete result;
17382 if(type==10)
17383 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
17384 else
17385 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17388 CharacterDatabase.BeginTransaction();
17389 if(type == 10)
17391 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
17392 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
17394 else
17396 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17397 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
17399 CharacterDatabase.CommitTransaction();
17402 void Player::LeaveAllArenaTeams(uint64 guid)
17404 QueryResult *result = CharacterDatabase.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u'", GUID_LOPART(guid));
17405 if(!result)
17406 return;
17410 Field *fields = result->Fetch();
17411 uint32 at_id = fields[0].GetUInt32();
17412 if(at_id != 0)
17414 ArenaTeam * at = sObjectMgr.GetArenaTeamById(at_id);
17415 if(at)
17416 at->DelMember(guid);
17418 } while (result->NextRow());
17420 delete result;
17423 void Player::SetRestBonus (float rest_bonus_new)
17425 // Prevent resting on max level
17426 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
17427 rest_bonus_new = 0;
17429 if(rest_bonus_new < 0)
17430 rest_bonus_new = 0;
17432 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
17434 if(rest_bonus_new > rest_bonus_max)
17435 m_rest_bonus = rest_bonus_max;
17436 else
17437 m_rest_bonus = rest_bonus_new;
17439 // update data for client
17440 if(m_rest_bonus>10)
17441 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
17442 else if(m_rest_bonus<=1)
17443 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
17445 //RestTickUpdate
17446 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
17449 void Player::HandleStealthedUnitsDetection()
17451 std::list<Unit*> stealthedUnits;
17453 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
17454 Cell cell(p);
17455 cell.data.Part.reserved = ALL_DISTRICT;
17456 cell.SetNoCreate();
17458 MaNGOS::AnyStealthedCheck u_check;
17459 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(this,stealthedUnits, u_check);
17461 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
17462 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
17464 cell.Visit(p, world_unit_searcher, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE);
17465 cell.Visit(p, grid_unit_searcher, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE);
17467 WorldObject const* viewPoint = GetViewPoint();
17469 for (std::list<Unit*>::const_iterator i = stealthedUnits.begin(); i != stealthedUnits.end(); ++i)
17471 if((*i)==this)
17472 continue;
17474 bool hasAtClient = HaveAtClient((*i));
17475 bool hasDetected = (*i)->isVisibleForOrDetect(this, viewPoint, true);
17477 if (hasDetected)
17479 if(!hasAtClient)
17481 (*i)->SendCreateUpdateToPlayer(this);
17482 m_clientGUIDs.insert((*i)->GetGUID());
17484 #ifdef MANGOS_DEBUG
17485 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17486 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
17487 #endif
17489 // target aura duration for caster show only if target exist at caster client
17490 // send data at target visibility change (adding to client)
17491 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
17492 SendAurasForTarget(*i);
17495 else
17497 if(hasAtClient)
17499 (*i)->DestroyForPlayer(this);
17500 m_clientGUIDs.erase((*i)->GetGUID());
17506 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, Creature* npc /*= NULL*/, uint32 spellid /*= 0*/)
17508 if(nodes.size() < 2)
17509 return false;
17511 // not let cheating with start flight in time of logout process || if casting not finished || while in combat || if not use Spell's with EffectSendTaxi
17512 if(GetSession()->isLogingOut() || isInCombat())
17514 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17515 data << uint32(ERR_TAXIPLAYERBUSY);
17516 GetSession()->SendPacket(&data);
17517 return false;
17520 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
17521 return false;
17523 // taximaster case
17524 if(npc)
17526 // not let cheating with start flight mounted
17527 if(IsMounted())
17529 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17530 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
17531 GetSession()->SendPacket(&data);
17532 return false;
17535 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
17537 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17538 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
17539 GetSession()->SendPacket(&data);
17540 return false;
17543 // not let cheating with start flight in time of logout process || if casting not finished || while in combat || if not use Spell's with EffectSendTaxi
17544 if(IsNonMeleeSpellCasted(false))
17546 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17547 data << uint32(ERR_TAXIPLAYERBUSY);
17548 GetSession()->SendPacket(&data);
17549 return false;
17552 // cast case or scripted call case
17553 else
17555 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
17557 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
17558 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
17560 if (Spell* spell = GetCurrentSpell(CURRENT_GENERIC_SPELL))
17561 if (spell->m_spellInfo->Id != spellid)
17562 InterruptSpell(CURRENT_GENERIC_SPELL,false);
17564 InterruptSpell(CURRENT_AUTOREPEAT_SPELL,false);
17566 if (Spell* spell = GetCurrentSpell(CURRENT_CHANNELED_SPELL))
17567 if (spell->m_spellInfo->Id != spellid)
17568 InterruptSpell(CURRENT_CHANNELED_SPELL,true);
17571 uint32 sourcenode = nodes[0];
17573 // starting node too far away (cheat?)
17574 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
17575 if (!node)
17577 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17578 data << uint32(ERR_TAXINOSUCHPATH);
17579 GetSession()->SendPacket(&data);
17580 return false;
17583 // check node starting pos data set case if provided
17584 if (node->x != 0.0f || node->y != 0.0f || node->z != 0.0f)
17586 if (node->map_id != GetMapId() ||
17587 (node->x - GetPositionX())*(node->x - GetPositionX())+
17588 (node->y - GetPositionY())*(node->y - GetPositionY())+
17589 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
17590 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE))
17592 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17593 data << uint32(ERR_TAXITOOFARAWAY);
17594 GetSession()->SendPacket(&data);
17595 return false;
17598 // node must have pos if taxi master case (npc != NULL)
17599 else if (npc)
17601 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17602 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17603 GetSession()->SendPacket(&data);
17604 return false;
17607 // Prepare to flight start now
17609 // stop combat at start taxi flight if any
17610 CombatStop();
17612 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
17613 TradeCancel(true);
17615 // clean not finished taxi path if any
17616 m_taxi.ClearTaxiDestinations();
17618 // 0 element current node
17619 m_taxi.AddTaxiDestination(sourcenode);
17621 // fill destinations path tail
17622 uint32 sourcepath = 0;
17623 uint32 totalcost = 0;
17625 uint32 prevnode = sourcenode;
17626 uint32 lastnode = 0;
17628 for(uint32 i = 1; i < nodes.size(); ++i)
17630 uint32 path, cost;
17632 lastnode = nodes[i];
17633 sObjectMgr.GetTaxiPath(prevnode, lastnode, path, cost);
17635 if(!path)
17637 m_taxi.ClearTaxiDestinations();
17638 return false;
17641 totalcost += cost;
17643 if(prevnode == sourcenode)
17644 sourcepath = path;
17646 m_taxi.AddTaxiDestination(lastnode);
17648 prevnode = lastnode;
17651 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
17652 uint32 mount_display_id = sObjectMgr.GetTaxiMountDisplayId(sourcenode, GetTeam(), npc == NULL);
17654 // in spell case allow 0 model
17655 if ((mount_display_id == 0 && spellid == 0) || sourcepath == 0)
17657 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17658 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
17659 GetSession()->SendPacket(&data);
17660 m_taxi.ClearTaxiDestinations();
17661 return false;
17664 uint32 money = GetMoney();
17666 if (npc)
17667 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
17669 if(money < totalcost)
17671 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17672 data << uint32(ERR_TAXINOTENOUGHMONEY);
17673 GetSession()->SendPacket(&data);
17674 m_taxi.ClearTaxiDestinations();
17675 return false;
17678 //Checks and preparations done, DO FLIGHT
17679 ModifyMoney(-(int32)totalcost);
17680 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING, totalcost);
17681 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN, 1);
17683 // prevent stealth flight
17684 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
17686 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
17687 data << uint32(ERR_TAXIOK);
17688 GetSession()->SendPacket(&data);
17690 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17692 GetSession()->SendDoFlight(mount_display_id, sourcepath);
17694 return true;
17697 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id, uint32 spellid /*= 0*/ )
17699 TaxiPathEntry const* entry = sTaxiPathStore.LookupEntry(taxi_path_id);
17700 if(!entry)
17701 return false;
17703 std::vector<uint32> nodes;
17705 nodes.resize(2);
17706 nodes[0] = entry->from;
17707 nodes[1] = entry->to;
17709 return ActivateTaxiPathTo(nodes,NULL,spellid);
17712 void Player::ContinueTaxiFlight()
17714 uint32 sourceNode = m_taxi.GetTaxiSource();
17715 if (!sourceNode)
17716 return;
17718 sLog.outDebug( "WORLD: Restart character %u taxi flight", GetGUIDLow() );
17720 uint32 mountDisplayId = sObjectMgr.GetTaxiMountDisplayId(sourceNode, GetTeam(),true);
17721 uint32 path = m_taxi.GetCurrentTaxiPath();
17723 // search appropriate start path node
17724 uint32 startNode = 0;
17726 TaxiPathNodeList const& nodeList = sTaxiPathNodesByPath[path];
17728 float distPrev = MAP_SIZE*MAP_SIZE;
17729 float distNext =
17730 (nodeList[0].x-GetPositionX())*(nodeList[0].x-GetPositionX())+
17731 (nodeList[0].y-GetPositionY())*(nodeList[0].y-GetPositionY())+
17732 (nodeList[0].z-GetPositionZ())*(nodeList[0].z-GetPositionZ());
17734 for(uint32 i = 1; i < nodeList.size(); ++i)
17736 TaxiPathNode const& node = nodeList[i];
17737 TaxiPathNode const& prevNode = nodeList[i-1];
17739 // skip nodes at another map
17740 if(node.mapid != GetMapId())
17741 continue;
17743 distPrev = distNext;
17745 distNext =
17746 (node.x-GetPositionX())*(node.x-GetPositionX())+
17747 (node.y-GetPositionY())*(node.y-GetPositionY())+
17748 (node.z-GetPositionZ())*(node.z-GetPositionZ());
17750 float distNodes =
17751 (node.x-prevNode.x)*(node.x-prevNode.x)+
17752 (node.y-prevNode.y)*(node.y-prevNode.y)+
17753 (node.z-prevNode.z)*(node.z-prevNode.z);
17755 if(distNext + distPrev < distNodes)
17757 startNode = i;
17758 break;
17762 GetSession()->SendDoFlight(mountDisplayId, path, startNode);
17765 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
17767 // last check 2.0.10
17768 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
17769 data << GetGUID();
17770 data << uint8(0x0); // flags (0x1, 0x2)
17771 time_t curTime = time(NULL);
17772 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17774 if (itr->second->state == PLAYERSPELL_REMOVED)
17775 continue;
17776 uint32 unSpellId = itr->first;
17777 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
17778 if (!spellInfo)
17780 ASSERT(spellInfo);
17781 continue;
17784 // Not send cooldown for this spells
17785 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
17786 continue;
17788 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
17790 data << uint32(unSpellId);
17791 data << uint32(unTimeMs); // in m.secs
17792 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/IN_MILISECONDS);
17795 GetSession()->SendPacket(&data);
17798 void Player::InitDataForForm(bool reapplyMods)
17800 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
17801 if(ssEntry && ssEntry->attackSpeed)
17803 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
17804 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
17805 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
17807 else
17808 SetRegularAttackTime();
17810 switch(m_form)
17812 case FORM_CAT:
17814 if(getPowerType()!=POWER_ENERGY)
17815 setPowerType(POWER_ENERGY);
17816 break;
17818 case FORM_BEAR:
17819 case FORM_DIREBEAR:
17821 if(getPowerType()!=POWER_RAGE)
17822 setPowerType(POWER_RAGE);
17823 break;
17825 default: // 0, for example
17827 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
17828 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
17829 setPowerType(Powers(cEntry->powerType));
17830 break;
17834 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17835 if (!reapplyMods)
17836 UpdateEquipSpellsAtFormChange();
17838 UpdateAttackPowerAndDamage();
17839 UpdateAttackPowerAndDamage(true);
17842 void Player::InitDisplayIds()
17844 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(), getClass());
17845 if(!info)
17847 sLog.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
17848 return;
17851 uint8 gender = getGender();
17852 switch(gender)
17854 case GENDER_FEMALE:
17855 SetDisplayId(info->displayId_f );
17856 SetNativeDisplayId(info->displayId_f );
17857 break;
17858 case GENDER_MALE:
17859 SetDisplayId(info->displayId_m );
17860 SetNativeDisplayId(info->displayId_m );
17861 break;
17862 default:
17863 sLog.outError("Invalid gender %u for player",gender);
17864 return;
17868 // Return true is the bought item has a max count to force refresh of window by caller
17869 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint8 bag, uint8 slot)
17871 // cheating attempt
17872 if (count < 1) count = 1;
17874 if (!isAlive())
17875 return false;
17877 ItemPrototype const *pProto = ObjectMgr::GetItemPrototype( item );
17878 if (!pProto)
17880 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
17881 return false;
17884 Creature *pCreature = GetNPCIfCanInteractWith(vendorguid,UNIT_NPC_FLAG_VENDOR);
17885 if (!pCreature)
17887 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
17888 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
17889 return false;
17892 VendorItemData const* vItems = pCreature->GetVendorItems();
17893 if(!vItems || vItems->Empty())
17895 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17896 return false;
17899 size_t vendor_slot = vItems->FindItemSlot(item);
17900 if (vendor_slot >= vItems->GetItemCount())
17902 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
17903 return false;
17906 VendorItem const* crItem = vItems->m_items[vendor_slot];
17908 // check current item amount if it limited
17909 if (crItem->maxcount != 0)
17911 if (pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
17913 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
17914 return false;
17918 if (uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
17920 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
17921 return false;
17924 if (crItem->ExtendedCost)
17926 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17927 if (!iece)
17929 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
17930 return false;
17933 // honor points price
17934 if (GetHonorPoints() < (iece->reqhonorpoints * count))
17936 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
17937 return false;
17940 // arena points price
17941 if (GetArenaPoints() < (iece->reqarenapoints * count))
17943 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
17944 return false;
17947 // item base price
17948 for (uint8 i = 0; i < 5; ++i)
17950 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
17952 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
17953 return false;
17957 // check for personal arena rating requirement
17958 if( GetMaxPersonalArenaRatingRequirement(iece->reqarenaslot) < iece->reqpersonalarenarating )
17960 // probably not the proper equip err
17961 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
17962 return false;
17966 uint32 price = pProto->BuyPrice * count;
17968 // reputation discount
17969 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
17971 if (GetMoney() < price)
17973 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
17974 return false;
17977 if ((bag == NULL_BAG && slot == NULL_SLOT) || IsInventoryPos(bag, slot))
17979 ItemPosCountVec dest;
17980 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
17981 if (msg != EQUIP_ERR_OK)
17983 SendEquipError( msg, NULL, NULL );
17984 return false;
17987 ModifyMoney( -(int32)price );
17988 if (crItem->ExtendedCost) // case for new honor system
17990 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
17991 if (iece->reqhonorpoints)
17992 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
17993 if (iece->reqarenapoints)
17994 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
17995 for (uint8 i = 0; i < 5; ++i)
17997 if (iece->reqitem[i])
17998 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
18002 if (Item *it = StoreNewItem( dest, item, true ))
18004 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
18006 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
18007 data << uint64(pCreature->GetGUID());
18008 data << uint32(vendor_slot+1); // numbered from 1 at client
18009 data << uint32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
18010 data << uint32(count);
18011 GetSession()->SendPacket(&data);
18013 SendNewItem(it, pProto->BuyCount*count, true, false, false);
18016 else if (IsEquipmentPos(bag, slot))
18018 if (pProto->BuyCount * count != 1)
18020 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED, NULL, NULL );
18021 return false;
18024 uint16 dest;
18025 uint8 msg = CanEquipNewItem( slot, dest, item, false );
18026 if (msg != EQUIP_ERR_OK)
18028 SendEquipError( msg, NULL, NULL );
18029 return false;
18032 ModifyMoney( -(int32)price );
18033 if (crItem->ExtendedCost) // case for new honor system
18035 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
18036 if (iece->reqhonorpoints)
18037 ModifyHonorPoints( - int32(iece->reqhonorpoints));
18038 if (iece->reqarenapoints)
18039 ModifyArenaPoints( - int32(iece->reqarenapoints));
18040 for (uint8 i = 0; i < 5; ++i)
18042 if(iece->reqitem[i])
18043 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
18047 if (Item *it = EquipNewItem( dest, item, true ))
18049 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
18051 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
18052 data << uint64(pCreature->GetGUID());
18053 data << uint32(vendor_slot + 1); // numbered from 1 at client
18054 data << uint32(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
18055 data << uint32(count);
18056 GetSession()->SendPacket(&data);
18058 SendNewItem(it, pProto->BuyCount*count, true, false, false);
18060 AutoUnequipOffhandIfNeed();
18063 else
18065 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
18066 return false;
18069 return crItem->maxcount != 0;
18072 uint32 Player::GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot)
18074 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
18075 // the personal rating of the arena team must match the required limit as well
18076 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
18077 uint32 max_personal_rating = 0;
18078 for(int i = minarenaslot; i < MAX_ARENA_SLOT; ++i)
18080 if(ArenaTeam * at = sObjectMgr.GetArenaTeamById(GetArenaTeamId(i)))
18082 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * ARENA_TEAM_END) + ARENA_TEAM_PERSONAL_RATING);
18083 uint32 t_rating = at->GetRating();
18084 p_rating = p_rating < t_rating ? p_rating : t_rating;
18085 if(max_personal_rating < p_rating)
18086 max_personal_rating = p_rating;
18089 return max_personal_rating;
18092 void Player::UpdateHomebindTime(uint32 time)
18094 // GMs never get homebind timer online
18095 if (m_InstanceValid || isGameMaster())
18097 if(m_HomebindTimer) // instance valid, but timer not reset
18099 // hide reminder
18100 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
18101 data << uint32(0);
18102 data << uint32(ERR_RAID_GROUP_NONE); // error used only when timer = 0
18103 GetSession()->SendPacket(&data);
18105 // instance is valid, reset homebind timer
18106 m_HomebindTimer = 0;
18108 else if (m_HomebindTimer > 0)
18110 if (time >= m_HomebindTimer)
18112 // teleport to nearest graveyard
18113 RepopAtGraveyard();
18115 else
18116 m_HomebindTimer -= time;
18118 else
18120 // instance is invalid, start homebind timer
18121 m_HomebindTimer = 60000;
18122 // send message to player
18123 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
18124 data << uint32(m_HomebindTimer);
18125 data << uint32(ERR_RAID_GROUP_NONE); // error used only when timer = 0
18126 GetSession()->SendPacket(&data);
18127 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
18131 void Player::UpdatePvP(bool state, bool ovrride)
18133 if(!state || ovrride)
18135 SetPvP(state);
18136 pvpInfo.endTimer = 0;
18138 else
18140 if(pvpInfo.endTimer != 0)
18141 pvpInfo.endTimer = time(NULL);
18142 else
18143 SetPvP(state);
18147 void Player::AddSpellAndCategoryCooldowns(SpellEntry const* spellInfo, uint32 itemId, Spell* spell, bool infinityCooldown)
18149 // init cooldown values
18150 uint32 cat = 0;
18151 int32 rec = -1;
18152 int32 catrec = -1;
18154 // some special item spells without correct cooldown in SpellInfo
18155 // cooldown information stored in item prototype
18156 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
18158 if(itemId)
18160 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(itemId))
18162 for(int idx = 0; idx < 5; ++idx)
18164 if(proto->Spells[idx].SpellId == spellInfo->Id)
18166 cat = proto->Spells[idx].SpellCategory;
18167 rec = proto->Spells[idx].SpellCooldown;
18168 catrec = proto->Spells[idx].SpellCategoryCooldown;
18169 break;
18175 // if no cooldown found above then base at DBC data
18176 if(rec < 0 && catrec < 0)
18178 cat = spellInfo->Category;
18179 rec = spellInfo->RecoveryTime;
18180 catrec = spellInfo->CategoryRecoveryTime;
18183 time_t curTime = time(NULL);
18185 time_t catrecTime;
18186 time_t recTime;
18188 // overwrite time for selected category
18189 if(infinityCooldown)
18191 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
18192 // but not allow ignore until reset or re-login
18193 catrecTime = catrec > 0 ? curTime+infinityCooldownDelay : 0;
18194 recTime = rec > 0 ? curTime+infinityCooldownDelay : catrecTime;
18196 else
18198 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
18199 // prevent 0 cooldowns set by another way
18200 if (rec <= 0 && catrec <= 0 && (cat == 76 || IsAutoRepeatRangedSpell(spellInfo) && spellInfo->Id != SPELL_ID_AUTOSHOT))
18201 rec = GetAttackTime(RANGED_ATTACK);
18203 // Now we have cooldown data (if found any), time to apply mods
18204 if(rec > 0)
18205 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, rec, spell);
18207 if(catrec > 0)
18208 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, catrec, spell);
18210 // replace negative cooldowns by 0
18211 if (rec < 0) rec = 0;
18212 if (catrec < 0) catrec = 0;
18214 // no cooldown after applying spell mods
18215 if( rec == 0 && catrec == 0)
18216 return;
18218 catrecTime = catrec ? curTime+catrec/IN_MILISECONDS : 0;
18219 recTime = rec ? curTime+rec/IN_MILISECONDS : catrecTime;
18222 // self spell cooldown
18223 if(recTime > 0)
18224 AddSpellCooldown(spellInfo->Id, itemId, recTime);
18226 // category spells
18227 if (cat && catrec > 0)
18229 SpellCategoryStore::const_iterator i_scstore = sSpellCategoryStore.find(cat);
18230 if(i_scstore != sSpellCategoryStore.end())
18232 for(SpellCategorySet::const_iterator i_scset = i_scstore->second.begin(); i_scset != i_scstore->second.end(); ++i_scset)
18234 if(*i_scset == spellInfo->Id) // skip main spell, already handled above
18235 continue;
18237 AddSpellCooldown(*i_scset, itemId, catrecTime);
18243 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
18245 SpellCooldown sc;
18246 sc.end = end_time;
18247 sc.itemid = itemid;
18248 m_spellCooldowns[spellid] = sc;
18251 void Player::SendCooldownEvent(SpellEntry const *spellInfo, uint32 itemId, Spell* spell)
18253 // start cooldowns at server side, if any
18254 AddSpellAndCategoryCooldowns(spellInfo, itemId, spell);
18256 // Send activate cooldown timer (possible 0) at client side
18257 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
18258 data << uint32(spellInfo->Id);
18259 data << uint64(GetGUID());
18260 SendDirectMessage(&data);
18263 void Player::UpdatePotionCooldown(Spell* spell)
18265 // no potion used i combat or still in combat
18266 if(!m_lastPotionId || isInCombat())
18267 return;
18269 // Call not from spell cast, send cooldown event for item spells if no in combat
18270 if(!spell)
18272 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
18273 if(ItemPrototype const* proto = ObjectMgr::GetItemPrototype(m_lastPotionId))
18274 for(int idx = 0; idx < 5; ++idx)
18275 if(proto->Spells[idx].SpellId && proto->Spells[idx].SpellTrigger == ITEM_SPELLTRIGGER_ON_USE)
18276 if(SpellEntry const* spellInfo = sSpellStore.LookupEntry(proto->Spells[idx].SpellId))
18277 SendCooldownEvent(spellInfo,m_lastPotionId);
18279 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
18280 else
18281 SendCooldownEvent(spell->m_spellInfo,m_lastPotionId,spell);
18283 m_lastPotionId = 0;
18286 //slot to be excluded while counting
18287 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
18289 if(!enchantmentcondition)
18290 return true;
18292 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
18294 if(!Condition)
18295 return true;
18297 uint8 curcount[4] = {0, 0, 0, 0};
18299 //counting current equipped gem colors
18300 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
18302 if(i == slot)
18303 continue;
18304 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
18305 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
18307 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18309 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18310 if(!enchant_id)
18311 continue;
18313 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18314 if(!enchantEntry)
18315 continue;
18317 uint32 gemid = enchantEntry->GemID;
18318 if(!gemid)
18319 continue;
18321 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
18322 if(!gemProto)
18323 continue;
18325 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
18326 if(!gemProperty)
18327 continue;
18329 uint8 GemColor = gemProperty->color;
18331 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
18333 if(tmpcolormask & GemColor)
18334 ++curcount[b];
18340 bool activate = true;
18342 for(int i = 0; i < 5; ++i)
18344 if(!Condition->Color[i])
18345 continue;
18347 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
18349 // if have <CompareColor> use them as count, else use <value> from Condition
18350 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
18352 switch(Condition->Comparator[i])
18354 case 2: // requires less <color> than (<value> || <comparecolor>) gems
18355 activate &= (_cur_gem < _cmp_gem) ? true : false;
18356 break;
18357 case 3: // requires more <color> than (<value> || <comparecolor>) gems
18358 activate &= (_cur_gem > _cmp_gem) ? true : false;
18359 break;
18360 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
18361 activate &= (_cur_gem >= _cmp_gem) ? true : false;
18362 break;
18366 sLog.outDebug("Checking Condition %u, there are %u Meta Gems, %u Red Gems, %u Yellow Gems and %u Blue Gems, Activate:%s", enchantmentcondition, curcount[0], curcount[1], curcount[2], curcount[3], activate ? "yes" : "no");
18368 return activate;
18371 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
18373 //cycle all equipped items
18374 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
18376 //enchants for the slot being socketed are handled by Player::ApplyItemMods
18377 if(slot == exceptslot)
18378 continue;
18380 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
18382 if(!pItem || !pItem->GetProto()->Socket[0].Color)
18383 continue;
18385 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18387 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18388 if(!enchant_id)
18389 continue;
18391 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18392 if(!enchantEntry)
18393 continue;
18395 uint32 condition = enchantEntry->EnchantmentCondition;
18396 if(condition)
18398 //was enchant active with/without item?
18399 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
18400 //should it now be?
18401 if(wasactive != EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
18403 // ignore item gem conditions
18404 //if state changed, (dis)apply enchant
18405 ApplyEnchantment(pItem, EnchantmentSlot(enchant_slot), !wasactive, true, true);
18412 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
18413 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
18415 //cycle all equipped items
18416 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
18418 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
18419 if(slot == exceptslot)
18420 continue;
18422 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
18424 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
18425 continue;
18427 //cycle all (gem)enchants
18428 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
18430 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
18431 if(!enchant_id) //if no enchant go to next enchant(slot)
18432 continue;
18434 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
18435 if(!enchantEntry)
18436 continue;
18438 //only metagems to be (de)activated, so only enchants with condition
18439 uint32 condition = enchantEntry->EnchantmentCondition;
18440 if(condition)
18441 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
18446 void Player::SetBattleGroundEntryPoint()
18448 // Taxi path store
18449 if (!m_taxi.empty())
18451 m_bgData.mountSpell = 0;
18452 m_bgData.taxiPath[0] = m_taxi.GetTaxiSource();
18453 m_bgData.taxiPath[1] = m_taxi.GetTaxiDestination();
18455 // On taxi we don't need check for dungeon
18456 m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
18457 return;
18459 else
18461 m_bgData.ClearTaxiPath();
18463 // Mount spell id storing
18464 if (IsMounted())
18466 AuraList const& auras = GetAurasByType(SPELL_AURA_MOUNTED);
18467 if (!auras.empty())
18468 m_bgData.mountSpell = (*auras.begin())->GetId();
18470 else
18471 m_bgData.mountSpell = 0;
18473 // If map is dungeon find linked graveyard
18474 if(GetMap()->IsDungeon())
18476 if (const WorldSafeLocsEntry* entry = sObjectMgr.GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
18478 m_bgData.joinPos = WorldLocation(entry->map_id, entry->x, entry->y, entry->z, 0.0f);
18479 return;
18481 else
18482 sLog.outError("SetBattleGroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId());
18484 // If new entry point is not BG or arena set it
18485 else if (!GetMap()->IsBattleGroundOrArena())
18487 m_bgData.joinPos = WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
18488 return;
18492 // In error cases use homebind position
18493 m_bgData.joinPos = WorldLocation(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, 0.0f);
18496 void Player::LeaveBattleground(bool teleportToEntryPoint)
18498 if(BattleGround *bg = GetBattleGround())
18500 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
18502 // call after remove to be sure that player resurrected for correct cast
18503 if( bg->isBattleGround() && !isGameMaster() && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER) )
18505 if( bg->GetStatus() == STATUS_IN_PROGRESS || bg->GetStatus() == STATUS_WAIT_JOIN )
18507 //lets check if player was teleported from BG and schedule delayed Deserter spell cast
18508 if(IsBeingTeleportedFar())
18510 ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER);
18511 return;
18514 CastSpell(this, 26013, true); // Deserter
18520 bool Player::CanJoinToBattleground() const
18522 // check Deserter debuff
18523 if(GetDummyAura(26013))
18524 return false;
18526 return true;
18529 bool Player::CanReportAfkDueToLimit()
18531 // a player can complain about 15 people per 5 minutes
18532 if(m_bgData.bgAfkReportedCount++ >= 15)
18533 return false;
18535 return true;
18538 ///This player has been blamed to be inactive in a battleground
18539 void Player::ReportedAfkBy(Player* reporter)
18541 BattleGround *bg = GetBattleGround();
18542 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
18543 return;
18545 // check if player has 'Idle' or 'Inactive' debuff
18546 if(m_bgData.bgAfkReporter.find(reporter->GetGUIDLow()) == m_bgData.bgAfkReporter.end() && !HasAura(43680, 0) && !HasAura(43681, 0) && reporter->CanReportAfkDueToLimit())
18548 m_bgData.bgAfkReporter.insert(reporter->GetGUIDLow());
18549 // 3 players have to complain to apply debuff
18550 if(m_bgData.bgAfkReporter.size() >= 3)
18552 // cast 'Idle' spell
18553 CastSpell(this, 43680, true);
18554 m_bgData.bgAfkReporter.clear();
18559 WorldObject const* Player::GetViewPoint() const
18561 if(uint64 far_sight = GetFarSight())
18563 WorldObject const* viewPoint = GetMap()->GetWorldObject(far_sight);
18564 return viewPoint ? viewPoint : this; // always expected not NULL
18566 else
18567 return this;
18570 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
18572 // gamemaster in GM mode see all, including ghosts
18573 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
18574 return true;
18576 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
18577 if (InBattleGround())
18579 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
18580 return false;
18581 return true;
18584 // Live player see live player or dead player with not realized corpse
18585 if(pl->isAlive() || pl->m_deathTimer > 0)
18587 return isAlive() || m_deathTimer > 0;
18590 // Ghost see other friendly ghosts, that's for sure
18591 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
18592 return true;
18594 // Dead player see live players near own corpse
18595 if(isAlive())
18597 Corpse *corpse = pl->GetCorpse();
18598 if(corpse)
18600 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
18601 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
18602 return true;
18606 // and not see any other
18607 return false;
18610 bool Player::IsVisibleGloballyFor( Player* u ) const
18612 if(!u)
18613 return false;
18615 // Always can see self
18616 if (u==this)
18617 return true;
18619 // Visible units, always are visible for all players
18620 if (GetVisibility() == VISIBILITY_ON)
18621 return true;
18623 // GMs are visible for higher gms (or players are visible for gms)
18624 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
18625 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
18627 // non faction visibility non-breakable for non-GMs
18628 if (GetVisibility() == VISIBILITY_OFF)
18629 return false;
18631 // non-gm stealth/invisibility not hide from global player lists
18632 return true;
18635 template<class T>
18636 inline void BeforeVisibilityDestroy(T* /*t*/, Player* /*p*/)
18640 template<>
18641 inline void BeforeVisibilityDestroy<Creature>(Creature* t, Player* p)
18643 if (p->GetPetGUID()==t->GetGUID() && ((Creature*)t)->isPet())
18644 ((Pet*)t)->Remove(PET_SAVE_NOT_IN_SLOT, true);
18647 void Player::UpdateVisibilityOf(WorldObject const* viewPoint, WorldObject* target)
18649 if(HaveAtClient(target))
18651 if(!target->isVisibleForInState(this, viewPoint, true))
18653 if (target->GetTypeId()==TYPEID_UNIT)
18654 BeforeVisibilityDestroy<Creature>((Creature*)target,this);
18656 target->DestroyForPlayer(this);
18657 m_clientGUIDs.erase(target->GetGUID());
18659 #ifdef MANGOS_DEBUG
18660 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18661 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
18662 #endif
18665 else
18667 if(target->isVisibleForInState(this, viewPoint, false))
18669 target->SendCreateUpdateToPlayer(this);
18670 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
18671 m_clientGUIDs.insert(target->GetGUID());
18673 #ifdef MANGOS_DEBUG
18674 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18675 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
18676 #endif
18678 // target aura duration for caster show only if target exist at caster client
18679 // send data at target visibility change (adding to client)
18680 if(target!=this && target->isType(TYPEMASK_UNIT))
18681 SendAurasForTarget((Unit*)target);
18683 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
18684 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
18689 template<class T>
18690 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
18692 s64.insert(target->GetGUID());
18695 template<>
18696 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
18698 if(!target->IsTransport())
18699 s64.insert(target->GetGUID());
18702 template<class T>
18703 void Player::UpdateVisibilityOf(WorldObject const* viewPoint, T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
18705 if(HaveAtClient(target))
18707 if(!target->isVisibleForInState(this,viewPoint,true))
18709 BeforeVisibilityDestroy<T>(target,this);
18711 target->BuildOutOfRangeUpdateBlock(&data);
18712 m_clientGUIDs.erase(target->GetGUID());
18714 #ifdef MANGOS_DEBUG
18715 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18716 sLog.outDebug("Object %u (Type: %u, Entry: %u) is out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),target->GetEntry(),GetGUIDLow(),GetDistance(target));
18717 #endif
18720 else
18722 if(target->isVisibleForInState(this,viewPoint,false))
18724 visibleNow.insert(target);
18725 target->BuildCreateUpdateBlockForPlayer(&data, this);
18726 UpdateVisibilityOf_helper(m_clientGUIDs,target);
18728 #ifdef MANGOS_DEBUG
18729 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
18730 sLog.outDebug("Object %u (Type: %u, Entry: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),target->GetEntry(),GetGUIDLow(),GetDistance(target));
18731 #endif
18736 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18737 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18738 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18739 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18740 template void Player::UpdateVisibilityOf(WorldObject const* viewPoint, DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
18742 void Player::InitPrimaryProfessions()
18744 SetFreePrimaryProfessions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
18747 void Player::SendComboPoints()
18749 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
18750 if (combotarget)
18752 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
18753 data.append(combotarget->GetPackGUID());
18754 data << uint8(m_comboPoints);
18755 GetSession()->SendPacket(&data);
18759 void Player::AddComboPoints(Unit* target, int8 count)
18761 if(!count)
18762 return;
18764 // without combo points lost (duration checked in aura)
18765 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18767 if(target->GetGUID() == m_comboTarget)
18769 m_comboPoints += count;
18771 else
18773 if(m_comboTarget)
18774 if(Unit* target2 = ObjectAccessor::GetUnit(*this,m_comboTarget))
18775 target2->RemoveComboPointHolder(GetGUIDLow());
18777 m_comboTarget = target->GetGUID();
18778 m_comboPoints = count;
18780 target->AddComboPointHolder(GetGUIDLow());
18783 if (m_comboPoints > 5) m_comboPoints = 5;
18784 if (m_comboPoints < 0) m_comboPoints = 0;
18786 SendComboPoints();
18789 void Player::ClearComboPoints()
18791 if(!m_comboTarget)
18792 return;
18794 // without combopoints lost (duration checked in aura)
18795 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
18797 m_comboPoints = 0;
18799 SendComboPoints();
18801 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
18802 target->RemoveComboPointHolder(GetGUIDLow());
18804 m_comboTarget = 0;
18807 void Player::SetGroup(Group *group, int8 subgroup)
18809 if(group == NULL)
18810 m_group.unlink();
18811 else
18813 // never use SetGroup without a subgroup unless you specify NULL for group
18814 assert(subgroup >= 0);
18815 m_group.link(group, this);
18816 m_group.setSubGroup((uint8)subgroup);
18820 void Player::SendInitialPacketsBeforeAddToMap()
18822 GetSocial()->SendSocialList();
18824 // Homebind
18825 WorldPacket data(SMSG_BINDPOINTUPDATE, 5*4);
18826 data << m_homebindX << m_homebindY << m_homebindZ;
18827 data << (uint32) m_homebindMapId;
18828 data << (uint32) m_homebindZoneId;
18829 GetSession()->SendPacket(&data);
18831 // SMSG_SET_PROFICIENCY
18832 // SMSG_SET_PCT_SPELL_MODIFIER
18833 // SMSG_SET_FLAT_SPELL_MODIFIER
18835 SendTalentsInfoData(false);
18837 data.Initialize(SMSG_INSTANCE_DIFFICULTY, 4+4);
18838 data << uint32(0);
18839 data << uint32(0);
18840 GetSession()->SendPacket(&data);
18842 SendInitialSpells();
18844 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
18845 data << uint32(0); // count, for(count) uint32;
18846 GetSession()->SendPacket(&data);
18848 SendInitialActionButtons();
18849 m_reputationMgr.SendInitialReputations();
18851 if(!isAlive())
18852 SendCorpseReclaimDelay(true);
18854 SendInitWorldStates(GetZoneId(), GetAreaId());
18856 SendEquipmentSetList();
18858 m_achievementMgr.SendAllAchievementData();
18860 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 4 + 4 + 4);
18861 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
18862 data << (float)0.01666667f; // game speed
18863 data << uint32(0); // added in 3.1.2
18864 GetSession()->SendPacket( &data );
18866 // SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...)
18867 // SMSG_PET_GUIDS
18868 // SMSG_POWER_UPDATE
18870 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
18871 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || HasAuraType(SPELL_AURA_FLY) || isInFlight())
18872 m_movementInfo.AddMovementFlag(MOVEFLAG_FLYING);
18874 m_mover = this;
18877 void Player::SendInitialPacketsAfterAddToMap()
18879 // update zone
18880 uint32 newzone, newarea;
18881 GetZoneAndAreaId(newzone,newarea);
18882 UpdateZone(newzone,newarea); // also call SendInitWorldStates();
18884 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
18885 data << uint32(0x00000000); // on blizz it increments periodically
18886 GetSession()->SendPacket(&data);
18888 CastSpell(this, 836, true); // LOGINEFFECT
18890 // set some aura effects that send packet to player client after add player to map
18891 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
18892 // same auras state lost at far teleport, send it one more time in this case also
18893 static const AuraType auratypes[] =
18895 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
18896 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
18897 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
18899 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
18901 Unit::AuraList const& auraList = GetAurasByType(*itr);
18902 if(!auraList.empty())
18903 auraList.front()->ApplyModifier(true,true);
18906 if(HasAuraType(SPELL_AURA_MOD_STUN))
18907 SetMovement(MOVE_ROOT);
18909 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
18910 if(HasAuraType(SPELL_AURA_MOD_ROOT))
18912 WorldPacket data2(SMSG_FORCE_MOVE_ROOT, 10);
18913 data2.append(GetPackGUID());
18914 data2 << (uint32)2;
18915 SendMessageToSet(&data2,true);
18918 SendAurasForTarget(this);
18919 SendEnchantmentDurations(); // must be after add to map
18920 SendItemDurations(); // must be after add to map
18923 void Player::SendUpdateToOutOfRangeGroupMembers()
18925 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
18926 return;
18927 if(Group* group = GetGroup())
18928 group->UpdatePlayerOutOfRange(this);
18930 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
18931 m_auraUpdateMask = 0;
18932 if(Pet *pet = GetPet())
18933 pet->ResetAuraUpdateMask();
18936 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
18938 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
18939 data << uint32(mapid);
18940 data << uint8(reason); // transfer abort reason
18941 switch(reason)
18943 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
18944 case TRANSFER_ABORT_DIFFICULTY:
18945 case TRANSFER_ABORT_UNIQUE_MESSAGE:
18946 data << uint8(arg);
18947 break;
18949 GetSession()->SendPacket(&data);
18952 void Player::SendInstanceResetWarning( uint32 mapid, Difficulty difficulty, uint32 time )
18954 // type of warning, based on the time remaining until reset
18955 uint32 type;
18956 if(time > 3600)
18957 type = RAID_INSTANCE_WELCOME;
18958 else if(time > 900 && time <= 3600)
18959 type = RAID_INSTANCE_WARNING_HOURS;
18960 else if(time > 300 && time <= 900)
18961 type = RAID_INSTANCE_WARNING_MIN;
18962 else
18963 type = RAID_INSTANCE_WARNING_MIN_SOON;
18965 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4+4);
18966 data << uint32(type);
18967 data << uint32(mapid);
18968 data << uint32(difficulty); // difficulty
18969 data << uint32(time);
18970 if(type == RAID_INSTANCE_WELCOME)
18972 data << uint8(0); // is your (1)
18973 data << uint8(0); // is extended (1), ignored if prev field is 0
18975 GetSession()->SendPacket(&data);
18978 void Player::ApplyEquipCooldown( Item * pItem )
18980 for(int i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i)
18982 _Spell const& spellData = pItem->GetProto()->Spells[i];
18984 // no spell
18985 if( !spellData.SpellId )
18986 continue;
18988 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18989 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
18990 continue;
18992 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
18994 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
18995 data << pItem->GetGUID();
18996 data << uint32(spellData.SpellId);
18997 GetSession()->SendPacket(&data);
19001 void Player::resetSpells()
19003 // not need after this call
19004 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
19005 RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS,true);
19007 // make full copy of map (spells removed and marked as deleted at another spell remove
19008 // and we can't use original map for safe iterative with visit each spell at loop end
19009 PlayerSpellMap smap = GetSpellMap();
19011 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
19012 removeSpell(iter->first,false,false); // only iter->first can be accessed, object by iter->second can be deleted already
19014 learnDefaultSpells();
19015 learnQuestRewardedSpells();
19018 void Player::learnDefaultSpells()
19020 // learn default race/class spells
19021 PlayerInfo const *info = sObjectMgr.GetPlayerInfo(getRace(),getClass());
19022 for (PlayerCreateInfoSpells::const_iterator itr = info->spell.begin(); itr!=info->spell.end(); ++itr)
19024 uint32 tspell = *itr;
19025 sLog.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell);
19026 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
19027 addSpell(tspell,true,true,true,false);
19028 else // but send in normal spell in game learn case
19029 learnSpell(tspell,true);
19033 void Player::learnQuestRewardedSpells(Quest const* quest)
19035 uint32 spell_id = quest->GetRewSpellCast();
19037 // skip quests without rewarded spell
19038 if( !spell_id )
19039 return;
19041 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
19042 if(!spellInfo)
19043 return;
19045 // check learned spells state
19046 bool found = false;
19047 for(int i=0; i < 3; ++i)
19049 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
19051 found = true;
19052 break;
19056 // skip quests with not teaching spell or already known spell
19057 if(!found)
19058 return;
19060 // prevent learn non first rank unknown profession and second specialization for same profession)
19061 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
19062 if( sSpellMgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
19064 // not have first rank learned (unlearned prof?)
19065 uint32 first_spell = sSpellMgr.GetFirstSpellInChain(learned_0);
19066 if( !HasSpell(first_spell) )
19067 return;
19069 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
19070 if(!learnedInfo)
19071 return;
19073 // specialization
19074 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
19076 // search other specialization for same prof
19077 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
19079 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
19080 continue;
19082 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
19083 if(!itrInfo)
19084 return;
19086 // compare only specializations
19087 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
19088 continue;
19090 // compare same chain spells
19091 if(sSpellMgr.GetFirstSpellInChain(itr->first) != first_spell)
19092 continue;
19094 // now we have 2 specialization, learn possible only if found is lesser specialization rank
19095 if(!sSpellMgr.IsHighRankOfSpell(learned_0,itr->first))
19096 return;
19101 CastSpell( this, spell_id, true);
19104 void Player::learnQuestRewardedSpells()
19106 // learn spells received from quest completing
19107 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
19109 // skip no rewarded quests
19110 if(!itr->second.m_rewarded)
19111 continue;
19113 Quest const* quest = sObjectMgr.GetQuestTemplate(itr->first);
19114 if( !quest )
19115 continue;
19117 learnQuestRewardedSpells(quest);
19121 void Player::learnSkillRewardedSpells(uint32 skill_id, uint32 skill_value )
19123 uint32 raceMask = getRaceMask();
19124 uint32 classMask = getClassMask();
19125 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
19127 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
19128 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
19129 continue;
19130 // Check race if set
19131 if (pAbility->racemask && !(pAbility->racemask & raceMask))
19132 continue;
19133 // Check class if set
19134 if (pAbility->classmask && !(pAbility->classmask & classMask))
19135 continue;
19137 if (sSpellStore.LookupEntry(pAbility->spellId))
19139 // need unlearn spell
19140 if (skill_value < pAbility->req_skill_value)
19141 removeSpell(pAbility->spellId);
19142 // need learn
19143 else if (!IsInWorld())
19144 addSpell(pAbility->spellId,true,true,true,false);
19145 else
19146 learnSpell(pAbility->spellId,true);
19151 void Player::SendAurasForTarget(Unit *target)
19153 if(target->GetVisibleAuras()->empty()) // speedup things
19154 return;
19156 WorldPacket data(SMSG_AURA_UPDATE_ALL);
19157 data.append(target->GetPackGUID());
19159 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
19160 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
19162 for(uint32 j = 0; j < 3; ++j)
19164 if(Aura *aura = target->GetAura(itr->second, j))
19166 data << uint8(aura->GetAuraSlot());
19167 data << uint32(aura->GetId());
19169 if(aura->GetId())
19171 uint8 auraFlags = aura->GetAuraFlags();
19172 // flags
19173 data << uint8(auraFlags);
19174 // level
19175 data << uint8(aura->GetAuraLevel());
19176 // charges
19177 if (aura->GetAuraCharges())
19178 data << uint8(aura->GetAuraCharges() * aura->GetStackAmount());
19179 else
19180 data << uint8(aura->GetStackAmount());
19182 if(!(auraFlags & AFLAG_NOT_CASTER))
19184 data << uint8(0); // packed GUID of someone (caster?)
19187 if(auraFlags & AFLAG_DURATION) // include aura duration
19189 data << uint32(aura->GetAuraMaxDuration());
19190 data << uint32(aura->GetAuraDuration());
19193 break;
19198 GetSession()->SendPacket(&data);
19201 void Player::SetDailyQuestStatus( uint32 quest_id )
19203 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
19205 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
19207 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
19208 m_lastDailyQuestTime = time(NULL); // last daily quest time
19209 m_DailyQuestChanged = true;
19210 break;
19215 void Player::ResetDailyQuestStatus()
19217 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
19218 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
19220 // DB data deleted in caller
19221 m_DailyQuestChanged = false;
19222 m_lastDailyQuestTime = 0;
19225 BattleGround* Player::GetBattleGround() const
19227 if(GetBattleGroundId()==0)
19228 return NULL;
19230 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId(), m_bgData.bgTypeID);
19233 bool Player::InArena() const
19235 BattleGround *bg = GetBattleGround();
19236 if(!bg || !bg->isArena())
19237 return false;
19239 return true;
19242 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId) const
19244 // get a template bg instead of running one
19245 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
19246 if(!bg)
19247 return false;
19249 // limit check leel to dbc compatible level range
19250 uint32 level = getLevel();
19251 if (level > DEFAULT_MAX_LEVEL)
19252 level = DEFAULT_MAX_LEVEL;
19254 if(level < bg->GetMinLevel() || level > bg->GetMaxLevel())
19255 return false;
19257 return true;
19260 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
19262 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
19263 if(!vendor_faction || !vendor_faction->faction)
19264 return 1.0f;
19266 ReputationRank rank = GetReputationRank(vendor_faction->faction);
19267 if(rank <= REP_NEUTRAL)
19268 return 1.0f;
19270 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
19273 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
19275 uint32 racemask = getRaceMask();
19276 uint32 classmask = getClassMask();
19278 SkillLineAbilityMapBounds bounds = sSpellMgr.GetSkillLineAbilityMapBounds(spell_id);
19279 if (bounds.first==bounds.second)
19280 return true;
19282 for(SkillLineAbilityMap::const_iterator _spell_idx = bounds.first; _spell_idx != bounds.second; ++_spell_idx)
19284 // skip wrong race skills
19285 if (_spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
19286 continue;
19288 // skip wrong class skills
19289 if (_spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
19290 continue;
19292 return true;
19295 return false;
19298 bool Player::HasQuestForGO(int32 GOId) const
19300 for( int i = 0; i < MAX_QUEST_LOG_SIZE; ++i )
19302 uint32 questid = GetQuestSlotQuestId(i);
19303 if ( questid == 0 )
19304 continue;
19306 QuestStatusMap::const_iterator qs_itr = mQuestStatus.find(questid);
19307 if(qs_itr == mQuestStatus.end())
19308 continue;
19310 QuestStatusData const& qs = qs_itr->second;
19312 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
19314 Quest const* qinfo = sObjectMgr.GetQuestTemplate(questid);
19315 if(!qinfo)
19316 continue;
19318 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
19319 continue;
19321 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; ++j)
19323 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
19324 continue;
19326 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
19327 return true;
19331 return false;
19334 void Player::UpdateForQuestWorldObjects()
19336 if(m_clientGUIDs.empty())
19337 return;
19339 UpdateData udata;
19340 WorldPacket packet;
19341 for(ClientGUIDs::const_iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
19343 if(IS_GAMEOBJECT_GUID(*itr))
19345 GameObject *obj = GetMap()->GetGameObject(*itr);
19346 if(obj)
19347 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
19349 else if(IS_CREATURE_GUID(*itr) || IS_VEHICLE_GUID(*itr))
19351 Creature *obj = GetMap()->GetCreatureOrPetOrVehicle(*itr);
19352 if(!obj)
19353 continue;
19355 // check if this unit requires quest specific flags
19356 if(!obj->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
19357 continue;
19359 SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(obj->GetEntry());
19360 for(SpellClickInfoMap::const_iterator _itr = clickPair.first; _itr != clickPair.second; ++_itr)
19362 if(_itr->second.questStart || _itr->second.questEnd)
19364 obj->BuildCreateUpdateBlockForPlayer(&udata,this);
19365 break;
19370 udata.BuildPacket(&packet);
19371 GetSession()->SendPacket(&packet);
19374 void Player::SummonIfPossible(bool agree)
19376 if(!agree)
19378 m_summon_expire = 0;
19379 return;
19382 // expire and auto declined
19383 if(m_summon_expire < time(NULL))
19384 return;
19386 // stop taxi flight at summon
19387 if(isInFlight())
19389 GetMotionMaster()->MovementExpired();
19390 m_taxi.ClearTaxiDestinations();
19393 // drop flag at summon
19394 // this code can be reached only when GM is summoning player who carries flag, because player should be immune to summoning spells when he carries flag
19395 if(BattleGround *bg = GetBattleGround())
19396 bg->EventPlayerDroppedFlag(this);
19398 m_summon_expire = 0;
19400 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS, 1);
19402 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
19405 void Player::RemoveItemDurations( Item *item )
19407 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
19409 if(*itr==item)
19411 m_itemDuration.erase(itr);
19412 break;
19417 void Player::AddItemDurations( Item *item )
19419 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
19421 m_itemDuration.push_back(item);
19422 item->SendTimeUpdate(this);
19426 void Player::AutoUnequipOffhandIfNeed()
19428 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
19429 if(!offItem)
19430 return;
19432 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
19433 if (CanTitanGrip() || (offItem->GetProto()->InventoryType != INVTYPE_2HWEAPON && !IsTwoHandUsed()))
19434 return;
19436 ItemPosCountVec off_dest;
19437 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
19438 if( off_msg == EQUIP_ERR_OK )
19440 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
19441 StoreItem( off_dest, offItem, true );
19443 else
19445 MoveItemFromInventory(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
19446 CharacterDatabase.BeginTransaction();
19447 offItem->DeleteFromInventoryDB(); // deletes item from character's inventory
19448 offItem->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
19449 CharacterDatabase.CommitTransaction();
19451 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
19452 MailDraft(subject).AddItem(offItem).SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM));
19456 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
19458 if(spellInfo->EquippedItemClass < 0)
19459 return true;
19461 // scan other equipped items for same requirements (mostly 2 daggers/etc)
19462 // for optimize check 2 used cases only
19463 switch(spellInfo->EquippedItemClass)
19465 case ITEM_CLASS_WEAPON:
19467 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
19468 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
19469 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19470 return true;
19471 break;
19473 case ITEM_CLASS_ARMOR:
19475 // tabard not have dependent spells
19476 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
19477 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
19478 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19479 return true;
19481 // shields can be equipped to offhand slot
19482 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
19483 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19484 return true;
19486 // ranged slot can have some armor subclasses
19487 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
19488 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
19489 return true;
19491 break;
19493 default:
19494 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
19495 break;
19498 return false;
19501 bool Player::CanNoReagentCast(SpellEntry const* spellInfo) const
19503 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
19504 if (spellInfo->AttributesEx5 & SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP &&
19505 HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PREPARATION))
19506 return true;
19508 // Check no reagent use mask
19509 uint64 noReagentMask_0_1 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1);
19510 uint32 noReagentMask_2 = GetUInt64Value(PLAYER_NO_REAGENT_COST_1+2);
19511 if (spellInfo->SpellFamilyFlags & noReagentMask_0_1 ||
19512 spellInfo->SpellFamilyFlags2 & noReagentMask_2)
19513 return true;
19515 return false;
19518 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
19520 AuraMap& auras = GetAuras();
19521 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); )
19523 Aura* aura = itr->second;
19525 // skip passive (passive item dependent spells work in another way) and not self applied auras
19526 SpellEntry const* spellInfo = aura->GetSpellProto();
19527 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
19529 ++itr;
19530 continue;
19533 // skip if not item dependent or have alternative item
19534 if(HasItemFitToSpellReqirements(spellInfo,pItem))
19536 ++itr;
19537 continue;
19540 // no alt item, remove aura, restart check
19541 RemoveAurasDueToSpell(aura->GetId());
19542 itr = auras.begin();
19545 // currently casted spells can be dependent from item
19546 for (uint32 i = 0; i < CURRENT_MAX_SPELL; ++i)
19547 if (Spell* spell = GetCurrentSpell(CurrentSpellTypes(i)))
19548 if (spell->getState()!=SPELL_STATE_DELAYED && !HasItemFitToSpellReqirements(spell->m_spellInfo,pItem) )
19549 InterruptSpell(CurrentSpellTypes(i));
19552 uint32 Player::GetResurrectionSpellId()
19554 // search priceless resurrection possibilities
19555 uint32 prio = 0;
19556 uint32 spell_id = 0;
19557 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
19558 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
19560 // Soulstone Resurrection // prio: 3 (max, non death persistent)
19561 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
19563 switch((*itr)->GetId())
19565 case 20707: spell_id = 3026; break; // rank 1
19566 case 20762: spell_id = 20758; break; // rank 2
19567 case 20763: spell_id = 20759; break; // rank 3
19568 case 20764: spell_id = 20760; break; // rank 4
19569 case 20765: spell_id = 20761; break; // rank 5
19570 case 27239: spell_id = 27240; break; // rank 6
19571 case 47883: spell_id = 47882; break; // rank 7
19572 default:
19573 sLog.outError("Unhandled spell %u: S.Resurrection",(*itr)->GetId());
19574 continue;
19577 prio = 3;
19579 // Twisting Nether // prio: 2 (max)
19580 else if((*itr)->GetId()==23701 && roll_chance_i(10))
19582 prio = 2;
19583 spell_id = 23700;
19587 // Reincarnation (passive spell) // prio: 1
19588 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
19589 spell_id = 21169;
19591 return spell_id;
19594 // Used in triggers for check "Only to targets that grant experience or honor" req
19595 bool Player::isHonorOrXPTarget(Unit* pVictim)
19597 uint32 v_level = pVictim->getLevel();
19598 uint32 k_grey = MaNGOS::XP::GetGrayLevel(getLevel());
19600 // Victim level less gray level
19601 if(v_level<=k_grey)
19602 return false;
19604 if(pVictim->GetTypeId() == TYPEID_UNIT)
19606 if (((Creature*)pVictim)->isTotem() ||
19607 ((Creature*)pVictim)->isPet() ||
19608 ((Creature*)pVictim)->GetCreatureInfo()->flags_extra & CREATURE_FLAG_EXTRA_NO_XP_AT_KILL)
19609 return false;
19611 return true;
19614 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
19616 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
19618 // prepare data for near group iteration (PvP and !PvP cases)
19619 uint32 xp = 0;
19620 bool honored_kill = false;
19622 if(Group *pGroup = GetGroup())
19624 uint32 count = 0;
19625 uint32 sum_level = 0;
19626 Player* member_with_max_level = NULL;
19627 Player* not_gray_member_with_max_level = NULL;
19629 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
19631 if(member_with_max_level)
19633 /// not get Xp in PvP or no not gray players in group
19634 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
19636 /// skip in check PvP case (for speed, not used)
19637 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
19638 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
19639 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
19641 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19643 Player* pGroupGuy = itr->getSource();
19644 if(!pGroupGuy)
19645 continue;
19647 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
19648 continue; // member (alive or dead) or his corpse at req. distance
19650 // honor can be in PvP and !PvP (racial leader) cases (for alive)
19651 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
19652 honored_kill = true;
19654 // xp and reputation only in !PvP case
19655 if(!PvP)
19657 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
19659 // if is in dungeon then all receive full reputation at kill
19660 // rewarded any alive/dead/near_corpse group member
19661 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
19663 // XP updated only for alive group member
19664 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
19665 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
19667 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
19669 pGroupGuy->GiveXP(itr_xp, pVictim);
19670 if(Pet* pet = pGroupGuy->GetPet())
19671 pet->GivePetXP(itr_xp/2);
19674 // quest objectives updated only for alive group member or dead but with not released body
19675 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
19677 // normal creature (not pet/etc) can be only in !PvP case
19678 if(pVictim->GetTypeId()==TYPEID_UNIT)
19679 pGroupGuy->KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
19685 else // if (!pGroup)
19687 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
19689 // honor can be in PvP and !PvP (racial leader) cases
19690 if(RewardHonor(pVictim,1))
19691 honored_kill = true;
19693 // xp and reputation only in !PvP case
19694 if(!PvP)
19696 RewardReputation(pVictim,1);
19697 GiveXP(xp, pVictim);
19699 if(Pet* pet = GetPet())
19700 pet->GivePetXP(xp);
19702 // normal creature (not pet/etc) can be only in !PvP case
19703 if(pVictim->GetTypeId()==TYPEID_UNIT)
19704 KilledMonster(((Creature*)pVictim)->GetCreatureInfo(), pVictim->GetGUID());
19707 return xp || honored_kill;
19710 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id, WorldObject* pRewardSource)
19712 uint64 creature_guid = pRewardSource->GetTypeId()==TYPEID_UNIT ? pRewardSource->GetGUID() : uint64(0);
19714 // prepare data for near group iteration
19715 if(Group *pGroup = GetGroup())
19717 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19719 Player* pGroupGuy = itr->getSource();
19720 if(!pGroupGuy)
19721 continue;
19723 if(!pGroupGuy->IsAtGroupRewardDistance(pRewardSource))
19724 continue; // member (alive or dead) or his corpse at req. distance
19726 // quest objectives updated only for alive group member or dead but with not released body
19727 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
19728 pGroupGuy->KilledMonsterCredit(creature_id, creature_guid);
19731 else // if (!pGroup)
19732 KilledMonsterCredit(creature_id, creature_guid);
19735 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
19737 if (pRewardSource->IsWithinDistInMap(this,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE)))
19738 return true;
19740 if (isAlive())
19741 return false;
19743 Corpse* corpse = GetCorpse();
19744 if (!corpse)
19745 return false;
19747 return pRewardSource->IsWithinDistInMap(corpse,sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE));
19750 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
19752 Item* item = GetWeaponForAttack(attType,true,true);
19754 // unarmed only with base attack
19755 if(attType != BASE_ATTACK && !item)
19756 return 0;
19758 // weapon skill or (unarmed for base attack)
19759 uint32 skill = item ? item->GetSkill() : uint32(SKILL_UNARMED);
19760 return GetBaseSkillValue(skill);
19763 void Player::ResurectUsingRequestData()
19765 /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
19766 if(IS_PLAYER_GUID(m_resurrectGUID))
19767 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
19769 //we cannot resurrect player when we triggered far teleport
19770 //player will be resurrected upon teleportation
19771 if(IsBeingTeleportedFar())
19773 ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER);
19774 return;
19777 ResurrectPlayer(0.0f,false);
19779 if(GetMaxHealth() > m_resurrectHealth)
19780 SetHealth( m_resurrectHealth );
19781 else
19782 SetHealth( GetMaxHealth() );
19784 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
19785 SetPower(POWER_MANA, m_resurrectMana );
19786 else
19787 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
19789 SetPower(POWER_RAGE, 0 );
19791 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
19793 SpawnCorpseBones();
19796 void Player::SetClientControl(Unit* target, uint8 allowMove)
19798 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
19799 data.append(target->GetPackGUID());
19800 data << uint8(allowMove);
19801 GetSession()->SendPacket(&data);
19804 void Player::UpdateZoneDependentAuras( uint32 newZone )
19806 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
19807 SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAreaMapBounds(newZone);
19808 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19809 if(itr->second->autocast && itr->second->IsFitToRequirements(this,newZone,0))
19810 if( !HasAura(itr->second->spellId,0) )
19811 CastSpell(this,itr->second->spellId,true);
19814 void Player::UpdateAreaDependentAuras( uint32 newArea )
19816 // remove auras from spells with area limitations
19817 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
19819 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
19820 if(sSpellMgr.GetSpellAllowedInLocationError(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea,this) != SPELL_CAST_OK)
19821 RemoveAura(iter);
19822 else
19823 ++iter;
19826 // some auras applied at subzone enter
19827 SpellAreaForAreaMapBounds saBounds = sSpellMgr.GetSpellAreaForAreaMapBounds(newArea);
19828 for(SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr)
19829 if(itr->second->autocast && itr->second->IsFitToRequirements(this,m_zoneUpdateId,newArea))
19830 if( !HasAura(itr->second->spellId,0) )
19831 CastSpell(this,itr->second->spellId,true);
19834 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
19836 if ((pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
19837 (!pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
19839 return copseReclaimDelay[0];
19842 time_t now = time(NULL);
19843 // 0..2 full period
19844 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
19845 return copseReclaimDelay[count];
19848 void Player::UpdateCorpseReclaimDelay()
19850 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
19852 if ((pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP)) ||
19853 (!pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) ))
19854 return;
19856 time_t now = time(NULL);
19857 if(now < m_deathExpireTime)
19859 // full and partly periods 1..3
19860 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
19861 if(count < MAX_DEATH_COUNT)
19862 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
19863 else
19864 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
19866 else
19867 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
19870 void Player::SendCorpseReclaimDelay(bool load)
19872 Corpse* corpse = GetCorpse();
19873 if(!corpse)
19874 return;
19876 uint32 delay;
19877 if(load)
19879 if(corpse->GetGhostTime() > m_deathExpireTime)
19880 return;
19882 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
19884 uint32 count;
19885 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
19886 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
19888 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
19889 if(count>=MAX_DEATH_COUNT)
19890 count = MAX_DEATH_COUNT-1;
19892 else
19893 count=0;
19895 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
19897 time_t now = time(NULL);
19898 if(now >= expected_time)
19899 return;
19901 delay = expected_time-now;
19903 else
19904 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
19906 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19907 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
19908 data << uint32(delay*IN_MILISECONDS);
19909 GetSession()->SendPacket( &data );
19912 Player* Player::GetNextRandomRaidMember(float radius)
19914 Group *pGroup = GetGroup();
19915 if(!pGroup)
19916 return NULL;
19918 std::vector<Player*> nearMembers;
19919 nearMembers.reserve(pGroup->GetMembersCount());
19921 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
19923 Player* Target = itr->getSource();
19925 // IsHostileTo check duel and controlled by enemy
19926 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
19927 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
19928 nearMembers.push_back(Target);
19931 if (nearMembers.empty())
19932 return NULL;
19934 uint32 randTarget = urand(0,nearMembers.size()-1);
19935 return nearMembers[randTarget];
19938 PartyResult Player::CanUninviteFromGroup() const
19940 const Group* grp = GetGroup();
19941 if(!grp)
19942 return PARTY_RESULT_YOU_NOT_IN_GROUP;
19944 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
19945 return PARTY_RESULT_YOU_NOT_LEADER;
19947 if(InBattleGround())
19948 return PARTY_RESULT_INVITE_RESTRICTED;
19950 return PARTY_RESULT_OK;
19953 void Player::SetBattleGroundRaid(Group* group, int8 subgroup)
19955 //we must move references from m_group to m_originalGroup
19956 SetOriginalGroup(GetGroup(), GetSubGroup());
19958 m_group.unlink();
19959 m_group.link(group, this);
19960 m_group.setSubGroup((uint8)subgroup);
19963 void Player::RemoveFromBattleGroundRaid()
19965 //remove existing reference
19966 m_group.unlink();
19967 if( Group* group = GetOriginalGroup() )
19969 m_group.link(group, this);
19970 m_group.setSubGroup(GetOriginalSubGroup());
19972 SetOriginalGroup(NULL);
19975 void Player::SetOriginalGroup(Group *group, int8 subgroup)
19977 if( group == NULL )
19978 m_originalGroup.unlink();
19979 else
19981 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
19982 assert(subgroup >= 0);
19983 m_originalGroup.link(group, this);
19984 m_originalGroup.setSubGroup((uint8)subgroup);
19988 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
19990 LiquidData liquid_status;
19991 ZLiquidStatus res = m->getLiquidStatus(x, y, z, MAP_ALL_LIQUIDS, &liquid_status);
19992 if (!res)
19994 m_MirrorTimerFlags &= ~(UNDERWATER_INWATER|UNDERWATER_INLAVA|UNDERWATER_INSLIME|UNDERWARER_INDARKWATER);
19995 // Small hack for enable breath in WMO
19996 if (IsInWater())
19997 m_MirrorTimerFlags|=UNDERWATER_INWATER;
19998 return;
20001 // All liquids type - check under water position
20002 if (liquid_status.type&(MAP_LIQUID_TYPE_WATER|MAP_LIQUID_TYPE_OCEAN|MAP_LIQUID_TYPE_MAGMA|MAP_LIQUID_TYPE_SLIME))
20004 if ( res & LIQUID_MAP_UNDER_WATER)
20005 m_MirrorTimerFlags |= UNDERWATER_INWATER;
20006 else
20007 m_MirrorTimerFlags &= ~UNDERWATER_INWATER;
20010 // Allow travel in dark water on taxi or transport
20011 if ((liquid_status.type & MAP_LIQUID_TYPE_DARK_WATER) && !isInFlight() && !GetTransport())
20012 m_MirrorTimerFlags |= UNDERWARER_INDARKWATER;
20013 else
20014 m_MirrorTimerFlags &= ~UNDERWARER_INDARKWATER;
20016 // in lava check, anywhere in lava level
20017 if (liquid_status.type&MAP_LIQUID_TYPE_MAGMA)
20019 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
20020 m_MirrorTimerFlags |= UNDERWATER_INLAVA;
20021 else
20022 m_MirrorTimerFlags &= ~UNDERWATER_INLAVA;
20024 // in slime check, anywhere in slime level
20025 if (liquid_status.type&MAP_LIQUID_TYPE_SLIME)
20027 if (res & (LIQUID_MAP_UNDER_WATER|LIQUID_MAP_IN_WATER|LIQUID_MAP_WATER_WALK))
20028 m_MirrorTimerFlags |= UNDERWATER_INSLIME;
20029 else
20030 m_MirrorTimerFlags &= ~UNDERWATER_INSLIME;
20034 void Player::SetCanParry( bool value )
20036 if(m_canParry==value)
20037 return;
20039 m_canParry = value;
20040 UpdateParryPercentage();
20043 void Player::SetCanBlock( bool value )
20045 if(m_canBlock==value)
20046 return;
20048 m_canBlock = value;
20049 UpdateBlockPercentage();
20052 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
20054 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
20055 if(itr->pos == pos)
20056 return true;
20058 return false;
20061 bool Player::CanUseBattleGroundObject()
20063 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
20064 // maybe gameobject code should handle that ForceReaction usage
20065 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
20066 return ( //InBattleGround() && // in battleground - not need, check in other cases
20067 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
20068 //player cannot use object when he is invulnerable (immune)
20069 !isTotalImmune() && // not totally immune
20070 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
20071 !HasStealthAura() && // not stealthed
20072 !HasInvisibilityAura() && // not invisible
20073 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
20074 isAlive() // live player
20078 bool Player::CanCaptureTowerPoint()
20080 return ( !HasStealthAura() && // not stealthed
20081 !HasInvisibilityAura() && // not invisible
20082 isAlive() // live player
20086 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
20088 uint32 level = getLevel();
20090 if(level > GT_MAX_LEVEL)
20091 level = GT_MAX_LEVEL; // max level in this dbc
20093 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
20094 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
20095 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
20097 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
20098 return 0;
20100 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
20102 if(!bsc) // shouldn't happen
20103 return 0xFFFFFFFF;
20105 float cost = 0;
20107 if(hairstyle != newhairstyle)
20108 cost += bsc->cost; // full price
20110 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
20111 cost += bsc->cost * 0.5f; // +1/2 of price
20113 if(facialhair != newfacialhair)
20114 cost += bsc->cost * 0.75f; // +3/4 of price
20116 return uint32(cost);
20119 void Player::InitGlyphsForLevel()
20121 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
20122 if(GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i))
20123 if(gs->Order)
20124 SetGlyphSlot(gs->Order - 1, gs->Id);
20126 uint32 level = getLevel();
20127 uint32 value = 0;
20129 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
20130 if(level >= 15)
20131 value |= (0x01 | 0x02);
20132 if(level >= 30)
20133 value |= 0x08;
20134 if(level >= 50)
20135 value |= 0x04;
20136 if(level >= 70)
20137 value |= 0x10;
20138 if(level >= 80)
20139 value |= 0x20;
20141 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
20144 void Player::EnterVehicle(Vehicle *vehicle)
20146 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
20147 if(!ve)
20148 return;
20150 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
20151 if(!veSeat)
20152 return;
20154 vehicle->SetCharmerGUID(GetGUID());
20155 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
20156 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
20157 vehicle->setFaction(getFaction());
20159 SetCharm(vehicle); // charm
20160 SetFarSightGUID(vehicle->GetGUID()); // set view
20162 SetClientControl(vehicle, 1); // redirect controls to vehicle
20163 SetMover(vehicle);
20165 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
20166 GetSession()->SendPacket(&data);
20168 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
20169 data.append(GetPackGUID());
20170 data << uint32(0); // counter?
20171 data << uint32(MOVEFLAG_ONTRANSPORT); // transport
20172 data << uint16(0); // special flags
20173 data << uint32(getMSTime()); // time
20174 data << vehicle->GetPositionX(); // x
20175 data << vehicle->GetPositionY(); // y
20176 data << vehicle->GetPositionZ(); // z
20177 data << vehicle->GetOrientation(); // o
20178 // transport part, TODO: load/calculate seat offsets
20179 data << uint64(vehicle->GetGUID()); // transport guid
20180 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
20181 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
20182 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
20183 data << float(0); // transport orientation
20184 data << uint32(getMSTime()); // transport time
20185 data << uint8(0); // seat
20186 // end of transport part
20187 data << uint32(0); // fall time
20188 GetSession()->SendPacket(&data);
20190 data.Initialize(SMSG_PET_SPELLS, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX+1+1);
20191 data << uint64(vehicle->GetGUID());
20192 data << uint16(0);
20193 data << uint32(0);
20194 data << uint32(0x00000101);
20196 for(uint32 i = 0; i < 10; ++i)
20197 data << uint16(0) << uint8(0) << uint8(i+8);
20199 data << uint8(0);
20200 data << uint8(0);
20201 GetSession()->SendPacket(&data);
20204 void Player::ExitVehicle(Vehicle *vehicle)
20206 vehicle->SetCharmerGUID(0);
20207 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
20208 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
20209 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
20211 SetCharm(NULL);
20212 SetFarSightGUID(0);
20214 SetClientControl(vehicle, 0);
20215 SetMover(NULL);
20217 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
20218 data.append(GetPackGUID());
20219 data << uint32(0); // counter?
20220 data << uint32(MOVEFLAG_FLY_UNK1); // fly unk
20221 data << uint16(0x40); // special flags
20222 data << uint32(getMSTime()); // time
20223 data << vehicle->GetPositionX(); // x
20224 data << vehicle->GetPositionY(); // y
20225 data << vehicle->GetPositionZ(); // z
20226 data << vehicle->GetOrientation(); // o
20227 data << uint32(0); // fall time
20228 GetSession()->SendPacket(&data);
20230 RemovePetActionBar();
20232 // maybe called at dummy aura remove?
20233 // CastSpell(this, 45472, true); // Parachute
20236 bool Player::isTotalImmune()
20238 AuraList const& immune = GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY);
20240 uint32 immuneMask = 0;
20241 for(AuraList::const_iterator itr = immune.begin(); itr != immune.end(); ++itr)
20243 immuneMask |= (*itr)->GetModifier()->m_miscvalue;
20244 if( immuneMask & SPELL_SCHOOL_MASK_ALL ) // total immunity
20245 return true;
20247 return false;
20250 bool Player::HasTitle(uint32 bitIndex)
20252 if (bitIndex > MAX_TITLE_INDEX)
20253 return false;
20255 uint32 fieldIndexOffset = bitIndex / 32;
20256 uint32 flag = 1 << (bitIndex % 32);
20257 return HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20260 void Player::SetTitle(CharTitlesEntry const* title, bool lost)
20262 uint32 fieldIndexOffset = title->bit_index / 32;
20263 uint32 flag = 1 << (title->bit_index % 32);
20265 if(lost)
20267 if(!HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
20268 return;
20270 RemoveFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20272 else
20274 if(HasFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag))
20275 return;
20277 SetFlag(PLAYER__FIELD_KNOWN_TITLES + fieldIndexOffset, flag);
20280 WorldPacket data(SMSG_TITLE_EARNED, 4 + 4);
20281 data << uint32(title->bit_index);
20282 data << uint32(lost ? 0 : 1); // 1 - earned, 0 - lost
20283 GetSession()->SendPacket(&data);
20286 void Player::ConvertRune(uint8 index, RuneType newType)
20288 SetCurrentRune(index, newType);
20290 WorldPacket data(SMSG_CONVERT_RUNE, 2);
20291 data << uint8(index);
20292 data << uint8(newType);
20293 GetSession()->SendPacket(&data);
20296 void Player::ResyncRunes(uint8 count)
20298 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
20299 for(uint32 i = 0; i < count; ++i)
20301 data << uint8(GetCurrentRune(i)); // rune type
20302 data << uint8(255 - ((GetRuneCooldown(i) / REGEN_TIME_FULL) * 51)); // passed cooldown time (0-255)
20304 GetSession()->SendPacket(&data);
20307 void Player::AddRunePower(uint8 index)
20309 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
20310 data << uint32(1 << index); // mask (0x00-0x3F probably)
20311 GetSession()->SendPacket(&data);
20314 static RuneType runeSlotTypes[MAX_RUNES] = {
20315 /*0*/ RUNE_BLOOD,
20316 /*1*/ RUNE_BLOOD,
20317 /*2*/ RUNE_UNHOLY,
20318 /*3*/ RUNE_UNHOLY,
20319 /*4*/ RUNE_FROST,
20320 /*5*/ RUNE_FROST
20323 void Player::InitRunes()
20325 if(getClass() != CLASS_DEATH_KNIGHT)
20326 return;
20328 m_runes = new Runes;
20330 m_runes->runeState = 0;
20332 for(uint32 i = 0; i < MAX_RUNES; ++i)
20334 SetBaseRune(i, runeSlotTypes[i]); // init base types
20335 SetCurrentRune(i, runeSlotTypes[i]); // init current types
20336 SetRuneCooldown(i, 0); // reset cooldowns
20337 m_runes->SetRuneState(i);
20340 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
20341 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);
20345 bool Player::IsBaseRuneSlotsOnCooldown( RuneType runeType ) const
20347 for(uint32 i = 0; i < MAX_RUNES; ++i)
20348 if (GetBaseRune(i) == runeType && GetRuneCooldown(i) == 0)
20349 return false;
20351 return true;
20354 void Player::AutoStoreLoot(uint8 bag, uint8 slot, uint32 loot_id, LootStore const& store, bool broadcast)
20356 Loot loot;
20357 loot.FillLoot (loot_id,store,this,true);
20359 uint32 max_slot = loot.GetMaxSlotInLootFor(this);
20360 for(uint32 i = 0; i < max_slot; ++i)
20362 LootItem* lootItem = loot.LootItemInSlot(i,this);
20364 ItemPosCountVec dest;
20365 uint8 msg = CanStoreNewItem (bag,slot,dest,lootItem->itemid,lootItem->count);
20366 if(msg != EQUIP_ERR_OK && slot != NULL_SLOT)
20367 msg = CanStoreNewItem( bag, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
20368 if( msg != EQUIP_ERR_OK && bag != NULL_BAG)
20369 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT,dest,lootItem->itemid,lootItem->count);
20370 if(msg != EQUIP_ERR_OK)
20372 SendEquipError( msg, NULL, NULL );
20373 continue;
20376 Item* pItem = StoreNewItem (dest,lootItem->itemid,true,lootItem->randomPropertyId);
20377 SendNewItem(pItem, lootItem->count, false, false, broadcast);
20381 uint32 Player::CalculateTalentsPoints() const
20383 uint32 base_talent = getLevel() < 10 ? 0 : getLevel()-9;
20385 if(getClass() != CLASS_DEATH_KNIGHT)
20386 return uint32(base_talent * sWorld.getRate(RATE_TALENT));
20388 uint32 talentPointsForLevel = getLevel() < 56 ? 0 : getLevel() - 55;
20389 talentPointsForLevel += m_questRewardTalentCount;
20391 if(talentPointsForLevel > base_talent)
20392 talentPointsForLevel = base_talent;
20394 return uint32(talentPointsForLevel * sWorld.getRate(RATE_TALENT));
20397 bool Player::IsKnowHowFlyIn(uint32 mapid, uint32 zone) const
20399 // continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update
20400 uint32 v_map = GetVirtualMapForMapAndZone(mapid, zone);
20401 return v_map != 571 || HasSpell(54197); // Cold Weather Flying
20404 struct DoPlayerLearnSpell
20406 DoPlayerLearnSpell(Player& _player) : player(_player) {}
20407 void operator() (uint32 spell_id) { player.learnSpell(spell_id,false); }
20408 Player& player;
20411 void Player::learnSpellHighRank(uint32 spellid)
20413 learnSpell(spellid,false);
20415 DoPlayerLearnSpell worker(*this);
20416 sSpellMgr.doForHighRanks(spellid,worker);
20419 void Player::_LoadSkills(QueryResult *result)
20421 // 0 1 2
20422 // SetPQuery(PLAYER_LOGIN_QUERY_LOADSKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = '%u'", GUID_LOPART(m_guid));
20424 uint32 count = 0;
20425 if (result)
20429 Field *fields = result->Fetch();
20431 uint16 skill = fields[0].GetUInt16();
20432 uint16 value = fields[1].GetUInt16();
20433 uint16 max = fields[2].GetUInt16();
20435 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(skill);
20436 if(!pSkill)
20438 sLog.outError("Character %u has skill %u that does not exist.", GetGUIDLow(), skill);
20439 continue;
20442 // set fixed skill ranges
20443 switch(GetSkillRangeType(pSkill,false))
20445 case SKILL_RANGE_LANGUAGE: // 300..300
20446 value = max = 300;
20447 break;
20448 case SKILL_RANGE_MONO: // 1..1, grey monolite bar
20449 value = max = 1;
20450 break;
20451 default:
20452 break;
20455 if(value == 0)
20457 sLog.outError("Character %u has skill %u with value 0. Will be deleted.", GetGUIDLow(), skill);
20458 CharacterDatabase.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), skill );
20459 continue;
20462 // enable unlearn button for primary professions only
20463 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
20464 SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,1));
20465 else
20466 SetUInt32Value(PLAYER_SKILL_INDEX(count), MAKE_PAIR32(skill,0));
20468 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),MAKE_SKILL_VALUE(value, max));
20469 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
20471 mSkillStatus.insert(SkillStatusMap::value_type(skill, SkillStatusData(count, SKILL_UNCHANGED)));
20473 learnSkillRewardedSpells(skill, value);
20475 ++count;
20477 if(count >= PLAYER_MAX_SKILLS) // client limit
20479 sLog.outError("Character %u has more than %u skills.", GetGUIDLow(), PLAYER_MAX_SKILLS);
20480 break;
20482 } while (result->NextRow());
20483 delete result;
20486 for (; count < PLAYER_MAX_SKILLS; ++count)
20488 SetUInt32Value(PLAYER_SKILL_INDEX(count), 0);
20489 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count),0);
20490 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count),0);
20493 // special settings
20494 if(getClass()==CLASS_DEATH_KNIGHT)
20496 uint32 base_level = std::min(getLevel(),sWorld.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL));
20497 if(base_level < 1)
20498 base_level = 1;
20499 uint32 base_skill = (base_level-1)*5; // 270 at starting level 55
20500 if(base_skill < 1)
20501 base_skill = 1; // skill mast be known and then > 0 in any case
20503 if(GetPureSkillValue (SKILL_FIRST_AID) < base_skill)
20504 SetSkill(SKILL_FIRST_AID,base_skill, base_skill);
20505 if(GetPureSkillValue (SKILL_AXES) < base_skill)
20506 SetSkill(SKILL_AXES, base_skill,base_skill);
20507 if(GetPureSkillValue (SKILL_DEFENSE) < base_skill)
20508 SetSkill(SKILL_DEFENSE, base_skill,base_skill);
20509 if(GetPureSkillValue (SKILL_POLEARMS) < base_skill)
20510 SetSkill(SKILL_POLEARMS, base_skill,base_skill);
20511 if(GetPureSkillValue (SKILL_SWORDS) < base_skill)
20512 SetSkill(SKILL_SWORDS, base_skill,base_skill);
20513 if(GetPureSkillValue (SKILL_2H_AXES) < base_skill)
20514 SetSkill(SKILL_2H_AXES, base_skill,base_skill);
20515 if(GetPureSkillValue (SKILL_2H_SWORDS) < base_skill)
20516 SetSkill(SKILL_2H_SWORDS, base_skill,base_skill);
20517 if(GetPureSkillValue (SKILL_UNARMED) < base_skill)
20518 SetSkill(SKILL_UNARMED, base_skill,base_skill);
20522 uint32 Player::GetPhaseMaskForSpawn() const
20524 uint32 phase = PHASEMASK_NORMAL;
20525 if(!isGameMaster())
20526 phase = GetPhaseMask();
20527 else
20529 AuraList const& phases = GetAurasByType(SPELL_AURA_PHASE);
20530 if(!phases.empty())
20531 phase = phases.front()->GetMiscValue();
20534 // some aura phases include 1 normal map in addition to phase itself
20535 if(uint32 n_phase = phase & ~PHASEMASK_NORMAL)
20536 return n_phase;
20538 return PHASEMASK_NORMAL;
20541 uint8 Player::CanEquipUniqueItem(Item* pItem, uint8 eslot, uint32 limit_count) const
20543 ItemPrototype const* pProto = pItem->GetProto();
20545 // proto based limitations
20546 if(uint8 res = CanEquipUniqueItem(pProto,eslot,limit_count))
20547 return res;
20549 // check unique-equipped on gems
20550 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
20552 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
20553 if(!enchant_id)
20554 continue;
20555 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
20556 if(!enchantEntry)
20557 continue;
20559 ItemPrototype const* pGem = ObjectMgr::GetItemPrototype(enchantEntry->GemID);
20560 if(!pGem)
20561 continue;
20563 // include for check equip another gems with same limit category for not equipped item (and then not counted)
20564 uint32 gem_limit_count = !pItem->IsEquipped() && pGem->ItemLimitCategory
20565 ? pItem->GetGemCountWithLimitCategory(pGem->ItemLimitCategory) : 1;
20567 if(uint8 res = CanEquipUniqueItem(pGem, eslot,gem_limit_count))
20568 return res;
20571 return EQUIP_ERR_OK;
20574 uint8 Player::CanEquipUniqueItem( ItemPrototype const* itemProto, uint8 except_slot, uint32 limit_count) const
20576 // check unique-equipped on item
20577 if (itemProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
20579 // there is an equip limit on this item
20580 if(HasItemOrGemWithIdEquipped(itemProto->ItemId,1,except_slot))
20581 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
20584 // check unique-equipped limit
20585 if (itemProto->ItemLimitCategory)
20587 ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(itemProto->ItemLimitCategory);
20588 if(!limitEntry)
20589 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
20591 if(limit_count > limitEntry->maxCount)
20592 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE; // attempt add too many limit category items (gems)
20594 // there is an equip limit on this item
20595 if(HasItemOrGemWithLimitCategoryEquipped(itemProto->ItemLimitCategory,limitEntry->maxCount-limit_count+1,except_slot))
20596 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
20599 return EQUIP_ERR_OK;
20602 void Player::HandleFall(MovementInfo const& movementInfo)
20604 // calculate total z distance of the fall
20605 float z_diff = m_lastFallZ - movementInfo.GetPos()->z;
20606 sLog.outDebug("zDiff = %f", z_diff);
20608 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
20609 // 14.57 can be calculated by resolving damageperc formula below to 0
20610 if (z_diff >= 14.57f && !isDead() && !isGameMaster() &&
20611 !HasAuraType(SPELL_AURA_HOVER) && !HasAuraType(SPELL_AURA_FEATHER_FALL) &&
20612 !HasAuraType(SPELL_AURA_FLY) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL) )
20614 //Safe fall, fall height reduction
20615 int32 safe_fall = GetTotalAuraModifier(SPELL_AURA_SAFE_FALL);
20617 float damageperc = 0.018f*(z_diff-safe_fall)-0.2426f;
20619 if(damageperc >0 )
20621 uint32 damage = (uint32)(damageperc * GetMaxHealth()*sWorld.getRate(RATE_DAMAGE_FALL));
20623 float height = movementInfo.GetPos()->z;
20624 UpdateGroundPositionZ(movementInfo.GetPos()->x, movementInfo.GetPos()->y, height);
20626 if (damage > 0)
20628 //Prevent fall damage from being more than the player maximum health
20629 if (damage > GetMaxHealth())
20630 damage = GetMaxHealth();
20632 // Gust of Wind
20633 if (GetDummyAura(43621))
20634 damage = GetMaxHealth()/2;
20636 uint32 original_health = GetHealth();
20637 uint32 final_damage = EnvironmentalDamage(DAMAGE_FALL, damage);
20639 // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
20640 if (isAlive() && final_damage < original_health)
20641 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING, uint32(z_diff*100));
20644 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
20645 DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo.GetPos()->z, height, GetPositionZ(), movementInfo.GetFallTime(), height, damage, safe_fall);
20650 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type, uint32 miscvalue1/*=0*/, uint32 miscvalue2/*=0*/, Unit *unit/*=NULL*/, uint32 time/*=0*/ )
20652 GetAchievementMgr().UpdateAchievementCriteria(type, miscvalue1,miscvalue2,unit,time);
20655 void Player::LearnTalent(uint32 talentId, uint32 talentRank)
20657 uint32 CurTalentPoints = GetFreeTalentPoints();
20659 if(CurTalentPoints == 0)
20660 return;
20662 if (talentRank >= MAX_TALENT_RANK)
20663 return;
20665 TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentId );
20667 if(!talentInfo)
20668 return;
20670 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
20672 if(!talentTabInfo)
20673 return;
20675 // prevent learn talent for different class (cheating)
20676 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
20677 return;
20679 // find current max talent rank
20680 int32 curtalent_maxrank = 0;
20681 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
20683 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
20685 curtalent_maxrank = k + 1;
20686 break;
20690 // we already have same or higher talent rank learned
20691 if(curtalent_maxrank >= (talentRank + 1))
20692 return;
20694 // check if we have enough talent points
20695 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
20696 return;
20698 // Check if it requires another talent
20699 if (talentInfo->DependsOn > 0)
20701 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
20703 bool hasEnoughRank = false;
20704 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
20706 if (depTalentInfo->RankID[i] != 0)
20707 if (HasSpell(depTalentInfo->RankID[i]))
20708 hasEnoughRank = true;
20710 if (!hasEnoughRank)
20711 return;
20715 // Find out how many points we have in this field
20716 uint32 spentPoints = 0;
20718 uint32 tTab = talentInfo->TalentTab;
20719 if (talentInfo->Row > 0)
20721 unsigned int numRows = sTalentStore.GetNumRows();
20722 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
20724 // Someday, someone needs to revamp
20725 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
20726 if (tmpTalent) // the way talents are tracked
20728 if (tmpTalent->TalentTab == tTab)
20730 for (int j = 0; j < MAX_TALENT_RANK; ++j)
20732 if (tmpTalent->RankID[j] != 0)
20734 if (HasSpell(tmpTalent->RankID[j]))
20736 spentPoints += j + 1;
20745 // not have required min points spent in talent tree
20746 if(spentPoints < (talentInfo->Row * MAX_TALENT_RANK))
20747 return;
20749 // spell not set in talent.dbc
20750 uint32 spellid = talentInfo->RankID[talentRank];
20751 if( spellid == 0 )
20753 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
20754 return;
20757 // already known
20758 if(HasSpell(spellid))
20759 return;
20761 // learn! (other talent ranks will unlearned at learning)
20762 learnSpell(spellid, false);
20763 sLog.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
20765 // update free talent points
20766 SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
20769 void Player::LearnPetTalent(uint64 petGuid, uint32 talentId, uint32 talentRank)
20771 Pet *pet = GetPet();
20773 if(!pet)
20774 return;
20776 if(petGuid != pet->GetGUID())
20777 return;
20779 uint32 CurTalentPoints = pet->GetFreeTalentPoints();
20781 if(CurTalentPoints == 0)
20782 return;
20784 if (talentRank >= MAX_PET_TALENT_RANK)
20785 return;
20787 TalentEntry const *talentInfo = sTalentStore.LookupEntry(talentId);
20789 if(!talentInfo)
20790 return;
20792 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry(talentInfo->TalentTab);
20794 if(!talentTabInfo)
20795 return;
20797 CreatureInfo const *ci = pet->GetCreatureInfo();
20799 if(!ci)
20800 return;
20802 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
20804 if(!pet_family)
20805 return;
20807 if(pet_family->petTalentType < 0) // not hunter pet
20808 return;
20810 // prevent learn talent for different family (cheating)
20811 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
20812 return;
20814 // find current max talent rank
20815 int32 curtalent_maxrank = 0;
20816 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
20818 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
20820 curtalent_maxrank = k + 1;
20821 break;
20825 // we already have same or higher talent rank learned
20826 if(curtalent_maxrank >= (talentRank + 1))
20827 return;
20829 // check if we have enough talent points
20830 if(CurTalentPoints < (talentRank - curtalent_maxrank + 1))
20831 return;
20833 // Check if it requires another talent
20834 if (talentInfo->DependsOn > 0)
20836 if(TalentEntry const *depTalentInfo = sTalentStore.LookupEntry(talentInfo->DependsOn))
20838 bool hasEnoughRank = false;
20839 for (int i = talentInfo->DependsOnRank; i < MAX_TALENT_RANK; ++i)
20841 if (depTalentInfo->RankID[i] != 0)
20842 if (pet->HasSpell(depTalentInfo->RankID[i]))
20843 hasEnoughRank = true;
20845 if (!hasEnoughRank)
20846 return;
20850 // Find out how many points we have in this field
20851 uint32 spentPoints = 0;
20853 uint32 tTab = talentInfo->TalentTab;
20854 if (talentInfo->Row > 0)
20856 unsigned int numRows = sTalentStore.GetNumRows();
20857 for (unsigned int i = 0; i < numRows; ++i) // Loop through all talents.
20859 // Someday, someone needs to revamp
20860 const TalentEntry *tmpTalent = sTalentStore.LookupEntry(i);
20861 if (tmpTalent) // the way talents are tracked
20863 if (tmpTalent->TalentTab == tTab)
20865 for (int j = 0; j < MAX_TALENT_RANK; ++j)
20867 if (tmpTalent->RankID[j] != 0)
20869 if (pet->HasSpell(tmpTalent->RankID[j]))
20871 spentPoints += j + 1;
20880 // not have required min points spent in talent tree
20881 if(spentPoints < (talentInfo->Row * MAX_PET_TALENT_RANK))
20882 return;
20884 // spell not set in talent.dbc
20885 uint32 spellid = talentInfo->RankID[talentRank];
20886 if( spellid == 0 )
20888 sLog.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId, talentRank);
20889 return;
20892 // already known
20893 if(pet->HasSpell(spellid))
20894 return;
20896 // learn! (other talent ranks will unlearned at learning)
20897 pet->learnSpell(spellid);
20898 sLog.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId, talentRank, spellid);
20900 // update free talent points
20901 pet->SetFreeTalentPoints(CurTalentPoints - (talentRank - curtalent_maxrank + 1));
20904 void Player::UpdateKnownCurrencies(uint32 itemId, bool apply)
20906 if(CurrencyTypesEntry const* ctEntry = sCurrencyTypesStore.LookupEntry(itemId))
20908 if(apply)
20909 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES, (UI64LIT(1) << (ctEntry->BitIndex - 1)));
20910 else
20911 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES, (UI64LIT(1) << (ctEntry->BitIndex - 1)));
20915 void Player::UpdateFallInformationIfNeed( MovementInfo const& minfo,uint16 opcode )
20917 if (m_lastFallTime >= minfo.GetFallTime() || m_lastFallZ <= minfo.GetPos()->z || opcode == MSG_MOVE_FALL_LAND)
20918 SetFallInformation(minfo.GetFallTime(), minfo.GetPos()->z);
20921 void Player::UnsummonPetTemporaryIfAny()
20923 Pet* pet = GetPet();
20924 if(!pet)
20925 return;
20927 if(!m_temporaryUnsummonedPetNumber && pet->isControlled() && !pet->isTemporarySummoned() )
20929 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
20930 m_oldpetspell = pet->GetUInt32Value(UNIT_CREATED_BY_SPELL);
20933 RemovePet(pet, PET_SAVE_AS_CURRENT);
20936 void Player::ResummonPetTemporaryUnSummonedIfAny()
20938 if(!m_temporaryUnsummonedPetNumber)
20939 return;
20941 // not resummon in not appropriate state
20942 if(IsPetNeedBeTemporaryUnsummoned())
20943 return;
20945 if(GetPetGUID())
20946 return;
20948 Pet* NewPet = new Pet;
20949 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
20950 delete NewPet;
20952 m_temporaryUnsummonedPetNumber = 0;
20955 bool Player::canSeeSpellClickOn(Creature const *c) const
20957 if(!c->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_SPELLCLICK))
20958 return false;
20960 SpellClickInfoMapBounds clickPair = sObjectMgr.GetSpellClickInfoMapBounds(c->GetEntry());
20961 for(SpellClickInfoMap::const_iterator itr = clickPair.first; itr != clickPair.second; ++itr)
20962 if(itr->second.IsFitToRequirements(this))
20963 return true;
20965 return false;
20968 void Player::BuildPlayerTalentsInfoData(WorldPacket *data)
20970 *data << uint32(GetFreeTalentPoints()); // unspentTalentPoints
20971 *data << uint8(m_specsCount); // talent group count (0, 1 or 2)
20972 *data << uint8(m_activeSpec); // talent group index (0 or 1)
20974 if(m_specsCount)
20976 // loop through all specs (only 1 for now)
20977 for(uint32 specIdx = 0; specIdx < m_specsCount; ++specIdx)
20979 uint8 talentIdCount = 0;
20980 size_t pos = data->wpos();
20981 *data << uint8(talentIdCount); // [PH], talentIdCount
20983 // find class talent tabs (all players have 3 talent tabs)
20984 uint32 const* talentTabIds = GetTalentTabPages(getClass());
20986 for(uint32 i = 0; i < 3; ++i)
20988 uint32 talentTabId = talentTabIds[i];
20990 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
20992 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
20993 if(!talentInfo)
20994 continue;
20996 // skip another tab talents
20997 if(talentInfo->TalentTab != talentTabId)
20998 continue;
21000 // find max talent rank
21001 int32 curtalent_maxrank = -1;
21002 for(int32 k = MAX_TALENT_RANK-1; k > -1; --k)
21004 if(talentInfo->RankID[k] && HasSpell(talentInfo->RankID[k]))
21006 curtalent_maxrank = k;
21007 break;
21011 // not learned talent
21012 if(curtalent_maxrank < 0)
21013 continue;
21015 *data << uint32(talentInfo->TalentID); // Talent.dbc
21016 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
21018 ++talentIdCount;
21022 data->put<uint8>(pos, talentIdCount); // put real count
21024 *data << uint8(MAX_GLYPH_SLOT_INDEX); // glyphs count
21026 for(uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
21027 *data << uint16(GetGlyph(i)); // GlyphProperties.dbc
21032 void Player::BuildPetTalentsInfoData(WorldPacket *data)
21034 uint32 unspentTalentPoints = 0;
21035 size_t pointsPos = data->wpos();
21036 *data << uint32(unspentTalentPoints); // [PH], unspentTalentPoints
21038 uint8 talentIdCount = 0;
21039 size_t countPos = data->wpos();
21040 *data << uint8(talentIdCount); // [PH], talentIdCount
21042 Pet *pet = GetPet();
21043 if(!pet)
21044 return;
21046 unspentTalentPoints = pet->GetFreeTalentPoints();
21048 data->put<uint32>(pointsPos, unspentTalentPoints); // put real points
21050 CreatureInfo const *ci = pet->GetCreatureInfo();
21051 if(!ci)
21052 return;
21054 CreatureFamilyEntry const *pet_family = sCreatureFamilyStore.LookupEntry(ci->family);
21055 if(!pet_family || pet_family->petTalentType < 0)
21056 return;
21058 for(uint32 talentTabId = 1; talentTabId < sTalentTabStore.GetNumRows(); ++talentTabId)
21060 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentTabId );
21061 if(!talentTabInfo)
21062 continue;
21064 if(!((1 << pet_family->petTalentType) & talentTabInfo->petTalentMask))
21065 continue;
21067 for(uint32 talentId = 0; talentId < sTalentStore.GetNumRows(); ++talentId)
21069 TalentEntry const* talentInfo = sTalentStore.LookupEntry(talentId);
21070 if(!talentInfo)
21071 continue;
21073 // skip another tab talents
21074 if(talentInfo->TalentTab != talentTabId)
21075 continue;
21077 // find max talent rank
21078 int32 curtalent_maxrank = -1;
21079 for(int32 k = 4; k > -1; --k)
21081 if(talentInfo->RankID[k] && pet->HasSpell(talentInfo->RankID[k]))
21083 curtalent_maxrank = k;
21084 break;
21088 // not learned talent
21089 if(curtalent_maxrank < 0)
21090 continue;
21092 *data << uint32(talentInfo->TalentID); // Talent.dbc
21093 *data << uint8(curtalent_maxrank); // talentMaxRank (0-4)
21095 ++talentIdCount;
21098 data->put<uint8>(countPos, talentIdCount); // put real count
21100 break;
21104 void Player::SendTalentsInfoData(bool pet)
21106 WorldPacket data(SMSG_TALENTS_INFO, 50);
21107 data << uint8(pet ? 1 : 0);
21108 if(pet)
21109 BuildPetTalentsInfoData(&data);
21110 else
21111 BuildPlayerTalentsInfoData(&data);
21112 GetSession()->SendPacket(&data);
21115 void Player::BuildEnchantmentsInfoData(WorldPacket *data)
21117 uint32 slotUsedMask = 0;
21118 size_t slotUsedMaskPos = data->wpos();
21119 *data << uint32(slotUsedMask); // slotUsedMask < 0x80000
21121 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
21123 Item *item = GetItemByPos(INVENTORY_SLOT_BAG_0, i);
21125 if(!item)
21126 continue;
21128 slotUsedMask |= (1 << i);
21130 *data << uint32(item->GetEntry()); // item entry
21132 uint16 enchantmentMask = 0;
21133 size_t enchantmentMaskPos = data->wpos();
21134 *data << uint16(enchantmentMask); // enchantmentMask < 0x1000
21136 for(uint32 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
21138 uint32 enchId = item->GetEnchantmentId(EnchantmentSlot(j));
21140 if(!enchId)
21141 continue;
21143 enchantmentMask |= (1 << j);
21145 *data << uint16(enchId); // enchantmentId?
21148 data->put<uint16>(enchantmentMaskPos, enchantmentMask);
21150 *data << uint16(0); // ?
21151 *data << uint8(0); // PGUID!
21152 *data << uint32(0); // seed?
21155 data->put<uint32>(slotUsedMaskPos, slotUsedMask);
21158 void Player::SendEquipmentSetList()
21160 uint32 count = 0;
21161 WorldPacket data(SMSG_EQUIPMENT_SET_LIST, 4);
21162 size_t count_pos = data.wpos();
21163 data << uint32(count); // count placeholder
21164 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21166 if(itr->second.state==EQUIPMENT_SET_DELETED)
21167 continue;
21168 data.appendPackGUID(itr->second.Guid);
21169 data << uint32(itr->first);
21170 data << itr->second.Name;
21171 data << itr->second.IconName;
21172 for(uint32 i = 0; i < EQUIPMENT_SLOT_END; ++i)
21173 data.appendPackGUID(MAKE_NEW_GUID(itr->second.Items[i], 0, HIGHGUID_ITEM));
21175 ++count; // client have limit but it checked at loading and set
21177 data.put<uint32>(count_pos, count);
21178 GetSession()->SendPacket(&data);
21181 void Player::SetEquipmentSet(uint32 index, EquipmentSet eqset)
21183 if(eqset.Guid != 0)
21185 bool found = false;
21187 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21189 if((itr->second.Guid == eqset.Guid) && (itr->first == index))
21191 found = true;
21192 break;
21196 if(!found) // something wrong...
21198 sLog.outError("Player %s tried to save equipment set "UI64FMTD" (index %u), but that equipment set not found!", GetName(), eqset.Guid, index);
21199 return;
21203 EquipmentSet& eqslot = m_EquipmentSets[index];
21205 EquipmentSetUpdateState old_state = eqslot.state;
21207 eqslot = eqset;
21209 if(eqset.Guid == 0)
21211 eqslot.Guid = sObjectMgr.GenerateEquipmentSetGuid();
21213 WorldPacket data(SMSG_EQUIPMENT_SET_SAVED, 4 + 1);
21214 data << uint32(index);
21215 data.appendPackGUID(eqslot.Guid);
21216 GetSession()->SendPacket(&data);
21219 eqslot.state = old_state == EQUIPMENT_SET_NEW ? EQUIPMENT_SET_NEW : EQUIPMENT_SET_CHANGED;
21222 void Player::_SaveEquipmentSets()
21224 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end();)
21226 uint32 index = itr->first;
21227 EquipmentSet& eqset = itr->second;
21228 switch(eqset.state)
21230 case EQUIPMENT_SET_UNCHANGED:
21231 ++itr;
21232 break; // nothing do
21233 case EQUIPMENT_SET_CHANGED:
21234 CharacterDatabase.PExecute("UPDATE character_equipmentsets SET name='%s', iconname='%s', item0='%u', item1='%u', item2='%u', item3='%u', item4='%u', item5='%u', item6='%u', item7='%u', item8='%u', item9='%u', item10='%u', item11='%u', item12='%u', item13='%u', item14='%u', item15='%u', item16='%u', item17='%u', item18='%u' WHERE guid='%u' AND setguid='"UI64FMTD"' AND setindex='%u'",
21235 eqset.Name.c_str(), eqset.IconName.c_str(), eqset.Items[0], eqset.Items[1], eqset.Items[2], eqset.Items[3], eqset.Items[4], eqset.Items[5], eqset.Items[6], eqset.Items[7],
21236 eqset.Items[8], eqset.Items[9], eqset.Items[10], eqset.Items[11], eqset.Items[12], eqset.Items[13], eqset.Items[14], eqset.Items[15], eqset.Items[16], eqset.Items[17], eqset.Items[18], GetGUIDLow(), eqset.Guid, index);
21237 eqset.state = EQUIPMENT_SET_UNCHANGED;
21238 ++itr;
21239 break;
21240 case EQUIPMENT_SET_NEW:
21241 CharacterDatabase.PExecute("INSERT INTO character_equipmentsets VALUES ('%u', '"UI64FMTD"', '%u', '%s', '%s', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
21242 GetGUIDLow(), eqset.Guid, index, eqset.Name.c_str(), eqset.IconName.c_str(), eqset.Items[0], eqset.Items[1], eqset.Items[2], eqset.Items[3], eqset.Items[4], eqset.Items[5], eqset.Items[6], eqset.Items[7],
21243 eqset.Items[8], eqset.Items[9], eqset.Items[10], eqset.Items[11], eqset.Items[12], eqset.Items[13], eqset.Items[14], eqset.Items[15], eqset.Items[16], eqset.Items[17], eqset.Items[18]);
21244 eqset.state = EQUIPMENT_SET_UNCHANGED;
21245 ++itr;
21246 break;
21247 case EQUIPMENT_SET_DELETED:
21248 CharacterDatabase.PExecute("DELETE FROM character_equipmentsets WHERE setguid="UI64FMTD, eqset.Guid);
21249 m_EquipmentSets.erase(itr++);
21250 break;
21255 void Player::_SaveBGData()
21257 CharacterDatabase.PExecute("DELETE FROM character_battleground_data WHERE guid='%u'", GetGUIDLow());
21258 if (m_bgData.bgInstanceID)
21260 /* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
21261 CharacterDatabase.PExecute("INSERT INTO character_battleground_data VALUES ('%u', '%u', '%u', '%f', '%f', '%f', '%f', '%u', '%u', '%u', '%u')",
21262 GetGUIDLow(), m_bgData.bgInstanceID, m_bgData.bgTeam, m_bgData.joinPos.coord_x, m_bgData.joinPos.coord_y, m_bgData.joinPos.coord_z,
21263 m_bgData.joinPos.orientation, m_bgData.joinPos.mapid, m_bgData.taxiPath[0], m_bgData.taxiPath[1], m_bgData.mountSpell);
21267 void Player::DeleteEquipmentSet(uint64 setGuid)
21269 for(EquipmentSets::iterator itr = m_EquipmentSets.begin(); itr != m_EquipmentSets.end(); ++itr)
21271 if(itr->second.Guid == setGuid)
21273 if(itr->second.state == EQUIPMENT_SET_NEW)
21274 m_EquipmentSets.erase(itr);
21275 else
21276 itr->second.state = EQUIPMENT_SET_DELETED;
21277 break;
21282 void Player::ActivateSpec(uint32 specNum)
21284 if(GetActiveSpec() == specNum)
21285 return;
21287 resetTalents(true);
21290 void Player::RemoveAtLoginFlag( AtLoginFlags f, bool in_db_also /*= false*/ )
21292 m_atLoginFlags &= ~f;
21294 if(in_db_also)
21295 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f), GetGUIDLow());
21298 void Player::SendClearCooldown( uint32 spell_id, Unit* target )
21300 WorldPacket data(SMSG_CLEAR_COOLDOWN, 4+8);
21301 data << uint32(spell_id);
21302 data << uint64(target->GetGUID());
21303 SendDirectMessage(&data);
21306 void Player::BuildTeleportAckMsg( WorldPacket *data, float x, float y, float z, float ang ) const
21308 data->Initialize(MSG_MOVE_TELEPORT_ACK, 41);
21309 data->append(GetPackGUID());
21310 *data << uint32(0); // this value increments every time
21311 *data << uint32(m_movementInfo.GetMovementFlags()); // movement flags
21312 *data << uint16(0); // 2.3.0
21313 *data << uint32(getMSTime()); // time
21314 *data << x;
21315 *data << y;
21316 *data << z;
21317 *data << ang;
21318 *data << uint32(0);
21321 bool Player::HasMovementFlag( MovementFlags f ) const
21323 return m_movementInfo.HasMovementFlag(f);
21326 void Player::SetFarSightGUID( uint64 guid )
21328 if(GetFarSight() == guid)
21329 return;
21331 SetUInt64Value(PLAYER_FARSIGHT, guid);
21333 // need triggering load grids around new view point
21334 UpdateVisibilityForPlayer();
21337 void Player::UpdateVisibilityForPlayer()
21339 WorldObject const* viewPoint = GetViewPoint();
21340 Map* m = GetMap();
21342 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
21343 Cell cell(p);
21345 m->UpdatePlayerVisibility(this, cell, p);
21347 if (this != viewPoint)
21349 CellPair pView(MaNGOS::ComputeCellPair(viewPoint->GetPositionX(), viewPoint->GetPositionY()));
21350 Cell cellView(pView);
21352 m->UpdateObjectsVisibilityFor(this, cellView, pView);
21354 else
21355 m->UpdateObjectsVisibilityFor(this, cell, p);
21358 void Player::SendDuelCountdown(uint32 counter)
21360 WorldPacket data(SMSG_DUEL_COUNTDOWN, 4);
21361 data << uint32(counter); // seconds
21362 GetSession()->SendPacket(&data);
21365 bool Player::IsImmunedToSpellEffect(SpellEntry const* spellInfo, uint32 index) const
21367 switch(spellInfo->Effect[index])
21369 case SPELL_EFFECT_ATTACK_ME:
21370 return true;
21371 default:
21372 break;
21374 switch(spellInfo->EffectApplyAuraName[index])
21376 case SPELL_AURA_MOD_TAUNT:
21377 return true;
21378 default:
21379 break;
21381 return Unit::IsImmunedToSpellEffect(spellInfo, index);
21384 void Player::SetHomebindToCurrentPos()
21386 m_homebindMapId = GetMapId();
21387 m_homebindZoneId = GetZoneId();
21388 m_homebindX = GetPositionX();
21389 m_homebindY = GetPositionY();
21390 m_homebindZ = GetPositionZ();
21392 // update sql homebind
21393 CharacterDatabase.PExecute("UPDATE character_homebind SET map = '%u', zone = '%u', position_x = '%f', position_y = '%f', position_z = '%f' WHERE guid = '%u'",
21394 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ, GetGUIDLow());