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
21 #include "Database/DatabaseEnv.h"
26 #include "WorldPacket.h"
27 #include "WorldSession.h"
28 #include "UpdateMask.h"
31 #include "SkillDiscovery.h"
33 #include "GossipDef.h"
34 #include "UpdateData.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"
43 #include "ObjectMgr.h"
44 #include "ObjectAccessor.h"
45 #include "ObjectGuid.h"
46 #include "CreatureAI.h"
52 #include "Transports.h"
54 #include "BattleGround.h"
55 #include "BattleGroundAV.h"
56 #include "BattleGroundMgr.h"
57 #include "ArenaTeam.h"
59 #include "Database/DatabaseImpl.h"
61 #include "SocialMgr.h"
62 #include "AchievementMgr.h"
67 #define ZONE_UPDATE_INTERVAL (1*IN_MILLISECONDS)
69 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
70 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
71 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
73 #define SKILL_VALUE(x) PAIR32_LOPART(x)
74 #define SKILL_MAX(x) PAIR32_HIPART(x)
75 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
77 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
78 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
79 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
83 CHARACTER_FLAG_NONE
= 0x00000000,
84 CHARACTER_FLAG_UNK1
= 0x00000001,
85 CHARACTER_FLAG_UNK2
= 0x00000002,
86 CHARACTER_LOCKED_FOR_TRANSFER
= 0x00000004,
87 CHARACTER_FLAG_UNK4
= 0x00000008,
88 CHARACTER_FLAG_UNK5
= 0x00000010,
89 CHARACTER_FLAG_UNK6
= 0x00000020,
90 CHARACTER_FLAG_UNK7
= 0x00000040,
91 CHARACTER_FLAG_UNK8
= 0x00000080,
92 CHARACTER_FLAG_UNK9
= 0x00000100,
93 CHARACTER_FLAG_UNK10
= 0x00000200,
94 CHARACTER_FLAG_HIDE_HELM
= 0x00000400,
95 CHARACTER_FLAG_HIDE_CLOAK
= 0x00000800,
96 CHARACTER_FLAG_UNK13
= 0x00001000,
97 CHARACTER_FLAG_GHOST
= 0x00002000,
98 CHARACTER_FLAG_RENAME
= 0x00004000,
99 CHARACTER_FLAG_UNK16
= 0x00008000,
100 CHARACTER_FLAG_UNK17
= 0x00010000,
101 CHARACTER_FLAG_UNK18
= 0x00020000,
102 CHARACTER_FLAG_UNK19
= 0x00040000,
103 CHARACTER_FLAG_UNK20
= 0x00080000,
104 CHARACTER_FLAG_UNK21
= 0x00100000,
105 CHARACTER_FLAG_UNK22
= 0x00200000,
106 CHARACTER_FLAG_UNK23
= 0x00400000,
107 CHARACTER_FLAG_UNK24
= 0x00800000,
108 CHARACTER_FLAG_LOCKED_BY_BILLING
= 0x01000000,
109 CHARACTER_FLAG_DECLINED
= 0x02000000,
110 CHARACTER_FLAG_UNK27
= 0x04000000,
111 CHARACTER_FLAG_UNK28
= 0x08000000,
112 CHARACTER_FLAG_UNK29
= 0x10000000,
113 CHARACTER_FLAG_UNK30
= 0x20000000,
114 CHARACTER_FLAG_UNK31
= 0x40000000,
115 CHARACTER_FLAG_UNK32
= 0x80000000
118 enum CharacterCustomizeFlags
120 CHAR_CUSTOMIZE_FLAG_NONE
= 0x00000000,
121 CHAR_CUSTOMIZE_FLAG_CUSTOMIZE
= 0x00000001, // name, gender, etc...
122 CHAR_CUSTOMIZE_FLAG_FACTION
= 0x00010000, // name, gender, faction, etc...
123 CHAR_CUSTOMIZE_FLAG_RACE
= 0x00100000 // name, gender, race, etc...
126 // corpse reclaim times
127 #define DEATH_EXPIRE_STEP (5*MINUTE)
128 #define MAX_DEATH_COUNT 3
130 static uint32 copseReclaimDelay
[MAX_DEATH_COUNT
] = { 30, 60, 120 };
132 //== PlayerTaxi ================================================
134 PlayerTaxi::PlayerTaxi()
137 memset(m_taximask
, 0, sizeof(m_taximask
));
140 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race
, uint32 chrClass
, uint32 level
)
142 // class specific initial known nodes
145 case CLASS_DEATH_KNIGHT
:
147 for(int i
= 0; i
< TaxiMaskSize
; ++i
)
148 m_taximask
[i
] |= sOldContinentsNodesMask
[i
];
153 // race specific initial known nodes: capital and taxi hub masks
156 case RACE_HUMAN
: SetTaximaskNode(2); break; // Human
157 case RACE_ORC
: SetTaximaskNode(23); break; // Orc
158 case RACE_DWARF
: SetTaximaskNode(6); break; // Dwarf
159 case RACE_NIGHTELF
: SetTaximaskNode(26);
160 SetTaximaskNode(27); break; // Night Elf
161 case RACE_UNDEAD_PLAYER
: SetTaximaskNode(11); break;// Undead
162 case RACE_TAUREN
: SetTaximaskNode(22); break; // Tauren
163 case RACE_GNOME
: SetTaximaskNode(6); break; // Gnome
164 case RACE_TROLL
: SetTaximaskNode(23); break; // Troll
165 case RACE_BLOODELF
: SetTaximaskNode(82); break; // Blood Elf
166 case RACE_DRAENEI
: SetTaximaskNode(94); break; // Draenei
169 // new continent starting masks (It will be accessible only at new map)
170 switch(Player::TeamForRace(race
))
172 case ALLIANCE
: SetTaximaskNode(100); break;
173 case HORDE
: SetTaximaskNode(99); break;
175 // level dependent taxi hubs
177 SetTaximaskNode(213); //Shattered Sun Staging Area
180 void PlayerTaxi::LoadTaxiMask(const char* data
)
182 Tokens tokens
= StrSplit(data
, " ");
185 Tokens::iterator iter
;
186 for (iter
= tokens
.begin(), index
= 0;
187 (index
< TaxiMaskSize
) && (iter
!= tokens
.end()); ++iter
, ++index
)
189 // load and set bits only for existed taxi nodes
190 m_taximask
[index
] = sTaxiNodesMask
[index
] & uint32(atol((*iter
).c_str()));
194 void PlayerTaxi::AppendTaximaskTo( ByteBuffer
& data
, bool all
)
198 for (uint8 i
=0; i
<TaxiMaskSize
; ++i
)
199 data
<< uint32(sTaxiNodesMask
[i
]); // all existed nodes
203 for (uint8 i
=0; i
<TaxiMaskSize
; ++i
)
204 data
<< uint32(m_taximask
[i
]); // known nodes
208 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string
& values
, uint32 team
)
210 ClearTaxiDestinations();
212 Tokens tokens
= StrSplit(values
," ");
214 for(Tokens::iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
)
216 uint32 node
= uint32(atol(iter
->c_str()));
217 AddTaxiDestination(node
);
220 if(m_TaxiDestinations
.empty())
224 if(m_TaxiDestinations
.size() < 2)
227 for(size_t i
= 1; i
< m_TaxiDestinations
.size(); ++i
)
231 sObjectMgr
.GetTaxiPath(m_TaxiDestinations
[i
-1],m_TaxiDestinations
[i
],path
,cost
);
236 // can't load taxi path without mount set (quest taxi path?)
237 if(!sObjectMgr
.GetTaxiMountDisplayId(GetTaxiSource(),team
,true))
243 std::string
PlayerTaxi::SaveTaxiDestinationsToString()
245 if(m_TaxiDestinations
.empty())
248 std::ostringstream ss
;
250 for(size_t i
=0; i
< m_TaxiDestinations
.size(); ++i
)
251 ss
<< m_TaxiDestinations
[i
] << " ";
256 uint32
PlayerTaxi::GetCurrentTaxiPath() const
258 if(m_TaxiDestinations
.size() < 2)
264 sObjectMgr
.GetTaxiPath(m_TaxiDestinations
[0],m_TaxiDestinations
[1],path
,cost
);
269 std::ostringstream
& operator<< (std::ostringstream
& ss
, PlayerTaxi
const& taxi
)
272 for(int i
= 0; i
< TaxiMaskSize
; ++i
)
273 ss
<< taxi
.m_taximask
[i
] << " ";
278 SpellModifier::SpellModifier( SpellModOp _op
, SpellModType _type
, int32 _value
, SpellEntry
const* spellEntry
, SpellEffectIndex eff
, int16 _charges
/*= 0*/ ) : op(_op
), type(_type
), charges(_charges
), value(_value
), spellId(spellEntry
->Id
), lastAffected(NULL
)
280 uint32
const* ptr
= spellEntry
->GetEffectSpellClassMask(eff
);
281 mask
= uint64(ptr
[0]) | (uint64(ptr
[1]) << 32);
285 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
)
287 uint32
const* ptr
= aura
->getAuraSpellClassMask();
288 mask
= uint64(ptr
[0]) | (uint64(ptr
[1]) << 32);
292 bool SpellModifier::isAffectedOnSpell( SpellEntry
const *spell
) const
294 SpellEntry
const *affect_spell
= sSpellStore
.LookupEntry(spellId
);
295 // False if affect_spell == NULL or spellFamily not equal
296 if (!affect_spell
|| affect_spell
->SpellFamilyName
!= spell
->SpellFamilyName
)
298 if (mask
& spell
->SpellFamilyFlags
)
300 if (mask2
& spell
->SpellFamilyFlags2
)
305 //== Player ====================================================
307 UpdateMask
Player::updateVisualBits
;
309 Player::Player (WorldSession
*session
): Unit(), m_achievementMgr(this), m_reputationMgr(this)
316 m_objectType
|= TYPEMASK_PLAYER
;
317 m_objectTypeId
= TYPEID_PLAYER
;
319 m_valuesCount
= PLAYER_END
;
326 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER
)
327 SetAcceptTicket(true);
329 // players always accept
330 if(GetSession()->GetSecurity() == SEC_PLAYER
)
331 SetAcceptWhispers(true);
339 m_usedTalentCount
= 0;
340 m_questRewardTalentCount
= 0;
343 m_weaponChangeTimer
= 0;
346 m_zoneUpdateTimer
= 0;
350 m_nextSave
= sWorld
.getConfig(CONFIG_UINT32_INTERVAL_SAVE
);
352 // randomize first save time in range [CONFIG_UINT32_INTERVAL_SAVE] around [CONFIG_UINT32_INTERVAL_SAVE]
353 // this must help in case next save after mass player load after server startup
354 m_nextSave
= urand(m_nextSave
/2,m_nextSave
*3/2);
356 clearResurrectRequestData();
358 m_SpellModRemoveCount
= 0;
360 memset(m_items
, 0, sizeof(Item
*)*PLAYER_SLOTS_COUNT
);
364 // group is initialized in the reference constructor
365 SetGroupInvite(NULL
);
366 m_groupUpdateMask
= 0;
367 m_auraUpdateMask
= 0;
371 m_GuildIdInvited
= 0;
372 m_ArenaTeamIdInvited
= 0;
374 m_atLoginFlags
= AT_LOGIN_NONE
;
376 mSemaphoreTeleport_Near
= false;
377 mSemaphoreTeleport_Far
= false;
379 m_DelayedOperations
= 0;
380 m_bCanDelayTeleport
= false;
381 m_bHasDelayedTeleport
= false;
382 m_teleport_options
= 0;
389 PlayerTalkClass
= new PlayerMenu( GetSession() );
390 m_currentBuybackSlot
= BUYBACK_SLOT_START
;
392 m_DailyQuestChanged
= false;
393 m_WeeklyQuestChanged
= false;
395 for (int i
=0; i
<MAX_TIMERS
; ++i
)
396 m_MirrorTimer
[i
] = DISABLED_MIRROR_TIMER
;
398 m_MirrorTimerFlags
= UNDERWATER_NONE
;
399 m_MirrorTimerFlagsLast
= UNDERWATER_NONE
;
405 m_deathExpireTime
= 0;
409 m_DetectInvTimer
= 1*IN_MILLISECONDS
;
411 for (int j
=0; j
< PLAYER_MAX_BATTLEGROUND_QUEUES
; ++j
)
413 m_bgBattleGroundQueueID
[j
].bgQueueTypeId
= BATTLEGROUND_QUEUE_NONE
;
414 m_bgBattleGroundQueueID
[j
].invitedToInstance
= 0;
417 m_logintime
= time(NULL
);
418 m_Last_tick
= m_logintime
;
419 m_WeaponProficiency
= 0;
420 m_ArmorProficiency
= 0;
423 m_canDualWield
= false;
424 m_canTitanGrip
= false;
427 m_temporaryUnsummonedPetNumber
= 0;
428 //cache for UNIT_CREATED_BY_SPELL to allow
429 //returning reagents for temporarily removed pets
430 //when dying/logging out
433 ////////////////////Rest System/////////////////////
437 rest_type
=REST_TYPE_NO
;
438 ////////////////////Rest System/////////////////////
440 m_mailsUpdated
= false;
442 m_nextMailDelivereTime
= 0;
444 m_resetTalentsCost
= 0;
445 m_resetTalentsTime
= 0;
446 m_itemUpdateQueueBlocked
= false;
448 for (int i
= 0; i
< MAX_MOVE_TYPE
; ++i
)
449 m_forced_speed_changes
[i
] = 0;
453 /////////////////// Instance System /////////////////////
456 m_InstanceValid
= true;
457 m_dungeonDifficulty
= DUNGEON_DIFFICULTY_NORMAL
;
458 m_raidDifficulty
= RAID_DIFFICULTY_10MAN_NORMAL
;
465 for (int i
= 0; i
< BASEMOD_END
; ++i
)
467 m_auraBaseMod
[i
][FLAT_MOD
] = 0.0f
;
468 m_auraBaseMod
[i
][PCT_MOD
] = 1.0f
;
471 for (int i
= 0; i
< MAX_COMBAT_RATING
; ++i
)
472 m_baseRatingValue
[i
] = 0;
474 m_baseSpellPower
= 0;
477 m_armorPenetrationPct
= 0.0f
;
480 m_lastHonorUpdateTime
= time(NULL
);
492 m_contestedPvPTimer
= 0;
494 m_declinedname
= NULL
;
503 CleanupsBeforeDelete();
505 // it must be unloaded already in PlayerLogout and accessed only for loggined player
508 // Note: buy back item already deleted from DB when player was saved
509 for(int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
516 //all mailed items should be deleted, also all mail should be deallocated
517 for (PlayerMails::const_iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
520 for (ItemMap::const_iterator iter
= mMitems
.begin(); iter
!= mMitems
.end(); ++iter
)
521 delete iter
->second
; //if item is duplicated... then server may crash ... but that item should be deallocated
523 delete PlayerTalkClass
;
527 m_transport
->RemovePassenger(this);
530 for(size_t x
= 0; x
< ItemSetEff
.size(); x
++)
532 delete ItemSetEff
[x
];
534 // clean up player-instance binds, may unload some instance saves
535 for(uint8 i
= 0; i
< MAX_DIFFICULTY
; ++i
)
536 for(BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
537 itr
->second
.save
->RemovePlayer(this);
539 delete m_declinedname
;
543 void Player::CleanupsBeforeDelete()
545 if(m_uint32Values
) // only for fully created Object
548 DuelComplete(DUEL_INTERUPTED
);
550 Unit::CleanupsBeforeDelete();
553 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 */)
555 //FIXME: outfitId not used in player creating
557 Object::_Create(guidlow
, 0, HIGHGUID_PLAYER
);
561 PlayerInfo
const* info
= sObjectMgr
.GetPlayerInfo(race
, class_
);
564 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
568 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
571 SetLocationMapId(info
->mapId
);
572 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
);
574 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(class_
);
577 sLog
.outError("Class %u not found in DBC (Wrong DBC files?)",class_
);
581 SetMap(sMapMgr
.CreateMap(info
->mapId
, this));
583 uint8 powertype
= cEntry
->powerType
;
585 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, DEFAULT_WORLD_OBJECT_SIZE
);
586 SetFloatValue(UNIT_FIELD_COMBATREACH
, 1.5f
);
588 setFactionForRace(race
);
590 uint32 RaceClassGender
= ( race
) | ( class_
<< 8 ) | ( gender
<< 16 );
592 SetUInt32Value(UNIT_FIELD_BYTES_0
, ( RaceClassGender
| ( powertype
<< 24 ) ) );
594 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_PVP
);
595 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
);
596 SetFlag(UNIT_FIELD_FLAGS_2
, UNIT_FLAG2_REGENERATE_POWER
);
597 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
); // fix cast time showed in spell tooltip on client
598 SetFloatValue(UNIT_FIELD_HOVERHEIGHT
, 1.0f
); // default for players in 3.0.3
600 // -1 is default value
601 SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX
, -1);
603 SetUInt32Value(PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
604 SetUInt32Value(PLAYER_BYTES_2
, (facialHair
| (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
605 SetByteValue(PLAYER_BYTES_3
, 0, gender
);
606 SetByteValue(PLAYER_BYTES_3
, 3, 0); // BattlefieldArenaFaction (0 or 1)
608 SetUInt32Value( PLAYER_GUILDID
, 0 );
609 SetUInt32Value( PLAYER_GUILDRANK
, 0 );
610 SetUInt32Value( PLAYER_GUILD_TIMESTAMP
, 0 );
612 for(int i
= 0; i
< KNOWN_TITLES_SIZE
; ++i
)
613 SetUInt64Value(PLAYER__FIELD_KNOWN_TITLES
+ i
, 0); // 0=disabled
614 SetUInt32Value( PLAYER_CHOSEN_TITLE
, 0 );
616 SetUInt32Value( PLAYER_FIELD_KILLS
, 0 );
617 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 0 );
618 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION
, 0 );
619 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0 );
621 // set starting level
622 uint32 start_level
= getClass() != CLASS_DEATH_KNIGHT
623 ? sWorld
.getConfig(CONFIG_UINT32_START_PLAYER_LEVEL
)
624 : sWorld
.getConfig(CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL
);
626 if (GetSession()->GetSecurity() >= SEC_MODERATOR
)
628 uint32 gm_level
= sWorld
.getConfig(CONFIG_UINT32_START_GM_LEVEL
);
629 if(gm_level
> start_level
)
630 start_level
= gm_level
;
633 SetUInt32Value(UNIT_FIELD_LEVEL
, start_level
);
637 SetUInt32Value (PLAYER_FIELD_COINAGE
, sWorld
.getConfig(CONFIG_UINT32_START_PLAYER_MONEY
));
638 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_UINT32_START_HONOR_POINTS
));
639 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_UINT32_START_ARENA_POINTS
));
642 m_Last_tick
= time(NULL
);
643 m_Played_time
[PLAYED_TIME_TOTAL
] = 0;
644 m_Played_time
[PLAYED_TIME_LEVEL
] = 0;
646 // base stats and related field values
648 InitTaxiNodesForLevel();
649 InitGlyphsForLevel();
650 InitTalentForLevel();
651 InitPrimaryProfessions(); // to max set before any spell added
653 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
654 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
655 SetHealth(GetMaxHealth());
656 if (getPowerType()==POWER_MANA
)
658 UpdateMaxPower(POWER_MANA
); // Update max Mana (for add bonus from intellect)
659 SetPower(POWER_MANA
,GetMaxPower(POWER_MANA
));
662 if(getPowerType() == POWER_RUNIC_POWER
)
664 SetPower(POWER_RUNE
, 8);
665 SetMaxPower(POWER_RUNE
, 8);
666 SetPower(POWER_RUNIC_POWER
, 0);
667 SetMaxPower(POWER_RUNIC_POWER
, 1000);
671 learnDefaultSpells();
673 // original action bar
674 for (PlayerCreateInfoActions::const_iterator action_itr
= info
->action
.begin(); action_itr
!= info
->action
.end(); ++action_itr
)
675 addActionButton(0, action_itr
->button
,action_itr
->action
,action_itr
->type
);
678 CharStartOutfitEntry
const* oEntry
= NULL
;
679 for (uint32 i
= 1; i
< sCharStartOutfitStore
.GetNumRows(); ++i
)
681 if(CharStartOutfitEntry
const* entry
= sCharStartOutfitStore
.LookupEntry(i
))
683 if(entry
->RaceClassGender
== RaceClassGender
)
693 for(int j
= 0; j
< MAX_OUTFIT_ITEMS
; ++j
)
695 if(oEntry
->ItemId
[j
] <= 0)
698 uint32 item_id
= oEntry
->ItemId
[j
];
700 // just skip, reported in ObjectMgr::LoadItemPrototypes
701 ItemPrototype
const* iProto
= ObjectMgr::GetItemPrototype(item_id
);
705 // BuyCount by default
706 int32 count
= iProto
->BuyCount
;
708 // special amount for foor/drink
709 if(iProto
->Class
==ITEM_CLASS_CONSUMABLE
&& iProto
->SubClass
==ITEM_SUBCLASS_FOOD
)
711 switch(iProto
->Spells
[0].SpellCategory
)
714 count
= getClass()==CLASS_DEATH_KNIGHT
? 10 : 4;
720 if(iProto
->Stackable
< count
)
721 count
= iProto
->Stackable
;
723 // special amount for daggers
724 else if(iProto
->Class
==ITEM_CLASS_WEAPON
&& iProto
->SubClass
==ITEM_SUBCLASS_WEAPON_DAGGER
)
726 count
= 2; // will placed to 2 slots
729 StoreNewItemInBestSlots(item_id
, count
);
733 for (PlayerCreateInfoItems::const_iterator item_id_itr
= info
->item
.begin(); item_id_itr
!=info
->item
.end(); ++item_id_itr
++)
734 StoreNewItemInBestSlots(item_id_itr
->item_id
, item_id_itr
->item_amount
);
736 // bags and main-hand weapon must equipped at this moment
737 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
738 // or ammo not equipped in special bag
739 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
741 if(Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
744 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
745 uint8 msg
= CanEquipItem( NULL_SLOT
, eDest
, pItem
, false );
746 if( msg
== EQUIP_ERR_OK
)
748 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
749 EquipItem( eDest
, pItem
, true);
751 // move other items to more appropriate slots (ammo not equipped in special bag)
754 ItemPosCountVec sDest
;
755 msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, sDest
, pItem
, false );
756 if( msg
== EQUIP_ERR_OK
)
758 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
759 pItem
= StoreItem( sDest
, pItem
, true);
762 // if this is ammo then use it
763 msg
= CanUseAmmo( pItem
->GetEntry() );
764 if( msg
== EQUIP_ERR_OK
)
765 SetAmmo( pItem
->GetEntry() );
769 // all item positions resolved
774 bool Player::StoreNewItemInBestSlots(uint32 titem_id
, uint32 titem_amount
)
776 sLog
.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id
, titem_amount
);
778 // attempt equip by one
779 while(titem_amount
> 0)
782 uint8 msg
= CanEquipNewItem( NULL_SLOT
, eDest
, titem_id
, false );
783 if( msg
!= EQUIP_ERR_OK
)
786 EquipNewItem( eDest
, titem_id
, true);
787 AutoUnequipOffhandIfNeed();
791 if(titem_amount
== 0)
792 return true; // equipped
795 ItemPosCountVec sDest
;
796 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
797 uint8 msg
= CanStoreNewItem( INVENTORY_SLOT_BAG_0
, NULL_SLOT
, sDest
, titem_id
, titem_amount
);
798 if( msg
== EQUIP_ERR_OK
)
800 StoreNewItem( sDest
, titem_id
, true, Item::GenerateItemRandomPropertyId(titem_id
) );
801 return true; // stored
804 // item can't be added
805 sLog
.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id
,getRace(),getClass(),msg
);
809 // helper function, mainly for script side, but can be used for simple task in mangos also.
810 Item
* Player::StoreNewItemInInventorySlot(uint32 itemEntry
, uint32 amount
)
812 ItemPosCountVec vDest
;
814 uint8 msg
= CanStoreNewItem(INVENTORY_SLOT_BAG_0
, NULL_SLOT
, vDest
, itemEntry
, amount
);
816 if (msg
== EQUIP_ERR_OK
)
818 if (Item
* pItem
= StoreNewItem(vDest
, itemEntry
, true, Item::GenerateItemRandomPropertyId(itemEntry
)))
825 void Player::SendMirrorTimer(MirrorTimerType Type
, uint32 MaxValue
, uint32 CurrentValue
, int32 Regen
)
827 if (int(MaxValue
) == DISABLED_MIRROR_TIMER
)
829 if (int(CurrentValue
) != DISABLED_MIRROR_TIMER
)
830 StopMirrorTimer(Type
);
833 WorldPacket
data(SMSG_START_MIRROR_TIMER
, (21));
834 data
<< (uint32
)Type
;
835 data
<< CurrentValue
;
839 data
<< (uint32
)0; // spell id
840 GetSession()->SendPacket( &data
);
843 void Player::StopMirrorTimer(MirrorTimerType Type
)
845 m_MirrorTimer
[Type
] = DISABLED_MIRROR_TIMER
;
846 WorldPacket
data(SMSG_STOP_MIRROR_TIMER
, 4);
847 data
<< (uint32
)Type
;
848 GetSession()->SendPacket( &data
);
851 uint32
Player::EnvironmentalDamage(EnviromentalDamage type
, uint32 damage
)
853 if(!isAlive() || isGameMaster())
856 // Absorb, resist some environmental damage type
859 if (type
== DAMAGE_LAVA
)
860 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE
, DIRECT_DAMAGE
, damage
, &absorb
, &resist
);
861 else if (type
== DAMAGE_SLIME
)
862 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE
, DIRECT_DAMAGE
, damage
, &absorb
, &resist
);
864 damage
-=absorb
+resist
;
866 DealDamageMods(this,damage
,&absorb
);
868 WorldPacket
data(SMSG_ENVIRONMENTALDAMAGELOG
, (21));
869 data
<< uint64(GetGUID());
870 data
<< uint8(type
!=DAMAGE_FALL_TO_VOID
? type
: DAMAGE_FALL
);
871 data
<< uint32(damage
);
872 data
<< uint32(absorb
);
873 data
<< uint32(resist
);
874 SendMessageToSet(&data
, true);
876 uint32 final_damage
= DealDamage(this, damage
, NULL
, SELF_DAMAGE
, SPELL_SCHOOL_MASK_NORMAL
, NULL
, false);
880 if(type
==DAMAGE_FALL
) // DealDamage not apply item durability loss at self damage
882 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
883 DurabilityLossAll(0.10f
,false);
884 // durability lost message
885 WorldPacket
data2(SMSG_DURABILITY_DAMAGE_DEATH
, 0);
886 GetSession()->SendPacket(&data2
);
889 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM
, 1, type
);
895 int32
Player::getMaxTimer(MirrorTimerType timer
)
900 if (GetSession()->GetSecurity() >= (AccountTypes
)sWorld
.getConfig(CONFIG_UINT32_TIMERBAR_FATIGUE_GMLEVEL
))
901 return DISABLED_MIRROR_TIMER
;
902 return sWorld
.getConfig(CONFIG_UINT32_TIMERBAR_FATIGUE_MAX
)*IN_MILLISECONDS
;
905 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING
) ||
906 GetSession()->GetSecurity() >= (AccountTypes
)sWorld
.getConfig(CONFIG_UINT32_TIMERBAR_BREATH_GMLEVEL
))
907 return DISABLED_MIRROR_TIMER
;
908 int32 UnderWaterTime
= sWorld
.getConfig(CONFIG_UINT32_TIMERBAR_BREATH_MAX
)*IN_MILLISECONDS
;
909 AuraList
const& mModWaterBreathing
= GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING
);
910 for(AuraList::const_iterator i
= mModWaterBreathing
.begin(); i
!= mModWaterBreathing
.end(); ++i
)
911 UnderWaterTime
= uint32(UnderWaterTime
* (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
);
912 return UnderWaterTime
;
916 if (!isAlive() || GetSession()->GetSecurity() >= (AccountTypes
)sWorld
.getConfig(CONFIG_UINT32_TIMERBAR_FIRE_GMLEVEL
))
917 return DISABLED_MIRROR_TIMER
;
918 return sWorld
.getConfig(CONFIG_UINT32_TIMERBAR_FIRE_MAX
)*IN_MILLISECONDS
;
926 void Player::UpdateMirrorTimers()
928 // Desync flags for update on next HandleDrowning
929 if (m_MirrorTimerFlags
)
930 m_MirrorTimerFlagsLast
= ~m_MirrorTimerFlags
;
933 void Player::HandleDrowning(uint32 time_diff
)
935 if (!m_MirrorTimerFlags
)
939 if (m_MirrorTimerFlags
& UNDERWATER_INWATER
)
941 // Breath timer not activated - activate it
942 if (m_MirrorTimer
[BREATH_TIMER
] == DISABLED_MIRROR_TIMER
)
944 m_MirrorTimer
[BREATH_TIMER
] = getMaxTimer(BREATH_TIMER
);
945 SendMirrorTimer(BREATH_TIMER
, m_MirrorTimer
[BREATH_TIMER
], m_MirrorTimer
[BREATH_TIMER
], -1);
947 else // If activated - do tick
949 m_MirrorTimer
[BREATH_TIMER
]-=time_diff
;
950 // Timer limit - need deal damage
951 if (m_MirrorTimer
[BREATH_TIMER
] < 0)
953 m_MirrorTimer
[BREATH_TIMER
]+= 1*IN_MILLISECONDS
;
954 // Calculate and deal damage
955 // TODO: Check this formula
956 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
957 EnvironmentalDamage(DAMAGE_DROWNING
, damage
);
959 else if (!(m_MirrorTimerFlagsLast
& UNDERWATER_INWATER
)) // Update time in client if need
960 SendMirrorTimer(BREATH_TIMER
, getMaxTimer(BREATH_TIMER
), m_MirrorTimer
[BREATH_TIMER
], -1);
963 else if (m_MirrorTimer
[BREATH_TIMER
] != DISABLED_MIRROR_TIMER
) // Regen timer
965 int32 UnderWaterTime
= getMaxTimer(BREATH_TIMER
);
967 m_MirrorTimer
[BREATH_TIMER
]+=10*time_diff
;
968 if (m_MirrorTimer
[BREATH_TIMER
] >= UnderWaterTime
|| !isAlive())
969 StopMirrorTimer(BREATH_TIMER
);
970 else if (m_MirrorTimerFlagsLast
& UNDERWATER_INWATER
)
971 SendMirrorTimer(BREATH_TIMER
, UnderWaterTime
, m_MirrorTimer
[BREATH_TIMER
], 10);
975 if (m_MirrorTimerFlags
& UNDERWATER_INDARKWATER
)
977 // Fatigue timer not activated - activate it
978 if (m_MirrorTimer
[FATIGUE_TIMER
] == DISABLED_MIRROR_TIMER
)
980 m_MirrorTimer
[FATIGUE_TIMER
] = getMaxTimer(FATIGUE_TIMER
);
981 SendMirrorTimer(FATIGUE_TIMER
, m_MirrorTimer
[FATIGUE_TIMER
], m_MirrorTimer
[FATIGUE_TIMER
], -1);
985 m_MirrorTimer
[FATIGUE_TIMER
]-=time_diff
;
986 // Timer limit - need deal damage or teleport ghost to graveyard
987 if (m_MirrorTimer
[FATIGUE_TIMER
] < 0)
989 m_MirrorTimer
[FATIGUE_TIMER
]+= 1*IN_MILLISECONDS
;
990 if (isAlive()) // Calculate and deal damage
992 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
993 EnvironmentalDamage(DAMAGE_EXHAUSTED
, damage
);
995 else if (HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
)) // Teleport ghost to graveyard
998 else if (!(m_MirrorTimerFlagsLast
& UNDERWATER_INDARKWATER
))
999 SendMirrorTimer(FATIGUE_TIMER
, getMaxTimer(FATIGUE_TIMER
), m_MirrorTimer
[FATIGUE_TIMER
], -1);
1002 else if (m_MirrorTimer
[FATIGUE_TIMER
] != DISABLED_MIRROR_TIMER
) // Regen timer
1004 int32 DarkWaterTime
= getMaxTimer(FATIGUE_TIMER
);
1005 m_MirrorTimer
[FATIGUE_TIMER
]+=10*time_diff
;
1006 if (m_MirrorTimer
[FATIGUE_TIMER
] >= DarkWaterTime
|| !isAlive())
1007 StopMirrorTimer(FATIGUE_TIMER
);
1008 else if (m_MirrorTimerFlagsLast
& UNDERWATER_INDARKWATER
)
1009 SendMirrorTimer(FATIGUE_TIMER
, DarkWaterTime
, m_MirrorTimer
[FATIGUE_TIMER
], 10);
1012 if (m_MirrorTimerFlags
& (UNDERWATER_INLAVA
|UNDERWATER_INSLIME
))
1014 // Breath timer not activated - activate it
1015 if (m_MirrorTimer
[FIRE_TIMER
] == DISABLED_MIRROR_TIMER
)
1016 m_MirrorTimer
[FIRE_TIMER
] = getMaxTimer(FIRE_TIMER
);
1019 m_MirrorTimer
[FIRE_TIMER
]-=time_diff
;
1020 if (m_MirrorTimer
[FIRE_TIMER
] < 0)
1022 m_MirrorTimer
[FIRE_TIMER
]+= 1*IN_MILLISECONDS
;
1023 // Calculate and deal damage
1024 // TODO: Check this formula
1025 uint32 damage
= urand(600, 700);
1026 if (m_MirrorTimerFlags
&UNDERWATER_INLAVA
)
1027 EnvironmentalDamage(DAMAGE_LAVA
, damage
);
1029 EnvironmentalDamage(DAMAGE_SLIME
, damage
);
1034 m_MirrorTimer
[FIRE_TIMER
] = DISABLED_MIRROR_TIMER
;
1036 // Recheck timers flag
1037 m_MirrorTimerFlags
&=~UNDERWATER_EXIST_TIMERS
;
1038 for (int i
= 0; i
< MAX_TIMERS
; ++i
)
1039 if (m_MirrorTimer
[i
]!=DISABLED_MIRROR_TIMER
)
1041 m_MirrorTimerFlags
|=UNDERWATER_EXIST_TIMERS
;
1044 m_MirrorTimerFlagsLast
= m_MirrorTimerFlags
;
1047 ///The player sobers by 256 every 10 seconds
1048 void Player::HandleSobering()
1052 uint32 drunk
= (m_drunk
<= 256) ? 0 : (m_drunk
- 256);
1053 SetDrunkValue(drunk
);
1056 DrunkenState
Player::GetDrunkenstateByValue(uint16 value
)
1059 return DRUNKEN_SMASHED
;
1061 return DRUNKEN_DRUNK
;
1063 return DRUNKEN_TIPSY
;
1064 return DRUNKEN_SOBER
;
1067 void Player::SetDrunkValue(uint16 newDrunkenValue
, uint32 itemId
)
1069 uint32 oldDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
1071 m_drunk
= newDrunkenValue
;
1072 SetUInt32Value(PLAYER_BYTES_3
,(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFF0001) | (m_drunk
& 0xFFFE));
1074 uint32 newDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
1076 // special drunk invisibility detection
1077 if(newDrunkenState
>= DRUNKEN_DRUNK
)
1078 m_detectInvisibilityMask
|= (1<<6);
1080 m_detectInvisibilityMask
&= ~(1<<6);
1082 if(newDrunkenState
== oldDrunkenState
)
1085 WorldPacket
data(SMSG_CROSSED_INEBRIATION_THRESHOLD
, (8+4+4));
1086 data
<< uint64(GetGUID());
1087 data
<< uint32(newDrunkenState
);
1088 data
<< uint32(itemId
);
1090 SendMessageToSet(&data
, true);
1093 void Player::Update( uint32 p_time
)
1099 if(m_nextMailDelivereTime
&& m_nextMailDelivereTime
<= time(NULL
))
1104 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1105 m_nextMailDelivereTime
= 0;
1108 //used to implement delayed far teleports
1109 SetCanDelayTeleport(true);
1110 Unit::Update( p_time
);
1111 SetCanDelayTeleport(false);
1113 // update player only attacks
1114 if(uint32 ranged_att
= getAttackTimer(RANGED_ATTACK
))
1116 setAttackTimer(RANGED_ATTACK
, (p_time
>= ranged_att
? 0 : ranged_att
- p_time
) );
1119 if(uint32 off_att
= getAttackTimer(OFF_ATTACK
))
1121 setAttackTimer(OFF_ATTACK
, (p_time
>= off_att
? 0 : off_att
- p_time
) );
1124 time_t now
= time (NULL
);
1128 UpdateContestedPvP(p_time
);
1130 UpdateDuelFlag(now
);
1132 CheckDuelDistance(now
);
1134 UpdateAfkReport(now
);
1136 // Update items that have just a limited lifetime
1137 if (now
>m_Last_tick
)
1138 UpdateItemDuration(uint32(now
- m_Last_tick
));
1140 if (!m_timedquests
.empty())
1142 QuestSet::iterator iter
= m_timedquests
.begin();
1143 while (iter
!= m_timedquests
.end())
1145 QuestStatusData
& q_status
= mQuestStatus
[*iter
];
1146 if( q_status
.m_timer
<= p_time
)
1148 uint32 quest_id
= *iter
;
1149 ++iter
; // current iter will be removed in FailQuest
1150 FailQuest(quest_id
);
1154 q_status
.m_timer
-= p_time
;
1155 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
1161 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING
))
1163 Unit
*pVictim
= getVictim();
1164 if (pVictim
&& !IsNonMeleeSpellCasted(false))
1166 // default combat reach 10
1167 // TODO add weapon,skill check
1169 float pldistance
= ATTACK_DISTANCE
;
1171 if (isAttackReady(BASE_ATTACK
))
1173 if(!IsWithinDistInMap(pVictim
, pldistance
))
1175 setAttackTimer(BASE_ATTACK
,100);
1176 if(m_swingErrorMsg
!= 1) // send single time (client auto repeat)
1178 SendAttackSwingNotInRange();
1179 m_swingErrorMsg
= 1;
1182 //120 degrees of radiant range
1183 else if( !HasInArc( 2*M_PI_F
/3, pVictim
))
1185 setAttackTimer(BASE_ATTACK
,100);
1186 if(m_swingErrorMsg
!= 2) // send single time (client auto repeat)
1188 SendAttackSwingBadFacingAttack();
1189 m_swingErrorMsg
= 2;
1194 m_swingErrorMsg
= 0; // reset swing error state
1196 // prevent base and off attack in same time, delay attack at 0.2 sec
1197 if(haveOffhandWeapon())
1199 uint32 off_att
= getAttackTimer(OFF_ATTACK
);
1200 if(off_att
< ATTACK_DISPLAY_DELAY
)
1201 setAttackTimer(OFF_ATTACK
,ATTACK_DISPLAY_DELAY
);
1203 AttackerStateUpdate(pVictim
, BASE_ATTACK
);
1204 resetAttackTimer(BASE_ATTACK
);
1208 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK
))
1210 if(!IsWithinDistInMap(pVictim
, pldistance
))
1212 setAttackTimer(OFF_ATTACK
,100);
1214 else if( !HasInArc( 2*M_PI_F
/3, pVictim
))
1216 setAttackTimer(OFF_ATTACK
,100);
1220 // prevent base and off attack in same time, delay attack at 0.2 sec
1221 uint32 base_att
= getAttackTimer(BASE_ATTACK
);
1222 if(base_att
< ATTACK_DISPLAY_DELAY
)
1223 setAttackTimer(BASE_ATTACK
,ATTACK_DISPLAY_DELAY
);
1225 AttackerStateUpdate(pVictim
, OFF_ATTACK
);
1226 resetAttackTimer(OFF_ATTACK
);
1230 Unit
*owner
= pVictim
->GetOwner();
1231 Unit
*u
= owner
? owner
: pVictim
;
1232 if(u
->IsPvP() && (!duel
|| duel
->opponent
!= u
))
1235 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT
);
1240 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
))
1242 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1244 time_t time_inn
= time(NULL
)-GetTimeInnEnter();
1245 if (time_inn
>= 10) //freeze update
1247 float bubble
= 0.125f
*sWorld
.getConfig(CONFIG_FLOAT_RATE_REST_INGAME
);
1248 //speed collect rest bonus (section/in hour)
1249 SetRestBonus( float(GetRestBonus()+ time_inn
*(GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
));
1250 UpdateInnerTime(time(NULL
));
1257 if(p_time
>= m_regenTimer
)
1260 m_regenTimer
-= p_time
;
1263 if (m_weaponChangeTimer
> 0)
1265 if(p_time
>= m_weaponChangeTimer
)
1266 m_weaponChangeTimer
= 0;
1268 m_weaponChangeTimer
-= p_time
;
1271 if (m_zoneUpdateTimer
> 0)
1273 if(p_time
>= m_zoneUpdateTimer
)
1275 uint32 newzone
, newarea
;
1276 GetZoneAndAreaId(newzone
,newarea
);
1278 if( m_zoneUpdateId
!= newzone
)
1279 UpdateZone(newzone
,newarea
); // also update area
1282 // use area updates as well
1283 // needed for free far all arenas for example
1284 if( m_areaUpdateId
!= newarea
)
1285 UpdateArea(newarea
);
1287 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
1291 m_zoneUpdateTimer
-= p_time
;
1294 if (m_timeSyncTimer
> 0)
1296 if(p_time
>= m_timeSyncTimer
)
1299 m_timeSyncTimer
-= p_time
;
1304 // if no longer casting, set regen power as soon as it is up.
1305 if (!IsUnderLastManaUseEffect())
1306 SetFlag(UNIT_FIELD_FLAGS_2
, UNIT_FLAG2_REGENERATE_POWER
);
1312 if (m_deathState
== JUST_DIED
)
1317 if(p_time
>= m_nextSave
)
1319 // m_nextSave reseted in SaveToDB call
1321 sLog
.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1324 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;
1339 m_DetectInvTimer
-= p_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
1353 m_drunkTimer
+= p_time
;
1355 if (m_drunkTimer
> 10*IN_MILLISECONDS
)
1359 // not auto-free ghost from body in instances
1360 if(m_deathTimer
> 0 && !GetBaseMap()->Instanceable())
1362 if(p_time
>= m_deathTimer
)
1369 m_deathTimer
-= p_time
;
1372 UpdateEnchantTime(p_time
);
1373 UpdateHomebindTime(p_time
);
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
1400 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
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
1414 // save value before aura remove in Unit::setDeathState
1415 ressSpellId
= GetUInt32Value(PLAYER_SELF_RES_SPELL
);
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
)
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.equipmentCache, 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
);
1459 sLog
.outError("Player %u has incorrect race/class pair. Don't build enum.", guid
);
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_BOOL_DECLINED_NAMES_USED
))
1501 if(!fields
[20].GetCppString().empty())
1502 char_flags
|= CHARACTER_FLAG_DECLINED
;
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
);
1511 *p_data
<< uint8(atLoginFlags
& AT_LOGIN_FIRST
? 1 : 0);
1515 uint32 petDisplayId
= 0;
1516 uint32 petLevel
= 0;
1517 uint32 petFamily
= 0;
1519 // show pet at selection character in character list only for non-ghost character
1520 if (result
&& !(playerFlags
& PLAYER_FLAGS_GHOST
) && (pClass
== CLASS_WARLOCK
|| pClass
== CLASS_HUNTER
|| pClass
== CLASS_DEATH_KNIGHT
))
1522 uint32 entry
= fields
[16].GetUInt32();
1523 CreatureInfo
const* cInfo
= sCreatureStorage
.LookupEntry
<CreatureInfo
>(entry
);
1526 petDisplayId
= fields
[17].GetUInt32();
1527 petLevel
= fields
[18].GetUInt32();
1528 petFamily
= cInfo
->family
;
1532 *p_data
<< uint32(petDisplayId
);
1533 *p_data
<< uint32(petLevel
);
1534 *p_data
<< uint32(petFamily
);
1538 Tokens data
= StrSplit(fields
[19].GetCppString(), " ");
1539 for (uint8 slot
= 0; slot
< EQUIPMENT_SLOT_END
; slot
++)
1541 uint32 visualbase
= slot
* 2;
1542 uint32 item_id
= GetUInt32ValueFromArray(data
, visualbase
);
1543 const ItemPrototype
* proto
= ObjectMgr::GetItemPrototype(item_id
);
1546 *p_data
<< uint32(0);
1547 *p_data
<< uint8(0);
1548 *p_data
<< uint32(0);
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);
1562 if ((enchant
= sSpellItemEnchantmentStore
.LookupEntry(enchantId
)))
1566 *p_data
<< uint32(proto
->DisplayInfoID
);
1567 *p_data
<< uint8(proto
->InventoryType
);
1568 *p_data
<< uint32(enchant
? enchant
->aura_id
: 0);
1571 *p_data
<< uint32(0); // bag 1 display id
1572 *p_data
<< uint8(0); // bag 1 inventory type
1573 *p_data
<< uint32(0); // enchant?
1574 *p_data
<< uint32(0); // bag 2 display id
1575 *p_data
<< uint8(0); // bag 2 inventory type
1576 *p_data
<< uint32(0); // enchant?
1577 *p_data
<< uint32(0); // bag 3 display id
1578 *p_data
<< uint8(0); // bag 3 inventory type
1579 *p_data
<< uint32(0); // enchant?
1580 *p_data
<< uint32(0); // bag 4 display id
1581 *p_data
<< uint8(0); // bag 4 inventory type
1582 *p_data
<< uint32(0); // enchant?
1587 bool Player::ToggleAFK()
1589 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1591 bool state
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1593 // afk player not allowed in battleground
1594 if(state
&& InBattleGround())
1595 LeaveBattleground();
1600 bool Player::ToggleDND()
1602 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1604 return HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1607 uint8
Player::chatTag() const
1624 bool Player::TeleportTo(uint32 mapid
, float x
, float y
, float z
, float orientation
, uint32 options
)
1626 if(!MapManager::IsValidMapCoord(mapid
, x
, y
, z
, orientation
))
1628 sLog
.outError("TeleportTo: invalid map %d or absent instance template.", mapid
);
1632 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1633 Pet
* pet
= GetPet();
1635 MapEntry
const* mEntry
= sMapStore
.LookupEntry(mapid
);
1637 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1638 // don't let gm level > 1 either
1639 if(!InBattleGround() && mEntry
->IsBattleGroundOrArena())
1642 // client without expansion support
1643 if(GetSession()->Expansion() < mEntry
->Expansion())
1645 sLog
.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid
);
1648 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1650 SendTransferAborted(mapid
, TRANSFER_ABORT_INSUF_EXPAN_LVL
, mEntry
->Expansion());
1652 return false; // normal client can't teleport to this map...
1656 sLog
.outDebug("Player %s is being teleported to map %u", GetName(), mapid
);
1659 // if we were on a transport, leave
1660 if (!(options
& TELE_TO_NOT_LEAVE_TRANSPORT
) && m_transport
)
1662 m_transport
->RemovePassenger(this);
1664 m_movementInfo
.SetTransportData(0, 0.0f
, 0.0f
, 0.0f
, 0.0f
, 0, -1);
1667 // The player was ported to another map and looses the duel immediately.
1668 // We have to perform this check before the teleport, otherwise the
1669 // ObjectAccessor won't find the flag.
1670 if (duel
&& GetMapId() != mapid
)
1672 GameObject
* obj
= GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER
));
1674 DuelComplete(DUEL_FLED
);
1677 // reset movement flags at teleport, because player will continue move with these flags after teleport
1678 m_movementInfo
.SetMovementFlags(MOVEFLAG_NONE
);
1680 if ((GetMapId() == mapid
) && (!m_transport
))
1682 //lets reset far teleport flag if it wasn't reset during chained teleports
1683 SetSemaphoreTeleportFar(false);
1684 //setup delayed teleport flag
1685 SetDelayedTeleportFlag(IsCanDelayTeleport());
1686 //if teleport spell is casted in Unit::Update() func
1687 //then we need to delay it until update process will be finished
1688 if(IsHasDelayedTeleport())
1690 SetSemaphoreTeleportNear(true);
1691 //lets save teleport destination for player
1692 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1693 m_teleport_options
= options
;
1697 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1699 //same map, only remove pet if out of range for new position
1700 if(pet
&& !pet
->IsWithinDist3d(x
, y
, z
, GetMap()->GetVisibilityDistance()))
1701 UnsummonPetTemporaryIfAny();
1704 if(!(options
& TELE_TO_NOT_LEAVE_COMBAT
))
1707 // this will be used instead of the current location in SaveToDB
1708 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1709 SetFallInformation(0, z
);
1711 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1712 // at client packet MSG_MOVE_TELEPORT_ACK
1713 SetSemaphoreTeleportNear(true);
1714 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1715 if(!GetSession()->PlayerLogout())
1718 BuildTeleportAckMsg(&data
, x
, y
, z
, orientation
);
1719 GetSession()->SendPacket(&data
);
1724 // far teleport to another map
1725 Map
* oldmap
= IsInWorld() ? GetMap() : NULL
;
1726 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1728 // Check enter rights before map getting to avoid creating instance copy for player
1729 // this check not dependent from map instance copy and same for all instance copies of selected map
1730 if (!sMapMgr
.CanPlayerEnter(mapid
, this))
1733 // If the map is not created, assume it is possible to enter it.
1734 // It will be created in the WorldPortAck.
1735 Map
*map
= sMapMgr
.FindMap(mapid
);
1736 if (!map
|| map
->CanEnter(this))
1738 //lets reset near teleport flag if it wasn't reset during chained teleports
1739 SetSemaphoreTeleportNear(false);
1740 //setup delayed teleport flag
1741 SetDelayedTeleportFlag(IsCanDelayTeleport());
1742 //if teleport spell is casted in Unit::Update() func
1743 //then we need to delay it until update process will be finished
1744 if(IsHasDelayedTeleport())
1746 SetSemaphoreTeleportFar(true);
1747 //lets save teleport destination for player
1748 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1749 m_teleport_options
= options
;
1757 ResetContestedPvP();
1759 // remove player from battleground on far teleport (when changing maps)
1760 if(BattleGround
const* bg
= GetBattleGround())
1762 // Note: at battleground join battleground id set before teleport
1763 // and we already will found "current" battleground
1764 // just need check that this is targeted map or leave
1765 if(bg
->GetMapId() != mapid
)
1766 LeaveBattleground(false); // don't teleport to entry point
1769 // remove pet on map change
1771 UnsummonPetTemporaryIfAny();
1773 // remove all dyn objects
1774 RemoveAllDynObjects();
1776 // stop spellcasting
1777 // not attempt interrupt teleportation spell at caster teleport
1778 if(!(options
& TELE_TO_SPELL
))
1779 if(IsNonMeleeSpellCasted(true))
1780 InterruptNonMeleeSpells(true);
1782 //remove auras before removing from map...
1783 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP
| AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
1785 if(!GetSession()->PlayerLogout())
1787 // send transfer packets
1788 WorldPacket
data(SMSG_TRANSFER_PENDING
, (4+4+4));
1789 data
<< uint32(mapid
);
1792 data
<< uint32(m_transport
->GetEntry());
1793 data
<< uint32(GetMapId());
1795 GetSession()->SendPacket(&data
);
1797 data
.Initialize(SMSG_NEW_WORLD
, (20));
1800 data
<< uint32(mapid
);
1801 data
<< float(m_movementInfo
.GetTransportPos()->x
);
1802 data
<< float(m_movementInfo
.GetTransportPos()->y
);
1803 data
<< float(m_movementInfo
.GetTransportPos()->z
);
1804 data
<< float(m_movementInfo
.GetTransportPos()->o
);
1808 data
<< uint32(mapid
);
1812 data
<< float(orientation
);
1814 GetSession()->SendPacket( &data
);
1815 SendSavedInstances();
1818 // remove from old map now
1820 oldmap
->Remove(this, false);
1822 // new final coordinates
1826 float final_o
= orientation
;
1830 final_x
+= m_movementInfo
.GetTransportPos()->x
;
1831 final_y
+= m_movementInfo
.GetTransportPos()->y
;
1832 final_z
+= m_movementInfo
.GetTransportPos()->z
;
1833 final_o
+= m_movementInfo
.GetTransportPos()->o
;
1836 m_teleport_dest
= WorldLocation(mapid
, final_x
, final_y
, final_z
, final_o
);
1837 SetFallInformation(0, final_z
);
1838 // if the player is saved before worldport ack (at logout for example)
1839 // this will be used instead of the current location in SaveToDB
1841 // move packet sent by client always after far teleport
1842 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1843 SetSemaphoreTeleportFar(true);
1851 bool Player::TeleportToBGEntryPoint()
1853 ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE
);
1854 ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE
);
1855 return TeleportTo(m_bgData
.joinPos
);
1858 void Player::ProcessDelayedOperations()
1860 if(m_DelayedOperations
== 0)
1863 if(m_DelayedOperations
& DELAYED_RESURRECT_PLAYER
)
1865 ResurrectPlayer(0.0f
, false);
1867 if(GetMaxHealth() > m_resurrectHealth
)
1868 SetHealth( m_resurrectHealth
);
1870 SetHealth( GetMaxHealth() );
1872 if(GetMaxPower(POWER_MANA
) > m_resurrectMana
)
1873 SetPower(POWER_MANA
, m_resurrectMana
);
1875 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
) );
1877 SetPower(POWER_RAGE
, 0 );
1878 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
) );
1883 if(m_DelayedOperations
& DELAYED_SAVE_PLAYER
)
1888 if(m_DelayedOperations
& DELAYED_SPELL_CAST_DESERTER
)
1890 CastSpell(this, 26013, true); // Deserter
1893 if (m_DelayedOperations
& DELAYED_BG_MOUNT_RESTORE
)
1895 if (m_bgData
.mountSpell
)
1897 CastSpell(this, m_bgData
.mountSpell
, true);
1898 m_bgData
.mountSpell
= 0;
1902 if (m_DelayedOperations
& DELAYED_BG_TAXI_RESTORE
)
1904 if (m_bgData
.HasTaxiPath())
1906 m_taxi
.AddTaxiDestination(m_bgData
.taxiPath
[0]);
1907 m_taxi
.AddTaxiDestination(m_bgData
.taxiPath
[1]);
1908 m_bgData
.ClearTaxiPath();
1910 ContinueTaxiFlight();
1914 //we have executed ALL delayed ops, so clear the flag
1915 m_DelayedOperations
= 0;
1918 void Player::AddToWorld()
1920 ///- Do not add/remove the player from the object storage
1921 ///- It will crash when updating the ObjectAccessor
1922 ///- The player should only be added when logging in
1925 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; ++i
)
1928 m_items
[i
]->AddToWorld();
1932 void Player::RemoveFromWorld()
1937 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1938 UnsummonAllTotems();
1942 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; ++i
)
1945 m_items
[i
]->RemoveFromWorld();
1948 ///- Do not add/remove the player from the object storage
1949 ///- It will crash when updating the ObjectAccessor
1950 ///- The player should only be removed when logging out
1951 Unit::RemoveFromWorld();
1954 void Player::RewardRage( uint32 damage
, uint32 weaponSpeedHitFactor
, bool attacker
)
1958 float rageconversion
= float((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911f
;
1962 addRage
= ((damage
/rageconversion
*7.5f
+ weaponSpeedHitFactor
)/2.0f
);
1964 // talent who gave more rage on attack
1965 addRage
*= 1.0f
+ GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT
) / 100.0f
;
1969 addRage
= damage
/rageconversion
*2.5f
;
1971 // Berserker Rage effect
1972 if (HasAura(18499, EFFECT_INDEX_0
))
1976 addRage
*= sWorld
.getConfig(CONFIG_FLOAT_RATE_POWER_RAGE_INCOME
);
1978 ModifyPower(POWER_RAGE
, uint32(addRage
*10));
1981 void Player::RegenerateAll(uint32 diff
)
1983 // Not in combat or they have regeneration
1984 if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) ||
1985 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
) || IsPolymorphed() )
1987 RegenerateHealth(diff
);
1988 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN
))
1990 Regenerate(POWER_RAGE
, diff
);
1991 if(getClass() == CLASS_DEATH_KNIGHT
)
1992 Regenerate(POWER_RUNIC_POWER
, diff
);
1996 Regenerate(POWER_ENERGY
, diff
);
1998 Regenerate(POWER_MANA
, diff
);
2000 if (getClass() == CLASS_DEATH_KNIGHT
)
2001 Regenerate(POWER_RUNE
, diff
);
2003 m_regenTimer
= REGEN_TIME_FULL
;
2006 // diff contains the time in milliseconds since last regen.
2007 void Player::Regenerate(Powers power
, uint32 diff
)
2009 uint32 curValue
= GetPower(power
);
2010 uint32 maxValue
= GetMaxPower(power
);
2012 float addvalue
= 0.0f
;
2018 bool recentCast
= IsUnderLastManaUseEffect();
2019 float ManaIncreaseRate
= sWorld
.getConfig(CONFIG_FLOAT_RATE_POWER_MANA
);
2022 // Mangos Updates Mana in intervals of 2s, which is correct
2023 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
2027 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
2030 case POWER_RAGE
: // Regenerate rage
2032 float RageDecreaseRate
= sWorld
.getConfig(CONFIG_FLOAT_RATE_POWER_RAGE_LOSS
);
2033 addvalue
= 20 * RageDecreaseRate
; // 2 rage by tick (= 2 seconds => 1 rage/sec)
2035 case POWER_ENERGY
: // Regenerate energy (rogue)
2038 case POWER_RUNIC_POWER
:
2040 float RunicPowerDecreaseRate
= sWorld
.getConfig(CONFIG_FLOAT_RATE_POWER_RUNICPOWER_LOSS
);
2041 addvalue
= 30 * RunicPowerDecreaseRate
; // 3 RunicPower by tick
2045 if (getClass() != CLASS_DEATH_KNIGHT
)
2048 for(uint32 rune
= 0; rune
< MAX_RUNES
; ++rune
)
2050 if(uint16 cd
= GetRuneCooldown(rune
)) // if we have cooldown, reduce it...
2052 uint32 cd_diff
= diff
;
2053 AuraList
const& ModPowerRegenPCTAuras
= GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT
);
2054 for(AuraList::const_iterator i
= ModPowerRegenPCTAuras
.begin(); i
!= ModPowerRegenPCTAuras
.end(); ++i
)
2055 if ((*i
)->GetModifier()->m_miscvalue
== power
&& (*i
)->GetMiscBValue()==GetCurrentRune(rune
))
2056 cd_diff
= cd_diff
* ((*i
)->GetModifier()->m_amount
+ 100) / 100;
2058 SetRuneCooldown(rune
, (cd
< cd_diff
) ? 0 : cd
- cd_diff
);
2063 case POWER_HAPPINESS
:
2068 // Mana regen calculated in Player::UpdateManaRegen()
2069 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
2070 if(power
!= POWER_MANA
)
2072 AuraList
const& ModPowerRegenPCTAuras
= GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT
);
2073 for(AuraList::const_iterator i
= ModPowerRegenPCTAuras
.begin(); i
!= ModPowerRegenPCTAuras
.end(); ++i
)
2074 if ((*i
)->GetModifier()->m_miscvalue
== power
)
2075 addvalue
*= ((*i
)->GetModifier()->m_amount
+ 100) / 100.0f
;
2078 // addvalue computed on a 2sec basis. => update to diff time
2079 addvalue
*= float(diff
) / REGEN_TIME_FULL
;
2081 if (power
!= POWER_RAGE
&& power
!= POWER_RUNIC_POWER
)
2083 curValue
+= uint32(addvalue
);
2084 if (curValue
> maxValue
)
2085 curValue
= maxValue
;
2089 if(curValue
<= uint32(addvalue
))
2092 curValue
-= uint32(addvalue
);
2094 SetPower(power
, curValue
);
2097 void Player::RegenerateHealth(uint32 diff
)
2099 uint32 curValue
= GetHealth();
2100 uint32 maxValue
= GetMaxHealth();
2102 if (curValue
>= maxValue
) return;
2104 float HealthIncreaseRate
= sWorld
.getConfig(CONFIG_FLOAT_RATE_HEALTH
);
2106 float addvalue
= 0.0f
;
2109 if ( IsPolymorphed() )
2110 addvalue
= (float)GetMaxHealth()/3;
2111 // normal regen case (maybe partly in combat case)
2112 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) )
2114 addvalue
= OCTRegenHPPerSpirit()* HealthIncreaseRate
;
2117 AuraList
const& mModHealthRegenPct
= GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT
);
2118 for(AuraList::const_iterator i
= mModHealthRegenPct
.begin(); i
!= mModHealthRegenPct
.end(); ++i
)
2119 addvalue
*= (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
;
2121 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
))
2122 addvalue
*= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) / 100.0f
;
2128 // always regeneration bonus (including combat)
2129 addvalue
+= GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
);
2134 addvalue
*= (float)diff
/ REGEN_TIME_FULL
;
2136 ModifyHealth(int32(addvalue
));
2139 Creature
* Player::GetNPCIfCanInteractWith(ObjectGuid guid
, uint32 npcflagmask
)
2141 // some basic checks
2142 if (guid
.IsEmpty() || !IsInWorld() || isInFlight())
2145 // exist (we need look pets also for some interaction (quest/etc)
2146 Creature
*unit
= GetMap()->GetCreatureOrPetOrVehicle(guid
);
2150 // appropriate npc type
2151 if (npcflagmask
&& !unit
->HasFlag( UNIT_NPC_FLAGS
, npcflagmask
))
2154 if (npcflagmask
== UNIT_NPC_FLAG_STABLEMASTER
)
2156 if (getClass() != CLASS_HUNTER
)
2160 // if a dead unit should be able to talk - the creature must be alive and have special flags
2161 if (!unit
->isAlive())
2164 if (isAlive() && unit
->isInvisibleForAlive())
2167 // not allow interaction under control, but allow with own pets
2168 if (unit
->GetCharmerGUID())
2172 if (unit
->IsHostileTo(this))
2176 if(FactionTemplateEntry
const* factionTemplate
= sFactionTemplateStore
.LookupEntry(unit
->getFaction()))
2177 if(factionTemplate
->faction
)
2178 if(FactionEntry
const* faction
= sFactionStore
.LookupEntry(factionTemplate
->faction
))
2179 if(faction
->reputationListID
>= 0 && GetReputationMgr().GetRank(faction
) <= REP_UNFRIENDLY
)
2183 if(!unit
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
2189 GameObject
* Player::GetGameObjectIfCanInteractWith(ObjectGuid guid
, uint32 gameobject_type
) const
2191 // some basic checks
2192 if (guid
.IsEmpty() || !IsInWorld() || isInFlight())
2195 if (GameObject
*go
= GetMap()->GetGameObject(guid
))
2197 if (uint32(go
->GetGoType()) == gameobject_type
|| gameobject_type
== MAX_GAMEOBJECT_TYPE
)
2200 switch(go
->GetGoType())
2202 // TODO: find out how the client calculates the maximal usage distance to spellless working
2203 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2204 case GAMEOBJECT_TYPE_GUILD_BANK
:
2205 case GAMEOBJECT_TYPE_MAILBOX
:
2208 case GAMEOBJECT_TYPE_FISHINGHOLE
:
2209 maxdist
= 20.0f
+CONTACT_DISTANCE
; // max spell range
2212 maxdist
= INTERACTION_DISTANCE
;
2216 if (go
->IsWithinDistInMap(this, maxdist
) && go
->isSpawned())
2219 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
,
2220 go
->GetGUIDLow(), GetName(), GetGUIDLow(), go
->GetDistance(this));
2226 bool Player::IsUnderWater() const
2228 return IsInWater() &&
2229 GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2232 void Player::SetInWater(bool apply
)
2234 if(m_isInWater
==apply
)
2237 //define player in water by opcodes
2238 //move player's guid into HateOfflineList of those mobs
2239 //which can't swim and move guid back into ThreatList when
2241 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2242 m_isInWater
= apply
;
2244 // remove auras that need water/land
2245 RemoveAurasWithInterruptFlags(apply
? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER
: AURA_INTERRUPT_FLAG_NOT_UNDERWATER
);
2247 getHostileRefManager().updateThreatTables();
2250 struct SetGameMasterOnHelper
2252 explicit SetGameMasterOnHelper() {}
2253 void operator()(Unit
* unit
) const
2255 unit
->setFaction(35);
2256 unit
->getHostileRefManager().setOnlineOfflineState(false);
2260 struct SetGameMasterOffHelper
2262 explicit SetGameMasterOffHelper(uint32 _faction
) : faction(_faction
) {}
2263 void operator()(Unit
* unit
) const
2265 unit
->setFaction(faction
);
2266 unit
->getHostileRefManager().setOnlineOfflineState(true);
2271 void Player::SetGameMaster(bool on
)
2275 m_ExtraFlags
|= PLAYER_EXTRA_GM_ON
;
2277 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2279 CallForAllControlledUnits(SetGameMasterOnHelper(),true,true,true,false);
2282 ResetContestedPvP();
2284 getHostileRefManager().setOnlineOfflineState(false);
2285 CombatStopWithPets();
2287 SetPhaseMask(PHASEMASK_ANYWHERE
,false); // see and visible in all phases
2292 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
2293 SetPhaseMask(!phases
.empty() ? phases
.front()->GetMiscValue() : PHASEMASK_NORMAL
,false);
2295 m_ExtraFlags
&= ~ PLAYER_EXTRA_GM_ON
;
2296 setFactionForRace(getRace());
2297 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2299 CallForAllControlledUnits(SetGameMasterOffHelper(getFaction()),true,true,true,false);
2301 // restore FFA PvP Server state
2302 if(sWorld
.IsFFAPvPRealm())
2305 // restore FFA PvP area state, remove not allowed for GM mounts
2306 UpdateArea(m_areaUpdateId
);
2308 getHostileRefManager().setOnlineOfflineState(true);
2311 UpdateVisibilityForPlayer();
2314 void Player::SetGMVisible(bool on
)
2318 m_ExtraFlags
&= ~PLAYER_EXTRA_GM_INVISIBLE
; //remove flag
2320 // Reapply stealth/invisibility if active or show if not any
2321 if(HasAuraType(SPELL_AURA_MOD_STEALTH
))
2322 SetVisibility(VISIBILITY_GROUP_STEALTH
);
2323 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY
))
2324 SetVisibility(VISIBILITY_GROUP_INVISIBILITY
);
2326 SetVisibility(VISIBILITY_ON
);
2330 m_ExtraFlags
|= PLAYER_EXTRA_GM_INVISIBLE
; //add flag
2332 SetAcceptWhispers(false);
2333 SetGameMaster(true);
2335 SetVisibility(VISIBILITY_OFF
);
2339 bool Player::IsGroupVisibleFor(Player
* p
) const
2341 switch(sWorld
.getConfig(CONFIG_UINT32_GROUP_VISIBILITY
))
2343 default: return IsInSameGroupWith(p
);
2344 case 1: return IsInSameRaidWith(p
);
2345 case 2: return GetTeam()==p
->GetTeam();
2349 bool Player::IsInSameGroupWith(Player
const* p
) const
2351 return (p
==this || (GetGroup() != NULL
&&
2352 GetGroup()->SameSubGroup((Player
*)this, (Player
*)p
)));
2355 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2356 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2357 void Player::UninviteFromGroup()
2359 Group
* group
= GetGroupInvite();
2363 group
->RemoveInvite(this);
2365 if(group
->GetMembersCount() <= 1) // group has just 1 member => disband
2367 if(group
->IsCreated())
2369 group
->Disband(true);
2370 sObjectMgr
.RemoveGroup(group
);
2373 group
->RemoveAllInvites();
2379 void Player::RemoveFromGroup(Group
* group
, uint64 guid
)
2383 if (group
->RemoveMember(guid
, 0) <= 1)
2385 // group->Disband(); already disbanded in RemoveMember
2386 sObjectMgr
.RemoveGroup(group
);
2388 // removemember sets the player's group pointer to NULL
2393 void Player::SendLogXPGain(uint32 GivenXP
, Unit
* victim
, uint32 RestXP
)
2395 WorldPacket
data(SMSG_LOG_XPGAIN
, 21);
2396 data
<< uint64(victim
? victim
->GetGUID() : 0); // guid
2397 data
<< uint32(GivenXP
+RestXP
); // given experience
2398 data
<< uint8(victim
? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2401 data
<< uint32(GivenXP
); // experience without rested bonus
2402 data
<< float(1); // 1 - none 0 - 100% group bonus output
2404 data
<< uint8(0); // new 2.4.0
2405 GetSession()->SendPacket(&data
);
2408 void Player::GiveXP(uint32 xp
, Unit
* victim
)
2416 uint32 level
= getLevel();
2418 // XP to money conversion processed in Player::RewardQuest
2419 if(level
>= sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
))
2424 // handle SPELL_AURA_MOD_KILL_XP_PCT auras
2425 Unit::AuraList
const& ModXPPctAuras
= GetAurasByType(SPELL_AURA_MOD_KILL_XP_PCT
);
2426 for(Unit::AuraList::const_iterator i
= ModXPPctAuras
.begin();i
!= ModXPPctAuras
.end(); ++i
)
2427 xp
= uint32(xp
*(1.0f
+ (*i
)->GetModifier()->m_amount
/ 100.0f
));
2431 // handle SPELL_AURA_MOD_QUEST_XP_PCT auras
2432 Unit::AuraList
const& ModXPPctAuras
= GetAurasByType(SPELL_AURA_MOD_QUEST_XP_PCT
);
2433 for(Unit::AuraList::const_iterator i
= ModXPPctAuras
.begin();i
!= ModXPPctAuras
.end(); ++i
)
2434 xp
= uint32(xp
*(1.0f
+ (*i
)->GetModifier()->m_amount
/ 100.0f
));
2437 // XP resting bonus for kill
2438 uint32 rested_bonus_xp
= victim
? GetXPRestBonus(xp
) : 0;
2440 SendLogXPGain(xp
,victim
,rested_bonus_xp
);
2442 uint32 curXP
= GetUInt32Value(PLAYER_XP
);
2443 uint32 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2444 uint32 newXP
= curXP
+ xp
+ rested_bonus_xp
;
2446 while( newXP
>= nextLvlXP
&& level
< sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
) )
2450 if ( level
< sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
) )
2451 GiveLevel(level
+ 1);
2454 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2457 SetUInt32Value(PLAYER_XP
, newXP
);
2460 // Update player to next level
2461 // Current player experience not update (must be update by caller)
2462 void Player::GiveLevel(uint32 level
)
2464 if ( level
== getLevel() )
2467 PlayerLevelInfo info
;
2468 sObjectMgr
.GetPlayerLevelInfo(getRace(),getClass(),level
,&info
);
2470 PlayerClassLevelInfo classInfo
;
2471 sObjectMgr
.GetPlayerClassLevelInfo(getClass(),level
,&classInfo
);
2473 // send levelup info to client
2474 WorldPacket
data(SMSG_LEVELUP_INFO
, (4+4+MAX_POWERS
*4+MAX_STATS
*4));
2475 data
<< uint32(level
);
2476 data
<< uint32(int32(classInfo
.basehealth
) - int32(GetCreateHealth()));
2477 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2478 data
<< uint32(int32(classInfo
.basemana
) - int32(GetCreateMana()));
2486 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
) // Stats loop (0-4)
2487 data
<< uint32(int32(info
.stats
[i
]) - GetCreateStat(Stats(i
)));
2489 GetSession()->SendPacket(&data
);
2491 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, sObjectMgr
.GetXPForLevel(level
));
2493 //update level, max level of skills
2494 m_Played_time
[PLAYED_TIME_LEVEL
] = 0; // Level Played Time reset
2496 _ApplyAllLevelScaleItemMods(false);
2500 UpdateSkillsForLevel ();
2502 // save base values (bonuses already included in stored stats
2503 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2504 SetCreateStat(Stats(i
), info
.stats
[i
]);
2506 SetCreateHealth(classInfo
.basehealth
);
2507 SetCreateMana(classInfo
.basemana
);
2509 InitTalentForLevel();
2510 InitTaxiNodesForLevel();
2511 InitGlyphsForLevel();
2515 // set current level health and mana/energy to maximum after applying all mods.
2516 SetHealth(GetMaxHealth());
2517 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2518 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2519 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2520 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2521 SetPower(POWER_FOCUS
, 0);
2522 SetPower(POWER_HAPPINESS
, 0);
2524 _ApplyAllLevelScaleItemMods(true);
2526 // update level to hunter/summon pet
2527 if (Pet
* pet
= GetPet())
2528 pet
->SynchronizeLevelWithOwner();
2530 if (MailLevelReward
const* mailReward
= sObjectMgr
.GetMailLevelReward(level
,getRaceMask()))
2531 MailDraft(mailReward
->mailTemplateId
).SendMailTo(this,MailSender(MAIL_CREATURE
,mailReward
->senderEntry
));
2533 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL
);
2536 void Player::UpdateFreeTalentPoints(bool resetIfNeed
)
2538 uint32 level
= getLevel();
2539 // talents base at level diff ( talents = level - 9 but some can be used already)
2542 // Remove all talent points
2543 if (m_usedTalentCount
> 0) // Free any used talents
2547 SetFreeTalentPoints(0);
2552 uint32 talentPointsForLevel
= CalculateTalentsPoints();
2554 // if used more that have then reset
2555 if (m_usedTalentCount
> talentPointsForLevel
)
2557 if (resetIfNeed
&& GetSession()->GetSecurity() < SEC_ADMINISTRATOR
)
2560 SetFreeTalentPoints(0);
2562 // else update amount of free points
2564 SetFreeTalentPoints(talentPointsForLevel
-m_usedTalentCount
);
2568 void Player::InitTalentForLevel()
2570 UpdateFreeTalentPoints();
2572 if (!GetSession()->PlayerLoading())
2573 SendTalentsInfoData(false); // update at client
2576 void Player::InitStatsForLevel(bool reapplyMods
)
2578 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2579 _RemoveAllStatBonuses();
2581 PlayerClassLevelInfo classInfo
;
2582 sObjectMgr
.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo
);
2584 PlayerLevelInfo info
;
2585 sObjectMgr
.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info
);
2587 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL
, sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
) );
2588 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, sObjectMgr
.GetXPForLevel(getLevel()));
2590 // reset before any aura state sources (health set/aura apply)
2591 SetUInt32Value(UNIT_FIELD_AURASTATE
, 0);
2593 UpdateSkillsForLevel ();
2595 // set default cast time multiplier
2596 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
);
2598 // reset size before reapply auras
2599 SetFloatValue(OBJECT_FIELD_SCALE_X
,1.0f
);
2601 // save base values (bonuses already included in stored stats
2602 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2603 SetCreateStat(Stats(i
), info
.stats
[i
]);
2605 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2606 SetStat(Stats(i
), info
.stats
[i
]);
2608 SetCreateHealth(classInfo
.basehealth
);
2611 SetCreateMana(classInfo
.basemana
);
2613 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2617 //reset rating fields values
2618 for(uint16 index
= PLAYER_FIELD_COMBAT_RATING_1
; index
< PLAYER_FIELD_COMBAT_RATING_1
+ MAX_COMBAT_RATING
; ++index
)
2619 SetUInt32Value(index
, 0);
2621 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS
,0);
2622 for (int i
= 0; i
< 7; ++i
)
2624 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
+i
, 0);
2625 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS
+i
, 0);
2626 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT
+i
, 1.00f
);
2629 //reset attack power, damage and attack speed fields
2630 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
, 2000.0f
);
2631 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
+ 1, 2000.0f
); // offhand attack time
2632 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME
, 2000.0f
);
2634 SetFloatValue(UNIT_FIELD_MINDAMAGE
, 0.0f
);
2635 SetFloatValue(UNIT_FIELD_MAXDAMAGE
, 0.0f
);
2636 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
, 0.0f
);
2637 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
, 0.0f
);
2638 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
, 0.0f
);
2639 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
, 0.0f
);
2641 SetInt32Value(UNIT_FIELD_ATTACK_POWER
, 0 );
2642 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS
, 0 );
2643 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER
,0.0f
);
2644 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER
, 0 );
2645 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS
,0 );
2646 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER
,0.0f
);
2648 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2649 SetFloatValue(PLAYER_CRIT_PERCENTAGE
,0.0f
);
2650 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE
,0.0f
);
2651 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE
,0.0f
);
2653 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2654 for (uint8 i
= 0; i
< 7; ++i
)
2655 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1
+i
, 0.0f
);
2657 SetFloatValue(PLAYER_PARRY_PERCENTAGE
, 0.0f
);
2658 SetFloatValue(PLAYER_BLOCK_PERCENTAGE
, 0.0f
);
2659 SetUInt32Value(PLAYER_SHIELD_BLOCK
, 0);
2662 SetFloatValue(PLAYER_DODGE_PERCENTAGE
, 0.0f
);
2664 // set armor (resistance 0) to original value (create_agility*2)
2665 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2666 SetResistanceBuffMods(SpellSchools(0), true, 0.0f
);
2667 SetResistanceBuffMods(SpellSchools(0), false, 0.0f
);
2668 // set other resistance to original value (0)
2669 for (int i
= 1; i
< MAX_SPELL_SCHOOL
; ++i
)
2671 SetResistance(SpellSchools(i
), 0);
2672 SetResistanceBuffMods(SpellSchools(i
), true, 0.0f
);
2673 SetResistanceBuffMods(SpellSchools(i
), false, 0.0f
);
2676 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE
,0);
2677 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE
,0);
2678 for(int i
= 0; i
< MAX_SPELL_SCHOOL
; ++i
)
2680 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER
+i
,0);
2681 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER
+i
,0.0f
);
2683 // Reset no reagent cost field
2684 for(int i
= 0; i
< 3; ++i
)
2685 SetUInt32Value(PLAYER_NO_REAGENT_COST_1
+ i
, 0);
2686 // Init data for form but skip reapply item mods for form
2687 InitDataForForm(reapplyMods
);
2690 for (int i
= POWER_MANA
; i
< MAX_POWERS
; ++i
)
2691 SetMaxPower(Powers(i
), uint32(GetCreatePowers(Powers(i
))));
2693 SetMaxHealth(classInfo
.basehealth
); // stamina bonus will applied later
2695 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2696 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID
, 0);
2698 // cleanup unit flags (will be re-applied if need at aura load).
2699 RemoveFlag( UNIT_FIELD_FLAGS
,
2700 UNIT_FLAG_NON_ATTACKABLE
| UNIT_FLAG_DISABLE_MOVE
| UNIT_FLAG_NOT_ATTACKABLE_1
|
2701 UNIT_FLAG_OOC_NOT_ATTACKABLE
| UNIT_FLAG_PASSIVE
| UNIT_FLAG_LOOTING
|
2702 UNIT_FLAG_PET_IN_COMBAT
| UNIT_FLAG_SILENCED
| UNIT_FLAG_PACIFIED
|
2703 UNIT_FLAG_STUNNED
| UNIT_FLAG_IN_COMBAT
| UNIT_FLAG_DISARMED
|
2704 UNIT_FLAG_CONFUSED
| UNIT_FLAG_FLEEING
| UNIT_FLAG_NOT_SELECTABLE
|
2705 UNIT_FLAG_SKINNABLE
| UNIT_FLAG_MOUNT
| UNIT_FLAG_TAXI_FLIGHT
);
2706 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
); // must be set
2708 SetFlag(UNIT_FIELD_FLAGS_2
,UNIT_FLAG2_REGENERATE_POWER
);// must be set
2710 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2711 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
| PLAYER_FLAGS_DND
| PLAYER_FLAGS_GM
| PLAYER_FLAGS_GHOST
);
2713 RemoveStandFlags(UNIT_STAND_FLAGS_ALL
); // one form stealth modified bytes
2714 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
| UNIT_BYTE2_FLAG_SANCTUARY
);
2716 // restore if need some important flags
2717 SetUInt32Value(PLAYER_FIELD_BYTES2
, 0 ); // flags empty by default
2719 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2720 _ApplyAllStatBonuses();
2722 // set current level health and mana/energy to maximum after applying all mods.
2723 SetHealth(GetMaxHealth());
2724 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2725 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2726 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2727 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2728 SetPower(POWER_FOCUS
, 0);
2729 SetPower(POWER_HAPPINESS
, 0);
2730 SetPower(POWER_RUNIC_POWER
, 0);
2732 // update level to hunter/summon pet
2733 if (Pet
* pet
= GetPet())
2734 pet
->SynchronizeLevelWithOwner();
2737 void Player::SendInitialSpells()
2739 time_t curTime
= time(NULL
);
2740 time_t infTime
= curTime
+ infinityCooldownDelayCheck
;
2742 uint16 spellCount
= 0;
2744 WorldPacket
data(SMSG_INITIAL_SPELLS
, (1+2+4*m_spells
.size()+2+m_spellCooldowns
.size()*(2+2+2+4+4)));
2747 size_t countPos
= data
.wpos();
2748 data
<< uint16(spellCount
); // spell count placeholder
2750 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2752 if(itr
->second
.state
== PLAYERSPELL_REMOVED
)
2755 if(!itr
->second
.active
|| itr
->second
.disabled
)
2758 data
<< uint32(itr
->first
);
2759 data
<< uint16(0); // it's not slot id
2764 data
.put
<uint16
>(countPos
,spellCount
); // write real count value
2766 uint16 spellCooldowns
= m_spellCooldowns
.size();
2767 data
<< uint16(spellCooldowns
);
2768 for(SpellCooldowns::const_iterator itr
=m_spellCooldowns
.begin(); itr
!=m_spellCooldowns
.end(); ++itr
)
2770 SpellEntry
const *sEntry
= sSpellStore
.LookupEntry(itr
->first
);
2774 data
<< uint32(itr
->first
);
2776 data
<< uint16(itr
->second
.itemid
); // cast item id
2777 data
<< uint16(sEntry
->Category
); // spell category
2779 // send infinity cooldown in special format
2780 if(itr
->second
.end
>= infTime
)
2782 data
<< uint32(1); // cooldown
2783 data
<< uint32(0x80000000); // category cooldown
2787 time_t cooldown
= itr
->second
.end
> curTime
? (itr
->second
.end
-curTime
)*IN_MILLISECONDS
: 0;
2789 if(sEntry
->Category
) // may be wrong, but anyway better than nothing...
2791 data
<< uint32(0); // cooldown
2792 data
<< uint32(cooldown
); // category cooldown
2796 data
<< uint32(cooldown
); // cooldown
2797 data
<< uint32(0); // category cooldown
2801 GetSession()->SendPacket(&data
);
2803 sLog
.outDetail( "CHARACTER: Sent Initial Spells" );
2806 void Player::RemoveMail(uint32 id
)
2808 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
2810 if ((*itr
)->messageID
== id
)
2812 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2819 void Player::SendMailResult(uint32 mailId
, MailResponseType mailAction
, MailResponseResult mailError
, uint32 equipError
, uint32 item_guid
, uint32 item_count
)
2821 WorldPacket
data(SMSG_SEND_MAIL_RESULT
, (4+4+4+(mailError
== MAIL_ERR_EQUIP_ERROR
?4:(mailAction
== MAIL_ITEM_TAKEN
?4+4:0))));
2822 data
<< (uint32
) mailId
;
2823 data
<< (uint32
) mailAction
;
2824 data
<< (uint32
) mailError
;
2825 if ( mailError
== MAIL_ERR_EQUIP_ERROR
)
2826 data
<< (uint32
) equipError
;
2827 else if( mailAction
== MAIL_ITEM_TAKEN
)
2829 data
<< (uint32
) item_guid
; // item guid low?
2830 data
<< (uint32
) item_count
; // item count?
2832 GetSession()->SendPacket(&data
);
2835 void Player::SendNewMail()
2837 // deliver undelivered mail
2838 WorldPacket
data(SMSG_RECEIVED_MAIL
, 4);
2840 GetSession()->SendPacket(&data
);
2843 void Player::UpdateNextMailTimeAndUnreads()
2845 // calculate next delivery time (min. from non-delivered mails
2846 // and recalculate unReadMail
2847 time_t cTime
= time(NULL
);
2848 m_nextMailDelivereTime
= 0;
2850 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
2852 if((*itr
)->deliver_time
> cTime
)
2854 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> (*itr
)->deliver_time
)
2855 m_nextMailDelivereTime
= (*itr
)->deliver_time
;
2857 else if(((*itr
)->checked
& MAIL_CHECK_MASK_READ
) == 0)
2862 void Player::AddNewMailDeliverTime(time_t deliver_time
)
2864 if(deliver_time
<= time(NULL
)) // ready now
2869 else // not ready and no have ready mails
2871 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> deliver_time
)
2872 m_nextMailDelivereTime
= deliver_time
;
2876 bool Player::addSpell(uint32 spell_id
, bool active
, bool learning
, bool dependent
, bool disabled
)
2878 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
2881 // do character spell book cleanup (all characters)
2882 if(!IsInWorld() && !learning
) // spell load case
2884 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id
);
2885 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2888 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id
);
2893 if(!SpellMgr::IsSpellValid(spellInfo
,this,false))
2895 // do character spell book cleanup (all characters)
2896 if(!IsInWorld() && !learning
) // spell load case
2898 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id
);
2899 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2902 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id
);
2907 PlayerSpellState state
= learning
? PLAYERSPELL_NEW
: PLAYERSPELL_UNCHANGED
;
2909 bool dependent_set
= false;
2910 bool disabled_case
= false;
2911 bool superceded_old
= false;
2913 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2914 if (itr
!= m_spells
.end())
2916 uint32 next_active_spell_id
= 0;
2917 // fix activate state for non-stackable low rank (and find next spell for !active case)
2918 if(!SpellMgr::canStackSpellRanks(spellInfo
) && sSpellMgr
.GetSpellRank(spellInfo
->Id
) != 0)
2920 SpellChainMapNext
const& nextMap
= sSpellMgr
.GetSpellChainNext();
2921 for(SpellChainMapNext::const_iterator next_itr
= nextMap
.lower_bound(spell_id
); next_itr
!= nextMap
.upper_bound(spell_id
); ++next_itr
)
2923 if(HasSpell(next_itr
->second
))
2925 // high rank already known so this must !active
2927 next_active_spell_id
= next_itr
->second
;
2933 // not do anything if already known in expected state
2934 if(itr
->second
.state
!= PLAYERSPELL_REMOVED
&& itr
->second
.active
== active
&&
2935 itr
->second
.dependent
== dependent
&& itr
->second
.disabled
== disabled
)
2937 if(!IsInWorld() && !learning
) // explicitly load from DB and then exist in it already and set correctly
2938 itr
->second
.state
= PLAYERSPELL_UNCHANGED
;
2943 // dependent spell known as not dependent, overwrite state
2944 if (itr
->second
.state
!= PLAYERSPELL_REMOVED
&& !itr
->second
.dependent
&& dependent
)
2946 itr
->second
.dependent
= dependent
;
2947 if (itr
->second
.state
!= PLAYERSPELL_NEW
)
2948 itr
->second
.state
= PLAYERSPELL_CHANGED
;
2949 dependent_set
= true;
2952 // update active state for known spell
2953 if(itr
->second
.active
!= active
&& itr
->second
.state
!= PLAYERSPELL_REMOVED
&& !itr
->second
.disabled
)
2955 itr
->second
.active
= active
;
2957 if(!IsInWorld() && !learning
&& !dependent_set
) // explicitly load from DB and then exist in it already and set correctly
2958 itr
->second
.state
= PLAYERSPELL_UNCHANGED
;
2959 else if(itr
->second
.state
!= PLAYERSPELL_NEW
)
2960 itr
->second
.state
= PLAYERSPELL_CHANGED
;
2964 if (IsPassiveSpell(spell_id
) && IsNeedCastPassiveSpellAtLearn(spellInfo
))
2965 CastSpell (this, spell_id
, true);
2967 else if(IsInWorld())
2969 if(next_active_spell_id
)
2971 // update spell ranks in spellbook and action bar
2972 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, 4 + 4);
2973 data
<< uint32(spell_id
);
2974 data
<< uint32(next_active_spell_id
);
2975 GetSession()->SendPacket( &data
);
2979 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2980 data
<< uint32(spell_id
);
2981 GetSession()->SendPacket(&data
);
2985 return active
; // learn (show in spell book if active now)
2988 if(itr
->second
.disabled
!= disabled
&& itr
->second
.state
!= PLAYERSPELL_REMOVED
)
2990 if(itr
->second
.state
!= PLAYERSPELL_NEW
)
2991 itr
->second
.state
= PLAYERSPELL_CHANGED
;
2992 itr
->second
.disabled
= disabled
;
2997 disabled_case
= true;
2999 else switch(itr
->second
.state
)
3001 case PLAYERSPELL_UNCHANGED
: // known saved spell
3003 case PLAYERSPELL_REMOVED
: // re-learning removed not saved spell
3005 m_spells
.erase(itr
);
3006 state
= PLAYERSPELL_CHANGED
;
3007 break; // need re-add
3009 default: // known not saved yet spell (new or modified)
3011 // can be in case spell loading but learned at some previous spell loading
3012 if(!IsInWorld() && !learning
&& !dependent_set
)
3013 itr
->second
.state
= PLAYERSPELL_UNCHANGED
;
3020 TalentSpellPos
const* talentPos
= GetTalentSpellPos(spell_id
);
3022 if(!disabled_case
) // skip new spell adding if spell already known (disabled spells case)
3024 // talent: unlearn all other talent ranks (high and low)
3027 if(TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentPos
->talent_id
))
3029 for(int i
=0; i
< MAX_TALENT_RANK
; ++i
)
3031 // skip learning spell and no rank spell case
3032 uint32 rankSpellId
= talentInfo
->RankID
[i
];
3033 if(!rankSpellId
|| rankSpellId
== spell_id
)
3036 removeSpell(rankSpellId
, false, false);
3040 // non talent spell: learn low ranks (recursive call)
3041 else if(uint32 prev_spell
= sSpellMgr
.GetPrevSpellInChain(spell_id
))
3043 if(!IsInWorld() || disabled
) // at spells loading, no output, but allow save
3044 addSpell(prev_spell
, active
, true, true, disabled
);
3045 else // at normal learning
3046 learnSpell(prev_spell
, true);
3049 PlayerSpell newspell
;
3050 newspell
.state
= state
;
3051 newspell
.active
= active
;
3052 newspell
.dependent
= dependent
;
3053 newspell
.disabled
= disabled
;
3055 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
3056 if(newspell
.active
&& !newspell
.disabled
&& !SpellMgr::canStackSpellRanks(spellInfo
) && sSpellMgr
.GetSpellRank(spellInfo
->Id
) != 0)
3058 for( PlayerSpellMap::iterator itr2
= m_spells
.begin(); itr2
!= m_spells
.end(); ++itr2
)
3060 if(itr2
->second
.state
== PLAYERSPELL_REMOVED
) continue;
3061 SpellEntry
const *i_spellInfo
= sSpellStore
.LookupEntry(itr2
->first
);
3062 if(!i_spellInfo
) continue;
3064 if( sSpellMgr
.IsRankSpellDueToSpell(spellInfo
, itr2
->first
) )
3066 if(itr2
->second
.active
)
3068 if(sSpellMgr
.IsHighRankOfSpell(spell_id
,itr2
->first
))
3070 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
3072 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, 4 + 4);
3073 data
<< uint32(itr2
->first
);
3074 data
<< uint32(spell_id
);
3075 GetSession()->SendPacket( &data
);
3078 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
3079 itr2
->second
.active
= false;
3080 if(itr2
->second
.state
!= PLAYERSPELL_NEW
)
3081 itr2
->second
.state
= PLAYERSPELL_CHANGED
;
3082 superceded_old
= true; // new spell replace old in action bars and spell book.
3084 else if(sSpellMgr
.IsHighRankOfSpell(itr2
->first
,spell_id
))
3086 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
3088 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, 4 + 4);
3089 data
<< uint32(spell_id
);
3090 data
<< uint32(itr2
->first
);
3091 GetSession()->SendPacket( &data
);
3094 // mark new spell as disable (not learned yet for client and will not learned)
3095 newspell
.active
= false;
3096 if(newspell
.state
!= PLAYERSPELL_NEW
)
3097 newspell
.state
= PLAYERSPELL_CHANGED
;
3104 m_spells
[spell_id
] = newspell
;
3106 // return false if spell disabled
3107 if (newspell
.disabled
)
3113 // update talent map
3114 PlayerTalentMap::iterator iter
= m_talents
[m_activeSpec
].find(talentPos
->talent_id
);
3115 if (iter
!= m_talents
[m_activeSpec
].end())
3117 // check if ranks different or removed
3118 if ((*iter
).second
.state
== PLAYERSPELL_REMOVED
|| talentPos
->rank
!= (*iter
).second
.currentRank
)
3120 (*iter
).second
.currentRank
= talentPos
->rank
;
3122 if ((*iter
).second
.state
!= PLAYERSPELL_NEW
)
3123 (*iter
).second
.state
= PLAYERSPELL_CHANGED
;
3128 PlayerTalent talent
;
3129 talent
.currentRank
= talentPos
->rank
;
3130 talent
.m_talentEntry
= sTalentStore
.LookupEntry(talentPos
->talent_id
);
3131 talent
.state
= IsInWorld() ? PLAYERSPELL_NEW
: PLAYERSPELL_UNCHANGED
;
3132 m_talents
[m_activeSpec
][talentPos
->talent_id
] = talent
;
3135 // update used talent points count
3136 m_usedTalentCount
+= GetTalentSpellCost(talentPos
);
3137 UpdateFreeTalentPoints(false);
3140 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
3141 if (uint32 freeProfs
= GetFreePrimaryProfessionPoints())
3143 if(sSpellMgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
3144 SetFreePrimaryProfessions(freeProfs
-1);
3147 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
3148 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
3149 if (talentPos
&& IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_LEARN_SPELL
))
3151 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
3152 CastSpell(this, spell_id
, true);
3154 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
3155 else if (IsPassiveSpell(spell_id
))
3157 if (IsNeedCastPassiveSpellAtLearn(spellInfo
))
3158 CastSpell(this, spell_id
, true);
3160 else if (IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_SKILL_STEP
))
3162 CastSpell(this, spell_id
, true);
3166 // add dependent skills
3167 uint16 maxskill
= GetMaxSkillValueForLevel();
3169 SpellLearnSkillNode
const* spellLearnSkill
= sSpellMgr
.GetSpellLearnSkill(spell_id
);
3171 SkillLineAbilityMapBounds skill_bounds
= sSpellMgr
.GetSkillLineAbilityMapBounds(spell_id
);
3173 if (spellLearnSkill
)
3175 uint32 skill_value
= GetPureSkillValue(spellLearnSkill
->skill
);
3176 uint32 skill_max_value
= GetPureMaxSkillValue(spellLearnSkill
->skill
);
3178 if (skill_value
< spellLearnSkill
->value
)
3179 skill_value
= spellLearnSkill
->value
;
3181 uint32 new_skill_max_value
= spellLearnSkill
->maxvalue
== 0 ? maxskill
: spellLearnSkill
->maxvalue
;
3183 if (skill_max_value
< new_skill_max_value
)
3184 skill_max_value
= new_skill_max_value
;
3186 SetSkill(spellLearnSkill
->skill
, spellLearnSkill
->step
, skill_value
, skill_max_value
);
3190 // not ranked skills
3191 for(SkillLineAbilityMap::const_iterator _spell_idx
= skill_bounds
.first
; _spell_idx
!= skill_bounds
.second
; ++_spell_idx
)
3193 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
3197 if (HasSkill(pSkill
->id
))
3200 if (_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
3201 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3202 ((pSkill
->id
==SKILL_LOCKPICKING
|| pSkill
->id
==SKILL_RUNEFORGING
) && _spell_idx
->second
->max_value
==0))
3204 switch(GetSkillRangeType(pSkill
, _spell_idx
->second
->racemask
!= 0))
3206 case SKILL_RANGE_LANGUAGE
:
3207 SetSkill(pSkill
->id
, GetSkillStep(pSkill
->id
), 300, 300 );
3209 case SKILL_RANGE_LEVEL
:
3210 SetSkill(pSkill
->id
, GetSkillStep(pSkill
->id
), 1, GetMaxSkillValueForLevel() );
3212 case SKILL_RANGE_MONO
:
3213 SetSkill(pSkill
->id
, GetSkillStep(pSkill
->id
), 1, 1 );
3222 // learn dependent spells
3223 SpellLearnSpellMapBounds spell_bounds
= sSpellMgr
.GetSpellLearnSpellMapBounds(spell_id
);
3225 for(SpellLearnSpellMap::const_iterator itr2
= spell_bounds
.first
; itr2
!= spell_bounds
.second
; ++itr2
)
3227 if (!itr2
->second
.autoLearned
)
3229 if (!IsInWorld() || !itr2
->second
.active
) // at spells loading, no output, but allow save
3230 addSpell(itr2
->second
.spell
,itr2
->second
.active
,true,true,false);
3231 else // at normal learning
3232 learnSpell(itr2
->second
.spell
, true);
3236 if (!GetSession()->PlayerLoading())
3238 // not ranked skills
3239 for(SkillLineAbilityMap::const_iterator _spell_idx
= skill_bounds
.first
; _spell_idx
!= skill_bounds
.second
; ++_spell_idx
)
3241 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE
,_spell_idx
->second
->skillId
);
3242 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS
,_spell_idx
->second
->skillId
);
3245 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL
,spell_id
);
3248 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
3249 return active
&& !disabled
&& !superceded_old
;
3252 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry
const* spellInfo
) const
3254 // note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell
3255 // talent dependent passives activated at form apply have proper stance data
3256 bool need_cast
= (!spellInfo
->Stances
|| (m_form
!= 0 && (spellInfo
->Stances
& (1<<(m_form
-1)))));
3258 //Check CasterAuraStates
3259 return need_cast
&& (!spellInfo
->CasterAuraState
|| HasAuraState(AuraState(spellInfo
->CasterAuraState
)));
3262 void Player::learnSpell(uint32 spell_id
, bool dependent
)
3264 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3266 bool disabled
= (itr
!= m_spells
.end()) ? itr
->second
.disabled
: false;
3267 bool active
= disabled
? itr
->second
.active
: true;
3269 bool learning
= addSpell(spell_id
, active
, true, dependent
, false);
3271 // learn all disabled higher ranks (recursive)
3274 SpellChainMapNext
const& nextMap
= sSpellMgr
.GetSpellChainNext();
3275 for(SpellChainMapNext::const_iterator i
= nextMap
.lower_bound(spell_id
); i
!= nextMap
.upper_bound(spell_id
); ++i
)
3277 PlayerSpellMap::iterator iter
= m_spells
.find(i
->second
);
3278 if (iter
!= m_spells
.end() && iter
->second
.disabled
)
3279 learnSpell(i
->second
, false);
3283 // prevent duplicated entires in spell book, also not send if not in world (loading)
3284 if(!learning
|| !IsInWorld ())
3287 WorldPacket
data(SMSG_LEARNED_SPELL
, 6);
3288 data
<< uint32(spell_id
);
3289 data
<< uint16(0); // 3.3.3 unk
3290 GetSession()->SendPacket(&data
);
3293 void Player::removeSpell(uint32 spell_id
, bool disabled
, bool learn_low_rank
, bool sendUpdate
)
3295 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3296 if (itr
== m_spells
.end())
3299 if (itr
->second
.state
== PLAYERSPELL_REMOVED
|| (disabled
&& itr
->second
.disabled
))
3302 // unlearn non talent higher ranks (recursive)
3303 SpellChainMapNext
const& nextMap
= sSpellMgr
.GetSpellChainNext();
3304 for(SpellChainMapNext::const_iterator itr2
= nextMap
.lower_bound(spell_id
); itr2
!= nextMap
.upper_bound(spell_id
); ++itr2
)
3305 if(HasSpell(itr2
->second
) && !GetTalentSpellPos(itr2
->second
))
3306 removeSpell(itr2
->second
, disabled
, false);
3308 // re-search, it can be corrupted in prev loop
3309 itr
= m_spells
.find(spell_id
);
3310 if (itr
== m_spells
.end() || itr
->second
.state
== PLAYERSPELL_REMOVED
)
3311 return; // already unleared
3313 bool cur_active
= itr
->second
.active
;
3314 bool cur_dependent
= itr
->second
.dependent
;
3318 itr
->second
.disabled
= disabled
;
3319 if(itr
->second
.state
!= PLAYERSPELL_NEW
)
3320 itr
->second
.state
= PLAYERSPELL_CHANGED
;
3324 if(itr
->second
.state
== PLAYERSPELL_NEW
)
3325 m_spells
.erase(itr
);
3327 itr
->second
.state
= PLAYERSPELL_REMOVED
;
3330 RemoveAurasDueToSpell(spell_id
);
3333 for(int i
= 0; i
< MAX_EFFECT_INDEX
; ++i
)
3334 if(PetAura
const* petSpell
= sSpellMgr
.GetPetAura(spell_id
, SpellEffectIndex(i
)))
3335 RemovePetAura(petSpell
);
3337 TalentSpellPos
const* talentPos
= GetTalentSpellPos(spell_id
);
3340 // update talent map
3341 PlayerTalentMap::iterator iter
= m_talents
[m_activeSpec
].find(talentPos
->talent_id
);
3342 if (iter
!= m_talents
[m_activeSpec
].end())
3344 if ((*iter
).second
.state
!= PLAYERSPELL_NEW
)
3345 (*iter
).second
.state
= PLAYERSPELL_REMOVED
;
3347 m_talents
[m_activeSpec
].erase(iter
);
3350 sLog
.outError("removeSpell: Player (GUID: %u) has talent spell (id: %u) but doesn't have talent",GetGUIDLow(), spell_id
);
3352 // free talent points
3353 uint32 talentCosts
= GetTalentSpellCost(talentPos
);
3355 if(talentCosts
< m_usedTalentCount
)
3356 m_usedTalentCount
-= talentCosts
;
3358 m_usedTalentCount
= 0;
3360 UpdateFreeTalentPoints(false);
3363 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3364 if(sSpellMgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
3366 uint32 freeProfs
= GetFreePrimaryProfessionPoints()+1;
3367 if(freeProfs
<= sWorld
.getConfig(CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL
))
3368 SetFreePrimaryProfessions(freeProfs
);
3371 // remove dependent skill
3372 SpellLearnSkillNode
const* spellLearnSkill
= sSpellMgr
.GetSpellLearnSkill(spell_id
);
3375 uint32 prev_spell
= sSpellMgr
.GetPrevSpellInChain(spell_id
);
3376 if(!prev_spell
) // first rank, remove skill
3377 SetSkill(spellLearnSkill
->skill
, 0, 0, 0);
3380 // search prev. skill setting by spell ranks chain
3381 SpellLearnSkillNode
const* prevSkill
= sSpellMgr
.GetSpellLearnSkill(prev_spell
);
3382 while(!prevSkill
&& prev_spell
)
3384 prev_spell
= sSpellMgr
.GetPrevSpellInChain(prev_spell
);
3385 prevSkill
= sSpellMgr
.GetSpellLearnSkill(sSpellMgr
.GetFirstSpellInChain(prev_spell
));
3388 if (!prevSkill
) // not found prev skill setting, remove skill
3389 SetSkill(spellLearnSkill
->skill
, 0, 0, 0);
3390 else // set to prev. skill setting values
3392 uint32 skill_value
= GetPureSkillValue(prevSkill
->skill
);
3393 uint32 skill_max_value
= GetPureMaxSkillValue(prevSkill
->skill
);
3395 if (skill_value
> prevSkill
->value
)
3396 skill_value
= prevSkill
->value
;
3398 uint32 new_skill_max_value
= prevSkill
->maxvalue
== 0 ? GetMaxSkillValueForLevel() : prevSkill
->maxvalue
;
3400 if (skill_max_value
> new_skill_max_value
)
3401 skill_max_value
= new_skill_max_value
;
3403 SetSkill(prevSkill
->skill
, prevSkill
->step
, skill_value
, skill_max_value
);
3410 // not ranked skills
3411 SkillLineAbilityMapBounds bounds
= sSpellMgr
.GetSkillLineAbilityMapBounds(spell_id
);
3413 for(SkillLineAbilityMap::const_iterator _spell_idx
= bounds
.first
; _spell_idx
!= bounds
.second
; ++_spell_idx
)
3415 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
3419 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
&&
3420 pSkill
->categoryId
!= SKILL_CATEGORY_CLASS
||// not unlearn class skills (spellbook/talent pages)
3421 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3422 ((pSkill
->id
== SKILL_LOCKPICKING
|| pSkill
->id
== SKILL_RUNEFORGING
) && _spell_idx
->second
->max_value
== 0))
3424 // not reset skills for professions and racial abilities
3425 if ((pSkill
->categoryId
== SKILL_CATEGORY_SECONDARY
|| pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
) &&
3426 (IsProfessionSkill(pSkill
->id
) || _spell_idx
->second
->racemask
!= 0))
3429 SetSkill(pSkill
->id
, GetSkillStep(pSkill
->id
), 0, 0);
3434 // remove dependent spells
3435 SpellLearnSpellMapBounds spell_bounds
= sSpellMgr
.GetSpellLearnSpellMapBounds(spell_id
);
3437 for(SpellLearnSpellMap::const_iterator itr2
= spell_bounds
.first
; itr2
!= spell_bounds
.second
; ++itr2
)
3438 removeSpell(itr2
->second
.spell
, disabled
);
3440 // activate lesser rank in spellbook/action bar, and cast it if need
3441 bool prev_activate
= false;
3443 if (uint32 prev_id
= sSpellMgr
.GetPrevSpellInChain (spell_id
))
3445 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
3447 // if talent then lesser rank also talent and need learn
3451 learnSpell(prev_id
, false);
3453 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3454 else if (cur_active
&& !SpellMgr::canStackSpellRanks(spellInfo
) && sSpellMgr
.GetSpellRank(spellInfo
->Id
) != 0)
3456 // need manually update dependence state (learn spell ignore like attempts)
3457 PlayerSpellMap::iterator prev_itr
= m_spells
.find(prev_id
);
3458 if (prev_itr
!= m_spells
.end())
3460 if (prev_itr
->second
.dependent
!= cur_dependent
)
3462 prev_itr
->second
.dependent
= cur_dependent
;
3463 if (prev_itr
->second
.state
!= PLAYERSPELL_NEW
)
3464 prev_itr
->second
.state
= PLAYERSPELL_CHANGED
;
3467 // now re-learn if need re-activate
3468 if (cur_active
&& !prev_itr
->second
.active
&& learn_low_rank
)
3470 if (addSpell(prev_id
, true, false, prev_itr
->second
.dependent
, prev_itr
->second
.disabled
))
3472 // downgrade spell ranks in spellbook and action bar
3473 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, 4 + 4);
3474 data
<< uint32(spell_id
);
3475 data
<< uint32(prev_id
);
3476 GetSession()->SendPacket( &data
);
3477 prev_activate
= true;
3486 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
3487 if (IsSpellHaveEffect(spellInfo
, SPELL_EFFECT_TITAN_GRIP
))
3489 m_canTitanGrip
= false;
3490 if(sWorld
.getConfig(CONFIG_BOOL_OFFHAND_CHECK_AT_TALENTS_RESET
))
3491 AutoUnequipOffhandIfNeed();
3495 // remove from spell book if not replaced by lesser rank
3496 if (!prev_activate
&& sendUpdate
)
3498 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
3499 data
<< uint32(spell_id
);
3500 GetSession()->SendPacket(&data
);
3504 void Player::RemoveSpellCooldown( uint32 spell_id
, bool update
/* = false */ )
3506 m_spellCooldowns
.erase(spell_id
);
3509 SendClearCooldown(spell_id
, this);
3512 void Player::RemoveSpellCategoryCooldown(uint32 cat
, bool update
/* = false */)
3514 SpellCategoryStore::const_iterator ct
= sSpellCategoryStore
.find(cat
);
3515 if (ct
== sSpellCategoryStore
.end())
3518 const SpellCategorySet
& ct_set
= ct
->second
;
3519 for (SpellCooldowns::const_iterator i
= m_spellCooldowns
.begin(); i
!= m_spellCooldowns
.end();)
3521 if (ct_set
.find(i
->first
) != ct_set
.end())
3522 RemoveSpellCooldown((i
++)->first
, update
);
3528 void Player::RemoveArenaSpellCooldowns()
3530 // remove cooldowns on spells that has < 15 min CD
3531 SpellCooldowns::iterator itr
, next
;
3532 // iterate spell cooldowns
3533 for(itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); itr
= next
)
3537 SpellEntry
const * entry
= sSpellStore
.LookupEntry(itr
->first
);
3538 // check if spellentry is present and if the cooldown is less than 15 mins
3540 entry
->RecoveryTime
<= 15 * MINUTE
* IN_MILLISECONDS
&&
3541 entry
->CategoryRecoveryTime
<= 15 * MINUTE
* IN_MILLISECONDS
)
3544 RemoveSpellCooldown(itr
->first
, true);
3549 void Player::RemoveAllSpellCooldown()
3551 if(!m_spellCooldowns
.empty())
3553 for(SpellCooldowns::const_iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); ++itr
)
3554 SendClearCooldown(itr
->first
, this);
3556 m_spellCooldowns
.clear();
3560 void Player::_LoadSpellCooldowns(QueryResult
*result
)
3562 // some cooldowns can be already set at aura loading...
3564 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3568 time_t curTime
= time(NULL
);
3572 Field
*fields
= result
->Fetch();
3574 uint32 spell_id
= fields
[0].GetUInt32();
3575 uint32 item_id
= fields
[1].GetUInt32();
3576 time_t db_time
= (time_t)fields
[2].GetUInt64();
3578 if(!sSpellStore
.LookupEntry(spell_id
))
3580 sLog
.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id
);
3584 // skip outdated cooldown
3585 if(db_time
<= curTime
)
3588 AddSpellCooldown(spell_id
, item_id
, db_time
);
3590 sLog
.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id
, item_id
, uint32(db_time
-curTime
));
3592 while( result
->NextRow() );
3598 void Player::_SaveSpellCooldowns()
3600 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3602 time_t curTime
= time(NULL
);
3603 time_t infTime
= curTime
+ infinityCooldownDelayCheck
;
3605 /* copied following sql-code partly from achievementmgr */
3606 bool first_round
= true;
3607 std::ostringstream ss
;
3609 // remove outdated and save active
3610 for(SpellCooldowns::iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end();)
3612 if(itr
->second
.end
<= curTime
)
3613 m_spellCooldowns
.erase(itr
++);
3614 else if(itr
->second
.end
<= infTime
) // not save locked cooldowns, it will be reset or set at reload
3618 ss
<< "INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ";
3619 first_round
= false;
3621 // next new/changed record prefix
3624 ss
<< "(" << GetGUIDLow() << "," << itr
->first
<< "," << itr
->second
.itemid
<< "," << uint64(itr
->second
.end
) << ")";
3631 // if something changed execute
3633 CharacterDatabase
.Execute( ss
.str().c_str() );
3636 uint32
Player::resetTalentsCost() const
3638 // The first time reset costs 1 gold
3639 if(m_resetTalentsCost
< 1*GOLD
)
3642 else if(m_resetTalentsCost
< 5*GOLD
)
3644 // After that it increases in increments of 5 gold
3645 else if(m_resetTalentsCost
< 10*GOLD
)
3649 time_t months
= (sWorld
.GetGameTime() - m_resetTalentsTime
)/MONTH
;
3652 // This cost will be reduced by a rate of 5 gold per month
3653 int32 new_cost
= int32((m_resetTalentsCost
) - 5*GOLD
*months
);
3654 // to a minimum of 10 gold.
3655 return uint32(new_cost
< 10*GOLD
? 10*GOLD
: new_cost
);
3659 // After that it increases in increments of 5 gold
3660 int32 new_cost
= m_resetTalentsCost
+ 5*GOLD
;
3661 // until it hits a cap of 50 gold.
3662 if(new_cost
> 50*GOLD
)
3669 bool Player::resetTalents(bool no_cost
, bool all_specs
)
3671 // not need after this call
3672 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS
) && all_specs
)
3673 RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS
,true);
3675 if (m_usedTalentCount
== 0 && !all_specs
)
3677 UpdateFreeTalentPoints(false); // for fix if need counter
3685 cost
= resetTalentsCost();
3687 if (GetMoney() < cost
)
3689 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, 0, 0, 0);
3694 for (PlayerTalentMap::iterator iter
= m_talents
[m_activeSpec
].begin(); iter
!= m_talents
[m_activeSpec
].end();)
3696 if (iter
->second
.state
== PLAYERSPELL_REMOVED
)
3702 TalentEntry
const *talentInfo
= (*iter
).second
.m_talentEntry
;
3705 m_talents
[m_activeSpec
].erase(iter
++);
3709 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
3713 m_talents
[m_activeSpec
].erase(iter
++);
3717 // unlearn only talents for character class
3718 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3719 // to prevent unexpected lost normal learned spell skip another class talents
3720 if ((getClassMask() & talentTabInfo
->ClassMask
) == 0)
3726 for (int j
= 0; j
< MAX_TALENT_RANK
; ++j
)
3727 if (talentInfo
->RankID
[j
])
3728 removeSpell(talentInfo
->RankID
[j
],!IsPassiveSpell(talentInfo
->RankID
[j
]),false);
3730 iter
= m_talents
[m_activeSpec
].begin();
3733 // for not current spec just mark removed all saved to DB case and drop not saved
3736 for (uint8 spec
= 0; spec
< MAX_TALENT_SPEC_COUNT
; ++spec
)
3738 if (spec
== m_activeSpec
)
3741 for (PlayerTalentMap::iterator iter
= m_talents
[spec
].begin(); iter
!= m_talents
[spec
].end();)
3743 switch (iter
->second
.state
)
3745 case PLAYERSPELL_REMOVED
:
3748 case PLAYERSPELL_NEW
:
3749 m_talents
[spec
].erase(iter
++);
3752 iter
->second
.state
= PLAYERSPELL_REMOVED
;
3760 UpdateFreeTalentPoints(false);
3764 ModifyMoney(-(int32
)cost
);
3765 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS
, cost
);
3766 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS
, 1);
3768 m_resetTalentsCost
= cost
;
3769 m_resetTalentsTime
= time(NULL
);
3772 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3773 RemovePet(NULL
,PET_SAVE_NOT_IN_SLOT
, true);
3774 /* when prev line will dropped use next line
3775 if(Pet* pet = GetPet())
3777 if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
3778 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3784 Mail
* Player::GetMail(uint32 id
)
3786 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
3788 if ((*itr
)->messageID
== id
)
3796 void Player::_SetCreateBits(UpdateMask
*updateMask
, Player
*target
) const
3800 Object::_SetCreateBits(updateMask
, target
);
3804 for(uint16 index
= 0; index
< m_valuesCount
; index
++)
3806 if(GetUInt32Value(index
) != 0 && updateVisualBits
.GetBit(index
))
3807 updateMask
->SetBit(index
);
3812 void Player::_SetUpdateBits(UpdateMask
*updateMask
, Player
*target
) const
3816 Object::_SetUpdateBits(updateMask
, target
);
3820 Object::_SetUpdateBits(updateMask
, target
);
3821 *updateMask
&= updateVisualBits
;
3825 void Player::InitVisibleBits()
3827 updateVisualBits
.SetCount(PLAYER_END
);
3829 updateVisualBits
.SetBit(OBJECT_FIELD_GUID
);
3830 updateVisualBits
.SetBit(OBJECT_FIELD_TYPE
);
3831 updateVisualBits
.SetBit(OBJECT_FIELD_ENTRY
);
3832 updateVisualBits
.SetBit(OBJECT_FIELD_SCALE_X
);
3833 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 0);
3834 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 1);
3835 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 0);
3836 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 1);
3837 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 0);
3838 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 1);
3839 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 0);
3840 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 1);
3841 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 0);
3842 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 1);
3843 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_0
);
3844 updateVisualBits
.SetBit(UNIT_FIELD_HEALTH
);
3845 updateVisualBits
.SetBit(UNIT_FIELD_POWER1
);
3846 updateVisualBits
.SetBit(UNIT_FIELD_POWER2
);
3847 updateVisualBits
.SetBit(UNIT_FIELD_POWER3
);
3848 updateVisualBits
.SetBit(UNIT_FIELD_POWER4
);
3849 updateVisualBits
.SetBit(UNIT_FIELD_POWER5
);
3850 updateVisualBits
.SetBit(UNIT_FIELD_POWER6
);
3851 updateVisualBits
.SetBit(UNIT_FIELD_POWER7
);
3852 updateVisualBits
.SetBit(UNIT_FIELD_MAXHEALTH
);
3853 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER1
);
3854 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER2
);
3855 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER3
);
3856 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER4
);
3857 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER5
);
3858 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER6
);
3859 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER7
);
3860 updateVisualBits
.SetBit(UNIT_FIELD_LEVEL
);
3861 updateVisualBits
.SetBit(UNIT_FIELD_FACTIONTEMPLATE
);
3862 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 0);
3863 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 1);
3864 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 2);
3865 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS
);
3866 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS_2
);
3867 updateVisualBits
.SetBit(UNIT_FIELD_AURASTATE
);
3868 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 0);
3869 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 1);
3870 updateVisualBits
.SetBit(UNIT_FIELD_BOUNDINGRADIUS
);
3871 updateVisualBits
.SetBit(UNIT_FIELD_COMBATREACH
);
3872 updateVisualBits
.SetBit(UNIT_FIELD_DISPLAYID
);
3873 updateVisualBits
.SetBit(UNIT_FIELD_NATIVEDISPLAYID
);
3874 updateVisualBits
.SetBit(UNIT_FIELD_MOUNTDISPLAYID
);
3875 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_1
);
3876 updateVisualBits
.SetBit(UNIT_FIELD_PETNUMBER
);
3877 updateVisualBits
.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP
);
3878 updateVisualBits
.SetBit(UNIT_DYNAMIC_FLAGS
);
3879 updateVisualBits
.SetBit(UNIT_CHANNEL_SPELL
);
3880 updateVisualBits
.SetBit(UNIT_MOD_CAST_SPEED
);
3881 updateVisualBits
.SetBit(UNIT_FIELD_BASE_MANA
);
3882 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_2
);
3883 updateVisualBits
.SetBit(UNIT_FIELD_HOVERHEIGHT
);
3885 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 0);
3886 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 1);
3887 updateVisualBits
.SetBit(PLAYER_FLAGS
);
3888 updateVisualBits
.SetBit(PLAYER_GUILDID
);
3889 updateVisualBits
.SetBit(PLAYER_GUILDRANK
);
3890 updateVisualBits
.SetBit(PLAYER_BYTES
);
3891 updateVisualBits
.SetBit(PLAYER_BYTES_2
);
3892 updateVisualBits
.SetBit(PLAYER_BYTES_3
);
3893 updateVisualBits
.SetBit(PLAYER_DUEL_TEAM
);
3894 updateVisualBits
.SetBit(PLAYER_GUILD_TIMESTAMP
);
3896 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3897 for(uint16 i
= PLAYER_QUEST_LOG_1_1
; i
< PLAYER_QUEST_LOG_25_2
; i
+= MAX_QUEST_OFFSET
)
3898 updateVisualBits
.SetBit(i
);
3900 // Players visible items are not inventory stuff
3901 for(uint16 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
3903 uint32 offset
= i
* 2;
3906 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID
+ offset
);
3908 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ offset
);
3911 updateVisualBits
.SetBit(PLAYER_CHOSEN_TITLE
);
3914 void Player::BuildCreateUpdateBlockForPlayer( UpdateData
*data
, Player
*target
) const
3916 for(int i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
3918 if(m_items
[i
] == NULL
)
3921 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3926 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
3928 if(m_items
[i
] == NULL
)
3931 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3933 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
3935 if(m_items
[i
] == NULL
)
3938 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3942 Unit::BuildCreateUpdateBlockForPlayer( data
, target
);
3945 void Player::DestroyForPlayer( Player
*target
, bool anim
) const
3947 Unit::DestroyForPlayer( target
, anim
);
3949 for(int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
3951 if(m_items
[i
] == NULL
)
3954 m_items
[i
]->DestroyForPlayer( target
);
3959 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
3961 if(m_items
[i
] == NULL
)
3964 m_items
[i
]->DestroyForPlayer( target
);
3966 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
3968 if(m_items
[i
] == NULL
)
3971 m_items
[i
]->DestroyForPlayer( target
);
3976 bool Player::HasSpell(uint32 spell
) const
3978 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3979 return (itr
!= m_spells
.end() && itr
->second
.state
!= PLAYERSPELL_REMOVED
&&
3980 !itr
->second
.disabled
);
3983 bool Player::HasActiveSpell(uint32 spell
) const
3985 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3986 return (itr
!= m_spells
.end() && itr
->second
.state
!= PLAYERSPELL_REMOVED
&&
3987 itr
->second
.active
&& !itr
->second
.disabled
);
3990 TrainerSpellState
Player::GetTrainerSpellState(TrainerSpell
const* trainer_spell
) const
3993 return TRAINER_SPELL_RED
;
3995 if (!trainer_spell
->learnedSpell
)
3996 return TRAINER_SPELL_RED
;
3999 if(HasSpell(trainer_spell
->learnedSpell
))
4000 return TRAINER_SPELL_GRAY
;
4002 // check race/class requirement
4003 if(!IsSpellFitByClassAndRace(trainer_spell
->learnedSpell
))
4004 return TRAINER_SPELL_RED
;
4006 // check level requirement
4007 if(getLevel() < trainer_spell
->reqLevel
)
4008 return TRAINER_SPELL_RED
;
4010 if(SpellChainNode
const* spell_chain
= sSpellMgr
.GetSpellChainNode(trainer_spell
->learnedSpell
))
4012 // check prev.rank requirement
4013 if(spell_chain
->prev
&& !HasSpell(spell_chain
->prev
))
4014 return TRAINER_SPELL_RED
;
4016 // check additional spell requirement
4017 if(spell_chain
->req
&& !HasSpell(spell_chain
->req
))
4018 return TRAINER_SPELL_RED
;
4021 // check skill requirement
4022 if(trainer_spell
->reqSkill
&& GetBaseSkillValue(trainer_spell
->reqSkill
) < trainer_spell
->reqSkillValue
)
4023 return TRAINER_SPELL_RED
;
4025 // exist, already checked at loading
4026 SpellEntry
const* spell
= sSpellStore
.LookupEntry(trainer_spell
->learnedSpell
);
4028 // secondary prof. or not prof. spell
4029 uint32 skill
= spell
->EffectMiscValue
[1];
4031 if(spell
->Effect
[1] != SPELL_EFFECT_SKILL
|| !IsPrimaryProfessionSkill(skill
))
4032 return TRAINER_SPELL_GREEN
;
4034 // check primary prof. limit
4035 if(sSpellMgr
.IsPrimaryProfessionFirstRankSpell(spell
->Id
) && GetFreePrimaryProfessionPoints() == 0)
4036 return TRAINER_SPELL_GREEN_DISABLED
;
4038 return TRAINER_SPELL_GREEN
;
4041 void Player::DeleteFromDB(uint64 playerguid
, uint32 accountId
, bool updateRealmChars
)
4043 uint32 guid
= GUID_LOPART(playerguid
);
4045 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
4046 // bones will be deleted by corpse/bones deleting thread shortly
4047 sObjectAccessor
.ConvertCorpseForPlayer(playerguid
);
4049 // remove from guild
4050 uint32 guildId
= GetGuildIdFromDB(playerguid
);
4053 Guild
* guild
= sObjectMgr
.GetGuildById(guildId
);
4055 guild
->DelMember(guid
);
4058 // remove from arena teams
4059 LeaveAllArenaTeams(playerguid
);
4061 // the player was uninvited already on logout so just remove from group
4062 QueryResult
*resultGroup
= CharacterDatabase
.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", guid
);
4065 uint32 groupId
= (*resultGroup
)[0].GetUInt32();
4067 if (Group
* group
= sObjectMgr
.GetGroupById(groupId
))
4068 RemoveFromGroup(group
, playerguid
);
4071 // remove signs from petitions (also remove petitions if owner);
4072 RemovePetitionsAndSigns(playerguid
, 10);
4074 // return back all mails with COD and Item 0 1 2 3 4 5 6 7
4075 QueryResult
*resultMail
= CharacterDatabase
.PQuery("SELECT id,messageType,mailTemplateId,sender,subject,body,money,has_items FROM mail WHERE receiver='%u' AND has_items<>0 AND cod<>0", guid
);
4080 Field
*fields
= resultMail
->Fetch();
4082 uint32 mail_id
= fields
[0].GetUInt32();
4083 uint16 mailType
= fields
[1].GetUInt16();
4084 uint16 mailTemplateId
= fields
[2].GetUInt16();
4085 uint32 sender
= fields
[3].GetUInt32();
4086 std::string subject
= fields
[4].GetCppString();
4087 std::string body
= fields
[5].GetCppString();
4088 uint32 money
= fields
[6].GetUInt32();
4089 bool has_items
= fields
[7].GetBool();
4091 //we can return mail now
4092 //so firstly delete the old one
4093 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id
);
4095 // mail not from player
4096 if (mailType
!= MAIL_NORMAL
)
4099 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id
);
4103 MailDraft
draft(subject
, body
);
4105 draft
= MailDraft(mailTemplateId
, false); // items already included
4109 // data needs to be at first place for Item::LoadFromDB
4111 QueryResult
*resultItems
= CharacterDatabase
.PQuery("SELECT data,text,item_guid,item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail_id
);
4116 Field
*fields2
= resultItems
->Fetch();
4118 uint32 item_guidlow
= fields2
[2].GetUInt32();
4119 uint32 item_template
= fields2
[3].GetUInt32();
4121 ItemPrototype
const* itemProto
= ObjectMgr::GetItemPrototype(item_template
);
4124 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow
);
4128 Item
*pItem
= NewItemOrBag(itemProto
);
4129 if(!pItem
->LoadFromDB(item_guidlow
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
),resultItems
))
4131 pItem
->FSetState(ITEM_REMOVED
);
4132 pItem
->SaveToDB(); // it also deletes item object !
4136 draft
.AddItem(pItem
);
4138 while (resultItems
->NextRow());
4144 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id
);
4146 uint32 pl_account
= sObjectMgr
.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
4148 draft
.AddMoney(money
).SendReturnToSender(pl_account
, guid
, sender
);
4150 while (resultMail
->NextRow());
4155 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
4156 // Get guids of character's pets, will deleted in transaction
4157 QueryResult
*resultPets
= CharacterDatabase
.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid
);
4159 // NOW we can finally clear other DB data related to character
4160 CharacterDatabase
.BeginTransaction();
4165 Field
*fields3
= resultPets
->Fetch();
4166 uint32 petguidlow
= fields3
[0].GetUInt32();
4167 Pet::DeleteFromDB(petguidlow
);
4168 } while (resultPets
->NextRow());
4172 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",guid
);
4173 CharacterDatabase
.PExecute("DELETE FROM character_account_data WHERE guid = '%u'",guid
);
4174 CharacterDatabase
.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid
);
4175 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid
);
4176 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid
);
4177 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid
);
4178 CharacterDatabase
.PExecute("DELETE FROM character_glyphs WHERE guid = '%u'",guid
);
4179 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid
);
4180 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid
);
4181 CharacterDatabase
.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid
);
4182 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid
);
4183 CharacterDatabase
.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid
);
4184 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",guid
);
4185 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_weekly WHERE guid = '%u'",guid
);
4186 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid
);
4187 CharacterDatabase
.PExecute("DELETE FROM character_skills WHERE guid = '%u'",guid
);
4188 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid
);
4189 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid
);
4190 CharacterDatabase
.PExecute("DELETE FROM character_talent WHERE guid = '%u'",guid
);
4191 CharacterDatabase
.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid
);
4192 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid
);
4193 CharacterDatabase
.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid
,guid
);
4194 CharacterDatabase
.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid
);
4195 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid
);
4196 CharacterDatabase
.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid
);
4197 CharacterDatabase
.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid
);
4198 CharacterDatabase
.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid
);
4199 CharacterDatabase
.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid
);
4200 CharacterDatabase
.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid
);
4201 CharacterDatabase
.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid1 = '%u' OR PlayerGuid2 = '%u'",guid
, guid
);
4202 CharacterDatabase
.PExecute("DELETE FROM guild_bank_eventlog WHERE PlayerGuid = '%u'",guid
);
4203 CharacterDatabase
.CommitTransaction();
4205 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
4206 if(updateRealmChars
) sWorld
.UpdateRealmCharCount(accountId
);
4209 void Player::SetMovement(PlayerMovementType pType
)
4214 case MOVE_ROOT
: data
.Initialize(SMSG_FORCE_MOVE_ROOT
, GetPackGUID().size()+4); break;
4215 case MOVE_UNROOT
: data
.Initialize(SMSG_FORCE_MOVE_UNROOT
, GetPackGUID().size()+4); break;
4216 case MOVE_WATER_WALK
: data
.Initialize(SMSG_MOVE_WATER_WALK
, GetPackGUID().size()+4); break;
4217 case MOVE_LAND_WALK
: data
.Initialize(SMSG_MOVE_LAND_WALK
, GetPackGUID().size()+4); break;
4219 sLog
.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType
);
4222 data
<< GetPackGUID();
4224 GetSession()->SendPacket( &data
);
4228 - a resurrectable corpse must not be loaded for the player (only bones)
4229 - the player must be in world
4231 void Player::BuildPlayerRepop()
4233 WorldPacket
data(SMSG_PRE_RESURRECT
, GetPackGUID().size());
4234 data
<< GetPackGUID();
4235 GetSession()->SendPacket(&data
);
4237 if(getRace() == RACE_NIGHTELF
)
4238 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)
4239 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
4241 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
4242 // there must be SMSG.STOP_MIRROR_TIMER
4243 // there we must send 888 opcode
4245 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
4248 sLog
.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
4252 // create a corpse and place it at the player's location
4253 Corpse
*corpse
= CreateCorpse();
4256 sLog
.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
4259 GetMap()->Add(corpse
);
4261 // convert player body to ghost
4264 SetMovement(MOVE_WATER_WALK
);
4265 if(!GetSession()->isLogingOut())
4266 SetMovement(MOVE_UNROOT
);
4268 // BG - remove insignia related
4269 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_SKINNABLE
);
4271 SendCorpseReclaimDelay();
4273 // to prevent cheating
4274 corpse
->ResetGhostTime();
4276 StopMirrorTimers(); //disable timers(bars)
4278 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, (float)1.0); //see radius of death player?
4280 // set and clear other
4281 SetByteValue(UNIT_FIELD_BYTES_1
, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND
);
4284 void Player::ResurrectPlayer(float restore_percent
, bool applySickness
)
4286 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // remove spirit healer position
4291 GetSession()->SendPacket(&data
);
4293 // speed change, land walk
4295 // remove death flag + set aura
4296 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0x00);
4297 if(getRace() == RACE_NIGHTELF
)
4298 RemoveAurasDueToSpell(20584); // speed bonuses
4299 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
4301 setDeathState(ALIVE
);
4303 SetMovement(MOVE_LAND_WALK
);
4304 SetMovement(MOVE_UNROOT
);
4308 // set health/powers (0- will be set in caller)
4309 if(restore_percent
>0.0f
)
4311 SetHealth(uint32(GetMaxHealth()*restore_percent
));
4312 SetPower(POWER_MANA
, uint32(GetMaxPower(POWER_MANA
)*restore_percent
));
4313 SetPower(POWER_RAGE
, 0);
4314 SetPower(POWER_ENERGY
, uint32(GetMaxPower(POWER_ENERGY
)*restore_percent
));
4317 // trigger update zone for alive state zone updates
4318 uint32 newzone
, newarea
;
4319 GetZoneAndAreaId(newzone
,newarea
);
4320 UpdateZone(newzone
,newarea
);
4322 // update visibility
4323 UpdateVisibilityForPlayer();
4328 //Characters from level 1-10 are not affected by resurrection sickness.
4329 //Characters from level 11-19 will suffer from one minute of sickness
4330 //for each level they are above 10.
4331 //Characters level 20 and up suffer from ten minutes of sickness.
4332 int32 startLevel
= sWorld
.getConfig(CONFIG_INT32_DEATH_SICKNESS_LEVEL
);
4334 if(int32(getLevel()) >= startLevel
)
4336 // set resurrection sickness
4337 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,true);
4339 // not full duration
4340 if(int32(getLevel()) < startLevel
+9)
4342 int32 delta
= (int32(getLevel()) - startLevel
+ 1)*MINUTE
;
4344 for(int i
= 0; i
< MAX_EFFECT_INDEX
; ++i
)
4346 if(Aura
* Aur
= GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,SpellEffectIndex(i
)))
4348 Aur
->SetAuraDuration(delta
*IN_MILLISECONDS
);
4349 Aur
->SendAuraUpdate(false);
4356 void Player::KillPlayer()
4358 SetMovement(MOVE_ROOT
);
4360 StopMirrorTimers(); //disable timers(bars)
4362 setDeathState(CORPSE
);
4363 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4365 SetFlag(UNIT_DYNAMIC_FLAGS
, 0x00);
4366 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, !sMapStore
.LookupEntry(GetMapId())->Instanceable());
4368 // 6 minutes until repop at graveyard
4369 m_deathTimer
= 6*MINUTE
*IN_MILLISECONDS
;
4371 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4373 // don't create corpse at this moment, player might be falling
4375 // update visibility
4376 UpdateObjectVisibility();
4379 Corpse
* Player::CreateCorpse()
4381 // prevent existence 2 corpse for player
4384 uint32 _uf
, _pb
, _pb2
, _cfb1
, _cfb2
;
4386 Corpse
*corpse
= new Corpse( (m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
) ? CORPSE_RESURRECTABLE_PVP
: CORPSE_RESURRECTABLE_PVE
);
4389 if (!corpse
->Create(sObjectMgr
.GenerateLowGuid(HIGHGUID_CORPSE
), this))
4395 _uf
= GetUInt32Value(UNIT_FIELD_BYTES_0
);
4396 _pb
= GetUInt32Value(PLAYER_BYTES
);
4397 _pb2
= GetUInt32Value(PLAYER_BYTES_2
);
4399 uint8 race
= (uint8
)(_uf
);
4400 uint8 skin
= (uint8
)(_pb
);
4401 uint8 face
= (uint8
)(_pb
>> 8);
4402 uint8 hairstyle
= (uint8
)(_pb
>> 16);
4403 uint8 haircolor
= (uint8
)(_pb
>> 24);
4404 uint8 facialhair
= (uint8
)(_pb2
);
4406 _cfb1
= ((0x00) | (race
<< 8) | (getGender() << 16) | (skin
<< 24));
4407 _cfb2
= ((face
) | (hairstyle
<< 8) | (haircolor
<< 16) | (facialhair
<< 24));
4409 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_1
, _cfb1
);
4410 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_2
, _cfb2
);
4412 uint32 flags
= CORPSE_FLAG_UNK2
;
4413 if (HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
4414 flags
|= CORPSE_FLAG_HIDE_HELM
;
4415 if (HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
4416 flags
|= CORPSE_FLAG_HIDE_CLOAK
;
4417 if (InBattleGround() && !InArena())
4418 flags
|= CORPSE_FLAG_LOOTABLE
; // to be able to remove insignia
4419 corpse
->SetUInt32Value( CORPSE_FIELD_FLAGS
, flags
);
4421 corpse
->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID
, GetNativeDisplayId() );
4423 corpse
->SetUInt32Value( CORPSE_FIELD_GUILD
, GetGuildId() );
4426 uint32 iIventoryType
;
4428 for (int i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
4432 iDisplayID
= m_items
[i
]->GetProto()->DisplayInfoID
;
4433 iIventoryType
= m_items
[i
]->GetProto()->InventoryType
;
4435 _cfi
= iDisplayID
| (iIventoryType
<< 24);
4436 corpse
->SetUInt32Value(CORPSE_FIELD_ITEM
+ i
, _cfi
);
4440 // we not need saved corpses for BG/arenas
4441 if (!GetMap()->IsBattleGroundOrArena())
4444 // register for player, but not show
4445 sObjectAccessor
.AddCorpse(corpse
);
4449 void Player::SpawnCorpseBones()
4451 if(sObjectAccessor
.ConvertCorpseForPlayer(GetGUID()))
4452 if (!GetSession()->PlayerLogoutWithSave()) // at logout we will already store the player
4453 SaveToDB(); // prevent loading as ghost without corpse
4456 Corpse
* Player::GetCorpse() const
4458 return sObjectAccessor
.GetCorpseForPlayerGUID(GetGUID());
4461 void Player::DurabilityLossAll(double percent
, bool inventory
)
4463 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
4464 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4465 DurabilityLoss(pItem
,percent
);
4469 // bags not have durability
4470 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4472 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
4473 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4474 DurabilityLoss(pItem
,percent
);
4476 // keys not have durability
4477 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4479 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
4480 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4481 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
4482 if(Item
* pItem
= GetItemByPos( i
, j
))
4483 DurabilityLoss(pItem
,percent
);
4487 void Player::DurabilityLoss(Item
* item
, double percent
)
4492 uint32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4497 uint32 pDurabilityLoss
= uint32(pMaxDurability
*percent
);
4499 if(pDurabilityLoss
< 1 )
4500 pDurabilityLoss
= 1;
4502 DurabilityPointsLoss(item
,pDurabilityLoss
);
4505 void Player::DurabilityPointsLossAll(int32 points
, bool inventory
)
4507 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
4508 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4509 DurabilityPointsLoss(pItem
,points
);
4513 // bags not have durability
4514 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4516 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
4517 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4518 DurabilityPointsLoss(pItem
,points
);
4520 // keys not have durability
4521 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4523 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
4524 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4525 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
4526 if(Item
* pItem
= GetItemByPos( i
, j
))
4527 DurabilityPointsLoss(pItem
,points
);
4531 void Player::DurabilityPointsLoss(Item
* item
, int32 points
)
4533 int32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4534 int32 pOldDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4535 int32 pNewDurability
= pOldDurability
- points
;
4537 if (pNewDurability
< 0)
4539 else if (pNewDurability
> pMaxDurability
)
4540 pNewDurability
= pMaxDurability
;
4542 if (pOldDurability
!= pNewDurability
)
4544 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4545 if ( pNewDurability
== 0 && pOldDurability
> 0 && item
->IsEquipped())
4546 _ApplyItemMods(item
,item
->GetSlot(), false);
4548 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, pNewDurability
);
4550 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4551 if ( pNewDurability
> 0 && pOldDurability
== 0 && item
->IsEquipped())
4552 _ApplyItemMods(item
,item
->GetSlot(), true);
4554 item
->SetState(ITEM_CHANGED
, this);
4558 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot
)
4560 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
))
4561 DurabilityPointsLoss(pItem
,1);
4564 uint32
Player::DurabilityRepairAll(bool cost
, float discountMod
, bool guildBank
)
4566 uint32 TotalCost
= 0;
4567 // equipped, backpack, bags itself
4568 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
4569 TotalCost
+= DurabilityRepair(( (INVENTORY_SLOT_BAG_0
<< 8) | i
),cost
,discountMod
, guildBank
);
4571 // bank, buyback and keys not repaired
4573 // items in inventory bags
4574 for(int j
= INVENTORY_SLOT_BAG_START
; j
< INVENTORY_SLOT_BAG_END
; ++j
)
4575 for(int i
= 0; i
< MAX_BAG_SIZE
; ++i
)
4576 TotalCost
+= DurabilityRepair(( (j
<< 8) | i
),cost
,discountMod
, guildBank
);
4580 uint32
Player::DurabilityRepair(uint16 pos
, bool cost
, float discountMod
, bool guildBank
)
4582 Item
* item
= GetItemByPos(pos
);
4584 uint32 TotalCost
= 0;
4588 uint32 maxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4592 uint32 curDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4596 uint32 LostDurability
= maxDurability
- curDurability
;
4597 if(LostDurability
>0)
4599 ItemPrototype
const *ditemProto
= item
->GetProto();
4601 DurabilityCostsEntry
const *dcost
= sDurabilityCostsStore
.LookupEntry(ditemProto
->ItemLevel
);
4604 sLog
.outError("RepairDurability: Wrong item lvl %u", ditemProto
->ItemLevel
);
4608 uint32 dQualitymodEntryId
= (ditemProto
->Quality
+1)*2;
4609 DurabilityQualityEntry
const *dQualitymodEntry
= sDurabilityQualityStore
.LookupEntry(dQualitymodEntryId
);
4610 if(!dQualitymodEntry
)
4612 sLog
.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId
);
4616 uint32 dmultiplier
= dcost
->multiplier
[ItemSubClassToDurabilityMultiplierId(ditemProto
->Class
,ditemProto
->SubClass
)];
4617 uint32 costs
= uint32(LostDurability
*dmultiplier
*double(dQualitymodEntry
->quality_mod
));
4619 costs
= uint32(costs
* discountMod
);
4621 if (costs
==0) //fix for ITEM_QUALITY_ARTIFACT
4626 if (GetGuildId()==0)
4628 DEBUG_LOG("You are not member of a guild");
4632 Guild
*pGuild
= sObjectMgr
.GetGuildById(GetGuildId());
4636 if (!pGuild
->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR
))
4638 DEBUG_LOG("You do not have rights to withdraw for repairs");
4642 if (pGuild
->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs
)
4644 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4648 if (pGuild
->GetGuildBankMoney() < costs
)
4650 DEBUG_LOG("There is not enough money in bank");
4654 pGuild
->MemberMoneyWithdraw(costs
, GetGUIDLow());
4657 else if (GetMoney() < costs
)
4659 DEBUG_LOG("You do not have enough money");
4663 ModifyMoney( -int32(costs
) );
4667 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, maxDurability
);
4668 item
->SetState(ITEM_CHANGED
, this);
4670 // reapply mods for total broken and repaired item if equipped
4671 if(IsEquipmentPos(pos
) && !curDurability
)
4672 _ApplyItemMods(item
,pos
& 255, true);
4676 void Player::RepopAtGraveyard()
4678 // note: this can be called also when the player is alive
4679 // for example from WorldSession::HandleMovementOpcodes
4681 AreaTableEntry
const *zone
= GetAreaEntryByAreaID(GetAreaId());
4683 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4684 if ((!isAlive() && zone
&& zone
->flags
& AREA_FLAG_NEED_FLY
) || GetTransport())
4686 ResurrectPlayer(0.5f
);
4690 WorldSafeLocsEntry
const *ClosestGrave
= NULL
;
4692 // Special handle for battleground maps
4693 if( BattleGround
*bg
= GetBattleGround() )
4694 ClosestGrave
= bg
->GetClosestGraveYard(this);
4696 ClosestGrave
= sObjectMgr
.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4698 // stop countdown until repop
4701 // if no grave found, stay at the current location
4702 // and don't show spirit healer location
4705 TeleportTo(ClosestGrave
->map_id
, ClosestGrave
->x
, ClosestGrave
->y
, ClosestGrave
->z
, GetOrientation());
4706 if(isDead()) // not send if alive, because it used in TeleportTo()
4708 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // show spirit healer position on minimap
4709 data
<< ClosestGrave
->map_id
;
4710 data
<< ClosestGrave
->x
;
4711 data
<< ClosestGrave
->y
;
4712 data
<< ClosestGrave
->z
;
4713 GetSession()->SendPacket(&data
);
4718 void Player::JoinedChannel(Channel
*c
)
4720 m_channels
.push_back(c
);
4723 void Player::LeftChannel(Channel
*c
)
4725 m_channels
.remove(c
);
4728 void Player::CleanupChannels()
4730 while(!m_channels
.empty())
4732 Channel
* ch
= *m_channels
.begin();
4733 m_channels
.erase(m_channels
.begin()); // remove from player's channel list
4734 ch
->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4735 if (ChannelMgr
* cMgr
= channelMgr(GetTeam()))
4736 cMgr
->LeftChannel(ch
->GetName()); // deleted channel if empty
4739 sLog
.outDebug("Player: channels cleaned up!");
4742 void Player::UpdateLocalChannels(uint32 newZone
)
4744 if(m_channels
.empty())
4747 AreaTableEntry
const* current_zone
= GetAreaEntryByAreaID(newZone
);
4751 ChannelMgr
* cMgr
= channelMgr(GetTeam());
4755 std::string current_zone_name
= current_zone
->area_name
[GetSession()->GetSessionDbcLocale()];
4757 for(JoinedChannelsList::iterator i
= m_channels
.begin(), next
; i
!= m_channels
.end(); i
= next
)
4761 // skip non built-in channels
4762 if(!(*i
)->IsConstant())
4765 ChatChannelsEntry
const* ch
= GetChannelEntryFor((*i
)->GetChannelId());
4769 if((ch
->flags
& 4) == 4) // global channel without zone name in pattern
4773 char new_channel_name_buf
[100];
4774 snprintf(new_channel_name_buf
,100,ch
->pattern
[m_session
->GetSessionDbcLocale()],current_zone_name
.c_str());
4775 Channel
* new_channel
= cMgr
->GetJoinChannel(new_channel_name_buf
,ch
->ChannelID
);
4777 if((*i
)!=new_channel
)
4779 new_channel
->Join(GetGUID(),""); // will output Changed Channel: N. Name
4781 // leave old channel
4782 (*i
)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4783 std::string name
= (*i
)->GetName(); // store name, (*i)erase in LeftChannel
4784 LeftChannel(*i
); // remove from player's channel list
4785 cMgr
->LeftChannel(name
); // delete if empty
4788 sLog
.outDebug("Player: channels cleaned up!");
4791 void Player::LeaveLFGChannel()
4793 for(JoinedChannelsList::iterator i
= m_channels
.begin(); i
!= m_channels
.end(); ++i
)
4797 (*i
)->Leave(GetGUID());
4803 void Player::UpdateDefense()
4805 uint32 defense_skill_gain
= sWorld
.getConfig(CONFIG_UINT32_SKILL_GAIN_DEFENSE
);
4807 if(UpdateSkill(SKILL_DEFENSE
,defense_skill_gain
))
4809 // update dependent from defense skill part
4810 UpdateDefenseBonusesMod();
4814 void Player::HandleBaseModValue(BaseModGroup modGroup
, BaseModType modType
, float amount
, bool apply
)
4816 if(modGroup
>= BASEMOD_END
|| modType
>= MOD_END
)
4818 sLog
.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4827 m_auraBaseMod
[modGroup
][modType
] += apply
? amount
: -amount
;
4830 if(amount
<= -100.0f
)
4833 val
= (100.0f
+ amount
) / 100.0f
;
4834 m_auraBaseMod
[modGroup
][modType
] *= apply
? val
: (1.0f
/val
);
4838 if(!CanModifyStats())
4843 case CRIT_PERCENTAGE
: UpdateCritPercentage(BASE_ATTACK
); break;
4844 case RANGED_CRIT_PERCENTAGE
: UpdateCritPercentage(RANGED_ATTACK
); break;
4845 case OFFHAND_CRIT_PERCENTAGE
: UpdateCritPercentage(OFF_ATTACK
); break;
4846 case SHIELD_BLOCK_VALUE
: UpdateShieldBlockValue(); break;
4851 float Player::GetBaseModValue(BaseModGroup modGroup
, BaseModType modType
) const
4853 if(modGroup
>= BASEMOD_END
|| modType
> MOD_END
)
4855 sLog
.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4859 if(modType
== PCT_MOD
&& m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4862 return m_auraBaseMod
[modGroup
][modType
];
4865 float Player::GetTotalBaseModValue(BaseModGroup modGroup
) const
4867 if(modGroup
>= BASEMOD_END
)
4869 sLog
.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4873 if(m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4876 return m_auraBaseMod
[modGroup
][FLAT_MOD
] * m_auraBaseMod
[modGroup
][PCT_MOD
];
4879 uint32
Player::GetShieldBlockValue() const
4881 float value
= (m_auraBaseMod
[SHIELD_BLOCK_VALUE
][FLAT_MOD
] + GetStat(STAT_STRENGTH
) * 0.5f
- 10)*m_auraBaseMod
[SHIELD_BLOCK_VALUE
][PCT_MOD
];
4883 value
= (value
< 0) ? 0 : value
;
4885 return uint32(value
);
4888 float Player::GetMeleeCritFromAgility()
4890 uint32 level
= getLevel();
4891 uint32 pclass
= getClass();
4893 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4895 GtChanceToMeleeCritBaseEntry
const *critBase
= sGtChanceToMeleeCritBaseStore
.LookupEntry(pclass
-1);
4896 GtChanceToMeleeCritEntry
const *critRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4897 if (critBase
==NULL
|| critRatio
==NULL
)
4900 float crit
=critBase
->base
+ GetStat(STAT_AGILITY
)*critRatio
->ratio
;
4904 float Player::GetDodgeFromAgility()
4906 // Table for base dodge values
4907 float dodge_base
[MAX_CLASSES
] = {
4909 0.00652f
, // Paladin
4916 0.02011f
, // Warlock
4920 // Crit/agility to dodge/agility coefficient multipliers
4921 float crit_to_dodge
[MAX_CLASSES
] = {
4935 uint32 level
= getLevel();
4936 uint32 pclass
= getClass();
4938 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4940 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4941 GtChanceToMeleeCritEntry
const *dodgeRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4942 if (dodgeRatio
==NULL
|| pclass
> MAX_CLASSES
)
4945 float dodge
=dodge_base
[pclass
-1] + GetStat(STAT_AGILITY
) * dodgeRatio
->ratio
* crit_to_dodge
[pclass
-1];
4946 return dodge
*100.0f
;
4949 float Player::GetSpellCritFromIntellect()
4951 uint32 level
= getLevel();
4952 uint32 pclass
= getClass();
4954 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4956 GtChanceToSpellCritBaseEntry
const *critBase
= sGtChanceToSpellCritBaseStore
.LookupEntry(pclass
-1);
4957 GtChanceToSpellCritEntry
const *critRatio
= sGtChanceToSpellCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4958 if (critBase
==NULL
|| critRatio
==NULL
)
4961 float crit
=critBase
->base
+ GetStat(STAT_INTELLECT
)*critRatio
->ratio
;
4965 float Player::GetRatingCoefficient(CombatRating cr
) const
4967 uint32 level
= getLevel();
4969 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4971 GtCombatRatingsEntry
const *Rating
= sGtCombatRatingsStore
.LookupEntry(cr
*GT_MAX_LEVEL
+level
-1);
4973 return 1.0f
; // By default use minimum coefficient (not must be called)
4975 return Rating
->ratio
;
4978 float Player::GetRatingBonusValue(CombatRating cr
) const
4980 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
)) / GetRatingCoefficient(cr
);
4983 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType
) const
4988 return GetUInt32Value(PLAYER_EXPERTISE
) / 4.0f
;
4990 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE
) / 4.0f
;
4997 float Player::OCTRegenHPPerSpirit()
4999 uint32 level
= getLevel();
5000 uint32 pclass
= getClass();
5002 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
5004 GtOCTRegenHPEntry
const *baseRatio
= sGtOCTRegenHPStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
5005 GtRegenHPPerSptEntry
const *moreRatio
= sGtRegenHPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
5006 if (baseRatio
==NULL
|| moreRatio
==NULL
)
5009 // Formula from PaperDollFrame script
5010 float spirit
= GetStat(STAT_SPIRIT
);
5011 float baseSpirit
= spirit
;
5012 if (baseSpirit
>50) baseSpirit
= 50;
5013 float moreSpirit
= spirit
- baseSpirit
;
5014 float regen
= baseSpirit
* baseRatio
->ratio
+ moreSpirit
* moreRatio
->ratio
;
5018 float Player::OCTRegenMPPerSpirit()
5020 uint32 level
= getLevel();
5021 uint32 pclass
= getClass();
5023 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
5025 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
5026 GtRegenMPPerSptEntry
const *moreRatio
= sGtRegenMPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
5027 if (moreRatio
==NULL
)
5030 // Formula get from PaperDollFrame script
5031 float spirit
= GetStat(STAT_SPIRIT
);
5032 float regen
= spirit
* moreRatio
->ratio
;
5036 void Player::ApplyRatingMod(CombatRating cr
, int32 value
, bool apply
)
5038 m_baseRatingValue
[cr
]+=(apply
? value
: -value
);
5040 // explicit affected values
5043 case CR_HASTE_MELEE
:
5045 float RatingChange
= value
/ GetRatingCoefficient(cr
);
5046 ApplyAttackTimePercentMod(BASE_ATTACK
,RatingChange
,apply
);
5047 ApplyAttackTimePercentMod(OFF_ATTACK
,RatingChange
,apply
);
5050 case CR_HASTE_RANGED
:
5052 float RatingChange
= value
/ GetRatingCoefficient(cr
);
5053 ApplyAttackTimePercentMod(RANGED_ATTACK
, RatingChange
, apply
);
5056 case CR_HASTE_SPELL
:
5058 float RatingChange
= value
/ GetRatingCoefficient(cr
);
5059 ApplyCastTimePercentMod(RatingChange
,apply
);
5067 void Player::UpdateRating(CombatRating cr
)
5069 int32 amount
= m_baseRatingValue
[cr
];
5070 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
5071 // stat used stored in miscValueB for this aura
5072 AuraList
const& modRatingFromStat
= GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT
);
5073 for(AuraList::const_iterator i
= modRatingFromStat
.begin();i
!= modRatingFromStat
.end(); ++i
)
5074 if ((*i
)->GetMiscValue() & (1<<cr
))
5075 amount
+= int32(GetStat(Stats((*i
)->GetMiscBValue())) * (*i
)->GetModifier()->m_amount
/ 100.0f
);
5078 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
, uint32(amount
));
5080 bool affectStats
= CanModifyStats();
5084 case CR_WEAPON_SKILL
: // Implemented in Unit::RollMeleeOutcomeAgainst
5085 case CR_DEFENSE_SKILL
:
5086 UpdateDefenseBonusesMod();
5089 UpdateDodgePercentage();
5092 UpdateParryPercentage();
5095 UpdateBlockPercentage();
5098 UpdateMeleeHitChances();
5101 UpdateRangedHitChances();
5104 UpdateSpellHitChances();
5109 UpdateCritPercentage(BASE_ATTACK
);
5110 UpdateCritPercentage(OFF_ATTACK
);
5113 case CR_CRIT_RANGED
:
5115 UpdateCritPercentage(RANGED_ATTACK
);
5119 UpdateAllSpellCritChances();
5121 case CR_HIT_TAKEN_MELEE
: // Implemented in Unit::MeleeMissChanceCalc
5122 case CR_HIT_TAKEN_RANGED
:
5124 case CR_HIT_TAKEN_SPELL
: // Implemented in Unit::MagicSpellHitResult
5126 case CR_CRIT_TAKEN_MELEE
: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
5127 case CR_CRIT_TAKEN_RANGED
:
5129 case CR_CRIT_TAKEN_SPELL
: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
5131 case CR_HASTE_MELEE
: // Implemented in Player::ApplyRatingMod
5132 case CR_HASTE_RANGED
:
5133 case CR_HASTE_SPELL
:
5135 case CR_WEAPON_SKILL_MAINHAND
: // Implemented in Unit::RollMeleeOutcomeAgainst
5136 case CR_WEAPON_SKILL_OFFHAND
:
5137 case CR_WEAPON_SKILL_RANGED
:
5142 UpdateExpertise(BASE_ATTACK
);
5143 UpdateExpertise(OFF_ATTACK
);
5146 case CR_ARMOR_PENETRATION
:
5148 UpdateArmorPenetration();
5153 void Player::UpdateAllRatings()
5155 for(int cr
= 0; cr
< MAX_COMBAT_RATING
; ++cr
)
5156 UpdateRating(CombatRating(cr
));
5159 void Player::SetRegularAttackTime()
5161 for(int i
= 0; i
< MAX_ATTACK
; ++i
)
5163 Item
*tmpitem
= GetWeaponForAttack(WeaponAttackType(i
),true,false);
5166 ItemPrototype
const *proto
= tmpitem
->GetProto();
5168 SetAttackTime(WeaponAttackType(i
), proto
->Delay
);
5170 SetAttackTime(WeaponAttackType(i
), BASE_ATTACK_TIME
);
5175 //skill+step, checking for max value
5176 bool Player::UpdateSkill(uint32 skill_id
, uint32 step
)
5181 SkillStatusMap::iterator itr
= mSkillStatus
.find(skill_id
);
5182 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5185 uint32 valueIndex
= PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
);
5186 uint32 data
= GetUInt32Value(valueIndex
);
5187 uint32 value
= SKILL_VALUE(data
);
5188 uint32 max
= SKILL_MAX(data
);
5190 if ((!max
) || (!value
) || (value
>= max
))
5193 if (value
*512 < max
*urand(0,512))
5195 uint32 new_value
= value
+step
;
5199 SetUInt32Value(valueIndex
,MAKE_SKILL_VALUE(new_value
,max
));
5200 if(itr
->second
.uState
!= SKILL_NEW
)
5201 itr
->second
.uState
= SKILL_CHANGED
;
5202 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,skill_id
);
5209 inline int SkillGainChance(uint32 SkillValue
, uint32 GrayLevel
, uint32 GreenLevel
, uint32 YellowLevel
)
5211 if ( SkillValue
>= GrayLevel
)
5212 return sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_GREY
)*10;
5213 if ( SkillValue
>= GreenLevel
)
5214 return sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_GREEN
)*10;
5215 if ( SkillValue
>= YellowLevel
)
5216 return sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_YELLOW
)*10;
5217 return sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_ORANGE
)*10;
5220 bool Player::UpdateCraftSkill(uint32 spellid
)
5222 sLog
.outDebug("UpdateCraftSkill spellid %d", spellid
);
5224 SkillLineAbilityMapBounds bounds
= sSpellMgr
.GetSkillLineAbilityMapBounds(spellid
);
5226 for(SkillLineAbilityMap::const_iterator _spell_idx
= bounds
.first
; _spell_idx
!= bounds
.second
; ++_spell_idx
)
5228 if (_spell_idx
->second
->skillId
)
5230 uint32 SkillValue
= GetPureSkillValue(_spell_idx
->second
->skillId
);
5232 // Alchemy Discoveries here
5233 SpellEntry
const* spellEntry
= sSpellStore
.LookupEntry(spellid
);
5234 if (spellEntry
&& spellEntry
->Mechanic
== MECHANIC_DISCOVERY
)
5236 if (uint32 discoveredSpell
= GetSkillDiscoverySpell(_spell_idx
->second
->skillId
, spellid
, this))
5237 learnSpell(discoveredSpell
, false);
5240 uint32 craft_skill_gain
= sWorld
.getConfig(CONFIG_UINT32_SKILL_GAIN_CRAFTING
);
5242 return UpdateSkillPro(_spell_idx
->second
->skillId
, SkillGainChance(SkillValue
,
5243 _spell_idx
->second
->max_value
,
5244 (_spell_idx
->second
->max_value
+ _spell_idx
->second
->min_value
)/2,
5245 _spell_idx
->second
->min_value
),
5252 bool Player::UpdateGatherSkill(uint32 SkillId
, uint32 SkillValue
, uint32 RedLevel
, uint32 Multiplicator
)
5254 sLog
.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId
, SkillValue
, RedLevel
);
5256 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_UINT32_SKILL_GAIN_GATHERING
);
5258 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
5261 case SKILL_HERBALISM
:
5262 case SKILL_LOCKPICKING
:
5263 case SKILL_JEWELCRAFTING
:
5264 case SKILL_INSCRIPTION
:
5265 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
5266 case SKILL_SKINNING
:
5267 if( sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_SKINNING_STEPS
)==0)
5268 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
5270 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_SKINNING_STEPS
)), gathering_skill_gain
);
5272 if (sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_MINING_STEPS
)==0)
5273 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
5275 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_MINING_STEPS
)),gathering_skill_gain
);
5280 bool Player::UpdateFishingSkill()
5282 sLog
.outDebug("UpdateFishingSkill");
5284 uint32 SkillValue
= GetPureSkillValue(SKILL_FISHING
);
5286 int32 chance
= SkillValue
< 75 ? 100 : 2500/(SkillValue
-50);
5288 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_UINT32_SKILL_GAIN_GATHERING
);
5290 return UpdateSkillPro(SKILL_FISHING
,chance
*10,gathering_skill_gain
);
5293 // levels sync. with spell requirement for skill levels to learn
5294 // bonus abilities in sSkillLineAbilityStore
5295 // Used only to avoid scan DBC at each skill grow
5296 static uint32 bonusSkillLevels
[] = {75,150,225,300,375,450};
5298 bool Player::UpdateSkillPro(uint16 SkillId
, int32 Chance
, uint32 step
)
5300 sLog
.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId
, Chance
/10.0);
5304 if(Chance
<= 0) // speedup in 0 chance case
5306 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
5310 SkillStatusMap::iterator itr
= mSkillStatus
.find(SkillId
);
5311 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5314 uint32 valueIndex
= PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
);
5316 uint32 data
= GetUInt32Value(valueIndex
);
5317 uint16 SkillValue
= SKILL_VALUE(data
);
5318 uint16 MaxValue
= SKILL_MAX(data
);
5320 if ( !MaxValue
|| !SkillValue
|| SkillValue
>= MaxValue
)
5323 int32 Roll
= irand(1,1000);
5325 if ( Roll
<= Chance
)
5327 uint32 new_value
= SkillValue
+step
;
5328 if(new_value
> MaxValue
)
5329 new_value
= MaxValue
;
5331 SetUInt32Value(valueIndex
,MAKE_SKILL_VALUE(new_value
,MaxValue
));
5332 if(itr
->second
.uState
!= SKILL_NEW
)
5333 itr
->second
.uState
= SKILL_CHANGED
;
5334 for(uint32
* bsl
= &bonusSkillLevels
[0]; *bsl
; ++bsl
)
5336 if((SkillValue
< *bsl
&& new_value
>= *bsl
))
5338 learnSkillRewardedSpells( SkillId
, new_value
);
5342 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,SkillId
);
5343 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance
/10.0);
5347 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
5351 void Player::UpdateWeaponSkill (WeaponAttackType attType
)
5353 // no skill gain in pvp
5354 Unit
*pVictim
= getVictim();
5355 if(pVictim
&& pVictim
->IsCharmerOrOwnerPlayerOrPlayerItself())
5359 return; // always maximized SKILL_FERAL_COMBAT in fact
5361 if(m_form
== FORM_TREE
)
5362 return; // use weapon but not skill up
5364 uint32 weapon_skill_gain
= sWorld
.getConfig(CONFIG_UINT32_SKILL_GAIN_WEAPON
);
5370 Item
*tmpitem
= GetWeaponForAttack(attType
,true,true);
5373 UpdateSkill(SKILL_UNARMED
,weapon_skill_gain
);
5374 else if(tmpitem
->GetProto()->SubClass
!= ITEM_SUBCLASS_WEAPON_FISHING_POLE
)
5375 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
5381 Item
*tmpitem
= GetWeaponForAttack(attType
,true,true);
5383 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
5387 UpdateAllCritPercentages();
5390 void Player::UpdateCombatSkills(Unit
*pVictim
, WeaponAttackType attType
, bool defence
)
5392 uint32 plevel
= getLevel(); // if defense than pVictim == attacker
5393 uint32 greylevel
= MaNGOS::XP::GetGrayLevel(plevel
);
5394 uint32 moblevel
= pVictim
->getLevelForTarget(this);
5395 if(moblevel
< greylevel
)
5398 if (moblevel
> plevel
+ 5)
5399 moblevel
= plevel
+ 5;
5401 uint32 lvldif
= moblevel
- greylevel
;
5405 uint32 skilldif
= 5 * plevel
- (defence
? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType
));
5409 float chance
= float(3 * lvldif
* skilldif
) / plevel
;
5412 if(getClass() == CLASS_WARRIOR
|| getClass() == CLASS_ROGUE
)
5413 chance
*= 0.1f
* GetStat(STAT_INTELLECT
);
5416 chance
= chance
< 1.0f
? 1.0f
: chance
; //minimum chance to increase skill is 1%
5418 if(roll_chance_f(chance
))
5423 UpdateWeaponSkill(attType
);
5429 void Player::ModifySkillBonus(uint32 skillid
,int32 val
, bool talent
)
5431 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skillid
);
5432 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5435 uint32 bonusIndex
= PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
);
5437 uint32 bonus_val
= GetUInt32Value(bonusIndex
);
5438 int16 temp_bonus
= SKILL_TEMP_BONUS(bonus_val
);
5439 int16 perm_bonus
= SKILL_PERM_BONUS(bonus_val
);
5441 if(talent
) // permanent bonus stored in high part
5442 SetUInt32Value(bonusIndex
,MAKE_SKILL_BONUS(temp_bonus
,perm_bonus
+val
));
5443 else // temporary/item bonus stored in low part
5444 SetUInt32Value(bonusIndex
,MAKE_SKILL_BONUS(temp_bonus
+val
,perm_bonus
));
5447 void Player::UpdateSkillsForLevel()
5449 uint16 maxconfskill
= sWorld
.GetConfigMaxSkillValue();
5450 uint32 maxSkill
= GetMaxSkillValueForLevel();
5452 bool alwaysMaxSkill
= sWorld
.getConfig(CONFIG_BOOL_ALWAYS_MAX_SKILL_FOR_LEVEL
);
5454 for(SkillStatusMap::iterator itr
= mSkillStatus
.begin(); itr
!= mSkillStatus
.end(); ++itr
)
5456 if(itr
->second
.uState
== SKILL_DELETED
)
5459 uint32 pskill
= itr
->first
;
5461 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(pskill
);
5465 if(GetSkillRangeType(pSkill
,false) != SKILL_RANGE_LEVEL
)
5468 uint32 valueIndex
= PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
);
5469 uint32 data
= GetUInt32Value(valueIndex
);
5470 uint32 max
= SKILL_MAX(data
);
5471 uint32 val
= SKILL_VALUE(data
);
5473 /// update only level dependent max skill values
5476 /// maximize skill always
5479 SetUInt32Value(valueIndex
, MAKE_SKILL_VALUE(maxSkill
,maxSkill
));
5480 if(itr
->second
.uState
!= SKILL_NEW
)
5481 itr
->second
.uState
= SKILL_CHANGED
;
5483 else if(max
!= maxconfskill
) /// update max skill value if current max skill not maximized
5485 SetUInt32Value(valueIndex
, MAKE_SKILL_VALUE(val
,maxSkill
));
5486 if(itr
->second
.uState
!= SKILL_NEW
)
5487 itr
->second
.uState
= SKILL_CHANGED
;
5493 void Player::UpdateSkillsToMaxSkillsForLevel()
5495 for(SkillStatusMap::iterator itr
= mSkillStatus
.begin(); itr
!= mSkillStatus
.end(); ++itr
)
5497 if(itr
->second
.uState
== SKILL_DELETED
)
5500 uint32 pskill
= itr
->first
;
5501 if( IsProfessionOrRidingSkill(pskill
))
5503 uint32 valueIndex
= PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
);
5504 uint32 data
= GetUInt32Value(valueIndex
);
5506 uint32 max
= SKILL_MAX(data
);
5510 SetUInt32Value(valueIndex
,MAKE_SKILL_VALUE(max
,max
));
5511 if(itr
->second
.uState
!= SKILL_NEW
)
5512 itr
->second
.uState
= SKILL_CHANGED
;
5515 if(pskill
== SKILL_DEFENSE
)
5516 UpdateDefenseBonusesMod();
5520 // This functions sets a skill line value (and adds if doesn't exist yet)
5521 // To "remove" a skill line, set it's values to zero
5522 void Player::SetSkill(uint16 id
, uint16 step
, uint16 currVal
, uint16 maxVal
)
5527 SkillStatusMap::iterator itr
= mSkillStatus
.find(id
);
5530 if(itr
!= mSkillStatus
.end() && itr
->second
.uState
!= SKILL_DELETED
)
5535 SetUInt32Value(PLAYER_SKILL_INDEX(itr
->second
.pos
), MAKE_PAIR32(id
, step
));
5537 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
), MAKE_SKILL_VALUE(currVal
, maxVal
));
5538 if(itr
->second
.uState
!= SKILL_NEW
)
5539 itr
->second
.uState
= SKILL_CHANGED
;
5540 learnSkillRewardedSpells(id
, currVal
);
5541 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
, id
);
5542 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL
, id
);
5546 // clear skill fields
5547 SetUInt32Value(PLAYER_SKILL_INDEX(itr
->second
.pos
), 0);
5548 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
), 0);
5549 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
), 0);
5551 // mark as deleted or simply remove from map if not saved yet
5552 if(itr
->second
.uState
!= SKILL_NEW
)
5553 itr
->second
.uState
= SKILL_DELETED
;
5555 mSkillStatus
.erase(itr
);
5557 // remove all spells that related to this skill
5558 for (uint32 j
= 0; j
< sSkillLineAbilityStore
.GetNumRows(); ++j
)
5559 if(SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
))
5560 if (pAbility
->skillId
== id
)
5561 removeSpell(sSpellMgr
.GetFirstSpellInChain(pAbility
->spellId
));
5564 else if(currVal
) // add
5566 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; ++i
)
5568 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5570 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
5573 sLog
.outError("Skill not found in SkillLineStore: skill #%u", id
);
5577 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
, step
));
5578 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
, maxVal
));
5579 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
, id
);
5580 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL
, id
);
5582 // insert new entry or update if not deleted old entry yet
5583 if(itr
!= mSkillStatus
.end())
5585 itr
->second
.pos
= i
;
5586 itr
->second
.uState
= SKILL_CHANGED
;
5589 mSkillStatus
.insert(SkillStatusMap::value_type(id
, SkillStatusData(i
, SKILL_NEW
)));
5591 // apply skill bonuses
5592 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
), 0);
5594 // temporary bonuses
5595 AuraList
const& mModSkill
= GetAurasByType(SPELL_AURA_MOD_SKILL
);
5596 for(AuraList::const_iterator j
= mModSkill
.begin(); j
!= mModSkill
.end(); ++j
)
5597 if ((*j
)->GetModifier()->m_miscvalue
== int32(id
))
5598 (*j
)->ApplyModifier(true);
5600 // permanent bonuses
5601 AuraList
const& mModSkillTalent
= GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT
);
5602 for(AuraList::const_iterator j
= mModSkillTalent
.begin(); j
!= mModSkillTalent
.end(); ++j
)
5603 if ((*j
)->GetModifier()->m_miscvalue
== int32(id
))
5604 (*j
)->ApplyModifier(true);
5606 // Learn all spells for skill
5607 learnSkillRewardedSpells(id
, currVal
);
5614 bool Player::HasSkill(uint32 skill
) const
5619 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5620 return (itr
!= mSkillStatus
.end() && itr
->second
.uState
!= SKILL_DELETED
);
5623 uint16
Player::GetSkillStep(uint16 skill
) const
5628 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5629 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5632 return PAIR32_HIPART(GetUInt32Value(PLAYER_SKILL_INDEX(itr
->second
.pos
)));
5635 uint16
Player::GetSkillValue(uint32 skill
) const
5640 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5641 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5644 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
));
5646 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
))));
5647 result
+= SKILL_TEMP_BONUS(bonus
);
5648 result
+= SKILL_PERM_BONUS(bonus
);
5649 return result
< 0 ? 0 : result
;
5652 uint16
Player::GetMaxSkillValue(uint32 skill
) const
5657 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5658 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5661 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
));
5663 int32 result
= int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
))));
5664 result
+= SKILL_TEMP_BONUS(bonus
);
5665 result
+= SKILL_PERM_BONUS(bonus
);
5666 return result
< 0 ? 0 : result
;
5669 uint16
Player::GetPureMaxSkillValue(uint32 skill
) const
5674 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5675 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5678 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
)));
5681 uint16
Player::GetBaseSkillValue(uint32 skill
) const
5686 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5687 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5690 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
))));
5691 result
+= SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
)));
5692 return result
< 0 ? 0 : result
;
5695 uint16
Player::GetPureSkillValue(uint32 skill
) const
5700 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5701 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5704 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
)));
5707 int16
Player::GetSkillPermBonusValue(uint32 skill
) const
5712 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5713 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5716 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
)));
5719 int16
Player::GetSkillTempBonusValue(uint32 skill
) const
5724 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5725 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5728 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
)));
5731 void Player::SendInitialActionButtons() const
5733 sLog
.outDetail( "Initializing Action Buttons for '%u' spec '%u'", GetGUIDLow(), m_activeSpec
);
5735 WorldPacket
data(SMSG_ACTION_BUTTONS
, 1+(MAX_ACTION_BUTTONS
*4));
5736 data
<< uint8(1); // talent spec amount (in packet)
5737 ActionButtonList
const& currentActionButtonList
= m_actionButtons
[m_activeSpec
];
5738 for(uint8 button
= 0; button
< MAX_ACTION_BUTTONS
; ++button
)
5740 ActionButtonList::const_iterator itr
= currentActionButtonList
.find(button
);
5741 if(itr
!= currentActionButtonList
.end() && itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
5742 data
<< uint32(itr
->second
.packedData
);
5747 GetSession()->SendPacket( &data
);
5748 sLog
.outDetail( "Action Buttons for '%u' spec '%u' Initialized", GetGUIDLow(), m_activeSpec
);
5751 bool Player::IsActionButtonDataValid(uint8 button
, uint32 action
, uint8 type
, Player
* player
, bool msg
)
5753 if(button
>= MAX_ACTION_BUTTONS
)
5758 sLog
.outError( "Action %u not added into button %u for player %s: button must be < %u", action
, button
, player
->GetName(), MAX_ACTION_BUTTONS
);
5760 sLog
.outError( "Table `playercreateinfo_action` have action %u into button %u : button must be < %u", action
, button
, MAX_ACTION_BUTTONS
);
5766 if(action
>= MAX_ACTION_BUTTON_ACTION_VALUE
)
5771 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
);
5773 sLog
.outError( "Table `playercreateinfo_action` have action %u into button %u : action must be < %u", action
, button
, MAX_ACTION_BUTTON_ACTION_VALUE
);
5780 case ACTION_BUTTON_SPELL
:
5781 if(!sSpellStore
.LookupEntry(action
))
5786 sLog
.outError( "Spell action %u not added into button %u for player %s: spell not exist", action
, button
, player
->GetName() );
5788 sLog
.outError( "Table `playercreateinfo_action` have spell action %u into button %u: spell not exist", action
, button
);
5793 if(player
&& !player
->HasSpell(action
))
5796 sLog
.outError( "Spell action %u not added into button %u for player %s: player don't known this spell", action
, button
, player
->GetName() );
5800 case ACTION_BUTTON_ITEM
:
5801 if(!ObjectMgr::GetItemPrototype(action
))
5806 sLog
.outError( "Item action %u not added into button %u for player %s: item not exist", action
, button
, player
->GetName() );
5808 sLog
.outError( "Table `playercreateinfo_action` have item action %u into button %u: item not exist", action
, button
);
5814 break; // other cases not checked at this moment
5820 ActionButton
* Player::addActionButton(uint8 spec
, uint8 button
, uint32 action
, uint8 type
)
5822 // check action only for active spec (so not check at copy/load passive spec)
5823 if (spec
== GetActiveSpec() && !IsActionButtonDataValid(button
,action
,type
,this))
5826 // it create new button (NEW state) if need or return existed
5827 ActionButton
& ab
= m_actionButtons
[spec
][button
];
5829 // set data and update to CHANGED if not NEW
5830 ab
.SetActionAndType(action
,ActionButtonType(type
));
5832 sLog
.outDetail("Player '%u' Added Action '%u' (type %u) to Button '%u' for spec %u", GetGUIDLow(), action
, uint32(type
), button
, spec
);
5836 void Player::removeActionButton(uint8 spec
, uint8 button
)
5838 ActionButtonList
& currentActionButtonList
= m_actionButtons
[spec
];
5839 ActionButtonList::iterator buttonItr
= currentActionButtonList
.find(button
);
5840 if (buttonItr
== currentActionButtonList
.end() || buttonItr
->second
.uState
== ACTIONBUTTON_DELETED
)
5843 if (buttonItr
->second
.uState
== ACTIONBUTTON_NEW
)
5844 currentActionButtonList
.erase(buttonItr
); // new and not saved
5846 buttonItr
->second
.uState
= ACTIONBUTTON_DELETED
; // saved, will deleted at next save
5848 sLog
.outDetail("Action Button '%u' Removed from Player '%u' for spec %u", button
, GetGUIDLow(), spec
);
5851 ActionButton
const* Player::GetActionButton(uint8 button
)
5853 ActionButtonList
& currentActionButtonList
= m_actionButtons
[m_activeSpec
];
5854 ActionButtonList::iterator buttonItr
= currentActionButtonList
.find(button
);
5855 if (buttonItr
==currentActionButtonList
.end() || buttonItr
->second
.uState
== ACTIONBUTTON_DELETED
)
5858 return &buttonItr
->second
;
5861 bool Player::SetPosition(float x
, float y
, float z
, float orientation
, bool teleport
)
5863 // prevent crash when a bad coord is sent by the client
5864 if(!MaNGOS::IsValidMapCoord(x
,y
,z
,orientation
))
5866 sLog
.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x
,y
,z
,orientation
,teleport
,GetGUIDLow());
5872 const float old_x
= GetPositionX();
5873 const float old_y
= GetPositionY();
5874 const float old_z
= GetPositionZ();
5875 const float old_r
= GetOrientation();
5877 if( teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
|| old_r
!= orientation
)
5879 if (teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
)
5880 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
5882 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING
);
5884 // move and update visible state if need
5885 m
->PlayerRelocation(this, x
, y
, z
, orientation
);
5887 // reread after Map::Relocation
5894 if(GetGroup() && (old_x
!= x
|| old_y
!= y
))
5895 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION
);
5898 // code block for underwater state update
5899 UpdateUnderwaterState(m
, x
, y
, z
);
5901 CheckExploreSystem();
5906 void Player::SaveRecallPosition()
5908 m_recallMap
= GetMapId();
5909 m_recallX
= GetPositionX();
5910 m_recallY
= GetPositionY();
5911 m_recallZ
= GetPositionZ();
5912 m_recallO
= GetOrientation();
5915 void Player::SendMessageToSet(WorldPacket
*data
, bool self
)
5917 Map
* _map
= IsInWorld() ? GetMap() : sMapMgr
.FindMap(GetMapId(), GetInstanceId());
5920 _map
->MessageBroadcast(this, data
, self
);
5924 //if player is not in world and map in not created/already destroyed
5925 //no need to create one, just send packet for itself!
5927 GetSession()->SendPacket(data
);
5930 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
)
5932 Map
* _map
= IsInWorld() ? GetMap() : sMapMgr
.FindMap(GetMapId(), GetInstanceId());
5935 _map
->MessageDistBroadcast(this, data
, dist
, self
);
5940 GetSession()->SendPacket(data
);
5943 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
, bool own_team_only
)
5945 Map
* _map
= IsInWorld() ? GetMap() : sMapMgr
.FindMap(GetMapId(), GetInstanceId());
5948 _map
->MessageDistBroadcast(this, data
, dist
, self
, own_team_only
);
5953 GetSession()->SendPacket(data
);
5956 void Player::SendDirectMessage(WorldPacket
*data
)
5958 GetSession()->SendPacket(data
);
5961 void Player::SendCinematicStart(uint32 CinematicSequenceId
)
5963 WorldPacket
data(SMSG_TRIGGER_CINEMATIC
, 4);
5964 data
<< uint32(CinematicSequenceId
);
5965 SendDirectMessage(&data
);
5968 void Player::SendMovieStart(uint32 MovieId
)
5970 WorldPacket
data(SMSG_TRIGGER_MOVIE
, 4);
5971 data
<< uint32(MovieId
);
5972 SendDirectMessage(&data
);
5975 void Player::CheckExploreSystem()
5983 uint16 areaFlag
= GetBaseMap()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5984 if(areaFlag
==0xffff)
5986 int offset
= areaFlag
/ 32;
5988 if(offset
>= PLAYER_EXPLORED_ZONES_SIZE
)
5990 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 < %u ).",areaFlag
,GetPositionX(),GetPositionY(),offset
,offset
, PLAYER_EXPLORED_ZONES_SIZE
);
5994 uint32 val
= (uint32
)(1 << (areaFlag
% 32));
5995 uint32 currFields
= GetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
);
5997 if( !(currFields
& val
) )
5999 SetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
, (uint32
)(currFields
| val
));
6001 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA
);
6003 AreaTableEntry
const *p
= GetAreaEntryByAreaFlagAndMap(areaFlag
,GetMapId());
6006 sLog
.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
6008 else if(p
->area_level
> 0)
6010 uint32 area
= p
->ID
;
6011 if (getLevel() >= sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
))
6013 SendExplorationExperience(area
,0);
6017 int32 diff
= int32(getLevel()) - p
->area_level
;
6021 XP
= uint32(sObjectMgr
.GetBaseXP(getLevel()+5)*sWorld
.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE
));
6025 int32 exploration_percent
= (100-((diff
-5)*5));
6026 if (exploration_percent
> 100)
6027 exploration_percent
= 100;
6028 else if (exploration_percent
< 0)
6029 exploration_percent
= 0;
6031 XP
= uint32(sObjectMgr
.GetBaseXP(p
->area_level
)*exploration_percent
/100*sWorld
.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE
));
6035 XP
= uint32(sObjectMgr
.GetBaseXP(p
->area_level
)*sWorld
.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE
));
6039 SendExplorationExperience(area
,XP
);
6041 sLog
.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area
);
6046 uint32
Player::TeamForRace(uint8 race
)
6048 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
6051 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
6055 switch(rEntry
->TeamID
)
6057 case 7: return ALLIANCE
;
6058 case 1: return HORDE
;
6061 sLog
.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race
),rEntry
->TeamID
);
6065 uint32
Player::getFactionForRace(uint8 race
)
6067 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
6070 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
6074 return rEntry
->FactionID
;
6077 void Player::setFactionForRace(uint8 race
)
6079 m_team
= TeamForRace(race
);
6080 setFaction( getFactionForRace(race
) );
6083 ReputationRank
Player::GetReputationRank(uint32 faction
) const
6085 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(faction
);
6086 return GetReputationMgr().GetRank(factionEntry
);
6089 //Calculate total reputation percent player gain with quest/creature level
6090 int32
Player::CalculateReputationGain(uint32 creatureOrQuestLevel
, int32 rep
, int32 faction
, bool for_quest
)
6092 float percent
= 100.0f
;
6094 float rate
= for_quest
? sWorld
.getConfig(CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_QUEST
) : sWorld
.getConfig(CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_KILL
);
6096 if (rate
!= 1.0f
&& creatureOrQuestLevel
<= MaNGOS::XP::GetGrayLevel(getLevel()))
6099 float repMod
= (float)GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN
);
6102 repMod
+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN
, faction
);
6104 percent
+= rep
> 0 ? repMod
: -repMod
;
6106 if (percent
<= 0.0f
)
6109 return int32(sWorld
.getConfig(CONFIG_FLOAT_RATE_REPUTATION_GAIN
)*rep
*percent
/100.0f
);
6112 //Calculates how many reputation points player gains in victim's enemy factions
6113 void Player::RewardReputation(Unit
*pVictim
, float rate
)
6115 if(!pVictim
|| pVictim
->GetTypeId() == TYPEID_PLAYER
)
6118 ReputationOnKillEntry
const* Rep
= sObjectMgr
.GetReputationOnKilEntry(((Creature
*)pVictim
)->GetCreatureInfo()->Entry
);
6123 if(Rep
->repfaction1
&& (!Rep
->team_dependent
|| GetTeam()==ALLIANCE
))
6125 int32 donerep1
= CalculateReputationGain(pVictim
->getLevel(), Rep
->repvalue1
, Rep
->repfaction1
, false);
6126 donerep1
= int32(donerep1
*rate
);
6127 FactionEntry
const *factionEntry1
= sFactionStore
.LookupEntry(Rep
->repfaction1
);
6128 uint32 current_reputation_rank1
= GetReputationMgr().GetRank(factionEntry1
);
6129 if (factionEntry1
&& current_reputation_rank1
<= Rep
->reputation_max_cap1
)
6130 GetReputationMgr().ModifyReputation(factionEntry1
, donerep1
);
6132 // Wiki: Team factions value divided by 2
6133 if (factionEntry1
&& Rep
->is_teamaward1
)
6135 FactionEntry
const *team1_factionEntry
= sFactionStore
.LookupEntry(factionEntry1
->team
);
6136 if(team1_factionEntry
)
6137 GetReputationMgr().ModifyReputation(team1_factionEntry
, donerep1
/ 2);
6141 if(Rep
->repfaction2
&& (!Rep
->team_dependent
|| GetTeam()==HORDE
))
6143 int32 donerep2
= CalculateReputationGain(pVictim
->getLevel(), Rep
->repvalue2
, Rep
->repfaction2
, false);
6144 donerep2
= int32(donerep2
*rate
);
6145 FactionEntry
const *factionEntry2
= sFactionStore
.LookupEntry(Rep
->repfaction2
);
6146 uint32 current_reputation_rank2
= GetReputationMgr().GetRank(factionEntry2
);
6147 if (factionEntry2
&& current_reputation_rank2
<= Rep
->reputation_max_cap2
)
6148 GetReputationMgr().ModifyReputation(factionEntry2
, donerep2
);
6150 // Wiki: Team factions value divided by 2
6151 if (factionEntry2
&& Rep
->is_teamaward2
)
6153 FactionEntry
const *team2_factionEntry
= sFactionStore
.LookupEntry(factionEntry2
->team
);
6154 if(team2_factionEntry
)
6155 GetReputationMgr().ModifyReputation(team2_factionEntry
, donerep2
/ 2);
6160 //Calculate how many reputation points player gain with the quest
6161 void Player::RewardReputation(Quest
const *pQuest
)
6163 // quest reputation reward/loss
6164 for(int i
= 0; i
< QUEST_REPUTATIONS_COUNT
; ++i
)
6166 if (!pQuest
->RewRepFaction
[i
])
6169 // For future, this row should be used as "override". Example quests are 10298 and 10870.
6170 // Typically, no diplomacy mod must apply to the final value (flat). Note the formula must be (finalValue = DBvalue/100)
6171 if (pQuest
->RewRepValue
[i
])
6173 int32 rep
= CalculateReputationGain(GetQuestLevelForPlayer(pQuest
), pQuest
->RewRepValue
[i
], pQuest
->RewRepFaction
[i
], true);
6175 if (FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->RewRepFaction
[i
]))
6176 GetReputationMgr().ModifyReputation(factionEntry
, rep
);
6180 uint32 row
= ((pQuest
->RewRepValueId
[i
] < 0) ? 1 : 0) + 1;
6181 uint32 field
= abs(pQuest
->RewRepValueId
[i
]);
6183 if (const QuestFactionRewardEntry
*pRow
= sQuestFactionRewardStore
.LookupEntry(row
))
6185 int32 repPoints
= pRow
->rewardValue
[field
];
6190 repPoints
= CalculateReputationGain(GetQuestLevelForPlayer(pQuest
), repPoints
, pQuest
->RewRepFaction
[i
], true);
6192 if (const FactionEntry
* factionEntry
= sFactionStore
.LookupEntry(pQuest
->RewRepFaction
[i
]))
6193 GetReputationMgr().ModifyReputation(factionEntry
, repPoints
);
6198 // TODO: implement reputation spillover
6201 void Player::UpdateArenaFields(void)
6203 /* arena calcs go here */
6206 void Player::UpdateHonorFields()
6208 /// called when rewarding honor and at each save
6209 time_t now
= time(NULL
);
6210 time_t today
= (time(NULL
) / DAY
) * DAY
;
6212 if(m_lastHonorUpdateTime
< today
)
6214 time_t yesterday
= today
- DAY
;
6216 uint16 kills_today
= PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS
));
6218 // update yesterday's contribution
6219 if(m_lastHonorUpdateTime
>= yesterday
)
6221 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
));
6223 // this is the first update today, reset today's contribution
6224 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, 0);
6225 SetUInt32Value(PLAYER_FIELD_KILLS
, MAKE_PAIR32(0,kills_today
));
6229 // no honor/kills yesterday or today, reset
6230 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0);
6231 SetUInt32Value(PLAYER_FIELD_KILLS
, 0);
6235 m_lastHonorUpdateTime
= now
;
6238 ///Calculate the amount of honor gained based on the victim
6239 ///and the size of the group for which the honor is divided
6240 ///An exact honor value can also be given (overriding the calcs)
6241 bool Player::RewardHonor(Unit
*uVictim
, uint32 groupsize
, float honor
)
6243 // do not reward honor in arenas, but enable onkill spellproc
6246 if(!uVictim
|| uVictim
== this || uVictim
->GetTypeId() != TYPEID_PLAYER
)
6249 if( GetBGTeam() == ((Player
*)uVictim
)->GetBGTeam() )
6255 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
6256 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE
))
6259 uint64 victim_guid
= 0;
6260 uint32 victim_rank
= 0;
6262 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6263 UpdateHonorFields();
6267 if(!uVictim
|| uVictim
== this || uVictim
->HasAuraType(SPELL_AURA_NO_PVP_CREDIT
))
6270 victim_guid
= uVictim
->GetGUID();
6272 if( uVictim
->GetTypeId() == TYPEID_PLAYER
)
6274 Player
*pVictim
= (Player
*)uVictim
;
6276 if( GetTeam() == pVictim
->GetTeam() && !sWorld
.IsFFAPvPRealm() )
6279 float f
= 1; //need for total kills (?? need more info)
6281 uint32 k_level
= getLevel();
6282 uint32 v_level
= pVictim
->getLevel();
6285 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6287 // [1..14] Alliance honor titles and player name
6288 // [15..28] Horde honor titles and player name
6289 // [29..38] Other title and player name
6291 uint32 victim_title
= pVictim
->GetUInt32Value(PLAYER_CHOSEN_TITLE
);
6292 // Get Killer titles, CharTitlesEntry::bit_index
6294 // title[1..14] -> rank[5..18]
6295 // title[15..28] -> rank[5..18]
6296 // title[other] -> 0
6297 if (victim_title
== 0)
6298 victim_guid
= 0; // Don't show HK: <rank> message, only log.
6299 else if (victim_title
< 15)
6300 victim_rank
= victim_title
+ 4;
6301 else if (victim_title
< 29)
6302 victim_rank
= victim_title
- 14 + 4;
6304 victim_guid
= 0; // Don't show HK: <rank> message, only log.
6307 k_grey
= MaNGOS::XP::GetGrayLevel(k_level
);
6312 float diff_level
= (k_level
== k_grey
) ? 1 : ((float(v_level
) - float(k_grey
)) / (float(k_level
) - float(k_grey
)));
6314 int32 v_rank
=1; //need more info
6316 honor
= ((f
* diff_level
* (190 + v_rank
*10))/6);
6317 honor
*= ((float)k_level
) / 70.0f
; //factor of dependence on levels of the killer
6319 // count the number of playerkills in one day
6320 ApplyModUInt32Value(PLAYER_FIELD_KILLS
, 1, true);
6321 // and those in a lifetime
6322 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 1, true);
6323 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL
);
6324 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS
, pVictim
->getClass());
6325 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE
, pVictim
->getRace());
6329 Creature
*cVictim
= (Creature
*)uVictim
;
6331 if (!cVictim
->isRacialLeader())
6334 honor
= 100; // ??? need more info
6335 victim_rank
= 19; // HK: Leader
6339 if (uVictim
!= NULL
)
6341 honor
*= sWorld
.getConfig(CONFIG_FLOAT_RATE_HONOR
);
6342 honor
*= (GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN
) + 100.0f
)/100.0f
;
6347 honor
*= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6350 // honor - for show honor points in log
6351 // victim_guid - for show victim name in log
6352 // victim_rank [1..4] HK: <dishonored rank>
6353 // victim_rank [5..19] HK: <alliance\horde rank>
6354 // victim_rank [0,20+] HK: <>
6355 WorldPacket
data(SMSG_PVP_CREDIT
,4+8+4);
6356 data
<< (uint32
) honor
;
6357 data
<< (uint64
) victim_guid
;
6358 data
<< (uint32
) victim_rank
;
6360 GetSession()->SendPacket(&data
);
6363 ModifyHonorPoints(int32(honor
));
6365 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, uint32(honor
), true);
6369 void Player::ModifyHonorPoints( int32 value
)
6373 if (GetHonorPoints() > sWorld
.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS
))
6374 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS
) + value
);
6376 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() > uint32(-value
) ? GetHonorPoints() + value
: 0);
6379 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() < sWorld
.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS
) - value
? GetHonorPoints() + value
: sWorld
.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS
));
6382 void Player::ModifyArenaPoints( int32 value
)
6386 if (GetArenaPoints() > sWorld
.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS
))
6387 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS
) + value
);
6389 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() > uint32(-value
) ? GetArenaPoints() + value
: 0);
6392 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() < sWorld
.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS
) - value
? GetArenaPoints() + value
: sWorld
.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS
));
6395 uint32
Player::GetGuildIdFromDB(uint64 guid
)
6397 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
));
6401 uint32 id
= result
->Fetch()[0].GetUInt32();
6406 uint32
Player::GetRankFromDB(uint64 guid
)
6408 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
) );
6411 uint32 v
= result
->Fetch()[0].GetUInt32();
6419 uint32
Player::GetArenaTeamIdFromDB(uint64 guid
, uint8 type
)
6421 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
);
6425 uint32 id
= (*result
)[0].GetUInt32();
6430 uint32
Player::GetZoneIdFromDB(uint64 guid
)
6432 uint32 guidLow
= GUID_LOPART(guid
);
6433 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow
);
6436 Field
* fields
= result
->Fetch();
6437 uint32 zone
= fields
[0].GetUInt32();
6442 // stored zone is zero, use generic and slow zone detection
6443 result
= CharacterDatabase
.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow
);
6446 fields
= result
->Fetch();
6447 uint32 map
= fields
[0].GetUInt32();
6448 float posx
= fields
[1].GetFloat();
6449 float posy
= fields
[2].GetFloat();
6450 float posz
= fields
[3].GetFloat();
6453 zone
= sMapMgr
.GetZoneId(map
,posx
,posy
,posz
);
6456 CharacterDatabase
.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone
, guidLow
);
6462 uint32
Player::GetLevelFromDB(uint64 guid
)
6464 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT level FROM characters WHERE guid='%u'", GUID_LOPART(guid
) );
6468 Field
* fields
= result
->Fetch();
6469 uint32 level
= fields
[0].GetUInt32();
6475 void Player::UpdateArea(uint32 newArea
)
6477 // FFA_PVP flags are area and not zone id dependent
6478 // so apply them accordingly
6479 m_areaUpdateId
= newArea
;
6481 AreaTableEntry
const* area
= GetAreaEntryByAreaID(newArea
);
6483 if(area
&& (area
->flags
& AREA_FLAG_ARENA
))
6490 // remove ffa flag only if not ffapvp realm
6491 // removal in sanctuaries and capitals is handled in zone update
6492 if(IsFFAPvP() && !sWorld
.IsFFAPvPRealm())
6496 UpdateAreaDependentAuras(newArea
);
6499 void Player::UpdateZone(uint32 newZone
, uint32 newArea
)
6501 AreaTableEntry
const* zone
= GetAreaEntryByAreaID(newZone
);
6505 if(m_zoneUpdateId
!= newZone
)
6507 SendInitWorldStates(newZone
, newArea
); // only if really enters to new zone, not just area change, works strange...
6509 if (sWorld
.getConfig(CONFIG_BOOL_WEATHER
))
6511 if(Weather
*wth
= sWorld
.FindWeather(zone
->ID
))
6512 wth
->SendWeatherUpdateToPlayer(this);
6513 else if(!sWorld
.AddWeather(zone
->ID
))
6515 // send fine weather packet to remove old zone's weather
6516 Weather::SendFineWeatherUpdateToPlayer(this);
6521 m_zoneUpdateId
= newZone
;
6522 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
6524 // zone changed, so area changed as well, update it
6525 UpdateArea(newArea
);
6527 // in PvP, any not controlled zone (except zone->team == 6, default case)
6528 // in PvE, only opposition team capital
6532 pvpInfo
.inHostileArea
= GetTeam() != ALLIANCE
&& (sWorld
.IsPvPRealm() || zone
->flags
& AREA_FLAG_CAPITAL
);
6534 case AREATEAM_HORDE
:
6535 pvpInfo
.inHostileArea
= GetTeam() != HORDE
&& (sWorld
.IsPvPRealm() || zone
->flags
& AREA_FLAG_CAPITAL
);
6538 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6539 pvpInfo
.inHostileArea
= sWorld
.IsPvPRealm() || InBattleGround();
6541 default: // 6 in fact
6542 pvpInfo
.inHostileArea
= false;
6546 if(pvpInfo
.inHostileArea
) // in hostile area
6548 if(!IsPvP() || pvpInfo
.endTimer
!= 0)
6549 UpdatePvP(true, true);
6551 else // in friendly area
6553 if(IsPvP() && !HasFlag(PLAYER_FLAGS
,PLAYER_FLAGS_IN_PVP
) && pvpInfo
.endTimer
== 0)
6554 pvpInfo
.endTimer
= time(0); // start toggle-off
6557 if(zone
->flags
& AREA_FLAG_SANCTUARY
) // in sanctuary
6559 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6560 if(sWorld
.IsFFAPvPRealm())
6565 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6568 if(zone
->flags
& AREA_FLAG_CAPITAL
) // in capital city
6569 SetRestType(REST_TYPE_IN_CITY
);
6570 else // anywhere else
6572 if (HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6574 if (GetRestType()==REST_TYPE_IN_TAVERN
) // has been in tavern. Is still in?
6576 AreaTriggerEntry
const* at
= sAreaTriggerStore
.LookupEntry(inn_trigger_id
);
6577 if (!at
|| !IsPointInAreaTriggerZone(at
, GetMapId(), GetPositionX(), GetPositionY(), GetPositionY()))
6578 SetRestType(REST_TYPE_NO
);
6580 else // not in tavern (leave city then)
6581 SetRestType(REST_TYPE_NO
);
6585 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6586 // if player resurrected at teleport this will be applied in resurrect code
6588 DestroyZoneLimitedItem( true, newZone
);
6590 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6591 AutoUnequipOffhandIfNeed();
6593 // recent client version not send leave/join channel packets for built-in local channels
6594 UpdateLocalChannels( newZone
);
6598 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE
);
6600 UpdateZoneDependentAuras(newZone
);
6603 //If players are too far way of duel flag... then player loose the duel
6604 void Player::CheckDuelDistance(time_t currTime
)
6609 uint64 duelFlagGUID
= GetUInt64Value(PLAYER_DUEL_ARBITER
);
6610 GameObject
* obj
= GetMap()->GetGameObject(duelFlagGUID
);
6614 if(duel
->outOfBound
== 0)
6616 if(!IsWithinDistInMap(obj
, 50))
6618 duel
->outOfBound
= currTime
;
6620 WorldPacket
data(SMSG_DUEL_OUTOFBOUNDS
, 0);
6621 GetSession()->SendPacket(&data
);
6626 if(IsWithinDistInMap(obj
, 40))
6628 duel
->outOfBound
= 0;
6630 WorldPacket
data(SMSG_DUEL_INBOUNDS
, 0);
6631 GetSession()->SendPacket(&data
);
6633 else if(currTime
>= (duel
->outOfBound
+10))
6635 DuelComplete(DUEL_FLED
);
6640 void Player::DuelComplete(DuelCompleteType type
)
6642 // duel not requested
6646 WorldPacket
data(SMSG_DUEL_COMPLETE
, (1));
6647 data
<< (uint8
)((type
!= DUEL_INTERUPTED
) ? 1 : 0);
6648 GetSession()->SendPacket(&data
);
6649 duel
->opponent
->GetSession()->SendPacket(&data
);
6651 if(type
!= DUEL_INTERUPTED
)
6653 data
.Initialize(SMSG_DUEL_WINNER
, (1+20)); // we guess size
6654 data
<< (uint8
)((type
==DUEL_WON
) ? 0 : 1); // 0 = just won; 1 = fled
6655 data
<< duel
->opponent
->GetName();
6657 SendMessageToSet(&data
,true);
6660 if (type
== DUEL_WON
)
6662 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL
, 1);
6664 duel
->opponent
->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL
, 1);
6667 //Remove Duel Flag object
6668 GameObject
* obj
= GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER
));
6670 duel
->initiator
->RemoveGameObject(obj
,true);
6673 std::vector
<uint32
> auras2remove
;
6674 AuraMap
const& vAuras
= duel
->opponent
->GetAuras();
6675 for (AuraMap::const_iterator i
= vAuras
.begin(); i
!= vAuras
.end(); ++i
)
6677 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6678 auras2remove
.push_back(i
->second
->GetId());
6681 for(size_t i
=0; i
<auras2remove
.size(); ++i
)
6682 duel
->opponent
->RemoveAurasDueToSpell(auras2remove
[i
]);
6684 auras2remove
.clear();
6685 AuraMap
const& auras
= GetAuras();
6686 for (AuraMap::const_iterator i
= auras
.begin(); i
!= auras
.end(); ++i
)
6688 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == duel
->opponent
->GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6689 auras2remove
.push_back(i
->second
->GetId());
6691 for(size_t i
=0; i
<auras2remove
.size(); ++i
)
6692 RemoveAurasDueToSpell(auras2remove
[i
]);
6694 // cleanup combo points
6695 if(GetComboTarget()==duel
->opponent
->GetGUID())
6697 else if(GetComboTarget()==duel
->opponent
->GetPetGUID())
6700 if(duel
->opponent
->GetComboTarget()==GetGUID())
6701 duel
->opponent
->ClearComboPoints();
6702 else if(duel
->opponent
->GetComboTarget()==GetPetGUID())
6703 duel
->opponent
->ClearComboPoints();
6706 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6707 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6708 duel
->opponent
->SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6709 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6711 delete duel
->opponent
->duel
;
6712 duel
->opponent
->duel
= NULL
;
6717 //---------------------------------------------------------//
6719 void Player::_ApplyItemMods(Item
*item
, uint8 slot
,bool apply
)
6721 if(slot
>= INVENTORY_SLOT_BAG_END
|| !item
)
6724 // not apply/remove mods for broken item
6725 if(item
->IsBroken())
6728 ItemPrototype
const *proto
= item
->GetProto();
6733 sLog
.outDetail("applying mods for item %u ",item
->GetGUIDLow());
6735 uint32 attacktype
= Player::GetAttackBySlot(slot
);
6736 if(attacktype
< MAX_ATTACK
)
6737 _ApplyWeaponDependentAuraMods(item
,WeaponAttackType(attacktype
),apply
);
6739 _ApplyItemBonuses(proto
,slot
,apply
);
6741 if( slot
==EQUIPMENT_SLOT_RANGED
)
6742 _ApplyAmmoBonuses();
6744 ApplyItemEquipSpell(item
,apply
);
6745 ApplyEnchantment(item
, apply
);
6747 if(proto
->Socket
[0].Color
) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6748 CorrectMetaGemEnchants(slot
, apply
);
6750 sLog
.outDebug("_ApplyItemMods complete.");
6753 void Player::_ApplyItemBonuses(ItemPrototype
const *proto
, uint8 slot
, bool apply
, bool only_level_scale
/*= false*/)
6755 if (slot
>= INVENTORY_SLOT_BAG_END
|| !proto
)
6758 ScalingStatDistributionEntry
const *ssd
= proto
->ScalingStatDistribution
? sScalingStatDistributionStore
.LookupEntry(proto
->ScalingStatDistribution
) : NULL
;
6759 if (only_level_scale
&& !ssd
)
6762 // req. check at equip, but allow use for extended range if range limit max level, set proper level
6763 uint32 ssd_level
= getLevel();
6764 if (ssd
&& ssd_level
> ssd
->MaxLevel
)
6765 ssd_level
= ssd
->MaxLevel
;
6767 ScalingStatValuesEntry
const *ssv
= proto
->ScalingStatValue
? sScalingStatValuesStore
.LookupEntry(ssd_level
) : NULL
;
6768 if (only_level_scale
&& !ssv
)
6771 for (uint32 i
= 0; i
< MAX_ITEM_PROTO_STATS
; ++i
)
6773 uint32 statType
= 0;
6775 // If set ScalingStatDistribution need get stats and values from it
6778 if (ssd
->StatMod
[i
] < 0)
6780 statType
= ssd
->StatMod
[i
];
6781 val
= (ssv
->getssdMultiplier(proto
->ScalingStatValue
) * ssd
->Modifier
[i
]) / 10000;
6785 if (i
>= proto
->StatsCount
)
6787 statType
= proto
->ItemStat
[i
].ItemStatType
;
6788 val
= proto
->ItemStat
[i
].ItemStatValue
;
6797 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(val
), apply
);
6799 case ITEM_MOD_HEALTH
: // modify HP
6800 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(val
), apply
);
6802 case ITEM_MOD_AGILITY
: // modify agility
6803 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, BASE_VALUE
, float(val
), apply
);
6804 ApplyStatBuffMod(STAT_AGILITY
, float(val
), apply
);
6806 case ITEM_MOD_STRENGTH
: //modify strength
6807 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, BASE_VALUE
, float(val
), apply
);
6808 ApplyStatBuffMod(STAT_STRENGTH
, float(val
), apply
);
6810 case ITEM_MOD_INTELLECT
: //modify intellect
6811 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, BASE_VALUE
, float(val
), apply
);
6812 ApplyStatBuffMod(STAT_INTELLECT
, float(val
), apply
);
6814 case ITEM_MOD_SPIRIT
: //modify spirit
6815 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, BASE_VALUE
, float(val
), apply
);
6816 ApplyStatBuffMod(STAT_SPIRIT
, float(val
), apply
);
6818 case ITEM_MOD_STAMINA
: //modify stamina
6819 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, BASE_VALUE
, float(val
), apply
);
6820 ApplyStatBuffMod(STAT_STAMINA
, float(val
), apply
);
6822 case ITEM_MOD_DEFENSE_SKILL_RATING
:
6823 ApplyRatingMod(CR_DEFENSE_SKILL
, int32(val
), apply
);
6825 case ITEM_MOD_DODGE_RATING
:
6826 ApplyRatingMod(CR_DODGE
, int32(val
), apply
);
6828 case ITEM_MOD_PARRY_RATING
:
6829 ApplyRatingMod(CR_PARRY
, int32(val
), apply
);
6831 case ITEM_MOD_BLOCK_RATING
:
6832 ApplyRatingMod(CR_BLOCK
, int32(val
), apply
);
6834 case ITEM_MOD_HIT_MELEE_RATING
:
6835 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6837 case ITEM_MOD_HIT_RANGED_RATING
:
6838 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6840 case ITEM_MOD_HIT_SPELL_RATING
:
6841 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6843 case ITEM_MOD_CRIT_MELEE_RATING
:
6844 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6846 case ITEM_MOD_CRIT_RANGED_RATING
:
6847 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6849 case ITEM_MOD_CRIT_SPELL_RATING
:
6850 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6852 case ITEM_MOD_HIT_TAKEN_MELEE_RATING
:
6853 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6855 case ITEM_MOD_HIT_TAKEN_RANGED_RATING
:
6856 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6858 case ITEM_MOD_HIT_TAKEN_SPELL_RATING
:
6859 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6861 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING
:
6862 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6864 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING
:
6865 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6867 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING
:
6868 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6870 case ITEM_MOD_HASTE_MELEE_RATING
:
6871 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6873 case ITEM_MOD_HASTE_RANGED_RATING
:
6874 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6876 case ITEM_MOD_HASTE_SPELL_RATING
:
6877 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6879 case ITEM_MOD_HIT_RATING
:
6880 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6881 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6882 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6884 case ITEM_MOD_CRIT_RATING
:
6885 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6886 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6887 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6889 case ITEM_MOD_HIT_TAKEN_RATING
:
6890 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6891 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6892 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6894 case ITEM_MOD_CRIT_TAKEN_RATING
:
6895 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6896 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6897 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6899 case ITEM_MOD_RESILIENCE_RATING
:
6900 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6901 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6902 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6904 case ITEM_MOD_HASTE_RATING
:
6905 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6906 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6907 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6909 case ITEM_MOD_EXPERTISE_RATING
:
6910 ApplyRatingMod(CR_EXPERTISE
, int32(val
), apply
);
6912 case ITEM_MOD_ATTACK_POWER
:
6913 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(val
), apply
);
6914 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6916 case ITEM_MOD_RANGED_ATTACK_POWER
:
6917 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6919 case ITEM_MOD_MANA_REGENERATION
:
6920 ApplyManaRegenBonus(int32(val
), apply
);
6922 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
6923 ApplyRatingMod(CR_ARMOR_PENETRATION
, int32(val
), apply
);
6925 case ITEM_MOD_SPELL_POWER
:
6926 ApplySpellPowerBonus(int32(val
), apply
);
6928 case ITEM_MOD_BLOCK_VALUE
:
6929 HandleBaseModValue(SHIELD_BLOCK_VALUE
, FLAT_MOD
, float(val
), apply
);
6931 // depricated item mods
6932 case ITEM_MOD_FERAL_ATTACK_POWER
:
6933 case ITEM_MOD_SPELL_HEALING_DONE
:
6934 case ITEM_MOD_SPELL_DAMAGE_DONE
:
6939 // Apply Spell Power from ScalingStatValue if set
6942 if (int32 spellbonus
= ssv
->getSpellBonus(proto
->ScalingStatValue
))
6943 ApplySpellPowerBonus(spellbonus
, apply
);
6946 // If set ScalingStatValue armor get it or use item armor
6947 uint32 armor
= proto
->Armor
;
6950 if (uint32 ssvarmor
= ssv
->getArmorMod(proto
->ScalingStatValue
))
6953 // Add armor bonus from ArmorDamageModifier if > 0
6954 if (proto
->ArmorDamageModifier
> 0)
6955 armor
+= uint32(proto
->ArmorDamageModifier
);
6958 HandleStatModifier(UNIT_MOD_ARMOR
, BASE_VALUE
, float(armor
), apply
);
6961 HandleBaseModValue(SHIELD_BLOCK_VALUE
, FLAT_MOD
, float(proto
->Block
), apply
);
6964 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY
, BASE_VALUE
, float(proto
->HolyRes
), apply
);
6967 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE
, BASE_VALUE
, float(proto
->FireRes
), apply
);
6969 if (proto
->NatureRes
)
6970 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE
, BASE_VALUE
, float(proto
->NatureRes
), apply
);
6972 if (proto
->FrostRes
)
6973 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST
, BASE_VALUE
, float(proto
->FrostRes
), apply
);
6975 if (proto
->ShadowRes
)
6976 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW
, BASE_VALUE
, float(proto
->ShadowRes
), apply
);
6978 if (proto
->ArcaneRes
)
6979 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE
, BASE_VALUE
, float(proto
->ArcaneRes
), apply
);
6981 WeaponAttackType attType
= BASE_ATTACK
;
6982 float damage
= 0.0f
;
6984 if( slot
== EQUIPMENT_SLOT_RANGED
&& (
6985 proto
->InventoryType
== INVTYPE_RANGED
|| proto
->InventoryType
== INVTYPE_THROWN
||
6986 proto
->InventoryType
== INVTYPE_RANGEDRIGHT
))
6988 attType
= RANGED_ATTACK
;
6990 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6992 attType
= OFF_ATTACK
;
6995 float minDamage
= proto
->Damage
[0].DamageMin
;
6996 float maxDamage
= proto
->Damage
[0].DamageMax
;
6998 // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
7001 if ((extraDPS
= ssv
->getDPSMod(proto
->ScalingStatValue
)))
7003 float average
= extraDPS
* proto
->Delay
/ 1000.0f
;
7004 minDamage
= 0.7f
* average
;
7005 maxDamage
= 1.3f
* average
;
7010 damage
= apply
? minDamage
: BASE_MINDAMAGE
;
7011 SetBaseWeaponDamage(attType
, MINDAMAGE
, damage
);
7012 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
7017 damage
= apply
? maxDamage
: BASE_MAXDAMAGE
;
7018 SetBaseWeaponDamage(attType
, MAXDAMAGE
, damage
);
7021 // Apply feral bonus from ScalingStatValue if set
7024 if (int32 feral_bonus
= ssv
->getFeralBonus(proto
->ScalingStatValue
))
7025 ApplyFeralAPBonus(feral_bonus
, apply
);
7027 // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
7028 if(getClass() == CLASS_DRUID
)
7030 int32 feral_bonus
= proto
->getFeralBonus(extraDPS
);
7031 if (feral_bonus
> 0)
7032 ApplyFeralAPBonus(feral_bonus
, apply
);
7035 if(!IsUseEquipedWeapon(slot
==EQUIPMENT_SLOT_MAINHAND
))
7040 if(slot
== EQUIPMENT_SLOT_RANGED
)
7041 SetAttackTime(RANGED_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
7042 else if(slot
==EQUIPMENT_SLOT_MAINHAND
)
7043 SetAttackTime(BASE_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
7044 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
7045 SetAttackTime(OFF_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
7048 if(CanModifyStats() && (damage
|| proto
->Delay
))
7049 UpdateDamagePhysical(attType
);
7052 void Player::_ApplyWeaponDependentAuraMods(Item
*item
,WeaponAttackType attackType
,bool apply
)
7054 AuraList
const& auraCritList
= GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT
);
7055 for(AuraList::const_iterator itr
= auraCritList
.begin(); itr
!=auraCritList
.end();++itr
)
7056 _ApplyWeaponDependentAuraCritMod(item
,attackType
,*itr
,apply
);
7058 AuraList
const& auraDamageFlatList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE
);
7059 for(AuraList::const_iterator itr
= auraDamageFlatList
.begin(); itr
!=auraDamageFlatList
.end();++itr
)
7060 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
7062 AuraList
const& auraDamagePCTList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
);
7063 for(AuraList::const_iterator itr
= auraDamagePCTList
.begin(); itr
!=auraDamagePCTList
.end();++itr
)
7064 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
7067 void Player::_ApplyWeaponDependentAuraCritMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
7069 // generic not weapon specific case processes in aura code
7070 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
7073 BaseModGroup mod
= BASEMOD_END
;
7076 case BASE_ATTACK
: mod
= CRIT_PERCENTAGE
; break;
7077 case OFF_ATTACK
: mod
= OFFHAND_CRIT_PERCENTAGE
;break;
7078 case RANGED_ATTACK
: mod
= RANGED_CRIT_PERCENTAGE
; break;
7082 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
7084 HandleBaseModValue(mod
, FLAT_MOD
, float (aura
->GetModifier()->m_amount
), apply
);
7088 void Player::_ApplyWeaponDependentAuraDamageMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
7090 // ignore spell mods for not wands
7091 Modifier
const* modifier
= aura
->GetModifier();
7092 if((modifier
->m_miscvalue
& SPELL_SCHOOL_MASK_NORMAL
)==0 && (getClassMask() & CLASSMASK_WAND_USERS
)==0)
7095 // generic not weapon specific case processes in aura code
7096 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
7099 UnitMods unitMod
= UNIT_MOD_END
;
7102 case BASE_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_MAINHAND
; break;
7103 case OFF_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_OFFHAND
; break;
7104 case RANGED_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_RANGED
; break;
7108 UnitModifierType unitModType
= TOTAL_VALUE
;
7109 switch(modifier
->m_auraname
)
7111 case SPELL_AURA_MOD_DAMAGE_DONE
: unitModType
= TOTAL_VALUE
; break;
7112 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
: unitModType
= TOTAL_PCT
; break;
7116 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
7118 HandleStatModifier(unitMod
, unitModType
, float(modifier
->m_amount
),apply
);
7122 void Player::ApplyItemEquipSpell(Item
*item
, bool apply
, bool form_change
)
7127 ItemPrototype
const *proto
= item
->GetProto();
7131 for (int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
7133 _Spell
const& spellData
= proto
->Spells
[i
];
7136 if(!spellData
.SpellId
)
7139 // wrong triggering type
7140 if(apply
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_EQUIP
)
7143 // check if it is valid spell
7144 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7148 ApplyEquipSpell(spellproto
,item
,apply
,form_change
);
7152 void Player::ApplyEquipSpell(SpellEntry
const* spellInfo
, Item
* item
, bool apply
, bool form_change
)
7156 // Cannot be used in this stance/form
7157 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
) != SPELL_CAST_OK
)
7160 if(form_change
) // check aura active state from other form
7163 for (int k
=0; k
< MAX_EFFECT_INDEX
; ++k
)
7165 spellEffectPair spair
= spellEffectPair(spellInfo
->Id
, SpellEffectIndex(k
));
7166 for (AuraMap::const_iterator iter
= m_Auras
.lower_bound(spair
); iter
!= m_Auras
.upper_bound(spair
); ++iter
)
7168 if(!item
|| iter
->second
->GetCastItemGUID() == item
->GetGUID())
7178 if(found
) // and skip re-cast already active aura at form change
7182 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item
? "item" : "itemset"), spellInfo
->Id
);
7184 CastSpell(this,spellInfo
,true,item
);
7188 if(form_change
) // check aura compatibility
7190 // Cannot be used in this stance/form
7191 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)==SPELL_CAST_OK
)
7192 return; // and remove only not compatible at form change
7196 RemoveAurasDueToItemSpell(item
,spellInfo
->Id
); // un-apply all spells , not only at-equipped
7198 RemoveAurasDueToSpell(spellInfo
->Id
); // un-apply spell (item set case)
7202 void Player::UpdateEquipSpellsAtFormChange()
7204 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7206 if(m_items
[i
] && !m_items
[i
]->IsBroken())
7208 ApplyItemEquipSpell(m_items
[i
],false,true); // remove spells that not fit to form
7209 ApplyItemEquipSpell(m_items
[i
],true,true); // add spells that fit form but not active
7213 // item set bonuses not dependent from item broken state
7214 for(size_t setindex
= 0; setindex
< ItemSetEff
.size(); ++setindex
)
7216 ItemSetEffect
* eff
= ItemSetEff
[setindex
];
7220 for(uint32 y
=0;y
<8; ++y
)
7222 SpellEntry
const* spellInfo
= eff
->spells
[y
];
7226 ApplyEquipSpell(spellInfo
,NULL
,false,true); // remove spells that not fit to form
7227 ApplyEquipSpell(spellInfo
,NULL
,true,true); // add spells that fit form but not active
7232 void Player::CastItemCombatSpell(Unit
* Target
, WeaponAttackType attType
)
7234 Item
*item
= GetWeaponForAttack(attType
, true, false);
7238 ItemPrototype
const *proto
= item
->GetProto();
7242 if (!Target
|| Target
== this )
7245 for (int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
7247 _Spell
const& spellData
= proto
->Spells
[i
];
7250 if(!spellData
.SpellId
)
7253 // wrong triggering type
7254 if(spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_CHANCE_ON_HIT
)
7257 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7260 sLog
.outError("WORLD: unknown Item spellid %i", spellData
.SpellId
);
7264 // not allow proc extra attack spell at extra attack
7265 if( m_extraAttacks
&& IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_ADD_EXTRA_ATTACKS
) )
7268 float chance
= (float)spellInfo
->procChance
;
7270 if(spellData
.SpellPPMRate
)
7272 uint32 WeaponSpeed
= proto
->Delay
;
7273 chance
= GetPPMProcChance(WeaponSpeed
, spellData
.SpellPPMRate
);
7275 else if(chance
> 100.0f
)
7277 chance
= GetWeaponProcChance();
7280 if (roll_chance_f(chance
))
7281 CastSpell(Target
, spellInfo
->Id
, true, item
);
7284 // item combat enchantments
7285 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
7287 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
7288 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
7289 if(!pEnchant
) continue;
7290 for (int s
= 0; s
< 3; ++s
)
7292 if (pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
)
7295 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
7298 sLog
.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
7302 // Use first rank to access spell item enchant procs
7303 float ppmRate
= sSpellMgr
.GetItemEnchantProcChance(spellInfo
->Id
);
7305 float chance
= ppmRate
7306 ? GetPPMProcChance(proto
->Delay
, ppmRate
)
7307 : pEnchant
->amount
[s
] != 0 ? float(pEnchant
->amount
[s
]) : GetWeaponProcChance();
7310 ApplySpellMod(spellInfo
->Id
,SPELLMOD_CHANCE_OF_SUCCESS
,chance
);
7311 ApplySpellMod(spellInfo
->Id
,SPELLMOD_FREQUENCY_OF_SUCCESS
,chance
);
7313 if (roll_chance_f(chance
))
7315 if(IsPositiveSpell(pEnchant
->spellid
[s
]))
7316 CastSpell(this, pEnchant
->spellid
[s
], true, item
);
7318 CastSpell(Target
, pEnchant
->spellid
[s
], true, item
);
7324 void Player::CastItemUseSpell(Item
*item
,SpellCastTargets
const& targets
,uint8 cast_count
, uint32 glyphIndex
)
7326 ItemPrototype
const* proto
= item
->GetProto();
7327 // special learning case
7328 if(proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN
|| proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN_PET
)
7330 uint32 learn_spell_id
= proto
->Spells
[0].SpellId
;
7331 uint32 learning_spell_id
= proto
->Spells
[1].SpellId
;
7333 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(learn_spell_id
);
7336 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto
->ItemId
, learn_spell_id
);
7337 SendEquipError(EQUIP_ERR_NONE
, item
);
7341 Spell
*spell
= new Spell(this, spellInfo
, false);
7342 spell
->m_CastItem
= item
;
7343 spell
->m_cast_count
= cast_count
; //set count of casts
7344 spell
->m_currentBasePoints
[EFFECT_INDEX_0
] = learning_spell_id
;
7345 spell
->prepare(&targets
);
7349 // use triggered flag only for items with many spell casts and for not first cast
7352 // item spells casted at use
7353 for(int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
7355 _Spell
const& spellData
= proto
->Spells
[i
];
7358 if(!spellData
.SpellId
)
7361 // wrong triggering type
7362 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_NO_DELAY_USE
)
7365 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7368 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto
->ItemId
, spellData
.SpellId
);
7372 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
7373 spell
->m_CastItem
= item
;
7374 spell
->m_cast_count
= cast_count
; // set count of casts
7375 spell
->m_glyphIndex
= glyphIndex
; // glyph index
7376 spell
->prepare(&targets
);
7381 // Item enchantments spells casted at use
7382 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
7384 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
7385 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
7386 if(!pEnchant
) continue;
7387 for (int s
= 0; s
< 3; ++s
)
7389 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL
)
7392 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
7395 sLog
.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
7399 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
7400 spell
->m_CastItem
= item
;
7401 spell
->m_cast_count
= cast_count
; // set count of casts
7402 spell
->m_glyphIndex
= glyphIndex
; // glyph index
7403 spell
->prepare(&targets
);
7410 void Player::_RemoveAllItemMods()
7412 sLog
.outDebug("_RemoveAllItemMods start.");
7414 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7418 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7422 // item set bonuses not dependent from item broken state
7424 RemoveItemsSetItem(this,proto
);
7426 if(m_items
[i
]->IsBroken())
7429 ApplyItemEquipSpell(m_items
[i
],false);
7430 ApplyEnchantment(m_items
[i
], false);
7434 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7438 if(m_items
[i
]->IsBroken())
7440 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7444 uint32 attacktype
= Player::GetAttackBySlot(i
);
7445 if(attacktype
< MAX_ATTACK
)
7446 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),false);
7448 _ApplyItemBonuses(proto
,i
, false);
7450 if( i
== EQUIPMENT_SLOT_RANGED
)
7451 _ApplyAmmoBonuses();
7455 sLog
.outDebug("_RemoveAllItemMods complete.");
7458 void Player::_ApplyAllItemMods()
7460 sLog
.outDebug("_ApplyAllItemMods start.");
7462 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7466 if(m_items
[i
]->IsBroken())
7469 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7473 uint32 attacktype
= Player::GetAttackBySlot(i
);
7474 if(attacktype
< MAX_ATTACK
)
7475 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),true);
7477 _ApplyItemBonuses(proto
,i
, true);
7479 if( i
== EQUIPMENT_SLOT_RANGED
)
7480 _ApplyAmmoBonuses();
7484 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7488 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7492 // item set bonuses not dependent from item broken state
7494 AddItemsSetItem(this,m_items
[i
]);
7496 if(m_items
[i
]->IsBroken())
7499 ApplyItemEquipSpell(m_items
[i
],true);
7500 ApplyEnchantment(m_items
[i
], true);
7504 sLog
.outDebug("_ApplyAllItemMods complete.");
7507 void Player::_ApplyAllLevelScaleItemMods(bool apply
)
7509 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7513 if(m_items
[i
]->IsBroken())
7516 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7520 _ApplyItemBonuses(proto
,i
, apply
, true);
7525 void Player::_ApplyAmmoBonuses()
7528 uint32 ammo_id
= GetUInt32Value(PLAYER_AMMO_ID
);
7532 float currentAmmoDPS
;
7534 ItemPrototype
const *ammo_proto
= ObjectMgr::GetItemPrototype( ammo_id
);
7535 if( !ammo_proto
|| ammo_proto
->Class
!=ITEM_CLASS_PROJECTILE
|| !CheckAmmoCompatibility(ammo_proto
))
7536 currentAmmoDPS
= 0.0f
;
7538 currentAmmoDPS
= ammo_proto
->Damage
[0].DamageMin
;
7540 if(currentAmmoDPS
== GetAmmoDPS())
7543 m_ammoDPS
= currentAmmoDPS
;
7545 if(CanModifyStats())
7546 UpdateDamagePhysical(RANGED_ATTACK
);
7549 bool Player::CheckAmmoCompatibility(const ItemPrototype
*ammo_proto
) const
7554 // check ranged weapon
7555 Item
*weapon
= GetWeaponForAttack( RANGED_ATTACK
, true, false );
7559 ItemPrototype
const* weapon_proto
= weapon
->GetProto();
7560 if(!weapon_proto
|| weapon_proto
->Class
!=ITEM_CLASS_WEAPON
)
7563 // check ammo ws. weapon compatibility
7564 switch(weapon_proto
->SubClass
)
7566 case ITEM_SUBCLASS_WEAPON_BOW
:
7567 case ITEM_SUBCLASS_WEAPON_CROSSBOW
:
7568 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_ARROW
)
7571 case ITEM_SUBCLASS_WEAPON_GUN
:
7572 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_BULLET
)
7582 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7583 Called by remove insignia spell effect */
7584 void Player::RemovedInsignia(Player
* looterPlr
)
7586 if (!GetBattleGroundId())
7589 // If not released spirit, do it !
7590 if(m_deathTimer
> 0)
7597 Corpse
*corpse
= GetCorpse();
7601 // We have to convert player corpse to bones, not to be able to resurrect there
7602 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7603 Corpse
*bones
= sObjectAccessor
.ConvertCorpseForPlayer(GetGUID(),true);
7607 // Now we must make bones lootable, and send player loot
7608 bones
->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS
, CORPSE_DYNFLAG_LOOTABLE
);
7610 // We store the level of our player in the gold field
7611 // We retrieve this information at Player::SendLoot()
7612 bones
->loot
.gold
= getLevel();
7613 bones
->lootRecipient
= looterPlr
;
7614 looterPlr
->SendLoot(bones
->GetGUID(), LOOT_INSIGNIA
);
7617 void Player::SendLootRelease(ObjectGuid guid
)
7619 WorldPacket
data( SMSG_LOOT_RELEASE_RESPONSE
, (8+1) );
7622 SendDirectMessage( &data
);
7625 void Player::SendLoot(ObjectGuid guid
, LootType loot_type
)
7627 if (uint64 lguid
= GetLootGUID())
7628 m_session
->DoLootRelease(lguid
);
7631 PermissionTypes permission
= ALL_PERMISSION
;
7633 sLog
.outDebug("Player::SendLoot");
7634 switch(guid
.GetHigh())
7636 case HIGHGUID_GAMEOBJECT
:
7638 sLog
.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7639 GameObject
*go
= GetMap()->GetGameObject(guid
);
7641 // not check distance for GO in case owned GO (fishing bobber case, for example)
7642 // And permit out of range GO with no owner in case fishing hole
7643 if (!go
|| (loot_type
!= LOOT_FISHINGHOLE
&& (loot_type
!= LOOT_FISHING
|| go
->GetOwnerGUID() != GetGUID()) && !go
->IsWithinDistInMap(this,INTERACTION_DISTANCE
)))
7645 SendLootRelease(guid
);
7651 if (go
->getLootState() == GO_READY
)
7653 uint32 lootid
= go
->GetGOInfo()->GetLootId();
7654 if ((go
->GetEntry() == BG_AV_OBJECTID_MINE_N
|| go
->GetEntry() == BG_AV_OBJECTID_MINE_S
))
7655 if (BattleGround
*bg
= GetBattleGround())
7656 if (bg
->GetTypeID() == BATTLEGROUND_AV
)
7657 if (!(((BattleGroundAV
*)bg
)->PlayerCanDoMineQuest(go
->GetEntry(), GetTeam())))
7659 SendLootRelease(guid
);
7665 sLog
.outDebug(" if(lootid)");
7667 loot
->FillLoot(lootid
, LootTemplates_Gameobject
, this, false);
7670 if (loot_type
== LOOT_FISHING
)
7671 go
->getFishLoot(loot
,this);
7673 go
->SetLootState(GO_ACTIVATED
);
7679 Item
*item
= GetItemByGuid( guid
);
7683 SendLootRelease(guid
);
7689 if (!item
->m_lootGenerated
)
7691 item
->m_lootGenerated
= true;
7696 case LOOT_DISENCHANTING
:
7697 loot
->FillLoot(item
->GetProto()->DisenchantID
, LootTemplates_Disenchant
, this,true);
7699 case LOOT_PROSPECTING
:
7700 loot
->FillLoot(item
->GetEntry(), LootTemplates_Prospecting
, this,true);
7703 loot
->FillLoot(item
->GetEntry(), LootTemplates_Milling
, this,true);
7706 loot
->FillLoot(item
->GetEntry(), LootTemplates_Item
, this,true);
7707 loot
->generateMoneyLoot(item
->GetProto()->MinMoneyLoot
,item
->GetProto()->MaxMoneyLoot
);
7713 case HIGHGUID_CORPSE
: // remove insignia
7715 Corpse
*bones
= GetMap()->GetCorpse(guid
);
7717 if (!bones
|| !((loot_type
== LOOT_CORPSE
) || (loot_type
== LOOT_INSIGNIA
)) || (bones
->GetType() != CORPSE_BONES
) )
7719 SendLootRelease(guid
);
7723 loot
= &bones
->loot
;
7725 if (!bones
->lootForBody
)
7727 bones
->lootForBody
= true;
7728 uint32 pLevel
= bones
->loot
.gold
;
7729 bones
->loot
.clear();
7730 if (GetBattleGround()->GetTypeID() == BATTLEGROUND_AV
)
7731 loot
->FillLoot(0, LootTemplates_Creature
, this, false);
7732 // It may need a better formula
7733 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7734 bones
->loot
.gold
= (uint32
)( urand(50, 150) * 0.016f
* pow( ((float)pLevel
)/5.76f
, 2.5f
) * sWorld
.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY
) );
7737 if (bones
->lootRecipient
!= this)
7738 permission
= NONE_PERMISSION
;
7743 Creature
*creature
= GetMap()->GetCreature(guid
);
7745 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7746 if (!creature
|| creature
->isAlive()!=(loot_type
== LOOT_PICKPOCKETING
) || !creature
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
7748 SendLootRelease(guid
);
7752 if (loot_type
== LOOT_PICKPOCKETING
&& IsFriendlyTo(creature
))
7754 SendLootRelease(guid
);
7758 loot
= &creature
->loot
;
7760 if (loot_type
== LOOT_PICKPOCKETING
)
7762 if (!creature
->lootForPickPocketed
)
7764 creature
->lootForPickPocketed
= true;
7767 if (uint32 lootid
= creature
->GetCreatureInfo()->pickpocketLootId
)
7768 loot
->FillLoot(lootid
, LootTemplates_Pickpocketing
, this, false);
7770 // Generate extra money for pick pocket loot
7771 const uint32 a
= urand(0, creature
->getLevel()/2);
7772 const uint32 b
= urand(0, getLevel()/2);
7773 loot
->gold
= uint32(10 * (a
+ b
) * sWorld
.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY
));
7778 // the player whose group may loot the corpse
7779 Player
*recipient
= creature
->GetLootRecipient();
7782 creature
->SetLootRecipient(this);
7786 if (creature
->lootForPickPocketed
)
7788 creature
->lootForPickPocketed
= false;
7792 if (!creature
->lootForBody
)
7794 creature
->lootForBody
= true;
7797 if (uint32 lootid
= creature
->GetCreatureInfo()->lootid
)
7798 loot
->FillLoot(lootid
, LootTemplates_Creature
, recipient
, false);
7800 loot
->generateMoneyLoot(creature
->GetCreatureInfo()->mingold
,creature
->GetCreatureInfo()->maxgold
);
7802 if (Group
* group
= recipient
->GetGroup())
7804 group
->UpdateLooterGuid(creature
,true);
7806 switch (group
->GetLootMethod())
7809 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7810 group
->GroupLoot(recipient
->GetObjectGuid(), loot
, creature
);
7812 case NEED_BEFORE_GREED
:
7813 group
->NeedBeforeGreed(recipient
->GetObjectGuid(), loot
, creature
);
7816 group
->MasterLoot(recipient
->GetObjectGuid(), loot
, creature
);
7824 // possible only if creature->lootForBody && loot->empty() at spell cast check
7825 if (loot_type
== LOOT_SKINNING
)
7828 loot
->FillLoot(creature
->GetCreatureInfo()->SkinLootId
, LootTemplates_Skinning
, this, false);
7830 // set group rights only for loot_type != LOOT_SKINNING
7833 if(Group
* group
= GetGroup())
7835 if (group
== recipient
->GetGroup())
7837 if (group
->GetLootMethod() == FREE_FOR_ALL
)
7838 permission
= ALL_PERMISSION
;
7839 else if (group
->GetLooterGuid() == GetGUID())
7841 if (group
->GetLootMethod() == MASTER_LOOT
)
7842 permission
= MASTER_PERMISSION
;
7844 permission
= ALL_PERMISSION
;
7847 permission
= GROUP_PERMISSION
;
7850 permission
= NONE_PERMISSION
;
7852 else if (recipient
== this)
7853 permission
= ALL_PERMISSION
;
7855 permission
= NONE_PERMISSION
;
7862 sLog
.outError("%s is unsupported for looting.", guid
.GetString().c_str());
7869 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7872 case LOOT_INSIGNIA
: loot_type
= LOOT_SKINNING
; break;
7873 case LOOT_FISHINGHOLE
: loot_type
= LOOT_FISHING
; break;
7877 // need know merged fishing/corpse loot type for achievements
7878 loot
->loot_type
= loot_type
;
7880 WorldPacket
data(SMSG_LOOT_RESPONSE
, (9+50)); // we guess size
7883 data
<< uint8(loot_type
);
7884 data
<< LootView(*loot
, this, permission
);
7886 SendDirectMessage(&data
);
7888 // add 'this' player as one of the players that are looting 'loot'
7889 if (permission
!= NONE_PERMISSION
)
7890 loot
->AddLooter(GetGUID());
7892 if (loot_type
== LOOT_CORPSE
&& !guid
.IsItem())
7893 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_LOOTING
);
7896 void Player::SendNotifyLootMoneyRemoved()
7898 WorldPacket
data(SMSG_LOOT_CLEAR_MONEY
, 0);
7899 GetSession()->SendPacket( &data
);
7902 void Player::SendNotifyLootItemRemoved(uint8 lootSlot
)
7904 WorldPacket
data(SMSG_LOOT_REMOVED
, 1);
7905 data
<< uint8(lootSlot
);
7906 GetSession()->SendPacket( &data
);
7909 void Player::SendUpdateWorldState(uint32 Field
, uint32 Value
)
7911 WorldPacket
data(SMSG_UPDATE_WORLD_STATE
, 8);
7914 GetSession()->SendPacket(&data
);
7917 void Player::SendInitWorldStates(uint32 zoneid
, uint32 areaid
)
7919 // data depends on zoneid/mapid...
7920 BattleGround
* bg
= GetBattleGround();
7921 uint16 NumberOfFields
= 0;
7922 uint32 mapid
= GetMapId();
7924 sLog
.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid
, zoneid
);
7926 // may be exist better way to do this...
7949 NumberOfFields
= 41;
7952 NumberOfFields
= 15;
7955 NumberOfFields
= 83;
7958 NumberOfFields
= 16;
7962 NumberOfFields
= 40;
7965 NumberOfFields
= 27;
7968 NumberOfFields
= 39;
7971 NumberOfFields
= 38;
7974 NumberOfFields
= 37;
7979 NumberOfFields
= 11;
7982 NumberOfFields
= 11;
7985 NumberOfFields
= 12;
7989 WorldPacket
data(SMSG_INIT_WORLD_STATES
, (4+4+4+2+(NumberOfFields
*8)));
7990 data
<< uint32(mapid
); // mapid
7991 data
<< uint32(zoneid
); // zone id
7992 data
<< uint32(areaid
); // area id, new 2.1.0
7993 data
<< uint16(NumberOfFields
); // count of uint64 blocks
7994 data
<< uint32(0x8d8) << uint32(0x0); // 1
7995 data
<< uint32(0x8d7) << uint32(0x0); // 2
7996 data
<< uint32(0x8d6) << uint32(0x0); // 3
7997 data
<< uint32(0x8d5) << uint32(0x0); // 4
7998 data
<< uint32(0x8d4) << uint32(0x0); // 5
7999 data
<< uint32(0x8d3) << uint32(0x0); // 6
8000 // 7 1 - Arena season in progress, 0 - end of season
8001 data
<< uint32(0xC77) << uint32(sWorld
.getConfig(CONFIG_BOOL_ARENA_SEASON_IN_PROGRESS
));
8002 // 8 Arena season id
8003 data
<< uint32(0xF3D) << uint32(sWorld
.getConfig(CONFIG_UINT32_ARENA_SEASON_ID
));
8004 if(mapid
== 530) // Outland
8006 data
<< uint32(0x9bf) << uint32(0x0); // 7
8007 data
<< uint32(0x9bd) << uint32(0xF); // 8
8008 data
<< uint32(0x9bb) << uint32(0xF); // 9
8023 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_AV
)
8024 bg
->FillInitialWorldStates(data
);
8027 data
<< uint32(0x7ae) << uint32(0x1); // 7 snowfall n
8028 data
<< uint32(0x532) << uint32(0x1); // 8 frostwolfhut hc
8029 data
<< uint32(0x531) << uint32(0x0); // 9 frostwolfhut ac
8030 data
<< uint32(0x52e) << uint32(0x0); // 10 stormpike firstaid a_a
8031 data
<< uint32(0x571) << uint32(0x0); // 11 east frostwolf tower horde assaulted -unused
8032 data
<< uint32(0x570) << uint32(0x0); // 12 west frostwolf tower horde assaulted - unused
8033 data
<< uint32(0x567) << uint32(0x1); // 13 frostwolfe c
8034 data
<< uint32(0x566) << uint32(0x1); // 14 frostwolfw c
8035 data
<< uint32(0x550) << uint32(0x1); // 15 irondeep (N) ally
8036 data
<< uint32(0x544) << uint32(0x0); // 16 ice grave a_a
8037 data
<< uint32(0x536) << uint32(0x0); // 17 stormpike grave h_c
8038 data
<< uint32(0x535) << uint32(0x1); // 18 stormpike grave a_c
8039 data
<< uint32(0x518) << uint32(0x0); // 19 stoneheart grave a_a
8040 data
<< uint32(0x517) << uint32(0x0); // 20 stoneheart grave h_a
8041 data
<< uint32(0x574) << uint32(0x0); // 21 1396 unk
8042 data
<< uint32(0x573) << uint32(0x0); // 22 iceblood tower horde assaulted -unused
8043 data
<< uint32(0x572) << uint32(0x0); // 23 towerpoint horde assaulted - unused
8044 data
<< uint32(0x56f) << uint32(0x0); // 24 1391 unk
8045 data
<< uint32(0x56e) << uint32(0x0); // 25 iceblood a
8046 data
<< uint32(0x56d) << uint32(0x0); // 26 towerp a
8047 data
<< uint32(0x56c) << uint32(0x0); // 27 frostwolfe a
8048 data
<< uint32(0x56b) << uint32(0x0); // 28 froswolfw a
8049 data
<< uint32(0x56a) << uint32(0x1); // 29 1386 unk
8050 data
<< uint32(0x569) << uint32(0x1); // 30 iceblood c
8051 data
<< uint32(0x568) << uint32(0x1); // 31 towerp c
8052 data
<< uint32(0x565) << uint32(0x0); // 32 stoneh tower a
8053 data
<< uint32(0x564) << uint32(0x0); // 33 icewing tower a
8054 data
<< uint32(0x563) << uint32(0x0); // 34 dunn a
8055 data
<< uint32(0x562) << uint32(0x0); // 35 duns a
8056 data
<< uint32(0x561) << uint32(0x0); // 36 stoneheart bunker alliance assaulted - unused
8057 data
<< uint32(0x560) << uint32(0x0); // 37 icewing bunker alliance assaulted - unused
8058 data
<< uint32(0x55f) << uint32(0x0); // 38 dunbaldar south alliance assaulted - unused
8059 data
<< uint32(0x55e) << uint32(0x0); // 39 dunbaldar north alliance assaulted - unused
8060 data
<< uint32(0x55d) << uint32(0x0); // 40 stone tower d
8061 data
<< uint32(0x3c6) << uint32(0x0); // 41 966 unk
8062 data
<< uint32(0x3c4) << uint32(0x0); // 42 964 unk
8063 data
<< uint32(0x3c2) << uint32(0x0); // 43 962 unk
8064 data
<< uint32(0x516) << uint32(0x1); // 44 stoneheart grave a_c
8065 data
<< uint32(0x515) << uint32(0x0); // 45 stonheart grave h_c
8066 data
<< uint32(0x3b6) << uint32(0x0); // 46 950 unk
8067 data
<< uint32(0x55c) << uint32(0x0); // 47 icewing tower d
8068 data
<< uint32(0x55b) << uint32(0x0); // 48 dunn d
8069 data
<< uint32(0x55a) << uint32(0x0); // 49 duns d
8070 data
<< uint32(0x559) << uint32(0x0); // 50 1369 unk
8071 data
<< uint32(0x558) << uint32(0x0); // 51 iceblood d
8072 data
<< uint32(0x557) << uint32(0x0); // 52 towerp d
8073 data
<< uint32(0x556) << uint32(0x0); // 53 frostwolfe d
8074 data
<< uint32(0x555) << uint32(0x0); // 54 frostwolfw d
8075 data
<< uint32(0x554) << uint32(0x1); // 55 stoneh tower c
8076 data
<< uint32(0x553) << uint32(0x1); // 56 icewing tower c
8077 data
<< uint32(0x552) << uint32(0x1); // 57 dunn c
8078 data
<< uint32(0x551) << uint32(0x1); // 58 duns c
8079 data
<< uint32(0x54f) << uint32(0x0); // 59 irondeep (N) horde
8080 data
<< uint32(0x54e) << uint32(0x0); // 60 irondeep (N) ally
8081 data
<< uint32(0x54d) << uint32(0x1); // 61 mine (S) neutral
8082 data
<< uint32(0x54c) << uint32(0x0); // 62 mine (S) horde
8083 data
<< uint32(0x54b) << uint32(0x0); // 63 mine (S) ally
8084 data
<< uint32(0x545) << uint32(0x0); // 64 iceblood h_a
8085 data
<< uint32(0x543) << uint32(0x1); // 65 iceblod h_c
8086 data
<< uint32(0x542) << uint32(0x0); // 66 iceblood a_c
8087 data
<< uint32(0x540) << uint32(0x0); // 67 snowfall h_a
8088 data
<< uint32(0x53f) << uint32(0x0); // 68 snowfall a_a
8089 data
<< uint32(0x53e) << uint32(0x0); // 69 snowfall h_c
8090 data
<< uint32(0x53d) << uint32(0x0); // 70 snowfall a_c
8091 data
<< uint32(0x53c) << uint32(0x0); // 71 frostwolf g h_a
8092 data
<< uint32(0x53b) << uint32(0x0); // 72 frostwolf g a_a
8093 data
<< uint32(0x53a) << uint32(0x1); // 73 frostwolf g h_c
8094 data
<< uint32(0x539) << uint32(0x0); // 74 frostwolf g a_c
8095 data
<< uint32(0x538) << uint32(0x0); // 75 stormpike grave h_a
8096 data
<< uint32(0x537) << uint32(0x0); // 76 stormpike grave a_a
8097 data
<< uint32(0x534) << uint32(0x0); // 77 frostwolf hut h_a
8098 data
<< uint32(0x533) << uint32(0x0); // 78 frostwolf hut a_a
8099 data
<< uint32(0x530) << uint32(0x0); // 79 stormpike first aid h_a
8100 data
<< uint32(0x52f) << uint32(0x0); // 80 stormpike first aid h_c
8101 data
<< uint32(0x52d) << uint32(0x1); // 81 stormpike first aid a_c
8105 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_WS
)
8106 bg
->FillInitialWorldStates(data
);
8109 data
<< uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
8110 data
<< uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
8111 data
<< uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
8112 data
<< uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
8113 data
<< uint32(0x60b) << uint32(0x2); // 11 1547 unk
8114 data
<< uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
8115 data
<< uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
8116 data
<< uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
8120 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_AB
)
8121 bg
->FillInitialWorldStates(data
);
8124 data
<< uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
8125 data
<< uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
8126 data
<< uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
8127 data
<< uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
8128 data
<< uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
8129 data
<< uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
8130 data
<< uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
8131 data
<< uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
8132 data
<< uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
8133 data
<< uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
8134 data
<< uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
8135 data
<< uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
8136 data
<< uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
8137 data
<< uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
8138 data
<< uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
8139 data
<< uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
8140 data
<< uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
8141 data
<< uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
8142 data
<< uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
8143 data
<< uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
8144 data
<< uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
8145 data
<< uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
8146 data
<< uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
8147 data
<< uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
8148 data
<< uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
8149 data
<< uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
8150 data
<< uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
8151 data
<< uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
8152 data
<< uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
8153 data
<< uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
8154 data
<< uint32(0x745) << uint32(0x2); // 37 1861 unk
8155 data
<< uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
8159 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_EY
)
8160 bg
->FillInitialWorldStates(data
);
8163 data
<< uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
8164 data
<< uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
8165 data
<< uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
8166 data
<< uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
8167 data
<< uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
8168 data
<< uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
8169 data
<< uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
8170 data
<< uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
8171 data
<< uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
8172 data
<< uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
8173 data
<< uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
8174 data
<< uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
8175 data
<< uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
8176 data
<< uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
8177 data
<< uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
8178 data
<< uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
8179 data
<< uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
8180 data
<< uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
8181 data
<< uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
8182 data
<< uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
8183 data
<< uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
8184 data
<< uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
8185 data
<< uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
8186 data
<< uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
8187 data
<< uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
8188 data
<< uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
8189 data
<< uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
8190 data
<< uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
8191 data
<< uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
8192 data
<< uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
8193 data
<< uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
8194 data
<< uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
8195 // and some more ... unknown
8198 case 3483: // Hellfire Peninsula
8199 data
<< uint32(0x9ba) << uint32(0x1); // 10
8200 data
<< uint32(0x9b9) << uint32(0x1); // 11
8201 data
<< uint32(0x9b5) << uint32(0x0); // 12
8202 data
<< uint32(0x9b4) << uint32(0x1); // 13
8203 data
<< uint32(0x9b3) << uint32(0x0); // 14
8204 data
<< uint32(0x9b2) << uint32(0x0); // 15
8205 data
<< uint32(0x9b1) << uint32(0x1); // 16
8206 data
<< uint32(0x9b0) << uint32(0x0); // 17
8207 data
<< uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
8208 data
<< uint32(0x9ac) << uint32(0x0); // 19
8209 data
<< uint32(0x9a8) << uint32(0x0); // 20
8210 data
<< uint32(0x9a7) << uint32(0x0); // 21
8211 data
<< uint32(0x9a6) << uint32(0x1); // 22
8213 case 3519: // Terokkar Forest
8214 data
<< uint32(0xa41) << uint32(0x0); // 10
8215 data
<< uint32(0xa40) << uint32(0x14); // 11
8216 data
<< uint32(0xa3f) << uint32(0x0); // 12
8217 data
<< uint32(0xa3e) << uint32(0x0); // 13
8218 data
<< uint32(0xa3d) << uint32(0x5); // 14
8219 data
<< uint32(0xa3c) << uint32(0x0); // 15
8220 data
<< uint32(0xa87) << uint32(0x0); // 16
8221 data
<< uint32(0xa86) << uint32(0x0); // 17
8222 data
<< uint32(0xa85) << uint32(0x0); // 18
8223 data
<< uint32(0xa84) << uint32(0x0); // 19
8224 data
<< uint32(0xa83) << uint32(0x0); // 20
8225 data
<< uint32(0xa82) << uint32(0x0); // 21
8226 data
<< uint32(0xa81) << uint32(0x0); // 22
8227 data
<< uint32(0xa80) << uint32(0x0); // 23
8228 data
<< uint32(0xa7e) << uint32(0x0); // 24
8229 data
<< uint32(0xa7d) << uint32(0x0); // 25
8230 data
<< uint32(0xa7c) << uint32(0x0); // 26
8231 data
<< uint32(0xa7b) << uint32(0x0); // 27
8232 data
<< uint32(0xa7a) << uint32(0x0); // 28
8233 data
<< uint32(0xa79) << uint32(0x0); // 29
8234 data
<< uint32(0x9d0) << uint32(0x5); // 30
8235 data
<< uint32(0x9ce) << uint32(0x0); // 31
8236 data
<< uint32(0x9cd) << uint32(0x0); // 32
8237 data
<< uint32(0x9cc) << uint32(0x0); // 33
8238 data
<< uint32(0xa88) << uint32(0x0); // 34
8239 data
<< uint32(0xad0) << uint32(0x0); // 35
8240 data
<< uint32(0xacf) << uint32(0x1); // 36
8242 case 3521: // Zangarmarsh
8243 data
<< uint32(0x9e1) << uint32(0x0); // 10
8244 data
<< uint32(0x9e0) << uint32(0x0); // 11
8245 data
<< uint32(0x9df) << uint32(0x0); // 12
8246 data
<< uint32(0xa5d) << uint32(0x1); // 13
8247 data
<< uint32(0xa5c) << uint32(0x0); // 14
8248 data
<< uint32(0xa5b) << uint32(0x1); // 15
8249 data
<< uint32(0xa5a) << uint32(0x0); // 16
8250 data
<< uint32(0xa59) << uint32(0x1); // 17
8251 data
<< uint32(0xa58) << uint32(0x0); // 18
8252 data
<< uint32(0xa57) << uint32(0x0); // 19
8253 data
<< uint32(0xa56) << uint32(0x0); // 20
8254 data
<< uint32(0xa55) << uint32(0x1); // 21
8255 data
<< uint32(0xa54) << uint32(0x0); // 22
8256 data
<< uint32(0x9e7) << uint32(0x0); // 23
8257 data
<< uint32(0x9e6) << uint32(0x0); // 24
8258 data
<< uint32(0x9e5) << uint32(0x0); // 25
8259 data
<< uint32(0xa00) << uint32(0x0); // 26
8260 data
<< uint32(0x9ff) << uint32(0x1); // 27
8261 data
<< uint32(0x9fe) << uint32(0x0); // 28
8262 data
<< uint32(0x9fd) << uint32(0x0); // 29
8263 data
<< uint32(0x9fc) << uint32(0x1); // 30
8264 data
<< uint32(0x9fb) << uint32(0x0); // 31
8265 data
<< uint32(0xa62) << uint32(0x0); // 32
8266 data
<< uint32(0xa61) << uint32(0x1); // 33
8267 data
<< uint32(0xa60) << uint32(0x1); // 34
8268 data
<< uint32(0xa5f) << uint32(0x0); // 35
8270 case 3698: // Nagrand Arena
8271 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_NA
)
8272 bg
->FillInitialWorldStates(data
);
8275 data
<< uint32(0xa0f) << uint32(0x0); // 7
8276 data
<< uint32(0xa10) << uint32(0x0); // 8
8277 data
<< uint32(0xa11) << uint32(0x0); // 9 show
8280 case 3702: // Blade's Edge Arena
8281 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_BE
)
8282 bg
->FillInitialWorldStates(data
);
8285 data
<< uint32(0x9f0) << uint32(0x0); // 7 gold
8286 data
<< uint32(0x9f1) << uint32(0x0); // 8 green
8287 data
<< uint32(0x9f3) << uint32(0x0); // 9 show
8290 case 3968: // Ruins of Lordaeron
8291 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_RL
)
8292 bg
->FillInitialWorldStates(data
);
8295 data
<< uint32(0xbb8) << uint32(0x0); // 7 gold
8296 data
<< uint32(0xbb9) << uint32(0x0); // 8 green
8297 data
<< uint32(0xbba) << uint32(0x0); // 9 show
8300 case 3703: // Shattrath City
8303 data
<< uint32(0x914) << uint32(0x0); // 7
8304 data
<< uint32(0x913) << uint32(0x0); // 8
8305 data
<< uint32(0x912) << uint32(0x0); // 9
8306 data
<< uint32(0x915) << uint32(0x0); // 10
8309 GetSession()->SendPacket(&data
);
8312 uint32
Player::GetXPRestBonus(uint32 xp
)
8314 uint32 rested_bonus
= (uint32
)GetRestBonus(); // xp for each rested bonus
8316 if(rested_bonus
> xp
) // max rested_bonus == xp or (r+x) = 200% xp
8319 SetRestBonus( GetRestBonus() - rested_bonus
);
8321 sLog
.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp
+rested_bonus
,rested_bonus
,GetRestBonus());
8322 return rested_bonus
;
8325 void Player::SetBindPoint(uint64 guid
)
8327 WorldPacket
data(SMSG_BINDER_CONFIRM
, 8);
8328 data
<< uint64(guid
);
8329 GetSession()->SendPacket( &data
);
8332 void Player::SendTalentWipeConfirm(uint64 guid
)
8334 WorldPacket
data(MSG_TALENT_WIPE_CONFIRM
, (8+4));
8335 data
<< uint64(guid
);
8336 data
<< uint32(resetTalentsCost());
8337 GetSession()->SendPacket( &data
);
8340 void Player::SendPetSkillWipeConfirm()
8342 Pet
* pet
= GetPet();
8345 WorldPacket
data(SMSG_PET_UNLEARN_CONFIRM
, (8+4));
8346 data
<< pet
->GetGUID();
8347 data
<< uint32(pet
->resetTalentsCost());
8348 GetSession()->SendPacket( &data
);
8351 /*********************************************************/
8352 /*** STORAGE SYSTEM ***/
8353 /*********************************************************/
8355 void Player::SetVirtualItemSlot( uint8 i
, Item
* item
)
8360 if(!item
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
))
8362 uint32 charges
= item
->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
);
8366 item
->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
,charges
-1);
8367 else if(charges
<= 1)
8369 ApplyEnchantment(item
,TEMP_ENCHANTMENT_SLOT
,false);
8370 item
->ClearEnchantment(TEMP_ENCHANTMENT_SLOT
);
8375 void Player::SetSheath( SheathState sheathed
)
8379 case SHEATH_STATE_UNARMED
: // no prepared weapon
8380 SetVirtualItemSlot(0,NULL
);
8381 SetVirtualItemSlot(1,NULL
);
8382 SetVirtualItemSlot(2,NULL
);
8384 case SHEATH_STATE_MELEE
: // prepared melee weapon
8386 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK
,true,true));
8387 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK
,true,true));
8388 SetVirtualItemSlot(2,NULL
);
8390 case SHEATH_STATE_RANGED
: // prepared ranged weapon
8391 SetVirtualItemSlot(0,NULL
);
8392 SetVirtualItemSlot(1,NULL
);
8393 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK
,true,true));
8396 SetVirtualItemSlot(0,NULL
);
8397 SetVirtualItemSlot(1,NULL
);
8398 SetVirtualItemSlot(2,NULL
);
8401 Unit::SetSheath(sheathed
); // this must visualize Sheath changing for other players...
8404 uint8
Player::FindEquipSlot( ItemPrototype
const* proto
, uint32 slot
, bool swap
) const
8406 uint8 pClass
= getClass();
8409 slots
[0] = NULL_SLOT
;
8410 slots
[1] = NULL_SLOT
;
8411 slots
[2] = NULL_SLOT
;
8412 slots
[3] = NULL_SLOT
;
8413 switch( proto
->InventoryType
)
8416 slots
[0] = EQUIPMENT_SLOT_HEAD
;
8419 slots
[0] = EQUIPMENT_SLOT_NECK
;
8421 case INVTYPE_SHOULDERS
:
8422 slots
[0] = EQUIPMENT_SLOT_SHOULDERS
;
8425 slots
[0] = EQUIPMENT_SLOT_BODY
;
8428 slots
[0] = EQUIPMENT_SLOT_CHEST
;
8431 slots
[0] = EQUIPMENT_SLOT_CHEST
;
8434 slots
[0] = EQUIPMENT_SLOT_WAIST
;
8437 slots
[0] = EQUIPMENT_SLOT_LEGS
;
8440 slots
[0] = EQUIPMENT_SLOT_FEET
;
8442 case INVTYPE_WRISTS
:
8443 slots
[0] = EQUIPMENT_SLOT_WRISTS
;
8446 slots
[0] = EQUIPMENT_SLOT_HANDS
;
8448 case INVTYPE_FINGER
:
8449 slots
[0] = EQUIPMENT_SLOT_FINGER1
;
8450 slots
[1] = EQUIPMENT_SLOT_FINGER2
;
8452 case INVTYPE_TRINKET
:
8453 slots
[0] = EQUIPMENT_SLOT_TRINKET1
;
8454 slots
[1] = EQUIPMENT_SLOT_TRINKET2
;
8457 slots
[0] = EQUIPMENT_SLOT_BACK
;
8459 case INVTYPE_WEAPON
:
8461 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8463 // suggest offhand slot only if know dual wielding
8464 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8466 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
8469 case INVTYPE_SHIELD
:
8470 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8472 case INVTYPE_RANGED
:
8473 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8475 case INVTYPE_2HWEAPON
:
8476 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8477 if (CanDualWield() && CanTitanGrip())
8478 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
8480 case INVTYPE_TABARD
:
8481 slots
[0] = EQUIPMENT_SLOT_TABARD
;
8483 case INVTYPE_WEAPONMAINHAND
:
8484 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8486 case INVTYPE_WEAPONOFFHAND
:
8487 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8489 case INVTYPE_HOLDABLE
:
8490 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8492 case INVTYPE_THROWN
:
8493 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8495 case INVTYPE_RANGEDRIGHT
:
8496 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8499 slots
[0] = INVENTORY_SLOT_BAG_START
+ 0;
8500 slots
[1] = INVENTORY_SLOT_BAG_START
+ 1;
8501 slots
[2] = INVENTORY_SLOT_BAG_START
+ 2;
8502 slots
[3] = INVENTORY_SLOT_BAG_START
+ 3;
8506 switch(proto
->SubClass
)
8508 case ITEM_SUBCLASS_ARMOR_LIBRAM
:
8509 if (pClass
== CLASS_PALADIN
)
8510 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8512 case ITEM_SUBCLASS_ARMOR_IDOL
:
8513 if (pClass
== CLASS_DRUID
)
8514 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8516 case ITEM_SUBCLASS_ARMOR_TOTEM
:
8517 if (pClass
== CLASS_SHAMAN
)
8518 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8520 case ITEM_SUBCLASS_ARMOR_MISC
:
8521 if (pClass
== CLASS_WARLOCK
)
8522 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8524 case ITEM_SUBCLASS_ARMOR_SIGIL
:
8525 if (pClass
== CLASS_DEATH_KNIGHT
)
8526 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8535 if( slot
!= NULL_SLOT
)
8537 if( swap
|| !GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
) )
8539 for (int i
= 0; i
< 4; ++i
)
8541 if ( slots
[i
] == slot
)
8548 // search free slot at first
8549 for (int i
= 0; i
< 4; ++i
)
8551 if ( slots
[i
] != NULL_SLOT
&& !GetItemByPos( INVENTORY_SLOT_BAG_0
, slots
[i
] ) )
8553 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8554 if(slots
[i
]!=EQUIPMENT_SLOT_OFFHAND
|| !IsTwoHandUsed())
8559 // if not found free and can swap return first appropriate from used
8560 for (int i
= 0; i
< 4; ++i
)
8562 if ( slots
[i
] != NULL_SLOT
&& swap
)
8571 uint8
Player::CanUnequipItems( uint32 item
, uint32 count
) const
8574 uint32 tempcount
= 0;
8576 uint8 res
= EQUIP_ERR_OK
;
8578 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8580 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8581 if( pItem
&& pItem
->GetEntry() == item
)
8583 uint8 ires
= CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false);
8584 if(ires
==EQUIP_ERR_OK
)
8586 tempcount
+= pItem
->GetCount();
8587 if( tempcount
>= count
)
8588 return EQUIP_ERR_OK
;
8594 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8596 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8597 if( pItem
&& pItem
->GetEntry() == item
)
8599 tempcount
+= pItem
->GetCount();
8600 if( tempcount
>= count
)
8601 return EQUIP_ERR_OK
;
8604 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8606 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8607 if( pItem
&& pItem
->GetEntry() == item
)
8609 tempcount
+= pItem
->GetCount();
8610 if( tempcount
>= count
)
8611 return EQUIP_ERR_OK
;
8615 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8617 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8620 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8622 pItem
= GetItemByPos( i
, j
);
8623 if( pItem
&& pItem
->GetEntry() == item
)
8625 tempcount
+= pItem
->GetCount();
8626 if( tempcount
>= count
)
8627 return EQUIP_ERR_OK
;
8633 // not found req. item count and have unequippable items
8637 uint32
Player::GetItemCount( uint32 item
, bool inBankAlso
, Item
* skipItem
) const
8640 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8642 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8643 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8644 count
+= pItem
->GetCount();
8646 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8648 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8649 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8650 count
+= pItem
->GetCount();
8652 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8654 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8656 count
+= pBag
->GetItemCount(item
,skipItem
);
8659 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8661 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8663 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8664 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8665 count
+= pItem
->GetGemCountWithID(item
);
8671 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
8673 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8674 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8675 count
+= pItem
->GetCount();
8677 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
8679 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8681 count
+= pBag
->GetItemCount(item
,skipItem
);
8684 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8686 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
8688 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8689 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8690 count
+= pItem
->GetGemCountWithID(item
);
8698 uint32
Player::GetItemCountWithLimitCategory( uint32 limitCategory
) const
8701 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8702 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8703 if (pItem
->GetProto()->ItemLimitCategory
== limitCategory
)
8704 count
+= pItem
->GetCount();
8706 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8707 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8708 if (pItem
->GetProto()->ItemLimitCategory
== limitCategory
)
8709 count
+= pItem
->GetCount();
8711 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8712 if (Bag
* pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8713 count
+= pBag
->GetItemCountWithLimitCategory(limitCategory
);
8715 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
8716 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8717 if (pItem
->GetProto()->ItemLimitCategory
== limitCategory
)
8718 count
+= pItem
->GetCount();
8720 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
8721 if (Bag
* pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8722 count
+= pBag
->GetItemCountWithLimitCategory(limitCategory
);
8727 Item
* Player::GetItemByEntry( uint32 item
) const
8729 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8730 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8731 if (pItem
->GetEntry() == item
)
8734 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8735 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8736 if (pItem
->GetEntry() == item
)
8739 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8740 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8741 if (Item
* itemPtr
= pBag
->GetItemByEntry(item
))
8747 Item
* Player::GetItemByLimitedCategory(uint32 limitedCategory
) const
8749 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8750 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8751 if (pItem
->GetProto()->ItemLimitCategory
== limitedCategory
)
8754 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8755 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8756 if (pItem
->GetProto()->ItemLimitCategory
== limitedCategory
)
8759 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8760 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8761 if (Item
* itemPtr
= pBag
->GetItemByLimitedCategory(limitedCategory
))
8767 Item
* Player::GetItemByGuid(ObjectGuid guid
) const
8769 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8770 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8771 if (pItem
->GetObjectGuid() == guid
)
8774 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8775 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8776 if (pItem
->GetObjectGuid() == guid
)
8779 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8780 if (Bag
*pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8781 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8782 if (Item
* pItem
= pBag
->GetItemByPos(j
))
8783 if (pItem
->GetObjectGuid() == guid
)
8786 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
8787 if (Bag
*pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8788 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8789 if (Item
* pItem
= pBag
->GetItemByPos(j
))
8790 if (pItem
->GetObjectGuid() == guid
)
8796 Item
* Player::GetItemByPos( uint16 pos
) const
8798 uint8 bag
= pos
>> 8;
8799 uint8 slot
= pos
& 255;
8800 return GetItemByPos( bag
, slot
);
8803 Item
* Player::GetItemByPos( uint8 bag
, uint8 slot
) const
8805 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< BANK_SLOT_BAG_END
|| (slot
>= KEYRING_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)) )
8806 return m_items
[slot
];
8807 else if ((bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8808 || (bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
) )
8810 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8812 return pBag
->GetItemByPos(slot
);
8817 Item
* Player::GetWeaponForAttack(WeaponAttackType attackType
, bool nonbroken
, bool useable
) const
8822 case BASE_ATTACK
: slot
= EQUIPMENT_SLOT_MAINHAND
; break;
8823 case OFF_ATTACK
: slot
= EQUIPMENT_SLOT_OFFHAND
; break;
8824 case RANGED_ATTACK
: slot
= EQUIPMENT_SLOT_RANGED
; break;
8825 default: return NULL
;
8828 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, slot
);
8829 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_WEAPON
)
8832 if (useable
&& !IsUseEquipedWeapon(attackType
==BASE_ATTACK
))
8835 if (nonbroken
&& item
->IsBroken())
8841 Item
* Player::GetShield(bool useable
) const
8843 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
8844 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_ARMOR
)
8850 if( item
->IsBroken())
8856 uint32
Player::GetAttackBySlot( uint8 slot
)
8860 case EQUIPMENT_SLOT_MAINHAND
: return BASE_ATTACK
;
8861 case EQUIPMENT_SLOT_OFFHAND
: return OFF_ATTACK
;
8862 case EQUIPMENT_SLOT_RANGED
: return RANGED_ATTACK
;
8863 default: return MAX_ATTACK
;
8867 bool Player::IsInventoryPos( uint8 bag
, uint8 slot
)
8869 if( bag
== INVENTORY_SLOT_BAG_0
&& slot
== NULL_SLOT
)
8871 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
) )
8873 if( bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8875 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= KEYRING_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
) )
8880 bool Player::IsEquipmentPos( uint8 bag
, uint8 slot
)
8882 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< EQUIPMENT_SLOT_END
) )
8884 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8889 bool Player::IsBankPos( uint8 bag
, uint8 slot
)
8891 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
) )
8893 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8895 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8900 bool Player::IsBagPos( uint16 pos
)
8902 uint8 bag
= pos
>> 8;
8903 uint8 slot
= pos
& 255;
8904 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8906 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8911 bool Player::IsValidPos( uint8 bag
, uint8 slot
, bool explicit_pos
) const
8914 if(bag
== NULL_BAG
&& !explicit_pos
)
8917 if (bag
== INVENTORY_SLOT_BAG_0
)
8919 // any post selected
8920 if (slot
== NULL_SLOT
&& !explicit_pos
)
8924 if (slot
< EQUIPMENT_SLOT_END
)
8928 if (slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
)
8932 if (slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
)
8936 if (slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_END
)
8940 if (slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
)
8944 if (slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
8950 // bag content slots
8951 if (bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8953 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8957 // any post selected
8958 if (slot
== NULL_SLOT
&& !explicit_pos
)
8961 return slot
< pBag
->GetBagSize();
8964 // bank bag content slots
8965 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8967 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8971 // any post selected
8972 if (slot
== NULL_SLOT
&& !explicit_pos
)
8975 return slot
< pBag
->GetBagSize();
8983 bool Player::HasItemCount( uint32 item
, uint32 count
, bool inBankAlso
) const
8985 uint32 tempcount
= 0;
8986 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8988 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8989 if( pItem
&& pItem
->GetEntry() == item
)
8991 tempcount
+= pItem
->GetCount();
8992 if( tempcount
>= count
)
8996 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8998 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8999 if( pItem
&& pItem
->GetEntry() == item
)
9001 tempcount
+= pItem
->GetCount();
9002 if( tempcount
>= count
)
9006 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9008 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
9010 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9012 Item
* pItem
= GetItemByPos( i
, j
);
9013 if( pItem
&& pItem
->GetEntry() == item
)
9015 tempcount
+= pItem
->GetCount();
9016 if( tempcount
>= count
)
9025 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
9027 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9028 if( pItem
&& pItem
->GetEntry() == item
)
9030 tempcount
+= pItem
->GetCount();
9031 if( tempcount
>= count
)
9035 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
9037 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
9039 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9041 Item
* pItem
= GetItemByPos( i
, j
);
9042 if( pItem
&& pItem
->GetEntry() == item
)
9044 tempcount
+= pItem
->GetCount();
9045 if( tempcount
>= count
)
9056 bool Player::HasItemOrGemWithIdEquipped( uint32 item
, uint32 count
, uint8 except_slot
) const
9058 uint32 tempcount
= 0;
9059 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
9061 if(i
==int(except_slot
))
9064 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9065 if( pItem
&& pItem
->GetEntry() == item
)
9067 tempcount
+= pItem
->GetCount();
9068 if( tempcount
>= count
)
9073 ItemPrototype
const *pProto
= ObjectMgr::GetItemPrototype(item
);
9074 if (pProto
&& pProto
->GemProperties
)
9076 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
9078 if(i
==int(except_slot
))
9081 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9082 if( pItem
&& pItem
->GetProto()->Socket
[0].Color
)
9084 tempcount
+= pItem
->GetGemCountWithID(item
);
9085 if( tempcount
>= count
)
9094 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory
, uint32 count
, uint8 except_slot
) const
9096 uint32 tempcount
= 0;
9097 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
9099 if(i
==int(except_slot
))
9102 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9106 ItemPrototype
const *pProto
= pItem
->GetProto();
9110 if (pProto
->ItemLimitCategory
== limitCategory
)
9112 tempcount
+= pItem
->GetCount();
9113 if( tempcount
>= count
)
9117 if( pProto
->Socket
[0].Color
)
9119 tempcount
+= pItem
->GetGemCountWithLimitCategory(limitCategory
);
9120 if( tempcount
>= count
)
9128 uint8
Player::_CanTakeMoreSimilarItems(uint32 entry
, uint32 count
, Item
* pItem
, uint32
* no_space_count
) const
9130 ItemPrototype
const *pProto
= ObjectMgr::GetItemPrototype(entry
);
9134 *no_space_count
= count
;
9135 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9139 if(pProto
->MaxCount
> 0)
9141 uint32 curcount
= GetItemCount(pProto
->ItemId
,true,pItem
);
9143 if (curcount
+ count
> uint32(pProto
->MaxCount
))
9146 *no_space_count
= count
+curcount
- pProto
->MaxCount
;
9147 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9151 // check unique-equipped limit
9152 if (pProto
->ItemLimitCategory
)
9154 ItemLimitCategoryEntry
const* limitEntry
= sItemLimitCategoryStore
.LookupEntry(pProto
->ItemLimitCategory
);
9158 *no_space_count
= count
;
9159 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9162 if (limitEntry
->mode
== ITEM_LIMIT_CATEGORY_MODE_HAVE
)
9164 uint32 curcount
= GetItemCountWithLimitCategory(pProto
->ItemLimitCategory
);
9166 if (curcount
+ count
> uint32(limitEntry
->maxCount
))
9169 *no_space_count
= count
+ curcount
- limitEntry
->maxCount
;
9170 return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS
;
9175 return EQUIP_ERR_OK
;
9178 bool Player::HasItemTotemCategory( uint32 TotemCategory
) const
9181 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
9183 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9184 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
9187 for(uint8 i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
9189 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9190 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
9193 for(uint8 i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9195 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
9197 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9199 pItem
= GetItemByPos( i
, j
);
9200 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
9208 uint8
Player::_CanStoreItem_InSpecificSlot( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, ItemPrototype
const *pProto
, uint32
& count
, bool swap
, Item
* pSrcItem
) const
9210 Item
* pItem2
= GetItemByPos( bag
, slot
);
9212 // ignore move item (this slot will be empty at move)
9213 if (pItem2
==pSrcItem
)
9218 // empty specific slot - check item fit to slot
9219 if (!pItem2
|| swap
)
9221 if (bag
== INVENTORY_SLOT_BAG_0
)
9224 if (slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_START
+GetMaxKeyringSize() && !(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
))
9225 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9227 // currencytoken case
9228 if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
&& !(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
))
9229 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9232 if (slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
|| slot
>= PLAYER_SLOT_END
)
9233 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9237 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
9239 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9241 ItemPrototype
const* pBagProto
= pBag
->GetProto();
9243 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9245 if (slot
>= pBagProto
->ContainerSlots
)
9246 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9248 if (!ItemCanGoIntoBag(pProto
,pBagProto
))
9249 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9252 // non empty stack with space
9253 need_space
= pProto
->GetMaxStackSize();
9255 // non empty slot, check item type
9258 // can be merged at least partly
9259 uint8 res
= pItem2
->CanBeMergedPartlyWith(pProto
);
9260 if (res
!= EQUIP_ERR_OK
)
9263 // free stack space or infinity
9264 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
9267 if (need_space
> count
)
9270 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | slot
, need_space
);
9271 if (!newPosition
.isContainedIn(dest
))
9273 dest
.push_back(newPosition
);
9274 count
-= need_space
;
9276 return EQUIP_ERR_OK
;
9279 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
9281 // skip specific bag already processed in first called _CanStoreItem_InBag
9283 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9285 // skip not existed bag or self targeted bag
9286 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
9287 if (!pBag
|| pBag
==pSrcItem
)
9288 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9290 ItemPrototype
const* pBagProto
= pBag
->GetProto();
9292 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9294 // specialized bag mode or non-specilized
9295 if (non_specialized
!= (pBagProto
->Class
== ITEM_CLASS_CONTAINER
&& pBagProto
->SubClass
== ITEM_SUBCLASS_CONTAINER
))
9296 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9298 if (!ItemCanGoIntoBag(pProto
,pBagProto
))
9299 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9301 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9303 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9307 Item
* pItem2
= GetItemByPos( bag
, j
);
9309 // ignore move item (this slot will be empty at move)
9310 if (pItem2
== pSrcItem
)
9313 // if merge skip empty, if !merge skip non-empty
9314 if ((pItem2
!= NULL
) != merge
)
9317 uint32 need_space
= pProto
->GetMaxStackSize();
9321 // can be merged at least partly
9322 uint8 res
= pItem2
->CanBeMergedPartlyWith(pProto
);
9323 if (res
!= EQUIP_ERR_OK
)
9326 // descrease at current stacksize
9327 need_space
-= pItem2
->GetCount();
9330 if (need_space
> count
)
9333 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
9334 if (!newPosition
.isContainedIn(dest
))
9336 dest
.push_back(newPosition
);
9337 count
-= need_space
;
9340 return EQUIP_ERR_OK
;
9343 return EQUIP_ERR_OK
;
9346 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
9348 for(uint32 j
= slot_begin
; j
< slot_end
; ++j
)
9350 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9351 if (INVENTORY_SLOT_BAG_0
==skip_bag
&& j
==skip_slot
)
9354 Item
* pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, j
);
9356 // ignore move item (this slot will be empty at move)
9357 if (pItem2
==pSrcItem
)
9360 // if merge skip empty, if !merge skip non-empty
9361 if ((pItem2
!= NULL
) != merge
)
9364 uint32 need_space
= pProto
->GetMaxStackSize();
9368 // can be merged at least partly
9369 uint8 res
= pItem2
->CanBeMergedPartlyWith(pProto
);
9370 if (res
!= EQUIP_ERR_OK
)
9373 // descrease at current stacksize
9374 need_space
-= pItem2
->GetCount();
9377 if (need_space
> count
)
9380 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
9381 if (!newPosition
.isContainedIn(dest
))
9383 dest
.push_back(newPosition
);
9384 count
-= need_space
;
9387 return EQUIP_ERR_OK
;
9390 return EQUIP_ERR_OK
;
9393 uint8
Player::_CanStoreItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, uint32 entry
, uint32 count
, Item
*pItem
, bool swap
, uint32
* no_space_count
) const
9395 sLog
.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, entry
, count
);
9397 ItemPrototype
const *pProto
= ObjectMgr::GetItemPrototype(entry
);
9401 *no_space_count
= count
;
9402 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
:EQUIP_ERR_ITEM_NOT_FOUND
;
9408 if(pItem
->m_lootGenerated
)
9411 *no_space_count
= count
;
9412 return EQUIP_ERR_ALREADY_LOOTED
;
9415 if (pItem
->IsBindedNotWith(this))
9418 *no_space_count
= count
;
9419 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9423 // check count of items (skip for auto move for same player from bank)
9424 uint32 no_similar_count
= 0; // can't store this amount similar items
9425 uint8 res
= _CanTakeMoreSimilarItems(entry
,count
,pItem
,&no_similar_count
);
9426 if (res
!=EQUIP_ERR_OK
)
9428 if (count
==no_similar_count
)
9431 *no_space_count
= no_similar_count
;
9434 count
-= no_similar_count
;
9438 if (bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
9440 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
9441 if (res
!=EQUIP_ERR_OK
)
9444 *no_space_count
= count
+ no_similar_count
;
9450 if (no_similar_count
==0)
9451 return EQUIP_ERR_OK
;
9454 *no_space_count
= count
+ no_similar_count
;
9455 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9459 // not specific slot or have space for partly store only in specific slot
9462 if (bag
!= NULL_BAG
)
9464 // search stack in bag for merge to
9465 if (pProto
->Stackable
!= 1)
9467 if (bag
== INVENTORY_SLOT_BAG_0
) // inventory
9469 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9470 if (res
!=EQUIP_ERR_OK
)
9473 *no_space_count
= count
+ no_similar_count
;
9479 if (no_similar_count
==0)
9480 return EQUIP_ERR_OK
;
9483 *no_space_count
= count
+ no_similar_count
;
9484 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9487 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9488 if (res
!=EQUIP_ERR_OK
)
9491 *no_space_count
= count
+ no_similar_count
;
9497 if (no_similar_count
==0)
9498 return EQUIP_ERR_OK
;
9501 *no_space_count
= count
+ no_similar_count
;
9502 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9505 else // equipped bag
9507 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9508 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
9509 if (res
!=EQUIP_ERR_OK
)
9510 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
9512 if (res
!=EQUIP_ERR_OK
)
9515 *no_space_count
= count
+ no_similar_count
;
9521 if (no_similar_count
==0)
9522 return EQUIP_ERR_OK
;
9525 *no_space_count
= count
+ no_similar_count
;
9526 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9531 // search free slot in bag for place to
9532 if(bag
== INVENTORY_SLOT_BAG_0
) // inventory
9534 // search free slot - keyring case
9535 if (pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9537 uint32 keyringSize
= GetMaxKeyringSize();
9538 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9539 if (res
!=EQUIP_ERR_OK
)
9542 *no_space_count
= count
+ no_similar_count
;
9548 if (no_similar_count
==0)
9549 return EQUIP_ERR_OK
;
9552 *no_space_count
= count
+ no_similar_count
;
9553 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9556 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9557 if (res
!=EQUIP_ERR_OK
)
9560 *no_space_count
= count
+ no_similar_count
;
9566 if (no_similar_count
==0)
9567 return EQUIP_ERR_OK
;
9570 *no_space_count
= count
+ no_similar_count
;
9571 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9574 else if (pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9576 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9577 if (res
!=EQUIP_ERR_OK
)
9580 *no_space_count
= count
+ no_similar_count
;
9586 if (no_similar_count
==0)
9587 return EQUIP_ERR_OK
;
9590 *no_space_count
= count
+ no_similar_count
;
9591 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9595 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9596 if (res
!=EQUIP_ERR_OK
)
9599 *no_space_count
= count
+ no_similar_count
;
9605 if (no_similar_count
==0)
9606 return EQUIP_ERR_OK
;
9609 *no_space_count
= count
+ no_similar_count
;
9610 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9613 else // equipped bag
9615 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9616 if (res
!=EQUIP_ERR_OK
)
9617 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9619 if (res
!=EQUIP_ERR_OK
)
9622 *no_space_count
= count
+ no_similar_count
;
9628 if (no_similar_count
==0)
9629 return EQUIP_ERR_OK
;
9632 *no_space_count
= count
+ no_similar_count
;
9633 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9638 // not specific bag or have space for partly store only in specific bag
9640 // search stack for merge to
9641 if (pProto
->Stackable
!= 1)
9643 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9644 if (res
!=EQUIP_ERR_OK
)
9647 *no_space_count
= count
+ no_similar_count
;
9653 if (no_similar_count
==0)
9654 return EQUIP_ERR_OK
;
9657 *no_space_count
= count
+ no_similar_count
;
9658 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9661 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9662 if (res
!=EQUIP_ERR_OK
)
9665 *no_space_count
= count
+ no_similar_count
;
9671 if (no_similar_count
==0)
9672 return EQUIP_ERR_OK
;
9675 *no_space_count
= count
+ no_similar_count
;
9676 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9679 if (pProto
->BagFamily
)
9681 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9683 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9684 if (res
!=EQUIP_ERR_OK
)
9689 if (no_similar_count
==0)
9690 return EQUIP_ERR_OK
;
9693 *no_space_count
= count
+ no_similar_count
;
9694 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9699 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9701 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9702 if (res
!=EQUIP_ERR_OK
)
9707 if (no_similar_count
==0)
9708 return EQUIP_ERR_OK
;
9711 *no_space_count
= count
+ no_similar_count
;
9712 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9717 // search free slot - special bag case
9718 if (pProto
->BagFamily
)
9720 if (pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9722 uint32 keyringSize
= GetMaxKeyringSize();
9723 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9724 if (res
!=EQUIP_ERR_OK
)
9727 *no_space_count
= count
+ no_similar_count
;
9733 if (no_similar_count
==0)
9734 return EQUIP_ERR_OK
;
9737 *no_space_count
= count
+ no_similar_count
;
9738 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9741 else if (pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9743 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9744 if (res
!=EQUIP_ERR_OK
)
9747 *no_space_count
= count
+ no_similar_count
;
9753 if (no_similar_count
==0)
9754 return EQUIP_ERR_OK
;
9757 *no_space_count
= count
+ no_similar_count
;
9758 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9762 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9764 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9765 if (res
!=EQUIP_ERR_OK
)
9770 if (no_similar_count
==0)
9771 return EQUIP_ERR_OK
;
9774 *no_space_count
= count
+ no_similar_count
;
9775 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9781 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9782 if (res
!=EQUIP_ERR_OK
)
9785 *no_space_count
= count
+ no_similar_count
;
9791 if (no_similar_count
==0)
9792 return EQUIP_ERR_OK
;
9795 *no_space_count
= count
+ no_similar_count
;
9796 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9799 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9801 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9802 if (res
!=EQUIP_ERR_OK
)
9807 if (no_similar_count
==0)
9808 return EQUIP_ERR_OK
;
9811 *no_space_count
= count
+ no_similar_count
;
9812 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9817 *no_space_count
= count
+ no_similar_count
;
9819 return EQUIP_ERR_INVENTORY_FULL
;
9822 //////////////////////////////////////////////////////////////////////////
9823 uint8
Player::CanStoreItems( Item
**pItems
,int count
) const
9828 int inv_slot_items
[INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
];
9829 int inv_bags
[INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
][MAX_BAG_SIZE
];
9830 int inv_keys
[KEYRING_SLOT_END
-KEYRING_SLOT_START
];
9831 int inv_tokens
[CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
];
9833 memset(inv_slot_items
,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
));
9834 memset(inv_bags
,0,sizeof(int)*(INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
)*MAX_BAG_SIZE
);
9835 memset(inv_keys
,0,sizeof(int)*(KEYRING_SLOT_END
-KEYRING_SLOT_START
));
9836 memset(inv_tokens
,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
));
9838 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
9840 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9842 if (pItem2
&& !pItem2
->IsInTrade())
9844 inv_slot_items
[i
-INVENTORY_SLOT_ITEM_START
] = pItem2
->GetCount();
9848 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; ++i
)
9850 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9852 if (pItem2
&& !pItem2
->IsInTrade())
9854 inv_keys
[i
-KEYRING_SLOT_START
] = pItem2
->GetCount();
9858 for(int i
= CURRENCYTOKEN_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
9860 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9862 if (pItem2
&& !pItem2
->IsInTrade())
9864 inv_tokens
[i
-CURRENCYTOKEN_SLOT_START
] = pItem2
->GetCount();
9868 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9870 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
9872 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9874 pItem2
= GetItemByPos( i
, j
);
9875 if (pItem2
&& !pItem2
->IsInTrade())
9877 inv_bags
[i
-INVENTORY_SLOT_BAG_START
][j
] = pItem2
->GetCount();
9883 // check free space for all items
9884 for (int k
= 0; k
< count
; ++k
)
9886 Item
*pItem
= pItems
[k
];
9889 if (!pItem
) continue;
9891 sLog
.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k
+1, pItem
->GetEntry(), pItem
->GetCount());
9892 ItemPrototype
const *pProto
= pItem
->GetProto();
9896 return EQUIP_ERR_ITEM_NOT_FOUND
;
9899 if(pItem
->m_lootGenerated
)
9900 return EQUIP_ERR_ALREADY_LOOTED
;
9903 if(pItem
->IsBindedNotWith(this))
9904 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9907 ItemPrototype
const *pBagProto
;
9909 // item is 'one item only'
9910 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9911 if(res
!= EQUIP_ERR_OK
)
9914 // search stack for merge to
9915 if( pProto
->Stackable
!= 1 )
9917 bool b_found
= false;
9919 for(int t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_END
; ++t
)
9921 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9922 if( pItem2
&& pItem2
->CanBeMergedPartlyWith(pProto
) == EQUIP_ERR_OK
&& inv_keys
[t
-KEYRING_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9924 inv_keys
[t
-KEYRING_SLOT_START
] += pItem
->GetCount();
9929 if (b_found
) continue;
9931 for(int t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; ++t
)
9933 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9934 if( pItem2
&& pItem2
->CanBeMergedPartlyWith(pProto
) == EQUIP_ERR_OK
&& inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9936 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] += pItem
->GetCount();
9941 if (b_found
) continue;
9943 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; ++t
)
9945 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9946 if( pItem2
&& pItem2
->CanBeMergedPartlyWith(pProto
) == EQUIP_ERR_OK
&& inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9948 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] += pItem
->GetCount();
9953 if (b_found
) continue;
9955 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; ++t
)
9957 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9960 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9962 pItem2
= GetItemByPos( t
, j
);
9963 if( pItem2
&& pItem2
->CanBeMergedPartlyWith(pProto
) == EQUIP_ERR_OK
&& inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9965 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] += pItem
->GetCount();
9972 if (b_found
) continue;
9976 if( pProto
->BagFamily
)
9978 bool b_found
= false;
9979 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9981 uint32 keyringSize
= GetMaxKeyringSize();
9982 for(uint32 t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_START
+keyringSize
; ++t
)
9984 if( inv_keys
[t
-KEYRING_SLOT_START
] == 0 )
9986 inv_keys
[t
-KEYRING_SLOT_START
] = 1;
9993 if (b_found
) continue;
9995 if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9997 for(uint32 t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; ++t
)
9999 if( inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] == 0 )
10001 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] = 1;
10008 if (b_found
) continue;
10010 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; ++t
)
10012 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
10015 pBagProto
= pBag
->GetProto();
10017 // not plain container check
10018 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
) &&
10019 ItemCanGoIntoBag(pProto
,pBagProto
) )
10021 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
10023 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
10025 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
10033 if (b_found
) continue;
10036 // search free slot
10037 bool b_found
= false;
10038 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; ++t
)
10040 if( inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] == 0 )
10042 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] = 1;
10047 if (b_found
) continue;
10049 // search free slot in bags
10050 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; ++t
)
10052 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
10055 pBagProto
= pBag
->GetProto();
10057 // special bag already checked
10058 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
))
10061 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
10063 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
10065 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
10073 // no free slot found?
10075 return EQUIP_ERR_INVENTORY_FULL
;
10078 return EQUIP_ERR_OK
;
10081 //////////////////////////////////////////////////////////////////////////
10082 uint8
Player::CanEquipNewItem( uint8 slot
, uint16
&dest
, uint32 item
, bool swap
) const
10085 Item
*pItem
= Item::CreateItem( item
, 1, this );
10088 uint8 result
= CanEquipItem(slot
, dest
, pItem
, swap
);
10093 return EQUIP_ERR_ITEM_NOT_FOUND
;
10096 uint8
Player::CanEquipItem( uint8 slot
, uint16
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
10101 sLog
.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot
, pItem
->GetEntry(), pItem
->GetCount());
10102 ItemPrototype
const *pProto
= pItem
->GetProto();
10106 if(pItem
->m_lootGenerated
)
10107 return EQUIP_ERR_ALREADY_LOOTED
;
10109 if(pItem
->IsBindedNotWith(this))
10110 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10112 // check count of items (skip for auto move for same player from bank)
10113 uint8 res
= CanTakeMoreSimilarItems(pItem
);
10114 if(res
!= EQUIP_ERR_OK
)
10117 // check this only in game
10120 // May be here should be more stronger checks; STUNNED checked
10121 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
10122 if (hasUnitState(UNIT_STAT_STUNNED
))
10123 return EQUIP_ERR_YOU_ARE_STUNNED
;
10125 // do not allow equipping gear except weapons, offhands, projectiles, relics in
10127 // - in-progress arenas
10128 if( !pProto
->CanChangeEquipStateInCombat() )
10131 return EQUIP_ERR_NOT_IN_COMBAT
;
10133 if(BattleGround
* bg
= GetBattleGround())
10134 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
10135 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
10138 if(isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
!= 0)
10139 return EQUIP_ERR_CANT_DO_RIGHT_NOW
; // maybe exist better err
10141 if(IsNonMeleeSpellCasted(false))
10142 return EQUIP_ERR_CANT_DO_RIGHT_NOW
;
10145 ScalingStatDistributionEntry
const *ssd
= pProto
->ScalingStatDistribution
? sScalingStatDistributionStore
.LookupEntry(pProto
->ScalingStatDistribution
) : 0;
10146 // 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)
10147 if (ssd
&& ssd
->MaxLevel
< DEFAULT_MAX_LEVEL
&& ssd
->MaxLevel
< getLevel())
10148 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
10150 uint8 eslot
= FindEquipSlot( pProto
, slot
, swap
);
10151 if (eslot
== NULL_SLOT
)
10152 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
10154 uint8 msg
= CanUseItem(pItem
, not_loading
);
10155 if (msg
!= EQUIP_ERR_OK
)
10157 if (!swap
&& GetItemByPos(INVENTORY_SLOT_BAG_0
, eslot
))
10158 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE
;
10160 // if swap ignore item (equipped also)
10161 if (uint8 res2
= CanEquipUniqueItem(pItem
, swap
? eslot
: NULL_SLOT
))
10164 // check unique-equipped special item classes
10165 if (pProto
->Class
== ITEM_CLASS_QUIVER
)
10167 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10169 if (Item
* pBag
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
10173 if (ItemPrototype
const* pBagProto
= pBag
->GetProto())
10175 if (pBagProto
->Class
==pProto
->Class
&& (!swap
|| pBag
->GetSlot() != eslot
))
10176 return (pBagProto
->SubClass
== ITEM_SUBCLASS_AMMO_POUCH
)
10177 ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
10178 : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER
;
10185 uint32 type
= pProto
->InventoryType
;
10187 if (eslot
== EQUIPMENT_SLOT_OFFHAND
)
10189 if (type
== INVTYPE_WEAPON
|| type
== INVTYPE_WEAPONOFFHAND
)
10191 if (!CanDualWield())
10192 return EQUIP_ERR_CANT_DUAL_WIELD
;
10194 else if (type
== INVTYPE_2HWEAPON
)
10196 if (!CanDualWield() || !CanTitanGrip())
10197 return EQUIP_ERR_CANT_DUAL_WIELD
;
10200 if (IsTwoHandUsed())
10201 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED
;
10204 // equip two-hand weapon case (with possible unequip 2 items)
10205 if (type
== INVTYPE_2HWEAPON
)
10207 if (eslot
== EQUIPMENT_SLOT_OFFHAND
)
10209 if (!CanTitanGrip())
10210 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
10212 else if (eslot
!= EQUIPMENT_SLOT_MAINHAND
)
10213 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
10215 if (!CanTitanGrip())
10217 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
10218 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
10219 ItemPosCountVec off_dest
;
10220 if (offItem
&& (!not_loading
||
10221 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0
) << 8 | EQUIPMENT_SLOT_OFFHAND
,false) != EQUIP_ERR_OK
||
10222 CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false ) != EQUIP_ERR_OK
))
10223 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_INVENTORY_FULL
;
10226 dest
= ((INVENTORY_SLOT_BAG_0
<< 8) | eslot
);
10227 return EQUIP_ERR_OK
;
10231 return !swap
? EQUIP_ERR_ITEM_NOT_FOUND
: EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
;
10234 uint8
Player::CanUnequipItem( uint16 pos
, bool swap
) const
10236 // Applied only to equipped items and bank bags
10237 if(!IsEquipmentPos(pos
) && !IsBagPos(pos
))
10238 return EQUIP_ERR_OK
;
10240 Item
* pItem
= GetItemByPos(pos
);
10242 // Applied only to existed equipped item
10244 return EQUIP_ERR_OK
;
10246 sLog
.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos
, pItem
->GetEntry(), pItem
->GetCount());
10248 ItemPrototype
const *pProto
= pItem
->GetProto();
10250 return EQUIP_ERR_ITEM_NOT_FOUND
;
10253 if(pItem
->m_lootGenerated
)
10254 return EQUIP_ERR_ALREADY_LOOTED
;
10256 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
10258 // - in-progress arenas
10259 if( !pProto
->CanChangeEquipStateInCombat() )
10262 return EQUIP_ERR_NOT_IN_COMBAT
;
10264 if(BattleGround
* bg
= GetBattleGround())
10265 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
10266 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
10269 if(!swap
&& pItem
->IsBag() && !((Bag
*)pItem
)->IsEmpty())
10270 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS
;
10272 return EQUIP_ERR_OK
;
10275 uint8
Player::CanBankItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
10278 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
10280 uint32 count
= pItem
->GetCount();
10282 sLog
.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), pItem
->GetCount());
10283 ItemPrototype
const *pProto
= pItem
->GetProto();
10285 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
10288 if(pItem
->m_lootGenerated
)
10289 return EQUIP_ERR_ALREADY_LOOTED
;
10291 if (pItem
->IsBindedNotWith(this))
10292 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10294 // check count of items (skip for auto move for same player from bank)
10295 uint8 res
= CanTakeMoreSimilarItems(pItem
);
10296 if (res
!= EQUIP_ERR_OK
)
10299 // in specific slot
10300 if (bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
10302 if (slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
10304 if (!pItem
->IsBag())
10305 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
;
10307 if (slot
- BANK_SLOT_BAG_START
>= GetBankBagSlotCount())
10308 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT
;
10310 if (uint8 cantuse
= CanUseItem( pItem
, not_loading
) != EQUIP_ERR_OK
)
10314 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
10315 if (res
!=EQUIP_ERR_OK
)
10319 return EQUIP_ERR_OK
;
10322 // not specific slot or have space for partly store only in specific slot
10325 if( bag
!= NULL_BAG
)
10327 if( pProto
->InventoryType
== INVTYPE_BAG
)
10329 Bag
*pBag
= (Bag
*)pItem
;
10330 if( pBag
&& !pBag
->IsEmpty() )
10331 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
10334 // search stack in bag for merge to
10335 if( pProto
->Stackable
!= 1 )
10337 if( bag
== INVENTORY_SLOT_BAG_0
)
10339 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
10340 if(res
!=EQUIP_ERR_OK
)
10344 return EQUIP_ERR_OK
;
10348 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
10349 if(res
!=EQUIP_ERR_OK
)
10350 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
10352 if(res
!=EQUIP_ERR_OK
)
10356 return EQUIP_ERR_OK
;
10360 // search free slot in bag
10361 if( bag
== INVENTORY_SLOT_BAG_0
)
10363 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
10364 if(res
!=EQUIP_ERR_OK
)
10368 return EQUIP_ERR_OK
;
10372 res
= _CanStoreItem_InBag(bag
, dest
, pProto
, count
, false, false, pItem
, NULL_BAG
, slot
);
10373 if(res
!= EQUIP_ERR_OK
)
10374 res
= _CanStoreItem_InBag(bag
, dest
, pProto
, count
, false, true, pItem
, NULL_BAG
, slot
);
10376 if(res
!= EQUIP_ERR_OK
)
10380 return EQUIP_ERR_OK
;
10384 // not specific bag or have space for partly store only in specific bag
10386 // search stack for merge to
10387 if( pProto
->Stackable
!= 1 )
10390 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
10391 if(res
!= EQUIP_ERR_OK
)
10395 return EQUIP_ERR_OK
;
10398 if( pProto
->BagFamily
)
10400 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
10402 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
10403 if(res
!=EQUIP_ERR_OK
)
10407 return EQUIP_ERR_OK
;
10411 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
10413 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
10414 if(res
!=EQUIP_ERR_OK
)
10418 return EQUIP_ERR_OK
;
10422 // search free place in special bag
10423 if( pProto
->BagFamily
)
10425 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
10427 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
10428 if(res
!=EQUIP_ERR_OK
)
10432 return EQUIP_ERR_OK
;
10436 // search free space
10437 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
10438 if(res
!=EQUIP_ERR_OK
)
10442 return EQUIP_ERR_OK
;
10444 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
10446 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
10447 if(res
!=EQUIP_ERR_OK
)
10451 return EQUIP_ERR_OK
;
10453 return EQUIP_ERR_BANK_FULL
;
10456 uint8
Player::CanUseItem( Item
*pItem
, bool not_loading
) const
10460 sLog
.outDebug( "STORAGE: CanUseItem item = %u", pItem
->GetEntry());
10462 if (!isAlive() && not_loading
)
10463 return EQUIP_ERR_YOU_ARE_DEAD
;
10466 // return EQUIP_ERR_YOU_ARE_STUNNED;
10468 ItemPrototype
const *pProto
= pItem
->GetProto();
10471 if (pItem
->IsBindedNotWith(this))
10472 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10474 if ((pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0)
10475 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
10477 if (uint32 item_use_skill
= pItem
->GetSkill())
10479 if (GetSkillValue(item_use_skill
) == 0)
10481 // armor items with scaling stats can downgrade armor skill reqs if related class can learn armor use at some level
10482 if (pProto
->Class
!= ITEM_CLASS_ARMOR
)
10483 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10485 ScalingStatDistributionEntry
const *ssd
= pProto
->ScalingStatDistribution
? sScalingStatDistributionStore
.LookupEntry(pProto
->ScalingStatDistribution
) : NULL
;
10487 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10489 bool allowScaleSkill
= false;
10490 for (uint32 i
= 0; i
< sSkillLineAbilityStore
.GetNumRows(); ++i
)
10492 SkillLineAbilityEntry
const *skillInfo
= sSkillLineAbilityStore
.LookupEntry(i
);
10496 if (skillInfo
->skillId
!= item_use_skill
)
10500 if (skillInfo
->classmask
&& (skillInfo
->classmask
& getClassMask()) == 0)
10503 if (skillInfo
->racemask
&& (skillInfo
->racemask
& getRaceMask()) == 0)
10506 allowScaleSkill
= true;
10510 if (!allowScaleSkill
)
10511 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10515 if (pProto
->RequiredSkill
!= 0)
10517 if (GetSkillValue( pProto
->RequiredSkill
) == 0)
10518 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10520 if (GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10521 return EQUIP_ERR_CANT_EQUIP_SKILL
;
10524 if (pProto
->RequiredSpell
!= 0 && !HasSpell(pProto
->RequiredSpell
))
10525 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10527 if (pProto
->RequiredReputationFaction
&& uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
10528 return EQUIP_ERR_CANT_EQUIP_REPUTATION
;
10530 if (getLevel() < pProto
->RequiredLevel
)
10531 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10533 return EQUIP_ERR_OK
;
10536 return EQUIP_ERR_ITEM_NOT_FOUND
;
10539 bool Player::CanUseItem( ItemPrototype
const *pProto
)
10541 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10545 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10547 if( pProto
->RequiredSkill
!= 0 )
10549 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10551 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10554 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10556 if( getLevel() < pProto
->RequiredLevel
)
10563 uint8
Player::CanUseAmmo( uint32 item
) const
10565 sLog
.outDebug( "STORAGE: CanUseAmmo item = %u", item
);
10567 return EQUIP_ERR_YOU_ARE_DEAD
;
10568 //if( isStunned() )
10569 // return EQUIP_ERR_YOU_ARE_STUNNED;
10570 ItemPrototype
const *pProto
= ObjectMgr::GetItemPrototype( item
);
10573 if( pProto
->InventoryType
!= INVTYPE_AMMO
)
10574 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE
;
10575 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10576 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
10577 if( pProto
->RequiredSkill
!= 0 )
10579 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10580 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10581 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10582 return EQUIP_ERR_CANT_EQUIP_SKILL
;
10584 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10585 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10586 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
10587 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10589 if( getLevel() < pProto
->RequiredLevel
)
10590 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10592 // Requires No Ammo
10593 if(GetDummyAura(46699))
10594 return EQUIP_ERR_BAG_FULL6
;
10596 return EQUIP_ERR_OK
;
10598 return EQUIP_ERR_ITEM_NOT_FOUND
;
10601 void Player::SetAmmo( uint32 item
)
10607 if( GetUInt32Value(PLAYER_AMMO_ID
) == item
)
10613 uint8 msg
= CanUseAmmo( item
);
10614 if (msg
!= EQUIP_ERR_OK
)
10616 SendEquipError(msg
, NULL
, NULL
, item
);
10621 SetUInt32Value(PLAYER_AMMO_ID
, item
);
10623 _ApplyAmmoBonuses();
10626 void Player::RemoveAmmo()
10628 SetUInt32Value(PLAYER_AMMO_ID
, 0);
10632 if (CanModifyStats())
10633 UpdateDamagePhysical(RANGED_ATTACK
);
10636 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10637 Item
* Player::StoreNewItem( ItemPosCountVec
const& dest
, uint32 item
, bool update
,int32 randomPropertyId
)
10640 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); ++itr
)
10641 count
+= itr
->count
;
10643 Item
*pItem
= Item::CreateItem( item
, count
, this );
10646 ItemAddedQuestCheck( item
, count
);
10647 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM
, item
, count
);
10648 if(randomPropertyId
)
10649 pItem
->SetItemRandomProperties(randomPropertyId
);
10650 pItem
= StoreItem( dest
, pItem
, update
);
10655 Item
* Player::StoreItem( ItemPosCountVec
const& dest
, Item
* pItem
, bool update
)
10660 Item
* lastItem
= pItem
;
10661 uint32 entry
= pItem
->GetEntry();
10662 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); )
10664 uint16 pos
= itr
->pos
;
10665 uint32 count
= itr
->count
;
10669 if(itr
== dest
.end())
10671 lastItem
= _StoreItem(pos
,pItem
,count
,false,update
);
10675 lastItem
= _StoreItem(pos
,pItem
,count
,true,update
);
10677 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM
, entry
);
10681 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10682 Item
* Player::_StoreItem( uint16 pos
, Item
*pItem
, uint32 count
, bool clone
, bool update
)
10687 uint8 bag
= pos
>> 8;
10688 uint8 slot
= pos
& 255;
10690 sLog
.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), count
);
10692 Item
*pItem2
= GetItemByPos( bag
, slot
);
10697 pItem
= pItem
->CloneItem(count
, this);
10699 pItem
->SetCount(count
);
10704 if (pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10705 pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10706 (pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
)))
10707 pItem
->SetBinding( true );
10709 if (bag
== INVENTORY_SLOT_BAG_0
)
10711 m_items
[slot
] = pItem
;
10712 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2), pItem
->GetGUID() );
10713 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10714 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10716 pItem
->SetSlot( slot
);
10717 pItem
->SetContainer( NULL
);
10719 // need update known currency
10720 if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
10721 UpdateKnownCurrencies(pItem
->GetEntry(), true);
10723 if (IsInWorld() && update
)
10725 pItem
->AddToWorld();
10726 pItem
->SendCreateUpdateToPlayer( this );
10729 pItem
->SetState(ITEM_CHANGED
, this);
10731 else if (Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
10733 pBag
->StoreItem( slot
, pItem
, update
);
10734 if( IsInWorld() && update
)
10736 pItem
->AddToWorld();
10737 pItem
->SendCreateUpdateToPlayer( this );
10739 pItem
->SetState(ITEM_CHANGED
, this);
10740 pBag
->SetState(ITEM_CHANGED
, this);
10743 AddEnchantmentDurations(pItem
);
10744 AddItemDurations(pItem
);
10750 if (pItem2
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10751 pItem2
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10752 (pItem2
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
)))
10753 pItem2
->SetBinding( true );
10755 pItem2
->SetCount( pItem2
->GetCount() + count
);
10756 if (IsInWorld() && update
)
10757 pItem2
->SendCreateUpdateToPlayer( this );
10761 // delete item (it not in any slot currently)
10762 if (IsInWorld() && update
)
10764 pItem
->RemoveFromWorld();
10765 pItem
->DestroyForPlayer( this );
10768 RemoveEnchantmentDurations(pItem
);
10769 RemoveItemDurations(pItem
);
10771 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10772 pItem
->SetState(ITEM_REMOVED
, this);
10775 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10776 AddEnchantmentDurations(pItem2
);
10778 pItem2
->SetState(ITEM_CHANGED
, this);
10784 Item
* Player::EquipNewItem( uint16 pos
, uint32 item
, bool update
)
10786 if (Item
*pItem
= Item::CreateItem( item
, 1, this ))
10788 ItemAddedQuestCheck( item
, 1 );
10789 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM
, item
, 1);
10790 return EquipItem( pos
, pItem
, update
);
10796 Item
* Player::EquipItem( uint16 pos
, Item
*pItem
, bool update
)
10798 AddEnchantmentDurations(pItem
);
10799 AddItemDurations(pItem
);
10801 uint8 bag
= pos
>> 8;
10802 uint8 slot
= pos
& 255;
10804 Item
*pItem2
= GetItemByPos( bag
, slot
);
10808 VisualizeItem( slot
, pItem
);
10812 ItemPrototype
const *pProto
= pItem
->GetProto();
10814 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10815 if(pProto
&& pProto
->ItemSet
)
10816 AddItemsSetItem(this, pItem
);
10818 _ApplyItemMods(pItem
, slot
, true);
10820 if(pProto
&& isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
== 0)
10822 uint32 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s
;
10824 if (getClass() == CLASS_ROGUE
)
10825 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s
;
10827 SpellEntry
const* spellProto
= sSpellStore
.LookupEntry(cooldownSpell
);
10830 sLog
.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell
);
10833 m_weaponChangeTimer
= spellProto
->StartRecoveryTime
;
10835 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+4);
10836 data
<< uint64(GetGUID());
10838 data
<< uint32(cooldownSpell
);
10840 GetSession()->SendPacket(&data
);
10845 if( IsInWorld() && update
)
10847 pItem
->AddToWorld();
10848 pItem
->SendCreateUpdateToPlayer( this );
10851 ApplyEquipCooldown(pItem
);
10853 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10855 UpdateExpertise(BASE_ATTACK
);
10856 UpdateArmorPenetration();
10858 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10860 UpdateExpertise(OFF_ATTACK
);
10861 UpdateArmorPenetration();
10866 pItem2
->SetCount( pItem2
->GetCount() + pItem
->GetCount() );
10867 if( IsInWorld() && update
)
10868 pItem2
->SendCreateUpdateToPlayer( this );
10870 // delete item (it not in any slot currently)
10871 //pItem->DeleteFromDB();
10872 if( IsInWorld() && update
)
10874 pItem
->RemoveFromWorld();
10875 pItem
->DestroyForPlayer( this );
10878 RemoveEnchantmentDurations(pItem
);
10879 RemoveItemDurations(pItem
);
10881 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10882 pItem
->SetState(ITEM_REMOVED
, this);
10883 pItem2
->SetState(ITEM_CHANGED
, this);
10885 ApplyEquipCooldown(pItem2
);
10890 // only for full equip instead adding to stack
10891 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM
, pItem
->GetEntry());
10892 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM
, slot
+1);
10897 void Player::QuickEquipItem( uint16 pos
, Item
*pItem
)
10901 AddEnchantmentDurations(pItem
);
10902 AddItemDurations(pItem
);
10904 uint8 slot
= pos
& 255;
10905 VisualizeItem( slot
, pItem
);
10909 pItem
->AddToWorld();
10910 pItem
->SendCreateUpdateToPlayer( this );
10913 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM
, pItem
->GetEntry());
10914 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM
, slot
+1);
10918 void Player::SetVisibleItemSlot(uint8 slot
, Item
*pItem
)
10922 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID
+ (slot
* 2), pItem
->GetEntry());
10923 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ (slot
* 2), 0, pItem
->GetEnchantmentId(PERM_ENCHANTMENT_SLOT
));
10924 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ (slot
* 2), 1, pItem
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
));
10928 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID
+ (slot
* 2), 0);
10929 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ (slot
* 2), 0);
10933 void Player::VisualizeItem( uint8 slot
, Item
*pItem
)
10938 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10939 if( pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
|| pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
|| pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
)
10940 pItem
->SetBinding( true );
10942 sLog
.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot
, pItem
->GetEntry());
10944 m_items
[slot
] = pItem
;
10945 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2), pItem
->GetGUID() );
10946 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10947 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10948 pItem
->SetSlot( slot
);
10949 pItem
->SetContainer( NULL
);
10951 if( slot
< EQUIPMENT_SLOT_END
)
10952 SetVisibleItemSlot(slot
, pItem
);
10954 pItem
->SetState(ITEM_CHANGED
, this);
10957 void Player::RemoveItem( uint8 bag
, uint8 slot
, bool update
)
10959 // note: removeitem does not actually change the item
10960 // it only takes the item out of storage temporarily
10961 // note2: if removeitem is to be used for delinking
10962 // the item must be removed from the player's updatequeue
10964 Item
*pItem
= GetItemByPos( bag
, slot
);
10967 sLog
.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10969 RemoveEnchantmentDurations(pItem
);
10970 RemoveItemDurations(pItem
);
10972 if( bag
== INVENTORY_SLOT_BAG_0
)
10974 if ( slot
< INVENTORY_SLOT_BAG_END
)
10976 ItemPrototype
const *pProto
= pItem
->GetProto();
10977 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10979 if(pProto
&& pProto
->ItemSet
)
10980 RemoveItemsSetItem(this, pProto
);
10982 _ApplyItemMods(pItem
, slot
, false);
10984 // remove item dependent auras and casts (only weapon and armor slots)
10985 if(slot
< EQUIPMENT_SLOT_END
)
10987 RemoveItemDependentAurasAndCasts(pItem
);
10989 // remove held enchantments, update expertise
10990 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10992 if (pItem
->GetItemSuffixFactor())
10994 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3
);
10995 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4
);
10999 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0
);
11000 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1
);
11003 UpdateExpertise(BASE_ATTACK
);
11004 UpdateArmorPenetration();
11006 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
11008 UpdateExpertise(OFF_ATTACK
);
11009 UpdateArmorPenetration();
11013 // need update known currency
11014 else if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
11015 UpdateKnownCurrencies(pItem
->GetEntry(), false);
11017 m_items
[slot
] = NULL
;
11018 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2), 0);
11020 if ( slot
< EQUIPMENT_SLOT_END
)
11021 SetVisibleItemSlot(slot
, NULL
);
11025 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
11027 pBag
->RemoveItem(slot
, update
);
11029 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
11030 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
11031 pItem
->SetSlot( NULL_SLOT
);
11032 if( IsInWorld() && update
)
11033 pItem
->SendCreateUpdateToPlayer( this );
11037 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
11038 void Player::MoveItemFromInventory(uint8 bag
, uint8 slot
, bool update
)
11040 if(Item
* it
= GetItemByPos(bag
,slot
))
11042 ItemRemovedQuestCheck(it
->GetEntry(), it
->GetCount());
11043 RemoveItem(bag
, slot
, update
);
11044 it
->RemoveFromUpdateQueueOf(this);
11045 if(it
->IsInWorld())
11047 it
->RemoveFromWorld();
11048 it
->DestroyForPlayer( this );
11053 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
11054 void Player::MoveItemToInventory(ItemPosCountVec
const& dest
, Item
* pItem
, bool update
, bool in_characterInventoryDB
)
11056 // update quest counters
11057 ItemAddedQuestCheck(pItem
->GetEntry(), pItem
->GetCount());
11058 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM
, pItem
->GetEntry(), pItem
->GetCount());
11061 Item
* pLastItem
= StoreItem(dest
, pItem
, update
);
11063 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
11064 if(pLastItem
== pItem
)
11066 // update owner for last item (this can be original item with wrong owner
11067 if(pLastItem
->GetOwnerGUID() != GetGUID())
11068 pLastItem
->SetOwnerGUID(GetGUID());
11070 // if this original item then it need create record in inventory
11071 // in case trade we already have item in other player inventory
11072 pLastItem
->SetState(in_characterInventoryDB
? ITEM_CHANGED
: ITEM_NEW
, this);
11076 void Player::DestroyItem( uint8 bag
, uint8 slot
, bool update
)
11078 Item
*pItem
= GetItemByPos( bag
, slot
);
11081 sLog
.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
11083 // start from destroy contained items (only equipped bag can have its)
11084 if (pItem
->IsBag() && pItem
->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
11086 for (int i
= 0; i
< MAX_BAG_SIZE
; ++i
)
11087 DestroyItem(slot
, i
, update
);
11090 if(pItem
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_WRAPPED
))
11091 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem
->GetGUIDLow());
11093 RemoveEnchantmentDurations(pItem
);
11094 RemoveItemDurations(pItem
);
11096 ItemRemovedQuestCheck( pItem
->GetEntry(), pItem
->GetCount() );
11098 if( bag
== INVENTORY_SLOT_BAG_0
)
11100 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2), 0);
11102 // equipment and equipped bags can have applied bonuses
11103 if ( slot
< INVENTORY_SLOT_BAG_END
)
11105 ItemPrototype
const *pProto
= pItem
->GetProto();
11107 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
11108 if(pProto
&& pProto
->ItemSet
)
11109 RemoveItemsSetItem(this, pProto
);
11111 _ApplyItemMods(pItem
, slot
, false);
11114 if ( slot
< EQUIPMENT_SLOT_END
)
11116 // remove item dependent auras and casts (only weapon and armor slots)
11117 RemoveItemDependentAurasAndCasts(pItem
);
11119 // update expertise
11120 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
11122 UpdateExpertise(BASE_ATTACK
);
11123 UpdateArmorPenetration();
11125 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
11127 UpdateExpertise(OFF_ATTACK
);
11128 UpdateArmorPenetration();
11131 // equipment visual show
11132 SetVisibleItemSlot(slot
, NULL
);
11134 // need update known currency
11135 else if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
11136 UpdateKnownCurrencies(pItem
->GetEntry(), false);
11138 m_items
[slot
] = NULL
;
11140 else if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
11141 pBag
->RemoveItem(slot
, update
);
11143 if( IsInWorld() && update
)
11145 pItem
->RemoveFromWorld();
11146 pItem
->DestroyForPlayer(this);
11149 //pItem->SetOwnerGUID(0);
11150 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
11151 pItem
->SetSlot( NULL_SLOT
);
11152 pItem
->SetState(ITEM_REMOVED
, this);
11156 void Player::DestroyItemCount( uint32 item
, uint32 count
, bool update
, bool unequip_check
)
11158 sLog
.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item
, count
);
11159 uint32 remcount
= 0;
11162 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
11164 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11166 if (pItem
->GetEntry() == item
)
11168 if (pItem
->GetCount() + remcount
<= count
)
11170 // all items in inventory can unequipped
11171 remcount
+= pItem
->GetCount();
11172 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11174 if (remcount
>= count
)
11179 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
11180 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
11181 if (IsInWorld() & update
)
11182 pItem
->SendCreateUpdateToPlayer( this );
11183 pItem
->SetState(ITEM_CHANGED
, this);
11190 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
11192 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11194 if (pItem
->GetEntry() == item
)
11196 if (pItem
->GetCount() + remcount
<= count
)
11198 // all keys can be unequipped
11199 remcount
+= pItem
->GetCount();
11200 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11202 if (remcount
>= count
)
11207 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
11208 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
11209 if (IsInWorld() & update
)
11210 pItem
->SendCreateUpdateToPlayer( this );
11211 pItem
->SetState(ITEM_CHANGED
, this);
11218 // in inventory bags
11219 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11221 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11223 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
11225 if(Item
* pItem
= pBag
->GetItemByPos(j
))
11227 if (pItem
->GetEntry() == item
)
11229 // all items in bags can be unequipped
11230 if (pItem
->GetCount() + remcount
<= count
)
11232 remcount
+= pItem
->GetCount();
11233 DestroyItem( i
, j
, update
);
11235 if (remcount
>= count
)
11240 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
11241 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
11242 if (IsInWorld() && update
)
11243 pItem
->SendCreateUpdateToPlayer( this );
11244 pItem
->SetState(ITEM_CHANGED
, this);
11253 // in equipment and bag list
11254 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11256 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11258 if (pItem
&& pItem
->GetEntry() == item
)
11260 if (pItem
->GetCount() + remcount
<= count
)
11262 if (!unequip_check
|| CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false) == EQUIP_ERR_OK
)
11264 remcount
+= pItem
->GetCount();
11265 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11267 if (remcount
>= count
)
11273 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
11274 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
11275 if (IsInWorld() & update
)
11276 pItem
->SendCreateUpdateToPlayer( this );
11277 pItem
->SetState(ITEM_CHANGED
, this);
11285 void Player::DestroyZoneLimitedItem( bool update
, uint32 new_zone
)
11287 sLog
.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone
);
11290 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
11291 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11292 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone
))
11293 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11295 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
11296 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11297 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone
))
11298 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11300 // in inventory bags
11301 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11302 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11303 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
11304 if (Item
* pItem
= pBag
->GetItemByPos(j
))
11305 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone
))
11306 DestroyItem(i
, j
, update
);
11308 // in equipment and bag list
11309 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11310 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11311 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone
))
11312 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11315 void Player::DestroyConjuredItems( bool update
)
11317 // used when entering arena
11318 // destroys all conjured items
11319 sLog
.outDebug( "STORAGE: DestroyConjuredItems" );
11322 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
11323 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11324 if (pItem
->IsConjuredConsumable())
11325 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11327 // in inventory bags
11328 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11329 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11330 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
11331 if (Item
* pItem
= pBag
->GetItemByPos(j
))
11332 if (pItem
->IsConjuredConsumable())
11333 DestroyItem( i
, j
, update
);
11335 // in equipment and bag list
11336 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11337 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11338 if (pItem
->IsConjuredConsumable())
11339 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11342 void Player::DestroyItemCount( Item
* pItem
, uint32
&count
, bool update
)
11347 sLog
.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem
->GetGUIDLow(),pItem
->GetEntry(), count
);
11349 if( pItem
->GetCount() <= count
)
11351 count
-= pItem
->GetCount();
11353 DestroyItem( pItem
->GetBagSlot(),pItem
->GetSlot(), update
);
11357 ItemRemovedQuestCheck( pItem
->GetEntry(), count
);
11358 pItem
->SetCount( pItem
->GetCount() - count
);
11360 if( IsInWorld() & update
)
11361 pItem
->SendCreateUpdateToPlayer( this );
11362 pItem
->SetState(ITEM_CHANGED
, this);
11366 void Player::SplitItem( uint16 src
, uint16 dst
, uint32 count
)
11368 uint8 srcbag
= src
>> 8;
11369 uint8 srcslot
= src
& 255;
11371 uint8 dstbag
= dst
>> 8;
11372 uint8 dstslot
= dst
& 255;
11374 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
11377 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
11381 if(pSrcItem
->m_lootGenerated
) // prevent split looting item (item
11383 //best error message found for attempting to split while looting
11384 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
11388 // not let split all items (can be only at cheating)
11389 if(pSrcItem
->GetCount() == count
)
11391 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
11395 // not let split more existed items (can be only at cheating)
11396 if(pSrcItem
->GetCount() < count
)
11398 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT
, pSrcItem
, NULL
);
11402 sLog
.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag
, dstslot
, pSrcItem
->GetEntry(), count
);
11403 Item
*pNewItem
= pSrcItem
->CloneItem( count
, this );
11406 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
11410 if( IsInventoryPos( dst
) )
11412 // change item amount before check (for unique max count check)
11413 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11415 ItemPosCountVec dest
;
11416 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pNewItem
, false );
11417 if( msg
!= EQUIP_ERR_OK
)
11420 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11421 SendEquipError( msg
, pSrcItem
, NULL
);
11426 pSrcItem
->SendCreateUpdateToPlayer( this );
11427 pSrcItem
->SetState(ITEM_CHANGED
, this);
11428 StoreItem( dest
, pNewItem
, true);
11430 else if( IsBankPos ( dst
) )
11432 // change item amount before check (for unique max count check)
11433 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11435 ItemPosCountVec dest
;
11436 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pNewItem
, false );
11437 if( msg
!= EQUIP_ERR_OK
)
11440 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11441 SendEquipError( msg
, pSrcItem
, NULL
);
11446 pSrcItem
->SendCreateUpdateToPlayer( this );
11447 pSrcItem
->SetState(ITEM_CHANGED
, this);
11448 BankItem( dest
, pNewItem
, true);
11450 else if( IsEquipmentPos ( dst
) )
11452 // change item amount before check (for unique max count check), provide space for splitted items
11453 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11456 uint8 msg
= CanEquipItem( dstslot
, dest
, pNewItem
, false );
11457 if( msg
!= EQUIP_ERR_OK
)
11460 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11461 SendEquipError( msg
, pSrcItem
, NULL
);
11466 pSrcItem
->SendCreateUpdateToPlayer( this );
11467 pSrcItem
->SetState(ITEM_CHANGED
, this);
11468 EquipItem( dest
, pNewItem
, true);
11469 AutoUnequipOffhandIfNeed();
11473 void Player::SwapItem( uint16 src
, uint16 dst
)
11475 uint8 srcbag
= src
>> 8;
11476 uint8 srcslot
= src
& 255;
11478 uint8 dstbag
= dst
>> 8;
11479 uint8 dstslot
= dst
& 255;
11481 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
11482 Item
*pDstItem
= GetItemByPos( dstbag
, dstslot
);
11487 sLog
.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag
, dstslot
, pSrcItem
->GetEntry());
11491 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD
, pSrcItem
, pDstItem
);
11497 // check unequip potability for equipped items and bank bags
11498 if (IsEquipmentPos(src
) || IsBagPos(src
))
11500 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11501 uint8 msg
= CanUnequipItem( src
, !IsBagPos ( src
) || IsBagPos ( dst
) || (pDstItem
&& pDstItem
->IsBag() && ((Bag
*)pDstItem
)->IsEmpty()));
11502 if (msg
!= EQUIP_ERR_OK
)
11504 SendEquipError( msg
, pSrcItem
, pDstItem
);
11509 // prevent put equipped/bank bag in self
11510 if (IsBagPos(src
) && srcslot
== dstbag
)
11512 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
11516 // prevent put equipped/bank bag in self
11517 if (IsBagPos(dst
) && dstslot
== srcbag
)
11519 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pDstItem
, pSrcItem
);
11527 // check unequip potability for equipped items and bank bags
11528 if(IsEquipmentPos ( dst
) || IsBagPos ( dst
))
11530 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11531 uint8 msg
= CanUnequipItem( dst
, !IsBagPos ( dst
) || IsBagPos ( src
) || (pSrcItem
->IsBag() && ((Bag
*)pSrcItem
)->IsEmpty()));
11532 if(msg
!= EQUIP_ERR_OK
)
11534 SendEquipError( msg
, pSrcItem
, pDstItem
);
11540 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11541 // or swap empty bag with another empty or not empty bag (with items exchange)
11546 if( IsInventoryPos( dst
) )
11548 ItemPosCountVec dest
;
11549 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pSrcItem
, false );
11550 if( msg
!= EQUIP_ERR_OK
)
11552 SendEquipError( msg
, pSrcItem
, NULL
);
11556 RemoveItem(srcbag
, srcslot
, true);
11557 StoreItem( dest
, pSrcItem
, true);
11559 else if( IsBankPos ( dst
) )
11561 ItemPosCountVec dest
;
11562 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pSrcItem
, false);
11563 if( msg
!= EQUIP_ERR_OK
)
11565 SendEquipError( msg
, pSrcItem
, NULL
);
11569 RemoveItem(srcbag
, srcslot
, true);
11570 BankItem( dest
, pSrcItem
, true);
11572 else if( IsEquipmentPos ( dst
) )
11575 uint8 msg
= CanEquipItem( dstslot
, dest
, pSrcItem
, false );
11576 if( msg
!= EQUIP_ERR_OK
)
11578 SendEquipError( msg
, pSrcItem
, NULL
);
11582 RemoveItem(srcbag
, srcslot
, true);
11583 EquipItem(dest
, pSrcItem
, true);
11584 AutoUnequipOffhandIfNeed();
11590 // attempt merge to / fill target item
11591 if(!pSrcItem
->IsBag() && !pDstItem
->IsBag())
11594 ItemPosCountVec sDest
;
11596 if( IsInventoryPos( dst
) )
11597 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11598 else if( IsBankPos ( dst
) )
11599 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11600 else if( IsEquipmentPos ( dst
) )
11601 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, false );
11605 // can be merge/fill
11606 if(msg
== EQUIP_ERR_OK
)
11608 if( pSrcItem
->GetCount() + pDstItem
->GetCount() <= pSrcItem
->GetProto()->GetMaxStackSize())
11610 RemoveItem(srcbag
, srcslot
, true);
11612 if( IsInventoryPos( dst
) )
11613 StoreItem( sDest
, pSrcItem
, true);
11614 else if( IsBankPos ( dst
) )
11615 BankItem( sDest
, pSrcItem
, true);
11616 else if( IsEquipmentPos ( dst
) )
11618 EquipItem( eDest
, pSrcItem
, true);
11619 AutoUnequipOffhandIfNeed();
11624 pSrcItem
->SetCount( pSrcItem
->GetCount() + pDstItem
->GetCount() - pSrcItem
->GetProto()->GetMaxStackSize());
11625 pDstItem
->SetCount( pSrcItem
->GetProto()->GetMaxStackSize());
11626 pSrcItem
->SetState(ITEM_CHANGED
, this);
11627 pDstItem
->SetState(ITEM_CHANGED
, this);
11630 pSrcItem
->SendCreateUpdateToPlayer( this );
11631 pDstItem
->SendCreateUpdateToPlayer( this );
11638 // impossible merge/fill, do real swap
11641 // check src->dest move possibility
11642 ItemPosCountVec sDest
;
11644 if( IsInventoryPos( dst
) )
11645 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11646 else if( IsBankPos( dst
) )
11647 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11648 else if( IsEquipmentPos( dst
) )
11650 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, true );
11651 if( msg
== EQUIP_ERR_OK
)
11652 msg
= CanUnequipItem( eDest
, true );
11655 if( msg
!= EQUIP_ERR_OK
)
11657 SendEquipError( msg
, pSrcItem
, pDstItem
);
11661 // check dest->src move possibility
11662 ItemPosCountVec sDest2
;
11664 if( IsInventoryPos( src
) )
11665 msg
= CanStoreItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11666 else if( IsBankPos( src
) )
11667 msg
= CanBankItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11668 else if( IsEquipmentPos( src
) )
11670 msg
= CanEquipItem( srcslot
, eDest2
, pDstItem
, true);
11671 if( msg
== EQUIP_ERR_OK
)
11672 msg
= CanUnequipItem( eDest2
, true);
11675 if( msg
!= EQUIP_ERR_OK
)
11677 SendEquipError( msg
, pDstItem
, pSrcItem
);
11681 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11682 if(pSrcItem
->IsBag() && pDstItem
->IsBag())
11684 Bag
* emptyBag
= NULL
;
11685 Bag
* fullBag
= NULL
;
11686 if(((Bag
*)pSrcItem
)->IsEmpty() && !IsBagPos(src
))
11688 emptyBag
= (Bag
*)pSrcItem
;
11689 fullBag
= (Bag
*)pDstItem
;
11691 else if(((Bag
*)pDstItem
)->IsEmpty() && !IsBagPos(dst
))
11693 emptyBag
= (Bag
*)pDstItem
;
11694 fullBag
= (Bag
*)pSrcItem
;
11697 // bag swap (with items exchange) case
11698 if(emptyBag
&& fullBag
)
11700 ItemPrototype
const* emotyProto
= emptyBag
->GetProto();
11704 for(uint32 i
=0; i
< fullBag
->GetBagSize(); ++i
)
11706 Item
*bagItem
= fullBag
->GetItemByPos(i
);
11710 ItemPrototype
const* bagItemProto
= bagItem
->GetProto();
11711 if (!bagItemProto
|| !ItemCanGoIntoBag(bagItemProto
, emotyProto
))
11713 // one from items not go to empty target bag
11714 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
11722 if (count
> emptyBag
->GetBagSize())
11724 // too small targeted bag
11725 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
, pSrcItem
, pDstItem
);
11730 count
= 0; // will pos in new bag
11731 for(uint32 i
= 0; i
< fullBag
->GetBagSize(); ++i
)
11733 Item
*bagItem
= fullBag
->GetItemByPos(i
);
11737 fullBag
->RemoveItem(i
, true);
11738 emptyBag
->StoreItem(count
, bagItem
, true);
11739 bagItem
->SetState(ITEM_CHANGED
, this);
11746 // now do moves, remove...
11747 RemoveItem(dstbag
, dstslot
, false);
11748 RemoveItem(srcbag
, srcslot
, false);
11751 if (IsInventoryPos(dst
))
11752 StoreItem(sDest
, pSrcItem
, true);
11753 else if (IsBankPos(dst
))
11754 BankItem(sDest
, pSrcItem
, true);
11755 else if (IsEquipmentPos(dst
))
11756 EquipItem(eDest
, pSrcItem
, true);
11759 if (IsInventoryPos(src
))
11760 StoreItem(sDest2
, pDstItem
, true);
11761 else if (IsBankPos(src
))
11762 BankItem(sDest2
, pDstItem
, true);
11763 else if (IsEquipmentPos(src
))
11764 EquipItem(eDest2
, pDstItem
, true);
11766 AutoUnequipOffhandIfNeed();
11769 void Player::AddItemToBuyBackSlot( Item
*pItem
)
11773 uint32 slot
= m_currentBuybackSlot
;
11774 // if current back slot non-empty search oldest or free
11777 uint32 oldest_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
);
11778 uint32 oldest_slot
= BUYBACK_SLOT_START
;
11780 for(uint32 i
= BUYBACK_SLOT_START
+1; i
< BUYBACK_SLOT_END
; ++i
)
11789 uint32 i_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ i
- BUYBACK_SLOT_START
);
11791 if (oldest_time
> i_time
)
11793 oldest_time
= i_time
;
11799 slot
= oldest_slot
;
11802 RemoveItemFromBuyBackSlot( slot
, true );
11803 sLog
.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem
->GetEntry(), slot
);
11805 m_items
[slot
] = pItem
;
11806 time_t base
= time(NULL
);
11807 uint32 etime
= uint32(base
- m_logintime
+ (30 * 3600));
11808 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11810 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ (eslot
* 2), pItem
->GetGUID() );
11811 if (ItemPrototype
const *pProto
= pItem
->GetProto())
11812 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, pProto
->SellPrice
* pItem
->GetCount() );
11814 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11815 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, (uint32
)etime
);
11817 // move to next (for non filled list is move most optimized choice)
11818 if (m_currentBuybackSlot
< BUYBACK_SLOT_END
- 1)
11819 ++m_currentBuybackSlot
;
11823 Item
* Player::GetItemFromBuyBackSlot( uint32 slot
)
11825 sLog
.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot
);
11826 if (slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11827 return m_items
[slot
];
11831 void Player::RemoveItemFromBuyBackSlot( uint32 slot
, bool del
)
11833 sLog
.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot
);
11834 if (slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11836 Item
*pItem
= m_items
[slot
];
11839 pItem
->RemoveFromWorld();
11840 if(del
) pItem
->SetState(ITEM_REMOVED
, this);
11843 m_items
[slot
] = NULL
;
11845 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11846 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ (eslot
* 2), 0 );
11847 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11848 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, 0 );
11850 // if current backslot is filled set to now free slot
11851 if (m_items
[m_currentBuybackSlot
])
11852 m_currentBuybackSlot
= slot
;
11856 void Player::SendEquipError( uint8 msg
, Item
* pItem
, Item
*pItem2
, uint32 itemid
/*= 0*/ )
11858 sLog
.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg
);
11859 WorldPacket
data(SMSG_INVENTORY_CHANGE_FAILURE
, 1+8+8+1);
11860 data
<< uint8(msg
);
11862 if (msg
!= EQUIP_ERR_OK
)
11864 data
<< uint64(pItem
? pItem
->GetGUID() : 0);
11865 data
<< uint64(pItem2
? pItem2
->GetGUID() : 0);
11866 data
<< uint8(0); // bag type subclass, used with EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM and EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG2
11870 case EQUIP_ERR_CANT_EQUIP_LEVEL_I
:
11871 case EQUIP_ERR_PURCHASE_LEVEL_TOO_LOW
:
11873 ItemPrototype
const* proto
= pItem
? pItem
->GetProto() : sObjectMgr
.GetItemPrototype(itemid
);
11874 data
<< uint32(proto
? proto
->RequiredLevel
: 0);
11877 case EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM
: // no idea about this one...
11884 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS
:
11885 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED_IS
:
11886 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS
:
11888 ItemPrototype
const* proto
= pItem
? pItem
->GetProto() : sObjectMgr
.GetItemPrototype(itemid
);
11889 data
<< uint32(proto
? proto
->ItemLimitCategory
: 0);
11896 GetSession()->SendPacket(&data
);
11899 void Player::SendBuyError( uint8 msg
, Creature
* pCreature
, uint32 item
, uint32 param
)
11901 sLog
.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11902 WorldPacket
data( SMSG_BUY_FAILED
, (8+4+4+1) );
11903 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11904 data
<< uint32(item
);
11906 data
<< uint32(param
);
11907 data
<< uint8(msg
);
11908 GetSession()->SendPacket(&data
);
11911 void Player::SendSellError( uint8 msg
, Creature
* pCreature
, uint64 guid
, uint32 param
)
11913 sLog
.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11914 WorldPacket
data( SMSG_SELL_ITEM
,(8+8+(param
?4:0)+1)); // last check 2.0.10
11915 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11916 data
<< uint64(guid
);
11918 data
<< uint32(param
);
11919 data
<< uint8(msg
);
11920 GetSession()->SendPacket(&data
);
11923 void Player::ClearTrade()
11926 acceptTrade
= false;
11927 for(int i
= 0; i
< TRADE_SLOT_COUNT
; ++i
)
11928 tradeItems
[i
] = NULL_SLOT
;
11931 void Player::TradeCancel(bool sendback
)
11935 // send yellow "Trade canceled" message to both traders
11939 ws
->SendCancelTrade();
11940 ws
= pTrader
->GetSession();
11941 if (!ws
->PlayerLogout())
11942 ws
->SendCancelTrade();
11946 pTrader
->ClearTrade();
11947 // prevent loss of reference
11948 pTrader
->pTrader
= NULL
;
11953 void Player::UpdateItemDuration(uint32 time
, bool realtimeonly
)
11955 if (m_itemDuration
.empty())
11958 sLog
.outDebug("Player::UpdateItemDuration(%u,%u)", time
, realtimeonly
);
11960 for(ItemDurationList::const_iterator itr
= m_itemDuration
.begin(); itr
!= m_itemDuration
.end(); )
11963 ++itr
; // current element can be erased in UpdateDuration
11965 if ((realtimeonly
&& (item
->GetProto()->ExtraFlags
& ITEM_EXTRA_REAL_TIME_DURATION
)) || !realtimeonly
)
11966 item
->UpdateDuration(this,time
);
11970 void Player::UpdateEnchantTime(uint32 time
)
11972 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11976 if (!itr
->item
->GetEnchantmentId(itr
->slot
))
11978 next
= m_enchantDuration
.erase(itr
);
11980 else if (itr
->leftduration
<= time
)
11982 ApplyEnchantment(itr
->item
, itr
->slot
, false, false);
11983 itr
->item
->ClearEnchantment(itr
->slot
);
11984 next
= m_enchantDuration
.erase(itr
);
11986 else if (itr
->leftduration
> time
)
11988 itr
->leftduration
-= time
;
11994 void Player::AddEnchantmentDurations(Item
*item
)
11996 for(int x
= 0; x
< MAX_ENCHANTMENT_SLOT
; ++x
)
11998 if (!item
->GetEnchantmentId(EnchantmentSlot(x
)))
12001 uint32 duration
= item
->GetEnchantmentDuration(EnchantmentSlot(x
));
12003 AddEnchantmentDuration(item
, EnchantmentSlot(x
), duration
);
12007 void Player::RemoveEnchantmentDurations(Item
*item
)
12009 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(); itr
!= m_enchantDuration
.end();)
12011 if (itr
->item
== item
)
12013 // save duration in item
12014 item
->SetEnchantmentDuration(EnchantmentSlot(itr
->slot
), itr
->leftduration
);
12015 itr
= m_enchantDuration
.erase(itr
);
12022 void Player::RemoveAllEnchantments(EnchantmentSlot slot
)
12024 // remove enchantments from equipped items first to clean up the m_enchantDuration list
12025 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(), next
; itr
!= m_enchantDuration
.end(); itr
= next
)
12028 if (itr
->slot
== slot
)
12030 if (itr
->item
&& itr
->item
->GetEnchantmentId(slot
))
12032 // remove from stats
12033 ApplyEnchantment(itr
->item
, slot
, false, false);
12035 itr
->item
->ClearEnchantment(slot
);
12037 // remove from update list
12038 next
= m_enchantDuration
.erase(itr
);
12044 // remove enchants from inventory items
12045 // NOTE: no need to remove these from stats, since these aren't equipped
12047 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
12048 if (Item
* pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
12049 if (pItem
->GetEnchantmentId(slot
))
12050 pItem
->ClearEnchantment(slot
);
12052 // in inventory bags
12053 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
12054 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
12055 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
12056 if (Item
* pItem
= pBag
->GetItemByPos(j
))
12057 if (pItem
->GetEnchantmentId(slot
))
12058 pItem
->ClearEnchantment(slot
);
12061 // duration == 0 will remove item enchant
12062 void Player::AddEnchantmentDuration(Item
*item
,EnchantmentSlot slot
,uint32 duration
)
12067 if (slot
>= MAX_ENCHANTMENT_SLOT
)
12070 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(); itr
!= m_enchantDuration
.end(); ++itr
)
12072 if (itr
->item
== item
&& itr
->slot
== slot
)
12074 itr
->item
->SetEnchantmentDuration(itr
->slot
, itr
->leftduration
);
12075 m_enchantDuration
.erase(itr
);
12079 if (item
&& duration
> 0 )
12081 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item
->GetGUID(), slot
, uint32(duration
/1000));
12082 m_enchantDuration
.push_back(EnchantDuration(item
, slot
, duration
));
12086 void Player::ApplyEnchantment(Item
*item
,bool apply
)
12088 for(uint32 slot
= 0; slot
< MAX_ENCHANTMENT_SLOT
; ++slot
)
12089 ApplyEnchantment(item
, EnchantmentSlot(slot
), apply
);
12092 void Player::ApplyEnchantment(Item
*item
, EnchantmentSlot slot
, bool apply
, bool apply_dur
, bool ignore_condition
)
12097 if (!item
->IsEquipped())
12100 if (slot
>= MAX_ENCHANTMENT_SLOT
)
12103 uint32 enchant_id
= item
->GetEnchantmentId(slot
);
12107 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
12111 if (!ignore_condition
&& pEnchant
->EnchantmentCondition
&& !((Player
*)this)->EnchantmentFitsRequirements(pEnchant
->EnchantmentCondition
, -1))
12114 if (!item
->IsBroken())
12116 for (int s
= 0; s
< 3; ++s
)
12118 uint32 enchant_display_type
= pEnchant
->type
[s
];
12119 uint32 enchant_amount
= pEnchant
->amount
[s
];
12120 uint32 enchant_spell_id
= pEnchant
->spellid
[s
];
12122 switch(enchant_display_type
)
12124 case ITEM_ENCHANTMENT_TYPE_NONE
:
12126 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
:
12127 // processed in Player::CastItemCombatSpell
12129 case ITEM_ENCHANTMENT_TYPE_DAMAGE
:
12130 if (item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
12131 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12132 else if (item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
12133 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12134 else if (item
->GetSlot() == EQUIPMENT_SLOT_RANGED
)
12135 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12137 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL
:
12138 if (enchant_spell_id
)
12142 int32 basepoints
= 0;
12143 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
12144 if (item
->GetItemRandomPropertyId())
12146 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
12149 // Search enchant_amount
12150 for (int k
= 0; k
< 3; ++k
)
12152 if(item_rand
->enchant_id
[k
] == enchant_id
)
12154 basepoints
= int32((item_rand
->prefix
[k
] * item
->GetItemSuffixFactor()) / 10000 );
12160 // Cast custom spell vs all equal basepoints getted from enchant_amount
12162 CastCustomSpell(this, enchant_spell_id
, &basepoints
, &basepoints
, &basepoints
, true, item
);
12164 CastSpell(this, enchant_spell_id
, true, item
);
12167 RemoveAurasDueToItemSpell(item
, enchant_spell_id
);
12170 case ITEM_ENCHANTMENT_TYPE_RESISTANCE
:
12171 if (!enchant_amount
)
12173 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
12176 for (int k
= 0; k
< 3; ++k
)
12178 if(item_rand
->enchant_id
[k
] == enchant_id
)
12180 enchant_amount
= uint32((item_rand
->prefix
[k
] * item
->GetItemSuffixFactor()) / 10000 );
12187 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START
+ enchant_spell_id
), TOTAL_VALUE
, float(enchant_amount
), apply
);
12189 case ITEM_ENCHANTMENT_TYPE_STAT
:
12191 if (!enchant_amount
)
12193 ItemRandomSuffixEntry
const *item_rand_suffix
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
12194 if(item_rand_suffix
)
12196 for (int k
= 0; k
< 3; ++k
)
12198 if(item_rand_suffix
->enchant_id
[k
] == enchant_id
)
12200 enchant_amount
= uint32((item_rand_suffix
->prefix
[k
] * item
->GetItemSuffixFactor()) / 10000 );
12207 sLog
.outDebug("Adding %u to stat nb %u",enchant_amount
,enchant_spell_id
);
12208 switch (enchant_spell_id
)
12210 case ITEM_MOD_MANA
:
12211 sLog
.outDebug("+ %u MANA",enchant_amount
);
12212 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(enchant_amount
), apply
);
12214 case ITEM_MOD_HEALTH
:
12215 sLog
.outDebug("+ %u HEALTH",enchant_amount
);
12216 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(enchant_amount
), apply
);
12218 case ITEM_MOD_AGILITY
:
12219 sLog
.outDebug("+ %u AGILITY",enchant_amount
);
12220 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12221 ApplyStatBuffMod(STAT_AGILITY
, float(enchant_amount
), apply
);
12223 case ITEM_MOD_STRENGTH
:
12224 sLog
.outDebug("+ %u STRENGTH",enchant_amount
);
12225 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12226 ApplyStatBuffMod(STAT_STRENGTH
, float(enchant_amount
), apply
);
12228 case ITEM_MOD_INTELLECT
:
12229 sLog
.outDebug("+ %u INTELLECT",enchant_amount
);
12230 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12231 ApplyStatBuffMod(STAT_INTELLECT
, float(enchant_amount
), apply
);
12233 case ITEM_MOD_SPIRIT
:
12234 sLog
.outDebug("+ %u SPIRIT",enchant_amount
);
12235 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12236 ApplyStatBuffMod(STAT_SPIRIT
, float(enchant_amount
), apply
);
12238 case ITEM_MOD_STAMINA
:
12239 sLog
.outDebug("+ %u STAMINA",enchant_amount
);
12240 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12241 ApplyStatBuffMod(STAT_STAMINA
, float(enchant_amount
), apply
);
12243 case ITEM_MOD_DEFENSE_SKILL_RATING
:
12244 ((Player
*)this)->ApplyRatingMod(CR_DEFENSE_SKILL
, enchant_amount
, apply
);
12245 sLog
.outDebug("+ %u DEFENCE", enchant_amount
);
12247 case ITEM_MOD_DODGE_RATING
:
12248 ((Player
*)this)->ApplyRatingMod(CR_DODGE
, enchant_amount
, apply
);
12249 sLog
.outDebug("+ %u DODGE", enchant_amount
);
12251 case ITEM_MOD_PARRY_RATING
:
12252 ((Player
*)this)->ApplyRatingMod(CR_PARRY
, enchant_amount
, apply
);
12253 sLog
.outDebug("+ %u PARRY", enchant_amount
);
12255 case ITEM_MOD_BLOCK_RATING
:
12256 ((Player
*)this)->ApplyRatingMod(CR_BLOCK
, enchant_amount
, apply
);
12257 sLog
.outDebug("+ %u SHIELD_BLOCK", enchant_amount
);
12259 case ITEM_MOD_HIT_MELEE_RATING
:
12260 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
12261 sLog
.outDebug("+ %u MELEE_HIT", enchant_amount
);
12263 case ITEM_MOD_HIT_RANGED_RATING
:
12264 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
12265 sLog
.outDebug("+ %u RANGED_HIT", enchant_amount
);
12267 case ITEM_MOD_HIT_SPELL_RATING
:
12268 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
12269 sLog
.outDebug("+ %u SPELL_HIT", enchant_amount
);
12271 case ITEM_MOD_CRIT_MELEE_RATING
:
12272 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
12273 sLog
.outDebug("+ %u MELEE_CRIT", enchant_amount
);
12275 case ITEM_MOD_CRIT_RANGED_RATING
:
12276 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
12277 sLog
.outDebug("+ %u RANGED_CRIT", enchant_amount
);
12279 case ITEM_MOD_CRIT_SPELL_RATING
:
12280 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
12281 sLog
.outDebug("+ %u SPELL_CRIT", enchant_amount
);
12283 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
12285 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
12286 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12288 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
12289 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12291 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
12292 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12294 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
12295 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12297 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
12298 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12300 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
12301 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12303 // case ITEM_MOD_HASTE_MELEE_RATING:
12304 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12306 // case ITEM_MOD_HASTE_RANGED_RATING:
12307 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12309 case ITEM_MOD_HASTE_SPELL_RATING
:
12310 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
12312 case ITEM_MOD_HIT_RATING
:
12313 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
12314 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
12315 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
12316 sLog
.outDebug("+ %u HIT", enchant_amount
);
12318 case ITEM_MOD_CRIT_RATING
:
12319 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
12320 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
12321 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
12322 sLog
.outDebug("+ %u CRITICAL", enchant_amount
);
12324 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
12325 // case ITEM_MOD_HIT_TAKEN_RATING:
12326 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12327 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12328 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12330 // case ITEM_MOD_CRIT_TAKEN_RATING:
12331 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12332 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12333 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12335 case ITEM_MOD_RESILIENCE_RATING
:
12336 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, enchant_amount
, apply
);
12337 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, enchant_amount
, apply
);
12338 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, enchant_amount
, apply
);
12339 sLog
.outDebug("+ %u RESILIENCE", enchant_amount
);
12341 case ITEM_MOD_HASTE_RATING
:
12342 ((Player
*)this)->ApplyRatingMod(CR_HASTE_MELEE
, enchant_amount
, apply
);
12343 ((Player
*)this)->ApplyRatingMod(CR_HASTE_RANGED
, enchant_amount
, apply
);
12344 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
12345 sLog
.outDebug("+ %u HASTE", enchant_amount
);
12347 case ITEM_MOD_EXPERTISE_RATING
:
12348 ((Player
*)this)->ApplyRatingMod(CR_EXPERTISE
, enchant_amount
, apply
);
12349 sLog
.outDebug("+ %u EXPERTISE", enchant_amount
);
12351 case ITEM_MOD_ATTACK_POWER
:
12352 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12353 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12354 sLog
.outDebug("+ %u ATTACK_POWER", enchant_amount
);
12356 case ITEM_MOD_RANGED_ATTACK_POWER
:
12357 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12358 sLog
.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount
);
12360 case ITEM_MOD_MANA_REGENERATION
:
12361 ((Player
*)this)->ApplyManaRegenBonus(enchant_amount
, apply
);
12362 sLog
.outDebug("+ %u MANA_REGENERATION", enchant_amount
);
12364 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
12365 ((Player
*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION
, enchant_amount
, apply
);
12366 sLog
.outDebug("+ %u ARMOR PENETRATION", enchant_amount
);
12368 case ITEM_MOD_SPELL_POWER
:
12369 ((Player
*)this)->ApplySpellPowerBonus(enchant_amount
, apply
);
12370 sLog
.outDebug("+ %u SPELL_POWER", enchant_amount
);
12372 case ITEM_MOD_BLOCK_VALUE
:
12373 HandleBaseModValue(SHIELD_BLOCK_VALUE
, FLAT_MOD
, float(enchant_amount
), apply
);
12375 case ITEM_MOD_FERAL_ATTACK_POWER
:
12376 case ITEM_MOD_SPELL_HEALING_DONE
: // deprecated
12377 case ITEM_MOD_SPELL_DAMAGE_DONE
: // deprecated
12383 case ITEM_ENCHANTMENT_TYPE_TOTEM
: // Shaman Rockbiter Weapon
12385 if(getClass() == CLASS_SHAMAN
)
12387 float addValue
= 0.0f
;
12388 if(item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
12390 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/ 1000.0f
);
12391 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, addValue
, apply
);
12393 else if(item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
12395 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/ 1000.0f
);
12396 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, addValue
, apply
);
12401 case ITEM_ENCHANTMENT_TYPE_USE_SPELL
:
12402 // processed in Player::CastItemUseSpell
12404 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET
:
12408 sLog
.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id
, enchant_display_type
);
12410 } /*switch(enchant_display_type)*/
12414 // visualize enchantment at player and equipped items
12415 if(slot
== PERM_ENCHANTMENT_SLOT
)
12416 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ (item
->GetSlot() * 2), 0, apply
? item
->GetEnchantmentId(slot
) : 0);
12418 if(slot
== TEMP_ENCHANTMENT_SLOT
)
12419 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ (item
->GetSlot() * 2), 1, apply
? item
->GetEnchantmentId(slot
) : 0);
12427 uint32 duration
= item
->GetEnchantmentDuration(slot
);
12429 AddEnchantmentDuration(item
, slot
, duration
);
12433 // duration == 0 will remove EnchantDuration
12434 AddEnchantmentDuration(item
, slot
, 0);
12439 void Player::SendEnchantmentDurations()
12441 for(EnchantDurationList::const_iterator itr
= m_enchantDuration
.begin(); itr
!= m_enchantDuration
.end(); ++itr
)
12443 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr
->item
->GetGUID(), itr
->slot
, uint32(itr
->leftduration
) / 1000);
12447 void Player::SendItemDurations()
12449 for(ItemDurationList::const_iterator itr
= m_itemDuration
.begin(); itr
!= m_itemDuration
.end(); ++itr
)
12451 (*itr
)->SendTimeUpdate(this);
12455 void Player::SendNewItem(Item
*item
, uint32 count
, bool received
, bool created
, bool broadcast
)
12457 if(!item
) // prevent crash
12460 // last check 2.0.10
12461 WorldPacket
data( SMSG_ITEM_PUSH_RESULT
, (8+4+4+4+1+4+4+4+4+4) );
12462 data
<< uint64(GetGUID()); // player GUID
12463 data
<< uint32(received
); // 0=looted, 1=from npc
12464 data
<< uint32(created
); // 0=received, 1=created
12465 data
<< uint32(1); // IsShowChatMessage
12466 data
<< uint8(item
->GetBagSlot()); // bagslot
12467 // item slot, but when added to stack: 0xFFFFFFFF
12468 data
<< uint32((item
->GetCount() == count
) ? item
->GetSlot() : -1);
12469 data
<< uint32(item
->GetEntry()); // item id
12470 data
<< uint32(item
->GetItemSuffixFactor()); // SuffixFactor
12471 data
<< uint32(item
->GetItemRandomPropertyId()); // random item property id
12472 data
<< uint32(count
); // count of items
12473 data
<< uint32(GetItemCount(item
->GetEntry())); // count of items in inventory
12475 if (broadcast
&& GetGroup())
12476 GetGroup()->BroadcastPacket(&data
, true);
12478 GetSession()->SendPacket(&data
);
12481 /*********************************************************/
12482 /*** GOSSIP SYSTEM ***/
12483 /*********************************************************/
12485 void Player::PrepareGossipMenu(WorldObject
*pSource
, uint32 menuId
)
12487 PlayerMenu
* pMenu
= PlayerTalkClass
;
12488 pMenu
->ClearMenus();
12490 pMenu
->GetGossipMenu().SetMenuId(menuId
);
12492 GossipMenuItemsMapBounds pMenuItemBounds
= sObjectMgr
.GetGossipMenuItemsMapBounds(menuId
);
12494 // if default menuId and no menu options exist for this, use options from default options
12495 if (pMenuItemBounds
.first
== pMenuItemBounds
.second
&& menuId
== GetDefaultGossipMenuForSource(pSource
))
12496 pMenuItemBounds
= sObjectMgr
.GetGossipMenuItemsMapBounds(0);
12498 for(GossipMenuItemsMap::const_iterator itr
= pMenuItemBounds
.first
; itr
!= pMenuItemBounds
.second
; ++itr
)
12500 bool bCanTalk
= true;
12502 if (itr
->second
.cond_1
&& !sObjectMgr
.IsPlayerMeetToCondition(this, itr
->second
.cond_1
))
12505 if (itr
->second
.cond_2
&& !sObjectMgr
.IsPlayerMeetToCondition(this, itr
->second
.cond_2
))
12508 if (itr
->second
.cond_3
&& !sObjectMgr
.IsPlayerMeetToCondition(this, itr
->second
.cond_3
))
12511 if (pSource
->GetTypeId() == TYPEID_UNIT
)
12513 Creature
*pCreature
= (Creature
*)pSource
;
12515 uint32 npcflags
= pCreature
->GetUInt32Value(UNIT_NPC_FLAGS
);
12517 if (!(itr
->second
.npc_option_npcflag
& npcflags
))
12520 switch(itr
->second
.option_id
)
12522 case GOSSIP_OPTION_QUESTGIVER
:
12523 PrepareQuestMenu(pSource
->GetGUID());
12526 case GOSSIP_OPTION_ARMORER
:
12527 bCanTalk
= false; // added in special mode
12529 case GOSSIP_OPTION_SPIRITHEALER
:
12533 case GOSSIP_OPTION_VENDOR
:
12535 VendorItemData
const* vItems
= pCreature
->GetVendorItems();
12536 if (!vItems
|| vItems
->Empty())
12538 sLog
.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", pCreature
->GetGUIDLow(), pCreature
->GetEntry());
12543 case GOSSIP_OPTION_TRAINER
:
12544 if (!pCreature
->isCanTrainingOf(this, false))
12547 case GOSSIP_OPTION_UNLEARNTALENTS
:
12548 if (!pCreature
->isCanTrainingAndResetTalentsOf(this))
12551 case GOSSIP_OPTION_UNLEARNPETSKILLS
:
12552 if (!GetPet() || GetPet()->getPetType() != HUNTER_PET
|| GetPet()->m_spells
.size() <= 1 || pCreature
->GetCreatureInfo()->trainer_type
!= TRAINER_TYPE_PETS
|| pCreature
->GetCreatureInfo()->trainer_class
!= CLASS_HUNTER
)
12555 case GOSSIP_OPTION_TAXIVENDOR
:
12556 if (GetSession()->SendLearnNewTaxiNode(pCreature
))
12559 case GOSSIP_OPTION_BATTLEFIELD
:
12560 if (!pCreature
->isCanInteractWithBattleMaster(this, false))
12563 case GOSSIP_OPTION_STABLEPET
:
12564 if (getClass() != CLASS_HUNTER
)
12567 case GOSSIP_OPTION_GOSSIP
:
12568 case GOSSIP_OPTION_SPIRITGUIDE
:
12569 case GOSSIP_OPTION_INNKEEPER
:
12570 case GOSSIP_OPTION_BANKER
:
12571 case GOSSIP_OPTION_PETITIONER
:
12572 case GOSSIP_OPTION_TABARDDESIGNER
:
12573 case GOSSIP_OPTION_AUCTIONEER
:
12574 break; // no checks
12576 sLog
.outErrorDb("Creature entry %u have unknown gossip option %u for menu %u", pCreature
->GetEntry(), itr
->second
.option_id
, itr
->second
.menu_id
);
12581 else if (pSource
->GetTypeId() == TYPEID_GAMEOBJECT
)
12583 GameObject
*pGo
= (GameObject
*)pSource
;
12585 switch(itr
->second
.option_id
)
12587 case GOSSIP_OPTION_QUESTGIVER
:
12588 if (pGo
->GetGoType() == GAMEOBJECT_TYPE_QUESTGIVER
)
12589 PrepareQuestMenu(pSource
->GetGUID());
12592 case GOSSIP_OPTION_GOSSIP
:
12593 if (pGo
->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER
&& pGo
->GetGoType() != GAMEOBJECT_TYPE_GOOBER
)
12604 std::string strOptionText
= itr
->second
.option_text
;
12605 std::string strBoxText
= itr
->second
.box_text
;
12607 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12611 uint32 idxEntry
= MAKE_PAIR32(menuId
, itr
->second
.id
);
12613 if (GossipMenuItemsLocale
const *no
= sObjectMgr
.GetGossipMenuItemsLocale(idxEntry
))
12615 if (no
->OptionText
.size() > (size_t)loc_idx
&& !no
->OptionText
[loc_idx
].empty())
12616 strOptionText
= no
->OptionText
[loc_idx
];
12618 if (no
->BoxText
.size() > (size_t)loc_idx
&& !no
->BoxText
[loc_idx
].empty())
12619 strBoxText
= no
->BoxText
[loc_idx
];
12623 pMenu
->GetGossipMenu().AddMenuItem(itr
->second
.option_icon
, strOptionText
, 0, itr
->second
.option_id
, strBoxText
, itr
->second
.box_money
, itr
->second
.box_coded
);
12624 pMenu
->GetGossipMenu().AddGossipMenuItemData(itr
->second
.action_menu_id
, itr
->second
.action_poi_id
, itr
->second
.action_script_id
);
12628 // some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
12629 /*if (pMenu->Empty())
12631 if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
12633 // output error message if need
12634 pCreature->isCanTrainingOf(this, true);
12637 if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
12639 // output error message if need
12640 pCreature->isCanInteractWithBattleMaster(this, true);
12645 void Player::SendPreparedGossip(WorldObject
*pSource
)
12650 if (pSource
->GetTypeId() == TYPEID_UNIT
)
12652 // in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
12653 if (!((Creature
*)pSource
)->HasFlag(UNIT_NPC_FLAGS
,UNIT_NPC_FLAG_GOSSIP
) && !PlayerTalkClass
->GetQuestMenu().Empty())
12655 SendPreparedQuest(pSource
->GetGUID());
12659 else if (pSource
->GetTypeId() == TYPEID_GAMEOBJECT
)
12661 // probably need to find a better way here
12662 if (!PlayerTalkClass
->GetGossipMenu().GetMenuId() && !PlayerTalkClass
->GetQuestMenu().Empty())
12664 SendPreparedQuest(pSource
->GetGUID());
12669 // in case non empty gossip menu (that not included quests list size) show it
12670 // (quest entries from quest menu will be included in list)
12672 uint32 textId
= GetGossipTextId(pSource
);
12674 if (uint32 menuId
= PlayerTalkClass
->GetGossipMenu().GetMenuId())
12675 textId
= GetGossipTextId(menuId
);
12677 PlayerTalkClass
->SendGossipMenu(textId
, pSource
->GetGUID());
12680 void Player::OnGossipSelect(WorldObject
* pSource
, uint32 gossipListId
, uint32 menuId
)
12682 GossipMenu
& gossipmenu
= PlayerTalkClass
->GetGossipMenu();
12684 if (gossipListId
>= gossipmenu
.MenuItemCount())
12687 // if not same, then something funky is going on
12688 if (menuId
!= gossipmenu
.GetMenuId())
12691 GossipMenuItem
const& menu_item
= gossipmenu
.GetItem(gossipListId
);
12693 uint32 gossipOptionId
= menu_item
.m_gOptionId
;
12694 uint64 guid
= pSource
->GetGUID();
12695 uint32 moneyTake
= menu_item
.m_gBoxMoney
;
12697 // if this function called and player have money for pay MoneyTake or cheating, proccess both cases
12700 if (GetMoney() >= moneyTake
)
12701 ModifyMoney(-int32(moneyTake
));
12703 return; // cheating
12706 if (pSource
->GetTypeId() == TYPEID_GAMEOBJECT
)
12708 if (gossipOptionId
> GOSSIP_OPTION_QUESTGIVER
)
12710 sLog
.outError("Player guid %u request invalid gossip option for GameObject entry %u", GetGUIDLow(), pSource
->GetEntry());
12715 GossipMenuItemData pMenuData
= gossipmenu
.GetItemData(gossipListId
);
12717 switch(gossipOptionId
)
12719 case GOSSIP_OPTION_GOSSIP
:
12721 if (pMenuData
.m_gAction_poi
)
12722 PlayerTalkClass
->SendPointOfInterest(pMenuData
.m_gAction_poi
);
12724 if (pMenuData
.m_gAction_menu
)
12726 PrepareGossipMenu(pSource
, pMenuData
.m_gAction_menu
);
12727 SendPreparedGossip(pSource
);
12730 if (pMenuData
.m_gAction_script
)
12732 if (pSource
->GetTypeId() == TYPEID_GAMEOBJECT
)
12733 GetMap()->ScriptsStart(sGossipScripts
, pMenuData
.m_gAction_script
, this, pSource
);
12734 else if (pSource
->GetTypeId() == TYPEID_UNIT
)
12735 GetMap()->ScriptsStart(sGossipScripts
, pMenuData
.m_gAction_script
, pSource
, this);
12740 case GOSSIP_OPTION_SPIRITHEALER
:
12742 ((Creature
*)pSource
)->CastSpell(((Creature
*)pSource
),17251,true,NULL
,NULL
,GetGUID());
12744 case GOSSIP_OPTION_QUESTGIVER
:
12745 PrepareQuestMenu(guid
);
12746 SendPreparedQuest(guid
);
12748 case GOSSIP_OPTION_VENDOR
:
12749 case GOSSIP_OPTION_ARMORER
:
12750 GetSession()->SendListInventory(guid
);
12752 case GOSSIP_OPTION_STABLEPET
:
12753 GetSession()->SendStablePet(guid
);
12755 case GOSSIP_OPTION_TRAINER
:
12756 GetSession()->SendTrainerList(guid
);
12758 case GOSSIP_OPTION_UNLEARNTALENTS
:
12759 PlayerTalkClass
->CloseGossip();
12760 SendTalentWipeConfirm(guid
);
12762 case GOSSIP_OPTION_UNLEARNPETSKILLS
:
12763 PlayerTalkClass
->CloseGossip();
12764 SendPetSkillWipeConfirm();
12766 case GOSSIP_OPTION_TAXIVENDOR
:
12767 GetSession()->SendTaxiMenu(((Creature
*)pSource
));
12769 case GOSSIP_OPTION_INNKEEPER
:
12770 PlayerTalkClass
->CloseGossip();
12771 SetBindPoint(guid
);
12773 case GOSSIP_OPTION_BANKER
:
12774 GetSession()->SendShowBank(guid
);
12776 case GOSSIP_OPTION_PETITIONER
:
12777 PlayerTalkClass
->CloseGossip();
12778 GetSession()->SendPetitionShowList(guid
);
12780 case GOSSIP_OPTION_TABARDDESIGNER
:
12781 PlayerTalkClass
->CloseGossip();
12782 GetSession()->SendTabardVendorActivate(guid
);
12784 case GOSSIP_OPTION_AUCTIONEER
:
12785 GetSession()->SendAuctionHello(guid
, ((Creature
*)pSource
));
12787 case GOSSIP_OPTION_SPIRITGUIDE
:
12788 PrepareGossipMenu(pSource
);
12789 SendPreparedGossip(pSource
);
12791 case GOSSIP_OPTION_BATTLEFIELD
:
12793 BattleGroundTypeId bgTypeId
= sBattleGroundMgr
.GetBattleMasterBG(pSource
->GetEntry());
12795 if (bgTypeId
== BATTLEGROUND_TYPE_NONE
)
12797 sLog
.outError("a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUIDLow());
12801 GetSession()->SendBattlegGroundList(guid
, bgTypeId
);
12807 uint32
Player::GetGossipTextId(WorldObject
*pSource
)
12809 if (!pSource
|| pSource
->GetTypeId() != TYPEID_UNIT
|| !((Creature
*)pSource
)->GetDBTableGUIDLow())
12810 return DEFAULT_GOSSIP_MESSAGE
;
12812 if (uint32 pos
= sObjectMgr
.GetNpcGossip(((Creature
*)pSource
)->GetDBTableGUIDLow()))
12815 return DEFAULT_GOSSIP_MESSAGE
;
12818 uint32
Player::GetGossipTextId(uint32 menuId
)
12820 uint32 textId
= DEFAULT_GOSSIP_MESSAGE
;
12825 GossipMenusMapBounds pMenuBounds
= sObjectMgr
.GetGossipMenusMapBounds(menuId
);
12827 for(GossipMenusMap::const_iterator itr
= pMenuBounds
.first
; itr
!= pMenuBounds
.second
; ++itr
)
12829 if (sObjectMgr
.IsPlayerMeetToCondition(this, itr
->second
.cond_1
) && sObjectMgr
.IsPlayerMeetToCondition(this, itr
->second
.cond_2
))
12830 textId
= itr
->second
.text_id
;
12836 uint32
Player::GetDefaultGossipMenuForSource(WorldObject
*pSource
)
12838 if (pSource
->GetTypeId() == TYPEID_UNIT
)
12839 return ((Creature
*)pSource
)->GetCreatureInfo()->GossipMenuId
;
12840 else if (pSource
->GetTypeId() == TYPEID_GAMEOBJECT
)
12841 return((GameObject
*)pSource
)->GetGOInfo()->GetGossipMenuId();
12846 /*********************************************************/
12847 /*** QUEST SYSTEM ***/
12848 /*********************************************************/
12850 void Player::PrepareQuestMenu( uint64 guid
)
12853 QuestRelations
* pObjectQR
;
12854 QuestRelations
* pObjectQIR
;
12856 // pets also can have quests
12857 if (Creature
*pCreature
= GetMap()->GetCreatureOrPetOrVehicle(guid
))
12859 pObject
= (Object
*)pCreature
;
12860 pObjectQR
= &sObjectMgr
.mCreatureQuestRelations
;
12861 pObjectQIR
= &sObjectMgr
.mCreatureQuestInvolvedRelations
;
12865 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12866 //only for quests which cast teleport spells on player
12867 Map
* _map
= IsInWorld() ? GetMap() : sMapMgr
.FindMap(GetMapId(), GetInstanceId());
12869 GameObject
*pGameObject
= _map
->GetGameObject(guid
);
12872 pObject
= (Object
*)pGameObject
;
12873 pObjectQR
= &sObjectMgr
.mGOQuestRelations
;
12874 pObjectQIR
= &sObjectMgr
.mGOQuestInvolvedRelations
;
12880 QuestMenu
&qm
= PlayerTalkClass
->GetQuestMenu();
12883 for(QuestRelations::const_iterator i
= pObjectQIR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQIR
->upper_bound(pObject
->GetEntry()); ++i
)
12885 uint32 quest_id
= i
->second
;
12886 QuestStatus status
= GetQuestStatus( quest_id
);
12887 if ( status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus( quest_id
) )
12888 qm
.AddMenuItem(quest_id
, 4);
12889 else if ( status
== QUEST_STATUS_INCOMPLETE
)
12890 qm
.AddMenuItem(quest_id
, 4);
12891 else if (status
== QUEST_STATUS_AVAILABLE
)
12892 qm
.AddMenuItem(quest_id
, 2);
12895 for(QuestRelations::const_iterator i
= pObjectQR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++i
)
12897 uint32 quest_id
= i
->second
;
12898 Quest
const* pQuest
= sObjectMgr
.GetQuestTemplate(quest_id
);
12899 if(!pQuest
) continue;
12901 QuestStatus status
= GetQuestStatus( quest_id
);
12903 if (pQuest
->IsAutoComplete() && CanTakeQuest(pQuest
, false))
12904 qm
.AddMenuItem(quest_id
, 4);
12905 else if ( status
== QUEST_STATUS_NONE
&& CanTakeQuest( pQuest
, false ) )
12906 qm
.AddMenuItem(quest_id
, 2);
12910 void Player::SendPreparedQuest(uint64 guid
)
12912 QuestMenu
& questMenu
= PlayerTalkClass
->GetQuestMenu();
12914 if (questMenu
.Empty())
12917 QuestMenuItem
const& qmi0
= questMenu
.GetItem(0);
12919 uint32 icon
= qmi0
.m_qIcon
;
12921 // single element case
12922 if (questMenu
.MenuItemCount() == 1)
12924 // Auto open -- maybe also should verify there is no greeting
12925 uint32 quest_id
= qmi0
.m_qId
;
12926 Quest
const* pQuest
= sObjectMgr
.GetQuestTemplate(quest_id
);
12930 if (icon
== 4 && !GetQuestRewardStatus(quest_id
))
12931 PlayerTalkClass
->SendQuestGiverRequestItems(pQuest
, guid
, CanRewardQuest(pQuest
, false), true);
12932 else if (icon
== 4)
12933 PlayerTalkClass
->SendQuestGiverRequestItems(pQuest
, guid
, CanRewardQuest(pQuest
, false), true);
12934 // Send completable on repeatable and autoCompletable quest if player don't have quest
12935 // TODO: verify if check for !pQuest->IsDaily() is really correct (possibly not)
12936 else if (pQuest
->IsAutoComplete() && pQuest
->IsRepeatable() && !pQuest
->IsDailyOrWeekly())
12937 PlayerTalkClass
->SendQuestGiverRequestItems(pQuest
, guid
, CanCompleteRepeatableQuest(pQuest
), true);
12939 PlayerTalkClass
->SendQuestGiverQuestDetails(pQuest
, guid
, true);
12942 // multiply entries
12948 std::string title
= "";
12950 // need pet case for some quests
12951 if (Creature
*pCreature
= GetMap()->GetCreatureOrPetOrVehicle(guid
))
12953 uint32 textid
= GetGossipTextId(pCreature
);
12955 GossipText
const* gossiptext
= sObjectMgr
.GetGossipText(textid
);
12958 qe
._Delay
= 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12959 qe
._Emote
= 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12964 qe
= gossiptext
->Options
[0].Emotes
[0];
12966 if(!gossiptext
->Options
[0].Text_0
.empty())
12968 title
= gossiptext
->Options
[0].Text_0
;
12970 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12973 NpcTextLocale
const *nl
= sObjectMgr
.GetNpcTextLocale(textid
);
12976 if ((int32
)nl
->Text_0
[0].size() > loc_idx
&& !nl
->Text_0
[0][loc_idx
].empty())
12977 title
= nl
->Text_0
[0][loc_idx
];
12983 title
= gossiptext
->Options
[0].Text_1
;
12985 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12988 NpcTextLocale
const *nl
= sObjectMgr
.GetNpcTextLocale(textid
);
12991 if ((int32
)nl
->Text_1
[0].size() > loc_idx
&& !nl
->Text_1
[0][loc_idx
].empty())
12992 title
= nl
->Text_1
[0][loc_idx
];
12998 PlayerTalkClass
->SendQuestGiverQuestList(qe
, title
, guid
);
13002 bool Player::IsActiveQuest( uint32 quest_id
) const
13004 QuestStatusMap::const_iterator itr
= mQuestStatus
.find(quest_id
);
13006 return itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
;
13009 Quest
const * Player::GetNextQuest( uint64 guid
, Quest
const *pQuest
)
13012 QuestRelations
* pObjectQR
;
13013 QuestRelations
* pObjectQIR
;
13015 if (Creature
*pCreature
= GetMap()->GetCreatureOrPetOrVehicle(guid
))
13017 pObject
= (Object
*)pCreature
;
13018 pObjectQR
= &sObjectMgr
.mCreatureQuestRelations
;
13019 pObjectQIR
= &sObjectMgr
.mCreatureQuestInvolvedRelations
;
13023 //we should obtain map pointer from GetMap() in 99% of cases. Special case
13024 //only for quests which cast teleport spells on player
13025 Map
* _map
= IsInWorld() ? GetMap() : sMapMgr
.FindMap(GetMapId(), GetInstanceId());
13027 GameObject
*pGameObject
= _map
->GetGameObject(guid
);
13030 pObject
= (Object
*)pGameObject
;
13031 pObjectQR
= &sObjectMgr
.mGOQuestRelations
;
13032 pObjectQIR
= &sObjectMgr
.mGOQuestInvolvedRelations
;
13038 uint32 nextQuestID
= pQuest
->GetNextQuestInChain();
13039 for(QuestRelations::const_iterator itr
= pObjectQR
->lower_bound(pObject
->GetEntry()); itr
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++itr
)
13041 if (itr
->second
== nextQuestID
)
13042 return sObjectMgr
.GetQuestTemplate(nextQuestID
);
13048 bool Player::CanSeeStartQuest( Quest
const *pQuest
)
13050 if( SatisfyQuestRace( pQuest
, false ) && SatisfyQuestSkillOrClass( pQuest
, false ) &&
13051 SatisfyQuestExclusiveGroup( pQuest
, false ) && SatisfyQuestReputation( pQuest
, false ) &&
13052 SatisfyQuestPreviousQuest( pQuest
, false ) && SatisfyQuestNextChain( pQuest
, false ) &&
13053 SatisfyQuestPrevChain( pQuest
, false ) && SatisfyQuestDay( pQuest
, false ) && SatisfyQuestWeek( pQuest
, false ) )
13055 return getLevel() + sWorld
.getConfig(CONFIG_UINT32_QUEST_HIGH_LEVEL_HIDE_DIFF
) >= pQuest
->GetMinLevel();
13061 bool Player::CanTakeQuest( Quest
const *pQuest
, bool msg
)
13063 return SatisfyQuestStatus( pQuest
, msg
) && SatisfyQuestExclusiveGroup( pQuest
, msg
)
13064 && SatisfyQuestRace( pQuest
, msg
) && SatisfyQuestLevel( pQuest
, msg
)
13065 && SatisfyQuestSkillOrClass( pQuest
, msg
) && SatisfyQuestReputation( pQuest
, msg
)
13066 && SatisfyQuestPreviousQuest( pQuest
, msg
) && SatisfyQuestTimed( pQuest
, msg
)
13067 && SatisfyQuestNextChain( pQuest
, msg
) && SatisfyQuestPrevChain( pQuest
, msg
)
13068 && SatisfyQuestDay( pQuest
, msg
) && SatisfyQuestWeek( pQuest
, msg
);
13071 bool Player::CanAddQuest( Quest
const *pQuest
, bool msg
)
13073 if( !SatisfyQuestLog( msg
) )
13076 uint32 srcitem
= pQuest
->GetSrcItemId();
13079 uint32 count
= pQuest
->GetSrcItemCount();
13080 ItemPosCountVec dest
;
13081 uint8 msg2
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
13083 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
13084 if( msg2
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
13086 else if( msg2
!= EQUIP_ERR_OK
)
13088 SendEquipError(msg2
, NULL
, NULL
, srcitem
);
13095 bool Player::CanCompleteQuest( uint32 quest_id
)
13099 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
13100 if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
13101 return false; // not allow re-complete quest
13103 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(quest_id
);
13108 // auto complete quest
13109 if (qInfo
->IsAutoComplete() && CanTakeQuest(qInfo
, false))
13112 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13115 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13117 for(int i
= 0; i
< QUEST_ITEM_OBJECTIVES_COUNT
; ++i
)
13119 if( qInfo
->ReqItemCount
[i
] != 0 && q_status
.m_itemcount
[i
] < qInfo
->ReqItemCount
[i
] )
13124 if ( qInfo
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
13126 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
13128 if( qInfo
->ReqCreatureOrGOId
[i
] == 0 )
13131 if( qInfo
->ReqCreatureOrGOCount
[i
] != 0 && q_status
.m_creatureOrGOcount
[i
] < qInfo
->ReqCreatureOrGOCount
[i
] )
13136 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT
) && !q_status
.m_explored
)
13139 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && q_status
.m_timer
== 0 )
13142 if ( qInfo
->GetRewOrReqMoney() < 0 )
13144 if ( GetMoney() < uint32(-qInfo
->GetRewOrReqMoney()) )
13148 uint32 repFacId
= qInfo
->GetRepObjectiveFaction();
13149 if ( repFacId
&& GetReputationMgr().GetReputation(repFacId
) < qInfo
->GetRepObjectiveValue() )
13158 bool Player::CanCompleteRepeatableQuest( Quest
const *pQuest
)
13160 // Solve problem that player don't have the quest and try complete it.
13161 // if repeatable she must be able to complete event if player don't have it.
13162 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
13163 if( !CanTakeQuest(pQuest
, false) )
13166 if (pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13167 for(int i
= 0; i
< QUEST_ITEM_OBJECTIVES_COUNT
; ++i
)
13168 if( pQuest
->ReqItemId
[i
] && pQuest
->ReqItemCount
[i
] && !HasItemCount(pQuest
->ReqItemId
[i
], pQuest
->ReqItemCount
[i
]) )
13171 if( !CanRewardQuest(pQuest
, false) )
13177 bool Player::CanRewardQuest( Quest
const *pQuest
, bool msg
)
13179 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
13180 if (!pQuest
->IsAutoComplete() && GetQuestStatus(pQuest
->GetQuestId()) != QUEST_STATUS_COMPLETE
)
13183 // daily quest can't be rewarded (25 daily quest already completed)
13184 if (!SatisfyQuestDay(pQuest
,true) || !SatisfyQuestWeek(pQuest
,true))
13187 // rewarded and not repeatable quest (only cheating case, then ignore without message)
13188 if (GetQuestRewardStatus(pQuest
->GetQuestId()))
13191 // prevent receive reward with quest items in bank
13192 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13194 for(int i
= 0; i
< QUEST_ITEM_OBJECTIVES_COUNT
; ++i
)
13196 if( pQuest
->ReqItemCount
[i
] != 0 &&
13197 GetItemCount(pQuest
->ReqItemId
[i
]) < pQuest
->ReqItemCount
[i
] )
13200 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, NULL
, NULL
, pQuest
->ReqItemId
[i
]);
13206 // prevent receive reward with low money and GetRewOrReqMoney() < 0
13207 if (pQuest
->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest
->GetRewOrReqMoney()) )
13213 bool Player::CanRewardQuest( Quest
const *pQuest
, uint32 reward
, bool msg
)
13215 // prevent receive reward with quest items in bank or for not completed quest
13216 if(!CanRewardQuest(pQuest
,msg
))
13219 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
13221 if( pQuest
->RewChoiceItemId
[reward
] )
13223 ItemPosCountVec dest
;
13224 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] );
13225 if( res
!= EQUIP_ERR_OK
)
13227 SendEquipError( res
, NULL
, NULL
, pQuest
->RewChoiceItemId
[reward
] );
13233 if ( pQuest
->GetRewItemsCount() > 0 )
13235 for (uint32 i
= 0; i
< pQuest
->GetRewItemsCount(); ++i
)
13237 if( pQuest
->RewItemId
[i
] )
13239 ItemPosCountVec dest
;
13240 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] );
13241 if( res
!= EQUIP_ERR_OK
)
13243 SendEquipError( res
, NULL
, NULL
);
13253 void Player::SendPetTameFailure(PetTameFailureReason reason
)
13255 WorldPacket
data(SMSG_PET_TAME_FAILURE
, 1);
13256 data
<< uint8(reason
);
13257 GetSession()->SendPacket(&data
);
13260 void Player::AddQuest( Quest
const *pQuest
, Object
*questGiver
)
13262 uint16 log_slot
= FindQuestSlot( 0 );
13263 ASSERT(log_slot
< MAX_QUEST_LOG_SIZE
);
13265 uint32 quest_id
= pQuest
->GetQuestId();
13267 // if not exist then created with set uState==NEW and rewarded=false
13268 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
13270 // check for repeatable quests status reset
13271 questStatusData
.m_status
= QUEST_STATUS_INCOMPLETE
;
13272 questStatusData
.m_explored
= false;
13274 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13276 for(int i
= 0; i
< QUEST_ITEM_OBJECTIVES_COUNT
; ++i
)
13277 questStatusData
.m_itemcount
[i
] = 0;
13280 if ( pQuest
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
13282 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
13283 questStatusData
.m_creatureOrGOcount
[i
] = 0;
13286 GiveQuestSourceItem( pQuest
);
13287 AdjustQuestReqItemCount( pQuest
, questStatusData
);
13289 if( pQuest
->GetRepObjectiveFaction() )
13290 if(FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->GetRepObjectiveFaction()))
13291 GetReputationMgr().SetVisible(factionEntry
);
13294 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
13296 uint32 limittime
= pQuest
->GetLimitTime();
13298 // shared timed quest
13299 if(questGiver
&& questGiver
->GetTypeId()==TYPEID_PLAYER
)
13300 limittime
= ((Player
*)questGiver
)->getQuestStatusMap()[quest_id
].m_timer
/ IN_MILLISECONDS
;
13302 AddTimedQuest( quest_id
);
13303 questStatusData
.m_timer
= limittime
* IN_MILLISECONDS
;
13304 qtime
= static_cast<uint32
>(time(NULL
)) + limittime
;
13307 questStatusData
.m_timer
= 0;
13309 SetQuestSlot(log_slot
, quest_id
, qtime
);
13311 if (questStatusData
.uState
!= QUEST_NEW
)
13312 questStatusData
.uState
= QUEST_CHANGED
;
13314 //starting initial quest script
13315 if(questGiver
&& pQuest
->GetQuestStartScript()!=0)
13316 GetMap()->ScriptsStart(sQuestStartScripts
, pQuest
->GetQuestStartScript(), questGiver
, this);
13318 // Some spells applied at quest activation
13319 SpellAreaForQuestMapBounds saBounds
= sSpellMgr
.GetSpellAreaForQuestMapBounds(quest_id
,true);
13320 if(saBounds
.first
!= saBounds
.second
)
13323 GetZoneAndAreaId(zone
,area
);
13325 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
13326 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,zone
,area
))
13327 if (!HasAura(itr
->second
->spellId
, EFFECT_INDEX_0
) )
13328 CastSpell(this,itr
->second
->spellId
,true);
13331 UpdateForQuestWorldObjects();
13334 void Player::CompleteQuest( uint32 quest_id
)
13338 SetQuestStatus( quest_id
, QUEST_STATUS_COMPLETE
);
13340 uint16 log_slot
= FindQuestSlot( quest_id
);
13341 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13342 SetQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
13344 if(Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(quest_id
))
13346 if( qInfo
->HasFlag(QUEST_FLAGS_AUTO_REWARDED
) )
13347 RewardQuest(qInfo
,0,this,false);
13349 SendQuestComplete( quest_id
);
13354 void Player::IncompleteQuest( uint32 quest_id
)
13358 SetQuestStatus( quest_id
, QUEST_STATUS_INCOMPLETE
);
13360 uint16 log_slot
= FindQuestSlot( quest_id
);
13361 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13362 RemoveQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
13366 void Player::RewardQuest( Quest
const *pQuest
, uint32 reward
, Object
* questGiver
, bool announce
)
13368 //this THING should be here to protect code from quest, which cast on player far teleport as a reward
13369 //should work fine, cause far teleport will be executed in Player::Update()
13370 SetCanDelayTeleport(true);
13372 uint32 quest_id
= pQuest
->GetQuestId();
13374 for (int i
= 0; i
< QUEST_ITEM_OBJECTIVES_COUNT
; ++i
)
13376 if (pQuest
->ReqItemId
[i
])
13377 DestroyItemCount( pQuest
->ReqItemId
[i
], pQuest
->ReqItemCount
[i
], true);
13380 RemoveTimedQuest(quest_id
);
13382 if (BattleGround
* bg
= GetBattleGround())
13383 if (bg
->GetTypeID() == BATTLEGROUND_AV
)
13384 ((BattleGroundAV
*)bg
)->HandleQuestComplete(pQuest
->GetQuestId(), this);
13386 if (pQuest
->GetRewChoiceItemsCount() > 0)
13388 if (uint32 itemId
= pQuest
->RewChoiceItemId
[reward
])
13390 ItemPosCountVec dest
;
13391 if (CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, itemId
, pQuest
->RewChoiceItemCount
[reward
] ) == EQUIP_ERR_OK
)
13393 Item
* item
= StoreNewItem( dest
, itemId
, true, Item::GenerateItemRandomPropertyId(itemId
));
13394 SendNewItem(item
, pQuest
->RewChoiceItemCount
[reward
], true, false);
13399 if (pQuest
->GetRewItemsCount() > 0)
13401 for (uint32 i
=0; i
< pQuest
->GetRewItemsCount(); ++i
)
13403 if (uint32 itemId
= pQuest
->RewItemId
[i
])
13405 ItemPosCountVec dest
;
13406 if (CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, itemId
, pQuest
->RewItemCount
[i
] ) == EQUIP_ERR_OK
)
13408 Item
* item
= StoreNewItem( dest
, itemId
, true, Item::GenerateItemRandomPropertyId(itemId
));
13409 SendNewItem(item
, pQuest
->RewItemCount
[i
], true, false);
13415 RewardReputation( pQuest
);
13417 uint16 log_slot
= FindQuestSlot( quest_id
);
13418 if (log_slot
< MAX_QUEST_LOG_SIZE
)
13419 SetQuestSlot(log_slot
,0);
13421 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
13423 // Not give XP in case already completed once repeatable quest
13424 uint32 XP
= q_status
.m_rewarded
? 0 : uint32(pQuest
->XPValue( this )*sWorld
.getConfig(CONFIG_FLOAT_RATE_XP_QUEST
));
13426 if (getLevel() < sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
))
13427 GiveXP( XP
, NULL
);
13430 uint32 money
= uint32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY
));
13431 ModifyMoney( money
);
13432 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD
, money
);
13435 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
13436 if (pQuest
->GetRewOrReqMoney())
13438 ModifyMoney( pQuest
->GetRewOrReqMoney() );
13440 if (pQuest
->GetRewOrReqMoney() > 0)
13441 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD
, pQuest
->GetRewOrReqMoney());
13445 if (pQuest
->GetRewHonorAddition())
13446 RewardHonor(NULL
, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorAddition()));
13449 if (pQuest
->GetCharTitleId())
13451 if (CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
13452 SetTitle(titleEntry
);
13455 if (pQuest
->GetBonusTalents())
13457 m_questRewardTalentCount
+=pQuest
->GetBonusTalents();
13458 InitTalentForLevel();
13461 // Send reward mail
13462 if (uint32 mail_template_id
= pQuest
->GetRewMailTemplateId())
13463 MailDraft(mail_template_id
).SendMailTo(MailReceiver(this), MailSender(questGiver
), MAIL_CHECK_MASK_HAS_BODY
, pQuest
->GetRewMailDelaySecs());
13465 if (pQuest
->IsDaily())
13467 SetDailyQuestStatus(quest_id
);
13468 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST
, 1);
13471 if (pQuest
->IsWeekly())
13472 SetWeeklyQuestStatus(quest_id
);
13474 if (!pQuest
->IsRepeatable())
13475 SetQuestStatus(quest_id
, QUEST_STATUS_COMPLETE
);
13477 SetQuestStatus(quest_id
, QUEST_STATUS_NONE
);
13479 q_status
.m_rewarded
= true;
13480 if (q_status
.uState
!= QUEST_NEW
)
13481 q_status
.uState
= QUEST_CHANGED
;
13484 SendQuestReward( pQuest
, XP
, questGiver
);
13486 // cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data)
13487 if (pQuest
->GetRewSpellCast() > 0)
13488 CastSpell( this, pQuest
->GetRewSpellCast(), true);
13489 else if ( pQuest
->GetRewSpell() > 0)
13490 CastSpell( this, pQuest
->GetRewSpell(), true);
13492 if (pQuest
->GetZoneOrSort() > 0)
13493 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE
, pQuest
->GetZoneOrSort());
13494 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT
);
13495 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST
, pQuest
->GetQuestId());
13500 // remove auras from spells with quest reward state limitations
13501 SpellAreaForQuestMapBounds saEndBounds
= sSpellMgr
.GetSpellAreaForQuestEndMapBounds(quest_id
);
13502 if(saEndBounds
.first
!= saEndBounds
.second
)
13504 GetZoneAndAreaId(zone
,area
);
13506 for(SpellAreaForAreaMap::const_iterator itr
= saEndBounds
.first
; itr
!= saEndBounds
.second
; ++itr
)
13507 if(!itr
->second
->IsFitToRequirements(this,zone
,area
))
13508 RemoveAurasDueToSpell(itr
->second
->spellId
);
13511 // Some spells applied at quest reward
13512 SpellAreaForQuestMapBounds saBounds
= sSpellMgr
.GetSpellAreaForQuestMapBounds(quest_id
,false);
13513 if(saBounds
.first
!= saBounds
.second
)
13516 GetZoneAndAreaId(zone
,area
);
13518 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
13519 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,zone
,area
))
13520 if (!HasAura(itr
->second
->spellId
, EFFECT_INDEX_0
))
13521 CastSpell(this,itr
->second
->spellId
,true);
13524 //lets remove flag for delayed teleports
13525 SetCanDelayTeleport(false);
13528 void Player::FailQuest(uint32 questId
)
13530 if (Quest
const* pQuest
= sObjectMgr
.GetQuestTemplate(questId
))
13532 SetQuestStatus(questId
, QUEST_STATUS_FAILED
);
13534 uint16 log_slot
= FindQuestSlot(questId
);
13536 if (log_slot
< MAX_QUEST_LOG_SIZE
)
13538 SetQuestSlotTimer(log_slot
, 1);
13539 SetQuestSlotState(log_slot
, QUEST_STATE_FAIL
);
13542 if (pQuest
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
))
13544 QuestStatusData
& q_status
= mQuestStatus
[questId
];
13546 RemoveTimedQuest(questId
);
13547 q_status
.m_timer
= 0;
13549 SendQuestTimerFailed(questId
);
13552 SendQuestFailed(questId
);
13556 bool Player::SatisfyQuestSkillOrClass( Quest
const* qInfo
, bool msg
)
13558 int32 zoneOrSort
= qInfo
->GetZoneOrSort();
13559 int32 skillOrClass
= qInfo
->GetSkillOrClass();
13561 // skip zone zoneOrSort and 0 case skillOrClass
13562 if( zoneOrSort
>= 0 && skillOrClass
== 0 )
13565 int32 questSort
= -zoneOrSort
;
13566 uint8 reqSortClass
= ClassByQuestSort(questSort
);
13568 // check class sort cases in zoneOrSort
13569 if( reqSortClass
!= 0 && getClass() != reqSortClass
)
13572 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13577 if( skillOrClass
< 0 )
13579 uint8 reqClass
= -int32(skillOrClass
);
13580 if(getClass() != reqClass
)
13583 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13588 else if( skillOrClass
> 0 )
13590 uint32 reqSkill
= skillOrClass
;
13591 if( GetSkillValue( reqSkill
) < qInfo
->GetRequiredSkillValue() )
13594 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13602 bool Player::SatisfyQuestLevel( Quest
const* qInfo
, bool msg
)
13604 if( getLevel() < qInfo
->GetMinLevel() )
13607 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13613 bool Player::SatisfyQuestLog( bool msg
)
13616 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE
)
13621 WorldPacket
data( SMSG_QUESTLOG_FULL
, 0 );
13622 GetSession()->SendPacket( &data
);
13623 sLog
.outDebug( "WORLD: Sent SMSG_QUESTLOG_FULL" );
13628 bool Player::SatisfyQuestPreviousQuest( Quest
const* qInfo
, bool msg
)
13630 // No previous quest (might be first quest in a series)
13631 if( qInfo
->prevQuests
.empty())
13634 for(Quest::PrevQuests::const_iterator iter
= qInfo
->prevQuests
.begin(); iter
!= qInfo
->prevQuests
.end(); ++iter
)
13636 uint32 prevId
= abs(*iter
);
13638 QuestStatusMap::const_iterator i_prevstatus
= mQuestStatus
.find( prevId
);
13639 Quest
const* qPrevInfo
= sObjectMgr
.GetQuestTemplate(prevId
);
13641 if( qPrevInfo
&& i_prevstatus
!= mQuestStatus
.end() )
13643 // If any of the positive previous quests completed, return true
13644 if( *iter
> 0 && i_prevstatus
->second
.m_rewarded
)
13646 // skip one-from-all exclusive group
13647 if(qPrevInfo
->GetExclusiveGroup() >= 0)
13650 // each-from-all exclusive group ( < 0)
13651 // can be start if only all quests in prev quest exclusive group completed and rewarded
13652 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2
= sObjectMgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
13653 ObjectMgr::ExclusiveQuestGroups::const_iterator end
= sObjectMgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
13655 ASSERT(iter2
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
13657 for(; iter2
!= end
; ++iter2
)
13659 uint32 exclude_Id
= iter2
->second
;
13661 // skip checked quest id, only state of other quests in group is interesting
13662 if(exclude_Id
== prevId
)
13665 QuestStatusMap::const_iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
13667 // alternative quest from group also must be completed and rewarded(reported)
13668 if( i_exstatus
== mQuestStatus
.end() || !i_exstatus
->second
.m_rewarded
)
13671 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13677 // If any of the negative previous quests active, return true
13678 if( *iter
< 0 && (i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
13679 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
))))
13681 // skip one-from-all exclusive group
13682 if(qPrevInfo
->GetExclusiveGroup() >= 0)
13685 // each-from-all exclusive group ( < 0)
13686 // can be start if only all quests in prev quest exclusive group active
13687 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2
= sObjectMgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
13688 ObjectMgr::ExclusiveQuestGroups::const_iterator end
= sObjectMgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
13690 ASSERT(iter2
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
13692 for(; iter2
!= end
; ++iter2
)
13694 uint32 exclude_Id
= iter2
->second
;
13696 // skip checked quest id, only state of other quests in group is interesting
13697 if(exclude_Id
== prevId
)
13700 QuestStatusMap::const_iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
13702 // alternative quest from group also must be active
13703 if( i_exstatus
== mQuestStatus
.end() ||
13704 i_exstatus
->second
.m_status
!= QUEST_STATUS_INCOMPLETE
&&
13705 (i_prevstatus
->second
.m_status
!= QUEST_STATUS_COMPLETE
|| GetQuestRewardStatus(prevId
)) )
13708 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13717 // Has only positive prev. quests in non-rewarded state
13718 // and negative prev. quests in non-active state
13720 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13725 bool Player::SatisfyQuestRace( Quest
const* qInfo
, bool msg
)
13727 uint32 reqraces
= qInfo
->GetRequiredRaces();
13728 if ( reqraces
== 0 )
13730 if( (reqraces
& getRaceMask()) == 0 )
13733 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE
);
13739 bool Player::SatisfyQuestReputation( Quest
const* qInfo
, bool msg
)
13741 uint32 fIdMin
= qInfo
->GetRequiredMinRepFaction(); //Min required rep
13742 if(fIdMin
&& GetReputationMgr().GetReputation(fIdMin
) < qInfo
->GetRequiredMinRepValue())
13745 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13749 uint32 fIdMax
= qInfo
->GetRequiredMaxRepFaction(); //Max required rep
13750 if(fIdMax
&& GetReputationMgr().GetReputation(fIdMax
) >= qInfo
->GetRequiredMaxRepValue())
13753 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13760 bool Player::SatisfyQuestStatus( Quest
const* qInfo
, bool msg
)
13762 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( qInfo
->GetQuestId() );
13763 if ( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
)
13766 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON
);
13772 bool Player::SatisfyQuestTimed(Quest
const* qInfo
, bool msg
)
13774 if (!m_timedquests
.empty() && qInfo
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
))
13777 SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED
);
13784 bool Player::SatisfyQuestExclusiveGroup( Quest
const* qInfo
, bool msg
)
13786 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13787 if (qInfo
->GetExclusiveGroup() <= 0)
13790 ObjectMgr::ExclusiveQuestGroups::const_iterator iter
= sObjectMgr
.mExclusiveQuestGroups
.lower_bound(qInfo
->GetExclusiveGroup());
13791 ObjectMgr::ExclusiveQuestGroups::const_iterator end
= sObjectMgr
.mExclusiveQuestGroups
.upper_bound(qInfo
->GetExclusiveGroup());
13793 ASSERT(iter
!=end
); // always must be found if qInfo->ExclusiveGroup != 0
13795 for(; iter
!= end
; ++iter
)
13797 uint32 exclude_Id
= iter
->second
;
13799 // skip checked quest id, only state of other quests in group is interesting
13800 if (exclude_Id
== qInfo
->GetQuestId())
13803 // not allow have daily quest if daily quest from exclusive group already recently completed
13804 Quest
const* Nquest
= sObjectMgr
.GetQuestTemplate(exclude_Id
);
13805 if (!SatisfyQuestDay(Nquest
, false) || !SatisfyQuestWeek(Nquest
, false))
13808 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13812 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
13814 // alternative quest already started or completed
13815 if (i_exstatus
!= mQuestStatus
.end()
13816 && (i_exstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
|| i_exstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
))
13819 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13826 bool Player::SatisfyQuestNextChain( Quest
const* qInfo
, bool msg
)
13828 if(!qInfo
->GetNextQuestInChain())
13831 // next quest in chain already started or completed
13832 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( qInfo
->GetNextQuestInChain() );
13833 if( itr
!= mQuestStatus
.end()
13834 && (itr
->second
.m_status
== QUEST_STATUS_COMPLETE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
13837 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13841 // check for all quests further up the chain
13842 // only necessary if there are quest chains with more than one quest that can be skipped
13843 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13847 bool Player::SatisfyQuestPrevChain( Quest
const* qInfo
, bool msg
)
13849 // No previous quest in chain
13850 if( qInfo
->prevChainQuests
.empty())
13853 for(Quest::PrevChainQuests::const_iterator iter
= qInfo
->prevChainQuests
.begin(); iter
!= qInfo
->prevChainQuests
.end(); ++iter
)
13855 uint32 prevId
= *iter
;
13857 QuestStatusMap::const_iterator i_prevstatus
= mQuestStatus
.find( prevId
);
13859 if( i_prevstatus
!= mQuestStatus
.end() )
13861 // If any of the previous quests in chain active, return false
13862 if( i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
13863 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
)))
13866 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13871 // check for all quests further down the chain
13872 // only necessary if there are quest chains with more than one quest that can be skipped
13873 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13877 // No previous quest in chain active
13881 bool Player::SatisfyQuestDay( Quest
const* qInfo
, bool msg
)
13883 if (!qInfo
->IsDaily())
13886 bool have_slot
= false;
13887 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
13889 uint32 id
= GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
);
13890 if (qInfo
->GetQuestId()==id
)
13900 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING
);
13907 bool Player::SatisfyQuestWeek( Quest
const* qInfo
, bool msg
)
13909 if (!qInfo
->IsWeekly() || m_weeklyquests
.empty())
13912 // if not found in cooldown list
13913 return m_weeklyquests
.find(qInfo
->GetQuestId()) == m_weeklyquests
.end();
13916 bool Player::GiveQuestSourceItem( Quest
const *pQuest
)
13918 uint32 srcitem
= pQuest
->GetSrcItemId();
13921 uint32 count
= pQuest
->GetSrcItemCount();
13925 ItemPosCountVec dest
;
13926 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
13927 if (msg
== EQUIP_ERR_OK
)
13929 Item
* item
= StoreNewItem(dest
, srcitem
, true);
13930 SendNewItem(item
, count
, true, false);
13933 // player already have max amount required item, just report success
13934 else if (msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
13937 SendEquipError( msg
, NULL
, NULL
, srcitem
);
13944 bool Player::TakeQuestSourceItem( uint32 quest_id
, bool msg
)
13946 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(quest_id
);
13949 uint32 srcitem
= qInfo
->GetSrcItemId();
13952 uint32 count
= qInfo
->GetSrcItemCount();
13956 // exist one case when destroy source quest item not possible:
13957 // non un-equippable item (equipped non-empty bag, for example)
13958 uint8 res
= CanUnequipItems(srcitem
,count
);
13959 if(res
!= EQUIP_ERR_OK
)
13962 SendEquipError( res
, NULL
, NULL
, srcitem
);
13966 DestroyItemCount(srcitem
, count
, true, true);
13972 bool Player::GetQuestRewardStatus( uint32 quest_id
) const
13974 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(quest_id
);
13977 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13978 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13979 if( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
13980 && !qInfo
->IsRepeatable() )
13981 return itr
->second
.m_rewarded
;
13988 QuestStatus
Player::GetQuestStatus( uint32 quest_id
) const
13992 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13993 if( itr
!= mQuestStatus
.end() )
13994 return itr
->second
.m_status
;
13996 return QUEST_STATUS_NONE
;
13999 bool Player::CanShareQuest(uint32 quest_id
) const
14001 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(quest_id
);
14002 if( qInfo
&& qInfo
->HasFlag(QUEST_FLAGS_SHARABLE
) )
14004 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
14005 if( itr
!= mQuestStatus
.end() )
14006 return itr
->second
.m_status
== QUEST_STATUS_NONE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
;
14011 void Player::SetQuestStatus(uint32 quest_id
, QuestStatus status
)
14013 if (sObjectMgr
.GetQuestTemplate(quest_id
))
14015 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
14017 q_status
.m_status
= status
;
14019 if (q_status
.uState
!= QUEST_NEW
)
14020 q_status
.uState
= QUEST_CHANGED
;
14023 UpdateForQuestWorldObjects();
14026 // not used in MaNGOS, but used in scripting code
14027 uint32
Player::GetReqKillOrCastCurrentCount(uint32 quest_id
, int32 entry
)
14029 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(quest_id
);
14033 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
14034 if ( qInfo
->ReqCreatureOrGOId
[j
] == entry
)
14035 return mQuestStatus
[quest_id
].m_creatureOrGOcount
[j
];
14040 void Player::AdjustQuestReqItemCount( Quest
const* pQuest
, QuestStatusData
& questStatusData
)
14042 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
14044 for(int i
= 0; i
< QUEST_ITEM_OBJECTIVES_COUNT
; ++i
)
14046 uint32 reqitemcount
= pQuest
->ReqItemCount
[i
];
14047 if( reqitemcount
!= 0 )
14049 uint32 curitemcount
= GetItemCount(pQuest
->ReqItemId
[i
], true);
14051 questStatusData
.m_itemcount
[i
] = std::min(curitemcount
, reqitemcount
);
14052 if (questStatusData
.uState
!= QUEST_NEW
) questStatusData
.uState
= QUEST_CHANGED
;
14058 uint16
Player::FindQuestSlot( uint32 quest_id
) const
14060 for ( uint16 i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14061 if ( GetQuestSlotQuestId(i
) == quest_id
)
14064 return MAX_QUEST_LOG_SIZE
;
14067 void Player::AreaExploredOrEventHappens( uint32 questId
)
14071 uint16 log_slot
= FindQuestSlot( questId
);
14072 if( log_slot
< MAX_QUEST_LOG_SIZE
)
14074 QuestStatusData
& q_status
= mQuestStatus
[questId
];
14076 if(!q_status
.m_explored
)
14078 q_status
.m_explored
= true;
14079 if (q_status
.uState
!= QUEST_NEW
)
14080 q_status
.uState
= QUEST_CHANGED
;
14083 if( CanCompleteQuest( questId
) )
14084 CompleteQuest( questId
);
14088 //not used in mangosd, function for external script library
14089 void Player::GroupEventHappens( uint32 questId
, WorldObject
const* pEventObject
)
14091 if( Group
*pGroup
= GetGroup() )
14093 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
14095 Player
*pGroupGuy
= itr
->getSource();
14097 // for any leave or dead (with not released body) group member at appropriate distance
14098 if( pGroupGuy
&& pGroupGuy
->IsAtGroupRewardDistance(pEventObject
) && !pGroupGuy
->HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
14099 pGroupGuy
->AreaExploredOrEventHappens(questId
);
14103 AreaExploredOrEventHappens(questId
);
14106 void Player::ItemAddedQuestCheck( uint32 entry
, uint32 count
)
14108 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14110 uint32 questid
= GetQuestSlotQuestId(i
);
14111 if ( questid
== 0 )
14114 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14116 if ( q_status
.m_status
!= QUEST_STATUS_INCOMPLETE
)
14119 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
);
14120 if( !qInfo
|| !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
14123 for (int j
= 0; j
< QUEST_ITEM_OBJECTIVES_COUNT
; ++j
)
14125 uint32 reqitem
= qInfo
->ReqItemId
[j
];
14126 if ( reqitem
== entry
)
14128 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
14129 uint32 curitemcount
= q_status
.m_itemcount
[j
];
14130 if ( curitemcount
< reqitemcount
)
14132 uint32 additemcount
= ( curitemcount
+ count
<= reqitemcount
? count
: reqitemcount
- curitemcount
);
14133 q_status
.m_itemcount
[j
] += additemcount
;
14134 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
14136 SendQuestUpdateAddItem( qInfo
, j
, additemcount
);
14138 if ( CanCompleteQuest( questid
) )
14139 CompleteQuest( questid
);
14144 UpdateForQuestWorldObjects();
14147 void Player::ItemRemovedQuestCheck( uint32 entry
, uint32 count
)
14149 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14151 uint32 questid
= GetQuestSlotQuestId(i
);
14154 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
);
14157 if( !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
14160 for (int j
= 0; j
< QUEST_ITEM_OBJECTIVES_COUNT
; ++j
)
14162 uint32 reqitem
= qInfo
->ReqItemId
[j
];
14163 if ( reqitem
== entry
)
14165 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14167 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
14168 uint32 curitemcount
;
14169 if( q_status
.m_status
!= QUEST_STATUS_COMPLETE
)
14170 curitemcount
= q_status
.m_itemcount
[j
];
14172 curitemcount
= GetItemCount(entry
, true);
14173 if ( curitemcount
< reqitemcount
+ count
)
14175 uint32 remitemcount
= ( curitemcount
<= reqitemcount
? count
: count
+ reqitemcount
- curitemcount
);
14176 q_status
.m_itemcount
[j
] = curitemcount
- remitemcount
;
14177 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
14179 IncompleteQuest( questid
);
14185 UpdateForQuestWorldObjects();
14188 void Player::KilledMonster( CreatureInfo
const* cInfo
, ObjectGuid guid
)
14191 KilledMonsterCredit(cInfo
->Entry
, guid
);
14193 for(int i
= 0; i
< MAX_KILL_CREDIT
; ++i
)
14194 if(cInfo
->KillCredit
[i
])
14195 KilledMonsterCredit(cInfo
->KillCredit
[i
], guid
);
14198 void Player::KilledMonsterCredit( uint32 entry
, ObjectGuid guid
)
14200 uint32 addkillcount
= 1;
14201 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE
, entry
, addkillcount
);
14202 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14204 uint32 questid
= GetQuestSlotQuestId(i
);
14208 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
);
14211 // just if !ingroup || !noraidgroup || raidgroup
14212 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14213 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
&& (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo
->GetType() == QUEST_TYPE_RAID
))
14215 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
14217 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
14219 // skip GO activate objective or none
14220 if(qInfo
->ReqCreatureOrGOId
[j
] <=0)
14223 // skip Cast at creature objective
14224 if(qInfo
->ReqSpell
[j
] !=0 )
14227 uint32 reqkill
= qInfo
->ReqCreatureOrGOId
[j
];
14229 if ( reqkill
== entry
)
14231 uint32 reqkillcount
= qInfo
->ReqCreatureOrGOCount
[j
];
14232 uint32 curkillcount
= q_status
.m_creatureOrGOcount
[j
];
14233 if ( curkillcount
< reqkillcount
)
14235 q_status
.m_creatureOrGOcount
[j
] = curkillcount
+ addkillcount
;
14236 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
14238 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curkillcount
, addkillcount
);
14240 if ( CanCompleteQuest( questid
) )
14241 CompleteQuest( questid
);
14243 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14252 void Player::CastedCreatureOrGO( uint32 entry
, ObjectGuid guid
, uint32 spell_id
)
14254 bool isCreature
= guid
.IsCreature();
14256 uint32 addCastCount
= 1;
14257 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14259 uint32 questid
= GetQuestSlotQuestId(i
);
14263 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
);
14267 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14269 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
14271 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
14273 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
14275 // skip kill creature objective (0) or wrong spell casts
14276 if(qInfo
->ReqSpell
[j
] != spell_id
)
14279 uint32 reqTarget
= 0;
14283 // creature activate objectives
14284 if(qInfo
->ReqCreatureOrGOId
[j
] > 0)
14285 // checked at quest_template loading
14286 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
14290 // GO activate objective
14291 if(qInfo
->ReqCreatureOrGOId
[j
] < 0)
14292 // checked at quest_template loading
14293 reqTarget
= - qInfo
->ReqCreatureOrGOId
[j
];
14296 // other not this creature/GO related objectives
14297 if( reqTarget
!= entry
)
14300 uint32 reqCastCount
= qInfo
->ReqCreatureOrGOCount
[j
];
14301 uint32 curCastCount
= q_status
.m_creatureOrGOcount
[j
];
14302 if ( curCastCount
< reqCastCount
)
14304 q_status
.m_creatureOrGOcount
[j
] = curCastCount
+ addCastCount
;
14305 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
14307 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curCastCount
, addCastCount
);
14310 if ( CanCompleteQuest( questid
) )
14311 CompleteQuest( questid
);
14313 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14321 void Player::TalkedToCreature( uint32 entry
, ObjectGuid guid
)
14323 uint32 addTalkCount
= 1;
14324 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14326 uint32 questid
= GetQuestSlotQuestId(i
);
14330 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
);
14334 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14336 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
14338 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
14340 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
14342 // skip spell casts and Gameobject objectives
14343 if(qInfo
->ReqSpell
[j
] > 0 || qInfo
->ReqCreatureOrGOId
[j
] < 0)
14346 uint32 reqTarget
= 0;
14348 if(qInfo
->ReqCreatureOrGOId
[j
] > 0) // creature activate objectives
14349 // checked at quest_template loading
14350 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
14354 if ( reqTarget
== entry
)
14356 uint32 reqTalkCount
= qInfo
->ReqCreatureOrGOCount
[j
];
14357 uint32 curTalkCount
= q_status
.m_creatureOrGOcount
[j
];
14358 if ( curTalkCount
< reqTalkCount
)
14360 q_status
.m_creatureOrGOcount
[j
] = curTalkCount
+ addTalkCount
;
14361 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
14363 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curTalkCount
, addTalkCount
);
14365 if ( CanCompleteQuest( questid
) )
14366 CompleteQuest( questid
);
14368 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14377 void Player::MoneyChanged( uint32 count
)
14379 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14381 uint32 questid
= GetQuestSlotQuestId(i
);
14385 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
);
14386 if( qInfo
&& qInfo
->GetRewOrReqMoney() < 0 )
14388 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14390 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
14392 if(int32(count
) >= -qInfo
->GetRewOrReqMoney())
14394 if ( CanCompleteQuest( questid
) )
14395 CompleteQuest( questid
);
14398 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
14400 if(int32(count
) < -qInfo
->GetRewOrReqMoney())
14401 IncompleteQuest( questid
);
14407 void Player::ReputationChanged(FactionEntry
const* factionEntry
)
14409 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14411 if(uint32 questid
= GetQuestSlotQuestId(i
))
14413 if(Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
))
14415 if(qInfo
->GetRepObjectiveFaction() == factionEntry
->ID
)
14417 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14418 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
14420 if(GetReputationMgr().GetReputation(factionEntry
) >= qInfo
->GetRepObjectiveValue())
14421 if ( CanCompleteQuest( questid
) )
14422 CompleteQuest( questid
);
14424 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
14426 if(GetReputationMgr().GetReputation(factionEntry
) < qInfo
->GetRepObjectiveValue())
14427 IncompleteQuest( questid
);
14435 bool Player::HasQuestForItem( uint32 itemid
) const
14437 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14439 uint32 questid
= GetQuestSlotQuestId(i
);
14440 if ( questid
== 0 )
14443 QuestStatusMap::const_iterator qs_itr
= mQuestStatus
.find(questid
);
14444 if(qs_itr
== mQuestStatus
.end())
14447 QuestStatusData
const& q_status
= qs_itr
->second
;
14449 if (q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
14451 Quest
const* qinfo
= sObjectMgr
.GetQuestTemplate(questid
);
14455 // hide quest if player is in raid-group and quest is no raid quest
14456 if (GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
14457 && !InBattleGround())
14460 // There should be no mixed ReqItem/ReqSource drop
14461 // This part for ReqItem drop
14462 for (int j
= 0; j
< QUEST_ITEM_OBJECTIVES_COUNT
; ++j
)
14464 if(itemid
== qinfo
->ReqItemId
[j
] && q_status
.m_itemcount
[j
] < qinfo
->ReqItemCount
[j
] )
14467 // This part - for ReqSource
14468 for (int j
= 0; j
< QUEST_SOURCE_ITEM_IDS_COUNT
; ++j
)
14470 // examined item is a source item
14471 if (qinfo
->ReqSourceId
[j
] == itemid
)
14473 ItemPrototype
const *pProto
= ObjectMgr::GetItemPrototype(itemid
);
14476 if (pProto
->MaxCount
&& (int32
)GetItemCount(itemid
,true) < pProto
->MaxCount
)
14479 // allows custom amount drop when not 0
14480 if (qinfo
->ReqSourceCount
[j
])
14482 if (GetItemCount(itemid
,true) < qinfo
->ReqSourceCount
[j
])
14484 } else if ((int32
)GetItemCount(itemid
,true) < pProto
->Stackable
)
14493 void Player::SendQuestComplete( uint32 quest_id
)
14497 WorldPacket
data( SMSG_QUESTUPDATE_COMPLETE
, 4 );
14498 data
<< uint32(quest_id
);
14499 GetSession()->SendPacket( &data
);
14500 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id
);
14504 void Player::SendQuestReward( Quest
const *pQuest
, uint32 XP
, Object
* questGiver
)
14506 uint32 questid
= pQuest
->GetQuestId();
14507 sLog
.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid
);
14508 WorldPacket
data( SMSG_QUESTGIVER_QUEST_COMPLETE
, (4+4+4+4+4) );
14509 data
<< uint32(questid
);
14511 if ( getLevel() < sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
) )
14513 data
<< uint32(XP
);
14514 data
<< uint32(pQuest
->GetRewOrReqMoney());
14519 data
<< uint32(pQuest
->GetRewOrReqMoney() + int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY
)));
14522 data
<< uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorAddition()));
14523 data
<< uint32(pQuest
->GetBonusTalents()); // bonus talents
14524 data
<< uint32(0); // arena points
14525 GetSession()->SendPacket( &data
);
14527 if (pQuest
->GetQuestCompleteScript() != 0)
14528 GetMap()->ScriptsStart(sQuestEndScripts
, pQuest
->GetQuestCompleteScript(), questGiver
, this);
14531 void Player::SendQuestFailed( uint32 quest_id
)
14535 WorldPacket
data( SMSG_QUESTGIVER_QUEST_FAILED
, 4+4 );
14536 data
<< uint32(quest_id
);
14537 data
<< uint32(0); // failed reason (4 for inventory is full)
14538 GetSession()->SendPacket( &data
);
14539 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
14543 void Player::SendQuestTimerFailed( uint32 quest_id
)
14547 WorldPacket
data( SMSG_QUESTUPDATE_FAILEDTIMER
, 4 );
14548 data
<< uint32(quest_id
);
14549 GetSession()->SendPacket( &data
);
14550 sLog
.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
14554 void Player::SendCanTakeQuestResponse( uint32 msg
)
14556 WorldPacket
data( SMSG_QUESTGIVER_QUEST_INVALID
, 4 );
14557 data
<< uint32(msg
);
14558 GetSession()->SendPacket( &data
);
14559 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
14562 void Player::SendQuestConfirmAccept(const Quest
* pQuest
, Player
* pReceiver
)
14566 std::string strTitle
= pQuest
->GetTitle();
14568 int loc_idx
= pReceiver
->GetSession()->GetSessionDbLocaleIndex();
14572 if (const QuestLocale
* pLocale
= sObjectMgr
.GetQuestLocale(pQuest
->GetQuestId()))
14574 if ((int32
)pLocale
->Title
.size() > loc_idx
&& !pLocale
->Title
[loc_idx
].empty())
14575 strTitle
= pLocale
->Title
[loc_idx
];
14579 WorldPacket
data(SMSG_QUEST_CONFIRM_ACCEPT
, (4 + strTitle
.size() + 8));
14580 data
<< uint32(pQuest
->GetQuestId());
14582 data
<< uint64(GetGUID());
14583 pReceiver
->GetSession()->SendPacket(&data
);
14585 sLog
.outDebug("WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT");
14589 void Player::SendPushToPartyResponse( Player
*pPlayer
, uint32 msg
)
14593 WorldPacket
data( MSG_QUEST_PUSH_RESULT
, (8+1) );
14594 data
<< uint64(pPlayer
->GetGUID());
14595 data
<< uint8(msg
); // valid values: 0-8
14596 GetSession()->SendPacket( &data
);
14597 sLog
.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
14601 void Player::SendQuestUpdateAddItem( Quest
const* /*pQuest*/, uint32
/*item_idx*/, uint32
/*count*/ )
14603 WorldPacket
data( SMSG_QUESTUPDATE_ADD_ITEM
, 0 );
14604 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
14605 //data << pQuest->ReqItemId[item_idx];
14607 GetSession()->SendPacket( &data
);
14610 void Player::SendQuestUpdateAddCreatureOrGo( Quest
const* pQuest
, ObjectGuid guid
, uint32 creatureOrGO_idx
, uint32 old_count
, uint32 add_count
)
14612 ASSERT(old_count
+ add_count
< 65536 && "mob/GO count store in 16 bits 2^16 = 65536 (0..65536)");
14614 int32 entry
= pQuest
->ReqCreatureOrGOId
[ creatureOrGO_idx
];
14616 // client expected gameobject template id in form (id|0x80000000)
14617 entry
= (-entry
) | 0x80000000;
14619 WorldPacket
data( SMSG_QUESTUPDATE_ADD_KILL
, (4*4+8) );
14620 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
14621 data
<< uint32(pQuest
->GetQuestId());
14622 data
<< uint32(entry
);
14623 data
<< uint32(old_count
+ add_count
);
14624 data
<< uint32(pQuest
->ReqCreatureOrGOCount
[ creatureOrGO_idx
]);
14626 GetSession()->SendPacket(&data
);
14628 uint16 log_slot
= FindQuestSlot( pQuest
->GetQuestId() );
14629 if( log_slot
< MAX_QUEST_LOG_SIZE
)
14630 SetQuestSlotCounter(log_slot
,creatureOrGO_idx
,GetQuestSlotCounter(log_slot
,creatureOrGO_idx
)+add_count
);
14633 /*********************************************************/
14634 /*** LOAD SYSTEM ***/
14635 /*********************************************************/
14637 void Player::_LoadDeclinedNames(QueryResult
* result
)
14643 delete m_declinedname
;
14645 m_declinedname
= new DeclinedName
;
14646 Field
*fields
= result
->Fetch();
14647 for(int i
= 0; i
< MAX_DECLINED_NAME_CASES
; ++i
)
14648 m_declinedname
->name
[i
] = fields
[i
].GetCppString();
14653 void Player::_LoadArenaTeamInfo(QueryResult
*result
)
14655 // arenateamid, played_week, played_season, personal_rating
14656 memset((void*)&m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
], 0, sizeof(uint32
) * MAX_ARENA_SLOT
* ARENA_TEAM_END
);
14662 Field
*fields
= result
->Fetch();
14664 uint32 arenateamid
= fields
[0].GetUInt32();
14665 uint32 played_week
= fields
[1].GetUInt32();
14666 uint32 played_season
= fields
[2].GetUInt32();
14667 uint32 wons_season
= fields
[3].GetUInt32();
14668 uint32 personal_rating
= fields
[4].GetUInt32();
14670 ArenaTeam
* aTeam
= sObjectMgr
.GetArenaTeamById(arenateamid
);
14673 sLog
.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u", arenateamid
);
14676 uint8 arenaSlot
= aTeam
->GetSlot();
14678 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_ID
, arenateamid
);
14679 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_TYPE
, aTeam
->GetType());
14680 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_MEMBER
, (aTeam
->GetCaptain() == GetGUID()) ? 0 : 1);
14681 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_GAMES_WEEK
, played_week
);
14682 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_GAMES_SEASON
, played_season
);
14683 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_WINS_SEASON
, wons_season
);
14684 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_PERSONAL_RATING
, personal_rating
);
14686 } while (result
->NextRow());
14690 void Player::_LoadEquipmentSets(QueryResult
*result
)
14692 // 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));
14699 Field
*fields
= result
->Fetch();
14701 EquipmentSet eqSet
;
14703 eqSet
.Guid
= fields
[0].GetUInt64();
14704 uint32 index
= fields
[1].GetUInt32();
14705 eqSet
.Name
= fields
[2].GetCppString();
14706 eqSet
.IconName
= fields
[3].GetCppString();
14707 eqSet
.state
= EQUIPMENT_SET_UNCHANGED
;
14709 for(uint32 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
14710 eqSet
.Items
[i
] = fields
[4+i
].GetUInt32();
14712 m_EquipmentSets
[index
] = eqSet
;
14716 if(count
>= MAX_EQUIPMENT_SET_INDEX
) // client limit
14718 } while (result
->NextRow());
14722 void Player::_LoadBGData(QueryResult
* result
)
14727 // Expecting only one row
14728 Field
*fields
= result
->Fetch();
14729 /* bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
14730 m_bgData
.bgInstanceID
= fields
[0].GetUInt32();
14731 m_bgData
.bgTeam
= fields
[1].GetUInt32();
14732 m_bgData
.joinPos
= WorldLocation(fields
[6].GetUInt32(), // Map
14733 fields
[2].GetFloat(), // X
14734 fields
[3].GetFloat(), // Y
14735 fields
[4].GetFloat(), // Z
14736 fields
[5].GetFloat()); // Orientation
14737 m_bgData
.taxiPath
[0] = fields
[7].GetUInt32();
14738 m_bgData
.taxiPath
[1] = fields
[8].GetUInt32();
14739 m_bgData
.mountSpell
= fields
[9].GetUInt32();
14744 bool Player::LoadPositionFromDB(uint32
& mapid
, float& x
,float& y
,float& z
,float& o
, bool& in_flight
, uint64 guid
)
14746 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid
));
14750 Field
*fields
= result
->Fetch();
14752 x
= fields
[0].GetFloat();
14753 y
= fields
[1].GetFloat();
14754 z
= fields
[2].GetFloat();
14755 o
= fields
[3].GetFloat();
14756 mapid
= fields
[4].GetUInt32();
14757 in_flight
= !fields
[5].GetCppString().empty();
14763 void Player::_LoadIntoDataField(const char* data
, uint32 startOffset
, uint32 count
)
14768 Tokens tokens
= StrSplit(data
, " ");
14770 if(tokens
.size() != count
)
14773 Tokens::iterator iter
;
14775 for (iter
= tokens
.begin(), index
= 0; index
< count
; ++iter
, ++index
)
14777 m_uint32Values
[startOffset
+ index
] = atol((*iter
).c_str());
14781 bool Player::LoadFromDB( uint32 guid
, SqlQueryHolder
*holder
)
14783 // 0 1 2 3 4 5 6 7 8 9 10 11
14784 //SELECT guid, account, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags,"
14785 // 12 13 14 15 16 17 18 19 20 21 22 23 24
14786 //"position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost,"
14787 // 25 26 27 28 29 30 31 32 33 34 35 36 37 38
14788 //"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,"
14789 // 39 40 41 42 43 44 45 46 47 48 49
14790 //"arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk,"
14791 // 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
14792 //"health, power1, power2, power3, power4, power5, power6, power7, specCount, activeSpec, exploredZones, equipmentCache, ammoId, knownTitles, actionBars FROM characters WHERE guid = '%u'", GUID_LOPART(m_guid));
14793 QueryResult
*result
= holder
->GetResult(PLAYER_LOGIN_QUERY_LOADFROM
);
14797 sLog
.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid
);
14801 Field
*fields
= result
->Fetch();
14803 uint32 dbAccountId
= fields
[1].GetUInt32();
14805 // check if the character's account in the db and the logged in account match.
14806 // player should be able to load/delete character only with correct account!
14807 if( dbAccountId
!= GetSession()->GetAccountId() )
14809 sLog
.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid
,GetSession()->GetAccountId(),dbAccountId
);
14814 Object::_Create( guid
, 0, HIGHGUID_PLAYER
);
14816 m_name
= fields
[2].GetCppString();
14818 // check name limitations
14819 if (ObjectMgr::CheckPlayerName(m_name
) != CHAR_NAME_SUCCESS
||
14820 (GetSession()->GetSecurity() == SEC_PLAYER
&& sObjectMgr
.IsReservedName(m_name
)))
14823 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME
),guid
);
14827 // overwrite possible wrong/corrupted guid
14828 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
14830 // overwrite some data fields
14832 bytes0
|= fields
[3].GetUInt8(); // race
14833 bytes0
|= fields
[4].GetUInt8() << 8; // class
14834 bytes0
|= fields
[5].GetUInt8() << 16; // gender
14835 SetUInt32Value(UNIT_FIELD_BYTES_0
, bytes0
);
14837 SetUInt32Value(UNIT_FIELD_LEVEL
, fields
[6].GetUInt8());
14838 SetUInt32Value(PLAYER_XP
, fields
[7].GetUInt32());
14840 _LoadIntoDataField(fields
[60].GetString(), PLAYER_EXPLORED_ZONES_1
, PLAYER_EXPLORED_ZONES_SIZE
);
14841 _LoadIntoDataField(fields
[63].GetString(), PLAYER__FIELD_KNOWN_TITLES
, KNOWN_TITLES_SIZE
*2);
14843 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, DEFAULT_WORLD_OBJECT_SIZE
);
14844 SetFloatValue(UNIT_FIELD_COMBATREACH
, 1.5f
);
14845 SetFloatValue(UNIT_FIELD_HOVERHEIGHT
, 1.0f
);
14847 uint32 money
= fields
[8].GetUInt32();
14848 if(money
> MAX_MONEY_AMOUNT
)
14849 money
= MAX_MONEY_AMOUNT
;
14852 SetUInt32Value(PLAYER_BYTES
, fields
[9].GetUInt32());
14853 SetUInt32Value(PLAYER_BYTES_2
, fields
[10].GetUInt32());
14854 SetUInt32Value(PLAYER_BYTES_3
, (fields
[49].GetUInt16() & 0xFFFE) | fields
[5].GetUInt8());
14855 SetUInt32Value(PLAYER_FLAGS
, fields
[11].GetUInt32());
14856 SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX
, fields
[48].GetInt32());
14858 SetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES
, fields
[47].GetUInt64());
14860 SetUInt32Value(PLAYER_AMMO_ID
, fields
[62].GetUInt32());
14861 SetByteValue(PLAYER_FIELD_BYTES
, 2, fields
[64].GetUInt8());
14866 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14867 for(uint8 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
14869 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2), 0 );
14870 SetVisibleItemSlot(slot
, NULL
);
14874 delete m_items
[slot
];
14875 m_items
[slot
] = NULL
;
14879 sLog
.outDebug("Load Basic value of player %s is: ", m_name
.c_str());
14882 //Need to call it to initialize m_team (m_team can be calculated from race)
14883 //Other way is to saves m_team into characters table.
14884 setFactionForRace(getRace());
14887 // load home bind and check in same time class/race pair, it used later for restore broken positions
14888 if(!_LoadHomeBind(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND
)))
14894 InitPrimaryProfessions(); // to max set before any spell loaded
14896 // init saved position, and fix it later if problematic
14897 uint32 transGUID
= fields
[30].GetUInt32();
14898 Relocate(fields
[12].GetFloat(),fields
[13].GetFloat(),fields
[14].GetFloat(),fields
[16].GetFloat());
14899 SetLocationMapId(fields
[15].GetUInt32());
14901 uint32 difficulty
= fields
[38].GetUInt32();
14902 if(difficulty
>= MAX_DUNGEON_DIFFICULTY
)
14903 difficulty
= DUNGEON_DIFFICULTY_NORMAL
;
14904 SetDungeonDifficulty(Difficulty(difficulty
)); // may be changed in _LoadGroup
14906 _LoadGroup(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP
));
14908 _LoadArenaTeamInfo(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO
));
14910 uint32 arena_currency
= fields
[39].GetUInt32();
14911 if (arena_currency
> sWorld
.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS
))
14912 arena_currency
= sWorld
.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS
);
14914 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, arena_currency
);
14916 // check arena teams integrity
14917 for(uint32 arena_slot
= 0; arena_slot
< MAX_ARENA_SLOT
; ++arena_slot
)
14919 uint32 arena_team_id
= GetArenaTeamId(arena_slot
);
14923 if(ArenaTeam
* at
= sObjectMgr
.GetArenaTeamById(arena_team_id
))
14924 if(at
->HaveMember(GetGUID()))
14927 // arena team not exist or not member, cleanup fields
14928 for(int j
= 0; j
< ARENA_TEAM_END
; ++j
)
14929 SetArenaTeamInfoField(arena_slot
, ArenaTeamInfoType(j
), 0);
14932 uint32 honor_currency
= fields
[40].GetUInt32();
14933 if (honor_currency
> sWorld
.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS
))
14934 honor_currency
= sWorld
.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS
);
14935 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, honor_currency
);
14937 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, fields
[41].GetUInt32());
14938 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, fields
[42].GetUInt32());
14939 SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, fields
[43].GetUInt32());
14940 SetUInt16Value(PLAYER_FIELD_KILLS
, 0, fields
[44].GetUInt16());
14941 SetUInt16Value(PLAYER_FIELD_KILLS
, 1, fields
[45].GetUInt16());
14943 _LoadBoundInstances(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES
));
14945 if(!IsPositionValid())
14947 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());
14948 RelocateToHomebind();
14952 m_movementInfo
.SetTransportData(0, 0.0f
, 0.0f
, 0.0f
, 0.0f
, 0, -1);
14955 _LoadBGData(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADBGDATA
));
14957 if(m_bgData
.bgInstanceID
) //saved in BattleGround
14959 BattleGround
*currentBg
= sBattleGroundMgr
.GetBattleGround(m_bgData
.bgInstanceID
, BATTLEGROUND_TYPE_NONE
);
14961 bool player_at_bg
= currentBg
&& currentBg
->IsPlayerInBattleGround(GetGUID());
14963 if(player_at_bg
&& currentBg
->GetStatus() != STATUS_WAIT_LEAVE
)
14965 BattleGroundQueueTypeId bgQueueTypeId
= BattleGroundMgr::BGQueueTypeId(currentBg
->GetTypeID(), currentBg
->GetArenaType());
14966 AddBattleGroundQueueId(bgQueueTypeId
);
14968 m_bgData
.bgTypeID
= currentBg
->GetTypeID();
14970 //join player to battleground group
14971 currentBg
->EventPlayerLoggedIn(this, GetGUID());
14972 currentBg
->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), m_bgData
.bgTeam
);
14974 SetInviteForBattleGroundQueueType(bgQueueTypeId
,currentBg
->GetInstanceID());
14980 currentBg
->RemovePlayerAtLeave(GetGUID(), false, true);
14982 // move to bg enter point
14983 const WorldLocation
& _loc
= GetBattleGroundEntryPoint();
14984 SetLocationMapId(_loc
.mapid
);
14985 Relocate(_loc
.coord_x
, _loc
.coord_y
, _loc
.coord_z
, _loc
.orientation
);
14987 // We are not in BG anymore
14988 m_bgData
.bgInstanceID
= 0;
14993 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(GetMapId());
14994 // if server restart after player save in BG or area
14995 // player can have current coordinates in to BG/Arena map, fix this
14996 if(!mapEntry
|| mapEntry
->IsBattleGroundOrArena())
14998 const WorldLocation
& _loc
= GetBattleGroundEntryPoint();
14999 SetLocationMapId(_loc
.mapid
);
15000 Relocate(_loc
.coord_x
, _loc
.coord_y
, _loc
.coord_z
, _loc
.orientation
);
15004 if (transGUID
!= 0)
15006 m_movementInfo
.SetTransportData(transGUID
, fields
[26].GetFloat(), fields
[27].GetFloat(), fields
[28].GetFloat(), fields
[29].GetFloat(), 0, -1);
15008 if( !MaNGOS::IsValidMapCoord(
15009 GetPositionX() + m_movementInfo
.GetTransportPos()->x
, GetPositionY() + m_movementInfo
.GetTransportPos()->y
,
15010 GetPositionZ() + m_movementInfo
.GetTransportPos()->z
, GetOrientation() + m_movementInfo
.GetTransportPos()->o
) ||
15011 // transport size limited
15012 m_movementInfo
.GetTransportPos()->x
> 50 || m_movementInfo
.GetTransportPos()->y
> 50 || m_movementInfo
.GetTransportPos()->z
> 50 )
15014 sLog
.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
15015 guid
, GetPositionX() + m_movementInfo
.GetTransportPos()->x
, GetPositionY() + m_movementInfo
.GetTransportPos()->y
,
15016 GetPositionZ() + m_movementInfo
.GetTransportPos()->z
, GetOrientation() + m_movementInfo
.GetTransportPos()->o
);
15018 RelocateToHomebind();
15020 m_movementInfo
.SetTransportData(0, 0.0f
, 0.0f
, 0.0f
, 0.0f
, 0, -1);
15026 if (transGUID
!= 0)
15028 for (MapManager::TransportSet::const_iterator iter
= sMapMgr
.m_Transports
.begin(); iter
!= sMapMgr
.m_Transports
.end(); ++iter
)
15030 if( (*iter
)->GetGUIDLow() == transGUID
)
15032 MapEntry
const* transMapEntry
= sMapStore
.LookupEntry((*iter
)->GetMapId());
15033 // client without expansion support
15034 if(GetSession()->Expansion() < transMapEntry
->Expansion())
15036 sLog
.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter
)->GetMapId());
15040 m_transport
= *iter
;
15041 m_transport
->AddPassenger(this);
15042 SetLocationMapId(m_transport
->GetMapId());
15049 sLog
.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
15052 RelocateToHomebind();
15054 m_movementInfo
.SetTransportData(0, 0.0f
, 0.0f
, 0.0f
, 0.0f
, 0, -1);
15059 else // not transport case
15061 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(GetMapId());
15062 // client without expansion support
15063 if(GetSession()->Expansion() < mapEntry
->Expansion())
15065 sLog
.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
15066 RelocateToHomebind();
15070 // NOW player must have valid map
15071 // load the player's map here if it's not already loaded
15072 SetMap(sMapMgr
.CreateMap(GetMapId(), this));
15074 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
15075 if(GetInstanceId() && !sInstanceSaveMgr
.GetInstanceSave(GetInstanceId()))
15077 AreaTrigger
const* at
= sObjectMgr
.GetMapEntranceTrigger(GetMapId());
15079 Relocate(at
->target_X
, at
->target_Y
, at
->target_Z
, at
->target_Orientation
);
15081 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());
15084 SaveRecallPosition();
15086 time_t now
= time(NULL
);
15087 time_t logoutTime
= time_t(fields
[22].GetUInt64());
15089 // since last logout (in seconds)
15090 uint32 time_diff
= uint32(now
- logoutTime
);
15092 // set value, including drunk invisibility detection
15093 // calculate sobering. after 15 minutes logged out, the player will be sober again
15095 if(time_diff
> 15*MINUTE
)
15098 soberFactor
= 1-time_diff
/(15.0f
*MINUTE
);
15099 uint16 newDrunkenValue
= uint16(soberFactor
*(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFE));
15100 SetDrunkValue(newDrunkenValue
);
15102 m_cinematic
= fields
[18].GetUInt32();
15103 m_Played_time
[PLAYED_TIME_TOTAL
]= fields
[19].GetUInt32();
15104 m_Played_time
[PLAYED_TIME_LEVEL
]= fields
[20].GetUInt32();
15106 m_resetTalentsCost
= fields
[24].GetUInt32();
15107 m_resetTalentsTime
= time_t(fields
[25].GetUInt64());
15109 // reserve some flags
15110 uint32 old_safe_flags
= GetUInt32Value(PLAYER_FLAGS
) & ( PLAYER_FLAGS_HIDE_CLOAK
| PLAYER_FLAGS_HIDE_HELM
);
15112 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
) )
15113 SetUInt32Value(PLAYER_FLAGS
, 0 | old_safe_flags
);
15115 m_taxi
.LoadTaxiMask( fields
[17].GetString() ); // must be before InitTaxiNodesForLevel
15117 uint32 extraflags
= fields
[31].GetUInt32();
15119 m_stableSlots
= fields
[32].GetUInt32();
15120 if(m_stableSlots
> MAX_PET_STABLES
)
15122 sLog
.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES
,uint32(m_stableSlots
));
15123 m_stableSlots
= MAX_PET_STABLES
;
15126 m_atLoginFlags
= fields
[33].GetUInt32();
15129 // Update Honor kills data
15130 m_lastHonorUpdateTime
= logoutTime
;
15131 UpdateHonorFields();
15133 m_deathExpireTime
= (time_t)fields
[36].GetUInt64();
15134 if(m_deathExpireTime
> now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
)
15135 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
-1;
15137 std::string taxi_nodes
= fields
[37].GetCppString();
15139 // clear channel spell data (if saved at channel spell casting)
15140 SetChannelObjectGUID(0);
15141 SetUInt32Value(UNIT_CHANNEL_SPELL
,0);
15143 // clear charm/summon related fields
15147 SetChannelObjectGUID(0);
15152 // reset some aura modifiers before aura apply
15153 SetFarSightGUID(0);
15154 SetUInt32Value(PLAYER_TRACK_CREATURES
, 0 );
15155 SetUInt32Value(PLAYER_TRACK_RESOURCES
, 0 );
15157 // cleanup aura list explicitly before skill load wher some spells can be applied
15160 // make sure the unit is considered out of combat for proper loading
15163 // make sure the unit is considered not in duel for proper loading
15164 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
15165 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
15167 // reset stats before loading any modifiers
15168 InitStatsForLevel();
15169 InitGlyphsForLevel();
15170 InitTaxiNodesForLevel();
15173 // rest bonus can only be calculated after InitStatsForLevel()
15174 m_rest_bonus
= fields
[21].GetFloat();
15178 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
15179 float bubble0
= 0.031f
;
15180 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
15181 float bubble1
= 0.125f
;
15182 float bubble
= fields
[23].GetUInt32() > 0
15183 ? bubble1
*sWorld
.getConfig(CONFIG_FLOAT_RATE_REST_OFFLINE_IN_TAVERN_OR_CITY
)
15184 : bubble0
*sWorld
.getConfig(CONFIG_FLOAT_RATE_REST_OFFLINE_IN_WILDERNESS
);
15186 SetRestBonus(GetRestBonus()+ time_diff
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
15189 // load skills after InitStatsForLevel because it triggering aura apply also
15190 _LoadSkills(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSKILLS
));
15192 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
15195 _LoadMails(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILS
));
15196 _LoadMailedItems(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILEDITEMS
));
15197 UpdateNextMailTimeAndUnreads();
15199 m_specsCount
= fields
[58].GetUInt8();
15200 m_activeSpec
= fields
[59].GetUInt8();
15202 _LoadGlyphs(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADGLYPHS
));
15204 _LoadAuras(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS
), time_diff
);
15207 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
15208 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
15209 m_deathState
= DEAD
;
15211 _LoadSpells(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS
));
15213 // after spell load, learn rewarded spell if need also
15214 _LoadQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS
));
15215 _LoadDailyQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS
));
15216 _LoadWeeklyQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADWEKLYQUESTSTATUS
));
15218 _LoadTalents(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADTALENTS
));
15220 // after spell and quest load
15221 InitTalentForLevel();
15222 learnDefaultSpells();
15224 // must be before inventory (some items required reputation check)
15225 m_reputationMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION
));
15227 _LoadInventory(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY
), time_diff
);
15229 // update items with duration and realtime
15230 UpdateItemDuration(time_diff
, true);
15232 _LoadActions(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS
));
15234 m_social
= sSocialMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST
), GetGUIDLow());
15236 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
15237 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
15238 uint32 curTitle
= fields
[46].GetUInt32();
15239 if (curTitle
&& !HasTitle(curTitle
))
15242 SetUInt32Value(PLAYER_CHOSEN_TITLE
, curTitle
);
15244 // Not finish taxi flight path
15245 if(m_bgData
.HasTaxiPath())
15247 m_taxi
.ClearTaxiDestinations();
15248 for (int i
= 0; i
< 2; ++i
)
15249 m_taxi
.AddTaxiDestination(m_bgData
.taxiPath
[i
]);
15251 else if(!m_taxi
.LoadTaxiDestinationsFromString(taxi_nodes
,GetTeam()))
15253 // problems with taxi path loading
15254 TaxiNodesEntry
const* nodeEntry
= NULL
;
15255 if(uint32 node_id
= m_taxi
.GetTaxiSource())
15256 nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
15258 if(!nodeEntry
) // don't know taxi start node, to homebind
15260 sLog
.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
15261 RelocateToHomebind();
15263 else // have start node, to it
15265 sLog
.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
15266 SetLocationMapId(nodeEntry
->map_id
);
15267 Relocate(nodeEntry
->x
, nodeEntry
->y
, nodeEntry
->z
,0.0f
);
15270 //we can be relocated from taxi and still have an outdated Map pointer!
15271 //so we need to get a new Map pointer!
15272 SetMap(sMapMgr
.CreateMap(GetMapId(), this));
15273 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
15275 m_taxi
.ClearTaxiDestinations();
15278 if(uint32 node_id
= m_taxi
.GetTaxiSource())
15280 // save source node as recall coord to prevent recall and fall from sky
15281 TaxiNodesEntry
const* nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
15282 ASSERT(nodeEntry
); // checked in m_taxi.LoadTaxiDestinationsFromString
15283 m_recallMap
= nodeEntry
->map_id
;
15284 m_recallX
= nodeEntry
->x
;
15285 m_recallY
= nodeEntry
->y
;
15286 m_recallZ
= nodeEntry
->z
;
15288 // flight will started later
15291 // has to be called after last Relocate() in Player::LoadFromDB
15292 SetFallInformation(0, GetPositionZ());
15294 _LoadSpellCooldowns(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS
));
15296 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
15297 // Do now before stats re-calculation cleanup for ghost state unexpected auras
15299 RemoveAllAurasOnDeath();
15301 //apply all stat bonuses from items and auras
15302 SetCanModifyStats(true);
15305 // restore remembered power/health values (but not more max values)
15306 uint32 savedhealth
= fields
[50].GetUInt32();
15307 SetHealth(savedhealth
> GetMaxHealth() ? GetMaxHealth() : savedhealth
);
15308 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
15310 uint32 savedpower
= fields
[51+i
].GetUInt32();
15311 SetPower(Powers(i
),savedpower
> GetMaxPower(Powers(i
)) ? GetMaxPower(Powers(i
)) : savedpower
);
15314 sLog
.outDebug("The value of player %s after load item and aura is: ", m_name
.c_str());
15321 if(GetSession()->GetSecurity() > SEC_PLAYER
)
15323 switch(sWorld
.getConfig(CONFIG_UINT32_GM_LOGIN_STATE
))
15326 case 0: break; // disable
15327 case 1: SetGameMaster(true); break; // enable
15328 case 2: // save state
15329 if(extraflags
& PLAYER_EXTRA_GM_ON
)
15330 SetGameMaster(true);
15334 switch(sWorld
.getConfig(CONFIG_UINT32_GM_VISIBLE_STATE
))
15337 case 0: SetGMVisible(false); break; // invisible
15338 case 1: break; // visible
15339 case 2: // save state
15340 if(extraflags
& PLAYER_EXTRA_GM_INVISIBLE
)
15341 SetGMVisible(false);
15345 switch(sWorld
.getConfig(CONFIG_UINT32_GM_ACCEPT_TICKETS
))
15348 case 0: break; // disable
15349 case 1: SetAcceptTicket(true); break; // enable
15350 case 2: // save state
15351 if(extraflags
& PLAYER_EXTRA_GM_ACCEPT_TICKETS
)
15352 SetAcceptTicket(true);
15356 switch(sWorld
.getConfig(CONFIG_UINT32_GM_CHAT
))
15359 case 0: break; // disable
15360 case 1: SetGMChat(true); break; // enable
15361 case 2: // save state
15362 if(extraflags
& PLAYER_EXTRA_GM_CHAT
)
15367 switch(sWorld
.getConfig(CONFIG_UINT32_GM_WISPERING_TO
))
15370 case 0: break; // disable
15371 case 1: SetAcceptWhispers(true); break; // enable
15372 case 2: // save state
15373 if(extraflags
& PLAYER_EXTRA_ACCEPT_WHISPERS
)
15374 SetAcceptWhispers(true);
15379 _LoadDeclinedNames(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES
));
15381 m_achievementMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS
));
15382 m_achievementMgr
.CheckAllAchievementCriteria();
15384 _LoadEquipmentSets(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS
));
15389 bool Player::isAllowedToLoot(Creature
* creature
)
15391 if(Player
* recipient
= creature
->GetLootRecipient())
15393 if (recipient
== this)
15395 if( Group
* otherGroup
= recipient
->GetGroup())
15397 Group
* thisGroup
= GetGroup();
15400 return thisGroup
== otherGroup
;
15405 // prevent other players from looting if the recipient got disconnected
15406 return !creature
->hasLootRecipient();
15409 void Player::_LoadActions(QueryResult
*result
)
15411 for(int i
= 0; i
< MAX_TALENT_SPEC_COUNT
; ++i
)
15412 m_actionButtons
[i
].clear();
15414 //QueryResult *result = CharacterDatabase.PQuery("SELECT spec, button,action,type FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
15420 Field
*fields
= result
->Fetch();
15422 uint8 spec
= fields
[0].GetUInt8();
15423 uint8 button
= fields
[1].GetUInt8();
15424 uint32 action
= fields
[2].GetUInt32();
15425 uint8 type
= fields
[3].GetUInt8();
15427 if(ActionButton
* ab
= addActionButton(spec
, button
, action
, type
))
15428 ab
->uState
= ACTIONBUTTON_UNCHANGED
;
15431 sLog
.outError( " ...at loading, and will deleted in DB also");
15433 // Will deleted in DB at next save (it can create data until save but marked as deleted)
15434 m_actionButtons
[spec
][button
].uState
= ACTIONBUTTON_DELETED
;
15437 while( result
->NextRow() );
15443 void Player::_LoadAuras(QueryResult
*result
, uint32 timediff
)
15445 //RemoveAllAuras(); -- some spells casted before aura load, for example in LoadSkills, aura list explcitly cleaned early
15447 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15453 Field
*fields
= result
->Fetch();
15454 uint64 caster_guid
= fields
[0].GetUInt64();
15455 uint32 spellid
= fields
[1].GetUInt32();
15456 SpellEffectIndex effindex
= SpellEffectIndex(fields
[2].GetUInt32());
15457 uint32 stackcount
= fields
[3].GetUInt32();
15458 int32 damage
= fields
[4].GetInt32();
15459 int32 maxduration
= fields
[5].GetInt32();
15460 int32 remaintime
= fields
[6].GetInt32();
15461 int32 remaincharges
= fields
[7].GetInt32();
15463 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellid
);
15466 sLog
.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid
,effindex
);
15470 if (effindex
>= MAX_EFFECT_INDEX
)
15472 sLog
.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid
,effindex
);
15476 // negative effects should continue counting down after logout
15477 if (remaintime
!= -1 && !IsPositiveEffect(spellid
, effindex
))
15479 if (remaintime
/IN_MILLISECONDS
<= int32(timediff
))
15482 remaintime
-= timediff
*IN_MILLISECONDS
;
15485 // prevent wrong values of remaincharges
15486 if (spellproto
->procCharges
)
15488 if (remaincharges
<= 0 || remaincharges
> (int32
)spellproto
->procCharges
)
15489 remaincharges
= spellproto
->procCharges
;
15495 for(uint32 i
= 0; i
< stackcount
; ++i
)
15497 Aura
* aura
= CreateAura(spellproto
, effindex
, NULL
, this, NULL
);
15499 damage
= aura
->GetModifier()->m_amount
;
15501 // reset stolen single target auras
15502 if (caster_guid
!= GetGUID() && aura
->IsSingleTarget())
15503 aura
->SetIsSingleTarget(false);
15505 aura
->SetLoadedState(caster_guid
,damage
,maxduration
,remaintime
,remaincharges
);
15507 sLog
.outDetail("Added aura spellid %u, effect %u", spellproto
->Id
, effindex
);
15510 while( result
->NextRow() );
15515 if(getClass() == CLASS_WARRIOR
&& !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT
))
15516 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
15519 void Player::_LoadGlyphs(QueryResult
*result
)
15525 // "SELECT spec, slot, glyph FROM character_glyphs WHERE guid='%u'"
15529 Field
*fields
= result
->Fetch();
15530 uint8 spec
= fields
[0].GetUInt8();
15531 uint8 slot
= fields
[1].GetUInt8();
15532 uint32 glyph
= fields
[2].GetUInt32();
15534 GlyphPropertiesEntry
const *gp
= sGlyphPropertiesStore
.LookupEntry(glyph
);
15537 sLog
.outError("Player %s has not existing glyph entry %u on index %u, spec %u", m_name
.c_str(), glyph
, slot
, spec
);
15541 GlyphSlotEntry
const *gs
= sGlyphSlotStore
.LookupEntry(GetGlyphSlot(slot
));
15544 sLog
.outError("Player %s has not existing glyph slot entry %u on index %u, spec %u", m_name
.c_str(), GetGlyphSlot(slot
), slot
, spec
);
15548 if(gp
->TypeFlags
!= gs
->TypeFlags
)
15550 sLog
.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name
.c_str(), gp
->TypeFlags
, gs
->TypeFlags
);
15554 m_glyphs
[spec
][slot
].id
= glyph
;
15556 } while( result
->NextRow() );
15563 void Player::LoadCorpse()
15567 sObjectAccessor
.ConvertCorpseForPlayer(GetGUID());
15571 if(Corpse
*corpse
= GetCorpse())
15573 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, corpse
&& !sMapStore
.LookupEntry(corpse
->GetMapId())->Instanceable() );
15577 //Prevent Dead Player login without corpse
15578 ResurrectPlayer(0.5f
);
15583 void Player::_LoadInventory(QueryResult
*result
, uint32 timediff
)
15585 //QueryResult *result = CharacterDatabase.PQuery("SELECT data,text,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());
15586 std::map
<uint64
, Bag
*> bagMap
; // fast guid lookup for bags
15587 //NOTE: the "order by `bag`" is important because it makes sure
15588 //the bagMap is filled before items in the bags are loaded
15589 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
15590 //expected to be equipped before offhand items (TODO: fixme)
15592 uint32 zone
= GetZoneId();
15596 std::list
<Item
*> problematicItems
;
15598 // prevent items from being added to the queue when stored
15599 m_itemUpdateQueueBlocked
= true;
15602 Field
*fields
= result
->Fetch();
15603 uint32 bag_guid
= fields
[2].GetUInt32();
15604 uint8 slot
= fields
[3].GetUInt8();
15605 uint32 item_guid
= fields
[4].GetUInt32();
15606 uint32 item_id
= fields
[5].GetUInt32();
15608 ItemPrototype
const * proto
= ObjectMgr::GetItemPrototype(item_id
);
15612 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
15613 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid
);
15614 sLog
.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id
);
15618 Item
*item
= NewItemOrBag(proto
);
15620 if(!item
->LoadFromDB(item_guid
, GetGUID(), result
))
15622 sLog
.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id
);
15623 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
15624 item
->FSetState(ITEM_REMOVED
);
15625 item
->SaveToDB(); // it also deletes item object !
15629 // not allow have in alive state item limited to another map/zone
15630 if(isAlive() && item
->IsLimitedToAnotherMapOrZone(GetMapId(),zone
) )
15632 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
15633 item
->FSetState(ITEM_REMOVED
);
15634 item
->SaveToDB(); // it also deletes item object !
15638 // "Conjured items disappear if you are logged out for more than 15 minutes"
15639 if (timediff
> 15*MINUTE
&& item
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_CONJURED
))
15641 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
15642 item
->FSetState(ITEM_REMOVED
);
15643 item
->SaveToDB(); // it also deletes item object !
15647 bool success
= true;
15649 // the item/bag is not in a bag
15652 item
->SetContainer( NULL
);
15653 item
->SetSlot(slot
);
15655 if( IsInventoryPos( INVENTORY_SLOT_BAG_0
, slot
) )
15657 ItemPosCountVec dest
;
15658 if( CanStoreItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false ) == EQUIP_ERR_OK
)
15659 item
= StoreItem(dest
, item
, true);
15663 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0
, slot
) )
15666 if( CanEquipItem( slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
15667 QuickEquipItem(dest
, item
);
15671 else if( IsBankPos( INVENTORY_SLOT_BAG_0
, slot
) )
15673 ItemPosCountVec dest
;
15674 if( CanBankItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
15675 item
= BankItem(dest
, item
, true);
15682 // store bags that may contain items in them
15683 if(item
->IsBag() && IsBagPos(item
->GetPos()))
15684 bagMap
[item_guid
] = (Bag
*)item
;
15687 // the item/bag in a bag
15690 item
->SetSlot(NULL_SLOT
);
15691 // the item is in a bag, find the bag
15692 std::map
<uint64
, Bag
*>::const_iterator itr
= bagMap
.find(bag_guid
);
15693 if(itr
!= bagMap
.end() && slot
< itr
->second
->GetBagSize())
15695 ItemPosCountVec dest
;
15696 if( CanStoreItem( itr
->second
->GetSlot(), slot
, dest
, item
, false ) == EQUIP_ERR_OK
)
15697 item
= StoreItem(dest
, item
, true);
15705 // item's state may have changed after stored
15708 item
->SetState(ITEM_UNCHANGED
, this);
15710 // recharged mana gem
15711 if (timediff
> 15*MINUTE
&& proto
->ItemLimitCategory
==ITEM_LIMIT_CATEGORY_MANA_GEM
)
15712 item
->RestoreCharges();
15716 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
);
15717 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
15718 problematicItems
.push_back(item
);
15720 } while (result
->NextRow());
15723 m_itemUpdateQueueBlocked
= false;
15725 // send by mail problematic items
15726 while(!problematicItems
.empty())
15728 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
15731 MailDraft
draft(subject
, "There's were problems with equipping item(s).");
15733 for(int i
= 0; !problematicItems
.empty() && i
< MAX_MAIL_ITEMS
; ++i
)
15735 Item
* item
= problematicItems
.front();
15736 problematicItems
.pop_front();
15738 draft
.AddItem(item
);
15741 draft
.SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM
));
15745 _ApplyAllItemMods();
15748 // load mailed item which should receive current player
15749 void Player::_LoadMailedItems(QueryResult
*result
)
15751 // data needs to be at first place for Item::LoadFromDB
15753 // "SELECT data, text, mail_id, item_guid, item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE receiver = '%u'", GUID_LOPART(m_guid)
15759 Field
*fields
= result
->Fetch();
15760 uint32 mail_id
= fields
[2].GetUInt32();
15761 uint32 item_guid_low
= fields
[3].GetUInt32();
15762 uint32 item_template
= fields
[4].GetUInt32();
15764 Mail
* mail
= GetMail(mail_id
);
15767 mail
->AddItem(item_guid_low
, item_template
);
15769 ItemPrototype
const *proto
= ObjectMgr::GetItemPrototype(item_template
);
15773 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
);
15774 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
15775 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low
);
15779 Item
*item
= NewItemOrBag(proto
);
15781 if(!item
->LoadFromDB(item_guid_low
, 0, result
))
15783 sLog
.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail
->messageID
, item_guid_low
);
15784 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
15785 item
->FSetState(ITEM_REMOVED
);
15786 item
->SaveToDB(); // it also deletes item object !
15791 } while (result
->NextRow());
15796 void Player::_LoadMails(QueryResult
*result
)
15799 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13
15800 //"SELECT id,messageType,sender,receiver,subject,body,has_items,expire_time,deliver_time,money,cod,checked,stationery,mailTemplateId FROM mail WHERE receiver = '%u' ORDER BY id DESC", GetGUIDLow()
15806 Field
*fields
= result
->Fetch();
15807 Mail
*m
= new Mail
;
15808 m
->messageID
= fields
[0].GetUInt32();
15809 m
->messageType
= fields
[1].GetUInt8();
15810 m
->sender
= fields
[2].GetUInt32();
15811 m
->receiver
= fields
[3].GetUInt32();
15812 m
->subject
= fields
[4].GetCppString();
15813 m
->body
= fields
[5].GetCppString();
15814 bool has_items
= fields
[6].GetBool();
15815 m
->expire_time
= (time_t)fields
[7].GetUInt64();
15816 m
->deliver_time
= (time_t)fields
[8].GetUInt64();
15817 m
->money
= fields
[9].GetUInt32();
15818 m
->COD
= fields
[10].GetUInt32();
15819 m
->checked
= fields
[11].GetUInt32();
15820 m
->stationery
= fields
[12].GetUInt8();
15821 m
->mailTemplateId
= fields
[13].GetInt16();
15823 if(m
->mailTemplateId
&& !sMailTemplateStore
.LookupEntry(m
->mailTemplateId
))
15825 sLog
.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m
->messageID
, m
->mailTemplateId
);
15826 m
->mailTemplateId
= 0;
15829 m
->state
= MAIL_STATE_UNCHANGED
;
15831 m_mail
.push_back(m
);
15832 } while( result
->NextRow() );
15836 void Player::LoadPet()
15838 // fixme: the pet should still be loaded if the player is not in world
15839 // just not added to the map
15842 Pet
*pet
= new Pet
;
15843 if(!pet
->LoadPetFromDB(this, 0, 0, true))
15848 void Player::_LoadQuestStatus(QueryResult
*result
)
15850 mQuestStatus
.clear();
15854 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15855 //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());
15861 Field
*fields
= result
->Fetch();
15863 uint32 quest_id
= fields
[0].GetUInt32();
15864 // used to be new, no delete?
15865 Quest
const* pQuest
= sObjectMgr
.GetQuestTemplate(quest_id
);
15869 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
15871 uint32 qstatus
= fields
[1].GetUInt32();
15872 if(qstatus
< MAX_QUEST_STATUS
)
15873 questStatusData
.m_status
= QuestStatus(qstatus
);
15876 questStatusData
.m_status
= QUEST_STATUS_NONE
;
15877 sLog
.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id
,qstatus
);
15880 questStatusData
.m_rewarded
= ( fields
[2].GetUInt8() > 0 );
15881 questStatusData
.m_explored
= ( fields
[3].GetUInt8() > 0 );
15883 time_t quest_time
= time_t(fields
[4].GetUInt64());
15885 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && !GetQuestRewardStatus(quest_id
) && questStatusData
.m_status
!= QUEST_STATUS_NONE
)
15887 AddTimedQuest( quest_id
);
15889 if (quest_time
<= sWorld
.GetGameTime())
15890 questStatusData
.m_timer
= 1;
15892 questStatusData
.m_timer
= uint32(quest_time
- sWorld
.GetGameTime()) * IN_MILLISECONDS
;
15897 questStatusData
.m_creatureOrGOcount
[0] = fields
[5].GetUInt32();
15898 questStatusData
.m_creatureOrGOcount
[1] = fields
[6].GetUInt32();
15899 questStatusData
.m_creatureOrGOcount
[2] = fields
[7].GetUInt32();
15900 questStatusData
.m_creatureOrGOcount
[3] = fields
[8].GetUInt32();
15901 questStatusData
.m_itemcount
[0] = fields
[9].GetUInt32();
15902 questStatusData
.m_itemcount
[1] = fields
[10].GetUInt32();
15903 questStatusData
.m_itemcount
[2] = fields
[11].GetUInt32();
15904 questStatusData
.m_itemcount
[3] = fields
[12].GetUInt32();
15906 questStatusData
.uState
= QUEST_UNCHANGED
;
15908 // add to quest log
15909 if (slot
< MAX_QUEST_LOG_SIZE
&&
15910 ((questStatusData
.m_status
== QUEST_STATUS_INCOMPLETE
||
15911 questStatusData
.m_status
== QUEST_STATUS_COMPLETE
||
15912 questStatusData
.m_status
== QUEST_STATUS_FAILED
) &&
15913 (!questStatusData
.m_rewarded
|| pQuest
->IsRepeatable())))
15915 SetQuestSlot(slot
, quest_id
, uint32(quest_time
));
15917 if (questStatusData
.m_status
== QUEST_STATUS_COMPLETE
)
15918 SetQuestSlotState(slot
, QUEST_STATE_COMPLETE
);
15920 if (questStatusData
.m_status
== QUEST_STATUS_FAILED
)
15921 SetQuestSlotState(slot
, QUEST_STATE_FAIL
);
15923 for(uint8 idx
= 0; idx
< QUEST_OBJECTIVES_COUNT
; ++idx
)
15924 if(questStatusData
.m_creatureOrGOcount
[idx
])
15925 SetQuestSlotCounter(slot
, idx
, questStatusData
.m_creatureOrGOcount
[idx
]);
15930 if(questStatusData
.m_rewarded
)
15932 // learn rewarded spell if unknown
15933 learnQuestRewardedSpells(pQuest
);
15935 // set rewarded title if any
15936 if(pQuest
->GetCharTitleId())
15938 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
15939 SetTitle(titleEntry
);
15942 if(pQuest
->GetBonusTalents())
15943 m_questRewardTalentCount
+= pQuest
->GetBonusTalents();
15946 sLog
.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData
.m_status
, quest_id
, GetGUIDLow());
15949 while( result
->NextRow() );
15954 // clear quest log tail
15955 for ( uint16 i
= slot
; i
< MAX_QUEST_LOG_SIZE
; ++i
)
15956 SetQuestSlot(i
, 0);
15959 void Player::_LoadDailyQuestStatus(QueryResult
*result
)
15961 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
15962 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
15964 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15968 uint32 quest_daily_idx
= 0;
15972 if(quest_daily_idx
>= PLAYER_MAX_DAILY_QUESTS
) // max amount with exist data in query
15974 sLog
.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15978 Field
*fields
= result
->Fetch();
15980 uint32 quest_id
= fields
[0].GetUInt32();
15982 Quest
const* pQuest
= sObjectMgr
.GetQuestTemplate(quest_id
);
15986 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
15989 sLog
.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id
, GetGUIDLow());
15991 while( result
->NextRow() );
15996 m_DailyQuestChanged
= false;
15999 void Player::_LoadWeeklyQuestStatus(QueryResult
*result
)
16001 m_weeklyquests
.clear();
16003 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest FROM character_queststatus_weekly WHERE guid = '%u'", GetGUIDLow());
16009 Field
*fields
= result
->Fetch();
16011 uint32 quest_id
= fields
[0].GetUInt32();
16013 Quest
const* pQuest
= sObjectMgr
.GetQuestTemplate(quest_id
);
16017 m_weeklyquests
.insert(quest_id
);
16019 sLog
.outDebug("Weekly quest {%u} cooldown for player (GUID: %u)", quest_id
, GetGUIDLow());
16021 while( result
->NextRow() );
16025 m_WeeklyQuestChanged
= false;
16028 void Player::_LoadSpells(QueryResult
*result
)
16030 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
16036 Field
*fields
= result
->Fetch();
16038 uint32 spell_id
= fields
[0].GetUInt32();
16040 // skip talents & drop unneeded data
16041 if(GetTalentSpellPos(spell_id
))
16043 sLog
.outError("Player::_LoadSpells: Player (GUID: %u) has talent spell in character_spell, removing it.", GetGUIDLow(), spell_id
);
16044 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'", spell_id
);
16048 addSpell(spell_id
, fields
[1].GetBool(), false, false, fields
[2].GetBool());
16050 while( result
->NextRow() );
16056 void Player::_LoadTalents(QueryResult
*result
)
16058 //QueryResult *result = CharacterDatabase.PQuery("SELECT talent_id, current_rank, spec FROM character_talent WHERE guid = '%u'",GetGUIDLow());
16063 Field
*fields
= result
->Fetch();
16065 uint32 talent_id
= fields
[0].GetUInt32();
16066 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talent_id
);
16070 sLog
.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talent_id: %u , this talent will be deleted from character_talent",GetGUIDLow(), talent_id
);
16071 CharacterDatabase
.PExecute("DELETE FROM character_talent WHERE talent_id = '%u'", talent_id
);
16075 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
16077 if (!talentTabInfo
)
16079 sLog
.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talentTabInfo: %u for talentID: %u , this talent will be deleted from character_talent",GetGUIDLow(), talentInfo
->TalentTab
, talentInfo
->TalentID
);
16080 CharacterDatabase
.PExecute("DELETE FROM character_talent WHERE talent_id = '%u'", talent_id
);
16084 // prevent load talent for different class (cheating)
16085 if ((getClassMask() & talentTabInfo
->ClassMask
) == 0)
16087 sLog
.outError("Player::_LoadTalents:Player (GUID: %u) has talent with ClassMask: %u , but Player's ClassMask is: %u , talentID: %u , this talent will be deleted from character_talent",GetGUIDLow(), talentTabInfo
->ClassMask
, getClassMask() ,talentInfo
->TalentID
);
16088 CharacterDatabase
.PExecute("DELETE FROM character_talent WHERE guid = '%u' AND talent_id = '%u'", GetGUIDLow(), talent_id
);
16092 uint32 currentRank
= fields
[1].GetUInt32();
16094 if (currentRank
> MAX_TALENT_RANK
|| talentInfo
->RankID
[currentRank
] == 0)
16096 sLog
.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talent rank: %u , talentID: %u , this talent will be deleted from character_talent",GetGUIDLow(), currentRank
, talentInfo
->TalentID
);
16097 CharacterDatabase
.PExecute("DELETE FROM character_talent WHERE guid = '%u' AND talent_id = '%u'", GetGUIDLow(), talent_id
);
16101 uint32 spec
= fields
[2].GetUInt32();
16103 if (spec
> MAX_TALENT_SPEC_COUNT
)
16105 sLog
.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talent spec: %u, spec will be deleted from character_talent", GetGUIDLow(), spec
);
16106 CharacterDatabase
.PExecute("DELETE FROM character_talent WHERE spec = '%u' ", spec
);
16110 if (spec
>= m_specsCount
)
16112 sLog
.outError("Player::_LoadTalents:Player (GUID: %u) has invalid talent spec: %u , this spec will be deleted from character_talent.", GetGUIDLow(), spec
);
16113 CharacterDatabase
.PExecute("DELETE FROM character_talent WHERE guid = '%u' AND spec = '%u' ", GetGUIDLow(), spec
);
16117 if (m_activeSpec
== spec
)
16118 addSpell(talentInfo
->RankID
[currentRank
], true,false,false,false);
16121 PlayerTalent talent
;
16122 talent
.currentRank
= currentRank
;
16123 talent
.m_talentEntry
= talentInfo
;
16124 talent
.state
= PLAYERSPELL_UNCHANGED
;
16125 m_talents
[spec
][talentInfo
->TalentID
] = talent
;
16128 while (result
->NextRow());
16132 void Player::_LoadGroup(QueryResult
*result
)
16134 //QueryResult *result = CharacterDatabase.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
16137 uint32 groupId
= (*result
)[0].GetUInt32();
16140 if (Group
* group
= sObjectMgr
.GetGroupById(groupId
))
16142 uint8 subgroup
= group
->GetMemberGroup(GetGUID());
16143 SetGroup(group
, subgroup
);
16144 if (getLevel() >= LEVELREQUIREMENT_HEROIC
)
16146 // the group leader may change the instance difficulty while the player is offline
16147 SetDungeonDifficulty(group
->GetDungeonDifficulty());
16148 SetRaidDifficulty(group
->GetRaidDifficulty());
16154 void Player::_LoadBoundInstances(QueryResult
*result
)
16156 for(uint8 i
= 0; i
< MAX_DIFFICULTY
; ++i
)
16157 m_boundInstances
[i
].clear();
16159 Group
*group
= GetGroup();
16161 //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));
16166 Field
*fields
= result
->Fetch();
16167 bool perm
= fields
[1].GetBool();
16168 uint32 mapId
= fields
[2].GetUInt32();
16169 uint32 instanceId
= fields
[0].GetUInt32();
16170 uint8 difficulty
= fields
[3].GetUInt8();
16172 time_t resetTime
= (time_t)fields
[4].GetUInt64();
16173 // the resettime for normal instances is only saved when the InstanceSave is unloaded
16174 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
16175 // and in that case it is not used
16177 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(mapId
);
16178 if(!mapEntry
|| !mapEntry
->IsDungeon())
16180 sLog
.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId
);
16181 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
16185 if(difficulty
>= MAX_DIFFICULTY
)
16187 sLog
.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty
, mapId
);
16188 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
16192 MapDifficulty
const* mapDiff
= GetMapDifficultyData(mapId
,Difficulty(difficulty
));
16195 sLog
.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty
, mapId
);
16196 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
16202 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
);
16203 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
16207 // since non permanent binds are always solo bind, they can always be reset
16208 InstanceSave
*save
= sInstanceSaveMgr
.AddInstanceSave(mapId
, instanceId
, Difficulty(difficulty
), resetTime
, !perm
, true);
16209 if(save
) BindToInstance(save
, perm
, true);
16210 } while(result
->NextRow());
16215 InstancePlayerBind
* Player::GetBoundInstance(uint32 mapid
, Difficulty difficulty
)
16217 // some instances only have one difficulty
16218 MapDifficulty
const* mapDiff
= GetMapDifficultyData(mapid
,difficulty
);
16222 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
16223 if(itr
!= m_boundInstances
[difficulty
].end())
16224 return &itr
->second
;
16229 void Player::UnbindInstance(uint32 mapid
, Difficulty difficulty
, bool unload
)
16231 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
16232 UnbindInstance(itr
, difficulty
, unload
);
16235 void Player::UnbindInstance(BoundInstancesMap::iterator
&itr
, Difficulty difficulty
, bool unload
)
16237 if(itr
!= m_boundInstances
[difficulty
].end())
16239 if(!unload
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr
->second
.save
->GetInstanceId());
16240 itr
->second
.save
->RemovePlayer(this); // save can become invalid
16241 m_boundInstances
[difficulty
].erase(itr
++);
16245 InstancePlayerBind
* Player::BindToInstance(InstanceSave
*save
, bool permanent
, bool load
)
16249 InstancePlayerBind
& bind
= m_boundInstances
[save
->GetDifficulty()][save
->GetMapId()];
16252 // update the save when the group kills a boss
16253 if(permanent
!= bind
.perm
|| save
!= bind
.save
)
16254 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());
16257 if(!load
) CharacterDatabase
.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save
->GetInstanceId(), permanent
);
16259 if(bind
.save
!= save
)
16261 if(bind
.save
) bind
.save
->RemovePlayer(this);
16262 save
->AddPlayer(this);
16265 if(permanent
) save
->SetCanReset(false);
16268 bind
.perm
= permanent
;
16269 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());
16276 void Player::SendRaidInfo()
16278 uint32 counter
= 0;
16280 WorldPacket
data(SMSG_RAID_INSTANCE_INFO
, 4);
16282 size_t p_counter
= data
.wpos();
16283 data
<< uint32(counter
); // placeholder
16285 time_t now
= time(NULL
);
16287 for(int i
= 0; i
< MAX_DIFFICULTY
; ++i
)
16289 for (BoundInstancesMap::const_iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
16291 if(itr
->second
.perm
)
16293 InstanceSave
*save
= itr
->second
.save
;
16294 data
<< uint32(save
->GetMapId()); // map id
16295 data
<< uint32(save
->GetDifficulty()); // difficulty
16296 data
<< uint64(save
->GetInstanceId()); // instance id
16297 data
<< uint8(1); // expired = 0
16298 data
<< uint8(0); // extended = 1
16299 data
<< uint32(save
->GetResetTime() - now
); // reset time
16304 data
.put
<uint32
>(p_counter
, counter
);
16305 GetSession()->SendPacket(&data
);
16309 - called on every successful teleportation to a map
16311 void Player::SendSavedInstances()
16313 bool hasBeenSaved
= false;
16316 for(uint8 i
= 0; i
< MAX_DIFFICULTY
; ++i
)
16318 for (BoundInstancesMap::const_iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
16320 if(itr
->second
.perm
) // only permanent binds are sent
16322 hasBeenSaved
= true;
16328 //Send opcode 811. true or false means, whether you have current raid/heroic instances
16329 data
.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP
);
16330 data
<< uint32(hasBeenSaved
);
16331 GetSession()->SendPacket(&data
);
16336 for(uint8 i
= 0; i
< MAX_DIFFICULTY
; ++i
)
16338 for (BoundInstancesMap::const_iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
16340 if(itr
->second
.perm
)
16342 data
.Initialize(SMSG_UPDATE_LAST_INSTANCE
);
16343 data
<< uint32(itr
->second
.save
->GetMapId());
16344 GetSession()->SendPacket(&data
);
16350 /// convert the player's binds to the group
16351 void Player::ConvertInstancesToGroup(Player
*player
, Group
*group
, uint64 player_guid
)
16353 bool has_binds
= false;
16354 bool has_solo
= false;
16356 if(player
) { player_guid
= player
->GetGUID(); if(!group
) group
= player
->GetGroup(); }
16357 ASSERT(player_guid
);
16359 // copy all binds to the group, when changing leader it's assumed the character
16360 // will not have any solo binds
16364 for(uint8 i
= 0; i
< MAX_DIFFICULTY
; ++i
)
16366 for (BoundInstancesMap::iterator itr
= player
->m_boundInstances
[i
].begin(); itr
!= player
->m_boundInstances
[i
].end();)
16369 if(group
) group
->BindToInstance(itr
->second
.save
, itr
->second
.perm
, true);
16370 // permanent binds are not removed
16371 if(!itr
->second
.perm
)
16373 // increments itr in call
16374 player
->UnbindInstance(itr
, Difficulty(i
), true);
16383 // if the player's not online we don't know what binds it has
16384 if(!player
|| !group
|| has_binds
)
16385 CharacterDatabase
.PExecute("INSERT INTO group_instance SELECT guid, instance, permanent FROM character_instance WHERE guid = '%u'", GUID_LOPART(player_guid
));
16387 // the following should not get executed when changing leaders
16388 if(!player
|| has_solo
)
16389 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid
));
16392 bool Player::_LoadHomeBind(QueryResult
*result
)
16394 PlayerInfo
const *info
= sObjectMgr
.GetPlayerInfo(getRace(), getClass());
16397 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
16402 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
16405 Field
*fields
= result
->Fetch();
16406 m_homebindMapId
= fields
[0].GetUInt32();
16407 m_homebindAreaId
= fields
[1].GetUInt16();
16408 m_homebindX
= fields
[2].GetFloat();
16409 m_homebindY
= fields
[3].GetFloat();
16410 m_homebindZ
= fields
[4].GetFloat();
16413 MapEntry
const* bindMapEntry
= sMapStore
.LookupEntry(m_homebindMapId
);
16415 // accept saved data only for valid position (and non instanceable), and accessable
16416 if( MapManager::IsValidMapCoord(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
) &&
16417 !bindMapEntry
->Instanceable() && GetSession()->Expansion() >= bindMapEntry
->Expansion())
16422 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
16427 m_homebindMapId
= info
->mapId
;
16428 m_homebindAreaId
= info
->areaId
;
16429 m_homebindX
= info
->positionX
;
16430 m_homebindY
= info
->positionY
;
16431 m_homebindZ
= info
->positionZ
;
16433 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_homebindAreaId
, m_homebindX
, m_homebindY
, m_homebindZ
);
16436 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
16437 m_homebindMapId
, m_homebindAreaId
, m_homebindX
, m_homebindY
, m_homebindZ
);
16442 /*********************************************************/
16443 /*** SAVE SYSTEM ***/
16444 /*********************************************************/
16446 void Player::SaveToDB()
16448 // we should assure this: ASSERT((m_nextSave != sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE)));
16449 // delay auto save at any saves (manual, in code, or autosave)
16450 m_nextSave
= sWorld
.getConfig(CONFIG_UINT32_INTERVAL_SAVE
);
16452 //lets allow only players in world to be saved
16453 if(IsBeingTeleportedFar())
16455 ScheduleDelayedOperation(DELAYED_SAVE_PLAYER
);
16459 // first save/honor gain after midnight will also update the player's honor fields
16460 UpdateHonorFields();
16462 sLog
.outDebug("The value of player %s at save: ", m_name
.c_str());
16465 CharacterDatabase
.BeginTransaction();
16467 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
16469 std::string sql_name
= m_name
;
16470 CharacterDatabase
.escape_string(sql_name
);
16472 std::ostringstream ss
;
16473 ss
<< "INSERT INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags,"
16474 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, "
16475 "taximask, online, cinematic, "
16476 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
16477 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
16478 "death_expire_time, taxi_path, arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, "
16479 "todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk, health, power1, power2, power3, "
16480 "power4, power5, power6, power7, specCount, activeSpec, exploredZones, equipmentCache, ammoId, knownTitles, actionBars) VALUES ("
16481 << GetGUIDLow() << ", "
16482 << GetSession()->GetAccountId() << ", '"
16483 << sql_name
<< "', "
16484 << (uint32
)getRace() << ", "
16485 << (uint32
)getClass() << ", "
16486 << (uint32
)getGender() << ", "
16487 << getLevel() << ", "
16488 << GetUInt32Value(PLAYER_XP
) << ", "
16489 << GetMoney() << ", "
16490 << GetUInt32Value(PLAYER_BYTES
) << ", "
16491 << GetUInt32Value(PLAYER_BYTES_2
) << ", "
16492 << GetUInt32Value(PLAYER_FLAGS
) << ", ";
16494 if(!IsBeingTeleported())
16496 ss
<< GetMapId() << ", "
16497 << (uint32
)GetDungeonDifficulty() << ", "
16498 << finiteAlways(GetPositionX()) << ", "
16499 << finiteAlways(GetPositionY()) << ", "
16500 << finiteAlways(GetPositionZ()) << ", "
16501 << finiteAlways(GetOrientation()) << ", ";
16505 ss
<< GetTeleportDest().mapid
<< ", "
16506 << (uint32
)GetDungeonDifficulty() << ", "
16507 << finiteAlways(GetTeleportDest().coord_x
) << ", "
16508 << finiteAlways(GetTeleportDest().coord_y
) << ", "
16509 << finiteAlways(GetTeleportDest().coord_z
) << ", "
16510 << finiteAlways(GetTeleportDest().orientation
) << ", ";
16513 ss
<< m_taxi
<< ", "; // string with TaxiMaskSize numbers
16515 ss
<< (IsInWorld() ? 1 : 0) << ", ";
16517 ss
<< m_cinematic
<< ", ";
16519 ss
<< m_Played_time
[PLAYED_TIME_TOTAL
] << ", ";
16520 ss
<< m_Played_time
[PLAYED_TIME_LEVEL
] << ", ";
16522 ss
<< finiteAlways(m_rest_bonus
) << ", ";
16523 ss
<< (uint64
)time(NULL
) << ", ";
16524 ss
<< (HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
) ? 1 : 0) << ", ";
16525 //save, far from tavern/city
16526 //save, but in tavern/city
16527 ss
<< m_resetTalentsCost
<< ", ";
16528 ss
<< (uint64
)m_resetTalentsTime
<< ", ";
16530 ss
<< finiteAlways(m_movementInfo
.GetTransportPos()->x
) << ", ";
16531 ss
<< finiteAlways(m_movementInfo
.GetTransportPos()->y
) << ", ";
16532 ss
<< finiteAlways(m_movementInfo
.GetTransportPos()->z
) << ", ";
16533 ss
<< finiteAlways(m_movementInfo
.GetTransportPos()->o
) << ", ";
16535 ss
<< m_transport
->GetGUIDLow();
16540 ss
<< m_ExtraFlags
<< ", ";
16542 ss
<< uint32(m_stableSlots
) << ", "; // to prevent save uint8 as char
16544 ss
<< uint32(m_atLoginFlags
) << ", ";
16546 ss
<< GetZoneId() << ", ";
16548 ss
<< (uint64
)m_deathExpireTime
<< ", '";
16550 ss
<< m_taxi
.SaveTaxiDestinationsToString() << "', ";
16552 ss
<< GetArenaPoints() << ", ";
16554 ss
<< GetHonorPoints() << ", ";
16556 ss
<< GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
) << ", ";
16558 ss
<< GetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
) << ", ";
16560 ss
<< GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
) << ", ";
16562 ss
<< GetUInt16Value(PLAYER_FIELD_KILLS
, 0) << ", ";
16564 ss
<< GetUInt16Value(PLAYER_FIELD_KILLS
, 1) << ", ";
16566 ss
<< GetUInt32Value(PLAYER_CHOSEN_TITLE
) << ", ";
16568 ss
<< GetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES
) << ", ";
16570 // FIXME: at this moment send to DB as unsigned, including unit32(-1)
16571 ss
<< GetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX
) << ", ";
16573 ss
<< (uint16
)(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFE) << ", ";
16577 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
16578 ss
<< "," << GetPower(Powers(i
));
16581 ss
<< uint32(m_specsCount
) << ", ";
16582 ss
<< uint32(m_activeSpec
) << ", '";
16583 for(uint32 i
= 0; i
< PLAYER_EXPLORED_ZONES_SIZE
; ++i
)
16585 ss
<< GetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ i
) << " ";
16589 for(uint32 i
= 0; i
< EQUIPMENT_SLOT_END
* 2; ++i
)
16591 ss
<< GetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID
+ i
) << " ";
16595 ss
<< GetUInt32Value(PLAYER_AMMO_ID
) << ", '";
16596 for(uint32 i
= 0; i
< KNOWN_TITLES_SIZE
*2; ++i
)
16598 ss
<< GetUInt32Value(PLAYER__FIELD_KNOWN_TITLES
+ i
) << " ";
16601 ss
<< uint32(GetByteValue(PLAYER_FIELD_BYTES
, 2));
16604 CharacterDatabase
.Execute( ss
.str().c_str() );
16606 if (m_mailsUpdated
) //save mails only when needed
16611 _SaveQuestStatus();
16612 _SaveDailyQuestStatus();
16613 _SaveWeeklyQuestStatus();
16615 _SaveSpellCooldowns();
16619 m_achievementMgr
.SaveToDB();
16620 m_reputationMgr
.SaveToDB();
16621 _SaveEquipmentSets();
16622 GetSession()->SaveTutorialsData(); // changed only while character in game
16626 CharacterDatabase
.CommitTransaction();
16628 // check if stats should only be saved on logout
16629 // save stats can be out of transaction
16630 if (m_session
->isLogingOut() || !sWorld
.getConfig(CONFIG_BOOL_STATS_SAVE_ONLY_ON_LOGOUT
))
16633 // save pet (hunter pet level and experience and all type pets health/mana).
16634 if (Pet
* pet
= GetPet())
16635 pet
->SavePetToDB(PET_SAVE_AS_CURRENT
);
16638 // fast save function for item/money cheating preventing - save only inventory and money state
16639 void Player::SaveInventoryAndGoldToDB()
16645 void Player::SaveGoldToDB()
16647 CharacterDatabase
.PExecute("UPDATE characters SET money = '%u' WHERE guid = '%u'", GetMoney(), GetGUIDLow());
16650 void Player::_SaveActions()
16652 for(int i
= 0; i
< MAX_TALENT_SPEC_COUNT
; ++i
)
16654 for(ActionButtonList::iterator itr
= m_actionButtons
[i
].begin(); itr
!= m_actionButtons
[i
].end(); )
16656 switch (itr
->second
.uState
)
16658 case ACTIONBUTTON_NEW
:
16659 CharacterDatabase
.PExecute("INSERT INTO character_action (guid,spec, button,action,type) VALUES ('%u', '%u', '%u', '%u', '%u')",
16660 GetGUIDLow(), i
, (uint32
)itr
->first
, (uint32
)itr
->second
.GetAction(), (uint32
)itr
->second
.GetType() );
16661 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
16664 case ACTIONBUTTON_CHANGED
:
16665 CharacterDatabase
.PExecute("UPDATE character_action SET action = '%u', type = '%u' WHERE guid= '%u' AND button= '%u' AND spec = '%u'",
16666 (uint32
)itr
->second
.GetAction(), (uint32
)itr
->second
.GetType(), GetGUIDLow(), (uint32
)itr
->first
, i
);
16667 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
16670 case ACTIONBUTTON_DELETED
:
16671 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u' AND button = '%u' AND spec = '%u'", GetGUIDLow(), (uint32
)itr
->first
, i
);
16672 m_actionButtons
[i
].erase(itr
++);
16682 void Player::_SaveAuras()
16684 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
16686 AuraMap
const& auras
= GetAuras();
16691 spellEffectPair lastEffectPair
= auras
.begin()->first
;
16692 uint32 stackCounter
= 1;
16694 /* copied following sql-code partly from achievementmgr */
16695 bool first_round
= true;
16696 std::ostringstream ss
;
16697 for(AuraMap::const_iterator itr
= auras
.begin(); ; ++itr
)
16699 if(itr
== auras
.end() || lastEffectPair
!= itr
->first
)
16701 AuraMap::const_iterator itr2
= itr
;
16702 // save previous spellEffectPair to db
16705 //skip all auras from spells that are passive
16706 //do not save single target auras (unless they were cast by the player)
16707 if (!itr2
->second
->IsPassive() && (itr2
->second
->GetCasterGUID() == GetGUID() || !itr2
->second
->IsSingleTarget()))
16711 ss
<< "INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges)VALUES ";
16712 first_round
= false;
16714 // next new/changed record prefix
16718 ss
<< "("<< GetGUIDLow() << "," << itr2
->second
->GetCasterGUID() << ","
16719 << (uint32
)itr2
->second
->GetId() << "," << (uint32
)itr2
->second
->GetEffIndex() << ","
16720 << stackCounter
<< "," << itr2
->second
->GetModifier()->m_amount
<< ","
16721 <<int(itr2
->second
->GetAuraMaxDuration()) << "," << int(itr2
->second
->GetAuraDuration()) << ","
16722 << int(itr2
->second
->GetAuraCharges()) << ")";
16725 if(itr
== auras
.end())
16729 if (lastEffectPair
== itr
->first
)
16733 lastEffectPair
= itr
->first
;
16738 // if something changed execute
16740 CharacterDatabase
.Execute( ss
.str().c_str() );
16743 void Player::_SaveGlyphs()
16746 for (uint8 spec
= 0; spec
< m_specsCount
; ++spec
)
16748 for (uint8 slot
= 0; slot
< MAX_GLYPH_SLOT_INDEX
; ++slot
)
16750 switch(m_glyphs
[spec
][slot
].uState
)
16753 CharacterDatabase
.PExecute("INSERT INTO character_glyphs (guid, spec, slot, glyph) VALUES ('%u', '%u', '%u', '%u')", GetGUIDLow(), spec
, slot
, m_glyphs
[spec
][slot
].GetId());
16755 case GLYPH_CHANGED
:
16756 CharacterDatabase
.PExecute("UPDATE character_glyphs SET glyph = '%u' WHERE guid='%u' AND spec = '%u' AND slot = '%u'", m_glyphs
[spec
][slot
].GetId(), GetGUIDLow(), spec
, slot
);
16758 case GLYPH_DELETED
:
16759 CharacterDatabase
.PExecute("DELETE FROM character_glyphs WHERE guid='%u' AND spec = '%u' AND slot = '%u'",GetGUIDLow(), spec
, slot
);
16761 case GLYPH_UNCHANGED
:
16764 m_glyphs
[spec
][slot
].uState
= GLYPH_UNCHANGED
;
16769 void Player::_SaveInventory()
16771 // force items in buyback slots to new state
16772 // and remove those that aren't already
16773 for (uint8 i
= BUYBACK_SLOT_START
; i
< BUYBACK_SLOT_END
; ++i
)
16775 Item
*item
= m_items
[i
];
16776 if (!item
|| item
->GetState() == ITEM_NEW
) continue;
16777 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
16778 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item
->GetGUIDLow());
16779 m_items
[i
]->FSetState(ITEM_NEW
);
16782 // update enchantment durations
16783 for(EnchantDurationList::const_iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
16785 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
16789 if (m_itemUpdateQueue
.empty()) return;
16791 // do not save if the update queue is corrupt
16792 bool error
= false;
16793 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); ++i
)
16795 Item
*item
= m_itemUpdateQueue
[i
];
16796 if(!item
|| item
->GetState() == ITEM_REMOVED
) continue;
16797 Item
*test
= GetItemByPos( item
->GetBagSlot(), item
->GetSlot());
16801 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());
16804 else if (test
!= item
)
16806 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());
16813 sLog
.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
16814 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED
);
16818 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); ++i
)
16820 Item
*item
= m_itemUpdateQueue
[i
];
16821 if(!item
) continue;
16823 Bag
*container
= item
->GetContainer();
16824 uint32 bag_guid
= container
? container
->GetGUIDLow() : 0;
16826 switch(item
->GetState())
16829 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());
16832 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());
16835 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
16837 case ITEM_UNCHANGED
:
16841 item
->SaveToDB(); // item have unchanged inventory record and can be save standalone
16843 m_itemUpdateQueue
.clear();
16846 void Player::_SaveMail()
16848 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
16851 if (m
->state
== MAIL_STATE_CHANGED
)
16853 CharacterDatabase
.PExecute("UPDATE mail SET has_items = '%u',expire_time = '" UI64FMTD
"', deliver_time = '" UI64FMTD
"',money = '%u',cod = '%u',checked = '%u' WHERE id = '%u'",
16854 m
->HasItems() ? 1 : 0, (uint64
)m
->expire_time
, (uint64
)m
->deliver_time
, m
->money
, m
->COD
, m
->checked
, m
->messageID
);
16855 if(m
->removedItems
.size())
16857 for(std::vector
<uint32
>::const_iterator itr2
= m
->removedItems
.begin(); itr2
!= m
->removedItems
.end(); ++itr2
)
16858 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2
);
16859 m
->removedItems
.clear();
16861 m
->state
= MAIL_STATE_UNCHANGED
;
16863 else if (m
->state
== MAIL_STATE_DELETED
)
16866 for(std::vector
<MailItemInfo
>::const_iterator itr2
= m
->items
.begin(); itr2
!= m
->items
.end(); ++itr2
)
16867 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2
->item_guid
);
16869 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", m
->messageID
);
16870 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m
->messageID
);
16874 //deallocate deleted mails...
16875 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); )
16877 if ((*itr
)->state
== MAIL_STATE_DELETED
)
16882 itr
= m_mail
.begin();
16888 m_mailsUpdated
= false;
16891 void Player::_SaveQuestStatus()
16893 // we don't need transactions here.
16894 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
16896 switch (i
->second
.uState
)
16899 CharacterDatabase
.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
16900 "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD
"', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
16901 GetGUIDLow(), i
->first
, i
->second
.m_status
, i
->second
.m_rewarded
, i
->second
.m_explored
, uint64(i
->second
.m_timer
/ IN_MILLISECONDS
+ 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]);
16903 case QUEST_CHANGED
:
16904 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' ",
16905 i
->second
.m_status
, i
->second
.m_rewarded
, i
->second
.m_explored
, uint64(i
->second
.m_timer
/ IN_MILLISECONDS
+ 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
);
16907 case QUEST_UNCHANGED
:
16910 i
->second
.uState
= QUEST_UNCHANGED
;
16914 void Player::_SaveDailyQuestStatus()
16916 if (!m_DailyQuestChanged
)
16919 // we don't need transactions here.
16920 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
16921 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
16922 if (GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
16923 CharacterDatabase
.PExecute("INSERT INTO character_queststatus_daily (guid,quest) VALUES ('%u', '%u')",
16924 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
));
16926 m_DailyQuestChanged
= false;
16929 void Player::_SaveWeeklyQuestStatus()
16931 if (!m_WeeklyQuestChanged
|| m_weeklyquests
.empty())
16934 // we don't need transactions here.
16935 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_weekly WHERE guid = '%u'",GetGUIDLow());
16937 for (QuestSet::const_iterator iter
= m_weeklyquests
.begin(); iter
!= m_weeklyquests
.end(); ++iter
)
16939 uint32 quest_id
= *iter
;
16941 CharacterDatabase
.PExecute("INSERT INTO character_queststatus_weekly (guid,quest) VALUES ('%u', '%u')", GetGUIDLow(), quest_id
);
16944 m_WeeklyQuestChanged
= false;
16947 void Player::_SaveSkills()
16949 // we don't need transactions here.
16950 for( SkillStatusMap::iterator itr
= mSkillStatus
.begin(); itr
!= mSkillStatus
.end(); )
16952 if(itr
->second
.uState
== SKILL_UNCHANGED
)
16958 if(itr
->second
.uState
== SKILL_DELETED
)
16960 CharacterDatabase
.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), itr
->first
);
16961 mSkillStatus
.erase(itr
++);
16965 uint32 valueData
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
));
16966 uint16 value
= SKILL_VALUE(valueData
);
16967 uint16 max
= SKILL_MAX(valueData
);
16969 switch (itr
->second
.uState
)
16972 CharacterDatabase
.PExecute("INSERT INTO character_skills (guid, skill, value, max) VALUES ('%u', '%u', '%u', '%u')",
16973 GetGUIDLow(), itr
->first
, value
, max
);
16975 case SKILL_CHANGED
:
16976 CharacterDatabase
.PExecute("UPDATE character_skills SET value = '%u',max = '%u'WHERE guid = '%u' AND skill = '%u' ",
16977 value
, max
, GetGUIDLow(), itr
->first
);
16980 itr
->second
.uState
= SKILL_UNCHANGED
;
16986 void Player::_SaveSpells()
16988 for (PlayerSpellMap::iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end();)
16990 uint32 talentCosts
= GetTalentSpellCost(itr
->first
);
16994 if (itr
->second
.state
== PLAYERSPELL_REMOVED
|| itr
->second
.state
== PLAYERSPELL_CHANGED
)
16995 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr
->first
);
16997 // add only changed/new not dependent spells
16998 if (!itr
->second
.dependent
&& (itr
->second
.state
== PLAYERSPELL_NEW
|| itr
->second
.state
== PLAYERSPELL_CHANGED
))
16999 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);
17002 if (itr
->second
.state
== PLAYERSPELL_REMOVED
)
17003 m_spells
.erase(itr
++);
17006 itr
->second
.state
= PLAYERSPELL_UNCHANGED
;
17013 void Player::_SaveTalents()
17015 for (int32 i
= 0; i
< MAX_TALENT_SPEC_COUNT
; ++i
)
17017 for (PlayerTalentMap::iterator itr
= m_talents
[i
].begin(); itr
!= m_talents
[i
].end();)
17019 if (itr
->second
.state
== PLAYERSPELL_REMOVED
|| itr
->second
.state
== PLAYERSPELL_CHANGED
)
17020 CharacterDatabase
.PExecute("DELETE FROM character_talent WHERE guid = '%u' and talent_id = '%u' and spec = '%u'", GetGUIDLow(),itr
->first
, i
);
17022 // add only changed/new talents
17023 if (itr
->second
.state
== PLAYERSPELL_NEW
|| itr
->second
.state
== PLAYERSPELL_CHANGED
)
17024 CharacterDatabase
.PExecute("INSERT INTO character_talent (guid, talent_id, current_rank , spec) VALUES ('%u', '%u', '%u', '%u')", GetGUIDLow(), itr
->first
, itr
->second
.currentRank
, i
);
17026 if (itr
->second
.state
== PLAYERSPELL_REMOVED
)
17027 m_talents
[i
].erase(itr
++);
17030 itr
->second
.state
= PLAYERSPELL_UNCHANGED
;
17037 // save player stats -- only for external usage
17038 // real stats will be recalculated on player login
17039 void Player::_SaveStats()
17041 // check if stat saving is enabled and if char level is high enough
17042 if(!sWorld
.getConfig(CONFIG_UINT32_MIN_LEVEL_STAT_SAVE
) || getLevel() < sWorld
.getConfig(CONFIG_UINT32_MIN_LEVEL_STAT_SAVE
))
17045 CharacterDatabase
.PExecute("DELETE FROM character_stats WHERE guid = '%u'", GetGUIDLow());
17046 std::ostringstream ss
;
17047 ss
<< "INSERT INTO character_stats (guid, maxhealth, maxpower1, maxpower2, maxpower3, maxpower4, maxpower5, maxpower6, maxpower7, "
17048 "strength, agility, stamina, intellect, spirit, armor, resHoly, resFire, resNature, resFrost, resShadow, resArcane, "
17049 "blockPct, dodgePct, parryPct, critPct, rangedCritPct, spellCritPct, attackPower, rangedAttackPower, spellPower) VALUES ("
17050 << GetGUIDLow() << ", "
17051 << GetMaxHealth() << ", ";
17052 for(int i
= 0; i
< MAX_POWERS
; ++i
)
17053 ss
<< GetMaxPower(Powers(i
)) << ", ";
17054 for(int i
= 0; i
< MAX_STATS
; ++i
)
17055 ss
<< GetStat(Stats(i
)) << ", ";
17056 // armor + school resistances
17057 for(int i
= 0; i
< MAX_SPELL_SCHOOL
; ++i
)
17058 ss
<< GetResistance(SpellSchools(i
)) << ",";
17059 ss
<< GetFloatValue(PLAYER_BLOCK_PERCENTAGE
) << ", "
17060 << GetFloatValue(PLAYER_DODGE_PERCENTAGE
) << ", "
17061 << GetFloatValue(PLAYER_PARRY_PERCENTAGE
) << ", "
17062 << GetFloatValue(PLAYER_CRIT_PERCENTAGE
) << ", "
17063 << GetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE
) << ", "
17064 << GetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1
) << ", "
17065 << GetUInt32Value(UNIT_FIELD_ATTACK_POWER
) << ", "
17066 << GetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER
) << ", "
17067 << GetBaseSpellPowerBonus() << ")";
17068 CharacterDatabase
.Execute( ss
.str().c_str() );
17071 void Player::outDebugValues() const
17073 if(!sLog
.IsOutDebug()) // optimize disabled debug output
17076 sLog
.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA
));
17077 sLog
.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY
), GetStat(STAT_STRENGTH
));
17078 sLog
.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT
), GetStat(STAT_SPIRIT
));
17079 sLog
.outDebug("STAMINA is: \t\t%f",GetStat(STAT_STAMINA
));
17080 sLog
.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE
));
17081 sLog
.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY
), GetResistance(SPELL_SCHOOL_FIRE
));
17082 sLog
.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE
), GetResistance(SPELL_SCHOOL_FROST
));
17083 sLog
.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW
), GetResistance(SPELL_SCHOOL_ARCANE
));
17084 sLog
.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE
), GetFloatValue(UNIT_FIELD_MAXDAMAGE
));
17085 sLog
.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
));
17086 sLog
.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
));
17087 sLog
.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK
), GetAttackTime(RANGED_ATTACK
));
17090 /*********************************************************/
17091 /*** FLOOD FILTER SYSTEM ***/
17092 /*********************************************************/
17094 void Player::UpdateSpeakTime()
17096 // ignore chat spam protection for GMs in any mode
17097 if(GetSession()->GetSecurity() > SEC_PLAYER
)
17100 time_t current
= time (NULL
);
17101 if(m_speakTime
> current
)
17103 uint32 max_count
= sWorld
.getConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_COUNT
);
17108 if(m_speakCount
>= max_count
)
17110 // prevent overwrite mute time, if message send just before mutes set, for example.
17111 time_t new_mute
= current
+ sWorld
.getConfig(CONFIG_UINT32_CHATFLOOD_MUTE_TIME
);
17112 if(GetSession()->m_muteTime
< new_mute
)
17113 GetSession()->m_muteTime
= new_mute
;
17121 m_speakTime
= current
+ sWorld
.getConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_DELAY
);
17124 bool Player::CanSpeak() const
17126 return GetSession()->m_muteTime
<= time (NULL
);
17129 /*********************************************************/
17130 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
17131 /*********************************************************/
17133 void Player::SendAttackSwingNotInRange()
17135 WorldPacket
data(SMSG_ATTACKSWING_NOTINRANGE
, 0);
17136 GetSession()->SendPacket( &data
);
17139 void Player::SavePositionInDB(uint32 mapid
, float x
,float y
,float z
,float o
,uint32 zone
,uint64 guid
)
17141 std::ostringstream ss
;
17142 ss
<< "UPDATE characters SET position_x='"<<x
<<"',position_y='"<<y
17143 << "',position_z='"<<z
<<"',orientation='"<<o
<<"',map='"<<mapid
17144 << "',zone='"<<zone
<<"',trans_x='0',trans_y='0',trans_z='0',"
17145 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
17146 sLog
.outDebug("%s", ss
.str().c_str());
17147 CharacterDatabase
.Execute(ss
.str().c_str());
17150 void Player::SetUInt32ValueInArray(Tokens
& tokens
,uint16 index
, uint32 value
)
17153 snprintf(buf
,11,"%u",value
);
17155 if(index
>= tokens
.size())
17158 tokens
[index
] = buf
;
17161 void Player::Customize(uint64 guid
, uint8 gender
, uint8 skin
, uint8 face
, uint8 hairStyle
, uint8 hairColor
, uint8 facialHair
)
17164 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", GUID_LOPART(guid
));
17168 Field
* fields
= result
->Fetch();
17170 uint32 player_bytes2
= fields
[0].GetUInt32();
17171 player_bytes2
&= ~0xFF;
17172 player_bytes2
|= facialHair
;
17174 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
));
17179 void Player::SendAttackSwingDeadTarget()
17181 WorldPacket
data(SMSG_ATTACKSWING_DEADTARGET
, 0);
17182 GetSession()->SendPacket( &data
);
17185 void Player::SendAttackSwingCantAttack()
17187 WorldPacket
data(SMSG_ATTACKSWING_CANT_ATTACK
, 0);
17188 GetSession()->SendPacket( &data
);
17191 void Player::SendAttackSwingCancelAttack()
17193 WorldPacket
data(SMSG_CANCEL_COMBAT
, 0);
17194 GetSession()->SendPacket( &data
);
17197 void Player::SendAttackSwingBadFacingAttack()
17199 WorldPacket
data(SMSG_ATTACKSWING_BADFACING
, 0);
17200 GetSession()->SendPacket( &data
);
17203 void Player::SendAutoRepeatCancel(Unit
*target
)
17205 WorldPacket
data(SMSG_CANCEL_AUTO_REPEAT
, target
->GetPackGUID().size());
17206 data
<< target
->GetPackGUID(); // may be it's target guid
17207 GetSession()->SendPacket( &data
);
17210 void Player::SendExplorationExperience(uint32 Area
, uint32 Experience
)
17212 WorldPacket
data( SMSG_EXPLORATION_EXPERIENCE
, 8 );
17213 data
<< uint32(Area
);
17214 data
<< uint32(Experience
);
17215 GetSession()->SendPacket(&data
);
17218 void Player::SendDungeonDifficulty(bool IsInGroup
)
17220 uint8 val
= 0x00000001;
17221 WorldPacket
data(MSG_SET_DUNGEON_DIFFICULTY
, 12);
17222 data
<< uint32(GetDungeonDifficulty());
17223 data
<< uint32(val
);
17224 data
<< uint32(IsInGroup
);
17225 GetSession()->SendPacket(&data
);
17228 void Player::SendRaidDifficulty(bool IsInGroup
)
17230 uint8 val
= 0x00000001;
17231 WorldPacket
data(MSG_SET_RAID_DIFFICULTY
, 12);
17232 data
<< uint32(GetRaidDifficulty());
17233 data
<< uint32(val
);
17234 data
<< uint32(IsInGroup
);
17235 GetSession()->SendPacket(&data
);
17238 void Player::SendResetFailedNotify(uint32 mapid
)
17240 WorldPacket
data(SMSG_RESET_FAILED_NOTIFY
, 4);
17241 data
<< uint32(mapid
);
17242 GetSession()->SendPacket(&data
);
17245 /// Reset all solo instances and optionally send a message on success for each
17246 void Player::ResetInstances(uint8 method
, bool isRaid
)
17248 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
17250 // we assume that when the difficulty changes, all instances that can be reset will be
17251 Difficulty diff
= GetDifficulty(isRaid
);
17253 for (BoundInstancesMap::iterator itr
= m_boundInstances
[diff
].begin(); itr
!= m_boundInstances
[diff
].end();)
17255 InstanceSave
*p
= itr
->second
.save
;
17256 const MapEntry
*entry
= sMapStore
.LookupEntry(itr
->first
);
17257 if(!entry
|| entry
->IsRaid() != isRaid
|| !p
->CanReset())
17263 if(method
== INSTANCE_RESET_ALL
)
17265 // the "reset all instances" method can only reset normal maps
17266 if(entry
->map_type
== MAP_RAID
|| diff
== DUNGEON_DIFFICULTY_HEROIC
)
17273 // if the map is loaded, reset it
17274 Map
*map
= sMapMgr
.FindMap(p
->GetMapId(), p
->GetInstanceId());
17275 if(map
&& map
->IsDungeon())
17276 ((InstanceMap
*)map
)->Reset(method
);
17278 // since this is a solo instance there should not be any players inside
17279 if(method
== INSTANCE_RESET_ALL
|| method
== INSTANCE_RESET_CHANGE_DIFFICULTY
)
17280 SendResetInstanceSuccess(p
->GetMapId());
17283 m_boundInstances
[diff
].erase(itr
++);
17285 // the following should remove the instance save from the manager and delete it as well
17286 p
->RemovePlayer(this);
17290 void Player::SendResetInstanceSuccess(uint32 MapId
)
17292 WorldPacket
data(SMSG_INSTANCE_RESET
, 4);
17293 data
<< uint32(MapId
);
17294 GetSession()->SendPacket(&data
);
17297 void Player::SendResetInstanceFailed(uint32 reason
, uint32 MapId
)
17299 // TODO: find what other fail reasons there are besides players in the instance
17300 WorldPacket
data(SMSG_INSTANCE_RESET_FAILED
, 4);
17301 data
<< uint32(reason
);
17302 data
<< uint32(MapId
);
17303 GetSession()->SendPacket(&data
);
17306 /*********************************************************/
17307 /*** Update timers ***/
17308 /*********************************************************/
17310 ///checks the 15 afk reports per 5 minutes limit
17311 void Player::UpdateAfkReport(time_t currTime
)
17313 if(m_bgData
.bgAfkReportedTimer
<= currTime
)
17315 m_bgData
.bgAfkReportedCount
= 0;
17316 m_bgData
.bgAfkReportedTimer
= currTime
+5*MINUTE
;
17320 void Player::UpdateContestedPvP(uint32 diff
)
17322 if(!m_contestedPvPTimer
||isInCombat())
17324 if(m_contestedPvPTimer
<= diff
)
17326 ResetContestedPvP();
17329 m_contestedPvPTimer
-= diff
;
17332 void Player::UpdatePvPFlag(time_t currTime
)
17336 if(pvpInfo
.endTimer
== 0 || currTime
< (pvpInfo
.endTimer
+ 300))
17342 void Player::UpdateDuelFlag(time_t currTime
)
17344 if(!duel
|| duel
->startTimer
== 0 ||currTime
< duel
->startTimer
+ 3)
17347 SetUInt32Value(PLAYER_DUEL_TEAM
, 1);
17348 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 2);
17350 duel
->startTimer
= 0;
17351 duel
->startTime
= currTime
;
17352 duel
->opponent
->duel
->startTimer
= 0;
17353 duel
->opponent
->duel
->startTime
= currTime
;
17356 void Player::RemovePet(Pet
* pet
, PetSaveMode mode
, bool returnreagent
)
17361 if (!pet
|| pet
->GetOwnerGUID() != GetGUID())
17364 // not save secondary permanent pet as current
17365 if (pet
&& m_temporaryUnsummonedPetNumber
&& m_temporaryUnsummonedPetNumber
!= pet
->GetCharmInfo()->GetPetNumber() && mode
== PET_SAVE_AS_CURRENT
)
17366 mode
= PET_SAVE_NOT_IN_SLOT
;
17368 if (returnreagent
&& pet
&& mode
!= PET_SAVE_AS_CURRENT
)
17370 //returning of reagents only for players, so best done here
17371 uint32 spellId
= pet
? pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
) : m_oldpetspell
;
17372 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
17376 for(uint32 i
= 0; i
< 7; ++i
)
17378 if(spellInfo
->Reagent
[i
] > 0)
17380 ItemPosCountVec dest
; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
17381 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, spellInfo
->Reagent
[i
], spellInfo
->ReagentCount
[i
] );
17382 if( msg
== EQUIP_ERR_OK
)
17384 Item
* item
= StoreNewItem( dest
, spellInfo
->Reagent
[i
], true);
17386 SendNewItem(item
,spellInfo
->ReagentCount
[i
],true,false);
17393 // only if current pet in slot
17394 switch(pet
->getPetType())
17400 RemoveGuardian(pet
);
17403 if (GetPetGUID() == pet
->GetGUID())
17410 pet
->SavePetToDB(mode
);
17412 pet
->AddObjectToRemoveList();
17413 pet
->m_removed
= true;
17415 if (pet
->isControlled())
17417 RemovePetActionBar();
17420 SetGroupUpdateFlag(GROUP_UPDATE_PET
);
17424 void Player::RemoveMiniPet()
17426 if (Pet
* pet
= GetMiniPet())
17428 pet
->Remove(PET_SAVE_AS_DELETED
);
17433 Pet
* Player::GetMiniPet()
17438 return GetMap()->GetPet(m_miniPet
);
17441 void Player::BuildPlayerChat(WorldPacket
*data
, uint8 msgtype
, const std::string
& text
, uint32 language
) const
17443 *data
<< (uint8
)msgtype
;
17444 *data
<< (uint32
)language
;
17445 *data
<< (uint64
)GetGUID();
17446 *data
<< (uint32
)language
; //language 2.1.0 ?
17447 *data
<< (uint64
)GetGUID();
17448 *data
<< (uint32
)(text
.length()+1);
17450 *data
<< (uint8
)chatTag();
17453 void Player::Say(const std::string
& text
, const uint32 language
)
17455 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
17456 BuildPlayerChat(&data
, CHAT_MSG_SAY
, text
, language
);
17457 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_FLOAT_LISTEN_RANGE_SAY
),true);
17460 void Player::Yell(const std::string
& text
, const uint32 language
)
17462 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
17463 BuildPlayerChat(&data
, CHAT_MSG_YELL
, text
, language
);
17464 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_FLOAT_LISTEN_RANGE_YELL
),true);
17467 void Player::TextEmote(const std::string
& text
)
17469 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
17470 BuildPlayerChat(&data
, CHAT_MSG_EMOTE
, text
, LANG_UNIVERSAL
);
17471 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_FLOAT_LISTEN_RANGE_TEXTEMOTE
),true, !sWorld
.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_CHAT
) );
17474 void Player::Whisper(const std::string
& text
, uint32 language
,uint64 receiver
)
17476 if (language
!= LANG_ADDON
) // if not addon data
17477 language
= LANG_UNIVERSAL
; // whispers should always be readable
17479 Player
*rPlayer
= sObjectMgr
.GetPlayer(receiver
);
17481 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
17482 if(!rPlayer
->isDND() || isGameMaster())
17484 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
17485 BuildPlayerChat(&data
, CHAT_MSG_WHISPER
, text
, language
);
17486 rPlayer
->GetSession()->SendPacket(&data
);
17488 // not send confirmation for addon messages
17489 if (language
!= LANG_ADDON
)
17491 data
.Initialize(SMSG_MESSAGECHAT
, 200);
17492 rPlayer
->BuildPlayerChat(&data
, CHAT_MSG_WHISPER_INFORM
, text
, language
);
17493 GetSession()->SendPacket(&data
);
17498 // announce to player that player he is whispering to is dnd and cannot receive his message
17499 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND
, rPlayer
->GetName(), rPlayer
->dndMsg
.c_str());
17502 if(!isAcceptWhispers())
17504 SetAcceptWhispers(true);
17505 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON
);
17508 // announce to player that player he is whispering to is afk
17509 if(rPlayer
->isAFK())
17510 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK
, rPlayer
->GetName(), rPlayer
->afkMsg
.c_str());
17512 // if player whisper someone, auto turn of dnd to be able to receive an answer
17513 if(isDND() && !rPlayer
->isGameMaster())
17517 void Player::PetSpellInitialize()
17519 Pet
* pet
= GetPet();
17524 sLog
.outDebug("Pet Spells Groups");
17526 CharmInfo
*charmInfo
= pet
->GetCharmInfo();
17528 WorldPacket
data(SMSG_PET_SPELLS
, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX
+1+1);
17529 data
<< uint64(pet
->GetGUID());
17530 data
<< uint16(pet
->GetCreatureInfo()->family
); // creature family (required for pet talents)
17532 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState()) << uint16(0);
17535 charmInfo
->BuildActionBar(&data
);
17537 size_t spellsCountPos
= data
.wpos();
17541 data
<< uint8(addlist
); // placeholder
17543 if (pet
->IsPermanentPetFor(this))
17546 for (PetSpellMap::const_iterator itr
= pet
->m_spells
.begin(); itr
!= pet
->m_spells
.end(); ++itr
)
17548 if(itr
->second
.state
== PETSPELL_REMOVED
)
17551 data
<< uint32(MAKE_UNIT_ACTION_BUTTON(itr
->first
,itr
->second
.active
));
17556 data
.put
<uint8
>(spellsCountPos
, addlist
);
17558 uint8 cooldownsCount
= pet
->m_CreatureSpellCooldowns
.size() + pet
->m_CreatureCategoryCooldowns
.size();
17559 data
<< uint8(cooldownsCount
);
17561 time_t curTime
= time(NULL
);
17563 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureSpellCooldowns
.begin(); itr
!= pet
->m_CreatureSpellCooldowns
.end(); ++itr
)
17565 time_t cooldown
= (itr
->second
> curTime
) ? (itr
->second
- curTime
) * IN_MILLISECONDS
: 0;
17567 data
<< uint32(itr
->first
); // spellid
17568 data
<< uint16(0); // spell category?
17569 data
<< uint32(cooldown
); // cooldown
17570 data
<< uint32(0); // category cooldown
17573 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureCategoryCooldowns
.begin(); itr
!= pet
->m_CreatureCategoryCooldowns
.end(); ++itr
)
17575 time_t cooldown
= (itr
->second
> curTime
) ? (itr
->second
- curTime
) * IN_MILLISECONDS
: 0;
17577 data
<< uint32(itr
->first
); // spellid
17578 data
<< uint16(0); // spell category?
17579 data
<< uint32(0); // cooldown
17580 data
<< uint32(cooldown
); // category cooldown
17583 GetSession()->SendPacket(&data
);
17586 void Player::SendPetGUIDs()
17591 // Later this function might get modified for multiple guids
17592 WorldPacket
data(SMSG_PET_GUIDS
, 12);
17593 data
<< uint32(1); // count
17594 data
<< uint64(GetPetGUID());
17595 GetSession()->SendPacket(&data
);
17598 void Player::PossessSpellInitialize()
17600 Unit
* charm
= GetCharm();
17605 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
17609 sLog
.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm
->GetGUIDLow(),charm
->GetTypeId());
17613 WorldPacket
data(SMSG_PET_SPELLS
, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX
+1+1);
17614 data
<< uint64(charm
->GetGUID());
17619 charmInfo
->BuildActionBar(&data
);
17621 data
<< uint8(0); // spells count
17622 data
<< uint8(0); // cooldowns count
17624 GetSession()->SendPacket(&data
);
17627 void Player::CharmSpellInitialize()
17629 Unit
* charm
= GetCharm();
17634 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
17637 sLog
.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm
->GetGUIDLow(),charm
->GetTypeId());
17643 if(charm
->GetTypeId() != TYPEID_PLAYER
)
17645 CreatureInfo
const *cinfo
= ((Creature
*)charm
)->GetCreatureInfo();
17647 if(cinfo
&& cinfo
->type
== CREATURE_TYPE_DEMON
&& getClass() == CLASS_WARLOCK
)
17649 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
17651 if(charmInfo
->GetCharmSpell(i
)->GetAction())
17657 WorldPacket
data(SMSG_PET_SPELLS
, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX
+1+4*addlist
+1);
17658 data
<< uint64(charm
->GetGUID());
17662 if(charm
->GetTypeId() != TYPEID_PLAYER
)
17663 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState()) << uint16(0);
17665 data
<< uint8(0) << uint8(0) << uint16(0);
17667 charmInfo
->BuildActionBar(&data
);
17669 data
<< uint8(addlist
);
17673 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
17675 CharmSpellEntry
*cspell
= charmInfo
->GetCharmSpell(i
);
17676 if(cspell
->GetAction())
17677 data
<< uint32(cspell
->packedData
);
17681 data
<< uint8(0); // cooldowns count
17683 GetSession()->SendPacket(&data
);
17686 void Player::RemovePetActionBar()
17688 WorldPacket
data(SMSG_PET_SPELLS
, 8);
17690 SendDirectMessage(&data
);
17693 bool Player::IsAffectedBySpellmod(SpellEntry
const *spellInfo
, SpellModifier
*mod
, Spell
const* spell
)
17695 if (!mod
|| !spellInfo
)
17698 if(mod
->charges
== -1 && mod
->lastAffected
) // marked as expired but locked until spell casting finish
17700 // prevent apply to any spell except spell that trigger expire
17703 if(mod
->lastAffected
!= spell
)
17706 else if(mod
->lastAffected
!= FindCurrentSpellBySpellId(spellInfo
->Id
))
17710 return mod
->isAffectedOnSpell(spellInfo
);
17713 void Player::AddSpellMod(SpellModifier
* mod
, bool apply
)
17715 uint16 Opcode
= (mod
->type
== SPELLMOD_FLAT
) ? SMSG_SET_FLAT_SPELL_MODIFIER
: SMSG_SET_PCT_SPELL_MODIFIER
;
17717 for(int eff
= 0; eff
< 96; ++eff
)
17723 _mask
= uint64(1) << (eff
- 0);
17725 _mask2
= uint32(1) << (eff
- 64);
17727 if ( mod
->mask
& _mask
|| mod
->mask2
& _mask2
)
17730 for (SpellModList::const_iterator itr
= m_spellMods
[mod
->op
].begin(); itr
!= m_spellMods
[mod
->op
].end(); ++itr
)
17732 if ((*itr
)->type
== mod
->type
&& ((*itr
)->mask
& _mask
|| (*itr
)->mask2
& _mask2
))
17733 val
+= (*itr
)->value
;
17735 val
+= apply
? mod
->value
: -(mod
->value
);
17736 WorldPacket
data(Opcode
, (1+1+4));
17737 data
<< uint8(eff
);
17738 data
<< uint8(mod
->op
);
17739 data
<< int32(val
);
17740 SendDirectMessage(&data
);
17745 m_spellMods
[mod
->op
].push_back(mod
);
17748 if (mod
->charges
== -1)
17749 --m_SpellModRemoveCount
;
17750 m_spellMods
[mod
->op
].remove(mod
);
17755 void Player::RemoveSpellMods(Spell
const* spell
)
17757 if(!spell
|| (m_SpellModRemoveCount
== 0))
17760 for(int i
=0;i
<MAX_SPELLMOD
;++i
)
17762 for (SpellModList::const_iterator itr
= m_spellMods
[i
].begin(); itr
!= m_spellMods
[i
].end();)
17764 SpellModifier
*mod
= *itr
;
17767 if (mod
&& mod
->charges
== -1 && (mod
->lastAffected
== spell
|| mod
->lastAffected
==NULL
))
17769 RemoveAurasDueToSpell(mod
->spellId
);
17770 if (m_spellMods
[i
].empty())
17773 itr
= m_spellMods
[i
].begin();
17779 // send Proficiency
17780 void Player::SendProficiency(uint8 pr1
, uint32 pr2
)
17782 WorldPacket
data(SMSG_SET_PROFICIENCY
, 8);
17783 data
<< uint8(pr1
) << uint32(pr2
);
17784 GetSession()->SendPacket (&data
);
17787 void Player::RemovePetitionsAndSigns(uint64 guid
, uint32 type
)
17789 QueryResult
*result
= NULL
;
17791 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
17793 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
17796 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.
17797 { // and SendPetitionQueryOpcode reads data from the DB
17798 Field
*fields
= result
->Fetch();
17799 uint64 ownerguid
= MAKE_NEW_GUID(fields
[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
17800 uint64 petitionguid
= MAKE_NEW_GUID(fields
[1].GetUInt32(), 0, HIGHGUID_ITEM
);
17802 // send update if charter owner in game
17803 Player
* owner
= sObjectMgr
.GetPlayer(ownerguid
);
17805 owner
->GetSession()->SendPetitionQueryOpcode(petitionguid
);
17807 } while ( result
->NextRow() );
17812 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
17814 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
17817 CharacterDatabase
.BeginTransaction();
17820 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid
));
17821 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid
));
17825 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
17826 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
17828 CharacterDatabase
.CommitTransaction();
17831 void Player::LeaveAllArenaTeams(uint64 guid
)
17833 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
));
17839 Field
*fields
= result
->Fetch();
17840 uint32 at_id
= fields
[0].GetUInt32();
17843 ArenaTeam
* at
= sObjectMgr
.GetArenaTeamById(at_id
);
17845 at
->DelMember(guid
);
17847 } while (result
->NextRow());
17852 void Player::SetRestBonus (float rest_bonus_new
)
17854 // Prevent resting on max level
17855 if(getLevel() >= sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
))
17856 rest_bonus_new
= 0;
17858 if(rest_bonus_new
< 0)
17859 rest_bonus_new
= 0;
17861 float rest_bonus_max
= (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)*1.5f
/2.0f
;
17863 if(rest_bonus_new
> rest_bonus_max
)
17864 m_rest_bonus
= rest_bonus_max
;
17866 m_rest_bonus
= rest_bonus_new
;
17868 // update data for client
17869 if(m_rest_bonus
>10)
17870 SetByteValue(PLAYER_BYTES_2
, 3, 0x01); // Set Reststate = Rested
17871 else if(m_rest_bonus
<=1)
17872 SetByteValue(PLAYER_BYTES_2
, 3, 0x02); // Set Reststate = Normal
17875 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE
, uint32(m_rest_bonus
));
17878 void Player::HandleStealthedUnitsDetection()
17880 std::list
<Unit
*> stealthedUnits
;
17882 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
17884 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
17885 cell
.SetNoCreate();
17887 MaNGOS::AnyStealthedCheck u_check
;
17888 MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
> searcher(this,stealthedUnits
, u_check
);
17890 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, WorldTypeMapContainer
> world_unit_searcher(searcher
);
17891 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, GridTypeMapContainer
> grid_unit_searcher(searcher
);
17893 cell
.Visit(p
, world_unit_searcher
, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE
);
17894 cell
.Visit(p
, grid_unit_searcher
, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE
);
17896 WorldObject
const* viewPoint
= GetViewPoint();
17898 for (std::list
<Unit
*>::const_iterator i
= stealthedUnits
.begin(); i
!= stealthedUnits
.end(); ++i
)
17903 bool hasAtClient
= HaveAtClient((*i
));
17904 bool hasDetected
= (*i
)->isVisibleForOrDetect(this, viewPoint
, true);
17910 ObjectGuid i_guid
= (*i
)->GetGUID();
17911 (*i
)->SendCreateUpdateToPlayer(this);
17912 m_clientGUIDs
.insert(i_guid
);
17914 #ifdef MANGOS_DEBUG
17915 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17916 sLog
.outDebug("%s is detected in stealth by player %u. Distance = %f",i_guid
.GetString().c_str(),GetGUIDLow(),GetDistance(*i
));
17919 // target aura duration for caster show only if target exist at caster client
17920 // send data at target visibility change (adding to client)
17921 if((*i
)!=this && (*i
)->isType(TYPEMASK_UNIT
))
17922 SendAurasForTarget(*i
);
17929 (*i
)->DestroyForPlayer(this);
17930 m_clientGUIDs
.erase((*i
)->GetGUID());
17936 bool Player::ActivateTaxiPathTo(std::vector
<uint32
> const& nodes
, Creature
* npc
/*= NULL*/, uint32 spellid
/*= 0*/)
17938 if(nodes
.size() < 2)
17941 // 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
17942 if(GetSession()->isLogingOut() || isInCombat())
17944 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17945 data
<< uint32(ERR_TAXIPLAYERBUSY
);
17946 GetSession()->SendPacket(&data
);
17950 if(HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_DISABLE_MOVE
))
17956 // not let cheating with start flight mounted
17959 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17960 data
<< uint32(ERR_TAXIPLAYERALREADYMOUNTED
);
17961 GetSession()->SendPacket(&data
);
17965 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
17967 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17968 data
<< uint32(ERR_TAXIPLAYERSHAPESHIFTED
);
17969 GetSession()->SendPacket(&data
);
17973 // 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
17974 if(IsNonMeleeSpellCasted(false))
17976 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17977 data
<< uint32(ERR_TAXIPLAYERBUSY
);
17978 GetSession()->SendPacket(&data
);
17982 // cast case or scripted call case
17985 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED
);
17987 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
17988 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId
);
17990 if (Spell
* spell
= GetCurrentSpell(CURRENT_GENERIC_SPELL
))
17991 if (spell
->m_spellInfo
->Id
!= spellid
)
17992 InterruptSpell(CURRENT_GENERIC_SPELL
,false);
17994 InterruptSpell(CURRENT_AUTOREPEAT_SPELL
,false);
17996 if (Spell
* spell
= GetCurrentSpell(CURRENT_CHANNELED_SPELL
))
17997 if (spell
->m_spellInfo
->Id
!= spellid
)
17998 InterruptSpell(CURRENT_CHANNELED_SPELL
,true);
18001 uint32 sourcenode
= nodes
[0];
18003 // starting node too far away (cheat?)
18004 TaxiNodesEntry
const* node
= sTaxiNodesStore
.LookupEntry(sourcenode
);
18007 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
18008 data
<< uint32(ERR_TAXINOSUCHPATH
);
18009 GetSession()->SendPacket(&data
);
18013 // check node starting pos data set case if provided
18014 if (node
->x
!= 0.0f
|| node
->y
!= 0.0f
|| node
->z
!= 0.0f
)
18016 if (node
->map_id
!= GetMapId() ||
18017 (node
->x
- GetPositionX())*(node
->x
- GetPositionX())+
18018 (node
->y
- GetPositionY())*(node
->y
- GetPositionY())+
18019 (node
->z
- GetPositionZ())*(node
->z
- GetPositionZ()) >
18020 (2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
))
18022 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
18023 data
<< uint32(ERR_TAXITOOFARAWAY
);
18024 GetSession()->SendPacket(&data
);
18028 // node must have pos if taxi master case (npc != NULL)
18031 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
18032 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
18033 GetSession()->SendPacket(&data
);
18037 // Prepare to flight start now
18039 // stop combat at start taxi flight if any
18042 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
18045 // clean not finished taxi path if any
18046 m_taxi
.ClearTaxiDestinations();
18048 // 0 element current node
18049 m_taxi
.AddTaxiDestination(sourcenode
);
18051 // fill destinations path tail
18052 uint32 sourcepath
= 0;
18053 uint32 totalcost
= 0;
18055 uint32 prevnode
= sourcenode
;
18056 uint32 lastnode
= 0;
18058 for(uint32 i
= 1; i
< nodes
.size(); ++i
)
18062 lastnode
= nodes
[i
];
18063 sObjectMgr
.GetTaxiPath(prevnode
, lastnode
, path
, cost
);
18067 m_taxi
.ClearTaxiDestinations();
18073 if(prevnode
== sourcenode
)
18076 m_taxi
.AddTaxiDestination(lastnode
);
18078 prevnode
= lastnode
;
18081 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
18082 uint32 mount_display_id
= sObjectMgr
.GetTaxiMountDisplayId(sourcenode
, GetTeam(), npc
== NULL
);
18084 // in spell case allow 0 model
18085 if ((mount_display_id
== 0 && spellid
== 0) || sourcepath
== 0)
18087 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
18088 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
18089 GetSession()->SendPacket(&data
);
18090 m_taxi
.ClearTaxiDestinations();
18094 uint32 money
= GetMoney();
18097 totalcost
= (uint32
)ceil(totalcost
*GetReputationPriceDiscount(npc
));
18099 if(money
< totalcost
)
18101 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
18102 data
<< uint32(ERR_TAXINOTENOUGHMONEY
);
18103 GetSession()->SendPacket(&data
);
18104 m_taxi
.ClearTaxiDestinations();
18108 //Checks and preparations done, DO FLIGHT
18109 ModifyMoney(-(int32
)totalcost
);
18110 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING
, totalcost
);
18111 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN
, 1);
18113 // prevent stealth flight
18114 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH
);
18116 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
18117 data
<< uint32(ERR_TAXIOK
);
18118 GetSession()->SendPacket(&data
);
18120 sLog
.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
18122 GetSession()->SendDoFlight(mount_display_id
, sourcepath
);
18127 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id
, uint32 spellid
/*= 0*/ )
18129 TaxiPathEntry
const* entry
= sTaxiPathStore
.LookupEntry(taxi_path_id
);
18133 std::vector
<uint32
> nodes
;
18136 nodes
[0] = entry
->from
;
18137 nodes
[1] = entry
->to
;
18139 return ActivateTaxiPathTo(nodes
,NULL
,spellid
);
18142 void Player::ContinueTaxiFlight()
18144 uint32 sourceNode
= m_taxi
.GetTaxiSource();
18148 sLog
.outDebug( "WORLD: Restart character %u taxi flight", GetGUIDLow() );
18150 uint32 mountDisplayId
= sObjectMgr
.GetTaxiMountDisplayId(sourceNode
, GetTeam(),true);
18151 uint32 path
= m_taxi
.GetCurrentTaxiPath();
18153 // search appropriate start path node
18154 uint32 startNode
= 0;
18156 TaxiPathNodeList
const& nodeList
= sTaxiPathNodesByPath
[path
];
18158 float distPrev
= MAP_SIZE
*MAP_SIZE
;
18160 (nodeList
[0].x
-GetPositionX())*(nodeList
[0].x
-GetPositionX())+
18161 (nodeList
[0].y
-GetPositionY())*(nodeList
[0].y
-GetPositionY())+
18162 (nodeList
[0].z
-GetPositionZ())*(nodeList
[0].z
-GetPositionZ());
18164 for(uint32 i
= 1; i
< nodeList
.size(); ++i
)
18166 TaxiPathNode
const& node
= nodeList
[i
];
18167 TaxiPathNode
const& prevNode
= nodeList
[i
-1];
18169 // skip nodes at another map
18170 if(node
.mapid
!= GetMapId())
18173 distPrev
= distNext
;
18176 (node
.x
-GetPositionX())*(node
.x
-GetPositionX())+
18177 (node
.y
-GetPositionY())*(node
.y
-GetPositionY())+
18178 (node
.z
-GetPositionZ())*(node
.z
-GetPositionZ());
18181 (node
.x
-prevNode
.x
)*(node
.x
-prevNode
.x
)+
18182 (node
.y
-prevNode
.y
)*(node
.y
-prevNode
.y
)+
18183 (node
.z
-prevNode
.z
)*(node
.z
-prevNode
.z
);
18185 if(distNext
+ distPrev
< distNodes
)
18192 GetSession()->SendDoFlight(mountDisplayId
, path
, startNode
);
18195 void Player::ProhibitSpellSchool(SpellSchoolMask idSchoolMask
, uint32 unTimeMs
)
18197 // last check 2.0.10
18198 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+m_spells
.size()*8);
18199 data
<< uint64(GetGUID());
18200 data
<< uint8(0x0); // flags (0x1, 0x2)
18201 time_t curTime
= time(NULL
);
18202 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
18204 if (itr
->second
.state
== PLAYERSPELL_REMOVED
)
18206 uint32 unSpellId
= itr
->first
;
18207 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(unSpellId
);
18214 // Not send cooldown for this spells
18215 if (spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
)
18218 if((idSchoolMask
& GetSpellSchoolMask(spellInfo
)) && GetSpellCooldownDelay(unSpellId
) < unTimeMs
)
18220 data
<< uint32(unSpellId
);
18221 data
<< uint32(unTimeMs
); // in m.secs
18222 AddSpellCooldown(unSpellId
, 0, curTime
+ unTimeMs
/IN_MILLISECONDS
);
18225 GetSession()->SendPacket(&data
);
18228 void Player::InitDataForForm(bool reapplyMods
)
18230 SpellShapeshiftEntry
const* ssEntry
= sSpellShapeshiftStore
.LookupEntry(m_form
);
18231 if(ssEntry
&& ssEntry
->attackSpeed
)
18233 SetAttackTime(BASE_ATTACK
,ssEntry
->attackSpeed
);
18234 SetAttackTime(OFF_ATTACK
,ssEntry
->attackSpeed
);
18235 SetAttackTime(RANGED_ATTACK
, BASE_ATTACK_TIME
);
18238 SetRegularAttackTime();
18244 if(getPowerType()!=POWER_ENERGY
)
18245 setPowerType(POWER_ENERGY
);
18249 case FORM_DIREBEAR
:
18251 if(getPowerType()!=POWER_RAGE
)
18252 setPowerType(POWER_RAGE
);
18255 default: // 0, for example
18257 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(getClass());
18258 if(cEntry
&& cEntry
->powerType
< MAX_POWERS
&& uint32(getPowerType()) != cEntry
->powerType
)
18259 setPowerType(Powers(cEntry
->powerType
));
18264 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
18266 UpdateEquipSpellsAtFormChange();
18268 UpdateAttackPowerAndDamage();
18269 UpdateAttackPowerAndDamage(true);
18272 void Player::InitDisplayIds()
18274 PlayerInfo
const *info
= sObjectMgr
.GetPlayerInfo(getRace(), getClass());
18277 sLog
.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
18281 uint8 gender
= getGender();
18284 case GENDER_FEMALE
:
18285 SetDisplayId(info
->displayId_f
);
18286 SetNativeDisplayId(info
->displayId_f
);
18289 SetDisplayId(info
->displayId_m
);
18290 SetNativeDisplayId(info
->displayId_m
);
18293 sLog
.outError("Invalid gender %u for player",gender
);
18298 // Return true is the bought item has a max count to force refresh of window by caller
18299 bool Player::BuyItemFromVendorSlot(uint64 vendorguid
, uint32 vendorslot
, uint32 item
, uint8 count
, uint8 bag
, uint8 slot
)
18301 // cheating attempt
18302 if (count
< 1) count
= 1;
18307 ItemPrototype
const *pProto
= ObjectMgr::GetItemPrototype( item
);
18310 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, NULL
, item
, 0);
18314 Creature
*pCreature
= GetNPCIfCanInteractWith(vendorguid
,UNIT_NPC_FLAG_VENDOR
);
18317 sLog
.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid
)) );
18318 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR
, NULL
, item
, 0);
18322 VendorItemData
const* vItems
= pCreature
->GetVendorItems();
18323 if(!vItems
|| vItems
->Empty())
18325 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
18329 if (vendorslot
>= vItems
->GetItemCount())
18331 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
18335 VendorItem
const* crItem
= vItems
->GetItem(vendorslot
);
18336 if(!crItem
|| crItem
->item
!= item
) // store diff item (cheating)
18338 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
18343 // check current item amount if it limited
18344 if (crItem
->maxcount
!= 0)
18346 if (pCreature
->GetVendorItemCurrentCount(crItem
) < pProto
->BuyCount
* count
)
18348 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD
, pCreature
, item
, 0);
18353 if (uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
18355 SendBuyError( BUY_ERR_REPUTATION_REQUIRE
, pCreature
, item
, 0);
18359 if (crItem
->ExtendedCost
)
18361 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
18364 sLog
.outError("Item %u have wrong ExtendedCost field value %u", pProto
->ItemId
, crItem
->ExtendedCost
);
18368 // honor points price
18369 if (GetHonorPoints() < (iece
->reqhonorpoints
* count
))
18371 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS
, NULL
, NULL
);
18375 // arena points price
18376 if (GetArenaPoints() < (iece
->reqarenapoints
* count
))
18378 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS
, NULL
, NULL
);
18383 for (uint8 i
= 0; i
< 5; ++i
)
18385 if(iece
->reqitem
[i
] && !HasItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
)))
18387 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS
, NULL
, NULL
);
18392 // check for personal arena rating requirement
18393 if( GetMaxPersonalArenaRatingRequirement(iece
->reqarenaslot
) < iece
->reqpersonalarenarating
)
18395 // probably not the proper equip err
18396 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK
,NULL
,NULL
);
18401 uint32 price
= pProto
->BuyPrice
* count
;
18403 // reputation discount
18404 price
= uint32(floor(price
* GetReputationPriceDiscount(pCreature
)));
18406 if (GetMoney() < price
)
18408 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, pCreature
, item
, 0);
18412 if ((bag
== NULL_BAG
&& slot
== NULL_SLOT
) || IsInventoryPos(bag
, slot
))
18414 ItemPosCountVec dest
;
18415 uint8 msg
= CanStoreNewItem( bag
, slot
, dest
, item
, pProto
->BuyCount
* count
);
18416 if (msg
!= EQUIP_ERR_OK
)
18418 SendEquipError( msg
, NULL
, NULL
, item
);
18422 ModifyMoney( -(int32
)price
);
18423 if (crItem
->ExtendedCost
) // case for new honor system
18425 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
18426 if (iece
->reqhonorpoints
)
18427 ModifyHonorPoints( - int32(iece
->reqhonorpoints
* count
));
18428 if (iece
->reqarenapoints
)
18429 ModifyArenaPoints( - int32(iece
->reqarenapoints
* count
));
18430 for (uint8 i
= 0; i
< 5; ++i
)
18432 if (iece
->reqitem
[i
])
18433 DestroyItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
), true);
18437 if (Item
*it
= StoreNewItem( dest
, item
, true ))
18439 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
18441 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
18442 data
<< uint64(pCreature
->GetGUID());
18443 data
<< uint32(vendorslot
+1); // numbered from 1 at client
18444 data
<< uint32(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
18445 data
<< uint32(count
);
18446 GetSession()->SendPacket(&data
);
18448 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
18451 else if (IsEquipmentPos(bag
, slot
))
18453 if (pProto
->BuyCount
* count
!= 1)
18455 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
, NULL
, NULL
);
18460 uint8 msg
= CanEquipNewItem( slot
, dest
, item
, false );
18461 if (msg
!= EQUIP_ERR_OK
)
18463 SendEquipError( msg
, NULL
, NULL
, item
);
18467 ModifyMoney( -(int32
)price
);
18468 if (crItem
->ExtendedCost
) // case for new honor system
18470 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
18471 if (iece
->reqhonorpoints
)
18472 ModifyHonorPoints( - int32(iece
->reqhonorpoints
));
18473 if (iece
->reqarenapoints
)
18474 ModifyArenaPoints( - int32(iece
->reqarenapoints
));
18475 for (uint8 i
= 0; i
< 5; ++i
)
18477 if(iece
->reqitem
[i
])
18478 DestroyItemCount(iece
->reqitem
[i
], iece
->reqitemcount
[i
], true);
18482 if (Item
*it
= EquipNewItem( dest
, item
, true ))
18484 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
18486 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
18487 data
<< uint64(pCreature
->GetGUID());
18488 data
<< uint32(vendorslot
+ 1); // numbered from 1 at client
18489 data
<< uint32(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
18490 data
<< uint32(count
);
18491 GetSession()->SendPacket(&data
);
18493 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
18495 AutoUnequipOffhandIfNeed();
18500 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
, NULL
, NULL
);
18504 return crItem
->maxcount
!= 0;
18507 uint32
Player::GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot
)
18509 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
18510 // the personal rating of the arena team must match the required limit as well
18511 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
18512 uint32 max_personal_rating
= 0;
18513 for(int i
= minarenaslot
; i
< MAX_ARENA_SLOT
; ++i
)
18515 if(ArenaTeam
* at
= sObjectMgr
.GetArenaTeamById(GetArenaTeamId(i
)))
18517 uint32 p_rating
= GetArenaPersonalRating(i
);
18518 uint32 t_rating
= at
->GetRating();
18519 p_rating
= p_rating
< t_rating
? p_rating
: t_rating
;
18520 if(max_personal_rating
< p_rating
)
18521 max_personal_rating
= p_rating
;
18524 return max_personal_rating
;
18527 void Player::UpdateHomebindTime(uint32 time
)
18529 // GMs never get homebind timer online
18530 if (m_InstanceValid
|| isGameMaster())
18532 if(m_HomebindTimer
) // instance valid, but timer not reset
18535 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
18537 data
<< uint32(ERR_RAID_GROUP_NONE
); // error used only when timer = 0
18538 GetSession()->SendPacket(&data
);
18540 // instance is valid, reset homebind timer
18541 m_HomebindTimer
= 0;
18543 else if (m_HomebindTimer
> 0)
18545 if (time
>= m_HomebindTimer
)
18547 // teleport to nearest graveyard
18548 RepopAtGraveyard();
18551 m_HomebindTimer
-= time
;
18555 // instance is invalid, start homebind timer
18556 m_HomebindTimer
= 60000;
18557 // send message to player
18558 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
18559 data
<< uint32(m_HomebindTimer
);
18560 data
<< uint32(ERR_RAID_GROUP_NONE
); // error used only when timer = 0
18561 GetSession()->SendPacket(&data
);
18562 sLog
.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
18566 void Player::UpdatePvP(bool state
, bool ovrride
)
18568 if(!state
|| ovrride
)
18571 pvpInfo
.endTimer
= 0;
18575 if(pvpInfo
.endTimer
!= 0)
18576 pvpInfo
.endTimer
= time(NULL
);
18582 void Player::AddSpellAndCategoryCooldowns(SpellEntry
const* spellInfo
, uint32 itemId
, Spell
* spell
, bool infinityCooldown
)
18584 // init cooldown values
18589 // some special item spells without correct cooldown in SpellInfo
18590 // cooldown information stored in item prototype
18591 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
18595 if(ItemPrototype
const* proto
= ObjectMgr::GetItemPrototype(itemId
))
18597 for(int idx
= 0; idx
< 5; ++idx
)
18599 if(proto
->Spells
[idx
].SpellId
== spellInfo
->Id
)
18601 cat
= proto
->Spells
[idx
].SpellCategory
;
18602 rec
= proto
->Spells
[idx
].SpellCooldown
;
18603 catrec
= proto
->Spells
[idx
].SpellCategoryCooldown
;
18610 // if no cooldown found above then base at DBC data
18611 if(rec
< 0 && catrec
< 0)
18613 cat
= spellInfo
->Category
;
18614 rec
= spellInfo
->RecoveryTime
;
18615 catrec
= spellInfo
->CategoryRecoveryTime
;
18618 time_t curTime
= time(NULL
);
18623 // overwrite time for selected category
18624 if(infinityCooldown
)
18626 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
18627 // but not allow ignore until reset or re-login
18628 catrecTime
= catrec
> 0 ? curTime
+infinityCooldownDelay
: 0;
18629 recTime
= rec
> 0 ? curTime
+infinityCooldownDelay
: catrecTime
;
18633 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
18634 // prevent 0 cooldowns set by another way
18635 if (rec
<= 0 && catrec
<= 0 && (cat
== 76 || IsAutoRepeatRangedSpell(spellInfo
) && spellInfo
->Id
!= SPELL_ID_AUTOSHOT
))
18636 rec
= GetAttackTime(RANGED_ATTACK
);
18638 // Now we have cooldown data (if found any), time to apply mods
18640 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, rec
, spell
);
18643 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, catrec
, spell
);
18645 // replace negative cooldowns by 0
18646 if (rec
< 0) rec
= 0;
18647 if (catrec
< 0) catrec
= 0;
18649 // no cooldown after applying spell mods
18650 if( rec
== 0 && catrec
== 0)
18653 catrecTime
= catrec
? curTime
+catrec
/IN_MILLISECONDS
: 0;
18654 recTime
= rec
? curTime
+rec
/IN_MILLISECONDS
: catrecTime
;
18657 // self spell cooldown
18659 AddSpellCooldown(spellInfo
->Id
, itemId
, recTime
);
18662 if (cat
&& catrec
> 0)
18664 SpellCategoryStore::const_iterator i_scstore
= sSpellCategoryStore
.find(cat
);
18665 if(i_scstore
!= sSpellCategoryStore
.end())
18667 for(SpellCategorySet::const_iterator i_scset
= i_scstore
->second
.begin(); i_scset
!= i_scstore
->second
.end(); ++i_scset
)
18669 if(*i_scset
== spellInfo
->Id
) // skip main spell, already handled above
18672 AddSpellCooldown(*i_scset
, itemId
, catrecTime
);
18678 void Player::AddSpellCooldown(uint32 spellid
, uint32 itemid
, time_t end_time
)
18682 sc
.itemid
= itemid
;
18683 m_spellCooldowns
[spellid
] = sc
;
18686 void Player::SendCooldownEvent(SpellEntry
const *spellInfo
, uint32 itemId
, Spell
* spell
)
18688 // start cooldowns at server side, if any
18689 AddSpellAndCategoryCooldowns(spellInfo
, itemId
, spell
);
18691 // Send activate cooldown timer (possible 0) at client side
18692 WorldPacket
data(SMSG_COOLDOWN_EVENT
, (4+8));
18693 data
<< uint32(spellInfo
->Id
);
18694 data
<< uint64(GetGUID());
18695 SendDirectMessage(&data
);
18698 void Player::UpdatePotionCooldown(Spell
* spell
)
18700 // no potion used i combat or still in combat
18701 if(!m_lastPotionId
|| isInCombat())
18704 // Call not from spell cast, send cooldown event for item spells if no in combat
18707 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
18708 if(ItemPrototype
const* proto
= ObjectMgr::GetItemPrototype(m_lastPotionId
))
18709 for(int idx
= 0; idx
< 5; ++idx
)
18710 if(proto
->Spells
[idx
].SpellId
&& proto
->Spells
[idx
].SpellTrigger
== ITEM_SPELLTRIGGER_ON_USE
)
18711 if(SpellEntry
const* spellInfo
= sSpellStore
.LookupEntry(proto
->Spells
[idx
].SpellId
))
18712 SendCooldownEvent(spellInfo
,m_lastPotionId
);
18714 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
18716 SendCooldownEvent(spell
->m_spellInfo
,m_lastPotionId
,spell
);
18718 m_lastPotionId
= 0;
18721 //slot to be excluded while counting
18722 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition
, int8 slot
)
18724 if(!enchantmentcondition
)
18727 SpellItemEnchantmentConditionEntry
const *Condition
= sSpellItemEnchantmentConditionStore
.LookupEntry(enchantmentcondition
);
18732 uint8 curcount
[4] = {0, 0, 0, 0};
18734 //counting current equipped gem colors
18735 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
18739 Item
*pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
18740 if(pItem2
&& !pItem2
->IsBroken() && pItem2
->GetProto()->Socket
[0].Color
)
18742 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
18744 uint32 enchant_id
= pItem2
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
18748 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
18752 uint32 gemid
= enchantEntry
->GemID
;
18756 ItemPrototype
const* gemProto
= sItemStorage
.LookupEntry
<ItemPrototype
>(gemid
);
18760 GemPropertiesEntry
const* gemProperty
= sGemPropertiesStore
.LookupEntry(gemProto
->GemProperties
);
18764 uint8 GemColor
= gemProperty
->color
;
18766 for(uint8 b
= 0, tmpcolormask
= 1; b
< 4; b
++, tmpcolormask
<<= 1)
18768 if(tmpcolormask
& GemColor
)
18775 bool activate
= true;
18777 for(int i
= 0; i
< 5; ++i
)
18779 if(!Condition
->Color
[i
])
18782 uint32 _cur_gem
= curcount
[Condition
->Color
[i
] - 1];
18784 // if have <CompareColor> use them as count, else use <value> from Condition
18785 uint32 _cmp_gem
= Condition
->CompareColor
[i
] ? curcount
[Condition
->CompareColor
[i
] - 1]: Condition
->Value
[i
];
18787 switch(Condition
->Comparator
[i
])
18789 case 2: // requires less <color> than (<value> || <comparecolor>) gems
18790 activate
&= (_cur_gem
< _cmp_gem
) ? true : false;
18792 case 3: // requires more <color> than (<value> || <comparecolor>) gems
18793 activate
&= (_cur_gem
> _cmp_gem
) ? true : false;
18795 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
18796 activate
&= (_cur_gem
>= _cmp_gem
) ? true : false;
18801 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");
18806 void Player::CorrectMetaGemEnchants(uint8 exceptslot
, bool apply
)
18808 //cycle all equipped items
18809 for(uint32 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
18811 //enchants for the slot being socketed are handled by Player::ApplyItemMods
18812 if(slot
== exceptslot
)
18815 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
18817 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
)
18820 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
18822 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
18826 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
18830 uint32 condition
= enchantEntry
->EnchantmentCondition
;
18833 //was enchant active with/without item?
18834 bool wasactive
= EnchantmentFitsRequirements(condition
, apply
? exceptslot
: -1);
18835 //should it now be?
18836 if(wasactive
!= EnchantmentFitsRequirements(condition
, apply
? -1 : exceptslot
))
18838 // ignore item gem conditions
18839 //if state changed, (dis)apply enchant
18840 ApplyEnchantment(pItem
, EnchantmentSlot(enchant_slot
), !wasactive
, true, true);
18847 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
18848 void Player::ToggleMetaGemsActive(uint8 exceptslot
, bool apply
)
18850 //cycle all equipped items
18851 for(int slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
18853 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
18854 if(slot
== exceptslot
)
18857 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
18859 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
) //if item has no sockets or no item is equipped go to next item
18862 //cycle all (gem)enchants
18863 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
18865 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
18866 if(!enchant_id
) //if no enchant go to next enchant(slot)
18869 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
18873 //only metagems to be (de)activated, so only enchants with condition
18874 uint32 condition
= enchantEntry
->EnchantmentCondition
;
18876 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
), apply
);
18881 void Player::SetBattleGroundEntryPoint()
18884 if (!m_taxi
.empty())
18886 m_bgData
.mountSpell
= 0;
18887 m_bgData
.taxiPath
[0] = m_taxi
.GetTaxiSource();
18888 m_bgData
.taxiPath
[1] = m_taxi
.GetTaxiDestination();
18890 // On taxi we don't need check for dungeon
18891 m_bgData
.joinPos
= WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
18896 m_bgData
.ClearTaxiPath();
18898 // Mount spell id storing
18901 AuraList
const& auras
= GetAurasByType(SPELL_AURA_MOUNTED
);
18902 if (!auras
.empty())
18903 m_bgData
.mountSpell
= (*auras
.begin())->GetId();
18906 m_bgData
.mountSpell
= 0;
18908 // If map is dungeon find linked graveyard
18909 if(GetMap()->IsDungeon())
18911 if (const WorldSafeLocsEntry
* entry
= sObjectMgr
.GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
18913 m_bgData
.joinPos
= WorldLocation(entry
->map_id
, entry
->x
, entry
->y
, entry
->z
, 0.0f
);
18917 sLog
.outError("SetBattleGroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId());
18919 // If new entry point is not BG or arena set it
18920 else if (!GetMap()->IsBattleGroundOrArena())
18922 m_bgData
.joinPos
= WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
18927 // In error cases use homebind position
18928 m_bgData
.joinPos
= WorldLocation(m_homebindMapId
, m_homebindX
, m_homebindY
, m_homebindZ
, 0.0f
);
18931 void Player::LeaveBattleground(bool teleportToEntryPoint
)
18933 if(BattleGround
*bg
= GetBattleGround())
18935 bg
->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint
, true);
18937 // call after remove to be sure that player resurrected for correct cast
18938 if( bg
->isBattleGround() && !isGameMaster() && sWorld
.getConfig(CONFIG_BOOL_BATTLEGROUND_CAST_DESERTER
) )
18940 if( bg
->GetStatus() == STATUS_IN_PROGRESS
|| bg
->GetStatus() == STATUS_WAIT_JOIN
)
18942 //lets check if player was teleported from BG and schedule delayed Deserter spell cast
18943 if(IsBeingTeleportedFar())
18945 ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER
);
18949 CastSpell(this, 26013, true); // Deserter
18955 bool Player::CanJoinToBattleground() const
18957 // check Deserter debuff
18958 if(GetDummyAura(26013))
18964 bool Player::CanReportAfkDueToLimit()
18966 // a player can complain about 15 people per 5 minutes
18967 if(m_bgData
.bgAfkReportedCount
++ >= 15)
18973 ///This player has been blamed to be inactive in a battleground
18974 void Player::ReportedAfkBy(Player
* reporter
)
18976 BattleGround
*bg
= GetBattleGround();
18977 if(!bg
|| bg
!= reporter
->GetBattleGround() || GetTeam() != reporter
->GetTeam())
18980 // check if player has 'Idle' or 'Inactive' debuff
18981 if(m_bgData
.bgAfkReporter
.find(reporter
->GetGUIDLow()) == m_bgData
.bgAfkReporter
.end() && !HasAura(43680, EFFECT_INDEX_0
) && !HasAura(43681, EFFECT_INDEX_0
) && reporter
->CanReportAfkDueToLimit())
18983 m_bgData
.bgAfkReporter
.insert(reporter
->GetGUIDLow());
18984 // 3 players have to complain to apply debuff
18985 if(m_bgData
.bgAfkReporter
.size() >= 3)
18987 // cast 'Idle' spell
18988 CastSpell(this, 43680, true);
18989 m_bgData
.bgAfkReporter
.clear();
18994 WorldObject
const* Player::GetViewPoint() const
18996 if(uint64 far_sight
= GetFarSight())
18998 WorldObject
const* viewPoint
= GetMap()->GetWorldObject(far_sight
);
18999 return viewPoint
? viewPoint
: this; // always expected not NULL
19005 bool Player::IsVisibleInGridForPlayer( Player
* pl
) const
19007 // gamemaster in GM mode see all, including ghosts
19008 if(pl
->isGameMaster() && GetSession()->GetSecurity() <= pl
->GetSession()->GetSecurity())
19011 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
19012 if (InBattleGround())
19014 if (!(isAlive() || m_deathTimer
> 0) && !IsFriendlyTo(pl
) )
19019 // Live player see live player or dead player with not realized corpse
19020 if(pl
->isAlive() || pl
->m_deathTimer
> 0)
19022 return isAlive() || m_deathTimer
> 0;
19025 // Ghost see other friendly ghosts, that's for sure
19026 if(!(isAlive() || m_deathTimer
> 0) && IsFriendlyTo(pl
))
19029 // Dead player see live players near own corpse
19032 Corpse
*corpse
= pl
->GetCorpse();
19035 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
19036 if(corpse
->IsWithinDistInMap(this,(20+25)*sWorld
.getConfig(CONFIG_FLOAT_RATE_CREATURE_AGGRO
)))
19041 // and not see any other
19045 bool Player::IsVisibleGloballyFor( Player
* u
) const
19050 // Always can see self
19054 // Visible units, always are visible for all players
19055 if (GetVisibility() == VISIBILITY_ON
)
19058 // GMs are visible for higher gms (or players are visible for gms)
19059 if (u
->GetSession()->GetSecurity() > SEC_PLAYER
)
19060 return GetSession()->GetSecurity() <= u
->GetSession()->GetSecurity();
19062 // non faction visibility non-breakable for non-GMs
19063 if (GetVisibility() == VISIBILITY_OFF
)
19066 // non-gm stealth/invisibility not hide from global player lists
19071 inline void BeforeVisibilityDestroy(T
* /*t*/, Player
* /*p*/)
19076 inline void BeforeVisibilityDestroy
<Creature
>(Creature
* t
, Player
* p
)
19078 if (p
->GetPetGUID()==t
->GetGUID() && ((Creature
*)t
)->isPet())
19079 ((Pet
*)t
)->Remove(PET_SAVE_NOT_IN_SLOT
, true);
19082 void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, WorldObject
* target
)
19084 if(HaveAtClient(target
))
19086 if(!target
->isVisibleForInState(this, viewPoint
, true))
19088 if (target
->GetTypeId()==TYPEID_UNIT
)
19089 BeforeVisibilityDestroy
<Creature
>((Creature
*)target
,this);
19091 ObjectGuid t_guid
= target
->GetGUID();
19093 target
->DestroyForPlayer(this);
19094 m_clientGUIDs
.erase(t_guid
);
19096 #ifdef MANGOS_DEBUG
19097 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
19098 sLog
.outDebug("%s out of range for player %u. Distance = %f",t_guid
.GetString().c_str(),GetGUIDLow(),GetDistance(target
));
19104 if(target
->isVisibleForInState(this, viewPoint
, false))
19106 target
->SendCreateUpdateToPlayer(this);
19107 if(target
->GetTypeId()!=TYPEID_GAMEOBJECT
||!((GameObject
*)target
)->IsTransport())
19108 m_clientGUIDs
.insert(target
->GetObjectGuid());
19110 #ifdef MANGOS_DEBUG
19111 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
19112 sLog
.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
19115 // target aura duration for caster show only if target exist at caster client
19116 // send data at target visibility change (adding to client)
19117 if(target
!=this && target
->isType(TYPEMASK_UNIT
))
19118 SendAurasForTarget((Unit
*)target
);
19120 if(target
->GetTypeId()==TYPEID_UNIT
&& ((Creature
*)target
)->isAlive())
19121 ((Creature
*)target
)->SendMonsterMoveWithSpeedToCurrentDestination(this);
19127 inline void UpdateVisibilityOf_helper(ObjectGuidSet
& s64
, T
* target
)
19129 s64
.insert(target
->GetGUID());
19133 inline void UpdateVisibilityOf_helper(ObjectGuidSet
& s64
, GameObject
* target
)
19135 if(!target
->IsTransport())
19136 s64
.insert(target
->GetGUID());
19140 void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, T
* target
, UpdateData
& data
, UpdateDataMapType
& /*data_updates*/, std::set
<WorldObject
*>& visibleNow
)
19142 if(HaveAtClient(target
))
19144 if(!target
->isVisibleForInState(this,viewPoint
,true))
19146 BeforeVisibilityDestroy
<T
>(target
,this);
19148 ObjectGuid t_guid
= target
->GetObjectGuid();
19150 target
->BuildOutOfRangeUpdateBlock(&data
);
19151 m_clientGUIDs
.erase(t_guid
);
19153 #ifdef MANGOS_DEBUG
19154 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
19155 sLog
.outDebug("%s is out of range for %s. Distance = %f",t_guid
.GetString().c_str(),GetObjectGuid().GetString().c_str(),GetDistance(target
));
19161 if(target
->isVisibleForInState(this,viewPoint
,false))
19163 visibleNow
.insert(target
);
19164 target
->BuildCreateUpdateBlockForPlayer(&data
, this);
19165 UpdateVisibilityOf_helper(m_clientGUIDs
,target
);
19167 #ifdef MANGOS_DEBUG
19168 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
19169 sLog
.outDebug("%s is visible now for %s. Distance = %f",target
->GetObjectGuid().GetString().c_str(),GetObjectGuid().GetString().c_str(),GetDistance(target
));
19175 template void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, Player
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
19176 template void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, Creature
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
19177 template void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, Corpse
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
19178 template void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, GameObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
19179 template void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, DynamicObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
19181 void Player::InitPrimaryProfessions()
19183 SetFreePrimaryProfessions(sWorld
.getConfig(CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL
));
19186 void Player::SendComboPoints()
19188 Unit
*combotarget
= ObjectAccessor::GetUnit(*this, m_comboTarget
);
19191 WorldPacket
data(SMSG_UPDATE_COMBO_POINTS
, combotarget
->GetPackGUID().size()+1);
19192 data
<< combotarget
->GetPackGUID();
19193 data
<< uint8(m_comboPoints
);
19194 GetSession()->SendPacket(&data
);
19198 void Player::AddComboPoints(Unit
* target
, int8 count
)
19203 // without combo points lost (duration checked in aura)
19204 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
19206 if(target
->GetGUID() == m_comboTarget
)
19208 m_comboPoints
+= count
;
19213 if(Unit
* target2
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
19214 target2
->RemoveComboPointHolder(GetGUIDLow());
19216 m_comboTarget
= target
->GetGUID();
19217 m_comboPoints
= count
;
19219 target
->AddComboPointHolder(GetGUIDLow());
19222 if (m_comboPoints
> 5) m_comboPoints
= 5;
19223 if (m_comboPoints
< 0) m_comboPoints
= 0;
19228 void Player::ClearComboPoints()
19233 // without combopoints lost (duration checked in aura)
19234 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
19240 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
19241 target
->RemoveComboPointHolder(GetGUIDLow());
19246 void Player::SetGroup(Group
*group
, int8 subgroup
)
19252 // never use SetGroup without a subgroup unless you specify NULL for group
19253 ASSERT(subgroup
>= 0);
19254 m_group
.link(group
, this);
19255 m_group
.setSubGroup((uint8
)subgroup
);
19259 void Player::SendInitialPacketsBeforeAddToMap()
19261 GetSocial()->SendSocialList();
19264 WorldPacket
data(SMSG_BINDPOINTUPDATE
, 5*4);
19265 data
<< m_homebindX
<< m_homebindY
<< m_homebindZ
;
19266 data
<< (uint32
) m_homebindMapId
;
19267 data
<< (uint32
) m_homebindAreaId
;
19268 GetSession()->SendPacket(&data
);
19270 // SMSG_SET_PROFICIENCY
19271 // SMSG_SET_PCT_SPELL_MODIFIER
19272 // SMSG_SET_FLAT_SPELL_MODIFIER
19274 SendTalentsInfoData(false);
19276 data
.Initialize(SMSG_INSTANCE_DIFFICULTY
, 4+4);
19279 GetSession()->SendPacket(&data
);
19281 SendInitialSpells();
19283 data
.Initialize(SMSG_SEND_UNLEARN_SPELLS
, 4);
19284 data
<< uint32(0); // count, for(count) uint32;
19285 GetSession()->SendPacket(&data
);
19287 SendInitialActionButtons();
19288 m_reputationMgr
.SendInitialReputations();
19291 SendCorpseReclaimDelay(true);
19293 SendInitWorldStates(GetZoneId(), GetAreaId());
19295 SendEquipmentSetList();
19297 m_achievementMgr
.SendAllAchievementData();
19299 data
.Initialize(SMSG_LOGIN_SETTIMESPEED
, 4 + 4 + 4);
19300 data
<< uint32(secsToTimeBitFields(sWorld
.GetGameTime()));
19301 data
<< (float)0.01666667f
; // game speed
19302 data
<< uint32(0); // added in 3.1.2
19303 GetSession()->SendPacket( &data
);
19305 // SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...)
19307 // SMSG_POWER_UPDATE
19309 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
19310 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
) || HasAuraType(SPELL_AURA_FLY
) || isInFlight())
19311 m_movementInfo
.AddMovementFlag(MOVEFLAG_FLYING
);
19316 void Player::SendInitialPacketsAfterAddToMap()
19319 uint32 newzone
, newarea
;
19320 GetZoneAndAreaId(newzone
,newarea
);
19321 UpdateZone(newzone
,newarea
); // also call SendInitWorldStates();
19326 CastSpell(this, 836, true); // LOGINEFFECT
19328 // set some aura effects that send packet to player client after add player to map
19329 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
19330 // same auras state lost at far teleport, send it one more time in this case also
19331 static const AuraType auratypes
[] =
19333 SPELL_AURA_MOD_FEAR
, SPELL_AURA_TRANSFORM
, SPELL_AURA_WATER_WALK
,
19334 SPELL_AURA_FEATHER_FALL
, SPELL_AURA_HOVER
, SPELL_AURA_SAFE_FALL
,
19335 SPELL_AURA_FLY
, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
, SPELL_AURA_NONE
19337 for(AuraType
const* itr
= &auratypes
[0]; itr
&& itr
[0] != SPELL_AURA_NONE
; ++itr
)
19339 Unit::AuraList
const& auraList
= GetAurasByType(*itr
);
19340 if(!auraList
.empty())
19341 auraList
.front()->ApplyModifier(true,true);
19344 if(HasAuraType(SPELL_AURA_MOD_STUN
))
19345 SetMovement(MOVE_ROOT
);
19347 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
19348 if(HasAuraType(SPELL_AURA_MOD_ROOT
))
19350 WorldPacket
data2(SMSG_FORCE_MOVE_ROOT
, 10);
19351 data2
<< GetPackGUID();
19352 data2
<< (uint32
)2;
19353 SendMessageToSet(&data2
,true);
19356 SendAurasForTarget(this);
19357 SendEnchantmentDurations(); // must be after add to map
19358 SendItemDurations(); // must be after add to map
19361 void Player::SendUpdateToOutOfRangeGroupMembers()
19363 if (m_groupUpdateMask
== GROUP_UPDATE_FLAG_NONE
)
19365 if(Group
* group
= GetGroup())
19366 group
->UpdatePlayerOutOfRange(this);
19368 m_groupUpdateMask
= GROUP_UPDATE_FLAG_NONE
;
19369 m_auraUpdateMask
= 0;
19370 if(Pet
*pet
= GetPet())
19371 pet
->ResetAuraUpdateMask();
19374 void Player::SendTransferAborted(uint32 mapid
, uint8 reason
, uint8 arg
)
19376 WorldPacket
data(SMSG_TRANSFER_ABORTED
, 4+2);
19377 data
<< uint32(mapid
);
19378 data
<< uint8(reason
); // transfer abort reason
19381 case TRANSFER_ABORT_INSUF_EXPAN_LVL
:
19382 case TRANSFER_ABORT_DIFFICULTY
:
19383 case TRANSFER_ABORT_UNIQUE_MESSAGE
:
19384 data
<< uint8(arg
);
19387 GetSession()->SendPacket(&data
);
19390 void Player::SendInstanceResetWarning( uint32 mapid
, Difficulty difficulty
, uint32 time
)
19392 // type of warning, based on the time remaining until reset
19395 type
= RAID_INSTANCE_WELCOME
;
19396 else if(time
> 900 && time
<= 3600)
19397 type
= RAID_INSTANCE_WARNING_HOURS
;
19398 else if(time
> 300 && time
<= 900)
19399 type
= RAID_INSTANCE_WARNING_MIN
;
19401 type
= RAID_INSTANCE_WARNING_MIN_SOON
;
19403 WorldPacket
data(SMSG_RAID_INSTANCE_MESSAGE
, 4+4+4+4);
19404 data
<< uint32(type
);
19405 data
<< uint32(mapid
);
19406 data
<< uint32(difficulty
); // difficulty
19407 data
<< uint32(time
);
19408 if(type
== RAID_INSTANCE_WELCOME
)
19410 data
<< uint8(0); // is your (1)
19411 data
<< uint8(0); // is extended (1), ignored if prev field is 0
19413 GetSession()->SendPacket(&data
);
19416 void Player::ApplyEquipCooldown( Item
* pItem
)
19418 for(int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
19420 _Spell
const& spellData
= pItem
->GetProto()->Spells
[i
];
19423 if( !spellData
.SpellId
)
19426 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
19427 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
)
19430 AddSpellCooldown(spellData
.SpellId
, pItem
->GetEntry(), time(NULL
) + 30);
19432 WorldPacket
data(SMSG_ITEM_COOLDOWN
, 12);
19433 data
<< pItem
->GetGUID();
19434 data
<< uint32(spellData
.SpellId
);
19435 GetSession()->SendPacket(&data
);
19439 void Player::resetSpells()
19441 // not need after this call
19442 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS
))
19443 RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS
,true);
19445 // make full copy of map (spells removed and marked as deleted at another spell remove
19446 // and we can't use original map for safe iterative with visit each spell at loop end
19447 PlayerSpellMap smap
= GetSpellMap();
19449 for(PlayerSpellMap::const_iterator iter
= smap
.begin();iter
!= smap
.end(); ++iter
)
19450 removeSpell(iter
->first
,false,false); // only iter->first can be accessed, object by iter->second can be deleted already
19452 learnDefaultSpells();
19453 learnQuestRewardedSpells();
19456 void Player::learnDefaultSpells()
19458 // learn default race/class spells
19459 PlayerInfo
const *info
= sObjectMgr
.GetPlayerInfo(getRace(),getClass());
19460 for (PlayerCreateInfoSpells::const_iterator itr
= info
->spell
.begin(); itr
!=info
->spell
.end(); ++itr
)
19462 uint32 tspell
= *itr
;
19463 sLog
.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell
);
19464 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
19465 addSpell(tspell
, true, true, true, false);
19466 else // but send in normal spell in game learn case
19467 learnSpell(tspell
, true);
19471 void Player::learnQuestRewardedSpells(Quest
const* quest
)
19473 uint32 spell_id
= quest
->GetRewSpellCast();
19475 // skip quests without rewarded spell
19479 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
19483 // check learned spells state
19484 bool found
= false;
19485 for(int i
=0; i
< MAX_EFFECT_INDEX
; ++i
)
19487 if(spellInfo
->Effect
[i
] == SPELL_EFFECT_LEARN_SPELL
&& !HasSpell(spellInfo
->EffectTriggerSpell
[i
]))
19494 // skip quests with not teaching spell or already known spell
19498 // prevent learn non first rank unknown profession and second specialization for same profession)
19499 uint32 learned_0
= spellInfo
->EffectTriggerSpell
[EFFECT_INDEX_0
];
19500 if( sSpellMgr
.GetSpellRank(learned_0
) > 1 && !HasSpell(learned_0
) )
19502 // not have first rank learned (unlearned prof?)
19503 uint32 first_spell
= sSpellMgr
.GetFirstSpellInChain(learned_0
);
19504 if( !HasSpell(first_spell
) )
19507 SpellEntry
const *learnedInfo
= sSpellStore
.LookupEntry(learned_0
);
19512 if (learnedInfo
->Effect
[EFFECT_INDEX_0
] == SPELL_EFFECT_TRADE_SKILL
&& learnedInfo
->Effect
[EFFECT_INDEX_1
] == 0)
19514 // search other specialization for same prof
19515 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
19517 if(itr
->second
.state
== PLAYERSPELL_REMOVED
|| itr
->first
==learned_0
)
19520 SpellEntry
const *itrInfo
= sSpellStore
.LookupEntry(itr
->first
);
19524 // compare only specializations
19525 if (itrInfo
->Effect
[EFFECT_INDEX_0
] != SPELL_EFFECT_TRADE_SKILL
|| itrInfo
->Effect
[EFFECT_INDEX_1
] != 0)
19528 // compare same chain spells
19529 if(sSpellMgr
.GetFirstSpellInChain(itr
->first
) != first_spell
)
19532 // now we have 2 specialization, learn possible only if found is lesser specialization rank
19533 if(!sSpellMgr
.IsHighRankOfSpell(learned_0
,itr
->first
))
19539 CastSpell( this, spell_id
, true);
19542 void Player::learnQuestRewardedSpells()
19544 // learn spells received from quest completing
19545 for(QuestStatusMap::const_iterator itr
= mQuestStatus
.begin(); itr
!= mQuestStatus
.end(); ++itr
)
19547 // skip no rewarded quests
19548 if(!itr
->second
.m_rewarded
)
19551 Quest
const* quest
= sObjectMgr
.GetQuestTemplate(itr
->first
);
19555 learnQuestRewardedSpells(quest
);
19559 void Player::learnSkillRewardedSpells(uint32 skill_id
, uint32 skill_value
)
19561 uint32 raceMask
= getRaceMask();
19562 uint32 classMask
= getClassMask();
19563 for (uint32 j
= 0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
19565 SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
);
19566 if (!pAbility
|| pAbility
->skillId
!=skill_id
|| pAbility
->learnOnGetSkill
!= ABILITY_LEARNED_ON_GET_PROFESSION_SKILL
)
19568 // Check race if set
19569 if (pAbility
->racemask
&& !(pAbility
->racemask
& raceMask
))
19571 // Check class if set
19572 if (pAbility
->classmask
&& !(pAbility
->classmask
& classMask
))
19575 if (sSpellStore
.LookupEntry(pAbility
->spellId
))
19577 // need unlearn spell
19578 if (skill_value
< pAbility
->req_skill_value
)
19579 removeSpell(pAbility
->spellId
);
19581 else if (!IsInWorld())
19582 addSpell(pAbility
->spellId
, true, true, true, false);
19584 learnSpell(pAbility
->spellId
, true);
19589 void Player::SendAurasForTarget(Unit
*target
)
19591 if(target
->GetVisibleAuras()->empty()) // speedup things
19594 WorldPacket
data(SMSG_AURA_UPDATE_ALL
);
19595 data
<< target
->GetPackGUID();
19597 Unit::VisibleAuraMap
const *visibleAuras
= target
->GetVisibleAuras();
19598 for(Unit::VisibleAuraMap::const_iterator itr
= visibleAuras
->begin(); itr
!= visibleAuras
->end(); ++itr
)
19600 for(int j
= 0; j
< MAX_EFFECT_INDEX
; ++j
)
19602 if(Aura
*aura
= target
->GetAura(itr
->second
, SpellEffectIndex(j
)))
19604 data
<< uint8(aura
->GetAuraSlot());
19605 data
<< uint32(aura
->GetId());
19609 uint8 auraFlags
= aura
->GetAuraFlags();
19611 data
<< uint8(auraFlags
);
19613 data
<< uint8(aura
->GetAuraLevel());
19615 if (aura
->GetAuraCharges())
19616 data
<< uint8(aura
->GetAuraCharges() * aura
->GetStackAmount());
19618 data
<< uint8(aura
->GetStackAmount());
19620 if(!(auraFlags
& AFLAG_NOT_CASTER
)) // packed GUID of caster
19622 data
.appendPackGUID(aura
->GetCasterGUID());
19625 if(auraFlags
& AFLAG_DURATION
) // include aura duration
19627 data
<< uint32(aura
->GetAuraMaxDuration());
19628 data
<< uint32(aura
->GetAuraDuration());
19636 GetSession()->SendPacket(&data
);
19639 void Player::SetDailyQuestStatus( uint32 quest_id
)
19641 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
19643 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
19645 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
19646 m_DailyQuestChanged
= true;
19652 void Player::SetWeeklyQuestStatus( uint32 quest_id
)
19654 m_weeklyquests
.insert(quest_id
);
19655 m_WeeklyQuestChanged
= true;
19658 void Player::ResetDailyQuestStatus()
19660 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
19661 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
19663 // DB data deleted in caller
19664 m_DailyQuestChanged
= false;
19667 void Player::ResetWeeklyQuestStatus()
19669 if (m_weeklyquests
.empty())
19672 m_weeklyquests
.clear();
19673 // DB data deleted in caller
19674 m_WeeklyQuestChanged
= false;
19677 BattleGround
* Player::GetBattleGround() const
19679 if(GetBattleGroundId()==0)
19682 return sBattleGroundMgr
.GetBattleGround(GetBattleGroundId(), m_bgData
.bgTypeID
);
19685 bool Player::InArena() const
19687 BattleGround
*bg
= GetBattleGround();
19688 if(!bg
|| !bg
->isArena())
19694 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId
) const
19696 // get a template bg instead of running one
19697 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGroundTemplate(bgTypeId
);
19701 // limit check leel to dbc compatible level range
19702 uint32 level
= getLevel();
19703 if (level
> DEFAULT_MAX_LEVEL
)
19704 level
= DEFAULT_MAX_LEVEL
;
19706 if(level
< bg
->GetMinLevel() || level
> bg
->GetMaxLevel())
19712 float Player::GetReputationPriceDiscount( Creature
const* pCreature
) const
19714 FactionTemplateEntry
const* vendor_faction
= pCreature
->getFactionTemplateEntry();
19715 if(!vendor_faction
|| !vendor_faction
->faction
)
19718 ReputationRank rank
= GetReputationRank(vendor_faction
->faction
);
19719 if(rank
<= REP_NEUTRAL
)
19722 return 1.0f
- 0.05f
* (rank
- REP_NEUTRAL
);
19725 bool Player::IsSpellFitByClassAndRace( uint32 spell_id
) const
19727 uint32 racemask
= getRaceMask();
19728 uint32 classmask
= getClassMask();
19730 SkillLineAbilityMapBounds bounds
= sSpellMgr
.GetSkillLineAbilityMapBounds(spell_id
);
19731 if (bounds
.first
==bounds
.second
)
19734 for(SkillLineAbilityMap::const_iterator _spell_idx
= bounds
.first
; _spell_idx
!= bounds
.second
; ++_spell_idx
)
19736 // skip wrong race skills
19737 if (_spell_idx
->second
->racemask
&& (_spell_idx
->second
->racemask
& racemask
) == 0)
19740 // skip wrong class skills
19741 if (_spell_idx
->second
->classmask
&& (_spell_idx
->second
->classmask
& classmask
) == 0)
19750 bool Player::HasQuestForGO(int32 GOId
) const
19752 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
19754 uint32 questid
= GetQuestSlotQuestId(i
);
19755 if ( questid
== 0 )
19758 QuestStatusMap::const_iterator qs_itr
= mQuestStatus
.find(questid
);
19759 if(qs_itr
== mQuestStatus
.end())
19762 QuestStatusData
const& qs
= qs_itr
->second
;
19764 if (qs
.m_status
== QUEST_STATUS_INCOMPLETE
)
19766 Quest
const* qinfo
= sObjectMgr
.GetQuestTemplate(questid
);
19770 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
19773 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
19775 if (qinfo
->ReqCreatureOrGOId
[j
]>=0) //skip non GO case
19778 if((-1)*GOId
== qinfo
->ReqCreatureOrGOId
[j
] && qs
.m_creatureOrGOcount
[j
] < qinfo
->ReqCreatureOrGOCount
[j
])
19786 void Player::UpdateForQuestWorldObjects()
19788 if(m_clientGUIDs
.empty())
19792 WorldPacket packet
;
19793 for(ObjectGuidSet::const_iterator itr
=m_clientGUIDs
.begin(); itr
!=m_clientGUIDs
.end(); ++itr
)
19795 if (itr
->IsGameobject())
19797 if (GameObject
*obj
= GetMap()->GetGameObject(*itr
))
19798 obj
->BuildValuesUpdateBlockForPlayer(&udata
,this);
19800 else if (itr
->IsCreatureOrVehicle())
19802 Creature
*obj
= GetMap()->GetCreatureOrPetOrVehicle(*itr
);
19806 // check if this unit requires quest specific flags
19807 if(!obj
->HasFlag(UNIT_NPC_FLAGS
,UNIT_NPC_FLAG_SPELLCLICK
))
19810 SpellClickInfoMapBounds clickPair
= sObjectMgr
.GetSpellClickInfoMapBounds(obj
->GetEntry());
19811 for(SpellClickInfoMap::const_iterator _itr
= clickPair
.first
; _itr
!= clickPair
.second
; ++_itr
)
19813 if(_itr
->second
.questStart
|| _itr
->second
.questEnd
)
19815 obj
->BuildCreateUpdateBlockForPlayer(&udata
,this);
19821 udata
.BuildPacket(&packet
);
19822 GetSession()->SendPacket(&packet
);
19825 void Player::SummonIfPossible(bool agree
)
19829 m_summon_expire
= 0;
19833 // expire and auto declined
19834 if(m_summon_expire
< time(NULL
))
19837 // stop taxi flight at summon
19840 GetMotionMaster()->MovementExpired();
19841 m_taxi
.ClearTaxiDestinations();
19844 // drop flag at summon
19845 // 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
19846 if(BattleGround
*bg
= GetBattleGround())
19847 bg
->EventPlayerDroppedFlag(this);
19849 m_summon_expire
= 0;
19851 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS
, 1);
19853 TeleportTo(m_summon_mapid
, m_summon_x
, m_summon_y
, m_summon_z
,GetOrientation());
19856 void Player::RemoveItemDurations( Item
*item
)
19858 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); ++itr
)
19862 m_itemDuration
.erase(itr
);
19868 void Player::AddItemDurations( Item
*item
)
19870 if(item
->GetUInt32Value(ITEM_FIELD_DURATION
))
19872 m_itemDuration
.push_back(item
);
19873 item
->SendTimeUpdate(this);
19877 void Player::AutoUnequipOffhandIfNeed()
19879 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
19883 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
19884 if (CanTitanGrip() || (offItem
->GetProto()->InventoryType
!= INVTYPE_2HWEAPON
&& !IsTwoHandUsed()))
19887 ItemPosCountVec off_dest
;
19888 uint8 off_msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false );
19889 if( off_msg
== EQUIP_ERR_OK
)
19891 RemoveItem(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
19892 StoreItem( off_dest
, offItem
, true );
19896 MoveItemFromInventory(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
19897 CharacterDatabase
.BeginTransaction();
19898 offItem
->DeleteFromInventoryDB(); // deletes item from character's inventory
19899 offItem
->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
19900 CharacterDatabase
.CommitTransaction();
19902 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
19903 MailDraft(subject
, "There's were problems with equipping this item.").AddItem(offItem
).SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM
));
19907 bool Player::HasItemFitToSpellReqirements(SpellEntry
const* spellInfo
, Item
const* ignoreItem
)
19909 if(spellInfo
->EquippedItemClass
< 0)
19912 // scan other equipped items for same requirements (mostly 2 daggers/etc)
19913 // for optimize check 2 used cases only
19914 switch(spellInfo
->EquippedItemClass
)
19916 case ITEM_CLASS_WEAPON
:
19918 for(int i
= EQUIPMENT_SLOT_MAINHAND
; i
< EQUIPMENT_SLOT_TABARD
; ++i
)
19919 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
19920 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
19924 case ITEM_CLASS_ARMOR
:
19926 // tabard not have dependent spells
19927 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_MAINHAND
; ++i
)
19928 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
19929 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
19932 // shields can be equipped to offhand slot
19933 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
))
19934 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
19937 // ranged slot can have some armor subclasses
19938 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_RANGED
))
19939 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
19945 sLog
.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo
->EquippedItemClass
);
19952 bool Player::CanNoReagentCast(SpellEntry
const* spellInfo
) const
19954 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
19955 if (spellInfo
->AttributesEx5
& SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
&&
19956 HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PREPARATION
))
19959 // Check no reagent use mask
19960 uint64 noReagentMask_0_1
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
);
19961 uint32 noReagentMask_2
= GetUInt32Value(PLAYER_NO_REAGENT_COST_1
+2);
19962 if (spellInfo
->SpellFamilyFlags
& noReagentMask_0_1
||
19963 spellInfo
->SpellFamilyFlags2
& noReagentMask_2
)
19969 void Player::RemoveItemDependentAurasAndCasts( Item
* pItem
)
19971 AuraMap
& auras
= GetAuras();
19972 for(AuraMap::const_iterator itr
= auras
.begin(); itr
!= auras
.end(); )
19974 Aura
* aura
= itr
->second
;
19976 // skip passive (passive item dependent spells work in another way) and not self applied auras
19977 SpellEntry
const* spellInfo
= aura
->GetSpellProto();
19978 if(aura
->IsPassive() || aura
->GetCasterGUID()!=GetGUID())
19984 // skip if not item dependent or have alternative item
19985 if(HasItemFitToSpellReqirements(spellInfo
,pItem
))
19991 // no alt item, remove aura, restart check
19992 RemoveAurasDueToSpell(aura
->GetId());
19993 itr
= auras
.begin();
19996 // currently casted spells can be dependent from item
19997 for (uint32 i
= 0; i
< CURRENT_MAX_SPELL
; ++i
)
19998 if (Spell
* spell
= GetCurrentSpell(CurrentSpellTypes(i
)))
19999 if (spell
->getState()!=SPELL_STATE_DELAYED
&& !HasItemFitToSpellReqirements(spell
->m_spellInfo
,pItem
) )
20000 InterruptSpell(CurrentSpellTypes(i
));
20003 uint32
Player::GetResurrectionSpellId()
20005 // search priceless resurrection possibilities
20007 uint32 spell_id
= 0;
20008 AuraList
const& dummyAuras
= GetAurasByType(SPELL_AURA_DUMMY
);
20009 for(AuraList::const_iterator itr
= dummyAuras
.begin(); itr
!= dummyAuras
.end(); ++itr
)
20011 // Soulstone Resurrection // prio: 3 (max, non death persistent)
20012 if( prio
< 2 && (*itr
)->GetSpellProto()->SpellVisual
[0] == 99 && (*itr
)->GetSpellProto()->SpellIconID
== 92 )
20014 switch((*itr
)->GetId())
20016 case 20707: spell_id
= 3026; break; // rank 1
20017 case 20762: spell_id
= 20758; break; // rank 2
20018 case 20763: spell_id
= 20759; break; // rank 3
20019 case 20764: spell_id
= 20760; break; // rank 4
20020 case 20765: spell_id
= 20761; break; // rank 5
20021 case 27239: spell_id
= 27240; break; // rank 6
20022 case 47883: spell_id
= 47882; break; // rank 7
20024 sLog
.outError("Unhandled spell %u: S.Resurrection",(*itr
)->GetId());
20030 // Twisting Nether // prio: 2 (max)
20031 else if((*itr
)->GetId()==23701 && roll_chance_i(10))
20038 // Reincarnation (passive spell) // prio: 1
20039 // Glyph of Renewed Life remove reagent requiremnnt
20040 if (prio
< 1 && HasSpell(20608) && !HasSpellCooldown(21169) && (HasItemCount(17030,1) || HasAura(58059, EFFECT_INDEX_0
)))
20046 // Used in triggers for check "Only to targets that grant experience or honor" req
20047 bool Player::isHonorOrXPTarget(Unit
* pVictim
) const
20049 uint32 v_level
= pVictim
->getLevel();
20050 uint32 k_grey
= MaNGOS::XP::GetGrayLevel(getLevel());
20052 // Victim level less gray level
20053 if(v_level
<=k_grey
)
20056 if(pVictim
->GetTypeId() == TYPEID_UNIT
)
20058 if (((Creature
*)pVictim
)->isTotem() ||
20059 ((Creature
*)pVictim
)->isPet() ||
20060 ((Creature
*)pVictim
)->GetCreatureInfo()->flags_extra
& CREATURE_FLAG_EXTRA_NO_XP_AT_KILL
)
20066 bool Player::RewardPlayerAndGroupAtKill(Unit
* pVictim
)
20068 bool PvP
= pVictim
->isCharmedOwnedByPlayerOrPlayer();
20070 // prepare data for near group iteration (PvP and !PvP cases)
20072 bool honored_kill
= false;
20074 if(Group
*pGroup
= GetGroup())
20077 uint32 sum_level
= 0;
20078 Player
* member_with_max_level
= NULL
;
20079 Player
* not_gray_member_with_max_level
= NULL
;
20081 pGroup
->GetDataForXPAtKill(pVictim
,count
,sum_level
,member_with_max_level
,not_gray_member_with_max_level
);
20083 if(member_with_max_level
)
20085 /// not get Xp in PvP or no not gray players in group
20086 xp
= (PvP
|| !not_gray_member_with_max_level
) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level
, pVictim
);
20088 /// skip in check PvP case (for speed, not used)
20089 bool is_raid
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsRaid() && pGroup
->isRaidGroup();
20090 bool is_dungeon
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsDungeon();
20091 float group_rate
= MaNGOS::XP::xp_in_group_rate(count
,is_raid
);
20093 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
20095 Player
* pGroupGuy
= itr
->getSource();
20099 if(!pGroupGuy
->IsAtGroupRewardDistance(pVictim
))
20100 continue; // member (alive or dead) or his corpse at req. distance
20102 // honor can be in PvP and !PvP (racial leader) cases (for alive)
20103 if(pGroupGuy
->isAlive() && pGroupGuy
->RewardHonor(pVictim
,count
) && pGroupGuy
==this)
20104 honored_kill
= true;
20106 // xp and reputation only in !PvP case
20109 float rate
= group_rate
* float(pGroupGuy
->getLevel()) / sum_level
;
20111 // if is in dungeon then all receive full reputation at kill
20112 // rewarded any alive/dead/near_corpse group member
20113 pGroupGuy
->RewardReputation(pVictim
,is_dungeon
? 1.0f
: rate
);
20115 // XP updated only for alive group member
20116 if(pGroupGuy
->isAlive() && not_gray_member_with_max_level
&&
20117 pGroupGuy
->getLevel() <= not_gray_member_with_max_level
->getLevel())
20119 uint32 itr_xp
= (member_with_max_level
== not_gray_member_with_max_level
) ? uint32(xp
*rate
) : uint32((xp
*rate
/2)+1);
20121 pGroupGuy
->GiveXP(itr_xp
, pVictim
);
20122 if(Pet
* pet
= pGroupGuy
->GetPet())
20123 pet
->GivePetXP(itr_xp
/2);
20126 // quest objectives updated only for alive group member or dead but with not released body
20127 if(pGroupGuy
->isAlive()|| !pGroupGuy
->HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
))
20129 // normal creature (not pet/etc) can be only in !PvP case
20130 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
20131 pGroupGuy
->KilledMonster(((Creature
*)pVictim
)->GetCreatureInfo(), pVictim
->GetObjectGuid());
20137 else // if (!pGroup)
20139 xp
= PvP
? 0 : MaNGOS::XP::Gain(this, pVictim
);
20141 // honor can be in PvP and !PvP (racial leader) cases
20142 if(RewardHonor(pVictim
,1))
20143 honored_kill
= true;
20145 // xp and reputation only in !PvP case
20148 RewardReputation(pVictim
,1);
20149 GiveXP(xp
, pVictim
);
20151 if(Pet
* pet
= GetPet())
20152 pet
->GivePetXP(xp
);
20154 // normal creature (not pet/etc) can be only in !PvP case
20155 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
20156 KilledMonster(((Creature
*)pVictim
)->GetCreatureInfo(), pVictim
->GetObjectGuid());
20159 return xp
|| honored_kill
;
20162 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id
, WorldObject
* pRewardSource
)
20164 uint64 creature_guid
= pRewardSource
->GetTypeId()==TYPEID_UNIT
? pRewardSource
->GetGUID() : uint64(0);
20166 // prepare data for near group iteration
20167 if(Group
*pGroup
= GetGroup())
20169 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
20171 Player
* pGroupGuy
= itr
->getSource();
20175 if(!pGroupGuy
->IsAtGroupRewardDistance(pRewardSource
))
20176 continue; // member (alive or dead) or his corpse at req. distance
20178 // quest objectives updated only for alive group member or dead but with not released body
20179 if(pGroupGuy
->isAlive()|| !pGroupGuy
->HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
))
20180 pGroupGuy
->KilledMonsterCredit(creature_id
, creature_guid
);
20183 else // if (!pGroup)
20184 KilledMonsterCredit(creature_id
, creature_guid
);
20187 bool Player::IsAtGroupRewardDistance(WorldObject
const* pRewardSource
) const
20189 if (pRewardSource
->IsWithinDistInMap(this,sWorld
.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE
)))
20195 Corpse
* corpse
= GetCorpse();
20199 return pRewardSource
->IsWithinDistInMap(corpse
,sWorld
.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE
));
20202 uint32
Player::GetBaseWeaponSkillValue (WeaponAttackType attType
) const
20204 Item
* item
= GetWeaponForAttack(attType
,true,true);
20206 // unarmed only with base attack
20207 if(attType
!= BASE_ATTACK
&& !item
)
20210 // weapon skill or (unarmed for base attack)
20211 uint32 skill
= item
? item
->GetSkill() : uint32(SKILL_UNARMED
);
20212 return GetBaseSkillValue(skill
);
20215 void Player::ResurectUsingRequestData()
20217 /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
20218 if(IS_PLAYER_GUID(m_resurrectGUID
))
20219 TeleportTo(m_resurrectMap
, m_resurrectX
, m_resurrectY
, m_resurrectZ
, GetOrientation());
20221 //we cannot resurrect player when we triggered far teleport
20222 //player will be resurrected upon teleportation
20223 if(IsBeingTeleportedFar())
20225 ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER
);
20229 ResurrectPlayer(0.0f
,false);
20231 if(GetMaxHealth() > m_resurrectHealth
)
20232 SetHealth( m_resurrectHealth
);
20234 SetHealth( GetMaxHealth() );
20236 if(GetMaxPower(POWER_MANA
) > m_resurrectMana
)
20237 SetPower(POWER_MANA
, m_resurrectMana
);
20239 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
) );
20241 SetPower(POWER_RAGE
, 0 );
20243 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
) );
20245 SpawnCorpseBones();
20248 void Player::SetClientControl(Unit
* target
, uint8 allowMove
)
20250 WorldPacket
data(SMSG_CLIENT_CONTROL_UPDATE
, target
->GetPackGUID().size()+1);
20251 data
<< target
->GetPackGUID();
20252 data
<< uint8(allowMove
);
20253 GetSession()->SendPacket(&data
);
20256 void Player::UpdateZoneDependentAuras( uint32 newZone
)
20258 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
20259 SpellAreaForAreaMapBounds saBounds
= sSpellMgr
.GetSpellAreaForAreaMapBounds(newZone
);
20260 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
20261 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,newZone
,0))
20262 if (!HasAura(itr
->second
->spellId
, EFFECT_INDEX_0
))
20263 CastSpell(this,itr
->second
->spellId
,true);
20266 void Player::UpdateAreaDependentAuras( uint32 newArea
)
20268 // remove auras from spells with area limitations
20269 for(AuraMap::iterator iter
= m_Auras
.begin(); iter
!= m_Auras
.end();)
20271 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
20272 if(sSpellMgr
.GetSpellAllowedInLocationError(iter
->second
->GetSpellProto(),GetMapId(),m_zoneUpdateId
,newArea
,this) != SPELL_CAST_OK
)
20278 // some auras applied at subzone enter
20279 SpellAreaForAreaMapBounds saBounds
= sSpellMgr
.GetSpellAreaForAreaMapBounds(newArea
);
20280 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
20281 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,m_zoneUpdateId
,newArea
))
20282 if (!HasAura(itr
->second
->spellId
, EFFECT_INDEX_0
))
20283 CastSpell(this,itr
->second
->spellId
,true);
20286 uint32
Player::GetCorpseReclaimDelay(bool pvp
) const
20288 if ((pvp
&& !sWorld
.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP
)) ||
20289 (!pvp
&& !sWorld
.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE
) ))
20291 return copseReclaimDelay
[0];
20294 time_t now
= time(NULL
);
20295 // 0..2 full period
20296 uint32 count
= (now
< m_deathExpireTime
) ? uint32((m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
) : 0;
20297 return copseReclaimDelay
[count
];
20300 void Player::UpdateCorpseReclaimDelay()
20302 bool pvp
= m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
;
20304 if ((pvp
&& !sWorld
.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP
)) ||
20305 (!pvp
&& !sWorld
.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE
) ))
20308 time_t now
= time(NULL
);
20309 if(now
< m_deathExpireTime
)
20311 // full and partly periods 1..3
20312 uint32 count
= uint32((m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
+1);
20313 if(count
< MAX_DEATH_COUNT
)
20314 m_deathExpireTime
= now
+(count
+1)*DEATH_EXPIRE_STEP
;
20316 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
;
20319 m_deathExpireTime
= now
+DEATH_EXPIRE_STEP
;
20322 void Player::SendCorpseReclaimDelay(bool load
)
20324 Corpse
* corpse
= GetCorpse();
20331 if(corpse
->GetGhostTime() > m_deathExpireTime
)
20334 bool pvp
= corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
;
20337 if( pvp
&& sWorld
.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
20338 !pvp
&& sWorld
.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
20340 count
= uint32(m_deathExpireTime
-corpse
->GetGhostTime())/DEATH_EXPIRE_STEP
;
20341 if(count
>=MAX_DEATH_COUNT
)
20342 count
= MAX_DEATH_COUNT
-1;
20347 time_t expected_time
= corpse
->GetGhostTime()+copseReclaimDelay
[count
];
20349 time_t now
= time(NULL
);
20350 if(now
>= expected_time
)
20353 delay
= uint32(expected_time
-now
);
20356 delay
= GetCorpseReclaimDelay(corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
);
20358 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
20359 WorldPacket
data(SMSG_CORPSE_RECLAIM_DELAY
, 4);
20360 data
<< uint32(delay
*IN_MILLISECONDS
);
20361 GetSession()->SendPacket( &data
);
20364 Player
* Player::GetNextRandomRaidMember(float radius
)
20366 Group
*pGroup
= GetGroup();
20370 std::vector
<Player
*> nearMembers
;
20371 nearMembers
.reserve(pGroup
->GetMembersCount());
20373 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
20375 Player
* Target
= itr
->getSource();
20377 // IsHostileTo check duel and controlled by enemy
20378 if( Target
&& Target
!= this && IsWithinDistInMap(Target
, radius
) &&
20379 !Target
->HasInvisibilityAura() && !IsHostileTo(Target
) )
20380 nearMembers
.push_back(Target
);
20383 if (nearMembers
.empty())
20386 uint32 randTarget
= urand(0,nearMembers
.size()-1);
20387 return nearMembers
[randTarget
];
20390 PartyResult
Player::CanUninviteFromGroup() const
20392 const Group
* grp
= GetGroup();
20394 return ERR_NOT_IN_GROUP
;
20396 if(!grp
->IsLeader(GetGUID()) && !grp
->IsAssistant(GetGUID()))
20397 return ERR_NOT_LEADER
;
20399 if(InBattleGround())
20400 return ERR_INVITE_RESTRICTED
;
20402 return ERR_PARTY_RESULT_OK
;
20405 void Player::SetBattleGroundRaid(Group
* group
, int8 subgroup
)
20407 //we must move references from m_group to m_originalGroup
20408 SetOriginalGroup(GetGroup(), GetSubGroup());
20411 m_group
.link(group
, this);
20412 m_group
.setSubGroup((uint8
)subgroup
);
20415 void Player::RemoveFromBattleGroundRaid()
20417 //remove existing reference
20419 if( Group
* group
= GetOriginalGroup() )
20421 m_group
.link(group
, this);
20422 m_group
.setSubGroup(GetOriginalSubGroup());
20424 SetOriginalGroup(NULL
);
20427 void Player::SetOriginalGroup(Group
*group
, int8 subgroup
)
20429 if( group
== NULL
)
20430 m_originalGroup
.unlink();
20433 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
20434 ASSERT(subgroup
>= 0);
20435 m_originalGroup
.link(group
, this);
20436 m_originalGroup
.setSubGroup((uint8
)subgroup
);
20440 void Player::UpdateUnderwaterState( Map
* m
, float x
, float y
, float z
)
20442 LiquidData liquid_status
;
20443 ZLiquidStatus res
= m
->getLiquidStatus(x
, y
, z
, MAP_ALL_LIQUIDS
, &liquid_status
);
20446 m_MirrorTimerFlags
&= ~(UNDERWATER_INWATER
|UNDERWATER_INLAVA
|UNDERWATER_INSLIME
|UNDERWATER_INDARKWATER
);
20447 // Small hack for enable breath in WMO
20449 m_MirrorTimerFlags
|=UNDERWATER_INWATER
;
20453 // All liquids type - check under water position
20454 if (liquid_status
.type
&(MAP_LIQUID_TYPE_WATER
|MAP_LIQUID_TYPE_OCEAN
|MAP_LIQUID_TYPE_MAGMA
|MAP_LIQUID_TYPE_SLIME
))
20456 if ( res
& LIQUID_MAP_UNDER_WATER
)
20457 m_MirrorTimerFlags
|= UNDERWATER_INWATER
;
20459 m_MirrorTimerFlags
&= ~UNDERWATER_INWATER
;
20462 // Allow travel in dark water on taxi or transport
20463 if ((liquid_status
.type
& MAP_LIQUID_TYPE_DARK_WATER
) && !isInFlight() && !GetTransport())
20464 m_MirrorTimerFlags
|= UNDERWATER_INDARKWATER
;
20466 m_MirrorTimerFlags
&= ~UNDERWATER_INDARKWATER
;
20468 // in lava check, anywhere in lava level
20469 if (liquid_status
.type
&MAP_LIQUID_TYPE_MAGMA
)
20471 if (res
& (LIQUID_MAP_UNDER_WATER
|LIQUID_MAP_IN_WATER
|LIQUID_MAP_WATER_WALK
))
20472 m_MirrorTimerFlags
|= UNDERWATER_INLAVA
;
20474 m_MirrorTimerFlags
&= ~UNDERWATER_INLAVA
;
20476 // in slime check, anywhere in slime level
20477 if (liquid_status
.type
&MAP_LIQUID_TYPE_SLIME
)
20479 if (res
& (LIQUID_MAP_UNDER_WATER
|LIQUID_MAP_IN_WATER
|LIQUID_MAP_WATER_WALK
))
20480 m_MirrorTimerFlags
|= UNDERWATER_INSLIME
;
20482 m_MirrorTimerFlags
&= ~UNDERWATER_INSLIME
;
20486 void Player::SetCanParry( bool value
)
20488 if(m_canParry
==value
)
20491 m_canParry
= value
;
20492 UpdateParryPercentage();
20495 void Player::SetCanBlock( bool value
)
20497 if(m_canBlock
==value
)
20500 m_canBlock
= value
;
20501 UpdateBlockPercentage();
20504 bool ItemPosCount::isContainedIn(ItemPosCountVec
const& vec
) const
20506 for(ItemPosCountVec::const_iterator itr
= vec
.begin(); itr
!= vec
.end();++itr
)
20507 if(itr
->pos
== pos
)
20513 bool Player::CanUseBattleGroundObject()
20515 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
20516 // maybe gameobject code should handle that ForceReaction usage
20517 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
20518 return ( //InBattleGround() && // in battleground - not need, check in other cases
20519 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
20520 //player cannot use object when he is invulnerable (immune)
20521 !isTotalImmune() && // not totally immune
20522 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
20523 !HasStealthAura() && // not stealthed
20524 !HasInvisibilityAura() && // not invisible
20525 !HasAura(SPELL_RECENTLY_DROPPED_FLAG
, EFFECT_INDEX_0
) &&// can't pickup
20526 isAlive() // live player
20530 bool Player::CanCaptureTowerPoint()
20532 return ( !HasStealthAura() && // not stealthed
20533 !HasInvisibilityAura() && // not invisible
20534 isAlive() // live player
20538 uint32
Player::GetBarberShopCost(uint8 newhairstyle
, uint8 newhaircolor
, uint8 newfacialhair
)
20540 uint32 level
= getLevel();
20542 if(level
> GT_MAX_LEVEL
)
20543 level
= GT_MAX_LEVEL
; // max level in this dbc
20545 uint8 hairstyle
= GetByteValue(PLAYER_BYTES
, 2);
20546 uint8 haircolor
= GetByteValue(PLAYER_BYTES
, 3);
20547 uint8 facialhair
= GetByteValue(PLAYER_BYTES_2
, 0);
20549 if((hairstyle
== newhairstyle
) && (haircolor
== newhaircolor
) && (facialhair
== newfacialhair
))
20552 GtBarberShopCostBaseEntry
const *bsc
= sGtBarberShopCostBaseStore
.LookupEntry(level
- 1);
20554 if(!bsc
) // shouldn't happen
20559 if(hairstyle
!= newhairstyle
)
20560 cost
+= bsc
->cost
; // full price
20562 if((haircolor
!= newhaircolor
) && (hairstyle
== newhairstyle
))
20563 cost
+= bsc
->cost
* 0.5f
; // +1/2 of price
20565 if(facialhair
!= newfacialhair
)
20566 cost
+= bsc
->cost
* 0.75f
; // +3/4 of price
20568 return uint32(cost
);
20571 void Player::InitGlyphsForLevel()
20573 for(uint32 i
= 0; i
< sGlyphSlotStore
.GetNumRows(); ++i
)
20574 if(GlyphSlotEntry
const * gs
= sGlyphSlotStore
.LookupEntry(i
))
20576 SetGlyphSlot(gs
->Order
- 1, gs
->Id
);
20578 uint32 level
= getLevel();
20581 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
20583 value
|= (0x01 | 0x02);
20593 SetUInt32Value(PLAYER_GLYPHS_ENABLED
, value
);
20596 void Player::ApplyGlyph(uint8 slot
, bool apply
)
20598 if (uint32 glyph
= GetGlyph(slot
))
20600 if(GlyphPropertiesEntry
const *gp
= sGlyphPropertiesStore
.LookupEntry(glyph
))
20604 CastSpell(this, gp
->SpellId
, true);
20605 SetUInt32Value(PLAYER_FIELD_GLYPHS_1
+ slot
, glyph
);
20609 RemoveAurasDueToSpell(gp
->SpellId
);
20610 SetUInt32Value(PLAYER_FIELD_GLYPHS_1
+ slot
, 0);
20616 void Player::ApplyGlyphs(bool apply
)
20618 for (uint8 i
= 0; i
< MAX_GLYPH_SLOT_INDEX
; ++i
)
20619 ApplyGlyph(i
,apply
);
20622 void Player::EnterVehicle(Vehicle
*vehicle
)
20624 VehicleEntry
const *ve
= sVehicleStore
.LookupEntry(vehicle
->GetVehicleId());
20628 VehicleSeatEntry
const *veSeat
= sVehicleSeatStore
.LookupEntry(ve
->m_seatID
[0]);
20632 vehicle
->SetCharmerGUID(GetGUID());
20633 vehicle
->RemoveFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
20634 vehicle
->SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PLAYER_CONTROLLED
);
20635 vehicle
->setFaction(getFaction());
20637 SetCharm(vehicle
); // charm
20638 SetFarSightGUID(vehicle
->GetGUID()); // set view
20640 SetClientControl(vehicle
, 1); // redirect controls to vehicle
20643 WorldPacket
data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA
, 0);
20644 GetSession()->SendPacket(&data
);
20646 data
.Initialize(MSG_MOVE_TELEPORT_ACK
, 30);
20647 data
<< GetPackGUID();
20648 data
<< uint32(0); // counter?
20649 data
<< uint32(MOVEFLAG_ONTRANSPORT
); // transport
20650 data
<< uint16(0); // special flags
20651 data
<< uint32(getMSTime()); // time
20652 data
<< vehicle
->GetPositionX(); // x
20653 data
<< vehicle
->GetPositionY(); // y
20654 data
<< vehicle
->GetPositionZ(); // z
20655 data
<< vehicle
->GetOrientation(); // o
20656 // transport part, TODO: load/calculate seat offsets
20657 data
<< uint64(vehicle
->GetGUID()); // transport guid
20658 data
<< float(veSeat
->m_attachmentOffsetX
); // transport offsetX
20659 data
<< float(veSeat
->m_attachmentOffsetY
); // transport offsetY
20660 data
<< float(veSeat
->m_attachmentOffsetZ
); // transport offsetZ
20661 data
<< float(0); // transport orientation
20662 data
<< uint32(getMSTime()); // transport time
20663 data
<< uint8(0); // seat
20664 // end of transport part
20665 data
<< uint32(0); // fall time
20666 GetSession()->SendPacket(&data
);
20668 data
.Initialize(SMSG_PET_SPELLS
, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX
+1+1);
20669 data
<< uint64(vehicle
->GetGUID());
20672 data
<< uint32(0x00000101);
20674 for(uint32 i
= 0; i
< 10; ++i
)
20675 data
<< uint16(0) << uint8(0) << uint8(i
+8);
20679 GetSession()->SendPacket(&data
);
20682 void Player::ExitVehicle(Vehicle
*vehicle
)
20684 vehicle
->SetCharmerGUID(0);
20685 vehicle
->SetFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
20686 vehicle
->RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PLAYER_CONTROLLED
);
20687 vehicle
->setFaction((GetTeam() == ALLIANCE
) ? vehicle
->GetCreatureInfo()->faction_A
: vehicle
->GetCreatureInfo()->faction_H
);
20690 SetFarSightGUID(0);
20692 SetClientControl(vehicle
, 0);
20695 WorldPacket
data(MSG_MOVE_TELEPORT_ACK
, 30);
20696 data
<< GetPackGUID();
20697 data
<< uint32(0); // counter?
20698 data
<< uint32(MOVEFLAG_ROOT
); // fly unk
20699 data
<< uint16(MOVEFLAG2_UNK4
); // special flags
20700 data
<< uint32(getMSTime()); // time
20701 data
<< vehicle
->GetPositionX(); // x
20702 data
<< vehicle
->GetPositionY(); // y
20703 data
<< vehicle
->GetPositionZ(); // z
20704 data
<< vehicle
->GetOrientation(); // o
20705 data
<< uint32(0); // fall time
20706 GetSession()->SendPacket(&data
);
20708 RemovePetActionBar();
20710 // maybe called at dummy aura remove?
20711 // CastSpell(this, 45472, true); // Parachute
20714 bool Player::isTotalImmune()
20716 AuraList
const& immune
= GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY
);
20718 uint32 immuneMask
= 0;
20719 for(AuraList::const_iterator itr
= immune
.begin(); itr
!= immune
.end(); ++itr
)
20721 immuneMask
|= (*itr
)->GetModifier()->m_miscvalue
;
20722 if( immuneMask
& SPELL_SCHOOL_MASK_ALL
) // total immunity
20728 bool Player::HasTitle(uint32 bitIndex
)
20730 if (bitIndex
> MAX_TITLE_INDEX
)
20733 uint32 fieldIndexOffset
= bitIndex
/ 32;
20734 uint32 flag
= 1 << (bitIndex
% 32);
20735 return HasFlag(PLAYER__FIELD_KNOWN_TITLES
+ fieldIndexOffset
, flag
);
20738 void Player::SetTitle(CharTitlesEntry
const* title
, bool lost
)
20740 uint32 fieldIndexOffset
= title
->bit_index
/ 32;
20741 uint32 flag
= 1 << (title
->bit_index
% 32);
20745 if(!HasFlag(PLAYER__FIELD_KNOWN_TITLES
+ fieldIndexOffset
, flag
))
20748 RemoveFlag(PLAYER__FIELD_KNOWN_TITLES
+ fieldIndexOffset
, flag
);
20752 if(HasFlag(PLAYER__FIELD_KNOWN_TITLES
+ fieldIndexOffset
, flag
))
20755 SetFlag(PLAYER__FIELD_KNOWN_TITLES
+ fieldIndexOffset
, flag
);
20758 WorldPacket
data(SMSG_TITLE_EARNED
, 4 + 4);
20759 data
<< uint32(title
->bit_index
);
20760 data
<< uint32(lost
? 0 : 1); // 1 - earned, 0 - lost
20761 GetSession()->SendPacket(&data
);
20764 void Player::ConvertRune(uint8 index
, RuneType newType
)
20766 SetCurrentRune(index
, newType
);
20768 WorldPacket
data(SMSG_CONVERT_RUNE
, 2);
20769 data
<< uint8(index
);
20770 data
<< uint8(newType
);
20771 GetSession()->SendPacket(&data
);
20774 void Player::ResyncRunes(uint8 count
)
20776 WorldPacket
data(SMSG_RESYNC_RUNES
, count
* 2);
20777 for(uint32 i
= 0; i
< count
; ++i
)
20779 data
<< uint8(GetCurrentRune(i
)); // rune type
20780 data
<< uint8(255 - ((GetRuneCooldown(i
) / REGEN_TIME_FULL
) * 51)); // passed cooldown time (0-255)
20782 GetSession()->SendPacket(&data
);
20785 void Player::AddRunePower(uint8 index
)
20787 WorldPacket
data(SMSG_ADD_RUNE_POWER
, 4);
20788 data
<< uint32(1 << index
); // mask (0x00-0x3F probably)
20789 GetSession()->SendPacket(&data
);
20792 static RuneType runeSlotTypes
[MAX_RUNES
] = {
20801 void Player::InitRunes()
20803 if(getClass() != CLASS_DEATH_KNIGHT
)
20806 m_runes
= new Runes
;
20808 m_runes
->runeState
= 0;
20810 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
20812 SetBaseRune(i
, runeSlotTypes
[i
]); // init base types
20813 SetCurrentRune(i
, runeSlotTypes
[i
]); // init current types
20814 SetRuneCooldown(i
, 0); // reset cooldowns
20815 m_runes
->SetRuneState(i
);
20818 for(uint32 i
= 0; i
< NUM_RUNE_TYPES
; ++i
)
20819 SetFloatValue(PLAYER_RUNE_REGEN_1
+ i
, 0.1f
);
20823 bool Player::IsBaseRuneSlotsOnCooldown( RuneType runeType
) const
20825 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
20826 if (GetBaseRune(i
) == runeType
&& GetRuneCooldown(i
) == 0)
20832 void Player::AutoStoreLoot(uint8 bag
, uint8 slot
, uint32 loot_id
, LootStore
const& store
, bool broadcast
)
20835 loot
.FillLoot (loot_id
,store
,this,true);
20837 uint32 max_slot
= loot
.GetMaxSlotInLootFor(this);
20838 for(uint32 i
= 0; i
< max_slot
; ++i
)
20840 LootItem
* lootItem
= loot
.LootItemInSlot(i
,this);
20842 ItemPosCountVec dest
;
20843 uint8 msg
= CanStoreNewItem (bag
,slot
,dest
,lootItem
->itemid
,lootItem
->count
);
20844 if(msg
!= EQUIP_ERR_OK
&& slot
!= NULL_SLOT
)
20845 msg
= CanStoreNewItem( bag
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
20846 if( msg
!= EQUIP_ERR_OK
&& bag
!= NULL_BAG
)
20847 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
20848 if(msg
!= EQUIP_ERR_OK
)
20850 SendEquipError( msg
, NULL
, NULL
, lootItem
->itemid
);
20854 Item
* pItem
= StoreNewItem (dest
,lootItem
->itemid
,true,lootItem
->randomPropertyId
);
20855 SendNewItem(pItem
, lootItem
->count
, false, false, broadcast
);
20859 uint32
Player::CalculateTalentsPoints() const
20861 uint32 base_talent
= getLevel() < 10 ? 0 : getLevel()-9;
20863 if(getClass() != CLASS_DEATH_KNIGHT
)
20864 return uint32(base_talent
* sWorld
.getConfig(CONFIG_FLOAT_RATE_TALENT
));
20866 uint32 talentPointsForLevel
= getLevel() < 56 ? 0 : getLevel() - 55;
20867 talentPointsForLevel
+= m_questRewardTalentCount
;
20869 if(talentPointsForLevel
> base_talent
)
20870 talentPointsForLevel
= base_talent
;
20872 return uint32(talentPointsForLevel
* sWorld
.getConfig(CONFIG_FLOAT_RATE_TALENT
));
20875 bool Player::IsKnowHowFlyIn(uint32 mapid
, uint32 zone
) const
20877 // continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update
20878 uint32 v_map
= GetVirtualMapForMapAndZone(mapid
, zone
);
20879 return v_map
!= 571 || HasSpell(54197); // Cold Weather Flying
20882 struct DoPlayerLearnSpell
20884 DoPlayerLearnSpell(Player
& _player
) : player(_player
) {}
20885 void operator() (uint32 spell_id
) { player
.learnSpell(spell_id
, false); }
20889 void Player::learnSpellHighRank(uint32 spellid
)
20891 learnSpell(spellid
, false);
20893 DoPlayerLearnSpell
worker(*this);
20894 sSpellMgr
.doForHighRanks(spellid
, worker
);
20897 void Player::_LoadSkills(QueryResult
*result
)
20900 // SetPQuery(PLAYER_LOGIN_QUERY_LOADSKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = '%u'", GUID_LOPART(m_guid));
20907 Field
*fields
= result
->Fetch();
20909 uint16 skill
= fields
[0].GetUInt16();
20910 uint16 value
= fields
[1].GetUInt16();
20911 uint16 max
= fields
[2].GetUInt16();
20913 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(skill
);
20916 sLog
.outError("Character %u has skill %u that does not exist.", GetGUIDLow(), skill
);
20920 // set fixed skill ranges
20921 switch(GetSkillRangeType(pSkill
,false))
20923 case SKILL_RANGE_LANGUAGE
: // 300..300
20926 case SKILL_RANGE_MONO
: // 1..1, grey monolite bar
20935 sLog
.outError("Character %u has skill %u with value 0. Will be deleted.", GetGUIDLow(), skill
);
20936 CharacterDatabase
.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), skill
);
20940 // enable unlearn button for primary professions only
20941 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
20942 SetUInt32Value(PLAYER_SKILL_INDEX(count
), MAKE_PAIR32(skill
,1));
20944 SetUInt32Value(PLAYER_SKILL_INDEX(count
), MAKE_PAIR32(skill
,0));
20946 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count
),MAKE_SKILL_VALUE(value
, max
));
20947 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count
),0);
20949 mSkillStatus
.insert(SkillStatusMap::value_type(skill
, SkillStatusData(count
, SKILL_UNCHANGED
)));
20951 learnSkillRewardedSpells(skill
, value
);
20955 if(count
>= PLAYER_MAX_SKILLS
) // client limit
20957 sLog
.outError("Character %u has more than %u skills.", GetGUIDLow(), PLAYER_MAX_SKILLS
);
20960 } while (result
->NextRow());
20964 for (; count
< PLAYER_MAX_SKILLS
; ++count
)
20966 SetUInt32Value(PLAYER_SKILL_INDEX(count
), 0);
20967 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count
),0);
20968 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count
),0);
20971 // special settings
20972 if(getClass()==CLASS_DEATH_KNIGHT
)
20974 uint32 base_level
= std::min(getLevel(),sWorld
.getConfig (CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL
));
20977 uint32 base_skill
= (base_level
-1)*5; // 270 at starting level 55
20979 base_skill
= 1; // skill mast be known and then > 0 in any case
20981 if(GetPureSkillValue (SKILL_FIRST_AID
) < base_skill
)
20982 SetSkill(SKILL_FIRST_AID
, 0, base_skill
, base_skill
);
20983 if(GetPureSkillValue (SKILL_AXES
) < base_skill
)
20984 SetSkill(SKILL_AXES
, 0, base_skill
, base_skill
);
20985 if(GetPureSkillValue (SKILL_DEFENSE
) < base_skill
)
20986 SetSkill(SKILL_DEFENSE
, 0, base_skill
, base_skill
);
20987 if(GetPureSkillValue (SKILL_POLEARMS
) < base_skill
)
20988 SetSkill(SKILL_POLEARMS
, 0, base_skill
, base_skill
);
20989 if(GetPureSkillValue (SKILL_SWORDS
) < base_skill
)
20990 SetSkill(SKILL_SWORDS
, 0, base_skill
, base_skill
);
20991 if(GetPureSkillValue (SKILL_2H_AXES
) < base_skill
)
20992 SetSkill(SKILL_2H_AXES
, 0, base_skill
, base_skill
);
20993 if(GetPureSkillValue (SKILL_2H_SWORDS
) < base_skill
)
20994 SetSkill(SKILL_2H_SWORDS
, 0, base_skill
, base_skill
);
20995 if(GetPureSkillValue (SKILL_UNARMED
) < base_skill
)
20996 SetSkill(SKILL_UNARMED
, 0, base_skill
, base_skill
);
21000 uint32
Player::GetPhaseMaskForSpawn() const
21002 uint32 phase
= PHASEMASK_NORMAL
;
21003 if(!isGameMaster())
21004 phase
= GetPhaseMask();
21007 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
21008 if(!phases
.empty())
21009 phase
= phases
.front()->GetMiscValue();
21012 // some aura phases include 1 normal map in addition to phase itself
21013 if(uint32 n_phase
= phase
& ~PHASEMASK_NORMAL
)
21016 return PHASEMASK_NORMAL
;
21019 uint8
Player::CanEquipUniqueItem(Item
* pItem
, uint8 eslot
, uint32 limit_count
) const
21021 ItemPrototype
const* pProto
= pItem
->GetProto();
21023 // proto based limitations
21024 if(uint8 res
= CanEquipUniqueItem(pProto
,eslot
,limit_count
))
21027 // check unique-equipped on gems
21028 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
21030 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
21033 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
21037 ItemPrototype
const* pGem
= ObjectMgr::GetItemPrototype(enchantEntry
->GemID
);
21041 // include for check equip another gems with same limit category for not equipped item (and then not counted)
21042 uint32 gem_limit_count
= !pItem
->IsEquipped() && pGem
->ItemLimitCategory
21043 ? pItem
->GetGemCountWithLimitCategory(pGem
->ItemLimitCategory
) : 1;
21045 if(uint8 res
= CanEquipUniqueItem(pGem
, eslot
,gem_limit_count
))
21049 return EQUIP_ERR_OK
;
21052 uint8
Player::CanEquipUniqueItem( ItemPrototype
const* itemProto
, uint8 except_slot
, uint32 limit_count
) const
21054 // check unique-equipped on item
21055 if (itemProto
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
)
21057 // there is an equip limit on this item
21058 if(HasItemOrGemWithIdEquipped(itemProto
->ItemId
,1,except_slot
))
21059 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
21062 // check unique-equipped limit
21063 if (itemProto
->ItemLimitCategory
)
21065 ItemLimitCategoryEntry
const* limitEntry
= sItemLimitCategoryStore
.LookupEntry(itemProto
->ItemLimitCategory
);
21067 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
21069 // NOTE: limitEntry->mode not checked because if item have have-limit then it applied and to equip case
21071 if(limit_count
> limitEntry
->maxCount
)
21072 return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS
;
21074 // there is an equip limit on this item
21075 if(HasItemOrGemWithLimitCategoryEquipped(itemProto
->ItemLimitCategory
,limitEntry
->maxCount
-limit_count
+1,except_slot
))
21076 return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS
;
21079 return EQUIP_ERR_OK
;
21082 void Player::HandleFall(MovementInfo
const& movementInfo
)
21084 // calculate total z distance of the fall
21085 float z_diff
= m_lastFallZ
- movementInfo
.GetPos()->z
;
21086 sLog
.outDebug("zDiff = %f", z_diff
);
21088 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
21089 // 14.57 can be calculated by resolving damageperc formula below to 0
21090 if (z_diff
>= 14.57f
&& !isDead() && !isGameMaster() &&
21091 !HasAuraType(SPELL_AURA_HOVER
) && !HasAuraType(SPELL_AURA_FEATHER_FALL
) &&
21092 !HasAuraType(SPELL_AURA_FLY
) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL
) )
21094 //Safe fall, fall height reduction
21095 int32 safe_fall
= GetTotalAuraModifier(SPELL_AURA_SAFE_FALL
);
21097 float damageperc
= 0.018f
*(z_diff
-safe_fall
)-0.2426f
;
21101 uint32 damage
= (uint32
)(damageperc
* GetMaxHealth()*sWorld
.getConfig(CONFIG_FLOAT_RATE_DAMAGE_FALL
));
21103 float height
= movementInfo
.GetPos()->z
;
21104 UpdateGroundPositionZ(movementInfo
.GetPos()->x
, movementInfo
.GetPos()->y
, height
);
21108 //Prevent fall damage from being more than the player maximum health
21109 if (damage
> GetMaxHealth())
21110 damage
= GetMaxHealth();
21113 if (GetDummyAura(43621))
21114 damage
= GetMaxHealth()/2;
21116 uint32 original_health
= GetHealth();
21117 uint32 final_damage
= EnvironmentalDamage(DAMAGE_FALL
, damage
);
21119 // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
21120 if (isAlive() && final_damage
< original_health
)
21121 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING
, uint32(z_diff
*100));
21124 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
21125 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
);
21130 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type
, uint32 miscvalue1
/*=0*/, uint32 miscvalue2
/*=0*/, Unit
*unit
/*=NULL*/, uint32 time
/*=0*/ )
21132 GetAchievementMgr().UpdateAchievementCriteria(type
, miscvalue1
,miscvalue2
,unit
,time
);
21135 void Player::LearnTalent(uint32 talentId
, uint32 talentRank
)
21137 uint32 CurTalentPoints
= GetFreeTalentPoints();
21139 if(CurTalentPoints
== 0)
21142 if (talentRank
>= MAX_TALENT_RANK
)
21145 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentId
);
21150 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
21155 // prevent learn talent for different class (cheating)
21156 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
21159 // find current max talent rank
21160 uint32 curtalent_maxrank
= 0;
21161 PlayerTalentMap::iterator itr
= m_talents
[m_activeSpec
].find(talentId
);
21162 if (itr
!= m_talents
[m_activeSpec
].end() && itr
->second
.state
!= PLAYERSPELL_REMOVED
)
21163 curtalent_maxrank
= itr
->second
.currentRank
+ 1;
21165 // we already have same or higher talent rank learned
21166 if(curtalent_maxrank
>= (talentRank
+ 1))
21169 // check if we have enough talent points
21170 if(CurTalentPoints
< (talentRank
- curtalent_maxrank
+ 1))
21173 // Check if it requires another talent
21174 if (talentInfo
->DependsOn
> 0)
21176 if(TalentEntry
const *depTalentInfo
= sTalentStore
.LookupEntry(talentInfo
->DependsOn
))
21178 bool hasEnoughRank
= false;
21179 PlayerTalentMap::iterator dependsOnTalent
= m_talents
[m_activeSpec
].find(depTalentInfo
->TalentID
);
21180 if (dependsOnTalent
!= m_talents
[m_activeSpec
].end() && dependsOnTalent
->second
.state
!= PLAYERSPELL_REMOVED
)
21182 PlayerTalent depTalent
= (*dependsOnTalent
).second
;
21183 if (depTalent
.currentRank
>= talentInfo
->DependsOnRank
)
21184 hasEnoughRank
= true;
21187 if (!hasEnoughRank
)
21192 // Find out how many points we have in this field
21193 uint32 spentPoints
= 0;
21195 uint32 tTab
= talentInfo
->TalentTab
;
21196 if (talentInfo
->Row
> 0)
21198 for (PlayerTalentMap::const_iterator iter
= m_talents
[m_activeSpec
].begin(); iter
!= m_talents
[m_activeSpec
].end(); ++iter
)
21199 if (iter
->second
.state
!= PLAYERSPELL_REMOVED
&& iter
->second
.m_talentEntry
->TalentTab
== tTab
)
21200 spentPoints
+= iter
->second
.currentRank
+ 1;
21203 // not have required min points spent in talent tree
21204 if(spentPoints
< (talentInfo
->Row
* MAX_TALENT_RANK
))
21207 // spell not set in talent.dbc
21208 uint32 spellid
= talentInfo
->RankID
[talentRank
];
21211 sLog
.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId
, talentRank
);
21216 if(HasSpell(spellid
))
21219 // learn! (other talent ranks will unlearned at learning)
21220 learnSpell(spellid
, false);
21221 sLog
.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId
, talentRank
, spellid
);
21224 void Player::LearnPetTalent(uint64 petGuid
, uint32 talentId
, uint32 talentRank
)
21226 Pet
*pet
= GetPet();
21231 if(petGuid
!= pet
->GetGUID())
21234 uint32 CurTalentPoints
= pet
->GetFreeTalentPoints();
21236 if(CurTalentPoints
== 0)
21239 if (talentRank
>= MAX_PET_TALENT_RANK
)
21242 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(talentId
);
21247 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry(talentInfo
->TalentTab
);
21252 CreatureInfo
const *ci
= pet
->GetCreatureInfo();
21257 CreatureFamilyEntry
const *pet_family
= sCreatureFamilyStore
.LookupEntry(ci
->family
);
21262 if(pet_family
->petTalentType
< 0) // not hunter pet
21265 // prevent learn talent for different family (cheating)
21266 if(!((1 << pet_family
->petTalentType
) & talentTabInfo
->petTalentMask
))
21269 // find current max talent rank
21270 int32 curtalent_maxrank
= 0;
21271 for(int32 k
= MAX_TALENT_RANK
-1; k
> -1; --k
)
21273 if(talentInfo
->RankID
[k
] && pet
->HasSpell(talentInfo
->RankID
[k
]))
21275 curtalent_maxrank
= k
+ 1;
21280 // we already have same or higher talent rank learned
21281 if(curtalent_maxrank
>= int32(talentRank
+ 1))
21284 // check if we have enough talent points
21285 if(CurTalentPoints
< (talentRank
- curtalent_maxrank
+ 1))
21288 // Check if it requires another talent
21289 if (talentInfo
->DependsOn
> 0)
21291 if(TalentEntry
const *depTalentInfo
= sTalentStore
.LookupEntry(talentInfo
->DependsOn
))
21293 bool hasEnoughRank
= false;
21294 for (int i
= talentInfo
->DependsOnRank
; i
< MAX_TALENT_RANK
; ++i
)
21296 if (depTalentInfo
->RankID
[i
] != 0)
21297 if (pet
->HasSpell(depTalentInfo
->RankID
[i
]))
21298 hasEnoughRank
= true;
21300 if (!hasEnoughRank
)
21305 // Find out how many points we have in this field
21306 uint32 spentPoints
= 0;
21308 uint32 tTab
= talentInfo
->TalentTab
;
21309 if (talentInfo
->Row
> 0)
21311 unsigned int numRows
= sTalentStore
.GetNumRows();
21312 for (unsigned int i
= 0; i
< numRows
; ++i
) // Loop through all talents.
21314 // Someday, someone needs to revamp
21315 const TalentEntry
*tmpTalent
= sTalentStore
.LookupEntry(i
);
21316 if (tmpTalent
) // the way talents are tracked
21318 if (tmpTalent
->TalentTab
== tTab
)
21320 for (int j
= 0; j
< MAX_TALENT_RANK
; ++j
)
21322 if (tmpTalent
->RankID
[j
] != 0)
21324 if (pet
->HasSpell(tmpTalent
->RankID
[j
]))
21326 spentPoints
+= j
+ 1;
21335 // not have required min points spent in talent tree
21336 if(spentPoints
< (talentInfo
->Row
* MAX_PET_TALENT_RANK
))
21339 // spell not set in talent.dbc
21340 uint32 spellid
= talentInfo
->RankID
[talentRank
];
21343 sLog
.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId
, talentRank
);
21348 if(pet
->HasSpell(spellid
))
21351 // learn! (other talent ranks will unlearned at learning)
21352 pet
->learnSpell(spellid
);
21353 sLog
.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId
, talentRank
, spellid
);
21356 void Player::UpdateKnownCurrencies(uint32 itemId
, bool apply
)
21358 if(CurrencyTypesEntry
const* ctEntry
= sCurrencyTypesStore
.LookupEntry(itemId
))
21361 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES
, (UI64LIT(1) << (ctEntry
->BitIndex
- 1)));
21363 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES
, (UI64LIT(1) << (ctEntry
->BitIndex
- 1)));
21367 void Player::UpdateFallInformationIfNeed( MovementInfo
const& minfo
,uint16 opcode
)
21369 if (m_lastFallTime
>= minfo
.GetFallTime() || m_lastFallZ
<= minfo
.GetPos()->z
|| opcode
== MSG_MOVE_FALL_LAND
)
21370 SetFallInformation(minfo
.GetFallTime(), minfo
.GetPos()->z
);
21373 void Player::UnsummonPetTemporaryIfAny()
21375 Pet
* pet
= GetPet();
21379 if(!m_temporaryUnsummonedPetNumber
&& pet
->isControlled() && !pet
->isTemporarySummoned() )
21381 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
21382 m_oldpetspell
= pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
);
21385 RemovePet(pet
, PET_SAVE_AS_CURRENT
);
21388 void Player::ResummonPetTemporaryUnSummonedIfAny()
21390 if(!m_temporaryUnsummonedPetNumber
)
21393 // not resummon in not appropriate state
21394 if(IsPetNeedBeTemporaryUnsummoned())
21400 Pet
* NewPet
= new Pet
;
21401 if(!NewPet
->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber
, true))
21404 m_temporaryUnsummonedPetNumber
= 0;
21407 bool Player::canSeeSpellClickOn(Creature
const *c
) const
21409 if(!c
->HasFlag(UNIT_NPC_FLAGS
,UNIT_NPC_FLAG_SPELLCLICK
))
21412 SpellClickInfoMapBounds clickPair
= sObjectMgr
.GetSpellClickInfoMapBounds(c
->GetEntry());
21413 for(SpellClickInfoMap::const_iterator itr
= clickPair
.first
; itr
!= clickPair
.second
; ++itr
)
21414 if(itr
->second
.IsFitToRequirements(this))
21420 void Player::BuildPlayerTalentsInfoData(WorldPacket
*data
)
21422 *data
<< uint32(GetFreeTalentPoints()); // unspentTalentPoints
21423 *data
<< uint8(m_specsCount
); // talent group count (0, 1 or 2)
21424 *data
<< uint8(m_activeSpec
); // talent group index (0 or 1)
21428 // loop through all specs (only 1 for now)
21429 for(uint32 specIdx
= 0; specIdx
< m_specsCount
; ++specIdx
)
21431 uint8 talentIdCount
= 0;
21432 size_t pos
= data
->wpos();
21433 *data
<< uint8(talentIdCount
); // [PH], talentIdCount
21435 // find class talent tabs (all players have 3 talent tabs)
21436 uint32
const* talentTabIds
= GetTalentTabPages(getClass());
21438 for(uint32 i
= 0; i
< 3; ++i
)
21440 uint32 talentTabId
= talentTabIds
[i
];
21441 for(PlayerTalentMap::iterator iter
= m_talents
[specIdx
].begin(); iter
!= m_talents
[specIdx
].end(); ++iter
)
21443 PlayerTalent talent
= (*iter
).second
;
21445 if (talent
.state
== PLAYERSPELL_REMOVED
)
21448 // skip another tab talents
21449 if(talent
.m_talentEntry
->TalentTab
!= talentTabId
)
21452 *data
<< uint32(talent
.m_talentEntry
->TalentID
); // Talent.dbc
21453 *data
<< uint8(talent
.currentRank
); // talentMaxRank (0-4)
21459 data
->put
<uint8
>(pos
, talentIdCount
); // put real count
21461 *data
<< uint8(MAX_GLYPH_SLOT_INDEX
); // glyphs count
21463 // GlyphProperties.dbc
21464 for(uint8 i
= 0; i
< MAX_GLYPH_SLOT_INDEX
; ++i
)
21465 *data
<< uint16(m_glyphs
[specIdx
][i
].GetId());
21470 void Player::BuildPetTalentsInfoData(WorldPacket
*data
)
21472 uint32 unspentTalentPoints
= 0;
21473 size_t pointsPos
= data
->wpos();
21474 *data
<< uint32(unspentTalentPoints
); // [PH], unspentTalentPoints
21476 uint8 talentIdCount
= 0;
21477 size_t countPos
= data
->wpos();
21478 *data
<< uint8(talentIdCount
); // [PH], talentIdCount
21480 Pet
*pet
= GetPet();
21484 unspentTalentPoints
= pet
->GetFreeTalentPoints();
21486 data
->put
<uint32
>(pointsPos
, unspentTalentPoints
); // put real points
21488 CreatureInfo
const *ci
= pet
->GetCreatureInfo();
21492 CreatureFamilyEntry
const *pet_family
= sCreatureFamilyStore
.LookupEntry(ci
->family
);
21493 if(!pet_family
|| pet_family
->petTalentType
< 0)
21496 for(uint32 talentTabId
= 1; talentTabId
< sTalentTabStore
.GetNumRows(); ++talentTabId
)
21498 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentTabId
);
21502 if(!((1 << pet_family
->petTalentType
) & talentTabInfo
->petTalentMask
))
21505 for(uint32 talentId
= 0; talentId
< sTalentStore
.GetNumRows(); ++talentId
)
21507 TalentEntry
const* talentInfo
= sTalentStore
.LookupEntry(talentId
);
21511 // skip another tab talents
21512 if(talentInfo
->TalentTab
!= talentTabId
)
21515 // find max talent rank
21516 int32 curtalent_maxrank
= -1;
21517 for(int32 k
= 4; k
> -1; --k
)
21519 if(talentInfo
->RankID
[k
] && pet
->HasSpell(talentInfo
->RankID
[k
]))
21521 curtalent_maxrank
= k
;
21526 // not learned talent
21527 if(curtalent_maxrank
< 0)
21530 *data
<< uint32(talentInfo
->TalentID
); // Talent.dbc
21531 *data
<< uint8(curtalent_maxrank
); // talentMaxRank (0-4)
21536 data
->put
<uint8
>(countPos
, talentIdCount
); // put real count
21542 void Player::SendTalentsInfoData(bool pet
)
21544 WorldPacket
data(SMSG_TALENTS_INFO
, 50);
21545 data
<< uint8(pet
? 1 : 0);
21547 BuildPetTalentsInfoData(&data
);
21549 BuildPlayerTalentsInfoData(&data
);
21550 GetSession()->SendPacket(&data
);
21553 void Player::BuildEnchantmentsInfoData(WorldPacket
*data
)
21555 uint32 slotUsedMask
= 0;
21556 size_t slotUsedMaskPos
= data
->wpos();
21557 *data
<< uint32(slotUsedMask
); // slotUsedMask < 0x80000
21559 for(uint32 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
21561 Item
*item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
);
21566 slotUsedMask
|= (1 << i
);
21568 *data
<< uint32(item
->GetEntry()); // item entry
21570 uint16 enchantmentMask
= 0;
21571 size_t enchantmentMaskPos
= data
->wpos();
21572 *data
<< uint16(enchantmentMask
); // enchantmentMask < 0x1000
21574 for(uint32 j
= 0; j
< MAX_ENCHANTMENT_SLOT
; ++j
)
21576 uint32 enchId
= item
->GetEnchantmentId(EnchantmentSlot(j
));
21581 enchantmentMask
|= (1 << j
);
21583 *data
<< uint16(enchId
); // enchantmentId?
21586 data
->put
<uint16
>(enchantmentMaskPos
, enchantmentMask
);
21588 *data
<< uint16(0); // ?
21589 *data
<< uint8(0); // PGUID!
21590 *data
<< uint32(0); // seed?
21593 data
->put
<uint32
>(slotUsedMaskPos
, slotUsedMask
);
21596 void Player::SendEquipmentSetList()
21599 WorldPacket
data(SMSG_EQUIPMENT_SET_LIST
, 4);
21600 size_t count_pos
= data
.wpos();
21601 data
<< uint32(count
); // count placeholder
21602 for(EquipmentSets::iterator itr
= m_EquipmentSets
.begin(); itr
!= m_EquipmentSets
.end(); ++itr
)
21604 if(itr
->second
.state
==EQUIPMENT_SET_DELETED
)
21606 data
.appendPackGUID(itr
->second
.Guid
);
21607 data
<< uint32(itr
->first
);
21608 data
<< itr
->second
.Name
;
21609 data
<< itr
->second
.IconName
;
21610 for(uint32 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
21611 data
.appendPackGUID(MAKE_NEW_GUID(itr
->second
.Items
[i
], 0, HIGHGUID_ITEM
));
21613 ++count
; // client have limit but it checked at loading and set
21615 data
.put
<uint32
>(count_pos
, count
);
21616 GetSession()->SendPacket(&data
);
21619 void Player::SetEquipmentSet(uint32 index
, EquipmentSet eqset
)
21621 if(eqset
.Guid
!= 0)
21623 bool found
= false;
21625 for(EquipmentSets::iterator itr
= m_EquipmentSets
.begin(); itr
!= m_EquipmentSets
.end(); ++itr
)
21627 if((itr
->second
.Guid
== eqset
.Guid
) && (itr
->first
== index
))
21634 if(!found
) // something wrong...
21636 sLog
.outError("Player %s tried to save equipment set "UI64FMTD
" (index %u), but that equipment set not found!", GetName(), eqset
.Guid
, index
);
21641 EquipmentSet
& eqslot
= m_EquipmentSets
[index
];
21643 EquipmentSetUpdateState old_state
= eqslot
.state
;
21647 if(eqset
.Guid
== 0)
21649 eqslot
.Guid
= sObjectMgr
.GenerateEquipmentSetGuid();
21651 WorldPacket
data(SMSG_EQUIPMENT_SET_SAVED
, 4 + 1);
21652 data
<< uint32(index
);
21653 data
.appendPackGUID(eqslot
.Guid
);
21654 GetSession()->SendPacket(&data
);
21657 eqslot
.state
= old_state
== EQUIPMENT_SET_NEW
? EQUIPMENT_SET_NEW
: EQUIPMENT_SET_CHANGED
;
21660 void Player::_SaveEquipmentSets()
21662 for(EquipmentSets::iterator itr
= m_EquipmentSets
.begin(); itr
!= m_EquipmentSets
.end();)
21664 uint32 index
= itr
->first
;
21665 EquipmentSet
& eqset
= itr
->second
;
21666 switch(eqset
.state
)
21668 case EQUIPMENT_SET_UNCHANGED
:
21670 break; // nothing do
21671 case EQUIPMENT_SET_CHANGED
:
21672 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'",
21673 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],
21674 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
);
21675 eqset
.state
= EQUIPMENT_SET_UNCHANGED
;
21678 case EQUIPMENT_SET_NEW
:
21679 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')",
21680 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],
21681 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]);
21682 eqset
.state
= EQUIPMENT_SET_UNCHANGED
;
21685 case EQUIPMENT_SET_DELETED
:
21686 CharacterDatabase
.PExecute("DELETE FROM character_equipmentsets WHERE setguid="UI64FMTD
, eqset
.Guid
);
21687 m_EquipmentSets
.erase(itr
++);
21693 void Player::_SaveBGData()
21695 CharacterDatabase
.PExecute("DELETE FROM character_battleground_data WHERE guid='%u'", GetGUIDLow());
21696 if (m_bgData
.bgInstanceID
)
21698 /* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
21699 CharacterDatabase
.PExecute("INSERT INTO character_battleground_data VALUES ('%u', '%u', '%u', '%f', '%f', '%f', '%f', '%u', '%u', '%u', '%u')",
21700 GetGUIDLow(), m_bgData
.bgInstanceID
, m_bgData
.bgTeam
, m_bgData
.joinPos
.coord_x
, m_bgData
.joinPos
.coord_y
, m_bgData
.joinPos
.coord_z
,
21701 m_bgData
.joinPos
.orientation
, m_bgData
.joinPos
.mapid
, m_bgData
.taxiPath
[0], m_bgData
.taxiPath
[1], m_bgData
.mountSpell
);
21705 void Player::DeleteEquipmentSet(uint64 setGuid
)
21707 for(EquipmentSets::iterator itr
= m_EquipmentSets
.begin(); itr
!= m_EquipmentSets
.end(); ++itr
)
21709 if(itr
->second
.Guid
== setGuid
)
21711 if(itr
->second
.state
== EQUIPMENT_SET_NEW
)
21712 m_EquipmentSets
.erase(itr
);
21714 itr
->second
.state
= EQUIPMENT_SET_DELETED
;
21720 void Player::ActivateSpec(uint8 specNum
)
21722 if(GetActiveSpec() == specNum
)
21725 if(specNum
>= GetSpecsCount())
21728 UnsummonPetTemporaryIfAny();
21730 ApplyGlyphs(false);
21732 // copy of new talent spec (we will use it as model for converting current tlanet state to new)
21733 PlayerTalentMap tempSpec
= m_talents
[specNum
];
21735 // copy old spec talents to new one, must be before spec switch to have previous spec num(as m_activeSpec)
21736 m_talents
[specNum
] = m_talents
[m_activeSpec
];
21738 SetActiveSpec(specNum
);
21740 // remove all talent spells that don't exist in next spec but exist in old
21741 for (PlayerTalentMap::iterator specIter
= m_talents
[m_activeSpec
].begin(); specIter
!= m_talents
[m_activeSpec
].end();)
21743 PlayerTalent
& talent
= (*specIter
).second
;
21745 if (talent
.state
== PLAYERSPELL_REMOVED
)
21751 PlayerTalentMap::iterator iterTempSpec
= tempSpec
.find(specIter
->first
);
21753 // remove any talent rank if talent not listed in temp spec
21754 if (iterTempSpec
== tempSpec
.end() || iterTempSpec
->second
.state
== PLAYERSPELL_REMOVED
)
21756 TalentEntry
const *talentInfo
= talent
.m_talentEntry
;
21758 for(int r
= 0; r
< MAX_TALENT_RANK
; ++r
)
21759 if (talentInfo
->RankID
[r
])
21760 removeSpell(talentInfo
->RankID
[r
],!IsPassiveSpell(talentInfo
->RankID
[r
]),false);
21762 specIter
= m_talents
[m_activeSpec
].begin();
21768 // now new spec data have only talents (maybe different rank) as in temp spec data, sync ranks then.
21769 for (PlayerTalentMap::const_iterator tempIter
= tempSpec
.begin(); tempIter
!= tempSpec
.end(); ++tempIter
)
21771 PlayerTalent
const& talent
= (*tempIter
).second
;
21773 // removed state talent already unlearned in prev. loop
21774 // but we need restore it if it deleted for finish removed-marked data in DB
21775 if (talent
.state
== PLAYERSPELL_REMOVED
)
21777 m_talents
[m_activeSpec
][tempIter
->first
] = talent
;
21781 uint32 talentSpellId
= talent
.m_talentEntry
->RankID
[talent
.currentRank
];
21783 // learn talent spells if they not in new spec (old spec copy)
21784 // and if they have different rank
21785 PlayerTalentMap::iterator specIter
= m_talents
[m_activeSpec
].find(tempIter
->first
);
21786 if (specIter
!= m_talents
[m_activeSpec
].end() && specIter
->second
.state
!= PLAYERSPELL_REMOVED
)
21788 if ((*specIter
).second
.currentRank
!= talent
.currentRank
)
21789 learnSpell(talentSpellId
, false);
21792 learnSpell(talentSpellId
, false);
21794 // sync states - original state is changed in addSpell that learnSpell calls
21795 specIter
= m_talents
[m_activeSpec
].find(tempIter
->first
);
21796 if (specIter
!= m_talents
[m_activeSpec
].end())
21797 (*specIter
).second
.state
= talent
.state
;
21800 sLog
.outError("ActivateSpec: Talent spell %u expected to learned at spec switch but not listed in talents at final check!", talentSpellId
);
21802 // attempt resync DB state (deleted lost spell from DB)
21803 if (talent
.state
!= PLAYERSPELL_NEW
)
21805 PlayerTalent
& talentNew
= m_talents
[m_activeSpec
][tempIter
->first
];
21806 talentNew
= talent
;
21807 talentNew
.state
= PLAYERSPELL_REMOVED
;
21812 InitTalentForLevel();
21814 // recheck action buttons (not checked at loading/spec copy)
21815 ActionButtonList
const& currentActionButtonList
= m_actionButtons
[m_activeSpec
];
21816 for(ActionButtonList::const_iterator itr
= currentActionButtonList
.begin(); itr
!= currentActionButtonList
.end(); ++itr
)
21817 if (itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
21818 // remove broken without any output (it can be not correct because talents not copied at spec creating)
21819 if (!IsActionButtonDataValid(itr
->first
,itr
->second
.GetAction(),itr
->second
.GetType(), this, false))
21820 removeActionButton(m_activeSpec
,itr
->first
);
21822 ResummonPetTemporaryUnSummonedIfAny();
21826 SendInitialActionButtons();
21828 Powers pw
= getPowerType();
21829 if(pw
!= POWER_MANA
)
21830 SetPower(POWER_MANA
, 0);
21835 void Player::UpdateSpecCount(uint8 count
)
21837 uint8 curCount
= GetSpecsCount();
21838 if (curCount
== count
)
21841 // maybe current spec data must be copied to 0 spec?
21842 if (m_activeSpec
>= count
)
21845 // copy spec data from new specs
21846 if (count
> curCount
)
21848 // copy action buttons from active spec (more easy in this case iterate first by button)
21849 ActionButtonList
const& currentActionButtonList
= m_actionButtons
[m_activeSpec
];
21851 for(ActionButtonList::const_iterator itr
= currentActionButtonList
.begin(); itr
!= currentActionButtonList
.end(); ++itr
)
21853 if (itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
21855 for(uint8 spec
= curCount
; spec
< count
; ++spec
)
21856 addActionButton(spec
,itr
->first
,itr
->second
.GetAction(),itr
->second
.GetType());
21860 // delete spec data for removed specs
21861 else if (count
< curCount
)
21863 // delete action buttons for removed spec
21864 for(uint8 spec
= count
; spec
< curCount
; ++spec
)
21866 // delete action buttons for removed spec
21867 for(uint8 button
= 0; button
< MAX_ACTION_BUTTONS
; ++button
)
21868 removeActionButton(spec
,button
);
21872 SetSpecsCount(count
);
21874 SendTalentsInfoData(false);
21877 void Player::RemoveAtLoginFlag( AtLoginFlags f
, bool in_db_also
/*= false*/ )
21879 m_atLoginFlags
&= ~f
;
21882 CharacterDatabase
.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f
), GetGUIDLow());
21885 void Player::SendClearCooldown( uint32 spell_id
, Unit
* target
)
21887 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, 4+8);
21888 data
<< uint32(spell_id
);
21889 data
<< uint64(target
->GetGUID());
21890 SendDirectMessage(&data
);
21893 void Player::BuildTeleportAckMsg( WorldPacket
*data
, float x
, float y
, float z
, float ang
) const
21895 data
->Initialize(MSG_MOVE_TELEPORT_ACK
, 41);
21896 *data
<< GetPackGUID();
21897 *data
<< uint32(0); // this value increments every time
21898 *data
<< uint32(m_movementInfo
.GetMovementFlags()); // movement flags
21899 *data
<< uint16(0); // 2.3.0
21900 *data
<< uint32(getMSTime()); // time
21905 *data
<< uint32(0);
21908 bool Player::HasMovementFlag( MovementFlags f
) const
21910 return m_movementInfo
.HasMovementFlag(f
);
21913 void Player::SetFarSightGUID( uint64 guid
)
21915 if(GetFarSight() == guid
)
21918 SetUInt64Value(PLAYER_FARSIGHT
, guid
);
21920 // need triggering load grids around new view point
21921 UpdateVisibilityForPlayer();
21924 void Player::UpdateVisibilityForPlayer()
21926 WorldObject
const* viewPoint
= GetViewPoint();
21929 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
21932 m
->UpdateObjectVisibility(this, cell
, p
);
21934 if (this != viewPoint
)
21936 CellPair
pView(MaNGOS::ComputeCellPair(viewPoint
->GetPositionX(), viewPoint
->GetPositionY()));
21937 Cell
cellView(pView
);
21939 m
->UpdateObjectsVisibilityFor(this, cellView
, pView
);
21942 m
->UpdateObjectsVisibilityFor(this, cell
, p
);
21945 void Player::ResetTimeSync()
21947 m_timeSyncCounter
= 0;
21948 m_timeSyncTimer
= 0;
21949 m_timeSyncClient
= 0;
21950 m_timeSyncServer
= getMSTime();
21953 void Player::SendTimeSync()
21955 WorldPacket
data(SMSG_TIME_SYNC_REQ
, 4);
21956 data
<< uint32(m_timeSyncCounter
++);
21957 GetSession()->SendPacket(&data
);
21959 // Schedule next sync in 10 sec
21960 m_timeSyncTimer
= 10000;
21961 m_timeSyncServer
= getMSTime();
21964 void Player::SendDuelCountdown(uint32 counter
)
21966 WorldPacket
data(SMSG_DUEL_COUNTDOWN
, 4);
21967 data
<< uint32(counter
); // seconds
21968 GetSession()->SendPacket(&data
);
21971 bool Player::IsImmunedToSpellEffect(SpellEntry
const* spellInfo
, SpellEffectIndex index
) const
21973 switch(spellInfo
->Effect
[index
])
21975 case SPELL_EFFECT_ATTACK_ME
:
21980 switch(spellInfo
->EffectApplyAuraName
[index
])
21982 case SPELL_AURA_MOD_TAUNT
:
21987 return Unit::IsImmunedToSpellEffect(spellInfo
, index
);
21990 void Player::SetHomebindToLocation(WorldLocation
const& loc
, uint32 area_id
)
21992 m_homebindMapId
= loc
.mapid
;
21993 m_homebindAreaId
= area_id
;
21994 m_homebindX
= loc
.coord_x
;
21995 m_homebindY
= loc
.coord_y
;
21996 m_homebindZ
= loc
.coord_z
;
21998 // update sql homebind
21999 CharacterDatabase
.PExecute("UPDATE character_homebind SET map = '%u', zone = '%u', position_x = '%f', position_y = '%f', position_z = '%f' WHERE guid = '%u'",
22000 m_homebindMapId
, m_homebindAreaId
, m_homebindX
, m_homebindY
, m_homebindZ
, GetGUIDLow());
22003 Object
* Player::GetObjectByTypeMask(ObjectGuid guid
, TypeMask typemask
)
22005 switch(guid
.GetHigh())
22007 case HIGHGUID_ITEM
:
22008 if (typemask
& TYPEMASK_ITEM
)
22009 return GetItemByGuid(guid
);
22011 case HIGHGUID_PLAYER
:
22012 if (GetObjectGuid()==guid
)
22014 if ((typemask
& TYPEMASK_PLAYER
) && IsInWorld())
22015 return ObjectAccessor::FindPlayer(guid
);
22017 case HIGHGUID_GAMEOBJECT
:
22018 if ((typemask
& TYPEMASK_GAMEOBJECT
) && IsInWorld())
22019 return GetMap()->GetGameObject(guid
);
22021 case HIGHGUID_UNIT
:
22022 if ((typemask
& TYPEMASK_UNIT
) && IsInWorld())
22023 return GetMap()->GetCreature(guid
);
22026 if ((typemask
& TYPEMASK_UNIT
) && IsInWorld())
22027 return GetMap()->GetPet(guid
);
22029 case HIGHGUID_VEHICLE
:
22030 if ((typemask
& TYPEMASK_UNIT
) && IsInWorld())
22031 return GetMap()->GetVehicle(guid
);
22033 case HIGHGUID_DYNAMICOBJECT
:
22034 if ((typemask
& TYPEMASK_DYNAMICOBJECT
) && IsInWorld())
22035 return GetMap()->GetDynamicObject(guid
);
22037 case HIGHGUID_TRANSPORT
:
22038 case HIGHGUID_CORPSE
:
22039 case HIGHGUID_MO_TRANSPORT
:
22046 void Player::SetRestType( RestType n_r_type
, uint32 areaTriggerId
/*= 0*/)
22048 rest_type
= n_r_type
;
22050 if (rest_type
== REST_TYPE_NO
)
22052 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
22054 // Set player to FFA PVP when not in rested environment.
22055 if(sWorld
.IsFFAPvPRealm())
22060 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
22062 inn_trigger_id
= areaTriggerId
;
22063 time_inn_enter
= time(NULL
);
22065 if(sWorld
.IsFFAPvPRealm())